covr.Docs

SDK reference

GatewayClient

A minimal client for covr's RFQ gateway. One client opens one /maker command socket, one read-only /rfqs/<asset alias> feed socket per asset, and reads RFQ snapshots over GET /api/rfqs/<id>. It sends your bearer token as Authorization: Bearer <token> on every socket upgrade and every HTTP read.

The client never reconnects. When any socket ends you get a closed event. Close the client and connect a new one, with backoff.

Note

covr turns gateway access on per desk and sends you the URL (wss://<provided by covr>) and your token. covr's markets list only covr's own maker today, so your bid intents are verified and then refused with Bid intent verified but not entered: this market does not list this maker yet (practice mode).

For the wire protocol itself see Gateway overview, Messages, Limits and Errors.

GatewayClient

The client class. Create it only with GatewayClient.connect; the constructor is private.

ts
export declare class GatewayClient {
    static connect(wsUrl: string, token?: string, options?: GatewayClientOptions): Promise<GatewayClient>;
    events(): AsyncIterable<GatewayEvent>;
    getRfq(id: string): Promise<RfqSnapshot>;
    sendBidIntent(intent: BidIntent): Promise<string>;
    sendQuote(intentSignature: string, quote: QuoteV2): Promise<string>;
    sendAwardDecline(rfqId: string, intentSignature: string): Promise<string>;
    sendRfqNote(rfqId: string, reason: RfqNoteReason): Promise<string>;
    close(): void;
}

(Private members omitted.)

MemberWireResolves
connectupgrades /maker and /rfqs/<alias>a connected client
eventsreads both socket kindsrfq, award, notice, closed events
getRfqGET /api/rfqs/<id>RfqSnapshot
sendBidIntentbid_intent"BID_ACCEPTED"
sendQuotequote"OK" (admitted, not filled)
sendAwardDeclineaward_decline"DECLINED"
sendRfqNoterfq_note"NOTED"
closecloses every socket
ts
import { setTimeout as sleep } from 'node:timers/promises';
import { GatewayClient, JITOSOL_MINT, type GatewayEvent } from '@covrfun/maker-sdk';

declare const token: string; // from covr; keep it secret
declare function onRfq(client: GatewayClient, event: Extract<GatewayEvent, { type: 'rfq' }>): Promise<void>;
declare function onAward(client: GatewayClient, event: Extract<GatewayEvent, { type: 'award' }>): Promise<void>;

let attempt = 0;
for (;;) {
  const startedAt = Date.now();
  try {
    const client = await GatewayClient.connect('wss://<provided by covr>', token, { assets: [JITOSOL_MINT] });
    for await (const event of client.events()) {
      // Never await a handler here: a slow RFQ read must not delay an award.
      if (event.type === 'rfq') void onRfq(client, event).catch(console.error);
      else if (event.type === 'award') void onAward(client, event).catch(console.error);
      else if (event.type === 'notice') console.log('gateway notice', event.message);
      else {
        console.log(`socket ${event.socket} closed (${event.code}: ${event.reason})`);
        break; // leaving the loop closes the client
      }
    }
  } catch (error) {
    console.error('connect failed', error);
  }
  if (Date.now() - startedAt > 60_000) attempt = 0; // a long session resets the backoff
  const step = Math.min(30_000, 1000 * 2 ** Math.min(attempt++, 30)); // 1 s doubling to 30 s
  await sleep(step / 2 + Math.random() * (step / 2)); // capped exponential backoff with jitter
}

GatewayClient.connect

Opens the /maker socket, then one feed per asset, in that order. It resolves once every socket's WebSocket upgrade has completed.

ts
static connect(wsUrl: string, token?: string, options?: GatewayClientOptions): Promise<GatewayClient>;
NameTypeDescription
wsUrlstringwss://<provided by covr>. Must be ws: or wss:. Trailing slashes are dropped; /maker and /rfqs/<alias> are appended.
tokenstringOptional. Your bearer token. Omit it only for a gateway that needs none.
optionsGatewayClientOptionsOptional. Assets, timeouts and limits.

Returns: Promise<GatewayClient>.

Listeners are attached before each socket opens, so a frame the gateway sends while later feeds are still connecting is queued, never lost.

Warning

A bad token does not reject connect. The gateway completes the upgrade and then closes the socket with code 4401. You see it as closed events with code: 4401. Likewise 4403 (an asset your token does not allow) and 4429 (more than 16 sockets for your maker).

Throws (the promise rejects):

ConditionError
wsUrl is not a URLTypeError: Invalid URL
wsUrl is not ws: or wss:maker-sdk: gateway URL must be ws:// or wss://
token is given but empty, not a string, or contains CR or LFmaker-sdk: invalid gateway token
An asset is neither a 0x + 40-hex alias nor a valid base58 mintSolanaError from @solana/kit
An option is not an integer in its rangemaker-sdk: <option> must be an integer 1..<max>
A socket fails before its upgrade completes (DNS, refused, TLS, a non-101 HTTP reply, handshake timeout)the ws library's error, for example Opening handshake has timed out; every socket opened so far is terminated
ts
import { GatewayClient, JITOSOL_MINT } from '@covrfun/maker-sdk';

declare const token: string;
const client = await GatewayClient.connect('wss://<provided by covr>', token, {
  assets: [JITOSOL_MINT],
  requestTimeoutMs: 2500,
});

GatewayClientOptions

OptionTypeDefaultRangeMeaning
assetsreadonly string[][JITOSOL_MINT]Collateral mints or 0x aliases to subscribe to. Mints are converted with assetAlias; duplicates are dropped. One feed socket each.
requestTimeoutMsnumber50001 to 60,000How long a /maker request waits for its reply. For comparison, the award window is 3,000 ms.
httpUrlstringwsUrl with ws → http, wss → httpsBase URL for GET /api/rfqs/<id>.
httpTimeoutMsnumber50001 to 60,000getRfq gives up after this.
maxQueuedEventsnumber10001 to 1,000,000Most unread events held for events. One more closes the client.
handshakeTimeoutMsnumber100001 to 60,000Each socket's upgrade must complete within this.
heartbeatIntervalMsnumber150001 to 300,000Every socket is pinged this often.
heartbeatTimeoutMsnumber300001 to 300,000A socket whose matching pong has not arrived this long after the ping is ended.

client.events

Returns the event stream: feed RFQs, awards, other gateway frames and socket closes, in arrival order.

ts
events(): AsyncIterable<GatewayEvent>;

Returns: AsyncIterable<GatewayEvent>.

  • Single consumer. Iterate it once.
  • Leaving the loop closes the client. break, return or a throw inside for await calls the iterator's return(), which calls close.
  • Ends after close. Events still queued when the client closes stay readable; then the stream ends.
  • Bounded. If more than maxQueuedEvents (default 1,000) events are unread, the client queues one last closed event with socket: 'client' and code: 1008, then closes every socket with 1008 event queue overflow. Handle events without blocking the loop.

Throws: nothing.

ts
import type { GatewayClient } from '@covrfun/maker-sdk';

declare const client: GatewayClient;
for await (const event of client.events()) {
  if (event.type === 'closed') break;
}

client.getRfq

Reads one RFQ's snapshot: market, writer wallet, deadlines and the request. Call it for every rfq event before you bid.

ts
getRfq(id: string): Promise<RfqSnapshot>;
NameTypeDescription
idstringThe RFQ id from the rfq event: a lowercase UUID v4.

Returns: RfqSnapshot. The gateway shows another maker's winning quote to no one but that maker.

Throws (the promise rejects):

ConditionError
id is not a lowercase UUID v4maker-sdk: invalid auction id
No response within httpTimeoutMsmaker-sdk: GET /api/rfqs/<id> timed out after <ms> ms
Network failurethe error fetch throws
The body is not JSONthe SyntaxError from parsing it
Non-2xx statusGatewayError with code = the HTTP status and message = the body's error (or RFQ read failed). The desk listener answers 401 Unauthorized, 404 RFQ not found (also for an asset your token does not allow), 404 Not found, 500 RFQ read failed and 503 Gateway stopping.
ts
import type { GatewayClient } from '@covrfun/maker-sdk';

declare const client: GatewayClient;
declare const id: string; // from an rfq event
const snapshot = await client.getRfq(id);
if (snapshot.status !== 'collecting' || Date.now() >= snapshot.closesAt) {
  // too late to bid
}

client.sendBidIntent

Sends a signed bid intent as bid_intent on /maker. One intent per maker per auction, before the collection window closes.

ts
sendBidIntent(intent: BidIntent): Promise<string>;
NameTypeDescription
intentBidIntentFrom signIntent. Sent as the params, with JSON-RPC id = intent.auctionId.

Returns: "BID_ACCEPTED": the gateway entered your intent in the auction.

Throws: the request errors. Gateway refusals reject with GatewayError (code: -32602), for example Bid intent verified but not entered: this market does not list this maker yet, Maker already bid in this auction or Auction collection closed.

ts
import type { BidIntent, GatewayClient } from '@covrfun/maker-sdk';

declare const client: GatewayClient;
declare const intent: BidIntent; // signed, and stored by RFQ id
const reply = await client.sendBidIntent(intent); // 'BID_ACCEPTED'

client.sendQuote

Answers the award you hold with a signed executable quote, as quote on /maker. Send it on the same client that sent the intent, before awardUntil.

ts
sendQuote(intentSignature: string, quote: QuoteV2): Promise<string>;
NameTypeDescription
intentSignaturestringThe signature of your awarded intent.
quoteQuoteV2From signQuote. JSON-RPC id = quote.auctionId.

Returns: "OK": the gateway admitted your quote and offers it to the customer. It is not a fill. The gateway sends no fill message: watch the chain for your position PDA (derivePosition).

Caution

If this rejects with OutcomeUnknownError, the quote may be live. Keep its nonce and cash holds until the chain settles it: a fill lands, or the chain clock passes validUntil. To kill it early, raise min_nonce above its nonce (configureMaker).

Throws: the request errors, or GatewayError for a refusal. Any failed answer from the award holder passes the award to the next bidder.

ts
import type { GatewayClient, QuoteV2 } from '@covrfun/maker-sdk';

declare const client: GatewayClient;
declare const intentSignature: string; // your stored intent's signature
declare const quote: QuoteV2; // journaled before signing
const reply = await client.sendQuote(intentSignature, quote); // 'OK' = admitted, not filled

client.sendAwardDecline

Passes the award you hold to the next bidder at once, as award_decline. Answer every award: a silent winner holds it until the hard deadline and the customer gets no quote.

ts
sendAwardDecline(rfqId: string, intentSignature: string): Promise<string>;
NameTypeDescription
rfqIdstringThe award's id.
intentSignaturestringThe awarded intent's signature (award.intent.signature).

Returns: "DECLINED".

Throws: the request errors, or GatewayError Maker is not the current award when you do not hold it on this socket.

ts
import type { Award, GatewayClient } from '@covrfun/maker-sdk';

declare const client: GatewayClient;
declare const award: Award;
await client.sendAwardDecline(award.id, award.intent.signature); // 'DECLINED'

client.sendRfqNote

Attaches a display-only reason to an RFQ you will not price. covr shows it to the customer if the RFQ ends with no quote.

ts
sendRfqNote(rfqId: string, reason: RfqNoteReason): Promise<string>;
NameTypeDescription
rfqIdstringThe RFQ id. Sent inside the params; the JSON-RPC id is a fresh random UUID.
reasonRfqNoteReasonOne of RFQ_NOTE_REASONS.

Returns: "NOTED".

The gateway accepts a note only on an ordinary RFQ, only from a maker that market lists, and only if no other maker has already noted that RFQ. In practice mode it is refused with RFQ note needs a maker this market lists.

Throws: maker-sdk: unknown rfq_note reason for a reason outside the list (nothing is sent); the request errors; or GatewayError.

ts
import type { GatewayClient } from '@covrfun/maker-sdk';

declare const client: GatewayClient;
declare const rfqId: string;
await client.sendRfqNote(rfqId, 'too_large');

client.close

Closes every socket and ends the event stream. Safe to call more than once.

ts
close(): void;

Returns: nothing.

Each socket gets a normal close handshake. One that has not finished closing 1 s later is terminated, on a timer that never keeps your process alive. Every request still waiting for its reply rejects with OutcomeUnknownError. No closed events are emitted after close().

Throws: nothing.

ts
import type { GatewayClient } from '@covrfun/maker-sdk';

declare const client: GatewayClient;
client.close();

Request errors

sendBidIntent, sendQuote, sendAwardDecline and sendRfqNote share one request path. Each request's JSON-RPC id is the RFQ id (for rfq_note, a fresh UUID), and the gateway's reply carries the same id.

Refused before sending (plain Error, nothing reaches the gateway):

ConditionMessage
The client is closed, or /maker is not openmaker-sdk: /maker socket is not open
The id is not a lowercase UUID v4maker-sdk: invalid auction id
An earlier request for this RFQ timed outmaker-sdk: not sending <method> for <id>: the earlier <method> for it timed out and its outcome is unknown (its late reply would look like this one's). Treat that <method> as possibly accepted
A request for this RFQ is still waiting for its replymaker-sdk: a request for this RFQ is already awaiting its reply
The JSON frame exceeds 16,384 bytesmaker-sdk: frame exceeds 16384 bytes

After sending:

OutcomeResult
Reply with resultresolves with it
Reply with errorrejects with GatewayError
No reply within requestTimeoutMsrejects with OutcomeUnknownError: maker-sdk: <method> for <id> timed out; its outcome is unknown: treat a signed quote as possibly live. No further request is sent for this RFQ
The socket failed while sendingrejects with OutcomeUnknownError: maker-sdk: <method> for <id>: the socket failed while sending it (<cause>); its outcome is unknown: treat a signed quote as possibly live (the send error is cause)
The /maker socket closed, you called close(), or the client closed itself on queue overflowrejects with OutcomeUnknownError: maker-sdk: <method> for <id> got no reply before <why>; its outcome is unknown: treat a signed quote as possibly live. <why> is the /maker socket closed (plus : <reason> when the close carried one), the client closed, or the client closed itself (more than <n> events went unread). A feed socket closing fails no request.

Only a timeout blocks later requests. After one, the client refuses every further request for that RFQ id, because a late reply would look like the new request's reply. It remembers the last 4,096 such ids. A send failure or a close does not add the id; after a close every request fails anyway with maker-sdk: /maker socket is not open. A reply that arrives after its request timed out appears as a notice event.

GatewayEvent

The union events yields.

ts
export type GatewayEvent = {
    type: 'rfq';
    asset: string;
    id: string;
    request: RfqRequest;
} | ({
    type: 'award';
} & Award) | {
    type: 'notice';
    socket: 'maker' | 'feed';
    message: unknown;
}
 | {
    type: 'closed';
    socket: 'maker' | 'feed' | 'client';
    asset?: string;
    code: number;
    reason: string;
};
typeWhenFields
rfqA feed frame { id, result } whose id is an RFQ id and whose result is an objectasset: the feed's lowercase alias. id: the RFQ id. request: the RfqRequest, unvalidated.
awardA /maker frame with method: 'award', a string id, an intent object and integer awardUntil and hardDeadlineAward fields: id, intent (as the gateway sent it, unvalidated), awardUntil and hardDeadline in epoch ms.
noticeAnything else: a late reply, any other gateway push, or text that is not JSONsocket: where it came from. message: the parsed JSON, or the raw string.
closedA socket ended: the gateway closed it, it errored after opening, or its heartbeat failed. Or the client closed itself on queue overflow.socket ('client' for overflow), asset for a feed, code, reason.

closed codes you may see:

codereasonMeaning
4401UnauthorizedNo token, or an unknown one. Sent right after the upgrade, before any RFQ.
4403Asset not allowedA feed for an asset your token does not allow.
4429Too many connectionsYour maker already holds 16 sockets across all its tokens.
4429Too many framesMore than 100 frames at once, or more than 20 a second after that, on one connection.
1006the error's message; no pong within <ms> ms; or emptyThe socket errored after opening (the error's message), missed its heartbeat (no pong ...), or the connection dropped without a close frame (empty). The client ends the socket at once in the first two cases.
1008maker-sdk: more than <n> events went unread; ...socket: 'client': the event queue overflowed. Always the last event.
any otherthe gateway's close reason, often emptyThe gateway closed the socket.
Tip

Answer an award only when award.intent equals the intent you signed and stored for award.id, and build the quote from your copy, never from the award's.

GatewayError

A refusal from the gateway: a JSON-RPC error reply, or a non-2xx HTTP status from getRfq. The gateway answered, and the answer is no.

ts
export declare class GatewayError extends Error {
    readonly code: number;
    readonly rfqId?: string | undefined;
    constructor(code: number, message: string, rfqId?: string | undefined);
}
FieldTypeMeaning
namestring'GatewayError'
codenumber-32602 for every /maker refusal; the HTTP status for getRfq.
messagestringThe gateway's reason, for example Maker is not the current award.
rfqIdstring | undefinedThe request's JSON-RPC id (the RFQ id), or the id passed to getRfq.

See Errors for every gateway reason.

ts
import { GatewayError, type BidIntent, type GatewayClient } from '@covrfun/maker-sdk';

declare const client: GatewayClient;
declare const intent: BidIntent;
try {
  await client.sendBidIntent(intent);
} catch (error) {
  if (error instanceof GatewayError) console.log('refused', error.code, error.message);
  else throw error;
}

OutcomeUnknownError

A request reached an open socket and its reply never came: it timed out, the socket failed while sending it, /maker closed, or the client closed while it waited. The gateway may have applied it. A failed send is included because frames queued behind one write share its result.

ts
export declare class OutcomeUnknownError extends Error {
    readonly method: string;
    readonly rfqId: string;
    constructor(method: string, rfqId: string, message: string, options?: {
        cause?: unknown;
    });
}
FieldTypeMeaning
namestring'OutcomeUnknownError'
methodstringbid_intent, quote, award_decline or rfq_note.
rfqIdstringThe request's JSON-RPC id: the RFQ id, or the note's own id for rfq_note.
causeunknownThe send error, when the socket failed while sending.

Treat a quote whose send ended this way as possibly live. Keep its holds until the chain settles it. Every other rejection is either a request refused before it was sent (plain Error) or the gateway's answer (GatewayError).

ts
import { OutcomeUnknownError, type GatewayClient, type QuoteV2 } from '@covrfun/maker-sdk';

declare const client: GatewayClient;
declare const intentSignature: string;
declare const quote: QuoteV2;
try {
  await client.sendQuote(intentSignature, quote);
} catch (error) {
  if (error instanceof OutcomeUnknownError) {
    // Possibly live: keep nonce and cash holds until a fill lands or validUntil passes on chain.
  } else throw error;
}

RFQ_NOTE_REASONS

The reasons sendRfqNote accepts. The gateway accepts exactly these. The array is frozen.

ts
export declare const RFQ_NOTE_REASONS: readonly ["warming_up", "fully_booked", "wallet_limit", "too_large", "not_priced"];
export type RfqNoteReason = typeof RFQ_NOTE_REASONS[number];
ReasonWhat the customer is told
warming_upQuotes start in a minute: the maker is getting ready.
fully_bookedThe maker has no room for new orders right now.
wallet_limitThe customer already has quotes waiting.
too_largeThe amount is more than the maker quotes for this market right now.
not_pricedThe market has no live price right now.
ts
import { RFQ_NOTE_REASONS } from '@covrfun/maker-sdk';

console.log(RFQ_NOTE_REASONS.includes('too_large')); // true

Reconnect, heartbeat and timeouts

MechanismDefaultBehaviour
ReconnectnoneThe client never reopens a socket. On any closed event, close it and connect a new client with capped exponential backoff and jitter. covr's example bot uses 1 s doubling to 30 s.
Upgrade timeout10,000 msconnect rejects if any socket's upgrade takes longer.
Heartbeatping every 15,000 msEach socket gets a WebSocket ping with 16 random bytes. Only a pong echoing those bytes counts.
Heartbeat timeout30,000 msNo matching pong within 30 s of the ping ends the socket: closed with code 1006, reason no pong within 30000 ms. A path that dies silently is reported within about 45 s.
Socket error after openEnds the socket at once: closed with code 1006 and the error text.
Request timeout5,000 msSee Request errors.
getRfq timeout5,000 msRejects with maker-sdk: GET /api/rfqs/<id> timed out after 5000 ms.
Inbound frame limit16,384 bytesA larger frame from the gateway ends that socket.
Close grace1,000 msclose() terminates a socket whose close handshake is still pending after 1 s.

The gateway pings every desk socket every 30 s and drops one that missed the previous ping or has more than 1 MiB of unread data queued. The ws library answers its pings automatically. Each connection counts toward your maker's 16-socket cap until the gateway sees it close, so close an old client before you connect a new one.