tx3_lang/
backend.rs

1use std::collections::HashSet;
2
3use crate::{applying, ir, UtxoRef, UtxoSet};
4
5#[derive(Debug, thiserror::Error)]
6pub enum Error {
7    #[error("transient error: {0}")]
8    TransientError(String),
9
10    #[error("store error: {0}")]
11    StoreError(String),
12
13    #[error("invalid pattern: {0}")]
14    InvalidPattern(String),
15
16    #[error("utxo not found: {0:?}")]
17    UtxoNotFound(UtxoRef),
18
19    #[error("error coercing {0} into {1}")]
20    CoerceError(String, String),
21
22    #[error("consistency error: {0}")]
23    ConsistencyError(String),
24
25    #[error("arg '{0}' not assigned")]
26    ArgNotAssigned(String),
27
28    #[error("format error {0}")]
29    FormatError(String),
30
31    #[error("missing expression: {0}")]
32    MissingExpression(String),
33
34    #[error("value overflow: {0}")]
35    ValueOverflow(String),
36
37    #[error("no AST analysis performed")]
38    NoAstAnalysis,
39
40    #[error("can't resolve symbol '{0}'")]
41    CantResolveSymbol(String),
42
43    #[error("can't reduce {0:?}")]
44    CantReduce(ir::CompilerOp),
45}
46
47#[derive(Debug, PartialEq)]
48pub struct TxEval {
49    pub payload: Vec<u8>,
50    pub hash: Vec<u8>,
51    pub fee: u64,
52    pub ex_units: u64,
53}
54
55pub trait Compiler {
56    fn compile(&mut self, tx: &ir::Tx) -> Result<TxEval, Error>;
57    fn execute(&self, op: ir::CompilerOp) -> Result<ir::Expression, Error>;
58}
59
60impl<C: Compiler> ir::Visitor for C {
61    fn reduce(&mut self, expr: ir::Expression) -> Result<ir::Expression, applying::Error> {
62        match expr {
63            ir::Expression::EvalCompiler(op) => Ok(self.execute(*op)?),
64            _ => Ok(expr),
65        }
66    }
67}
68
69pub enum UtxoPattern<'a> {
70    ByAddress(&'a [u8]),
71    ByAssetPolicy(&'a [u8]),
72    ByAsset(&'a [u8], &'a [u8]),
73}
74
75impl<'a> UtxoPattern<'a> {
76    pub fn by_address(address: &'a [u8]) -> Self {
77        Self::ByAddress(address)
78    }
79
80    pub fn by_asset_policy(policy: &'a [u8]) -> Self {
81        Self::ByAssetPolicy(policy)
82    }
83
84    pub fn by_asset(policy: &'a [u8], name: &'a [u8]) -> Self {
85        Self::ByAsset(policy, name)
86    }
87}
88
89#[trait_variant::make(Send)]
90pub trait UtxoStore {
91    async fn narrow_refs(&self, pattern: UtxoPattern) -> Result<HashSet<UtxoRef>, Error>;
92    async fn fetch_utxos(&self, refs: HashSet<UtxoRef>) -> Result<UtxoSet, Error>;
93}