1. What this is

A platform where managers run funds that trade on Polymarket and investors buy/redeem fund shares at NAV — with custody in non-custodial on-chain vaults. Each fund is one FundVault contract on Polygon that is the custody address and the ERC-20 share token. The manager's key can only produce Polymarket order signatures; investors always have a permissionless pro-rata exit (redeemInKind). Neither the platform nor the manager can transfer vault assets directly, but the platform's signed share prices can move value between holders, within per-vault budgets (§3). For the same system told through the investor's and manager's journeys, including the PM-116 limits that PM-117 builds, see ARCHITECTURE_FLOWS.md.

Status: custody, deposits, NAV and both redemption paths are live on Polygon. The contracts (the fee structure and the factory's quote guard) are frozen and reviewed, and their factory is deployed (§10). CLOB trading is blocked by Polymarket's off-chain API policy, not by cryptography — see §8. The selected path is a factory-wide vault allowlist; deposit-wallet execution is not part of the product. Every finding of the September security reviews and of the external audit is fixed and merged. Do not take third-party money (§9).

2. System overview

flowchart LR
  subgraph Users
    I[Investor wallet]
    M[Manager wallet]
    K[Anyone as keeper]
  end
  subgraph Polygon
    F[FundVaultFactory<br/>signer set · budgets · guardian] -->|CREATE2 clones| V[FundVault xN]
    V -->|authorize each signed deposit / cash exit| F
    V <-->|pUSD / USDC.e / CTF-1155| PM[Polymarket contracts<br/>Exchanges · Onramp/Offramp · NegRiskAdapter]
  end
  subgraph App ["Backend (FastAPI, read-only on chain)"]
    Q[quotes.py<br/>signs share-price quotes]
    O[orders.py<br/>builds 7739 envelopes, relays to CLOB]
    IX[indexer.py<br/>events → DB cache]
    N[nav.py<br/>marks + quote defense]
  end
  CLOB[CLOB off-chain API] -->|settlements| PM
  I -->|approve + deposit / redeem| V
  M -->|deploy vault| F
  M -->|signs typed data| O
  O --> CLOB
  Q --> N
  K -->|redeem resolved / wrap idle| V
  IX -->|eth_getLogs| V

The backend never sends transactions and holds no fund keys. Every state-changing on-chain action is initiated by an investor, manager, or keeper wallet.

What runs where.

Layer What it is What it holds What it may do
Polygon: FundVaultFactory and one FundVault per fund Immutable contracts (§4) Every fund's assets; the share token; the quote signer set, budgets and governance Everything that moves value, and only when a wallet calls it with a valid quote or signature
Polymarket The two exchanges, the Onramp/Offramp, the CTF and NegRisk contracts; off chain the CLOB, Gamma and Data APIs The order book; market metadata; position values Match and settle the vault's orders; resolve markets
Backend (backend/, FastAPI, one worker, SQLite) A read-only observer of the chain plus the quote signer and the order relay (§5) The quote key; accounts; encrypted CLOB credentials and delegate keys; a cache of events and holdings Sign share-price quotes; build and relay the manager's orders; index events; alert
Frontend (frontend/, Next.js, static pages) The pages, run in the browser with the user's wallet (§6) A session token; nothing of value Ask the backend; check every payload; ask the wallet to sign or send

The backend's routes, grouped (every route is under errors_router, so its answers and error details are redacted of the RPC URL and key, PM-143):

Group Routes Who
Accounts Wallet sign-in: POST /auth/siwe/challenge, POST /auth/siwe; GET and PATCH /auth/me; the contact email: POST and DELETE /auth/email, POST /auth/email/verify; the wallet link: POST /auth/link-wallet/challenge, POST /auth/link-wallet, GET /auth/link-wallet/message; POST /auth/register and POST /auth/login answer 410 Anyone for sign-in and the email link; a session for the rest
Funds, public GET /funds, GET /funds/{id}, /nav, /redeemable, /registry, /inkind-preview, GET /funds/config; the quote GET /funds/{id}/quote and /capacity Anyone, rate-limited per caller and account
Funds, private POST /funds (create), /deployment, /confirm-deployment, /find-deployment (a lost transaction hash), DELETE /funds/{id} (a fund never deployed), /holdings (manager), /transactions (manager: all; investor: own), GET /funds/mine/holdings A session; the manager for the manager's
Trading /trading/status, the CLOB credentials (clob-auth-payload, clob-creds), the delegate key (delegate-key, /revoke, /challenge, /step-up), orders/build, orders/{id}/submit, GET orders, GET history The fund's manager, with a trading token for orders
Markets GET /markets, /search, /{token}/book, /{token}/history Anyone; cached and bounded

5. Backend (backend/, FastAPI + SQLAlchemy/SQLite + web3.py)

On-chain is the ledger; the DB is a cache plus accounts/CLOB plumbing. Boot refuses to start without its secrets set (their names are in §13) and when its key is not an active signer of the factory.

Service Role
services/vault.py Read-only web3 (POA middleware): balances, totalSupply, deployment verification (VaultCreated event + CREATE2 cross-check), resolved-collateral detection. Every vault state read names its block: a ChainSnapshot pinned by block hash (EIP-1898), or an explicit LATEST
services/nav.py NAV = vault pUSD + USDC.e + Σ(on-chain CTF balance × CLOB midpoint), with every on-chain input read at one snapshot. Share price divides by on-chain totalSupply() + pending fee shares, never the DB cache. This midpoint NAV is for display; signed quotes price positions with marks.py. Snapshots come from the NAV loop (every NAV_SNAPSHOT_INTERVAL) and from fund-page reads (at most once a minute); the chart's history (routers/funds.py, nav_history) covers the fund's whole life in at most 500 equal time slices, from its first snapshot to its newest (PM-122)
services/marks.py Quote marks (PM-118): each deposit or cash exit priced at the average price of trading its slice of each position through the order book, the worse of now and the median of one-minute samples over 10 minutes; refuses wide, moving, thin, stale or unsampled books
services/quotes.py Signs bound quotes (EIP-712, the vault's own domain) for one operation, account and amount, with a random 128-bit nonce; TTL QUOTE_TTL_SECONDS (default 30 s, at most 120). Before signing, at the pinned block, applies the factory's gates, envelope and budgets and refuses (409) with the remaining capacity; never quotes a vault the configured factory did not create. Persists every issued quote with its binding and the block and mark times it was priced from
services/orders.py Builds Exchange-V2 orders (maker = signer = vault, sigtype 3), the exact eth_signTypedData_v4 payload for the manager's wallet, and the ERC-7739 envelope for the CLOB. Owns the CLOB REST transport (L1 ClobAuth handshake, L2 HMAC headers) via httpx — py-clob-client-v2's 1271 paths have known bugs (#64/#66/#70/#77), so we own the bytes
services/indexer.py Polls eth_getLogs per fund (confirmation lag, capped span), idempotently upserts Deposit/RedeemCash/RedeemInKind events, keeps holdings and tracked cost basis in event order (deposits add their cash and their entry fee, exits remove their pro-rata part, fee shares cost nothing, transferred shares carry the sender's average cost; PM-120). It never combines balances from different blocks, and certifies a block only after checking every holder with shares and the vault's supply there. A mismatch, an event without its pair (a mint without its deposit or harvest, a burn without its exit, a fee-charging vault's deposit without its entry fee), unknown starting balances or a reorganisation mark a fund's basis unverified (hidden and alerted; events, quote attribution and order cancellation carry on) until a reconciliation from the last verified checkpoint is complete and matches the chain. Scans and reconciliation record events through one path, so an event only a reconciliation finds still gets its cancellation and quote attribution, once; an exit's burn and exit event share one durable cancellation record, so finding either again never cancels later orders. A scan accounts only between two blocks whose hashes it has read; otherwise it records events and does the safety work, scans the range again, and shows the basis as still being checked, with an alert after ten minutes. It also attributes each signed use to its issued quote by nonce from the calldata, only when every signed field matches the issuance; other contents under an issued nonce raise quote_altered, and a use whose calldata cannot be read or decoded is attributed to nothing (quote_use_unattributed). Scans the factory's budget and governance events and raises alerts

Quote defense (app-only, fail-closed) — before signing any quote, nav.py refuses if: the Data API is down; any registered position lacks a CLOB midpoint; the on-chain×mid mark and the Data API mark disagree by more than NAV_MARK_MAX_BPS; or pending harvest shares can't be read (prevents overpaying a cash redeemer after an in-tx fee harvest). Both marks value the same portfolio, the vault's registered positions matched by token id (PM-158): a registered position of more than 0.01 tokens that the Data API does not list refuses too, and a token sent to the vault without being registered is listed apart (unregistered_positions) and is in neither the NAV nor the share price.

Quote marks (PM-118) — a signed quote values each position at what its transaction's slice would trade for: the asks for a deposit, the bids for a cash exit, walked to the slice's size. The mark is the worse, for the investor transacting, of that price now and a directional 10-minute median (lower for exits, upper for deposits): a push must be as large as the slice and appear in more than half the samples to set the median, though each pushed sample can nudge it by one honest sample. A /books answer whose server time is more than 5 s from ours is refused; history is kept by read time, so a quiet market's unchanged book still counts (a book's timestamp is its last change, PM-125). Quotes are refused (409) on a spread over 10¢, a move over 5¢ from the median, a slice that would move the price over 5¢, or a deposit paying over twice a position's midpoint, and cannot be signed (503) on a book unchanged for over 30 minutes or fewer than 6 samples. Each quote records its marks. The settings were checked on 24 hours of live books (PM-125, PM-128).

One block per price (PM-115) — balances, supply, pending fees, the position registry and CTF balances are read at one block chosen NAV_BLOCK_LAG (default 2) blocks behind the head, and each read sends that block's hash. Separate latest-block reads could divide cash read before a deposit by supply read after it, and the quote endpoint is public, so an investor could time requests around their own deposit or redemption. The empty-vault (bootstrap) decision uses the same block, except that a vault that is empty or not yet deployed at the lagged block is read at the newest block for the whole calculation: the contract makes that decision from its supply when the deposit executes, and the client's first-deposit race recovery needs a signed quote once shares exist. Quotes are refused when the block is older than QUOTE_MAX_BLOCK_AGE_SECONDS (default 60), checked when it is selected and again before signing. A failed read or stale block restarts the whole calculation from a new block up to QUOTE_BLOCK_RETRIES times (default 1); no read falls back to another block, and the quote then fails with 503. Each issued quote records its block number, hash, timestamp and when marks were collected. A block that is later reorged away is still one consistent state, so quotes are not tracked after signing.

Trading flow — POST /trading/orders/build (tick-snapping, ±500 bps price band around mid, CLOB min-size, vault-balance preflight, geoblock check) → manager's wallet signs typed data → POST /orders/{id}/submit wraps the signature into the 7739 envelope and POSTs to the CLOB. Optional delegate key: server-generated, powerless until the manager calls addSigner on-chain, revocable with removeSigner, and stopped by a manager handover (PM-140), neither of which reaches an order the exchange's operator has already preapproved. The manager routes (the trading routes, the investor register, the full history and the deployment pages) serve, once the vault is deployed, the account whose linked wallet is the vault's manager() read from the chain, kept at most MANAGER_CACHE_SECONDS (10) per vault and read again just before the delegate key signs and when its approval is issued; the record follows that read, and an unreadable chain refuses with 502 (PM-167). Cancellations are verified against the open-order list, read page by page to the end (an unreadable page or cursor fails closed): cancel-all keeps its retry marker until the list is empty, and a single order is cancelled only once the CLOB confirms it and the list, asked for that order alone (its id filter, since an offset cursor can skip an order when the book changes mid-read), no longer has it; until then it is cancel_pending, and one that left without a confirmed cancellation (for example filled) is closed. The CLOB's reason is kept in the order history, including for a refused cancellation (PM-121). An order the CLOB matched at once (fill-or-kill) is closed when it is submitted; one not signed within five minutes of being built is expired and cannot be sent; and one whose send got no answer is unknown, kept under its order hash: it becomes submitted if the open-order list shows it, and otherwise stays unknown, for the fund's positions to tell whether it filled. It is never sent twice. Every change of an order's status goes through one table (backend/app/services/order_state.py), which refuses to move a final status.

Auth — JWT accounts; wallet linking via one signature; CLOB creds and delegate keys are encrypted at rest (§13). Single uvicorn worker recommended (background indexer + SQLite). The link's signature is of a one-use challenge, as the delegate approval's is (PM-159): issued for this site's domain, the account and the wallet, valid five minutes, checked by the page before the wallet signs and consumed once; a link spends the account's other open challenges. The wallet is the account (#64): the site signs in with Sign-In with Ethereum (EIP-4361), and there are no passwords. The page asks for a one-use message issued for this site's domain and origin, Polygon and the wallet, with a random nonce and a five-minute window; the wallet signs it (personal_sign, no gas); the backend recovers the signer, consumes the message once and signs in the account whose wallet it is, or makes one, named by the shortened wallet. An account made before keeps its funds and history when it signs in with the wallet it linked; one that never linked a wallet can no longer sign in. Every page says so when the browser wallet's account is not the signed-in one, and offers to sign in with it. Sign-in messages and sign-ins are limited per caller (SIGN_IN_RATE_LIMIT_PER_IP, 10 a minute); a refused request answers 429 with Retry-After. The contact email is optional: an address is the account's only once the one-use link sent to it (24 hours, only its hash stored) is opened, and verification emails are limited per account (EMAIL_VERIFY_RATE_LIMIT_PER_ACCOUNT, 3 an hour). They go from ACCOUNT_EMAIL_FROM (docs/alerts.md); without it the site offers no email.

A cross-stack golden vector (contracts/test/GoldenVector.t.sol ↔ backend/tests/test_order_flow.py) pins the ERC-7739 order-envelope bytes on both sides.

Limits (PM-144) — the backend's own, per process (several workers multiply them):

  • Quotes (GET /funds/{id}/quote, public, no session): per caller, QUOTE_RATE_LIMIT_PER_IP (30 a minute), and per caller and account, QUOTE_RATE_LIMIT_PER_ACCOUNT (10). Nothing shared refuses a quote, so a stranger's requests, even for an investor's account, spend only the stranger's allowance. A quote needs no session or signature: it is bound to its account and single-use. More than QUOTE_RATE_LIMIT_PER_VAULT (120) a minute for one fund raises an alert (§13) and refuses nothing. A fund's quote reads (the block, the NAV, the factory's gates and budgets) are kept QUOTE_READ_CACHE_SECONDS (3): each quote still checks its block's age, and a guardian's pause stops new quotes within that time here, and any quote at once on chain.
  • The caller is the connection's address, or, only when the connection comes from a trusted proxy (a setting, §13), the right-most address in X-Forwarded-For that is not one. An IPv6 address counts as its /64. The limiter forgets a caller after its window and holds at most 10,000.
  • Public reads: GET /funds/{id}/nav is kept NAV_CACHE_SECONDS (5) per fund and does not read the exchange with the fund's credentials; its open_order_count is the last credentialed read's (the manager's pages, cancels, the indexer), with open_order_count_age, and null when older than OPEN_ORDER_COUNT_MAX_AGE (300 s). The markets routes bound limit (100), offset, the search text and the token id, and keep each answer MARKETS_CACHE_SECONDS (10). These caches compute a missing answer once however many requests ask for it at the same moment, keep a failed NAV or quote read PUBLIC_READ_FAILURE_SECONDS (3, at most the cache's own time), and run at most PUBLIC_READ_MAX_CONCURRENCY (8) computations at once, a request beyond them answered 503 with Retry-After (PM-166). The capacity (GET /funds/{id}/capacity) answers from the NAV's entry, the in-kind preview's chain reads, the registry and the redeemable list are kept the same way per fund, and a caller makes at most PUBLIC_READ_RATE_LIMIT_PER_IP (60) requests a minute to these five routes together, a request beyond them answered 429 with Retry-After (PM-168).
  • Numbers in a request are bounded: an id in a path is from 1 to SQLite's largest integer, a share count is positive and finite, and an order's price and size are finite; anything else is refused with 422 (PM-166).
  • Funds per account: an account creates at most MAX_FUNDS_PER_ACCOUNT (10) funds, every fund it has recorded counting, so that nobody takes fund names at will (PM-166).
  • Who lists a fund: only an approved wallet records a fund on the site. The site's admin, a signed-in account whose wallet ADMIN_WALLETS names, approves wallets at /admin: a wallet asks from the "Create a fund" page, and the admin approves it, declines it or takes an approval away (backend/app/services/listing.py). FUND_LISTING_WALLETS approves wallets from the server's settings as well. Both settings are empty until the owner fills them. The same approval is asked at each step that confirms a fund's vault. The public list shows the funds whose vault is confirmed; a fund still being created is shown to the account creating it alone. A description is at most 1,000 characters. A manager gives an X handle before asking and before recording a fund; the admin sees it, the fund's page links to it, and it cannot be replaced by another once the wallet has asked or is approved, since the site cannot prove whose it is. An admin reaches no fund, key or money. The factory itself is open to any address: a vault made there without approval has no page on the site.

6. Frontend (frontend/, Next.js 15 + Tailwind 4 + viem)

All investor/manager actions are wallet transactions from the browser (injected provider, auto Polygon-switch): approve+deposit with quote and minShares, redeem-for-cash / redeem-in-kind, factory deploy on fund creation, typed-data order signing on the trade ticket, permissionless "Redeem resolved" keeper button. Money math lives in lib/money.mjs (unit-tested: applySlippage, toMicro, integer coercion). uint256 values in wallet payloads are strings — Polymarket token ids overflow JS Number.

The pages.

Route Who What it does
/ and the content pages (/how-it-works, /investors, /managers, /faq, /community, /legal, /docs/…, /whitepaper) Anyone The product explained; every sentence of the content pages rests on a document, a line of code or a test
/funds Anyone Every fund with NAV, share price, change since launch and shares
/funds/{id} Anyone; more for the manager The fund: NAV and its history, cash, positions with their prices and P&L, the registry, the capacity notice, transactions; the deposit, cash-exit and in-kind panels with their quotes and previews; "Redeem resolved" and "Wrap idle"; for the manager the holders table and the way to the trade page
/funds/{id}/trade The manager Enabling trading (CLOB credentials), the delegate key, market search, the order ticket, open orders with cancel, order history
/new-fund A signed-in account Name, symbol, description; the createVault call for the wallet; confirmation of the deployment
/portfolio A signed-in account The linked wallet's holdings across funds, with tracked basis
/login Anyone Sign in with the wallet; the first sign-in makes the account
/account A signed-in account The wallet, the display name and the optional contact email; /account/verify opens an email's verification link

What the pages let a wallet sign (PM-145). The backend builds every payload, and the pages check it before the wallet is asked (lib/signing-checks.mjs). An order must be exactly this vault's order on one of Polymarket's two exchanges, on Polygon, for the outcome, side, price and size of the form; the exchange login must be the exchange's login, for the vault or for the connected wallet, with the timestamp and nonce sent back; a delegate approval's text must be this site's template, for this host, account, fund and wallet; a sign-in message must be this site's EIP-4361 template, for this host and origin, the wallet and Polygon. Anything else is refused with what differs, so a compromised server cannot put a token permit in front of the manager's wallet. The tokens and the exchanges are built into the pages (lib/chain.mjs); the factory is a build setting, NEXT_PUBLIC_FACTORY_ADDRESS. Before an approval or a deposit the page asks that factory, through the wallet's RPC, whether the fund's vault is one of its own (isVault); a configuration from the backend that names another token or factory stops the deposit or the creation.

A transaction sent is not sent again (#40). Once the wallet returns a deposit's or a cash exit's hash, the page keeps it in the browser, per wallet, chain, vault and operation (lib/pending.mjs). A receipt that cannot be read is reported as sent and unconfirmed, never as a failure: no expired quote or vault that is no longer empty leads to another request, since the vault may hold the investor's own first deposit. Before the next deposit or cash exit, the page reads the kept transaction's receipt: it reports one that landed and sends nothing, lets one that reverted go, and holds while there is no receipt until the investor, having checked their wallet, says it never went through (the receipt is read once more first). A transaction is forgotten only once the page has reported how it ended, so an investor who left before the receipt arrived is told on the next visit. A receipt that says it reverted, and an expiry before sending, may still be requoted once.

7. Lifecycle walkthroughs

sequenceDiagram
  participant Mgr as Manager wallet
  participant Fac as Factory
  participant V as FundVault
  participant BE as Backend
  participant Inv as Investor wallet
  Mgr->>Fac: createVault(name,symbol,manager,salt)
  Fac-->>BE: VaultCreated event → fund active
  Inv->>V: depositUSDCe(amount, quote, sig, minShares)
  Note right of V: wrap→pUSD, harvest, 1% entry fee → treasury, mint shares @ quoted price
  Mgr->>BE: build order → sign typed data → submit
  BE->>CLOB: POST /order (7739 envelope, maker=vault)
  CLOB->>V: exchange settles fills on-chain
  K->>V: redeemResolved* / wrapIdleUSDCe (permissionless)
  Inv->>V: redeemCash(shares, quote…) OR redeemInKind(shares)
  Note right of V: in-kind = pro-rata cash + every position, no permission

8. Trading status — the one open blocker

The cryptography works: a vault validates our ERC-7739 ClobAuth and order envelopes on-chain (eth_call → 0x1626ba7e), and the digests byte-match py-clob-client-v2. What is missing is Polymarket's off-chain onboarding: its order book accepts orders only from makers it has onboarded, and vaults are not yet among them.

The decision: pursue the vault allowlist with Polymarket directly. The request may use L2 keys on the vault or manager-EOA L1 authentication, but every accepted order must remain maker = signer = vault, signature type 3. Polymarket's deposit wallets are not part of the product: they would hold the fund's trading money outside the vault.

The allowlist target is the factory 0x42b12e6e1AF2EeCa057585FEe256fd69A8CCba0b (§10).

10. Key Polymarket facts (June 2026)

  • Trading settles in pUSD (ERC-20, 6 decimals, 1:1 USDC.e via CollateralOnramp/Offramp).
  • CLOB (clob.polymarket.com): off-chain matching, on-chain settlement by the exchange contracts. Orders are EIP-712; L2 API creds authenticate REST calls; makers pay no gas. Exchange V2 order struct: Order(salt, maker, signer, tokenId, makerAmount, takerAmount, side, signatureType, timestamp, metadata, builder).
  • Market metadata: Gamma API; positions/PnL per address: Data API v2 (both public).
Contract Address (Polygon)
pUSD 0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB
CollateralOnramp 0x93070a847efEf7F70739046A929D47a521F5B8ee
CollateralOfframp 0x2957922Eb93258b93368531d39fAcCA3B4dC5854
USDC.e 0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174
CTF Exchange V2 0xE111180000d2663C0091e4f400237545B87B996B
Neg Risk CTF Exchange V2 0xe2222d279d744050d28e00520010520000310F59
Neg Risk Adapter 0xd91E80cF2E7be2e162c6513ceD06f1dD0dA35296
Conditional Tokens 0x4D97DCd97eC945f40cF65F87097ACe5EA0476045
FundVaultFactory 0x42b12e6e1AF2EeCa057585FEe256fd69A8CCba0b (FACTORY_ADDRESS)

11. Tests & CI

cd contracts && forge test                                  # unit suite incl. 1271 matrix
cd contracts && POLYGON_RPC_URL=... forge test --match-path 'test/fork/*'   # live Polygon
cd backend  && python -m pytest                             # quotes, indexer, orders, accounting
cd contracts && forge build && cd ../backend && python -m pytest tests/test_integration_anvil.py
                                                            # backend quotes → contracts on Anvil
cd frontend && npm test && npm run build                    # money math + build

CI (.github/workflows/ci.yml): contracts unit (with fuzzed charges and random attack sequences) + fmt, backend pytest, the Anvil integration test, frontend test+build, ABI-sync check (export-abis.sh then git diff --exit-code). Fork tests run locally/nightly with POLYGON_RPC_URL. The backend jobs install backend/requirements.lock, every package pinned with the hashes of its files (pip install --require-hashes), and the backend job fails on any advisory pip-audit reports in it, except python-ecdsa's, which has no fix and is in code the backend never loads (PM-146). The frontend job fails on a high or critical advisory in what the site ships (npm audit).

Source

This page is the project's own document, shown as it is: ARCHITECTURE.md, sections 1, 2, 5 to 8, 10 and 11.