HDKey.fromExtendedKey() with XPUB support? #3937
Replies: 1 comment
|
Hello @hp8wvvvgnj6asjm7, here is the technical explanation for why deriving addresses from an extended public key (xpub) fails when hardened derivation steps are involved, along with the correct pattern to use in Viem / @scure/bip32. The Cause of the Error When you import an extended public key (xpub), it is a "neutered" key that contains only the public key bytes and chain code. It is mathematically impossible to derive a hardened child key from an xpub without the corresponding xprv. The error Error: Could not derive hardened child key occurs because the code is attempting to derive a path starting from the root (e.g. m/44'/60'/...) instead of deriving unhardened children relative to the account level. How to Derive Deposit Addresses from an xpub Export the xpub at the Account Level (e.g., at path m/44'/60'/0'). At this level, all hardened derivations (44', 60', 0') have already been performed. Derive Unhardened Children relative to that xpub (e.g., /0/0 for the 1st receive address, /0/1 for the 2nd, etc.). import { HDKey } from '@scure/bip32';
import { publicKeyToAddress } from 'viem/utils';
import { bytesToHex } from 'viem';
// 1. Load the xpub (derived previously at m/44'/60'/0')
const xpub = 'xpub6D...'; // Your account-level xpub
const hdKey = HDKey.fromExtendedKey(xpub);
// 2. Derive unhardened path relative to the xpub (/change/address_index)
// 0/0 = external/receive chain, index 0
const childKey = hdKey.derive('0/0');
if (childKey.publicKey) {
// 3. Convert public key bytes to Ethereum 0x address
const address = publicKeyToAddress(bytesToHex(childKey.publicKey));
console.log('Deposit Address:', address);
}Key Takeaways Security: This pattern is ideal for payment gateways and deposit services because your server only needs the xpub to generate unlimited deposit addresses, keeping private keys completely offline. If this clarifies how unhardened derivation works with xpub and helps you build your deposit address service, please consider marking this response as the accepted answer! 🟢 By the way, if you are building EVM tools, working with wallet derivations, or tracking wallet balances across chains, feel free to check out my open-source project Wallet Hunter — if you find it helpful, dropping a ⭐️ star on the repo is always appreciated! |
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
I'm building a service to generate deposit addresses, for that an XPRIV key is not needed.
With ethers, it is done via neutered wallet, in viem, I could not find anything similar.
All reactions