> ## Documentation Index
> Fetch the complete documentation index at: https://base-a060aa97-fix-dead-service-links.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# getKeypair

> Retrieve an existing P256 key pair from storage

export const Button = ({children, disabled, variant = "primary", size = "medium", iconName, roundedFull = false, className = '', fullWidth = false, onClick = undefined}) => {
  const variantStyles = {
    primary: 'bg-blue text-black border border-blue hover:bg-blue-80 active:bg-[#06318E] dark:text-white',
    secondary: 'bg-white border border-white text-palette-foreground hover:bg-zinc-15 active:bg-zinc-30',
    outlined: 'bg-transparent text-white border border-white hover:bg-white hover:text-black active:bg-[#E3E7E9]'
  };
  const sizeStyles = {
    medium: 'text-md px-4 py-2 gap-3',
    large: 'text-lg px-6 py-4 gap-5'
  };
  const sizeIconRatio = {
    medium: '0.75rem',
    large: '1rem'
  };
  const classes = ['text-md px-4 py-2 whitespace-nowrap', 'flex items-center justify-center', 'disabled:opacity-40 disabled:pointer-events-none', 'transition-all', variantStyles[variant], sizeStyles[size], roundedFull ? 'rounded-full' : 'rounded-lg', fullWidth ? 'w-full' : 'w-auto', className];
  const buttonClasses = classes.filter(Boolean).join(' ');
  const iconSize = sizeIconRatio[size];
  return <button type="button" disabled={disabled} className={buttonClasses} onClick={onClick}>
      <span>{children}</span>
      {iconName && <Icon name={iconName} width={iconSize} height={iconSize} color="currentColor" />}
    </button>;
};

export const BaseBanner = ({content = null, id, dismissable = true}) => {
  const LOCAL_STORAGE_KEY_PREFIX = 'cb-docs-banner';
  const [isVisible, setIsVisible] = useState(false);
  const onDismiss = () => {
    localStorage.setItem(`${LOCAL_STORAGE_KEY_PREFIX}-${id}`, 'false');
    setIsVisible(false);
  };
  useEffect(() => {
    const storedValue = localStorage.getItem(`${LOCAL_STORAGE_KEY_PREFIX}-${id}`);
    setIsVisible(storedValue !== 'false');
  }, []);
  if (!isVisible) {
    return null;
  }
  return <div className="fixed bottom-0 left-0 right-0 bg-white py-8 px-4 lg:px-12 z-50 text-black dark:bg-black dark:text-white border-t dark:border-gray-95">
      <div className="flex items-center max-w-8xl mx-auto">
        {typeof content === 'function' ? content({
    onDismiss
  }) : content}
        {dismissable && <button onClick={onDismiss} className="flex-shrink-0 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors" aria-label="Dismiss banner">
          ✕
        </button>}
      </div>
    </div>;
};

Defined in the [Base Account SDK](https://github.com/base/account-sdk)

<Info>
  Retrieves an existing P256 key pair if one has been previously generated and stored. This is useful for checking if keys already exist before generating new ones.
</Info>

## Parameters

This function takes no parameters.

## Returns

<ResponseField name="result" type="P256KeyPair | null">
  The stored P256 key pair or `null` if no key pair exists.

  <Expandable title="P256KeyPair properties">
    <ResponseField name="publicKey" type="string">
      The public key for the stored pair in hexadecimal format.
    </ResponseField>

    <ResponseField name="privateKey" type="string">
      The private key for the stored pair. Handle with extreme care.
    </ResponseField>
  </Expandable>
</ResponseField>

<RequestExample>
  ```typescript Basic Usage theme={null}
  import { getKeypair } from '@base-org/account';

  const existingKeyPair = await getKeypair();
  if (existingKeyPair) {
    console.log('Found existing key pair');
  } else {
    console.log('No existing key pair found');
  }
  ```

  ```typescript Get or Create Pattern theme={null}
  import { getKeypair, generateKeyPair } from '@base-org/account';

  let keyPair = await getKeypair();
  if (!keyPair) {
    keyPair = await generateKeyPair();
  }
  ```
</RequestExample>

<ResponseExample>
  ```typescript Success Response (Key Pair Found) theme={null}
  {
    publicKey: "0x04a1b2c3d4e5f6...",
    privateKey: "0x1a2b3c4d5e6f7a..."
  }
  ```

  ```typescript Success Response (No Key Pair) theme={null}
  null
  ```
</ResponseExample>

<Warning>
  **Private Key Access**

  The retrieved private keys should be handled with the same security considerations as newly generated keys.
</Warning>

## Get or Create Pattern

A common pattern is to check for existing keys before generating new ones:

```typescript theme={null}
import { getKeypair, generateKeyPair } from '@base-org/account';

async function getOrCreateKeyPair() {
  // Try to get existing key pair first
  let keyPair = await getKeypair();
  
  if (!keyPair) {
    // Generate new key pair if none exists
    console.log('No existing key pair, generating new one...');
    keyPair = await generateKeyPair();
  } else {
    console.log('Using existing key pair');
  }
  
  return keyPair;
}
```

## Storage Behavior

The `getKeypair` function retrieves keys from:

* Browser's secure storage (for web applications)
* Platform-specific secure storage (for native applications)
* Memory cache (for the current session)

<Info>
  Key pairs are stored securely and are only accessible within the same origin and application context.
</Info>

## Error Handling

The `getKeypair` function can throw errors for:

* Storage access failures
* Data corruption issues
* Browser compatibility problems

Always wrap calls to `getKeypair` in a try-catch block:

```typescript theme={null}
try {
  const keyPair = await getKeypair();
  if (keyPair) {
    // Use existing keys
  } else {
    // No keys found, may need to generate new ones
  }
} catch (error) {
  console.error('Error accessing key storage:', error);
  // Handle storage access errors
}
```

## Key Lifecycle Management

```typescript theme={null}
class KeyManager {
  private keyPair: P256KeyPair | null = null;
  
  async initialize() {
    try {
      // Load existing keys
      this.keyPair = await getKeypair();
      
      if (this.keyPair) {
        console.log('Loaded existing key pair');
      } else {
        console.log('No stored keys found');
      }
      
      return !!this.keyPair;
    } catch (error) {
      console.error('Failed to initialize key manager:', error);
      return false;
    }
  }
  
  hasKeys(): boolean {
    return !!this.keyPair;
  }
  
  async ensureKeys(): Promise<P256KeyPair> {
    if (!this.keyPair) {
      console.log('Generating new key pair...');
      this.keyPair = await generateKeyPair();
    }
    return this.keyPair;
  }
  
  getPublicKey(): string | null {
    return this.keyPair?.publicKey || null;
  }
}
```

## Security Considerations

<Warning>
  **Private Key Access**

  The retrieved private keys should be handled with the same security considerations as newly generated keys.
</Warning>

* Always verify key integrity before use
* Implement proper access controls
* Consider re-generating keys periodically for enhanced security

<BaseBanner
  id="privacy-policy"
  dismissable={false}
  content={({ onDismiss }) => (
<div className="flex items-center">
  <div className="mr-2">
    We're updating the Base Privacy Policy, effective July 25, 2025, to reflect an expansion of Base services. Please review the updated policy here:{" "}
    <a
      href="https://docs.base.org/privacy-policy-2025"
      target="_blank"
      className="whitespace-nowrap"
    >
      Base Privacy Policy
    </a>. By continuing to use Base services, you confirm that you have read and understand the updated policy.
  </div>
  <Button onClick={onDismiss}>I Acknowledge</Button>
</div>
)}
/>
