import { generateKeyPair } from '@base-org/account';

const keyPair = await generateKeyPair();
console.log('Public key:', keyPair.publicKey);
{
  publicKey: "0x04a1b2c3d4e5f6...",
  privateKey: "0x1a2b3c4d5e6f7a..."
}
Defined in the Base Account SDK
Generates a new P256 key pair for use with Base Account. This is essential for advanced integrations and Sub Account management.

Parameters

This function takes no parameters.

Returns

result
P256KeyPair
A P256 key pair object containing the public and private keys.
import { generateKeyPair } from '@base-org/account';

const keyPair = await generateKeyPair();
console.log('Public key:', keyPair.publicKey);
{
  publicKey: "0x04a1b2c3d4e5f6...",
  privateKey: "0x1a2b3c4d5e6f7a..."
}

Error Handling

CodeMessageDescription
4100Key generation not supportedBrowser does not support cryptographic key generation
4200Insufficient entropySystem lacks sufficient randomness for secure key generation
4300Cryptographic system failureHardware or software cryptographic failure
Private Key SecurityNever expose private keys in client-side code or transmit them over insecure channels. Store them securely using appropriate key management systems.

Integration with Sub Accounts

import { generateKeyPair, createBaseAccountSDK } from '@base-org/account';

async function createSubAccountWithNewKeys() {
  const sdk = createBaseAccountSDK({
    appName: 'My App',
    appLogoUrl: 'https://example.com/logo.png',
    appChainIds: [8453], // Base mainnet
  });

  // Generate new key pair for sub account
  const keyPair = await generateKeyPair();
  
  // Create sub account with the generated keys
  const subAccount = await sdk.subAccount.create({
    type: 'create',
    keys: [{
      type: 'webauthn-p256',
      publicKey: keyPair.publicKey,
    }],
  });
  
  return { subAccount, keyPair };
}

Error Handling

The generateKeyPair function can throw errors for:
  • Cryptographic system failures
  • Insufficient entropy
  • Browser compatibility issues
Always wrap calls to generateKeyPair in a try-catch block:
try {
  const keyPair = await generateKeyPair();
  // Handle successful generation
} catch (error) {
  if (error.message.includes('not supported')) {
    console.error('Browser does not support key generation');
  } else {
    console.error('Key generation failed:', error);
  }
}

Security Considerations

Private Key SecurityNever expose private keys in client-side code or transmit them over insecure channels. Store them securely using appropriate key management systems.
  • Store private keys using secure storage mechanisms
  • Never log private keys to console in production
  • Consider using hardware security modules for production applications
  • Implement proper key rotation policies