Skip to content

Conversation

@drewstone
Copy link
Contributor

Summary

Complete implementation of Tangle v2, a production-ready EVM-native restaking protocol for Tempo L1.

Core Features

  • Tangle.sol - Monolithic core contract with modular architecture
  • MultiAssetDelegation.sol - O(1) share-based staking with proportional slashing
  • InflationPool.sol - Pre-funded reward distribution
  • Governance - TangleGovernor + TangleToken + TangleTimelock

Key Capabilities

  • Blueprint registration and service lifecycle management
  • Job submission with result verification
  • Payment processing with configurable splits
  • O(1) Masterchef-style rewards distribution
  • Proportional slashing with dispute windows
  • Blueprint-aware slashing (only affects exposed delegators)
  • Exposure system for per-operator risk management
  • Metrics recording for rewards/slashing tracking

Extensions

  • Tokenized blueprint extensions for community tokens
  • Payment receiver hooks
  • Price oracle infrastructure
  • Beacon chain validator pod system (experimental)

Test Coverage

926 tests passing across 45 test suites:

  • Core protocol tests
  • Delegation and slashing tests
  • Governance tests
  • Comprehensive fuzz tests
  • End-to-end integration tests

SDK Integration

Rust bindings generated via forge bind:

  • Tangle, ITangle, ITangleFull
  • IBlueprintServiceManager
  • MultiAssetDelegation
  • InflationPool

Compatible with blueprint-tangle-evm-extra crate.

Test plan

  • All 926 tests pass
  • Blueprint SDK compiles with new bindings
  • Documentation updated

🤖 Generated with Claude Code

drewstone and others added 30 commits December 3, 2025 04:05
- Update solc from 0.8.20 to 0.8.26
- Switch EVM version from shanghai to cancun
- Enable via_ir for optimized compilation
- Add OpenZeppelin upgradeable contracts dependency
- Add Tempo network RPC endpoints

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
Architecture design documents for Tangle v2 EVM protocol:
- 00: Current state analysis
- 01: Design principles
- 02: Shared security interface (IRestaking)
- 03: Protocol contracts specification
- 04: SDK updates roadmap
- 05: Implementation plan
- 06: Beacon chain validator restaking
- DESIGN.md: High-level overview
- PROGRESS.md: Implementation tracker

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
Protocol governance model and token economics for Tangle.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
Complete implementation of Tangle v2 protocol for Tempo L1:

## Core Contracts
- Tangle.sol: Unified protocol entry point
- TangleStorage.sol: State management
- BlueprintServiceManagerBase.sol: Base for custom managers
- MBSMRegistry.sol: Master blueprint manager registry

## Protocol Modules
- core/Base.sol: Shared base logic
- core/Blueprints.sol: Blueprint registration and management
- core/Operators.sol: Operator lifecycle
- core/Services.sol: Service lifecycle
- core/Jobs.sol: Job submission and results
- core/Quotes.sol: Quote verification
- core/Payments.sol: Payment and billing
- core/Slashing.sol: Slashing proposals and disputes

## Restaking System
- MultiAssetDelegation.sol: Multi-asset delegation core
- OperatorManager.sol: Operator stake management
- DepositManager.sol: Delegator deposits
- RewardsManager.sol: Reward distribution
- SlashingManager.sol: Proportional slashing
- OperatorStatusRegistry.sol: Heartbeats and status
- LiquidDelegationFactory.sol: ERC7540 vault factory
- LiquidDelegationVault.sol: Liquid staking vault

## Rewards System
- InflationController.sol: Protocol inflation
- RewardVaults.sol: Reward distribution
- TangleMetrics.sol: Performance metrics

## Governance
- TangleToken.sol: TNT token
- TangleGovernor.sol: On-chain governance
- TangleTimelock.sol: Timelock controller

## Beacon Chain (L1 ETH Restaking)
- ValidatorPod.sol: Beacon validator wrapper
- ValidatorPodManager.sol: Pod lifecycle
- BeaconChainProofs.sol: SSZ proof verification
- BeaconRootReceiver.sol: L2 beacon root sync

## Test Suite (743 tests passing)
- Unit tests for all modules
- Integration tests (end-to-end flows)
- Fuzz tests (invariant, payment, slashing)
- Edge case tests

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
… risk

Refactor inflation architecture to use pre-funded pool instead of minting:

- Add InflationPool.sol: Pre-funded reward distribution pool
  - Receives tokens from treasury/governance via fund()
  - Distributes via epoch-based streaming (same logic as InflationController)
  - Cannot mint - only transfers from pool balance
  - Emergency withdraw for migration to new pool versions

- Update RewardVaults.sol:
  - Change _mintRewards() to _transferRewards()
  - Now distributes from funded balance instead of minting

- Update TangleToken.sol:
  - Document that MINTER_ROLE should only be held by governance
  - Protocol contracts cannot mint, isolating token risk

Benefits:
- If protocol contracts have bugs, attackers cannot mint unlimited tokens
- Can deploy new pool versions without affecting token holders
- Governance controls inflation by funding pool from treasury
- Cleaner separation between token and protocol

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
- Remove InflationController.sol (replaced by InflationPool)
- Remove InflationController.t.sol and InflationControllerE2E.t.sol
- Add comprehensive InflationPool.t.sol with claim flow tests
- Update Rewards.t.sol to fund vaults (pre-funded model, no minting)
- Update GOVERNANCE.md to document new inflation architecture

The new pre-funded model means:
- Protocol contracts cannot mint tokens
- InflationPool receives funds from governance and distributes them
- Operator/customer rewards accumulate in pool until claimed
- Staking rewards transfer immediately to RewardVaults

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
- Add _recordJobCompletion call in submitResult when job completes
- Add _recordJobCompletion call in submitResults (batch) when job completes
- Add _recordAggregatedJobCompletion to credit ALL signers in bitmap
  when aggregated results are submitted

This ensures operators get credit for job completions in TangleMetrics,
which is used by InflationPool to calculate merit-based rewards.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
The _recordSlash() helper existed in Base.sol but was never invoked
during slash execution. This meant slashing events were not tracked
in the metrics recorder, preventing accurate rewards deduction for
slashed operators.

Changes:
- Add _recordSlash() call to executeSlash() after marking executed
- Add _recordSlash() call to executeSlashBatch() for batch operations
- Update ITangleSlashing.proposeSlash to return slashId (interface sync)

This enables the metrics recorder to track operator slashing history
for proper rewards distribution calculations.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
Connect TangleMetrics recording functions to core contract events:
- Blueprints.sol: Record blueprint creation for developer metrics
- Operators.sol: Record operator registration for blueprint stats
- Quotes.sol: Record service creation when activated via quotes
- Jobs.sol: Record job calls and payments for customer metrics
- Payments.sol: Record escrow funding for customer fee tracking

These hooks enable accurate tracking of ecosystem activity for
merit-based inflation distribution across all stakeholder categories.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
…nge mechanism

Comprehensive improvements to slashing test coverage:

EndToEndSlashingTest:
- Add test_E2E_SlashingRecordedInMetrics verifying metrics recording
- Add test_E2E_BatchSlashingRecordedInMetrics for batch operations
- Add ChallengingSquareBSM contract for on-chain result verification
- Add challenge flow tests for invalid computation results
- Strengthen balance assertions for operator and delegator stakes

SlashingFuzz:
- Fix rounding assertions using assertApproxEqAbs (1 wei tolerance)
- Adjust proportionality checks for extreme stake distributions
- Skip ratio validation when remaining stakes are below thresholds

All 18 slashing tests now pass with comprehensive coverage of:
- Proportional slashing with exact balance verification
- Multi-operator isolation during slashing
- Challenge mechanism for invalid results
- Cumulative slashing to stake depletion
- Exposure scaling effects
- Dispute window enforcement

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
Add comprehensive documentation for the TNT inflation reward system:
- Distribution weights and verification commands
- Scoring formulas for operators, developers, and customers
- Redistribution behavior when categories have no participants
- Admin configuration functions for weights and epoch settings
- Funding and claiming procedures

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
Enable blueprint managers to receive and handle revenue payments:
- Add receive() function to accept native token payments
- Add _onPaymentReceived() virtual hook for custom handling
- Allows BSMs to redirect developer share to themselves
- Foundation for tokenized blueprint extensions

This enables blueprint developers to build token communities where
revenue flows into the BSM contract for distribution to stakeholders.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
Introduce extension contracts for blueprints with token economics:

TokenizedBlueprintBase:
- ERC20 community token for blueprint participation
- Synthetix-style staking rewards for O(1) gas efficiency
- Multi-token reward support (ETH + ERC20)
- Instant or streaming distribution modes
- Auto-redirects developer revenue to contract

BuybackBlueprintBase:
- Extends TokenizedBlueprintBase with AMM integration
- Uniswap V3 SwapRouter interface for token buybacks
- Three modes: MANUAL, AUTO, THRESHOLD
- Configurable token destination: BURN, DISTRIBUTE, TREASURY
- Slippage protection and stats tracking

These extensions enable blueprint developers to create sustainable
token communities where revenue flows back to token holders.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
Implements a comprehensive exposure management system aligned with Tangle
pallet design patterns. Operators can configure per-asset exposure limits
(1-100%) that control how much of their delegated stake is exposed to
each service.

Key components:
- ExposureTypes: Core type definitions for exposure limits and calculations
- IExposureManager: Interface for operator exposure configuration
- ExposureManager: Implementation with commitment validation
- ExposureCalculator: Library for exposure-weighted calculations

Features:
- Per-asset exposure limits with global fallback
- Commitment validation against service requirements
- Delegation stake verification
- Weighted exposure calculation across multiple assets
- Slash amount calculation based on exposure percentage
- Reward distribution proportional to exposure

This integrates with the existing SlashingLib which uses exposureBps
to calculate effective slash amounts.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
Introduces a modular price oracle system for converting asset amounts
to USD values, supporting multiple oracle providers for price discovery.

Contracts:
- IPriceOracle: Standard interface for price queries and conversions
- IPriceOracleAdmin: Administrative interface for feed configuration
- ChainlinkOracle: Chainlink price feed adapter with staleness checks
- UniswapV3Oracle: Uniswap V3 TWAP oracle for on-chain price discovery

Features:
- Configurable maximum price age for staleness protection
- Automatic decimal normalization to 18 decimals
- Batch USD conversion for multi-asset calculations
- Support for native and ERC20 tokens

The price oracle system complements the exposure system by enabling
USD-denominated display and comparison of exposure values across
different asset types.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
Adds thorough test coverage for the exposure management system including
unit tests, edge cases, boundary conditions, and fuzz testing.

Test coverage:
- ExposureManagerTest: 22 tests for operator configuration and validation
- ExposureCalculatorTest: 14 tests for calculation library functions
- ExposureEdgeCasesTest: 27 tests for boundary and edge cases
- ExposureFuzzTest: 7 fuzz tests with 1000 runs each

Edge cases covered:
- Boundary values (0, 1, 9999, 10000 basis points)
- Large stake values up to uint128 max
- Tiny stake rounding behavior
- Multi-operator and multi-asset scenarios
- Global vs per-asset limit precedence
- Slashing integration with exposure
- Reward distribution proportionality

The fuzz tests verify invariants across random inputs for exposure
calculations, slash amounts, reward shares, and weighted averages.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
Fixes compilation errors caused by Solidity's strict type checking for
contracts with payable fallback functions. The MockBSM contracts require
explicit payable() casts when converting from address type.

Changes:
- BSMHooksLifecycle.t.sol: Add payable() casts to all MockBSM instantiations
- CrossVersionCompatibility.t.sol: Fix address declarations and casts

This resolves the "Explicit type conversion not allowed from non-payable
address to contract" compilation errors introduced when MockBSM contracts
gained payable fallback functions.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
Implements a cross-chain messaging abstraction for propagating slashing
events from the beacon chain to L2 networks where validator rewards may
be distributed.

Components:
- ICrossChainMessenger: Abstract interface for cross-chain messaging
- L2SlashingConnector: Sends slashing notifications from L1 to L2
- L2SlashingReceiver: Receives and processes slashing on L2
- TangleL2Slasher: L2 implementation of the slashing interface

Bridge implementations:
- BaseBridge: Optimism-style native bridge adapter
- ArbitrumBridge: Arbitrum retryable ticket adapter
- LayerZeroBridge: LayerZero cross-chain messaging adapter
- HyperlaneBridge: Hyperlane mailbox adapter

Features:
- Configurable message fee handling
- Bridge-specific retry mechanisms
- Validator pubkey to withdrawal address resolution
- Slashing amount capping to prevent excessive penalties

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
Comprehensive test coverage for the cross-chain slashing infrastructure
including connector, receiver, and bridge implementations.

Tests cover:
- L2SlashingConnector initialization and configuration
- Message sending with proper fee handling
- L2SlashingReceiver slash processing
- TangleL2Slasher slash amount capping
- Bridge adapter message encoding

Includes 21 test cases covering normal operations, edge cases,
access control, and error conditions.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
Deployment scripts for the beacon chain slashing system components
on both L1 (mainnet) and L2 networks.

Scripts:
- DeployBeaconSlashing.s.sol: Deploys ValidatorPodManager with slashing
- DeployL2Slashing.s.sol: Deploys L2 slashing receiver and connectors

Configuration:
- Environment variable support for deployment addresses
- Configurable bridge selection (Base, Arbitrum, LayerZero, Hyperlane)
- Automatic bridge adapter deployment

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
Major enhancements to the beacon chain restaking infrastructure to
support validator slashing detection and cross-chain propagation.

ValidatorPod changes:
- Add slashing detection via beacon state proofs
- Track slashed validator status
- Support for withdrawal credential verification
- Integration with L2SlashingConnector for cross-chain notifications

ValidatorPodManager changes:
- Batch validator verification
- Slashing event coordination
- Pod delegation tracking

BeaconChainProofs changes:
- Add slashing proof verification
- Validator status extraction from proofs
- Enhanced merkle proof validation

ValidatorTypes changes:
- Add SlashingInfo struct
- Extended validator status enums

AUDIT.md updates:
- Document new slashing attack vectors
- Security considerations for cross-chain messaging

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
Extends test coverage for the beacon chain restaking and slashing
infrastructure with unit, integration, and fuzz tests.

Test files:
- BeaconChainProofsTest: Merkle proof verification tests
- ValidatorPodTest: Pod lifecycle and slashing detection tests
- ValidatorPodManagerTest: Manager operations and batch processing
- BeaconIntegrationTest: End-to-end integration scenarios
- BeaconFuzzTest: Fuzz testing for proof verification
- BeaconProofFixtureTest: Tests using real beacon chain fixtures
- LiveBeaconTest: Live network integration tests (skipped by default)

Fixtures:
- Real beacon state proofs for mainnet validators
- Slashing event data for verification testing

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
Implements BN254 elliptic curve operations for BLS signature
aggregation and verification.

BN254.sol:
- G1 and G2 point operations
- Pairing verification for BLS signatures
- Hash-to-curve implementation
- Point compression/decompression

BLSAggregation.t.sol:
- Unit tests for curve operations
- Signature aggregation verification tests
- Edge case handling for invalid inputs

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
Extends core interfaces and type definitions to support the expanded
feature set including exposure-based slashing and cross-chain operations.

Interface changes:
- IBlueprintHook: Add slashing notification hooks
- IBlueprintServiceManager: Add exposure query methods
- ITangleJobs: Add job result metadata types

Library changes:
- Errors: Add new error types for exposure and cross-chain operations
- Types: Add AssetSecurityRequirement, AssetSecurityCommitment structs

These changes provide the foundational types required for the exposure
management system integration.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
…tion

Updates the inflation pool and metrics system to support exposure-weighted
reward distribution.

InflationPool changes:
- Integrate exposure percentage into reward calculations
- Support for multi-asset reward distribution
- Enhanced epoch management

TangleMetrics changes:
- Track exposure-weighted participation
- Slashing impact on metrics

Test updates:
- Add tests for exposure-weighted distributions
- Verify reward proportionality to exposure

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
…port

Updates core contracts to integrate with the exposure management system.

Tangle.sol:
- Import and use exposure manager for commitment validation
- Pass exposure data through service creation flow

OperatorStatusRegistry.sol:
- Track operator exposure configurations
- Add slashable operator queries

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
Documents the complete slashing architecture including:
- ELIP-004 slashing factor mechanism
- Cross-chain slashing propagation design
- Exposure-based slash calculation
- Bridge adapter architecture
- Security considerations

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
Introduce Go-based command-line tool for generating beacon chain proofs
required for TanglePod restaking operations.

Commands:
- status: Query validator status via beaconcha.in API
- credentials: Generate withdrawal credential proofs for restaking
- checkpoint: Generate checkpoint proofs for balance synchronization
- stale-balance: Generate proofs for slashing enforcement

Features:
- Multi-network support (mainnet, holesky, sepolia)
- EIP-4788 beacon root validation
- Full beacon state SSZ parsing with Merkle proof generation
- Support for 0x01 and 0x02 (Pectra compounding) credentials

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
- Update PROGRESS.md with current test count (926 tests)
- Update README.md with accurate file structure
- Rename 00-current-state.md to 00-v1-substrate-architecture.md (historical)
- Add references to new architecture documents

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
Comprehensive roadmap documenting:
- Current SDK binding and feature status
- Missing SDK features needed for full v2 support
- Integration test scenarios required
- Implementation phases with priorities

Key gaps identified:
- Operator lifecycle operations (register, stake, unstake)
- Service approval/rejection from operator side
- Slashing monitoring and dispute operations
- Rewards claiming
- Heartbeat/liveness submission

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
@vutuanlinh2k2 vutuanlinh2k2 marked this pull request as draft December 22, 2025 15:34
drewstone and others added 18 commits December 22, 2025 14:54
… docs

- Add configurable CORS origins to SP1 prover API via CORS_ALLOWED_ORIGINS env var
  - Supports comma-separated origins for production use
  - Falls back to allowing all origins if not set

- Add claim-relayer service for gasless claim submissions
  - Express.js API with rate limiting (10 req/min per IP)
  - Input validation for pubkey, amount, merkle proof, zk proof
  - Transaction simulation before submission
  - Health check and status endpoints

- Enhance SP1 workspace configuration
  - Update dependencies and Cargo.lock
  - Improve prover-api Dockerfile and README
  - Update lib with public values encoding/decoding

- Add PRODUCTION-TEST-GUIDE.md with end-to-end testing documentation
  - Step-by-step setup for SP1 program, contracts, and services
  - Environment configuration examples

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Add secondary rate limiting by pubkey to prevent abuse via proxy
rotation. IP-only rate limiting could be bypassed with proxies/VPNs.

- Add pubkey rate limit map with stricter 5 req/min limit
- Normalize pubkey to lowercase for consistent keying
- Check pubkey limit after format validation, before contract calls

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Fail-safe CORS configuration for SP1 prover API:
- Require explicit CORS_ALLOWED_ORIGINS when SP1_PROVER=network
- Exit with error if CORS_ALLOWED_ORIGINS is set but contains no valid origins
- Only allow permissive CORS (Any) for local/mock testing

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Drop per-blueprint bond fields from Types and storage, and delete bond token/default bond config

Remove payable bond handling and refund paths from operator registration and admin surface

Update interfaces, scripts, configs, and docs to rely on restaking self-stake only

Adjust tests and regen bindings/ABIs; bump bindings and fixtures to v0.5.0

BREAKING CHANGE: per-blueprint bond parameters, stored bond amounts, and operator bond admin functions are removed; registerOperator is no longer payable
feat: claim migration QA improvements and local dev setup
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants