KeyBay KeyBay Capital Bitcoin L1 Yield Launch App
Products KBY Token Docs Security Blog Team Launch App
Agent Infrastructure · HTTP 402 · March 2026

Why We Built Agent Infrastructure for Bitcoin DeFi

DeFi protocols are built for humans with wallets. The next wave of capital allocation will be driven by autonomous agents that need programmatic, pay-per-call access to financial data and execution. Here is how we are building for that future on Bitcoin L1.

The Problem

Every DeFi protocol today assumes the same user: a human being sitting in front of a browser, clicking buttons inside a wallet-connected interface. The deposit flow expects a person to review parameters, approve a transaction, and wait for confirmation. The dashboard expects eyes on a screen. The documentation expects a developer who will manually integrate an SDK and ship a frontend for other humans to use.

This model worked when DeFi was a niche experiment used by a few thousand people. It does not scale to a world where software agents are the primary consumers of financial infrastructure. Autonomous agents do not click buttons. They do not connect wallets through browser extensions. They do not read dashboards. They issue HTTP requests, parse structured responses, and make decisions based on data.

The gap is not theoretical. Today, if an autonomous yield aggregation agent wants to check the current exchange rate of kbBTC to BTC on the KeyBay vault, it has no clean way to do so. It could try to scrape the frontend. It could attempt to call the OP_NET contract directly, which requires running an OP_NET node or depending on a third-party indexer. It could try to reverse-engineer the webapp's API calls. None of these are stable interfaces. None of them were designed for machine consumption. And none of them have a built-in mechanism for the agent to pay for the data it consumes.

The missing piece is not the data itself. KeyBay already has oracle prices, vault state, credit positions, and transaction history. The missing piece is the access layer: a stable, authenticated, metered API that agents can discover, negotiate payment for, and consume without human intervention. That access layer is what HTTP 402 was designed to provide.

HTTP 402: The Internet's Forgotten Status Code

HTTP 402 Payment Required has been part of the HTTP specification since 1997. The original RFC reserved it for future use, noting that it was intended to enable digital cash or micropayment schemes. For nearly three decades, it sat unused. Browsers never implemented special handling for it. Servers never returned it. The web moved on to advertising-funded models, and the idea of paying for individual HTTP requests seemed quaint.

That changed when machine-to-machine communication became a real economic activity. When one piece of software needs data from another piece of software, the advertising model breaks down completely. There are no eyeballs to monetize. There is no attention to capture. There is only a request and a response, and someone needs to pay for the compute, storage, and bandwidth required to produce that response.

Three protocols have emerged to fill this gap, each approaching the problem from a different angle.

L402, originally called LSAT, was pioneered by Lightning Labs. It combines HTTP 402 responses with Lightning Network macaroons. When a server returns a 402, it includes a macaroon and a Lightning invoice. The client pays the invoice, receives a preimage, and uses the preimage plus the macaroon as a bearer credential for subsequent requests. L402 is elegant and battle-tested, but it requires both parties to have Lightning infrastructure.

x402 is Coinbase's approach, designed for broader compatibility. It uses the same 402 response pattern but supports payment verification across multiple networks including Ethereum, Base, and Solana. The x402 header includes a payment requirement that the client fulfills through any supported payment rail, and the server verifies receipt before serving the response. Coinbase Commerce handles the verification layer.

s402 is the protocol we built at KeyBay. It is designed specifically for Bitcoin-native DeFi infrastructure where the payment and the data share the same settlement layer. Today the implementation centers on s402 payment proofs, with broader multi-rail verification still on the roadmap. The important point is that the API surface is already machine-readable and metered, so agents can integrate against a stable contract while the surrounding payment options continue to expand.

The key insight across all three protocols is the same: HTTP 402 turns API access into a market. Every endpoint has a price. Every request is a transaction. Agents can discover what data is available, how much it costs, and pay for exactly what they need without accounts, API keys, or subscription contracts. The protocol negotiation happens in HTTP headers, which means any HTTP client can participate.

Protocol-Agnostic by Design

When we started building the agent infrastructure layer for KeyBay, we faced a choice: pick one payment protocol and optimize for it, or design the system so it can grow into a broader payment router over time. We chose the second path.

The reasoning is straightforward. Different agents operate in different environments. Some are already built around Bitcoin-native settlement, while others will eventually want x402, L402, or OP_NET-native payment options. Designing toward that broader future now keeps the API surface stable even while the first production rollout stays narrower.

The KeyBay payment router works as follows. When an agent makes an unauthenticated request to a metered endpoint, the server returns HTTP 402 with a structured header that describes the available payment methods and their costs. The header format is:

HTTP/1.1 402 Payment Required
Content-Type: application/json
X-Payment-Methods: s402
X-Payment-Amount: 100
X-Payment-Currency: sat
X-Payment-Address: bc1q...
X-Payment-Invoice: lnbc...
X-Payment-Token: <request-bound-token>

The agent makes the required payment, includes the proof in a follow-up request, and the server verifies that proof before returning the data. The entire negotiation happens in two HTTP round trips: one to discover the price, one to pay and receive.

Each verification method has its own latency and trust profile, which is why the current rollout is narrower than the long-term design. The goal is to add more rails without forcing agents to reintegrate every time the payment layer expands.

This architecture means KeyBay does not need to bet on which payment protocol wins. If a new protocol emerges next year, we add a verification backend and update the payment methods header. Existing agents continue to work unchanged. New agents can use whichever method their infrastructure supports.

What You Can Build

The agent API exposes every piece of data and computation that KeyBay produces. Here are the use cases we are already seeing in early integrations.

Yield Aggregation Bots

A yield aggregation agent monitors rates across multiple DeFi protocols and allocates capital to the highest risk-adjusted return. To include KeyBay in its universe, the agent needs the current vault exchange rate, the trailing 30-day yield, the collateral ratio, and the available deposit capacity. All four data points are available through the agent API. The agent calls the oracle endpoint to get the current kbBTC/BTC rate, the vault state endpoint for TVL and collateral ratio, and the yield history endpoint for trailing performance. Each call costs a few satoshis. The agent can poll every epoch, every hour, or every block depending on its strategy.

Credit Monitoring Agents

An agent managing a portfolio of BTC-collateralized credit positions needs to monitor loan-to-value ratios in real time. If BTC price drops and LTV approaches the liquidation threshold, the agent needs to act: deposit more collateral, repay part of the debt, or close the position entirely. The credit state endpoint returns the current LTV, collateral value, accrued interest, liquidation price, and available borrow capacity for any vault address. An agent can monitor multiple positions across multiple protocols and trigger defensive actions when thresholds are breached.

Arbitrage Detection

The KeyBay vault exchange rate reflects the net asset value of the underlying strategy. If the kbBTC/BTC rate on Motoswap diverges from the vault's reported rate, an arbitrage opportunity exists. An agent can monitor both prices through their respective APIs, detect the spread, and execute a trade to capture it. The agent API provides the vault-side price. The Motoswap contract provides the market-side price. The agent does the math and acts.

Portfolio Rebalancing

Institutional allocators running multi-strategy portfolios need to rebalance periodically. An agent managing a portfolio that includes a KeyBay vault position needs to know the current value of that position, the unrealized yield, and the withdrawal timeline. The vault state and position endpoints provide all of this. The agent can compute the portfolio weights, determine whether rebalancing is needed, and generate the appropriate transaction if it is.

These are not hypothetical use cases. They are the natural consequence of making financial data available through a stable, metered, machine-readable interface. Once the data is accessible, agents will find ways to use it that we have not anticipated.

The SDK

The TypeScript SDK, published as @keybay/sdk, is the reference implementation for consuming the KeyBay agent API. It is designed for environments where correctness matters more than convenience, which is the right tradeoff when the code is managing real capital.

BigInt-Only Amounts

Every amount in the SDK is represented as a bigint. There are no floating-point numbers anywhere in the financial computation path. This is a deliberate and non-negotiable design decision. JavaScript's number type uses IEEE 754 double-precision floating point, which cannot represent many decimal values exactly. The classic example is that 0.1 + 0.2 !== 0.3 in JavaScript. When you are computing exchange rates, collateral ratios, and liquidation thresholds with real Bitcoin at stake, floating-point arithmetic is not acceptable.

All satoshi amounts are bigint. All token amounts are bigint. All intermediate computation results are bigint. The SDK provides formatting utilities that convert to human-readable strings for display, but the underlying values never touch a floating-point register. If you pass a number where a bigint is expected, TypeScript will catch it at compile time.

Result Pattern

Every SDK function that can fail returns a Result<T> type rather than throwing exceptions. The Result type is a discriminated union: either { ok: true, value: T } or { ok: false, error: SDKError }. This forces the caller to handle errors explicitly at every call site.

The motivation is the same as the bigint decision: when code manages real capital, implicit error handling is dangerous. A thrown exception that is not caught can crash an agent process mid-operation. An unhandled promise rejection can leave a position in an inconsistent state. The Result pattern makes error handling visible and mandatory. You cannot access the value without first checking ok.

Pure Computation Functions

The SDK separates data fetching from computation. Functions like computeLtv, computeLiquidationPrice, and computeExchangeRate are pure functions: they take inputs and return outputs with no side effects, no network calls, and no state mutation. This makes them trivially testable and safe to call in any context.

The data fetching layer handles HTTP 402 negotiation, payment, and response parsing. It returns typed data structures that can be passed directly to the computation functions. This separation means you can use the computation functions without the HTTP layer if you have your own data source, and you can use the HTTP layer without the computation functions if you just need raw data.

import { createClient, computeLtv } from '@keybay/sdk';

const client = createClient({
  endpoint: 'https://api.keybaycapital.com',
  paymentMethod: 'spark',
  sparkWallet: walletInstance,
});

const vaultState = await client.getVaultState();
if (!vaultState.ok) {
  console.error(vaultState.error.code, vaultState.error.message);
  process.exit(1);
}

const ltv = computeLtv({
  collateralSats: vaultState.value.collateralSats,
  debtAmountUsd: vaultState.value.debtAmountUsd,
  btcPriceUsd: vaultState.value.oraclePrice,
});

console.log('Current LTV:', ltv.toString());

The client constructor takes a payment method configuration. When the client encounters a 402 response, it automatically handles the payment negotiation using the configured method. The caller does not need to manage payment flows manually unless it wants to. All amounts in the response are bigint values. All computations use integer arithmetic. The types are exported so downstream code gets full IDE support and compile-time safety.

What's Next

The agent API and SDK ship today in preview. Here is what is coming next.

Full Spark Integration

Spark is a Bitcoin-native payment layer that enables instant, low-cost transfers without requiring a full Lightning node. Our current implementation supports Spark as a payment method, but the integration is not yet complete. Full Spark integration means agents can fund a Spark wallet with a single on-chain transaction and then make thousands of API calls without touching the chain again. The latency per call drops to the time it takes to verify a Spark payment, which is under 200 milliseconds. For high-frequency monitoring agents, this is the difference between viable and not.

x402 via Coinbase Commerce (Planned)

Coinbase's x402 protocol is a planned expansion path for agents that already operate on Ethereum, Base, and other EVM chains. When implemented, it would let an agent pay for KeyBay API calls without holding Bitcoin directly. That is particularly relevant for cross-chain aggregation agents monitoring opportunities across multiple ecosystems.

OP_NET Native Payments (Planned)

When implemented, OP_NET-native payments would let an agent already holding kbBTC or other OP_20 tokens pay for API access directly through an OP_NET contract call. That would keep both the capital and the payment rail on the same Bitcoin-native settlement stack.

More Endpoints

The initial API covers vault state, oracle prices, credit positions, and yield history. The roadmap includes transaction simulation endpoints (preview a deposit or withdrawal before executing), strategy breakdown endpoints (per-sleeve allocation and performance data), risk metric feeds (delta exposure, counterparty concentration, and drawdown statistics), and historical data exports for backtesting. Each endpoint will follow the same pattern: HTTP 402 negotiation, structured JSON response, typed SDK bindings.

We are also exploring webhook-style push notifications where agents register a callback URL and pay a subscription fee to receive real-time updates when vault state changes, when LTV thresholds are crossed, or when new epochs settle. This inverts the polling model: instead of the agent checking every block, the server pushes updates when they matter.

The Bigger Picture

The hypothesis behind all of this is that Bitcoin DeFi will not be used primarily by humans clicking buttons in browsers. It will be used by agents acting on behalf of humans, other agents, and protocols. The total addressable market for financial data is not the number of people who visit a dashboard. It is the number of software processes that need to make decisions using that data.

HTTP 402 turns financial infrastructure into an API marketplace. Every vault, every oracle, every credit facility becomes a metered service that any agent can discover, evaluate, and consume. The payment happens at the protocol level, not the business relationship level. There are no sales calls, no API key applications, no enterprise contracts. There is a price, a payment, and a response.

We built KeyBay to generate yield on Bitcoin. We are building the agent layer so that the rest of the internet's software can participate in that yield without needing a human in the loop. If you are building agents that interact with DeFi protocols, the SDK is available now. The API is in preview. The documentation covers every endpoint, every type, and every payment method. Start building.