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

# Quickstart

> Start building with Grid Accounts in minutes with step-by-step integration instructions

Grid Accounts make it simple to build modern fintech applications with email-based onboarding, programmable spending limits, and sub-penny transaction costs. This guide will get you up and running in minutes.

<Tip>
  Grid Accounts currently **support any Solana token** and are **compatible with
  Solana-based programs**, providing a powerful base for composability.
</Tip>

## Get API Keys

Before you can start building, you'll need API credentials from the Grid dashboard.

<Card title="Get API Keys" icon="key" href="https://grid.squads.xyz/dashboard">
  Visit the Grid dashboard to generate your sandbox and production API keys
</Card>

<Warning>
  Keep your API keys secure and never expose them in client-side code. Always
  use environment variables or secure key management systems.
</Warning>

## Prerequisites

Before integrating Grid Accounts, ensure you have:

* **Node.js 18+** or another runtime environment
* **API credentials** from the Grid dashboard
* **Basic understanding** of REST APIs and async/await patterns

### SDK Installation

Install the official Grid SDK to get started quickly:

```bash theme={null}
npm install @sqds/grid
```

The Grid SDK provides TypeScript support out of the box and handles authentication, error handling, and API communication automatically.

<Card title="Grid SDK Documentation" icon="book" href="https://www.npmjs.com/package/@sqds/grid">
  View complete SDK documentation, API reference, and additional examples on NPM
</Card>

<Tip>
  **Migrating from grid-sdk?** The new @sqds/grid package provides enhanced
  features including multi-provider support and React Native compatibility. View
  our [migration guide](/grid/v1/accounts/migration-from-grid-sdk).
</Tip>

## SDK Initialization

Set up your Grid client using the official SDK:

<CodeGroup>
  ```typescript theme={null}
  import { GridClient } from "@sqds/grid";

  // Initialize the Grid client
  const gridClient = new GridClient({
    environment: "sandbox", // Use 'production' for live applications
    apiKey: process.env.GRID_API_KEY!, // Your API key from the dashboard
    baseUrl: "https://grid.squads.xyz", // Base URL of the Grid API
  });

  // Verify the connection
  console.log("Grid client initialized successfully");
  ```

  ```typescript theme={null}
  // .env file
  GRID_API_KEY = your_sandbox_api_key_here;

  // For production:
  // GRID_API_KEY=your_production_api_key_here
  // GRID_ENVIRONMENT=production

  // gridClient.ts
  import { GridClient } from "@sqds/grid";

  if (!process.env.GRID_API_KEY) {
    throw new Error("GRID_API_KEY environment variable is required");
  }

  export const gridClient = new GridClient({
    environment:
      process.env.GRID_ENVIRONMENT === "production" ? "production" : "sandbox",
    apiKey: process.env.GRID_API_KEY,
    baseUrl: "https://grid.squads.xyz",
  });
  ```
</CodeGroup>

<Note>
  The Grid SDK automatically handles API authentication, request retries, and
  error formatting. You don't need to build your own HTTP client.
</Note>

## Complete Integration Example

<Tabs>
  <Tab title="SDK Integration">
    Complete workflow from account creation through transaction execution:

    <Steps>
      <Step title="Initialize Grid Client">
        Set up your Grid SDK client with API credentials:

        ```typescript theme={null}
        import { GridClient } from '@sqds/grid';

        const gridClient = new GridClient({
          environment: 'sandbox', // Use 'production' for live applications
          apiKey: process.env.GRID_API_KEY!,
          baseUrl: "https://grid.squads.xyz",
        });
        ```
      </Step>

      <Step title="Generate Session Secrets">
        Create cryptographic keypairs that will authorize all future transactions:

        ```typescript theme={null}
        const sessionSecrets = await gridClient.generateSessionSecrets();
        console.log('Session secrets generated - these contain private keys needed for signing!');
        ```

        <Warning>
          Session secrets contain private keys that enable transaction signing. Store them encrypted and never expose them in client-side code.
        </Warning>
      </Step>

      <Step title="Create Email Account">
        Create a new Grid account using email-based onboarding:

        <Danger>
          Grid accounts do not have the same address in sandbox and production. **DO NOT** send funds to the same address in both environments. Create unique accounts for each environment and ensure you use the correct address for your environment.
        </Danger>

        ```typescript theme={null}
        const user = await gridClient.createAccount({
          email: 'user@example.com',
        });
        console.log('Account creation initiated for:', user.email);
        console.log('OTP sent to email for verification');
        ```
      </Step>

      <Step title="Verify Account with OTP">
        Complete account verification using the OTP sent to the user's email:

        ```typescript theme={null}
        const verifiedAccount = await gridClient.completeAuthAndCreateAccount({
          user: user,
          otpCode: '123456', // User receives this via email
          sessionSecrets: sessionSecrets,
        });
        console.log('Account created successfully');
        ```
      </Step>

      <Step title="Authenticate Existing Account (Alternative)">
        For users who already have a Grid account, use the authentication flow:

        ```typescript theme={null}
        // Generate fresh session secrets for authentication
        const authSessionSecrets = await gridClient.generateSessionSecrets();

        // Initialize authentication for existing account
        const authUser = await gridClient.initAuth({
          email: 'existing@example.com',
        });
        console.log('Authentication initiated for:', authUser.email);
        console.log('OTP sent to email for verification');

        // Complete authentication with OTP
        const authenticatedAccount = await gridClient.completeAuth({
          user: authUser,
          otpCode: '123456', // User receives this via email
          sessionSecrets: authSessionSecrets,
        });
        console.log('Account authenticated successfully');
        ```

        <Note>
          Use `initAuth` and `completeAuth` for existing accounts, or `createAccount` and `completeAuthAndCreateAccount` for new account creation. Always generate fresh session secrets for each authentication flow.
        </Note>
      </Step>

      <Step title="Prepare Transaction">
        Before executing, prepare the transaction payload using the SDK:

        ```typescript theme={null}
        const rawTransactionPayload = {
          transaction: "AQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAEDArc20SI/X2z8FPQhKgWWbWfXOTI3TDjuQQB8JfpF+1e4u3shfDGrJc7jvYd11DguvNKYg2PsUz7b7GZKwcAjMBoCAAECAAkDAAAAAMOhGsIAAAAA", // Your Solana transaction
          transaction_signers: [verifiedAccount.address] // Optional: only needed when signing with local signers
        };

        // Prepare the transaction payload
        const transactionPayload = await gridClient.prepareArbitraryTransaction(
          verifiedAccount.address,
          rawTransactionPayload
        );
        console.log('Transaction prepared successfully');
        ```

        <Note>
          The `transaction_signers` field is optional and only required when you need to sign the transaction with additional local signers alongside Grid's signing.
        </Note>
      </Step>

      <Step title="Execute Transactions">
        Use the `signAndSend` method to execute the prepared transaction:

        ```typescript theme={null}
        const executedTx = await gridClient.signAndSend({
          sessionSecrets, // Private keys for cryptographic signing
          session: verifiedAccount, // Authenticated account session
          transactionPayload, // Prepared transaction payload
          address: verifiedAccount.address
        });
        console.log('Transaction executed:', executedTx.signature);
        ```

        <Note>
          The `signAndSend` method handles both cryptographic signing and network submission in a single call, simplifying transaction execution.
        </Note>
      </Step>
    </Steps>

    <Tip>
      For production applications, implement proper error handling, retry logic, and secure secret management around each of these steps.
    </Tip>
  </Tab>

  <Tab title="LLM Integration Prompts">
    Comprehensive LLM prompts that provide complete implementation guidance for Grid Accounts integration:

    <Steps>
      <Step title="Step 1: Initialize Grid Client Setup">
        Copy this comprehensive prompt to your LLM:

        ```markdown theme={null}
        # IMPLEMENT GRID ACCOUNTS CLIENT SETUP

        ## TASK OVERVIEW
        Set up Grid SDK client initialization in my application following my existing patterns.

        ## MY APPLICATION CONTEXT
        **Tech Stack:**
        - Framework: [React/Next.js/Express/Django/etc.]
        - Environment management: [How you handle config/env vars]
        - Service architecture: [How you organize API services]
        - Error handling: [Your current error handling approach]

        ## GRID V1 CLIENT REQUIREMENTS
        **Installation:** npm install @sqds/grid

        **Import:** import { GridClient } from '@sqds/grid';

        **Configuration Options:**
        - environment: 'sandbox' | 'production'
        - apiKey: string (from Grid dashboard at https://grid.squads.xyz/dashboard)

        **Complete Initialization Example:**
        const gridClient = new GridClient({
          environment: process.env.NODE_ENV === 'production' ? 'production' : 'sandbox',
          apiKey: process.env.GRID_API_KEY!,
          baseUrl: "https://grid.squads.xyz",
        });

        ## IMPLEMENTATION REQUEST
        Create a Grid client service that:
        1. Follows my application's service patterns
        2. Handles environment configuration properly
        3. Includes comprehensive error handling
        4. Provides a clean interface for other parts of my app
        5. Includes proper TypeScript types if I'm using TypeScript

        Show me the complete implementation with file structure and code.

        ## DOCUMENTATION REFERENCES
        - Grid SDK Documentation: https://www.npmjs.com/package/@sqds/grid
        - API Dashboard: https://grid.squads.xyz/dashboard
        ```
      </Step>

      <Step title="Step 2: Generate and Store Session Secrets">
        Copy this comprehensive prompt to your LLM:

        ```markdown theme={null}
        # IMPLEMENT GRID SESSION SECRETS MANAGEMENT

        ## TASK OVERVIEW
        Implement secure generation and storage of Grid session secrets for transaction signing.

        ## MY APPLICATION CONTEXT
        **Security Setup:**
        - Current encryption library: [crypto/bcrypt/etc.]
        - Database/storage: [PostgreSQL/MongoDB/Redis/etc.]
        - User data storage patterns: [How you store user information]
        - Environment variables: [Your env var management]

        ## GRID SESSION SECRETS EXPLAINED
        Session secrets are cryptographic keypairs that authorize transaction signing. They contain:
        - Private keys for signing transactions
        - Public keys for verification
        - CRITICAL: Must never be exposed in client-side code or logs

        **Generation Method:**
        const sessionSecrets = await gridClient.generateSessionSecrets();
        // Returns object with signing keys - treat as highly sensitive

        ## SECURITY REQUIREMENTS
        1. **Encrypt before storage** - Never store plaintext
        2. **Server-side only** - Never send to client
        3. **Secure key management** - Use environment variables for encryption keys
        4. **Access logging** - Log when secrets are accessed

        ## IMPLEMENTATION REQUEST
        Create a secure session secrets management system that:
        1. Generates session secrets using Grid SDK
        2. Encrypts them using my existing encryption approach
        3. Stores encrypted secrets in my database
        4. Provides secure retrieval and decryption
        5. Includes proper error handling for encryption/decryption failures
        6. Follows my application's security patterns

        Show me the complete implementation including database schema, encryption/decryption functions, and service methods.

        ## DOCUMENTATION REFERENCES
        - Grid SDK Documentation: https://www.npmjs.com/package/@sqds/grid
        - Authentication Methods Guide: https://grid.squads.xyz/grid/v1/accounts/authentication-methods
        ```
      </Step>

      <Step title="Step 3: Implement Account Creation Flow">
        Copy this comprehensive prompt to your LLM:

        ```markdown theme={null}
        # IMPLEMENT GRID ACCOUNT CREATION WITH EMAIL AUTHENTICATION

        ## TASK OVERVIEW
        Integrate Grid account creation into my user registration flow with email-based authentication.

        ## MY APPLICATION CONTEXT
        **Current User Registration:**
        - Registration flow: [Describe your signup process]
        - User data model: [Your user schema/model]
        - Email handling: [How you send emails/notifications]
        - Database operations: [Your ORM/database pattern]

        ## GRID ACCOUNT CREATION PROCESS
        **Step 1:** Generate session secrets (from previous step)
        **Step 2:** Create account with email
        **Step 3:** Handle OTP verification

        **Account Creation Method:**
        const accountData = await gridClient.createAccount({
          email: 'user@example.com',
        });
        // Returns: { address: string, ... }
        // Automatically sends OTP to email

        **Account Verification Method:**
        const verifiedAccount = await gridClient.completeAuthAndCreateAccount({
          user: user,
          otpCode: '123456', // From user email
          sessionSecrets: sessionSecrets,
        });
        // Returns verified account session

        **For Existing Accounts (Alternative):**
        // Generate fresh session secrets for authentication
        const authSessionSecrets = await gridClient.generateSessionSecrets();

        // Initialize authentication for existing account
        const authUser = await gridClient.initAuth({
          email: 'existing@example.com',
        });

        // Complete authentication with OTP
        const authenticatedAccount = await gridClient.completeAuth({
          user: authUser,
          otpCode: '123456', // From user email
          sessionSecrets: authSessionSecrets,
        });
        // Returns authenticated account session

        ## INTEGRATION REQUIREMENTS
        1. **Integrate with existing registration** - Add Grid account creation to my signup flow
        2. **Handle existing users** - Support both new account creation and existing account authentication
        3. **Store account data** - Save Grid address and session info
        4. **Handle OTP flow** - Create UI/API for OTP verification
        5. **Link to user records** - Associate Grid accounts with my user model
        6. **Error handling** - Handle network failures, invalid emails, expired OTPs

        ## IMPLEMENTATION REQUEST
        Show me how to:
        1. Modify my user registration to include Grid account creation
        2. Add existing user authentication flow using initAuth/completeAuth
        3. Update my user model/schema to store Grid data
        4. Create OTP verification endpoints/UI
        5. Handle both new account creation and existing account authentication flows
        6. Add appropriate error handling and user feedback

        Provide complete code examples that integrate with my existing patterns.

        ## DOCUMENTATION REFERENCES
        - Grid SDK Documentation: https://www.npmjs.com/package/@sqds/grid
        - Authentication Methods Guide: https://grid.squads.xyz/grid/v1/accounts/authentication-methods
        ```
      </Step>

      <Step title="Step 4: Implement Transaction Preparation">
        Copy this comprehensive prompt to your LLM:

        ```markdown theme={null}
        # IMPLEMENT GRID TRANSACTION PREPARATION

        ## TASK OVERVIEW
        Implement transaction preparation for executing Solana transactions through Grid accounts.

        ## MY APPLICATION CONTEXT
        **Current Transaction Flow:**
        - Payment/transaction handling: [How you process payments]
        - Transaction data: [How you structure transaction info]
        - Business logic: [Your transaction validation/processing]

        ## GRID TRANSACTION PREPARATION EXPLAINED
        Before executing transactions, you must prepare the transaction payload:

        **Raw Transaction Structure:**
        const rawTransactionPayload = {
          transaction: "BASE64_ENCODED_SOLANA_TRANSACTION", // Your Solana transaction
          transaction_signers: [accountAddress] // Optional: additional local signers
        };

        **Preparation Method:**
        const transactionPayload = await gridClient.prepareArbitraryTransaction(
          accountAddress,
          rawTransactionPayload
        );

        **Key Points:**
        - `transaction`: Base64-encoded Solana transaction bytes
        - `transaction_signers`: Optional array for additional signing requirements
        - Returns prepared payload ready for signing and submission

        ## SOLANA TRANSACTION CONTEXT
        Grid works with any Solana transaction including:
        - Token transfers (SPL tokens, stablecoins)
        - Program interactions (DeFi protocols, NFTs)
        - Smart contract calls
        - Multi-signature operations

        ## IMPLEMENTATION REQUEST
        Create a transaction preparation service that:
        1. Accepts transaction data from my application
        2. Converts it to proper Solana transaction format
        3. Uses Grid's prepareArbitraryTransaction method
        4. Handles different transaction types I need
        5. Includes validation and error handling
        6. Integrates with my existing transaction flow

        Show me:
        - How to structure different types of transactions for Grid
        - Complete transaction preparation implementation
        - Integration with my existing payment/transaction system
        - Error handling for invalid transactions

        ## DOCUMENTATION REFERENCES
        - Grid SDK Documentation: https://www.npmjs.com/package/@sqds/grid
        - Automated Workflows Guide: https://grid.squads.xyz/grid/v1/accounts/automated-workflows
        ```
      </Step>

      <Step title="Step 5: Implement Transaction Execution">
        Copy this comprehensive prompt to your LLM:

        ```markdown theme={null}
        # IMPLEMENT GRID TRANSACTION EXECUTION

        ## TASK OVERVIEW
        Implement the final step: executing prepared transactions using Grid's signAndSend method.

        ## MY APPLICATION CONTEXT
        **Transaction Processing:**
        - Current payment completion: [How you finalize transactions]
        - Transaction logging: [How you track transaction history]
        - User feedback: [How you notify users of transaction status]

        ## GRID TRANSACTION EXECUTION
        **signAndSend Method Signature:**
        const executedTx = await gridClient.signAndSend({
          sessionSecrets, // Decrypted session secrets from secure storage
          session: verifiedAccount, // Account session from authentication
          transactionPayload, // Prepared transaction from previous step
          address: accountAddress // Grid account address
        });
        // Returns: { signature: string, ... } - Solana transaction signature

        **Complete Flow:**
        1. Retrieve and decrypt user's session secrets
        2. Get user's verified account session
        3. Use prepared transaction payload
        4. Execute with signAndSend
        5. Handle success/failure and update user

        ## IMPLEMENTATION REQUIREMENTS
        1. **Secure secret retrieval** - Get and decrypt session secrets safely
        2. **Transaction execution** - Use signAndSend method properly
        3. **Result handling** - Process success/failure responses
        4. **Transaction tracking** - Log results in my system
        5. **User feedback** - Notify users of transaction status
        6. **Error recovery** - Handle network failures, signing errors

        ## COMMON TRANSACTION SCENARIOS
        - **Stablecoin transfers** - Moving USDC/USDT between accounts
        - **Payment processing** - Merchant payment acceptance
        - **DeFi interactions** - Yield farming, swaps, lending
        - **Batch operations** - Multiple transactions in sequence

        ## IMPLEMENTATION REQUEST
        Create a complete transaction execution system that:
        1. Integrates with my transaction preparation (previous step)
        2. Handles secure session secret management
        3. Executes transactions using Grid's signAndSend
        4. Provides comprehensive error handling and retry logic
        5. Updates my application state based on transaction results
        6. Includes proper logging and user notifications

        Show me the complete implementation with all error scenarios handled.

        ## DOCUMENTATION REFERENCES
        - Grid SDK Documentation: https://www.npmjs.com/package/@sqds/grid
        - Fault Tolerance Guide: https://grid.squads.xyz/grid/v1/accounts/fault-tolerance
        ```
      </Step>
    </Steps>

    <Tip>
      Each prompt is self-contained with complete context, specifications, and documentation links. Copy any prompt to your LLM along with your specific technical details for comprehensive implementation guidance.
    </Tip>
  </Tab>
</Tabs>

<Tip>
  Ready to go live? Make sure to update your API endpoints to production URLs
  and use your production API keys. Grid provides the same API structure across
  sandbox and production environments.
</Tip>
