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

# Export Key

The Export Key screen allows users to export their wallet's private key. This screen includes security warnings and confirmation steps to ensure users understand the risks of exposing their private key.

<Warning>
  Exporting private keys is a sensitive operation. Users should be warned that anyone with access to their private key has full control of their wallet and funds.
</Warning>

## How it works

When a user requests to export their private key:

1. Your app calls the export key method from the MoonKey SDK
2. The Export Key screen appears with security warnings
3. User reviews the warnings and understands the risks
4. User confirms they want to proceed
5. The private key is displayed to the user
6. User can copy the private key for backup or import into another wallet

## Triggering the Export Key screen

Use the `useExportPrivateKey` hook from the MoonKey SDK to trigger the Export Key screen:

<Tabs>
  <Tab title="Ethereum">
    ```tsx theme={null}
    import { useMoonKey } from '@moon-key/react-auth';
    import { useExportPrivateKey } from '@moon-key/react-auth/ethereum';

    export default function ExportKeyButton() {
      const { user } = useMoonKey();
      const { exportPrivateKey } = useExportPrivateKey();
      
      const handleExport = async () => {
        if (!user?.wallet) {
          alert('No wallet found');
          return;
        }
        
        try {
          const privateKey = await exportPrivateKey({
            wallet: user.wallet,
            uiConfig: {
              title: 'Export Private Key',
              privateKeyDescription: 'Your private key provides full access to this wallet and all funds',
              neverShareDescription: 'Never share your private key with anyone, including MoonKey support',
              loadingExportOptionsText: 'Preparing export options...'
            }
          });
          
          console.log('Private key exported');
          // The UI will display the key to the user
        } catch (error) {
          console.error('User cancelled export:', error);
        }
      };
      
      return <button onClick={handleExport}>Export Private Key</button>;
    }
    ```
  </Tab>

  <Tab title="Solana">
    ```tsx theme={null}
    import { useMoonKey } from '@moon-key/react-auth';
    import { useExportPrivateKey } from '@moon-key/react-auth/solana';

    export default function ExportKeyButton() {
      const { user } = useMoonKey();
      const { exportPrivateKey } = useExportPrivateKey();
      
      const handleExport = async () => {
        if (!user?.wallet) {
          alert('No wallet found');
          return;
        }
        
        try {
          const privateKey = await exportPrivateKey({
            wallet: user.wallet,
            uiConfig: {
              title: 'Export Private Key',
              privateKeyDescription: 'Your private key provides full access to this wallet and all funds',
              neverShareDescription: 'Never share your private key with anyone, including MoonKey support',
              loadingExportOptionsText: 'Preparing export options...'
            }
          });
          
          console.log('Private key exported');
          // The UI will display the key to the user
        } catch (error) {
          console.error('User cancelled export:', error);
        }
      };
      
      return <button onClick={handleExport}>Export Private Key</button>;
    }
    ```
  </Tab>
</Tabs>

## Customizing the Export Key screen

You can customize the Export Key screen by passing UI configuration:

```tsx theme={null}
const privateKey = await exportPrivateKey({
  wallet: user.wallet,
  uiConfig: {
    title: 'Backup Your Wallet',
    hdDescription: 'Your HD wallet seed phrase can restore all your wallets',
    privateKeyDescription: 'Your private key provides complete control over this specific wallet',
    neverShareDescription: 'Never share these with anyone. MoonKey will never ask for them.',
    loadingExportOptionsText: 'Loading export options...',
    logoUrl: 'https://your-app.com/logo.png'
  }
});
```

## Configuration options

<ParamField path="title" type="string">
  Custom title text displayed at the top of the Export Key screen.

  **Example:**

  ```tsx theme={null}
  uiConfig: {
    title: 'Backup Your Wallet'
  }
  ```
</ParamField>

<ParamField path="hdDescription" type="string">
  Description text for HD (Hierarchical Deterministic) wallet seed phrase export option.

  This text explains what an HD seed phrase is and its purpose.

  **Example:**

  ```tsx theme={null}
  uiConfig: {
    hdDescription: 'Your seed phrase can restore all wallets derived from it'
  }
  ```
</ParamField>

<ParamField path="privateKeyDescription" type="string">
  Description text for the private key export option.

  This text explains what the private key is and how it's used.

  **Example:**

  ```tsx theme={null}
  uiConfig: {
    privateKeyDescription: 'Your private key gives full access to this wallet and all its funds'
  }
  ```
</ParamField>

<ParamField path="neverShareDescription" type="string">
  Warning text emphasizing that private keys should never be shared.

  This critical security warning is prominently displayed.

  **Example:**

  ```tsx theme={null}
  uiConfig: {
    neverShareDescription: 'Never share your private key. MoonKey support will never ask for it.'
  }
  ```
</ParamField>

<ParamField path="loadingExportOptionsText" type="string">
  Text displayed while export options are being loaded.

  **Example:**

  ```tsx theme={null}
  uiConfig: {
    loadingExportOptionsText: 'Preparing secure export...'
  }
  ```
</ParamField>

<ParamField path="logoUrl" type="string">
  URL to your company logo. Displayed at the top of the Export Key screen.

  **Example:**

  ```tsx theme={null}
  uiConfig: {
    logoUrl: 'https://myapp.com/logo.png'
  }
  ```
</ParamField>

## Security warnings

The Export Key screen displays multiple security warnings to users:

<AccordionGroup>
  <Accordion title="Private Key = Full Access">
    Anyone with access to your private key has complete control over your wallet and all funds in it.
  </Accordion>

  <Accordion title="Never Share">
    Never share your private key with anyone. MoonKey support will never ask for your private key.
  </Accordion>

  <Accordion title="Secure Storage">
    If you choose to store your private key, keep it in a secure location like a password manager or offline storage.
  </Accordion>

  <Accordion title="Phishing Risk">
    Be cautious of phishing attempts. Only export your key when you initiated the action.
  </Accordion>
</AccordionGroup>

## Use cases

### Wallet backup

Allow users to backup their wallet for recovery purposes:

```tsx theme={null}
import { useMoonKey } from '@moon-key/react-auth';
import { useExportPrivateKey } from '@moon-key/react-auth/ethereum';

export default function BackupWallet() {
  const { user } = useMoonKey();
  const { exportPrivateKey } = useExportPrivateKey();
  
  const handleBackup = async () => {
    if (!user?.wallet) return;
    
    try {
      await exportPrivateKey({
        wallet: user.wallet,
        uiConfig: {
          title: 'Backup Your Wallet',
          privateKeyDescription: 'Save your private key in a secure location for wallet recovery',
          neverShareDescription: 'Store securely. Never share with anyone.'
        }
      });
      
      // Log backup action
      await logUserAction('wallet_backup', {
        userId: user.id,
        timestamp: Date.now()
      });
    } catch (error) {
      console.error('Backup cancelled:', error);
    }
  };
  
  return (
    <div>
      <h3>Wallet Backup</h3>
      <p>Create a backup of your wallet to prevent loss of access.</p>
      <button onClick={handleBackup}>Backup Wallet</button>
    </div>
  );
}
```

### Migrate to another wallet

Help users migrate their wallet to another application:

```tsx theme={null}
const migrateWallet = async () => {
  if (!user?.wallet) return;
  
  try {
    await exportPrivateKey({
      wallet: user.wallet,
      uiConfig: {
        title: 'Export for Migration',
        privateKeyDescription: 'Use this private key to import your wallet into MetaMask, Phantom, or other compatible wallets',
        neverShareDescription: 'Only use this key for importing into trusted wallet applications'
      }
    });
    
    alert('You can now import this private key into MetaMask, Phantom, or any compatible wallet.');
  } catch (error) {
    console.error('Migration cancelled:', error);
  }
};
```

### Advanced users self-custody

Provide power users with their private key for self-custody:

```tsx theme={null}
const enableSelfCustody = async () => {
  if (!user?.wallet) return;
  
  try {
    await exportPrivateKey({
      wallet: user.wallet,
      uiConfig: {
        title: 'Enable Self-Custody',
        privateKeyDescription: 'Take full control of your wallet by exporting your private key',
        neverShareDescription: 'Keep this key secure for complete self-custody'
      }
    });
    
    // Update user preference
    await updateUserSettings(user.id, {
      selfCustodyEnabled: true,
      exportedAt: Date.now()
    });
  } catch (error) {
    console.error('Self-custody setup cancelled:', error);
  }
};
```

## Complete example

Here's a complete example with proper warnings and logging:

```tsx theme={null}
'use client';
import { useMoonKey } from '@moon-key/react-auth';
import { useExportPrivateKey } from '@moon-key/react-auth/ethereum';
import { useState } from 'react';

export default function ExportKeyDemo() {
  const { user, isAuthenticated } = useMoonKey();
  const { exportPrivateKey } = useExportPrivateKey();
  const [exported, setExported] = useState(false);
  
  if (!isAuthenticated) {
    return <div>Please sign in first</div>;
  }
  
  if (!user?.wallet) {
    return <div>No wallet found</div>;
  }
  
  const handleExport = async () => {
    // Show additional confirmation
    const confirmed = confirm(
      'WARNING: Your private key gives complete control of your wallet. ' +
      'Only export if you understand the risks. Continue?'
    );
    
    if (!confirmed) return;
    
    try {
      await exportPrivateKey({
        wallet: user.wallet,
        uiConfig: {
          title: 'Export Private Key',
          privateKeyDescription: 'Your private key provides full access to your wallet and all funds',
          neverShareDescription: 'Never share your private key with anyone. MoonKey will never ask for it.',
          loadingExportOptionsText: 'Preparing secure export...'
        }
      });
      
      setExported(true);
      
      // Log the export action for security audit
      await fetch('/api/log-security-event', {
        method: 'POST',
        body: JSON.stringify({
          event: 'private_key_export',
          userId: user.id,
          walletAddress: user.wallet.address,
          timestamp: Date.now()
        })
      });
      
      console.log('Private key exported successfully');
    } catch (error) {
      console.error('Export failed or cancelled:', error);
    }
  };
  
  return (
    <div style={{ padding: '20px', maxWidth: '600px' }}>
      <h2>Export Private Key</h2>
      <p>Wallet: {user.wallet.address}</p>
      
      <div style={{
        background: '#fff3cd',
        border: '1px solid #ffc107',
        padding: '15px',
        borderRadius: '5px',
        marginTop: '20px',
        marginBottom: '20px'
      }}>
        <h3 style={{ marginTop: 0 }}>⚠️ Security Warning</h3>
        <ul style={{ marginBottom: 0 }}>
          <li>Your private key gives <strong>complete control</strong> of your wallet</li>
          <li><strong>Never share</strong> your private key with anyone</li>
          <li>MoonKey support will <strong>never ask</strong> for your private key</li>
          <li>Store it securely in a password manager or offline</li>
        </ul>
      </div>
      
      <button 
        onClick={handleExport}
        style={{
          padding: '10px 20px',
          background: '#dc3545',
          color: 'white',
          border: 'none',
          borderRadius: '5px',
          cursor: 'pointer'
        }}
      >
        Export Private Key
      </button>
      
      {exported && (
        <div style={{
          marginTop: '20px',
          padding: '15px',
          background: '#d1ecf1',
          borderRadius: '5px'
        }}>
          <p style={{ margin: 0 }}>
            ✓ Private key exported successfully. Make sure to store it securely!
          </p>
        </div>
      )}
    </div>
  );
}
```

## User experience flow

<Steps>
  <Step title="Trigger export">
    User clicks button to export their private key.
  </Step>

  <Step title="Security warnings">
    The Export Key screen displays comprehensive security warnings about the risks.
  </Step>

  <Step title="User acknowledges risks">
    User must acknowledge they understand the risks before proceeding.
  </Step>

  <Step title="Private key displayed">
    The private key is displayed on screen, typically with a copy button.
  </Step>

  <Step title="User copies key">
    User copies the private key to store it securely.
  </Step>

  <Step title="Confirmation">
    User confirms they have securely stored the key before closing the screen.
  </Step>
</Steps>

## Best practices

<AccordionGroup>
  <Accordion title="Add extra confirmation">
    Require additional confirmation before showing the Export Key screen:

    ```tsx theme={null}
    const handleExport = async () => {
      const confirmed = confirm(
        'WARNING: This will reveal your private key. Only proceed if you understand the security risks.'
      );
      
      if (!confirmed) return;
      
      await exportPrivateKey({ wallet: user.wallet });
    };
    ```
  </Accordion>

  <Accordion title="Log export events">
    Keep a security audit log of private key exports:

    ```tsx theme={null}
    await exportPrivateKey({ wallet: user.wallet });

    // Log for security audit
    await logSecurityEvent({
      type: 'private_key_export',
      userId: user.id,
      walletAddress: user.wallet.address,
      timestamp: Date.now(),
      ipAddress: req.ip
    });
    ```
  </Accordion>

  <Accordion title="Educate users">
    Provide educational content about key security:

    ```tsx theme={null}
    <div className="security-education">
      <h3>Before you export</h3>
      <ul>
        <li>Understand that your private key = full wallet access</li>
        <li>Never share it with anyone, including support</li>
        <li>Store it in a password manager or write it down offline</li>
        <li>Be aware of phishing attempts</li>
      </ul>
    </div>
    ```
  </Accordion>

  <Accordion title="Limit export frequency">
    Consider rate limiting exports to prevent abuse:

    ```tsx theme={null}
    const lastExport = await getLastExportTime(user.id);
    const timeSinceExport = Date.now() - lastExport;

    if (timeSinceExport < 3600000) { // 1 hour
      alert('Please wait before exporting again');
      return;
    }

    await exportPrivateKey({ wallet: user.wallet });
    ```
  </Accordion>

  <Accordion title="Require re-authentication">
    For sensitive operations, require fresh authentication:

    ```tsx theme={null}
    const handleExport = async () => {
      // Require user to re-authenticate
      const reauthed = await requireReauth();
      
      if (!reauthed) {
        alert('Re-authentication required');
        return;
      }
      
      await exportPrivateKey({ wallet: user.wallet });
    };
    ```
  </Accordion>

  <Accordion title="Provide alternatives">
    Suggest safer alternatives when appropriate:

    ```tsx theme={null}
    <div className="export-alternatives">
      <p>Consider these safer alternatives:</p>
      <ul>
        <li><strong>Seed phrase backup</strong> - More secure than raw private key</li>
        <li><strong>Hardware wallet</strong> - Best security for long-term storage</li>
        <li><strong>Multi-sig wallet</strong> - Requires multiple approvals</li>
      </ul>
    </div>
    ```
  </Accordion>
</AccordionGroup>

## Security considerations

<Warning>
  Private key export is one of the most sensitive operations in a wallet application. Implement multiple layers of security and education.
</Warning>

**For developers:**

1. **Multiple confirmations** - Require users to confirm multiple times
2. **Clear warnings** - Display unmistakable security warnings
3. **Audit logging** - Log all export events with timestamps and IP addresses
4. **Rate limiting** - Limit how often users can export keys
5. **Re-authentication** - Require fresh login before export
6. **User education** - Provide resources about key security
7. **Alternative options** - Suggest safer backup methods when possible
8. **Compliance** - Ensure export functionality meets regulatory requirements

**For users:**

The Export Key screen helps users by:

* Displaying clear warnings about the risks
* Explaining what a private key is and why it's sensitive
* Requiring explicit confirmation before revealing the key
* Providing guidance on secure storage
* Warning against common phishing attempts

**Common threats to warn about:**

* **Phishing websites** that trick users into entering their private key
* **Malicious browser extensions** that steal private keys
* **Screen recording malware** that captures the displayed key
* **Social engineering** where attackers impersonate support
* **Insecure storage** like plaintext files or unencrypted notes

## Displaying the private key

After user confirmation, the private key should be displayed securely:

```tsx theme={null}
<div className="private-key-display">
  <h3>Your Private Key</h3>
  
  <div className="key-container">
    <code>{privateKey}</code>
    <button onClick={() => copyToClipboard(privateKey)}>
      Copy
    </button>
  </div>
  
  <div className="warnings">
    <p>⚠️ <strong>Never share this key with anyone</strong></p>
    <p>⚠️ Store it in a secure location</p>
    <p>⚠️ Anyone with this key can access your funds</p>
  </div>
  
  <label>
    <input type="checkbox" required />
    I have securely stored my private key
  </label>
</div>
```
