Last active
February 27, 2024 16:15
-
-
Save ZigBalthazar/c9c37eedb230862af02caa6e3ec625ef to your computer and use it in GitHub Desktop.
EIP-712
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { ethers, verifyTypedData, JsonRpcProvider, Wallet, TypedDataField } from "ethers"; | |
interface IProviderAndSigner { | |
provider: JsonRpcProvider; | |
signer: Wallet; | |
} | |
interface IDomain { | |
name: string, | |
version: string, | |
}; | |
async function getProviderAndSigner(): Promise<IProviderAndSigner> { | |
const provider: JsonRpcProvider = new ethers.JsonRpcProvider("{RPC_URL}"); | |
const signer: Wallet = new ethers.Wallet("{PRIVATE_KEY}", provider); | |
return { provider, signer }; | |
} | |
interface Auth { | |
nick: string; | |
} | |
function constructMessage(nick: string): Auth { | |
return { nick }; | |
} | |
async function signTransaction( | |
signer: Wallet, | |
domain: IDomain, | |
types: Record<string, TypedDataField[]>, | |
message: Auth | |
): Promise<string> { | |
return await signer.signTypedData(domain, types, message); | |
} | |
async function verifySignature( | |
domain: IDomain, | |
types: Record<string, TypedDataField[]>, | |
message: Auth, | |
signature: string | |
): Promise<string> { | |
return verifyTypedData(domain, types, message, signature); | |
} | |
async function main(): Promise<void> { | |
const { provider, signer } = await getProviderAndSigner(); | |
const types: Record<string, TypedDataField[]> = { | |
Auth: [ | |
{ | |
name: "nick", | |
type: "string", | |
}, | |
], | |
}; | |
const domain: IDomain = { | |
name: "EIP712Authentication", | |
version: "1.0.0", | |
}; | |
const message: Auth = constructMessage("Unknown"); | |
const signature: string = await signTransaction(signer, domain, types, message); | |
console.log("Signature:", signature); | |
const r = signature.slice(0, 66); | |
const s = "0x" + signature.slice(66, 130); | |
const v = parseInt(signature.slice(130, 132), 16); | |
console.log({ r, s, v }); | |
const signerAddress: string = await verifySignature(domain, types, message, signature); | |
console.log("Signer address in the signature is:", signerAddress); | |
console.log("Signer address is:", signer.address); | |
} | |
main().catch((error: Error) => { | |
console.error(error); | |
process.exitCode = 1; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment