Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 18 additions & 3 deletions src/provider/viem-adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,23 @@ export interface ViemAdapterParams {
rpcUrl?: string
}

/** Infer the EIP-712 root struct: the named type no other struct references. */
function inferPrimaryType(types: Record<string, Array<{ type: string }>>): string {
const namedTypes = Object.keys(types).filter(key => key !== "EIP712Domain")
const referencedTypes = new Set<string>()

for (const fields of Object.values(types)) {
for (const field of fields) {
const referencedType = field.type.replace(/\[[^\]]*\]$/g, "")
if (namedTypes.includes(referencedType)) {
referencedTypes.add(referencedType)
}
}
}

return namedTypes.find(type => !referencedTypes.has(type)) ?? namedTypes[0] ?? ""
}

/**
* Creates an OpenSeaWallet from viem clients.
*/
Expand Down Expand Up @@ -95,9 +112,7 @@ function createViemSigner(
verifyingContract: domain.verifyingContract as `0x${string}`,
},
types,
primaryType:
Object.keys(types).find(key => key !== "EIP712Domain") ||
Object.keys(types)[0],
primaryType: inferPrimaryType(types),
message: value,
account: walletClient.account,
})
Expand Down
50 changes: 50 additions & 0 deletions test/provider/viem-adapter.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import { describe, expect, test, vi } from "vitest"
import { createViemWallet } from "../../src/provider/viem-adapter"

describe("createViemWallet", () => {
test("infers the EIP-712 root primaryType instead of using the first type key", async () => {
const signTypedData = vi.fn().mockResolvedValue("0xsignature")
const walletClient = {
account: { address: "0x0000000000000000000000000000000000000001" },
chain: { id: 1 },
signTypedData,
}
const publicClient = {
waitForTransactionReceipt: vi.fn(),
}

const wallet = createViemWallet({
publicClient: publicClient as never,
walletClient: walletClient as never,
})
if (!("signer" in wallet)) {
throw new Error("expected signer")
}

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

await wallet.signer.signTypedData(
{
name: "Example",
version: "1",
chainId: 1,
verifyingContract: "0x0000000000000000000000000000000000000002",
},
types,
{
from: { wallet: walletClient.account.address },
contents: "hello",
},
)

expect(signTypedData).toHaveBeenCalledWith(
expect.objectContaining({ primaryType: "Mail" }),
)
})
})