Skip to main content

xrpl_escrow_stdlib/ctx/
escrow_finish.rs

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