Skip to content

P2P economy layer, on-chain escrow, ERC-7579 smart accounts, and agent UX improvements#52

Merged
langowarny merged 28 commits intomainfrom
dev
Mar 9, 2026
Merged

P2P economy layer, on-chain escrow, ERC-7579 smart accounts, and agent UX improvements#52
langowarny merged 28 commits intomainfrom
dev

Conversation

@langowarny
Copy link
Collaborator

Summary

This PR merges the dev branch into main, incorporating 5 major feature areas
developed across PRs #47#51 (~644 files changed, +74k/-9.8k lines).


What's Changed

P2P Economy Layer (#47)

  • Agent-to-agent P2P economy with budget management, risk assessment, dynamic pricing, and negotiation engine
  • Escrow integration at the economy layer
  • New CLI commands for economy operations (lango economy ...)
  • Contract interaction support within the economy layer
  • Observability & monitoring system with token usage tracking

Test Infrastructure Refactoring (#48)

  • Enhanced test parallelism across test suites
  • Improved assertions and test coverage consistency
  • Foundation work enabling reliable testing of the new features below

On-Chain Escrow & Security Sentinel (#49)

  • On-chain escrow hub (LangoEscrowHub.sol) with dual-mode settlement (optimistic + dispute)
  • LangoVault and LangoVaultFactory for agent fund management
  • Security Sentinel skill for monitoring suspicious activity
  • Foundry-based contract test suite with full coverage
  • Deployment configuration for Base Sepolia (chain 84532)

ERC-7579 Modular Smart Accounts & ERC-4337 Paymaster (#50)

  • LangoSessionValidator module: session key management with spending limits and time bounds
  • LangoSpendingHook module: per-session USDC spending enforcement
  • LangoEscrowExecutor module: escrow-aware execution validation
  • ERC-4337 paymaster support for gasless USDC transactions
  • New CLI commands for smart account operations (lango smartaccount ...)
  • ABI check script (scripts/check-abi.sh) for contract sync validation

Agent Error UX & Auto-Extend Timeout (#51)

  • Auto-extend timeout mechanism to prevent premature agent task termination
  • Real-time progress indicators during long-running agent tasks
  • Structured error handling with user-friendly error formatting
  • Cross-layer integration tests for app/adk boundaries

New Contracts (Base Sepolia, Chain ID: 84532)

Contract Address
EscrowHub 0x1820A1C403A5811660a4893Ae028862208e4f7A8
EscrowExecutor 0x5d08310987C5B59cB03F01363142656C5AE23997
SessionValidator 0xB52877B5E27F77795Fbe59101D07CA81dbd3f8aC
SpendingHook 0xc428774991dBDf6645E254be793cb93A66cd9b4B
VaultFactory 0x1CA47128D7fdDD0D875C3AeC7274C894F2c792C2
VaultImplementation 0x18167Daeca7A09B32D8BE93c73737B95B64A7ff8
USDC (tokenAddress) 0x036CbD53842c5426634e7929541eC2318f3dCF7e
Deployer 0x4BDBDE4A725A83820B7A94cD5dB523eb4515dDAd

Documentation

  • New CLI reference docs: docs/cli/economy.md, docs/cli/smartaccount.md, docs/cli/contract.md, docs/cli/metrics.md
  • New feature docs: docs/features/economy.md, docs/features/smart-accounts.md, docs/features/observability.md, docs/features/contracts.md
  • Updated README.md with P2P economy and smart account overview

Introduce an autonomous economic behavior layer on top of the existing
P2P infrastructure. Agents can now independently manage budgets, assess
risk, negotiate prices, and protect funds through milestone-based escrow.

New packages:
- internal/economy/budget: per-task budget allocation, spend tracking,
  threshold alerts, burn rate, and hard limit enforcement
- internal/economy/risk: trust-based risk assessment (trust × value ×
  verifiability) with strategy routing (DirectPay, MicroPayment, Escrow,
  ZKFirst)
- internal/economy/pricing: rule-based dynamic pricing engine with
  trust/volume discounts and paygate adapter
- internal/economy/negotiation: P2P propose/counter/accept/reject state
  machine with auto-negotiation strategies
- internal/economy/escrow: milestone-based escrow lifecycle
  (create → fund → activate → milestone → release/dispute/refund/expire)

Modified packages:
- internal/app: wire all 5 subsystems via initEconomy(), expose 12 agent
  tools for runtime economy operations
- internal/p2p/protocol: add negotiate message types and protocol handler
- internal/eventbus: add 8 economy domain events
- internal/config: add EconomyConfig with 5 sub-configs to root Config
- internal/cli/economy: add `lango economy` CLI group with
  budget/risk/pricing/negotiate/escrow subcommands
- cmd/lango/main.go: register economy CLI commands
- Consolidate `parseUSDC` function by utilizing `wallet.ParseUSDC` in both budget and risk engines, ensuring consistent error handling.
- Replace string comparisons for negotiation actions with typed constants in `wiring_economy.go` for better type safety.
- Add compile-time interface verification for `noopSettler` to ensure it implements `escrow.SettlementExecutor`.
- Refactor `checkThresholds` in `budget/engine.go` to collect alerts under lock and invoke callbacks after unlocking, preventing potential deadlocks.
- Introduce capacity hints for slice allocations in `tools_economy.go` and `escrow/store.go` to enhance performance.
- Introduced a new command for contract interactions in the CLI, enabling smart contract operations.
- Enhanced the economy layer to support on-chain settlement via a USDC settler when payment components are available.
- Updated the economy initialization to accept payment components, allowing for flexible escrow settlement configurations.
- Registered contract tools in the tool catalog for improved access and usability.
- Added new configuration options for escrow settlement parameters, including receipt timeout and maximum retries.
   Capture actual token usage from all LLM providers (OpenAI, Anthropic,
   Gemini) that was previously discarded. Add in-memory MetricsCollector,
   health check registry, token cost calculator, event bus wiring,
   persistent Ent storage, CLI metrics commands, gateway API endpoints,
   and audit recorder.

   Key changes:
   - Usage struct on StreamEvent for backward-compatible token propagation
   - MetricsCollector with per-session/agent/tool aggregation
   - TokenTracker subscribing to event bus for automatic collection
   - ModelAdapter.OnTokenUsage callback to avoid import cycles
   - HealthRegistry with database/memory/provider checks
   - Ent token_usage schema for persistent history
   - CLI: lango metrics [sessions|tools|agents|history]
   - Gateway: /metrics/*, /health/detailed endpoints
   - AuditRecorder wiring existing AuditLog schema
   - Fix ToolExecutedEvent.Duration via PreToolHook timing
- Added P2P Economy commands for budget management, risk assessment, dynamic pricing, negotiation, and escrow.
- Introduced Smart Contract commands for interacting with EVM contracts, including read, call, and ABI loading functionalities.
- Implemented observability features for tracking token usage, health monitoring, and metrics collection.
- Updated documentation to reflect new features and CLI commands for economy, contracts, and observability.
- Enhanced configuration options for economy and observability layers in the settings editor.
- Added `t.Parallel()` to various test functions to enable concurrent execution, improving test performance.
- Replaced traditional error handling with `require` and `assert` from the `testify` package for better readability and consistency in tests across `agent_test.go`, `child_session_test.go`, `context_model_test.go`, `context_providers_test.go`, `model_test.go`, `session_service_test.go`, `state_test.go`, `tools_test.go`, and `app_test.go`.
- Updated assertions to use `require` and `assert` for clearer failure messages and streamlined test logic.
Enhance test parallelism, improve assertions across multiple tests
   Implement trustless on-chain escrow system for P2P agent economy on Base
   network with Hub + Vault (EIP-1167) dual-mode settlement, event monitoring,
   and security anomaly detection.

   New packages:
   - contracts/ — Foundry project with LangoEscrowHub, LangoVault, LangoVaultFactory
   - internal/economy/escrow/hub/ — ABI embedding, typed clients, settlers, event monitor
   - internal/economy/escrow/sentinel/ — 5 anomaly detectors + sentinel engine
   - internal/app/tools_escrow.go — 10 escrow agent tools
   - internal/app/tools_sentinel.go — 4 sentinel agent tools
   - internal/ent/schema/escrow_deal.go — Ent schema for persistent escrow storage
   - internal/economy/escrow/ent_store.go — Ent-backed Store implementation
   - skills/security-sentinel.yaml — Sentinel skill definition

   Modified:
   - Config: EscrowOnChainConfig sub-struct (additive)
   - Event bus: 6 on-chain event types
   - Wiring: selectSettler() for hub/vault/custodian mode selection
   - CLI: expanded escrow subcommands (list, show, sentinel)
   - App: registered escrow + sentinel tool categories
- Added Foundry project structure with LangoEscrowHub, LangoVault, and LangoVaultFactory for on-chain escrow management.
- Introduced new test files for LangoEscrowHub and LangoVault, ensuring comprehensive coverage of contract functionalities.
- Updated .gitignore to exclude Foundry build artifacts and added .gitmodules for submodule management.
- Enhanced internal client architecture to support contract interactions with typed access and improved error handling.
- Implemented ABI parsing tests to validate contract method and event availability.
- Added comprehensive on-chain escrow configuration options, including dual-mode (Hub/Vault) support for escrow management.
- Implemented new CLI commands for escrow operations: `escrow list`, `escrow show`, and `escrow sentinel status`.
- Introduced Security Sentinel for monitoring escrow activities, with anomaly detection capabilities and alert generation.
- Updated documentation to reflect new features, including detailed descriptions of on-chain escrow processes and sentinel functionalities.
- Enhanced the settings editor to support on-chain escrow configurations, ensuring user-friendly management of escrow parameters.
On-Chain P2P Escrow System with Security Sentinel
  Introduce Safe-based smart accounts with ERC-7579 modules enabling
  controlled agent autonomy via time-limited, scope-restricted session keys.
  The master key is never exposed during routine operations.

  Solidity (3 modules + tests):
  - LangoSessionValidator: validates UserOp signatures against session policies
  - LangoSpendingHook: enforces per-tx/daily/cumulative spending limits
  - LangoEscrowExecutor: batched escrow operations in single UserOp

  Go (internal/smartaccount/):
  - Core types, AccountManager interface, 13 sentinel errors
  - Session key lifecycle (create/revoke/sign with hierarchical policies)
  - Policy engine with off-chain pre-flight validation
  - Module registry with ERC-7579 ABI encoding
  - Bundler JSON-RPC client (eth_sendUserOperation)
  - ABI bindings for all contracts + Safe7579

  Integration:
  - Config: SmartAccountConfig with session/module settings
  - Wallet: UserOpSigner interface for ERC-4337 signing
  - App wiring: initSmartAccount() with callback-based cross-package deps
  - 10 agent tools (deploy, session, policy, module, execute)
  - CLI: lango account {deploy,info,session,module,policy}
  - Economy: OnChainTracker, PolicyAdapter, SessionGuard callbacks

  Tests: 121 Foundry + 42 Go tests all passing.
  Add PaymasterProvider interface with Circle, Pimlico, and Alchemy
  implementations enabling users to pay gas in USDC instead of ETH.
  Two-phase sponsorship flow (stub → final) integrates into existing
  Manager.submitUserOp() via callback injection without breaking
  non-paymaster flows.

  - Solidity: allowedPaymasters field in SessionPolicy for on-chain
    paymaster restriction + Foundry tests (9 new test cases)
  - Go: internal/smartaccount/paymaster/ package (7 files)
  - Go: SmartAccountPaymasterConfig, PaymasterDataFunc, Manager 2-phase flow
  - Go: paymaster_status/paymaster_approve agent tools + CLI commands
  - Go: 5 new manager integration tests, all existing tests pass
DoABI/Encoding (Phase A :
 ❯ 1.Align SessionValida or ABI w th allowedP ymast rs field
   2.RYwrite SpdndingHook ABI to m:tch Solidity (setLimits/getConfig/getSpendState)
   -.Implement ERC-4337 v0.7 PackedUserOperation hash format
   - Replace Safe.setup() placeholder with proper ABI encoding
 Esc tetch nonce from EntryPo nt instead of hardcoded zero
     Deduplicat  Saf 7579ABI constant i to bindings package

   Security (P  se B):
     Fix SQL i j ction in dbmigra e PRAGMA passphras  interpolation
   - Store hex-encoded encrypted session key ciphertext (was discarded)
   - Add default-deny ApprovalFn with reputation-based auto-approve
     S gn ZK challe ges with wallet ECDSA key (was echoing challenge)
     Ma age No ceCache lifecycle to pr vent goroutine le ks

   Callback Wiring (Phase C):
   - Wire session on-chain registration/revocation via SessionValidatorClient
   - Conn c  OnChainTracker to budget engine Record() (was log-only)
     Wire CardFn, star  goss p service, conne t team invoke to ha dl r
     Expose SmartA count sub-components via public acc ssor methods

   Implementation (Phase D):
   - Replace all CLI stubs with real service calls via smartAccountDeps
     Add Pol cySyncer for Go ↔ on-chain poli y drift detection
   - Add RecoverableProvider with retry/fallback for paymaster errors

   Testing (Phase E):
   - 22 new integration tests across SmartAccount, P2P, and cross-layer
  - Fix enclave provider crash with actionable error listing valid providers
  - Implement Telegram DownloadFile (HTTP GET, 30s timeout)
  - Remove dead NewX402Client and context.TODO() from x402 package
  - Document GVisor stub behavior with tests
  - Add unit tests for 10 security-critical packages:
    wallet (68 tests), security (28), payment (38 subtests),
    smartaccount factory/session/ABI/paymaster/policy (95+),
    economy/risk (22), p2p/team (28 subtests), p2p/protocol (29)
- Added Smart Account configuration forms and CLI commands for managing session keys, modules, and paymaster settings.
- Enhanced documentation to include comprehensive details on smart accounts, including features, commands, and configuration options.
- Updated README and Makefile to reflect new smart account capabilities.
- Integrated smart account management into the TUI settings and multi-agent routing.

This commit ensures all relevant components are aligned with the new smart account subsystem.
ERC-7579 Smart Account + ERC-4337 Paymaster support for gasless P2P transactions
- Introduced optional auto-extension of request timeout based on agent activity, configurable via AgentConfig.
- Implemented "Thinking..." placeholder messages during processing in Discord, Slack, and Telegram channels, with periodic updates on elapsed time.
- Updated agent methods to support new run options for handling activity callbacks and partial results.
- Enhanced error handling to return partial results when available, improving user experience during agent execution failures.
- Added tests to verify new functionality and ensure proper behavior of progress indicators and error handling.
…uration

- Introduced `agent.autoExtendTimeout` and `agent.maxRequestTimeout` settings in README and configuration documentation.
- Updated TUI settings form to include fields for auto-extend timeout and maximum request timeout.
- Enhanced WebSocket events documentation to include `agent.progress`, `agent.warning`, and `agent.error` events.
- Added "Progressive thinking" capability to channel features documentation, detailing real-time updates during agent execution.
- Introduced a new .env.example file for environment variable configuration.
- Updated foundry.toml to include RPC endpoints and etherscan settings.
- Added a new deployment JSON file for chain ID 84532.
- Enhanced the Deploy script to deploy additional contracts and write deployment addresses to JSON files.
- Introduced new economy settings including budget management, risk assessment, negotiation protocols, and escrow functionalities.
- Added smart account configurations for dynamic pricing and escrow management.
- Enhanced documentation to reflect these experimental features and their respective configurations.
@langowarny langowarny self-assigned this Mar 9, 2026
@langowarny langowarny added documentation Improvements or additions to documentation enhancement New feature or request labels Mar 9, 2026
- Introduced new ABI JSON files for LangoEscrowHub, LangoVault, and LangoVaultFactory to support escrow functionalities.
- Updated .gitignore to include ABI files in the internal directory for version control.
- Updated parameter handling in module installation and uninstallation tools to remove unused variable assignments.
- Enhanced comments in the economy initialization process for better understanding of budget engine setup.
- Removed redundant mock structures from smart account tests to streamline test code.
- Simplified public key assertions in crypto tests for clarity and consistency.
@langowarny langowarny merged commit 1e058e9 into main Mar 9, 2026
4 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

documentation Improvements or additions to documentation enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant