Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Break out domainHash generation #301

Merged
merged 2 commits into from
Mar 17, 2023
Merged
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
35 changes: 26 additions & 9 deletions src/sign-typed-data.ts
Original file line number Diff line number Diff line change
Expand Up @@ -327,7 +327,10 @@ function hashStruct(
): Buffer {
validateVersion(version, [SignTypedDataVersion.V3, SignTypedDataVersion.V4]);

return arrToBufArr(keccak256(encodeData(primaryType, data, types, version)));
const encoded = encodeData(primaryType, data, types, version);
const hashed = keccak256(encoded);
const buf = arrToBufArr(hashed);
return buf;
}

/**
Expand Down Expand Up @@ -367,6 +370,26 @@ function sanitizeData<T extends MessageTypes>(
return sanitizedData as Required<TypedMessage<T>>;
}

/**
* Create a EIP-712 Domain Hash.
* This hash is used at the top of the EIP-712 encoding.
*
* @param typedData - The typed message to hash.
* @param version - The EIP-712 version the encoding should comply with.
* @returns The hash of the domain object.
*/
function eip712DomainHash<T extends MessageTypes>(
typedData: TypedMessage<T>,
version: SignTypedDataVersion.V3 | SignTypedDataVersion.V4,
): Buffer {
validateVersion(version, [SignTypedDataVersion.V3, SignTypedDataVersion.V4]);

const sanitizedData = sanitizeData(typedData);
const { domain } = sanitizedData;
const domainType = { EIP712Domain: sanitizedData.types.EIP712Domain };
return hashStruct('EIP712Domain', domain, domainType, version);
}

/**
* Hash a typed message according to EIP-712. The returned message starts with the EIP-712 prefix,
* which is "1901", followed by the hash of the domain separator, then the data (if any).
Expand All @@ -387,14 +410,7 @@ function eip712Hash<T extends MessageTypes>(

const sanitizedData = sanitizeData(typedData);
const parts = [Buffer.from('1901', 'hex')];
parts.push(
hashStruct(
'EIP712Domain',
sanitizedData.domain,
sanitizedData.types,
version,
),
);
parts.push(eip712DomainHash(typedData, version));

if (sanitizedData.primaryType !== 'EIP712Domain') {
parts.push(
Expand All @@ -421,6 +437,7 @@ export const TypedDataUtils = {
hashType,
sanitizeData,
eip712Hash,
eip712DomainHash,
};

/**
Expand Down