-
Notifications
You must be signed in to change notification settings - Fork 5.1k
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
Implement EIP712 RPC Wrapper Methods and getEncodedEip712Data
Util
#6286
Merged
Merged
Changes from 14 commits
Commits
Show all changes
15 commits
Select commit
Hold shift + click to select a range
d685859
Add Eip712TypeDetails and Eip712TypedData interfaces
spacesailor24 387ff5e
Init signTypedData rpc method and test
spacesailor24 a4f606f
Init getEncodedEip712Message and test
spacesailor24 d1278f5
Init signTypedData methods and tests
spacesailor24 6a6b3f6
Add return type to signTypedData
spacesailor24 5f45d0e
Add eth_signTypedData and eth_signTypedData_v4 to web3_eth_execution_api
spacesailor24 930d2b4
Add itIf to signTypedData integration test
spacesailor24 a3dd40c
Merge branch '4.x' into wyatt/4.x/5927-eip-712
spacesailor24 30bb2e6
Replace use of Buffer.from with bytesToHex
spacesailor24 a7b12c4
Add additional test cases
spacesailor24 0ace228
Merge branch '4.x' into wyatt/4.x/5927-eip-712
spacesailor24 44fefec
Rename getEncodedEip712Message to getEncodedEip712Data
spacesailor24 2c948d3
Update CHANGELOGs and renamed some files
spacesailor24 7095b8b
Update packages/web3-rpc-methods/test/unit/eth_rpc_methods/sign_typed…
spacesailor24 d80a590
Merge branch '4.x' into wyatt/4.x/5927-eip-712
spacesailor24 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
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
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,201 @@ | ||
/* | ||
This file is part of web3.js. | ||
|
||
web3.js is free software: you can redistribute it and/or modify | ||
it under the terms of the GNU Lesser General Public License as published by | ||
the Free Software Foundation, either version 3 of the License, or | ||
(at your option) any later version. | ||
|
||
web3.js is distributed in the hope that it will be useful, | ||
but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
GNU Lesser General Public License for more details. | ||
|
||
You should have received a copy of the GNU Lesser General Public License | ||
along with web3.js. If not, see <http://www.gnu.org/licenses/>. | ||
*/ | ||
|
||
/** | ||
* @note This code was taken from: https://github.com/Mrtenz/eip-712/tree/master | ||
*/ | ||
|
||
import { Eip712TypedData } from 'web3-types'; | ||
import { isNullish, keccak256 } from 'web3-utils'; | ||
|
||
import ethersAbiCoder from './ethers_abi_coder.js'; | ||
|
||
const TYPE_REGEX = /^\w+/; | ||
const ARRAY_REGEX = /^(.*)\[([0-9]*?)]$/; | ||
|
||
/** | ||
* Get the dependencies of a struct type. If a struct has the same dependency multiple times, it's only included once | ||
* in the resulting array. | ||
*/ | ||
const getDependencies = ( | ||
typedData: Eip712TypedData, | ||
type: string, | ||
dependencies: string[] = [], | ||
): string[] => { | ||
const match = type.match(TYPE_REGEX)!; | ||
const actualType = match[0]; | ||
if (dependencies.includes(actualType)) { | ||
return dependencies; | ||
} | ||
|
||
if (!typedData.types[actualType]) { | ||
return dependencies; | ||
} | ||
|
||
return [ | ||
actualType, | ||
...typedData.types[actualType].reduce<string[]>( | ||
(previous, _type) => [ | ||
...previous, | ||
...getDependencies(typedData, _type.type, previous).filter( | ||
dependency => !previous.includes(dependency), | ||
), | ||
], | ||
[], | ||
), | ||
]; | ||
}; | ||
|
||
/** | ||
* Encode a type to a string. All dependant types are alphabetically sorted. | ||
* | ||
* @param {TypedData} typedData | ||
* @param {string} type | ||
* @param {Options} [options] | ||
* @return {string} | ||
*/ | ||
const encodeType = (typedData: Eip712TypedData, type: string): string => { | ||
const [primary, ...dependencies] = getDependencies(typedData, type); | ||
// eslint-disable-next-line @typescript-eslint/require-array-sort-compare | ||
const types = [primary, ...dependencies.sort()]; | ||
|
||
return types | ||
.map( | ||
dependency => | ||
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions | ||
`${dependency}(${typedData.types[dependency].map( | ||
_type => `${_type.type} ${_type.name}`, | ||
)})`, | ||
) | ||
.join(''); | ||
}; | ||
|
||
/** | ||
* Get a type string as hash. | ||
*/ | ||
const getTypeHash = (typedData: Eip712TypedData, type: string) => | ||
keccak256(encodeType(typedData, type)); | ||
|
||
/** | ||
* Get encoded data as a hash. The data should be a key -> value object with all the required values. All dependant | ||
* types are automatically encoded. | ||
*/ | ||
const getStructHash = ( | ||
typedData: Eip712TypedData, | ||
type: string, | ||
data: Record<string, unknown>, | ||
// eslint-disable-next-line no-use-before-define | ||
): string => keccak256(encodeData(typedData, type, data)); | ||
|
||
/** | ||
* Get the EIP-191 encoded message to sign, from the typedData object. If `hash` is enabled, the message will be hashed | ||
* with Keccak256. | ||
*/ | ||
export const getMessage = (typedData: Eip712TypedData, hash?: boolean): string => { | ||
const EIP_191_PREFIX = '1901'; | ||
const message = `0x${EIP_191_PREFIX}${getStructHash( | ||
typedData, | ||
'EIP712Domain', | ||
typedData.domain as Record<string, unknown>, | ||
).substring(2)}${getStructHash(typedData, typedData.primaryType, typedData.message).substring( | ||
2, | ||
)}`; | ||
|
||
if (hash) { | ||
return keccak256(message); | ||
} | ||
|
||
return message; | ||
}; | ||
|
||
/** | ||
* Encodes a single value to an ABI serialisable string, number or Buffer. Returns the data as tuple, which consists of | ||
* an array of ABI compatible types, and an array of corresponding values. | ||
*/ | ||
const encodeValue = ( | ||
typedData: Eip712TypedData, | ||
type: string, | ||
data: unknown, | ||
): [string, string | Uint8Array | number] => { | ||
const match = type.match(ARRAY_REGEX); | ||
|
||
// Checks for array types | ||
if (match) { | ||
const arrayType = match[1]; | ||
const length = Number(match[2]) || undefined; | ||
|
||
if (!Array.isArray(data)) { | ||
throw new Error('Cannot encode data: value is not of array type'); | ||
} | ||
|
||
if (length && data.length !== length) { | ||
throw new Error( | ||
`Cannot encode data: expected length of ${length}, but got ${data.length}`, | ||
); | ||
} | ||
|
||
const encodedData = data.map(item => encodeValue(typedData, arrayType, item)); | ||
const types = encodedData.map(item => item[0]); | ||
const values = encodedData.map(item => item[1]); | ||
|
||
return ['bytes32', keccak256(ethersAbiCoder.encode(types, values))]; | ||
} | ||
|
||
if (typedData.types[type]) { | ||
return ['bytes32', getStructHash(typedData, type, data as Record<string, unknown>)]; | ||
} | ||
|
||
// Strings and arbitrary byte arrays are hashed to bytes32 | ||
if (type === 'string') { | ||
return ['bytes32', keccak256(data as string)]; | ||
} | ||
|
||
if (type === 'bytes') { | ||
return ['bytes32', keccak256(data as string)]; | ||
} | ||
|
||
return [type, data as string]; | ||
}; | ||
|
||
/** | ||
* Encode the data to an ABI encoded Buffer. The data should be a key -> value object with all the required values. All | ||
* dependant types are automatically encoded. | ||
*/ | ||
const encodeData = ( | ||
typedData: Eip712TypedData, | ||
type: string, | ||
data: Record<string, unknown>, | ||
): string => { | ||
const [types, values] = typedData.types[type].reduce<[string[], unknown[]]>( | ||
([_types, _values], field) => { | ||
if (isNullish(data[field.name]) || isNullish(data[field.name])) { | ||
throw new Error(`Cannot encode data: missing data for '${field.name}'`); | ||
} | ||
|
||
const value = data[field.name]; | ||
const [_type, encodedValue] = encodeValue(typedData, field.type, value); | ||
|
||
return [ | ||
[..._types, _type], | ||
[..._values, encodedValue], | ||
]; | ||
}, | ||
[['bytes32'], [getTypeHash(typedData, type)]], | ||
); | ||
|
||
return ethersAbiCoder.encode(types, values); | ||
}; |
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
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This file has a couple places where
new Error('...')
is used, I've opted not to wrap these asWeb3Error
s as done in the rest of the codebase. I'm choosing to do this so there's some flexibility when this code gets refactored when we implement on own ABI encoder to replace the use of ethers'. I've created #6291 to track this