Pular para o conteúdo
MZGrid

Esta página está disponível apenas em inglês. A versão em inglês é a que prevalece.

TypeScript SDK

Install @mzgrid/sdk, create a client with an API key or wallet, and browse offers, create and fund jobs, wait for endpoints, read logs and stop jobs.

@mzgrid/sdk is a fully typed ESM client for the MZGrid API and contracts. It uses viem for wallet and chain interaction.

Install

Shell
npm install @mzgrid/sdk viem

The SDK runs in Node.js and modern browsers.

Create a client

TypeScript
import { MZGridClient } from "@mzgrid/sdk";

// Server-side, with an API key
const client = new MZGridClient({
  apiUrl: "https://api.mzgrid.io",
  apiKey: process.env.MZG_API_KEY,
});

apiUrl is the API origin; the SDK adds the /v1 prefix. For local development use http://localhost:8787.

In the browser you can authenticate with the user's wallet instead. The client performs the wallet sign-in (nonce + personal_sign) on first use. Wallet sign-in requires the user to accept the Terms of Service, Privacy Policy and Risk Disclosure: show them first, then pass the accepted version as termsVersion. The SDK never fills it in for you — without it, sign-in fails with terms_not_accepted.

TypeScript
import { CURRENT_TERMS_VERSION, MZGridClient } from "@mzgrid/sdk";
import { createWalletClient, custom } from "viem";
import { base } from "viem/chains";

const [account] = await window.ethereum.request({ method: "eth_requestAccounts" });
const walletClient = createWalletClient({ account, chain: base, transport: custom(window.ethereum) });

// After the user has accepted the terms (current version: "2026-11-05")
const client = new MZGridClient({ apiUrl: "https://api.mzgrid.io", walletClient, termsVersion: CURRENT_TERMS_VERSION });

To sign in explicitly, call client.auth.signIn(termsVersion, walletClient?); it returns and stores the session token. The lower-level calls are auth.nonce(address, termsVersion?) and auth.verify(address, signature, termsVersion), which returns { token, expiresAt, address, termsVersion }. client.account() includes termsVersion and termsAcceptedAt. API-key clients are not affected.

Catalogue and marketplace

TypeScript
const gpus = await client.catalog.gpus();
for (const g of gpus) {
  console.log(g.sku, g.vramGb, "GB", "from", g.lowestPrice, "MZG/h");
}

const { items: offers, nextCursor } = await client.market.offers({
  sku: "h100-sxm",
  region: "eu-central",
  minReliability: 95,
  sort: "price",
  limit: 10,
});

market.offers(q) accepts the same filters as GET /v1/market/offers: sku, region, minVram, minReliability, sort, limit and cursor.

Jobs

jobs.create()

TypeScript
const created = await client.jobs.create({
  offerId: offers[0].id,           // or: sku: "h100-sxm", autoSelect: true
  template: "llama-3.3-70b",
  maxDurationHours: 4,
  config: {
    args: ["--max-model-len", "16384"],
    env: { HF_TOKEN: process.env.HF_TOKEN ?? "" },
  },
});

created.job;    // Job, status "awaiting_funding"
created.escrow; // { contract, jobIdBytes32, provider, pricePerHourWei, maxDurationS, depositWei, specHash }

jobs.fund(job, walletClient)

Moves the deposit into MZGridEscrow and reports the transaction to the API. It signs an EIP-2612 permit and calls createJobWithPermit when possible, and otherwise sends approve followed by createJob. It resolves once the coordinator has confirmed the JobFunded event.

TypeScript
const funded = await client.jobs.fund(created, walletClient);
console.log(funded.status);   // "funded"
console.log(funded.txs.fund); // transaction hash on Base

The wallet must be on Base (8453) — or Base Sepolia (84532) when using a testnet coordinator — and hold the deposit in MZG plus a little ETH for gas.

jobs.get(), jobs.waitForEndpoint()

TypeScript
const job = await client.jobs.get(created.job.id);

// Polls until the job is running with an endpointUrl, or throws if it fails or times out.
const ready = await client.jobs.waitForEndpoint(created.job.id, { timeoutMs: 15 * 60_000 });
console.log(ready.endpointUrl);

jobs.logs()

TypeScript
let since: string | undefined;
const { lines } = await client.jobs.logs(created.job.id, { since });
for (const l of lines) console.log(l.t, l.stream, l.text);
since = lines.at(-1)?.t;

jobs.stop()

TypeScript
const stopped = await client.jobs.stop(created.job.id);
// After settlement: stopped.charged, stopped.refund, stopped.usedSeconds

Network statistics

TypeScript
const stats = await client.network.stats();
console.log(stats.gpusOnline, "GPUs online in", stats.countries, "countries");

End-to-end example

Deploy Qwen2.5 32B on the best-scoring RTX 5090, query it with the OpenAI client, and stop it.

TypeScript
import { MZGridClient } from "@mzgrid/sdk";
import OpenAI from "openai";
import { createWalletClient, http } from "viem";
import { privateKeyToAccount } from "viem/accounts";
import { base } from "viem/chains";

const walletClient = createWalletClient({
  account: privateKeyToAccount(process.env.WALLET_PRIVATE_KEY as `0x${string}`),
  chain: base,
  transport: http(),
});
const mzg = new MZGridClient({ apiUrl: "https://api.mzgrid.io", apiKey: process.env.MZG_API_KEY });

const created = await mzg.jobs.create({
  sku: "rtx5090",
  autoSelect: true,
  template: "qwen2.5-32b",
  maxDurationHours: 3,
});
console.log(`Deposit ${created.job.deposit} MZG at ${created.job.pricePerHour} MZG/h on ${created.job.region}`);

await mzg.jobs.fund(created, walletClient);
const job = await mzg.jobs.waitForEndpoint(created.job.id, { timeoutMs: 15 * 60_000 });

try {
  const openai = new OpenAI({ baseURL: `${job.endpointUrl}/v1`, apiKey: "unused" });
  const res = await openai.chat.completions.create({
    model: "Qwen/Qwen2.5-32B-Instruct-AWQ",
    messages: [{ role: "user", content: "Write a haiku about idle GPUs." }],
  });
  console.log(res.choices[0]?.message.content);
} finally {
  const settled = await mzg.jobs.stop(job.id);
  console.log(`Charged ${settled.charged} MZG, refunded ${settled.refund} MZG`);
}

ABIs and addresses

The SDK exports the contract ABIs as const arrays, so viem infers argument and return types, and the deployed addresses per chain id:

TypeScript
import { mzgTokenAbi, mzgridEscrowAbi, providerRegistryAbi, addresses } from "@mzgrid/sdk";
import { createPublicClient, http, formatUnits } from "viem";
import { base } from "viem/chains";

const publicClient = createPublicClient({ chain: base, transport: http() });
const { escrow, registry } = addresses[base.id];

const providerAddress = "0x..." as const; // a provider's wallet address
const cap = await publicClient.readContract({
  address: registry,
  abi: providerRegistryAbi,
  functionName: "jobCap",
  args: [providerAddress],
});
console.log("job cap:", formatUnits(cap, 18), "MZG");

const fee = await publicClient.readContract({ address: escrow, abi: mzgridEscrowAbi, functionName: "FEE_BPS" });
console.log("fee bps:", fee); // 700n

addresses has entries for Base (8453) and Base Sepolia (84532), each with token, registry and escrow. The canonical list is on Smart contracts.

Types

Every response is typed: Job, JobStatus, Offer, GpuSku, Template, NetworkStats, CreateJobRequest, CreateJobResponse and more are exported from the package root. Amount fields are string (MZG with up to 6 decimals); fields ending in Wei are decimal strings of wei.

Errors

Failed requests throw an MZGridApiError with status (HTTP), code and message taken from the API's error body:

TypeScript
import { MZGridApiError } from "@mzgrid/sdk";

try {
  await mzg.jobs.create({ sku: "h100-sxm", autoSelect: true, template: "llama-3.3-70b", maxDurationHours: 72 });
} catch (err) {
  if (err instanceof MZGridApiError && err.code === "deposit_exceeds_cap") {
    // choose a shorter duration or an offer whose provider has a higher cap
  }
  throw err;
}