Skip to main content

rpc/natives/
template.rs

1//! Render-only draft natives.
2//!
3//! These host fns take no database action; each mutates the
4//! [`TransactionDraft`](crate::draft::TransactionDraft) held in the session's
5//! Store data, which the render entry point reads back via `store.into_data()`.
6//!
7//! They are *functionally* render-only: the linker binds them on BOTH the
8//! normal eval channel ([`super::link`]) and the render surface
9//! ([`super::link_render`]) — the import must resolve wherever a compiled module
10//! references it — but the draft accumulator is armed only under render
11//! (`SessionData::for_render`). On the normal channel `with_draft` finds no
12//! draft and traps, so a non-render program can compile/link a draft native yet
13//! never accumulate anything. That trap is a safety net, not the boundary; the
14//! real gate is the render compiler-spec allowlist (a normal template/eval that
15//! shouldn't see these simply doesn't have them in scope). They are harmless on
16//! the normal channel either way: no DB, no secret, no mutation.
17//!
18//! `draft-split` takes the entity refs returned by `get-account` /
19//! `get-commodity` plus a rational amount; it reads each entity's `id` field
20//! (slot 0, per `ENTITY_LAYOUTS`) host-side so the draft records stable uuids.
21
22use nomiscript::EntityKind;
23use scripting::runtime::{read_entity_string_field, read_ratio_arg, read_string_arg};
24use wasmtime::{ArrayRef, Linker, Rooted, StructRef};
25
26use crate::draft::{DraftSplit, DraftTag};
27use crate::natives::args::args_error;
28use crate::natives::native::register_native;
29use crate::session::SessionData;
30
31pub const REGISTERED_COMMANDS: &[&str] = &[
32    "set-draft-note",
33    "set-draft-date",
34    "draft-split",
35    "draft-tag",
36    "draft-split-tag",
37];
38
39type StringArg = Option<Rooted<ArrayRef>>;
40type StructArg = Option<Rooted<StructRef>>;
41
42pub fn register(linker: &mut Linker<SessionData>) -> wasmtime::Result<()> {
43    register_native(
44        linker,
45        "template_set_draft_note",
46        |caller, (note_arg,): (StringArg,)| {
47            Box::pin(async move {
48                let note = read_string_arg(caller, note_arg)?
49                    .ok_or_else(|| args_error("set-draft-note: missing note"))?;
50                caller.data().with_draft(|d| d.set_note(note))?;
51                Ok(1)
52            })
53        },
54    )?;
55    register_native(
56        linker,
57        "template_set_draft_date",
58        |caller, (date_arg,): (StringArg,)| {
59            Box::pin(async move {
60                let date = read_string_arg(caller, date_arg)?
61                    .ok_or_else(|| args_error("set-draft-date: missing date"))?;
62                caller.data().with_draft(|d| d.set_date(date))?;
63                Ok(1)
64            })
65        },
66    )?;
67    register_native(
68        linker,
69        "template_draft_split",
70        |caller, (account_arg, commodity_arg, amount_arg): (StructArg, StructArg, StructArg)| {
71            Box::pin(async move {
72                let account_id =
73                    read_entity_string_field(caller, account_arg, EntityKind::Account, "id")?
74                        .ok_or_else(|| args_error("draft-split: missing account"))?;
75                let commodity_id =
76                    read_entity_string_field(caller, commodity_arg, EntityKind::Commodity, "id")?
77                        .ok_or_else(|| args_error("draft-split: missing commodity"))?;
78                let (value_num, value_denom) = read_ratio_arg(caller, amount_arg)?
79                    .ok_or_else(|| args_error("draft-split: missing amount"))?;
80                // Return the split's index as the handle a template passes to
81                // `draft-split-tag` to tag this specific split. Reject the absurd
82                // >i32::MAX case BEFORE inserting so a failed call never leaves a
83                // partially-mutated draft (and a stale handle can never silently
84                // address the wrong split).
85                let mut index: Option<usize> = None;
86                caller.data().with_draft(|d| {
87                    if i32::try_from(d.split_count()).is_ok() {
88                        index = Some(d.add_split(DraftSplit {
89                            account_id,
90                            commodity_id,
91                            value_num,
92                            value_denom,
93                            tags: Vec::new(),
94                        }));
95                    }
96                })?;
97                let index = index.ok_or_else(|| args_error("draft-split: too many splits"))?;
98                i32::try_from(index).map_err(|_| args_error("draft-split: too many splits"))
99            })
100        },
101    )?;
102    register_native(
103        linker,
104        "template_draft_tag",
105        |caller, (name_arg, value_arg): (StringArg, StringArg)| {
106            Box::pin(async move {
107                let name = read_string_arg(caller, name_arg)?
108                    .ok_or_else(|| args_error("draft-tag: missing name"))?;
109                let value = read_string_arg(caller, value_arg)?
110                    .ok_or_else(|| args_error("draft-tag: missing value"))?;
111                caller
112                    .data()
113                    .with_draft(|d| d.add_tag(DraftTag { name, value }))?;
114                Ok(1)
115            })
116        },
117    )?;
118    register_native(
119        linker,
120        "template_draft_split_tag",
121        |caller, (index_arg, name_arg, value_arg): (i32, StringArg, StringArg)| {
122            Box::pin(async move {
123                let index = usize::try_from(index_arg)
124                    .map_err(|_| args_error("draft-split-tag: split index must be non-negative"))?;
125                let name = read_string_arg(caller, name_arg)?
126                    .ok_or_else(|| args_error("draft-split-tag: missing name"))?;
127                let value = read_string_arg(caller, value_arg)?
128                    .ok_or_else(|| args_error("draft-split-tag: missing value"))?;
129                let mut ok = false;
130                caller
131                    .data()
132                    .with_draft(|d| ok = d.add_split_tag(index, DraftTag { name, value }))?;
133                if !ok {
134                    return Err(args_error(format!(
135                        "draft-split-tag: no draft split at index {index} \
136                         (pass the value returned by draft-split)"
137                    )));
138                }
139                Ok(1)
140            })
141        },
142    )?;
143    Ok(())
144}