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
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
// Copyright (C) 2022 Parity Technologies (UK) Ltd. (admin@parity.io)
// This file is a part of the scale-value crate.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//         http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use super::{type_id::TypeId, ScaleTypeDef as TypeDef};
use crate::value::{Composite, Primitive, Value, ValueDef, Variant};
use codec::{Compact, Encode};
use scale_info::{
	form::PortableForm, Field, PortableRegistry, TypeDefArray, TypeDefBitSequence, TypeDefCompact,
	TypeDefComposite, TypeDefPrimitive, TypeDefSequence, TypeDefTuple, TypeDefVariant,
};

/// An error encoding a [`Value`] into SCALE bytes.
#[derive(Debug, Clone, thiserror::Error, PartialEq, Eq)]
pub enum EncodeError<T> {
	/// The composite type we're trying to encode is the wrong length for the type we're trying to encode it into.
	#[error("Composite type is the wrong length; expected length is {expected_len}, but got {}", actual.len())]
	CompositeIsWrongLength {
		/// The composite value that is the wrong length.
		actual: Composite<T>,
		/// The type we're trying to encode it into.
		expected: TypeId,
		/// The length we're expecting our composite type to be to encode properly.
		expected_len: usize,
	},
	/// The variant we're trying to encode was not found in the type we're encoding into.
	#[error("Variant {} was not found", actual.name)]
	VariantNotFound {
		/// The variant type we're trying to encode.
		actual: Variant<T>,
		/// The type we're trying to encode it into.
		expected: TypeId,
	},
	/// The variant or composite field we're trying to encode is not present in the type we're encoding into.
	#[error("The field {missing_field_name} is present on the type we're trying to encode to but hasn't been provided")]
	CompositeFieldIsMissing {
		/// The name of the composite field we can't find.
		missing_field_name: String,
		/// The type we're trying to encode this into.
		expected: TypeId,
	},
	/// The type we're trying to encode into cannot be found in the type registry provided.
	#[error("Cannot find type with ID {0}")]
	TypeIdNotFound(TypeId),
	/// The [`Value`] type we're trying to encode is not the correct shape for the type we're trying to encode it into.
	#[error("Value shape is wrong; expected type ID {expected}, but got value {actual:?}, which could not be coerced into it")]
	WrongShape {
		/// The value we're trying to encode.
		actual: Value<T>,
		/// The type we're trying to encode it into.
		expected: TypeId,
	},
	/// There was an error trying to encode the bit sequence provided.
	#[error("Cannot encode bit sequence: {0}")]
	BitSequenceError(BitSequenceError),
	/// The type ID given is supposed to be compact encoded, but this is not possible to do automatically.
	#[error("The type {0} cannot be compact encoded")]
	CannotCompactEncode(TypeId),
}

/// An error that can occur attempting to encode a bit sequence.
pub type BitSequenceError = scale_bits::scale::format::FromMetadataError;

/// Attempt to SCALE Encode a Value according to the [`TypeId`] and
/// [`PortableRegistry`] provided.
pub fn encode_value_as_type<T: Clone, Id: Into<TypeId>>(
	value: &Value<T>,
	ty_id: Id,
	types: &PortableRegistry,
	bytes: &mut Vec<u8>,
) -> Result<(), EncodeError<T>> {
	let ty_id = ty_id.into();
	let ty = types.resolve(ty_id.id()).ok_or(EncodeError::TypeIdNotFound(ty_id))?;

	match ty.type_def() {
		TypeDef::Composite(inner) => encode_composite_value(value, ty_id, inner, types, bytes),
		TypeDef::Sequence(inner) => encode_sequence_value(value, ty_id, inner, types, bytes),
		TypeDef::Array(inner) => encode_array_value(value, ty_id, inner, types, bytes),
		TypeDef::Tuple(inner) => encode_tuple_value(value, ty_id, inner, types, bytes),
		TypeDef::Variant(inner) => encode_variant_value(value, ty_id, inner, types, bytes),
		TypeDef::Primitive(inner) => encode_primitive_value(value, ty_id, inner, bytes),
		TypeDef::Compact(inner) => encode_compact_value(value, ty_id, inner, types, bytes),
		TypeDef::BitSequence(inner) => encode_bitsequence_value(value, ty_id, inner, types, bytes),
	}?;

	Ok(())
}

fn encode_composite_value<T: Clone>(
	value: &Value<T>,
	type_id: TypeId,
	ty: &TypeDefComposite<PortableForm>,
	types: &PortableRegistry,
	bytes: &mut Vec<u8>,
) -> Result<(), EncodeError<T>> {
	match &value.value {
		ValueDef::Composite(composite) => {
			if ty.fields().len() == 1 && composite.len() != 1 {
				// The composite we've provided doesn't have 1 field; it has many.
				// perhaps the type we're encoding to is a wrapper type then; let's
				// jump in and try to encode our composite to the contents of it (1
				// field composites are transparent anyway in SCALE terms).
				encode_value_as_type(value, ty.fields()[0].ty(), types, bytes)
			} else {
				encode_composite_fields(composite, ty.fields(), type_id, types, bytes)
			}
		}
		_ => {
			if ty.fields().len() == 1 {
				// We didn't provide a composite type, but the composite type we're
				// aiming for has exactly 1 field. Perhaps it's a wrapper type, so let's
				// aim to encode to the contents of it instead (1 field composites are
				// transparent anyway in SCALE terms).
				encode_value_as_type(value, ty.fields()[0].ty(), types, bytes)
			} else {
				Err(EncodeError::WrongShape { actual: value.clone(), expected: type_id })
			}
		}
	}
}

fn encode_sequence_value<T: Clone>(
	value: &Value<T>,
	type_id: TypeId,
	ty: &TypeDefSequence<PortableForm>,
	types: &PortableRegistry,
	bytes: &mut Vec<u8>,
) -> Result<(), EncodeError<T>> {
	match &value.value {
		// Let's see whether our composite type is the right length,
		// and try to encode each inner value into what the sequence wants.
		ValueDef::Composite(c) => {
			// Compact encoded length comes first
			Compact(c.len() as u64).encode_to(bytes);
			let ty = ty.type_param();
			for value in c.values() {
				encode_value_as_type(value, ty, types, bytes)?;
			}
		}
		// As a special case, primitive U256/I256s are arrays, and may be compatible
		// with the sequence type being asked for, too.
		ValueDef::Primitive(Primitive::I256(a) | Primitive::U256(a)) => {
			// Compact encoded length comes first
			Compact(a.len() as u64).encode_to(bytes);
			let ty = ty.type_param();
			for val in a {
				if encode_value_as_type(&Value::u128(*val as u128), ty, types, bytes).is_err() {
					return Err(EncodeError::WrongShape {
						actual: value.clone(),
						expected: type_id,
					});
				}
			}
		}
		_ => return Err(EncodeError::WrongShape { actual: value.clone(), expected: type_id }),
	};
	Ok(())
}

fn encode_array_value<T: Clone>(
	value: &Value<T>,
	type_id: TypeId,
	ty: &TypeDefArray<PortableForm>,
	types: &PortableRegistry,
	bytes: &mut Vec<u8>,
) -> Result<(), EncodeError<T>> {
	match &value.value {
		// Let's see whether our composite type is the right length,
		// and try to encode each inner value into what the array wants.
		ValueDef::Composite(c) => {
			let arr_len = ty.len() as usize;
			if c.len() != arr_len {
				return Err(EncodeError::CompositeIsWrongLength {
					actual: c.clone(),
					expected: type_id,
					expected_len: arr_len,
				});
			}

			let ty = ty.type_param();
			for value in c.values() {
				encode_value_as_type(value, ty, types, bytes)?;
			}
		}
		// As a special case, primitive U256/I256s are arrays, and may be compatible
		// with the array type being asked for, too.
		ValueDef::Primitive(Primitive::I256(a) | Primitive::U256(a)) => {
			let arr_len = ty.len() as usize;
			if a.len() != arr_len {
				return Err(EncodeError::WrongShape { actual: value.clone(), expected: type_id });
			}

			let ty = ty.type_param();
			for val in a {
				if encode_value_as_type(&Value::u128(*val as u128), ty, types, bytes).is_err() {
					return Err(EncodeError::WrongShape {
						actual: value.clone(),
						expected: type_id,
					});
				}
			}
		}
		_ => return Err(EncodeError::WrongShape { actual: value.clone(), expected: type_id }),
	};
	Ok(())
}

fn encode_tuple_value<T: Clone>(
	value: &Value<T>,
	type_id: TypeId,
	ty: &TypeDefTuple<PortableForm>,
	types: &PortableRegistry,
	bytes: &mut Vec<u8>,
) -> Result<(), EncodeError<T>> {
	match &value.value {
		ValueDef::Composite(composite) => {
			if composite.len() != ty.fields().len() {
				return Err(EncodeError::CompositeIsWrongLength {
					actual: composite.clone(),
					expected: type_id,
					expected_len: ty.fields().len(),
				});
			}
			// We don't care whether the fields are named or unnamed
			// as long as we have the number of them that we expect..
			let field_value_pairs = ty.fields().iter().zip(composite.values());
			for (ty, value) in field_value_pairs {
				encode_value_as_type(value, ty, types, bytes)?;
			}
			Ok(())
		}
		_ => {
			if ty.fields().len() == 1 {
				// A 1-field tuple? try encoding inner content then.
				encode_value_as_type(value, ty.fields()[0], types, bytes)
			} else {
				Err(EncodeError::WrongShape { actual: value.clone(), expected: type_id })
			}
		}
	}
}

fn encode_variant_value<T: Clone>(
	value: &Value<T>,
	type_id: TypeId,
	ty: &TypeDefVariant<PortableForm>,
	types: &PortableRegistry,
	bytes: &mut Vec<u8>,
) -> Result<(), EncodeError<T>> {
	let variant = match &value.value {
		ValueDef::Variant(variant) => variant,
		_ => return Err(EncodeError::WrongShape { actual: value.clone(), expected: type_id }),
	};

	let variant_type = ty.variants().iter().find(|v| v.name() == &variant.name);

	let variant_type = match variant_type {
		None => {
			return Err(EncodeError::VariantNotFound { actual: variant.clone(), expected: type_id })
		}
		Some(v) => v,
	};

	variant_type.index().encode_to(bytes);
	encode_composite_fields(&variant.values, variant_type.fields(), type_id, types, bytes)
}

fn encode_composite_fields<T: Clone>(
	composite: &Composite<T>,
	fields: &[Field<PortableForm>],
	type_id: TypeId,
	types: &PortableRegistry,
	bytes: &mut Vec<u8>,
) -> Result<(), EncodeError<T>> {
	if fields.len() != composite.len() {
		return Err(EncodeError::CompositeIsWrongLength {
			actual: composite.clone(),
			expected: type_id,
			expected_len: fields.len(),
		});
	}

	// 0 length? Nothing more to do!
	if composite.is_empty() {
		return Ok(());
	}

	// Does the type we're encoding to have named fields or not?
	let is_named = fields[0].name().is_some();

	match (composite, is_named) {
		// If we provide named fields, and named fields are present on the target
		// type, then we encode according to the names.
		(Composite::Named(values), true) => {
			// Match up named values with those of the type we're encoding to.
			for field in fields.iter() {
				let field_name = field.name().expect("field should be named; checked above");
				let value = values.iter().find(|(n, _)| field_name == n).map(|(_, value)| value);

				match value {
					Some(value) => {
						encode_value_as_type(value, field.ty(), types, bytes)?;
					}
					None => {
						return Err(EncodeError::CompositeFieldIsMissing {
							expected: type_id,
							missing_field_name: field_name.clone(),
						})
					}
				}
			}
			Ok(())
		}
		// If we provide named fields, and the target is unnamed fields, we'll just
		// try to line them up in the order that they were given.
		(Composite::Named(values), false) => {
			for (field, (_name, value)) in fields.iter().zip(values) {
				encode_value_as_type(value, field.ty(), types, bytes)?;
			}
			Ok(())
		}
		// If we provide unnamed fields, we don't care whether the target fields are
		// named or not; we'll just line them up.
		(Composite::Unnamed(values), _) => {
			for (field, value) in fields.iter().zip(values) {
				encode_value_as_type(value, field.ty(), types, bytes)?;
			}
			Ok(())
		}
	}
}

// Attempt to convert a given primitive value into the integer type
// required, failing with an appropriate EncodeValueError if not successful.
macro_rules! primitive_to_integer {
	($id:ident, $prim:ident, $value:expr => $ty:ident) => {{
		macro_rules! err {
			() => {
				EncodeError::WrongShape { actual: $value.clone(), expected: $id }
			};
		}
		let out: Result<$ty, _> = match $prim {
			Primitive::U128(v) => v.clone().try_into().map_err(|_| err!()),
			Primitive::I128(v) => v.clone().try_into().map_err(|_| err!()),
			// Treat chars as u32s to mirror what we do for decoding:
			Primitive::Char(v) => (v.clone() as u32).try_into().map_err(|_| err!()),
			_ => Err(err!()),
		};
		out
	}};
}

fn encode_primitive_value<T: Clone>(
	value: &Value<T>,
	type_id: TypeId,
	ty: &TypeDefPrimitive,
	bytes: &mut Vec<u8>,
) -> Result<(), EncodeError<T>> {
	let primitive = match &value.value {
		ValueDef::Primitive(primitive) => primitive,
		_ => return Err(EncodeError::WrongShape { actual: value.clone(), expected: type_id }),
	};

	// Attempt to encode our value type into the expected shape.
	match (ty, primitive) {
		(TypeDefPrimitive::Bool, Primitive::Bool(bool)) => {
			bool.encode_to(bytes);
		}
		(TypeDefPrimitive::Char, Primitive::Char(c)) => {
			// Treat chars as u32's
			(*c as u32).encode_to(bytes);
		}
		(TypeDefPrimitive::Str, Primitive::String(s)) => {
			s.encode_to(bytes);
		}
		(TypeDefPrimitive::I256, Primitive::I256(a)) => {
			a.encode_to(bytes);
		}
		(TypeDefPrimitive::U256, Primitive::U256(a)) => {
			a.encode_to(bytes);
		}
		(TypeDefPrimitive::U8, primitive) => {
			primitive_to_integer!(type_id, primitive, value => u8)?.encode_to(bytes);
		}
		(TypeDefPrimitive::U16, primitive) => {
			primitive_to_integer!(type_id, primitive, value => u16)?.encode_to(bytes);
		}
		(TypeDefPrimitive::U32, primitive) => {
			primitive_to_integer!(type_id, primitive, value => u32)?.encode_to(bytes);
		}
		(TypeDefPrimitive::U64, primitive) => {
			primitive_to_integer!(type_id, primitive, value => u64)?.encode_to(bytes);
		}
		(TypeDefPrimitive::U128, primitive) => {
			primitive_to_integer!(type_id, primitive, value => u128)?.encode_to(bytes);
		}
		(TypeDefPrimitive::I8, primitive) => {
			primitive_to_integer!(type_id, primitive, value => i8)?.encode_to(bytes);
		}
		(TypeDefPrimitive::I16, primitive) => {
			primitive_to_integer!(type_id, primitive, value => i16)?.encode_to(bytes);
		}
		(TypeDefPrimitive::I32, primitive) => {
			primitive_to_integer!(type_id, primitive, value => i32)?.encode_to(bytes);
		}
		(TypeDefPrimitive::I64, primitive) => {
			primitive_to_integer!(type_id, primitive, value => i64)?.encode_to(bytes);
		}
		(TypeDefPrimitive::I128, primitive) => {
			primitive_to_integer!(type_id, primitive, value => i128)?.encode_to(bytes);
		}
		_ => {
			return Err(EncodeError::WrongShape { actual: value.clone(), expected: type_id });
		}
	}
	Ok(())
}

fn encode_compact_value<T: Clone>(
	value: &Value<T>,
	type_id: TypeId,
	ty: &TypeDefCompact<PortableForm>,
	types: &PortableRegistry,
	bytes: &mut Vec<u8>,
) -> Result<(), EncodeError<T>> {
	// Types that are compact encodable:
	enum CompactTy {
		U8,
		U16,
		U32,
		U64,
		U128,
	}

	// Resolve to a primitive type inside the compact encoded type (or fail if
	// we hit some type we wouldn't know how to work with).
	let mut inner_ty_id = ty.type_param().id();
	let inner_ty = loop {
		let inner_ty = types
			.resolve(inner_ty_id)
			.ok_or_else(|| EncodeError::TypeIdNotFound(inner_ty_id.into()))?
			.type_def();

		match inner_ty {
			TypeDef::Composite(c) => {
				if c.fields().len() == 1 {
					inner_ty_id = c.fields()[0].ty().id();
				} else {
					return Err(EncodeError::CannotCompactEncode(inner_ty_id.into()));
				}
			}
			TypeDef::Tuple(t) => {
				if t.fields().len() == 1 {
					inner_ty_id = t.fields()[0].id();
				} else {
					return Err(EncodeError::CannotCompactEncode(inner_ty_id.into()));
				}
			}
			TypeDef::Primitive(primitive) => {
				break match primitive {
					// These are the primitives that we can compact encode:
					TypeDefPrimitive::U8 => CompactTy::U8,
					TypeDefPrimitive::U16 => CompactTy::U16,
					TypeDefPrimitive::U32 => CompactTy::U32,
					TypeDefPrimitive::U64 => CompactTy::U64,
					TypeDefPrimitive::U128 => CompactTy::U128,
					_ => return Err(EncodeError::CannotCompactEncode(inner_ty_id.into())),
				};
			}
			TypeDef::Variant(_)
			| TypeDef::Sequence(_)
			| TypeDef::Array(_)
			| TypeDef::Compact(_)
			| TypeDef::BitSequence(_) => return Err(EncodeError::CannotCompactEncode(inner_ty_id.into())),
		}
	};

	// resolve to the innermost value that we have in the same way, expecting to get out
	// a single primitive value.
	let mut value = value;
	let inner_primitive = {
		loop {
			match &value.value {
				ValueDef::Composite(c) => {
					if c.len() == 1 {
						value = c.values().next().expect("length of 1; value should exist");
					} else {
						return Err(EncodeError::WrongShape {
							actual: value.clone(),
							expected: inner_ty_id.into(),
						});
					}
				}
				ValueDef::Primitive(primitive) => break primitive,
				ValueDef::Variant(_) | ValueDef::BitSequence(_) => {
					return Err(EncodeError::WrongShape {
						actual: value.clone(),
						expected: inner_ty_id.into(),
					})
				}
			}
		}
	};

	// Try to compact encode the primitive type we have into the type asked for:
	match inner_ty {
		CompactTy::U8 => {
			let val = primitive_to_integer!(type_id, inner_primitive, value => u8)?;
			Compact(val).encode_to(bytes);
		}
		CompactTy::U16 => {
			let val = primitive_to_integer!(type_id, inner_primitive, value => u16)?;
			Compact(val).encode_to(bytes);
		}
		CompactTy::U32 => {
			let val = primitive_to_integer!(type_id, inner_primitive, value => u32)?;
			Compact(val).encode_to(bytes);
		}
		CompactTy::U64 => {
			let val = primitive_to_integer!(type_id, inner_primitive, value => u64)?;
			Compact(val).encode_to(bytes);
		}
		CompactTy::U128 => {
			let val = primitive_to_integer!(type_id, inner_primitive, value => u128)?;
			Compact(val).encode_to(bytes);
		}
	};

	Ok(())
}

fn encode_bitsequence_value<T: Clone>(
	value: &Value<T>,
	type_id: TypeId,
	ty: &TypeDefBitSequence<PortableForm>,
	types: &PortableRegistry,
	bytes: &mut Vec<u8>,
) -> Result<(), EncodeError<T>> {
	let format =
		scale_bits::Format::from_metadata(ty, types).map_err(EncodeError::BitSequenceError)?;

	match &value.value {
		ValueDef::BitSequence(bits) => {
			// Bits can be encoded easily enough:
			scale_bits::encode_using_format_to(bits.iter(), format, bytes)
		}
		ValueDef::Composite(Composite::Unnamed(vals)) => {
			// For composite bools we need to find and store them first:
			let mut bools = Vec::with_capacity(vals.len());
			for val in vals {
				match val.value {
					ValueDef::Primitive(Primitive::Bool(b)) => bools.push(b),
					_ => {
						return Err(EncodeError::WrongShape {
							actual: val.clone(),
							expected: type_id,
						})
					}
				}
			}
			// And then we can encode them:
			scale_bits::encode_using_format_to(bools.into_iter(), format, bytes)
		}
		_ => return Err(EncodeError::WrongShape { actual: value.clone(), expected: type_id }),
	};

	Ok(())
}

#[cfg(test)]
mod test {
	use super::*;

	/// Given a type definition, return the PortableType and PortableRegistry
	/// that our decode functions expect.
	fn make_type<T: scale_info::TypeInfo + 'static>() -> (TypeId, PortableRegistry) {
		let m = scale_info::MetaType::new::<T>();
		let mut types = scale_info::Registry::new();
		let id = types.register_type(&m);
		let portable_registry: PortableRegistry = types.into();

		(id.into(), portable_registry)
	}

	// Attempt to SCALE encode a Value and expect it to match the standard Encode impl for the second param given.
	fn assert_can_encode_to_type<T: Encode + scale_info::TypeInfo + 'static>(
		value: Value<()>,
		ty: T,
	) {
		let expected = ty.encode();
		let mut buf = Vec::new();

		let (ty_id, types) = make_type::<T>();

		encode_value_as_type(&value, ty_id, &types, &mut buf)
			.expect("error encoding value as type");
		assert_eq!(expected, buf);
	}

	#[test]
	fn can_encode_basic_primitive_values() {
		assert_can_encode_to_type(Value::i128(123), 123i8);
		assert_can_encode_to_type(Value::i128(123), 123i16);
		assert_can_encode_to_type(Value::i128(123), 123i32);
		assert_can_encode_to_type(Value::i128(123), 123i64);
		assert_can_encode_to_type(Value::i128(123), 123i128);

		assert_can_encode_to_type(Value::u128(123), 123u8);
		assert_can_encode_to_type(Value::u128(123), 123u16);
		assert_can_encode_to_type(Value::u128(123), 123u32);
		assert_can_encode_to_type(Value::u128(123), 123u64);
		assert_can_encode_to_type(Value::u128(123), 123u128);

		assert_can_encode_to_type(Value::bool(true), true);
		assert_can_encode_to_type(Value::bool(false), false);

		assert_can_encode_to_type(Value::string("Hello"), "Hello");
		assert_can_encode_to_type(Value::string("Hello"), "Hello".to_string());
	}

	#[test]
	fn chars_encoded_like_numbers() {
		assert_can_encode_to_type(Value::char('j'), 'j' as u32);
		assert_can_encode_to_type(Value::char('j'), b'j');
	}

	#[test]
	fn can_encode_primitive_arrs_to_array() {
		use crate::Primitive;

		assert_can_encode_to_type(Value::primitive(Primitive::U256([12u8; 32])), [12u8; 32]);
		assert_can_encode_to_type(Value::primitive(Primitive::I256([12u8; 32])), [12u8; 32]);
	}

	#[test]
	fn can_encode_primitive_arrs_to_vecs() {
		use crate::Primitive;

		assert_can_encode_to_type(Value::primitive(Primitive::U256([12u8; 32])), vec![12u8; 32]);
		assert_can_encode_to_type(Value::primitive(Primitive::I256([12u8; 32])), vec![12u8; 32]);
	}

	#[test]
	fn can_encode_arrays() {
		let value = Value::unnamed_composite(vec![
			Value::u128(1),
			Value::u128(2),
			Value::u128(3),
			Value::u128(4),
		]);
		assert_can_encode_to_type(value, [1u16, 2, 3, 4]);
	}

	#[test]
	fn can_encode_variants() {
		#[derive(Encode, scale_info::TypeInfo)]
		enum Foo {
			Named { hello: String, foo: bool },
			Unnamed(u64, Vec<bool>),
		}

		let named_value = Value::named_variant(
			"Named",
			[
				// Deliverately a different order; order shouldn't matter:
				("foo", Value::bool(true)),
				("hello", Value::string("world")),
			],
		);
		assert_can_encode_to_type(named_value, Foo::Named { hello: "world".into(), foo: true });

		let unnamed_value = Value::unnamed_variant(
			"Unnamed",
			[
				Value::u128(123),
				Value::unnamed_composite(vec![
					Value::bool(true),
					Value::bool(false),
					Value::bool(true),
				]),
			],
		);
		assert_can_encode_to_type(unnamed_value, Foo::Unnamed(123, vec![true, false, true]));
	}

	#[test]
	fn can_encode_structs() {
		#[derive(Encode, scale_info::TypeInfo)]
		struct Foo {
			hello: String,
			foo: bool,
		}

		let named_value = Value::named_composite([
			// Deliverately a different order; order shouldn't matter:
			("foo", Value::bool(true)),
			("hello", Value::string("world")),
		]);
		assert_can_encode_to_type(named_value, Foo { hello: "world".into(), foo: true });
	}

	#[test]
	fn can_encode_tuples_from_named_composite() {
		let named_value =
			Value::named_composite([("hello", Value::string("world")), ("foo", Value::bool(true))]);
		assert_can_encode_to_type(named_value, ("world", true));
	}

	#[test]
	fn can_encode_tuples_from_unnamed_composite() {
		let unnamed_value = Value::unnamed_composite([Value::string("world"), Value::bool(true)]);
		assert_can_encode_to_type(unnamed_value, ("world", true));
	}

	#[test]
	fn can_encode_unnamed_composite_to_named_struct() {
		#[derive(Encode, scale_info::TypeInfo)]
		struct Foo {
			hello: String,
			foo: bool,
		}

		// This is useful because things like transaction calls are often named composites, but
		// we just want to be able to provide the correct values as simply as possible without
		// necessarily knowing the names.
		let unnamed_value = Value::unnamed_composite([Value::string("world"), Value::bool(true)]);
		assert_can_encode_to_type(unnamed_value, Foo { hello: "world".to_string(), foo: true });
	}

	#[test]
	fn can_encode_bitvecs() {
		use scale_bits::bits;

		// We have more thorough tests of bitvec encoding in scale-bits.
		// Here we just do a basic confirmation that bool composites or
		// bitsequences encode to the bits we'd expect.
		assert_can_encode_to_type(
			Value::bit_sequence(bits![0, 1, 1, 0, 0, 1]),
			bits![0, 1, 1, 0, 0, 1],
		);
		assert_can_encode_to_type(
			Value::unnamed_composite(vec![
				Value::bool(false),
				Value::bool(true),
				Value::bool(true),
				Value::bool(false),
				Value::bool(false),
				Value::bool(true),
			]),
			bits![0, 1, 1, 0, 0, 1],
		);
	}

	#[test]
	fn can_encode_to_compact_types() {
		assert_can_encode_to_type(Value::u128(123), Compact(123u64));
		assert_can_encode_to_type(Value::u128(123), Compact(123u64));
		assert_can_encode_to_type(Value::u128(123), Compact(123u64));
		assert_can_encode_to_type(Value::u128(123), Compact(123u64));

		// As a special case, as long as ultimately we have a primitive value, we can compact encode it:
		assert_can_encode_to_type(Value::unnamed_composite([Value::u128(123)]), Compact(123u64));
		assert_can_encode_to_type(
			Value::unnamed_composite([Value::named_composite([(
				"foo".to_string(),
				Value::u128(123),
			)])]),
			Compact(123u64),
		);
	}

	#[test]
	fn can_encode_skipping_newtype_wrappers() {
		// One layer of "newtype" can be ignored:
		#[derive(Encode, scale_info::TypeInfo)]
		struct Foo {
			inner: u32,
		}
		assert_can_encode_to_type(Value::u128(32), Foo { inner: 32 });

		// Two layers can be ignored:
		#[derive(Encode, scale_info::TypeInfo)]
		struct Bar(Foo);
		assert_can_encode_to_type(Value::u128(32), Bar(Foo { inner: 32 }));

		// Encoding a Composite to a Composite(Composite) shape is fine too:
		#[derive(Encode, scale_info::TypeInfo)]
		struct SomeBytes(Vec<u8>);
		assert_can_encode_to_type(
			Value::from_bytes(&[1, 2, 3, 4, 5]),
			SomeBytes(vec![1, 2, 3, 4, 5]),
		);
	}
}