> ## Documentation Index
> Fetch the complete documentation index at: https://docs.b1nary.app/llms.txt
> Use this file to discover all available pages before exploring further.

# Integration Guide

> Direct trade and bridge-and-trade flows across Base and Solana.

## Choosing an execution path

Every quote has a target `chain`.

* Use **direct Base trade** when the quote is on Base and the Base smart trading account has enough collateral.
* Use **direct Solana trade** when the quote is on Solana and the Solana embedded trading account has enough collateral.
* Use **bridge-and-trade** when USDC exists across the user's b1nary account but is on the wrong chain for the selected cash-secured put.

Covered calls require asset collateral on the target chain. Bridge-and-trade is for USDC collateral only.

## Direct Base example

This is a complete working example of selling a cash-secured put on b1nary using Python.

```python theme={null}
import requests
from web3 import Web3

# -- Pick your environment --
# Production (Base mainnet, real money):
# API = "https://api.b1nary.app"
# RPC = "https://mainnet.base.org"
# BATCH_SETTLER = "0xd281ADdB8b5574360Fd6BFC245B811ad5C582a3B"
# MARGIN_POOL = "0xa1e04873F6d112d84824C88c9D6937bE38811657"
# USDC = "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"

# Testnet (Base Sepolia, no real money):
API = "https://optionsprotocolbackend-staging.up.railway.app"
RPC = "https://sepolia.base.org"
BATCH_SETTLER = "0x766bD3aF1D102f7EbcB65a7B7bC12478C2DbA918"
MARGIN_POOL = "0x727ddBD04A691E73feaE26349F48144953Ef20d6"
USDC = "0xAB51a471493832C1D70cef8ff937A850cf37c860"  # LUSD on testnet

w3 = Web3(Web3.HTTPProvider(RPC))

# 1. Get test tokens (testnet only, one-time)
requests.post(f"{API}/faucet", json={"address": MY_ADDRESS})

# 2. Approve USDC to MarginPool (one-time)
usdc = w3.eth.contract(address=USDC, abi=ERC20_ABI)
usdc.functions.approve(
    MARGIN_POOL, 2**256 - 1
).transact({"from": MY_ADDRESS})

# 3. Read prices
prices = requests.get(f"{API}/prices?asset=eth").json()

# 4. Pick a PUT with an otoken_address
put = next(
    p for p in prices
    if p["option_type"] == "put" and p["otoken_address"]
)

# 5. Calculate collateral for $2,400 commitment
usd_amount = 2400
eth_units = usd_amount / put["strike"]
otoken_amount = int(eth_units * 1e8)
strike_8dec = int(put["strike"] * 1e8)
collateral = (otoken_amount * strike_8dec) // 10**10

# 6. Build quote struct from API response
quote = (
    put["otoken_address"],      # oToken
    int(put["bid_price_raw"]),   # bidPrice
    int(put["deadline"]),        # deadline
    int(put["quote_id"]),        # quoteId
    int(put["max_amount_raw"]),  # maxAmount
    int(put["maker_nonce"]),     # makerNonce
)

# 7. Execute order
settler = w3.eth.contract(
    address=BATCH_SETTLER, abi=SETTLER_ABI
)
tx = settler.functions.executeOrder(
    quote,
    bytes.fromhex(put["signature"][2:]),
    otoken_amount,
    collateral,
).transact({"from": MY_ADDRESS})

# 8. Check position
positions = requests.get(
    f"{API}/positions/{MY_ADDRESS}"
).json()
```

## Direct Base step-by-step

### 1. Get test tokens

Testnet only, one-time. The faucet sends 0.005 ETH (gas), 50 LETH, and 100,000 LUSD.

### 2. Approve collateral

One-time per token. For puts, approve USDC (or LUSD on testnet) to the MarginPool. For calls, approve WETH or cbBTC.

### 3. Read prices

`GET /prices` returns all available options with signed quotes. Each entry has the strike, expiry, premium, delta, and the complete EIP-712 data needed for on-chain execution.

Filter by `option_type` (PUT or CALL) and ensure `otoken_address` and `signature` are present.

### 4. Calculate collateral

For puts: `(amount * strike_8dec) / 1e10` gives USDC amount in 6 decimals.

For ETH calls: `amount * 1e10` gives WETH amount in 18 decimals.

For BTC calls: `amount` directly (cbBTC has 8 decimals, same as oToken).

### 5. Execute on-chain

Call `executeOrder(quote, signature, amount, collateral)` on BatchSettler. Premium arrives in your wallet in the same transaction.

### 6. Monitor

`GET /positions/{address}` shows all open and settled positions with the `outcome` field.

## Direct Solana trade

For Solana quotes (`chain = "solana"`), build a Solana `ExecuteOrder` transaction using the quote fields from `GET /prices`.

Important rules:

* The user's Solana embedded trading wallet is the trading authority.
* Backend/operator sponsorship should pay transaction fees and setup costs where supported.
* USDC and wSOL use the SPL Token Program.
* TSLAx uses Token-2022: `TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb`.
* SOL covered calls must wrap SOL to wSOL before execution if wSOL collateral is insufficient.
* Use the actual token balance on Solana. Do not assume a bridge `burn_amount` equals final available collateral.

Pseudo-flow:

```ts theme={null}
const prices = await fetch(`${API}/prices?asset=sol`).then((r) => r.json());
const quote = prices.find((q) => q.chain === "solana" && q.option_type === "put");

// 1. Ensure the user's b1nary account has a verified Solana trading wallet.
// 2. Ensure USDC/wSOL/TSLAx token accounts exist and collateral is sufficient.
// 3. Build ExecuteOrder transaction from quote fields.
// 4. User signs where authority is required.
// 5. Backend/operator sponsors fee payer and setup where supported.
// 6. Submit and monitor with GET /positions/{solanaTradingWallet}
//    or GET /b1nary-account/positions?privy_user_id=...
```

## Bridge-and-trade

Bridge-and-trade consolidates USDC with Circle CCTP V2, then executes on the destination chain.

### Base -> Solana

Use this when the user wants a Solana cash-secured put but USDC is on Base.

<Steps>
  <Step title="Resolve the Solana USDC token account">
    Derive the user's Solana USDC ATA. This ATA is the CCTP `mint_recipient`. Do not use the Solana wallet owner as `mint_recipient`.
  </Step>

  <Step title="Reserve the bridge job">
    Call `POST /api/bridge-and-trade/reserve` before burning on Base. Backend validates or creates the Solana USDC ATA with the operator hot wallet as payer.
  </Step>

  <Step title="Burn USDC on Base">
    Send the Base smart-wallet batch: USDC `approve(TokenMessengerV2)` and CCTP V2 `depositForBurn`.
  </Step>

  <Step title="Finalize the bridge job">
    Call `POST /api/bridge-and-trade` with the real `burn_tx_hash`, `source_chain="base"`, `dest_chain="solana"`, `quote_id`, `mint_recipient`, and `burn_amount`.
  </Step>

  <Step title="Wait and execute">
    Poll `GET /api/bridge-status/{job_id}` until `mint_completed`, then execute the Solana trade using the actual USDC amount received after fees/rounding.
  </Step>
</Steps>

### Solana -> Base

Use this when the user wants a Base cash-secured put but USDC is on Solana.

<Steps>
  <Step title="Prepare sponsored burn">
    Call `POST /api/bridge/solana-cctp-burn/prepare`. Backend creates a Solana CCTP burn transaction with the operator as fee payer.
  </Step>

  <Step title="Sign as owner">
    The user's Solana trading wallet signs the prepared transaction as USDC owner. The user does not pay Solana gas.
  </Step>

  <Step title="Submit burn">
    Call `POST /api/bridge/solana-cctp-burn/submit` with the signed transaction, `dest_chain="base"`, `mint_recipient` as the Base smart trading account, and the selected `quote_id`.
  </Step>

  <Step title="Wait and execute">
    Poll `GET /api/bridge-status/{job_id}` until USDC is minted on Base, then execute the Base trade through the Base smart trading account.
  </Step>
</Steps>

Bridge-only withdrawals use the same consolidation principle: bridge first, then withdraw from the destination trading account. For bridge-only jobs, use `quote_id=null` and `signed_trade_tx=null` where the endpoint supports it.

## The Wheel (automated loop)

The optimal automated strategy is a continuous cycle:

1. Start with USDC. Sell a cash-secured put at a strike you'd buy at.
2. If OTM: collateral returned. Collect premium, sell another put.
3. If ITM: you receive the asset. Sell a covered call.
4. If call OTM: keep asset and premium. Sell another call.
5. If call ITM: asset sold at strike. Back to USDC. Repeat from step 1.

Use `GET /positions/{address}` or `GET /b1nary-account/positions?privy_user_id=...` to check settlement outcomes and decide the next move.

## Dependencies

```bash theme={null}
pip install web3 requests
```
