P2P economy layer, on-chain escrow, ERC-7579 smart accounts, and agent UX improvements#52
Merged
langowarny merged 28 commits intomainfrom Mar 9, 2026
Merged
P2P economy layer, on-chain escrow, ERC-7579 smart accounts, and agent UX improvements#52langowarny merged 28 commits intomainfrom
langowarny merged 28 commits intomainfrom
Conversation
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.
Feature/p2p economy
- 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.
Enhance Agent Error UX
- 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.
- 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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
This PR merges the
devbranch intomain, incorporating 5 major feature areasdeveloped across PRs #47–#51 (~644 files changed, +74k/-9.8k lines).
What's Changed
P2P Economy Layer (#47)
lango economy ...)Test Infrastructure Refactoring (#48)
On-Chain Escrow & Security Sentinel (#49)
LangoEscrowHub.sol) with dual-mode settlement (optimistic + dispute)LangoVaultandLangoVaultFactoryfor agent fund managementERC-7579 Modular Smart Accounts & ERC-4337 Paymaster (#50)
LangoSessionValidatormodule: session key management with spending limits and time boundsLangoSpendingHookmodule: per-session USDC spending enforcementLangoEscrowExecutormodule: escrow-aware execution validationlango smartaccount ...)scripts/check-abi.sh) for contract sync validationAgent Error UX & Auto-Extend Timeout (#51)
New Contracts (Base Sepolia, Chain ID: 84532)
0x1820A1C403A5811660a4893Ae028862208e4f7A80x5d08310987C5B59cB03F01363142656C5AE239970xB52877B5E27F77795Fbe59101D07CA81dbd3f8aC0xc428774991dBDf6645E254be793cb93A66cd9b4B0x1CA47128D7fdDD0D875C3AeC7274C894F2c792C20x18167Daeca7A09B32D8BE93c73737B95B64A7ff80x036CbD53842c5426634e7929541eC2318f3dCF7e0x4BDBDE4A725A83820B7A94cD5dB523eb4515dDAdDocumentation
docs/cli/economy.md,docs/cli/smartaccount.md,docs/cli/contract.md,docs/cli/metrics.mddocs/features/economy.md,docs/features/smart-accounts.md,docs/features/observability.md,docs/features/contracts.mdREADME.mdwith P2P economy and smart account overview