Skip to content

Commit

Permalink
demo for signTypedData
Browse files Browse the repository at this point in the history
  • Loading branch information
Eason Smith committed Nov 18, 2024
1 parent 981be33 commit 113687a
Showing 1 changed file with 45 additions and 0 deletions.
45 changes: 45 additions & 0 deletions pages/ethers/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ export default function Index() {
}
const provider = new ethers.BrowserProvider(window.ethereum)
const wallet = await provider.getSigner()
// wallet.signTypedData()
const tx = await wallet.sendTransaction({
to: '0x0000000000000000000000000000000000000000',
value: '1'
Expand All @@ -29,12 +30,56 @@ export default function Index() {
const balance = await provider.getBalance(wallet.getAddress())
setBalance(ethers.formatEther(balance))
}

const signTypedDataTest = async () => {
if (!window.ethereum) return

try {
const provider = new ethers.BrowserProvider(window.ethereum);
await provider.send("eth_requestAccounts", []);
const wallet = await provider.getSigner();
const domain = {
name: "TestApp",
version: "1",
chainId: await provider.getNetwork().then((net) => net.chainId),
verifyingContract: "0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC"
};

const types = {
Person: [
{ name: "name", type: "string" },
{ name: "wallet", type: "address" }
],
Mail: [
{ name: "from", type: "Person" },
{ name: "to", type: "Person" },
{ name: "contents", type: "string" }
]
};

const message = {
from: { name: "Alice", wallet: "0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC" },
to: { name: "Bob", wallet: "0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB" },
contents: "Hello, Bob!"
};

const signature = await wallet.signTypedData(domain, types, message);
console.log("Signature:", signature);

console.log(`Signature: ${signature}`)
} catch (error:any) {
console.error("Error signing typed data:", error);
alert(`Error: ${error.message}`)
}
}

return <Box display="flex" flexDirection="column" alignItems="center" justifyContent="center" height="100vh">
<Box display="flex" flexDirection="row" alignItems="center" justifyContent="center" marginBottom="1rem">
<Text attributes={{marginRight: '1rem'}}>Balance: {balance}</Text>
<Button onClick={getBalance} size="sm">Fetch</Button>
</Box>
<Button onClick={send}>Send</Button>
<Button onClick={signTypedDataTest} attributes={{marginTop: '1rem'}}>signTypedDataTest</Button>
{transactionReceipt && <Text attributes={{whiteSpace: 'pre-line', padding: '2rem'}} as="div">{JSON.stringify(transactionReceipt, null, 2)}</Text>}
</Box>
}

0 comments on commit 113687a

Please sign in to comment.