1use crate::UIfmt;
4use alloy_primitives::{Address, B256};
5use serde::{Deserialize, Serialize};
6use tempo_alloy::primitives::{
7 SignatureType, TempoSignature, TempoTransaction,
8 transaction::{
9 ConfigurableAccountConfig, ConfigurableAccountOwner, ConfigurableAccountSignature,
10 KeychainSignature,
11 },
12};
13
14#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
17pub struct ConfigJson {
18 salt: B256,
19 version: u64,
20 threshold: u8,
21 owners: Vec<OwnerJson>,
22}
23
24#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
25struct OwnerJson {
26 owner: Address,
27 weight: u8,
28}
29
30impl From<&ConfigurableAccountConfig> for ConfigJson {
31 fn from(config: &ConfigurableAccountConfig) -> Self {
32 Self {
33 salt: config.salt,
34 version: config.version,
35 threshold: config.threshold,
36 owners: config
37 .owners
38 .iter()
39 .map(|owner| OwnerJson { owner: owner.owner, weight: owner.weight })
40 .collect(),
41 }
42 }
43}
44
45impl TryFrom<ConfigJson> for ConfigurableAccountConfig {
46 type Error = eyre::Report;
47
48 fn try_from(json: ConfigJson) -> eyre::Result<Self> {
50 let ConfigJson { salt, version, threshold, owners } = json;
51 let mut owners = owners
52 .into_iter()
53 .map(|owner| ConfigurableAccountOwner { owner: owner.owner, weight: owner.weight })
54 .collect::<Vec<_>>();
55 owners.sort_by_key(|owner| owner.owner);
56 let config = Self { salt, version, threshold, owners };
57 config.validate().map_err(|err| eyre::eyre!("invalid configuration: {err}"))?;
58 Ok(config)
59 }
60}
61
62pub fn add_configurable_account_details(tx: &mut serde_json::Value) {
67 if let Some(details) = ConfigurableAccountSignatureDetails::from_json(tx)
68 && let Some(tx) = tx.as_object_mut()
69 {
70 tx.insert(
71 "configurableAccountSignature".into(),
72 serde_json::to_value(details).expect("infallible"),
73 );
74 }
75}
76
77#[derive(Serialize)]
79#[serde(rename_all = "camelCase")]
80pub(crate) struct ConfigurableAccountSignatureDetails {
81 #[serde(skip_serializing_if = "Option::is_none")]
84 keychain_root_account: Option<Address>,
85 account: Address,
86 config: ConfigJson,
87 approvals: Vec<ApprovalDetails>,
88}
89
90#[derive(Serialize)]
92struct ApprovalDetails {
93 #[serde(rename = "type")]
94 ty: SignatureType,
95 owner: Option<Address>,
97 weight: Option<u8>,
99}
100
101impl ConfigurableAccountSignatureDetails {
102 pub(crate) fn from_tx(tx: &TempoTransaction, signature: &TempoSignature) -> Option<Self> {
105 match signature {
106 TempoSignature::ConfigurableAccount(signature) => {
107 Some(Self::new(None, signature, tx.signature_hash()))
108 }
109 TempoSignature::Keychain(keychain) if !keychain.is_legacy() => Some(Self::new(
111 Some(keychain.user_address),
112 keychain.signature.as_configurable_account()?,
113 KeychainSignature::signing_hash(tx.signature_hash(), keychain.user_address),
114 )),
115 _ => None,
116 }
117 }
118
119 pub(crate) fn from_json(tx: &serde_json::Value) -> Option<Self> {
121 let signature =
122 serde_json::from_value::<TempoSignature>(tx.get("signature")?.clone()).ok()?;
123 let tx = serde_json::from_value::<TempoTransaction>(tx.clone()).ok()?;
124 Self::from_tx(&tx, &signature)
125 }
126
127 fn new(
128 keychain_root_account: Option<Address>,
129 signature: &ConfigurableAccountSignature,
130 inner_digest: B256,
131 ) -> Self {
132 let config = signature.config();
133 let digest = signature.digest(inner_digest);
134 let approvals = signature
135 .signatures()
136 .iter()
137 .map(|approval| {
138 let owner = approval.recover_signer(&digest).ok();
139 ApprovalDetails {
140 ty: approval.signature_type(),
141 owner,
142 weight: owner.and_then(|owner| config.owner_weight(owner)),
143 }
144 })
145 .collect();
146 Self {
147 keychain_root_account,
148 account: signature.account(),
149 config: config.into(),
150 approvals,
151 }
152 }
153}
154
155impl UIfmt for ConfigurableAccountSignatureDetails {
156 fn pretty(&self) -> String {
157 let owners = self
158 .config
159 .owners
160 .iter()
161 .map(|owner| format!("{} (weight {})", owner.owner, owner.weight))
162 .collect::<Vec<_>>();
163 let approvals = self
164 .approvals
165 .iter()
166 .map(|approval| {
167 let ty = match approval.ty {
168 SignatureType::Secp256k1 => "secp256k1",
169 SignatureType::P256 => "p256",
170 SignatureType::WebAuthn => "webAuthn",
171 SignatureType::ConfigurableAccount => "configurableAccount",
172 };
173 match (approval.owner, approval.weight) {
174 (Some(owner), Some(weight)) => format!("{owner} ({ty}, weight {weight})"),
175 (Some(owner), None) => format!("{owner} ({ty}, not an owner)"),
176 (None, _) => format!("invalid {ty} signature"),
177 }
178 })
179 .collect::<Vec<_>>();
180 let kind = match self.keychain_root_account {
181 Some(root) => format!("keychain\nkeychainRootAccount {}", root.pretty()),
182 None => "configurableAccount".to_string(),
183 };
184 format!(
185 "{kind}
186configurableAccount {}
187configSalt {}
188configVersion {}
189threshold {}
190owners {}
191approvals {}",
192 self.account.pretty(),
193 self.config.salt.pretty(),
194 self.config.version.pretty(),
195 self.config.threshold,
196 owners.pretty(),
197 approvals.pretty(),
198 )
199 }
200}
201
202#[cfg(test)]
203mod tests {
204 use super::*;
205 use alloy_primitives::{Bytes, Signature, U256};
206 use alloy_signer::SignerSync;
207 use alloy_signer_local::PrivateKeySigner;
208 use similar_asserts::assert_eq;
209 use tempo_alloy::primitives::transaction::{
210 Call, PrimitiveSignature, configurable_account_digest,
211 };
212
213 #[test]
218 fn configurable_account_signature_details() {
219 let mut owners = [0x11, 0x22]
220 .map(|byte| PrivateKeySigner::from_bytes(&B256::repeat_byte(byte)).unwrap());
221 owners.sort_by_key(|owner| owner.address());
222 let stranger = PrivateKeySigner::from_bytes(&B256::repeat_byte(0x33)).unwrap();
223 let config = ConfigurableAccountConfig {
224 salt: B256::ZERO,
225 version: 0,
226 threshold: 2,
227 owners: owners
228 .iter()
229 .map(|owner| ConfigurableAccountOwner { owner: owner.address(), weight: 1 })
230 .collect(),
231 };
232 let account = config.derive_account().unwrap();
233 let tx = TempoTransaction {
234 chain_id: 1,
235 calls: vec![Call::new(Address::repeat_byte(0x44), Bytes::new())],
236 ..Default::default()
237 };
238 let sign = |signer: &PrivateKeySigner, inner_digest: B256| {
239 let digest = configurable_account_digest(inner_digest, account, config.version);
240 PrimitiveSignature::Secp256k1(signer.sign_hash_sync(&digest).unwrap())
241 };
242 let (owner, other_owner, stranger) =
243 (owners[0].address(), owners[1].address(), stranger.address());
244
245 let sig_hash = tx.signature_hash();
247 let approvals = vec![
248 sign(&owners[0], sig_hash),
249 sign(&PrivateKeySigner::from_bytes(&B256::repeat_byte(0x33)).unwrap(), sig_hash),
250 PrimitiveSignature::Secp256k1(Signature::new(U256::ZERO, U256::ZERO, false)),
251 ];
252 let signature = TempoSignature::ConfigurableAccount(
253 ConfigurableAccountSignature::try_new(account, config.clone(), approvals).unwrap(),
254 );
255 let details = ConfigurableAccountSignatureDetails::from_tx(&tx, &signature).unwrap();
256 assert_eq!(
257 details.pretty(),
258 format!(
259 "configurableAccount
260configurableAccount {account}
261configSalt {}
262configVersion 0
263threshold 2
264owners [
265\t{owner} (weight 1)
266\t{other_owner} (weight 1)
267]
268approvals [
269\t{owner} (secp256k1, weight 1)
270\t{stranger} (secp256k1, not an owner)
271\tinvalid secp256k1 signature
272]",
273 B256::ZERO,
274 )
275 );
276 let mut json = serde_json::to_value(tx.clone().into_signed(signature)).unwrap();
277 add_configurable_account_details(&mut json);
278 assert!(json["signature"].is_string(), "{json}");
279 assert_eq!(
280 json["configurableAccountSignature"],
281 serde_json::json!({
282 "account": account,
283 "config": {
284 "salt": B256::ZERO,
285 "version": 0,
286 "threshold": 2,
287 "owners": [
288 { "owner": owner, "weight": 1 },
289 { "owner": other_owner, "weight": 1 },
290 ],
291 },
292 "approvals": [
293 { "type": "secp256k1", "owner": owner, "weight": 1 },
294 { "type": "secp256k1", "owner": stranger, "weight": null },
295 { "type": "secp256k1", "owner": null, "weight": null },
296 ],
297 })
298 );
299
300 let root = Address::repeat_byte(0x55);
302 let keychain_hash = KeychainSignature::signing_hash(sig_hash, root);
303 let approvals = owners.iter().map(|owner| sign(owner, keychain_hash)).collect();
304 let signature = TempoSignature::Keychain(KeychainSignature::new(
305 root,
306 ConfigurableAccountSignature::try_new(account, config, approvals).unwrap(),
307 ));
308 let details = ConfigurableAccountSignatureDetails::from_tx(&tx, &signature).unwrap();
309 assert_eq!(
310 details.pretty(),
311 format!(
312 "keychain
313keychainRootAccount {root}
314configurableAccount {account}
315configSalt {}
316configVersion 0
317threshold 2
318owners [
319\t{owner} (weight 1)
320\t{other_owner} (weight 1)
321]
322approvals [
323\t{owner} (secp256k1, weight 1)
324\t{other_owner} (secp256k1, weight 1)
325]",
326 B256::ZERO,
327 )
328 );
329 let mut json = serde_json::to_value(tx.into_signed(signature)).unwrap();
330 add_configurable_account_details(&mut json);
331 assert_eq!(
332 json["configurableAccountSignature"]["keychainRootAccount"],
333 serde_json::json!(root)
334 );
335 assert_eq!(
336 json["configurableAccountSignature"]["approvals"],
337 serde_json::json!([
338 { "type": "secp256k1", "owner": owner, "weight": 1 },
339 { "type": "secp256k1", "owner": other_owner, "weight": 1 },
340 ])
341 );
342 }
343}