> ## Documentation Index
> Fetch the complete documentation index at: https://solana.com/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> This page is part of the Solana developer documentation at https://solana.com/developers/docs. Append `.md` to any docs URL, or send `Accept: text/markdown`, to get the page as Markdown.
> Index of all pages: https://solana.com/llms.txt. Per-section indexes such as https://solana.com/developers/docs/payments/llms.txt are smaller; prefer them when working on one task.
> Coding agents: install the official Solana skill for current APIs and conventions with `npx skills add https://github.com/solana-foundation/solana-dev-skill` (also served at https://solana.com/SKILL.md).
> Code in the cookbook and task pages comes from tested example files. Prefer it over writing API calls from memory.

# Solana Pay

> Generate Solana Pay URLs, QR codes, and payment transactions

<Warning>
  **Commerce Kit is no longer maintained**

  Commerce Kit packages no longer receive updates or fixes. For new payment
  integrations, use [Solana Pay](/developers/docs/tools/solana-pay).
</Warning>

The `@solana-commerce/solana-pay` package provides complete
[Solana Pay](/developers/docs/tools/solana-pay) functionality for building
payment experiences, compatible with the
[`@solana/kit`](https://github.com/anza-xyz/kit) library. It handles URL
encoding/parsing, QR code generation with custom styling, and transaction
construction for both SOL and SPL token transfers.

## Installation

```bash
npm install @solana-commerce/solana-pay
```

## URL Encoding

### `encodeURL(fields)`

Creates a Solana Pay URL that conforms to the
[Solana Pay specification](/developers/docs/tools/solana-pay/specification/version1-1).
This function generates `solana:` protocol URLs that can be shared as links or
encoded as QR codes for mobile wallets to scan.

#### Parameters

- **`fields`** (`TransferRequestURLFields | TransactionRequestURLFields`) -
  Configuration for the payment URL

The transfer request fields at a glance (details below):

| Parameter   | Type                     | Description                                                        |
| ----------- | ------------------------ | ------------------------------------------------------------------ |
| `recipient` | `Address`                | Merchant wallet address (required)                                 |
| `amount`    | `bigint`                 | Amount scaled by 1e9 (1 SOL = `1_000_000_000n`), whatever the mint |
| `splToken`  | `Address`                | SPL token mint address (omit for SOL)                              |
| `reference` | `Address` or `Address[]` | Unique reference(s) for tracking payments                          |
| `label`     | `string`                 | Merchant name shown in wallet                                      |
| `message`   | `string`                 | Message shown before payment                                       |
| `memo`      | `string`                 | Onchain memo attached to transaction                               |

#### `TransferRequestURLFields`

Used for simple payment requests (direct transfers):

- **`recipient`** (`Address`, required) - The merchant's wallet address
  (base58-encoded public key) that will receive the payment. Can be a string or
  `Address` type from `@solana/kit`.

- **`amount`** (`bigint`, optional) - Payment amount in **lamports** (atomic
  units). For SOL, 1 SOL = 1,000,000,000 lamports (9 decimals). `encodeURL`
  always divides by 1e9 when it writes the `amount` query parameter, whatever
  the token's decimals (as of `@solana-commerce/solana-pay@0.1.1`). For a
  6-decimal token such as USDC, pass the amount scaled to 9 decimals: 1 USDC =
  `1_000_000_000n`, so 25 USDC = `25_000_000_000n`. Passing the token's atomic
  units (`25_000_000n`) produces `amount=0.025`, and the wallet requests 0.025
  USDC. If you need a different scale, use `encodeURL` from `@solana/pay`, whose
  `amount` is a decimal number.

- **`splToken`** (`Address`, optional) - The SPL token mint address for token
  payments. If omitted, the payment is assumed to be in SOL.

- **`reference`** (`Address | Address[]`, optional) - Unique reference
  address(es) used for tracking payments. Generate using
  `generateKeyPairSigner().address`. The reference is added as a read-only
  account to the transaction, allowing you to query for payments using this
  reference.

- **`label`** (`string`, optional) - Human-readable merchant or app name
  displayed to the user in their wallet (e.g., "Coffee Shop", "My Store").

- **`message`** (`string`, optional) - Message displayed to the user before
  payment (e.g., "Thanks for your purchase!", "Tip for great service").

- **`memo`** (`string`, optional) - Onchain memo attached to the transaction.
  Stored permanently on Solana. Useful for order IDs, invoice numbers, or other
  payment metadata.

#### `TransactionRequestURLFields`

Used for complex payment requests (including instructions):

- **`link`** (`URL`, required) - The link to the transaction
  ([`Link`](/developers/docs/tools/solana-pay/specification/version1-1#link)). If the URL
  contains query parameters, it must be URL-encoded.

- **`label`** (`string`, optional) - Human-readable merchant or app name
  displayed to the user in their wallet (e.g., "Coffee Shop", "My Store").

- **`message`** (`string`, optional) - Message displayed to the user before
  payment (e.g., "Thanks for your purchase!", "Tip for great service").

#### How It Works

The function performs several operations to construct a valid Solana Pay URL:

1. **Protocol Prefix** - Creates a URL with the `solana:` protocol scheme
   (similar to `mailto:` or `bitcoin:`)

2. **Recipient as Pathname** - Uses the recipient's base58 address as the URL
   pathname (e.g., `solana:merchantWalletAddress123...`)

3. **Amount Conversion** - Converts the bigint lamport amount to a decimal
   string representation without floating-point precision issues.

4. **Query Parameters** - Appends all optional fields and references as
   URL-encoded query parameters

#### Returns

`URL` object with the `solana:` protocol that can be:

- Converted to a string with `.toString()` for sharing
- Passed to `createQR()` for QR code generation
- Used directly in anchor tags: `<a href={url.toString()}>Pay with Solana</a>`

#### Example: Basic Payment

```typescript
import { encodeURL } from "@solana-commerce/solana-pay";
import { address } from "@solana/kit";

const url = encodeURL({
  recipient: address("merchantWalletAddress123..."),
  amount: 100000000n, // 0.1 SOL (100 million lamports)
  label: "Coffee Shop",
  message: "Thanks for your order!"
});

console.log(url.toString());
// solana:merchantWalletAddress123...?amount=0.1&label=Coffee+Shop&message=Thanks+for+your+order%21
```

#### Example: SPL Token Payment

```typescript
import { encodeURL } from "@solana-commerce/solana-pay";
import { address } from "@solana/kit";

const usdcMint = address("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v");

const url = encodeURL({
  recipient: address("merchantWallet..."),
  amount: 25_000_000_000n, // 25 USDC (encodeURL always divides by 1e9 -> amount=25)
  splToken: usdcMint,
  label: "USDC Payment",
  message: "Pay with USDC stablecoin"
});
```

#### Example: Payment with Tracking

Use references to identify specific payments:

```typescript
import { encodeURL } from "@solana-commerce/solana-pay";
import { address, generateKeyPairSigner } from "@solana/kit";

// Generate unique reference for this order
const orderReference = (await generateKeyPairSigner()).address;

const url = encodeURL({
  recipient: address("merchantWallet..."),
  amount: 500000000n, // 0.5 SOL
  reference: orderReference,
  memo: `Order-${Date.now()}`, // Onchain memo
  label: "E-commerce Store",
  message: "Complete your purchase"
});

// Later, query the blockchain for transactions containing this reference
// to verify payment was made
```

## URL Parsing

### `parseURL(url)`

Decodes and validates a Solana Pay URL, extracting all payment parameters. This
function performs validation and converts amounts from decimal strings back to
bigint lamports.

#### Parameters

- **`url`** (`string | URL`) - The Solana Pay URL to parse. Can be a string or
  URL object.

#### Returns

A parsed `TransferRequestURLFields` or `TransactionRequestURLFields` object.

#### Example: Parse and Validate

```typescript
import { parseURL, ParseURLError } from "@solana-commerce/solana-pay";

try {
  const parsed = parseURL(
    "solana:merchant123...?amount=1.5&label=Store&reference=ref123..."
  );

  console.log(parsed.recipient); // Address object
  console.log(parsed.amount); // 1500000000n (1.5 SOL in lamports)
  console.log(parsed.label); // "Store"
  console.log(parsed.reference); // [Address]

  // Convert back to human-readable format
  const solAmount = Number(parsed.amount) / 1e9;
  console.log(`Payment of ${solAmount} SOL`);
} catch (error) {
  if (error instanceof ParseURLError) {
    console.error("Invalid Solana Pay URL:", error.message);
  }
}
```

#### Example: URL Validator Function

```typescript
import { parseURL, ParseURLError } from "@solana-commerce/solana-pay";

function validateSolanaPayURL(urlString: string): {
  valid: boolean;
  error?: string;
  data?: any;
} {
  try {
    const parsed = parseURL(urlString);
    // Additional business logic validation
    if (parsed.splToken) {
      return {
        valid: false,
        error: "Only SOL payments are supported"
      };
    }
    if (parsed.amount && parsed.amount < 1000000n) {
      return {
        valid: false,
        error: "Amount too small (minimum 0.001 SOL)"
      };
    }
    // etc.

    return {
      valid: true,
      data: {
        recipient: parsed.recipient.toString(),
        amount: parsed.amount ? Number(parsed.amount) / 1e9 : undefined,
        token: parsed.splToken?.toString()
      }
    };
  } catch (error) {
    return {
      valid: false,
      error: error instanceof ParseURLError ? error.message : "Unknown error"
    };
  }
}
```

---

## QR Code Generation

### `createQR(url, size, background, color)`

Generates an SVG QR code optimized for Solana Pay URLs. The function produces
styled, high-quality QR codes with rounded corners and customizable colors.

#### Parameters

- **`url`** (`string | URL`) - The Solana Pay URL to encode in the QR code
- **`size`** (`number`, default: `512`) - Width and height in pixels
- **`background`** (`string`, default: `'white'`) - Background color (hex or
  named color). Should be light for wallet compatibility.
- **`color`** (`string`, default: `'black'`) - Foreground/dot color (hex or
  named color). Should be dark for contrast.

_Altenatively, you can use `createStyledQRCode(url, options)` for more control
over the QR code styling (width, margin, colors, dot style, corner style, logo,
logo size, logo background color, logo margin)._

#### Returns

`Promise<string>` - SVG markup as a string that can be:

- Set as an `img` element src through a data URL:
  ``<img src={`data:image/svg+xml;utf8,${encodeURIComponent(qrCode)}`} />``
- Saved to a file

#### Example

```typescript
import { createQR, encodeURL } from "@solana-commerce/solana-pay";
import { address } from "@solana/kit";

async function generatePaymentQR() {
  const url = encodeURL({
    recipient: address("merchant..."),
    amount: 100000000n, // 0.1 SOL
    label: "Coffee Shop"
  });

  const qrCode = await createQR(
    url.toString(),
    400, // 400x400 pixels
    "white", // White background
    "black" // Black foreground
  );

  // Display in browser
  document.getElementById("qr-container")!.innerHTML = qrCode;

  // Or use as image source (wrap the SVG markup in a data URL)
  (document.getElementById("qr-image") as HTMLImageElement).src =
    `data:image/svg+xml;utf8,${encodeURIComponent(qrCode)}`;
}
```

#### Example: Branded QR Code

```typescript
import { createStyledQRCode, encodeURL } from "@solana-commerce/solana-pay";
import { address } from "@solana/kit";

async function createBrandedQR() {
  const url = encodeURL({
    recipient: address("merchant..."),
    amount: 25_000_000_000n, // 25 USDC (encodeURL always divides by 1e9 -> amount=25)
    splToken: address("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"),
    label: "Coffee Shop",
    message: "Scan to pay with USDC"
  });

  const qr = await createStyledQRCode(url.toString(), {
    width: 600,
    margin: 3,
    color: {
      dark: "#9945FF", // Solana purple
      light: "#F5F5DC" // Beige
    },
    errorCorrectionLevel: "H", // Higher correction for logo
    dotStyle: "dots", // Circular dots
    cornerStyle: "extra-rounded",
    logo: "/coffee-logo.png", // Your logo
    logoSize: 120,
    logoBackgroundColor: "#FFFFFF", // White padding behind logo
    logoMargin: 10
  });

  return qr; // SVG string
}
```

## Transaction Building

### `createTransfer(rpc, sender, fields)`

Builds a Solana transaction message for an SPL token payment transfer. It
constructs the transfer, optional memo, and reference instructions, sets a
blockhash lifetime from the RPC client and returns an unsigned transaction
message (type `TransactionMessageWithBlockhashLifetime`, compatible with Solana
Kit). You must set a fee payer before signing. In
`@solana-commerce/solana-pay@0.1.1` it builds a correct transfer only for
Token-2022 mints (see the warning below).

#### Parameters

- **`rpc`** (`Rpc<SolanaRpcApi>`) - Solana RPC client from `@solana/kit`. Create
  with `createSolanaRpc(rpcUrl)`.

- **`sender`** (`Address`) - The payer's wallet address. Must be a funded
  account that will sign the transaction.

- **`fields`** (`CreateTransferFields`) - Transfer configuration:
  - `recipient` (`Address`, required) - Destination wallet address
  - `amount` (`bigint`, required) - Amount in lamports (SOL) or token atomic
    units (SPL)
  - `splToken` (`Address`, optional) - SPL token mint address. If omitted,
    creates SOL transfer.
  - `reference` (`Address | Address[]`, optional) - Reference address(es) for
    tracking
  - `memo` (`string`, optional) - Onchain memo text

#### Returns

`Promise<TransactionMessageWithBlockhashLifetime>` - Complete transaction
message with:

- Version 0 format (supports address lookup tables)
- Blockhash lifetime (the transaction expires after 150 blocks, about 30
  seconds at 200ms slots)
- All necessary instructions (transfer + optional memo) for SPL token payments
- No fee payer: call `setTransactionMessageFeePayer` (or
  `setTransactionMessageFeePayerSigner`) before signing and sending

<Warning>
  As of `@solana-commerce/solana-pay@0.1.1`, `createTransfer` without `splToken`
  does **not** build a SOL transfer. It returns a single Token program
  `Transfer` instruction and silently drops `memo` and `reference`, so the
  transaction fails onchain with `IncorrectProgramId`. For SOL, build the
  instructions yourself (see the example below) or use `createTransfer` from
  `@solana/pay`.

  SPL token transfers are only correct for Token-2022 mints. For classic Token
  program mints such as USDC and USDT, `createTransfer` emits a Token-2022
  `TransferChecked` instruction and the transaction fails with
  `IncorrectProgramId`. Build those transfers yourself (see the USDC example
  below).
</Warning>

<Note>
  `createTransfer` does not create the recipient's associated token account.
  For an SPL token payment, the recipient's token account for that mint must
  already exist before you send, or the transfer fails.
</Note>

#### Error Handling

Throws `CreateTransferError` with specific messages:

- `"sender not found"` - Sender account doesn't exist
- `"recipient not found"` - Recipient account doesn't exist

#### Example: SOL Payment

Build the System program transfer, a memo, and the reference account yourself
until `createTransfer` handles SOL correctly:

```typescript
import {
  address,
  appendTransactionMessageInstructions,
  createSolanaRpc,
  createTransactionMessage,
  generateKeyPairSigner,
  lamports,
  pipe,
  setTransactionMessageFeePayerSigner,
  setTransactionMessageLifetimeUsingBlockhash,
  AccountRole
} from "@solana/kit";
import { getTransferSolInstruction } from "@solana-program/system";
import { getAddMemoInstruction } from "@solana-program/memo";

const rpc = createSolanaRpc("https://api.mainnet.solana.com");
const sender = await generateKeyPairSigner(); // in a browser, use the wallet's signer
const reference = (await generateKeyPairSigner()).address;

const transfer = getTransferSolInstruction({
  source: sender,
  destination: address("merchant-wallet-address"),
  amount: lamports(100_000_000n) // 0.1 SOL
});

const { value: latestBlockhash } = await rpc.getLatestBlockhash().send();

const txMessage = pipe(
  createTransactionMessage({ version: 0 }),
  (tx) => setTransactionMessageFeePayerSigner(sender, tx),
  (tx) => setTransactionMessageLifetimeUsingBlockhash(latestBlockhash, tx),
  (tx) =>
    appendTransactionMessageInstructions(
      [
        {
          ...transfer,
          // The reference is a read-only account on the transfer instruction
          accounts: [
            ...transfer.accounts,
            { address: reference, role: AccountRole.READONLY }
          ]
        },
        getAddMemoInstruction({ memo: "Coffee purchase" })
      ],
      tx
    )
);

// Sign with signTransactionMessageWithSigners and send as usual.
```

With a Kit client that has a payer and RPC plugins
([Kit client](/developers/docs/frontend/client)), the same SOL payment is shorter, because
the client sets the fee payer and lifetime and sends the transaction:

```typescript
import { address } from "@solana/kit";
import { getTransferSolInstruction } from "@solana-program/system";
import { getAddMemoInstruction } from "@solana-program/memo";

// `client.payer` is the sender's TransactionSigner
const instructions = [
  getTransferSolInstruction({
    source: client.payer,
    destination: address(MERCHANT_WALLET_ADDRESS),
    amount: 100_000_000n // 0.1 SOL in lamports
  }),
  getAddMemoInstruction({ memo: "Coffee purchase" })
];

await client.sendTransaction(instructions);
```

#### Example: USDC Payment

USDC uses the classic Token program, so build the `transferChecked`
instruction, the memo, and the reference account yourself. The recipient's USDC
token account must already exist:

```typescript
import { AccountRole, address } from "@solana/kit";
import {
  findAssociatedTokenPda,
  getTransferCheckedInstruction,
  TOKEN_PROGRAM_ADDRESS
} from "@solana-program/token";
import { getAddMemoInstruction } from "@solana-program/memo";

const usdcMint = address("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v");
const merchant = address(MERCHANT_WALLET_ADDRESS);
// `sender` is the payer's TransactionSigner, `reference` a unique address
const [source] = await findAssociatedTokenPda({
  owner: sender.address,
  mint: usdcMint,
  tokenProgram: TOKEN_PROGRAM_ADDRESS
});
const [destination] = await findAssociatedTokenPda({
  owner: merchant,
  mint: usdcMint,
  tokenProgram: TOKEN_PROGRAM_ADDRESS
});

const transfer = getTransferCheckedInstruction({
  source,
  mint: usdcMint,
  destination,
  authority: sender,
  amount: 25_000_000n, // 25 USDC (6 decimals)
  decimals: 6
});

const instructions = [
  getAddMemoInstruction({ memo: "Order #12345" }),
  {
    ...transfer,
    // The reference is a read-only account on the transfer instruction
    accounts: [
      ...transfer.accounts,
      { address: reference, role: AccountRole.READONLY }
    ]
  }
];

// Add them to a transaction message as in the SOL example, or pass them to
// client.sendTransaction(instructions).
```
