Skip to main content

xmtp_configuration/common/
chains.rs

1//! Chain identifier rules shared by the backend and the client.
2
3/// Why a chain identifier is not a routable `eip155` chain id.
4#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
5pub enum Eip155ChainIdError {
6    #[error("chain id is not prefixed with eip155:")]
7    MissingPrefix,
8    #[error("chain id is not a u64 in canonical decimal form")]
9    NotCanonical,
10}
11
12/// The chain id of an `eip155` CAIP-2 identifier, whose reference must be the
13/// chain id in canonical decimal form: no sign, no leading zero.
14///
15/// The backend accepts a `chains` key only when this parses it, and a client
16/// routes a smart contract wallet signature only when it parses the account's
17/// chain, so both sides agree on which chains exist.
18pub fn parse_eip155_chain_id(chain: &str) -> Result<u64, Eip155ChainIdError> {
19    let reference = chain
20        .strip_prefix("eip155:")
21        .ok_or(Eip155ChainIdError::MissingPrefix)?;
22    reference
23        .parse::<u64>()
24        .ok()
25        .filter(|chain_id| chain_id.to_string() == reference)
26        .ok_or(Eip155ChainIdError::NotCanonical)
27}
28
29#[cfg(test)]
30mod tests;