alloy_sol_types/
eip712.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
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
use crate::SolValue;
use alloc::{borrow::Cow, string::String, vec::Vec};
use alloy_primitives::{keccak256, Address, FixedBytes, B256, U256};

/// EIP-712 domain attributes used in determining the domain separator.
///
/// Unused fields are left out of the struct type.
///
/// Protocol designers only need to include the fields that make sense for
/// their signing domain.
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "eip712-serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "eip712-serde", serde(rename_all = "camelCase"))]
pub struct Eip712Domain {
    /// The user readable name of signing domain, i.e. the name of the DApp or
    /// the protocol.
    #[cfg_attr(feature = "eip712-serde", serde(default, skip_serializing_if = "Option::is_none"))]
    pub name: Option<Cow<'static, str>>,

    /// The current major version of the signing domain. Signatures from
    /// different versions are not compatible.
    #[cfg_attr(feature = "eip712-serde", serde(default, skip_serializing_if = "Option::is_none"))]
    pub version: Option<Cow<'static, str>>,

    /// The EIP-155 chain ID. The user-agent should refuse signing if it does
    /// not match the currently active chain.
    #[cfg_attr(feature = "eip712-serde", serde(default, skip_serializing_if = "Option::is_none"))]
    pub chain_id: Option<U256>,

    /// The address of the contract that will verify the signature.
    #[cfg_attr(feature = "eip712-serde", serde(default, skip_serializing_if = "Option::is_none"))]
    pub verifying_contract: Option<Address>,

    /// A disambiguating salt for the protocol. This can be used as a domain
    /// separator of last resort.
    #[cfg_attr(feature = "eip712-serde", serde(default, skip_serializing_if = "Option::is_none"))]
    pub salt: Option<B256>,
}

impl Eip712Domain {
    /// The name of the struct.
    pub const NAME: &'static str = "EIP712Domain";

    /// Instantiate a new EIP-712 domain.
    ///
    /// Use the [`eip712_domain!`](crate::eip712_domain!) macro for easier
    /// instantiation.
    #[inline]
    pub const fn new(
        name: Option<Cow<'static, str>>,
        version: Option<Cow<'static, str>>,
        chain_id: Option<U256>,
        verifying_contract: Option<Address>,
        salt: Option<B256>,
    ) -> Self {
        Self { name, version, chain_id, verifying_contract, salt }
    }

    /// Calculate the domain separator for the domain object.
    #[inline]
    pub fn separator(&self) -> B256 {
        self.hash_struct()
    }

    /// The EIP-712-encoded type string.
    ///
    /// See [EIP-712 `encodeType`](https://eips.ethereum.org/EIPS/eip-712#definition-of-encodetype).
    pub fn encode_type(&self) -> String {
        // commas not included
        macro_rules! encode_type {
            ($($field:ident => $repr:literal),+ $(,)?) => {
                let mut ty = String::with_capacity(Self::NAME.len() + 2 $(+ $repr.len() * self.$field.is_some() as usize)+);
                ty.push_str(Self::NAME);
                ty.push('(');

                $(
                    if self.$field.is_some() {
                        ty.push_str($repr);
                    }
                )+
                if ty.ends_with(',') {
                    ty.pop();
                }

                ty.push(')');
                ty
            };
        }

        encode_type! {
            name               => "string name,",
            version            => "string version,",
            chain_id           => "uint256 chainId,",
            verifying_contract => "address verifyingContract,",
            salt               => "bytes32 salt",
        }
    }

    /// Calculates the [EIP-712 `typeHash`](https://eips.ethereum.org/EIPS/eip-712#rationale-for-typehash)
    /// for this domain.
    ///
    /// This is defined as the Keccak-256 hash of the
    /// [`encodeType`](Self::encode_type) string.
    #[inline]
    pub fn type_hash(&self) -> B256 {
        keccak256(self.encode_type().as_bytes())
    }

    /// Returns the number of ABI words (32 bytes) that will be used to encode
    /// the domain.
    #[inline]
    pub const fn num_words(&self) -> usize {
        self.name.is_some() as usize
            + self.version.is_some() as usize
            + self.chain_id.is_some() as usize
            + self.verifying_contract.is_some() as usize
            + self.salt.is_some() as usize
    }

    /// Returns the number of bytes that will be used to encode the domain.
    #[inline]
    pub const fn abi_encoded_size(&self) -> usize {
        self.num_words() * 32
    }

    /// Encodes this domain using [EIP-712 `encodeData`](https://eips.ethereum.org/EIPS/eip-712#definition-of-encodedata)
    /// into the given buffer.
    pub fn encode_data_to(&self, out: &mut Vec<u8>) {
        // This only works because all of the fields are encoded as words.
        macro_rules! encode_opt {
            ($opt:expr) => {
                if let Some(t) = $opt {
                    out.extend_from_slice(t.tokenize().as_slice());
                }
            };
        }

        #[inline]
        #[allow(clippy::ptr_arg)]
        fn cow_keccak256(s: &Cow<'_, str>) -> FixedBytes<32> {
            keccak256(s.as_bytes())
        }

        out.reserve(self.abi_encoded_size());
        encode_opt!(self.name.as_ref().map(cow_keccak256));
        encode_opt!(self.version.as_ref().map(cow_keccak256));
        encode_opt!(&self.chain_id);
        encode_opt!(&self.verifying_contract);
        encode_opt!(&self.salt);
    }

    /// Encodes this domain using [EIP-712 `encodeData`](https://eips.ethereum.org/EIPS/eip-712#definition-of-encodedata).
    pub fn encode_data(&self) -> Vec<u8> {
        let mut out = Vec::new();
        self.encode_data_to(&mut out);
        out
    }

    /// Hashes this domain according to [EIP-712 `hashStruct`](https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct).
    #[inline]
    pub fn hash_struct(&self) -> B256 {
        let mut hasher = alloy_primitives::Keccak256::new();
        hasher.update(self.type_hash());
        hasher.update(self.encode_data());
        hasher.finalize()
    }
}

/// Convenience macro to instantiate an [EIP-712 domain](Eip712Domain).
///
/// This macro allows you to instantiate an [EIP-712 domain](Eip712Domain)
/// struct without manually writing `None` for unused fields.
///
/// It may be used to declare a domain with any combination of fields. Each
/// field must be labeled with the name of the field, and the fields must be in
/// order. The fields for the domain are:
/// - `name`
/// - `version`
/// - `chain_id`
/// - `verifying_contract`
/// - `salt`
///
/// # Examples
///
/// ```
/// # use alloy_sol_types::{Eip712Domain, eip712_domain};
/// # use alloy_primitives::keccak256;
/// const MY_DOMAIN: Eip712Domain = eip712_domain! {
///     name: "MyCoolProtocol",
/// };
///
/// let dynamic_name = String::from("MyCoolProtocol");
/// let my_other_domain: Eip712Domain = eip712_domain! {
///     name: dynamic_name,
///     version: "1.0.0",
///     salt: keccak256("my domain salt"),
/// };
/// ```
#[macro_export]
macro_rules! eip712_domain {
    (@opt) => { $crate::private::None };
    (@opt $e:expr) => { $crate::private::Some($e) };

    // special case literals to allow calling this in const contexts
    (@cow) => { $crate::private::None };
    (@cow $l:literal) => { $crate::private::Some($crate::private::Cow::Borrowed($l)) };
    (@cow $e:expr) => { $crate::private::Some(<$crate::private::Cow<'static, str> as $crate::private::From<_>>::from($e)) };

    (
        $(name: $name:expr,)?
        $(version: $version:expr,)?
        $(chain_id: $chain_id:expr,)?
        $(verifying_contract: $verifying_contract:expr,)?
        $(salt: $salt:expr)?
        $(,)?
    ) => {
        $crate::Eip712Domain::new(
            $crate::eip712_domain!(@cow $($name)?),
            $crate::eip712_domain!(@cow $($version)?),
            $crate::eip712_domain!(@opt $($crate::private::u256($chain_id))?),
            $crate::eip712_domain!(@opt $($verifying_contract)?),
            $crate::eip712_domain!(@opt $($salt)?),
        )
    };
}

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

    const _: Eip712Domain = eip712_domain! {
        name: "abcd",
    };
    const _: Eip712Domain = eip712_domain! {
        name: "abcd",
        version: "1",
    };
    const _: Eip712Domain = eip712_domain! {
        name: "abcd",
        version: "1",
        chain_id: 1,
    };
    const _: Eip712Domain = eip712_domain! {
        name: "abcd",
        version: "1",
        chain_id: 1,
        verifying_contract: Address::ZERO,
    };
    const _: Eip712Domain = eip712_domain! {
        name: "abcd",
        version: "1",
        chain_id: 1,
        verifying_contract: Address::ZERO,
        salt: B256::ZERO // no trailing comma
    };
    const _: Eip712Domain = eip712_domain! {
        name: "abcd",
        version: "1",
        chain_id: 1,
        verifying_contract: Address::ZERO,
        salt: B256::ZERO, // trailing comma
    };

    const _: Eip712Domain = eip712_domain! {
        name: "abcd",
        version: "1",
        // chain_id: 1,
        verifying_contract: Address::ZERO,
        salt: B256::ZERO,
    };
    const _: Eip712Domain = eip712_domain! {
        name: "abcd",
        // version: "1",
        chain_id: 1,
        verifying_contract: Address::ZERO,
        salt: B256::ZERO,
    };
    const _: Eip712Domain = eip712_domain! {
        name: "abcd",
        // version: "1",
        // chain_id: 1,
        verifying_contract: Address::ZERO,
        salt: B256::ZERO,
    };
    const _: Eip712Domain = eip712_domain! {
        name: "abcd",
        // version: "1",
        // chain_id: 1,
        // verifying_contract: Address::ZERO,
        salt: B256::ZERO,
    };
    const _: Eip712Domain = eip712_domain! {
        // name: "abcd",
        version: "1",
        // chain_id: 1,
        // verifying_contract: Address::ZERO,
        salt: B256::ZERO,
    };
    const _: Eip712Domain = eip712_domain! {
        // name: "abcd",
        version: "1",
        // chain_id: 1,
        verifying_contract: Address::ZERO,
        salt: B256::ZERO,
    };

    #[test]
    fn runtime_domains() {
        let _: Eip712Domain = eip712_domain! {
            name: String::new(),
            version: String::new(),
        };

        let my_string = String::from("!@#$%^&*()_+");
        let _: Eip712Domain = eip712_domain! {
            name: my_string.clone(),
            version: my_string,
        };

        let my_cow = Cow::from("my_cow");
        let _: Eip712Domain = eip712_domain! {
            name: my_cow.clone(),
            version: my_cow.into_owned(),
        };
    }
}