use super::*;
use crate::subnet_catalog::MAINNET_NETWORK;
use std::{
future::Future,
pin::pin,
task::{Context, Poll, Waker},
};
use validation::{
validate_governance_metrics, validate_governance_response_size, validate_source_provenance,
};
#[test]
fn governance_report_context_serializes_flattened() {
let report = NnsGovernanceMaturityModulationReport {
context: NnsGovernanceReportContext {
schema_version: 1,
network: "ic".to_string(),
governance_canister_id: "rrkah-fqaaa-aaaaa-aaaaq-cai".to_string(),
fetched_at: "2026-07-30T00:00:00Z".to_string(),
source: NnsGovernanceSourceProvenance::ReplicaQuery {
endpoint: DEFAULT_NNS_GOVERNANCE_SOURCE_ENDPOINT.to_string(),
fetched_by: "fixture".to_string(),
},
},
maturity_modulation: None,
};
let value = serde_json::to_value(report).expect("serialize report");
assert_eq!(value["schema_version"], 1);
assert_eq!(value["network"], "ic");
assert!(value.get("context").is_none());
assert_eq!(value["source"]["source_transport"], "replica_query");
assert!(value["maturity_modulation"].is_null());
}
#[test]
fn canister_provenance_is_tagged_and_derives_replicated_assurance() {
let source = NnsGovernanceSourceProvenance::ReplicatedInterCanisterCall {
collector_canister_id: "aaaaa-aa".to_string(),
};
let value = serde_json::to_value(&source).expect("serialize canister provenance");
assert_eq!(value["source_transport"], "replicated_inter_canister_call");
assert_eq!(value["collector_canister_id"], "aaaaa-aa");
assert_eq!(
source.execution_assurance(),
NnsGovernanceExecutionAssurance::ReplicatedExecution
);
}
#[test]
fn replicated_provenance_requires_canonical_collector_evidence() {
for (collector, accepted) in [("aaaaa-aa", true), ("AAAAA-AA", false), ("invalid", false)] {
let provenance = NnsGovernanceSourceProvenance::ReplicatedInterCanisterCall {
collector_canister_id: collector.to_string(),
};
let result = validate_source_provenance(
&NnsGovernanceSourceSelection::ReplicatedInterCanisterCall,
&provenance,
);
if accepted {
result.expect("canonical collector evidence");
} else {
assert!(matches!(
result,
Err(NnsGovernanceError::SourceEvidenceMismatch { .. })
));
}
}
}
#[test]
fn source_provenance_must_echo_the_selected_transport() {
let selection = NnsGovernanceSourceSelection::ReplicaQuery {
endpoint: "https://example.test".to_string(),
fetched_by: "fixture".to_string(),
};
let actual = NnsGovernanceSourceProvenance::ReplicatedInterCanisterCall {
collector_canister_id: "aaaaa-aa".to_string(),
};
assert!(matches!(
validate_source_provenance(&selection, &actual),
Err(NnsGovernanceError::SourceEvidenceMismatch { .. })
));
}
#[test]
fn raw_governance_response_limit_is_enforced_before_decode() {
assert!(
validate_governance_response_size("fixture", MAX_NNS_GOVERNANCE_RESPONSE_BYTES).is_ok()
);
assert!(matches!(
validate_governance_response_size("fixture", MAX_NNS_GOVERNANCE_RESPONSE_BYTES + 1),
Err(NnsGovernanceError::ResponseTooLarge {
method: "fixture",
actual_bytes,
maximum_bytes: MAX_NNS_GOVERNANCE_RESPONSE_BYTES,
}) if actual_bytes == MAX_NNS_GOVERNANCE_RESPONSE_BYTES + 1
));
}
#[tokio::test(flavor = "current_thread")]
async fn live_governance_source_rejects_non_mainnet_before_agent_construction() {
let request = NnsGovernanceRequest::replica_query(
"local",
"this-is-not-a-valid-url",
"2026-07-30T00:00:00Z",
"fixture",
);
assert!(matches!(
build_nns_governance_economics_report_with_source(&request, &crate::nns::LiveNnsSource::default()).await,
Err(NnsGovernanceError::UnsupportedNetwork { network }) if network == "local"
));
assert!(matches!(
build_nns_governance_metrics_report_with_source(&request, &crate::nns::LiveNnsSource::default()).await,
Err(NnsGovernanceError::UnsupportedNetwork { network }) if network == "local"
));
assert!(matches!(
build_nns_governance_reward_event_report_with_source(&request, &crate::nns::LiveNnsSource::default()).await,
Err(NnsGovernanceError::UnsupportedNetwork { network }) if network == "local"
));
assert!(matches!(
build_nns_governance_maturity_modulation_report_with_source(&request, &crate::nns::LiveNnsSource::default()).await,
Err(NnsGovernanceError::UnsupportedNetwork { network }) if network == "local"
));
}
#[tokio::test(flavor = "current_thread")]
async fn custom_source_builder_preserves_shared_provenance() {
let request = NnsGovernanceRequest::replica_query(
MAINNET_NETWORK,
"https://example.test",
"2026-07-30T00:00:00Z",
"fixture",
);
let report = build_nns_governance_economics_report_with_source(&request, &FixtureSource)
.await
.expect("fixture economics report");
assert_eq!(report.context.network, MAINNET_NETWORK);
assert_eq!(
report.context.source,
NnsGovernanceSourceProvenance::ReplicaQuery {
endpoint: "https://example.test".to_string(),
fetched_by: "fixture".to_string(),
}
);
assert_eq!(report.economics.reject_cost_e8s, 1_000_000_000);
}
#[tokio::test(flavor = "current_thread")]
async fn builder_rejects_non_mainnet_before_custom_source_call() {
let request = NnsGovernanceRequest::replica_query(
"local",
"https://example.test",
"2026-07-30T00:00:00Z",
"fixture",
);
let error = build_nns_governance_economics_report_with_source(&request, &PanicSource)
.await
.expect_err("non-mainnet request must fail");
assert!(matches!(
error,
NnsGovernanceError::UnsupportedNetwork { network } if network == "local"
));
}
#[tokio::test(flavor = "current_thread")]
async fn builder_rejects_invalid_replica_selection_before_source() {
let request = NnsGovernanceRequest::replica_query(
"ic",
"not-an-absolute-url",
"2026-08-14T00:00:00Z",
"fixture",
);
let error = build_nns_governance_economics_report_with_source(&request, &PanicSource)
.await
.expect_err("invalid endpoint must fail");
assert!(matches!(
error,
NnsGovernanceError::InvalidSourceSelection { reason }
if !reason.is_empty()
));
}
#[test]
fn governance_rejects_invalid_request_timestamps_before_source_calls() {
for mut request in [
NnsGovernanceRequest::replica_query_from_unix_secs(
"ic",
"https://example.com",
1_700_000_000,
"fixture",
),
NnsGovernanceRequest::replicated_inter_canister_call_from_unix_secs("ic", 1_700_000_000),
] {
for timestamp in [
"invalid",
"2026-02-29T00:00:00Z",
"2026-6-04T00:00:00Z",
"2026-06-04T0:00:00Z",
"+2026-06-04T00:00:00Z",
"9223372036854775807-01-01T00:00:00Z",
] {
request.fetched_at = timestamp.to_string();
assert!(matches!(
run_ready(build_nns_governance_economics_report_with_source(
&request,
&PanicSource
)),
Err(NnsGovernanceError::InvalidTimestamp {
field: "fetched_at",
value,
..
}) if value == timestamp
));
}
}
}
fn run_ready<T>(future: impl Future<Output = T>) -> T {
let mut future = pin!(future);
let mut context = Context::from_waker(Waker::noop());
match future.as_mut().poll(&mut context) {
Poll::Ready(value) => value,
Poll::Pending => panic!("fixture future unexpectedly returned Pending"),
}
}
#[test]
fn economics_candid_shape_preserves_nested_native_options() {
let bytes = include_bytes!("fixtures/economics.bin");
let economics = crate::candid_codec::decode_reply::<NnsGovernanceEconomics>(bytes)
.expect("decode native economics");
assert!(
crate::candid_codec::decode_reply::<NnsGovernanceEconomics>(&bytes[..bytes.len() - 1])
.is_err()
);
let fund = economics
.neurons_fund_economics
.expect("Neurons' Fund economics");
assert_eq!(
fund.maximum_icp_xdr_rate
.expect("maximum rate wrapper")
.basis_points,
None
);
assert_eq!(
fund.neurons_fund_matched_funding_curve_coefficients
.expect("curve")
.contribution_threshold_xdr
.expect("threshold")
.human_readable
.as_deref(),
Some("1.25")
);
assert_eq!(
economics
.voting_power_economics
.expect("voting economics")
.neuron_minimum_dissolve_delay_to_vote_seconds,
Some(15_778_800)
);
}
#[test]
fn reward_and_maturity_external_records_project_into_reports() {
let bytes = include_bytes!("fixtures/reward-event.bin");
let decoded: NnsGovernanceRewardEvent =
crate::candid_codec::decode_reply(bytes).expect("decode reward event");
assert_eq!(
serde_json::to_value(decoded).unwrap(),
serde_json::json!({
"rounds_since_last_distribution": 1, "day_after_genesis": 2,
"actual_timestamp_seconds": 3, "total_available_e8s_equivalent": 4,
"latest_round_available_e8s_equivalent": 5, "distributed_e8s_equivalent": 6,
"settled_proposals": [{"id": 7}]
})
);
let bytes = include_bytes!("fixtures/maturity.bin");
let decoded: super::wire::GetMaturityModulationResponse =
crate::candid_codec::decode_reply(bytes).expect("decode maturity response");
let modulation: NnsGovernanceMaturityModulation =
decoded.maturity_modulation.expect("maturity modulation");
assert_eq!(modulation.current_value_permyriad, Some(-125));
assert_eq!(modulation.updated_at_timestamp_seconds, Some(8));
}
#[test]
fn metrics_projection_names_unlabeled_buckets_and_preserves_subsets() {
let metrics = crate::candid_codec::decode_reply::<NnsGovernanceMetrics>(include_bytes!(
"fixtures/metric-buckets.bin"
))
.unwrap();
assert_eq!(metrics.total_supply_icp, 42);
assert_eq!(
metrics.not_dissolving_neurons_e8s_buckets,
vec![NnsGovernanceMetricBucket {
key: 10,
value: 20.5,
}]
);
let public = metrics.public_neuron_subset_metrics.expect("public subset");
assert_eq!(public.count, Some(3));
assert_eq!(
public.count_buckets,
vec![NnsGovernanceMetricBucket { key: 100, value: 2 }]
);
}
#[test]
fn metrics_result_preserves_the_native_candid_variant_shape() {
let bytes = include_bytes!("fixtures/metrics-ok.bin");
let decoded: super::wire::GetMetricsResult =
crate::candid_codec::decode_reply(bytes).expect("decode metrics result");
let super::wire::GetMetricsResult::Ok(metrics) = decoded else {
panic!("expected native Ok metrics variant");
};
assert_eq!(metrics.total_supply_icp, 42);
}
#[test]
fn metrics_validation_rejects_non_finite_json_values() {
let metrics = crate::candid_codec::decode_reply::<NnsGovernanceMetrics>(include_bytes!(
"fixtures/metrics-nonfinite.bin"
))
.unwrap();
let error = validate_governance_metrics(&metrics).expect_err("non-finite metric must fail");
assert!(matches!(
error,
NnsGovernanceError::InvalidMetrics {
field: "dissolving_neurons_e8s_buckets",
key: 30,
value,
} if value.is_nan()
));
}
#[test]
fn metrics_governance_error_remains_typed() {
let bytes = include_bytes!("fixtures/metrics-error.bin");
let result = source::metrics_result(crate::candid_codec::decode_reply(bytes).unwrap());
let Err(error) = result else {
panic!("typed Governance error must fail");
};
assert!(matches!(
error,
NnsGovernanceError::Governance {
error_type: 5,
message,
} if message == "unavailable"
));
}
struct FixtureSource;
impl NnsGovernanceSource for FixtureSource {
fn fetch_economics<'a>(
&'a self,
request: &'a NnsGovernanceRequest,
) -> NnsGovernanceSourceFuture<'a, NnsGovernanceEconomics> {
Box::pin(async move {
Ok(NnsGovernanceSourceData::new(
sample_economics(),
fixture_provenance(request),
))
})
}
fn fetch_metrics<'a>(
&'a self,
_request: &'a NnsGovernanceRequest,
) -> NnsGovernanceSourceFuture<'a, NnsGovernanceMetrics> {
Box::pin(async { unreachable!("not used by this fixture") })
}
fn fetch_reward_event<'a>(
&'a self,
_request: &'a NnsGovernanceRequest,
) -> NnsGovernanceSourceFuture<'a, NnsGovernanceRewardEvent> {
Box::pin(async { unreachable!("not used by this fixture") })
}
fn fetch_maturity_modulation<'a>(
&'a self,
_request: &'a NnsGovernanceRequest,
) -> NnsGovernanceSourceFuture<'a, Option<NnsGovernanceMaturityModulation>> {
Box::pin(async { unreachable!("not used by this fixture") })
}
}
struct PanicSource;
impl NnsGovernanceSource for PanicSource {
fn fetch_economics<'a>(
&'a self,
_request: &'a NnsGovernanceRequest,
) -> NnsGovernanceSourceFuture<'a, NnsGovernanceEconomics> {
panic!("source must not be called")
}
fn fetch_metrics<'a>(
&'a self,
_request: &'a NnsGovernanceRequest,
) -> NnsGovernanceSourceFuture<'a, NnsGovernanceMetrics> {
panic!("source must not be called")
}
fn fetch_reward_event<'a>(
&'a self,
_request: &'a NnsGovernanceRequest,
) -> NnsGovernanceSourceFuture<'a, NnsGovernanceRewardEvent> {
panic!("source must not be called")
}
fn fetch_maturity_modulation<'a>(
&'a self,
_request: &'a NnsGovernanceRequest,
) -> NnsGovernanceSourceFuture<'a, Option<NnsGovernanceMaturityModulation>> {
panic!("source must not be called")
}
}
fn fixture_provenance(request: &NnsGovernanceRequest) -> NnsGovernanceSourceProvenance {
let NnsGovernanceSourceSelection::ReplicaQuery {
endpoint,
fetched_by,
} = &request.source
else {
panic!("fixture requires replica provenance")
};
NnsGovernanceSourceProvenance::ReplicaQuery {
endpoint: endpoint.clone(),
fetched_by: fetched_by.clone(),
}
}
pub(super) const fn sample_economics() -> NnsGovernanceEconomics {
NnsGovernanceEconomics {
neuron_minimum_stake_e8s: 100_000_000,
max_proposals_to_keep_per_topic: 100,
neuron_management_fee_per_proposal_e8s: 10_000,
reject_cost_e8s: 1_000_000_000,
transaction_fee_e8s: 10_000,
neuron_spawn_dissolve_delay_seconds: 604_800,
minimum_icp_xdr_rate: 100,
maximum_node_provider_rewards_e8s: 200_000_000,
neurons_fund_economics: None,
voting_power_economics: None,
}
}