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

# Hyperliquid HyperCore (hypercore)

## Trade and deploy on HyperCore with "hypercore"

`ctx.hypercore` lets a task read from and act on **HyperCore**, the native Hyperliquid exchange:
place and cancel orders, move funds, stake, manage subaccounts and vaults, operate HIP-3 perp
markets, and deploy and settle HIP-4 outcome markets.

HyperCore is not an EVM chain. Actions are signed payloads posted to Hyperliquid's exchange
endpoint, not transactions. HyperEVM, the EVM chain that runs alongside it, is served by
[`ctx.evm`](/compose/context/evm/overview) like any other chain — use `ctx.hypercore` for the
exchange itself and `ctx.evm` for contracts on HyperEVM.

Wallets come from [`ctx.evm.wallet`](/compose/context/evm/wallets): Hyperliquid accounts are
ordinary Ethereum keypairs, so the same wallet object signs both.

```typescript theme={null}
const wallet = await ctx.evm.wallet({ name: "trading-wallet" });

const mids = await ctx.hypercore.info.allMids("mainnet");

await ctx.hypercore.trade.order("mainnet", wallet, {
  orders: [{
    a: 0,                                  // asset index (BTC)
    b: true,                               // isBuy
    p: mids.BTC,                           // price
    s: "0.001",                            // size
    r: false,                              // reduceOnly
    t: { limit: { tif: "Ioc" } },
  }],
  grouping: "na",
});
```

### Every call names its network

The first argument of every method is `"mainnet"` or `"testnet"`. There is no default and no
app-level setting, for the same reason [`ctx.evm`](/compose/context/evm/chains) makes you pass a
chain: a forgotten argument must be a type error, never a silent mainnet action.

### Field order is handled for you

A HyperCore action is hashed with its fields in a canonical order. Get that order wrong and the
signature recovers a different address, so the exchange rejects the action with a confusing
`User or API Wallet 0x... does not exist` error.

Compose canonicalizes every known action against Hyperliquid's own schemas before signing, so this
class of failure cannot reach the wire — including actions you build by hand and pass to
`exchange`. An action type Compose does not recognize (a brand new one, for example) is sent
through unchanged with a warning in your logs, and then field order is yours to get right.

### Namespaces

```typescript theme={null}
hypercore: {
  info(network, query, retryConfig?): Promise<T>;
  exchange(network, wallet, action, options?): Promise<HypercoreExchangeResponse>;

  info.allMids / l2Book / outcomeMeta / outcomeTemplates / clearinghouseState
     / spotClearinghouseState / delegatorSummary / userFills

  trade:      order, cancel, cancelByCloid, modify, batchModify, twapOrder, twapCancel,
              scheduleCancel, updateLeverage, updateIsolatedMargin, topUpIsolatedOnlyMargin
  transfer:   usdSend, spotSend, withdraw, usdClassTransfer, sendAsset, vaultTransfer,
              subAccountTransfer, subAccountSpotTransfer
  stake:      deposit, withdraw, delegate
  agent:      approve, approveBuilderFee
  outcome:    activateDeployer, deactivateDeployer, deploy, deployQuestion, settle,
              settleQuestion, tokenOperation
  perpDeploy: registerAsset, setOracle, haltTrading, setFundingMultipliers,
              setFundingInterestRates, setOpenInterestCaps, setSubDeployers, setFeeRecipient,
              setMarginTableIds, setMarginModes, setDeployerFees, setPerpAnnotation, disableDex
  account:    createSubAccount, subAccountModify, createVault, vaultModify, vaultDistribute,
              setDisplayName, setReferrer, registerReferrer, claimRewards, spotUser,
              evmUserModify, reserveRequestWeight, borrowLend, setAbstraction, setPortfolioMargin
}
```

Every action method has the same shape:

```typescript theme={null}
ns.method(network, wallet, params, options?): Promise<HypercoreExchangeResponse>
```

`params` matches Hyperliquid's action fields for that action. Method names follow Hyperliquid's
own names, except where those names are opaque: `stake.deposit` is `cDeposit`, `stake.withdraw`
is `cWithdraw`, `stake.delegate` is `tokenDelegate`, and `transfer.withdraw` is `withdraw3`. Each
method's doc comment records the raw action name so you can cross-reference the Hyperliquid docs.

### Options

```typescript theme={null}
type HypercoreCallOptions = {
  envelope?: {
    vaultAddress?: Address;  // act on behalf of a subaccount or vault
    expiresAfter?: number;   // reject the action after this ms timestamp
  };
  retryConfig?: RetryConfig;
};
```

`vaultAddress` is only valid for order-book style actions. Fund actions
(`transfer`, `stake`, `agent`) use Hyperliquid's user-signed scheme, which has no vault field, and
passing one throws.

### Reads

`info` is a plain read against Hyperliquid's info endpoint. The common queries have typed helpers,
and the generic form covers everything else:

```typescript theme={null}
const mids = await ctx.hypercore.info.allMids("mainnet");
const state = await ctx.hypercore.info.clearinghouseState("mainnet", wallet.address);

// anything without a helper
const fills = await ctx.hypercore.info("mainnet", {
  type: "userFillsByTime",
  user: wallet.address,
  startTime: since,
});
```

Reads are retried automatically. Actions are not: they are mutations, so they run once per task
attempt (see below).

### How actions are signed

Hyperliquid has two signing schemes and Compose picks the right one per action:

* **L1 actions** (orders, cancels, deployer actions) are msgpack-hashed and signed inside an
  EIP-712 envelope.
* **User-signed actions** (transfers, staking, agent approval) are signed as per-action EIP-712
  typed data.

Both work with either wallet type. A managed wallet signs on the Compose host. A wallet created
from a private key signs inside your task process, so the key never leaves it — Compose builds the
payload, your task signs it, and Compose submits the signed result.

### Retries and duplicate actions

Exchange actions are mutations: by default they are attempted once, and a task retry replays the
recorded result rather than sending a second action.

HyperCore nonces are single-use, which Compose leans on for the ambiguous case where an action was
submitted but the result never came back. A replay re-submits the identical signed action, the
exchange rejects the reused nonce, and Compose reports that as success:

```json theme={null}
{ "status": "ok", "response": { "type": "duplicateNonce" } }
```

The action landed the first time. Read current state with `info` if you need the original response.

<Note>
  Nonces are timestamps and must fall within roughly two days of now. A run resumed after that
  window fails with a stale-nonce error rather than silently re-executing an action that may
  already have landed.
</Note>

### Rate limits

Hyperliquid limits actions per address, roughly one action per 1 USDC of cumulative traded volume,
after an initial allowance. Reads are limited per IP. An app that submits actions far faster than
it trades will eventually be throttled by the exchange; see Hyperliquid's
[rate limit documentation](https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/rate-limits-and-user-limits).

### HIP-3: builder-deployed perp markets

`perpDeploy` operates a perp DEX you have deployed. The deployer supplies the oracle, and
Hyperliquid expects a price roughly every three seconds:

```typescript theme={null}
await ctx.hypercore.perpDeploy.setOracle("mainnet", wallet, {
  dex: "mydex",
  oraclePxs: [["GOLD", "2650.5"]],        // sorted by key
  markPxs: [],
  externalPerpPxs: [["GOLD", "2650.4"]],  // sorted by key
});
```

<Warning>
  A Compose task is a scheduled run, not a long-lived process. `setOracle` works for a periodic
  push, but the fastest cron is once a minute, so Compose alone does not meet the three second
  cadence HIP-3 expects of a production oracle. Treat this as a way to operate deployer actions,
  not as a complete price-feed service.
</Warning>

All list-of-tuple parameters must be sorted by key before signing. Compose sorts the ones it
builds for you; when you pass tuples directly, sort them.

### HIP-4: outcome markets

`outcome` deploys and settles HIP-4 outcome markets. Markets are instantiated from templates that
validators have approved, so you fill in a template's keywords rather than defining an arbitrary
market:

```typescript theme={null}
// what templates exist right now
const templates = await ctx.hypercore.info.outcomeTemplates("testnet");

await ctx.hypercore.outcome.deploy("testnet", wallet, {
  templateId: "binaryPrice2",
  keywordToValue: { perp: "BTC", threshold: "65000", time: "20260815-1800" },
});
```

Settlement must echo the market's canonical metadata exactly as `outcomeMeta` reports it, so store
it when you deploy:

```typescript theme={null}
const meta = await ctx.hypercore.info.outcomeMeta("testnet");
const market = meta.outcomes.find((o) => o.outcome === outcomeIndex);

await ctx.hypercore.outcome.settle("testnet", wallet, {
  outcome: market.outcome,
  settleFraction: priceAtExpiry > threshold ? "1" : "0",
  nameAndDescription: [market.name, market.description],
  sideNames: [market.sideSpecs[0].name, market.sideSpecs[1].name],
});
```

<Note>
  Outcome token side index `0` is the **Yes** side: it maps to `sideSpecs[0]`. Deploying and
  settling outcomes requires an activated outcome deployer, which has a staking requirement, and
  testnet caps how many outcomes a deployer can have open and deploy per day.
</Note>

### Raw actions

Anything without a helper goes through `exchange`, which signs, canonicalizes, and submits any
action:

```typescript theme={null}
await ctx.hypercore.exchange("mainnet", wallet, {
  type: "scheduleCancel",
  time: Date.now() + 60_000,
});
```

### Example

A complete app that runs a vault on HyperCore — deposits attributed from on-chain transfers, share
accounting in [collections](/compose/context/collections), a strategy leg trading a perp, and
conditional payouts — is in
[documentation-examples](https://github.com/goldsky-io/documentation-examples/tree/main/compose/hypercore-vault).
A second example,
[hip4-outcome-oracle](https://github.com/goldsky-io/documentation-examples/tree/main/compose/hip4-outcome-oracle),
deploys and settles recurring HIP-4 markets.


## Related topics

- [Hypercore Sources](/turbo-pipelines/sources/hypercore.md)
- [Turbo - Supported sources](/turbo-pipelines/sources/overview.md)
- [HyperEVM](/chains/hyperevm.md)
- [ThunderCore](/chains/thundercore.md)
- [HyperEVM System Tx](/edge-rpc/capabilities/hyperevm-system-transactions.md)
