import type { AbiParameter } from "../abi.js"; import { getIntTypeRange, parseIntType } from "../abi.js"; import { AbiValueOutOfBoundsError, DuplicateAbiParameterNameError, InvalidAbiValueError, UnsupportedAbiTypeError, } from "../errors/abi.js"; import { isAddress, isValidChecksumAddress } from "../eth.js"; import { getPrefixedHexString, getUnprefixedHexString, hexStringToBytes, isHexString, isPrefixedHexString, } from "../hex.js"; import { isObject } from "../lang.js"; /** * A value in the shape that the encoder expects. Aggregates are always * positional, because we strip the parameter names before encoding. */ export type NormalizedAbiValue = bigint | boolean | string | Uint8Array | NormalizedAbiValue[]; /** * An ABI parameter with every name removed, recursively. */ export interface UnnamedAbiParameter { readonly type: string; readonly components?: readonly UnnamedAbiParameter[]; } // In Solidity the rightmost suffix is the outermost array, so `uint256[2][]` is // a dynamic array of `uint256[2]`. The greedy `.+` matches that last suffix. const ARRAY_REGEX = /^(.+)(\[(\d+)?\])$/; const FIXED_BYTES_TYPE_REGEX = /^bytes([1-9]\d?)$/; const DECIMAL_REGEX = /^\d+$/; const HEX_REGEX = /^0x[0-9a-f]+$/i; /** * Parses a Solidity fixed-size bytes type name, like `bytes32`, into its size. * * @param type The type name to parse. * @returns The size in bytes, from 1 to 32, or `undefined` if it isn't a * fixed-size bytes type. */ export function parseFixedBytesType(type: string): number | undefined { const match = FIXED_BYTES_TYPE_REGEX.exec(type); if (match === null) { return undefined; } const size = Number(match[1]); return size <= 32 ? size : undefined; } /** * Throws if two of the given parameters share a name. * * This is checked against the parameter list rather than the value, so that the * array and object input shapes fail the same way. * * @param parameters The parameters to check. * @param path The path of their container, or undefined at the top level. * @throws DuplicateAbiParameterNameError If a name is repeated. */ export function assertNoDuplicateAbiParameterNames( parameters: readonly AbiParameter[], path?: string, ): void { const seen = new Set(); for (const { name } of parameters) { if (name === undefined || name === "") { continue; } if (seen.has(name)) { throw new DuplicateAbiParameterNameError(path, name); } seen.add(name); } } /** * Removes the names of a list of ABI parameters, recursively. * * The encoder derives the shape of the value it expects from whether the * parameters are named: named ones take an object keyed by name, unnamed ones * take a positional array. Dropping the names makes every aggregate positional, * at every nesting level. * * @param parameters The parameters to strip. * @returns The same parameters, without their names. */ export function toUnnamedAbiParameters( parameters: readonly AbiParameter[], ): UnnamedAbiParameter[] { return parameters.map(({ type, components }) => components === undefined ? { type } : { type, components: toUnnamedAbiParameters(components) }, ); } /** * Converts a value into the shape that the encoder expects for a parameter, * validating it against the parameter's Solidity type. * * @param parameter The ABI parameter to normalize the value for. * @param value The value to normalize. * @param path The path of the parameter, used to report errors. * @returns The normalized value. * @throws InvalidAbiValueError If the value can't be encoded as the type. * @throws AbiValueOutOfBoundsError If a numeric value is out of the type's range. * @throws UnsupportedAbiTypeError If the type itself can't be encoded. */ export async function normalizeAbiValue( parameter: AbiParameter, value: unknown, path: string, ): Promise { const { type } = parameter; // Arrays must be checked first, as the check is recursive. const arrayMatch = ARRAY_REGEX.exec(type); if (arrayMatch !== null) { return await normalizeArray(parameter, value, path, arrayMatch); } if (type === "tuple") { return await normalizeTuple(parameter, value, path); } if (type === "address") { return await normalizeAddress(value, path); } if (type === "bool") { return normalizeBool(value, path); } if (type === "string") { if (typeof value !== "string") { throw new InvalidAbiValueError(path, type, value, "invalid string value"); } return value; } if (type === "bytes") { return normalizeBytes(value, path, type, undefined); } const fixedBytesSize = parseFixedBytesType(type); if (fixedBytesSize !== undefined) { return normalizeBytes(value, path, type, fixedBytesSize); } const intType = parseIntType(type); if (intType !== undefined) { return normalizeInt(value, path, type, intType); } throw new UnsupportedAbiTypeError(path, type); } async function normalizeArray( parameter: AbiParameter, value: unknown, path: string, arrayMatch: RegExpExecArray, ): Promise { const { type } = parameter; const elementType = arrayMatch[1]; const fixedLength = arrayMatch[3]; if (!Array.isArray(value)) { throw new InvalidAbiValueError( path, type, value, "invalid array value, expected a JS array", ); } if (fixedLength !== undefined && value.length !== Number(fixedLength)) { throw new InvalidAbiValueError( path, type, value, `invalid array length, expected ${fixedLength} elements but got ${value.length}`, ); } const elementParameter = { ...parameter, type: elementType }; const normalized: NormalizedAbiValue[] = []; for (const [i, element] of value.entries()) { normalized.push( await normalizeAbiValue(elementParameter, element, `${path}[${i}]`), ); } return normalized; } async function normalizeTuple( parameter: AbiParameter, value: unknown, path: string, ): Promise { const { type, components } = parameter; // The encoder rejects zero-sized tuples, as arrays of them can be used to // DoS the decoder. if (components === undefined || components.length === 0) { throw new UnsupportedAbiTypeError(path, type); } assertNoDuplicateAbiParameterNames(components, path); if (Array.isArray(value)) { if (value.length !== components.length) { throw new InvalidAbiValueError( path, type, value, `invalid tuple length, expected ${components.length} components but got ${value.length}`, ); } const normalized: NormalizedAbiValue[] = []; for (const [i, component] of components.entries()) { normalized.push( await normalizeAbiValue( component, value[i], component.name === undefined ? `${path}[${i}]` : `${path}.${component.name}`, ), ); } return normalized; } if (isObject(value)) { const normalized: NormalizedAbiValue[] = []; for (const component of components) { const { name } = component; if (name === undefined || name === "") { throw new InvalidAbiValueError( path, type, value, "invalid tuple value, it has unnamed components so it must be provided as an array", ); } const componentPath = `${path}.${name}`; if (!Object.hasOwn(value, name)) { throw new InvalidAbiValueError( componentPath, component.type, undefined, `missing value for the tuple component "${name}"`, ); } normalized.push( await normalizeAbiValue(component, value[name], componentPath), ); } return normalized; } throw new InvalidAbiValueError( path, type, value, "invalid tuple value, expected an array or an object", ); } function normalizeBool(value: unknown, path: string): boolean { if (typeof value === "boolean") { return value; } // Command line arguments always arrive as strings, so the two Solidity // literals are accepted. Any other string is rejected. if (value === "true") { return true; } if (value === "false") { return false; } throw new InvalidAbiValueError(path, "bool", value, "invalid boolean value"); } async function normalizeAddress(value: unknown, path: string): Promise { if (typeof value !== "string") { throw new InvalidAbiValueError( path, "address", value, "invalid address value, expected a string", ); } // The prefix is re-added in lowercase, so that a "0X"-prefixed address still // matches the checksummed form it is compared against below. const address = getPrefixedHexString(getUnprefixedHexString(value)); if (!isAddress(address)) { throw new InvalidAbiValueError( path, "address", value, "invalid address value", ); } // A mixed-case address carries an EIP-55 checksum, so it is validated to // catch mistyped addresses here instead of failing later, somewhere else. // An all-lowercase or all-uppercase one carries no checksum to validate. const hexAddress = getUnprefixedHexString(address); const isCaseless = hexAddress === hexAddress.toLowerCase() || hexAddress === hexAddress.toUpperCase(); if (!isCaseless && !(await isValidChecksumAddress(address))) { throw new InvalidAbiValueError( path, "address", value, "invalid address checksum", ); } return address.toLowerCase(); } function normalizeBytes( value: unknown, path: string, type: string, length: number | undefined, ): Uint8Array { let bytes: Uint8Array; if (value instanceof Uint8Array) { bytes = value; // The "0x" prefix is required, as an unprefixed string is more likely to // be a value that was meant to be something other than bytes. } else if ( typeof value === "string" && isPrefixedHexString(value) && isHexString(value) ) { if (getUnprefixedHexString(value).length % 2 !== 0) { throw new InvalidAbiValueError( path, type, value, "invalid bytes value, the hex string has an odd length", ); } bytes = hexStringToBytes(value); } else { throw new InvalidAbiValueError( path, type, value, 'invalid bytes value, expected a "0x"-prefixed hex string or a Uint8Array', ); } if (length !== undefined && bytes.length !== length) { throw new InvalidAbiValueError( path, type, value, `invalid bytes length, expected ${length} bytes but got ${bytes.length}`, ); } return bytes; } function normalizeInt( value: unknown, path: string, type: string, intType: { signed: boolean; bits: number }, ): bigint { let normalized: bigint; if (typeof value === "bigint") { normalized = value; } else if (typeof value === "number") { if (!Number.isSafeInteger(value)) { throw new InvalidAbiValueError( path, type, value, "invalid numeric value, it is not a safe integer; use a bigint or a string instead", ); } normalized = BigInt(value); } else if (typeof value === "string") { normalized = parseIntValue(value, path, type); } else { throw new InvalidAbiValueError(path, type, value, "invalid numeric value"); } const { min, max } = getIntTypeRange(intType); if (normalized < min || normalized > max) { throw new AbiValueOutOfBoundsError(path, type, value, min, max); } return normalized; } function parseIntValue(value: string, path: string, type: string): bigint { // BigInt() throws on a signed hex string, so the sign is handled here. const negative = value.startsWith("-"); const magnitude = negative ? value.slice(1) : value; if (!DECIMAL_REGEX.test(magnitude) && !HEX_REGEX.test(magnitude)) { throw new InvalidAbiValueError(path, type, value, "invalid numeric value"); } const parsed = BigInt(magnitude); return negative ? -parsed : parsed; }