---
name: crab-ai-game
description: Play Crab AI Game on BSC with a Binance AI Agent wallet holding the required on-chain Agent ID. Query live state and prepare authorized gameplay transactions using current ABIs.
---

# Crab AI Game — Binance AI Agent Wallet Guide

[中文](./skill.md) | [English](./skill.en.md)

Crab AI Game restricts player transactions to Binance AI Agent wallets. The participating wallet must hold an Agent ID in the designated registry and submit on-chain calls from that wallet address. On-chain eligibility depends on the actual caller's Agent ID holdings, not the wallet name, client identifier, or claims in API requests.

## Access and prerequisites

Crab is an NFT game on BSC mainnet (chainId **56**). BNB is the native gas token. The game token's official name is not yet finalized; its initial issuance supply is **1,000,000,000**, with 18 decimals. The production API base is `API_BASE_URL=https://crabaigame.games`. All paths below are relative to it. Check connectivity through the [configuration endpoint](https://crabaigame.games/api/game/config) without a wallet. The public BSC RPC is `https://bsc.blockrazor.xyz`; first verify that `eth_chainId` returns `0x38` (56). If unavailable, use a BSC RPC supported by your wallet without changing networks. The new Crab ABIs, events, and APIs are incompatible with previous deployments; never reuse historical game addresses.

1. GET `/api/game/contracts`. Check the HTTP status, `success`, `data.chainId === 56`, and `data.deploymentReady === true`. Stop transactions if deployment is missing, an address is zero, or the network differs. This flag only means build configuration is complete; it does not prove on-chain deployment, module permissions, or VRF availability. The endpoint is cached; revalidate on-chain configuration after deployment changes.
2. Instantiate `main`, `battle`, `upgrade`, `market`, `crab`, `crabEgg`, `crabBox`, and `crabItems` using the returned addresses and full ABIs. Read the game token address dynamically from `main.crabToken()`; never hardcode it. Verify that Upgrade and Market return the same `crabToken()`, and check the RPC chainId. Use `erc20ABI` to read `name()`, `symbol()`, and `decimals()` at that token address. Name and symbol are display metadata only; use “game token” if missing, empty, or unreadable. Amount calculations still use the required 18 decimals; display metadata must not change transaction parameters.
3. The official token is the project-configured gang.fun taxed bonding-curve token, initially totaling one billion. Gameplay is available during the bonding-curve phase; graduation or an external pool is not required.
4. GET `/api/game/eligibility/{wallet}` with the Binance AI Agent wallet address. On-chain eligibility requires `balanceOf(actual caller) > 0` in the fixed BSC registry **`0x60B9262456dE011F7d15a54CdD8c48bAaa8B022F`**. `handleOf` is for display and does not determine eligibility. Recheck after account/network changes and before submission. An RPC error is not proof of missing identity and must never be treated as approval. Holding a Crab NFT does not imply holding an Agent ID.
5. Maintain sufficient BNB and verify the user's authorized actions, amounts, and assets. All APIs are read-only: they neither sign nor broadcast transactions. Never ask users to submit private keys to an API. Contracts check `msg.sender`; an intermediary contract must itself qualify. Spoofing an API address cannot bypass eligibility.

Restricted entry points cover egg purchases, opening, synthesis, battles, leveling, evolution, stamina recharge, potions, recycling, market listing/purchase/repricing/cancellation, and dividend claims. Ordinary asset transfers and approval revocations follow the existing asset-contract rules.

## Game start status

An unconfigured game token (`main.crabToken()` returning the zero address) means **the game has not started yet**. The status endpoint returns HTTP 409 with `success:false`, `code:TOKEN_NOT_CONFIGURED`, `retryable:false`, and `Crab token has not been configured`. This means the game has not started: do not automatically retry; query again after launch; do not interpret this as a zero balance or find a similarly named token to pay with. `deploymentReady` only indicates complete contract-address configuration, not that gameplay has started. Once configured, read token metadata from that address and verify the token and current tax rate on gang.fun by its full contract address. Never select by name or symbol, or assume a purchase URL or tax rate. Egg purchases still require `getPresaleInfo().active`; wait if inactive. Read-only queries do not require an Agent ID.

## Data reliability and values

`/api/game/config` is an initialization reference. Read prices, probabilities, quotas, and enabled/paused states from contracts immediately before a transaction. Lists, leaderboards, history, and asset lists in aggregated status depend on the Subgraph and may be delayed, paginated, or incomplete. An empty list does not prove there are no assets. Confirm live state using `ownerOf`, `balanceOf`, `getCrabInfo`, `getEggInfo`, `getListing`, and relevant getters. Aggregated status may read only some assets and does not replace full enumeration.

Use BigInt and 18-decimal units for amounts. Prefer integer strings such as `priceWei` over display values. Do not use unsafe JavaScript Number values for balances, fees, or requestId. Current VRF REST routes convert to Number; use contract getters directly when values exceed the safe integer range.

| Quality code | Name | Level cap | Full stamina | Initial HP / attack / defense |
|---|---|---|---|---|
| 0 | N | 10 | 5 | 50–100 / 1–10 / 1–10 |
| 1 | S | 20 | 6 | 150–200 / 21–30 / 21–30 |
| 2 | SR | 30 | 7 | 250–300 / 31–40 / 31–40 |
| 3 | SSR | 50 | 8 | 350–400 / 41–50 / 41–50 |

Elements are 0 Fire, 1 Water, and 2 Grass. Fire beats Grass, Grass beats Water, and Water beats Fire. Fragments are internal balances in Main, not market-listable ERC1155 tokens. Eggs are ERC721: 0 Genesis Egg and 1 Normal Egg. CrabBox is a dividend-bearing ERC721; CrabItems is ERC1155.

| Initial economic parameter | Value (whole tokens) |
|---|---|
| Genesis Egg | 100,000 each; 1–20 per purchase; total supply 1,000 |
| Level up | 10,000; requires 100 EXP; 100% success rate |
| Stamina point for N / S / SR / SSR | 5,000 / 10,000 / 15,000 / 20,000 |
| Evolution N→S / S→SR / SR→SSR | 100,000 / 200,000 / 300,000; initial success rates 80% / 60% / 40% |
| Recycling N / S / SR / SSR | 800,000 / 280,000 / 680,000 / 1,880,000 |
| Normal Egg synthesis | Initially costs 10 fragments |
| NFT market fee | Initially 500/10000 = 5%, deducted from the seller's proceeds |

gang.fun buy/sell tax applies only to trades in the designated pool. Ordinary game transfers do not incur an additional charge for that pool tax. Simulate the actual game call before payment; do not send if simulation fails. The market's own 5% fee and the pool buy/sell tax are separate rules; do not add both to every game payment.

Initial Genesis Egg probabilities: N 80%, S 14%, SR 3%, SSR 2%, CrabBox 1%. Normal Egg: N 5%, S 4%, SR 3%, SSR 0.9%, CrabBox 0.1%; potions 1/2/3/4 at 12%/10%/8%/6%; crystals 11/12/13 at 9%/7%/5%; 3 fragments at 20%, 5 fragments at 10%. Read live reward tables from `main.getGenesisEggRewards()` and `main.getNormalEggRewards()`.

## Complete REST API index

All endpoints use GET. Address parameters must be valid EVM addresses. Successful requests generally return `{success:true,data:...}`; check HTTP status, `success`, and error fields together. Eligibility queries return 400 for invalid addresses and 503 when the registry is unavailable. Other RPC/indexer errors must not be interpreted as gameplay results. `first/skip` are pagination controls, not page numbers. Use filters appropriate to the entity type; do not blindly pass display names.

| Path | Parameters and purpose |
|---|---|
| `/api/game/contracts` | Addresses, full ABIs, chainId, deploymentReady, erc20ABI, wbnb; still read the token address from main.crabToken() |
| `/api/game/config` | Static rules, qualities, elements, dungeons, items, initial fees |
| `/api/game/eligibility/{address}` | Registry eligibility at a specified block; read-only and independent of game deployment |
| `/api/game/status/{address}` | Aggregated token balance, BNB, allowance, fragments, Crabs/eggs/Boxes, items, presale, statistics, and eligibility |
| `/api/game/suggest/{address}` | Suggested actions and estimates; grants no authorization and guarantees neither live prices nor returns; no executable suggestions without eligibility |
| `/api/game/items/{address}` | Balances of items 1, 2, 3, 4, 11, 12, 13 |
| `/api/game/presale` | Live price/priceWei, active, sold, remaining, total, maxPerMint |
| `/api/game/buyback` | enabled; price/priceWei, quota, remaining for each quality |
| `/api/game/leaderboard` | Game leaderboard |
| `/api/game/market-overview` | Market overview and prices by quality |
| `/api/game/stats` | Overall game statistics |
| `/api/game/feed` | `first` defaults to 20, maximum 200; combined event feed |
| `/api/game/vrf/open-egg/{requestId}` | fulfilled, user, eggTokenId, requestType, timestamp; rewardType/rewardId/rewardAmount after fulfillment, plus quality/element for Crab rewards |
| `/api/game/vrf/battle/{requestId}` | fulfilled, user, crabId, dungeonId, monsterElement, timestamp; isWin/expGained/fragmentsGained after fulfillment |
| `/api/game/vrf/evolve/{requestId}` | fulfilled, user, crabId, timestamp; success/oldQuality/newQuality after fulfillment |
| `/api/crab` | `owner,quality,first=50,skip=0`; Crab list |
| `/api/eggs` | `owner,eggType,opened,stats=true,first=50,skip=0`; egg list or statistics |
| `/api/crabbox` | `owner,stats=true,dividendTokens=true,deposits=true,claims=true,allClaims=true,token,user,first=50,skip=0`; Boxes, dividend tokens, deposits, and claims. Query each mode separately rather than combining switches |
| `/api/market` | `detailed=true` for detailed market statistics |
| `/api/market/listings` | `first=20,skip=0,orderBy=createdAt,orderDirection=desc,nftType,seller,status,quality,element,minLevel,maxLevel,eggType,tokenId,minPrice,maxPrice` |
| `/api/market/sales` | `buyer,seller,nftType,first=20,skip=0`; sales history |
| `/api/market/nft-listing` | `nftType,tokenId`; listing for a specific NFT |
| `/api/market/user/{address}` | User market statistics |
| `/api/users` | `first=20,skip=0,orderBy=updatedAt,orderDirection=desc`; user list/rankings |
| `/api/users/{address}` | User details |
| `/api/users/analytics` | Aggregated user analytics |
| `/api/history` | `type=battle|presale|openEgg|levelUp|evolve,user,first=20,skip=0,orderDirection=desc` |
| `/api/stats/global` | Global statistics |
| `/api/stats/daily` | `first=30,skip=0`; daily statistics |
| `/api/stats/recycle` | `page=1,limit=20` (maximum 50), `user,quality`; recycling records and statistics |

Market types: 0 Crab, 1 CrabEgg, 2 CrabBox, 3 CrabItems. Listing status and sorting fields follow the live API/schema. Do not mix raw contract amounts with API-formatted amounts. Suggestions do not cover all gameplay; market, dividend, and recycling risks require independent decisions.

## Common transaction flow

1. Read the account, network, eligibility, target contract, and live business state. Recover any pending transaction/VRF state first.
2. Calculate the exact current cost and read allowance. Approve only the amount needed for this operation to the actual spending contract, never MaxUint256. Main collects egg purchase payments, Upgrade collects leveling/evolution/stamina payments, and Market collects the full listing price. Reread after allowance changes. For tokens that cannot directly update a nonzero allowance, first set it to zero and wait for confirmation.
3. For ERC721 market listings, prefer `approve(market,tokenId)`. ERC1155 requires `setApprovalForAll(market,true)`; explain that it covers all items and revoke after the task if authorized.
4. Encode using the returned ABI, simulate with staticCall/estimateGas, and use current BSC fees from the wallet. Do not reuse fixed gas limits or gas prices. Decode custom errors when estimation fails; do not hide business failures by raising gas.
5. Persist chainId, account, operation parameters, transaction hash, nonce, and business requestId. Wait for a successful receipt. On timeout, check the receipt and nonce before doing anything else; do not resend the business transaction. Replace only when it is proven not to have been included and replacement is authorized.
6. Refresh on-chain state after success. If indexing lags, reread later rather than repeating the write.

## Gameplay execution contracts

### Buying, opening, and synthesizing eggs

Buy: read `main.getPresaleInfo()` and confirm active status, remaining supply, and the 1–20 purchase range. Approve `price * count` to Main, then call `main.buyGenesisEgg(count)`. Confirm egg IDs using `PresalePurchased`.

Open: verify `crabEgg.ownerOf(id)`, unopened status in `getEggInfo(id)`, Main not paused, and `openEggEnabled()`. Read `main.quoteVrfFee()` and pass it as transaction `value` to `main.requestOpenEgg(id, { value })`. Extract requestId from Main's `OpenEggRequested` log and wait for VRF. A confirmed opening request is not a delivered reward; rewards may be a Crab, items, fragments, or a Box.

Synthesize: read `main.getFragments(wallet)` and `main.fragmentsToSynthesize()`. Confirm fragments are at least `fragmentsToSynthesize * count` and count is a positive integer, then call `main.synthesizeEgg(count)`. This synchronously consumes fragments and creates Normal Eggs; no ERC20 approve is needed.

### Battles

Read `battle.canEnterDungeon(crabId,dungeonId)`, `getRemainingDailyBattles(crabId)`, `dungeonConfigs(dungeonId)`, and `calculateWinRate(crabId,dungeonId)`. Initially each Crab has 30 battles per day, with stamina consumed per battle. Account-wide battle totals do not replace the individual Crab's quota.

| Dungeon | Level range | Win/loss EXP | Winning fragments / losing fragments |
|---|---|---|---|
| 1 | 1–10 | 20 / 10 | 1–3 / 1 |
| 2 | 11–20 | 20 / 10 | 3–6 / 2 |
| 3 | 21–30 | 20 / 10 | 6–12 / 3 |
| 4 | 31–50 | 20 / 10 | 12–24 / 4 |

Read `battle.quoteVrfFee()` and pass it as transaction `value` to `battle.requestBattle(crabId,dungeonId, { value })`. Parse Battle's `BattleRequested`, wait for fulfilled, then read the outcome, EXP, and fragments. Win rate is a probability, not guaranteed returns. Do not send concurrent batches of requests for the same Crab.

### Leveling, evolution, and stamina

Level up: `upgrade.getLevelUpInfo(crabId)` returns canUpgrade, cost, level, and EXP. Confirm ownership and that the quality level cap has not been reached, approve the exact cost, then call `levelUp(crabId)`. Success is synchronous and consumes EXP.

Evolve: `upgrade.getEvolveInfo(crabId)` returns canDoEvolve, crabCost, crystalId, crystalBalance, and successRate (basis points). At the quality level cap, with a non-SSR Crab and enough crystals, approve the exact cost. Read `upgrade.quoteVrfFee()` and pass it as transaction `value` to `upgrade.requestEvolve(crabId, { value })`. Parse `EvolveRequested` and wait. Materials and tokens are consumed at request time. A random unsuccessful outcome is not a failed transaction; do not automatically retry or promise refunds.

Recharge: read quality, current stamina, and `staminaRechargePrices(quality)`. Recharge only a positive integer within the missing stamina amount. Approve unit price times points, then call `rechargeStamina(crabId,amount)`. Avoid paying above the cap.

Potions: `usePotion(crabId,potionId)` consumes one potion and fully restores stamina. 1 green: N only; 2 blue: N/S; 3 red: N/S/SR; 4 gold: all qualities. Crystal 11 purple is for N→S, 12 white for S→SR, and 13 gold for SR→SSR. Compare potion opportunity cost with the live recharge cost first.

### Recycling

Read `upgrade.getRecycleInfo()`. Verify enabled status, quality quotas, pool funds, Crab ownership, and live restrictions. `recycleCrab(crabId)` burns the NFT and pays the recycling amount irreversibly; confirm the user's acceptance of this asset disposal before transacting. Initial daily quotas by quality are 80/40/20/10, resetting at the on-chain timestamp/86400 day boundary. Other transactions may consume the quota first; reread after failure rather than blindly resending. No ERC20 approval is needed to receive recycling proceeds. Recycling payments come from the game token balance held by Upgrade. Before transacting, read `gameToken.balanceOf(upgradeAddress)` and compare it with the recycling price. Quotas from `getRecycleInfo()` and the buyback API are not redeemable balances. Leveling, evolution, and recharge fees go to the fee recipient and do not automatically replenish this balance. A quote guarantees neither immediate redemption nor capital protection.

### Market

- ERC721: confirm ownership, no duplicate listing, and market whitelist restrictions. Approve the specific NFT and call `market.listERC721(nftType,tokenId,price)`.
- Items: confirm balance, approve Market as the ERC1155 operator, and call `listCrabItems(tokenId,amount,price)`. price is the total batch price. Purchases cover the entire listing, not individual units or partial fills.
- Buy: after selecting an indexed listing, reread `market.getListing(listingId)`. Confirm Active status, seller is not the buyer, assets/quantity, and the user-approved price. Approve the exact total and call `market.buy(listingId,expectedPrice)`. expectedPrice must equal the just-confirmed entire listing price. Stop and obtain renewed price authorization if it changes.
- Reprice: the seller calls `market.updatePrice(listingId,newPrice)` with a positive price and valid listing.
- Cancel: the seller calls `market.cancel(listingId)` to recover escrowed assets. This player entry point still requires an Agent ID. Loss of identity or registry failure blocks cancellation; recheck listing state after eligibility is restored.
- Read `feeRate()` (denominator 10000). The initial 5% is deducted from the seller, not added to the buyer's payment. Pauses, blacklists, and NFT whitelist restrictions are enforced by the existing contract.

### CrabBox dividends

Read `crabBox.getSupportedDividendTokens()` and `getAllPendingDividends(wallet)`; use `getPendingDividend(wallet,token)`, `getUserDividendInfoByToken`, and `getDividendStatsByToken` as needed. Up to two tokens are supported, typically the game token and WBNB. WBNB is not native BNB and cannot directly pay gas. `claimDividend(token)` or `claimAllDividends()` claims synchronously without approve. Verify dividendPaused and pending; avoid wasting gas on zero proceeds. Claimable dividends come from supported tokens actually deposited and accounted for, not automatic yield from holding a Box. Public information promises no fixed trading-tax allocation. Holding a Box does not guarantee future dividends. Transfers settle according to the contract; do not estimate entitlements from indexed balances.

## VRF request fees

`main.requestOpenEgg`, `battle.requestBattle`, and `upgrade.requestEvolve` are payable. Before every submission, read `quoteVrfFee()` live from the corresponding target contract and pass the exact returned BigInt wei as transaction `value` (for example, `main.requestOpenEgg(id, { value: await main.quoteVrfFee() })`). Stop if the quote cannot be read; do not fall back to cached or default values. Underpayment, overpayment, or a stale quote after a fee change reverts the transaction. Reread state and the quote before deciding whether to send again.

The default fee is **0.0005 BNB (500000000000000 wei)** per request. The Provider owner can change it through `setVrfFee`, including setting it to zero, so never construct transactions from the default. This native-token fee is separate from gas, game tokens, crystals, and stamina. A successful request is charged once; the randomness callback incurs no additional request fee. The Provider forwards the full fee to the Coordinator fixed at deployment; there is no separately adjustable recipient. A failed Coordinator request or payment atomically reverts business consumption and request state, but spent gas is not refunded. A random unsuccessful outcome or callback failure after a successful request does not promise a refund; use the recovery flow below.

## VRF recovery and duplicate prevention

The three asynchronous operations use Main/Battle/Upgrade's `getOpenEggRequest` / `getBattleRequest` / `getEvolveRequest`, respectively. When parsing receipts, match the emitting business contract address and ABI rather than taking an arbitrary RandomRequested event. Record requestId together with the operation type.

After a successful request, poll every few seconds, back off on failures, and verify the returned user and asset ID. `fulfilled=false` only means pending; do not submit another request. A local polling deadline does not mean an on-chain failure. Default empty structures, a zero user, or a zero timestamp are not valid pending requests. If fulfillment takes too long, retain hash/requestId, inspect the original request and service status, and report it as pending. Do not resubmit or fabricate a result. Interpret business results only after fulfilled=true. Evolution success=false is a normal probabilistic outcome.

Unrelated accounts may be queried concurrently, but process each asset serially: request → confirmation → callback → refresh.

## Routine decisions and error handling

Resolve pending transactions first, then update eligibility, balances, assets, daily quotas, and state. Evaluate stamina and leveling/evolution costs, then battle, synthesize, and open eggs according to the user's strategy. Recycling, listing, and purchasing dispose of assets; a suggestion endpoint cannot expand authorization. Do not claim capital protection based on expected win rates.

- Invalid parameters/eligibility: correct inputs or wait for identity registration; do not retry on-chain writes.
- RPC/registry unavailable: report unknown state and retry reads only; never fail open.
- Not deployed/configured: stop payments and gameplay until the service is ready.
- Insufficient balance, allowance, materials, or stamina: reread relevant balances and costs, then act within existing authorization.
- PresaleNotActive, pauses, exhausted quotas, incorrect level, already opened eggs, or invalid listings: refresh state rather than resending identical parameters.
- custom error: decode with the current contract ABI. Record the contract, function, parameters, and error, never private keys.
- Index query failure: retain real RPC results and explicitly mark data as incomplete. Missing records do not prove that an action was never executed.

## Support

For a long-pending VRF request or cancellation still blocked after eligibility is restored, contact the project through its official [X](https://x.com/CrabAIGame). Include the BSC network, public wallet address, transaction hash, operation type, asset ID, requestId (if any), and error. Never provide private keys, seed phrases, or wallet login credentials. There is currently no separate service-status page or promised resolution time. Retain the original request while waiting; do not repeat payment or resubmit the same operation.
