Skip to content

Instantly share code, notes, and snippets.

@ChristianOConnor
Last active May 28, 2023 07:16
Show Gist options
  • Save ChristianOConnor/047dbedd32abad68cda3f68648f04fba to your computer and use it in GitHub Desktop.
Save ChristianOConnor/047dbedd32abad68cda3f68648f04fba to your computer and use it in GitHub Desktop.
Getting the address from a signature in javascript with ethers.js
const { ethers } = require('ethers');
async function recoverSigner(address, nonce, deadline, v, r, s) {
const domain = {
name: "RandomReachDebug5Local",
version: "1",
chainId: 31337,
verifyingContract: "0x8464135c8F25Da09e49BC8782676a84730C318bC",
};
// Hash the EIP712 Domain Separator
let domainSeparator = ethers.utils.keccak256(
ethers.utils.defaultAbiCoder.encode(
["bytes32", "bytes32", "bytes32", "uint256", "address"],
[
ethers.utils.id("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
ethers.utils.id(domain.name),
ethers.utils.id(domain.version),
domain.chainId,
domain.verifyingContract,
]
)
);
// Hash the EIP712 Message
let messageHash = ethers.utils.keccak256(
ethers.utils.defaultAbiCoder.encode(
["bytes32", "address", "uint256", "uint256"],
[
ethers.utils.id("Request(address minter,uint256 nonce,uint256 deadline)"),
address,
nonce,
deadline,
]
)
);
// Calculate the final digest
let digest = ethers.utils.keccak256(
ethers.utils.solidityPack(
["bytes1", "bytes1", "bytes32", "bytes32"],
["0x19", "0x01", domainSeparator, messageHash]
)
);
const sig = {
r: r,
s: s,
v: v,
};
if (sig.v < 27) {
sig.v += 27;
}
const signer = ethers.utils.recoverAddress(digest, sig);
console.log('this is the digest');
console.log(digest);
return signer;
}
const address = "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266";
const nonce = 0;
const deadline = 1685255589;
const v = 28;
const r = "0xf611b84952f4e151c561865c94c9d1655937eae46470dc0574e822095773f4b5";
const s = "0x3d06c4e5d77364ef6765ddd820578ff6f7cfc4cca2140bf8feee99fa3ef71290";
async function run() {
try {
const signer = await recoverSigner(address, nonce, deadline, v, r, s);
console.log(`The signer is: ${signer}`);
} catch (error) {
console.error(`Error in recovering signer: ${error}`);
}
}
run();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment