Skip to main content

Legacy Account Key

Import the ethers and @kaiachain/ethers-ext packages to add kaia features on ethers.js

Define sender's address and private key

Set up the provider with the specified kaia Baobab testnet URL. A provider in ethers is a read-only abstraction to access the blockchain data.

Also, you can change the provider URL from baobab to allthatnode

Create a sender's wallet with the private key and provider

Define a message to be signed and recovered

Sign the message with sender's wallet

Recover the address from signed message using ethers.utils.verifyMessage

Recover the address from signed message using klay_recoverFromMessage

SignMsgWithLegacyExample.js

const { ethers } = require("ethers");
const { Wallet } = require("@kaiachain/ethers-ext");
const senderAddr = "0x24e8efd18d65bcb6b3ba15a4698c0b0d69d13ff7";
const senderPriv = "0x4a72b3d09c3d5e28e8652e0111f9c4ce252e8299aad95bb219a38eb0a3f4da49";
const provider = new ethers.providers.JsonRpcProvider("https://public-en-kairos.node.kaia.io");
const wallet = new Wallet(senderPriv, provider);
async function main() {
const msg = "hello";
const msghex = ethers.utils.hexlify(ethers.utils.toUtf8Bytes(msg));
const sig = await wallet.signMessage(msg);
console.log({ senderAddr, msg, msghex, sig });
const addr1 = ethers.utils.verifyMessage(msg, sig);
console.log("recoveredAddr lib", addr1, addr1.toLowerCase() === senderAddr);
const addr2 = await provider.send("klay_recoverFromMessage", [senderAddr, msghex, sig, "latest"]);
console.log("recoveredAddr rpc", addr2, addr2.toLowerCase() === senderAddr);
}
main().catch(console.error);

output

❯ js SignMsgWithLegacyExample.js
{
senderAddr: '0x24e8efd18d65bcb6b3ba15a4698c0b0d69d13ff7',
msg: 'hello',
msghex: '0x68656c6c6f',
sig: '0xcf6792ecd73ccc5efc1612f461bffa699e824a4ed64ec1073709c9d6b8c6daf608060326371544811e2015398f7e48ad839e1f3c551e8cb7c3c82f10d226bd671b'
}
recoveredAddr lib 0x24e8eFD18D65bCb6b3Ba15a4698c0b0d69d13fF7 true
recoveredAddr rpc 0x24e8efd18d65bcb6b3ba15a4698c0b0d69d13ff7 true