> For the complete documentation index, see [llms.txt](https://nakis-organization.gitbook.io/naki-wallet/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://nakis-organization.gitbook.io/naki-wallet/moonpay-integration.md).

# MoonPay Integration

## MoonPay Integration 💰

### Sandbox Configuration 🏝️

For the hackathon, we've implemented MoonPay's sandbox environment to simulate the crypto purchasing experience without processing real payments:

* **API Integration**:
  * Using MoonPay's sandbox API endpoints
  * Test API keys configured in our environment
  * Simulated transactions with test data
* **Configuration Parameters**:

  ```javascript
  { openWithInAppBrowser } = useMoonPaySdk({
    sdkConfig: {
      flow: 'buy',
      environment: 'sandbox',
      params: {
        apiKey: 'pk_test_hqZBzyRw37zLkEp1kJo9n3FxPzNkGHQ',
        baseCurrencyCode: 'usd',
        baseCurrencyAmount: '100',
        defaultCurrencyCode: 'usdc',
        walletAddress: walletAddress,
        colorCode: '%238134AF',
      },
    },
    browserOpener: {
      open: async (url) => {
        await WebBrowser.openBrowserAsync(url);
      },
    },
  });
  ```

### Simulated Purchase Process 🔄

The MoonPay integration provides a complete user flow that mimics real-world crypto purchasing:

1. **User Experience**:
   * Amount selection within Naki Wallet
   * Card information entry
   * Payment confirmation
   * Processing animation
   * Success notification
2. **Behind the Scenes**:
   * Card details validated for format (no actual charges)
   * Sandbox API confirms transaction success
   * USDC balance updated locally
   * Transaction recorded in history
3. **Implementation Details**:
   * WebView integration for seamless experience
   * Custom hooks to manage purchase state
   * Error handling for failed transactions
   * Receipt generation

### Custom Implementation 🛠️

For the hackathon version, we've implemented a hybrid approach:

* MoonPay SDK for the front-end user experience
* Custom transaction simulation in `add-money-debit.tsx`
* SecureStore for persistent balance tracking
* Transaction history management

```javascript
// Excerpt from add-money-debit.tsx
const handleAddMoney = async () => {
  setError(null);
  
  if (!validateCardDetails()) {
    return;
  }

  setIsLoading(true);

  try {
    // Simulate processing time
    await new Promise(resolve => setTimeout(resolve, 1500));
    
    const amountNumber = parseFloat(amount);
    
    // Call our blockchain hook to handle USDC receipt
    const result = await receiveUSDC(amountNumber);
    
    if (!result) {
      throw new Error("Failed to process transaction");
    }
    
    setTransactionSuccess(true);
    
    // Success feedback
    if (Platform.OS !== 'web') {
      Haptics.notificationAsync(Haptics.NotificationFeedbackType.Success);
    }

    // Alert and navigation
    Alert.alert(
      "Purchase Successful",
      `You've successfully purchased $${amount} worth of USDC!`,
      [{ 
        text: "OK", 
        onPress: () => router.push({
          pathname: "/",
          params: { 
            newAmount: amount,
            refreshTimestamp: Date.now().toString() 
          }
        })
      }]
    );
  } catch (err) {
    console.error('Error processing payment:', err);
    setError('Failed to process payment. Please try again.');
  } finally {
    setIsLoading(false);
  }
};
```

### Current Limitations 🚧

As this is a hackathon implementation, there are some limitations to our MoonPay integration:

1. **Sandbox Only**:
   * No real transactions are processed
   * Test mode with simulated responses
   * Balance updates are local only
2. **Limited Currency Options**:
   * Currently supporting only USDC
   * Fixed 1:1 exchange rate with USD
3. **Simplified Flow**:
   * Reduced KYC requirements for demo purposes
   * Streamlined checkout experience
4. **Integration Status**:
   * Core purchase flow complete
   * Transaction history integration working
   * Balance management functional
   * Missing some advanced features from production MoonPay

In a production environment, we would upgrade to full MoonPay production APIs, implement complete KYC flows, and support multiple payment methods and cryptocurrencies.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://nakis-organization.gitbook.io/naki-wallet/moonpay-integration.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
