# AgentPerp DEX (v2) — Perpetual Futures Guide for AI Agents > AgentPerp is an agent-only continuous perpetual futures DEX on BNB Smart Chain (chainId 56). Only wallets holding a Binance `.ai` Agent ID can open positions or deposit LP. Collateral, PnL, and fees are settled 100% in Agentic Coin (AGC). Every trade pays 0.10% of notional size in AGC on open and 0.10% on close: **95% is burned permanently to `0x000000000000000000000000000000000000dEaD`** and **5% goes to the protocol maintainer**. > Leveraged futures and LP vault deposits carry real risk of total capital loss. Never open a position or deposit LP without showing your user a clear transaction preview and receiving explicit confirmation. ## Contracts & Roles (BNB Smart Chain, chainId 56) - AgentPerpVault (v2): `0x7cE99689e6Fd215ef7bd47d763F33606CE58eDF4` ([Sourcify](https://repo.sourcify.dev/56/0x7cE99689e6Fd215ef7bd47d763F33606CE58eDF4)) - AgentTwapOracle (v2): `0x741285E703cbb744Fbc2D95169195315F7075F50` ([Sourcify](https://repo.sourcify.dev/56/0x741285E703cbb744Fbc2D95169195315F7075F50)) - Collateral & Fee Token (AGC): `0x63dea5aCdbE1F27c968907D08610A5f0A0284bA6` (18 decimals) - Binance `.ai` Agent ID Registry (`vault.registry()`): `0x60B9262456dE011F7d15a54CdD8c48bAaa8B022F` - Burn Address: `0x000000000000000000000000000000000000dEaD` - Vault & Oracle Owner / 5% Fee Recipient: `0x7A36eD2ddA7f41211e1f9F1Ef406e3D2B402b95A` (`Ownable2Step`; **no oracle registrar role in v2**) - Automated TWAP Keeper Wallet: `0x27eACc82B81d5cadc926FCF1C5cE94755e7C163C` (Cloudflare Workers Cron `*/15 * * * *`; live status: `https://keeper.agentperp.workers.dev/health`) - Public Agent JSON API (vault TVL, LP share price, projected borrow APY, live market prices/caps, open positions): `https://keeper.agentperp.workers.dev/stats.json` - Verified Factories: PancakeSwap V2 (`0xcA143Ce32Fe78f1f7019d7d551a6402fC5350c73`), PancakeSwap V3 (`0x0BFbCF9fa4f9C56B0F40a671Ad40E0805A091865`), WBNB (`0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c`) ## Markets (Perpetual Futures Contracts) | marketId | Contract | Token Address | Index Pricing Source | Max Leverage | |---:|---|---|---|---:| | 0 | `AGCBNB` | `0x63dea5aCdbE1F27c968907D08610A5f0A0284bA6` | PancakeSwap V2 (`0xE56041CdDBB46DB01c67B7A62684F428a04Db8C6`) 15m TWAP | 5× | | 1 | `AIBNB` | `0x2a60AaB19b182B5C4b47fffC066ADA06Ab27924f` | PancakeSwap V2 (`0x6c3d8b927B8c38d5907aE64b17804871c97CEf97`) 15m TWAP | 5× | | 2 | `STARSAIBNB` | `0x81c3Ab2C7EE773aF2AC823b8CEF3c430ef11F039` | PancakeSwap V3 (`0x38fbdD5ce58a73De08e670AD114b2A78c4298956`) 15m TWAP | 5× | Additional WBNB-quoted PancakeSwap V2/V3 pairs may only be listed after a mandatory **48-hour on-chain timelock** and must hold `>= 50 WBNB` quote liquidity. Read `marketCount()`, `getMarket(id)`, and `getEffectiveOiCaps(id)` live. ## Oracle Price Freshness - Every market runs an on-chain 2-slot sliding **15-minute TWAP** (`MIN_TWAP_WINDOW = 900s`). - The AgentPerp keeper (`0x27eACc82B81d5cadc926FCF1C5cE94755e7C163C`) runs 24/7 on Cloudflare Workers Cron **every 15 minutes** (`*/15 * * * *`) to call `oracle.update(marketId)`. - `oracle.update(marketId)` is **100% permissionless** (anyone can call it once 15 minutes have elapsed) and every `openPosition`, `closePosition`, and `liquidate` opportunistically advances the sliding window on-chain. ## Before Acting 1. Confirm your wallet holds a Binance `.ai` Agent ID by calling `isAgent(yourAddress)` on `AgentPerpVault`. Non-agent wallets revert with `NotAgent()`. 2. Never ask for or store a private key or seed phrase. Sign only via the user's connected Binance Agentic Wallet. 3. Show the user one clear transaction preview (contract, function, arguments, collateral AGC, leverage, 0.10% fee, liquidation & exit risks) and execute only after explicit confirmation. 4. Wallet-to-wallet AGC transfers to/from `AgentPerpVault` are **tax-free** (AGC's 2% tax applies only on PancakeSwap pair swaps). ## Open a Position 1. Read `getMarket(marketId)`, `getEffectiveOiCaps(marketId)`, and `getVaultStats()` on `AgentPerpVault`. Confirm `!opensPaused`, `poolWbnb >= 50 WBNB`, OI headroom below `effectiveLongCapAgc`/`effectiveShortCapAgc`, and `availableForReserve_ >= min(sizeAgc, netCollateral * 3)`. 2. Read `getExecutionPrice(marketId, isLong, true)` on `AgentTwapOracle`. It returns `(execPrice, spotPrice, twapPrice, deviationBps)` in `1e30` precision. Stop if `deviationBps > 1500` (15%). - Set `acceptablePrice` for slippage protection: for Long, `execPrice * 101 / 100` (+1%); for Short, `execPrice * 99 / 100` (-1%). 3. Calculate `openFee = sizeAgc * 10 / 10000` (0.10%). Ensure `collateralAgc - openFee >= 100,000 AGC` (`100000e18`) and `1 <= sizeAgc / (collateralAgc - openFee) <= maxLeverage`. 4. Check `allowance(yourAddress, VAULT)` on AGC (`0x63dea5aCdbE1F27c968907D08610A5f0A0284bA6`). If below `collateralAgc`, include `approve(VAULT, collateralAgc)` in the preview. 5. Call `openPosition(marketId, isLong, collateralAgc, sizeAgc, acceptablePrice)` on `AgentPerpVault` (no BNB attached). 6. Record the returned `positionId` from the `PositionOpened` event. ## Monitor & Close a Position (Exit Conditions) 1. Call `getPositionStatus(positionId)` on `AgentPerpVault` to read `(pnlAgc, borrowFeeAgc, closeFeeAgc, netEquityAgc, execPrice, liquidatable)`. 2. Minimum hold time before manual close is **60 seconds** (`MIN_HOLD_SECONDS`). 3. To add margin and avoid liquidation: `approve` AGC and call `addCollateral(positionId, amountAgc)`. 4. To close: call `closePosition(positionId, minPayoutAgc)` on `AgentPerpVault`. Payout arrives in your wallet in the same transaction. - **Important exit constraints:** `closePosition` does NOT query the external Agent ID registry and does NOT depend on the 50 WBNB pool liquidity floor, **but it reverts with `PriceDeviationTooHigh()` whenever live spot deviates by more than 15% (`MAX_DEVIATION_BPS = 1500`) from the 15-minute TWAP**. During sharp volatility or spot manipulation (>15% deviation), closing is temporarily blocked until spot and TWAP converge within 15%. ## Deposit / Withdraw LP (Agent LP Vault) & LP Risk Notice - Agents can deposit AGC (`>= 100,000 AGC`) via `depositLP(amountAgc)` to back trader open interest and earn borrowing fees (`0.10% / day` of open notional) plus counterparty PnL. - **Withdrawal restrictions:** LP shares carry a **1-hour post-deposit cooldown** (`LP_COOLDOWN`) and **cannot be withdrawn while doing so would push vault utilization above 80%** (`reservedAgc > 80% × newVaultAgc`, reverting with `VaultUtilizationExceeded()`). When utilization is high, LPs must wait until open positions close or new LP deposits arrive before withdrawing the reserved portion. (`withdrawLP` does not query the external Agent ID registry.) - Because post-bootstrap new markets enforce a **48-hour timelock**, LPs have `>= 47 hours` after a new market is queued to withdraw available (unreserved) LP before activation. ### LP Risk Notice (Read Carefully Before Depositing LP) 1. **Sustained TWAP manipulation on thin pools:** On thin DEX pools, the 15-minute TWAP can be moved by a sustained pump or dump; any resulting trader profit is paid from the LP vault and **the loss falls directly on LPs**. 2. **LP share price excludes unrealized PnL:** The LP share price (`vaultAgc / totalLpShares`) reflects **realized vault balance only** and **does not include unrealized PnL** of currently open positions. Share price updates only when positions close or liquidate, which can create dilution/timing risk when large open PnL exists. 3. **OI cap changes have no timelock:** While listing *new* markets requires a 48-hour timelock, the owner can adjust or raise configured per-market OI caps via `setMarketParams` **without a timelock** (effective per-side OI remains hard-capped on-chain at `5%` of pool WBNB depth). 4. **Counterparty & fee-split risk:** Trading fees (0.10% per side) are split 95% burn / 5% owner (0% to LPs); LPs act as counterparty to traders and can lose principal if traders profit net of borrow fees. ## Verified Function Selectors (`AgentPerpVault` v2) ``` 0x1ffbb064 function isAgent(address account) view returns (bool) 0xec979082 function marketCount() view returns (uint256) 0xeb44fdd3 function getMarket(uint256 marketId) view returns ((bool exists, bool opensPaused, uint8 maxLeverage, string symbol, uint256 maxLongOiAgc, uint256 maxShortOiAgc, uint256 longOiAgc, uint256 shortOiAgc)) 0x749904be function getEffectiveOiCaps(uint256 marketId) view returns (uint256 effectiveLongCapAgc, uint256 effectiveShortCapAgc, uint256 poolDepthCapAgc, uint256 poolWbnb) 0xa59aa5a6 function getVaultStats() view returns (uint256 vaultAgc_, uint256 totalLpShares_, uint256 reservedAgc_, uint256 availableForReserve_, uint256 totalTraderCollateral_, uint256 totalVolumeAgc_, uint256 totalBurnedAgc_, uint256 totalOwnerFeesAgc_, uint256 totalTrades_) 0xeb02c301 function getPosition(uint256 positionId) view returns ((bool isOpen, bool isLong, uint256 marketId, address trader, uint256 collateralAgc, uint256 sizeAgc, uint256 maxProfitAgc, uint256 entryPrice, uint64 openedAt)) 0x22fb73d9 function getPositionStatus(uint256 positionId) view returns (int256 pnlAgc, uint256 borrowFeeAgc, uint256 closeFeeAgc, int256 netEquityAgc, uint256 execPrice, bool liquidatable) 0xeb37acfc function depositLP(uint256 amountAgc) returns (uint256 shares) 0xe4456ecb function withdrawLP(uint256 shares) returns (uint256 amountAgc) 0x143e9137 function previewWithdrawLP(uint256 shares) view returns (uint256 amountAgc) 0xeaf1f1e6 function openPosition(uint256 marketId, bool isLong, uint256 collateralAgc, uint256 sizeAgc, uint256 acceptablePrice) returns (uint256 positionId) 0xa8f35adf function addCollateral(uint256 positionId, uint256 amountAgc) 0x2d6ce61d function closePosition(uint256 positionId, uint256 minPayoutAgc) returns (uint256 payoutAgc) 0x415f1240 function liquidate(uint256 positionId) ``` ## Verified Function Selectors (`AgentTwapOracle` v2) ``` 0x91492956 function getPrices(uint256 marketId) view returns (uint256 spotPrice, uint256 twapPrice, uint256 lastUpdatedAt) 0xfe0ba5b1 function getExecutionPrice(uint256 marketId, bool isLong, bool isOpen) view returns (uint256 execPrice, uint256 spotPrice, uint256 twapPrice, uint256 deviationBps) 0x9a8b7002 function getPoolQuoteWbnb(uint256 marketId) view returns (uint256 quoteWbnb) 0x82ab890a function update(uint256 marketId) ``` ## Rules, Pricing & Admin Powers (Immutable) - **Trading fee:** 0.10% of notional size on open + 0.10% on close → **95% burned (`0x…dEaD`)**, **5% to owner**. - **Borrowing fee:** 0.10% of notional size per 24h (accrued per second) → **100% to LP Vault**. - **Leverage & Profit Cap:** 1× to 5× max; profit capped at `min(sizeAgc, 3 × netCollateral)` so vault solvency is guaranteed (`reservedAgc <= 80% × vaultAgc`). - **Flash-Loan-Proof Liquidations:** `liquidate()` evaluates PnL strictly on **TWAP only** (never spot) AND reverts if `deviationBps > 1500` (15%). Triggered permissionlessly when TWAP equity `<= 5% × sizeAgc`. Liquidator receives 5% of collateral; close fee is split 95% burn / 5% owner; remainder goes to LP Vault. - **Deviation Breaker:** `deviationBps <= 1500` (15%) is enforced on **open, close, AND liquidation** (meaning manual closes temporarily revert whenever spot diverges > 15% from TWAP). - **Admin Powers (Strictly Bounded):** Owner (`0x7A36eD…b95A`, no registrar role) can: (1) queue/execute new markets ONLY behind a **48-hour on-chain timelock** (`queueMarketFeed` + `queueMarket`), ONLY for official PancakeSwap V2/V3 WBNB pairs with `>= 50 WBNB` quote depth and `>= 15m` TWAP window; (2) adjust/raise configured per-market OI caps via `setMarketParams` **without a timelock** (effective per-side OI remains dynamically hard-capped on-chain at `5%` of pool WBNB depth / `2.5%` of 2-sided TVL) or pause new opens only; (3) update `feeRecipient`. Owner cannot withdraw trader collateral or LP funds, cannot pause closes/liquidations/LP withdrawals, and cannot upgrade contracts or alter fees. ## Errors | Error | Meaning | |---|---| | `NotAgent()` | Caller does not hold a Binance `.ai` Agent ID | | `CollateralTooSmall()` | Net collateral after 0.10% open fee is below 100,000 AGC | | `InvalidLeverage()` | Leverage outside `[1×, maxLeverage]` | | `PriceDeviationTooHigh()` | Spot diverges > 15% from TWAP (temporarily blocks open, close, and liquidate until prices converge) | | `PoolLiquidityTooLow()` | Pool WBNB quote reserve is below 50 WBNB minimum | | `SlippageExceeded()` | Execution price or payout worse than your slippage guard | | `OpenInterestExceeded()` | Market Long/Short effective OI cap (min of config & 5% pool WBNB depth) reached | | `VaultUtilizationExceeded()` | Vault utilization would exceed 80% (blocks new opens and LP withdrawals of reserved liquidity) | | `MinHoldNotElapsed()` | Must hold at least 60 seconds before manual close | | `NotLiquidatable()` | Position TWAP equity is still above 5% maintenance margin | | `CooldownActive()` | LP withdrawal attempted within 1 hour of last deposit | | `TwapNotReady()` | Oracle initial 15-minute TWAP window has not elapsed yet | ## Disclaimer Not affiliated with Binance or the core AGC team. Leveraged trading and LPing carry high risk of capital loss. All smart contract interactions on-chain are final.