npm package: @solforge/qr-tx-encoder
Description: Encode Solana transactions into QR-friendly payloads for dApps
Author: nitishxyz
Latest version: 0.0.1

# @solforge/qr-tx-encoder

Encode Solana transactions into QR-friendly payloads for dApps to display to users.

Part of the [Solana QR Transaction Standard](https://github.com/nitishxyz/solforge-qr-sdk) - an open standard for transferring Solana transactions between dApps and wallets without extensions or WalletConnect.

## Installation

```bash
bun add @solforge/qr-tx-encoder
```

## Quick Start

```typescript
import { encodeTransaction } from '@solforge/qr-tx-encoder';
import { Transaction, SystemProgram, PublicKey, LAMPORTS_PER_SOL } from '@solana/web3.js';

// Create a simple SOL transfer transaction
const transaction = new Transaction().add(
  SystemProgram.transfer({
    fromPubkey: new PublicKey('sender-pubkey'),
    toPubkey: new PublicKey('recipient-pubkey'),
    lamports: 0.1 * LAMPORTS_PER_SOL
  })
);

// Encode for QR display
const result = await encodeTransaction(transaction, {
  sessionId: 'unique-session-id',
  network: 'mainnet-beta',
  origin: 'https://your-dapp.com',
  description: 'Send 0.1 SOL to friend',
  requiredSigners: ['sender-pubkey'],
  signatureReturnUrl: 'https://your-dapp.com/api/sessions/:id/signature'
});

// Display QR frames (animated QR for large transactions)
result.frames.forEach((frame, index) => {
  console.log(`Frame ${index + 1}/${result.totalFrames}: ${frame}`);
});
```

## API Reference

### `encodeTransaction(transaction, options)`

Encodes a Solana transaction into QR-friendly format.

**Parameters:**
- `transaction`: `Transaction | VersionedTransaction` - The Solana transaction to encode
- `options`: `EncodeOptions` - Configuration options

**Returns:** `Promise<EncodeResult>`

### `EncodeOptions`

```typescript
interface EncodeOptions {
  sessionId: string;           // Unique session identifier
  network: string;             // Solana network (mainnet-beta, devnet, testnet)
  origin: string;              // dApp origin URL
  description?: string;        // Human-readable transaction description
  requiredSigners: string[];   // Array of required signer public keys
  signatureReturnUrl: string;  // URL where wallet should POST signature
  compress?: boolean;          // Enable gzip compression (default: true)
  maxFrameSize?: number;       // Max bytes per QR frame (default: 1000)
  expirationMinutes?: number;  // Transaction expiration (default: 10)
}
```

### `EncodeResult`

```typescript
interface EncodeResult {
  frames: string[];           // Array of QR frame data
  totalFrames: number;        // Total number of frames
  payload: TransactionPayload; // The encoded payload object
  compressed: boolean;        // Whether compression was used
}
```

## Features

- **Multiple Transaction Types**: Supports both `Transaction` and `VersionedTransaction`
- **Animated QR Codes**: Automatically splits large transactions into multiple frames
- **Compression**: Optional gzip compression to reduce QR size
- **Security**: Built-in checksum validation and expiration
- **Flexible**: Configurable frame sizes and compression settings

## Transaction Payload Format

The encoder creates a standardized JSON payload:

```json
{
  "v": 1,
  "type": "solana-tx",
  "session": "unique-session-id",
  "network": "mainnet-beta",
  "tx": "base64-serialized-transaction",
  "meta": {
    "origin": "https://your-dapp.com",
    "created_at": 1733872000,
    "description": "Send 0.1 SOL to friend",
    "required_signers": ["sender-pubkey"],
    "expires_at": 1733872600
  },
  "checksum": "sha256-hash",
  "sig_return": {
    "method": "https",
    "url": "https://your-dapp.com/api/sessions/:id/signature"
  }
}
```

## Error Handling

```typescript
try {
  const result = await encodeTransaction(transaction, options);
  // Handle successful encoding
} catch (error) {
  if (error.code === 'TRANSACTION_TOO_LARGE') {
    // Transaction exceeds maximum size even with compression
  } else if (error.code === 'INVALID_SIGNER') {
    // Required signer not found in transaction
  }
  // Handle other errors
}
```

## Best Practices

1. **Session Management**: Use unique, unpredictable session IDs
2. **Expiration**: Set reasonable expiration times (5-15 minutes)
3. **Compression**: Enable compression for better QR code density
4. **Frame Size**: Adjust `maxFrameSize` based on your QR display capabilities
5. **Error Handling**: Always handle encoding errors gracefully

## Related Packages

- [@solforge/qr-tx-decoder](https://www.npmjs.com/package/@solforge/qr-tx-decoder) - Decode QR payloads in wallets

## License

MIT

## Links

- [GitHub Repository](https://github.com/nitishxyz/solforge-qr-sdk)
- [Full Documentation](https://github.com/nitishxyz/solforge-qr-sdk#readme)
- [Report Issues](https://github.com/nitishxyz/solforge-qr-sdk/issues)