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
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
use fuels_types::{
core::{Bits256, Byte, EvmAddress, Identity, SizedAsciiString, StringToken, Token, B512},
errors::Error,
param_types::ParamType,
Address, AssetId, ContractId,
};
use crate::traits::Parameterize;
pub trait Tokenizable {
fn from_token(token: Token) -> Result<Self, Error>
where
Self: Sized;
fn into_token(self) -> Token;
}
impl Tokenizable for Token {
fn from_token(token: Token) -> Result<Self, Error> {
Ok(token)
}
fn into_token(self) -> Token {
self
}
}
impl Tokenizable for Bits256 {
fn from_token(token: Token) -> Result<Self, Error>
where
Self: Sized,
{
match token {
Token::B256(data) => Ok(Bits256(data)),
_ => Err(Error::InvalidData(format!(
"Bits256 cannot be constructed from token {token}"
))),
}
}
fn into_token(self) -> Token {
Token::B256(self.0)
}
}
impl Tokenizable for B512 {
fn from_token(token: Token) -> Result<Self, Error>
where
Self: Sized,
{
if let Token::Struct(tokens) = token {
if let [Token::Array(data)] = tokens.as_slice() {
Ok(B512 {
bytes: <[Bits256; 2usize]>::from_token(Token::Array(data.to_vec()))?,
})
} else {
Err(Error::InstantiationError(format!(
"B512 expected one `Token::Array`, got {tokens:?}",
)))
}
} else {
Err(Error::InstantiationError(format!(
"B512 expected `Token::Struct`, got {token:?}",
)))
}
}
fn into_token(self) -> Token {
Token::Struct(vec![self.bytes.into_token()])
}
}
impl Tokenizable for EvmAddress {
fn from_token(token: Token) -> Result<Self, Error>
where
Self: Sized,
{
if let Token::Struct(tokens) = token {
if let [Token::B256(data)] = tokens.as_slice() {
Ok(EvmAddress::from(Bits256(*data)))
} else {
Err(Error::InstantiationError(format!(
"EvmAddress expected one `Token::B256`, got {tokens:?}",
)))
}
} else {
Err(Error::InstantiationError(format!(
"EvmAddress expected `Token::Struct` got {token:?}",
)))
}
}
fn into_token(self) -> Token {
Token::Struct(vec![Bits256(self.value.0).into_token()])
}
}
impl Tokenizable for Byte {
fn from_token(token: Token) -> Result<Self, Error>
where
Self: Sized,
{
match token {
Token::Byte(value) => Ok(Byte(value)),
_ => Err(Error::InvalidData(format!(
"Byte::from_token failed! Can only handle Token::Byte, got {token:?}"
))),
}
}
fn into_token(self) -> Token {
Token::Byte(self.0)
}
}
impl<T: Tokenizable> Tokenizable for Vec<T> {
fn from_token(token: Token) -> Result<Self, Error>
where
Self: Sized,
{
if let Token::Vector(tokens) = token {
tokens.into_iter().map(Tokenizable::from_token).collect()
} else {
Err(Error::InvalidData(format!(
"Vec::from_token must only be given a Token::Vector. Got: {token}"
)))
}
}
fn into_token(self) -> Token {
let tokens = self.into_iter().map(Tokenizable::into_token).collect();
Token::Vector(tokens)
}
}
impl Tokenizable for bool {
fn from_token(token: Token) -> Result<Self, Error> {
match token {
Token::Bool(data) => Ok(data),
other => Err(Error::InstantiationError(format!(
"Expected `bool`, got {:?}",
other
))),
}
}
fn into_token(self) -> Token {
Token::Bool(self)
}
}
impl Tokenizable for () {
fn from_token(token: Token) -> Result<Self, Error>
where
Self: Sized,
{
match token {
Token::Unit => Ok(()),
other => Err(Error::InstantiationError(format!(
"Expected `Unit`, got {:?}",
other
))),
}
}
fn into_token(self) -> Token {
Token::Unit
}
}
impl Tokenizable for u8 {
fn from_token(token: Token) -> Result<Self, Error> {
match token {
Token::U8(data) => Ok(data),
other => Err(Error::InstantiationError(format!(
"Expected `u8`, got {:?}",
other
))),
}
}
fn into_token(self) -> Token {
Token::U8(self)
}
}
impl Tokenizable for u16 {
fn from_token(token: Token) -> Result<Self, Error> {
match token {
Token::U16(data) => Ok(data),
other => Err(Error::InstantiationError(format!(
"Expected `u16`, got {:?}",
other
))),
}
}
fn into_token(self) -> Token {
Token::U16(self)
}
}
impl Tokenizable for u32 {
fn from_token(token: Token) -> Result<Self, Error> {
match token {
Token::U32(data) => Ok(data),
other => Err(Error::InstantiationError(format!(
"Expected `u32`, got {:?}",
other
))),
}
}
fn into_token(self) -> Token {
Token::U32(self)
}
}
impl Tokenizable for u64 {
fn from_token(token: Token) -> Result<Self, Error> {
match token {
Token::U64(data) => Ok(data),
other => Err(Error::InstantiationError(format!(
"Expected `u64`, got {:?}",
other
))),
}
}
fn into_token(self) -> Token {
Token::U64(self)
}
}
macro_rules! impl_tokenizable_tuples {
($num: expr, $( $ty: ident : $no: tt, )+) => {
impl<$($ty, )+> Tokenizable for ($($ty,)+) where
$(
$ty: Tokenizable,
)+
{
fn from_token(token: Token) -> Result<Self, Error> {
match token {
Token::Tuple(tokens) => {
let mut it = tokens.into_iter();
let mut next_token = move || {
it.next().ok_or_else(|| {
Error::InstantiationError("Ran out of tokens before tuple could be constructed".to_string())
})
};
Ok(($(
$ty::from_token(next_token()?)?,
)+))
},
other => Err(Error::InstantiationError(format!(
"Expected `Tuple`, got {:?}",
other,
))),
}
}
fn into_token(self) -> Token {
Token::Tuple(vec![
$( self.$no.into_token(), )+
])
}
}
}
}
impl_tokenizable_tuples!(1, A:0, );
impl_tokenizable_tuples!(2, A:0, B:1, );
impl_tokenizable_tuples!(3, A:0, B:1, C:2, );
impl_tokenizable_tuples!(4, A:0, B:1, C:2, D:3, );
impl_tokenizable_tuples!(5, A:0, B:1, C:2, D:3, E:4, );
impl_tokenizable_tuples!(6, A:0, B:1, C:2, D:3, E:4, F:5, );
impl_tokenizable_tuples!(7, A:0, B:1, C:2, D:3, E:4, F:5, G:6, );
impl_tokenizable_tuples!(8, A:0, B:1, C:2, D:3, E:4, F:5, G:6, H:7, );
impl_tokenizable_tuples!(9, A:0, B:1, C:2, D:3, E:4, F:5, G:6, H:7, I:8, );
impl_tokenizable_tuples!(10, A:0, B:1, C:2, D:3, E:4, F:5, G:6, H:7, I:8, J:9, );
impl_tokenizable_tuples!(11, A:0, B:1, C:2, D:3, E:4, F:5, G:6, H:7, I:8, J:9, K:10, );
impl_tokenizable_tuples!(12, A:0, B:1, C:2, D:3, E:4, F:5, G:6, H:7, I:8, J:9, K:10, L:11, );
impl_tokenizable_tuples!(13, A:0, B:1, C:2, D:3, E:4, F:5, G:6, H:7, I:8, J:9, K:10, L:11, M:12, );
impl_tokenizable_tuples!(14, A:0, B:1, C:2, D:3, E:4, F:5, G:6, H:7, I:8, J:9, K:10, L:11, M:12, N:13, );
impl_tokenizable_tuples!(15, A:0, B:1, C:2, D:3, E:4, F:5, G:6, H:7, I:8, J:9, K:10, L:11, M:12, N:13, O:14, );
impl_tokenizable_tuples!(16, A:0, B:1, C:2, D:3, E:4, F:5, G:6, H:7, I:8, J:9, K:10, L:11, M:12, N:13, O:14, P:15, );
impl Tokenizable for ContractId {
fn from_token(token: Token) -> Result<Self, Error>
where
Self: Sized,
{
if let Token::Struct(tokens) = token {
if let [Token::B256(data)] = tokens.as_slice() {
Ok(ContractId::from(*data))
} else {
Err(Error::InstantiationError(format!(
"ContractId expected one `Token::B256`, got {tokens:?}"
)))
}
} else {
Err(Error::InstantiationError(format!(
"Address expected `Token::Struct` got {token:?}",
)))
}
}
fn into_token(self) -> Token {
let underlying_data: &[u8; 32] = &self;
Token::Struct(vec![Bits256(*underlying_data).into_token()])
}
}
impl Tokenizable for Address {
fn from_token(token: Token) -> Result<Self, Error>
where
Self: Sized,
{
if let Token::Struct(tokens) = token {
if let [Token::B256(data)] = tokens.as_slice() {
Ok(Address::from(*data))
} else {
Err(Error::InstantiationError(format!(
"Address expected one `Token::B256`, got {tokens:?}"
)))
}
} else {
Err(Error::InstantiationError(format!(
"Address expected `Token::Struct` got {token:?}",
)))
}
}
fn into_token(self) -> Token {
let underlying_data: &[u8; 32] = &self;
Token::Struct(vec![Bits256(*underlying_data).into_token()])
}
}
impl Tokenizable for AssetId {
fn from_token(token: Token) -> Result<Self, Error>
where
Self: Sized,
{
if let Token::Struct(tokens) = token {
if let [Token::B256(data)] = tokens.as_slice() {
Ok(AssetId::from(*data))
} else {
Err(Error::InstantiationError(format!(
"AssetId expected one `Token::B256`, got {tokens:?}"
)))
}
} else {
Err(Error::InstantiationError(format!(
"AssetId expected `Token::Struct` got {token:?}",
)))
}
}
fn into_token(self) -> Token {
let underlying_data: &[u8; 32] = &self;
Token::Struct(vec![Bits256(*underlying_data).into_token()])
}
}
impl<T> Tokenizable for Option<T>
where
T: Tokenizable + Parameterize,
{
fn from_token(token: Token) -> Result<Self, Error> {
if let Token::Enum(enum_selector) = token {
match *enum_selector {
(0u8, _, _) => Ok(None),
(1u8, token, _) => Ok(Option::<T>::Some(T::from_token(token)?)),
(_, _, _) => Err(Error::InstantiationError(format!(
"Could not construct Option from enum_selector. Received: {:?}",
enum_selector
))),
}
} else {
Err(Error::InstantiationError(format!(
"Could not construct Option from token. Received: {token:?}",
)))
}
}
fn into_token(self) -> Token {
let (dis, tok) = match self {
None => (0u8, Token::Unit),
Some(value) => (1u8, value.into_token()),
};
if let ParamType::Enum { variants, .. } = Self::param_type() {
let selector = (dis, tok, variants);
Token::Enum(Box::new(selector))
} else {
panic!("should never happen as Option::param_type() returns valid Enum variants");
}
}
}
impl<T, E> Tokenizable for Result<T, E>
where
T: Tokenizable + Parameterize,
E: Tokenizable + Parameterize,
{
fn from_token(token: Token) -> Result<Self, Error> {
if let Token::Enum(enum_selector) = token {
match *enum_selector {
(0u8, token, _) => Ok(Result::<T, E>::Ok(T::from_token(token)?)),
(1u8, token, _) => Ok(Result::<T, E>::Err(E::from_token(token)?)),
(_, _, _) => Err(Error::InstantiationError(format!(
"Could not construct Result from enum_selector. Received: {:?}",
enum_selector
))),
}
} else {
Err(Error::InstantiationError(format!(
"Could not construct Result from token. Received: {token:?}",
)))
}
}
fn into_token(self) -> Token {
let (dis, tok) = match self {
Ok(value) => (0u8, value.into_token()),
Err(value) => (1u8, value.into_token()),
};
if let ParamType::Enum { variants, .. } = Self::param_type() {
let selector = (dis, tok, variants);
Token::Enum(Box::new(selector))
} else {
panic!("should never happen as Result::param_type() returns valid Enum variants");
}
}
}
impl Tokenizable for Identity {
fn from_token(token: Token) -> Result<Self, Error> {
if let Token::Enum(enum_selector) = token {
match *enum_selector {
(0u8, token, _) => Ok(Identity::Address(Address::from_token(token)?)),
(1u8, token, _) => Ok(Identity::ContractId(ContractId::from_token(token)?)),
(_, _, _) => Err(Error::InstantiationError(format!(
"Could not construct Identity from enum_selector. Received: {:?}",
enum_selector
))),
}
} else {
Err(Error::InstantiationError(format!(
"Could not construct Identity from token. Received: {token:?}",
)))
}
}
fn into_token(self) -> Token {
let (dis, tok) = match self {
Self::Address(value) => (0u8, value.into_token()),
Self::ContractId(value) => (1u8, value.into_token()),
};
if let ParamType::Enum { variants, .. } = Self::param_type() {
let selector = (dis, tok, variants);
Token::Enum(Box::new(selector))
} else {
panic!("should never happen as Identity::param_type() returns valid Enum variants");
}
}
}
impl<const SIZE: usize, T: Tokenizable> Tokenizable for [T; SIZE] {
fn from_token(token: Token) -> Result<Self, Error>
where
Self: Sized,
{
let gen_error = |reason| {
Error::InvalidData(format!(
"While constructing an array of size {SIZE}: {reason}"
))
};
match token {
Token::Array(elements) => {
let len = elements.len();
if len != SIZE {
return Err(gen_error(format!(
"Was given a Token::Array with wrong number of elements: {len}"
)));
}
let detokenized = elements
.into_iter()
.map(Tokenizable::from_token)
.collect::<Result<Vec<T>, _>>()
.map_err(|err| {
gen_error(format!(", not all elements could be detokenized: {err}"))
})?;
Ok(detokenized.try_into().unwrap_or_else(|_| {
panic!("This should never fail since we're checking the length beforehand.")
}))
}
_ => Err(gen_error(format!("Expected a Token::Array, got {token}"))),
}
}
fn into_token(self) -> Token {
Token::Array(self.map(Tokenizable::into_token).to_vec())
}
}
impl<const LEN: usize> Tokenizable for SizedAsciiString<LEN> {
fn from_token(token: Token) -> Result<Self, Error>
where
Self: Sized,
{
match token {
Token::String(contents) => {
let expected_len = contents.get_encodable_str()?.len() ;
if expected_len!= LEN {
return Err(Error::InvalidData(format!("SizedAsciiString<{LEN}>::from_token got a Token::String whose expected length({}) is != {LEN}", expected_len)))
}
Self::new(contents.try_into()?)
},
_ => {
Err(Error::InvalidData(format!("SizedAsciiString<{LEN}>::from_token expected a token of the variant Token::String, got: {token}")))
}
}
}
fn into_token(self) -> Token {
Token::String(StringToken::new(self.into(), LEN))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_from_token_b256() -> Result<(), Error> {
let data = [1u8; 32];
let token = Token::B256(data);
let bits256 = Bits256::from_token(token)?;
assert_eq!(bits256.0, data);
Ok(())
}
#[test]
fn test_into_token_b256() {
let data = [1u8; 32];
let bits256 = Bits256(data);
let token = bits256.into_token();
assert_eq!(token, Token::B256(data));
}
#[test]
fn test_from_token_evm_addr() -> Result<(), Error> {
let data = [1u8; 32];
let token = Token::Struct(vec![Token::B256(data)]);
let evm_address = EvmAddress::from_token(token)?;
let expected_data = [
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1,
];
assert_eq!(evm_address.value.0, expected_data);
Ok(())
}
#[test]
fn test_into_token_evm_addr() {
let data = [1u8; 32];
let evm_address = EvmAddress::from(Bits256(data));
let token = evm_address.into_token();
let expected_data = [
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1,
];
assert_eq!(token, Token::Struct(vec![Token::B256(expected_data)]));
}
#[test]
fn sized_ascii_string_is_tokenized_correctly() -> Result<(), Error> {
let sut = SizedAsciiString::<3>::new("abc".to_string())?;
let token = sut.into_token();
match token {
Token::String(string_token) => {
let contents = string_token.get_encodable_str()?;
assert_eq!(contents, "abc");
}
_ => {
panic!("Not tokenized correctly! Should have gotten a Token::String")
}
}
Ok(())
}
#[test]
fn sized_ascii_string_is_detokenized_correctly() -> anyhow::Result<()> {
let token = Token::String(StringToken::new("abc".to_string(), 3));
let sized_ascii_string =
SizedAsciiString::<3>::from_token(token).expect("Should have succeeded");
assert_eq!(sized_ascii_string, "abc");
Ok(())
}
}