Compare commits

...

6 Commits

Author SHA1 Message Date
Tommy Verrall 7abe9a987d PR comments addressed
- Changed peer_interaction_timeout from u64 milliseconds to Duration type
- Made timeout non-configurable (always uses safe 5s default) to prevent
  users from setting unsafe values
- Removed timeout from CLI args, env vars, and config template
- Added suspend/resume scenario documentation
- Simplified code by removing unnecessary tuple
- Reverted old_config migration code (to be handled in separate PR)
2025-12-11 14:46:16 +01:00
Tommy Verrall 24ccba3a19 expose peer timeout config + update migration 2025-11-21 16:34:25 +01:00
Tommy Verrall 21a1376900 drop registration lock and enhance gateway reservation 2025-11-21 12:25:03 +01:00
Tommy Verrall 451107efb5 add configurable peer-controller timeout and make registration lockless 2025-11-21 09:57:20 +01:00
Tommy Verrall 8dbbd2bdf4 gateway/authenticator: add peer-controller timeouts and lock tweaks to keep registration responsive after suspend 2025-11-21 09:26:41 +01:00
Mark Sinclair 96e3ff2af9 Node Status UI (#6210)
Co-authored-by: Mark Sinclair <mmsinclair@users.noreply.github.com>
2025-11-17 09:18:01 +00:00
73 changed files with 6278 additions and 58 deletions
Generated
+1
View File
@@ -6432,6 +6432,7 @@ dependencies = [
"futures",
"hkdf",
"human-repr",
"humantime",
"humantime-serde",
"indicatif",
"ipnetwork",
@@ -7,6 +7,7 @@ use nym_network_defaults::{
};
use serde::{Deserialize, Serialize};
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr};
use std::time::Duration;
pub use nym_client_core::config::Config as BaseClientConfig;
pub use persistence::AuthenticatorPaths;
@@ -26,7 +27,6 @@ pub struct Config {
impl Config {
pub fn validate(&self) -> bool {
// no other sections have explicit requirements (yet)
self.base.validate()
}
}
@@ -57,6 +57,12 @@ pub struct Authenticator {
/// The prefix denoting the maximum number of the clients that can be connected via Wireguard using IPv6.
/// The maximum value for IPv6 is 128
pub private_network_prefix_v6: u8,
/// Timeout to wait for responses from the peer controller before failing.
/// Helps the authenticator recover from suspend/resume scenarios where the peer controller
/// process/task can get stuck and never respond to oneshot RPC responses, which previously
/// caused the authenticator to block forever waiting on the oneshot channel.
pub peer_interaction_timeout: Duration,
}
impl Default for Authenticator {
@@ -68,6 +74,7 @@ impl Default for Authenticator {
tunnel_announced_port: WG_TUNNEL_PORT,
private_network_prefix_v4: WG_TUN_DEVICE_NETMASK_V4,
private_network_prefix_v6: WG_TUN_DEVICE_NETMASK_V6,
peer_interaction_timeout: default_peer_interaction_timeout(),
}
}
}
@@ -85,3 +92,7 @@ impl From<Authenticator> for nym_wireguard_types::Config {
}
}
}
pub fn default_peer_interaction_timeout() -> Duration {
Duration::from_millis(5_000)
}
@@ -85,6 +85,9 @@ pub enum AuthenticatorError {
#[error("peers can't be interacted with anymore")]
PeerInteractionStopped,
#[error("peers interaction timed out while attempting to {operation}")]
PeerInteractionTimeout { operation: &'static str },
#[error("unknown version number")]
UnknownVersion,
@@ -42,7 +42,6 @@ use std::{
sync::Arc,
time::{Duration, SystemTime},
};
use tokio::sync::RwLock;
use tokio_stream::wrappers::IntervalStream;
type AuthenticatorHandleResult = Result<(Vec<u8>, Option<Recipient>), AuthenticatorError>;
@@ -74,7 +73,7 @@ pub(crate) struct MixnetListener {
pub(crate) mixnet_client: nym_sdk::mixnet::MixnetClient,
// Registrations awaiting confirmation
pub(crate) registered_and_free: RwLock<RegisteredAndFree>,
pub(crate) registered_and_free: RegisteredAndFree,
pub(crate) peer_manager: PeerManager,
@@ -95,14 +94,15 @@ impl MixnetListener {
mixnet_client: nym_sdk::mixnet::MixnetClient,
upgrade_mode: UpgradeModeDetails,
ecash_verifier: Arc<dyn EcashManager + Send + Sync>,
peer_interaction_timeout: Duration,
) -> Self {
let timeout_check_interval =
IntervalStream::new(tokio::time::interval(DEFAULT_REGISTRATION_TIMEOUT_CHECK));
MixnetListener {
config,
mixnet_client,
registered_and_free: RwLock::new(RegisteredAndFree::new(free_private_network_ips)),
peer_manager: PeerManager::new(wireguard_gateway_data),
registered_and_free: RegisteredAndFree::new(free_private_network_ips),
peer_manager: PeerManager::new(wireguard_gateway_data, peer_interaction_timeout),
upgrade_mode,
ecash_verifier,
timeout_check_interval,
@@ -131,8 +131,8 @@ impl MixnetListener {
))
}
async fn remove_stale_registrations(&self) -> Result<(), AuthenticatorError> {
let mut registered_and_free = self.registered_and_free.write().await;
async fn remove_stale_registrations(&mut self) -> Result<(), AuthenticatorError> {
let registered_and_free = &mut self.registered_and_free;
let registered_values: Vec<_> = registered_and_free
.registration_in_progres
.values()
@@ -185,8 +185,9 @@ impl MixnetListener {
) -> AuthenticatorHandleResult {
let remote_public = init_message.pub_key();
let nonce: u64 = fastrand::u64(..);
let mut registered_and_free = self.registered_and_free.write().await;
if let Some(registration_data) = registered_and_free
if let Some(registration_data) = self
.registered_and_free
.registration_in_progres
.get(&remote_public)
{
@@ -292,7 +293,17 @@ impl MixnetListener {
return Ok((bytes, reply_to));
}
let peer = self.peer_manager.query_peer(remote_public).await?;
let peer = match self.peer_manager.query_peer(remote_public).await {
Ok(peer) => peer,
Err(err) => {
tracing::warn!(
"Failed to query peer {}: {err}. Continuing with fresh registration",
remote_public
);
None
}
};
if let Some(peer) = peer {
let allowed_ipv4 = peer
.allowed_ips
@@ -383,19 +394,21 @@ impl MixnetListener {
return Ok((bytes, reply_to));
}
let private_ip_ref = registered_and_free
let private_ip = self
.registered_and_free
.free_private_network_ips
.iter_mut()
.filter(|r| r.1.is_none())
.choose(&mut thread_rng())
.ok_or(AuthenticatorError::NoFreeIp)?;
let private_ips = *private_ip_ref.0;
let private_ips = *private_ip.0;
// mark it as used, even though it's not final
*private_ip_ref.1 = Some(SystemTime::now());
*private_ip.1 = Some(SystemTime::now());
let gateway_data = GatewayClient::new(
self.keypair().private_key(),
remote_public.inner(),
*private_ip_ref.0,
private_ips,
nonce,
);
let registration_data = latest::registration::RegistrationData {
@@ -403,7 +416,8 @@ impl MixnetListener {
gateway_data: gateway_data.clone(),
wg_port: self.config.authenticator.tunnel_announced_port,
};
registered_and_free
self.registered_and_free
.registration_in_progres
.insert(remote_public, registration_data.clone());
let bytes = match AuthenticatorVersion::from(protocol) {
@@ -539,12 +553,12 @@ impl MixnetListener {
request_id: u64,
reply_to: Option<Recipient>,
) -> AuthenticatorHandleResult {
let mut registered_and_free = self.registered_and_free.write().await;
let registration_data = registered_and_free
let registration_data = self
.registered_and_free
.registration_in_progres
.get(&final_message.gateway_client_pub_key())
.ok_or(AuthenticatorError::RegistrationNotInProgress)?
.clone();
.cloned()
.ok_or(AuthenticatorError::RegistrationNotInProgress)?;
if final_message
.verify(self.keypair().private_key(), registration_data.nonce)
@@ -595,7 +609,7 @@ impl MixnetListener {
return Err(e);
}
registered_and_free
self.registered_and_free
.registration_in_progres
.remove(&final_message.gateway_client_pub_key());
@@ -818,7 +832,7 @@ impl MixnetListener {
.to_bytes()
.map_err(AuthenticatorError::response_serialisation)?,
AuthenticatorVersion::V1 | AuthenticatorVersion::V2 | AuthenticatorVersion::UNKNOWN => {
return Err(AuthenticatorError::UnknownVersion)
return Err(AuthenticatorError::UnknownVersion);
}
};
@@ -151,6 +151,7 @@ impl Authenticator {
}
})
.collect();
let peer_timeout = self.config.authenticator.peer_interaction_timeout;
let mixnet_listener = crate::node::internal_service_providers::authenticator::mixnet_listener::MixnetListener::new(
self.config,
free_private_network_ips,
@@ -158,6 +159,7 @@ impl Authenticator {
mixnet_client,
self.upgrade_mode_state,
self.ecash_verifier,
peer_timeout,
);
tracing::info!("The address of this client is: {self_address}");
@@ -8,15 +8,19 @@ use nym_credential_verification::{ClientBandwidth, TicketVerifier};
use nym_credentials_interface::CredentialSpendingData;
use nym_wireguard::{peer_controller::PeerControlRequest, WireguardGatewayData};
use nym_wireguard_types::PeerPublicKey;
use std::time::Duration;
use tokio::time::timeout;
pub struct PeerManager {
pub(crate) wireguard_gateway_data: WireguardGatewayData,
response_timeout: Duration,
}
impl PeerManager {
pub fn new(wireguard_gateway_data: WireguardGatewayData) -> Self {
pub fn new(wireguard_gateway_data: WireguardGatewayData, response_timeout: Duration) -> Self {
PeerManager {
wireguard_gateway_data,
response_timeout,
}
}
pub async fn add_peer(&self, peer: Peer) -> Result<(), AuthenticatorError> {
@@ -28,9 +32,8 @@ impl PeerManager {
.await
.map_err(|_| AuthenticatorError::PeerInteractionStopped)?;
response_rx
.await
.map_err(|_| AuthenticatorError::InternalError("no response for add peer".to_string()))?
recv_with_timeout(response_rx, "add peer", self.response_timeout)
.await?
.map_err(|err| {
AuthenticatorError::InternalError(format!(
"adding peer could not be performed: {err:?}"
@@ -48,11 +51,8 @@ impl PeerManager {
.await
.map_err(|_| AuthenticatorError::PeerInteractionStopped)?;
response_rx
.await
.map_err(|_| {
AuthenticatorError::InternalError("no response for remove peer".to_string())
})?
recv_with_timeout(response_rx, "remove peer", self.response_timeout)
.await?
.map_err(|err| {
AuthenticatorError::InternalError(format!(
"removing peer could not be performed: {err:?}"
@@ -73,11 +73,8 @@ impl PeerManager {
.await
.map_err(|_| AuthenticatorError::PeerInteractionStopped)?;
response_rx
.await
.map_err(|_| {
AuthenticatorError::InternalError("no response for query peer".to_string())
})?
recv_with_timeout(response_rx, "query peer", self.response_timeout)
.await?
.map_err(|err| {
AuthenticatorError::InternalError(format!(
"querying peer could not be performed: {err:?}"
@@ -106,13 +103,8 @@ impl PeerManager {
.await
.map_err(|_| AuthenticatorError::PeerInteractionStopped)?;
response_rx
.await
.map_err(|_| {
AuthenticatorError::InternalError(
"no response for query client bandwidth".to_string(),
)
})?
recv_with_timeout(response_rx, "query client bandwidth", self.response_timeout)
.await?
.map_err(|err| {
AuthenticatorError::InternalError(format!(
"querying client bandwidth could not be performed: {err:?}"
@@ -138,11 +130,8 @@ impl PeerManager {
.await
.map_err(|_| AuthenticatorError::PeerInteractionStopped)?;
response_rx
.await
.map_err(|_| {
AuthenticatorError::InternalError("no response for query verifier".to_string())
})?
recv_with_timeout(response_rx, "query verifier", self.response_timeout)
.await?
.map_err(|err| {
AuthenticatorError::InternalError(format!(
"querying verifier could not be performed: {err:?}"
@@ -151,10 +140,31 @@ impl PeerManager {
}
}
async fn recv_with_timeout<T>(
response_rx: oneshot::Receiver<T>,
operation: &'static str,
timeout_duration: Duration,
) -> Result<T, AuthenticatorError> {
// Suspend/resume can wedge the peer controller, so we bound the wait to avoid deadlocking
// authenticator responses on a stuck oneshot channel.
match timeout(timeout_duration, response_rx).await {
Ok(Ok(value)) => Ok(value),
Ok(Err(_)) => Err(AuthenticatorError::PeerInteractionStopped),
Err(_) => {
tracing::warn!(
"peer controller response timed out while attempting to {operation} after {:?}",
timeout_duration
);
Err(AuthenticatorError::PeerInteractionTimeout { operation })
}
}
}
#[cfg(test)]
mod tests {
use std::{str::FromStr, sync::Arc};
use futures::channel::oneshot;
use nym_credential_verification::{
bandwidth_storage_manager::BandwidthStorageManager, ecash::MockEcashManager,
};
@@ -163,7 +173,8 @@ mod tests {
use nym_gateway_storage::traits::{mock::MockGatewayStorage, BandwidthGatewayStorage};
use nym_wireguard::peer_controller::{start_controller, stop_controller};
use rand::rngs::OsRng;
use time::{Duration, OffsetDateTime};
use std::time::Duration;
use time::{Duration as TimeDuration, OffsetDateTime};
use tokio::sync::RwLock;
use crate::nym_authenticator::{
@@ -243,7 +254,7 @@ mod tests {
Authenticator::default().into(),
Arc::new(KeyPair::new(&mut OsRng)),
);
let peer_manager = PeerManager::new(wireguard_data);
let peer_manager = PeerManager::new(wireguard_data, Duration::from_secs(5));
let (storage, task_manager) = start_controller(
peer_manager.wireguard_gateway_data.peer_tx().clone(),
request_rx,
@@ -291,7 +302,7 @@ mod tests {
Authenticator::default().into(),
Arc::new(KeyPair::new(&mut OsRng)),
);
let mut peer_manager = PeerManager::new(wireguard_data);
let mut peer_manager = PeerManager::new(wireguard_data, Duration::from_secs(5));
let key = Key::default();
let public_key = PeerPublicKey::from_str(&key.to_string()).unwrap();
let (storage, task_manager) = start_controller(
@@ -311,7 +322,7 @@ mod tests {
Authenticator::default().into(),
Arc::new(KeyPair::new(&mut OsRng)),
);
let mut peer_manager = PeerManager::new(wireguard_data);
let mut peer_manager = PeerManager::new(wireguard_data, Duration::from_secs(5));
let key = Key::default();
let public_key = PeerPublicKey::from_str(&key.to_string()).unwrap();
let (storage, task_manager) = start_controller(
@@ -334,7 +345,7 @@ mod tests {
Authenticator::default().into(),
Arc::new(KeyPair::new(&mut OsRng)),
);
let mut peer_manager = PeerManager::new(wireguard_data);
let mut peer_manager = PeerManager::new(wireguard_data, Duration::from_secs(5));
let key = Key::default();
let public_key = PeerPublicKey::from_str(&key.to_string()).unwrap();
let (storage, task_manager) = start_controller(
@@ -357,7 +368,7 @@ mod tests {
Authenticator::default().into(),
Arc::new(KeyPair::new(&mut OsRng)),
);
let mut peer_manager = PeerManager::new(wireguard_data);
let mut peer_manager = PeerManager::new(wireguard_data, Duration::from_secs(5));
let key = Key::default();
let public_key = PeerPublicKey::from_str(&key.to_string()).unwrap();
let (storage, task_manager) = start_controller(
@@ -388,7 +399,7 @@ mod tests {
Authenticator::default().into(),
Arc::new(KeyPair::new(&mut OsRng)),
);
let mut peer_manager = PeerManager::new(wireguard_data);
let mut peer_manager = PeerManager::new(wireguard_data, Duration::from_secs(5));
let key = Key::default();
let public_key = PeerPublicKey::from_str(&key.to_string()).unwrap();
let (storage, task_manager) = start_controller(
@@ -417,7 +428,7 @@ mod tests {
Authenticator::default().into(),
Arc::new(KeyPair::new(&mut OsRng)),
);
let mut peer_manager = PeerManager::new(wireguard_data);
let mut peer_manager = PeerManager::new(wireguard_data, Duration::from_secs(5));
let key = Key::default();
let public_key = PeerPublicKey::from_str(&key.to_string()).unwrap();
let top_up = 42;
@@ -444,7 +455,7 @@ mod tests {
.increase_bandwidth(
Bandwidth::new_unchecked(top_up as u64),
OffsetDateTime::now_utc()
.checked_add(Duration::minutes(1))
.checked_add(TimeDuration::minutes(1))
.unwrap(),
)
.await
@@ -466,4 +477,28 @@ mod tests {
stop_controller(task_manager).await;
}
#[tokio::test]
async fn recv_with_timeout_errors_after_deadline() {
let (_tx, rx) = oneshot::channel::<()>();
let err = super::recv_with_timeout(rx, "unit-test", Duration::from_millis(10))
.await
.unwrap_err();
assert!(matches!(
err,
AuthenticatorError::PeerInteractionTimeout {
operation: "unit-test"
}
));
}
#[tokio::test]
async fn recv_with_timeout_succeeds_before_deadline() {
let (tx, rx) = oneshot::channel::<u8>();
tx.send(42).unwrap();
let value = super::recv_with_timeout(rx, "unit-test", Duration::from_secs(1))
.await
.unwrap();
assert_eq!(value, 42);
}
}
@@ -19,6 +19,7 @@
"@mui/x-charts": "^8.8.0",
"@mui/x-date-pickers": "^7.29.4",
"@tanstack/react-query": "^5.83.0",
"d3-array": "^3.2.4",
"dayjs": "^1.11.13",
"material-react-table": "^3.2.1",
"next": "^15.4.1",
@@ -30,6 +31,7 @@
"devDependencies": {
"@biomejs/biome": "^1.9.4",
"@tanstack/react-query-devtools": "^5.83.0",
"@types/d3-array": "^3.2.2",
"@types/node": "^20",
"@types/react": "^19",
"@types/react-dom": "^19",
+11
View File
@@ -32,6 +32,9 @@ importers:
'@tanstack/react-query':
specifier: ^5.83.0
version: 5.83.0(react@19.0.0)
d3-array:
specifier: ^3.2.4
version: 3.2.4
dayjs:
specifier: ^1.11.13
version: 1.11.13
@@ -60,6 +63,9 @@ importers:
'@tanstack/react-query-devtools':
specifier: ^5.83.0
version: 5.83.0(@tanstack/react-query@5.83.0(react@19.0.0))(react@19.0.0)
'@types/d3-array':
specifier: ^3.2.2
version: 3.2.2
'@types/node':
specifier: ^20
version: 20.17.14
@@ -659,6 +665,9 @@ packages:
'@tanstack/virtual-core@3.11.2':
resolution: {integrity: sha512-vTtpNt7mKCiZ1pwU9hfKPhpdVO2sVzFQsxoVBGtOSHxlrRRzYr8iQ2TlwbAcRYCcEiZ9ECAM8kBzH0v2+VzfKw==}
'@types/d3-array@3.2.2':
resolution: {integrity: sha512-hOLWVbm7uRza0BYXpIIW5pxfrKe0W+D5lrFiAEYR+pb6w3N2SwSMaJbXdUfSEv+dT4MfHBLtn5js0LAWaO6otw==}
'@types/d3-color@3.1.3':
resolution: {integrity: sha512-iO90scth9WAbmgv7ogoq57O9YpKmFBbmoEoCHDB2xMBY0+/KVrqAaCDyCE16dUspeOvIxFFRI+0sEtqDqy2b4A==}
@@ -1723,6 +1732,8 @@ snapshots:
'@tanstack/virtual-core@3.11.2': {}
'@types/d3-array@3.2.2': {}
'@types/d3-color@3.1.3': {}
'@types/d3-delaunay@6.0.4': {}
@@ -0,0 +1,379 @@
import type { DVpnGateway } from "@/client";
import { ReverseScoreIcon, ScoreIcon } from "@/components/ScoreIcon";
import { useDVpnGatewaysTransformed } from "@/hooks/useGatewaysTransformed";
import RefreshIcon from "@mui/icons-material/Refresh";
import {
IconButton,
Table,
TableBody,
TableCell,
TableHead,
TableRow,
Tooltip,
} from "@mui/material";
import Box from "@mui/material/Box";
import Typography from "@mui/material/Typography";
import dayjs from "dayjs";
import duration from "dayjs/plugin/duration";
import relativeTime from "dayjs/plugin/relativeTime";
import {
type MRT_ColumnDef,
MaterialReactTable,
useMaterialReactTable,
} from "material-react-table";
import { useMemo } from "react";
import ReactCountryFlag from "react-country-flag";
dayjs.extend(duration);
dayjs.extend(relativeTime);
const regionNamesInEnglish = new Intl.DisplayNames(["en"], { type: "region" });
const staleGatewayBinWidthMinutes = 15;
interface StaleGatewayStats {
bins: number[];
average: number;
sum: number;
count: number;
}
export default function GatewaysTable() {
const { data, isError, isRefetching, isLoading, refetch } =
useDVpnGatewaysTransformed().query;
const staleGateways = useMemo(
() =>
(data || []).reduce(
(acc, g) => {
const last_updated_utc = g.last_probe
? dayjs(g.last_probe.last_updated_utc)
: null;
if (!last_updated_utc) return acc;
const diff = dayjs().diff(last_updated_utc, "minutes");
const bin = Math.floor(diff / staleGatewayBinWidthMinutes);
if (!acc.bins[bin]) {
acc.bins[bin] = 0;
}
acc.bins[bin] += 1;
acc.sum += diff;
acc.count += 1;
acc.average = acc.sum / acc.count;
return acc;
},
{
bins: [],
average: 0,
sum: 0,
count: 0,
} as StaleGatewayStats,
),
[data],
);
const columns = useMemo<MRT_ColumnDef<DVpnGateway>[]>(
//column definitions...
() => [
{
accessorKey: "name",
header: "Name",
},
{
accessorKey: "identity_key",
header: "Identity Key",
Cell: ({ cell }) => (
<code>{cell.getValue<string>()?.slice(0, 8)}...</code>
),
},
{
accessorKey: "location.two_letter_iso_country_code",
header: "Country",
Cell: ({ cell }) => {
const value = cell.getValue<string>();
return (
<>
<ReactCountryFlag countryCode={value} /> <code>{value}</code>
<Typography ml={2} fontSize="inherit" component="span">
{regionNamesInEnglish.of(value)}
</Typography>
</>
);
},
},
{
accessorKey: "location.region",
header: "City / Region",
Cell: ({ row }) => {
return (
<>
<Typography ml={2} fontSize="inherit" component="span">
{(row.original.location as any).city}/
{(row.original.location as any).region}
</Typography>
</>
);
},
},
{
accessorKey: "performance_v2.score",
width: 20,
header: "Score",
Cell: ({ cell }) => {
const value = cell.getValue<string>();
return (
<>
<Typography
ml={2}
fontSize="inherit"
component="span"
display="flex"
alignItems="center"
gap={1}
>
<ScoreIcon score={value} />
<span>{value || "-"}</span>
</Typography>
</>
);
},
},
{
accessorKey: "performance_v2.load",
width: 20,
header: "Load",
Cell: ({ cell }) => {
const value = cell.getValue<string>();
return (
<>
<Typography
ml={2}
fontSize="inherit"
component="span"
display="flex"
alignItems="center"
gap={1}
>
<ReverseScoreIcon score={value} />
<span>{value || "-"}</span>
</Typography>
</>
);
},
},
{
accessorKey: "extra.downloadSpeedMBPerSec",
header: "Download Speed ipv4 (MB/sec)",
Cell: ({ renderedCellValue, cell }) => {
if (!cell.getValue()) {
return null;
}
return (
<Typography
ml={2}
fontSize="inherit"
component="span"
display="flex"
justifyContent="end"
mr={2}
>
{renderedCellValue} MB/sec
</Typography>
);
},
},
{
accessorKey: "extra.downloadSpeedIpv6MBPerSec",
header: "Download Speed ipv6 (MB/sec)",
Cell: ({ renderedCellValue, cell }) => {
if (!cell.getValue()) {
return null;
}
return (
<Typography
ml={2}
fontSize="inherit"
component="span"
display="flex"
justifyContent="end"
mr={2}
>
{renderedCellValue} MB/sec
</Typography>
);
},
},
{
accessorKey: "last_probe.outcome.wg.ping_ips_performance_v4",
header: "Probe pings (IPV4)",
Cell: ({ cell }) => {
const value = Math.floor(
Number.parseFloat(cell.getValue<string>() || "0") * 100,
);
return (
<>
<Typography
ml={2}
fontSize="inherit"
component="span"
display="flex"
alignItems="center"
gap={1}
>
<span>{value}%</span>
</Typography>
</>
);
},
},
{
accessorKey: "performance_v2.uptime_percentage_last_24_hours",
width: 20,
header: "Uptime",
Cell: ({ cell, row }) => {
const value: number =
((row.original as any).performance_v2
?.uptime_percentage_last_24_hours || 0) * 100;
// const value = Math.floor(Number.parseFloat(cell.getValue<string>()) * 100);
return (
<>
<Typography
ml={2}
fontSize="inherit"
component="span"
display="flex"
alignItems="center"
gap={1}
>
<span>{value}%</span>
</Typography>
</>
);
},
},
{
accessorKey: "last_probe.outcome.wg.can_query_metadata_v4",
header: "Can query metadata?",
Cell: ({ cell }) => {
const wg = cell.row.original.last_probe?.outcome.wg as any;
const can_query_metadata_v4 = wg?.can_query_metadata_v4;
return (
<>
<Typography
ml={2}
fontSize="inherit"
component="span"
display="flex"
alignItems="center"
gap={1}
>
{can_query_metadata_v4 === null ||
(can_query_metadata_v4 === undefined && <span>-</span>)}
{can_query_metadata_v4 === true && <span></span>}
{can_query_metadata_v4 === false && <span></span>}
</Typography>
</>
);
},
},
{
accessorKey: "last_probe.last_updated_utc",
header: "Last Probed At",
Cell: ({ cell }) => {
const parsed = dayjs(cell.getValue<string>());
return (
<Box display="flex" justifyContent="space-between" width="100%">
<div>
<code>{parsed.format()}</code>
</div>
<div>
<strong>({parsed.fromNow()})</strong>
</div>
</Box>
);
},
},
{
id: "last_probe_age",
accessorKey: "last_probe.last_updated_utc",
header: "Last Probed Age",
Cell: ({ cell, row }) => {
const value = row.original.last_probe?.last_updated_utc;
if (!value) {
return "-";
}
const parsed = dayjs(value);
const age = dayjs().diff(parsed, "minutes");
return <>{age} minutes</>;
},
},
{
accessorKey: "build_information.build_version",
header: "Version",
},
],
[],
//end
);
const table = useMaterialReactTable({
columns,
data: data || [],
initialState: {
showColumnFilters: true,
density: "compact",
pagination: {
pageIndex: 0,
pageSize: 100,
},
},
muiToolbarAlertBannerProps: isError
? {
color: "error",
children: "Error loading data",
}
: undefined,
renderTopToolbarCustomActions: () => (
<Tooltip arrow title="Refresh Data">
<IconButton onClick={() => refetch()}>
<RefreshIcon />
</IconButton>
</Tooltip>
),
rowCount: data?.length || 0,
state: {
isLoading,
showAlertBanner: isError,
showProgressBars: isRefetching,
},
});
return (
<>
<MaterialReactTable table={table} />
<h2>Gateway probe age</h2>
<Box mb={2}>
Average age is {Math.round(staleGateways.average * 10) / 10} minutes old
</Box>
<Box mb={2}>
<Table style={{ width: "auto" }}>
<TableHead>
<TableRow>
<TableCell width={150}>Age</TableCell>
<TableCell>Gateways</TableCell>
</TableRow>
</TableHead>
<TableBody>
{staleGateways.bins.map((r, i) => (
<TableRow key={`${(i + 1) * staleGatewayBinWidthMinutes}-bin`}>
<TableCell>
{(i + 1) * staleGatewayBinWidthMinutes} mins old
</TableCell>
<TableCell>{r}</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</Box>
</>
);
}
@@ -0,0 +1,15 @@
"use client";
import GatewaysTable from "@/app/dvpn/GatewaysTable";
import NestedLayoutWithHeader from "@/layouts/NestedLayoutWithHeader";
import Box from "@mui/material/Box";
export default function Page() {
return (
<NestedLayoutWithHeader header="dVPN Gateways">
<Box width="100%">
<GatewaysTable />
</Box>
</NestedLayoutWithHeader>
);
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

@@ -1,10 +1,30 @@
"use client";
import { QueryContextProvider } from "@/context/queryContext";
import LayoutWithNav from "@/layouts/LayoutWithNav";
import AppTheme from "@/theme";
import { AppRouterCacheProvider } from "@mui/material-nextjs/v15-appRouter";
import CssBaseline from "@mui/material/CssBaseline";
import InitColorSchemeScript from "@mui/material/InitColorSchemeScript";
import { AdapterDayjs } from "@mui/x-date-pickers/AdapterDayjs";
import { LocalizationProvider } from "@mui/x-date-pickers/LocalizationProvider";
export default function RootLayout(props: { children: React.ReactNode }) {
return (
<html lang="en" suppressHydrationWarning>
<body>
{props.children}
<InitColorSchemeScript attribute="class" />
<AppRouterCacheProvider options={{ enableCssLayer: true }}>
<AppTheme>
{/* CssBaseline kickstart an elegant, consistent, and simple baseline to build upon. */}
<CssBaseline enableColorScheme />
<LocalizationProvider dateAdapter={AdapterDayjs}>
<QueryContextProvider>
<LayoutWithNav>{props.children}</LayoutWithNav>
</QueryContextProvider>
</LocalizationProvider>
</AppTheme>
</AppRouterCacheProvider>
</body>
</html>
);
@@ -0,0 +1,124 @@
import { useAllNymNodes } from "@/hooks/useAllNymNodes";
import type { NymNode } from "@/hooks/useNymNodes";
import RefreshIcon from "@mui/icons-material/Refresh";
import { IconButton, Tooltip } from "@mui/material";
import {
type MRT_ColumnDef,
MaterialReactTable,
useMaterialReactTable,
} from "material-react-table";
import { useMemo } from "react";
export default function NodesTable() {
const { data, isError, isRefetching, isLoading, refetch } =
useAllNymNodes().query;
const columns = useMemo<MRT_ColumnDef<NymNode>[]>(
//column definitions...
() => [
{
accessorKey: "node_id",
header: "Node Id",
size: 25,
},
{
accessorKey: "description.moniker",
header: "Moniker",
},
{
accessorKey: "identity_key",
header: "Identity Key",
Cell: ({ cell }) => (
<code>{cell.getValue<string>()?.slice(0, 8)}...</code>
),
},
{
accessorKey: "node_type",
header: "Node Type",
},
{
accessorKey: "bonded",
header: "Bonded",
Cell: ({ cell }) => (cell.getValue<boolean>() ? "✅" : "⛔️"),
},
{
accessorKey: "geoip.country",
header: "Country",
},
{
accessorKey: "geoip.city",
header: "City",
},
{
accessorKey: "self_description.build_information.build_version",
header: "Version",
},
{
accessorKey: "self_description.declared_role.entry",
header: "Entry gateway",
Cell: ({ cell }) => (cell.getValue<boolean>() ? "✅" : "-"),
},
{
accessorKey: "self_description.declared_role.exit",
header: "Exit gateway",
Cell: ({ cell }) => (cell.getValue<boolean>() ? "✅" : "-"),
},
{
accessorKey: "self_description.declared_role.mixnode",
header: "Mixnode",
Cell: ({ cell }) => (cell.getValue<boolean>() ? "✅" : "-"),
},
{
accessorKey: "self_description.declared_role.exit_ipr",
header: "Runs IPR",
Cell: ({ cell }) => (cell.getValue<boolean>() ? "✅" : "-"),
},
{
accessorKey: "self_description.declared_role.exit_nr",
header: "Runs SOCKS5 NR",
Cell: ({ cell }) => (cell.getValue<boolean>() ? "✅" : "-"),
},
{
accessorKey: "self_description.host_information.ip_address",
header: "IP Address",
},
{
accessorKey: "uptime",
header: "Uptime",
},
],
[],
//end
);
const table = useMaterialReactTable({
columns,
data: data || [],
initialState: {
showColumnFilters: true,
density: "compact",
pagination: { pageIndex: 0, pageSize: 100 },
},
muiToolbarAlertBannerProps: isError
? {
color: "error",
children: "Error loading data",
}
: undefined,
renderTopToolbarCustomActions: () => (
<Tooltip arrow title="Refresh Data">
<IconButton onClick={() => refetch()}>
<RefreshIcon />
</IconButton>
</Tooltip>
),
rowCount: data?.length ?? 0,
state: {
isLoading,
showAlertBanner: isError,
showProgressBars: isRefetching,
},
});
return <MaterialReactTable table={table} />;
}
@@ -0,0 +1,15 @@
"use client";
import NodesTable from "@/app/nodes/NodesTable";
import NestedLayoutWithHeader from "@/layouts/NestedLayoutWithHeader";
import Box from "@mui/material/Box";
export default function Page() {
return (
<NestedLayoutWithHeader header="Nym Network Nodes">
<Box width="100%">
<NodesTable />
</Box>
</NestedLayoutWithHeader>
);
}
@@ -0,0 +1,115 @@
import type { DVpnGateway } from "@/client";
import { useDVpnGateways } from "@/hooks/useGateways";
import RefreshIcon from "@mui/icons-material/Refresh";
import { IconButton, Tooltip } from "@mui/material";
import Box from "@mui/material/Box";
import Typography from "@mui/material/Typography";
import dayjs from "dayjs";
import duration from "dayjs/plugin/duration";
import relativeTime from "dayjs/plugin/relativeTime";
import {
type MRT_ColumnDef,
MaterialReactTable,
useMaterialReactTable,
} from "material-react-table";
import { useMemo } from "react";
import ReactCountryFlag from "react-country-flag";
dayjs.extend(duration);
dayjs.extend(relativeTime);
const regionNamesInEnglish = new Intl.DisplayNames(["en"], { type: "region" });
export default function GatewaysTable() {
const { data, isError, isRefetching, isLoading, refetch } =
useDVpnGateways().query;
const columns = useMemo<MRT_ColumnDef<DVpnGateway>[]>(
//column definitions...
() => [
{
accessorKey: "name",
header: "Name",
},
{
accessorKey: "identity_key",
header: "Identity Key",
Cell: ({ cell }) => (
<code>{cell.getValue<string>()?.slice(0, 8)}...</code>
),
},
{
accessorKey: "location.two_letter_iso_country_code",
header: "Country",
Cell: ({ cell }) => {
const value = cell.getValue<string>();
return (
<>
<ReactCountryFlag countryCode={value} /> <code>{value}</code>
<Typography ml={2} fontSize="inherit" component="span">
{regionNamesInEnglish.of(value)}
</Typography>
</>
);
},
},
{
accessorKey: "last_probe.last_updated_utc",
header: "Last Probed At",
Cell: ({ cell }) => {
const parsed = dayjs(cell.getValue<string>());
return (
<Box display="flex" justifyContent="space-between" width="100%">
<div>
<code>{parsed.format()}</code>
</div>
<div>
<strong>({parsed.fromNow()})</strong>
</div>
</Box>
);
},
},
{
accessorKey: "build_information.build_version",
header: "Version",
},
],
[],
//end
);
const table = useMaterialReactTable({
columns,
data: data || [],
initialState: {
showColumnFilters: true,
density: "compact",
pagination: {
pageIndex: 0,
pageSize: 100,
},
},
muiToolbarAlertBannerProps: isError
? {
color: "error",
children: "Error loading data",
}
: undefined,
renderTopToolbarCustomActions: () => (
<Tooltip arrow title="Refresh Data">
<IconButton onClick={() => refetch()}>
<RefreshIcon />
</IconButton>
</Tooltip>
),
rowCount: data?.length || 0,
state: {
isLoading,
showAlertBanner: isError,
showProgressBars: isRefetching,
},
});
return <MaterialReactTable table={table} />;
}
@@ -0,0 +1,15 @@
"use client";
import GatewaysTable from "@/app/dvpn/GatewaysTable";
import NestedLayoutWithHeader from "@/layouts/NestedLayoutWithHeader";
import Box from "@mui/material/Box";
export default function Page() {
return (
<NestedLayoutWithHeader header="NymVPN API Gateways">
<Box width="100%">
<GatewaysTable />
</Box>
</NestedLayoutWithHeader>
);
}
@@ -1,7 +1,61 @@
"use client";
import GraphCard from "@/components/GraphCard";
import { GatewayCanQueryMetadataTopup } from "@/components/graphs/GatewayCanQueryMetadataTopup";
import { GatewayDownloadSpeeds } from "@/components/graphs/GatewayDownloadSpeeds";
import { GatewayLoads } from "@/components/graphs/GatewayLoads";
import { GatewayPingPercentage } from "@/components/graphs/GatewayPingPercentage";
import { GatewayScores } from "@/components/graphs/GatewayScores";
import { GatewayUptimePercentage } from "@/components/graphs/GatewayUptimePercentage";
import { GatewayVersions } from "@/components/graphs/GatewayVersions";
import NestedLayoutWithHeader from "@/layouts/NestedLayoutWithHeader";
import Grid from "@mui/material/Grid";
export default function Home() {
return (
<div>TODO</div>
<NestedLayoutWithHeader>
<Grid
container
spacing={2}
columns={12}
sx={{ mb: (theme) => theme.spacing(2) }}
>
<Grid size={{ xs: 12, sm: 8, lg: 4 }}>
<GraphCard title="Gateway download speeds">
<GatewayDownloadSpeeds />
</GraphCard>
</Grid>
<Grid size={{ xs: 12, sm: 8, lg: 4 }}>
<GraphCard title="Gateway ipv4 ping %">
<GatewayPingPercentage />
</GraphCard>
</Grid>
<Grid size={{ xs: 12, sm: 8, lg: 4 }}>
<GraphCard title="Gateway Uptime %">
<GatewayUptimePercentage />
</GraphCard>
</Grid>
<Grid size={{ xs: 12, sm: 8, lg: 4 }}>
<GraphCard title="Gateway scores">
<GatewayScores />
</GraphCard>
</Grid>
<Grid size={{ xs: 12, sm: 8, lg: 4 }}>
<GraphCard title="Gateway loads">
<GatewayLoads />
</GraphCard>
</Grid>
<Grid size={{ xs: 12, sm: 8, lg: 4 }}>
<GraphCard title="Gateway versions">
<GatewayVersions />
</GraphCard>
</Grid>
<Grid size={{ xs: 12, sm: 8, lg: 4 }}>
<GraphCard title="Gateways with metadata top-up endpoint">
<GatewayCanQueryMetadataTopup />
</GraphCard>
</Grid>
</Grid>
</NestedLayoutWithHeader>
);
}
@@ -0,0 +1,11 @@
"use client";
import NestedLayoutWithHeader from "@/layouts/NestedLayoutWithHeader";
export default function Page() {
return (
<NestedLayoutWithHeader header="SOCKS5 Network Requesters">
<div>SOCKS5</div>
</NestedLayoutWithHeader>
);
}
@@ -0,0 +1,11 @@
"use client";
import NestedLayoutWithHeader from "@/layouts/NestedLayoutWithHeader";
export default function Page() {
return (
<NestedLayoutWithHeader header="Nyx Cosmos Chain Validators">
<div>Validators</div>
</NestedLayoutWithHeader>
);
}
@@ -0,0 +1,11 @@
"use client";
import NestedLayoutWithHeader from "@/layouts/NestedLayoutWithHeader";
export default function Page() {
return (
<NestedLayoutWithHeader header="zk-nym Signing Authorities">
<div>zk-nym signers</div>
</NestedLayoutWithHeader>
);
}
@@ -0,0 +1,936 @@
// This file is auto-generated by @hey-api/openapi-ts
import {
type DefaultError,
type InfiniteData,
infiniteQueryOptions,
queryOptions,
} from "@tanstack/react-query";
import { client as _heyApiClient } from "../client.gen";
import {
type Options,
buildInformation,
gateways,
gatewaysSkinny,
getAllSessions,
getEntryGatewayCountries,
getEntryGateways,
getEntryGatewaysByCountry,
getExitGatewayCountries,
getExitGateways,
getExitGatewaysByCountry,
getGateway,
getGatewayCountries,
getGateways,
getGatewaysByCountry,
getMixnodes,
getStats,
health,
mixnodes,
mixnodes2,
nodeDelegations,
nymNodes,
summary,
summaryHistory,
} from "../sdk.gen";
import type {
BuildInformationData,
GatewaysData,
GatewaysResponse,
GatewaysSkinnyData,
GatewaysSkinnyResponse,
GetAllSessionsData,
GetAllSessionsResponse,
GetEntryGatewayCountriesData,
GetEntryGatewaysByCountryData,
GetEntryGatewaysData,
GetExitGatewayCountriesData,
GetExitGatewaysByCountryData,
GetExitGatewaysData,
GetGatewayCountriesData,
GetGatewayData,
GetGatewaysByCountryData,
GetGatewaysData,
GetMixnodesData,
GetStatsData,
GetStatsResponse,
HealthData,
Mixnodes2Data,
Mixnodes2Response,
MixnodesData,
MixnodesResponse,
NodeDelegationsData,
NymNodesData,
NymNodesResponse,
SummaryData,
SummaryHistoryData,
} from "../types.gen";
export type QueryKey<TOptions extends Options> = [
Pick<TOptions, "baseUrl" | "body" | "headers" | "path" | "query"> & {
_id: string;
_infinite?: boolean;
},
];
const createQueryKey = <TOptions extends Options>(
id: string,
options?: TOptions,
infinite?: boolean,
): [QueryKey<TOptions>[0]] => {
const params: QueryKey<TOptions>[0] = {
_id: id,
baseUrl: (options?.client ?? _heyApiClient).getConfig().baseUrl,
} as QueryKey<TOptions>[0];
if (infinite) {
params._infinite = infinite;
}
if (options?.body) {
params.body = options.body;
}
if (options?.headers) {
params.headers = options.headers;
}
if (options?.path) {
params.path = options.path;
}
if (options?.query) {
params.query = options.query;
}
return [params];
};
export const getGatewaysQueryKey = (options?: Options<GetGatewaysData>) =>
createQueryKey("getGateways", options);
/**
* Gets available entry and exit gateways from the Nym network directory
*/
export const getGatewaysOptions = (options?: Options<GetGatewaysData>) => {
return queryOptions({
queryFn: async ({ queryKey, signal }) => {
const { data } = await getGateways({
...options,
...queryKey[0],
signal,
throwOnError: true,
});
return data;
},
queryKey: getGatewaysQueryKey(options),
});
};
export const getGatewayCountriesQueryKey = (
options?: Options<GetGatewayCountriesData>,
) => createQueryKey("getGatewayCountries", options);
/**
* Gets available exit gateway countries as two-letter ISO country codes from the Nym network directory
*/
export const getGatewayCountriesOptions = (
options?: Options<GetGatewayCountriesData>,
) => {
return queryOptions({
queryFn: async ({ queryKey, signal }) => {
const { data } = await getGatewayCountries({
...options,
...queryKey[0],
signal,
throwOnError: true,
});
return data;
},
queryKey: getGatewayCountriesQueryKey(options),
});
};
export const getGatewaysByCountryQueryKey = (
options: Options<GetGatewaysByCountryData>,
) => createQueryKey("getGatewaysByCountry", options);
/**
* Gets available gateways from the Nym network directory by country
*/
export const getGatewaysByCountryOptions = (
options: Options<GetGatewaysByCountryData>,
) => {
return queryOptions({
queryFn: async ({ queryKey, signal }) => {
const { data } = await getGatewaysByCountry({
...options,
...queryKey[0],
signal,
throwOnError: true,
});
return data;
},
queryKey: getGatewaysByCountryQueryKey(options),
});
};
export const getEntryGatewaysQueryKey = (
options?: Options<GetEntryGatewaysData>,
) => createQueryKey("getEntryGateways", options);
/**
* Gets available entry gateways from the Nym network directory
*/
export const getEntryGatewaysOptions = (
options?: Options<GetEntryGatewaysData>,
) => {
return queryOptions({
queryFn: async ({ queryKey, signal }) => {
const { data } = await getEntryGateways({
...options,
...queryKey[0],
signal,
throwOnError: true,
});
return data;
},
queryKey: getEntryGatewaysQueryKey(options),
});
};
export const getEntryGatewayCountriesQueryKey = (
options?: Options<GetEntryGatewayCountriesData>,
) => createQueryKey("getEntryGatewayCountries", options);
/**
* Gets available entry gateway countries as two-letter ISO country codes from the Nym network directory
*/
export const getEntryGatewayCountriesOptions = (
options?: Options<GetEntryGatewayCountriesData>,
) => {
return queryOptions({
queryFn: async ({ queryKey, signal }) => {
const { data } = await getEntryGatewayCountries({
...options,
...queryKey[0],
signal,
throwOnError: true,
});
return data;
},
queryKey: getEntryGatewayCountriesQueryKey(options),
});
};
export const getEntryGatewaysByCountryQueryKey = (
options: Options<GetEntryGatewaysByCountryData>,
) => createQueryKey("getEntryGatewaysByCountry", options);
/**
* Gets available entry gateways from the Nym network directory by country
*/
export const getEntryGatewaysByCountryOptions = (
options: Options<GetEntryGatewaysByCountryData>,
) => {
return queryOptions({
queryFn: async ({ queryKey, signal }) => {
const { data } = await getEntryGatewaysByCountry({
...options,
...queryKey[0],
signal,
throwOnError: true,
});
return data;
},
queryKey: getEntryGatewaysByCountryQueryKey(options),
});
};
export const getExitGatewaysQueryKey = (
options?: Options<GetExitGatewaysData>,
) => createQueryKey("getExitGateways", options);
/**
* Gets available exit gateways from the Nym network directory
*/
export const getExitGatewaysOptions = (
options?: Options<GetExitGatewaysData>,
) => {
return queryOptions({
queryFn: async ({ queryKey, signal }) => {
const { data } = await getExitGateways({
...options,
...queryKey[0],
signal,
throwOnError: true,
});
return data;
},
queryKey: getExitGatewaysQueryKey(options),
});
};
export const getExitGatewayCountriesQueryKey = (
options?: Options<GetExitGatewayCountriesData>,
) => createQueryKey("getExitGatewayCountries", options);
/**
* Gets available exit gateway countries as two-letter ISO country codes from the Nym network directory
*/
export const getExitGatewayCountriesOptions = (
options?: Options<GetExitGatewayCountriesData>,
) => {
return queryOptions({
queryFn: async ({ queryKey, signal }) => {
const { data } = await getExitGatewayCountries({
...options,
...queryKey[0],
signal,
throwOnError: true,
});
return data;
},
queryKey: getExitGatewayCountriesQueryKey(options),
});
};
export const getExitGatewaysByCountryQueryKey = (
options: Options<GetExitGatewaysByCountryData>,
) => createQueryKey("getExitGatewaysByCountry", options);
/**
* Gets available exit gateways from the Nym network directory by country
*/
export const getExitGatewaysByCountryOptions = (
options: Options<GetExitGatewaysByCountryData>,
) => {
return queryOptions({
queryFn: async ({ queryKey, signal }) => {
const { data } = await getExitGatewaysByCountry({
...options,
...queryKey[0],
signal,
throwOnError: true,
});
return data;
},
queryKey: getExitGatewaysByCountryQueryKey(options),
});
};
export const nymNodesQueryKey = (options?: Options<NymNodesData>) =>
createQueryKey("nymNodes", options);
export const nymNodesOptions = (options?: Options<NymNodesData>) => {
return queryOptions({
queryFn: async ({ queryKey, signal }) => {
const { data } = await nymNodes({
...options,
...queryKey[0],
signal,
throwOnError: true,
});
return data;
},
queryKey: nymNodesQueryKey(options),
});
};
const createInfiniteParams = <
K extends Pick<QueryKey<Options>[0], "body" | "headers" | "path" | "query">,
>(
queryKey: QueryKey<Options>,
page: K,
) => {
const params = {
...queryKey[0],
};
if (page.body) {
params.body = {
...(queryKey[0].body as any),
...(page.body as any),
};
}
if (page.headers) {
params.headers = {
...queryKey[0].headers,
...page.headers,
};
}
if (page.path) {
params.path = {
...(queryKey[0].path as any),
...(page.path as any),
};
}
if (page.query) {
params.query = {
...(queryKey[0].query as any),
...(page.query as any),
};
}
return params as unknown as typeof page;
};
export const nymNodesInfiniteQueryKey = (
options?: Options<NymNodesData>,
): QueryKey<Options<NymNodesData>> => createQueryKey("nymNodes", options, true);
export const nymNodesInfiniteOptions = (options?: Options<NymNodesData>) => {
return infiniteQueryOptions<
NymNodesResponse,
DefaultError,
InfiniteData<NymNodesResponse>,
QueryKey<Options<NymNodesData>>,
| number
| Pick<
QueryKey<Options<NymNodesData>>[0],
"body" | "headers" | "path" | "query"
>
>(
// @ts-ignore
{
queryFn: async ({ pageParam, queryKey, signal }) => {
// @ts-ignore
const page: Pick<
QueryKey<Options<NymNodesData>>[0],
"body" | "headers" | "path" | "query"
> =
typeof pageParam === "object"
? pageParam
: {
query: {
page: pageParam,
},
};
const params = createInfiniteParams(queryKey, page);
const { data } = await nymNodes({
...options,
...params,
signal,
throwOnError: true,
});
return data;
},
queryKey: nymNodesInfiniteQueryKey(options),
},
);
};
export const nodeDelegationsQueryKey = (
options: Options<NodeDelegationsData>,
) => createQueryKey("nodeDelegations", options);
export const nodeDelegationsOptions = (
options: Options<NodeDelegationsData>,
) => {
return queryOptions({
queryFn: async ({ queryKey, signal }) => {
const { data } = await nodeDelegations({
...options,
...queryKey[0],
signal,
throwOnError: true,
});
return data;
},
queryKey: nodeDelegationsQueryKey(options),
});
};
export const gatewaysQueryKey = (options?: Options<GatewaysData>) =>
createQueryKey("gateways", options);
export const gatewaysOptions = (options?: Options<GatewaysData>) => {
return queryOptions({
queryFn: async ({ queryKey, signal }) => {
const { data } = await gateways({
...options,
...queryKey[0],
signal,
throwOnError: true,
});
return data;
},
queryKey: gatewaysQueryKey(options),
});
};
export const gatewaysInfiniteQueryKey = (
options?: Options<GatewaysData>,
): QueryKey<Options<GatewaysData>> => createQueryKey("gateways", options, true);
export const gatewaysInfiniteOptions = (options?: Options<GatewaysData>) => {
return infiniteQueryOptions<
GatewaysResponse,
DefaultError,
InfiniteData<GatewaysResponse>,
QueryKey<Options<GatewaysData>>,
| number
| Pick<
QueryKey<Options<GatewaysData>>[0],
"body" | "headers" | "path" | "query"
>
>(
// @ts-ignore
{
queryFn: async ({ pageParam, queryKey, signal }) => {
// @ts-ignore
const page: Pick<
QueryKey<Options<GatewaysData>>[0],
"body" | "headers" | "path" | "query"
> =
typeof pageParam === "object"
? pageParam
: {
query: {
page: pageParam,
},
};
const params = createInfiniteParams(queryKey, page);
const { data } = await gateways({
...options,
...params,
signal,
throwOnError: true,
});
return data;
},
queryKey: gatewaysInfiniteQueryKey(options),
},
);
};
export const gatewaysSkinnyQueryKey = (options?: Options<GatewaysSkinnyData>) =>
createQueryKey("gatewaysSkinny", options);
export const gatewaysSkinnyOptions = (
options?: Options<GatewaysSkinnyData>,
) => {
return queryOptions({
queryFn: async ({ queryKey, signal }) => {
const { data } = await gatewaysSkinny({
...options,
...queryKey[0],
signal,
throwOnError: true,
});
return data;
},
queryKey: gatewaysSkinnyQueryKey(options),
});
};
export const gatewaysSkinnyInfiniteQueryKey = (
options?: Options<GatewaysSkinnyData>,
): QueryKey<Options<GatewaysSkinnyData>> =>
createQueryKey("gatewaysSkinny", options, true);
export const gatewaysSkinnyInfiniteOptions = (
options?: Options<GatewaysSkinnyData>,
) => {
return infiniteQueryOptions<
GatewaysSkinnyResponse,
DefaultError,
InfiniteData<GatewaysSkinnyResponse>,
QueryKey<Options<GatewaysSkinnyData>>,
| number
| Pick<
QueryKey<Options<GatewaysSkinnyData>>[0],
"body" | "headers" | "path" | "query"
>
>(
// @ts-ignore
{
queryFn: async ({ pageParam, queryKey, signal }) => {
// @ts-ignore
const page: Pick<
QueryKey<Options<GatewaysSkinnyData>>[0],
"body" | "headers" | "path" | "query"
> =
typeof pageParam === "object"
? pageParam
: {
query: {
page: pageParam,
},
};
const params = createInfiniteParams(queryKey, page);
const { data } = await gatewaysSkinny({
...options,
...params,
signal,
throwOnError: true,
});
return data;
},
queryKey: gatewaysSkinnyInfiniteQueryKey(options),
},
);
};
export const getGatewayQueryKey = (options: Options<GetGatewayData>) =>
createQueryKey("getGateway", options);
export const getGatewayOptions = (options: Options<GetGatewayData>) => {
return queryOptions({
queryFn: async ({ queryKey, signal }) => {
const { data } = await getGateway({
...options,
...queryKey[0],
signal,
throwOnError: true,
});
return data;
},
queryKey: getGatewayQueryKey(options),
});
};
export const getAllSessionsQueryKey = (options?: Options<GetAllSessionsData>) =>
createQueryKey("getAllSessions", options);
export const getAllSessionsOptions = (
options?: Options<GetAllSessionsData>,
) => {
return queryOptions({
queryFn: async ({ queryKey, signal }) => {
const { data } = await getAllSessions({
...options,
...queryKey[0],
signal,
throwOnError: true,
});
return data;
},
queryKey: getAllSessionsQueryKey(options),
});
};
export const getAllSessionsInfiniteQueryKey = (
options?: Options<GetAllSessionsData>,
): QueryKey<Options<GetAllSessionsData>> =>
createQueryKey("getAllSessions", options, true);
export const getAllSessionsInfiniteOptions = (
options?: Options<GetAllSessionsData>,
) => {
return infiniteQueryOptions<
GetAllSessionsResponse,
DefaultError,
InfiniteData<GetAllSessionsResponse>,
QueryKey<Options<GetAllSessionsData>>,
| number
| Pick<
QueryKey<Options<GetAllSessionsData>>[0],
"body" | "headers" | "path" | "query"
>
>(
// @ts-ignore
{
queryFn: async ({ pageParam, queryKey, signal }) => {
// @ts-ignore
const page: Pick<
QueryKey<Options<GetAllSessionsData>>[0],
"body" | "headers" | "path" | "query"
> =
typeof pageParam === "object"
? pageParam
: {
query: {
page: pageParam,
},
};
const params = createInfiniteParams(queryKey, page);
const { data } = await getAllSessions({
...options,
...params,
signal,
throwOnError: true,
});
return data;
},
queryKey: getAllSessionsInfiniteQueryKey(options),
},
);
};
export const mixnodesQueryKey = (options?: Options<MixnodesData>) =>
createQueryKey("mixnodes", options);
export const mixnodesOptions = (options?: Options<MixnodesData>) => {
return queryOptions({
queryFn: async ({ queryKey, signal }) => {
const { data } = await mixnodes({
...options,
...queryKey[0],
signal,
throwOnError: true,
});
return data;
},
queryKey: mixnodesQueryKey(options),
});
};
export const mixnodesInfiniteQueryKey = (
options?: Options<MixnodesData>,
): QueryKey<Options<MixnodesData>> => createQueryKey("mixnodes", options, true);
export const mixnodesInfiniteOptions = (options?: Options<MixnodesData>) => {
return infiniteQueryOptions<
MixnodesResponse,
DefaultError,
InfiniteData<MixnodesResponse>,
QueryKey<Options<MixnodesData>>,
| number
| Pick<
QueryKey<Options<MixnodesData>>[0],
"body" | "headers" | "path" | "query"
>
>(
// @ts-ignore
{
queryFn: async ({ pageParam, queryKey, signal }) => {
// @ts-ignore
const page: Pick<
QueryKey<Options<MixnodesData>>[0],
"body" | "headers" | "path" | "query"
> =
typeof pageParam === "object"
? pageParam
: {
query: {
page: pageParam,
},
};
const params = createInfiniteParams(queryKey, page);
const { data } = await mixnodes({
...options,
...params,
signal,
throwOnError: true,
});
return data;
},
queryKey: mixnodesInfiniteQueryKey(options),
},
);
};
export const getStatsQueryKey = (options?: Options<GetStatsData>) =>
createQueryKey("getStats", options);
export const getStatsOptions = (options?: Options<GetStatsData>) => {
return queryOptions({
queryFn: async ({ queryKey, signal }) => {
const { data } = await getStats({
...options,
...queryKey[0],
signal,
throwOnError: true,
});
return data;
},
queryKey: getStatsQueryKey(options),
});
};
export const getStatsInfiniteQueryKey = (
options?: Options<GetStatsData>,
): QueryKey<Options<GetStatsData>> => createQueryKey("getStats", options, true);
export const getStatsInfiniteOptions = (options?: Options<GetStatsData>) => {
return infiniteQueryOptions<
GetStatsResponse,
DefaultError,
InfiniteData<GetStatsResponse>,
QueryKey<Options<GetStatsData>>,
| number
| Pick<
QueryKey<Options<GetStatsData>>[0],
"body" | "headers" | "path" | "query"
>
>(
// @ts-ignore
{
queryFn: async ({ pageParam, queryKey, signal }) => {
// @ts-ignore
const page: Pick<
QueryKey<Options<GetStatsData>>[0],
"body" | "headers" | "path" | "query"
> =
typeof pageParam === "object"
? pageParam
: {
query: {
offset: pageParam,
},
};
const params = createInfiniteParams(queryKey, page);
const { data } = await getStats({
...options,
...params,
signal,
throwOnError: true,
});
return data;
},
queryKey: getStatsInfiniteQueryKey(options),
},
);
};
export const getMixnodesQueryKey = (options: Options<GetMixnodesData>) =>
createQueryKey("getMixnodes", options);
export const getMixnodesOptions = (options: Options<GetMixnodesData>) => {
return queryOptions({
queryFn: async ({ queryKey, signal }) => {
const { data } = await getMixnodes({
...options,
...queryKey[0],
signal,
throwOnError: true,
});
return data;
},
queryKey: getMixnodesQueryKey(options),
});
};
export const mixnodes2QueryKey = (options?: Options<Mixnodes2Data>) =>
createQueryKey("mixnodes2", options);
export const mixnodes2Options = (options?: Options<Mixnodes2Data>) => {
return queryOptions({
queryFn: async ({ queryKey, signal }) => {
const { data } = await mixnodes2({
...options,
...queryKey[0],
signal,
throwOnError: true,
});
return data;
},
queryKey: mixnodes2QueryKey(options),
});
};
export const mixnodes2InfiniteQueryKey = (
options?: Options<Mixnodes2Data>,
): QueryKey<Options<Mixnodes2Data>> =>
createQueryKey("mixnodes2", options, true);
export const mixnodes2InfiniteOptions = (options?: Options<Mixnodes2Data>) => {
return infiniteQueryOptions<
Mixnodes2Response,
DefaultError,
InfiniteData<Mixnodes2Response>,
QueryKey<Options<Mixnodes2Data>>,
| number
| Pick<
QueryKey<Options<Mixnodes2Data>>[0],
"body" | "headers" | "path" | "query"
>
>(
// @ts-ignore
{
queryFn: async ({ pageParam, queryKey, signal }) => {
// @ts-ignore
const page: Pick<
QueryKey<Options<Mixnodes2Data>>[0],
"body" | "headers" | "path" | "query"
> =
typeof pageParam === "object"
? pageParam
: {
query: {
page: pageParam,
},
};
const params = createInfiniteParams(queryKey, page);
const { data } = await mixnodes2({
...options,
...params,
signal,
throwOnError: true,
});
return data;
},
queryKey: mixnodes2InfiniteQueryKey(options),
},
);
};
export const buildInformationQueryKey = (
options?: Options<BuildInformationData>,
) => createQueryKey("buildInformation", options);
export const buildInformationOptions = (
options?: Options<BuildInformationData>,
) => {
return queryOptions({
queryFn: async ({ queryKey, signal }) => {
const { data } = await buildInformation({
...options,
...queryKey[0],
signal,
throwOnError: true,
});
return data;
},
queryKey: buildInformationQueryKey(options),
});
};
export const healthQueryKey = (options?: Options<HealthData>) =>
createQueryKey("health", options);
export const healthOptions = (options?: Options<HealthData>) => {
return queryOptions({
queryFn: async ({ queryKey, signal }) => {
const { data } = await health({
...options,
...queryKey[0],
signal,
throwOnError: true,
});
return data;
},
queryKey: healthQueryKey(options),
});
};
export const summaryQueryKey = (options?: Options<SummaryData>) =>
createQueryKey("summary", options);
export const summaryOptions = (options?: Options<SummaryData>) => {
return queryOptions({
queryFn: async ({ queryKey, signal }) => {
const { data } = await summary({
...options,
...queryKey[0],
signal,
throwOnError: true,
});
return data;
},
queryKey: summaryQueryKey(options),
});
};
export const summaryHistoryQueryKey = (options?: Options<SummaryHistoryData>) =>
createQueryKey("summaryHistory", options);
export const summaryHistoryOptions = (
options?: Options<SummaryHistoryData>,
) => {
return queryOptions({
queryFn: async ({ queryKey, signal }) => {
const { data } = await summaryHistory({
...options,
...queryKey[0],
signal,
throwOnError: true,
});
return data;
},
queryKey: summaryHistoryQueryKey(options),
});
};
@@ -0,0 +1,28 @@
// This file is auto-generated by @hey-api/openapi-ts
import {
type Config,
type ClientOptions as DefaultClientOptions,
createClient,
createConfig,
} from "./client";
import type { ClientOptions } from "./types.gen";
/**
* The `createClientConfig()` function will be called on client initialization
* and the returned object will become the client's initial configuration.
*
* You may want to initialize your client this way instead of calling
* `setConfig()`. This is useful for example if you're using Next.js
* to ensure your client always has the correct values.
*/
export type CreateClientConfig<T extends DefaultClientOptions = ClientOptions> =
(
override?: Config<DefaultClientOptions & T>,
) => Config<Required<DefaultClientOptions> & T>;
export const client = createClient(
createConfig<ClientOptions>({
baseUrl: "https://mainnet-node-status-api.nymtech.cc",
}),
);
@@ -0,0 +1,195 @@
import type { Client, Config, RequestOptions } from "./types";
import {
buildUrl,
createConfig,
createInterceptors,
getParseAs,
mergeConfigs,
mergeHeaders,
setAuthParams,
} from "./utils";
type ReqInit = Omit<RequestInit, "body" | "headers"> & {
body?: any;
headers: ReturnType<typeof mergeHeaders>;
};
export const createClient = (config: Config = {}): Client => {
let _config = mergeConfigs(createConfig(), config);
const getConfig = (): Config => ({ ..._config });
const setConfig = (config: Config): Config => {
_config = mergeConfigs(_config, config);
return getConfig();
};
const interceptors = createInterceptors<
Request,
Response,
unknown,
RequestOptions
>();
const request: Client["request"] = async (options) => {
const opts = {
..._config,
...options,
fetch: options.fetch ?? _config.fetch ?? globalThis.fetch,
headers: mergeHeaders(_config.headers, options.headers),
};
if (opts.security) {
await setAuthParams({
...opts,
security: opts.security,
});
}
if (opts.requestValidator) {
await opts.requestValidator(opts);
}
if (opts.body && opts.bodySerializer) {
opts.body = opts.bodySerializer(opts.body);
}
// remove Content-Type header if body is empty to avoid sending invalid requests
if (opts.body === undefined || opts.body === "") {
opts.headers.delete("Content-Type");
}
const url = buildUrl(opts);
const requestInit: ReqInit = {
redirect: "follow",
...opts,
};
let request = new Request(url, requestInit);
for (const fn of interceptors.request._fns) {
if (fn) {
request = await fn(request, opts);
}
}
// fetch must be assigned here, otherwise it would throw the error:
// TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation
const _fetch = opts.fetch!;
let response = await _fetch(request);
for (const fn of interceptors.response._fns) {
if (fn) {
response = await fn(response, request, opts);
}
}
const result = {
request,
response,
};
if (response.ok) {
if (
response.status === 204 ||
response.headers.get("Content-Length") === "0"
) {
return opts.responseStyle === "data"
? {}
: {
data: {},
...result,
};
}
const parseAs =
(opts.parseAs === "auto"
? getParseAs(response.headers.get("Content-Type"))
: opts.parseAs) ?? "json";
let data: any;
switch (parseAs) {
case "arrayBuffer":
case "blob":
case "formData":
case "json":
case "text":
data = await response[parseAs]();
break;
case "stream":
return opts.responseStyle === "data"
? response.body
: {
data: response.body,
...result,
};
}
if (parseAs === "json") {
if (opts.responseValidator) {
await opts.responseValidator(data);
}
if (opts.responseTransformer) {
data = await opts.responseTransformer(data);
}
}
return opts.responseStyle === "data"
? data
: {
data,
...result,
};
}
const textError = await response.text();
let jsonError: unknown;
try {
jsonError = JSON.parse(textError);
} catch {
// noop
}
const error = jsonError ?? textError;
let finalError = error;
for (const fn of interceptors.error._fns) {
if (fn) {
finalError = (await fn(error, response, request, opts)) as string;
}
}
finalError = finalError || ({} as string);
if (opts.throwOnError) {
throw finalError;
}
// TODO: we probably want to return error and improve types
return opts.responseStyle === "data"
? undefined
: {
error: finalError,
...result,
};
};
return {
buildUrl,
connect: (options) => request({ ...options, method: "CONNECT" }),
delete: (options) => request({ ...options, method: "DELETE" }),
get: (options) => request({ ...options, method: "GET" }),
getConfig,
head: (options) => request({ ...options, method: "HEAD" }),
interceptors,
options: (options) => request({ ...options, method: "OPTIONS" }),
patch: (options) => request({ ...options, method: "PATCH" }),
post: (options) => request({ ...options, method: "POST" }),
put: (options) => request({ ...options, method: "PUT" }),
request,
setConfig,
trace: (options) => request({ ...options, method: "TRACE" }),
};
};
@@ -0,0 +1,22 @@
export type { Auth } from "../core/auth";
export type { QuerySerializerOptions } from "../core/bodySerializer";
export {
formDataBodySerializer,
jsonBodySerializer,
urlSearchParamsBodySerializer,
} from "../core/bodySerializer";
export { buildClientParams } from "../core/params";
export { createClient } from "./client";
export type {
Client,
ClientOptions,
Config,
CreateClientConfig,
Options,
OptionsLegacyParser,
RequestOptions,
RequestResult,
ResponseStyle,
TDataShape,
} from "./types";
export { createConfig, mergeHeaders } from "./utils";
@@ -0,0 +1,219 @@
import type { Auth } from "../core/auth";
import type { Client as CoreClient, Config as CoreConfig } from "../core/types";
import type { Middleware } from "./utils";
export type ResponseStyle = "data" | "fields";
export interface Config<T extends ClientOptions = ClientOptions>
extends Omit<RequestInit, "body" | "headers" | "method">,
CoreConfig {
/**
* Base URL for all requests made by this client.
*/
baseUrl?: T["baseUrl"];
/**
* Fetch API implementation. You can use this option to provide a custom
* fetch instance.
*
* @default globalThis.fetch
*/
fetch?: (request: Request) => ReturnType<typeof fetch>;
/**
* Please don't use the Fetch client for Next.js applications. The `next`
* options won't have any effect.
*
* Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead.
*/
next?: never;
/**
* Return the response data parsed in a specified format. By default, `auto`
* will infer the appropriate method from the `Content-Type` response header.
* You can override this behavior with any of the {@link Body} methods.
* Select `stream` if you don't want to parse response data at all.
*
* @default 'auto'
*/
parseAs?:
| "arrayBuffer"
| "auto"
| "blob"
| "formData"
| "json"
| "stream"
| "text";
/**
* Should we return only data or multiple fields (data, error, response, etc.)?
*
* @default 'fields'
*/
responseStyle?: ResponseStyle;
/**
* Throw an error instead of returning it in the response?
*
* @default false
*/
throwOnError?: T["throwOnError"];
}
export interface RequestOptions<
TResponseStyle extends ResponseStyle = "fields",
ThrowOnError extends boolean = boolean,
Url extends string = string,
> extends Config<{
responseStyle: TResponseStyle;
throwOnError: ThrowOnError;
}> {
/**
* Any body that you want to add to your request.
*
* {@link https://developer.mozilla.org/docs/Web/API/fetch#body}
*/
body?: unknown;
path?: Record<string, unknown>;
query?: Record<string, unknown>;
/**
* Security mechanism(s) to use for the request.
*/
security?: ReadonlyArray<Auth>;
url: Url;
}
export type RequestResult<
TData = unknown,
TError = unknown,
ThrowOnError extends boolean = boolean,
TResponseStyle extends ResponseStyle = "fields",
> = ThrowOnError extends true
? Promise<
TResponseStyle extends "data"
? TData extends Record<string, unknown>
? TData[keyof TData]
: TData
: {
data: TData extends Record<string, unknown>
? TData[keyof TData]
: TData;
request: Request;
response: Response;
}
>
: Promise<
TResponseStyle extends "data"
?
| (TData extends Record<string, unknown>
? TData[keyof TData]
: TData)
| undefined
: (
| {
data: TData extends Record<string, unknown>
? TData[keyof TData]
: TData;
error: undefined;
}
| {
data: undefined;
error: TError extends Record<string, unknown>
? TError[keyof TError]
: TError;
}
) & {
request: Request;
response: Response;
}
>;
export interface ClientOptions {
baseUrl?: string;
responseStyle?: ResponseStyle;
throwOnError?: boolean;
}
type MethodFn = <
TData = unknown,
TError = unknown,
ThrowOnError extends boolean = false,
TResponseStyle extends ResponseStyle = "fields",
>(
options: Omit<RequestOptions<TResponseStyle, ThrowOnError>, "method">,
) => RequestResult<TData, TError, ThrowOnError, TResponseStyle>;
type RequestFn = <
TData = unknown,
TError = unknown,
ThrowOnError extends boolean = false,
TResponseStyle extends ResponseStyle = "fields",
>(
options: Omit<RequestOptions<TResponseStyle, ThrowOnError>, "method"> &
Pick<Required<RequestOptions<TResponseStyle, ThrowOnError>>, "method">,
) => RequestResult<TData, TError, ThrowOnError, TResponseStyle>;
type BuildUrlFn = <
TData extends {
body?: unknown;
path?: Record<string, unknown>;
query?: Record<string, unknown>;
url: string;
},
>(
options: Pick<TData, "url"> & Options<TData>,
) => string;
export type Client = CoreClient<RequestFn, Config, MethodFn, BuildUrlFn> & {
interceptors: Middleware<Request, Response, unknown, RequestOptions>;
};
/**
* The `createClientConfig()` function will be called on client initialization
* and the returned object will become the client's initial configuration.
*
* You may want to initialize your client this way instead of calling
* `setConfig()`. This is useful for example if you're using Next.js
* to ensure your client always has the correct values.
*/
export type CreateClientConfig<T extends ClientOptions = ClientOptions> = (
override?: Config<ClientOptions & T>,
) => Config<Required<ClientOptions> & T>;
export interface TDataShape {
body?: unknown;
headers?: unknown;
path?: unknown;
query?: unknown;
url: string;
}
type OmitKeys<T, K> = Pick<T, Exclude<keyof T, K>>;
export type Options<
TData extends TDataShape = TDataShape,
ThrowOnError extends boolean = boolean,
TResponseStyle extends ResponseStyle = "fields",
> = OmitKeys<
RequestOptions<TResponseStyle, ThrowOnError>,
"body" | "path" | "query" | "url"
> &
Omit<TData, "url">;
export type OptionsLegacyParser<
TData = unknown,
ThrowOnError extends boolean = boolean,
TResponseStyle extends ResponseStyle = "fields",
> = TData extends { body?: any }
? TData extends { headers?: any }
? OmitKeys<
RequestOptions<TResponseStyle, ThrowOnError>,
"body" | "headers" | "url"
> &
TData
: OmitKeys<RequestOptions<TResponseStyle, ThrowOnError>, "body" | "url"> &
TData &
Pick<RequestOptions<TResponseStyle, ThrowOnError>, "headers">
: TData extends { headers?: any }
? OmitKeys<
RequestOptions<TResponseStyle, ThrowOnError>,
"headers" | "url"
> &
TData &
Pick<RequestOptions<TResponseStyle, ThrowOnError>, "body">
: OmitKeys<RequestOptions<TResponseStyle, ThrowOnError>, "url"> & TData;
@@ -0,0 +1,417 @@
import { getAuthToken } from "../core/auth";
import type {
QuerySerializer,
QuerySerializerOptions,
} from "../core/bodySerializer";
import { jsonBodySerializer } from "../core/bodySerializer";
import {
serializeArrayParam,
serializeObjectParam,
serializePrimitiveParam,
} from "../core/pathSerializer";
import type { Client, ClientOptions, Config, RequestOptions } from "./types";
interface PathSerializer {
path: Record<string, unknown>;
url: string;
}
const PATH_PARAM_RE = /\{[^{}]+\}/g;
type ArrayStyle = "form" | "spaceDelimited" | "pipeDelimited";
type MatrixStyle = "label" | "matrix" | "simple";
type ArraySeparatorStyle = ArrayStyle | MatrixStyle;
const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => {
let url = _url;
const matches = _url.match(PATH_PARAM_RE);
if (matches) {
for (const match of matches) {
let explode = false;
let name = match.substring(1, match.length - 1);
let style: ArraySeparatorStyle = "simple";
if (name.endsWith("*")) {
explode = true;
name = name.substring(0, name.length - 1);
}
if (name.startsWith(".")) {
name = name.substring(1);
style = "label";
} else if (name.startsWith(";")) {
name = name.substring(1);
style = "matrix";
}
const value = path[name];
if (value === undefined || value === null) {
continue;
}
if (Array.isArray(value)) {
url = url.replace(
match,
serializeArrayParam({ explode, name, style, value }),
);
continue;
}
if (typeof value === "object") {
url = url.replace(
match,
serializeObjectParam({
explode,
name,
style,
value: value as Record<string, unknown>,
valueOnly: true,
}),
);
continue;
}
if (style === "matrix") {
url = url.replace(
match,
`;${serializePrimitiveParam({
name,
value: value as string,
})}`,
);
continue;
}
const replaceValue = encodeURIComponent(
style === "label" ? `.${value as string}` : (value as string),
);
url = url.replace(match, replaceValue);
}
}
return url;
};
export const createQuerySerializer = <T = unknown>({
allowReserved,
array,
object,
}: QuerySerializerOptions = {}) => {
const querySerializer = (queryParams: T) => {
const search: string[] = [];
if (queryParams && typeof queryParams === "object") {
for (const name in queryParams) {
const value = queryParams[name];
if (value === undefined || value === null) {
continue;
}
if (Array.isArray(value)) {
const serializedArray = serializeArrayParam({
allowReserved,
explode: true,
name,
style: "form",
value,
...array,
});
if (serializedArray) search.push(serializedArray);
} else if (typeof value === "object") {
const serializedObject = serializeObjectParam({
allowReserved,
explode: true,
name,
style: "deepObject",
value: value as Record<string, unknown>,
...object,
});
if (serializedObject) search.push(serializedObject);
} else {
const serializedPrimitive = serializePrimitiveParam({
allowReserved,
name,
value: value as string,
});
if (serializedPrimitive) search.push(serializedPrimitive);
}
}
}
return search.join("&");
};
return querySerializer;
};
/**
* Infers parseAs value from provided Content-Type header.
*/
export const getParseAs = (
contentType: string | null,
): Exclude<Config["parseAs"], "auto"> => {
if (!contentType) {
// If no Content-Type header is provided, the best we can do is return the raw response body,
// which is effectively the same as the 'stream' option.
return "stream";
}
const cleanContent = contentType.split(";")[0]?.trim();
if (!cleanContent) {
return;
}
if (
cleanContent.startsWith("application/json") ||
cleanContent.endsWith("+json")
) {
return "json";
}
if (cleanContent === "multipart/form-data") {
return "formData";
}
if (
["application/", "audio/", "image/", "video/"].some((type) =>
cleanContent.startsWith(type),
)
) {
return "blob";
}
if (cleanContent.startsWith("text/")) {
return "text";
}
return;
};
export const setAuthParams = async ({
security,
...options
}: Pick<Required<RequestOptions>, "security"> &
Pick<RequestOptions, "auth" | "query"> & {
headers: Headers;
}) => {
for (const auth of security) {
const token = await getAuthToken(auth, options.auth);
if (!token) {
continue;
}
const name = auth.name ?? "Authorization";
switch (auth.in) {
case "query":
if (!options.query) {
options.query = {};
}
options.query[name] = token;
break;
case "cookie":
options.headers.append("Cookie", `${name}=${token}`);
break;
case "header":
default:
options.headers.set(name, token);
break;
}
return;
}
};
export const buildUrl: Client["buildUrl"] = (options) => {
const url = getUrl({
baseUrl: options.baseUrl as string,
path: options.path,
query: options.query,
querySerializer:
typeof options.querySerializer === "function"
? options.querySerializer
: createQuerySerializer(options.querySerializer),
url: options.url,
});
return url;
};
export const getUrl = ({
baseUrl,
path,
query,
querySerializer,
url: _url,
}: {
baseUrl?: string;
path?: Record<string, unknown>;
query?: Record<string, unknown>;
querySerializer: QuerySerializer;
url: string;
}) => {
const pathUrl = _url.startsWith("/") ? _url : `/${_url}`;
let url = (baseUrl ?? "") + pathUrl;
if (path) {
url = defaultPathSerializer({ path, url });
}
let search = query ? querySerializer(query) : "";
if (search.startsWith("?")) {
search = search.substring(1);
}
if (search) {
url += `?${search}`;
}
return url;
};
export const mergeConfigs = (a: Config, b: Config): Config => {
const config = { ...a, ...b };
if (config.baseUrl?.endsWith("/")) {
config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1);
}
config.headers = mergeHeaders(a.headers, b.headers);
return config;
};
export const mergeHeaders = (
...headers: Array<Required<Config>["headers"] | undefined>
): Headers => {
const mergedHeaders = new Headers();
for (const header of headers) {
if (!header || typeof header !== "object") {
continue;
}
const iterator =
header instanceof Headers ? header.entries() : Object.entries(header);
for (const [key, value] of iterator) {
if (value === null) {
mergedHeaders.delete(key);
} else if (Array.isArray(value)) {
for (const v of value) {
mergedHeaders.append(key, v as string);
}
} else if (value !== undefined) {
// assume object headers are meant to be JSON stringified, i.e. their
// content value in OpenAPI specification is 'application/json'
mergedHeaders.set(
key,
typeof value === "object" ? JSON.stringify(value) : (value as string),
);
}
}
}
return mergedHeaders;
};
type ErrInterceptor<Err, Res, Req, Options> = (
error: Err,
response: Res,
request: Req,
options: Options,
) => Err | Promise<Err>;
type ReqInterceptor<Req, Options> = (
request: Req,
options: Options,
) => Req | Promise<Req>;
type ResInterceptor<Res, Req, Options> = (
response: Res,
request: Req,
options: Options,
) => Res | Promise<Res>;
class Interceptors<Interceptor> {
_fns: (Interceptor | null)[];
constructor() {
this._fns = [];
}
clear() {
this._fns = [];
}
getInterceptorIndex(id: number | Interceptor): number {
if (typeof id === "number") {
return this._fns[id] ? id : -1;
} else {
return this._fns.indexOf(id);
}
}
exists(id: number | Interceptor) {
const index = this.getInterceptorIndex(id);
return !!this._fns[index];
}
eject(id: number | Interceptor) {
const index = this.getInterceptorIndex(id);
if (this._fns[index]) {
this._fns[index] = null;
}
}
update(id: number | Interceptor, fn: Interceptor) {
const index = this.getInterceptorIndex(id);
if (this._fns[index]) {
this._fns[index] = fn;
return id;
} else {
return false;
}
}
use(fn: Interceptor) {
this._fns = [...this._fns, fn];
return this._fns.length - 1;
}
}
// `createInterceptors()` response, meant for external use as it does not
// expose internals
export interface Middleware<Req, Res, Err, Options> {
error: Pick<
Interceptors<ErrInterceptor<Err, Res, Req, Options>>,
"eject" | "use"
>;
request: Pick<Interceptors<ReqInterceptor<Req, Options>>, "eject" | "use">;
response: Pick<
Interceptors<ResInterceptor<Res, Req, Options>>,
"eject" | "use"
>;
}
// do not add `Middleware` as return type so we can use _fns internally
export const createInterceptors = <Req, Res, Err, Options>() => ({
error: new Interceptors<ErrInterceptor<Err, Res, Req, Options>>(),
request: new Interceptors<ReqInterceptor<Req, Options>>(),
response: new Interceptors<ResInterceptor<Res, Req, Options>>(),
});
const defaultQuerySerializer = createQuerySerializer({
allowReserved: false,
array: {
explode: true,
style: "form",
},
object: {
explode: true,
style: "deepObject",
},
});
const defaultHeaders = {
"Content-Type": "application/json",
};
export const createConfig = <T extends ClientOptions = ClientOptions>(
override: Config<Omit<ClientOptions, keyof T> & T> = {},
): Config<Omit<ClientOptions, keyof T> & T> => ({
...jsonBodySerializer,
headers: defaultHeaders,
parseAs: "auto",
querySerializer: defaultQuerySerializer,
...override,
});
@@ -0,0 +1,40 @@
export type AuthToken = string | undefined;
export interface Auth {
/**
* Which part of the request do we use to send the auth?
*
* @default 'header'
*/
in?: "header" | "query" | "cookie";
/**
* Header or query parameter name.
*
* @default 'Authorization'
*/
name?: string;
scheme?: "basic" | "bearer";
type: "apiKey" | "http";
}
export const getAuthToken = async (
auth: Auth,
callback: ((auth: Auth) => Promise<AuthToken> | AuthToken) | AuthToken,
): Promise<string | undefined> => {
const token =
typeof callback === "function" ? await callback(auth) : callback;
if (!token) {
return;
}
if (auth.scheme === "bearer") {
return `Bearer ${token}`;
}
if (auth.scheme === "basic") {
return `Basic ${btoa(token)}`;
}
return token;
};
@@ -0,0 +1,88 @@
import type {
ArrayStyle,
ObjectStyle,
SerializerOptions,
} from "./pathSerializer";
export type QuerySerializer = (query: Record<string, unknown>) => string;
export type BodySerializer = (body: any) => any;
export interface QuerySerializerOptions {
allowReserved?: boolean;
array?: SerializerOptions<ArrayStyle>;
object?: SerializerOptions<ObjectStyle>;
}
const serializeFormDataPair = (
data: FormData,
key: string,
value: unknown,
): void => {
if (typeof value === "string" || value instanceof Blob) {
data.append(key, value);
} else {
data.append(key, JSON.stringify(value));
}
};
const serializeUrlSearchParamsPair = (
data: URLSearchParams,
key: string,
value: unknown,
): void => {
if (typeof value === "string") {
data.append(key, value);
} else {
data.append(key, JSON.stringify(value));
}
};
export const formDataBodySerializer = {
bodySerializer: <T extends Record<string, any> | Array<Record<string, any>>>(
body: T,
): FormData => {
const data = new FormData();
Object.entries(body).forEach(([key, value]) => {
if (value === undefined || value === null) {
return;
}
if (Array.isArray(value)) {
value.forEach((v) => serializeFormDataPair(data, key, v));
} else {
serializeFormDataPair(data, key, value);
}
});
return data;
},
};
export const jsonBodySerializer = {
bodySerializer: <T>(body: T): string =>
JSON.stringify(body, (_key, value) =>
typeof value === "bigint" ? value.toString() : value,
),
};
export const urlSearchParamsBodySerializer = {
bodySerializer: <T extends Record<string, any> | Array<Record<string, any>>>(
body: T,
): string => {
const data = new URLSearchParams();
Object.entries(body).forEach(([key, value]) => {
if (value === undefined || value === null) {
return;
}
if (Array.isArray(value)) {
value.forEach((v) => serializeUrlSearchParamsPair(data, key, v));
} else {
serializeUrlSearchParamsPair(data, key, value);
}
});
return data.toString();
},
};
@@ -0,0 +1,141 @@
type Slot = "body" | "headers" | "path" | "query";
export type Field =
| {
in: Exclude<Slot, "body">;
key: string;
map?: string;
}
| {
in: Extract<Slot, "body">;
key?: string;
map?: string;
};
export interface Fields {
allowExtra?: Partial<Record<Slot, boolean>>;
args?: ReadonlyArray<Field>;
}
export type FieldsConfig = ReadonlyArray<Field | Fields>;
const extraPrefixesMap: Record<string, Slot> = {
$body_: "body",
$headers_: "headers",
$path_: "path",
$query_: "query",
};
const extraPrefixes = Object.entries(extraPrefixesMap);
type KeyMap = Map<
string,
{
in: Slot;
map?: string;
}
>;
const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => {
if (!map) {
map = new Map();
}
for (const config of fields) {
if ("in" in config) {
if (config.key) {
map.set(config.key, {
in: config.in,
map: config.map,
});
}
} else if (config.args) {
buildKeyMap(config.args, map);
}
}
return map;
};
interface Params {
body: unknown;
headers: Record<string, unknown>;
path: Record<string, unknown>;
query: Record<string, unknown>;
}
const stripEmptySlots = (params: Params) => {
for (const [slot, value] of Object.entries(params)) {
if (value && typeof value === "object" && !Object.keys(value).length) {
delete params[slot as Slot];
}
}
};
export const buildClientParams = (
args: ReadonlyArray<unknown>,
fields: FieldsConfig,
) => {
const params: Params = {
body: {},
headers: {},
path: {},
query: {},
};
const map = buildKeyMap(fields);
let config: FieldsConfig[number] | undefined;
for (const [index, arg] of args.entries()) {
if (fields[index]) {
config = fields[index];
}
if (!config) {
continue;
}
if ("in" in config) {
if (config.key) {
const field = map.get(config.key)!;
const name = field.map || config.key;
(params[field.in] as Record<string, unknown>)[name] = arg;
} else {
params.body = arg;
}
} else {
for (const [key, value] of Object.entries(arg ?? {})) {
const field = map.get(key);
if (field) {
const name = field.map || key;
(params[field.in] as Record<string, unknown>)[name] = value;
} else {
const extra = extraPrefixes.find(([prefix]) =>
key.startsWith(prefix),
);
if (extra) {
const [prefix, slot] = extra;
(params[slot] as Record<string, unknown>)[
key.slice(prefix.length)
] = value;
} else {
for (const [slot, allowed] of Object.entries(
config.allowExtra ?? {},
)) {
if (allowed) {
(params[slot as Slot] as Record<string, unknown>)[key] = value;
break;
}
}
}
}
}
}
}
stripEmptySlots(params);
return params;
};
@@ -0,0 +1,179 @@
interface SerializeOptions<T>
extends SerializePrimitiveOptions,
SerializerOptions<T> {}
interface SerializePrimitiveOptions {
allowReserved?: boolean;
name: string;
}
export interface SerializerOptions<T> {
/**
* @default true
*/
explode: boolean;
style: T;
}
export type ArrayStyle = "form" | "spaceDelimited" | "pipeDelimited";
export type ArraySeparatorStyle = ArrayStyle | MatrixStyle;
type MatrixStyle = "label" | "matrix" | "simple";
export type ObjectStyle = "form" | "deepObject";
type ObjectSeparatorStyle = ObjectStyle | MatrixStyle;
interface SerializePrimitiveParam extends SerializePrimitiveOptions {
value: string;
}
export const separatorArrayExplode = (style: ArraySeparatorStyle) => {
switch (style) {
case "label":
return ".";
case "matrix":
return ";";
case "simple":
return ",";
default:
return "&";
}
};
export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => {
switch (style) {
case "form":
return ",";
case "pipeDelimited":
return "|";
case "spaceDelimited":
return "%20";
default:
return ",";
}
};
export const separatorObjectExplode = (style: ObjectSeparatorStyle) => {
switch (style) {
case "label":
return ".";
case "matrix":
return ";";
case "simple":
return ",";
default:
return "&";
}
};
export const serializeArrayParam = ({
allowReserved,
explode,
name,
style,
value,
}: SerializeOptions<ArraySeparatorStyle> & {
value: unknown[];
}) => {
if (!explode) {
const joinedValues = (
allowReserved ? value : value.map((v) => encodeURIComponent(v as string))
).join(separatorArrayNoExplode(style));
switch (style) {
case "label":
return `.${joinedValues}`;
case "matrix":
return `;${name}=${joinedValues}`;
case "simple":
return joinedValues;
default:
return `${name}=${joinedValues}`;
}
}
const separator = separatorArrayExplode(style);
const joinedValues = value
.map((v) => {
if (style === "label" || style === "simple") {
return allowReserved ? v : encodeURIComponent(v as string);
}
return serializePrimitiveParam({
allowReserved,
name,
value: v as string,
});
})
.join(separator);
return style === "label" || style === "matrix"
? separator + joinedValues
: joinedValues;
};
export const serializePrimitiveParam = ({
allowReserved,
name,
value,
}: SerializePrimitiveParam) => {
if (value === undefined || value === null) {
return "";
}
if (typeof value === "object") {
throw new Error(
"Deeply-nested arrays/objects arent supported. Provide your own `querySerializer()` to handle these.",
);
}
return `${name}=${allowReserved ? value : encodeURIComponent(value)}`;
};
export const serializeObjectParam = ({
allowReserved,
explode,
name,
style,
value,
valueOnly,
}: SerializeOptions<ObjectSeparatorStyle> & {
value: Record<string, unknown> | Date;
valueOnly?: boolean;
}) => {
if (value instanceof Date) {
return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`;
}
if (style !== "deepObject" && !explode) {
let values: string[] = [];
Object.entries(value).forEach(([key, v]) => {
values = [
...values,
key,
allowReserved ? (v as string) : encodeURIComponent(v as string),
];
});
const joinedValues = values.join(",");
switch (style) {
case "form":
return `${name}=${joinedValues}`;
case "label":
return `.${joinedValues}`;
case "matrix":
return `;${name}=${joinedValues}`;
default:
return joinedValues;
}
}
const separator = separatorObjectExplode(style);
const joinedValues = Object.entries(value)
.map(([key, v]) =>
serializePrimitiveParam({
allowReserved,
name: style === "deepObject" ? `${name}[${key}]` : key,
value: v as string,
}),
)
.join(separator);
return style === "label" || style === "matrix"
? separator + joinedValues
: joinedValues;
};
@@ -0,0 +1,104 @@
import type { Auth, AuthToken } from "./auth";
import type {
BodySerializer,
QuerySerializer,
QuerySerializerOptions,
} from "./bodySerializer";
export interface Client<
RequestFn = never,
Config = unknown,
MethodFn = never,
BuildUrlFn = never,
> {
/**
* Returns the final request URL.
*/
buildUrl: BuildUrlFn;
connect: MethodFn;
delete: MethodFn;
get: MethodFn;
getConfig: () => Config;
head: MethodFn;
options: MethodFn;
patch: MethodFn;
post: MethodFn;
put: MethodFn;
request: RequestFn;
setConfig: (config: Config) => Config;
trace: MethodFn;
}
export interface Config {
/**
* Auth token or a function returning auth token. The resolved value will be
* added to the request payload as defined by its `security` array.
*/
auth?: ((auth: Auth) => Promise<AuthToken> | AuthToken) | AuthToken;
/**
* A function for serializing request body parameter. By default,
* {@link JSON.stringify()} will be used.
*/
bodySerializer?: BodySerializer | null;
/**
* An object containing any HTTP headers that you want to pre-populate your
* `Headers` object with.
*
* {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more}
*/
headers?:
| RequestInit["headers"]
| Record<
string,
| string
| number
| boolean
| (string | number | boolean)[]
| null
| undefined
| unknown
>;
/**
* The request method.
*
* {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more}
*/
method?:
| "CONNECT"
| "DELETE"
| "GET"
| "HEAD"
| "OPTIONS"
| "PATCH"
| "POST"
| "PUT"
| "TRACE";
/**
* A function for serializing request query parameters. By default, arrays
* will be exploded in form style, objects will be exploded in deepObject
* style, and reserved characters are percent-encoded.
*
* This method will have no effect if the native `paramsSerializer()` Axios
* API function is used.
*
* {@link https://swagger.io/docs/specification/serialization/#query View examples}
*/
querySerializer?: QuerySerializer | QuerySerializerOptions;
/**
* A function validating request data. This is useful if you want to ensure
* the request conforms to the desired shape, so it can be safely sent to
* the server.
*/
requestValidator?: (data: unknown) => Promise<unknown>;
/**
* A function transforming response data before it's returned. This is useful
* for post-processing data, e.g. converting ISO strings into Date objects.
*/
responseTransformer?: (data: unknown) => Promise<unknown>;
/**
* A function validating response data. This is useful if you want to ensure
* the response conforms to the desired shape, so it can be safely passed to
* the transformers and returned to the user.
*/
responseValidator?: (data: unknown) => Promise<unknown>;
}
@@ -0,0 +1,3 @@
// This file is auto-generated by @hey-api/openapi-ts
export * from "./types.gen";
export * from "./sdk.gen";
@@ -0,0 +1,395 @@
// This file is auto-generated by @hey-api/openapi-ts
import type { Client, Options as ClientOptions, TDataShape } from "./client";
import { client as _heyApiClient } from "./client.gen";
import type {
BuildInformationData,
BuildInformationResponses,
GatewaysData,
GatewaysResponses,
GatewaysSkinnyData,
GatewaysSkinnyResponses,
GetAllSessionsData,
GetAllSessionsResponses,
GetEntryGatewayCountriesData,
GetEntryGatewayCountriesResponses,
GetEntryGatewaysByCountryData,
GetEntryGatewaysByCountryResponses,
GetEntryGatewaysData,
GetEntryGatewaysResponses,
GetExitGatewayCountriesData,
GetExitGatewayCountriesResponses,
GetExitGatewaysByCountryData,
GetExitGatewaysByCountryResponses,
GetExitGatewaysData,
GetExitGatewaysResponses,
GetGatewayCountriesData,
GetGatewayCountriesResponses,
GetGatewayData,
GetGatewayResponses,
GetGatewaysByCountryData,
GetGatewaysByCountryResponses,
GetGatewaysData,
GetGatewaysResponses,
GetMixnodesData,
GetMixnodesResponses,
GetStatsData,
GetStatsResponses,
HealthData,
HealthResponses,
Mixnodes2Data,
Mixnodes2Responses,
MixnodesData,
MixnodesResponses,
NodeDelegationsData,
NodeDelegationsResponses,
NymNodesData,
NymNodesResponses,
SummaryData,
SummaryHistoryData,
SummaryHistoryResponses,
SummaryResponses,
} from "./types.gen";
export type Options<
TData extends TDataShape = TDataShape,
ThrowOnError extends boolean = boolean,
> = ClientOptions<TData, ThrowOnError> & {
/**
* You can provide a client instance returned by `createClient()` instead of
* individual options. This might be also useful if you want to implement a
* custom client.
*/
client?: Client;
/**
* You can pass arbitrary values through the `meta` object. This can be
* used to access values that aren't defined as part of the SDK function.
*/
meta?: Record<string, unknown>;
};
/**
* Gets available entry and exit gateways from the Nym network directory
*/
export const getGateways = <ThrowOnError extends boolean = false>(
options?: Options<GetGatewaysData, ThrowOnError>,
) => {
return (options?.client ?? _heyApiClient).get<
GetGatewaysResponses,
unknown,
ThrowOnError
>({
url: "/dvpn/v1/directory/gateways",
...options,
});
};
/**
* Gets available exit gateway countries as two-letter ISO country codes from the Nym network directory
*/
export const getGatewayCountries = <ThrowOnError extends boolean = false>(
options?: Options<GetGatewayCountriesData, ThrowOnError>,
) => {
return (options?.client ?? _heyApiClient).get<
GetGatewayCountriesResponses,
unknown,
ThrowOnError
>({
url: "/dvpn/v1/directory/gateways/countries",
...options,
});
};
/**
* Gets available gateways from the Nym network directory by country
*/
export const getGatewaysByCountry = <ThrowOnError extends boolean = false>(
options: Options<GetGatewaysByCountryData, ThrowOnError>,
) => {
return (options.client ?? _heyApiClient).get<
GetGatewaysByCountryResponses,
unknown,
ThrowOnError
>({
url: "/dvpn/v1/directory/gateways/country/{two_letter_country_code}",
...options,
});
};
/**
* Gets available entry gateways from the Nym network directory
*/
export const getEntryGateways = <ThrowOnError extends boolean = false>(
options?: Options<GetEntryGatewaysData, ThrowOnError>,
) => {
return (options?.client ?? _heyApiClient).get<
GetEntryGatewaysResponses,
unknown,
ThrowOnError
>({
url: "/dvpn/v1/directory/gateways/entry",
...options,
});
};
/**
* Gets available entry gateway countries as two-letter ISO country codes from the Nym network directory
*/
export const getEntryGatewayCountries = <ThrowOnError extends boolean = false>(
options?: Options<GetEntryGatewayCountriesData, ThrowOnError>,
) => {
return (options?.client ?? _heyApiClient).get<
GetEntryGatewayCountriesResponses,
unknown,
ThrowOnError
>({
url: "/dvpn/v1/directory/gateways/entry/countries",
...options,
});
};
/**
* Gets available entry gateways from the Nym network directory by country
*/
export const getEntryGatewaysByCountry = <ThrowOnError extends boolean = false>(
options: Options<GetEntryGatewaysByCountryData, ThrowOnError>,
) => {
return (options.client ?? _heyApiClient).get<
GetEntryGatewaysByCountryResponses,
unknown,
ThrowOnError
>({
url: "/dvpn/v1/directory/gateways/entry/country/{two_letter_country_code}",
...options,
});
};
/**
* Gets available exit gateways from the Nym network directory
*/
export const getExitGateways = <ThrowOnError extends boolean = false>(
options?: Options<GetExitGatewaysData, ThrowOnError>,
) => {
return (options?.client ?? _heyApiClient).get<
GetExitGatewaysResponses,
unknown,
ThrowOnError
>({
url: "/dvpn/v1/directory/gateways/exit",
...options,
});
};
/**
* Gets available exit gateway countries as two-letter ISO country codes from the Nym network directory
*/
export const getExitGatewayCountries = <ThrowOnError extends boolean = false>(
options?: Options<GetExitGatewayCountriesData, ThrowOnError>,
) => {
return (options?.client ?? _heyApiClient).get<
GetExitGatewayCountriesResponses,
unknown,
ThrowOnError
>({
url: "/dvpn/v1/directory/gateways/exit/countries",
...options,
});
};
/**
* Gets available exit gateways from the Nym network directory by country
*/
export const getExitGatewaysByCountry = <ThrowOnError extends boolean = false>(
options: Options<GetExitGatewaysByCountryData, ThrowOnError>,
) => {
return (options.client ?? _heyApiClient).get<
GetExitGatewaysByCountryResponses,
unknown,
ThrowOnError
>({
url: "/dvpn/v1/directory/gateways/exit/country/{two_letter_country_code}",
...options,
});
};
export const nymNodes = <ThrowOnError extends boolean = false>(
options?: Options<NymNodesData, ThrowOnError>,
) => {
return (options?.client ?? _heyApiClient).get<
NymNodesResponses,
unknown,
ThrowOnError
>({
url: "/explorer/v3/nym-nodes",
...options,
});
};
export const nodeDelegations = <ThrowOnError extends boolean = false>(
options: Options<NodeDelegationsData, ThrowOnError>,
) => {
return (options.client ?? _heyApiClient).get<
NodeDelegationsResponses,
unknown,
ThrowOnError
>({
url: "/explorer/v3/nym-nodes/{node_id}/delegations",
...options,
});
};
export const gateways = <ThrowOnError extends boolean = false>(
options?: Options<GatewaysData, ThrowOnError>,
) => {
return (options?.client ?? _heyApiClient).get<
GatewaysResponses,
unknown,
ThrowOnError
>({
url: "/v2/gateways",
...options,
});
};
export const gatewaysSkinny = <ThrowOnError extends boolean = false>(
options?: Options<GatewaysSkinnyData, ThrowOnError>,
) => {
return (options?.client ?? _heyApiClient).get<
GatewaysSkinnyResponses,
unknown,
ThrowOnError
>({
url: "/v2/gateways/skinny",
...options,
});
};
export const getGateway = <ThrowOnError extends boolean = false>(
options: Options<GetGatewayData, ThrowOnError>,
) => {
return (options.client ?? _heyApiClient).get<
GetGatewayResponses,
unknown,
ThrowOnError
>({
url: "/v2/gateways/{identity_key}",
...options,
});
};
export const getAllSessions = <ThrowOnError extends boolean = false>(
options?: Options<GetAllSessionsData, ThrowOnError>,
) => {
return (options?.client ?? _heyApiClient).get<
GetAllSessionsResponses,
unknown,
ThrowOnError
>({
url: "/v2/metrics/sessions",
...options,
});
};
export const mixnodes = <ThrowOnError extends boolean = false>(
options?: Options<MixnodesData, ThrowOnError>,
) => {
return (options?.client ?? _heyApiClient).get<
MixnodesResponses,
unknown,
ThrowOnError
>({
url: "/v2/mixnodes",
...options,
});
};
export const getStats = <ThrowOnError extends boolean = false>(
options?: Options<GetStatsData, ThrowOnError>,
) => {
return (options?.client ?? _heyApiClient).get<
GetStatsResponses,
unknown,
ThrowOnError
>({
url: "/v2/mixnodes/stats",
...options,
});
};
export const getMixnodes = <ThrowOnError extends boolean = false>(
options: Options<GetMixnodesData, ThrowOnError>,
) => {
return (options.client ?? _heyApiClient).get<
GetMixnodesResponses,
unknown,
ThrowOnError
>({
url: "/v2/mixnodes/{mix_id}",
...options,
});
};
export const mixnodes2 = <ThrowOnError extends boolean = false>(
options?: Options<Mixnodes2Data, ThrowOnError>,
) => {
return (options?.client ?? _heyApiClient).get<
Mixnodes2Responses,
unknown,
ThrowOnError
>({
url: "/v2/services",
...options,
});
};
export const buildInformation = <ThrowOnError extends boolean = false>(
options?: Options<BuildInformationData, ThrowOnError>,
) => {
return (options?.client ?? _heyApiClient).get<
BuildInformationResponses,
unknown,
ThrowOnError
>({
url: "/v2/status/build_information",
...options,
});
};
export const health = <ThrowOnError extends boolean = false>(
options?: Options<HealthData, ThrowOnError>,
) => {
return (options?.client ?? _heyApiClient).get<
HealthResponses,
unknown,
ThrowOnError
>({
url: "/v2/status/health",
...options,
});
};
export const summary = <ThrowOnError extends boolean = false>(
options?: Options<SummaryData, ThrowOnError>,
) => {
return (options?.client ?? _heyApiClient).get<
SummaryResponses,
unknown,
ThrowOnError
>({
url: "/v2/summary",
...options,
});
};
export const summaryHistory = <ThrowOnError extends boolean = false>(
options?: Options<SummaryHistoryData, ThrowOnError>,
) => {
return (options?.client ?? _heyApiClient).get<
SummaryHistoryResponses,
unknown,
ThrowOnError
>({
url: "/v2/summary/history",
...options,
});
};
@@ -0,0 +1,940 @@
// This file is auto-generated by @hey-api/openapi-ts
export type AnnouncePorts = {
mix_port?: number | null;
verloc_port?: number | null;
};
export type AuthenticatorDetails = {
/**
* address of the embedded authenticator
*/
address: string;
};
/**
* Auxiliary details of the associated Nym Node.
*/
export type AuxiliaryDetails = {
/**
* Specifies whether this node operator has agreed to the terms and conditions
* as defined at <https://nymtech.net/terms-and-conditions/operators/v1.0.0>
*/
accepted_operator_terms_and_conditions?: boolean;
announce_ports?: AnnouncePorts;
/**
* Optional ISO 3166 alpha-2 two-letter country code of the node's **physical** location
*/
location?: string | null;
};
export type BasicEntryInformation = {
hostname?: string | null;
ws_port: number;
wss_port?: number | null;
};
export type BinaryBuildInformationOwned = {
/**
* Provides the name of the binary, i.e. the content of `CARGO_PKG_NAME` environmental variable.
*/
binary_name: string;
/**
* Provides the build timestamp, for example `2021-02-23T20:14:46.558472672+00:00`.
*/
build_timestamp: string;
/**
* Provides the build version, for example `0.1.0-9-g46f83e1`.
*/
build_version: string;
/**
* Provides the cargo debug mode that was used for the build.
*/
cargo_profile: string;
/**
* Provides the cargo target triple that was used for the build.
*/
cargo_triple?: string;
/**
* Provides the name of the git branch that was used for the build, for example `master`.
*/
commit_branch: string;
/**
* Provides the hash of the commit that was used for the build, for example `46f83e112520533338245862d366f6a02cef07d4`.
*/
commit_sha: string;
/**
* Provides the timestamp of the commit that was used for the build, for example `2021-02-23T08:08:02-05:00`.
*/
commit_timestamp: string;
/**
* Provides the rustc channel that was used for the build, for example `nightly`.
*/
rustc_channel: string;
/**
* Provides the rustc version that was used for the build, for example `1.52.0-nightly`.
*/
rustc_version: string;
};
export type BuildInformation = {
build_version: string;
commit_branch: string;
commit_sha: string;
};
/**
* Coin
*/
export type CoinSchema = {
amount: string;
denom: string;
};
export type DVpnGateway = {
authenticator?: null | AuthenticatorDetails;
build_information: BinaryBuildInformationOwned;
entry?: null | BasicEntryInformation;
identity_key: string;
ip_addresses: Array<string>;
ip_packet_router?: null | IpPacketRouterDetails;
last_probe?: null | DirectoryGwProbe;
location: Location;
mix_port: number;
name: string;
performance: string;
role: NodeRole;
};
export type DailyStats = {
date_utc: string;
total_packets_dropped: number;
total_packets_received: number;
total_packets_sent: number;
total_stake: number;
};
export type DeclaredRoles = {
entry: boolean;
exit_ipr: boolean;
exit_nr: boolean;
mixnode: boolean;
};
export type DescribedNodeType =
| "legacy_mixnode"
| "legacy_gateway"
| "nym_node";
export type DirectoryGwProbe = {
last_updated_utc: string;
outcome: ProbeOutcome;
};
export type Entry = EntryTestResult | null;
export type EntryTestResult = {
can_connect: boolean;
can_route: boolean;
};
export type Exit = {
can_connect: boolean;
can_route_ip_external_v4: boolean;
can_route_ip_external_v6: boolean;
can_route_ip_v4: boolean;
can_route_ip_v6: boolean;
};
export type ExtendedNymNode = {
accepted_tnc: boolean;
bonded: boolean;
bonding_address?: string | null;
description: NodeDescription;
geoip?: null | NodeGeoData;
identity_key: string;
ip_address: string;
node_id: U32;
node_type: DescribedNodeType;
original_pledge: number;
rewarding_details?: null | NodeRewarding;
self_description: NymNodeData;
total_stake: string;
uptime: number;
};
export type Gateway = {
bonded: boolean;
config_score: number;
description: NodeDescription;
explorer_pretty_bond?: unknown;
gateway_identity_key: string;
last_probe_log?: string | null;
last_probe_result?: unknown;
last_testrun_utc?: string | null;
last_updated_utc: string;
performance: number;
routing_score: number;
self_described?: unknown;
};
export type GatewaySkinny = {
config_score: number;
explorer_pretty_bond?: unknown;
gateway_identity_key: string;
last_probe_result?: unknown;
last_testrun_utc?: string | null;
last_updated_utc: string;
performance: number;
routing_score: number;
self_described?: unknown;
};
export type GatewaySummary = {
bonded: GatewaySummaryBonded;
historical: GatewaySummaryHistorical;
};
export type GatewaySummaryBonded = {
count: number;
entry: number;
exit: number;
last_updated_utc: string;
};
export type GatewaySummaryHistorical = {
count: number;
last_updated_utc: string;
};
export type HealthInfo = {
uptime: number;
};
export type HostInformation = {
hostname?: string | null;
ip_address: Array<string>;
keys: HostKeys;
};
export type HostKeys = {
ed25519: string;
x25519: string;
x25519_noise?: string;
};
export type IpPacketRouterDetails = {
/**
* address of the embedded ip packet router
*/
address: string;
};
/**
* based on
* https://github.com/nymtech/nym-vpn-client/blob/nym-vpn-core-v1.10.0/nym-vpn-core/crates/nym-gateway-probe/src/types.rs
* TODO: long term types should be moved into this repo because nym-vpn-client
* could pull it as a dependency and we'd have a single source of truth
*/
export type LastProbeResult = {
node: string;
outcome: ProbeOutcome;
used_entry: string;
};
export type Location = {
latitude: number;
longitude: number;
two_letter_iso_country_code: string;
};
export type MixingNodesSummary = {
count: number;
last_updated_utc: string;
legacy: number;
self_described: number;
};
export type Mixnode = {
bonded: boolean;
description: NodeDescription;
full_details?: unknown;
is_dp_delegatee: boolean;
last_updated_utc: string;
mix_id: number;
self_described?: unknown;
total_stake: number;
};
export type MixnodeSummary = {
bonded: MixingNodesSummary;
historical: MixnodeSummaryHistorical;
};
export type MixnodeSummaryHistorical = {
count: number;
last_updated_utc: string;
};
export type NetworkRequesterDetails = {
/**
* address of the embedded network requester
*/
address: string;
/**
* flag indicating whether this network requester uses the exit policy rather than the deprecated allow list
*/
uses_exit_policy: boolean;
};
export type NetworkSummary = {
gateways: GatewaySummary;
mixnodes: MixnodeSummary;
total_nodes: number;
};
/**
* The cost parameters, or the cost function, defined for the particular mixnode that influences
* how the rewards should be split between the node operator and its delegators.
*/
export type NodeCostParams = {
/**
* Operating cost of the associated node per the entire interval.
*/
interval_operating_cost: CoinSchema;
/**
* The profit margin of the associated node, i.e. the desired percent of the reward to be distributed to the operator.
*/
profit_margin_percent: string;
};
export type NodeDelegation = {
amount: CoinSchema;
block_height: number;
cumulative_reward_ratio: string;
owner: string;
proxy?: string | null;
};
export type NodeDescription = {
/**
* details define other optional details.
*/
details: string;
/**
* moniker defines a human-readable name for the node.
*/
moniker: string;
/**
* security contact defines an optional email for security contact.
*/
security_contact: string;
/**
* website defines an optional website link.
*/
website: string;
};
export type NodeGeoData = {
city: string;
country: string;
ip_address: string;
latitude: string;
longitude: string;
org: string;
postal: string;
region: string;
timezone: string;
};
export type NodeRewarding = {
/**
* Information provided by the operator that influence the cost function.
*/
cost_params: NodeCostParams;
/**
* Total delegation and compounded reward earned by all node delegators.
*/
delegates: string;
/**
* Marks the epoch when this node was last rewarded so that we wouldn't accidentally attempt
* to reward it multiple times in the same epoch.
*/
last_rewarded_epoch: U32;
/**
* Total pledge and compounded reward earned by the node operator.
*/
operator: string;
/**
* Cumulative reward earned by the "unit delegation" since the block 0.
*/
total_unit_reward: string;
unique_delegations: number;
/**
* Value of the theoretical "unit delegation" that has delegated to this node at block 0.
*/
unit_delegation: string;
};
export type NodeRole =
| {
Mixnode: {
layer: number;
};
}
| "EntryGateway"
| "ExitGateway"
| "Standby"
| "Inactive";
export type NymNodeData = {
authenticator?: null | AuthenticatorDetails;
auxiliary_details?: AuxiliaryDetails;
build_information: BinaryBuildInformationOwned;
declared_role?: DeclaredRoles;
host_information: HostInformation;
ip_packet_router?: null | IpPacketRouterDetails;
last_polled?: OffsetDateTimeJsonSchemaWrapper;
mixnet_websockets: WebSockets;
network_requester?: null | NetworkRequesterDetails;
wireguard?: null | WireguardDetails;
};
export type OffsetDateTimeJsonSchemaWrapper = string;
export type PagedResultExtendedNymNode = {
items: Array<{
accepted_tnc: boolean;
bonded: boolean;
bonding_address?: string | null;
description: NodeDescription;
geoip?: null | NodeGeoData;
identity_key: string;
ip_address: string;
node_id: U32;
node_type: DescribedNodeType;
original_pledge: number;
rewarding_details?: null | NodeRewarding;
self_description: NymNodeData;
total_stake: string;
uptime: number;
}>;
page: number;
size: number;
total: number;
};
export type PagedResultGateway = {
items: Array<{
bonded: boolean;
config_score: number;
description: NodeDescription;
explorer_pretty_bond?: unknown;
gateway_identity_key: string;
last_probe_log?: string | null;
last_probe_result?: unknown;
last_testrun_utc?: string | null;
last_updated_utc: string;
performance: number;
routing_score: number;
self_described?: unknown;
}>;
page: number;
size: number;
total: number;
};
export type PagedResultGatewaySkinny = {
items: Array<{
config_score: number;
explorer_pretty_bond?: unknown;
gateway_identity_key: string;
last_probe_result?: unknown;
last_testrun_utc?: string | null;
last_updated_utc: string;
performance: number;
routing_score: number;
self_described?: unknown;
}>;
page: number;
size: number;
total: number;
};
export type PagedResultMixnode = {
items: Array<{
bonded: boolean;
description: NodeDescription;
full_details?: unknown;
is_dp_delegatee: boolean;
last_updated_utc: string;
mix_id: number;
self_described?: unknown;
total_stake: number;
}>;
page: number;
size: number;
total: number;
};
export type PagedResultService = {
items: Array<{
gateway_identity_key: string;
hostname?: string | null;
ip_address?: string | null;
last_successful_ping_utc?: string | null;
last_updated_utc: string;
mixnet_websockets?: unknown;
routing_score: number;
service_provider_client_id?: string | null;
}>;
page: number;
size: number;
total: number;
};
export type PagedResultSessionStats = {
items: Array<{
day: string;
gateway_identity_key: string;
mixnet_sessions?: unknown;
node_id: number;
session_started: number;
unique_active_clients: number;
unknown_sessions?: unknown;
users_hashes?: unknown;
vpn_sessions?: unknown;
}>;
page: number;
size: number;
total: number;
};
export type ProbeOutcome = {
as_entry: Entry;
as_exit?: null | Exit;
wg?: null | ProbeOutcomeV1;
};
export type ProbeOutcomeV1 = {
can_handshake_v4: boolean;
can_handshake_v6: boolean;
can_register: boolean;
can_resolve_dns_v4: boolean;
can_resolve_dns_v6: boolean;
download_duration_sec_v4: number;
download_duration_sec_v6: number;
download_error_v4: string;
download_error_v6: string;
downloaded_file_v4: string;
downloaded_file_v6: string;
ping_hosts_performance_v4: number;
ping_hosts_performance_v6: number;
ping_ips_performance_v4: number;
ping_ips_performance_v6: number;
};
export type Service = {
gateway_identity_key: string;
hostname?: string | null;
ip_address?: string | null;
last_successful_ping_utc?: string | null;
last_updated_utc: string;
mixnet_websockets?: unknown;
routing_score: number;
service_provider_client_id?: string | null;
};
export type SessionStats = {
day: string;
gateway_identity_key: string;
mixnet_sessions?: unknown;
node_id: number;
session_started: number;
unique_active_clients: number;
unknown_sessions?: unknown;
users_hashes?: unknown;
vpn_sessions?: unknown;
};
export type SummaryHistory = {
date: string;
timestamp_utc: string;
value_json: unknown;
};
export type TestRun = {
id: number;
identity_key: string;
log: string;
status: string;
};
export type WebSockets = {
ws_port: number;
wss_port?: number | null;
};
export type WireguardDetails = {
port: number;
public_key: string;
};
export type U32 = number;
export type GetGatewaysData = {
body?: never;
path?: never;
query?: {
min_node_version?: string;
};
url: "/dvpn/v1/directory/gateways";
};
export type GetGatewaysResponses = {
200: Array<DVpnGateway>;
};
export type GetGatewaysResponse =
GetGatewaysResponses[keyof GetGatewaysResponses];
export type GetGatewayCountriesData = {
body?: never;
path?: never;
query?: never;
url: "/dvpn/v1/directory/gateways/countries";
};
export type GetGatewayCountriesResponses = {
200: Array<string>;
};
export type GetGatewayCountriesResponse =
GetGatewayCountriesResponses[keyof GetGatewayCountriesResponses];
export type GetGatewaysByCountryData = {
body?: never;
path: {
two_letter_country_code: string;
};
query?: never;
url: "/dvpn/v1/directory/gateways/country/{two_letter_country_code}";
};
export type GetGatewaysByCountryResponses = {
200: Array<DVpnGateway>;
};
export type GetGatewaysByCountryResponse =
GetGatewaysByCountryResponses[keyof GetGatewaysByCountryResponses];
export type GetEntryGatewaysData = {
body?: never;
path?: never;
query?: never;
url: "/dvpn/v1/directory/gateways/entry";
};
export type GetEntryGatewaysResponses = {
200: Array<DVpnGateway>;
};
export type GetEntryGatewaysResponse =
GetEntryGatewaysResponses[keyof GetEntryGatewaysResponses];
export type GetEntryGatewayCountriesData = {
body?: never;
path?: never;
query?: never;
url: "/dvpn/v1/directory/gateways/entry/countries";
};
export type GetEntryGatewayCountriesResponses = {
200: Array<string>;
};
export type GetEntryGatewayCountriesResponse =
GetEntryGatewayCountriesResponses[keyof GetEntryGatewayCountriesResponses];
export type GetEntryGatewaysByCountryData = {
body?: never;
path: {
two_letter_country_code: string;
};
query?: never;
url: "/dvpn/v1/directory/gateways/entry/country/{two_letter_country_code}";
};
export type GetEntryGatewaysByCountryResponses = {
200: Array<DVpnGateway>;
};
export type GetEntryGatewaysByCountryResponse =
GetEntryGatewaysByCountryResponses[keyof GetEntryGatewaysByCountryResponses];
export type GetExitGatewaysData = {
body?: never;
path?: never;
query?: never;
url: "/dvpn/v1/directory/gateways/exit";
};
export type GetExitGatewaysResponses = {
200: Array<DVpnGateway>;
};
export type GetExitGatewaysResponse =
GetExitGatewaysResponses[keyof GetExitGatewaysResponses];
export type GetExitGatewayCountriesData = {
body?: never;
path?: never;
query?: never;
url: "/dvpn/v1/directory/gateways/exit/countries";
};
export type GetExitGatewayCountriesResponses = {
200: Array<string>;
};
export type GetExitGatewayCountriesResponse =
GetExitGatewayCountriesResponses[keyof GetExitGatewayCountriesResponses];
export type GetExitGatewaysByCountryData = {
body?: never;
path: {
two_letter_country_code: string;
};
query?: never;
url: "/dvpn/v1/directory/gateways/exit/country/{two_letter_country_code}";
};
export type GetExitGatewaysByCountryResponses = {
200: Array<DVpnGateway>;
};
export type GetExitGatewaysByCountryResponse =
GetExitGatewaysByCountryResponses[keyof GetExitGatewaysByCountryResponses];
export type NymNodesData = {
body?: never;
path?: never;
query?: {
size?: number;
page?: number;
};
url: "/explorer/v3/nym-nodes";
};
export type NymNodesResponses = {
200: PagedResultExtendedNymNode;
};
export type NymNodesResponse = NymNodesResponses[keyof NymNodesResponses];
export type NodeDelegationsData = {
body?: never;
path: {
node_id: U32;
};
query?: never;
url: "/explorer/v3/nym-nodes/{node_id}/delegations";
};
export type NodeDelegationsResponses = {
200: NodeDelegation;
};
export type NodeDelegationsResponse =
NodeDelegationsResponses[keyof NodeDelegationsResponses];
export type GatewaysData = {
body?: never;
path?: never;
query?: {
size?: number;
page?: number;
};
url: "/v2/gateways";
};
export type GatewaysResponses = {
200: PagedResultGateway;
};
export type GatewaysResponse = GatewaysResponses[keyof GatewaysResponses];
export type GatewaysSkinnyData = {
body?: never;
path?: never;
query?: {
size?: number;
page?: number;
};
url: "/v2/gateways/skinny";
};
export type GatewaysSkinnyResponses = {
200: PagedResultGatewaySkinny;
};
export type GatewaysSkinnyResponse =
GatewaysSkinnyResponses[keyof GatewaysSkinnyResponses];
export type GetGatewayData = {
body?: never;
path: {
identity_key: string;
};
query?: never;
url: "/v2/gateways/{identity_key}";
};
export type GetGatewayResponses = {
200: Gateway;
};
export type GetGatewayResponse = GetGatewayResponses[keyof GetGatewayResponses];
export type GetAllSessionsData = {
body?: never;
path?: never;
query?: {
size?: number;
page?: number;
node_id?: string;
day?: string;
};
url: "/v2/metrics/sessions";
};
export type GetAllSessionsResponses = {
200: PagedResultSessionStats;
};
export type GetAllSessionsResponse =
GetAllSessionsResponses[keyof GetAllSessionsResponses];
export type MixnodesData = {
body?: never;
path?: never;
query?: {
size?: number;
page?: number;
};
url: "/v2/mixnodes";
};
export type MixnodesResponses = {
200: PagedResultMixnode;
};
export type MixnodesResponse = MixnodesResponses[keyof MixnodesResponses];
export type GetStatsData = {
body?: never;
path?: never;
query?: {
offset?: number;
};
url: "/v2/mixnodes/stats";
};
export type GetStatsResponses = {
200: Array<DailyStats>;
};
export type GetStatsResponse = GetStatsResponses[keyof GetStatsResponses];
export type GetMixnodesData = {
body?: never;
path: {
mix_id: string;
};
query?: never;
url: "/v2/mixnodes/{mix_id}";
};
export type GetMixnodesResponses = {
200: Mixnode;
};
export type GetMixnodesResponse =
GetMixnodesResponses[keyof GetMixnodesResponses];
export type Mixnodes2Data = {
body?: never;
path?: never;
query?: {
size?: number;
page?: number;
wss?: boolean;
hostname?: boolean;
entry?: boolean;
};
url: "/v2/services";
};
export type Mixnodes2Responses = {
200: PagedResultService;
};
export type Mixnodes2Response = Mixnodes2Responses[keyof Mixnodes2Responses];
export type BuildInformationData = {
body?: never;
path?: never;
query?: never;
url: "/v2/status/build_information";
};
export type BuildInformationResponses = {
200: BinaryBuildInformationOwned;
};
export type BuildInformationResponse =
BuildInformationResponses[keyof BuildInformationResponses];
export type HealthData = {
body?: never;
path?: never;
query?: never;
url: "/v2/status/health";
};
export type HealthResponses = {
200: HealthInfo;
};
export type HealthResponse = HealthResponses[keyof HealthResponses];
export type SummaryData = {
body?: never;
path?: never;
query?: never;
url: "/v2/summary";
};
export type SummaryResponses = {
200: NetworkSummary;
};
export type SummaryResponse = SummaryResponses[keyof SummaryResponses];
export type SummaryHistoryData = {
body?: never;
path?: never;
query?: never;
url: "/v2/summary/history";
};
export type SummaryHistoryResponses = {
200: Array<SummaryHistory>;
};
export type SummaryHistoryResponse =
SummaryHistoryResponses[keyof SummaryHistoryResponses];
export type ClientOptions = {
baseUrl: "https://mainnet-node-status-api.nymtech.cc" | (string & {});
};
@@ -0,0 +1,25 @@
"use client";
import AutoAwesomeRoundedIcon from "@mui/icons-material/AutoAwesomeRounded";
import Button from "@mui/material/Button";
import Card from "@mui/material/Card";
import CardContent from "@mui/material/CardContent";
import Typography from "@mui/material/Typography";
export default function CardAlert() {
return (
<Card variant="outlined" sx={{ m: 1.5, flexShrink: 0 }}>
<CardContent>
<AutoAwesomeRoundedIcon fontSize="small" />
<Typography gutterBottom sx={{ fontWeight: 600 }}>
Plan about to expire
</Typography>
<Typography variant="body2" sx={{ mb: 2, color: "text.secondary" }}>
Enjoy 10% off when renewing your plan today.
</Typography>
<Button variant="contained" size="small" fullWidth>
Get the discount
</Button>
</CardContent>
</Card>
);
}
@@ -0,0 +1,24 @@
import Link from "@mui/material/Link";
import Typography from "@mui/material/Typography";
export default function Copyright(props: any) {
return (
<Typography
variant="body2"
align="center"
{...props}
sx={[
{
color: "text.secondary",
},
...(Array.isArray(props.sx) ? props.sx : [props.sx]),
]}
>
{"Copyright © "}
<Link color="inherit" href="https://nym.com/">
Nym Technologies SA
</Link>{" "}
{new Date().getFullYear()}
</Typography>
);
}
@@ -0,0 +1,23 @@
"use client";
import Card from "@mui/material/Card";
import CardContent from "@mui/material/CardContent";
import Typography from "@mui/material/Typography";
export type GraphProps = {
title: string;
children?: React.ReactNode;
};
export default function GraphCard({ title, children }: GraphProps) {
return (
<Card variant="outlined" sx={{ height: "100%", flexGrow: 1 }}>
<CardContent>
<Typography component="h2" variant="subtitle2" gutterBottom>
{title}
</Typography>
{children}
</CardContent>
</Card>
);
}
@@ -0,0 +1,42 @@
"use client";
import ChevronRightRoundedIcon from "@mui/icons-material/ChevronRightRounded";
import InsightsRoundedIcon from "@mui/icons-material/InsightsRounded";
import Button from "@mui/material/Button";
import Card from "@mui/material/Card";
import CardContent from "@mui/material/CardContent";
import Typography from "@mui/material/Typography";
import { useTheme } from "@mui/material/styles";
import useMediaQuery from "@mui/material/useMediaQuery";
export default function HighlightedCard() {
const theme = useTheme();
const isSmallScreen = useMediaQuery(theme.breakpoints.down("sm"));
return (
<Card sx={{ height: "100%" }}>
<CardContent>
<InsightsRoundedIcon />
<Typography
component="h2"
variant="subtitle2"
gutterBottom
sx={{ fontWeight: "600" }}
>
Explore your data
</Typography>
<Typography sx={{ color: "text.secondary", mb: "8px" }}>
Uncover performance and visitor insights with our data wizardry.
</Typography>
<Button
variant="contained"
size="small"
color="primary"
endIcon={<ChevronRightRoundedIcon />}
fullWidth={isSmallScreen}
>
Get insights
</Button>
</CardContent>
</Card>
);
}
@@ -0,0 +1,36 @@
import SignalCellularAltIcon from "@mui/icons-material/SignalCellularAlt";
import SignalCellularAlt1Bar from "@mui/icons-material/SignalCellularAlt1Bar";
import SignalCellularAlt2Bar from "@mui/icons-material/SignalCellularAlt2Bar";
import SignalCellularConnectedNoInternet0BarIcon from "@mui/icons-material/SignalCellularConnectedNoInternet0Bar";
export const ScoreIcon = ({ score }: { score?: string }) => {
if (!score) {
return <SignalCellularAltIcon color="error" />;
}
if (score.toLowerCase() === "offline") {
return <SignalCellularConnectedNoInternet0BarIcon color="disabled" />;
}
if (score.toLowerCase() === "high") {
return <SignalCellularAltIcon color="success" />;
}
if (score.toLowerCase() === "medium") {
return <SignalCellularAlt2Bar color="warning" />;
}
return <SignalCellularAlt1Bar color="disabled" />;
};
export const ReverseScoreIcon = ({ score }: { score?: string }) => {
if (!score) {
return <SignalCellularConnectedNoInternet0BarIcon color="disabled" />;
}
if (score.toLowerCase() === "offline") {
return <SignalCellularConnectedNoInternet0BarIcon color="disabled" />;
}
if (score.toLowerCase() === "low") {
return <SignalCellularAlt1Bar color="success" />;
}
if (score.toLowerCase() === "medium") {
return <SignalCellularAlt2Bar color="warning" />;
}
return <SignalCellularAltIcon color="error" />;
};
@@ -0,0 +1,130 @@
"use client";
import Box from "@mui/material/Box";
import Card from "@mui/material/Card";
import CardContent from "@mui/material/CardContent";
import Chip from "@mui/material/Chip";
import Stack from "@mui/material/Stack";
import Typography from "@mui/material/Typography";
import { useTheme } from "@mui/material/styles";
import { areaElementClasses } from "@mui/x-charts/LineChart";
import { SparkLineChart } from "@mui/x-charts/SparkLineChart";
export type StatCardProps = {
title: string;
value: string;
interval: string;
trend: "up" | "down" | "neutral";
data: number[];
};
function getDaysInMonth(month: number, year: number) {
const date = new Date(year, month, 0);
const monthName = date.toLocaleDateString("en-US", {
month: "short",
});
const daysInMonth = date.getDate();
const days = [];
let i = 1;
while (days.length < daysInMonth) {
days.push(`${monthName} ${i}`);
i += 1;
}
return days;
}
function AreaGradient({ color, id }: { color: string; id: string }) {
return (
<defs>
<linearGradient id={id} x1="50%" y1="0%" x2="50%" y2="100%">
<stop offset="0%" stopColor={color} stopOpacity={0.3} />
<stop offset="100%" stopColor={color} stopOpacity={0} />
</linearGradient>
</defs>
);
}
export default function StatCard({
title,
value,
interval,
trend,
data,
}: StatCardProps) {
const theme = useTheme();
const daysInWeek = getDaysInMonth(4, 2024);
const trendColors = {
up:
theme.palette.mode === "light"
? theme.palette.success.main
: theme.palette.success.dark,
down:
theme.palette.mode === "light"
? theme.palette.error.main
: theme.palette.error.dark,
neutral:
theme.palette.mode === "light"
? theme.palette.grey[400]
: theme.palette.grey[700],
};
const labelColors = {
up: "success" as const,
down: "error" as const,
neutral: "default" as const,
};
const color = labelColors[trend];
const chartColor = trendColors[trend];
const trendValues = { up: "+25%", down: "-25%", neutral: "+5%" };
return (
<Card variant="outlined" sx={{ height: "100%", flexGrow: 1 }}>
<CardContent>
<Typography component="h2" variant="subtitle2" gutterBottom>
{title}
</Typography>
<Stack
direction="column"
sx={{ justifyContent: "space-between", flexGrow: "1", gap: 1 }}
>
<Stack sx={{ justifyContent: "space-between" }}>
<Stack
direction="row"
sx={{ justifyContent: "space-between", alignItems: "center" }}
>
<Typography variant="h4" component="p">
{value}
</Typography>
<Chip size="small" color={color} label={trendValues[trend]} />
</Stack>
<Typography variant="caption" sx={{ color: "text.secondary" }}>
{interval}
</Typography>
</Stack>
<Box sx={{ width: "100%", height: 50 }}>
<SparkLineChart
color={chartColor}
data={data}
area
showHighlight
showTooltip
xAxis={{
scaleType: "band",
data: daysInWeek, // Use the correct property 'data' for xAxis
}}
sx={{
[`& .${areaElementClasses.root}`]: {
fill: `url(#area-gradient-${value})`,
},
}}
>
<AreaGradient color={chartColor} id={`area-gradient-${value}`} />
</SparkLineChart>
</Box>
</Stack>
</CardContent>
</Card>
);
}
@@ -0,0 +1,58 @@
import { useDVpnGatewaysTransformed } from "@/hooks/useGatewaysTransformed";
import Box from "@mui/material/Box";
import { BarChart } from "@mui/x-charts/BarChart";
import { rollup } from "d3-array";
import React from "react";
export const GatewayCanQueryMetadataTopup = () => {
const {
query: { isSuccess, isError, data },
} = useDVpnGatewaysTransformed();
const binnedData = React.useMemo(() => {
if (!isSuccess || data === undefined) {
return undefined;
}
const results = data.map((g) => {
const r = (g.last_probe?.outcome.wg as any)?.can_query_metadata_v4;
if (r === undefined) {
return "-";
}
if (r === true) {
return "yes";
}
return "no";
});
// count occurrences of each result
const resultCounts = rollup(
results,
(v) => v.length,
(v) => v, // group by result string
);
const chartData = Array.from(resultCounts, ([result, count]) => ({
result,
count,
}));
const labels = chartData.map((d) => d.result);
const values = chartData.map((d) => d.count);
return { labels, values };
}, [data, isSuccess]);
if (isError || !binnedData) {
return null;
}
const { labels, values } = binnedData;
return (
<Box>
<BarChart
xAxis={[{ scaleType: "band", data: labels }]}
series={[{ data: values }]}
height={225}
/>
</Box>
);
};
@@ -0,0 +1,43 @@
import { useDVpnGatewaysTransformed } from "@/hooks/useGatewaysTransformed";
import Box from "@mui/material/Box";
import { BarChart } from "@mui/x-charts/BarChart";
import { bin } from "d3-array";
import React from "react";
export const GatewayDownloadSpeeds = () => {
const {
query: { isSuccess, isError, data },
} = useDVpnGatewaysTransformed();
const binnedData = React.useMemo(() => {
if (!isSuccess || data === undefined) {
return undefined;
}
const binner = bin().thresholds(10); // Number of bins
const bins = binner(
data
.map((g) => g.extra.downloadSpeedMBPerSec)
.filter((g) => Boolean(g)) as number[],
);
const labels = bins.map((b) => `${b.x0}-${b.x1} MB/sec`);
const values = bins.map((b) => b.length); // count per bin
return { labels, values };
}, [data, isSuccess]);
if (isError || !binnedData) {
return null;
}
const { labels, values } = binnedData;
return (
<Box>
<BarChart
xAxis={[{ scaleType: "band", data: labels }]}
series={[{ data: values }]}
height={225}
/>
</Box>
);
};
@@ -0,0 +1,45 @@
import { useDVpnGatewaysTransformed } from "@/hooks/useGatewaysTransformed";
import Box from "@mui/material/Box";
import { BarChart } from "@mui/x-charts/BarChart";
import React from "react";
export const GatewayLoads = () => {
const {
query: { isSuccess, isError, data },
} = useDVpnGatewaysTransformed();
const binnedData = React.useMemo(() => {
if (!isSuccess || data === undefined) {
return undefined;
}
const binned = data.reduce(
(acc, g) => {
const score: "low" | "medium" | "high" | "offline" =
(g as any).performance_v2?.load || "offline";
acc[score] += 1;
return acc;
},
{ offline: 0, low: 0, medium: 0, high: 0 },
);
const labels = ["offline", "low", "medium", "high"];
const values = Object.values(binned);
return { labels, values };
}, [data, isSuccess]);
if (isError || !binnedData) {
return null;
}
const { labels, values } = binnedData;
return (
<Box>
<BarChart
xAxis={[{ scaleType: "band", data: labels }]}
series={[{ data: values }]}
height={225}
/>
</Box>
);
};
@@ -0,0 +1,43 @@
import { useDVpnGatewaysTransformed } from "@/hooks/useGatewaysTransformed";
import Box from "@mui/material/Box";
import { BarChart } from "@mui/x-charts/BarChart";
import { bin } from "d3-array";
import React from "react";
export const GatewayPingPercentage = () => {
const {
query: { isSuccess, isError, data },
} = useDVpnGatewaysTransformed();
const binnedData = React.useMemo(() => {
if (!isSuccess || data === undefined) {
return undefined;
}
const binner = bin().domain([0, 1]).thresholds(10); // Number of bins
const bins = binner(
data.map((g) => g.last_probe?.outcome.wg?.ping_ips_performance_v4 || 0),
);
const labels = bins.map(
(b) => `${(b.x0 || 0) * 100}-${(b.x1 || 0) * 100}%`,
);
const values = bins.map((b) => b.length); // count per bin
return { labels, values };
}, [data, isSuccess]);
if (isError || !binnedData) {
return null;
}
const { labels, values } = binnedData;
return (
<Box>
<BarChart
xAxis={[{ scaleType: "band", data: labels }]}
series={[{ data: values }]}
height={225}
/>
</Box>
);
};
@@ -0,0 +1,45 @@
import { useDVpnGatewaysTransformed } from "@/hooks/useGatewaysTransformed";
import Box from "@mui/material/Box";
import { BarChart } from "@mui/x-charts/BarChart";
import React from "react";
export const GatewayScores = () => {
const {
query: { isSuccess, isError, data },
} = useDVpnGatewaysTransformed();
const binnedData = React.useMemo(() => {
if (!isSuccess || data === undefined) {
return undefined;
}
const binned = data.reduce(
(acc, g) => {
const score: "low" | "medium" | "high" | "offline" =
(g as any).performance_v2?.score || "offline";
acc[score] += 1;
return acc;
},
{ offline: 0, low: 0, medium: 0, high: 0 },
);
const labels = ["offline", "low", "medium", "high"];
const values = Object.values(binned);
return { labels, values };
}, [data, isSuccess]);
if (isError || !binnedData) {
return null;
}
const { labels, values } = binnedData;
return (
<Box>
<BarChart
xAxis={[{ scaleType: "band", data: labels }]}
series={[{ data: values }]}
height={225}
/>
</Box>
);
};
@@ -0,0 +1,41 @@
import { useDVpnGatewaysTransformed } from "@/hooks/useGatewaysTransformed";
import Box from "@mui/material/Box";
import { BarChart } from "@mui/x-charts/BarChart";
import { bin } from "d3-array";
import React from "react";
export const GatewayUptimePercentage = () => {
const {
query: { isSuccess, isError, data },
} = useDVpnGatewaysTransformed();
const binnedData = React.useMemo(() => {
if (!isSuccess || data === undefined) {
return undefined;
}
const binner = bin().domain([0, 1]).thresholds(20); // Number of bins
const bins = binner(data.map((g) => Number.parseFloat(g.performance)));
const labels = bins.map(
(b) => `${(b.x0 || 0) * 100}-${(b.x1 || 0) * 100}%`,
);
const values = bins.map((b) => b.length); // count per bin
return { labels, values };
}, [data, isSuccess]);
if (isError || !binnedData) {
return null;
}
const { labels, values } = binnedData;
return (
<Box>
<BarChart
xAxis={[{ scaleType: "band", data: labels }]}
series={[{ data: values }]}
height={225}
/>
</Box>
);
};
@@ -0,0 +1,49 @@
import { useDVpnGatewaysTransformed } from "@/hooks/useGatewaysTransformed";
import Box from "@mui/material/Box";
import { BarChart } from "@mui/x-charts/BarChart";
import { rollup } from "d3-array";
import React from "react";
export const GatewayVersions = () => {
const {
query: { isSuccess, isError, data },
} = useDVpnGatewaysTransformed();
const binnedData = React.useMemo(() => {
if (!isSuccess || data === undefined) {
return undefined;
}
const versions = data.map((g) => g.build_information.build_version);
// count occurrences of each version
const versionCounts = rollup(
versions,
(v) => v.length,
(v) => v, // group by version string
);
const chartData = Array.from(versionCounts, ([version, count]) => ({
version,
count,
}));
const labels = chartData.map((d) => d.version);
const values = chartData.map((d) => d.count);
return { labels, values };
}, [data, isSuccess]);
if (isError || !binnedData) {
return null;
}
const { labels, values } = binnedData;
return (
<Box>
<BarChart
xAxis={[{ scaleType: "band", data: labels }]}
series={[{ data: values }]}
height={225}
/>
</Box>
);
};
@@ -0,0 +1,77 @@
"use client";
import ColorModeIconDropdown from "@/theme/ColorModeIconDropdown";
import MenuRoundedIcon from "@mui/icons-material/MenuRounded";
import AppBar from "@mui/material/AppBar";
import Stack from "@mui/material/Stack";
import { tabsClasses } from "@mui/material/Tabs";
import MuiToolbar from "@mui/material/Toolbar";
import { styled } from "@mui/material/styles";
import * as React from "react";
import MenuButton from "./MenuButton";
import SideMenuMobile from "./SideMenuMobile";
import { SiteLogo } from "./SiteLogo";
const Toolbar = styled(MuiToolbar)({
width: "100%",
padding: "12px",
display: "flex",
flexDirection: "column",
alignItems: "start",
justifyContent: "center",
gap: "12px",
flexShrink: 0,
[`& ${tabsClasses.flexContainer}`]: {
gap: "8px",
p: "8px",
pb: 0,
},
});
export default function AppNavbar() {
const [open, setOpen] = React.useState(false);
const toggleDrawer = (newOpen: boolean) => () => {
setOpen(newOpen);
};
return (
<AppBar
position="fixed"
sx={{
display: { xs: "auto", md: "none" },
boxShadow: 0,
bgcolor: "background.paper",
backgroundImage: "none",
borderBottom: "1px solid",
borderColor: "divider",
top: "var(--template-frame-height, 0px)",
}}
>
<Toolbar variant="regular">
<Stack
direction="row"
sx={{
alignItems: "center",
flexGrow: 1,
width: "100%",
gap: 1,
}}
>
<Stack
direction="row"
spacing={1}
sx={{ justifyContent: "center", mr: "auto" }}
>
<SiteLogo />
</Stack>
<ColorModeIconDropdown />
<MenuButton aria-label="menu" onClick={toggleDrawer(true)}>
<MenuRoundedIcon />
</MenuButton>
<SideMenuMobile open={open} toggleDrawer={toggleDrawer} />
</Stack>
</Toolbar>
</AppBar>
);
}
@@ -0,0 +1,91 @@
"use client";
import DarkModeIcon from "@mui/icons-material/DarkModeRounded";
import LightModeIcon from "@mui/icons-material/LightModeRounded";
import Box from "@mui/material/Box";
import IconButton, { type IconButtonOwnProps } from "@mui/material/IconButton";
import Menu from "@mui/material/Menu";
import MenuItem from "@mui/material/MenuItem";
import { useColorScheme } from "@mui/material/styles";
import * as React from "react";
export default function ColorModeIconDropdown(props: IconButtonOwnProps) {
const { mode, systemMode, setMode } = useColorScheme();
const [anchorEl, setAnchorEl] = React.useState<null | HTMLElement>(null);
const open = Boolean(anchorEl);
const handleClick = (event: React.MouseEvent<HTMLElement>) => {
setAnchorEl(event.currentTarget);
};
const handleClose = () => {
setAnchorEl(null);
};
const handleMode = (targetMode: "system" | "light" | "dark") => () => {
setMode(targetMode);
handleClose();
};
if (!mode) {
return (
<Box
data-screenshot="toggle-mode"
sx={(theme) => ({
verticalAlign: "bottom",
display: "inline-flex",
width: "2.25rem",
height: "2.25rem",
borderRadius: theme.shape.borderRadius,
border: "1px solid",
borderColor: theme.palette.divider,
})}
/>
);
}
const resolvedMode = (systemMode || mode) as "light" | "dark";
const icon = {
light: <LightModeIcon />,
dark: <DarkModeIcon />,
}[resolvedMode];
return (
<React.Fragment>
<IconButton
data-screenshot="toggle-mode"
onClick={handleClick}
disableRipple
size="small"
aria-controls={open ? "color-scheme-menu" : undefined}
aria-haspopup="true"
aria-expanded={open ? "true" : undefined}
{...props}
>
{icon}
</IconButton>
<Menu
anchorEl={anchorEl}
id="account-menu"
open={open}
onClose={handleClose}
onClick={handleClose}
slotProps={{
paper: {
variant: "outlined",
elevation: 0,
sx: {
my: "4px",
},
},
}}
transformOrigin={{ horizontal: "right", vertical: "top" }}
anchorOrigin={{ horizontal: "right", vertical: "bottom" }}
>
<MenuItem selected={mode === "system"} onClick={handleMode("system")}>
System
</MenuItem>
<MenuItem selected={mode === "light"} onClick={handleMode("light")}>
Light
</MenuItem>
<MenuItem selected={mode === "dark"} onClick={handleMode("dark")}>
Dark
</MenuItem>
</Menu>
</React.Fragment>
);
}
@@ -0,0 +1,29 @@
"use client";
import MenuItem from "@mui/material/MenuItem";
import Select, { type SelectProps } from "@mui/material/Select";
import { useColorScheme } from "@mui/material/styles";
export default function ColorModeSelect(props: SelectProps) {
const { mode, setMode } = useColorScheme();
if (!mode) {
return null;
}
return (
<Select
value={mode}
onChange={(event) =>
setMode(event.target.value as "system" | "light" | "dark")
}
SelectDisplayProps={{
// @ts-ignore
"data-screenshot": "toggle-mode",
}}
{...props}
>
<MenuItem value="system">System</MenuItem>
<MenuItem value="light">Light</MenuItem>
<MenuItem value="dark">Dark</MenuItem>
</Select>
);
}
@@ -0,0 +1,33 @@
"use client";
import ColorModeIconDropdown from "@/theme/ColorModeIconDropdown";
import Stack from "@mui/material/Stack";
import NavbarBreadcrumbs from "./NavbarBreadcrumbs";
import type React from "react";
import Search from "./Search";
const showSearch = false;
export default function Header({ title }: { title?: React.ReactNode }) {
return (
<Stack
direction="row"
sx={{
display: { xs: "none", md: "flex" },
width: "100%",
alignItems: { xs: "flex-start", md: "center" },
justifyContent: "space-between",
maxWidth: { sm: "100%", md: "1700px" },
pt: 1.5,
}}
spacing={2}
>
<NavbarBreadcrumbs title={title} />
<Stack direction="row" sx={{ gap: 1 }}>
{showSearch && <Search />}
<ColorModeIconDropdown />
</Stack>
</Stack>
);
}
@@ -0,0 +1,23 @@
"use client";
import Badge, { badgeClasses } from "@mui/material/Badge";
import IconButton, { type IconButtonProps } from "@mui/material/IconButton";
export interface MenuButtonProps extends IconButtonProps {
showBadge?: boolean;
}
export default function MenuButton({
showBadge = false,
...props
}: MenuButtonProps) {
return (
<Badge
color="error"
variant="dot"
invisible={!showBadge}
sx={{ [`& .${badgeClasses.badge}`]: { right: 2, top: 2 } }}
>
<IconButton size="small" {...props} />
</Badge>
);
}
@@ -0,0 +1,60 @@
"use client";
import List from "@mui/material/List";
import ListItem from "@mui/material/ListItem";
import ListItemButton from "@mui/material/ListItemButton";
import ListItemIcon from "@mui/material/ListItemIcon";
import ListItemText from "@mui/material/ListItemText";
import Stack from "@mui/material/Stack";
import NextLink from "next/link";
import { usePathname } from "next/navigation";
import DoorSlidingOutlinedIcon from "@mui/icons-material/DoorSlidingOutlined";
import HubIcon from "@mui/icons-material/Hub";
import SettingsInputAntennaIcon from "@mui/icons-material/SettingsInputAntenna";
import ViewModuleIcon from "@mui/icons-material/ViewModule";
import WorkspacePremiumIcon from "@mui/icons-material/WorkspacePremium";
const mainListItemsAll = [
{ text: "Network Nodes", icon: <HubIcon />, url: "/nodes" },
{ text: "dVPN Gateways", icon: <DoorSlidingOutlinedIcon />, url: "/dvpn" },
{ text: "SOCKS5 NRs", icon: <SettingsInputAntennaIcon />, url: "/socks5" },
{
text: "zk-nym Signers",
icon: <WorkspacePremiumIcon />,
url: "/zk-nym-signers",
},
{
text: "Nyx Chain Validators",
icon: <ViewModuleIcon />,
url: "/validators",
},
];
const mainListItems = [mainListItemsAll[0], mainListItemsAll[1]];
export default function MenuContent() {
const path = usePathname();
return (
<Stack sx={{ flexGrow: 1, p: 1, justifyContent: "space-between" }}>
<List dense>
{mainListItems.map((item, index) => (
<ListItem
key={`${index}-${item.url}`}
disablePadding
sx={{ display: "block" }}
>
<ListItemButton
selected={path === item.url}
component={NextLink}
href={item.url}
>
<ListItemIcon>{item.icon}</ListItemIcon>
<ListItemText primary={item.text} />
</ListItemButton>
</ListItem>
))}
</List>
</Stack>
);
}
@@ -0,0 +1,37 @@
"use client";
import NavigateNextRoundedIcon from "@mui/icons-material/NavigateNextRounded";
import Breadcrumbs, { breadcrumbsClasses } from "@mui/material/Breadcrumbs";
import Typography from "@mui/material/Typography";
import { styled } from "@mui/material/styles";
import type React from "react";
const StyledBreadcrumbs = styled(Breadcrumbs)(({ theme }) => ({
margin: theme.spacing(1, 0),
[`& .${breadcrumbsClasses.separator}`]: {
color: theme.palette.action.disabled,
margin: 1,
},
[`& .${breadcrumbsClasses.ol}`]: {
alignItems: "center",
},
}));
export default function NavbarBreadcrumbs({
title,
}: { title?: React.ReactNode }) {
return (
<StyledBreadcrumbs
aria-label="breadcrumb"
separator={<NavigateNextRoundedIcon fontSize="small" />}
>
<Typography variant="body1">Dashboard</Typography>
<Typography
variant="body1"
sx={{ color: "text.primary", fontWeight: 600 }}
>
{title || "Home"}
</Typography>
</StyledBreadcrumbs>
);
}
@@ -0,0 +1,81 @@
"use client";
import LogoutRoundedIcon from "@mui/icons-material/LogoutRounded";
import MoreVertRoundedIcon from "@mui/icons-material/MoreVertRounded";
import Divider, { dividerClasses } from "@mui/material/Divider";
import { listClasses } from "@mui/material/List";
import ListItemIcon, { listItemIconClasses } from "@mui/material/ListItemIcon";
import ListItemText from "@mui/material/ListItemText";
import Menu from "@mui/material/Menu";
import MuiMenuItem from "@mui/material/MenuItem";
import { paperClasses } from "@mui/material/Paper";
import { styled } from "@mui/material/styles";
import * as React from "react";
import MenuButton from "./MenuButton";
const MenuItem = styled(MuiMenuItem)({
margin: "2px 0",
});
export default function OptionsMenu() {
const [anchorEl, setAnchorEl] = React.useState<null | HTMLElement>(null);
const open = Boolean(anchorEl);
const handleClick = (event: React.MouseEvent<HTMLElement>) => {
setAnchorEl(event.currentTarget);
};
const handleClose = () => {
setAnchorEl(null);
};
return (
<React.Fragment>
<MenuButton
aria-label="Open menu"
onClick={handleClick}
sx={{ borderColor: "transparent" }}
>
<MoreVertRoundedIcon />
</MenuButton>
<Menu
anchorEl={anchorEl}
id="menu"
open={open}
onClose={handleClose}
onClick={handleClose}
transformOrigin={{ horizontal: "right", vertical: "top" }}
anchorOrigin={{ horizontal: "right", vertical: "bottom" }}
sx={{
[`& .${listClasses.root}`]: {
padding: "4px",
},
[`& .${paperClasses.root}`]: {
padding: 0,
},
[`& .${dividerClasses.root}`]: {
margin: "4px -4px",
},
}}
>
<MenuItem onClick={handleClose}>Profile</MenuItem>
<MenuItem onClick={handleClose}>My account</MenuItem>
<Divider />
<MenuItem onClick={handleClose}>Add another account</MenuItem>
<MenuItem onClick={handleClose}>Settings</MenuItem>
<Divider />
<MenuItem
onClick={handleClose}
sx={{
[`& .${listItemIconClasses.root}`]: {
ml: "auto",
minWidth: 0,
},
}}
>
<ListItemText>Logout</ListItemText>
<ListItemIcon>
<LogoutRoundedIcon fontSize="small" />
</ListItemIcon>
</MenuItem>
</Menu>
</React.Fragment>
);
}
@@ -0,0 +1,27 @@
"use client";
import SearchRoundedIcon from "@mui/icons-material/SearchRounded";
import FormControl from "@mui/material/FormControl";
import InputAdornment from "@mui/material/InputAdornment";
import OutlinedInput from "@mui/material/OutlinedInput";
export default function Search() {
return (
<FormControl sx={{ width: { xs: "100%", md: "25ch" } }} variant="outlined">
<OutlinedInput
size="small"
id="search"
placeholder="Search…"
sx={{ flexGrow: 1 }}
startAdornment={
<InputAdornment position="start" sx={{ color: "text.primary" }}>
<SearchRoundedIcon fontSize="small" />
</InputAdornment>
}
inputProps={{
"aria-label": "search",
}}
/>
</FormControl>
);
}
@@ -0,0 +1,107 @@
"use client";
import AddRoundedIcon from "@mui/icons-material/AddRounded";
import ConstructionRoundedIcon from "@mui/icons-material/ConstructionRounded";
import DevicesRoundedIcon from "@mui/icons-material/DevicesRounded";
import SmartphoneRoundedIcon from "@mui/icons-material/SmartphoneRounded";
import MuiAvatar from "@mui/material/Avatar";
import Divider from "@mui/material/Divider";
import MuiListItemAvatar from "@mui/material/ListItemAvatar";
import ListItemIcon from "@mui/material/ListItemIcon";
import ListItemText from "@mui/material/ListItemText";
import ListSubheader from "@mui/material/ListSubheader";
import MenuItem from "@mui/material/MenuItem";
import Select, {
type SelectChangeEvent,
selectClasses,
} from "@mui/material/Select";
import { styled } from "@mui/material/styles";
import * as React from "react";
const Avatar = styled(MuiAvatar)(({ theme }) => ({
width: 28,
height: 28,
backgroundColor: theme.palette.background.paper,
color: theme.palette.text.secondary,
border: `1px solid ${theme.palette.divider}`,
}));
const ListItemAvatar = styled(MuiListItemAvatar)({
minWidth: 0,
marginRight: 12,
});
export default function SelectContent() {
const [company, setCompany] = React.useState("");
const handleChange = (event: SelectChangeEvent) => {
setCompany(event.target.value as string);
};
return (
<Select
labelId="company-select"
id="company-simple-select"
value={company}
onChange={handleChange}
displayEmpty
inputProps={{ "aria-label": "Select company" }}
fullWidth
sx={{
maxHeight: 56,
width: 215,
"&.MuiList-root": {
p: "8px",
},
[`& .${selectClasses.select}`]: {
display: "flex",
alignItems: "center",
gap: "2px",
pl: 1,
},
}}
>
<ListSubheader sx={{ pt: 0 }}>Production</ListSubheader>
<MenuItem value="">
<ListItemAvatar>
<Avatar alt="Sitemark web">
<DevicesRoundedIcon sx={{ fontSize: "1rem" }} />
</Avatar>
</ListItemAvatar>
<ListItemText primary="Sitemark-web" secondary="Web app" />
</MenuItem>
<MenuItem value={10}>
<ListItemAvatar>
<Avatar alt="Sitemark App">
<SmartphoneRoundedIcon sx={{ fontSize: "1rem" }} />
</Avatar>
</ListItemAvatar>
<ListItemText primary="Sitemark-app" secondary="Mobile application" />
</MenuItem>
<MenuItem value={20}>
<ListItemAvatar>
<Avatar alt="Sitemark Store">
<DevicesRoundedIcon sx={{ fontSize: "1rem" }} />
</Avatar>
</ListItemAvatar>
<ListItemText primary="Sitemark-Store" secondary="Web app" />
</MenuItem>
<ListSubheader>Development</ListSubheader>
<MenuItem value={30}>
<ListItemAvatar>
<Avatar alt="Sitemark Store">
<ConstructionRoundedIcon sx={{ fontSize: "1rem" }} />
</Avatar>
</ListItemAvatar>
<ListItemText primary="Sitemark-Admin" secondary="Web app" />
</MenuItem>
<Divider sx={{ mx: -1 }} />
<MenuItem value={40}>
<ListItemIcon>
<AddRoundedIcon />
</ListItemIcon>
<ListItemText primary="Add product" secondary="Web app" />
</MenuItem>
</Select>
);
}
@@ -0,0 +1,56 @@
"use client";
import { SiteLogo } from "@/components/nav/SiteLogo";
import Box from "@mui/material/Box";
import Divider from "@mui/material/Divider";
import MuiDrawer, { drawerClasses } from "@mui/material/Drawer";
import { styled } from "@mui/material/styles";
import MenuContent from "./MenuContent";
const drawerWidth = 240;
const Drawer = styled(MuiDrawer)({
width: drawerWidth,
flexShrink: 0,
boxSizing: "border-box",
mt: 10,
[`& .${drawerClasses.paper}`]: {
width: drawerWidth,
boxSizing: "border-box",
},
});
export default function SideMenu() {
return (
<Drawer
variant="permanent"
sx={{
display: { xs: "none", md: "block" },
[`& .${drawerClasses.paper}`]: {
backgroundColor: "background.paper",
},
}}
>
<Box
sx={{
display: "flex",
mt: "calc(var(--template-frame-height, 0px) + 4px)",
p: 1.5,
}}
>
<SiteLogo />
</Box>
<Divider />
<Box
sx={{
overflow: "auto",
height: "100%",
display: "flex",
flexDirection: "column",
}}
>
<MenuContent />
</Box>
</Drawer>
);
}
@@ -0,0 +1,43 @@
"use client";
import Divider from "@mui/material/Divider";
import Drawer, { drawerClasses } from "@mui/material/Drawer";
import Stack from "@mui/material/Stack";
import MenuContent from "./MenuContent";
interface SideMenuMobileProps {
open: boolean | undefined;
toggleDrawer: (newOpen: boolean) => () => void;
}
export default function SideMenuMobile({
open,
toggleDrawer,
}: SideMenuMobileProps) {
return (
<Drawer
anchor="right"
open={open}
onClose={toggleDrawer(false)}
sx={{
zIndex: (theme) => theme.zIndex.drawer + 1,
[`& .${drawerClasses.paper}`]: {
backgroundImage: "none",
backgroundColor: "background.paper",
},
}}
>
<Stack
sx={{
maxWidth: "70dvw",
height: "100%",
}}
>
<Stack sx={{ flexGrow: 1 }}>
<MenuContent />
<Divider />
</Stack>
</Stack>
</Drawer>
);
}
@@ -0,0 +1,15 @@
import Link from "@mui/material/Link";
import NextLink from "next/link";
export function SiteLogo() {
return (
<Link
component={NextLink}
underline="hover"
sx={{ color: "text.primary", fontSize: "18px" }}
href="/"
>
Nym Node Status
</Link>
);
}
@@ -0,0 +1,45 @@
"use client";
import { type Client, createClient } from "@/client/client";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { ReactQueryDevtools } from "@tanstack/react-query-devtools";
import type React from "react";
import { createContext, useContext, useRef } from "react";
interface State {
client?: Client;
}
export const QueryContext = createContext<State>({
client: undefined,
});
export const useQueryContext = (): React.ContextType<typeof QueryContext> =>
useContext<State>(QueryContext);
export const QueryContextProvider = ({
children,
}: {
children: React.ReactNode | React.ReactNode[];
}) => {
const openApiClient = useRef(
createClient({ baseUrl: "https://mainnet-node-status-api.nymtech.cc" }),
);
const queryClient = useRef(new QueryClient());
const state: State = {
client: openApiClient.current,
};
return (
<QueryContext.Provider value={state}>
<QueryClientProvider client={queryClient.current}>
{children}
{/* Add devtools in development */}
{process.env.NODE_ENV === "development" && (
<ReactQueryDevtools initialIsOpen={false} />
)}
</QueryClientProvider>
</QueryContext.Provider>
);
};
@@ -0,0 +1,4 @@
export interface Pagination {
pageIndex?: number;
pageSize?: number;
}
@@ -0,0 +1,39 @@
import { nymNodes } from "@/client/sdk.gen";
import { useQueryContext } from "@/context/queryContext";
import type { NymNode } from "@/hooks/useNymNodes";
import { useQuery } from "@tanstack/react-query";
import React from "react";
export const useAllNymNodes = () => {
const { client } = useQueryContext();
const key = "nym-nodes-all";
const queryFn = React.useCallback(async (): Promise<NymNode[]> => {
const size = 100;
let busy = true;
let page = 0;
const allData = [];
do {
const { data, error } = await nymNodes({ client, query: { page, size } });
if (error) throw error;
if (data?.items) {
allData.push(...data.items);
}
// keep querying until data is less than a page
if ((data?.items.length || 0) < size) {
busy = false;
}
page += 1;
} while (busy);
return allData;
}, [client]);
const query = useQuery({ queryKey: [key], queryFn });
return {
key,
query,
};
};
@@ -0,0 +1,20 @@
import { getGatewaysOptions } from "@/client/@tanstack/react-query.gen";
import { useQueryContext } from "@/context/queryContext";
import { keepPreviousData, useQuery } from "@tanstack/react-query";
export const useDVpnGateways = () => {
const { client } = useQueryContext();
const key = "gateways";
const query = useQuery({
...getGatewaysOptions({
client,
}),
placeholderData: keepPreviousData,
});
return {
key,
query,
};
};
@@ -0,0 +1,47 @@
import { getGateways } from "@/client/sdk.gen";
import { useQueryContext } from "@/context/queryContext";
import { keepPreviousData, useQuery } from "@tanstack/react-query";
import React from "react";
export const useDVpnGatewaysTransformed = () => {
const { client } = useQueryContext();
const key = "gateways";
const queryFn = React.useCallback(async () => {
const { data, error } = await getGateways({ client });
if (error) throw error;
return (data || []).map((g) => {
const wg = g.last_probe?.outcome.wg as any;
const downloadSpeedMBPerSec = wg
? Math.round(
(10 * ((wg?.downloaded_file_size_bytes_v4 || 0) / 1024 / 1024)) /
((wg?.download_duration_milliseconds_v4 || 1) / 1000),
) / 10
: undefined;
const downloadSpeedIpv6MBPerSec = wg
? Math.round(
(10 * ((wg?.downloaded_file_size_bytes_v6 || 0) / 1024 / 1024)) /
((wg?.download_duration_milliseconds_v6 || 1) / 1000),
) / 10
: undefined;
return {
...g,
extra: {
downloadSpeedMBPerSec,
downloadSpeedIpv6MBPerSec,
},
};
});
}, [client]);
const query = useQuery({
queryKey: [key],
queryFn,
placeholderData: keepPreviousData,
});
return {
key,
query,
};
};
@@ -0,0 +1,52 @@
import type {
DescribedNodeType,
NodeDescription,
NodeGeoData,
NodeRewarding,
NymNodeData,
U32,
} from "@/client";
import { nymNodesOptions } from "@/client/@tanstack/react-query.gen";
import { useQueryContext } from "@/context/queryContext";
import type { Pagination } from "@/hooks/types";
import { keepPreviousData, useQuery } from "@tanstack/react-query";
// TODO: how to re-use autogenerated subtype
export type NymNode = {
accepted_tnc: boolean;
bonded: boolean;
bonding_address?: string | null;
description: NodeDescription;
geoip?: null | NodeGeoData;
identity_key: string;
ip_address: string;
node_id: U32;
node_type: DescribedNodeType;
original_pledge: number;
rewarding_details?: null | NodeRewarding;
self_description: NymNodeData;
total_stake: string;
uptime: number;
};
export const useNymNodes = (props?: Pagination) => {
const { client } = useQueryContext();
const { pageIndex = 0, pageSize = 10 } = props || {};
const key = "nym-nodes";
const query = useQuery({
...nymNodesOptions({
client,
query: {
page: pageIndex,
size: pageSize,
},
}),
placeholderData: keepPreviousData,
});
return {
key,
query,
};
};
@@ -0,0 +1,29 @@
import Copyright from "@/components/Copyright";
import AppNavbar from "@/components/nav/AppNavbar";
import SideMenu from "@/components/nav/SideMenu";
import Box from "@mui/material/Box";
import { alpha } from "@mui/material/styles";
import type React from "react";
export default function LayoutWithNav({
children,
}: { children?: React.ReactNode }) {
return (
<Box sx={{ display: "flex" }}>
<SideMenu />
<AppNavbar />
{/* Main content */}
<Box
component="main"
sx={(theme) => ({
flexGrow: 1,
backgroundColor: alpha(theme.palette.background.default, 1),
overflow: "auto",
})}
>
{children}
<Copyright />
</Box>
</Box>
);
}
@@ -0,0 +1,23 @@
import Header from "@/components/nav/Header";
import Stack from "@mui/material/Stack";
import type React from "react";
export default function NestedLayoutWithHeader({
children,
header,
}: { children?: React.ReactNode; header?: React.ReactNode }) {
return (
<Stack
spacing={2}
sx={{
alignItems: "center",
mx: 3,
pb: 5,
mt: { xs: 8, md: 0 },
}}
>
<Header title={header} />
{children}
</Stack>
);
}
@@ -0,0 +1,91 @@
"use client";
import DarkModeIcon from "@mui/icons-material/DarkModeRounded";
import LightModeIcon from "@mui/icons-material/LightModeRounded";
import Box from "@mui/material/Box";
import IconButton, { type IconButtonOwnProps } from "@mui/material/IconButton";
import Menu from "@mui/material/Menu";
import MenuItem from "@mui/material/MenuItem";
import { useColorScheme } from "@mui/material/styles";
import * as React from "react";
export default function ColorModeIconDropdown(props: IconButtonOwnProps) {
const { mode, systemMode, setMode } = useColorScheme();
const [anchorEl, setAnchorEl] = React.useState<null | HTMLElement>(null);
const open = Boolean(anchorEl);
const handleClick = (event: React.MouseEvent<HTMLElement>) => {
setAnchorEl(event.currentTarget);
};
const handleClose = () => {
setAnchorEl(null);
};
const handleMode = (targetMode: "system" | "light" | "dark") => () => {
setMode(targetMode);
handleClose();
};
if (!mode) {
return (
<Box
data-screenshot="toggle-mode"
sx={(theme) => ({
verticalAlign: "bottom",
display: "inline-flex",
width: "2.25rem",
height: "2.25rem",
borderRadius: theme.shape.borderRadius,
border: "1px solid",
borderColor: theme.palette.divider,
})}
/>
);
}
const resolvedMode = (systemMode || mode) as "light" | "dark";
const icon = {
light: <LightModeIcon />,
dark: <DarkModeIcon />,
}[resolvedMode];
return (
<React.Fragment>
<IconButton
data-screenshot="toggle-mode"
onClick={handleClick}
disableRipple
size="small"
aria-controls={open ? "color-scheme-menu" : undefined}
aria-haspopup="true"
aria-expanded={open ? "true" : undefined}
{...props}
>
{icon}
</IconButton>
<Menu
anchorEl={anchorEl}
id="account-menu"
open={open}
onClose={handleClose}
onClick={handleClose}
slotProps={{
paper: {
variant: "outlined",
elevation: 0,
sx: {
my: "4px",
},
},
}}
transformOrigin={{ horizontal: "right", vertical: "top" }}
anchorOrigin={{ horizontal: "right", vertical: "bottom" }}
>
<MenuItem selected={mode === "system"} onClick={handleMode("system")}>
System
</MenuItem>
<MenuItem selected={mode === "light"} onClick={handleMode("light")}>
Light
</MenuItem>
<MenuItem selected={mode === "dark"} onClick={handleMode("dark")}>
Dark
</MenuItem>
</Menu>
</React.Fragment>
);
}
@@ -0,0 +1,27 @@
import { ThemeProvider, createTheme } from "@mui/material/styles";
import * as React from "react";
interface AppThemeProps {
children: React.ReactNode;
// themeComponents?: ThemeOptions["components"];
}
export default function AppTheme(props: AppThemeProps) {
const { children } = props;
const theme = React.useMemo(() => {
return createTheme({
colorSchemes: {
dark: true,
light: true,
},
typography: {
fontFamily: "system-ui, sans-serif",
},
});
}, []);
return (
<ThemeProvider theme={theme} disableTransitionOnChange>
{children}
</ThemeProvider>
);
}
+1
View File
@@ -27,6 +27,7 @@ console-subscriber = { workspace = true, optional = true }
csv = { workspace = true }
clap = { workspace = true, features = ["cargo", "env"] }
futures = { workspace = true }
humantime = { workspace = true }
humantime-serde = { workspace = true }
human-repr = { workspace = true }
ipnetwork = { workspace = true }
+2
View File
@@ -944,6 +944,7 @@ pub struct Wireguard {
/// Tunnel port announced to external clients wishing to connect to the wireguard interface.
/// Useful in the instances where the node is behind a proxy.
#[serde(alias = "announced_port")]
pub announced_tunnel_port: u16,
/// Metadata port announced to external clients wishing to connect to the metadata endpoint.
@@ -1001,6 +1002,7 @@ impl From<Wireguard> for nym_authenticator::config::Authenticator {
tunnel_announced_port: value.announced_tunnel_port,
private_network_prefix_v4: value.private_network_prefix_v4,
private_network_prefix_v6: value.private_network_prefix_v6,
peer_interaction_timeout: nym_authenticator::config::default_peer_interaction_timeout(),
}
}
}
@@ -63,6 +63,7 @@ pub struct WireguardV10 {
/// Port announced to external clients wishing to connect to the wireguard interface.
/// Useful in the instances where the node is behind a proxy.
#[serde(alias = "announced_tunnel_port")]
pub announced_port: u16,
/// The prefix denoting the maximum number of the clients that can be connected via Wireguard using IPv4.