Skip to Content
Athanor

SDK

@athanor-trade/sdk: the published operations typed from the schema, and a client that authenticates, sends documents by hash, and reads refusals as typed errors.

npm install @athanor-trade/sdk

The SDK is written in Effect on Effect's HttpClient. A codebase that does not use Effect imports @athanor-trade/sdk/promises: the same client, Promises back, the same typed errors as rejections.

Without Effect

import {
  createClient,
  FederatedAuth,
  Vercel,
  AthanorApiError,
  OrdersFeedDocument,
  AdvanceOrderDocument,
} from "@athanor-trade/sdk/promises";

const athanor = createClient({
  environment: "sandbox", // or "live"
  auth: FederatedAuth.layer({
    clientId: process.env.ATHANOR_CLIENT_ID!,
    subjectToken: () => Vercel.subjectToken(),
    scopes: ["dealer:orders:read", "dealer:orders:write"],
  }),
});

const page = await athanor.execute(OrdersFeedDocument, { first: 50 });

try {
  const { advanceOrder } = await athanor.execute(AdvanceOrderDocument, {
    input: {
      orderId,
      idempotencyKey: "po-4471-lock",
      step: { lockPrices: { expectedAllIn: "51234.00" } },
    },
  });
} catch (error) {
  if (error instanceof AthanorApiError && error.reason === "quote_moved") {
    // read the record again, show the new total, try once more
  }
}

createClient builds a runtime over the platform's fetch, or the fetch you pass. Call dispose() when the process is done with it. urls overrides the hosts for a local build or a preview.

With Effect

Athanor is a service; Athanor.layer({ environment }) needs an Auth layer and an HttpClient.

import { Effect, Layer } from "effect";
import { FetchHttpClient } from "effect/http";
import { Athanor, PrivateKeyAuth, DealerContextDocument } from "@athanor-trade/sdk";

const live = Athanor.layer({ environment: "live" }).pipe(
  Layer.provide(
    PrivateKeyAuth.layer({
      clientId,
      privateKey: { pem, algorithm: "ES256" },
      scopes,
    }),
  ),
  Layer.provide(FetchHttpClient.layer),
);

const program = Effect.gen(function* () {
  const athanor = yield* Athanor;
  const { viewer } = yield* athanor.execute(DealerContextDocument);

  return viewer;
}).pipe(
  Effect.catchTag("AthanorApiError", (error) =>
    Effect.logWarning(`refused: ${error.code} ${error.reason ?? ""}`),
  ),
);

execute fails with AthanorApiError (the API's refusal), AthanorAuthError (the auth service refused the credential) or Effect's HttpClientError. Each is a Schema.TaggedError, so Effect.catchTag and Schema.is work on them.

Auth layers

LayerWhat it is
FederatedAuth.layer({ clientId, subjectToken, scopes })Where the workload runs. subjectToken is (http) => Effect<string>; GitHubActions.subjectToken() and Vercel.subjectToken() are the two the SDK reads.
PrivateKeyAuth.layer({ clientId, privateKey, scopes })A private key, PKCS#8 PEM with its algorithm or a JWK. A key that cannot sign fails the layer, so misconfiguration surfaces at construction.
TokenAuth.layer(token)Not a way in: carries a token the caller obtained through one of the two, as a string or an Effect asked for on every request so a rotated token is picked up.

Any Layer<Auth> plugs in. See Authentication for what each means on the server.

Documents and refusals

  • On live a document goes by its registered hash (documentId), so a client that chose trusted_only sends nothing else. On sandbox it goes by its text, so an operation edited in development runs without a registration step. persisted: true | false overrides either.
  • A refusal is an AthanorApiError: code is the API's stable code, reason the refusal's own, data what resolved beside it. See Refusals.
  • A 429 is waited out as Retry-After says and tried again, three times at most, a minute at most each; after that it is the answer. See Budgets.

The published set

The SDK's documents/ folder holds every published operation as GraphQL, typed by GraphQL Code Generator's client preset with persisted documents on: each document carries __meta__.hash, sha256: of its text, and persisted-documents.json maps every hash to that text. See Operations.

npx athanor-publish-documents sandbox   # registers the set against your client; also live

The publish step needs ATHANOR_CLIENT_ID and ATHANOR_PRIVATE_KEY (and ATHANOR_KEY_ALGORITHM if not ES256). A document the schema no longer accepts fails the run with the validator's words.

Your own operations

Any document typed with @graphql-typed-document-node/core runs through execute. To send one by hash on live, register it first (registerDocument, or the publish script over your own persisted-documents.json) and give it a __meta__.hash of sha256:<hex of the text>, which is what GraphQL Code Generator's client preset emits with persistedDocuments on.

On this page