whisky_pallas/wrapper/transaction_body/
transaction_output.rs

1use std::str::FromStr;
2
3use pallas::codec::utils::{Bytes, CborWrap, KeepRaw};
4use pallas::ledger::primitives::babbage::{GenPostAlonzoTransactionOutput, GenTransactionOutput};
5use pallas::ledger::primitives::conway::TransactionOutput as PallasTransactionOutput;
6use pallas::ledger::primitives::Fragment;
7use whisky_common::WError;
8
9use crate::wrapper::transaction_body::{Datum, ScriptRef, Value};
10
11#[derive(Debug, PartialEq, Clone)]
12pub struct TransactionOutput<'a> {
13    pub inner: PallasTransactionOutput<'a>,
14}
15
16impl<'a> TransactionOutput<'a> {
17    pub fn new(
18        address: &str,
19        value: Value,
20        datum: Option<Datum<'a>>,
21        script_ref: Option<ScriptRef<'a>>,
22    ) -> Result<Self, WError> {
23        let address = Bytes::from_str(&address).map_err(|e| {
24            WError::new(
25                "WhiskyPallas - Creating transaction output:",
26                &format!("Invalid address bytes: {}", e),
27            )
28        })?;
29
30        let pallas_transaction_output =
31            GenTransactionOutput::PostAlonzo(KeepRaw::from(GenPostAlonzoTransactionOutput {
32                address,
33                value: value.inner,
34                datum_option: datum.map(|d| KeepRaw::from(d.inner)),
35                script_ref: script_ref.map(|s| CborWrap(s.inner)),
36            }));
37
38        Ok(Self {
39            inner: pallas_transaction_output,
40        })
41    }
42
43    pub fn encode(&self) -> Result<String, WError> {
44        self.inner
45            .encode_fragment()
46            .map(|bytes| hex::encode(bytes))
47            .map_err(|_| {
48                WError::new(
49                    "WhiskyPallas - Encoding transaction output:",
50                    "Failed to encode fragment",
51                )
52            })
53    }
54
55    pub fn decode_bytes(bytes: &'a [u8]) -> Result<Self, WError> {
56        let inner = PallasTransactionOutput::decode_fragment(&bytes).map_err(|e| {
57            WError::new(
58                "WhiskyPallas - Decoding transaction output:",
59                &format!("Fragment decode error: {}", e.to_string()),
60            )
61        })?;
62        Ok(Self { inner })
63    }
64}