This is what I use in my app to handle this issue:
// Sometimes TKey will generate a random number between 1 and 0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141 (the range of valid private keys) and is occasionally less than 64 digits long.
// Although the key generated is of type secp256k1, ethers.Wallet will error with INVALID_ARGUMENT if the private key is less than 64 digits.
// To circumvent this issue, we add the leading zero.
function ensure64DigitPrivateKey(privateKey: string): string {
if (privateKey.length < 64) {
return privateKey.padStart(64, "0");
}
return privateKey;
}
// ...
const eoaSigner = new ethers.Wallet(
ensure64DigitPrivateKey(privateKey)
);