Skip to Content
Scalar

Build on Scalar

Sign an order with EIP-712 and submit it over REST or WebSocket.

This guide takes you from nothing to a signed order on the testnet book. It uses TypeScript and viem, but any language that can sign EIP-712 typed data works. You need a wallet with a balance in the Scalar contract. See Your first trade to fund one.

Endpoints

ServiceTestnet URLUse it for
Trading RESThttps://testnet-api.scalar.marketOrders, cancels, withdrawals, account and depth
Trading WebSocketwss://testnet-api.scalar.market/wsOrder entry and your private order and fill events
Market data WebSocketwss://testnet-api.scalar.market/market-data/wsOrder book depth and trades for every market
Data RESThttps://data.scalar.marketProducts, cycles, history, candles and account data

Every endpoint is documented in the API reference. The WebSocket frames are in WebSocket protocols.

Units

ValueUnit on the APIUnit in the signed order and onchain
PriceDollars, for example 5.25. 0 < price ≤ 10, on a $0.01 grid.Micro-dollars: dollars × 1,000,000
SizeWhole contractsWhole contracts
Balances and marginMicro-dollars, as a base-10 stringUSDC base units (6 decimals)
TimesSeconds since the Unix epochSeconds

1. Find a market

A market is an instrument: one product, one cycle and one set of levels. Read the live cycle of every product from the Data API:

const res = await fetch("https://data.scalar.market/products/current");
const { items } = await res.json();

const spread = items.find((item) => item.product.name === "Spread-BTC-Hourly");
// spread.product.product_ptr  the product's address
// spread.cycle                the live cycle number
// spread.product.params_list  one entry per set of levels
// spread.start_prices         the start price of this cycle

The instrument is 32 bytes. The product address fills the top 160 bits, the cycle number the next 64 bits and the index into params_list the low 32 bits:

import type { Address, Hex } from "viem";

function encodeInstrument(
  productPtr: Address,
  cycle: number,
  paramsIndex: number
): Hex {
  const packed =
    (BigInt(productPtr) << 96n) | (BigInt(cycle) << 32n) | BigInt(paramsIndex);
  return `0x${packed.toString(16).padStart(64, "0")}`;
}

const instrument = encodeInstrument(
  spread.product.product_ptr,
  spread.cycle,
  0
);

An order must be for the cycle that is live now. When the cycle ends, compute the instrument of the next cycle.

2. Make the order nonce

Each order has a 128-bit nonce. The API calls it client_tag. It has three parts:

BitsContent
64–127The time now, in Unix milliseconds
32–63Reserved. Must be zero.
0–31A value that is unique for you, for example random
function createNonce(nowMs = Date.now()): bigint {
  const [unique = 0] = crypto.getRandomValues(new Uint32Array(1));
  return (BigInt(nowMs) << 64n) | BigInt(unique);
}

The timestamp must be within 5 seconds of the server time when the order arrives. Make the nonce just before you sign.

3. Sign the order

The order is EIP-712 typed data. The domain must be the domain of the deployed Scalar contract, because the contract checks the same signature again when the trade settles onchain. A signature over any other domain can pass the API and then fail onchain.

import { createWalletClient, http } from "viem";
import { privateKeyToAccount } from "viem/accounts";
import { baseSepolia } from "viem/chains";

const account = privateKeyToAccount(process.env.PRIVATE_KEY as Hex);
const wallet = createWalletClient({
  account,
  chain: baseSepolia,
  transport: http()
});

const domain = {
  name: "ScalarProtocol",
  version: "1",
  chainId: 84532,
  verifyingContract: "0xCe2499d306D82EBEa3167710C6e0A9659de5CD05"
} as const;

const types = {
  Order: [
    { name: "instrumentBytes", type: "bytes32" },
    { name: "nonce", type: "uint128" },
    { name: "isBid", type: "bool" },
    { name: "signer", type: "address" },
    { name: "price", type: "uint256" },
    { name: "size", type: "uint256" }
  ]
} as const;

const nonce = createNonce();
const order = {
  instrumentBytes: instrument,
  nonce,
  isBid: true,
  signer: account.address,
  price: 4_500_000n, // $4.50 in micro-dollars
  size: 10n
};

const signature = await wallet.signTypedData({
  domain,
  types,
  primaryType: "Order",
  message: order
});

4. Submit the order

Send the same values to POST /orders. The price is in dollars here. The signature is the only proof of ownership that this call needs.

const now = Math.floor(Date.now() / 1000);

const ack = await fetch("https://testnet-api.scalar.market/orders", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({
    user: account.address,
    client_tag: `0x${nonce.toString(16)}`,
    instrument,
    side: "bid",
    price: 4.5,
    quantity: 10,
    time_in_force: "GTC",
    valid_till: now + 3_600,
    signature
  })
}).then((r) => r.json());
FieldRule
sidebid to buy the long side, ask to sell it. It must match isBid in the signature.
time_in_forceGTC rests on the book. IOC fills what it can at once and cancels the rest.
valid_tillMore than 150 seconds ahead and at most 7 days ahead. The order stops matching 150 seconds before valid_till, and is canceled as expired at valid_till.

The reply is an order acknowledgment with the client_tag and the exchange time. If the order ended at once instead of resting, cancel_reason says why: filled, ioc, self_trade, expired or cancelled. If the order was rejected, the reply is an error envelope with a stable code that you can branch on. Fills arrive as fill frames on the trading WebSocket.

5. Authenticate for private calls

Cancels, the orders list and the account calls need a session token. The token is a Sign-In with Ethereum (EIP-4361) message and your signature over it, valid for 24 hours:

import { SiweMessage } from "siwe";

const message = new SiweMessage({
  domain: "testnet.scalar.market",
  address: account.address,
  statement: "Sign in to Scalar Market.",
  uri: "https://testnet.scalar.market",
  version: "1",
  chainId: 84532,
  nonce: crypto.randomUUID().replaceAll("-", ""),
  issuedAt: new Date().toISOString(),
  expirationTime: new Date(Date.now() + 86_400_000).toISOString()
}).prepareMessage();

const sessionSignature = await wallet.signMessage({ message });
const token = btoa(JSON.stringify([message, sessionSignature]));

// Cancel one order
await fetch(
  `https://testnet-api.scalar.market/orders/0x${nonce.toString(16)}` +
    `?user=${account.address}&instrument=${instrument}`,
  { method: "DELETE", headers: { Authorization: `Bearer ${token}` } }
);

On the trading WebSocket, send the same token in the first frame, authenticate. See WebSocket protocols.

For market makers

  • Quote over the trading WebSocket. It accepts the same orders as REST and pushes your fills and cancels as they happen.
  • Arm the dead man's switch with set_dead_mans_switch. Every frame you send resets its timer. If the timer runs out, the server closes the connection with code 1008. Send heartbeat frames to keep it open.
  • Cancel in bulk with DELETE /orders or cancel_all. The scope can be all orders, one instrument or one product.
  • Margin on one instrument is the larger of your bid side and your ask side, not the sum. A two-sided quote reserves only one side. See Orders.
  • Each cycle is a new instrument. Roll your quotes when a cycle ends. Its levels are set from the start price, which GET /products/current returns once the cycle opens.

Read the chain

Every trade, settlement and withdrawal emits an event on the Scalar contract, for example OrdersMatched, ProofSubmitted and PositionsSettled. The addresses are on Contract addresses. To prove a market yourself, call submitProof(instrument, proofData) with signed Pyth Lazer updates. How settlers work explains which prices each settler needs.

On this page