
afterbook
io.github.Hryhorii77/afterbook
Checked trade plans, baskets and loan health for Coinbase tokenized stocks on Base. You sign.
Documentation
Afterbook
Live at afterbook.app.
Cash close vs the Aero book, in shares, for the Coinbase tokenized stocks on Base. The tape, Lot Lab and My Lots are read-only — no wallet ever signs anything there. Three places ask your wallet to sign; Afterbook holds no funds or keys in any of them (for Baskets, Glider's agent holds a permission on the account, see below): Portfolio's Revoke (it only ever sets a leftover router approval to zero, see Approvals), Buy / Sell in the Execute panel (an in-app swap from your own wallet through KyberSwap's router, see "In-app swaps" below) and Baskets (/baskets), run on Glider, where you sign an enrollment (new enrollments paused since 2026-11-19) and withdrawals and send USDC from your own wallet. See "Baskets (Basis Tilt)" below.
Pages: / and /[symbol] (the tape for a stock), /today ("Today's gap"), /borrow, /build (basket builder), /baskets, /baskets/risks.
What it shows
-
Tape: cash-market last price vs Aerodrome's on-chain mid price for the 39 Coinbase tokenized stocks Afterbook tracks (NVDAc, AAPLc, METAc, GOOGLc, AMZNc, MSFTc, MSTRc, SNDKc, SPCXc, TSLAc, PLTRc and MUc, plus the 26 Base announced as live on 2026-10-27: NFLXc, SKHYc, HIMSc, ORCLc, AMDc, AVGOc, LLYc, MRVLc and 18 non-US companies' ADRs such as SONYc, SAPc and NVOc, and ANTc, Anthropic, added 2026-11-20, the day after its Nasdaq IPO), basis in bp, plus real pool depth. Each stock is read from its deepest USDC pool: Aero's (Aerodrome's successor) for 21 of them, the older Aerodrome factory for the 18 seeded on 2026-10-27 (see "Contract addresses"). Each row is a card with the token's icon, a 24h change and a past-N-days chart (see "UI architecture"). During pre-market and after-hours, "cash" is the live extended-hours print, not the frozen 4pm close (Yahoo's
preMarketPrice/postMarketPricemeta fields when present; since about October 2026 Yahoo stopped sending them, so the tape reads today's one-minute bars withincludePrePost=trueduring those hours and takes the newest trade after the close from the last 4 hours,lastBarAfterinlib/market/tape.ts; on 2026-10-28 that turned GOOGLc's −1,025 bp "gap" against the 4pm close into +23 bp against its $290 after-hours trade) — comparing on-chain against a stale close would misreport a real overnight tradfi move as basis. Overnight and at weekends (cash fully closed) the hero's gap number and sentence (and/today) are anchored to the regular-session close; in pre-market and after-hours both use the row's live extended-hours trade when it has one (todayReferenceinlib/market/todaySnapshot.ts, the same rule asheroGapBp), so the home page,/today, its card and its share text never disagree about the same instant. In pre-market/after-hours the hero labels the cash price by the row's realcashPriceType: only when Yahoo has an extended-hours print does it say "cash pre-market/after-hours price"; with no print the cash price is still the last close, so it says "Friday's close" and the card says "Cash close". The tape's cash column header and the note under "Tape" follow the same rule, computed from all rows: no row on a print → "Cash close" and "No pre-market trades yet, so the basis is measured against the last regular-session close"; every row on a print → "Cash pre-market/after-hours"; a mix → "Cash (latest)" and a note saying it is a live print where there is one and the last close otherwise. Link-preview, share-card and footer copy use plain language, not the "Aero book" jargon. A symbol reporting earnings within 5 days gets a small "Earnings in Nd" flag in the tape and a caveat in Lot Lab — a widened spread near earnings is expected, not a sign the tape's basis math is broken. A line under the Tape heading says how fresh the numbers are (TapeFreshnessinapp/components/markets/Tape.tsx, with the tape table, phone cards and sort helpers; moved out ofHomeClient.tsxon 2026-10-29): "Live · updated 15s ago · refreshes every 20s", or, in amber, "Delayed · last updated 3 min ago" when the tape is over 90 s old, the server is serving last known values (error), or this page's last refresh failed; it also names the stocks whose cash price is a carried-forward last good value (cashStale, the STALE tag). Only the Live/Delayed word is a live region. The column headers are sort buttons (keyboard and screen readers:aria-sort, "Sort by Gap, now highest first"), rows can be picked with Enter, and "What the columns mean" opens a short legend (Gap, Onchain price, Pool liquidity, 24h, Trend). On phones each card shows the gap, cash → onchain price and pool liquidity; its Details button opens the 24h move, shares in the pool and the 30-day line with its change in words (sparkSummary, also every small chart's label). Earnings warnings stay on the card. -
Liquid vs thin split: pools with real depth (≥ $1M; at the time of writing NVDAc/AAPLc/METAc/GOOGLc/AMZNc/MSTRc/SNDKc/SPCXc — MSFTc, TSLAc, PLTRc and MUc are thin) lead the tape and hero grid; everything thinner collapses behind a "Show N thin books" toggle at reduced size. A $10k pool's basis swings hundreds of bp on noise alone — giving it the same visual weight as a $2M pool made the tape read as broken. $100k used to be the bar, but
depthUsdis a pool's total real token balance, not liquidity active near the current tick — a pool can clear $100k on stale/off-range positions while still swinging hundreds of bp (MSTRc did, at ~$965k depth and +257bp), so the bar moved to where the pools actually separate into a calm tier and a still-noisy one. The split is driven by live depth, not a hardcoded symbol list, so a thin pool graduates automatically once it actually has liquidity. Landing directly on a thin symbol (URL or dropdown) gets a small "thin book · $Xk depth" chip under the sticky bar, since the hero/tape's own thin-tier demotion is otherwise the only clue. -
Every tokenized stock (
/stocks): all of Coinbase's tokenized stocks (173 on 2026-10-18) as a table, searchable, filterable, sortable (24h volume, value on Base, 24h move, memes) and paged 25 at a time. Each row has price on Base, 24h move and 24h volume from the token's deepest pool on any Base exchange, "On Base" (that price × tokens in circulation on Base, not the company's market cap; Dexscreener's batch token endpoint, cached 5 minutes), the verified memes priced in it (logos and a count, linking to/memes?stock=…), its icon, contract (BaseScan link) and Aerodrome USDC pool status: Tracked (theSTOCKSlist, linking to its page, with the tape's live depth), Small pool (an Aerodrome USDC pool too shallow to track, with its depth, the three-hour low for any pool over $250k; 46 on 2026-10-18. LLYc reads up to ~$250k, but about $200k of that is a bot's liquidity that comes and goes; its three-hour low was $29k on 2026-10-20), No pool yet, or Not checked yet (listed by Coinbase after the last daily check). Untracked tokens get no gap, no alerts and no swaps: in a pool that small one trade moves the price, so the gap is noise. The pool column comes from the dailydiscover-tokensjob, which already measures every untracked token and saves one snapshot (directory:pools,saveDirectoryPoolsinlib/stocks/stockDirectory.ts); the page reads it through Next's data cache (an hour) and Coinbase's list (cached an hour), so a page view costs no chain reads for untracked tokens and at most one Redis request an hour. Listed in the sitemap; in the header nav (desktop) and the phone menu. -
Memestocks (
/memes,/memes/<address>): Base meme tokens whose pool is quoted in one of the tracked stock tokens (BLUECHIP/NVDAc, IPOD/AAPLc…), each with its 1h/6h/24h move next to its stock's, price, 24h volume, liquidity, the stock held in the pool, market cap and pool age. A not-dismissable warning sits above the numbers ("Any memecoin can go to zero; the stock token in the pool does not make the meme safer"), the list is sorted by volume or by move, never by our pick, and pools under $10k of liquidity sit under "thin". The list is its own allowlist (memes:poolsin Redis,lib/memes/memestocks.ts), written by the dailydiscover-memesjob; it never touchesSTOCKSorBASKET_SYMBOLS. The job reads Dexscreener's pairs for every tracked stock, drops majors, staked ETH (rETH, wstETH, cbETH, weETH), AAVE, AERO and stablecoins (by address, and any symbol containing USD/EUR) and other Coinbase stock tokens, and lists a pool only if it is proven on the chain: Aerodrome Slipstream and Uniswap v3 through their factories'getPool; Uniswap v4 (most of this market, 2026-10-18) through PositionManager'spoolKeyshashing to the pool id ("proven"), or, for pools created outside PositionManager (launchpads), the pool existing in StateView with liquidity and a price within 3% of the pair ("price-matched"; public RPCs refuse the old logs that would prove the key). A meme must also have a KyberSwap route back to USDC (a basic can-it-be-sold check). Memes are identified by contract address: several tokens share names (three "GPU"s on 2026-10-18). Live numbers come from Dexscreener (cached 2 minutes) and the allowlist through Next's data cache (an hour), so a view costs no chain reads. Each meme page has its own share card (/card?page=meme&addr=…). Meme logos are Dexscreener's (info.imageUrl, only https oncdn.dexscreener.com, the one meme image host in the CSP'simg-src), requested at 128 px: that CDN serves only some sizes and answers 96 px with a 422./memes?stock=NVDAcopens filtered to one stock. Prices are written out in full, never as "1.554e-7"; on a meme page a price under $0.001 shows its zeros as a count, "$0.0₆1554" (six zeros after the point), the way Dexscreener does, with the full number on hover. -
Home page (Trade) (2026-11-03, from an external review;
app/page.tsx,TradeHome.tsx): one heading and sentence ("Buy, borrow and earn with tokenized stocks on Base 24/7"), the US market's state, the five stocks with the biggest pools (Base price, the real stock's price, the gap as a percent, a Buy button that fills the card) and one action card with three tabs. Swap is the in-app swap below, behind the eligibility checkbox (ticked for every trade). Borrow links to the in-app Aave loan on/borrow#borrow-here(see Borrow; Afterbook sends Aave's own calls for the wallet to sign and never holds the loan) and to Morpho's site; Lend quotes the lenders' current rate (Aave's reads, cached a minute and dropped after 1.5 s) and links to the in-app USDC deposit on/borrow#lend-here(see Borrow) and to Aave's site; Borrow's "Open on Morpho ↗" is a link under its note, so each tab has two buttons. Under the stocks, Plan before you buy (2026-11-17, for the Stocks Maxxing quest: most visitors landed here and never found these) links to the trade plan (/plan), Describe a basket (/plan#basket, which opens that tab) and stock rules (/rules), one sentence each. Two columns on desktop with the card sticky beside the list, one column at 900px and narrower. The navigation is five tabs (Trade, Markets, Borrow, Portfolio, More): in the header on desktop, in a bar fixed to the bottom of the screen at 900px and narrower. Markets (/markets) is the tape page described below, which was the home page until then; Portfolio (/portfolio) holds the wallet's positions (My Lots, headed "Your positions" there); More (/more) lists baskets, the basket builder, memestocks, Telegram, the README and the API. -
Hero card + compact bar: the first thing on the tape page (
/markets). It opens on the day's biggest liquid gap (the same pick/todayuses, chosen on the server inapp/markets/page.tsx;/NVDAcetc. still open on that stock). It holds the stock chooser, the market-session pill, the big gap number with one plain sentence ("On Base, Strategy (MSTR) is trading 2.7% (268.2 bp) above Friday's close. Cash reopens Mon 9:30 AM ET.": where the onchain price is leads, so "on Base" never reads as where the cash price is; the sentence says Base, not the exchange (owner, 2026-11-08); percent first, because strangers read it faster, bp in brackets; under 5 bp only the bp is shown, since the percent would round to 0.00% and look like a mistake:gapSizeTextinlib/format.ts, also used for the share text), cash and Aero price cards, a primary "Size a SYMBOL trade" button (scrolls to Lot Lab, where the eligibility check lives; it never opens Aerodrome directly), a Telegram alerts link (tot.me/afterbook_bot; the bot's display name is "AfterbookAlertsBot", which is not its username), and a one-time note defining Aero and "100 bp = 1%". While cash is closed the number is anchored to the actual close (same as/today), not a live extended-hours print. A compact bar with the same number sticks to the top once the hero scrolls away. A visible<h1>sits above it (2026-10-28)./todayand the share cards lead with the same percent-plus-bp figure and the same sentence (2026-10-29); the cards write prices as "Cash $1,323.55 Aero $1,325.65". -
No tile grid: an earlier version repeated every liquid stock as a clickable tile under the hero (the same numbers as the ticker and the table). It was removed; the tape rows below are the way to switch stock, and clicking one still jumps to Lot Lab.
-
Basis since close: a sparkline of the selected symbol's basis from the last cash close to now, sampled into Redis every 5 minutes by the alerts cron (
recordTapeSamplesinlib/market/tape.ts, one write per stock per tick however many serverless instances are warm; until 2026-10-18 each instance sampled off its own traffic, which helped use up the Upstash plan's monthly request cap), and it works with zero setup (just renders empty) if no Redis store is configured. Recorded for every tracked stock regardless of the liquid/thin split above — it briefly reused that same $1M gate and silently stopped recording six symbols' history until that got decoupled; a thin pool's basis history is at least as useful to someone deciding whether to trade it. The same 30-day retained history also powers two one-line stats underneath, once there's enough sampled history: mean/max basis while the cash market was closed, and an open-snap convergence stat (getOpenSnapStats,lib/market/history.ts) — for each trading day, compares the last sample before that day's 9:30am NY open against samples ~30/90 min after, and reports how often |basis| shrank rather than widened ("basis moved toward $0 within 30 min in X% of the last N sessions"). Requires at least 8 valid trading days in the window before showing anything, same "collecting data" honesty as the sparkline itself rather than a percentage computed off too few days. -
NY session clock: cash-open / pre-market / after-hours / weekend / holiday state, so the 24/7-onchain-vs-24/5-cash gap is explicit, not implied.
-
Plain labels (owner, 2026-10-19): the price on Aerodrome is the "Onchain price" everywhere a person reads it (hero, tape column,
/today,/build, cards), the hero's big number is "Onchain price vs cash price", and its Onchain price card is the stronger of the two (firmer edge, heavier number, "Pool liquidity" under it) because it is the price you can trade at./borrowkeeps "Aero exit" / "Aero vs oracle", which that page defines. -
First screen for newcomers (2026-10-28, from an external review): a visible heading ("Stock prices on Base 24/7 next to the real market") and one plain sentence above the hero; the gap as a percent with bp beside it; a visible three-step strip (see the gap, check the pool, trade from your wallet); the "since close" chart panel hidden until it has data; the tape listing every pool of at least $250k with smaller ones behind "Show N smaller pools"; and a plain line in the trade panel when trading is off for a US or unknown region. "What the words mean" (bottom of the Tape hero, closed by default, nothing remembered between visits; "New here?" until 2026-10-28): five short definitions (tokenized stocks, with the stock on screen as the example; cash price; onchain price; the gap in bp; when a wallet is needed) and the US line. It shares its look with the tape's "What the columns mean" (
.explain/.tape-legend). -
Trade calculator (called Lot Lab in the code,
lotLabTab; shown as "Trade calculator" since 2026-10-19): type a USDC amount (or pick a size preset — $250 / $1k / $5k / 1% of the pool), see shares out, execution price, and a price-impact curve across a log-spaced range of trade sizes ($500–$1M) — computed from the pool's liveslot0()/liquidity(), not a cached reserve snapshot. The panel is split into Trade / LP / Carry tabs (Trade is the default) rather than stacking trade sizing, the depth chart, and the carry math into one long card — keeps the primary execution flow front and center and makes the tool readable on mobile. While cash is closed and the basis spread exceeds 20bp, also shows a cash-and-carry edge calculator (lib/market/arb.ts) in its own Carry tab: gross basis, pool fee, price impact, and a flat gas estimate netted out, then annualized over the actual time remaining until the cash market reopens — the tab itself is hidden outside that window rather than shown with nothing worth acting on. Still buy-only in the sense that this app never shorts or borrows, but the Carry tab now has both directions: a buy basis side (on-chain priced below cash — the classic setup) and a short basis / inventory-unwind side (on-chain priced above cash — for someone who already holds spot shares and wants to sell into that premium now, then rebuy the same notional in cash pre-market once it reopens).computeCashAndCarryEdge(lib/market/arb.ts) takes adirectionparam that mirrors the sign; the toggle defaults to whichever side actually has an edge for the active symbol's current basis. A delta-neutral hedge note below the calculator explains pairing either side with a same-notional perp position to strip out the stock's own price risk — links to real, individually-verified venues (Hyperliquid, Avantis, Synthetix) for checking live funding, not a live integration this app computes itself (no third-party price/data API, on purpose — see "Why the math is done the way it is"). Also shows the same amount priced as a full-range LP position (≈50/50 by value — exact for full-range concentrated liquidity, with a caveat that Aerodrome defaults new deposits to a narrower range). Below that, a liquidity-depth chart (lib/market/depth.ts) reconstructs active liquidity across a ±25% price window from the pool's own tick-bitmap/ticks()data — no subgraph, no indexer. Slipstream'sticks()returns 10 fields, not upstream V3's 8; until 2026-10-12 it was decoded with the V3 layout, every read failed, and the chart showed the current tick's liquidity flat across the window. The fix was checked by summing the USDC the reconstruction puts below the price against each pool's real USDC balance (within ~2% for all twelve). The chart doubles as an interactive LP range selector: drag its two handles to size a candidate range and see, live, its capital efficiency (lib/lp/lpRange.ts— derived from the same virtual-reserve equations as the impact curve, not a recalled formula), an estimated fee APR for the range (the APR a full-range unstaked position earned, read from the pool's ownfeeGrowthGlobalcounters, times that multiplier;rangeAprPctinlib/lp/lpRange.ts), the probability the range is still in range at the same 7-day horizon My Lots uses for real positions, and a divergence-loss-at-boundary figure (computeDivergenceLossAtBoundary,lib/lp/lpRange.ts) — the standard concentrated-liquidity impermanent-loss benchmark if price reaches exactly the low or high edge, verified against the classic Uniswap V2 IL formula in the full-range limit before trusting it. Dragging itself is gated behind an explicit "Adjust range" toggle, off by default — the range stays visible either way, but a finger landing on the chart on mobile scrolls the page instead of getting captured as a drag unless that toggle is on. Handles clamp to each other and to the current price, so a dragged range always brackets it — the underlying math assumes that. Below the range metrics, an auto-recenter note explains what re-centering an out-of-range position actually involves and links to Gelato Web3 Functions and Bankr for building that automation yourself — Afterbook doesn't run it, for the same reason it doesn't construct swap calldata (see "Why the math is done the way it is" above). A "Copy trade" button copies the sized trade as plain text. When a symbol has real earnings-move history (see below), Lot Lab also shows an earnings volatility spread: how many days of the stock's realized volatility the pool's own liquidity concentration (lib/lp/lpRange.ts's highest-density-region construction) would justify, compared to the actual days until the next report and the historical average size of this stock's post-earnings moves (lib/stocks/earningsHistory.ts). Not implied volatility in the options-market sense — there's no options market on these pools — a liquidity-concentration proxy translated into a comparable "days" unit via the same realized-vol model used elsewhere, not a fabricated number. -
My Lots: a wallet chip, summary cards (total / spot / Aerodrome LP value) and one card per holding (spot as icon, USD value and share of holdings; LP with an in-range badge and range bar). Connect a wallet — a RainbowKit picker showing every installed browser-extension wallet (Rabby, Coinbase Wallet, etc., detected live via EIP-6963) plus a manual fallback, read-only — the connection only reveals your public address, nothing is ever signed — to see spot share balances and Aerodrome LP positions across the tracked stocks, priced live. Shows your Basename instead of the raw address when one's set, resolved directly against Base's own L2Resolver — no separate mainnet RPC, no extra dependency. LP position data comes from each CL factory's own NFT position manager (Aero's
0x4857…C60b; the older factory's0xe1f8…8b53, not the publicly documented0x8279…one, which is bound to a different factory), plus positions staked in each pool's gauge (stakedValues); amounts and uncollected fees are computed from the pool's ticks (lib/lp/lots.ts). Until 2026-10-27 this used Aerodrome's "Sugar" helper (positionsByFactory), which stopped returning live positions after the Aero upgrade, and Aero has none. Positions in the 12 original stocks' old pools (before the Aero move) still show, marked as in the older pool. Each LP position also shows its price range with in-range/out-of-range status, and uncollected fees (emissions and lock expiry were Sugar fields and are no longer read). The range is now also a visual bar marking where the current price sits, plus two estimates: fee APR for the position's own range while it is in range (from daily on-chain snapshots of the pool's ownfeeGrowthGlobal0X128/feeGrowthGlobal1X128counters, which are fees per unit of unstaked in-range liquidity, already net of Slipstream's 10%unstakedFeecut; turned into a full-range APR and multiplied by the range's capital efficiency, not a third-party volume API). Until 2026-10-12 this was "fees x one snapshot's active liquidity / pool value", which swung with whatever liquidity the snapshot caught, counted staked liquidity (up to 96% of a pool) that earns no fees, and then got multiplied by capital efficiency on top of already-concentrated LPs: Lot Lab showed 6,093% for an NVDAc range that earns about 12% and the odds the price is still in range 7 days out (from realized volatility of recently-sampled on-chain price, via a standard lognormal estimate). Both are on-chain-only by design — no third-party price/volume API. In-range odds still start as "collecting data" until enough samples exist, but fee APR no longer does:computeFeeAprWithFallback(lib/lp/feeApr.ts) falls back to summing real Swap-event volume over the last hour, found by block timestamp (blockAtOrBeforeinlib/market/blocks.ts) and read in 2,000-block chunks, mainnet.base.org'seth_getLogscap (until Base's Denim upgrade on 2026-11-05 it read a fixed ~1,900 blocks, an hour at 2 s blocks, which at 200 ms would have been 6 minutes; the estimate costs about 20 RPC calls, so each pool's is kept in memory for 5 minutes, a null for 1) and annualizing that window's fee per unit of liquidity (fee on each swap's input, less the unstaked cut, over the swap's liquidity), whenever there isn't yet enough feeGrowthGlobal snapshot history — verified end-to-end against real chain data for three live pools before trusting it. Labeled "prelim." in the UI so it doesn't read as the same-confidence real figure. My Lots also shows a gauge-vs-fee yield comparison (lib/lp/gaugeYield.ts): the AERO staking APR for the same range (rewardRateper unit of staked liquidity, on the same full-range-times-capital-efficiency basis as the fee APR) next to the unstaked fee APR above, so the panel says outright which currently earns more. Out-of-range positions say they earn neither. AERO's own USD price is read from a real on-chain Aerodrome pool (found via the CL factory'sgetPool, not hardcoded) — this app previously had no AERO price source at all and showed emissions as a raw token amount for exactly that reason; that gap's closed now. Staked liquidity's USD value can't use the same virtual-reserve math the impact curve does (that describes trade-impact behavior, not actual holdings, and overstates a concentrated position's real value) — instead it scales the pool's real, balance-based depth by the staked/total liquidity ratio, an approximation that assumes staked and unstaked positions are concentrated similarly on average. A position also gets flagged when the most recent epoch's veAERO voting incentives (bribes, from Aerodrome'sRewardsSugar.epochsByAddress) outpaid real trading fees for that same pool/epoch — a signal that a pool's gauge APR may be governance-subsidized rather than earned from organic volume. -
Approvals (
/portfolio#approvals,RouterApprovals.tsx, 2026-11-03): what KyberSwap's router (the only contract Afterbook's swaps approve) may still spend from the connected wallet, read for USDC and every tracked stock token in one multicall and shown as an amount or "unlimited". Each row has Revoke, which asks the wallet forapprove(router, 0)with the Builder Code (revokeRouterinuseSwapWallet.ts). Afterbook's own approvals are exact and used up by the swap, so a row means a basket run stopped part way or the wallet approved the router elsewhere (KyberSwap's own site uses the same router); the basket panels' "still approved" notes link here. Approvals to other contracts are not listed. -
Visitor counts (
app/layout.tsx): Vercel Web Analytics (@vercel/analytics, the<Analytics />tag, switched on in the Vercel project's Analytics tab). It is cookieless, stores no personal data and counts page views and visitors per page and referrer; it knows nothing about wallets. The script is served from the site's own/_vercel/insights/path, so the CSP needed no change ('strict-dynamic'covers it), and it 404s undernext start/next devlocally, which is expected: only the live site can confirm it. Outbound clicks are logged separately (lib/server/clicks.ts). -
Deposit visibility (
BasketPanel.tsx): the USDC held in the user's Basis Tilt smart account is read straight from the chain every 15 seconds (balanceOfon the deposit address), so a deposit is visible as soon as it confirms. If Glider's positions still say $0.00 the panel explains that the money is the user's, only they can withdraw it, and Withdraw stays off until Glider counts it; after a send it links the transaction on Basescan. Measured 2026-10-08: a 2 USDC deposit showed on-chain at once and Glider counted it in about an hour (not at the daily run, whosenextDueAtis shown by the API but is not what triggers the count). -
Base Builder Code (ERC-8021,
lib/wallet/builderCode.ts):bc_hebg61t4, registered at base.dev, is appended to the calldata of every transaction the app asks a wallet to send, so Base can attribute that activity to Afterbook (the dashboard is Settings → Project Settings → Builder Code; it tracks transactions, not website visitors). The app sends four kinds: the USDC deposit on the Baskets panel; the exact-amount approval and the swap in the Execute panel's Buy / Sell, a/buildbasket buy or sell and a meme buy ("In-app swaps"; all four go throughuseSwapWallet.ts); Portfolio's Revoke, an approval of zero (see Approvals); and the in-app Aave loan's approvals,multicall,repayandwithdraw(see Borrow). Liquidity still happens on Aerodrome's own site and cannot carry the code. It is passed per call asdataSuffix(the swap, sent withsendTransaction, has it appended to its calldata withconcat): a code set increateConfigis ignored byuseWriteContract(wevm/wagmi #5248, open in 2026-10). Check any transaction by its calldata ending in80218021802180218021802180218021. -
Wallets (2026-11-03): Base Account (RainbowKit's
basewallet: a passkey sign-in in a Coinbase window, no seed phrase) is first in the list everywhere. It was left out until then because its SDK pulls in a Solana package that isn't installed;serverExternalPackagesinnext.config.jsalready keeps the build out of that path. On a phone in a normal browser (no injected provider) the list is just Base Account and WalletConnect, whose entry opens WalletConnect's own "All Wallets" window (a search box over hundreds of wallets, with MetaMask, Rabby, Base, Trust, Rainbow, OKX and Zerion first:explorerRecommendedWalletIdsinlib/wallet/wagmiConfig.ts); from 2026-10-05 until 2026-11-03 Connect opened that window directly on phones. The ids come from WalletConnect's registry:curl 'https://api.web3modal.org/getWallets?projectId=<id>&st=appkit&sv=html-core-1.7.8&page=1&entries=5&search=<name>&chains=eip155%3A8453', with curl, not Python urllib which gets a 403. In that window you pick a wallet, tap Open, and the wallet app opens, approves and returns. Desktop, and a phone inside a wallet app's own browser (injected provider present), get the full RainbowKit list;modalSize="compact"removes the "What is a Wallet?" panel on desktop (a small "New to Ethereum wallets? Learn More" footer remains). MetaMask is not in the RainbowKit list: its entry uses MetaMask's own SDK relay and did nothing when tapped on a phone, while MetaMask works through WalletConnect's list; on desktop it also clashes with Rabby (see below). The project id is public (inlined in the browser bundle, so env changes need a redeploy) andafterbook.appis on the Reown Cloud project's allowlist. The CSP (middleware.ts) allowsblob:images (the wallet icons) andverify.walletconnect.org/.comframes; Google Fonts for that window stay blocked on purpose (system fonts are used). -
Wallet connect mechanics:
app/providers.tsx/lib/wallet/wagmiConfig.ts(wagmi + RainbowKit), with a second always-visible "Connect wallet" entry point in the header (app/components/layout/WalletConnectButton.tsx) alongside My Lots' own — both read the same global wagmi account state, so connecting or disconnecting from either stays in sync. Disconnect callswallet_revokePermissions(MetaMask's real revoke) before clearing local state — clearing local state alone leaves the wallet extension still considering the site authorized, so the next Connect would silently reuse the same account with no way to switch. NometaMaskWalletentry, deliberately: RainbowKit's per-wallet detection is flag-based (window.ethereum.isMetaMask), not EIP-6963/rdns, and several alternative wallets (Rabby included) set that same compatibility flag for dapp-compat purposes — with both installed, whichever wallet currently holdswindow.ethereumanswers to "MetaMask" regardless of which one is real, and confirmed in practice (Error: MetaMask extension not found, thrown from inside the click) rather than just connecting to the wrong wallet silently.rabbyWallet's own entry checksisRabbyspecifically, which only Rabby sets, so it doesn't have this ambiguity; the generic "Browser Wallet" entry remains the correct fallback for a real MetaMask-only setup with no other flag-setting wallet installed. WalletConnect/mobile-wallet options (and Trust/OKX/Zerion/Rainbow, whose desktop connectors fall back to WalletConnect when their own extension isn't installed) only appear whenNEXT_PUBLIC_WALLETCONNECT_PROJECT_ID(a free Reown Cloud project id) is set — without one, that connector eagerly opens a relay socket at page load and, observed directly, spins a Chrome renderer's CPU into a runaway climb rather than failing quietly, so it's left out entirely rather than shipped half-working. Every extension-based wallet (Coinbase Wallet, Rabby, plus any other EIP-6963-announced extension via the generic "Browser Wallet" entry) works with no env var at all. Thebase/"Base Account" wallet is first in the list since 2026-11-03 (see Wallets above for why it was left out before). It is RainbowKit'sbasewallet wrapped inlib/wallet/baseAccountWallet.ts(2026-11-19): wagmi 2's Base Account connector answered every page reload's reconnect withwallet_connect, which needs a Coinbase window, so each reload opened one (or, with the window blocked, showed "Afterbook wants to continue in Base Account → Try again") and dropped to "Connect wallet" until the person signed in again. The wrapper reconnects witheth_accountsfrom the SDK's saved session, which never opens a window, as wagmi 3's connector does; a real click on Base still goes through the original connector. Base Account is a smart wallet, which has two known gaps: its swaps reach the chain as a bundled transaction (to the EntryPoint, from a bundler), which the swap log reads inside the user operation since 2026-11-18 (it refused them before, so/api/swap/statsundercounted Base Account trades until then); and whether Glider accepts its passkey (ERC-1271) signatures for a basket enroll or withdrawal has not been tested. Whether Base credits the Builder Code inside a bundled call is also unconfirmed. -
Execute: Buy / Sell the stock in-app from the connected wallet (
SwapPanel.tsx, see "In-app swaps"), plus Aerodrome's own swap and add-liquidity UIs under "Or trade on Aerodrome's own site", all gated behind a non-US geo check and an eligibility checkbox./todaylinks to the biggest gap's Execute panel (/<SYMBOL>#execute). A one-line trade summary ("AMZNc · $2,500 · ~9.67 sh · pool 0xd03B…") sits above the eligibility checkbox, visible regardless of whether it's checked — a user shouldn't have to affirm a legal checkbox just to see what they'd be trading — with its own "Copy lot" button that copies the whole line as plain text (AMZNc $2500 ~9.67 0xd03Bc8..., full untruncated pool address) for pasting into a chat/ticket/agent prompt. Aerodrome's swap URL only acceptsfrom/to/chainparams — no amount (verified live: typing into the Sell field updates the page but never the URL, and an&amount=param is silently ignored) — so inside "Or trade on Aerodrome's own site" a "Copy $X" button copies just the bare numeric amount for Aerodrome's own amount field, and a 3-step checklist (copy → open → paste and sign) spells out the sequence. Those Aerodrome links are secondary buttons now; the panel's one primary action is the swap's Review / Buy. Below the token/pool addresses, a backing & issuer note shows the token's livetotalSupply()(real, on-chain, confirmed via a direct contract read) next to the custodian claim (Alpaca Securities, ADGM-supervised, 1:1, per Coinbase's own published docs) — explicitly labeled as the issuer's stated claim, not something this app verified, since there's no on-chain reserve-attestation contract for B20 tokens the way there is for some wrapped assets (checked directly:owner()/paused()both revert on the token contract, so there's no standard admin/pause interface to read either). -
Log: a session-local, timestamped feed of notable events (starting with "cash just closed" plus each liquid symbol's basis at that instant).
-
Telegram alerts:
/alert STOCK BP(NVDAorNVDAc, any case) pings when a stock's |basis| crosses a threshold, then re-arms only once the gap is back to 80% of the level or lower (REARM_RATIOandnextBasisStateinlib/alerts/alerts.ts; before 2026-10-08 it re-armed the instant the gap touched the line and a gap hovering near 50 bp sent about 14 messages in a day and a half, visible in a user's public screenshot), and a missing tape reading keeps the state so a data blip can't re-arm it;/closepings once with every liquid name's basis the moment the cash market closes.- Loan alerts (since 2026-10-14):
/watch 0xADDRESS [HEALTH]watches a wallet's stock-backed USDC loans on Base, Aave V4's MAG7 spoke and every listed Morpho stock market (lib/lending/loanPositions.ts, on-chain reads; Morpho Blue0xBBBB…EFFCb).- When it warns: once, when the lowest health drops below the threshold (default 1.2, allowed 1.01–3; liquidation is below 1.00). It re-arms only above threshold × 1.05 (
nextLoanState,LOAN_REARM_FACTORinlib/lending/loanHealth.ts). - Aerodrome's price: health is also worked out at Aerodrome's price, the edge here. Lending oracles follow the shut cash market while Aerodrome trades, so the warning can come before the oracle moves, and the message says when that is the reason.
- Failed reads and closed loans: a failed read keeps the state, so it can't fire or re-arm. A wallet with no loans re-arms. Posted collateral or an open Morpho position whose oracle price couldn't be read counts as a failed read, never as a smaller loan or no loan (2026-11-21).
- Limits: one wallet per chat, the free tier (
MAX_LOAN_RULES_PER_CHAT); a second/watchreplaces the first. More wallets and custom thresholds are the planned paid tier. /loansshows the watched wallet's loans now./plan STOCK [STOCK…] USD(2026-11-22,lib/alerts/telegramPlan.ts): e.g./plan NVDA 100, up to 4 stocks. The same checked plan as/planand the MCPmake_plan(runPlan, fixed words, never Claude, the page's default limits), one line per stock from the code's verdicts and sizes, and, when there is a buy, a saved plan link (via: 'telegram', see "Plan links") that opens on afterbook.app, where the person connects their own wallet and signs each buy after the checks run again. 10 a minute per chat (mcpPlanLimiteronly, keytg:<chat>; no in-memory limit as on the MCP route) and the same 300 saved links a day site-wide (planLinkDailyLimiter). The plan has 25 s, a reply send 10 s, and each Telegram update is answered once (tgupd:<update_id>, an hour), so a resent update doesn't plan, save or reply twice. A stock onAUTO_PICK_HOLDsays the link won't offer it. The bot itself never asks for a wallet or a signature.- Delivery (2026-11-21): an alert counts as sent only when Telegram accepts it or refuses it for good (403, or a 400 saying the chat was not found: the bot was blocked, the chat is gone; any other 400 is retried;
sendTelegramMessageStatus,stateAfterSend); otherwise the rule keeps its state and the next run tries again; one run sends at a time (alerts:lock, 120 s, over the run's 60 s limit), since Vercel can double-invoke a cron. Rules are read in a few MGETs and chats are checked 8 at a time within a 30 s budget (each loan read and Telegram send limited to 10 s, so a run ends inside its 60 s; if the re-read before a write fails, the run's own state is saved), from a random starting chat each run; a chat whose state changed is re-read just before its write and onlyactive/failedReadsare carried onto its current rules by id, so a/stopor a rule changed in the bot meanwhile isn't undone; one chat's error is counted and the run goes on; each run logs and returns how many chats it checked, couldn't read, or skipped for time (2026-11-22). After 30 minutes of failed reads of a watched wallet (LOAN_READ_FAIL_NOTICE, kept per rule asfailedReads) the chat gets one heads-up that warnings are paused until it can be read (the count stops there, so an unreadable wallet doesn't rewrite the rules every tick). Weekend and holiday heads-up (2026-11-22,longBreakCloseinlib/market/marketClock.ts,longBreakTextinlib/lending/loanHealth.ts): once after-hours trading has ended (8 pm ET, 5 pm after a 1 pm early close) after a close that starts a weekend or a holiday (the next trading day isn't the next calendar day), each watched wallet with a loan gets one message with, per loan, its health if the next open matches Base's price. Far from the person's line it leads with "Market break check…: nothing urgent" and has no links; with the lower of health now and at Base's price under 1.25x their alert threshold (HEADS_UP_URGENT_FACTOR, owner 2026-11-22) it is a heads-up with an Aave loan's repay/add links. Once per such close per rule (breakSent, carried by the re-read likeactive; a/watchmade during the break starts with it set, since its reply already shows the loan; the holiday list covers 2026 and 2027, and past it no heads-up is sent), only after a good read, only once Telegram accepts it; a warning due on the same tick goes first. Not built: a staleness check on the oracle price (only a missing price is a failed read) and a second, "critical" warning level. - Repay and add-collateral links (2026-11-21,
lib/lending/rescueLink.ts): a warning about an Aave loan ends with two links to/borrow?rescue=repay|add&fall=…&target=…#borrow-here. They preset the rescue planner (the fall the oracle would take to reach Aero's price, rounded up to the planner's next choice, and its first target above the alert's line) and fill the panel's own Repay or Add field once, from the connected wallet's live loan (only if the wallet holds the USDC or one of the stocks). The link carries no amount and no wallet, a value that isn't one of the planner's own choices is ignored, and the person checks it and signs with the panel's usual button and exact approval, with the Builder Code. Morpho loans get no link (no in-app Morpho panel). - Storage: the address is stored with the chat's rules in Redis until
/stop. Addresses are public, and the bot never asks anyone to connect a wallet or sign anything. - Checked against the sources: health matches Aave's
getUserAccountDataand Morpho's API to 4 decimals (checked 2026-10-14 on real borrowers).
- When it warns: once, when the lowest health drops below the threshold (default 1.2, allowed 1.01–3; liquidation is below 1.00). It re-arms only above threshold × 1.05 (
- A Vercel Cron job re-evaluates every 5 minutes against live tape data and fires only on the transition, not every tick a condition holds. The bot is @afterbook_bot (
t.me/afterbook_bot, linked from the tape hero); its display name, "AfterbookAlertsBot", is not a username andt.me/AfterbookAlertsBotdoes not exist.
- Loan alerts (since 2026-10-14):
-
Live ticker strip under the header on every page: each stock's on-chain price with a coloured ▲/▼ for its live basis, as a slow marquee. Each item links to that stock's page (
/NVDAcetc.). It pauses while a mouse hovers it (only on devices that really hover — see the note inapp/styles/layout.css), runs again on leave and right after a tap, and never pauses on focus or press.prefers-reduced-motionstops it. -
Today's gap (
/today, "Biggest gap" until 2026-10-19): the single biggest cash-vs-chain gap right now as a hero card (icon, gap, cash and onchain prices, and what it takes to trade it: price impact of a $25k clip and the size needed to move the price 50/100 bp), liquidity-behind-the-tape stat cards, and a "who mean-reverts at the open" card per stock. The mean-revert stats are cached 10 minutes (unstable_cache) because they read thousands of history samples per symbol. -
Borrow (
/borrow): every USDC lending market on Base that takes a tracked stock as collateral, from two lenders, in one shape (lib/lending/lendingMarket.ts):- Morpho (
lib/lending/morpho.ts): listed markets only; the market list, rates and totals come from Morpho's public GraphQL API, and the oracle price is read on-chain from each market's oracle. - Aave V4's Equities Hub (
lib/lending/aave.ts, since 2026-10-14): read straight from the contracts, with no API or key. The hub0xa4d5…864Eis one shared USDC pool; the "MAG7" spoke0x1790…7B8Dtakes 7 stock tokens. Addresses are from Aave's address book (bgd-labs/aave-address-book,AaveV4Base.sol).- Per stock: collateral factor (used as the LLTV), collateral pledged and its cap, and the spoke oracle's price (8 decimals; a USDC sanity check throws if the units ever change).
- Borrows, rate (
getAssetDrawnRate, RAY per year) and the borrow cap belong to the shared pool, so an Aave market'sborrowUsdisnulland the page shows the pool once. - The liquidation incentive is
1 + (maxBonus − 1) × liquidationBonusFactor × (1 − liquidationFee), the smallest bonus, about 4.46% today (aaveV4LiquidationIncentiveFactor).
- One lender failing to load leaves the other on the page.
- Borrow with Aave (
#borrow-here, since 2026-11-03;AaveBorrowSection.tsx,AaveBorrowPanel.tsx,lib/lending/aaveBorrow.ts): an in-app USDC loan on Aave's MAG7 spoke, from the visitor's own wallet, behind the same region check and eligibility box as trading. While the cash market is fully shut (overnight, a weekend or a holiday; not pre-market or after-hours), the loan's summary adds "If Monday opens at Base's price: health X" (2026-11-22): Aave's own health scaled by the collateral's value at Base's per-token price (from/api/tape, hidden when the tape is carried over or over 90 s old) over its value at the oracle (healthAtPrices). Display only, never an amount or a limit. With a wallet that runs batches atomically on Base (Base Account), each action is one signature (2026-11-24,lib/lending/aaveBatch.ts): the exact approval of what the spoke pulls (only if the allowance is short) and the spoke call (the borrow multicall, repay or withdraw; the lend panel's supply or withdraw) as one atomic batch, refused unlessaaveBatchProblempasses: only approvals of a reserve's own token naming the spoke, never unlimited, each exactly what the batch's supply or repay pulls (a full repay at most the panel's capped buffer), and only spoke calls on behalf of the signer, all with the Builder Code. Each batch is dry-run on Base first (as single swaps are) and isn't sent if it would revert. Other wallets keep the two steps. On the owner's real borrow and repay (2026-11-24) the browser blocked Base Account's second window every time. Aave, not Morpho, because that is where the USDC is: on 2026-11-03 the Equities pool had $1.23M to lend at ~3.6%, the listed Morpho stock markets about $3,200 in total.- Contract facts (verified that day against the deployed implementation's full Sourcify match,
SpokeInstance, solc 0.8.28): the spoke pulls tokens itself, so approvals name the spoke; borrow and withdraw pay the caller; every action needsonBehalfOf= the signer (no position managers are set up); supplying does not make collateral,setUsingAsCollateraldoes;repaycaps an oversized amount at the debt;multicallruns on the spoke itself. - Borrow: an exact approval of the stock for the spoke (skipped when it already covers it), then one
multicall:supply,setUsingAsCollateral(only if not on yet),borrow. Either half can be left out. "Max" is the protocol limit (health 1.0, owner's choice) less 0.5% so a price tick or a few minutes' interest doesn't revert it, capped at $25,000 per borrow and the pool's free USDC. - Repay: exact approval and
repay, or for "All" the debt plus 1 bp and one unit (repayAllApproval) andrepay(MAX), which takes only what is owed. Withdraw:withdraw, at most what keeps the loan within the limit (less the margin); everything with no debt. - Shown before signing: collateral, debt, Aave's own health factor, and after the change the projected health and how far all collateral can fall together before liquidation (
1 − 1/health), red under 1.25. The panel says stock prices can stop updating while the market is closed and that interest runs all weekend. - Rescue planner (2026-11-08, for the Stocks Maxxing entry;
LoanRescue.tsx,lib/lending/rescue.ts): shown in the panel when the wallet owes USDC. The person picks a stress (prices as they are, or every stock 10/20/30% lower together; the USDC debt doesn't move) and a health to keep (1.3, 1.5 or 2.0). It shows the health under that stress and the two ways back to the target: the USDC to repay (rounded up to a cent, "all" when only a full repay gets there) and, for each stock the wallet holds, the tokens to add as collateral (the smallest amount that reaches it, found with the same maths the panel's projection uses, so a stock posted but not yet counted as collateral is handled). Each amount is worked out for the target plus 0.2% (RESCUE_MARGIN) for interest and rounding. When the wallet holds less, it offers what the wallet holds and the health that reaches. A button only fills the panel's own Repay or Add field and switches to that tab: the panel's button, its exact approval, its checks and the Builder Code do the rest, so the planner adds no transaction code. It turns itself off when its health and Aave's own differ by over 2% (RESCUE_MAX_MODEL_GAP: after a governance change to a collateral factor, the user's snapshotted factor differs from today's, and a repay or add doesn't refresh it); inside that, when Aave reads lower, every health shown is scaled down to Aave's and the amounts aim that much higher, so the result reaches the target on Aave's own number. A full repay is offered only when the wallet holds the debt plus the interest buffer (repayAllApproval), otherwise just under the debt; amounts in its sentences are exact, never rounded, so they match the filled box; and adding to a stock posted but switched off as collateral says that it turns it on. Checked on 2026-11-08 against real loans (health 1.16 and 1.17, read with a fake wallet that refuses to sign): its health matched Aave's, and a fill led to an approval of exactly the filled amount to the spoke, with the Builder Code. Tests:tests/loanRescue.test.ts. - Checks: each stock reserve's token and decimals, the USDC reserve and the oracle address are read from the spoke and compared with what the page expects; any mismatch or failed read pauses the panel. Debt is valued at the oracle's USDC price, as Aave does, and a wallet with debt in another asset on the spoke gets a pause (only USDC loans are modelled). The current health shown is Aave's own (it uses the collateral factors snapshotted for that user); the projection uses today's factors, which every borrow or withdraw applies, so the two can differ only after Aave governance changes a factor. The region and eligibility gate is in the page only: the calls go straight to Aave, with no Afterbook server route in between. Every call carries the Builder Code. Tested with
eth_simulateV1from real holders (borrow, repay all, withdraw all; max withdraw passes, 10% over reverts) and a fake wallet.
- Contract facts (verified that day against the deployed implementation's full Sourcify match,
- Lend USDC with Aave (
#lend-here, since 2026-11-03;AaveLendSection.tsx,AaveLendPanel.tsx, the lending part oflib/lending/aaveBorrow.ts): deposit USDC into the same spoke's USDC reserve, i.e. the Equities pool the loans above borrow from, and withdraw it, behind its own region check and eligibility box (which also says lenders can lose money and may wait to withdraw). Later on 2026-11-03 the pool had $6.42M lent in, 85% borrowed ($0.97M free), lenders earning ~2.9% a year.- Deposit: an exact USDC approval for the spoke (skipped when it covers it), then
supply(usdcReserve, amount, signer); at most $25,000 per deposit (MAX_LEND_USD) and the wallet's balance. Withdraw:withdraw(usdcReserve, amount, signer), at most what the wallet supplied and what the pool has free (getAssetLiquidityon the hub, read live); taking everything sendsMAXso the last interest comes too, but only when the pool's free USDC exceeds the deposit by 0.1% plus $1 (lendWithdrawArg); balances, allowance and free USDC are re-read just before the first wallet call. - Contract facts (same deployed source): supply never turns a reserve on as collateral, and USDC's collateral factor on this spoke is 0, so a deposit never counts toward borrowing; withdraw runs the health check only for a collateral reserve, so lending and a loan in the same wallet don't affect each other, unless the wallet has switched USDC on as collateral elsewhere (the spoke allows it even at factor 0; then a withdrawal re-checks the loan), in which case the panel pauses. A withdrawal larger than the pool's free USDC reverts.
- Shown: what the wallet has lent (interest included) and about what it earns a year at today's rate, the lenders' rate (borrow rate × utilization less the hub's fee, before incentive programs) and utilization, and the pool's free USDC. The panel pauses if the USDC reserve's token, decimals, hub or asset id changes or the reserve is paused; a frozen reserve blocks deposits only. Every call carries the Builder Code. Tested with
eth_simulateV1(deposit $1,000, withdraw $400, withdrawMAX: back to the start less one unit of rounding; a deposit without approval reverts) and a fake wallet.
- Deposit: an exact USDC approval for the spoke (skipped when it covers it), then
For each market: borrow and lend rates, collateral and borrows, USDC still free to borrow (Morpho per market; Aave from the shared pool, within its borrow cap), the Aero-vs-oracle gap, and how much a liquidator could sell on Aerodrome right now and still profit (
lib/lending/liquidationRisk.ts). The card shows that as "Aero exit": a word first (aeroExitinlib/lending/borrowSummary.ts: Deep if the pool could take the market's whole collateral twice over, Tight if just, Short if not in one go), then the amount, in neutral colours on the page and the share card (owner decision 2026-10-15: it is a worst case, not an alarm). It is a worst case (every loan liquidated at once); the page says real liquidations are usually much smaller, especially on Aave. Each card's "Check a loan" link (#check=<marketId>) opens the calculator on that market with a 40% loan. The cards (.borrow-grid) are at least 280px wide, one line per row with values right-aligned, the rate labelled beside the big number, and a rule between the loan terms and the liquidation risk; Aave cards drop the Borrowed row (the pool is shared, the note above says so). Morpho Blue's liquidation incentive ismin(1.15, 1/(1 - 0.3*(1 - LLTV)))(lib/lending/liquidationMath.ts); each market carries its own incentive, so a liquidator who sells on Aerodrome profits only while the average fill stays above oracle / incentive. Fills are simulated sell-side by walking the pool's real tick liquidity within 25% of the price (lib/market/swapSim.ts, on top oflib/market/depth.ts), sinceestimateLotonly models buys within one tick. A "Check a loan" calculator (app/components/lending/BorrowCalculator.tsx, same pure math as the API) gives the liquidation price, room to fall, and whether Aerodrome could absorb that liquidation, assuming the same liquidity per tick and the same gap at the liquidation price (depth scales with the square root of price under that assumption, not linearly). Markets with no collateral collapse to one line. "Morpho ↗" links follow the same non-US gate as Aerodrome links; Aave cards link to the spoke contract ("BaseScan ↗"), because Aave's own app link for this market is not confirmed. Aave liquidates only enough of a loan to restore its target health (1.24), so the calculator's whole-loan seizure is an upper bound there. Afterbook signs nothing on this page. - Morpho (
-
Build a basket (
/build,/build/<spec>): pick 2–4 tracked stocks and whole-percent weights; the basket lives in the URL (/build/NVDAc-40_AAPLc-30_METAc-30, or/build/NVDAc_AAPLc_METAcfor equal weights;lib/build/customBasket.tsparses and renormalizes it, and a malformed one is a real 404 viaapp/build/[spec]/layout.tsx). Changing the basket keeps your scroll position: the picker navigates withscroll: falseinside a transition, and the route deliberately has noloading.tsx, whose full-page placeholder replaced the page on every change and made it jump to the top. It shows the basket's weighted gap with the home hero's rules and labels (close-anchored while cash is fully closed,cashPriceType-driven wording otherwise), each leg's contribution, and what buying $1k / $10k / $50k of it costs on Aerodrome, plus the largest buy under 1% total cost (lib/build/basketCost.ts). Costs walk each leg's slice through that pool's real tick liquidity (simulateBuyinlib/market/swapSim.ts), notestimateLot's single-tick math, which matches it for small sizes but understates large ones (NVDAc $100k: 14.5 bp walked vs 8.2 bp single-tick on 2026-10-12). Each basket has its own share card (buildBasketOgImage)./buildredirects to the three deepest pools at equal weights. "Buy or sell it" buys or sells the basket from the visitor's wallet (see In-app swaps → Basket buys); nothing here touches Glider or Basis Tilt. In the header nav as "Build", and linked from/basketsand/today. Five links fit the phone nav down to 320px only because "Biggest gap" reads "Gap" at 420px and below (owner decision, 2026-10-12;shortinSiteHeader.tsx, screen readers still get the full label). The two-row phone header now applies up to 980px: at 641–900px the one-row nav used to be cut off. -
Trade plan (
/plan, owner 2026-11-08; linked from More): a person picks stocks (or "the 5 deepest"), a budget, the most they'll pay over the real stock, the most a fill may cost, and whether to wait before earnings, plus an optional note. Afterbook's code decides; Claude only explains.lib/agent/plan.tschecks each stock in order: a fresh price (else skip), a pool of at least $250k (TAPE_MAIN_DEPTH_USD, else skip), the gap against the same reference the hero uses (todayReference: the close while cash is closed; over 3% either way, wait, because a gap that wide is more often a stale pool or news than a bargain, BILIc read 9% below on 2026-11-08; over the person's limit, wait), and earnings within the chosen days (wait). A stock with no date is said to have no report in the next 14 days only if the earnings job's last full scan (15 days ahead,EARNINGS_SCAN_DAYS, every day fetched) is under 36 hours old (earnings:syncedAtin Redis); otherwise the plan says it couldn't confirm the date and to check before buying. The job tells a failed Nasdaq day from an empty one (fetchNasdaqEarningsForDatereturns null on failure) and, if any day failed, only adds found dates: it never deletes a saved one and doesn't moveearnings:syncedAt. It then splits the budget equally over what passed (a split under $10 a stock is skipped with that reason), caps each buy at the swap's own limits ($25k, 10% of the pool), and sizes it down until the walked fill cost (getBuyQuoter, price impact plus the pool fee, plus Afterbook's own fee ifSWAP_FEE_BPSis ever on) fits the person's limit; every reason is a sentence written from the numbers.lib/agent/explain.tssends the finished plan (as JSON, with the counts and, for each wait or skip, the one reason that decided it,decidedBy, apart from side notes such as an unconfirmed earnings date: on 2026-11-08 Claude, given one flat list, said a split-too-small skip was also because of the earnings warning) and the note (as quoted text, never instructions) to Claude (claude-haiku-5-5, no thinking, 400 tokens at most: a few sentences about numbers already decided; from an external review the same day, it was Opus with 4,000 tokens), which writes 3–6 plain sentences; it cannot change a verdict or a number, and is told never to forecast or call anything advice. Its reply is shown only if it finished (end_turn), ends a sentence, has no Markdown at all (*,_, backticks,#, links, list bullets) and says nothing banned: a forecast ("will rise", "will moon", "going up"…, punctuation after it included), "should buy/sell", or any form of recommend, guarantee, profit, advice/advise, moon, pump or price target (acceptExplanation, tightened after a second review found "NVDAc will rise." slipping through); otherwise the fixed words are used. WithoutANTHROPIC_API_KEY, over the limits (10 explained plans an hour per visitor, 500 a day for the whole site, RedisSafeLimiters) or if Claude fails, the same facts are explained in fixed words (fallbackExplanation) and the page says so. A buy that passes opens the normal swap panel (SwapPanel) pre-filled with that amount, behind the same region gate and eligibility checkbox, with a fresh quote and all the swap checks; nothing is signed by the plan. Past plans are kept in the browser only (localStorage['afterbook-plans'], last 20), each buy with the onchain price at the time and how far it has moved since (before costs). Traction (2026-11-08, for the Stocks Maxxing entry): each plan adds to an anonymous per-day count in Redis (stats:plans:YYYY-MM-DD: made, explained by Claude, with a buy; nothing about the person; the plan waits at most 300 ms for the count,lib/agent/planStats.ts), and a buy reviewed from a plan is built withsource: 'plan', so the swap log counts trades signed from a plan, their volume and distinct hashed wallets, each verified onchain like every swap.GET /api/agent/stats?days=30(cron bearer) returns both.POST /api/agent/planis the route (read-only,limitReadin the 10-a-minute bucket plus the Claude limits above; without Redis it never calls Claude). Tests:tests/agentPlan.test.ts,agentExplain.test.ts,agentRoute.test.ts. -
Describe a basket (
/plan, second tab, 2026-11-13): instead of picking stocks, a person gives a theme (fixed chips: AI chips, Memory & storage, Software & cloud, Internet & media, Consumer tech, EVs & autonomy, Health care, China, Outside the US, Bitcoin, Space, or Any), sectors to leave out (GICS), how many stocks to spread over (at least 2, 3 or 4, about 50/33/25% in each), a budget up to $25k (one basket buy), cash to keep (0–50%) and the plan's price, cost and earnings limits. The code picks; Claude only explains.lib/agent/brief.ts: the stocks with that theme (lib/stocks/sectors.ts, hand-made, checked against live sources 2026-11-13; a test fails if a tracked stock has no entry), minus the excluded sectors, with a pool that stayed over $250k for the last 3 hours (below), through the plan's ownscreenchecks, then the up to 4 deepest (ties by symbol), equal amounts of the budget less cash, sized bysizeLegs(the swap caps and the cost limit; what a leg is cut by stays as cash). The basket buy splits by whole-percent weights (34/33/33 for three), so the total is then lowered until no stock gets more than it was sized for, and each pick shows exactly what the buy will split; a stock under 1% of the basket is dropped with that reason (real-money review, 2026-11-13). A small budget takes fewer stocks (each needs the $10 swap minimum; too little for the spread asked is said as a budget problem), and a stock the cost limit drops is replaced by the next deepest that passed, and the basket is sized again (the 8 deepest that passed are the candidates,BRIEF_LIMITS.maxCandidates, and the route reads cost models for exactly those, each with an 8-second timeout after which that pool counts as unreadable; until 2026-11-14 the basket just shrank). When the cost limit leaves out every stock it was tried on, the page says that, not "No stock on Base meets this brief", and a stock past the 8 that was never tried says so rather than "4 with deeper pools made it". Whole-percent weights always add to 100 (apportioninlib/build/customBasket.tshanded out only about half the leftover points until 2026-11-13, so 5/5/3/3 gave 99% and the buy put the missing 1% into the biggest stock; this also fixed some/buildlinks). Every number in Claude's explanation must be one of the basket's own figures, rounded at most to 2 decimals and with its sign if it has one; small whole numbers up to 10 pass only as counts, never with $ or %; spelled-out amounts and scale words (thousand, million…) are refused (numbersAllowed; a number can't end on a comma, so "$147, and" is $147, while a decimal comma such as "3,40" is still refused: until 2026-11-13 any number before a comma threw the reply away); otherwise the fixed words are shown. It can't tell which stock a right number is said about, so the page's own figures below stay the reference. A depth reading is not saved when the cron's tape is the cached one after a failed fetch (tape.error), and right after a deploy the page says "readings only since HH:MM" instead of claiming 3 hours. The page shows how the stocks were narrowed step by step: every stock that passed the price and earnings checks is counted, and each later cut (the 4 deepest, what the budget covers, the cost limit) is a step of its own only when it removes a stock; until 2026-11-13 the limits step counted only the picks, so a live basket said "4 passed" when 15 had (external review). Fewer than asked: no basket, and the page shows those steps, why each stock was left out, and, if at least 2 passed, a button to spread over that many instead. Each pick shows its sector and themes, the gap, the fill cost and its pool's lowest depth with the time of the newest reading; fixed assumption lines from the code; no opinion. Steady depth (lib/market/depthSamples.ts): the 5-minute alerts cron writes every pool's depth as one key per run (depth:<5-minute slot>, 4-hour expiry, ~8,640 writes a month); a failed read is stored as missing, never $0; a stock's depth is the lowest good sample in 3 hours (and the live read, which can only lower it), and unknown (left out) if no good sample is under 15 minutes old, so a flickering pool can't get in on one lucky read (and right after a deploy the page says the readings aren't there yet). Claude (explainBrief, same model,acceptExplanationand limits as the plan, shared vialib/agent/explainGate.ts) gets the steps, picks, cash, shortfall and drop reasons (each dropped stock with its name: given only a ticker, it called SK hynix "Skyhigh"), pluscashWhywhen the cash is at least $1 more than asked, naming the real cause: a stock the cost limit or the swap caps cut (each pick'ssizedDownBy), else whole-percent weights and whole dollars ($118 of $1,000 with 10% asked); the first version always blamed the weights (review of PR #172). Claude must call stocks only by the given name or ticker and not say why a stock is a good or bad choice. Both/api/agent/planand/api/agent/briefreturnfixedBecausewhen the fixed words were used:not-configured(no key),no-limiter(no Redis limiters),rate-limited,cut-off(the reply hit the length cap),refused-by-checkorclaude-error(null when Claude explained it). "Review & buy the basket" opens/build'sBasketBuyPanelwith those whole-percent weights and the invested amount pre-filled (defaultUsd, editable; typing more than it shows a note that the plan didn't size that much and a stock may cost more to trade than the person's limit, without blocking it), behind the region gate and eligibility box: one exact approval, one checked swap per stock (source: 'basket').POST /api/agent/brief(read-only,limitRead10 a minute, counted in the same plan stats). Tests:tests/agentBrief.test.ts,depthSamples.test.ts,sectors.test.ts. -
Stock rules (
/rules, owner 2026-11-11; linked from More and/plan): recurring buys with the person's own limits, for example $50 of NVDA every Monday, at most 0.5% over the real stock, pausing within 2 days of earnings. A rule has a stock, an amount per run ($10–$25,000, the swap's cap), a schedule (every week or every other week on a chosen weekday, or monthly on day 1–28), an optional total cap, and the plan's limits (premium, fill cost, earnings). A rule never buys by itself. When a run is due the page shows it; "Check this run" posts the run's inputs toPOST /api/agent/rule-check, which runs the trade plan's ownscreen+sizeLegsfor that one stock with the run's amount as the budget (no Claude call;limitReadin the 10-a-minute bucket), and a run that passes opens the normalSwapPanelwith that amount (source: 'rule', Buy only, andmaxUsdrefuses more than the run may spend), behind the same region gate and eligibility checkbox. One buy per run: the run is saved as pending (with its hash, counted toward the cap) the moment the wallet sends the swap, becomes bought once mined (the check then closes), and a mined revert makes it due again. If the tab closes first, the next visit settles a pending run from its receipt (re-read every 30 s while open); while a buy is pending its swap panel is hidden, so no second buy can be made for the run. The swap panel is shown only while the checked run is still due, so once a run is pending or bought (in this tab, another tab via thestorageevent, or the chain check) no second buy can be made for it. The page settles a pending run only from a receipt (success → bought, revert → due again); an RPC error leaves it pending. A hash the node doesn't know, or whose nonce the sender has since used (a wallet "Speed up" mines the same buy under a new hash), is never freed automatically: after 30 minutes the page offers "It didn't go through" with a warning to check the wallet's activity first. The swap hook records the hash that was actually mined (a sped-up swap's) and treats a wallet "Cancel" as nothing bought. A passed check expires after 15 minutes, at midnight or when the rule is paused. The person can skip a run; a run that doesn't pass can be checked again later the same day. The schedule maths is pure (lib/agent/rules.ts, calendar days in the person's own time zone): a missed run stays due until the next scheduled day replaces it, so runs never pile up; the last run is cut to what is left of the total cap, and under $10 left the rule is finished. Storage is the browser only (owner choice: nothing to attack or leak on the server):localStorage['afterbook-rules']and['afterbook-rule-runs'](one per rule and day, a buy winning over a pending run over a skip; trimmed to 200, but never the bought or pending runs of a rule that still exists, since its total cap is counted from them), validated field by field on every read. Clearing site data deletes them and they don't sync, so the page says so and offers Export/Import (a JSON file,app: 'afterbook-rules', version: 1; import validates every rule, drops unknown stocks or bad values, replaces rules with the same id and keeps at most 12). A run is only noticed when the page is opened; there are no reminders yet.SwapPanel's optionalonBuySent/onBought/onBuyRevertedcallbacks (fromuseReviewedSwap'sonSent/onSendFailed, the exact USDC reviewed and the hash) keep the history; they change nothing in the swap. Traction: each check addsruleChecks(andrulePassed) to the same day hash as the plans (countRuleCheck), and/api/agent/statsreturnsruleSwapsfrom the swap log. Tests:tests/agentRules.test.ts,agentRuleRoute.test.ts,planTraction.test.ts. -
Rebalance rules (
/rules, second kind of rule, owner 2026-11-14): target weights for 2–4 stocks (whole percents adding to 100) on the same schedules, amounts, caps and limits as a stock rule. Buy-only top-up: each run puts new USDC into the stocks under target and never sells (selling to rebalance is planned after the quest as an opt-in with a drift threshold). "Check this run" reads what the connected wallet holds of the rule's stocks onchain, all at one Base block (balanceOf; the page shows the time and block), and posts only the balances, targets, amount and limits toPOST /api/agent/rebalance-check(read-only,limitRead, no model, never the address). The route values them as tokens × the B20 multiplier × the onchain price (as My Lots does), andlib/agent/rebalancePlan.tssplits the run withtopUpSplit(lib/agent/rebalance.ts): each stock's shortfall is how far it is below its target share of holdings plus the run; the run goes to those below in proportion to the shortfall (with nothing held, that is the target weights). Over all the targets the shortfalls add up to at least the run, so this only falls short when a stock under target can't be bought this run: then each other stock gets at most its own shortfall and the rest stays in the wallet, never going into a stock past its target share (review, 2026-11-14). The exception is a basket with nothing held yet (owner, 2026-11-14; holdings under $1 or 1% of the run, such as a 1-wei airdrop or what a partial sell leaves, count as nothing:nothingHeldinlib/agent/rebalance.ts, one rule for the split, the plan and the drift view, which shows their value but no percentages and says where the line is, e.g. "under $250.00 here"): there is no balance to keep in line and leftover money isn't carried to later runs, so the whole run goes to the buyable stocks at their target weights, the page says so ("NVDA didn't pass its checks. With nothing held yet, this run buys the others at their weights…"), and later runs put more into the one that sat out. A first run too small to give every stock the $10 minimum says so too ("This run is too small to give each of the 3 stocks $10 or more at your target weights, so MSFT and AAPL sit it out; later runs add them."). A stock left out only for the $10 minimum, at any stage (the first split, or after sizing and the percent split), failed no check, so its money goes by target weight to the others still under their target share, or stays in the wallet when none is (topUpLegs'spreDropped), and the run is split again. When a stock fails its checks, every stock dropped for the minimum is looked at again, since without the failed one its share may be big enough (recheck, 2026-11-14: they stayed dropped and their money went into a stock far over target). Each stock then goes through the plan'sscreen(gap, stale pool, earnings, depth) andsizeLegsat its share (cost limit, $25k, 10% of the pool, 8-second pool-read timeout); one that fails is left out with its reason and the rest are split again. The result becomes whole-percent weights and a total the basket buy splits without giving any stock more than it was sized for (wholePercentBasket, whosebestWholePercentspicks the weights that let the largest total through, not the nearest percents). A stock with a tiny share forces the total down to 100× its amount, so the plan also tries without the smallest stock and keeps that when it spends at least 1% of the run more (over 5,000 random runs the 99th percentile left 1.8% unspent, the worst 5.4%, both tiny runs; before, 10.9% and 58%). The page says why any money stays in the wallet, in short parts that add up to it ("$141.00 … stays in your wallet: $140.42 because NVDA can't be bought this run; $0.58 is rounding") (held back for a stock under target that failed; cut by the cost limit or the swap caps, only for stocks whose size was really cut; rounding), and shows each stock's share after this run next to where it stands now, since the split aims at the share after the run (a stock a little over target now can get a small part). The page shows the drift (value, % now vs target, points), what the run buys and why any stock gets nothing (a failed check, or "at or over its target"), and a link to the basket's/buildpage to rebalance by hand. The buy is the normalBasketBuyPanelbehind the region gate and eligibility box (maxUsd= the run's budget, no "Review the rest"); the run is saved as pending at the first signed swap, as bought with what was paid and every hash when the run ends (a stop part way is noted), and is due again only if the first swap was a mined revert or a wallet cancel. While the tab is buying, its panel stays on screen and the chain check skips that run; once the run ends the panel closes, so it can't be bought twice. A stored rebalance rule hassymbol: 'basket', so a page from before this drops it instead of reading it as a one-stock rule. (A tab still open on the old page saves its store without the rule, so it is lost there; reloading avoids that.) While a run is being bought, from the review onward, the eligibility box, Skip, Pause, Delete, Import and other checks are locked, so nothing can unmount the buy mid-run and offer a second one (real-money review). The amount box can still be raised up to the run's budget: each swap's own checks and caps apply, but the cost limit was sized at the shown amount, and the panel says so. Tests:tests/rebalance.test.ts,rebalancePlan.test.ts,rebalanceRoute.test.ts. -
Baskets (
/baskets): Afterbook Basis Tilt — see "Baskets (Basis Tilt)" below. -
Notification bell: see "Notifications" below.
-
Public API: a versioned, documented
/api/v1/tapefor external consumers, separate from the unauthenticated/api/tapethe site itself polls — see "Public API" below. -
Crawlers:
app/robots.ts(everything public is allowed,/api/is not) andapp/sitemap.ts(home,/today,/borrow,/build,/baskets,/baskets/risksand one page per stock inlib/stocks/tokens.ts, so adding a stock updates it by itself). Both build their URLs fromlib/share/siteUrl.ts(the production alias on Vercel, shared with the layout'smetadataBase). -
Card route and versions (
app/card/route.tsx, drawn bylib/share/ogImage.tsx): one route draws every card,/card?page=home|stock|today|build|borrow&sym=…&spec=…&theme=light&v=N. Every page'sog:image/twitter:imagepoints at it (shareMetadatainlib/share/shareMeta.ts, which also sets the page's canonical URL) and the Share panel's "Download card" uses the same URL, so the preview, the download and the screen agree. Until 2026-10-13 cards came from eightopengraph-image/twitter-imagefiles, which can't see a link's query string:/today's card re-picked the leading stock when it was fetched (a post about METAc showed an AAPLc card, the two 0.4 bp apart), and every card was dark even when shared from the light theme. Now a shared link carries the sharer's theme (theme=light) and, on/today, the stock on screen (sym). Card version: X and Telegram cache a card per URL, sovisCARD_VERSIONinlib/share/cardUrl.ts; bump it wheneverlib/share/ogImage.tsxchanges (.claude/skills/card-version-bump/bump.sh). -
Card layout rule: keep the bottom-left corner of every card free. X draws the image's alt text as a label there (it covered the footer line until the third card version), so the footer line (
CardFooterinlib/share/ogImage.tsx: "Afterbook never holds your funds.", since 2026-10-14. It was shortened the same day because X's title label, which grows with the page title, covered the start of a longer line on the/borrowcard. Before that it said "Trades are signed in your own wallet…", and from 2026-10-13 "Trades execute on Aerodrome", untrue once in-app swaps routed through KyberSwap; before that it said "No wallet connect", untrue once Baskets connected wallets) is bottom-right. -
Share cards: the OG/Twitter preview images are generated live from the same tape data (
lib/share/ogImage.tsx). The home card shows the biggest movers among the liquid names;/<SYMBOL>shows that stock;/todayshows the single biggest gap with the Afterbook mark, the stock's Coinbase icon beside its symbol (downloaded server-side, PNG signature and size checked, embedded as a data URI because Coinbase serves the PNGs asbinary/octet-stream; a 3-second limit, and on any failure the same tinted ticker tile the site uses), the gap, cash and Aero prices and, when the stock has at least 8 usable sessions, the line "MSTRc's gap shrank within 30 min of the 9:30 ET open in 13 of the last 13 sessions. Past sessions, not a forecast." That is the same statistic/todayand the tape show (getOpenSnapStatsinlib/market/history.ts: per session, was |basis| smaller 30 min after the open than just before it), with the exact count and sample size, never just a percentage. It is cached 10 minutes and given 3 seconds; if the read is slow or the stock has too little history (PLTRc, MUc for now) the line is simply left out and the rest of the card renders. -
Base Mini App: registered on base.dev, verified via the
base:app_idmeta tag inapp/layout.tsx. Base split from the Farcaster Mini App spec in April 2026 — registered apps are treated as standard web apps now, so there's no manifest file or SDK call here, just the base.dev listing itself. -
Light and dark themes: dark is the default, light is opt-in via the sun/moon toggle in the header (saved in
localStorage), falling back to the OS setting. See "UI architecture".
Why the math is done the way it is
The stock/USDC pools are Aerodrome Slipstream (concentrated-liquidity, Uniswap-V3-style) pools, not classic constant-product pools — confirmed on-chain (stable()/getReserves() revert, slot0()/liquidity()/tickSpacing() work). Aerodrome's documented public Quoter and SwapRouter are bound to a different CL factory than the one these pools were deployed through (pool.factory() != quoter.factory(), verified on-chain), so the standard Quoter reverts on these pools and can't be used here.
Instead, lib/market/quote.ts reads slot0() and liquidity() directly and uses the fact that a CL pool behaves exactly like a constant-product pool with virtual reserves (L / sqrtP, L * sqrtP) as long as a trade stays within the current tick's liquidity — that's exact math, not an approximation, but it stops being exact once a trade is large enough to cross into a different tick range (flagged as largeTradeCaveat, and shaded on the impact curve). Since 2026-10-12 every served estimate walks the real tick liquidity instead (lib/market/lotQuote.ts → simulateBuy in lib/market/swapSim.ts, over the ±25% window lib/market/depth.ts reads): Lot Lab, /api/quote, the MCP get_quote tool, the x402 quote and execute-link routes and /today's sizing cards. Single-tick math was off in both directions past the current tick (NVDAc $100k: 8.2 bp single-tick vs 14.5 bp walked; SPCXc $100k: 45 vs 39), with no caveat shown. largeTradeCaveat keeps its name but now means the trade ran past that window; the cost shown is then for the part that fits in it, a lower bound the UI prefixes with "≥" (the first deploy divided the full amount by only the fillable shares and showed TSLAc $500k as +30,226 bp; fixed the same day). The single-tick estimateLot remains only as the fallback if the tick scan fails. The x402 execute-link route with direction=sell used to return the buy estimate; it now sizes a sell by its dollar value at the Aero price and returns sharesIn/usdcOut from the sell-side walk. This is explicitly framed in the UI as an estimate for sizing a trade, not a firm quote — the actual fill always happens on Aerodrome's own app.
Pool depth (the tape's Depth column, and the liquid/thin split) comes from real token.balanceOf(pool) reads — deliberately not the virtual reserves used for impact math, which describe in-range liquidity depth and run much larger than what's actually deployed.
All token and pool addresses in lib/stocks/tokens.ts were verified on-chain (decimals(), token0()/token1(), fee(), factory()) and cross-checked against Dexscreener's Aerodrome pair listings — the original four on 2026-09-04, plus AMZNc/MSFTc/MSTRc/SNDKc/SPCXc/TSLAc on 2026-09-05 when Base expanded to ten tokenized stocks. All ten share the same CL factory, 0.05% fee tier, and tick spacing. PLTRc and MUc were added on 2026-10-01 after being matched against Coinbase's own public list (api.coinbase.com/v1/tokenized-stocks: contract address, decimals, multiplier()), checked on-chain (USDC is token0, fee 500, tick spacing 10) and against Dexscreener's Aerodrome listings; both pools hold roughly $0.6M, so they sit in the thin tier. 2026-10-27, the Aero move: Aerodrome and Velodrome became Aero on 2026-10-22, with a new CL factory (0x9CB2…7a76). By the 27th every tracked stock was deeper on its Aero pool than on the one the tape read (METAc $933k vs $146k, PLTRc $401k vs $13.5k) and did most of its volume there, so all twelve moved to their Aero pools, and 26 more were added the same day (Base's "more tokenized stocks are live" post): 8 with Aero pools of about $200k each, seeded that day, and 18 with about $51k each in a tick-spacing-1 pool on the older factory. Each was matched against Coinbase's list (address, decimals, US ISIN), Yahoo (a USD listing whose price agreed with the pool's) and Dexscreener (pair address). Aero pools charge a dynamic fee, read live; their gauges pay a new AERO token and have no Sugar, so My Lots reads Aero LP positions from Aero's position manager (0x4857…C60b, wallet-held plus gauge-staked) and shows no gauge APR, voting-incentive flag or emissions for them. Fee-APR snapshots are keyed by pool, so the moved stocks started a new series. Liquidity on the newer six is much thinner ($10k–$110k vs $1–2M on the original four) — that's why the tape splits them out, and why their impact curves and largeTradeCaveat trip at far smaller sizes.
Each stock token also implements the B20 asset standard's multiplier() — a fixed-point scalar the issuer can change without migrating raw balances. This isn't split-only, despite how this file used to describe it: per Base's own B20 spec, cash dividends are reinvested into additional shares by raising the same multiplier, net of withholding tax and a Coinbase fee. All tracked tokens read 1.0x today, but lib/market/quote.ts reads it live on every quote rather than assuming 1.0 forever, so "shares out" stays correct the moment either happens — and lib/stocks/corporateActions.ts watches for exactly that: a Telegram ping to the maintainer whenever a symbol's multiplier changes from its last known value, since that's a real corporate action worth a human glance. The active stock's page also shows the redemption ratio directly whenever it's not 1.0x. Dividends and splits on stock pages (2026-11-17, quest option B): every change emits MultiplierUpdated(uint256 newMultiplier) from the token, and lib/stocks/multiplierHistory.ts keeps them all: the date, the multiplier before (read one block earlier) and after, and the transaction. The stock pages (/markets, /<SYMBOL>) show the selected token's list ("Dividend reinvested: each token now holds 0.050% more AAPL (1.000000 → 1.000500 shares a token)", with a Basescan link; classifyAction in lib/stocks/multiplierActions.ts calls a rise under 20% a dividend and a whole-number ratio of 2 or more a split), or "No dividend or split so far", plus one line on how Coinbase reinvests dividends. The first full scan, on 2026-11-17, found 10, all reinvested dividends: GOOGLc (Sep 14), METAc (Sep 28), NVDAc (Oct 1), ORCLc, MUc, SANc, MRVLc, NOKc, AAPLc and INFYc (Nov 16). Logs come from publicnode (mainnet.base.org refuses eth_getLogs), which answers at most 50,000 blocks and about 10 addresses a query and keeps logs only from about 2026-09-07; the scan starts at block 51,020,000, where every token deployed by then (the first ten, from 2026-07-26) still read exactly 1.0, so nothing earlier is missed. The daily /api/cron/corporate-actions scans forward from a cursor (corp:cursor; events in corp:actions; corp:scanned lists the tokens covered, so a token added to STOCKS later gets its past scanned once), stopping after 75 s and carrying on next run (the first full scan took about 250 s; progressed: false in its reply means the first query failed). One run at a time (corp:lock, 130 s, holding a random value per run and released only if it still holds that value), so a manual call can't overlap the daily one and drop a find. The panel stays hidden until the first full scan reaches the head (corp:ready), so a half-done history never says "none so far". Pages read the list through Next's data cache (an hour), refreshed when a run finds something or first catches up. A token added to STOCKS later says "none so far" until the next run has scanned its past. Tests: tests/multiplierHistory.test.ts.
On-chain reads go through https://mainnet.base.org, Base's documented official RPC endpoint, with a public third-party RPC as a fallback.
Earnings dates come from Nasdaq's public, undocumented api.nasdaq.com/api/calendar/earnings endpoint — no key, same "open but unofficial" trust shape as the Yahoo endpoint above. Yahoo's own calendar endpoint (quoteSummary + calendarEvents, which used to return this) now needs a crumb+cookie handshake this app doesn't have, so it wasn't an option. A ticker with no date on file (expect this for SPCX, which only IPO'd in mid-2026) just shows nothing, not an error.
lib/stocks/earningsHistory.ts separately accumulates past reports (the calendar endpoint above only ever holds the next upcoming date, overwritten as time passes) — for each report, the % move from the last close before it to the first close on or after the day after, from Yahoo's historical daily-close data (same host, a longer period1/period2 window instead of range=1d). Seeded with a one-time ~400-day backfill; the daily earnings-sync cron extends it by a few days' lag going forward, so the sample grows every quarter. A symbol with no reports yet in the window just shows no historical-average stat, not a fabricated one.
In-app swaps
Get USDC on Base (2026-11-20, app/components/swap/GetUsdcGuide.tsx): the stock, basket and meme (USDC) buy panels show a short guide when the connected wallet holds less USDC on Base than the buy needs, open by itself at zero: the wallet's address with a copy button, three ways in (an exchange withdrawal on the Base network, a swap from ETH already on Base, a bridge to Base), and how to tell the right USDC (Circle's, 0x8335…2913, linked on Basescan; bridged USDbC can't be used). Display only; no new transaction or link to a third-party service.
Buy / Sell in the Execute panel swaps USDC ↔ a tracked stock token from the visitor's own wallet. The trade is routed by KyberSwap's aggregator, which splits it across Aerodrome and other Base pools (prop AMMs such as Metric, Bebop, Kipseli); in the spike on 2026-10-13 it routed all twelve tokens at $1k and $10k within −5 to +8 bp of the Aerodrome-only quote. KyberSwap was chosen over 0x because it needed no account or API key, takes no protocol fee on swaps (it keeps positive slippage), and supports an integrator fee. Until 2026-11-12 every call ran on the keyless public tier with an unregistered x-client-id: afterbook; KyberSwap's team then issued an API key for their keyed gateway (api.kyberswap.com/swap, higher limits), kept in KYBERSWAP_API_KEY and sent only as x-api-key (lib/swap/kyberClient.ts; unset, the public host and the old header are used). The build body's source stays afterbook.
-
Flow:
/api/swap/quote(price preview, refreshed every 15 s) → Review →/api/swap/buildbuilds the transaction for the connected wallet and checks it (checkSwapCalldatainlib/swap/swap.ts) → the review card shows pay, estimate, minimum received, Afterbook fee, route and router → Confirm: an exact-amountapproveof the router for the reviewed amount if the allowance is short; after an approval, or if the card has been open over 60 s, a fresh rebuild that is sent only if it is the same trade with a minimum at least as good as the card's (otherwise the card shows the new numbers and asks again); then the swap with the Builder Code appended →/api/swap/log. The wallet never signs a minimum lower than the one on screen. Since 2026-11-19 the browser also checks every build itself before showing it (lib/swap/swapFloor.ts, run bybuildSwapinuseSwapWallet.tsfor every panel): the calldata trades the tokens the person asked for (worked out from their own request), spends the amount asked and pays the connected wallet, has no fee, no permit and no split above its amount, its signed minimum is exactly the card's and no lower than the quote less the person's own slippage setting, and a stock quote is at most 1% worse than what that stock's own pool would pay for exactly this amount, worked out in the browser by walking the pool's real tick liquidity, read from public RPC by the browser itself (readPoolState+getLiquidityDistribution(…, strict)+simulateBuy/simulateSell), so a compromised server that set both the card and the minimum near zero is still refused. The first version (owner review of #193, 2026-11-19) compared with the pool's spot price instead and refused ordinary trades in thin pools (INFYc buys from $50, WRDc from $500), which fill well under spot at any size: comparing with the pool's own fill for the same amount accounts for depth. A trade the pool couldn't fill within 25% of its price is refused with "try a smaller amount". It is a backstop, not a tight bound: a compromised server could still take up to the 1% margin plus slippage, so the server's checks stay the main ones. Meme buys get every check but the pool price (their pool comes from the server-written allowlist); the $1,000 cap bounds them. TurningSWAP_FEE_BPSon would refuse every swap here until this check is changed. -
Contract: KyberSwap
MetaAggregationRouterV2at0x6131B5fae19EA4f9D964eAc0408E4408b66337b5(verified on Sourcify). The only contract a swap calls or an approval names. -
Meme buys (
/memes/<address>,MemeBuySection.tsx/MemeBuyPanel.tsx,lib/swap/memeSwap.ts): the same quote → review → build → approve → swap flow and the samecheckSwapCalldata, buy only. The server accepts a meme only if it is on the verified allowlist (lib/memes/memestocks.ts) and its pool holds at least $10k right now, paid with USDC or the stock token that meme's pool is priced in (nothing else), at most $1,000 a buy (MAX_MEME_SWAP_USD), and never with Afterbook's fee (feeForinlib/swap/swap.tsreturns none for a meme even whenSWAP_FEE_BPSis set). The panel re-checks that the built transaction is this meme, this pay token and a buy, shows the share of value lost to price impact and pool fees (with a warning over 5%), and repeats the "any memecoin can go to zero" warning above the Buy button. The page needs the non-US region and a box the visitor ticks (eligibility plus "can go to zero"). The swap log records a meme buy only if the mined call's tokens and recipient match the stored build (sourcememe). -
Limits: a slippage limit the trader picks, 0.1% to 1% with 0.5% as the default (owner, 2026-11-03; the same for memes and basket legs; chips plus a custom box under the amount,
slippage.tsx, remembered in that browser only). The request carriesslippageBps(10–100, default 50); the server refuses anything else, builds the swap with it andcheckSwapCalldatarequires the minimum within that limit of the quote, so the router reverts below it. Above 0.5% the panel warns that bots can take part of the gap. The floor check allows 1 bp more for rounding. A basket leg's "at least" figure is its minimum less another 0.5% (BASKET_DRIFT_BPS, prices moving between legs), so at the 1% setting a leg can fill up to about 1.5% under its reviewed estimate; the review card says so. $25,000 per swap, and a stock buy at most 10% of that stock's live pool depth (MAX_BUY_DEPTH_SHARE, owner 2026-10-27; about $5k for the 18 seeded ~$51k pools, no change for pools over $250k;/buildbasket legs too, refused at the review step before any approval, and again at each leg's rebuild just before signing, which stops the run and offers the rest; sells are not depth-capped), 30 swap API calls per minute per IP (swapLimiter; KyberSwap's public limit is 3 requests/s for the whole server). -
Fee:
SWAP_FEE_BPS(1–100) toSWAP_FEE_RECIPIENT, both required, else no fee. Always taken in USDC: on the way in for a buy, out for a sell. The review card shows it in % and dollars. Owner decision: the fee stays at 0 until a legal check on charging a fee on tokenized-stock trades. -
Gates: same as the rest of Execute: the non-US region check (fail-closed, on every
/api/swap/*route too) and the eligibility checkbox. -
Log and stats:
/api/swap/buildremembers keccak256 of every calldata it returns (2 hours, with the account and fee);/api/swap/logre-reads the hash from the chain and records it only if the mined calldata (minus the Builder Code) is one of those, it succeeded, and it was made by that account: sent straight to the router from it, or, for a smart account such as Base Account (2026-11-18), a router call inside that account's user operation in a bundler'shandleOps, counted only when the EntryPoint reports that operation as successful and the account ran it as a genuine Coinbase Smart Wallet (the factories' proxy or Coinbase's EIP-7702 proxy, pointing at one of the two implementations Coinbase's factories deploy, both before and after that block or deployed in it by one of Coinbase's factories, with no change in that block to any other implementation; an account of anyone's making could claim one call and run another) (routerCallsinlib/swap/swapLog.ts; each router call in it is its own record,<hash>:<n>, so a batch of several swaps counts each). Either way the router's ownSwappedevent must show that swap ran (the account as caller, the built tokens, recipient and exact amount; one event per call), a build counts for one swap only (swapused:*), and a sell is sized by USDC reaching the account, capped at the swap'sreturnAmount. Fee and size come from the stored build (size capped at $25,000), so a hand-made router call with the public Builder Code cannot inflate the numbers. Wallets are stored as a short pseudonymous hash (counts unique traders; not a privacy guarantee)./api/swap/stats?days=7(cron bearer, like/api/clicks/stats) returns swaps, unique traders, volume, fees, per-stock counts andbySource(swaps, volume and distinct hashed wallets per panel:stock,basket,meme,plan,rule,agent). Test wallets are left out (2026-11-21,lib/swap/testWallets.ts): the owner's wallet in code plusTRACTION_TEST_WALLETS(comma-separated addresses or 16-hex wallet ids, a public list set in Vercel), matched by the same hash;testsLeftOutsays how many swaps and how much volume were left out, and?tests=1includes them. Plan counts (/api/agent/statsplans,paid) have no wallet and can't be filtered: they include the owner's own test calls. -
Traction page (
/traction, 2026-11-21,lib/swap/traction.ts): the same records, test wallets left out, for the last 30 days and since the first swap, by where the swap came from, paid agent plans in the last 30 days (plans carry no wallet, so the page says this count includes the owner's tests) and the swaps signed from agents' plan links, with Telegram/planlinks counted apart (source: 'telegram', 2026-11-22: a person typing to the bot isn't an agent; cache keytraction-v2). No transaction hash is shown (a hash leads to the signer's wallet on any explorer); the newest agent-link hashes are in the maintainer-only/api/agent/stats(recentAgentLinkSwaps). All-time reads every logged record in one MGET: fine today, but past a few thousand swaps it should become a rolling counter. Read through the data cache for an hour (two Redis requests for the swaps, one pipeline of 30 for the plans). -
Basket buys (
/build/<spec>, "Buy it", since 2026-10-14;BasketBuyPanel.tsx,lib/swap/basketBuy.ts):- The split: one USDC amount is split by the basket's weights (
splitBasketUsdc: floors each leg, gives the remainder to the biggest, always sums exactly). - The review: each leg is built and checked by
/api/swap/buildlike a single buy. The review card shows every leg's estimate and an "at least" amount, which is the leg's minimum lessBASKET_DRIFT_BPS(0.5%). - Signing: one approval of exactly the total for the router (skipped if the allowance already covers it), then one swap per stock, each rebuilt just before signing. The panel pauses 4 s after each confirmed leg (
LEG_PAUSE_MS), because on the first real basket (AMZNc + MSTRc, 2026-10-14) Rabby showed a falseTRANSFER_FROM_FAILEDon the second leg: its simulation counted the first swap twice. The same swap simulated fine on-chain and went through on "Review the rest". A leg is sent only if its minimum is at least the card's "at least" figure, so the wallet never signs below what was shown. - One signature (2026-11-18, quest option A): a wallet that says it can run a batch atomically on Base (EIP-5792
wallet_getCapabilities→atomic: supported, such as Base Account) gets the approval (only if needed) and every swap as one batch (wallet_sendCallswithforceAtomic,lib/swap/basketBatch.ts), so the person signs once and the basket goes through together or not at all: a failed batch leaves nothing bought and nothing approved. Every call is checked again before sending (USDC approval naming the router, or a router swap) and carries the Builder Code; the batch also passes it as thedataSuffixcapability, which a smart account puts at the end of its whole operation, where Base reads it. A review under a minute old is signed as built (rebuilding every leg straight after the review got KyberSwap's 429 in testing); an older one is rebuilt, a second apart, and sent only if every leg still meets its "at least" figure. A wallet without it ("ready", which would first upgrade the account, counts as without) keeps the steps below, and so does a/rulesrebalance run, whose pending record is keyed by a transaction hash a batch doesn't have until it is mined. Tests:tests/basketBatch.test.ts. - When it stops: a decline, a revert or a price move halts the run. The panel lists what was bought and offers "Review the rest" for the remaining legs, and nothing retries on its own. It also says the router may keep an approval for the unbought USDC.
- Limits: at least $1 per leg, $25,000 per basket.
- Selling ("Sell basket",
BasketSellPanel.tsx,basketSellAmounts):- How much: a whole percent (1–100) of whatever the wallet holds of each of the basket's stocks, including any bought outside the basket (the panel lists the holdings and says so). Stocks the wallet doesn't hold are left out.
- Signing: each stock is a different token, so each leg asks for its own approval of exactly what it sells, for the router only (skipped if the allowance covers it), then its swap to USDC. That is up to 2 requests per stock, with the same 4 s pause after each.
- One signature (2026-11-19): a wallet that runs batches atomically on Base (Base Account) signs the whole sale once: one batch of, per stock, its exact approval (only if needed) and its swap (
basketSellBatchCalls), together or not at all, with the buy's freshness, account and outcome rules. Base Account's window opens from the person's own click, so there is no "continue in Base Account" pop-up prompt before every step. Before any batch is sent,basketBatchProblemrefuses it unless every approval is exactly what its swaps spend of that token, and every swap pays the account with no fee, no permit and a minimum above 0, trading USDC against a tracked stock; each swap's calldata must also spend exactly the amount shown and sign exactly the "at least" figure shown. - Same rules as buying: each leg is built and checked by
/api/swap/build(sidesell,source: 'basket'), rebuilt before signing and sent only if it returns at least the card's "at least" USDC. A stop lists what was sold, offers "Review the rest", and says if one stock's approval is still open.
- Gates: the same region gate and eligibility box as Execute.
- Stats: builds carry
source: 'basket', so/api/swap/statsreportsbySource(stock panel vs basket legs; buys reviewed from/plancarrysource: 'plan', runs bought from/rulessource: 'rule'). The label is what the browser sends: it can't inflate counts or volume (those still need a mined, matching build), but a caller could mislabel their own swaps. Swaps logged before this have no source and count asstock.
- The split: one USDC amount is split by the basket's weights (
-
Verified before launch (2026-10-13):
eth_call/eth_simulateV1of server-built buys and a sell with the Builder Code appended (fee reached the recipient: $0.20 on a $100 buy at 20 bp; nothing with the fee off); tampered calldata refused; a fake wallet in a real browser was asked for an exact approval (USDC, router, 100 USDC, Builder Code) and then the swap (to the router, Builder Code), at 390px light and desktop dark. -
Dry run before every swap (2026-11-24, owner;
useSwapWallet.ts,lib/swap/dryRun.ts): just before the wallet opens, the exact calls are run on Base without sending them (eth_simulateV1from the connected account). If the swap would revert (a real/rulesswap reverted inside KyberSwap's route on 2026-11-24 and the paymaster still charged its fee), the panel gets one fresh route, held to the card's minimum, and dry-runs it again; if that still reverts it says so and sends nothing. A node that can't simulate doesn't block the swap; right after an approval the dry run waits (up to about 4 s) for the node to reach the approval's block, and doesn't block on a node that hasn't. Base Account takes its network fee in USDC from the same wallet after the calls run, so for a Base Account wallet (one signature or two steps) the USDC Max buttons (stock buy, basket buy, lend deposit) leave $0.05 (lib/wallet/feeReserve.ts) (USDC_FEE_RESERVE_RAW) and a near-full amount (or Repay all) says to leave it; revert messages say the network fee was still paid (2026-11-25). Repay all reads the debt again just before approving, so a tab left open for days can't approve less than the interest has grown to. -
One signature for a single swap with Base Account (2026-11-24): on a stock's Buy / Sell (
SwapPanel), a wallet that runs batches atomically on Base signs the exact approval (only when needed) and the swap together, the same checked batch as a one-leg basket (basketBatchCalls/basketSellBatchCalls,basketBatchProblem); nothing is left approved between two steps. A/rulesrun keeps the two steps (its pending record needs the swap's hash;SwapPanelturns one signature off for any caller passingonBuySent), and meme buys never batch. A plan link keeps one signature and locks its other stocks while a buy is in flight withonBuyStarted/onBuyFailed, which need no hash. A card is dropped when the connected account changes.
Baskets (Basis Tilt)
/baskets offers Afterbook Basis Tilt: a basket of ten Base tokenized stocks (NVDAc, AAPLc, METAc, GOOGLc, AMZNc, MSFTc, MSTRc, SNDKc, SPCXc, TSLAc) weighted by what the on-chain books show instead of equally or by market cap. It runs on Glider's B2B API: the user's funds sit in a smart account they own on Base, Glider's automation rebalances it (swaps route through LI.FI to Aerodrome), and Afterbook only chooses the target weights. Afterbook never holds funds, keys or executes trades for baskets. Glider's agent can move the account's funds (read from chain, 2026-11-19): enrolling enables a Kernel permission for Glider's agent key (ZeroDev's ECDSASigner) under ZeroDev's SudoPolicy, with no limits, on execute, so only Glider's own system, not a contract rule, keeps it to rebalancing and to withdrawals to the owner; through execute it can also call the account itself (change the root validator, upgrade, install modules), delegatecall, and sign as the account under ERC-1271 (permission flag 0x0000, no SKIP_SIGNATURE; owner's check of Kernel v3.1's source, 2026-11-19). The panel and /baskets/risks say so, and the enrollment review card says what the signature grants. Not available in the US (the same best-effort, fail-closed x-vercel-ip-country gate as the rest of the app, applied to the page and to every /api/baskets/* route). No Afterbook fee. "Start automation" needs the owner's signature (2026-11-22, from an outside review: POST /api/baskets/start used to restart rebalancing for any address it was sent): the wallet signs a short dated text (startMessage in lib/baskets/startAuth.ts; it moves no funds), and the route checks it with viem's verifyMessage (EOAs, and smart wallets through ERC-1271/6492) names the site and chain (URI: https://afterbook.app, Chain ID: 8453), and is refused if more than 5 minutes old or already used (basketauth:<action>:<wallet>:<time>, NX: keyed on what was signed, since one signature has several valid encodings). The server then runs the panel's own account checks (depositAccountProblem, deployedAccountProblem) and never starts a tampered account. A withdrawal that sells to USDC (liquidate: true) needs the same kind of signature (withdraw-sell) at stage 1 too, until Glider confirms asking for it changes nothing.
New enrollments are paused (owner, 2026-11-19, lib/baskets/enrollPause.ts): enrolling signs a bare 32-byte hash that Glider returns through our server, and Kernel accounts accept a signature over a hash as authorisation, so until the browser recomputes that hash from the enable data it should mean, the panel offers no enrollment and both enrollment routes answer 503 without contacting Glider. Enrolled wallets keep deposit, start and withdraw. User flow (app/components/baskets/BasketPanel.tsx): connect wallet → review and sign one message (creates the smart account; no funds move) → send USDC from the wallet to the account (an in-app plain ERC-20 transfer with a balance check and Max) → Glider buys the basket → withdraw any time, as USDC (Glider sells) or as the tokens, with an EIP-712 signature that expires in 10 minutes. Outcomes also show as toasts, and the withdrawal status is polled from Glider's operation endpoint. Enrolling requires ticking an acknowledgement linking to /baskets/risks. The deposit address is checked in the browser (2026-11-19, lib/baskets/depositAccount.ts): it comes from Glider through our server, so before the panel shows it or sends to it, the browser recomputes it from the connected wallet. Glider's Base accounts are ZeroDev Kernel v3.1 accounts made with CREATE2 by KernelFactory v3.1 (0xaac5…E419), initialised with ZeroDev's MultiChainValidator (0x5c97…4f5f, source verified on Sourcify) as root validator and the owner as its signer, no hook and no other modules (read from a real deployment), so an address that recomputes from the wallet was created with that wallet as its only root signer, deployed or not. The maths can't see later changes, so for a deployed account the browser also reads its implementation, root validator and that validator's signer from the chain (public RPC) and refuses on any difference or failed read (deployedAccountProblem); the send checks both again. Glider's salts appear to be 0x8b0300 plus the enrollment's account index (seen on chain: 0x8b0329, 0x8b032a, 0x8b0335); the browser scans 4,096 of them (pure maths, no chain read), and an address it can't match is not shown and can't be sent to. The salt needs no trust: the owner is inside the hashed data. Glider's agent permission, enabled by the enrollment signature, is by design and not part of this check. The withdrawal is checked in the browser too (2026-11-19, lib/baskets/withdrawCheck.ts): before the wallet signs Glider's EIP-712 data, it must be exactly a Withdrawal in the domain "Glider Withdrawal Authorization" (version 1, or 2 with liquidate), chain 8453, verifying contract = the portfolio's Base account, with exactly Glider's types and fields, this portfolio, the connected wallet on Base as recipient, the same assets and raw amounts as asked (any order, no duplicates), a bytes32 nonce, an expiry no further than an hour out (with five minutes' slack for a slow device clock) and, when selling, settlement in USDC on Base. Pinned to Glider's real stage-1 answers for an enrolled test wallet (nothing signed); anything else, such as another recipient or a permit or Kernel Enable in its place, is refused before the wallet opens. Before even asking Glider, the account must pass the deposit check's address maths. What the chain shows (deployedAccountStatus: each read on its own, any wrong value is a mismatch, a failed or garbled read is unread) never blocks a withdrawal, unlike a deposit: a flaky RPC can't trap funds, and an account no longer set up as created (mismatch) gets a strong warning above the buttons and can still withdraw, because the recipient is pinned to the wallet either way (owner, 2026-11-19). The amounts asked for come from the server's own positions, so matching them only shows the server agrees with itself; the protection is the pinned recipient and format. Still unchecked: the enrollment hash, which is why new enrollments are paused.
Weights (lib/baskets/weights.ts, pure): half follows real pool depth, half follows |cash-vs-chain basis| counted only for liquid pools (≥ $1M; a thin pool's basis is mostly noise). Each name is bounded to 2–25%; bounds are enforced by scaling the raw scores with a bisection so the weights always sum to exactly 1, then rounded to 2-decimal percent strings that sum to exactly 100 (largest-remainder), which is the format Glider requires. lib/baskets/tilt.ts turns the tape into weights and CAIP-19 asset ids (eip155:8453/erc20:0x…).
The basket universe is explicit. BASKET_SYMBOLS in lib/baskets/tilt.ts is the ten names above and is deliberately separate from the tracked list in lib/stocks/tokens.ts: adding a stock to the tape must never silently change what enrolled users hold. Widening the basket is a deliberate decision plus a new strategy version.
Smoothing (smoothWeights): the published weights follow an exponential moving average (alpha 0.3) of the target, and a new Glider strategy version is published only when at least 10% of the basket would change hands (MIN_TURNOVER; it was 5% until 2026-10-07, when a replay of 19 days of stored history showed 5% would have changed the basket on about 2 days in 3, roughly 90 bp a month in trading cost at ~0.9% per unit moved, versus about 3 publishes and ~50 bp at 10%) — every published version makes every enrolled portfolio trade (about 0.9% round trip in a measured $5 test), so a noisy basis must not cause daily churn. The daily job (/api/cron/basket-tilt, 22:00 UTC) saves the moving average on every scheduled run, publishes only when BASKET_AUTOPUBLISH=1, and messages TELEGRAM_ADMIN_CHAT_ID each time it publishes; ?dry=1 reports the plan, writes nothing, and shows autopublishEnabled.
Strategy settings (set once on the Glider strategy, not in code): private (isPublic: false), daily schedule, 1% slippage, 1% price impact, $1 minimum swap (Glider's own floor).
Server routes (app/api/baskets/): enroll/signature, enroll, portfolio, start, withdraw/signature, withdraw, operation. All go through guardBasketRequest (lib/baskets/guard.ts): fail-closed geo gate, config check (GLIDER_API_KEY and GLIDER_STRATEGY_ID both set — removing either is the off switch for the whole feature), then a Redis rate limiter that refuses when Redis is missing. The strategy and chain are fixed server-side, and a user's portfolio is always resolved from their owner address, never from a caller-supplied id. lib/baskets/glider.ts is the typed client (retries only on 429 and API_506; env values are trimmed because a stray space from a dashboard paste once broke enrollment on the live site).
Daily job (/api/cron/basket-tilt, 22:00 UTC): plans the next update and publishes only when BASKET_AUTOPUBLISH=1 and ?dry=1 is not set; otherwise it just reports the plan and writes nothing. It refuses to touch a strategy whose asset list is not exactly the basket names. Auto-publish is off unless the variable is set, and it is on in Production since 2026-10-07 (owner decision, after the threshold went to 10%); unsetting it and redeploying is the off switch (see the basis-tilt-ops skill).
Environment variables: GLIDER_API_KEY (a production tenant key — Glider's B2B API has no staging; test with separate keys. Production needs the six scopes strategies:read/write, enroll:write, portfolios:read/write/withdraw; a local dev key needs only strategies:read, portfolios:read, enroll:write), GLIDER_API_BASE (optional; defaults to https://api.glider.fi/v2), GLIDER_STRATEGY_ID, BASKET_AUTOPUBLISH, and DEV_GEO_COUNTRY (honoured only under next dev, so a developer machine can pass the fail-closed gate; a production build ignores it).
Notifications
The bell in the header opens a small settings popover: a Live market alerts switch (on by default), a locked Your transactions — always on row, and a short Recent list. The choice is stored in localStorage only (no accounts), and the bell's dot is a status light — shown while live alerts are on.
- Live market alerts (
lib/alerts/liveAlerts.ts, pure;app/components/notifications/LiveAlerts.tsxpolls/api/tapeevery 60s while the tab is visible): a toast when a liquid pool's |gap| crosses 100 bp (it must fall back under 80 bp before it can fire again) or the cash market opens or closes. The first read after load only sets a baseline, so nothing fires for something already true. Alerts exist only while the site is open; Telegram covers the closed-tab case. - Transaction toasts (
app/components/notifications/notify.tsx): enroll, deposit, withdrawal progress and failures in the basket panel always show; the switch cannot turn them off.
UI architecture
- Themes (
app/styles/tokens.css): dark tokens live on:root, light is a token override on:root[data-theme='light']. A small inline script in<head>(app/components/layout/theme.ts, nonce'd to satisfy the CSP) setsdata-themebefore first paint from the saved choice, else the OS setting. Hard-coded greys were replaced by tokens (--inset,--surface-hover,--overlay-*), and RainbowKit switches between its dark and light themes with the app. - Wallet button (
WalletConnectButton.tsx, used in the header, My Lots and Baskets): connected, it opens an account panel (address, wallet name, copy, Basescan link, network, Disconnect) and never disconnects on a bare click. The app is Base-only (lib/wallet/wagmiConfig.tshas one chain), so on any other network the button turns amber ("Wrong network") and the panel offers a one-click "Switch to Base". The component is split into a wagmi wrapper and a props-onlyWalletButtonViewso every state can be rendered without a wallet. - Ticker strip (
TickerStrip.tsx): each item shows icon, symbol, Aero price and gap, so a stranger can tell which stock is which; items link to the stock's page. - Share button (
ShareButton.tsx): on the tape hero (next to "Size a … trade"), on/today, on/build/<spec>, on/borrowand on each/memes/<address>page, one identical standard secondary button (.btn btn-secondary) on both pages. It opens a small panel: "Share via…" (the browser's system share sheet, only wherenavigator.shareexists), "Post on X" (anx.com/intent/postlink with the hero sentence and the page URL), "Copy link", and "Download card" (the same/card?…PNG the link preview uses, in the theme on screen). The link is built from the page's own origin, so previews only work on the live site. Every share gets its own URL (?s=<stamp>, set when the panel opens): X caches a link's preview card by URL for about a week and the card shows live numbers, so a bare/MSTRckept showing the first card ever fetched, contradicting the post's sentence (seen 2026-10-07: post said 91.8 bp, cached card said +278.6 bp from two days earlier). Those URLs stay crawlable (X's and Telegram's preview crawlers obeyrobots.txt; aDisallow: /*?s=left every shared link on X without a card until 2026-10-13), and each page's canonical URL keeps them out of search results as duplicates. The link also carries the sharer's theme and, on/today, the stock on screen, and "Download card" is the same image as the preview. The text is the hero sentence's wording, facts only; keep it free of advice. The per-stock cards (/card?page=stock&sym=…) now carry the same icon and fade line as the/todaycard. The/borrowcard (page=borrow, since 2026-10-14) shows the stock collateral and USDC borrowed across Aave and Morpho, and the four biggest markets with their Aero exit (Deep / Tight / Short and the amount, neutral colours). Its numbers and sentence come from onegetBorrowSummary()read,lib/lending/borrowSummary.ts, frozen in the snapshot'sborrowfield. A meme card (page=meme) freezes the meme's whole row in the snapshot'smemefield (only a meme on the verified allowlist gets one) and shows its own logo from Dexscreener's CDN, or the letter tile if that can't be fetched. Until 2026-10-19 meme shares had no snapshot, and a post saying BLUECHIP −3.2% went out over a card drawn later at −7.5%. Share snapshots (lib/share/shareSnapshot.ts,POST /api/share): when the panel opens, the server reads the tape once, writes the post's sentence from it (lib/share/shareText.ts, the same functions the page uses for its hero sentence) and stores that frozen tape in Redis for 30 days under the share's id, which becomes the link'ss. The card for that link draws from the stored tape, so the sentence and the card always show the same number; the card's header says when ("Cash market open · 10:21 ET"). Before this, the sentence came from the screen and the card from live prices seconds later: a post said 8.0 bp over a +2.8 bp card. Numbers are computed on the server, never read from the link, so editing a URL can't put made-up numbers on a card. Rate limit 20 shares per 10 minutes per IP (shareLimiter). Until the snapshot is back the panel shows "Freezing the numbers…"; if it fails (no Redis, rate limit, 6 s), the button falls back to the on-screen sentence and a live card. - Brand mark: a crescent (after hours) over two stepped lines (the order book). Defined once in
lib/brand.tsand used by the header (BrandMark.tsx, themed: sky tile in dark mode, blue in light), the favicon (app/icon.svg, hand-copied from the same path) and the share cards (lib/share/ogImage.tsx). Apps that bookmark the site need raster icons (the Base app showed a letter "A" with only the SVG, 2026-10-18), so there are also PNGs rendered fromicon.svg:app/favicon.ico(16/32/48),app/icon1.png(512, a PNG<link rel="icon">),app/apple-icon.png(180, iOS home screen) andpublic/icon-192.png/icon-512.pnglisted in the web app manifest (app/manifest.ts). If the mark changes, updateicon.svgand re-render all of them. - Header (
app/components/layout/SiteHeader.tsx): five tabs and the wallet in a full-width bar that condenses into a floating centred pill after about 32px of scroll (with hysteresis; wider than 900px only). At 900px and narrower the header is one row that scrolls away and the tabs move to a bottom bar (.tab-bar; the page gets bottom padding so the bar never covers its end). The element keeps its height so nothing below shifts. - Token icons (
lib/stocks/coinbaseIcons.ts): the root layout reads Coinbase's public tokenized-stock list on the server (cached six hours), keeps an icon only when the entry's contract address matcheslib/stocks/tokens.tsand the URL is onmetadata.coinbase.com, and passes the URLs through context.SymbolTilerenders the icon or a tinted letter tile (lib/stocks/symbolStyle.ts) when it is missing or fails. The icons are the companies' own logos served by Coinbase; the footer says they belong to their owners and Afterbook is not affiliated. - Trends (
/api/sparklines): one request for every row — up to 30 days of time-bucketed on-chain price samples plus the 24h change (reported only when a sample exists within 3 hours of 24 hours ago). All rows are drawn on one shared time axis whose length is the oldest stored sample (up to 30 days), and the tape header reads "Past Nd" with that real span, so it never claims 30 days before there are 30. A token with less than 3 days of its own history shows a small "New · Nd" label instead of a chart (a line stretched across the axis would pass for a long trend); from 3 days it draws only the part of the axis it covers. A token's 24h change uses the sample nearest to 24 hours ago within a 3-hour tolerance, so for a day-old token it is measured over slightly under 24 hours. - Markets page (
/marketsand every/<SYMBOL>page,app/components/markets/HomeClient.tsx): a short shell that owns the page state (active stock, calculator size, eligibility box) and its data (markets/useMarketData.ts: the 20 s tape poll, trends, the calculator quote and the per-stock reads). Each section is its own file inapp/components/markets/:MarketsHero(with the pinned gap bar),TapeSection,LotLabwithLotLabLpandLotLabCarry,ExecuteSectionandMarketsFooter(split on 2026-11-03; the page renders the same as before). - Swap panels share their wallet steps through
app/components/swap/useSwapWallet.ts(2026-11-03): the exact-amount router-only approval and the router swap, both with the Builder Code, the allowance read, the chain switch, the error and toast wording runner, the 15 s price preview, and the single-swap review / rebuild / confirm flow used bySwapPanelandMemeBuyPanel. The basket panels use the same steps in their per-leg loops. A change to how any swap is signed goes there, once. - Form controls: one zero-specificity rule styles every
selectand text input inside<main>(so components like the compact.sticky-symbol-selectcan still override it); the RainbowKit modal portals outside<main>and is untouched. Interactive elements without their own ring get a fallback:focus-visibleoutline.
Scheduled jobs
Defined in vercel.json. Every route requires Authorization: Bearer $CRON_SECRET (cronAuthorized in lib/server/sharedSecret.ts); with the secret unset they stay open under next dev but refuse every call in any built deployment (production, previews, next start), so a missing variable can't make them public. The maintainer-only /api/clicks/stats (outbound-click log) uses the same check.
| Route | Schedule (UTC) | What it does |
|---|---|---|
/api/cron/alerts | every 5 min | evaluates Telegram alert rules against the live tape |
/api/cron/discover-tokens | 13:00 daily | first runs the list guard (lib/stocks/coinbaseListGuard.ts: saves the last good list to cblist:lastgood, or alerts when the list is over 25% smaller than it or a tracked stock is missing from it; ?dry=1&guard=1 returns just that), then reads Coinbase's token list, finds untracked names with a USDC pool (Aero or the older Aerodrome factory, any tick spacing; the deepest counts) and real depth, sends one Telegram digest (which also names, once, any listed token the site skips: an unexpected symbol, no address, a duplicate), and saves every untracked token's pool and depth for /stocks (?dry=1 sends and saves nothing) |
/api/cron/discover-memes | 13:30 daily | finds and verifies meme pools quoted in tracked stock tokens and replaces the /memes allowlist (?dry=1 saves nothing; an empty result is never saved; each stock's Dexscreener lookup is retried twice, and a stock whose lookup still fails keeps its pools from the saved list for up to three days from their last proof (never a pool the not-a-meme filters reject), and nothing is saved unless the run itself verified a pool: before 2026-10-31 a failure counted as "no memes" and the live list held only the first five stocks' memes) |
/api/cron/fee-snapshot | 06:00 daily | snapshots pool fee-growth counters for fee APR |
/api/cron/earnings-sync | 11:00 daily | refreshes earnings dates 15 days ahead (deletes a date only after a scan with no failed day, then records earnings:syncedAt) and history |
/api/cron/corporate-actions | 11:30 daily | records dividends and splits of the tracked tokens from their onchain MultiplierUpdated events, forward from a cursor (lib/stocks/multiplierHistory.ts) |
/api/cron/basket-tilt | 22:00 daily | plans the Basis Tilt update; publishes only with BASKET_AUTOPUBLISH=1 |
Security model
- Allowlisted contracts only — 39 token addresses, 39 pool addresses, all verified on-chain. The active stock's token and pool addresses are also shown directly in the Execute panel with BaseScan links, so you don't have to trust this README or leave the app to check what you're actually trading.
- All price/quote fetches happen server-side (Next.js route handlers); the browser only talks to this app's own
/api/*routes. - Rate limits on the read routes (2026-11-03):
/api/lots(10 a minute per IP: one call reads every tracked stock's balance and LP positions),/api/basename(20) and/api/quote,/api/depth,/api/history,/api/history/stats,/api/price-history,/api/earnings-history(60 each) answer 429 withRetry-Afterpast the limit (limitRead,lib/server/readGuard.ts). They count in memory per server instance (MemoryLimiter,lib/server/ratelimit.ts), not in Redis, because every open tab polls them: a brake on one client hammering the RPC, not an exact limit. The app itself stays far below them (one/api/lotscall per wallet, the others once a minute and on a stock change). The swap, basket, share, click and key routes keep their Redis-backed limiters. - My Lots connects a wallet to read balances — no seed phrase ever touches this app and no signature or approval is ever requested there. Connecting only exposes the public address, which is already public on-chain regardless. Baskets are different and say so: enrolling asks the user to sign a bare 32-byte hash from Glider that the browser can't yet check (why new enrollments are paused), and withdrawing asks for an EIP-712 signature that the browser checks is exactly the withdrawal asked for (
lib/baskets/withdrawCheck.ts), and a deposit is a plain USDC transfer the user sends from their own wallet. Afterbook never holds funds or keys for baskets; Glider's agent holds an unrestricted (SudoPolicy) permission onexecute, so only Glider's own system keeps it to rebalancing and to withdrawals to the owner (see "Baskets (Basis Tilt)"). - The non-US geofence (
x-vercel-ip-country) counts the US territories (Puerto Rico, Guam, the US Virgin Islands, American Samoa, the Northern Mariana Islands, the minor outlying islands;US_REGIONSinlib/server/geo.ts, 2026-11-22) as the US. It is a best-effort UX gate, not a compliance control — it's defeated by any VPN, and the UI says so. Detected-US viewers see explicit "not available" copy rather than a silently-disabled button. - In-app swaps (since 2026-10). Until then the README promised "no custom swap router, and this app never constructs swap calldata." Buy / Sell changed that, so the promise is now narrower and enforced in code (
lib/swap/swap.ts): Afterbook deploys no contract and holds no funds; KyberSwap builds the transaction and the server refuses it unless the decoded fields that decide the outcome match the request (router0x6131…37b5, input and output token, recipient = the connected wallet, amount and its split, a minimum received within the trader's chosen slippage (0.1–1%, default 0.5%) of the quote, Afterbook's fee or none, no permit; the route's internal steps are KyberSwap's, bounded by the router's minimum-received check); the wallet is only ever asked to approve that router for the exact amount, never unlimited; the review card shows the checked numbers before anything is signed.checkSwapCalldatais tested with tampered calldata (wrong recipient, lower minimum, other token, other fee recipient, a permit: all refused). - "Or trade on Aerodrome's own site" still deep-links to
aerodrome.finance's swap page (a token pair, routed by Aerodrome). Add liquidity opens the stock's own pool:app.aero.xyz/deposit/8453-<pool>for an Aero pool, Aerodrome's "New deposit" page for the others. - Strict CSP (script-src limited to same-origin + a fresh per-request nonce — the tiny theme-init script in
<head>carries that nonce), HSTS, X-Frame-Options: DENY, no third-party scripts or fonts (Poppins is self-hosted bynext/font). The only third-party images are the token icons frommetadata.coinbase.com, allowed inimg-srcand loaded withreferrerPolicy="no-referrer"; each falls back to a letter tile if it fails. - No user secrets anywhere. Server-side configuration is Redis (Upstash) credentials, the Telegram and CRON secrets, the x402 CDP keys, the Glider tenant API key (
GLIDER_API_KEY) and the Claude API key for the trade plan's explanation (ANTHROPIC_API_KEY) — credentials for this server, never tied to a user or a wallet, and never sent to the browser (every/api/baskets/*route calls Glider from the server and resolves a user's portfolio from their address, never from a caller-supplied id). A full git-history secret scan was clean on 2026-10-13 (the only long hex strings are public transaction hashes).npm audit --omit=devthe same day: no critical, no high, 16 moderate. npm's suggested fix is wagmi 3, but RainbowKit (latest 2.2.11) only supports wagmi 2, so insteadpackage.jsonoverridespin the patched versions inside the wallet libraries:ws@8→ ^8.21.0 (the high: memory disclosure / DoS; WalletConnect's v7 copy is untouched, it isn't affected) anduuid→ ^11.1.1. The 16 moderates left are one advisory,decode-uri-component0.2.2 under WalletConnect'squery-string7: its fix (0.5.0) is ESM-only and would break that CommonJSrequire, and the worst case is a visitor's own tab hanging on a malformed WalletConnect link. They go away when RainbowKit supports wagmi 3. After touching the overrides, re-check the phone and desktop Connect wallet windows (verifyskill). Next.js was moved to 16.3.8 the same day for a criticalnext/ogadvisory. 2026-10-27 audit: Next.js 16.3.8 → 16.4.2 (two criticals, remote code execution through the image optimizer, which is on even though the app uses nonext/image, and throughuse cache, plus a Server Actions DoS; all fixed in 16.4.1),@modelcontextprotocol/server2.0.0 → 2.3.1 (two highs on/api/mcp: one HTTP client's messages delivered to another, and memory exhaustion from one request),zod4.6.5 → 4.6.6 and afollow-redirectsoverride to ^1.16.1. Left: 0 critical, 20 high and 7 moderate, all inside the x402 and wallet libraries. The highs are one zod advisory (memory exhaustion on oversized arrays) in the zod 3 copies those libraries bundle, which has no zod 3 fix; it goes away when@coinbase/x402,@x402/*and WalletConnect/Reown move to zod 4. The moderates aredecode-uri-component(above),fast-uriandhono, also from those libraries. 2026-11-03 audit (after an external review counted 25 highs):@x402/core,@x402/evmand@x402/next2.26 → 2.29 (@x402/*moved to zod 4.6.6, which closes the zod advisory where it mattered:@x402/corevalidates what an x402 caller sends, on our server),hono4.13.8 → 4.13.16 andfast-uri3.1.8 → 3.1.9. Left: 0 critical, 21 high, 3 low, none reachable by a caller on our server: zod 3 inside@coinbase/x402/@coinbase/cdp-sdk(which only sign this server's own requests to Coinbase's facilitator; no zod 4 release of either yet) and inside Reown'sappkit-wallet(the browser's WalletConnect window, latest still pins zod 3.22.4);decode-uri-component/query-stringin WalletConnect 2.21 (newer WalletConnect dropped query-string, but the version is set by wagmi 2's connectors);deepmerge(low) under RainbowKit. npm counts each package on those chains as its own high. Forcing zod 4 into the wallet libraries was not done: it can break the wallet window, which can only be fully tested with a real phone and wallet. They go with the wagmi 3 move, once RainbowKit supports it.
The "Liquid" label (2026-11-19, owner's bar; lib/market/liquidityBar.ts): a tracked stock is "Liquid" when its pool held at least $100k at every 5-minute depth reading over the last 72 hours, "Thin" when any reading dipped under (the lowest is shown), and "measuring" until 72 hours of readings exist (at least 80% of slots read). A lone $0 between two good readings at or above $100k, each within two slots, counts as a failed read (a node answering 0; seen on 2026-11-19), at most two per window, so one glitch can't mark a deep stock thin for days. A $0 at either edge (including the newest reading, just before the daily compute), a $0 next to a reading under the bar, and any pull above $0 always count. Coverage counts distinct 5-minute slots. A run that reads no samples at all keeps the previous labels instead of saving "measuring". A saved label over 48 hours old isn't shown, so a stopped cron can't leave stale labels up. $100k rather than $50k because 18 pools seeded at ~$51k on 2026-10-27 sit right on a $50k line, and a $100k bar falls in a clean gap (on 2026-11-19's samples nothing sat between $88k and $180k). The 5-minute alerts cron's samples are kept 73 hours (one key per run, as before); the daily discover-tokens cron computes the label and saves liquidbar:latest (?dry=1&bar=1 returns it unsaved); /stocks (tracked rows) and /memes (each meme's stock) read it through the data cache. Display only: isLiquid (the $1M line) and the Basis Tilt weights don't use it until the weighting replay is redone and the owner agrees.
Coinbase's list can shrink under us (2026-11-19: 358 tokens became 90, one page, no paging field; all 38 tracked stocks still in it). /stocks, the token icons and the meme job (which rules out other Coinbase stock tokens) read it through getCoinbaseStockList (lib/stocks/coinbaseListGuard.ts): a fresh list more than 25% smaller than the last good one is not used, the last good one is, and the daily discover-tokens cron alerts the owner. Only that cron writes the last good list (cblist:lastgood, slimmed to symbol, address, name and icon); readers keep it in memory for an hour. The cron also alerts when a tracked stock is missing from the list though the count holds. The saved list only ever grows on its own: a list that is smaller than it (any amount) or is missing a tracked stock is never saved, and a drop of over 10% alerts even below the 25% fallback, so a slow daily shrink can't walk the baseline down (owner, 2026-11-19). The cron's own discovery and /stocks pool refresh use the guarded list too, and a failed fetch on two daily runs in a row alerts (cblist:fetchfail). A baseline frozen for a week (a small drop, or a missing tracked stock) is reported once a week, timed from the last report (cblist:stalereport) so a missed cron day can't skip it. A drop of 10% or less (one real delisting, say) freezes the baseline with no alert of its own; only that weekly report says so. The drop, shrink and missing-stock alerts are sent once when the condition starts, not every day (cblist:alertstate); a drop that moves into another 5% band (deeper or back up), a change in which stocks are missing, or a move from a drop into a shrink is sent again. The cron sends first and records only what Telegram accepted, so a failed send is retried on the next run (the weekly report too). When the guard itself fails, that day's /stocks pool refresh is skipped and yesterday's stays up. Deleting cblist:lastgood resets the baseline only if no tracked stock is missing; a tracked stock Coinbase really dropped has to come back to the list or be removed from STOCKS first. The meme job doesn't use the list alone: it rules out the union of the tracked stocks, the fresh list and the last good list (getStockTokenExclusions), so a glitch can't let a stock token through as a meme. The cron reads the baseline straight from Redis and fails (with a "guard failed" alert, saving nothing) if it can't, so a failed read never accepts a collapsed list. If a smaller list is real, delete cblist:lastgood and the next run takes it as the baseline.
Contract addresses
All on Base mainnet, verified on-chain (decimals()/token0()/token1()/fee()/tickSpacing()/factory(), and the factory's getPool returning the pool) against Dexscreener's pair listings — see lib/stocks/tokens.ts for the full verification note. ANTc (2026-11-20): Coinbase's list (address, 8 decimals, multiplier 1, US ISIN, first minted 2026-11-19), on chain (Aero factory, token0 USDC, tick spacing 10, fee 500, the factory's pool), Dexscreener (the same Aero pair, ~$1.06M, $6.9M traded in 24 hours), Yahoo (ANT on Nasdaq; the pool's $87.70 against the pre-market $87.20). Its three-hour depth low was $244k and its 24-hour low ~$42k while liquidity arrived after the IPO, so it is held out of every automatic pick and of what leads a page (AUTO_PICK_HOLD, lib/agent/limits.ts: Describe a basket, the plan's default list, /build's starting basket, the /rules default, the headline gap and opening stock, live alerts, share-card rows, the close digest) until its depth proves itself; its own page, the tape row and a named buy work as for any stock. The home page's top-5-by-pool list ranks it like any stock but tags it "New listing" (neutral colour) while it is held, so a day-two IPO doesn't look as settled as NVDAc. Each stock points at its deepest USDC pool; all 38 were re-verified on 2026-10-27.
| Symbol | Token address | Pool address (USDC pair) | Factory, tick spacing |
|---|---|---|---|
| NVDAc | 0xb20000000000000000000078ee7ce2fE4908108C | 0xF668e21993f0ACd7ab00BB1cFbAeD0df28A3C8EC | Aero, 10 |
| AAPLc | 0xb200000000000000000000C2e324d24d7eEcd1fb | 0xF5FCB9CDAFcE67d50AfEf298F88E709d2B946BA6 | Aero, 10 |
| METAc | 0xb2000000000000000000008bC8786B856E61707C | 0xd072410fa13D242e1d53721Bcf7AF02e3455DC96 | Aero, 10 |
| GOOGLc | 0xb2000000000000000000002D0BA3164cc74f58B7 | 0x16c70F04C3080a127486Cdf5a4C33c066bBF47C3 | Aero, 10 |
| AMZNc | 0xb200000000000000000000d9192b6B456483C2E8 | 0x532e0F46d1e528507FC9454d5847C231f23bDDf6 | Aero, 10 |
| MSFTc | 0xB200000000000000000000Ab99cFa739E253872B | 0x2740C0faAb738F6e346e545fDE02aEF9B1A01ee7 | Aero, 10 |
| MSTRc | 0xb2000000000000000000004884b426556b92883d | 0x66DCd42E6314B287110922AE36cB2a8bdEECc153 | Aero, 10 |
| SNDKc | 0xb200000000000000000000397293Cb8cda9a10c5 | 0x2836e062a3fe75943a7F4A552E2365b98E414E75 | Aero, 10 |
| SPCXc | 0xb2000000000000000000007b9fcbd005511aCBd5 | 0x880dB7Dda4407D99508574E680d067D1164B3cFE | Aero, 10 |
| TSLAc | 0xb2000000000000000000001e800a7f5189430cD0 | 0x7A33000372f3F028f074182CCb9d16cBEEfBF920 | Aero, 10 |
| PLTRc | 0xb2000000000000000000007d16372840dF4dAbbe | 0xA0473ceD0cd1bfB857e3E04B5FA4b6aF18C5e44d | Aero, 10 |
| MUc | 0xb200000000000000000000Fd2f87532B90095211 | 0x41e21950362B1014bC629252ecFFF8fcA5F1646C | Aero, 10 |
| NFLXc | 0xb20000000000000000000058B8c947e44011dFE6 | 0x67Ba8dBeDC6D7f93f0F5967Aa2420715f1edC756 | Aero, 10 |
| SKHYc | 0xb200000000000000000000187f7071D6E321a7d2 | 0xEBC746A47ebb274de1dbDC9a465E6C5C2301C5DA | Aero, 10 |
| HIMSc | 0xB20000000000000000000043a599976181Bcf336 | 0x41D7793FAa4Ca181B6f021423fF3F9015C00b2ff | Aero, 10 |
| ORCLc | 0xb200000000000000000000347AFbA223D7B6b63C | 0x62B5452E80E50B047dcF6dd3Fb6a1D266C678eB5 | Aero, 10 |
| AMDc | 0xB2000000000000000000000d8Ce462E99ee7A47B | 0x138Cb591C4A7D854D796E1906af8228d84CB7642 | Aero, 10 |
| AVGOc | 0xB200000000000000000000Fc737aeA6196aB5a4c | 0x086A1447D0851F0aeA9D09D6c547fEC8E97be413 | Aero, 10 |
| LLYc | 0xB200000000000000000000f1a0F91e34892E4718 | 0x2b7ee4623ec6AfbC1e587b2668c0ED8F3ff44949 | Aero, 10 |
| MRVLc | 0xB200000000000000000000eC3c4c7395Cc609813 | 0x611ab290422d534D9595b01e648911fefA963137 | Aero, 10 |
| SONYc | 0xb200000000000000000000a26326a922FFA87f6C | 0x26Dd2AC81eA9a212afC84848893EdC21c5A76FDC | Aerodrome, 1 |
| BILIc | 0xb200000000000000000000ca7C6D1438e7245eb6 | 0x32A3cE6C3a8D6c24C4A51A5cF2869410CbF4D637 | Aerodrome, 1 |
| SAPc | 0xb200000000000000000000da6F64c306234127E0 | 0x21313A06B7f8ed38D8bC1fb8Be2fBD847634A6ec | Aerodrome, 1 |
| SANc | 0xB20000000000000000000017BB66E9301E913A99 | 0xE531069DF73530bf59c954F3718945D5fAA2e7dF | Aerodrome, 1 |
| NOKc | 0xB2000000000000000000005ac674f707E357409c | 0xc541eAc49f32D46C1E2f88952f22215Ef0f2Db71 | Aerodrome, 1 |
| PDDc | 0xB200000000000000000000c8A7223510467D8563 | 0x84608BE6d655ee05032303FE7f0D6F3A51c2CF51 | Aerodrome, 1 |
| LIc | 0xb200000000000000000000D61eFD9F54A23ef9eB | 0xD71b2D9cB3532477Df77AE26e780963CCe784a0c | Aerodrome, 1 |
| BIDUc | 0xb200000000000000000000d2b7D9aeE52F6C6BEf | 0xD47b8F13ffC3198148B138D3f07CC89C92042950 | Aerodrome, 1 |
| VALEc | 0xB20000000000000000000063376b142C0764B489 | 0x0F48336b76ee52Fa6bb19edf5AF358529Df57574 | Aerodrome, 1 |
| BUDc | 0xB200000000000000000000c36ce081Dd09e86cA2 | 0x5ee52963d3d33196a47Fad722ABB897E0FA395d9 | Aerodrome, 1 |
| NIOc | 0xb2000000000000000000002D2B5dc53c61f1bA06 | 0x484cc2CA594ced3fE38362FE950C60cE66f53F6D | Aerodrome, 1 |
| ARMc | 0xB20000000000000000000026215D755356E5043f | 0x9A0F4Fd0766Ccdb792bA58fE631aA7720097623c | Aerodrome, 1 |
| INFYc | 0xb200000000000000000000F6b0417af5F52341FC | 0x356cC16Fe38A6ad0eB25e655759dD963F8D674BF | Aerodrome, 1 |
| ULc | 0xB200000000000000000000349ef3Aa93a0897476 | 0x013FCB940735d17c81D3B91557aCC62Da723d9D5 | Aerodrome, 1 |
| WRDc | 0xb200000000000000000000e88EFe88D8aDE3f0dA | 0xbc440AFf9A79cCed69d5B21c7B71e60BD0278EFB | Aerodrome, 1 |
| NVOc | 0xb2000000000000000000008D5328e9208773dC58 | 0xc1ba39D668F14Eee2462CA5877402e4a7c4d1f34 | Aerodrome, 1 |
| SEc | 0xB2000000000000000000003088798F6d0722AaAC | 0x0274e5078033cB3fE788cf76bb97150FD9bc4547 | Aerodrome, 1 |
| HSAIc | 0xb200000000000000000000f3049F4aa834b23b64 | 0xDc8D2C31de17bf4dF00C05E4E132BCEA22F24c3b | Aerodrome, 1 |
| ANTc | 0xb20000000000000000000016e38FD364d271Ba28 | 0x599C4225FE90214795a0be228D20d7680f8CED15 | Aero, 10 |
USDC on Base: 0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913. CL factories: Aero's 0x9CB220581b91b0C83223012FE69688b92aD07a76 (Aerodrome and Velodrome became Aero on 2026-10-22; address from Aero's dromos-labs/metadex-slipstream-public deployment files) and the older Aerodrome one 0xf8f2eB4940CFE7d13603DDDD87f123820Fc061Ef (not Aerodrome's public Quoter/SwapRouter factory — see security model above). Aero pools charge a dynamic fee (0.015–0.05% on 2026-10-27), so quotes read the pool's live fee() (PoolState.feePpm); feePpm in lib/stocks/tokens.ts is only the fallback.
Code map
lib/ is grouped by feature (2026-11-04); put a new module in the folder of what it serves:
| Folder | What lives there |
|---|---|
lib/swap/ | In-app swaps (real money): KyberSwap build and checks, the request guard, the swap log, meme and basket buys |
lib/lending/ | Aave and Morpho reads, the in-app Aave borrow and lend maths and calls (real money), liquidation and loan-health maths |
lib/baskets/ | Basis Tilt on Glider (real money): the Glider client, weights, the tilt job |
lib/wallet/ | Wallet setup: wagmi config, the Builder Code suffix, Basenames |
lib/market/ | Prices and pools: the tape, quotes, depth, liquidity lines, the NY session clock, history, volatility, swap simulation, the /today snapshot |
lib/stocks/ | Which tokens exist and their data: tokens.ts (STOCKS), Coinbase's list and icons, discovery, earnings, corporate actions, symbol colours, /stocks |
lib/lp/ | LP positions and range maths: My Lots, fee APR, gauge yield |
lib/build/ | /build custom baskets: the spec in the URL and its cost |
lib/memes/ | Memestocks: the verified pool allowlist and formatting |
lib/share/ | Share cards and link previews: the card image, metadata, snapshots, share text |
lib/alerts/ | Telegram alerts and the in-page toasts |
lib/agent/ | The trade plan (/plan): the checks and sizing (plan.ts), "Describe a basket" (brief.ts), its input limits (limits.ts), Claude's explanation (explain.ts) and its rate-limit gate (explainGate.ts); stock rules (/rules): schedules, caps, validation and export (rules.ts) |
lib/server/ | Server plumbing: Redis, rate limits, the shared-secret check, region lookup, x402, the click log |
lib/format.ts, lib/brand.ts | Shared number formatting and the logo |
app/components/ is grouped the same way (2026-11-04):
| Folder | What lives there |
|---|---|
home/ | The Trade home page (TradeHome.tsx) |
agent/ | The trade plan page (PlanClient.tsx, with "Describe a basket" in BriefClient.tsx); its buys use the swap panel and, for a basket, /build's basket buy |
swap/ | The swap panel and its shared wallet steps (useSwapWallet.ts), slippage, Portfolio's router approvals (real money) |
lending/ | The in-app Aave borrow and lend panels and the loan calculator (real money) |
baskets/ | Basis Tilt's deposit panel and /build's basket picker, buy and sell (real money) |
memes/ | The memestock board and meme buy panel (real money) |
markets/ | The /markets page (HomeClient.tsx and its sections), the tape, charts and /stocks |
portfolio/ | My Lots |
notifications/ | Toasts, the bell and the live alerts |
layout/ | Header, ticker strip, theme, the wallet button, the logo |
ui/ | Small shared pieces: symbol tiles, token icons, the Share button, the session pill |
Styles are one stylesheet per area in app/styles/ (2026-11-04), loaded in a fixed order by app/globals.css: tokens, base, ui, layout, notifications, markets, stocks, memes, baskets, lending, swap, home, agent, then overrides.css (touch targets, phone field sizes, reading text), which must stay last. Order decides ties, so a new rule goes in the file of the area it styles, and a rule meant to beat other areas goes in overrides.css. When splitting was done, every element's computed style on every page (desktop and phone, both themes) was compared with the single file before it: identical.
Running it
Needs Node 20.9 or newer (Next.js 16).
npm install
npm run dev # http://localhost:3000
npm test # Vitest unit tests for the swap path, the trade plan and more (offline, mocked)
npm run typecheck # tsc --noEmit
npm run build # production build; CI runs all three on every PR
No environment variables required to run it — the app works fully without them. .env.example lists every variable the code reads, empty; copy it to .env.local and fill only what you need. (vercel env pull would bring the project's real values, production keys included: read CLAUDE.md first.) Optionally:
KV_REST_API_URL/KV_REST_API_TOKEN(orUPSTASH_REDIS_REST_URL/UPSTASH_REDIS_REST_TOKEN) — a Redis (Upstash) REST endpoint. Enables the "basis since close" sparkline's history, Telegram alerts, and the public API's key storage. Without it, the sparkline stays empty and both features return503.TELEGRAM_BOT_TOKEN,TELEGRAM_WEBHOOK_SECRET— enables Telegram alerts. The token comes from @BotFather; the webhook secret is any random string you generate yourself, passed to Telegram'ssetWebhookassecret_tokenand checked against theX-Telegram-Bot-Api-Secret-Tokenheader on every incoming update (in any built deployment the webhook refuses everything if it is unset). To confirm the bot's real username, call Telegram'sgetMewith the token (do not print the token).CRON_SECRET— a random string Vercel automatically attaches asAuthorization: Bearer <secret>on cron-triggered requests (documented pattern); secures the cron routes against being triggered by anyone else.TELEGRAM_ADMIN_CHAT_ID— maintainer-only. A daily cron diffs Coinbase's public tokenized-stock list (api.coinbase.com/v1/tokenized-stocks, 106 names on 2026-10-08, 92 on 2026-10-07, 58 on 2026-10-01; the newest Aerodrome pools are still tiny (deepest $708), none near the $250k line; the older base.org/stocks page it used to scrape lists only ten) against the tickers tracked inlib/stocks/tokens.ts, checks each untracked one for an Aerodrome USDC pool and its real depth, and sends one Telegram digest to this chat ID (plus a ready-to-paste entry for any pool over $250k). A pool over $50k on one read (well under the $250k snippet line) is judged by the lowest its depth has been in the last three hours (today's depth walked back through every deposit and withdrawal in the pool's logs,lowestRecentDepthUsdinlib/stocks/discovery.ts; the three hours are found by block timestamp since Denim made Base's blocks 200 ms on 2026-11-05, so a fixed block count no longer means a fixed time), for the digest and for/stocks; if those logs can't be read it gets no snippet. On 2026-10-19 a bot was moving about $200k in and out of the LLYc pool (in half the time, for up to 32 minutes; out for up to 45), so a single read reported $254k for a pool whose lowest in three hours was $39k; the next day it read $229k, under $250k, and /stocks showed that until the check started at $50k (its low was $29k). A token is reported when it first has a pool and again when that pool first becomes liquid, never repeatedly. The digest also names, once each, any token in Coinbase's list that/stocksand the check leave out (splitListedTokensinlib/stocks/coinbaseStockList.ts: a symbol that doesn't match, no contract address, or a repeated symbol); until 2026-11-04 such tokens vanished silently, and BRK.Bc was missing from/stocksbecause of the dot in its symbol. It never editslib/stocks/tokens.tsitself — a human still reviews and adds each one. Also used to flag a real B20multiplier()change (split or dividend) on any tracked stock.GLIDER_API_KEY,GLIDER_STRATEGY_ID(and optionallyGLIDER_API_BASE,BASKET_AUTOPUBLISH) — enable Baskets; see "Baskets (Basis Tilt)". Without the first two the/basketsenroll panel stays off and every/api/baskets/*route answers503.DEV_GEO_COUNTRY(e.g.DE) works only undernext dev.KYBERSWAP_API_KEY— Afterbook's KyberSwap API key. Set, every aggregator call (swaps, the meme job's sell check) goes to the keyed gatewayhttps://api.kyberswap.com/swap/base/api/v1with onlyx-api-key; unset, to the publicaggregator-api.kyberswap.comwithx-client-id: afterbook. Secret.SWAP_FEE_BPS,SWAP_FEE_RECIPIENT— Afterbook's fee on in-app swaps (1–100 bp, and a public receiving address). The fee is off unless both are set and valid, and is always taken in USDC. See "In-app swaps".ANTHROPIC_API_KEY— lets Claude write the trade plan's explanation (/plan, see "Trade plan"). Without it every plan is explained in fixed words. Set a monthly spend limit on the key in the Claude Console; the site also caps explained plans at 10 an hour per visitor and 500 a day.CDP_API_KEY_ID,CDP_API_KEY_SECRET,X402_PAYOUT_ADDRESS— enables the pay-per-call agent API (see "Pay-per-call agent API (x402)" below). The CDP keys are Coinbase Developer Platform platform credentials (from portal.cdp.coinbase.com), not a blockchain signing key — they authenticate this server to Coinbase's facilitator service, which is what actually settles payment on-chain.X402_PAYOUT_ADDRESSis any wallet address you control; USDC lands there directly. Without all three set, every/api/v1/x402/*route returns503.
Public API
/api/v1/tape is a separate, versioned, documented contract for external consumers (bots, agents) — distinct from the unauthenticated /api/tape the site's own frontend polls, so internal refactors never silently break external callers.
Get a key (free, instant, no signup):
curl -X POST https://afterbook.app/api/v1/keys
A key lasts a year (expiresAt in the answer); ask for a new one after that. Afterbook stores only the key's SHA-256 hash (lib/server/apiKeys.ts, 2026-11-22), so it can't show a lost key again. Keys issued before then were stored as plain text with no expiry: each moves to the hashed form, with a fresh year, the first time it is used. A key issued before then and never used again stays in plain text until a one-off migration (scan apikey:ab_*, write the hashed record with the expiry, delete the plain one) is run against production Redis, with the owner.
Call the tape with it:
curl https://afterbook.app/api/v1/tape -H "Authorization: Bearer ab_..."
Response shape (frozen — internal-only fields like cashTicker/name/cashStale are deliberately not part of this contract):
{
"session": { "state": "after-hours", "label": "After-hours", "nyTime": "16:30" },
"asOf": 1735000000000,
"rows": [
{ "symbol": "NVDAc", "cashUsd": 218.36, "midUsd": 218.65, "basisBp": 13.5, "depthUsd": 2500000 }
]
}
Rate limit: 1 request/second per key.
Agent / MCP
Listed for agents (2026-11-25). server.json (repo root) is the server's entry in the official MCP Registry (io.github.Hryhorii77/afterbook, remote Streamable HTTP at https://afterbook.app/api/mcp), published with mcp-publisher (mcp-publisher validate, login github, publish) by the repo owner; bump its version to publish a change. Each paid x402 route declares a Bazaar discovery entry (lib/server/x402Discovery.ts, bazaarResourceServerExtension registered in lib/server/x402.ts): service name, tags, icon, input schema and an example output, so Coinbase's facilitator can list it in the x402 Bazaar. Listing metadata only: no price, payee, check or answer changes. Every settled payment is also recorded once, by its transaction, in a Redis hash (x402:paid, lib/server/x402Ledger.ts, the x402 server's onAfterSettle, which never fails a paid answer), and /traction's "Paid agent calls" shows the count and USDC per route (30 days and all; any payer, the owner's own Bankr calls included, owner decision 2026-11-25). The first nine (2026-11-25, the owner's Bankr wallet, $0.33) were backfilled from their onchain transferWithAuthorization transfers (scripts/x402/find-payments.mts finds them in a time window; scripts/x402/backfill-2026-11-25.mts wrote them, safe to rerun). The payout address is shared with another app's paid calls, so the ledger counts only payments Afterbook's own x402 server settled, never everything sent to the address.
The page /agents (2026-11-25, app/agents/page.tsx, linked from More) says the same for people: how to connect (Claude Code, Claude Desktop and claude.ai, any MCP client), the seven tools, a plan-to-signed-buy example, the paid x402 routes with their prices (read from lib/server/x402.ts), and what an agent can't do. A plan link page (/plan/<id>) has Copy link and, where the browser has one, Share (PlanLinkShare.tsx), so a person can pass a plan on; the link carries no wallet or amount and is checked again on every visit. /agents has its own share card (/card?page=agents, buildAgentsOgImage, static text, CARD_VERSION 21).
https://afterbook.app/api/mcp is a remote MCP server for agents (Claude, etc.) — no key, no signup, read-only (it never builds or signs a transaction). Add it as a remote MCP server in Claude Code, Claude Desktop, or any MCP-compatible client pointed at that URL.
Seven tools:
get_tape— no input. Same data as/api/v1/tapeabove.get_quote—{ symbol, usdcIn }. Shares out, execution price, and price impact for sizing a USDC → stock trade — the same estimate Lot Lab shows, not a firm quote; the actual fill happens in the swap on afterbook.app, signed in the trader's own wallet.get_basis_stats—{ symbol }. Mean/mean-absolute/max-absolute basis in bp while the cash market was closed, over the last 30 days of sampled history.nullif there isn't enough history yet.make_plan— the same input as/api/v1/x402/planbelow (symbolsas an array). The trade plan, explained in fixed words, plusplanUrl, a saved plan link (see "Plan links" below). 2026-11-21.make_basket— the same input as/api/v1/x402/basketbelow (themeandexcludefrom the fixed lists). The basket, explained in fixed words, plusbuyUrl, a saved plan link.check_loan_health—{ wallet, threshold? }(2026-11-22). The same answer as/api/v1/x402/loan-healthbelow (lib/lending/loanReport.ts), free: each loan's health at the oracle and at Base's price,healthIfNextOpenAtBasewhile the cash market is shut, and an Aave loan's repay/add links. Reads public positions only. One call per request, held to the read routes' per-caller limit in memory (no Redis).make_rescue_link—{ wallet, action: repay | add, threshold? }(2026-11-22). For an Aave loan, the loan warning's own link to the Aave panel (lib/lending/rescueLink.ts):urlpresets the rescue planner's fall (from Base's price now) and target (abovethreshold, default 1.2) and which field to fill, never an amount or a wallet; the person connects the borrowing wallet, the panel fills the amount from that loan, and they check it and sign.url: nullwith a reason when the wallet has no Aave loan. Sharescheck_loan_health's limits (one of the two per request).
The two plan tools run the same code as the page and the paid routes (runPlan/runBrief) but never call Claude (explain: false, so a free tool can't run up the Claude bill; fixedBecause is not-requested); the paid x402 routes add Claude's explanation. The route's POST reads the JSON-RPC body before handing it on: one plan call per request (a batch with more is refused before anything is counted), held to the plan routes' 10 a minute per caller in each instance and across instances by mcpPlanLimiter (Upstash); links saved by these free tools stop at 300 a day site-wide (planLinkDailyLimiter), after which the plan answers without one.
Pay-per-call agent API (x402)
/api/v1/x402/tape and /api/v1/x402/quote are the same data as /api/v1/tape and /api/quote above, gated by the x402 HTTP micropayment protocol instead of an API key — $0.02 in USDC per call on Base, paid directly from an agent's own wallet via EIP-3009 transferWithAuthorization. No signup, no key, no rate-limit ceiling — payment itself is the throttle. Same $0.02 tier: /api/v1/x402/execute-link — { symbol, usdcIn, direction?: 'buy' | 'sell' }, a sized trade estimate (same shape as /api/v1/x402/quote) plus swapUrl, the stock's page on afterbook.app at its swap (/<SYMBOL>#execute), where a person signs the trade in their own wallet through the checked in-app swap (see "In-app swaps"), with the Builder Code. Deliberately a link, not raw calldata: this route never returns calldata or touches a key. Until 2026-11-21 the link opened Aerodrome's own app (when the route was written this app had no router it could confirm worked on these Slipstream pools); a trade signed there skipped Afterbook's swap checks and carried no Builder Code. For a checked plan whose link opens already filled in, use /api/v1/x402/plan.
This isn't exclusive data — /api/quote and every MCP tool above stay fully free and unauthenticated, on purpose. This tier's actual value is zero setup friction for an agent that would rather pay $0.02 than provision a key and live under a rate limit.
Three higher, $0.05 endpoints for agents doing heavier analysis:
/api/v1/x402/history—{ symbol }. 30 days of sampled basis history (same data/api/historyserves free) plus the pool's current on-chain tick-liquidity distribution (same data/api/depthserves free) — bundled into one call for backtesting agents that want both the historical mispricing signal and how thick the book was at the time./api/v1/x402/lp-range—{ symbol, holdingDays?, targetProbabilityPct? }. A recommended concentrated-liquidity tick range sized from realized volatility over a target holding period (default 7 days, 70% coverage), widened when the symbol's next earnings date falls inside that window. This one has no free equivalent — it's genuinely new derived output, not a convenience bundle of already-free routes. The earnings widening is a documented flat heuristic (no options-implied-vol data source exists in this app), not a real implied move. Also returnsdivergenceLossAtBoundary— the impermanent-loss benchmark at each edge of that range (lib/lp/lpRange.ts)./api/v1/x402/liquidation-capacity—{ symbol, collateralShares?, borrowUsd?, marketId? }. The/borrownumbers for one stock: its Morpho and Aave V4 USDC markets (each withvenue; Aave ids areaave:<reserveId>, andborrowUsdis null because the pool is shared), the Aero-vs-oracle gap, the largest liquidation Aerodrome can absorb at a profit, a sell-side impact curve, and (with a position) its liquidation price and whether that liquidation could be sold on Aerodrome.marketIddefaults to the market holding the most collateral. $0.05.
Afterbook never holds a signing key for this. Settlement is executed by Coinbase's hosted CDP facilitator, not by this app — Afterbook only supplies a plain receiving wallet address (X402_PAYOUT_ADDRESS) and a CDP platform API key/secret pair that authenticates this server to Coinbase's facilitator service (not a blockchain key). Payment lands directly in that address (the owner's own wallet); nothing is ever custodied here, same as everywhere else in this app, and nothing swaps or spends it automatically.
Trade plans and baskets for agents (x402, $0.05; 2026-11-16, for the Stocks Maxxing quest). The same code as /plan (lib/agent/runPlan.ts, shared with /api/agent/plan and /api/agent/brief): the code decides every verdict and size, Claude only explains (or the fixed words do, under the same Claude limits). Read-only: neither builds anything a wallet could sign; a person buys on afterbook.app, from the plan link, behind the region gate and eligibility box.
/api/v1/x402/plan—{ symbols?, budgetUsd, maxPremiumBp?, maxCostBp?, earningsDays? }(symbolscomma-separated, e.g.NVDAc,AAPLc; none = the deepest pools). Returns{ plan, explanation, explainedBy, fixedBecause, planUrl, buyAt }: each stock's buy, wait or skip with its reasons and size, as on the page, and the plan link (buyAtis the same link, or/planwhen there is none)./api/v1/x402/basket—{ theme?, exclude?, minStocks?, budgetUsd, cashPct?, maxPremiumBp?, maxCostBp?, earningsDays? }(excludecomma-separated GICS sectors; encode&in "Memory & storage"). Returns{ brief, explanation, explainedBy, fixedBecause, buyUrl, buildUrl }: the 2–4 picks with amounts, every dropped stock and why, the plan link (buyUrl; the/buildpage if it couldn't be saved) and the basket's/buildpage.
Plan links (/plan/<id>, 2026-11-21; lib/agent/planLink.ts, lib/agent/savedPlan.ts, app/plan/[id]/page.tsx, SavedPlanClient.tsx). A plan or basket with something to buy, from the x402 routes, the MCP plan tools or the Telegram bot's /plan (2026-11-22, via: 'telegram'; the page then says the person asked the bot, not an agent), is saved (one Redis key agentplan:<id>, 96 random bits, 7 days, written once; the page reads it through the data cache, which keeps a found plan for an hour and never caches a miss; links always use the production address, siteUrl, even from a preview deploy) and returned as a link an agent hands to a person: agents pay, people sign. Opening it runs the plan's checks again (recheckSavedPlan): only the stocks the plan said to buy, with the same limits, each sized on its own against its saved amount. A stock plan offers each stock that still passes, at most that amount, in the normal swap panel (buy only, maxUsd); a basket is offered whole at its saved total, in the basket buy (maxUsd; one signature with Base Account), or not at all if any stock now fails or is cut. "Check again" reruns it. The link carries only what the code decided, never an agent's numbers; the person still ticks the eligibility box and signs each buy, with the Builder Code. Swaps from an agent's link are logged as source: 'agent' (agentLinkSwaps in /api/agent/stats); from a Telegram /plan link as source: 'telegram' (telegramLinkSwaps; 2026-11-22, owner: never counted as agent traction), each its own row on /traction. A Telegram-link swap signed in the hour or so between #217's deploy and this split (2026-11-22) is stored as agent. The amount offered always comes from the latest recheck (a panel open during "Check again" follows it, and closes if the stock stops passing), and each stock, or the basket, closes after one buy on the visit (a reload offers it again, still capped and signed by the person; there is no server-side total per link, owner 2026-11-21: a link isn't permission to spend). A basket goes through whole or not at all only with Base Account's one signature; other wallets sign each swap in turn and can stop partway. A new listing (AUTO_PICK_HOLD, ANTc today) is never offered from a link, even one the agent named: its card says so and links its own page. Receipts (2026-11-25, lib/agent/planReceipt.ts, PlanReceipts.tsx): each buy signed from a link carries the plan's id in its build (planId, kept by rememberBuiltSwap only for a valid id on an agent or Telegram link's buy), and once the swap log verifies it onchain it is listed under the plan (agentplan:<id>:fills, 8 days) with the stock the router's own Swapped event says was received, the quote and the signed minimum. The link's page then shows, per fill, what the plan said (amount, price a share, cost estimate and limit) next to what filled (paid, tokens, price a share with the token's multiplier, against the plan's price and the quote, the signed minimum and the plan's amount). Numbers only, rounded (whole dollars, tokens to 3 significant figures) so they can't be searched on chain, and only for stocks the plan listed: no transaction hash or wallet, since a link can be shared. The fills list keeps the latest 50 and the page reads it through the data cache for a minute. Tests: tests/planReceipt.test.ts and the plan-link cases in tests/swapLog.test.ts. Not indexed (noindex). Tests: tests/planLink.test.ts, tests/x402Plan.test.ts.
Both take query parameters (GET, like the other routes), refuse unknown ones (a typo is a 400, not a silent default) and take no note: on the page it is the person's own words, and from an agent it would only be text for Claude, while the numbers decide (lib/agent/x402Input.ts). A 400 or 502 isn't charged (withX402 settles only a successful response). Each paid call counts as a plan in the traction stats and in paid (/api/agent/stats); it is counted once the payment is verified, so a call whose settlement then fails still counts. Both routes keep the page's 10-a-minute limitRead per caller (the handler runs before settlement, so one signed payment sent many times at once can't run many plans; a 429 isn't charged), and paid calls share the page's Claude limits: past them the plan comes with the fixed words and fixedBecause says why. Tests: tests/x402Plan.test.ts.
/api/v1/x402/loan-health—{ wallet, threshold? }($0.02; 2026-11-21). A wallet's Aave V4 and Morpho stock loans on Base, the same reads and rules as the Telegram loan alerts: health at the oracle and at Aero's price, the worst of the two, how far the collateral could fall before liquidation, whether it is underthreshold(default 1.2), a one-line summary and, for an Aave loan,actions.repayUrl/addUrl, the alert's links to the Aave panel. Read-only; a failed read is a 502 (not charged), never "no loans". Since 2026-11-22 it also returnsmarket(the session, the next open and its weekday, whether a weekend or holiday break is on) and per loanhealthIfNextOpenAtBase(health at Aero's price while the cash market is fully shut: overnight, a weekend or a holiday; null otherwise), the same answer as the free MCP toolcheck_loan_health(lib/lending/loanReport.ts). Tests:tests/rescueLink.test.ts.
All nine routes 503 with { "error": "x402 tier not configured" } until CDP_API_KEY_ID, CDP_API_KEY_SECRET, and X402_PAYOUT_ADDRESS are all set.
Deploying
npx vercel
or import the repo in the Vercel dashboard. No env vars required — add the Redis ones from "Running it" above (e.g. via a Vercel-connected Upstash integration) if you want the sparkline to accumulate history in production.
License
MIT.
No installation packages available.