Skip to content

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

1 watching

Forks

Latest commit

 

History

34 Commits

Folders and files

Repository files navigation

Solana Sponsorship SDK

A TypeScript SDK for handling Solana transaction sponsorship, built with Bun.

Installation

bun add @solana/kit @solana-program/system @zerodev/solana-sponsorship-sdk

Quick Start

import { generateKeyPairSigner, lamports } from "@solana/kit";
import { getTransferSolInstruction } from "@solana-program/system";
import { createZeroDevSponsorClient } from "@zerodev/solana-sponsorship-sdk";

async function main() {
  const client = createZeroDevSponsorClient({
    projectId: PROJECT_ID,
    network: "devnet",
  });

  const from = await generateKeyPairSigner();
  const to = await generateKeyPairSigner();

  // Standard `@solana-program/system` instruction — anything `IInstruction`
  // works here.
  const transferIx = getTransferSolInstruction({
    source: from,
    destination: to.address,
    amount: lamports(0n),
  });
  const { signature, confirmation } = await client.sponsorAndSend({
    instructions: [transferIx],
    signers: [from],
  });

  console.log(
    `Sponsored & ${confirmation?.kind ?? "broadcast"}: ` +
      `https://explorer.solana.com/tx/${signature}?cluster=devnet`,
  );
}

Usage with Privy

Privy manages the wallet for you and signs raw wire bytes. Pass an externalSign hook to client.sponsorAndSend — the SDK builds the transaction, hands Privy the wire-encoded bytes to sign, and ships the result through the sponsor:

import { createZeroDevSponsorClient } from "@zerodev/solana-sponsorship-sdk";
import { useStandardSignTransaction } from "@privy-io/react-auth/solana";

const client = createZeroDevSponsorClient({
  projectId: PROJECT_ID,
  network: "devnet",
});

// Inside your React component:
const { signTransaction } = useStandardSignTransaction();

const { signature, confirmation } = await client.sponsorAndSend({
  instructions: [transferIx],
  externalSign: async (transaction) => {
    return signTransaction({
      transaction,
      wallet,
    });
  },
});

See examples/sponsorship-with-privy.ts for a complete example.

Usage with Dynamic

Dynamic's Solana signer operates on @solana/web3.js transactions. Keep that interop at the externalSign boundary: let this SDK build and sponsor the @solana/kit transaction, then deserialize the wire bytes for Dynamic to sign. Use signTransaction here, not signAndSendTransaction, because ZeroDev broadcasts the sponsored transaction.

import { isSolanaWallet } from "@dynamic-labs/solana";
import { useDynamicContext } from "@dynamic-labs/sdk-react-core";
import { address, createNoopSigner, lamports } from "@solana/kit";
import { getTransferSolInstruction } from "@solana-program/system";
import { createZeroDevSponsorClient } from "@zerodev/solana-sponsorship-sdk";

const { primaryWallet } = useDynamicContext();
if (!primaryWallet || !isSolanaWallet(primaryWallet)) {
  throw new Error("No Solana wallet");
}

const client = createZeroDevSponsorClient({
  projectId: PROJECT_ID,
  network: "mainnet",
  solanaRpcUrl: "https://api.mainnet-beta.solana.com",
});

const signer = await primaryWallet.getSigner();
const transferIx = getTransferSolInstruction({
  source: createNoopSigner(address(primaryWallet.address)),
  destination: address(recipientAddress),
  amount: lamports(5_000n),
});

const { signature, confirmation } = await client.sponsorAndSend({
  instructions: [transferIx],
  externalSign: async (wireBytes) => {
    const { VersionedTransaction } = await import("@solana/web3.js");
    const transaction = VersionedTransaction.deserialize(wireBytes);
    const signedTransaction = await signer.signTransaction(transaction);
    return signedTransaction.serialize();
  },
});

Install @solana/web3.js in apps that do not already get it from Dynamic.

See examples/sponsorship-with-dynamic.ts for a complete example.

Passkeys & Session Keys

The SDK ships a complete browser-passkey flow on top of a sponsored swig wallet. One client object, one PasskeyAccount per credential:

  • Passkey-controlled wallets — the user holds the only private key.
  • Session keys — short-lived Ed25519 delegates that skip WebAuthn prompts for high-frequency UX.
  • Sponsored every step.

All snippets below run in a browser. For Node / CI use, see Testing without a browser.

Concepts

Term What it is
Credential {credentialId, publicKeyBytes, rpId} from a registered WebAuthn passkey. publicKeyBytes is the 33-byte compressed P-256 pubkey; extract via extractCompressedP256.
PasskeyAccount A swig wallet whose root authorities are bound to a passkey. Returned by client.passkey.createAccount. Holds both a session-authority role and a direct-passkey role on the same swig — the SDK routes by signWith at send time.
SessionKey Plain KeyPairSigner minted by the SDK and registered as a delegate on the account, expiring at a fixed slot. Create via account.createSession.
MAX_SESSION_SLOTS Swig's hard cap on session duration (216_000n ≈ 24h at 400 ms/slot).

Step 1 — Register a passkey

The SDK doesn't dictate which passkey server you use; it just needs the credentialId, the 33-byte compressed P-256 pubkey, and the rpId you registered against. To pull the compressed pubkey out of a WebAuthn registration response:

import { extractCompressedP256 } from "@zerodev/solana-sponsorship-sdk";

const cred = (await navigator.credentials.create({
  publicKey: createOptions,
})) as PublicKeyCredential;
const publicKeyBytes = extractCompressedP256(cred); // 33-byte compressed P-256

const credential = {
  credentialId: new Uint8Array(cred.rawId),
  publicKeyBytes,
  rpId: createOptions.rp.id ?? "localhost",
};

extractCompressedP256 enforces ES256 (alg = -7) — the only curve the on-chain swig verifier accepts.

Step 2 — Create the client and the account

import { createZeroDevSponsorClient } from "@zerodev/solana-sponsorship-sdk";

const client = createZeroDevSponsorClient({
  projectId: PROJECT_ID,
  network: "devnet", // or "mainnet"
});

// One account per credential. Default authorities cover both signing paths.
const { account } = await client.passkey.createAccount({
  credential, // {credentialId, publicKeyBytes, rpId}
  // authorities: ['session', 'direct']  // default — explicit if you want
});

// account.address       — the swig PDA
// account.depositAddress — the inner address; this is where SOL lives

Or do create + first session in one orchestration:

const result = await client.passkey.createAccountWithSession({
  credential,
  sessionDurationSlots: 5_000n, // ~33 min on mainnet (400 ms/slot)
});

if (result.kind === "wallet_failed") {
  // The wallet creation transaction failed on-chain. The swig PDA does
  // not exist. result.walletSignature/walletAddress identify the
  // attempted broadcast; result.walletError carries the chain error.
  throw result.walletError;
}
if (result.kind === "session_failed") {
  // The wallet exists but session bootstrap failed. result.account is
  // usable; retry via account.createSession.
  console.warn(result.sessionError);
}
// result.kind === "ok" — narrow and use account + session.
const { account, session } = result;

Step 3 — Send session-signed transactions

Session-signed transactions skip WebAuthn prompts and pay no SOL (sponsor covers it).

const { signature } = await account.transferSol({
  to: recipientAddress,
  lamports: 100_000n,
  signWith: session,
});

const tokenResult = await account.transferToken({
  mint,
  to: recipientAddress,
  amount: 1_000_000n,
  decimals: 6,
  signWith: session,
});

account.send({signWith, instructions}) is the general form for multi-instruction sends; account.transferSol and account.transferToken are single-call conveniences.

Step 4 — Send passkey-signed transactions (no session, prompts WebAuthn)

For high-value or admin operations, sign each tx with the passkey directly. Same account, just different signWith:

const { signature } = await account.transferSol({
  to: recipientAddress,
  lamports: 100_000n,
  signWith: { kind: "passkey" }, // triggers WebAuthn prompt
});

The PasskeySigner is auto-resolved from the same per-credential cache that account.createSession uses — primed by client.passkey.createAccount / client.passkey.attachAccount. Pass an explicit { kind: "passkey", signer } only when you need to override the cached entry or when the cache cannot be primed.

This works because client.passkey.createAccount creates ONE swig wallet with BOTH authorities (session and direct) by default. If you want a session-only or direct-only account, pass authorities: ['session'] or authorities: ['direct'].

Step 5 — Persist and rehydrate sessions

// Serialize for IndexedDB / localStorage.
const blob = await account.exportSession(session);

// After reload:
const account = await client.passkey.attachAccount({
  walletAddress,
  credential,
});
const session = await account.importSession(blob);
// throws SessionExpiredError if past expiresAtSlot
// throws WrongAccountError if the blob was bound to a different account
// throws WrongNetworkError if the blob was minted on a different chainId

Testing without a browser

@zerodev/solana-sponsorship-sdk/testing exports a software passkey signer that signs with a held-in-memory P-256 keypair, no WebAuthn ceremony required. Use it from Node, Vitest, Playwright fixtures, or anywhere navigator.credentials is not available:

import { createSoftwarePasskeySigner } from "@zerodev/solana-sponsorship-sdk/testing";

const signer = await createSoftwarePasskeySigner({ rpId: "localhost" });

// `signer` is a `PasskeySigner` — drop into the same client.passkey.* flows
// in place of the browser-resolved signer.

End-to-end reference

The full canonical flow — register → account → session key → session-signed transfer → direct passkey-signed transfer — lives in solana-passkey-e2e. The Playwright real mode spec drives the same code path against a local validator and a live passkey server, so it's the closest thing to a runnable production example.

Documentation

Core Concepts

  • Sponsorship RPC: Create and manage transaction sponsorship
  • Fee Payer: Get and set the sponsor's fee payer
  • Transaction Signing: Handle transaction signing with sponsored fee payer
  • Utils: Helper functions for common operations

API Reference

createSponsorshipRpc(config: SponsorshipConfig)

Creates a sponsorship RPC client for interacting with the sponsorship server.

sponsorTransaction(rpc, message)

Sponsors a transaction and returns a SponsorshipResponse. response.signature is the broadcast transaction signature, and response.message is the sponsored base64 wire transaction returned by the server.

getFeePayer()

Gets the sponsor's fee payer address from the sponsorship server.

Passkey API

Symbol Purpose
createZeroDevSponsorClient(params) High-level sponsor client with cached fee-payer lookup, sponsorAndSend, and the client.passkey.* surface.
client.passkey.createAccount({credential, authorities?, walletId?, confirm?}) Mint a swig wallet with the requested authorities. Default is ['session', 'direct'] — one swig handling both signing paths. confirm: false skips wallet confirmation and returns a lazy account whose depositAddress resolves on first use.
client.passkey.createAccountWithSession({credential, authorities?, sessionDurationSlots, walletConfirmation?, sessionConfirmation?, walletId?}) Create the account and its first session in one orchestrated flow. Tagged-union result: {kind: 'ok' | 'session_failed' | 'wallet_failed', ...}. wallet_failed carries walletError: WalletConfirmationError with no account (the PDA doesn't exist); session_failed carries the live account so the caller can retry via account.createSession.
client.passkey.attachAccount({walletAddress, credential}) Rehydrate an existing account after a page reload. Verifies on-chain that the swig has a role for the supplied credential.
account.createSession({durationSlots, passkeySigner?, confirm?}) Delegate a fresh KeyPairSigner as a time-bound authority. passkeySigner is auto-resolved from the client's internal cache when omitted.
account.exportSession(session) / account.importSession(blob) Async session persistence helpers. Blobs are scoped to this account and chainId.
account.send({signWith, instructions, confirm?}) Route through the right swig role (session, direct passkey, or arbitrary ed25519) based on signWith.
account.transferSol({to, lamports, signWith, confirm?}) Single-call convenience for SOL transfer from the account's depositAddress.
account.transferToken({mint, to, amount, decimals, signWith, confirm?, tokenProgram?}) Single-call convenience for SPL Token / Token-2022 transfers. Derives source/destination ATAs and prepends idempotent destination ATA creation.
passkey.createBrowserPasskeySigner({credentialId, publicKeyBytes, rpId}) Pure helper — build a PasskeySigner from a registered credential. Not normally needed (cached by the client).
passkey.computePasskeyChallenge(message) SHA-256 of the wire-message preimage used as the WebAuthn challenge.
extractCompressedP256(cred) / coseToCompressedP256(cose) / spkiToCompressedP256(spki) Pull a 33-byte compressed P-256 pubkey from various input formats.
passkey.MAX_SESSION_SLOTS 216_000n — swig's hard cap on session duration.
passkey.SessionExpiredError, passkey.SessionBootstrapError, passkey.WalletConfirmationError, passkey.WrongAccountError, passkey.WrongNetworkError, passkey.MalformedSessionBlobError, passkey.UnexportableSessionError, passkey.SessionConfirmationError, passkey.AttachAccountMismatchError, passkey.CredentialMismatchError Typed errors — see Errors.

Power users who want to compose their own swig-authorized transactions can also import getSwigTransferSolInstruction, getSwigTransferTokenInstruction, and getSwigCreateAssociatedTokenIdempotentInstruction directly — these are the underlying builders that the account convenience methods wrap.

Testing helpers (@zerodev/solana-sponsorship-sdk/testing)

Symbol Purpose
createSoftwarePasskeySigner({ rpId }) In-memory P-256 PasskeySigner for Node tests; no WebAuthn ceremony.
buildClientDataJSON, buildAuthenticatorData Low-level helpers for constructing canonical WebAuthn assertion components in fixtures.

License

MIT License

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages