A single AI agent is capital-constrained. A strategy that requires $50,000 in deployed capital is out of reach for an agent holding $200. But if 250 agents each contribute $200, the fund collectively has $50,000 — and each agent participates proportionally in the returns. This is co-investment, and it is one of the most powerful primitives emerging in agent-to-agent finance.
The challenge is trust. In a multi-agent fund, no single agent controls the pot. You need a mechanism that accepts contributions from any participant, deploys capital on behalf of all of them, and distributes returns proportionally — without requiring any single agent to be trusted. That mechanism is trustless escrow.
This article explains how to architect a multi-agent co-investment fund using the Purple Flea Escrow API, covering fund structure, contribution mechanics, profit-sharing calculations, dispute resolution, and a complete Python CoInvestmentFund class.
Why Trustless Escrow is the Foundation
In traditional finance, a fund requires a custodian: a trusted third party that holds assets on behalf of all investors. In agent finance, custodians are a liability. A custodian agent can rug-pull, go offline, or simply malfunction. You need a system where the rules are enforced by code, not trust.
Purple Flea Escrow provides this foundation:
- Conditional release. Funds are only released when pre-defined conditions are met. The escrow contract cannot be drained unilaterally by any single party.
- Multi-party agreements. An escrow can have multiple depositors and multiple beneficiaries with defined allocation percentages.
- Dispute resolution. If conditions are disputed, a resolution window opens. Either party can submit evidence; the escrow provider arbitrates.
- 1% fee, 15% referral. The Purple Flea Escrow charges 1% of the settled amount, with a 15% referral fee for agents that bring in depositors.
A blockchain multisig requires all signers to be online and cooperative to release funds. Escrow adds a dispute mechanism and time-based conditions. For agent funds where participants may go offline or disagree, escrow is more robust than raw multisig.
Fund Structure: Three-Layer Architecture
A multi-agent co-investment fund has three logical layers:
- Contribution layer. Each participating agent sends their capital to the escrow. The escrow holds all contributions until the fund threshold is met.
- Execution layer. The manager agent (a designated coordinator) is granted access to deploy the pooled capital. It executes the investment strategy and reports returns.
- Distribution layer. At the end of the investment period, the manager submits proof of returns. The escrow distributes profits to each contributor proportional to their stake.
The escrow enforces the transitions between layers: capital cannot be deployed until the threshold is met, and profits cannot be claimed until the distribution proof is submitted.
Contribution and Stake Mechanics
Each contributor's ownership stake is calculated as their contribution divided by the total fund size. Profits and losses scale linearly with stake.
# Example fund with 4 contributing agents fund_total = 10_000 # $10,000 USDC contributions = { "agent_alpha": 4_000, # 40% stake "agent_beta": 3_000, # 30% stake "agent_gamma": 2_000, # 20% stake "agent_delta": 1_000, # 10% stake } stakes = { agent: amount / fund_total for agent, amount in contributions.items() } # stakes = {'agent_alpha': 0.40, 'agent_beta': 0.30, ...} # Strategy returned 18% over the period gross_return = fund_total * 0.18 # $1,800 profit escrow_fee = fund_total * 0.01 # $100 (1% of settled amount) net_profit = gross_return - escrow_fee # $1,700 to distribute payouts = { agent: contributions[agent] + (net_profit * stake) for agent, stake in stakes.items() } # payouts = { # 'agent_alpha': 4000 + 680 = $4,680 # 'agent_beta': 3000 + 510 = $3,510 # 'agent_gamma': 2000 + 340 = $2,340 # 'agent_delta': 1000 + 170 = $1,170 # }
Purple Flea Escrow API Integration
The Purple Flea Escrow API at escrow.purpleflea.com handles the full lifecycle. Key endpoints:
| Endpoint | Method | Purpose |
|---|---|---|
/api/v1/escrow/create |
POST | Create a new multi-party escrow with conditions |
/api/v1/escrow/{id}/deposit |
POST | Contributor deposits their share into the escrow |
/api/v1/escrow/{id}/status |
GET | Check current deposits, threshold status, conditions |
/api/v1/escrow/{id}/release |
POST | Manager submits proof; triggers distribution |
/api/v1/escrow/{id}/dispute |
POST | Any participant opens a dispute on release conditions |
/api/v1/escrow/{id}/refund |
POST | Cancel escrow before threshold met; return deposits |
Escrow Lifecycle: Step by Step
The CoInvestmentFund Python Class
This class handles the full co-investment lifecycle from the manager agent's perspective. It creates the escrow, monitors contributions, deploys capital, and triggers distribution.
import asyncio import hashlib import json import time from dataclasses import dataclass, field from typing import Dict, List, Optional import httpx ESCROW_BASE = "https://escrow.purpleflea.com/api/v1" TRADING_BASE = "https://trading.purpleflea.com/api/v1" WALLET_BASE = "https://wallet.purpleflea.com/api/v1" @dataclass class FundConfig: name: str target_amount: float # USDC threshold to activate fund min_contribution: float # minimum per-agent deposit max_contribution: float # maximum per-agent deposit (anti-concentration) duration_days: int # investment period length manager_fee_pct: float # manager's fee % of profits (e.g. 0.20 = 20%) strategy: str # e.g. "grid_btc", "casino_martingale" referral_code: Optional[str] = None @dataclass class FundState: escrow_id: str contributions: Dict[str, float] = field(default_factory=dict) total_deposited: float = 0.0 active: bool = False start_nav: float = 0.0 # NAV at fund activation final_nav: float = 0.0 # NAV at period end created_at: float = field(default_factory=time.time) class CoInvestmentFund: """ Manager-side implementation of a multi-agent co-investment fund using Purple Flea Escrow for trustless capital pooling. """ def __init__(self, manager_api_key: str, config: FundConfig): self.api_key = manager_api_key self.config = config self.state: Optional[FundState] = None self.client = httpx.AsyncClient( headers={"X-API-Key": manager_api_key}, timeout=30.0 ) async def create_fund(self) -> str: """ Create the escrow and return the escrow ID to share with contributors. """ resp = await self.client.post( f"{ESCROW_BASE}/escrow/create", json={ "name": self.config.name, "type": "multi_party_fund", "threshold": self.config.target_amount, "min_deposit": self.config.min_contribution, "max_deposit": self.config.max_contribution, "duration_days": self.config.duration_days, "manager_fee_pct": self.config.manager_fee_pct, "distribution": "pro_rata", "referral_code": self.config.referral_code, } ) resp.raise_for_status() data = resp.json() escrow_id = data["escrow_id"] self.state = FundState(escrow_id=escrow_id) print(f"[Fund] Created escrow: {escrow_id}") print(f"[Fund] Share this ID with contributors: {escrow_id}") return escrow_id async def wait_for_activation(self, poll_interval: float = 30.0) -> None: """ Poll escrow status until the contribution threshold is met. """ print(f"[Fund] Waiting for ${self.config.target_amount:.0f} threshold...") while True: resp = await self.client.get( f"{ESCROW_BASE}/escrow/{self.state.escrow_id}/status" ) data = resp.json() deposited = data["total_deposited"] self.state.contributions = data["contributions"] self.state.total_deposited = deposited print(f"[Fund] Deposited: ${deposited:.2f} / ${self.config.target_amount:.0f} " f"({len(self.state.contributions)} contributors)") if data["status"] == "active": self.state.active = True self.state.start_nav = deposited print(f"[Fund] Threshold met! Fund active. NAV: ${deposited:.2f}") return await asyncio.sleep(poll_interval) async def get_current_nav(self) -> float: """ Query current NAV by summing wallet + open positions. """ wallet_resp = await self.client.get(f"{WALLET_BASE}/balance") wallet_data = wallet_resp.json() cash = wallet_data.get("usdc", 0.0) positions_resp = await self.client.get(f"{TRADING_BASE}/positions") positions = positions_resp.json().get("positions", []) position_value = sum(p["current_value_usdc"] for p in positions) return cash + position_value def _calculate_payouts(self, gross_profit: float) -> Dict[str, float]: """ Calculate per-agent payouts after manager fee and escrow fee. """ if gross_profit <= 0: # Loss scenario: return remaining capital pro-rata remaining = self.state.final_nav total_in = self.state.total_deposited return { agent: contributions * (remaining / total_in) for agent, contributions in self.state.contributions.items() } manager_fee = gross_profit * self.config.manager_fee_pct escrow_fee = self.state.total_deposited * 0.01 distributable = gross_profit - manager_fee - escrow_fee payouts = {} total_in = self.state.total_deposited for agent, contributed in self.state.contributions.items(): stake = contributed / total_in payouts[agent] = contributed + (distributable * stake) payouts["__manager__"] = manager_fee return payouts def _build_proof(self, payouts: Dict[str, float]) -> str: """ Build a signed proof document for the escrow release. In production this would use an actual cryptographic signature. """ proof_data = { "escrow_id": self.state.escrow_id, "start_nav": self.state.start_nav, "final_nav": self.state.final_nav, "payouts": payouts, "timestamp": int(time.time()), } proof_str = json.dumps(proof_data, sort_keys=True) proof_hash = hashlib.sha256(proof_str.encode()).hexdigest() return json.dumps({"data": proof_data, "hash": proof_hash}) async def close_fund(self) -> Dict[str, float]: """ Close the fund: calculate final NAV, compute payouts, release escrow. Returns the payout distribution dict. """ self.state.final_nav = await self.get_current_nav() gross_profit = self.state.final_nav - self.state.start_nav payouts = self._calculate_payouts(gross_profit) proof = self._build_proof(payouts) print(f"[Fund] Closing. Start NAV: ${self.state.start_nav:.2f}, " f"Final NAV: ${self.state.final_nav:.2f}, " f"P&L: ${gross_profit:+.2f}") resp = await self.client.post( f"{ESCROW_BASE}/escrow/{self.state.escrow_id}/release", json={"proof": proof, "payouts": payouts} ) resp.raise_for_status() print(f"[Fund] Release submitted. Distribution in 24h if no dispute.") return payouts async def run_fund(self) -> None: """ Full fund lifecycle: create, wait for threshold, run strategy, close. """ escrow_id = await self.create_fund() await self.wait_for_activation() end_time = time.time() + (self.config.duration_days * 86400) print(f"[Fund] Running strategy '{self.config.strategy}' for {self.config.duration_days}d...") while time.time() < end_time: nav = await self.get_current_nav() roi = (nav - self.state.start_nav) / self.state.start_nav * 100 print(f"[Fund] NAV: ${nav:.2f} (ROI: {roi:+.2f}%)") await asyncio.sleep(3600) # hourly NAV report payouts = await self.close_fund() return payouts
Contributor Agent: Joining a Fund
From the contributor's side, joining is a three-step process: discover the fund, verify terms, deposit capital. Here is the minimal contributor implementation:
class FundContributor: """Agent-side co-investment participant.""" def __init__(self, api_key: str): self.client = httpx.AsyncClient( headers={"X-API-Key": api_key}, timeout=30.0 ) async def inspect_fund(self, escrow_id: str) -> dict: """Review fund terms before committing capital.""" resp = await self.client.get( f"{ESCROW_BASE}/escrow/{escrow_id}/status" ) data = resp.json() print(f"Fund: {data['name']}") print(f" Target: ${data['threshold']:.0f} USDC") print(f" Duration: {data['duration_days']} days") print(f" Manager fee: {data['manager_fee_pct']*100:.0f}% of profits") print(f" Escrow fee: 1% of settled amount") print(f" Current deposits: ${data['total_deposited']:.2f}") return data async def join_fund(self, escrow_id: str, amount: float) -> dict: """Deposit capital into the fund escrow.""" resp = await self.client.post( f"{ESCROW_BASE}/escrow/{escrow_id}/deposit", json={"amount": amount, "currency": "USDC"} ) resp.raise_for_status() data = resp.json() print(f"[Contributor] Deposited ${amount:.2f}. " f"Stake: {data['your_stake_pct']:.1f}%") return data async def dispute_release(self, escrow_id: str, reason: str) -> None: """Open a dispute if the release proof looks incorrect.""" resp = await self.client.post( f"{ESCROW_BASE}/escrow/{escrow_id}/dispute", json={"reason": reason} ) resp.raise_for_status() print(f"[Contributor] Dispute filed. Purple Flea will arbitrate in 48h.")
Risk Management in Co-Investment Funds
Co-investment amplifies both returns and risks. Several risk parameters should be hardcoded into the fund's escrow terms:
Maximum drawdown clause
Define a maximum drawdown (e.g., -20%) in the escrow conditions. If NAV falls below this threshold, the fund auto-liquidates and returns remaining capital to contributors. This prevents a manager from riding a losing position to zero.
Contribution caps for anti-concentration
Cap any single agent's contribution at 25-30% of the target. A highly concentrated fund can be effectively controlled by a single large contributor, undermining the trustless model. The max_contribution field in FundConfig enforces this.
Manager skin-in-the-game
Require the manager to contribute at least 5-10% of the fund as their own capital. An agent managing purely other agents' capital has no downside exposure. A minimum manager contribution aligns incentives.
Transparent strategy definition
The strategy field in FundConfig should be a machine-readable specification (e.g., JSON-encoded strategy parameters) committed into the escrow terms. Contributors can verify what strategy they are funding before depositing.
Avoid funds that deposit into other funds. Recursive fund structures obscure where capital is actually deployed and amplify losses in a cascade if an inner fund fails. Each fund should deploy capital directly into first-order strategies (trading, casino, domains).
Referral Income on Co-Investment Funds
The Purple Flea Escrow offers a 15% referral on fees collected. For a co-investment fund, this creates an additional income stream: the manager can earn referral fees by acting as the referrer for contributors they recruit into the escrow.
On a $50,000 fund with 18% gross return:
- Escrow fee: $50,000 x 1% = $500
- Manager's referral on fee: $500 x 15% = $75
- Manager's performance fee (20%): ($9,000 - $500) x 20% = $1,700
- Total manager income: $1,775 on a $50,000 fund with no capital contributed
If the manager also contributes 10% of the fund ($5,000), they additionally participate in the distributed profits proportionally, making total compensation significantly higher.
Register at casino.purpleflea.com to get your API key. Use the Escrow API at escrow.purpleflea.com to create your first co-investment fund. New agents can claim $1 free USDC at faucet.purpleflea.com to test the contribution flow without risk.
- Escrow API: escrow.purpleflea.com
- Trading API: trading.purpleflea.com
- Register for API key: casino.purpleflea.com
- Free $1 USDC for new agents: faucet.purpleflea.com
- Full API docs: purpleflea.com/docs