From 1e4f176d4f9d0c7dcef6d3e0b18d0eed4d073163 Mon Sep 17 00:00:00 2001 From: Alex Date: Thu, 28 Jul 2022 11:35:56 -0500 Subject: [PATCH] fix something --- src/sign-typed-data.ts | 27 +++++++++++++-------------- src/utils.ts | 3 +++ 2 files changed, 16 insertions(+), 14 deletions(-) diff --git a/src/sign-typed-data.ts b/src/sign-typed-data.ts index f6d1ae80..f13bcbdf 100644 --- a/src/sign-typed-data.ts +++ b/src/sign-typed-data.ts @@ -159,7 +159,7 @@ function encodeField( 'bytes32', version === SignTypedDataVersion.V4 && value == null // eslint-disable-line no-eq-null ? '0x0000000000000000000000000000000000000000000000000000000000000000' - : keccak256(encodeData(type, value, types, version)), + : toBuffer(keccak256(encodeData(type, value, types, version))), ]; } @@ -167,8 +167,9 @@ function encodeField( throw new Error(`missing value for field ${name} of type ${type}`); } + const textEncoder = new (global as any).TextEncoder(); if (type === 'bytes') { - return ['bytes32', keccak256(value)]; + return ['bytes32', toBuffer(keccak256(textEncoder.encode(value)))]; } if (type === 'string') { @@ -176,7 +177,7 @@ function encodeField( if (typeof value === 'string') { value = Buffer.from(value, 'utf8'); } - return ['bytes32', keccak256(value)]; + return ['bytes32', toBuffer(keccak256(textEncoder.encode(value)))]; } if (type.lastIndexOf(']') === type.length - 1) { @@ -191,10 +192,12 @@ function encodeField( ); return [ 'bytes32', - keccak256( - rawEncode( - typeValuePairs.map(([t]) => t), - typeValuePairs.map(([, v]) => v), + toBuffer( + keccak256( + rawEncode( + typeValuePairs.map(([t]) => t), + typeValuePairs.map(([, v]) => v), + ), ), ), ]; @@ -313,10 +316,8 @@ function hashStruct( version: SignTypedDataVersion.V3 | SignTypedDataVersion.V4, ): Buffer { validateVersion(version, [SignTypedDataVersion.V3, SignTypedDataVersion.V4]); - const encodedData = new Uint8Array( - encodeData(primaryType, data, types, version), - ); - return toBuffer(keccak256(encodedData)); + + return toBuffer(keccak256(encodeData(primaryType, data, types, version))); } /** @@ -331,9 +332,7 @@ function hashType( types: Record, ): Buffer { const textEncoder = new (global as any).TextEncoder(); - const encodedHashType = textEncoder.encode( - encodeType(primaryType, types), - ); + const encodedHashType = textEncoder.encode(encodeType(primaryType, types)); return toBuffer(keccak256(encodedHashType)); } diff --git a/src/utils.ts b/src/utils.ts index 31b95480..3719f6a0 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -108,6 +108,9 @@ export function normalize(input: number | string): string { } if (typeof input === 'number') { + if (input < 0) { + return '0x'; + } const buffer = toBuffer(input); input = bufferToHex(buffer); }