pub use saorsa_transport::webrtc::{BrowserEndpoint, BrowserPaymentNetwork, WebRtcDirectEndpoint};
use serde::{Deserialize, Serialize};
pub const BROWSER_MANIFEST_VERSION: u16 = 6;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct BrowserBootstrapNode {
#[serde(flatten)]
pub endpoint: BrowserEndpoint,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct BrowserPublicFile {
pub name: String,
pub address: String,
pub size: usize,
pub content_type: String,
pub blake3: String,
pub data_map_size: usize,
pub chunks: Vec<BrowserChunkInfo>,
pub replicas: usize,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct BrowserChunkInfo {
pub index: usize,
pub dst_hash: String,
pub src_hash: String,
pub src_size: usize,
}
#[cfg(any(feature = "webrtc-direct", test))]
pub(crate) async fn browser_payment_network(
network: &evmlib::Network,
) -> crate::Result<BrowserPaymentNetwork> {
let chain_id = match network {
evmlib::Network::ArbitrumOne => 42_161,
evmlib::Network::ArbitrumSepoliaTest => 421_614,
evmlib::Network::Custom(_) => payment_chain_id(network.rpc_url()).await?,
};
Ok(BrowserPaymentNetwork {
chain_id,
payment_token_address: format!("{:?}", network.payment_token_address()),
payment_vault_address: format!("{:?}", network.payment_vault_address()),
})
}
#[cfg(any(feature = "webrtc-direct", test))]
async fn payment_chain_id(rpc_url: &reqwest::Url) -> crate::Result<u64> {
let unavailable = || {
crate::Error::Config(
"could not resolve the custom EVM chain ID for browser payment metadata".to_string(),
)
};
let invalid = || {
crate::Error::Config("custom EVM RPC returned an invalid eth_chainId response".to_string())
};
let client = reqwest::Client::builder()
.timeout(std::time::Duration::from_secs(10))
.redirect(reqwest::redirect::Policy::none())
.build()
.map_err(|_| unavailable())?;
let mut response = client
.post(rpc_url.clone())
.json(
&serde_json::json!({"jsonrpc": "2.0", "id": 1, "method": "eth_chainId", "params": []}),
)
.send()
.await
.map_err(|_| unavailable())?
.error_for_status()
.map_err(|_| unavailable())?;
let mut body = Vec::new();
while let Some(chunk) = response.chunk().await.map_err(|_| unavailable())? {
if body.len() + chunk.len() > 4096 {
return Err(invalid());
}
body.extend_from_slice(&chunk);
}
let response: serde_json::Value = serde_json::from_slice(&body).map_err(|_| invalid())?;
if response["jsonrpc"] != "2.0" || response["id"] != 1 || response.get("error").is_some() {
return Err(invalid());
}
let hex = response["result"]
.as_str()
.and_then(|value| value.strip_prefix("0x"))
.filter(|hex| {
!hex.is_empty()
&& (hex.len() == 1 || !hex.starts_with('0'))
&& hex.bytes().all(|byte| byte.is_ascii_hexdigit())
})
.ok_or_else(invalid)?;
u64::from_str_radix(hex, 16).map_err(|_| invalid())
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct BrowserDevnetManifest {
pub version: u16,
pub network_id: String,
pub created_at: String,
pub endpoints: Vec<BrowserBootstrapNode>,
pub payment: BrowserPaymentNetwork,
pub files: Vec<BrowserPublicFile>,
}
impl BrowserDevnetManifest {
#[must_use]
pub fn new(
network_id: String,
created_at: String,
endpoints: Vec<BrowserBootstrapNode>,
payment: BrowserPaymentNetwork,
files: Vec<BrowserPublicFile>,
) -> Self {
Self {
version: BROWSER_MANIFEST_VERSION,
network_id,
created_at,
endpoints,
payment,
files,
}
}
}
#[cfg(test)]
mod tests {
use super::browser_payment_network;
#[tokio::test]
async fn builtin_payment_identity_contains_only_chain_and_contracts(
) -> Result<(), Box<dyn std::error::Error>> {
for (network, chain_id) in [
(evmlib::Network::ArbitrumOne, 42_161),
(evmlib::Network::ArbitrumSepoliaTest, 421_614),
] {
let identity = browser_payment_network(&network).await?;
assert_eq!(identity.chain_id, chain_id);
assert_eq!(
serde_json::to_value(identity)?,
serde_json::json!({
"chain_id": chain_id,
"payment_token_address": format!("{:?}", network.payment_token_address()),
"payment_vault_address": format!("{:?}", network.payment_vault_address()),
})
);
}
Ok(())
}
}