MCPcopy Create free account
hub / github.com/wevm/viem / encodeEventTopics

Function encodeEventTopics

src/utils/abi/encodeEventTopics.ts:94–144  ·  view source on GitHub ↗
(
  parameters: EncodeEventTopicsParameters<abi, eventName>,
)

Source from the content-addressed store, hash-verified

92 | ErrorType
93
94export function encodeEventTopics<
95 const abi extends Abi | readonly unknown[],
96 eventName extends ContractEventName<abi> | undefined = undefined,
97>(
98 parameters: EncodeEventTopicsParameters<abi, eventName>,
99): EncodeEventTopicsReturnType<abi, eventName> {
100 const { abi, eventName, args } = parameters as EncodeEventTopicsParameters
101
102 let abiItem = abi[0]
103 if (eventName) {
104 const item = getAbiItem({ abi, name: eventName })
105 if (!item) throw new AbiEventNotFoundError(eventName, { docsPath })
106 abiItem = item
107 }
108
109 if (abiItem.type !== 'event')
110 throw new AbiEventNotFoundError(undefined, { docsPath })
111
112 let topics: (Hex | Hex[] | null)[] = []
113 if (args && 'inputs' in abiItem) {
114 const indexedInputs = abiItem.inputs?.filter(
115 (param) => 'indexed' in param && param.indexed,
116 )
117 const args_ = Array.isArray(args)
118 ? args
119 : Object.values(args).length > 0
120 ? (indexedInputs?.map((x: any) => (args as any)[x.name]) ?? [])
121 : []
122
123 if (args_.length > 0) {
124 topics =
125 indexedInputs?.map((param, i) => {
126 if (Array.isArray(args_[i]))
127 return args_[i].map((_: any, j: number) =>
128 encodeArg({ param, value: args_[i][j] }),
129 )
130 return typeof args_[i] !== 'undefined' && args_[i] !== null
131 ? encodeArg({ param, value: args_[i] })
132 : null
133 }) ?? []
134 }
135 }
136 // Anonymous events are not identified by a signature topic, so the event
137 // selector must not be prepended.
138 if (abiItem.anonymous)
139 return topics as EncodeEventTopicsReturnType<abi, eventName>
140
141 const definition = formatAbiItem(abiItem)
142 const signature = toEventSelector(definition as EventDefinition)
143 return [signature, ...topics] as EncodeEventTopicsReturnType<abi, eventName>
144}
145
146export type EncodeArgErrorType =
147 | Keccak256ErrorType

Callers 7

subscribeContractEventFunction · 0.85
subscribeEventFunction · 0.85
createEventFilterFunction · 0.85
getLogsFunction · 0.85

Calls 3

getAbiItemFunction · 0.85
encodeArgFunction · 0.85
formatAbiItemFunction · 0.85

Tested by

no test coverage detected