Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions packages/walletkit/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@
"@tonconnect/protocol": "^2.3.0",
"@tonconnect/sdk": "^3.2.0",
"@truecarry/tlb-abi": "^0.2.0",
"bip39": "^3.1.0",
"lru-cache": "^11.1.0",
"node-hid": "^3.2.0",
"vite": "^7.1.3"
Expand Down
31 changes: 25 additions & 6 deletions packages/walletkit/src/utils/mnemonic.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,31 @@
import { mnemonicToWalletKey, mnemonicNew } from '@ton/crypto';
import { mnemonicToWalletKey, mnemonicNew, keyPairFromSeed, deriveEd25519Path } from '@ton/crypto';
import { mnemonicToSeed as bip39MnemonicToSeed } from 'bip39';

import { WalletKitError, ERROR_CODES } from '../errors';

async function bip39ToPrivateKey(mnemonic: string[]) {
const seed = await bip39MnemonicToSeed(mnemonic.join(' '));
const TON_DERIVATION_PATH = [44, 607, 0];
const seedContainer = await deriveEd25519Path(seed, TON_DERIVATION_PATH);
return keyPairFromSeed(seedContainer.subarray(0, 32));
}

/**
* Convert a mnemonic to a key pair
* @param mnemonic - The mnemonic to convert, can be an array of strings or a string. 12 or 24 words
* @param mnemonicType - The type of mnemonic to convert, can be 'ton' or 'bip39'
* @returns The key pair
*/
export async function MnemonicToKeyPair(
mnemonic: string | string[],
mnemonicType: 'ton' | 'bip39' = 'ton',
): Promise<{ publicKey: Uint8Array; secretKey: Uint8Array }> {
const mnemonicArray = Array.isArray(mnemonic) ? mnemonic : mnemonic.split(' ');
if (mnemonicArray.length !== 24) {

if (mnemonicArray.length !== 12 && mnemonicArray.length !== 24) {
throw new WalletKitError(
ERROR_CODES.VALIDATION_ERROR,
`Invalid mnemonic length: expected 24 words, got ${mnemonicArray.length}`,
undefined,
{ receivedLength: mnemonicArray.length, expectedLength: 24 },
`Invalid mnemonic length: expected 12 or 24 words, got ${mnemonicArray.length}`,
);
}

Expand All @@ -24,7 +37,13 @@ export async function MnemonicToKeyPair(
};
}

// TODO bip39 support
if (mnemonicType === 'bip39') {
const key = await bip39ToPrivateKey(mnemonicArray);
return {
publicKey: new Uint8Array(key.publicKey),
secretKey: new Uint8Array(key.secretKey),
};
}

throw new WalletKitError(
ERROR_CODES.VALIDATION_ERROR,
Expand Down
10 changes: 10 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading