daml_grpc/service/
daml_command_submission_service.rs

1use std::convert::TryFrom;
2use std::fmt::Debug;
3
4use tonic::transport::Channel;
5use tracing::{instrument, trace};
6
7use crate::data::DamlCommands;
8use crate::data::DamlError;
9use crate::data::DamlResult;
10use crate::grpc_protobuf::com::daml::ledger::api::v1::command_submission_service_client::CommandSubmissionServiceClient;
11use crate::grpc_protobuf::com::daml::ledger::api::v1::{Commands, SubmitRequest};
12use crate::service::common::make_request;
13
14/// Advance the state of a Daml ledger by submitting commands.
15#[derive(Debug)]
16pub struct DamlCommandSubmissionService<'a> {
17    channel: Channel,
18    ledger_id: &'a str,
19    auth_token: Option<&'a str>,
20}
21
22impl<'a> DamlCommandSubmissionService<'a> {
23    pub fn new(channel: Channel, ledger_id: &'a str, auth_token: Option<&'a str>) -> Self {
24        Self {
25            channel,
26            ledger_id,
27            auth_token,
28        }
29    }
30
31    /// Override the JWT token to use for this service.
32    pub fn with_token(self, auth_token: &'a str) -> Self {
33        Self {
34            auth_token: Some(auth_token),
35            ..self
36        }
37    }
38
39    /// Override the ledger id to use for this service.
40    pub fn with_ledger_id(self, ledger_id: &'a str) -> Self {
41        Self {
42            ledger_id,
43            ..self
44        }
45    }
46
47    /// DOCME fully document this
48    #[instrument(skip(self))]
49    pub async fn submit_request(&self, commands: impl Into<DamlCommands> + Debug) -> DamlResult<String> {
50        let commands = commands.into();
51        let command_id = commands.command_id().to_owned();
52        let payload = SubmitRequest {
53            commands: Some(self.create_ledger_commands(commands)?),
54        };
55        trace!(payload = ?payload, token = ?self.auth_token);
56        self.client().submit(make_request(payload, self.auth_token)?).await.map_err(DamlError::from)?;
57        trace!(?command_id);
58        Ok(command_id)
59    }
60
61    fn client(&self) -> CommandSubmissionServiceClient<Channel> {
62        CommandSubmissionServiceClient::new(self.channel.clone())
63    }
64
65    // Convert into a GRPC `Commands` and inject the ledger id
66    fn create_ledger_commands(&self, commands: DamlCommands) -> DamlResult<Commands> {
67        let mut commands = Commands::try_from(commands)?;
68        commands.ledger_id = self.ledger_id.to_string();
69        Ok(commands)
70    }
71}