solabi 0.0.3

Solidity ABI implementation in Rust
Documentation
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
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
//! Module containing various encoder implementations for `Value` Solidity ABI
//! elements.

use super::{Decodable, Encodable, Value, ValueKind};
use crate::{
    abi::{ConstructorDescriptor, ErrorDescriptor, EventDescriptor, FunctionDescriptor},
    decode::{
        context::{self, DecodeContext},
        DecodeError, Decoder,
    },
    encode::{Encode, Encoder, Size},
    function::Selector,
    log::{Log, Topics},
    primitive::Word,
};
use std::borrow::Cow;

/// An error indicating that some value data is not of the correct type.
#[derive(Debug)]
pub struct ValueKindError;

/// A function encoder.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct FunctionEncoder {
    selector: Selector,
    params: Vec<ValueKind>,
    returns: Vec<ValueKind>,
}

impl FunctionEncoder {
    /// Creates a new function encoder for the specified ABI descriptor.
    pub fn new(descriptor: &FunctionDescriptor) -> Self {
        Self {
            selector: descriptor.selector(),
            params: descriptor
                .inputs
                .iter()
                .map(|i| i.field.kind.clone())
                .collect(),
            returns: descriptor
                .outputs
                .iter()
                .map(|i| i.field.kind.clone())
                .collect(),
        }
    }

    /// Encodes a function call for the specified parameters.
    pub fn encode_params(&self, params: &[Value]) -> Result<Vec<u8>, ValueKindError> {
        of_kind(params, &self.params)?;
        Ok(Value::encode_tuple_with_selector(self.selector, params))
    }

    /// Decodes a function call into its parameters.
    pub fn decode_params(&self, data: &[u8]) -> Result<Vec<Value>, DecodeError> {
        Value::decode_tuple_with_selector(&self.params, self.selector, data)
    }

    /// Encodes function return data.
    pub fn encode_returns(&self, returns: &[Value]) -> Result<Vec<u8>, ValueKindError> {
        of_kind(returns, &self.returns)?;
        Ok(Value::encode_tuple(returns))
    }

    /// Decodes function return data.
    pub fn decode_returns(&self, data: &[u8]) -> Result<Vec<Value>, DecodeError> {
        Value::decode_tuple(&self.returns, data)
    }
}

/// A constructor encoder.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ConstructorEncoder {
    code: Vec<u8>,
    params: Vec<ValueKind>,
}

impl ConstructorEncoder {
    /// Creates a new constructor encoder from a selector.
    pub fn new(code: Vec<u8>, descriptor: &ConstructorDescriptor) -> Self {
        Self {
            code,
            params: descriptor
                .inputs
                .iter()
                .map(|i| i.field.kind.clone())
                .collect(),
        }
    }

    /// Encodes a contract deployment for the specified parameters.
    pub fn encode(&self, params: &[Value]) -> Result<Vec<u8>, ValueKindError> {
        of_kind(params, &self.params)?;
        Ok(Value::encode_tuple_with_prefix(&self.code, params))
    }

    /// Encodes a contract deployment parameters without any code.
    pub fn encode_params(&self, params: &[Value]) -> Result<Vec<u8>, ValueKindError> {
        of_kind(params, &self.params)?;
        Ok(Value::encode_tuple(params))
    }

    /// Decodes the contract deployment parameters from the specified calldata.
    pub fn decode(&self, data: &[u8]) -> Result<Vec<Value>, DecodeError> {
        Value::decode_tuple_with_prefix(&self.params, &self.code, data)
    }

    /// Decodes the contract deployment parameters without any code.
    pub fn decode_params(&self, data: &[u8]) -> Result<Vec<Value>, DecodeError> {
        Value::decode_tuple(&self.params, data)
    }
}

/// An event encoder.
pub struct EventEncoder {
    selector: Option<Word>,
    fields: Vec<(bool, ValueKind)>,
}

impl EventEncoder {
    /// Creates a new error encoder from a selector.
    pub fn new(descriptor: &EventDescriptor) -> Result<Self, ValueKindError> {
        let selector = descriptor.selector();
        if selector.iter().count() + descriptor.inputs.iter().filter(|i| i.indexed).count()
            > Topics::MAX_LEN
        {
            return Err(ValueKindError);
        }

        Ok(Self {
            selector,
            fields: descriptor
                .inputs
                .iter()
                .map(|i| (i.indexed, i.field.kind.clone()))
                .collect(),
        })
    }

    /// Encodes a Solidity error for the specified data.
    pub fn encode(&self, fields: &[Value]) -> Result<Log<'static>, ValueKindError> {
        of_kind(fields, self.fields.iter().map(|(_, kind)| kind))?;
        let encoding = EncodeLog(&self.fields, fields);
        let data = crate::encode(&encoding);

        let mut topics = Topics::default();
        if let Some(selector) = self.selector {
            topics.push(selector)
        }

        for (_, value) in self
            .fields
            .iter()
            .zip(fields)
            .filter(|((indexed, _), _)| *indexed)
        {
            topics.push(value.to_topic());
        }

        Ok(Log {
            topics,
            data: Cow::Owned(data),
        })
    }

    /// Decodes a Solidity error from the return bytes call into its data.
    pub fn decode(&self, log: &Log) -> Result<Vec<Value>, DecodeError> {
        let mut topics = log.topics.into_iter();
        if let Some(selector) = self.selector {
            if !matches!(topics.next(), Some(topic) if topic == selector) {
                return Err(DecodeError::InvalidData);
            }
        }

        let mut fields = context::decode::<DecodeLog>(&log.data, &self.fields)?.0;
        for (((_, kind), value), topic) in self
            .fields
            .iter()
            .zip(&mut fields)
            .filter(|((indexed, kind), _)| *indexed && kind.is_primitive())
            .zip(topics)
        {
            *value = Value::from_word(kind, topic).unwrap();
        }

        Ok(fields)
    }
}

/// Internal type for encoding log data, skipping indexed fields.
struct EncodeLog<'a>(&'a [(bool, ValueKind)], &'a [Value]);

impl EncodeLog<'_> {
    fn values(&self) -> impl Iterator<Item = &'_ Value> + '_ {
        self.0
            .iter()
            .zip(self.1)
            .filter(|((indexed, _), _)| !indexed)
            .map(|(_, value)| value)
    }
}

impl Encode for EncodeLog<'_> {
    fn size(&self) -> Size {
        Size::tuple(self.values().map(|item| Encodable(item).size()))
    }

    fn encode(&self, encoder: &mut Encoder) {
        for value in self.values() {
            encoder.write(&Encodable(value))
        }
    }
}

/// Internal type for decoding log data, skipping indexed fields.
struct DecodeLog(Vec<Value>);

impl DecodeContext for DecodeLog {
    type Context = [(bool, ValueKind)];

    fn is_dynamic_context(context: &Self::Context) -> bool {
        context
            .iter()
            .filter(|(indexed, _)| !indexed)
            .any(|(_, kind)| Decodable::is_dynamic_context(kind))
    }

    fn decode_context(decoder: &mut Decoder, context: &Self::Context) -> Result<Self, DecodeError> {
        Ok(Self(
            context
                .iter()
                .map(|(indexed, kind)| {
                    if *indexed {
                        Ok(Value::default(kind))
                    } else {
                        Ok(decoder.read_context::<Decodable>(kind)?.0)
                    }
                })
                .collect::<Result<_, _>>()?,
        ))
    }
}

/// An error encoder.
pub struct ErrorEncoder {
    selector: Selector,
    fields: Vec<ValueKind>,
}

impl ErrorEncoder {
    /// Creates a new error encoder from a selector.
    pub fn new(descriptor: &ErrorDescriptor) -> Self {
        Self {
            selector: descriptor.selector(),
            fields: descriptor.inputs.iter().map(|i| i.kind.clone()).collect(),
        }
    }

    /// Encodes a Solidity error for the specified data.
    pub fn encode(&self, fields: &[Value]) -> Result<Vec<u8>, ValueKindError> {
        of_kind(fields, &self.fields)?;
        Ok(Value::encode_tuple_with_selector(self.selector, fields))
    }

    /// Decodes a Solidity error from the return bytes call into its data.
    pub fn decode(&self, data: &[u8]) -> Result<Vec<Value>, DecodeError> {
        Value::decode_tuple_with_selector(&self.fields, self.selector, data)
    }
}

fn of_kind<'a, I>(values: &'a [Value], kinds: I) -> Result<(), ValueKindError>
where
    I: IntoIterator<Item = &'a ValueKind>,
    I::IntoIter: ExactSizeIterator,
{
    let kinds = kinds.into_iter();
    if values.len() != kinds.len()
        || values
            .iter()
            .zip(kinds)
            .any(|(value, kind)| !value.is_kind(kind))
    {
        return Err(ValueKindError);
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::value::{Array, Uint};
    use ethprim::{address, uint, U256};
    use hex_literal::hex;

    #[test]
    fn transfer_function_encoding() {
        let function = FunctionDescriptor::parse_declaration(
            "function transfer(address to, uint value) returns (bool)",
        )
        .unwrap();
        let encoder = FunctionEncoder::new(&function);

        let params = [
            Value::Address(address!("0x0101010101010101010101010101010101010101")),
            Value::Uint(Uint::new(256, uint!("4_200_000_000_000_000_000")).unwrap()),
        ];

        let call = hex!(
            "a9059cbb
             0000000000000000000000000101010101010101010101010101010101010101
             0000000000000000000000000000000000000000000000003a4965bf58a40000"
        );

        assert_eq!(encoder.encode_params(&params).unwrap(), call);
        assert_eq!(encoder.decode_params(&call).unwrap(), params);

        let returns = [Value::Bool(true)];

        let ret = hex!("0000000000000000000000000000000000000000000000000000000000000001");

        assert_eq!(encoder.encode_returns(&returns).unwrap(), ret);
        assert_eq!(encoder.decode_returns(&ret).unwrap(), returns);
    }

    #[test]
    fn proxy_constructor() {
        let constructor =
            ConstructorDescriptor::parse_declaration("constructor(address implementation)")
                .unwrap();
        let code = hex!(
            "60a060405234801561001057600080fd5b506040516101083803806101088339
             8101604081905261002f91610040565b6001600160a01b031660805261007056
             5b60006020828403121561005257600080fd5b81516001600160a01b03811681
             1461006957600080fd5b9392505050565b608051608061008860003960006006
             015260806000f3fe60806040527f000000000000000000000000000000000000
             00000000000000000000000000003660008037600080366000845af43d600080
             3e80600181146045573d6000fd5b3d6000f3fea264697066735822122007589b
             6aeb4b41bc48a82fc5939d02ccb42a23fd27c8bf5430706f182fd9a47164736f
             6c63430008100033"
        );
        let encoder = ConstructorEncoder::new(code.to_vec(), &constructor);

        let params = [Value::Address(address!(
            "0x0101010101010101010101010101010101010101"
        ))];

        let data = hex!("0000000000000000000000000101010101010101010101010101010101010101");
        let call = [&code[..], &data[..]].concat();

        assert_eq!(encoder.encode(&params).unwrap(), call);
        assert_eq!(encoder.encode_params(&params).unwrap(), data);
        assert_eq!(encoder.decode(&call).unwrap(), params);
        assert_eq!(encoder.decode_params(&data).unwrap(), params);
    }

    #[test]
    fn transfer_event() {
        let event = EventDescriptor::parse_declaration(
            "event Transfer(address indexed to, address indexed from, uint256 value)",
        )
        .unwrap();
        let encoder = EventEncoder::new(&event).unwrap();

        let fields = [
            Value::Address(address!("0x0101010101010101010101010101010101010101")),
            Value::Address(address!("0x0202020202020202020202020202020202020202")),
            Value::Uint(Uint::new(256, uint!("4_200_000_000_000_000_000")).unwrap()),
        ];

        let log = Log {
            topics: Topics::from([
                event.selector().unwrap(),
                hex!("0000000000000000000000000101010101010101010101010101010101010101"),
                hex!("0000000000000000000000000202020202020202020202020202020202020202"),
            ]),
            data: hex!("0000000000000000000000000000000000000000000000003a4965bf58a40000")[..]
                .into(),
        };

        assert_eq!(encoder.encode(&fields).unwrap(), log);
        assert_eq!(encoder.decode(&log).unwrap(), fields);
    }

    #[test]
    fn anonymous_event_with_indexed_dynamic_field() {
        let event = EventDescriptor::parse_declaration(
            r#"
            event Log(
                uint,
                string indexed,
                (uint, (bool, bytes))[] indexed,
                uint
            ) anonymous
            "#,
        )
        .unwrap();
        let encoder = EventEncoder::new(&event).unwrap();

        let mut fields = [
            Value::Uint(Uint::new(256, uint!("1")).unwrap()),
            Value::String("hello world".to_owned()),
            Value::Array(
                Array::from_values(vec![
                    Value::Tuple(vec![
                        Value::Uint(Uint::new(256, U256::MAX - 1).unwrap()),
                        Value::Tuple(vec![
                            Value::Bool(true),
                            Value::Bytes(hex!("010203").to_vec()),
                        ]),
                    ]),
                    Value::Tuple(vec![
                        Value::Uint(Uint::new(256, U256::MAX - 2).unwrap()),
                        Value::Tuple(vec![
                            Value::Bool(true),
                            Value::Bytes(hex!("040506").to_vec()),
                        ]),
                    ]),
                ])
                .unwrap(),
            ),
            Value::Uint(Uint::new(256, uint!("2")).unwrap()),
        ];

        let log = Log {
            topics: Topics::from([
                hex!("47173285a8d7341e5e972fc677286384f802f8ef42a5ec5f03bbfa254cb01fad"),
                hex!("6b8a0e75eceddd0e7d4d0413a720bce2cb899061e362357db170c49c5563672f"),
            ]),
            data: hex!(
                "0000000000000000000000000000000000000000000000000000000000000001
                 0000000000000000000000000000000000000000000000000000000000000002"
            )[..]
                .into(),
        };

        assert_eq!(encoder.encode(&fields).unwrap(), log);

        // Note that indexed dynamic fields are **not** actually recoverable.
        fields[1] = Value::default(&fields[1].kind());
        fields[2] = Value::default(&fields[2].kind());
        assert_eq!(encoder.decode(&log).unwrap(), fields);
    }

    #[test]
    fn revert_error() {
        let error = ErrorDescriptor::parse_declaration("error Error(string message)").unwrap();
        let encoder = ErrorEncoder::new(&error);

        let fields = [Value::String("revert".to_owned())];

        let data = hex!(
            "08c379a0
             0000000000000000000000000000000000000000000000000000000000000020
             0000000000000000000000000000000000000000000000000000000000000006
             7265766572740000000000000000000000000000000000000000000000000000"
        );

        assert_eq!(encoder.encode(&fields).unwrap(), data);
        assert_eq!(encoder.decode(&data).unwrap(), fields);
    }
}