polyc-state-connect 2026.10.2

State plane transport adapter: capability-specific Connect clients and server-trait glue mapping the generated wire types onto the polyc-state kernel — typed outcomes, per-call admission, and the conformance surface the authenticated shell proves itself against (docs/proposals/separated-planes.md).
//! Capability-specific wallet-link and spend-policy client.
//!
//! Async end to end. The generated client is async, every method here awaits
//! it, and nothing in this family reaches for a blocking bridge or a blocking
//! pool.
//!
//! Every call carries the caller's remaining budget in its
//! [`DeclaredCall`](crate::wire::DeclaredCall), and the caller is expected to
//! supply a real one. This family gates a delegation ceremony: a read that
//! never returns is a ceremony that hangs holding key material, which is the
//! outcome failing closed exists to avoid.

use connectrpc::client::{ClientConfig, ClientTransport};
use polyc_proto::proto::polychrome::state::v1 as pb;
use polyc_state::{
    error::StateError,
    id::{CommandId, NamespaceId},
    receipt::Receipt,
    revision::Revision,
    wallet::{
        PersonaId, SpendPolicyRecord, WalletAddress, WalletAddressPointer, WalletCommand,
        WalletFact, WalletLinkRecord, WalletView,
    },
};

use crate::{
    MAX_WIRE_MESSAGE_BYTES,
    error::{TransportFallback, from_connect_error},
    trace::bounded_traced_options,
    wire::{DeclaredCall, Kernel},
};

use super::wire::{
    link_from_wire, metadata_to_wire, operation_to_wire, pointer_from_wire, policy_from_wire,
};

/// Client bound to one wallet namespace and no other State capability.
pub struct WalletClient<T> {
    inner: pb::StateWalletServiceClient<T>,
    namespace: NamespaceId,
}

impl<T> WalletClient<T>
where
    T: ClientTransport,
    <T::ResponseBody as connectrpc::http_body::Body>::Error: std::fmt::Display,
{
    /// Builds a namespace-bound client.
    #[must_use]
    pub fn new(transport: T, config: ClientConfig, namespace: NamespaceId) -> Self {
        Self {
            inner: pb::StateWalletServiceClient::new(
                transport,
                config.with_default_max_message_size(MAX_WIRE_MESSAGE_BYTES),
            ),
            namespace,
        }
    }

    fn fallback(declared: &DeclaredCall, attempted: usize) -> TransportFallback {
        TransportFallback::new(
            polyc_state::wallet::family(),
            MAX_WIRE_MESSAGE_BYTES as u64,
            attempted as u64,
            declared.budget,
        )
    }

    /// Commits one typed wallet mutation.
    ///
    /// # Errors
    ///
    /// Returns a typed State or transport failure. A link over an address
    /// another persona holds, and a revocation naming a superseded key handle,
    /// come back as refusals rather than as quiet successes.
    pub async fn transact(
        &self,
        declared: &DeclaredCall,
        command: &WalletCommand,
    ) -> Result<Receipt, StateError> {
        if command.metadata().scope().namespace() != &self.namespace {
            return Err(StateError::Denied {
                family: polyc_state::wallet::family(),
            });
        }
        let request = pb::TransactStateWalletRequest {
            context: buffa::MessageField::some(Kernel(declared).into()),
            metadata: buffa::MessageField::some(metadata_to_wire(command)),
            persona_id: command.persona().as_str().to_owned(),
            operation: buffa::MessageField::some(operation_to_wire(command.operation())),
            __buffa_unknown_fields: buffa::UnknownFields::default(),
        };
        let attempted = buffa::Message::encoded_len(&request) as usize;
        let reply = self
            .inner
            .transact_with_options(request, bounded_traced_options(declared))
            .await
            .map_err(|error| from_connect_error(&error, &Self::fallback(declared, attempted)))?
            .into_owned();
        Kernel::<Receipt>::try_from(reply.receipt.into_option().ok_or_else(|| {
            StateError::Malformed {
                field: "receipt".into(),
                reason: "a successful wallet mutation returns a receipt".into(),
            }
        })?)
        .map(Kernel::into_inner)
    }

    /// Reads one persona's wallet link.
    ///
    /// # Errors
    ///
    /// Returns a typed State or transport failure.
    pub async fn link(
        &self,
        declared: &DeclaredCall,
        persona: &PersonaId,
    ) -> Result<WalletFact<Option<WalletLinkRecord>>, StateError> {
        let request = pb::GetStateWalletLinkRequest {
            context: buffa::MessageField::some(Kernel(declared).into()),
            namespace: self.namespace.as_str().to_owned(),
            persona_id: persona.as_str().to_owned(),
            __buffa_unknown_fields: buffa::UnknownFields::default(),
        };
        let attempted = buffa::Message::encoded_len(&request) as usize;
        let reply = self
            .inner
            .get_link_with_options(request, bounded_traced_options(declared))
            .await
            .map_err(|error| from_connect_error(&error, &Self::fallback(declared, attempted)))?
            .into_owned();
        Ok(WalletFact::observed(
            reply.link.into_option().map(link_from_wire),
            Revision::new(reply.snapshot_revision),
            reply.entry_revision.map(Revision::new),
        ))
    }

    /// Reads one persona's spend policy.
    ///
    /// # Errors
    ///
    /// Returns a typed State or transport failure.
    pub async fn policy(
        &self,
        declared: &DeclaredCall,
        persona: &PersonaId,
    ) -> Result<WalletFact<Option<SpendPolicyRecord>>, StateError> {
        let request = pb::GetStateWalletPolicyRequest {
            context: buffa::MessageField::some(Kernel(declared).into()),
            namespace: self.namespace.as_str().to_owned(),
            persona_id: persona.as_str().to_owned(),
            __buffa_unknown_fields: buffa::UnknownFields::default(),
        };
        let attempted = buffa::Message::encoded_len(&request) as usize;
        let reply = self
            .inner
            .get_policy_with_options(request, bounded_traced_options(declared))
            .await
            .map_err(|error| from_connect_error(&error, &Self::fallback(declared, attempted)))?
            .into_owned();
        Ok(WalletFact::observed(
            reply.policy.into_option().map(policy_from_wire),
            Revision::new(reply.snapshot_revision),
            reply.entry_revision.map(Revision::new),
        ))
    }

    /// Reads one persona's link and policy at one revision.
    ///
    /// # Errors
    ///
    /// Returns a typed State or transport failure.
    pub async fn view(
        &self,
        declared: &DeclaredCall,
        persona: &PersonaId,
    ) -> Result<WalletView, StateError> {
        let request = pb::GetStateWalletViewRequest {
            context: buffa::MessageField::some(Kernel(declared).into()),
            namespace: self.namespace.as_str().to_owned(),
            persona_id: persona.as_str().to_owned(),
            __buffa_unknown_fields: buffa::UnknownFields::default(),
        };
        let attempted = buffa::Message::encoded_len(&request) as usize;
        let reply = self
            .inner
            .get_view_with_options(request, bounded_traced_options(declared))
            .await
            .map_err(|error| from_connect_error(&error, &Self::fallback(declared, attempted)))?
            .into_owned();
        Ok(WalletView::observed(
            reply.link.into_option().map(link_from_wire),
            reply.policy.into_option().map(policy_from_wire),
            Revision::new(reply.snapshot_revision),
            reply.link_revision.map(Revision::new),
            reply.policy_revision.map(Revision::new),
        ))
    }

    /// Reads which persona holds one wallet address.
    ///
    /// # Errors
    ///
    /// Returns a typed State or transport failure.
    pub async fn resolve_address(
        &self,
        declared: &DeclaredCall,
        address: &WalletAddress,
    ) -> Result<WalletFact<Option<WalletAddressPointer>>, StateError> {
        let request = pb::ResolveStateWalletAddressRequest {
            context: buffa::MessageField::some(Kernel(declared).into()),
            namespace: self.namespace.as_str().to_owned(),
            wallet_address: address.as_str().to_owned(),
            __buffa_unknown_fields: buffa::UnknownFields::default(),
        };
        let attempted = buffa::Message::encoded_len(&request) as usize;
        let reply = self
            .inner
            .resolve_address_with_options(request, bounded_traced_options(declared))
            .await
            .map_err(|error| from_connect_error(&error, &Self::fallback(declared, attempted)))?
            .into_owned();
        Ok(WalletFact::observed(
            reply.pointer.into_option().map(pointer_from_wire),
            Revision::new(reply.snapshot_revision),
            reply.entry_revision.map(Revision::new),
        ))
    }

    /// Settles an ambiguous command from its durable receipt.
    ///
    /// # Errors
    ///
    /// Returns a typed State or transport failure.
    pub async fn committed_receipt(
        &self,
        declared: &DeclaredCall,
        command_id: &CommandId,
    ) -> Result<Option<Receipt>, StateError> {
        let request = pb::GetStateWalletReceiptRequest {
            context: buffa::MessageField::some(Kernel(declared).into()),
            namespace: self.namespace.as_str().to_owned(),
            command_id: command_id.as_str().to_owned(),
            __buffa_unknown_fields: buffa::UnknownFields::default(),
        };
        let attempted = buffa::Message::encoded_len(&request) as usize;
        let reply = self
            .inner
            .get_receipt_with_options(request, bounded_traced_options(declared))
            .await
            .map_err(|error| from_connect_error(&error, &Self::fallback(declared, attempted)))?
            .into_owned();
        reply
            .receipt
            .into_option()
            .map(|value| Kernel::<Receipt>::try_from(value).map(Kernel::into_inner))
            .transpose()
    }
}