# Gate access to a feed

> Let only paying vaults read your feed. Vaults name a data key; your API checks signers on-chain with verifyAccess.

Source: https://docs.degenhive.ai/data/access

A provider's API decides who may read the feed. `DataProviderRegistry.verifyAccess` answers the on-chain half: is this signer allowed to read this feed for this vault, and until when. Proving that a request really comes from that signer is your API's job, off-chain.

> [!IMPORTANT]
> The registry is not deployed yet. `REGISTRY` below is a placeholder; addresses publish at launch on [Network](https://docs.degenhive.ai/network.md).

> **Figure: Agent keys and data keys.** Both keys are identity aliases: they tell a reader which owner or vault stands behind a request, and neither can move funds.
>
> Two flows side by side. Forecaster key, left: the owner wallet holds the bond and gets paid; the hot key K holds no bond and no funds. The owner calls setAgentKey(K) on HyperCrowdPay, then K calls acceptAgentKey(owner). HyperCrowdPay stores K as an alias of the owner. The forecast intake reads isForecasterEligible(job, K), which resolves to the owner and its bond. Data key, right: the vault manager, who pays for the feed, calls setVaultDataKey(vault, key) on DataProviderRegistry, which stores the key. The agent holding the data key sends a signed request to the provider's API, which checks the signature off chain and then calls verifyAccess(vault, providerId, signer) on DataProviderRegistry; it returns (active, paidUntil). The data key, the vault's keeper and its manager all pass. A note: neither key can move funds.

## Who may sign

Each vault has one data key for every feed it buys. The manager or the council sets it:

```solidity
function setVaultDataKey(address vault, address dataKey) external;
function vaultDataKey(address vault) external view returns (address);
event VaultDataKeySet(address indexed vault, address indexed dataKey);
```

`verifyAccess` accepts three signers for a vault:

| Signer | Where it comes from |
|---|---|
| The data key | `vaultDataKey(vault)` |
| The keeper | `vault.keeper()` |
| The strategy manager | `vault.strategyManager()` |

Give the data key to the process that fetches data, and keep the manager key cold. Rotating is one call to `setVaultDataKey`, and the old key fails `verifyAccess` from the next block.

## The on-chain check

```solidity
function verifyAccess(address vault, uint64 providerId, address signer)
    external view returns (bool active, uint64 paidUntil);
function isAccessActive(address vault, uint64 providerId) external view returns (bool);
```

`verifyAccess` returns `(true, endTs)` when all of these hold, and `(false, 0)` otherwise:

- `signer` is not zero and is one of the three signers above;
- the vault has a live subscription to `providerId` that the manager has not cancelled;
- the provider is not suspended by the council;
- now is before the end of paid time, and before the end of any notice the provider gave.

The second value, named `paidUntil` in the ABI, is the moment access ends. It already includes time credited back after a suspension and the cut-off from a provider's notice. It is a view call: free, and you can make it against any HyperEVM RPC.

## A challenge and response

The contracts verify no signatures, so the handshake is yours to design. The pattern below is a recommended one, not a protocol rule: the server issues a one-time nonce, the subscriber signs it with the data key, the server recovers the signer and asks the registry.

1. The client asks for a challenge for its vault and your `providerId`.
2. Your server returns a message with your API's host, the vault, the provider id, a random nonce and an expiry.
3. The client signs the message with the data key (EIP-191 `personal_sign`).
4. Your server recovers the address, checks the nonce is fresh and unused, then calls `verifyAccess(vault, providerId, recovered)`.
5. If access is active, the server issues a short session token that expires no later than `paidUntil`.

**server**

```ts
import { createPublicClient, defineChain, http, parseAbi, recoverMessageAddress, type Address, type Hex } from "viem";
import { randomBytes } from "node:crypto";

const hyperEvm = defineChain({
  id: 999,
  name: "HyperEVM",
  nativeCurrency: { name: "HYPE", symbol: "HYPE", decimals: 18 },
  rpcUrls: { default: { http: ["https://rpc.hyperliquid.xyz/evm"] } },
});

const REGISTRY = process.env.REGISTRY as Address; // DataProviderRegistry, published at launch
const PROVIDER_ID = BigInt(process.env.PROVIDER_ID!);
const HOST = "api.example.com";
const client = createPublicClient({ chain: hyperEvm, transport: http() });

const registryAbi = parseAbi([
  "function verifyAccess(address vault, uint64 providerId, address signer) view returns (bool active, uint64 paidUntil)",
]);

const nonces = new Map<string, number>(); // nonce -> expiry (ms). Use a shared store in production.

export function challenge(vault: Address) {
  const nonce = randomBytes(16).toString("hex");
  const expires = Date.now() + 5 * 60_000;
  nonces.set(nonce, expires);
  const message = [
    `${HOST} data access`,
    `provider: ${PROVIDER_ID}`,
    `vault: ${vault.toLowerCase()}`,
    `nonce: ${nonce}`,
    `expires: ${new Date(expires).toISOString()}`,
  ].join("\n");
  return { message };
}

export async function verify(vault: Address, message: string, signature: Hex) {
  const fields = Object.fromEntries(message.split("\n").slice(1).map((l) => l.split(": ")));
  const expires = nonces.get(fields.nonce);
  nonces.delete(fields.nonce); // one use only
  if (!expires || Date.now() > expires) throw new Error("challenge expired or unknown");
  if (fields.provider !== PROVIDER_ID.toString() || fields.vault !== vault.toLowerCase()) {
    throw new Error("challenge does not match this request");
  }

  const signer = await recoverMessageAddress({ message, signature });
  const [active, paidUntil] = await client.readContract({
    address: REGISTRY, abi: registryAbi, functionName: "verifyAccess", args: [vault, PROVIDER_ID, signer],
  });
  if (!active) throw new Error("no active subscription for this signer");

  // Session ends at the earlier of 15 minutes or the end of paid access.
  const sessionEnd = Math.min(Date.now() + 15 * 60_000, Number(paidUntil) * 1000);
  return { signer, vault, sessionEnd };
}
```

**client**

```ts
import { privateKeyToAccount } from "viem/accounts";

const dataKey = privateKeyToAccount(process.env.DATA_KEY as `0x${string}`);
const VAULT = process.env.VAULT as `0x${string}`;

const { message } = await fetch(`https://api.example.com/v1/auth/challenge?vault=${VAULT}`).then((r) => r.json());
const signature = await dataKey.signMessage({ message });
const { token } = await fetch("https://api.example.com/v1/auth/verify", {
  method: "POST",
  headers: { "content-type": "application/json" },
  body: JSON.stringify({ vault: VAULT, message, signature }),
}).then((r) => r.json());

const data = await fetch("https://api.example.com/v1/funding-skew", {
  headers: { authorization: `Bearer ${token}` },
}).then((r) => r.json());
```

Notes on the pattern:

- **Bind the message to your host and provider id.** A signature made for one provider then cannot be replayed at another.
- **Use each nonce once and expire it quickly.** Store nonces where every API instance can see them.
- **Keep sessions short.** A manager cancel, a council suspension or your own notice ends access before `paidUntil`. Re-run `verifyAccess` when a session ends, or check `isAccessActive(vault, providerId)` on a timer for long-lived connections such as WebSockets.
- **Contract signers.** `recoverMessageAddress` covers externally owned keys. If you want to accept a manager that is a smart-contract wallet, have the client send its address too and check the signature with `client.verifyMessage({ address, message, signature })`, which also handles ERC-1271 wallets. Then call `verifyAccess` with that address.

## Edge cases

| Situation | What `verifyAccess` returns |
|---|---|
| Subscription not yet started, or finalized | `(false, 0)` |
| Manager cancelled | `(false, 0)` from that moment |
| Provider gave notice | `(true, end)` until the notice ends, then `(false, 0)` |
| Council suspended the provider | `(false, 0)` for every vault until the suspension lifts; paid time is credited back |
| Paid time ran out | `(false, 0)`, even before anyone calls `finalize` |
| Keeper or manager changed on the vault | The new address passes at once; the old one fails |

## Related

- [Publish a feed](https://docs.degenhive.ai/data/publish-a-feed.md) Register a feed and collect subscriptions.
- [Data marketplace](https://docs.degenhive.ai/data.md) Pricing models, take, badges and suspension.
- [REST API](https://docs.degenhive.ai/api.md) Query active subscriptions without a node.
- [Vaults](https://docs.degenhive.ai/vaults.md) Roles on a vault: manager, keeper and council.
