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

# Troubleshooting

> Common issues, error codes, and solutions for Amplify SDK integration

This guide helps you diagnose and resolve common issues when integrating the Amplify SDK.

## Quick Diagnosis

<AccordionGroup>
  <Accordion title="SDK throws 'SDK_NOT_INITIALIZED'">
    **Cause:** Calling SDK functions before `initAmplifySDK()` completes.

    **Solution:**

    * Ensure `initAmplifySDK()` is called at app startup and awaited
    * In React, use a provider pattern or custom hook
    * Check that the API key environment variable is set

    ```ts theme={null}
    // Correct: await initialization
    await initAmplifySDK("pxl_your_api_key");
    const auth = await prepareDepositAuthorization(params);

    // Wrong: not awaiting
    initAmplifySDK("pxl_your_api_key"); // Missing await!
    const auth = await prepareDepositAuthorization(params); // Throws!
    ```

    See [Project Setup](/v0.3.0/intro/products/earn/developers/guides/project-setup) for initialization patterns.
  </Accordion>

  <Accordion title="'VAULT_NOT_FOUND' error">
    **Cause:** No vault matches the provided yieldType, token, and chainId combination.

    **Solution:**

    * Verify the token address is correct for the chain
    * Check that the yield type supports the token via `fetchSupportedAssets()`
    * Ensure you're using the correct chain ID

    ```ts theme={null}
    // Verify supported assets first
    const assets = await fetchSupportedAssets({
      yieldType: YieldType.CORE,
    });

    // Check if your token is supported
    const isSupported = assets.some(
      (asset) => asset.address.toLowerCase() === tokenAddress.toLowerCase()
    );
    ```
  </Accordion>

  <Accordion title="Permit signature fails or is rejected">
    **Cause:** Token may not support EIP-2612, or wallet doesn't support `eth_signTypedData_v4`.

    **Solution:**

    * The SDK automatically falls back to approval flow
    * For smart wallets, use `forceMethod: "approval"` as they cannot sign permits
    * Check wallet compatibility with typed data signing

    ```ts theme={null}
    // Force approval flow for smart wallets
    const auth = await prepareDepositAuthorization({
      ...params,
      forceMethod: "approval",
    });
    ```
  </Accordion>

  <Accordion title="Transaction reverts on deposit">
    **Cause:** Insufficient balance, allowance, or slippage exceeded.

    **Solution:**

    * Verify user has sufficient token balance
    * Check that approval transaction confirmed before deposit
    * Increase slippage tolerance if market conditions are volatile

    ```ts theme={null}
    // Increase slippage for volatile conditions
    const prepared = await prepareDeposit({
      ...params,
      slippage: 100, // 1% instead of default 0.5%
    });
    ```
  </Accordion>

  <Accordion title="Withdrawal fails with liquidity error">
    **Cause:** Vault may have temporary withdrawal limits.

    **Solution:**

    * Try a smaller withdrawal amount
    * Wait and retry during different market conditions
    * Surface the `endpoint` and `statusCode` from `APIError` to understand the specific failure

    ```ts theme={null}
    try {
      const tx = await prepareWithdrawTxData(params);
    } catch (error) {
      if (error instanceof APIError && error.code === "LIQUIDITY_UNAVAILABLE") {
        // Show user-friendly message
        showError("Withdrawals are temporarily limited. Please try a smaller amount.");
      }
    }
    ```
  </Accordion>
</AccordionGroup>

## Error Reference

All SDK functions throw `APIError` with structured metadata:

```ts theme={null}
import { APIError } from "@paxoslabs/amplify-sdk";

try {
  const auth = await prepareDepositAuthorization(params);
} catch (error) {
  if (error instanceof APIError) {
    console.log(error.code);       // Error code
    console.log(error.endpoint);   // Function that threw
    console.log(error.statusCode); // HTTP status if applicable
    console.log(error.message);    // Human-readable message
  }
}
```

### Error Codes

| Code                     | Description                 | Resolution                                     |
| ------------------------ | --------------------------- | ---------------------------------------------- |
| `SDK_NOT_INITIALIZED`    | SDK used before init        | Call `initAmplifySDK()` at app startup         |
| `INVALID_API_KEY`        | API key validation failed   | Check key format (`pxl_...`)                   |
| `VAULT_NOT_FOUND`        | No vault matches params     | Verify yieldType, token, chainId               |
| `PERMIT_NOT_SUPPORTED`   | Token lacks EIP-2612        | Use approval flow or `forceMethod: "approval"` |
| `INSUFFICIENT_ALLOWANCE` | Approval amount too low     | Increase approval or use permit                |
| `LIQUIDITY_UNAVAILABLE`  | Vault has withdrawal limits | Try smaller amount or wait                     |

## Wallet-Specific Issues

### Smart Wallets (Privy Smart Wallet, Alchemy)

| Issue                       | Cause                               | Solution                          |
| --------------------------- | ----------------------------------- | --------------------------------- |
| Permit signing fails        | Smart contracts cannot sign EIP-712 | Use `forceMethod: "approval"`     |
| UserOperation times out     | Bundler congestion                  | Increase timeout, retry later     |
| Batched transaction reverts | One call in batch failing           | Debug individual calls separately |

### EOA Wallets

| Issue                              | Cause                | Solution                         |
| ---------------------------------- | -------------------- | -------------------------------- |
| `eth_signTypedData_v4` unsupported | Older wallet version | Update wallet, or force approval |
| Gas estimation fails               | Simulation reverted  | Check parameters, token balance  |

## Debugging Checklist

<Steps>
  <Step title="Enable debug logging">
    ```ts theme={null}
    import { initAmplifySDK, LogLevel } from "@paxoslabs/amplify-sdk";

    await initAmplifySDK("pxl_your_api_key", {
      logLevel: LogLevel.DEBUG,
    });
    ```
  </Step>

  <Step title="Check SDK initialization">
    Ensure `initAmplifySDK()` completed successfully before any other SDK calls.
  </Step>

  <Step title="Verify parameters">
    * Token address is checksummed
    * Chain ID matches the network
    * Amount is a valid decimal string (e.g., "100.25")
  </Step>

  <Step title="Inspect APIError details">
    Catch errors and log `error.code`, `error.endpoint`, and `error.message`.
  </Step>

  <Step title="Check transaction status">
    If a transaction was submitted, verify on block explorer whether it reverted or succeeded.
  </Step>
</Steps>

## Common Patterns

### Retry with Exponential Backoff

```ts theme={null}
async function withRetry<T>(
  fn: () => Promise<T>,
  maxRetries = 3
): Promise<T> {
  for (let i = 0; i < maxRetries; i++) {
    try {
      return await fn();
    } catch (error) {
      if (i === maxRetries - 1) throw error;
      await new Promise((r) => setTimeout(r, 1000 * Math.pow(2, i)));
    }
  }
  throw new Error("Max retries exceeded");
}

// Usage
const auth = await withRetry(() => prepareDepositAuthorization(params));
```

### User-Friendly Error Messages

```ts theme={null}
function getUserMessage(error: APIError): string {
  const messages: Record<string, string> = {
    SDK_NOT_INITIALIZED: "Please wait while we connect...",
    VAULT_NOT_FOUND: "This token is not available for the selected strategy.",
    PERMIT_NOT_SUPPORTED: "Please approve the transaction in your wallet.",
    LIQUIDITY_UNAVAILABLE: "Withdrawals are temporarily limited.",
  };
  return messages[error.code] || "An unexpected error occurred.";
}
```

## Getting Help

If you've tried these steps and still have issues:

1. Enable `LogLevel.DEBUG` and capture full console output
2. Note the exact error code and message
3. Check the [Changelog](/v0.3.0/intro/products/earn/developers/changelog) for breaking changes
4. Contact [support@paxoslabs.com](mailto:support@paxoslabs.com) with details
