use std::collections::HashMap;
use compact_str::CompactString;
use serde::{Deserialize, Serialize};
use serde_with::{VecSkipError, serde_as};
use crate::network::ChainId;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
#[non_exhaustive]
pub struct SupportedPaymentKind {
pub x402_version: u8,
pub scheme: CompactString,
pub network: CompactString,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub extra: Option<serde_json::Value>,
}
impl SupportedPaymentKind {
#[must_use]
pub fn new(
x402_version: u8,
scheme: impl Into<CompactString>,
network: impl Into<CompactString>,
) -> Self {
Self {
x402_version,
scheme: scheme.into(),
network: network.into(),
extra: None,
}
}
#[must_use]
pub fn with_extra(mut self, extra: serde_json::Value) -> Self {
self.extra = Some(extra);
self
}
#[must_use]
pub fn with_optional_extra(mut self, extra: Option<serde_json::Value>) -> Self {
self.extra = extra;
self
}
}
#[serde_as]
#[derive(Clone, Default, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
#[non_exhaustive]
pub struct SupportedResponse {
#[serde_as(as = "VecSkipError<_>")]
pub kinds: Vec<SupportedPaymentKind>,
#[serde(default)]
pub extensions: Vec<CompactString>,
#[serde(default)]
pub signers: HashMap<CompactString, Vec<CompactString>>,
}
impl SupportedResponse {
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn with_kinds(mut self, kinds: Vec<SupportedPaymentKind>) -> Self {
self.kinds = kinds;
self
}
#[must_use]
pub fn with_extensions(mut self, extensions: Vec<CompactString>) -> Self {
self.extensions = extensions;
self
}
#[must_use]
#[allow(
clippy::implicit_hasher,
reason = "wire map is a JSON object with no hasher contract"
)]
pub fn with_signers(mut self, signers: HashMap<CompactString, Vec<CompactString>>) -> Self {
self.signers = signers;
self
}
#[must_use]
pub fn signers_for_chain(&self, chain_id: &ChainId) -> Vec<&str> {
let exact = CompactString::from(chain_id.to_string());
let wildcard = CompactString::from(format!("{}:*", chain_id.namespace()));
let mut out = Vec::new();
if let Some(list) = self.signers.get(&exact) {
out.extend(list.iter().map(CompactString::as_str));
}
if let Some(list) = self.signers.get(&wildcard) {
out.extend(list.iter().map(CompactString::as_str));
}
out
}
}