Skip to content
Docs

Platforms

Next.js

Use the wallet SDKs in client components and @gray3/cloud in route handlers, with a full end-to-end example.

Overview

A Next.js app has two halves, and each uses different packages:

  • Client components use @gray3/client and @gray3/keystore. Keys stay in the user's browser.
  • Route handlers (or server actions) use @gray3/cloud with your project secret key. The browser calls these routes, never the Gray3 Cloud API directly.

transpilePackages is not needed. Polkadot and Bittensor WebAssembly is inlined, so the only file you host is the SQLite WebAssembly binary for the keystore.

1. Install

bash
npm install @gray3/client @gray3/keystore sql.js @gray3/cloud server-only

Copy the sql.js WebAssembly binary into public/. It is never fetched from a CDN.

bash
cp node_modules/sql.js/dist/sql-wasm.wasm public/sql-wasm.wasm

Add the copy to a postinstall script so the file stays in sync with the installed sql.js version.

2. Environment variables

bash
# .env.local — server only. Never prefix these with NEXT_PUBLIC_.
GRAY_PROJECT_ID=proj_…
GRAY_SECRET_KEY=gray_sk_…

3. Server side

Create the Cloud client in a module marked server-only, so importing it from a client component fails the build instead of leaking the secret.

ts
// lib/gray-server.ts
import "server-only";
import { Gray, isGrayError } from "@gray3/cloud";

export const gray = new Gray({
  projectId: process.env.GRAY_PROJECT_ID!,
  secretKey: process.env.GRAY_SECRET_KEY!,
});

/** Forward the Gray3 envelope: { data } on success, { error: { code, message } } on failure. */
export async function respond<T>(work: () => Promise<T>): Promise<Response> {
  try {
    return Response.json({ data: await work() });
  } catch (err) {
    if (!isGrayError(err)) throw err;
    return Response.json(
      { error: { code: err.code, message: err.message, retryable: err.retryable } },
      { status: err.httpStatus ?? 500 },
    );
  }
}

export function badRequest(message: string): Response {
  return Response.json({ error: { code: "invalid_argument", message } }, { status: 400 });
}
ts
// app/api/portfolio/route.ts
import { gray, respond, badRequest } from "@/lib/gray-server";

export async function GET(request: Request) {
  const url = new URL(request.url);
  const address = url.searchParams.get("address");
  const chainId = url.searchParams.get("chainId") ?? "ethereum";
  if (!address) return badRequest("address is required");
  return respond(() => gray.portfolio.get({ chainId, address }));
}
ts
// app/api/tx/prepare/route.ts
import { gray, respond, badRequest } from "@/lib/gray-server";

const ALLOWED_CHAINS = new Set(["ethereum", "base"]);

export async function POST(request: Request) {
  const { chainId, from, to, value } = await request.json();
  if (!ALLOWED_CHAINS.has(chainId)) return badRequest("chain not allowed");
  if (!/^\d+$/.test(String(value))) return badRequest("value must be a base-unit integer string");
  return respond(() => gray.transactions.prepare({ kind: "transfer", chainId, from, to, value }));
}
ts
// app/api/tx/broadcast/route.ts
import { gray, respond, badRequest } from "@/lib/gray-server";

export async function POST(request: Request) {
  const { chainId, signedPayload } = await request.json();
  if (!chainId || !signedPayload) return badRequest("chainId and signedPayload are required");
  return respond(() => gray.transactions.broadcast({ chainId, signedPayload }));
  // → { data: { txHash: string | null, status: "broadcast" | "submitted", … } }
}

Add your own user authentication to these routes. Without it, anyone can spend your project's credits through them.

4. Client side

Use the SDK only from client components ("use client"). Create the keystore and client in an effect or an event handler, never at module scope: server rendering evaluates modules with the Node.js build, which has no IndexedDB.

tsx
// app/wallet/wallet-panel.tsx
"use client";

import { useState } from "react";
import { GrayClient, type Account } from "@gray3/client";
import { GrayKeystore } from "@gray3/keystore";

async function api<T>(path: string, init?: RequestInit): Promise<T> {
  const res = await fetch(path, {
    ...init,
    headers: { "content-type": "application/json", ...init?.headers },
  });
  const body = await res.json();
  if (body.error) throw new Error(`${body.error.code}: ${body.error.message}`);
  return body.data as T;
}

export function WalletPanel() {
  const [account, setAccount] = useState<Account | null>(null);
  const [address, setAddress] = useState("");
  const [portfolio, setPortfolio] = useState<unknown>(null);

  async function unlock(pin: string) {
    const storage = await GrayKeystore.create({
      sqlite: { web: { name: "gray-wallets", wasmUrl: "/sql-wasm.wasm" } },
      password: pin,
    });
    const client = await GrayClient.create({ storage, chains: ["ethereum", "base"] });
    const [first] = await client.wallets.list();
    const wallet = first
      ? await client.wallets.open(first.id, { password: pin })
      : await client.wallets.create({ label: "Main", password: pin });
    const acct = wallet.account(0);
    const addr = acct.address("ethereum");
    setAccount(acct);
    setAddress(addr);
    setPortfolio(await api(`/api/portfolio?chainId=ethereum&address=${addr}`));
  }

  async function send(to: string, valueWei: string) {
    if (!account) return;
    // 1. Your server prepares the unsigned transaction
    const prepared = await api("/api/tx/prepare", {
      method: "POST",
      body: JSON.stringify({ chainId: "ethereum", from: address, to, value: valueWei }),
    });
    // 2. The browser signs it; the key never leaves this device
    const { signedPayload } = await account.signPreparedTransaction(prepared as never);
    // 3. Your server broadcasts it
    return api("/api/tx/broadcast", {
      method: "POST",
      body: JSON.stringify({ chainId: "ethereum", signedPayload }),
    });
  }

  // …render a PIN form that calls unlock(pin), then show address, portfolio, and a send form
  return null;
}

Type the prepared transaction as PreparedTx from @gray3/client in real code instead of the cast shown above.

Gram signing

Gram (TON) signing in the browser needs a global Buffer. See the Buffer note; add it in a client component that runs before the first Gram signature.