@@ -211,13 +211,67 @@ extension ABI.Element.Function {
211211 }
212212}
213213
214- // MARK: - Event logs decoding
214+ // MARK: - Event logs decoding & encoding
215215
216216extension ABI . Element . Event {
217217 public func decodeReturnedLogs( eventLogTopics: [ Data ] , eventLogData: Data ) -> [ String : Any ] ? {
218218 guard let eventContent = ABIDecoder . decodeLog ( event: self , eventLogTopics: eventLogTopics, eventLogData: eventLogData) else { return nil }
219219 return eventContent
220220 }
221+
222+ func encodeTopic( input: ABI . Element . Event . Input , value: Any ) -> EventFilterParameters . Topic ? {
223+ if case . string = input. type {
224+ guard let string = value as? String else {
225+ return nil
226+ }
227+ return . string( string. sha3 ( . keccak256) . addHexPrefix ( ) )
228+ } else if case . dynamicBytes = input. type {
229+ guard let data = ABIEncoder . convertToData ( value) else {
230+ return nil
231+ }
232+ return . string( data. sha3 ( . keccak256) . toHexString ( ) . addHexPrefix ( ) )
233+ } else if case . address = input. type {
234+ guard let encoded = ABIEncoder . encode ( types: [ input. type] , values: [ value] ) else {
235+ return nil
236+ }
237+ return . string( encoded. toHexString ( ) . addHexPrefix ( ) )
238+ }
239+ guard let data = ABIEncoder . convertToData ( value) !. setLengthLeft ( 32 ) else {
240+ return nil
241+ }
242+ return . string( data. toHexString ( ) . addHexPrefix ( ) )
243+ }
244+
245+ public func encodeParameters( _ parameters: [ Any ? ] ) -> [ EventFilterParameters . Topic ? ] {
246+ guard parameters. count <= inputs. count else {
247+ // too many arguments for fragment
248+ return [ ]
249+ }
250+ var topics : [ EventFilterParameters . Topic ? ] = [ ]
251+
252+ if !anonymous {
253+ topics. append ( . string( topic. toHexString ( ) . addHexPrefix ( ) ) )
254+ }
255+
256+ for (i, p) in parameters. enumerated ( ) {
257+ let input = inputs [ i]
258+ if !input. indexed {
259+ // cannot filter non-indexed parameters; must be null
260+ return [ ]
261+ }
262+ if p == nil {
263+ topics. append ( . string( nil ) )
264+ } else if input. type. isArray {
265+ // filtering with tuples or arrays not supported
266+ return [ ]
267+ } else if let p = p as? Array < Any > {
268+ topics. append ( . strings( p. map { encodeTopic ( input: input, value: $0) } ) )
269+ } else {
270+ topics. append ( encodeTopic ( input: input, value: p!) )
271+ }
272+ }
273+ return topics
274+ }
221275}
222276
223277// MARK: - Function input/output decoding
0 commit comments