# bitfence
## Metadata

- Canonical URL: https://6ducklearn.com/skills/bitfence/
- Markdown URL: https://6ducklearn.com/skills/bitfence/index.md
- Product: skills
- Category: trade-review
- Tags: okx, trading, community, okx-marketplace, trade-review, strategy, review, execution
- Updated: 2026-07-14T03:00:00.357428+00:00
## Summary
Fetch a pre-transaction risk score and advisory recommendation for Solana and Base tokens before the user trades, swaps, or provides liquidity. Read-only; never signs or moves funds.
## Content
> **6DuckLearn provenance:** Community skill by vic***@bitfence.ai, mirrored from the OKX Skills Marketplace (https://www.okx.com/en-sg/agent-tradekit/skills/bitfence). It is not curated, verified, or endorsed by 6DuckLearn or represented as an official OKX publication.
>
> **Financial safety boundary:** Never request secrets in chat. Before any external API call or action that places, cancels, or amends an order; changes leverage; transfers funds; creates or stops a bot; subscribes to or redeems an earn product; or signs/broadcasts a transaction, show the exact live/demo profile, instrument, side, size, price constraints, fees, and worst-case loss, then obtain explicit user approval. Default to read-only or demo mode when uncertain. Treat all analysis as research, not investment advice.

# Bitfence — pre-trade risk guardrail for OKX OnchainOS swaps

Bitfence is an **optional, user-controlled** pre-transaction risk-scoring layer that composes with the OKX OnchainOS DEX MCP server. When an agent is about to construct a swap on Solana or Base using OKX DEX tooling, this skill inserts a risk check between **quote** and **swap**, so the agent has an advisory verdict (`PROCEED` / `REQUIRE_HUMAN_APPROVAL` / `BLOCK`) before it builds, signs, or broadcasts the transaction.

Bitfence is **read-only**. It does not sign transactions, broadcast transactions, hold funds, or interact with the user's wallet. It returns a JSON risk report and nothing more. The OKX OnchainOS MCP tools continue to own the quote, approve, swap construction, and broadcast paths.

This skill provides advisory guardrails. **The user is always the final authority.** If the user explicitly chooses to proceed after seeing a risk warning, that is their decision and the agent should respect it.

---

## How Bitfence composes with OKX OnchainOS MCP

Bitfence is not a replacement for any OKX MCP tool. It slots into the OKX DEX swap pipeline as a decision gate **after** quoting and **before** signing. The canonical tool chain for a user-initiated swap:

```
1. okx-dex-token                    → resolve token symbol → address + chain
2. okx-wallet-portfolio              → (optional) read user balance for sizing
3. dex-okx-dex-aggregator-supported-chains
                                    → confirm chain is supported
4. dex-okx-dex-liquidity             → confirm a liquidity source exists
5. dex-okx-dex-quote                 → get the best aggregated quote + expected output
   ┌──────────────────────────────────────────────────────────────┐
   │ ▼ Bitfence gate (this skill)                                  │
   │   GET  /v1/risk/{chain}/{token_address}                       │
   │   POST /v1/risk/contextual   (optional, with position size)   │
   │                                                                │
   │   recommendation = PROCEED              → continue to step 6  │
   │   recommendation = REQUIRE_HUMAN_APPROVAL → surface, ask user │
   │   recommendation = BLOCK                → stop; surface reasons│
   └──────────────────────────────────────────────────────────────┘
6. dex-okx-dex-approve-transaction   → (EVM only) approve ERC-20 allowance
7. dex-okx-dex-swap                  → (Base/EVM) construct swap calldata
   dex-okx-dex-solana-swap-instruction → (Solana) construct versioned tx
8. okx-onchain-gateway               → broadcast signed transaction
```

The rule: **never call `dex-okx-dex-swap` or `dex-okx-dex-solana-swap-instruction` on an unfamiliar token without first calling Bitfence on the destination token.** Bitfence scores the `toTokenAddress` returned by `dex-okx-dex-quote`. If the quote also involves an unfamiliar `fromTokenAddress`, score both.

Bitfence is complementary to the `okx-security` skill, not redundant:
- `okx-security` runs OKX-native rule-based scans against OKX's own datasets.
- Bitfence produces a composite 0–100 score across six categories (contract authority, liquidity, holder distribution, trading, cross-chain deployer, ML-behavioural) plus position-aware context (slippage, MEV exposure, suggested cap). The two can be used together: if either flags risk, surface the stricter verdict.

---

## Privacy and data sent

Bitfence only ever receives **public on-chain identifiers**. Specifically:

- **Token risk endpoint** (`GET /v1/risk/{chain}/{token_address}`) — sends only the chain name and the public token contract address. No wallet address, no portfolio, no transaction details.
- **Contextual endpoint** (`POST /v1/risk/contextual`) — additionally sends the position size and total portfolio size in USD, **only when the user has explicitly opted in to contextual analysis**. No wallet address is ever transmitted.

When pulling position size or portfolio totals from `okx-wallet-portfolio` to feed the contextual endpoint, aggregate to USD locally before sending; do not forward raw balances, per-token holdings, or wallet addresses.

Do not call the contextual endpoint without the user's awareness that position-size context will be shared with the API.

---

## Cost transparency

Bitfence is monetised via the x402 protocol — each scoring request costs a small amount of USDC on Base mainnet (typically a few tenths of a cent). Before you begin using Bitfence in a session:

- **Inform the user** that risk checks are paid and will draw from the wallet's USDC balance on Base mainnet.
- **Ask for the user's consent** the first time you call Bitfence in a session, or when the user has not previously authorised paid risk checks.
- **Do not call Bitfence repeatedly** in tight loops, batch operations, or polling patterns. Use it once per distinct trade decision.
- If the user declines paid checks, fall back to whatever native safety checks (including `okx-security`) the agent and the user have agreed on.

If x402 payment fails, do not retry blindly. Inform the user that the wallet needs USDC on Base mainnet to use Bitfence, and let the user decide whether to top up or skip the check.

---

## Available endpoints

Base URL: `https://api.bitfence.ai`

| Method | Path | Purpose | Paid? |
|---|---|---|---|
| `GET` | `/` | Service metadata — name, version, status. | Free |
| `GET` | `/health` | Health probe. Returns `200 OK` when operational. | Free |
| `GET` | `/v1/risk/{chain}/{token_address}` | Token risk assessment. `chain` is `solana` or `base`. | Yes (x402) |
| `POST` | `/v1/risk/contextual` | Position-aware risk assessment with slippage, MEV exposure, and a suggested position cap. | Yes (x402) |

---

## When Bitfence is useful

Bitfence is most useful before the agent is about to construct an OKX DEX swap involving an **unfamiliar or unverified token**. Typical situations:

- A `dex-okx-dex-quote` call has returned a route for a destination token the user has not traded before
- A user has pasted a contract address from an external source the agent has not vetted
- The agent is composing a multi-leg route where one leg touches an unfamiliar token
- Providing liquidity or staking into a pool involving an unfamiliar token

Bitfence is **not needed** for:

- Transfers of native gas tokens (SOL, ETH) between the user's own wallets (no swap involved)
- Swaps exclusively involving well-established stablecoins (USDC, USDT, DAI) and major assets (WETH, WSOL, cbBTC)
- Tokens the user has already verified earlier in the session

If you are unsure whether a check is warranted, ask the user.

---

## How to call Bitfence

**Token risk only** — use when the position size is not yet known, or immediately after `okx-dex-token` resolution:

```
GET https://api.bitfence.ai/v1/risk/{chain}/{token_address}
```

Supported chains: `solana`, `base` (lowercase). These match OKX DEX aggregator chain identifiers.

Examples:
```
GET https://api.bitfence.ai/v1/risk/solana/EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v
GET https://api.bitfence.ai/v1/risk/base/0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913
```

**Contextual risk** — use when the agent has a concrete position size (typically taken from `dex-okx-dex-quote` output) and the user has opted in to share it:

```
POST https://api.bitfence.ai/v1/risk/contextual
Content-Type: application/json

{
  "chain": "solana",
  "token": "<token_address>",
  "position_size_usd": <amount>,
  "agent_portfolio_usd": <total_portfolio>
}
```

`position_size_usd` should be derived from the quote's expected output amount × reference price. `agent_portfolio_usd` is optional and, if provided, should come from a USD aggregation of `okx-wallet-portfolio` — never forward raw per-token balances or wallet addresses.

The contextual response adds estimated slippage, MEV exposure category, and a suggested position cap. If the suggested cap is lower than the quoted amount, surface this to the user before proceeding to `dex-okx-dex-swap`.

---

## How to interpret the response

The response contains a `recommendation` field. Treat it as **advisory**:

| `recommendation` | Action in the OKX DEX swap pipeline |
|---|---|
| `PROCEED` | Continue to `dex-okx-dex-approve-transaction` (EVM) or directly to `dex-okx-dex-swap` / `dex-okx-dex-solana-swap-instruction`. |
| `REQUIRE_HUMAN_APPROVAL` | Do **not** call `dex-okx-dex-swap` yet. Surface the `reasoning` field to the user and ask whether they want to proceed. Only continue on explicit user confirmation. |
| `BLOCK` | Stop. Do **not** construct a swap transaction. Surface every entry in `circuit_breakers` to the user verbatim and ask for an explicit, informed decision. The user remains free to override after seeing the warnings; if they do, proceed with a clear acknowledgement in the response. |

Treat `confidence < 0.5` as a sign that the underlying data was incomplete; mention this to the user when reporting the result, and consider escalating a `PROCEED` to `REQUIRE_HUMAN_APPROVAL` in this case.

The user is always the final authority. The job of this skill is to present the risk findings accurately and let the user decide.

---

## Circuit breakers

If `circuit_breakers` is non-empty, the API has detected one or more hard safety conditions (for example, a token whose sell function reverts, or unbounded supply controls). Each entry includes a human-readable `description`.

When this happens:

- Present every breaker description to the user verbatim.
- Recommend not proceeding and explain why.
- If the user explicitly chooses to proceed anyway after being informed, respect their decision and acknowledge it clearly in the response before continuing to `dex-okx-dex-swap`.

---

## Error handling

If Bitfence returns an error or is unreachable:

- Inform the user that the risk check could not complete.
- Offer the user the choice to proceed without the check (using `okx-security` alone, if available), retry, or abandon the action.
- Do not silently retry more than once.
- Do not fall back to calling `dex-okx-dex-swap` without explicit user acknowledgement that the Bitfence check did not complete.

---

## End-to-end example — Solana swap with Bitfence gate

User: "Swap 100 USDC for BONK on Solana."

```
1. okx-dex-token({ symbol: "BONK", chain: "solana" })
   → { address: "DezX...bonk", chain: "solana" }

2. dex-okx-dex-quote({
     chainIndex: "501",                            // Solana
     fromTokenAddress: "EPjFWdd5...USDC",
     toTokenAddress:   "DezX...bonk",
     amount: "100000000"                           // 100 USDC (6 decimals)
   })
   → { expectedOutput: "...", priceImpact: "...", route: [...] }

3. Bitfence gate — destination token is unfamiliar:
   GET https://api.bitfence.ai/v1/risk/solana/DezX...bonk
   → {
       "risk_score": 35,
       "risk_level": "MEDIUM",
       "confidence": 0.88,
       "recommendation": "REQUIRE_HUMAN_APPROVAL",
       "reasoning": "Moderate holder concentration; mint authority retained.",
       "circuit_breakers": []
     }

4. Surface reasoning to the user; ask for explicit confirmation.

5. On user approval:
   dex-okx-dex-solana-swap-instruction({ ...same params as step 2 })
   → versioned transaction instructions

6. User's wallet (or okx-agentic-wallet) signs and broadcasts.
```

On `BLOCK`, steps 5 and 6 are skipped and the user is shown the circuit-breaker list. On `PROCEED`, step 4 is skipped and the pipeline continues directly.

## End-to-end example — Base swap with contextual sizing

User: "Swap 0.5 ETH for BRETT on Base, but don't blow up my portfolio."

```
1. okx-dex-token({ symbol: "BRETT", chain: "base" })
   → { address: "0x532F...BRETT", chain: "base" }

2. okx-wallet-portfolio({ chain: "base" })
   → aggregate to total_usd (local aggregation; no raw balances forwarded)

3. dex-okx-dex-quote({
     chainIndex: "8453",                           // Base
     fromTokenAddress: "0xEeee...ETH",
     toTokenAddress:   "0x532F...BRETT",
     amount: "500000000000000000"                  // 0.5 ETH
   })
   → { expectedOutput, priceImpact, ... }

4. POST https://api.bitfence.ai/v1/risk/contextual
   {
     "chain": "base",
     "token": "0x532F...BRETT",
     "position_size_usd": <quote-derived USD>,
     "agent_portfolio_usd": <aggregated USD from step 2>
   }
   → {
       "recommendation": "REQUIRE_HUMAN_APPROVAL",
       "context": {
         "estimated_slippage_pct": 6.4,
         "mev_exposure": "medium",
         "suggested_max_usd": 450,
         "portfolio_concentration_pct": 12.0
       },
       ...
     }

5. Surface: "Estimated slippage 6.4%, suggested max $450 (current request ~$X).
   Do you want to (a) proceed as-is, (b) resize to $450, (c) cancel?"

6. On user choice (b): re-quote via dex-okx-dex-quote with the adjusted amount,
   then dex-okx-dex-approve-transaction → dex-okx-dex-swap.
```

---

## Example response

```json
{
  "chain": "solana",
  "token": "So11111111111111111111111111111111111111112",
  "risk_score": 12,
  "risk_level": "LOW",
  "confidence": 0.94,
  "recommendation": "PROCEED",
  "reasoning": "Established token with deep liquidity and stable holder distribution.",
  "circuit_breakers": [],
  "signals": { },
  "cached": false,
  "cache_age_seconds": 0
}
```

For the contextual endpoint, an additional `context` object is returned with slippage, MEV exposure, and a `suggested_max_usd` position cap.

---

## Response fields reference

```
risk_score          integer 0–100     Composite risk score. 0 = safe, 100 = maximum risk.
risk_level          string            LOW | MEDIUM | HIGH (advisory tier)
confidence          float 0–1         Coverage of live on-chain data. Below 0.5 = limited data.
recommendation      string            Advisory action. See table above.
reasoning           string            Human-readable explanation. Quote to the user when relevant.
circuit_breakers    array             Hard safety conditions. Each entry has a `description` field.
signals             object            Per-category breakdown. Treat as diagnostic data.
cached              boolean           True if the response came from cache.
cache_age_seconds   integer           Age of the cached result in seconds.

context.*           (contextual endpoint only)
  pool_liquidity_usd          Total liquidity in the token's primary pool
  estimated_slippage_pct      Slippage % for the specified position size
  effective_cost_usd          Cost after slippage
  max_safe_position_usd       Largest position keeping slippage low
  portfolio_concentration_pct Position as % of total portfolio
  mev_exposure                Sandwich attack risk: low | medium | high
  suggested_max_usd           Recommended position cap
```

---

## Supported chains

Bitfence chain identifiers map 1:1 onto OKX DEX aggregator chains:

| Chain | Bitfence id | OKX `chainIndex` | Token address format |
|---|---|---|---|
| Solana | `solana` | `501` | Base58 mint address (32–44 chars) |
| Base (EVM) | `base` | `8453` | `0x`-prefixed 42-char hex address |

Before calling Bitfence, confirm the target chain is currently supported via `dex-okx-dex-aggregator-supported-chains`. Additional chains will be added to Bitfence in lockstep with OKX aggregator coverage.

---

## Minimum integration checklist

For an agent using this skill alongside `okx-dex-swap`:

- [ ] Before any `dex-okx-dex-swap` or `dex-okx-dex-solana-swap-instruction` call on a non-whitelisted token, call Bitfence on the `toTokenAddress`.
- [ ] If the user has opted in to portfolio-aware checks, compute `position_size_usd` from the quote and call `/v1/risk/contextual` instead of the basic endpoint.
- [ ] Never override `BLOCK` silently — always surface `circuit_breakers` and obtain explicit user confirmation.
- [ ] Never forward wallet addresses, raw per-token balances, or transaction calldata to Bitfence.
- [ ] On Bitfence error, offer the user a choice; do not fall through to the swap without acknowledgement.

---

## Useful links

- Website: https://bitfence.ai
- Twitter / X: https://x.com/bitfenceai
- API root: https://api.bitfence.ai
- OKX OnchainOS DEX MCP: https://web3.okx.com/onchainos/dev-docs/trade/dex-ai-tools-mcp-server
- OKX Agentic Wallet: https://web3.okx.com/onchainos/dev-docs/home/install-your-agentic-wallet

Bitfence is operated by the Bitfence team as an independent, read-only risk oracle. It does not custody user funds, does not have the ability to move user funds, and does not communicate with the user's wallet beyond receiving x402 micropayments that the user's agent voluntarily initiates. The agent's existing wallet stack (including `okx-agentic-wallet`, `okx-onchain-gateway`, and the OKX DEX MCP tools) remains the sole path for signing and broadcasting.

## Related Skills

- [ai ma trend v2](https://6ducklearn.com/skills/ai-ma-trend-v2/index.md): This strategy is based on moving average trends and multi-period resonance, combining funding rates, volatility, trading volume, and market sentiment to comprehensively assess market setup indicators. It employs dynamic position sizing and a tiered risk control approach, adapting to both trending and ranging markets to achieve robust automated trading.
- [btc grid buy okb](https://6ducklearn.com/skills/btc-grid-buy-okb/index.md): BTC contract grid operates like a perpetual mining machine, continuously generating profits, which are automatically converted into OKB holdings. Risk control with red and yellow lines provides dual protection, with scheduled inspections and intelligent adjustments, all parameters customizable. One-click start for effortless compound earnings.
- [btc usdt swap defensive ai](https://6ducklearn.com/skills/btc-usdt-swap-defensive-ai/index.md): A defensive AI perpetual contract strategy Skill for trading only BTC-USDT-SWAP. It uses multi-timeframe trends, funding rates, open interest, volatility, and account risk control for comprehensive judgment, and automatically executes opening and closing positions and stop-losses through the Agent Trade Kit, suitable for cautious real trading.
- [okx 600u pnl percent v1](https://6ducklearn.com/skills/okx-600u-pnl-percent-v1/index.md): Yield-focused OKX Agent Trade Kit strategy for a 600 USDT account, trading only BTC and ETH USDT perpetuals with single-position risk control, strict stop loss, and skip-first execution logic.
- [dual signal analyzer](https://6ducklearn.com/skills/dual-signal-analyzer/index.md): Analysis Skill of market setup indicators based on RSI and MACD dual indicator cross-validation, providing intelligent buy and sell signals and risk management advice
- [hindsight reviewer](https://6ducklearn.com/skills/hindsight-reviewer/index.md): After each transaction, AI transforms into a strict review judge, using counterfactual reasoning to restore "What would have happened if I had done the right thing at that time?" It doesn't criticize you, but simply tells you with numbers what you missed, how much you benefited, and what the optimal decision was. It activates when users say "review," "why did I lose?", "where did this trade go wrong?", or "hindsight bias."
