1use crate::{
4 decode::{Decode, DecodeError},
5 encode::Encode,
6 fmt::Hex,
7};
8use std::{
9 fmt::{self, Debug, Formatter},
10 marker::PhantomData,
11};
12
13pub struct ConstructorEncoder<B, P> {
15 pub code: B,
17 _marker: PhantomData<*const P>,
18}
19
20impl<B, P> ConstructorEncoder<B, P>
21where
22 B: AsRef<[u8]>,
23{
24 pub const fn new(code: B) -> Self {
26 Self {
27 code,
28 _marker: PhantomData,
29 }
30 }
31}
32
33impl<B, P> ConstructorEncoder<B, P>
34where
35 B: AsRef<[u8]>,
36 P: Encode,
37{
38 pub fn encode(&self, data: &P) -> Vec<u8> {
40 crate::encode_with_prefix(self.code.as_ref(), data)
41 }
42
43 pub fn encode_params(&self, data: &P) -> Vec<u8> {
45 crate::encode(data)
46 }
47}
48
49impl<B, P> ConstructorEncoder<B, P>
50where
51 B: AsRef<[u8]>,
52 P: Decode,
53{
54 pub fn decode(&self, data: &[u8]) -> Result<P, DecodeError> {
56 crate::decode_with_prefix(self.code.as_ref(), data)
57 }
58
59 pub fn decode_params(&self, data: &[u8]) -> Result<P, DecodeError> {
61 crate::decode(data)
62 }
63}
64
65impl<B, P> Debug for ConstructorEncoder<B, P>
66where
67 B: AsRef<[u8]>,
68{
69 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
70 f.debug_struct("ConstructorEncoder")
71 .field("code", &Hex(self.code.as_ref()))
72 .finish()
73 }
74}
75
76#[cfg(test)]
77mod tests {
78 use super::*;
79 use ethprim::{address, Address};
80 use hex_literal::hex;
81
82 #[test]
83 fn round_trips_deployment_encoding() {
84 let code = hex!(
85 "60a060405234801561001057600080fd5b506040516101083803806101088339
86 8101604081905261002f91610040565b6001600160a01b031660805261007056
87 5b60006020828403121561005257600080fd5b81516001600160a01b03811681
88 1461006957600080fd5b9392505050565b608051608061008860003960006006
89 015260806000f3fe60806040527f000000000000000000000000000000000000
90 00000000000000000000000000003660008037600080366000845af43d600080
91 3e80600181146045573d6000fd5b3d6000f3fea264697066735822122007589b
92 6aeb4b41bc48a82fc5939d02ccb42a23fd27c8bf5430706f182fd9a47164736f
93 6c63430008100033"
94 );
95 let proxy = ConstructorEncoder::<_, (Address,)>::new(code);
96
97 let account = address!("0x0101010101010101010101010101010101010101");
98
99 let params = hex!("0000000000000000000000000101010101010101010101010101010101010101");
100 let call = [&code[..], ¶ms[..]].concat();
101
102 assert_eq!(proxy.encode(&(account,)), call);
103 assert_eq!(proxy.encode_params(&(account,)), params);
104 assert_eq!(proxy.decode(&call).unwrap(), (account,));
105 assert_eq!(proxy.decode_params(¶ms).unwrap(), (account,));
106 }
107}