Skip to content
Terra WalletDevelopers

Early access. The Terra API and SDKs may change before launch, and the SDK packages are not published yet.

View as Markdown

SDK and widgets

Early access

Code samples

Terra Connect

// Terra Connect in Next.js (App Router): find Terra Wallet with EIP-6963, then sign in with a signed message.// Works today with the Terra Wallet extension. No Terra SDK needed.// npm install ethers // File: app/components/connect-terra-wallet.tsx"use client"; import { useEffect, useState } from "react"; type Eip1193Provider = { request(args: { method: string; params?: unknown[] }): Promise<unknown> };type Announced = { info: { uuid: string; name: string; icon: string; rdns: string }; provider: Eip1193Provider }; const TERRA_RDNS = "com.terrawallet.app"; export function ConnectTerraWallet() {  const [terra, setTerra] = useState<Announced | null>(null);  const [account, setAccount] = useState<string | null>(null);  const [error, setError] = useState<string | null>(null);   useEffect(() => {    const onAnnounce = (event: Event) => {      const detail = (event as CustomEvent<Announced>).detail;      if (detail?.info?.rdns === TERRA_RDNS) setTerra(detail);    };    window.addEventListener("eip6963:announceProvider", onAnnounce);    window.dispatchEvent(new Event("eip6963:requestProvider"));    return () => window.removeEventListener("eip6963:announceProvider", onAnnounce);  }, []);   async function signIn() {    setError(null);    if (!terra) {      setError("Terra Wallet is not installed in this browser. On a phone, use WalletConnect.");      return;    }    try {      const [address] = (await terra.provider.request({ method: "eth_requestAccounts" })) as string[];      const { message } = await fetch("/api/auth/nonce", {        method: "POST",        headers: { "Content-Type": "application/json" },        body: JSON.stringify({ address }),      }).then((r) => r.json());      const signature = await terra.provider.request({ method: "personal_sign", params: [message, address] });      const res = await fetch("/api/auth/verify", {        method: "POST",        headers: { "Content-Type": "application/json" },        body: JSON.stringify({ message, signature }),      });      if (!res.ok) throw new Error("verification failed");      setAccount(address);    } catch (e) {      setError((e as { code?: number }).code === 4001 ? "You rejected the request." : "Could not sign in.");    }  }   if (account) return <p>Signed in as {account}</p>;  return (    <div>      <button onClick={signIn}>{terra ? "Sign in with Terra Wallet" : "Terra Wallet not found"}</button>      {error && <p role="alert">{error}</p>}    </div>  );} // File: app/api/auth/nonce/route.tsimport { NextResponse } from "next/server";import { randomBytes } from "node:crypto";import { getAddress } from "ethers"; export async function POST(req: Request) {  const { address } = await req.json();  const nonce = randomBytes(16).toString("hex");  const domain = "shop.example.com"; // your domain  // Sign-In with Ethereum (EIP-4361) message format.  const message =    `${domain} wants you to sign in with your Ethereum account:\n${getAddress(address)}\n\n` +    `Sign in to ${domain}.\n\nURI: https://${domain}\nVersion: 1\nChain ID: 1\nNonce: ${nonce}\n` +    `Issued At: ${new Date().toISOString()}`;  const res = NextResponse.json({ message });  res.cookies.set("siwe_nonce", nonce, { httpOnly: true, secure: true, sameSite: "strict", maxAge: 300 });  return res;} // File: app/api/auth/verify/route.tsimport { NextRequest } from "next/server";import { verifyMessage } from "ethers"; export async function POST(req: NextRequest) {  const { message, signature } = await req.json();  const nonce = req.cookies.get("siwe_nonce")?.value;  if (!nonce || typeof message !== "string" || !message.includes(`\nNonce: ${nonce}\n`)) {    return NextResponse.json({ ok: false }, { status: 400 });  }  let address: string;  try {    address = verifyMessage(message, signature); // recovers the signer  } catch {    return NextResponse.json({ ok: false }, { status: 400 });  }  if (!message.includes(`\n${address}\n`)) return NextResponse.json({ ok: false }, { status: 400 });  const res = NextResponse.json({ ok: true, address });  res.cookies.delete("siwe_nonce"); // one nonce, one sign-in  // Create your own session for `address` here.  return res;}

Terra Pay checkout

// Terra Pay in Next.js (App Router): create a payment intent on the server and redirect to hosted checkout.// Preview: the Terra API is in early access and may change before launch.// Set TERRA_SECRET_KEY (tw_test_sk_... or tw_live_sk_...) in your server environment only, never NEXT_PUBLIC_. // File: app/api/checkout/route.tsimport { NextResponse } from "next/server"; // Live-mode (mainnet) assets with verified contracts, from the Terra docs page "Supported networks and assets".// Test mode accepts testnet assets only.const ACCEPTED_ASSETS = [  { chain: "tron", symbol: "USDT", contract: "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t", decimals: 6 },  { chain: "base", symbol: "USDC", contract: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", decimals: 6 },  { chain: "solana", symbol: "USDC", contract: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v", decimals: 6 },]; // Your own data access. Never take the price from the browser.declare function loadOrder(id: string): Promise<{ id: string; total: string } | null>; export async function POST(req: Request) {  const { orderId } = (await req.json()) as { orderId?: string };  const order = orderId ? await loadOrder(orderId) : null;  if (!order) return NextResponse.json({ error: "ORDER_NOT_FOUND" }, { status: 404 });   const res = await fetch("https://terrawallet.us/api/v1/payment_intents", {    method: "POST",    headers: {      Authorization: `Bearer ${process.env.TERRA_SECRET_KEY}`,      "Content-Type": "application/json",      "Idempotency-Key": `order-${order.id}-checkout`, // a retry returns the same intent    },    body: JSON.stringify({      amount: order.total, // a decimal string such as "120.00"      currency: "USD",      accepted_assets: ACCEPTED_ASSETS,      description: `Order ${order.id}`,      metadata: { order_id: order.id },      success_url: `https://shop.example.com/orders/${order.id}/thanks`,      cancel_url: "https://shop.example.com/cart",    }),  });  const intent = await res.json();  if (!res.ok) {    console.error("Terra API error", res.status, intent?.error?.code, intent?.error?.requestId);    return NextResponse.json({ error: "CHECKOUT_UNAVAILABLE" }, { status: 502 });  }  // Store intent.id with the order, then send the customer to hosted checkout.  return NextResponse.json({ checkoutUrl: intent.checkout_url });} // File: app/checkout/pay-button.tsx"use client"; import { useState } from "react"; export function PayButton({ orderId }: { orderId: string }) {  const [busy, setBusy] = useState(false);  const [error, setError] = useState<string | null>(null);   async function pay() {    setBusy(true);    setError(null);    try {      const res = await fetch("/api/checkout", {        method: "POST",        headers: { "Content-Type": "application/json" },        body: JSON.stringify({ orderId }),      });      if (!res.ok) throw new Error("checkout failed");      const { checkoutUrl } = await res.json();      window.location.assign(checkoutUrl); // https://pay.terrawallet.us/c/pi_...    } catch {      setError("Checkout is not available right now. Please try again.");      setBusy(false);    }  }   return (    <>      <button onClick={pay} disabled={busy}>{busy ? "Opening checkout..." : "Pay with crypto"}</button>      {error && <p role="alert">{error}</p>}    </>  );} // Fulfil the order only from a verified payment_intent.succeeded webhook, never from the success_url redirect.// See the "webhooks" sample for Next.js.

Subscriptions

// Terra Pay subscriptions in Next.js (App Router): subscribe the signed-in user to a plan, and grant or remove// access from verified subscription webhooks.// Preview: the Terra API is in early access and may change before launch.// v1 subscriptions are "pay each period": Terra emails a renewal invoice each period and the customer pays it// from their own wallet. Nothing is ever taken from a wallet automatically.// Create the plan once (see the node sample) and set TERRA_PLAN_ID=plan_... in your environment. // File: app/api/subscribe/route.tsimport { NextResponse } from "next/server"; declare function currentUser(): Promise<{ id: string; email: string } | null>; // your auth export async function POST() {  const user = await currentUser();  if (!user) return NextResponse.json({ error: "SIGN_IN_REQUIRED" }, { status: 401 });   const res = await fetch("https://terrawallet.us/api/v1/subscriptions", {    method: "POST",    headers: {      Authorization: `Bearer ${process.env.TERRA_SECRET_KEY}`,      "Content-Type": "application/json",      "Idempotency-Key": `subscribe-${user.id}-${process.env.TERRA_PLAN_ID}`,    },    body: JSON.stringify({ plan: process.env.TERRA_PLAN_ID, customer_email: user.email }),  });  const subscription = await res.json();  if (!res.ok) {    console.error("Terra API error", res.status, subscription?.error?.code, subscription?.error?.requestId);    return NextResponse.json({ error: "SUBSCRIBE_UNAVAILABLE" }, { status: 502 });  }  // Save subscription.id with the user. The first invoice is emailed to the customer.  return NextResponse.json({ subscriptionId: subscription.id, status: subscription.status });} // No sign-in on your side? Share the plan's subscription link instead://   https://pay.terrawallet.us/s/plan_... // File: app/api/webhooks/terra/route.ts (subscription events)// Verify the signature first: see the "webhooks" sample for verifyTerraSignature.declare function verifyTerraSignature(rawBody: string, header: string | null, secret: string | undefined): boolean;declare function alreadyHandled(eventId: string): Promise<boolean>;declare function setAccess(event: { id: string; type: string }, active: boolean): Promise<void>; export async function handleSubscriptionWebhook(req: Request) {  const raw = await req.text();  if (!verifyTerraSignature(raw, req.headers.get("Terra-Signature"), process.env.TERRA_WEBHOOK_SECRET)) {    return new Response("invalid signature", { status: 400 });  }  const event = JSON.parse(raw) as { id: string; type: string };  if (await alreadyHandled(event.id)) return new Response(null, { status: 200 });   switch (event.type) {    case "subscription.created":    case "subscription.renewed":      await setAccess(event, true);      break;    case "subscription.past_due":    case "subscription.canceled":      await setAccess(event, false);      break;    case "subscription.payment_failed":      // Remind the customer to pay their renewal invoice.      break;  }  return new Response(null, { status: 200 });}

Webhooks

// Terra webhooks in Next.js (App Router): verify the Terra-Signature header on the raw body, handle each event// once, and answer fast.// Preview: the Terra API is in early access and may change before launch.// Set TERRA_WEBHOOK_SECRET (whsec_..., shown once when you registered the endpoint) in your server environment. // File: app/api/webhooks/terra/route.tsimport { createHmac, timingSafeEqual } from "node:crypto"; export const runtime = "nodejs"; // node:cryptoexport const dynamic = "force-dynamic"; const TOLERANCE_SECONDS = 5 * 60; function verifyTerraSignature(rawBody: string, header: string | null, secret: string | undefined): boolean {  if (!header || header.length > 1024 || !secret) return false;  let timestamp: string | null = null;  const signatures: string[] = [];  for (const part of header.split(",")) {    const i = part.indexOf("=");    if (i < 0) continue;    const key = part.slice(0, i).trim();    const value = part.slice(i + 1).trim();    if (key === "t") timestamp = value;    else if (key === "v1") signatures.push(value);  }  if (!timestamp || !/^\d+$/.test(timestamp) || signatures.length === 0) return false;  if (Math.abs(Date.now() / 1000 - Number(timestamp)) > TOLERANCE_SECONDS) return false;  const expected = createHmac("sha256", secret).update(`${timestamp}.${rawBody}`).digest();  return signatures.some((sig) => {    if (!/^[0-a-f]+$/i.test(sig)) return false;    const given = Buffer.from(sig, "hex");    return given.length === expected.length && timingSafeEqual(given, expected);  });} // Your own storage and job queue.declare function markHandled(eventId: string): Promise<boolean>; // false if the id was already storeddeclare function enqueue(event: { id: string; type: string }): Promise<void>; export async function POST(req: Request) {  const raw = await req.text(); // the exact body Terra signed; do not use req.json() first  if (!verifyTerraSignature(raw, req.headers.get("Terra-Signature"), process.env.TERRA_WEBHOOK_SECRET)) {    return new Response("invalid signature", { status: 400 });  }  const event = JSON.parse(raw) as { id: string; type: string };   // Deliveries can repeat and arrive out of order: handle each event id once.  if (!(await markHandled(event.id))) return new Response(null, { status: 200 });   // Answer within seconds; do the real work (fulfilment, emails) in a background job. Before shipping goods,  // confirm the payment's current state with the API using your secret key.  await enqueue(event);  return new Response(null, { status: 200 });}