# Mobile Architecture

Patterns for building Solana mobile applications. Covers framework selection, SDK integration, and the unique challenges of mobile crypto.

## Framework Decision

| Framework | Best For | Wallet Connection | Recommended Starting Point |
|-----------|---------|-------------------|----------------------------|
| React Native | Cross-platform, JS/TS teams | MWA, wallet-ui integrations, mobile wallet flows | `create-solana-dapp` mobile template + `react-native-samples` |
| Kotlin + Compose | Native Android | MWA (first-class) | Native Android scaffold / current Solana Mobile Android docs |
| Solana App Kit | Rapid prototyping | Built-in abstractions | Use only if the abstraction matches the product needs |

### React Native (Recommended for most teams)

Start from the current Solana Mobile React Native template flow:

```bash
npm create solana-dapp@latest
cd MySolanaDapp
npm install
npx expo run:android
```

Current React Native references worth following:
- `react-native-samples` for up-to-date example apps and app structure
- Solana Mobile React Native docs for installation and setup
- Current mobile templates generated by `create-solana-dapp`

What current sample apps commonly include:
- Mobile wallet integration patterns
- `react-native-quick-crypto` polyfill setup
- Expo custom development builds (`expo run:android`)
- Example transaction signing and wallet connection flows
- Modern Solana client usage — newer samples like `skr-staking` use `@solana/kit`, while official React Native installation docs and several other samples still use `@solana/web3.js`

### Kotlin + Jetpack Compose (Native Android)

Use native Android when you need:
- Performance-critical apps
- Apps that need deep Android integration
- Teams with Kotlin experience

### Solana App Kit (Fastest to ship)

Pre-built modules for common Solana mobile patterns. Build an app in under 15 minutes.

```bash
git clone https://github.com/sendaifun/solana-app-kit.git
```

**Repos:** `solana-app-kit` (pre-built modules for rapid Solana app development)

## React Native Setup Notes

Modern Solana Mobile React Native projects typically use:
- custom Expo development builds instead of Expo Go
- `react-native-quick-crypto` for crypto polyfills
- a dedicated entrypoint that imports polyfills before Solana libraries
- current sample-app patterns rather than older ad hoc Node polyfill recipes

### Current Polyfill Pattern

```javascript
// polyfill.js
import { install } from "react-native-quick-crypto";
install();
```

```javascript
// index.js
import "./polyfill";
import "expo-router/entry"; // if using Expo Router
```

### Why this matters

Current Solana JS client stacks used in React Native mobile apps still rely on early crypto polyfill setup. Official React Native installation docs call this out for `@solana/web3.js`, and newer Kit-based samples still use the same early `react-native-quick-crypto` entrypoint pattern. Import polyfills before any Solana imports.

### Development and Device Testing

For development:
- use any Android device or emulator
- use Mock MWA Wallet when testing wallet flows without a production wallet
- validate app-switching, timeout handling, and reconnect flows early

Before signoff:
- repeat the critical wallet and transaction flow on a physical device with a real wallet installed

## Mobile App Structure

```
src/
  App.tsx                    # Entry point, providers
  providers/
    WalletProvider.tsx       # MWA or Phantom mobile flow
    ConnectionProvider.tsx   # RPC connection
  screens/
    HomeScreen.tsx           # Main app screen
    WalletScreen.tsx         # Balance, tokens, history
  hooks/
    useWallet.ts             # Wallet connection state
    useTransaction.ts        # Transaction building + sending
    useBalance.ts            # SOL + token balances
  utils/
    transaction.ts           # Transaction helpers
    constants.ts             # Program IDs, RPC URLs
```

## RPC Connection on Mobile

Use the RPC client and transport pattern that matches the chosen stack/template:
- for newer Kit-based apps, follow the current `skr-staking` and Solana Kit patterns
- for web3.js-based apps, follow the official Solana Mobile React Native installation/docs flow
- use a dedicated RPC provider for mobile production traffic
- add timeout, retry, reconnect, and fresh-blockhash handling for mobile network conditions

### Current Kit-Based Pattern (from `skr-staking`)

A good default structure for newer Kit-based React Native apps is:

```typescript
import { Slot } from 'expo-router';
import { MobileWalletProvider, createSolanaMainnet } from '@wallet-ui/react-native-kit';

const cluster = createSolanaMainnet({
  url: process.env.EXPO_PUBLIC_RPC_URL || 'https://api.mainnet-beta.solana.com',
  label: 'Solana Mainnet',
});

const identity = {
  name: 'My Mobile App',
  uri: 'https://myapp.com/',
};

export default function Layout() {
  return (
    <MobileWalletProvider cluster={cluster} identity={identity}>
      <Slot />
    </MobileWalletProvider>
  );
}
```

For data access and PDA derivation, the current Kit-style pattern is:

```typescript
import {
  address,
  createSolanaRpc,
  getAddressEncoder,
  getProgramDerivedAddress,
  getUtf8Encoder,
} from '@solana/kit';

const rpc = createSolanaRpc(
  process.env.EXPO_PUBLIC_RPC_URL || 'https://api.mainnet-beta.solana.com'
);

const PROGRAM_ID = address('YourProgram111111111111111111111111111111111');

async function derivePda(userAddress: string) {
  const encoder = getAddressEncoder();
  const [pda] = await getProgramDerivedAddress({
    programAddress: PROGRAM_ID,
    seeds: [
      getUtf8Encoder().encode('profile'),
      encoder.encode(address(userAddress)),
    ],
  });
  return pda;
}
```

This is the pattern to copy for new mobile apps using Kit:
- `MobileWalletProvider` at the layout/root level
- cluster configuration via `createSolanaMainnet(...)`
- RPC access via `createSolanaRpc(...)`
- addresses/PDAs via `address(...)` and `getProgramDerivedAddress(...)`
- keep `polyfill.js` imported before the app entrypoint

**MCPs:** `helius-mcp` (60+ tools for RPC, DAS API, webhooks — use for production RPC)

## Handling Mobile-Specific Challenges

### Network Interruptions

```typescript
import NetInfo from "@react-native-community/netinfo";

NetInfo.addEventListener((state) => {
  if (!state.isConnected) {
    // Show offline UI
    showToast("No internet connection");
  }
});
```

### App Backgrounding During Wallet Sign

```typescript
import { AppState } from "react-native";

let appState = AppState.currentState;

AppState.addEventListener("change", (nextState) => {
  if (appState === "active" && nextState.match(/inactive|background/)) {
    // App went to background (likely wallet opened)
    console.log("App backgrounded — wallet may be open");
  }

  if (appState.match(/inactive|background/) && nextState === "active") {
    // App came back to foreground
    // Check if wallet request completed or timed out
    checkPendingTransactionStatus();
  }

  appState = nextState;
});
```

### Deep Link Handling

```typescript
import { Linking } from "react-native";

// Handle wallet deep link callbacks
Linking.addEventListener("url", ({ url }) => {
  if (url.startsWith("myapp://wallet-callback")) {
    // Parse callback params
    const params = new URL(url).searchParams;
    handleWalletCallback(params);
  }
});
```

## Sources

- [Solana Mobile Docs — Create a Project](https://docs.solanamobile.com/get-started/react-native/create-solana-mobile-app)
- [Solana Mobile Docs — Installation](https://docs.solanamobile.com/get-started/react-native/installation)
- [Solana Mobile Docs — Test with any Android device](https://docs.solanamobile.com/recipes/general/test-with-any-android-device)
- [solana-mobile/react-native-samples](https://github.com/solana-mobile/react-native-samples)
