Skip to content

AbiEvent.encode

ABI-encodes the provided event input (inputs) into an array of Event Topics.

Imports

Named
import { AbiEvent } from 'ox'

Examples

import { AbiEvent } from 'ox'
 
const transfer = AbiEvent.from(
  'event Transfer(address indexed from, address indexed to, uint256 value)'
)
 
const { topics } = AbiEvent.encode(transfer)
['0x406dade31f7ae4b5dbc276258c28dde5ae6d5c2773c5745802c493a2360e55e0']

Passing Arguments

You can pass indexed parameter values to AbiEvent.encode.

TypeScript types will be inferred from the ABI Event, to guard you from inserting the wrong values.

For example, the Transfer event below accepts an address type for the from and to attributes.

import { AbiEvent } from 'ox'
 
const transfer = AbiEvent.from(
  'event Transfer(address indexed from, address indexed to, uint256 value)'
)
 
const { topics } = AbiEvent.encode(transfer, {
  from: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', 
  to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8'
})
[
'0x406dade31f7ae4b5dbc276258c28dde5ae6d5c2773c5745802c493a2360e55e0',
'0x00000000000000000000000000000000f39fd6e51aad88f6f4ce6ab8827279cfffb92266',
'0x0000000000000000000000000000000070997970c51812dc3a010c7d01b50e0d17dc79c8'
]

End-to-end

Below is an end-to-end example of using AbiEvent.encode to encode the topics of a Transfer event and query for events matching the encoded topics on the Wagmi Mint Example contract.

import 'ox/window'
import { AbiEvent, Hex } from 'ox'
 
// 1. Instantiate the `Transfer` ABI Event.
const transfer = AbiEvent.from(
  'event Transfer(address indexed from, address indexed to, uint256 value)',
)
 
// 2. Encode the ABI Event into Event Topics.
const { topics } = AbiEvent.encode(transfer)
 
// 3. Query for events matching the encoded Topics.
const logs = await window.ethereum!.request({
  method: 'eth_getLogs',
  params: [
    {
      address: '0xfba3912ca04dd458c843e2ee08967fc04f3579c2',
      fromBlock: Hex.fromNumber(19760235n),
      toBlock: Hex.fromNumber(19760240n),
      topics,
    },
  ],
})
[
"0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef",
"0x0000000000000000000000000000000000000000000000000000000000000000",
"0x0000000000000000000000000c04d9e9278ec5e4d424476d3ebec70cb5d648d1",
"0x000000000000000000000000000000000000000000000000000000000000025b",
]

Definition

function encode<abiEvent>(
  abiEvent: abiEvent | AbiEvent,
  [args]: encode.Args<abiEvent>,
): encode.ReturnType

Source: src/AbiEvent.ts

Parameters

abiEvent

  • Type: abiEvent | AbiEvent

The event to encode.

[args]

  • Type: encode.Args<abiEvent>

Return Type

The encoded event topics.

encode.ReturnType

Error Type

AbiEvent.encode.ErrorType