Skip to main content

xrpl_escrow_stdlib/ctx/
escrow_finish.rs

1use xrpl_wasm_stdlib::ctx::SmartFeatureContext;
2use xrpl_wasm_stdlib::host;
3
4use crate::current_tx::escrow_finish::EscrowFinish;
5use crate::ledger_objects::current_escrow::CurrentEscrow;
6
7/// Entry-point context for a Smart Escrow finish operation.
8///
9/// Provides access to the current [`EscrowFinish`] transaction via
10/// [`SmartFeatureContext::tx`] and to the escrow ledger object via
11/// [`escrow`](EscrowFinishContext::escrow). Escrow-unique host functions
12/// (e.g., [`update_data`](EscrowFinishContext::update_data)) are exposed as
13/// safe inherent methods; no `unsafe` code is needed in user crates.
14///
15/// The `#[smart_escrow]` macro constructs this via `Default::default()` and
16/// passes it to the user function.
17pub struct EscrowFinishContext {
18    tx: EscrowFinish,
19    escrow: CurrentEscrow,
20}
21
22impl Default for EscrowFinishContext {
23    fn default() -> Self {
24        Self {
25            tx: EscrowFinish,
26            escrow: CurrentEscrow,
27        }
28    }
29}
30
31impl SmartFeatureContext for EscrowFinishContext {
32    type Tx = EscrowFinish;
33    fn tx(&self) -> &Self::Tx {
34        &self.tx
35    }
36}
37
38impl EscrowFinishContext {
39    /// Returns a reference to the current escrow ledger object.
40    pub fn escrow(&self) -> &CurrentEscrow {
41        &self.escrow
42    }
43
44    /// **[host fn]** Write new data to the Smart Escrow object.
45    pub fn update_data(&self, data: &[u8]) -> host::Result<()> {
46        let n = unsafe { host::update_data(data.as_ptr(), data.len()) };
47        if n < 0 {
48            return host::Result::Err(host::Error::from_code(n));
49        }
50        host::Result::Ok(())
51    }
52}
53
54#[cfg(test)]
55mod tests {
56    use super::*;
57    use xrpl_stdlib_test_utils::EscrowScenario;
58    use xrpl_wasm_stdlib::host::Error;
59
60    #[test]
61    fn default_constructs() {
62        let _ctx = EscrowFinishContext::default();
63    }
64
65    #[test]
66    fn tx_and_escrow_accessors() {
67        let ctx = EscrowFinishContext::default();
68        let _tx: &EscrowFinish = ctx.tx();
69        let _escrow: &CurrentEscrow = ctx.escrow();
70    }
71
72    #[test]
73    fn update_data_returns_ok_on_success() {
74        let _guard = EscrowScenario::builder()
75            .with_update_data_returns(Ok(()))
76            .install();
77
78        let ctx = EscrowFinishContext::default();
79        assert!(ctx.update_data(b"payload").is_ok());
80    }
81
82    #[test]
83    fn update_data_returns_err_on_negative_code() {
84        let _guard = EscrowScenario::builder()
85            .with_update_data_returns(Err(Error::InternalError))
86            .install();
87
88        let ctx = EscrowFinishContext::default();
89        assert!(ctx.update_data(b"payload").is_err());
90    }
91}