# `useEmbeddedEthereumWallet`

Manages embedded Ethereum wallets with creation, activation, recovery, and signing capabilities.

**Wallet types supported:**

* Smart Contract Accounts (Account Abstraction)
* EOA (Externally Owned Accounts)

**Recovery methods:**

* Automatic recovery (via encryption session)
* Password-based recovery
* Passkey-based recovery (biometric)

## Usage

```tsx
import { useEmbeddedEthereumWallet } from '@openfort/react-native';

function WalletManager() {
  const ethereum = useEmbeddedEthereumWallet({
    chainId: 137, // Polygon
    onCreateSuccess: (account, provider) => {
      console.log('Wallet created:', account.address);
    },
  });

  if (ethereum.status === 'connecting' || ethereum.status === 'creating') {
    return <ActivityIndicator />;
  }

  if (ethereum.status === 'connected') {
    return (
      <View>
        <Text>{ethereum.activeWallet.address}</Text>
        <Button
          title="Send Transaction"
          onPress={() => ethereum.provider.request({
            method: 'eth_sendTransaction',
            params: [{ from: ethereum.activeWallet.address, to: '0x...', value: '0x0' }]
          })}
        />
      </View>
    );
  }

  if (ethereum.wallets.length === 0) {
    return <Button title="Create Wallet" onPress={() => ethereum.create()} />;
  }

  return (
    <Button
      title="Connect"
      onPress={() => ethereum.setActive({
        address: ethereum.wallets[0].address,
        recoveryPassword: 'optional-password'
      })}
    />
  );
}
```

## Return type

Returns a discriminated union based on the `status` field:

```ts
type EmbeddedEthereumWalletState = {
  status: 'disconnected' | 'fetching-wallets' | 'connecting' | 'reconnecting' | 'creating' | 'needs-recovery' | 'connected' | 'error'
  wallets: ConnectedEmbeddedEthereumWallet[]
  activeWallet: ConnectedEmbeddedEthereumWallet | null
  provider?: OpenfortEmbeddedEthereumWalletProvider  // Available when connected
  error?: string  // Available when error
  create: (options?: CreateOptions) => Promise<EmbeddedAccount>
  setActive: (options: SetActiveOptions) => Promise<void>
  setRecovery: (options: SetRecoveryOptions) => Promise<void>
  exportPrivateKey: () => Promise<string>
}

type ConnectedEmbeddedEthereumWallet = {
  id: string
  address: string
  chainType: 'EVM'
  chainId?: number
  ownerAddress?: string
  factoryAddress?: string
  salt?: string
  accountType: AccountTypeEnum
  implementationAddress?: string
  createdAt?: number
  implementationType?: string
  recoveryMethod?: RecoveryMethod
  recoveryMethodDetails?: RecoveryMethodDetails
  walletIndex: number
  getProvider: () => Promise<OpenfortEmbeddedEthereumWalletProvider>
}

type OpenfortEmbeddedEthereumWalletProvider = {
  request(args: { method: string; params?: readonly unknown[] | object }): Promise<unknown>
  on(event: string, handler: (...args: unknown[]) => void): void
  removeListener(event: string, handler: (...args: unknown[]) => void): void
}
```

## Parameters

### Hook options

Pass these options when initializing the hook:

```ts
type UseEmbeddedEthereumWalletOptions = {
  chainId?: number
  onCreateSuccess?: (account: EmbeddedAccount, provider: OpenfortEmbeddedEthereumWalletProvider) => void
  onCreateError?: (error: OpenfortError) => void
  onSetActiveSuccess?: (wallet: ConnectedEmbeddedEthereumWallet, provider: OpenfortEmbeddedEthereumWalletProvider) => void
  onSetActiveError?: (error: OpenfortError) => void
  onSetRecoverySuccess?: () => void
  onSetRecoveryError?: (error: OpenfortError) => void
}
```

### `create`

Creates a new embedded Ethereum wallet.

```ts
type CreateOptions = {
  chainId?: number
  recoveryPassword?: string
  otpCode?: string  // OTP code for Shield verification when using automatic recovery
  accountType?: AccountTypeEnum  // SMART_ACCOUNT or EOA
  feeSponsorshipId?: string
  recoveryMethod?: 'automatic' | 'password' | 'passkey'  // Recovery method to use
  passkeyId?: string  // Passkey credential ID (for passkey recovery)
  onSuccess?: (data: CreateResult) => void
  onError?: (error: OpenfortError) => void
  throwOnError?: boolean
}

type CreateResult = {
  account?: EmbeddedAccount
  provider?: OpenfortEmbeddedEthereumWalletProvider
  error?: OpenfortError
}
```

### `setActive`

Activates an existing wallet and makes it the active wallet.

```ts
type SetActiveOptions = {
  address: Hex  // `0x${string}` — must be a hex-prefixed address
  chainId?: number
  recoveryPassword?: string
  otpCode?: string  // OTP code for Shield verification when using automatic recovery
  recoveryMethod?: 'automatic' | 'password' | 'passkey'  // Recovery method to use
  passkeyId?: string  // Passkey credential ID (auto-detected from wallet if not provided)
  onSuccess?: (data: SetActiveResult) => void
  onError?: (error: OpenfortError) => void
  throwOnError?: boolean
}

type SetActiveResult = {
  wallet?: ConnectedEmbeddedEthereumWallet
  provider?: OpenfortEmbeddedEthereumWalletProvider
  error?: OpenfortError
}
```

### `setRecovery`

Changes the recovery method for the wallet.

```ts
type SetRecoveryOptions = {
  previousRecovery: RecoveryParams
  newRecovery: RecoveryParams
  onSuccess?: (data: SetRecoveryResult) => void
  onError?: (error: OpenfortError) => void
  throwOnError?: boolean
}

type RecoveryParams = {
  recoveryMethod: 'automatic' | 'password' | 'passkey'
  password?: string
  encryptionSession?: string
}

type SetRecoveryResult = {
  error?: OpenfortError
}
```

## Passkey recovery

Passkey recovery uses device biometrics (Face ID, Touch ID, fingerprint) for secure wallet recovery without passwords. The SDK automatically detects the recovery method from the wallet when calling `setActive`.

:::info
Passkey support requires native builds and proper domain configuration. See the [Passkey Quickstart](/docs/products/embedded-wallet/react-native/quickstart/passkey) for setup instructions.
:::

### Creating a wallet with passkey

```tsx
import { useEmbeddedEthereumWallet, usePasskeyPrfSupport } from '@openfort/react-native';

function WalletCreation() {
  const { isSupported: passkeySupported } = usePasskeyPrfSupport();
  const { create, status } = useEmbeddedEthereumWallet();

  const createWithPasskey = async () => {
    await create({
      recoveryMethod: 'passkey',
      onSuccess: ({ account }) => {
        console.log('Wallet created with passkey:', account?.address);
      },
      onError: (error) => {
        console.error('Failed:', error.message);
      },
    });
  };

  return (
    <Button
      title="Create with Passkey"
      onPress={createWithPasskey}
      disabled={!passkeySupported || status === 'creating'}
    />
  );
}
```

### Recovering a wallet with passkey

When a wallet was created with passkey recovery, `setActive` automatically triggers the biometric prompt:

```tsx
function WalletRecovery() {
  const { wallets, setActive } = useEmbeddedEthereumWallet();

  const recoverWallet = async (wallet) => {
    // Recovery method is auto-detected from wallet.recoveryMethod
    // For passkey wallets, this triggers the biometric prompt
    await setActive({
      address: wallet.address,
      chainId: 84532,
      onSuccess: () => console.log('Wallet recovered'),
      onError: (error) => console.error('Recovery failed:', error.message),
    });
  };

  return (
    <View>
      {wallets.map((wallet) => (
        <Button
          key={wallet.address}
          title={`Recover ${wallet.recoveryMethod === 'passkey' ? '(Passkey)' : ''}`}
          onPress={() => recoverWallet(wallet)}
        />
      ))}
    </View>
  );
}
```
