Function encode

  • Encode the data with the provided types. The types must be valid Solidity ABI types.

    This will attempt to parse the values into the correct types. For example, if you pass in a hex string for a uint256, it will be parsed into a bigint. Regular strings are interpreted as UTF-8 strings. If you want to pass in a hex string, you must pass it in as a Uint8Array, or use the "0x"-prefix.

    It will also attempt to infer the types of the values. For example, if you pass in a string for a uint256, it will result in a TypeScript compile-time error. This does not work for all types, however. For example, if you use nested arrays or tuples, the type will be inferred as unknown.

    The following types are supported:

    • address: A 20-byte Ethereum address.
      • As a 40-character-long hexadecimal string, starting with "0x".
      • As a 20-byte-long byte array, i.e., Uint8Array.
    • bool: A boolean value.
      • As a boolean literal, i.e., true or false.
      • As the strings "true" or "false".
    • bytes(n): A dynamic byte array.
      • As a hexadecimal string, starting with "0x".
      • As a byte array, i.e., Uint8Array.
      • As a regular string, which will be interpreted as UTF-8.
    • function: A Solidity function.
      • As a 48-character-long hexadecimal string, starting with "0x".
      • As a 24-byte-long byte array, i.e., Uint8Array.
      • As a SolidityFunction object.
    • int(n): A signed integer.
      • As a number.
      • As a bigint.
      • As a hexadecimal string, starting with "0x".
    • string: A dynamic UTF-8 string.
      • As a regular string.
      • As a hexadecimal string, starting with "0x".
      • As a byte array, i.e., Uint8Array.
    • tuple: A tuple of values.
      • As an array of values.
    • uint(n): An unsigned integer.
      • As a number.
      • As a bigint.
      • As a hexadecimal string, starting with "0x".

    Example

    import { encode, decode } from '@metamask/abi-utils';

    const types = ['uint256', 'string'];
    const encoded = encode(types, [42, 'Hello, world!']);
    const decoded = decode(types, encoded);

    console.log(decoded); // [42n, 'Hello, world!']

    See

    https://docs.soliditylang.org/en/v0.8.17/abi-spec.html

    Returns

    The ABI encoded bytes.

    Type Parameters

    • Type extends readonly string[]

    Parameters

    • types: Type

      The types to encode.

    • values: TypeMap<Type, "input">

      The values to encode. This array must have the same length as the types array.

    • Optional packed: boolean

      Whether to use the non-standard packed mode. Defaults to false.

    • Optional tight: boolean

      Whether to pack the values tightly. When enabled, the values will be packed without any padding. This matches the behaviour of ethereumjs-abi. Defaults to false.

    Returns Uint8Array