datafusion_ethers/
udf.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
use std::any::Any;
use std::sync::Arc;

use alloy::dyn_abi::{DecodedEvent, DynSolValue, EventExt as _};
use alloy::hex::ToHexExt;
use alloy::json_abi::Event;
use alloy::primitives::B256;
use datafusion::arrow::array::{self, Array as _};
use datafusion::error::DataFusionError;
use datafusion::execution::FunctionRegistry;
use datafusion::{
    arrow::datatypes::DataType,
    common::plan_err,
    logical_expr::{ColumnarValue, ScalarUDF, ScalarUDFImpl, Signature, Volatility},
    scalar::ScalarValue,
};

///////////////////////////////////////////////////////////////////////////////////////////////////

pub fn event_to_json(schema: &Event, event: &DecodedEvent) -> serde_json::Value {
    let mut obj = serde_json::Map::new();
    obj.insert("name".to_string(), schema.name.clone().into());

    let mut i_indexed = 0;
    let mut i_body = 0;

    for input in &schema.inputs {
        let value = if input.indexed {
            let v = &event.indexed[i_indexed];
            i_indexed += 1;
            v
        } else {
            let v = &event.body[i_body];
            i_body += 1;
            v
        };

        obj.insert(input.name.clone(), solidity_value_to_json(value));
    }

    obj.into()
}

pub fn solidity_value_to_json(value: &DynSolValue) -> serde_json::Value {
    use serde_json::Value;
    match value {
        DynSolValue::Bool(v) => Value::Bool(*v),
        DynSolValue::Int(v, bits) if *bits <= 64 => Value::Number(v.as_i64().into()),
        DynSolValue::Int(v, _) => Value::String(v.to_string()),
        DynSolValue::Uint(v, bits) if *bits <= 64 => Value::Number(v.to::<u64>().into()),
        DynSolValue::Uint(v, _) => Value::String(v.to_string()),
        DynSolValue::FixedBytes(v, _) => Value::String(v.encode_hex()),
        DynSolValue::Address(v) => Value::String(v.encode_hex()),
        DynSolValue::Function(_) => todo!(),
        DynSolValue::Bytes(v) => Value::String(v.encode_hex()),
        DynSolValue::String(v) => Value::String(v.clone()),
        DynSolValue::Array(_) => todo!(),
        DynSolValue::FixedArray(_) => todo!(),
        DynSolValue::Tuple(_) => todo!(),
    }
}

///////////////////////////////////////////////////////////////////////////////////////////////////

#[derive(Debug)]
struct UdfEthDecodeEvent {
    signature: Signature,
}

impl UdfEthDecodeEvent {
    fn new() -> Self {
        Self {
            signature: Signature::variadic_any(Volatility::Immutable),
        }
    }
}

impl ScalarUDFImpl for UdfEthDecodeEvent {
    fn as_any(&self) -> &dyn Any {
        self
    }

    fn name(&self) -> &str {
        "eth_decode_event"
    }

    fn signature(&self) -> &Signature {
        &self.signature
    }

    #[allow(clippy::get_first)]
    fn return_type(&self, args: &[DataType]) -> datafusion::error::Result<DataType> {
        if args.len() != 6 {
            return plan_err!("eth_decode_event accepts 6 arguments: event_signature, topic0, topic1, topic2, topic3, data");
        }
        if !matches!(args.get(0), Some(&DataType::Utf8)) {
            return plan_err!("event_signature must be a Utf8 scalar");
        }
        if !matches!(args.get(1), Some(&DataType::Binary)) {
            return plan_err!("topic0 must be a Binary");
        }
        if !matches!(args.get(2), Some(&DataType::Binary)) {
            return plan_err!("topic1 must be a Binary");
        }
        if !matches!(args.get(3), Some(&DataType::Binary)) {
            return plan_err!("topic2 must be a Binary");
        }
        if !matches!(args.get(4), Some(&DataType::Binary)) {
            return plan_err!("topic3 must be a Binary");
        }
        if !matches!(args.get(5), Some(&DataType::Binary)) {
            return plan_err!("data must be a Binary");
        }
        Ok(DataType::Utf8)
    }

    fn invoke(&self, args: &[ColumnarValue]) -> datafusion::error::Result<ColumnarValue> {
        let signature = match &args[0] {
            ColumnarValue::Scalar(ScalarValue::Utf8(Some(v))) => v,
            _ => return plan_err!("Event signature must be a Utf8 scalar"),
        };

        let event = Event::parse(signature)
            .map_err(|e| datafusion::error::DataFusionError::External(e.into()))?;

        let args = ColumnarValue::values_to_arrays(&args[1..])?;
        let c_topic0 = datafusion::common::cast::as_binary_array(&args[0])?;
        let c_topic1 = datafusion::common::cast::as_binary_array(&args[1])?;
        let c_topic2 = datafusion::common::cast::as_binary_array(&args[2])?;
        let c_topic3 = datafusion::common::cast::as_binary_array(&args[3])?;
        let c_data = datafusion::common::cast::as_binary_array(&args[4])?;

        let mut builder = array::StringBuilder::new();

        for i in 0..c_topic0.len() {
            let mut topics = Vec::with_capacity(4);

            for c_topic in [c_topic0, c_topic1, c_topic2, c_topic3] {
                if c_topic.is_null(i) {
                    break;
                }
                topics.push(B256::try_from(c_topic.value(i)).expect("??"));
            }
            let data = c_data.value(i);

            let decoded = event
                .decode_log_parts(topics, data, true)
                .map_err(|e| DataFusionError::External(e.into()))?;

            builder.append_value(event_to_json(&event, &decoded).to_string());
        }

        Ok(ColumnarValue::Array(Arc::new(builder.finish())))
    }
}

///////////////////////////////////////////////////////////////////////////////////////////////////

#[derive(Debug)]
struct UdfEthTryDecodeEvent {
    signature: Signature,
}

impl UdfEthTryDecodeEvent {
    fn new() -> Self {
        Self {
            signature: Signature::variadic_any(Volatility::Immutable),
        }
    }
}

impl ScalarUDFImpl for UdfEthTryDecodeEvent {
    fn as_any(&self) -> &dyn Any {
        self
    }

    fn name(&self) -> &str {
        "eth_try_decode_event"
    }

    fn signature(&self) -> &Signature {
        &self.signature
    }

    #[allow(clippy::get_first)]
    fn return_type(&self, args: &[DataType]) -> datafusion::error::Result<DataType> {
        if args.len() != 6 {
            return plan_err!("eth_decode_event accepts 6 arguments: event_signature, topic0, topic1, topic2, topic3, data");
        }
        if !matches!(args.get(0), Some(&DataType::Utf8)) {
            return plan_err!("event_signature must be a Utf8 scalar");
        }
        if !matches!(args.get(1), Some(&DataType::Binary)) {
            return plan_err!("topic0 must be a Binary");
        }
        if !matches!(args.get(2), Some(&DataType::Binary)) {
            return plan_err!("topic1 must be a Binary");
        }
        if !matches!(args.get(3), Some(&DataType::Binary)) {
            return plan_err!("topic2 must be a Binary");
        }
        if !matches!(args.get(4), Some(&DataType::Binary)) {
            return plan_err!("topic3 must be a Binary");
        }
        if !matches!(args.get(5), Some(&DataType::Binary)) {
            return plan_err!("data must be a Binary");
        }
        Ok(DataType::Utf8)
    }

    fn invoke(&self, args: &[ColumnarValue]) -> datafusion::error::Result<ColumnarValue> {
        let signature = match &args[0] {
            ColumnarValue::Scalar(ScalarValue::Utf8(Some(v))) => v,
            _ => return plan_err!("Event signature must be a Utf8 scalar"),
        };

        let event = Event::parse(signature)
            .map_err(|e| datafusion::error::DataFusionError::External(e.into()))?;

        let args = ColumnarValue::values_to_arrays(&args[1..])?;
        let c_topic0 = datafusion::common::cast::as_binary_array(&args[0])?;
        let c_topic1 = datafusion::common::cast::as_binary_array(&args[1])?;
        let c_topic2 = datafusion::common::cast::as_binary_array(&args[2])?;
        let c_topic3 = datafusion::common::cast::as_binary_array(&args[3])?;
        let c_data = datafusion::common::cast::as_binary_array(&args[4])?;

        let mut builder = array::StringBuilder::new();

        for i in 0..c_topic0.len() {
            let mut topics = Vec::with_capacity(4);

            for c_topic in [c_topic0, c_topic1, c_topic2, c_topic3] {
                if c_topic.is_null(i) {
                    break;
                }
                topics.push(B256::try_from(c_topic.value(i)).expect("??"));
            }
            let data = c_data.value(i);

            match event.decode_log_parts(topics, data, true) {
                Ok(decoded) => builder.append_value(event_to_json(&event, &decoded).to_string()),
                Err(_) => builder.append_null(),
            }
        }

        Ok(ColumnarValue::Array(Arc::new(builder.finish())))
    }
}

///////////////////////////////////////////////////////////////////////////////////////////////////

#[derive(Debug)]
struct UdfEthEventSelector {
    signature: Signature,
}

impl UdfEthEventSelector {
    fn new() -> Self {
        Self {
            signature: Signature::exact(vec![DataType::Utf8], Volatility::Immutable),
        }
    }
}

impl ScalarUDFImpl for UdfEthEventSelector {
    fn as_any(&self) -> &dyn Any {
        self
    }

    fn name(&self) -> &str {
        "eth_event_selector"
    }

    fn signature(&self) -> &Signature {
        &self.signature
    }

    fn return_type(&self, _args: &[DataType]) -> datafusion::error::Result<DataType> {
        Ok(DataType::Binary)
    }

    fn invoke(&self, args: &[ColumnarValue]) -> datafusion::error::Result<ColumnarValue> {
        let signature = match &args[0] {
            ColumnarValue::Scalar(ScalarValue::Utf8(Some(v))) => v,
            _ => return plan_err!("Event signature must be a Utf8 scalar"),
        };

        let event = Event::parse(signature)
            .map_err(|e| datafusion::error::DataFusionError::External(e.into()))?;

        let mut builder = array::BinaryBuilder::new();
        builder.append_value(event.selector().as_slice());
        Ok(ColumnarValue::Array(Arc::new(builder.finish())))
    }
}

///////////////////////////////////////////////////////////////////////////////////////////////////

pub fn register_all(registry: &mut dyn FunctionRegistry) -> datafusion::error::Result<()> {
    registry.register_udf(Arc::new(ScalarUDF::from(UdfEthDecodeEvent::new())))?;
    registry.register_udf(Arc::new(ScalarUDF::from(UdfEthTryDecodeEvent::new())))?;
    registry.register_udf(Arc::new(ScalarUDF::from(UdfEthEventSelector::new())))?;
    Ok(())
}

///////////////////////////////////////////////////////////////////////////////////////////////////