All files / evm-wallet-experiment/src/lib keyring.ts

96.42% Statements 27/28
91.66% Branches 11/12
88.88% Functions 8/9
100% Lines 27/27

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133                        3x                                                                             158x     158x 132x   132x     26x     5x 4x         1x     21x 1x       20x   21x 21x                   141x 1x   140x     140x 140x 140x     153x   254x       9x       106x       36x       2x                     3x    
import {
  english,
  generateMnemonic,
  mnemonicToAccount,
  privateKeyToAccount,
  generatePrivateKey,
} from 'viem/accounts';
import type { HDAccount, LocalAccount } from 'viem/accounts';
 
import type { EncryptedMnemonicData } from './mnemonic-crypto.ts';
import type { Address, Hex } from '../types.ts';
 
const harden = globalThis.harden ?? (<T>(value: T): T => value);
 
/**
 * Options for initializing a keyring.
 */
export type KeyringInitOptions =
  | { type: 'srp'; mnemonic: string }
  | { type: 'throwaway'; entropy?: Hex };
 
/**
 * Encrypted keyring init data stored in baggage when a password is used.
 */
export type EncryptedKeyringInit = EncryptedMnemonicData & {
  type: 'srp';
};
 
/**
 * The shape of keyring init data stored in baggage — either plaintext or encrypted.
 */
export type StoredKeyringInit = KeyringInitOptions | EncryptedKeyringInit;
 
/**
 * A keyring manages private keys and signing. Keys never leave this module.
 */
export type Keyring = {
  getAccounts: () => Address[];
  deriveAccount: (index: number) => Address;
  getAccount: (address: Address) => LocalAccount | undefined;
  hasKeys: () => boolean;
  getMnemonic: () => string | undefined;
};
 
/**
 * Create a new keyring from an SRP mnemonic or a throwaway key.
 *
 * @param options - Initialization options.
 * @returns The keyring instance.
 */
export function makeKeyring(options: KeyringInitOptions): Keyring {
  const accounts = new Map<Address, LocalAccount>();
  let mnemonic: string | undefined;
 
  if (options.type === 'srp') {
    mnemonic = options.mnemonic;
    // Derive the first account by default
    deriveAccountInternal(0);
  } else {
    let privateKey: Hex;
    if (options.entropy) {
      // Caller-provided entropy (for SES compartments without crypto global).
      // The caller is responsible for providing cryptographically secure bytes.
      if (!/^0x[\da-f]{64}$/iu.test(options.entropy)) {
        throw new Error(
          'Invalid entropy: expected a 0x-prefixed 32-byte hex string' +
            ` (got ${String(options.entropy).length} chars)`,
        );
      }
      privateKey = options.entropy;
    } else {
      // eslint-disable-next-line n/no-unsupported-features/node-builtins
      if (!globalThis.crypto?.getRandomValues) {
        throw new Error(
          'Throwaway keyring requires crypto.getRandomValues or caller-provided entropy',
        );
      }
      privateKey = generatePrivateKey();
    }
    const account = privateKeyToAccount(privateKey);
    accounts.set(account.address.toLowerCase() as Address, account);
  }
 
  /**
   * Derive an account at the given BIP-44 index.
   *
   * @param index - The address index to derive.
   * @returns The derived account address.
   */
  function deriveAccountInternal(index: number): Address {
    if (!mnemonic) {
      throw new Error('Cannot derive accounts from a throwaway keyring');
    }
    const account: HDAccount = mnemonicToAccount(mnemonic, {
      addressIndex: index,
    });
    const address = account.address.toLowerCase() as Address;
    accounts.set(address, account);
    return address;
  }
 
  return harden({
    getAccounts(): Address[] {
      return [...accounts.keys()];
    },
 
    deriveAccount(index: number): Address {
      return deriveAccountInternal(index);
    },
 
    getAccount(address: Address): LocalAccount | undefined {
      return accounts.get(address.toLowerCase() as Address);
    },
 
    hasKeys(): boolean {
      return accounts.size > 0;
    },
 
    getMnemonic(): string | undefined {
      return mnemonic;
    },
  });
}
 
/**
 * Generate a new random BIP-39 mnemonic phrase (12 words).
 *
 * @returns The mnemonic string.
 */
export function generateMnemonicPhrase(): string {
  return generateMnemonic(english);
}