Skip to main content

hyperstack_interpreter/
resolvers.rs

1use std::collections::{BTreeMap, HashMap, HashSet};
2use std::sync::OnceLock;
3
4use futures::future::join_all;
5
6use serde::{Deserialize, Serialize};
7use serde_json::Value;
8
9/// Context provided to primary key resolver functions
10pub struct ResolveContext<'a> {
11    #[allow(dead_code)]
12    pub(crate) state_id: u32,
13    pub(crate) slot: u64,
14    pub(crate) signature: String,
15    pub(crate) reverse_lookups:
16        &'a mut std::collections::HashMap<String, crate::vm::PdaReverseLookup>,
17}
18
19impl<'a> ResolveContext<'a> {
20    /// Create a new ResolveContext (primarily for use by generated code)
21    pub fn new(
22        state_id: u32,
23        slot: u64,
24        signature: String,
25        reverse_lookups: &'a mut std::collections::HashMap<String, crate::vm::PdaReverseLookup>,
26    ) -> Self {
27        Self {
28            state_id,
29            slot,
30            signature,
31            reverse_lookups,
32        }
33    }
34
35    /// Try to reverse lookup a PDA address to find the seed value
36    /// This is typically used to find the primary key from a PDA account address
37    pub fn pda_reverse_lookup(&mut self, pda_address: &str) -> Option<String> {
38        let lookup_name = "default_pda_lookup";
39        self.reverse_lookups
40            .get_mut(lookup_name)
41            .and_then(|t| t.lookup(pda_address))
42    }
43
44    pub fn slot(&self) -> u64 {
45        self.slot
46    }
47
48    pub fn signature(&self) -> &str {
49        &self.signature
50    }
51}
52
53/// Result of attempting to resolve a primary key
54pub enum KeyResolution {
55    /// Primary key successfully resolved
56    Found(String),
57
58    /// Queue this update until we see one of these instruction discriminators
59    /// The discriminators identify which instructions can populate the reverse lookup
60    QueueUntil(&'static [u8]),
61
62    /// Skip this update entirely (don't queue)
63    Skip,
64}
65
66/// Context provided to instruction hook functions
67pub struct InstructionContext<'a> {
68    pub(crate) accounts: HashMap<String, String>,
69    #[allow(dead_code)]
70    pub(crate) state_id: u32,
71    pub(crate) reverse_lookup_tx: &'a mut dyn ReverseLookupUpdater,
72    pub(crate) pending_updates: Vec<crate::vm::PendingAccountUpdate>,
73    pub(crate) registers: Option<&'a mut Vec<crate::vm::RegisterValue>>,
74    pub(crate) state_reg: Option<crate::vm::Register>,
75    #[allow(dead_code)]
76    pub(crate) compiled_paths: Option<&'a HashMap<String, crate::metrics_context::CompiledPath>>,
77    pub(crate) instruction_data: Option<&'a serde_json::Value>,
78    pub(crate) slot: Option<u64>,
79    pub(crate) signature: Option<String>,
80    pub(crate) timestamp: Option<i64>,
81    pub(crate) dirty_tracker: crate::vm::DirtyTracker,
82}
83
84pub trait ReverseLookupUpdater {
85    fn update(
86        &mut self,
87        pda_address: String,
88        seed_value: String,
89    ) -> Vec<crate::vm::PendingAccountUpdate>;
90    fn flush_pending(&mut self, pda_address: &str) -> Vec<crate::vm::PendingAccountUpdate>;
91}
92
93#[derive(Debug, Clone, Serialize, Deserialize)]
94pub struct TokenMetadata {
95    pub mint: String,
96    pub name: Option<String>,
97    pub symbol: Option<String>,
98    pub decimals: Option<u8>,
99    pub logo_uri: Option<String>,
100}
101
102#[derive(Debug, Clone, Copy)]
103pub struct ResolverTypeScriptSchema {
104    pub name: &'static str,
105    pub definition: &'static str,
106}
107
108#[derive(Debug, Clone, Copy)]
109pub struct ResolverComputedMethod {
110    pub name: &'static str,
111    pub arg_count: usize,
112}
113
114pub trait ResolverDefinition: Send + Sync {
115    fn name(&self) -> &'static str;
116    fn output_type(&self) -> &'static str;
117    fn computed_methods(&self) -> &'static [ResolverComputedMethod];
118    fn evaluate_computed(
119        &self,
120        method: &str,
121        args: &[Value],
122    ) -> std::result::Result<Value, Box<dyn std::error::Error>>;
123    fn typescript_interface(&self) -> Option<&'static str> {
124        None
125    }
126    fn typescript_schema(&self) -> Option<ResolverTypeScriptSchema> {
127        None
128    }
129    fn extra_output_types(&self) -> &'static [&'static str] {
130        &[]
131    }
132}
133
134pub struct ResolverRegistry {
135    resolvers: BTreeMap<String, Box<dyn ResolverDefinition>>,
136}
137
138impl Default for ResolverRegistry {
139    fn default() -> Self {
140        Self::new()
141    }
142}
143
144impl ResolverRegistry {
145    pub fn new() -> Self {
146        Self {
147            resolvers: BTreeMap::new(),
148        }
149    }
150
151    pub fn register(&mut self, resolver: Box<dyn ResolverDefinition>) {
152        self.resolvers.insert(resolver.name().to_string(), resolver);
153    }
154
155    pub fn resolver(&self, name: &str) -> Option<&dyn ResolverDefinition> {
156        self.resolvers.get(name).map(|resolver| resolver.as_ref())
157    }
158
159    pub fn definitions(&self) -> impl Iterator<Item = &dyn ResolverDefinition> {
160        self.resolvers.values().map(|resolver| resolver.as_ref())
161    }
162
163    pub fn is_output_type(&self, type_name: &str) -> bool {
164        self.resolvers.values().any(|resolver| {
165            resolver.output_type() == type_name
166                || resolver.extra_output_types().contains(&type_name)
167        })
168    }
169
170    pub fn evaluate_computed(
171        &self,
172        resolver: &str,
173        method: &str,
174        args: &[Value],
175    ) -> std::result::Result<Value, Box<dyn std::error::Error>> {
176        let resolver_impl = self
177            .resolver(resolver)
178            .ok_or_else(|| format!("Unknown resolver '{}'", resolver))?;
179
180        let method_spec = resolver_impl
181            .computed_methods()
182            .iter()
183            .find(|spec| spec.name == method)
184            .ok_or_else(|| {
185                format!(
186                    "Resolver '{}' does not provide method '{}'",
187                    resolver, method
188                )
189            })?;
190
191        if method_spec.arg_count != args.len() {
192            return Err(format!(
193                "Resolver '{}' method '{}' expects {} args, got {}",
194                resolver,
195                method,
196                method_spec.arg_count,
197                args.len()
198            )
199            .into());
200        }
201
202        resolver_impl.evaluate_computed(method, args)
203    }
204
205    pub fn validate_computed_expr(
206        &self,
207        expr: &crate::ast::ComputedExpr,
208        errors: &mut Vec<String>,
209    ) {
210        match expr {
211            crate::ast::ComputedExpr::ResolverComputed {
212                resolver,
213                method,
214                args,
215            } => {
216                let resolver_impl = self.resolver(resolver);
217                if resolver_impl.is_none() {
218                    errors.push(format!("Unknown resolver '{}'", resolver));
219                } else if let Some(resolver_impl) = resolver_impl {
220                    let method_spec = resolver_impl
221                        .computed_methods()
222                        .iter()
223                        .find(|spec| spec.name == method);
224                    if let Some(method_spec) = method_spec {
225                        if method_spec.arg_count != args.len() {
226                            errors.push(format!(
227                                "Resolver '{}' method '{}' expects {} args, got {}",
228                                resolver,
229                                method,
230                                method_spec.arg_count,
231                                args.len()
232                            ));
233                        }
234                    } else {
235                        errors.push(format!(
236                            "Resolver '{}' does not provide method '{}'",
237                            resolver, method
238                        ));
239                    }
240                }
241
242                for arg in args {
243                    self.validate_computed_expr(arg, errors);
244                }
245            }
246            crate::ast::ComputedExpr::FieldRef { .. }
247            | crate::ast::ComputedExpr::Literal { .. }
248            | crate::ast::ComputedExpr::None
249            | crate::ast::ComputedExpr::Var { .. }
250            | crate::ast::ComputedExpr::ByteArray { .. }
251            | crate::ast::ComputedExpr::ContextSlot
252            | crate::ast::ComputedExpr::ContextTimestamp => {}
253            crate::ast::ComputedExpr::UnwrapOr { expr, .. }
254            | crate::ast::ComputedExpr::Cast { expr, .. }
255            | crate::ast::ComputedExpr::Paren { expr }
256            | crate::ast::ComputedExpr::Some { value: expr }
257            | crate::ast::ComputedExpr::Slice { expr, .. }
258            | crate::ast::ComputedExpr::Index { expr, .. }
259            | crate::ast::ComputedExpr::U64FromLeBytes { bytes: expr }
260            | crate::ast::ComputedExpr::U64FromBeBytes { bytes: expr }
261            | crate::ast::ComputedExpr::JsonToBytes { expr }
262            | crate::ast::ComputedExpr::Keccak256 { expr }
263            | crate::ast::ComputedExpr::Unary { expr, .. } => {
264                self.validate_computed_expr(expr, errors);
265            }
266            crate::ast::ComputedExpr::Binary { left, right, .. } => {
267                self.validate_computed_expr(left, errors);
268                self.validate_computed_expr(right, errors);
269            }
270            crate::ast::ComputedExpr::MethodCall { expr, args, .. } => {
271                self.validate_computed_expr(expr, errors);
272                for arg in args {
273                    self.validate_computed_expr(arg, errors);
274                }
275            }
276            crate::ast::ComputedExpr::Let { value, body, .. } => {
277                self.validate_computed_expr(value, errors);
278                self.validate_computed_expr(body, errors);
279            }
280            crate::ast::ComputedExpr::If {
281                condition,
282                then_branch,
283                else_branch,
284            } => {
285                self.validate_computed_expr(condition, errors);
286                self.validate_computed_expr(then_branch, errors);
287                self.validate_computed_expr(else_branch, errors);
288            }
289            crate::ast::ComputedExpr::Closure { body, .. } => {
290                self.validate_computed_expr(body, errors);
291            }
292        }
293    }
294}
295
296static BUILTIN_RESOLVER_REGISTRY: OnceLock<ResolverRegistry> = OnceLock::new();
297
298pub fn register_builtin_resolvers(registry: &mut ResolverRegistry) {
299    registry.register(Box::new(SlotHashResolver));
300    registry.register(Box::new(TokenMetadataResolver));
301}
302
303pub fn builtin_resolver_registry() -> &'static ResolverRegistry {
304    BUILTIN_RESOLVER_REGISTRY.get_or_init(|| {
305        let mut registry = ResolverRegistry::new();
306        register_builtin_resolvers(&mut registry);
307        registry
308    })
309}
310
311pub fn evaluate_resolver_computed(
312    resolver: &str,
313    method: &str,
314    args: &[Value],
315) -> std::result::Result<Value, Box<dyn std::error::Error>> {
316    builtin_resolver_registry().evaluate_computed(resolver, method, args)
317}
318
319pub fn validate_resolver_computed_specs(
320    specs: &[crate::ast::ComputedFieldSpec],
321) -> std::result::Result<(), Box<dyn std::error::Error>> {
322    let registry = builtin_resolver_registry();
323    let mut errors = Vec::new();
324
325    for spec in specs {
326        registry.validate_computed_expr(&spec.expression, &mut errors);
327    }
328
329    if errors.is_empty() {
330        Ok(())
331    } else {
332        Err(errors.join("\n").into())
333    }
334}
335
336pub fn is_resolver_output_type(type_name: &str) -> bool {
337    builtin_resolver_registry().is_output_type(type_name)
338}
339
340const DEFAULT_DAS_BATCH_SIZE: usize = 100;
341const DEFAULT_DAS_TIMEOUT_SECS: u64 = 10;
342const DAS_API_ENDPOINT_ENV: &str = "DAS_API_ENDPOINT";
343const DAS_API_BATCH_ENV: &str = "DAS_API_BATCH_SIZE";
344
345pub struct TokenMetadataResolverClient {
346    endpoint: String,
347    client: reqwest::Client,
348    batch_size: usize,
349}
350
351impl TokenMetadataResolverClient {
352    pub fn new(
353        endpoint: String,
354        batch_size: usize,
355    ) -> Result<Self, Box<dyn std::error::Error + Send + Sync>> {
356        let client = reqwest::Client::builder()
357            .timeout(std::time::Duration::from_secs(DEFAULT_DAS_TIMEOUT_SECS))
358            .build()?;
359
360        Ok(Self {
361            endpoint,
362            client,
363            batch_size: batch_size.max(1),
364        })
365    }
366
367    pub fn from_env() -> Result<Option<Self>, Box<dyn std::error::Error + Send + Sync>> {
368        let Some(endpoint) = std::env::var(DAS_API_ENDPOINT_ENV).ok() else {
369            return Ok(None);
370        };
371
372        let batch_size = std::env::var(DAS_API_BATCH_ENV)
373            .ok()
374            .and_then(|value| value.parse::<usize>().ok())
375            .unwrap_or(DEFAULT_DAS_BATCH_SIZE);
376
377        Ok(Some(Self::new(endpoint, batch_size)?))
378    }
379
380    pub async fn resolve_token_metadata(
381        &self,
382        mints: &[String],
383    ) -> Result<HashMap<String, Value>, Box<dyn std::error::Error + Send + Sync>> {
384        let mut unique = HashSet::new();
385        let mut deduped = Vec::new();
386
387        for mint in mints {
388            if mint.is_empty() {
389                continue;
390            }
391            if unique.insert(mint.clone()) {
392                deduped.push(mint.clone());
393            }
394        }
395
396        let mut results = HashMap::new();
397        if deduped.is_empty() {
398            return Ok(results);
399        }
400
401        for chunk in deduped.chunks(self.batch_size) {
402            let assets = self.fetch_assets(chunk).await?;
403            for asset in assets {
404                if let Some((mint, value)) = Self::build_token_metadata(&asset) {
405                    results.insert(mint, value);
406                }
407            }
408        }
409
410        Ok(results)
411    }
412
413    async fn fetch_assets(
414        &self,
415        ids: &[String],
416    ) -> Result<Vec<Value>, Box<dyn std::error::Error + Send + Sync>> {
417        let payload = serde_json::json!({
418            "jsonrpc": "2.0",
419            "id": "1",
420            "method": "getAssetBatch",
421            "params": {
422                "ids": ids,
423                "options": {
424                    "showFungible": true,
425                },
426            },
427        });
428
429        let response = self
430            .client
431            .post(&self.endpoint)
432            .json(&payload)
433            .send()
434            .await?;
435        let response = response.error_for_status()?;
436        let value = response.json::<Value>().await?;
437
438        if let Some(error) = value.get("error") {
439            return Err(format!("Resolver response error: {}", error).into());
440        }
441
442        let assets = value
443            .get("result")
444            .and_then(|result| match result {
445                Value::Array(items) => Some(items.clone()),
446                Value::Object(obj) => obj.get("items").and_then(|items| items.as_array()).cloned(),
447                _ => None,
448            })
449            .ok_or_else(|| "Resolver response missing result".to_string())?;
450
451        let assets = assets.into_iter().filter(|a| !a.is_null()).collect();
452        Ok(assets)
453    }
454
455    fn build_token_metadata(asset: &Value) -> Option<(String, Value)> {
456        let mint = asset
457            .get("id")
458            .and_then(|value| value.as_str())?
459            .to_string();
460
461        let name = asset
462            .pointer("/content/metadata/name")
463            .and_then(|value| value.as_str());
464
465        let symbol = asset
466            .pointer("/content/metadata/symbol")
467            .and_then(|value| value.as_str());
468
469        let token_info = asset
470            .get("token_info")
471            .or_else(|| asset.pointer("/content/token_info"));
472
473        let decimals = token_info
474            .and_then(|info| info.get("decimals"))
475            .and_then(|value| value.as_u64());
476
477        let logo_uri = asset
478            .pointer("/content/links/image")
479            .and_then(|value| value.as_str())
480            .or_else(|| {
481                asset
482                    .pointer("/content/links/image_uri")
483                    .and_then(|value| value.as_str())
484            });
485
486        let mut obj = serde_json::Map::new();
487        obj.insert("mint".to_string(), serde_json::json!(mint));
488        obj.insert(
489            "name".to_string(),
490            name.map(|value| serde_json::json!(value))
491                .unwrap_or(Value::Null),
492        );
493        obj.insert(
494            "symbol".to_string(),
495            symbol
496                .map(|value| serde_json::json!(value))
497                .unwrap_or(Value::Null),
498        );
499        obj.insert(
500            "decimals".to_string(),
501            decimals
502                .map(|value| serde_json::json!(value))
503                .unwrap_or(Value::Null),
504        );
505        obj.insert(
506            "logo_uri".to_string(),
507            logo_uri
508                .map(|value| serde_json::json!(value))
509                .unwrap_or(Value::Null),
510        );
511
512        Some((mint, Value::Object(obj)))
513    }
514}
515
516// ============================================================================
517// URL Resolver Client - Fetch and parse data from external URLs
518// ============================================================================
519
520const DEFAULT_URL_TIMEOUT_SECS: u64 = 30;
521
522pub struct UrlResolverClient {
523    client: reqwest::Client,
524}
525
526impl Default for UrlResolverClient {
527    fn default() -> Self {
528        Self::new()
529    }
530}
531
532impl UrlResolverClient {
533    pub fn new() -> Self {
534        let client = reqwest::Client::builder()
535            .timeout(std::time::Duration::from_secs(DEFAULT_URL_TIMEOUT_SECS))
536            .build()
537            .expect("Failed to create HTTP client for URL resolver");
538
539        Self { client }
540    }
541
542    pub fn with_timeout(timeout_secs: u64) -> Self {
543        let client = reqwest::Client::builder()
544            .timeout(std::time::Duration::from_secs(timeout_secs))
545            .build()
546            .expect("Failed to create HTTP client for URL resolver");
547
548        Self { client }
549    }
550
551    /// Resolve a URL and return the parsed JSON response
552    pub async fn resolve(
553        &self,
554        url: &str,
555        method: &crate::ast::HttpMethod,
556    ) -> Result<Value, Box<dyn std::error::Error + Send + Sync>> {
557        if url.is_empty() {
558            return Err("URL is empty".into());
559        }
560
561        let response = match method {
562            crate::ast::HttpMethod::Get => self.client.get(url).send().await?,
563            crate::ast::HttpMethod::Post => self.client.post(url).send().await?,
564        };
565
566        let response = response.error_for_status()?;
567        let value = response.json::<Value>().await?;
568
569        Ok(value)
570    }
571
572    /// Resolve a URL and extract a specific JSON path from the response
573    pub async fn resolve_with_extract(
574        &self,
575        url: &str,
576        method: &crate::ast::HttpMethod,
577        extract_path: Option<&str>,
578    ) -> Result<Value, Box<dyn std::error::Error + Send + Sync>> {
579        let response = self.resolve(url, method).await?;
580
581        if let Some(path) = extract_path {
582            Self::extract_json_path(&response, path)
583        } else {
584            Ok(response)
585        }
586    }
587
588    /// Extract a value from a JSON object using dot-notation path
589    /// e.g., "data.image" extracts response["data"]["image"]
590    pub fn extract_json_path(
591        value: &Value,
592        path: &str,
593    ) -> Result<Value, Box<dyn std::error::Error + Send + Sync>> {
594        if path.is_empty() {
595            return Ok(value.clone());
596        }
597
598        let mut current = value;
599        for segment in path.split('.') {
600            // Try as object key first
601            if let Some(next) = current.get(segment) {
602                current = next;
603            } else if let Ok(index) = segment.parse::<usize>() {
604                // Try as array index
605                if let Some(next) = current.get(index) {
606                    current = next;
607                } else {
608                    return Err(
609                        format!("Index '{}' out of bounds in path '{}'", index, path).into(),
610                    );
611                }
612            } else {
613                return Err(format!("Key '{}' not found in path '{}'", segment, path).into());
614            }
615        }
616
617        Ok(current.clone())
618    }
619
620    /// Batch resolve multiple URLs in parallel with deduplication.
621    /// Returns raw JSON keyed by method+URL. Identical requests are only fetched once.
622    pub async fn resolve_batch(
623        &self,
624        urls: &[(String, crate::ast::HttpMethod)],
625    ) -> HashMap<(String, crate::ast::HttpMethod), Value> {
626        let mut unique: HashMap<(String, crate::ast::HttpMethod), ()> = HashMap::new();
627        for (url, method) in urls {
628            if !url.is_empty() {
629                unique.entry((url.clone(), method.clone())).or_insert(());
630            }
631        }
632
633        let futures = unique.into_keys().map(|(url, method)| async move {
634            let result = self.resolve(&url, &method).await;
635            ((url, method), result)
636        });
637
638        join_all(futures)
639            .await
640            .into_iter()
641            .filter_map(|((url, method), result)| match result {
642                Ok(value) => Some(((url, method), value)),
643                Err(e) => {
644                    tracing::warn!(url = %url, error = %e, "Failed to resolve URL");
645                    None
646                }
647            })
648            .collect()
649    }
650}
651
652/// Resolver for looking up slot hashes by slot number
653/// Uses the global slot hash cache populated from gRPC stream
654struct SlotHashResolver;
655
656const SLOT_HASH_METHODS: &[ResolverComputedMethod] = &[
657    ResolverComputedMethod {
658        name: "slot_hash",
659        arg_count: 1,
660    },
661    ResolverComputedMethod {
662        name: "keccak_rng",
663        arg_count: 3,
664    },
665];
666
667impl SlotHashResolver {
668    /// Compute keccak256(slot_hash || seed || samples_le_bytes) and XOR-fold into a u64.
669    /// args[0] = slot_hash bytes (JSON array of 32 bytes)
670    /// args[1] = seed bytes (JSON array of 32 bytes)
671    /// args[2] = samples (u64 number)
672    fn evaluate_keccak_rng(args: &[Value]) -> Result<Value, Box<dyn std::error::Error>> {
673        if args.len() != 3 {
674            return Ok(Value::Null);
675        }
676
677        // slot_hash() returns { bytes: [...] }, so extract the bytes array
678        let slot_hash_bytes = match &args[0] {
679            Value::Object(obj) => obj.get("bytes").cloned().unwrap_or(Value::Null),
680            _ => args[0].clone(),
681        };
682        let slot_hash = Self::json_array_to_bytes(&slot_hash_bytes, 32);
683        let seed = Self::json_array_to_bytes(&args[1], 32);
684        let samples = match &args[2] {
685            Value::Number(n) => n.as_u64(),
686            _ => None,
687        };
688
689        let (slot_hash, seed, samples) = match (slot_hash, seed, samples) {
690            (Some(s), Some(sd), Some(sm)) => (s, sd, sm),
691            _ => return Ok(Value::Null),
692        };
693
694        // Build input: slot_hash[32] || seed[32] || samples_le_bytes[8]
695        let mut input = Vec::with_capacity(72);
696        input.extend_from_slice(&slot_hash);
697        input.extend_from_slice(&seed);
698        input.extend_from_slice(&samples.to_le_bytes());
699
700        // keccak256
701        use sha3::{Digest, Keccak256};
702        let hash = Keccak256::digest(&input);
703
704        // XOR-fold four u64 chunks
705        let r1 = u64::from_le_bytes(hash[0..8].try_into()?);
706        let r2 = u64::from_le_bytes(hash[8..16].try_into()?);
707        let r3 = u64::from_le_bytes(hash[16..24].try_into()?);
708        let r4 = u64::from_le_bytes(hash[24..32].try_into()?);
709        let rng = r1 ^ r2 ^ r3 ^ r4;
710
711        Ok(Value::Number(serde_json::Number::from(rng)))
712    }
713
714    /// Extract a byte array of expected length from a JSON array value.
715    fn json_array_to_bytes(value: &Value, expected_len: usize) -> Option<Vec<u8>> {
716        let arr = value.as_array()?;
717        let bytes: Vec<u8> = arr
718            .iter()
719            .filter_map(|v| v.as_u64().and_then(|n| u8::try_from(n).ok()))
720            .collect();
721        if bytes.len() == expected_len {
722            Some(bytes)
723        } else {
724            tracing::debug!(
725                got = bytes.len(),
726                expected = expected_len,
727                "json_array_to_bytes: length mismatch or out-of-range element"
728            );
729            None
730        }
731    }
732
733    fn evaluate_slot_hash(args: &[Value]) -> Result<Value, Box<dyn std::error::Error>> {
734        if args.len() != 1 {
735            return Ok(Value::Null);
736        }
737
738        let slot = match &args[0] {
739            Value::Number(n) => n.as_u64().unwrap_or(0),
740            _ => return Ok(Value::Null),
741        };
742
743        if slot == 0 {
744            return Ok(Value::Null);
745        }
746
747        // Try to get the slot hash from the global cache
748        let slot_hash = crate::slot_hash_cache::get_slot_hash(slot);
749
750        match slot_hash {
751            Some(hash) => {
752                // Convert the base58 encoded slot hash to bytes
753                // The slot hash is a 32-byte value base58 encoded
754                match bs58::decode(&hash).into_vec() {
755                    Ok(bytes) if bytes.len() == 32 => {
756                        // Return as { bytes: [...] } to match the SlotHashBytes TypeScript interface
757                        let json_bytes: Vec<Value> =
758                            bytes.into_iter().map(|b| Value::Number(b.into())).collect();
759                        let mut obj = serde_json::Map::new();
760                        obj.insert("bytes".to_string(), Value::Array(json_bytes));
761                        Ok(Value::Object(obj))
762                    }
763                    _ => {
764                        tracing::warn!(slot = slot, hash = hash, "Failed to decode slot hash");
765                        Ok(Value::Null)
766                    }
767                }
768            }
769            None => {
770                tracing::debug!(slot = slot, "Slot hash not found in cache");
771                Ok(Value::Null)
772            }
773        }
774    }
775}
776
777impl ResolverDefinition for SlotHashResolver {
778    fn name(&self) -> &'static str {
779        "SlotHash"
780    }
781
782    fn output_type(&self) -> &'static str {
783        "SlotHash"
784    }
785
786    fn computed_methods(&self) -> &'static [ResolverComputedMethod] {
787        SLOT_HASH_METHODS
788    }
789
790    fn evaluate_computed(
791        &self,
792        method: &str,
793        args: &[Value],
794    ) -> std::result::Result<Value, Box<dyn std::error::Error>> {
795        match method {
796            "slot_hash" => Self::evaluate_slot_hash(args),
797            "keccak_rng" => Self::evaluate_keccak_rng(args),
798            _ => Err(format!("Unknown SlotHash method '{}'", method).into()),
799        }
800    }
801
802    fn typescript_interface(&self) -> Option<&'static str> {
803        Some(
804            r#"export interface SlotHashBytes {
805  /** 32-byte slot hash as array of numbers (0-255) */
806  bytes: number[];
807}
808
809export type KeccakRngValue = string;"#,
810        )
811    }
812
813    fn extra_output_types(&self) -> &'static [&'static str] {
814        &["SlotHashBytes", "KeccakRngValue"]
815    }
816
817    fn typescript_schema(&self) -> Option<ResolverTypeScriptSchema> {
818        Some(ResolverTypeScriptSchema {
819            name: "SlotHashTypes",
820            definition: r#"export const SlotHashBytesSchema = z.object({
821  bytes: z.array(z.number().int().min(0).max(255)).length(32),
822});
823
824export const KeccakRngValueSchema = z.string();"#,
825        })
826    }
827}
828
829struct TokenMetadataResolver;
830
831const TOKEN_METADATA_METHODS: &[ResolverComputedMethod] = &[
832    ResolverComputedMethod {
833        name: "ui_amount",
834        arg_count: 2,
835    },
836    ResolverComputedMethod {
837        name: "raw_amount",
838        arg_count: 2,
839    },
840];
841
842impl TokenMetadataResolver {
843    fn optional_f64(value: &Value) -> Option<f64> {
844        if value.is_null() {
845            return None;
846        }
847        match value {
848            Value::Number(number) => number.as_f64(),
849            Value::String(text) => text.parse::<f64>().ok(),
850            _ => None,
851        }
852    }
853
854    fn optional_u8(value: &Value) -> Option<u8> {
855        if value.is_null() {
856            return None;
857        }
858        match value {
859            Value::Number(number) => number
860                .as_u64()
861                .or_else(|| {
862                    number
863                        .as_i64()
864                        .and_then(|v| if v >= 0 { Some(v as u64) } else { None })
865                })
866                .and_then(|v| u8::try_from(v).ok()),
867            Value::String(text) => text.parse::<u8>().ok(),
868            _ => None,
869        }
870    }
871
872    fn evaluate_ui_amount(
873        args: &[Value],
874    ) -> std::result::Result<Value, Box<dyn std::error::Error>> {
875        let raw_value = Self::optional_f64(&args[0]);
876        let decimals = Self::optional_u8(&args[1]);
877
878        match (raw_value, decimals) {
879            (Some(value), Some(decimals)) => {
880                let factor = 10_f64.powi(decimals as i32);
881                let result = value / factor;
882                if result.is_finite() {
883                    serde_json::Number::from_f64(result)
884                        .map(Value::Number)
885                        .ok_or_else(|| "Failed to serialize ui_amount".into())
886                } else {
887                    Err("ui_amount result is not finite".into())
888                }
889            }
890            _ => Ok(Value::Null),
891        }
892    }
893
894    fn evaluate_raw_amount(
895        args: &[Value],
896    ) -> std::result::Result<Value, Box<dyn std::error::Error>> {
897        let ui_value = Self::optional_f64(&args[0]);
898        let decimals = Self::optional_u8(&args[1]);
899
900        match (ui_value, decimals) {
901            (Some(value), Some(decimals)) => {
902                let factor = 10_f64.powi(decimals as i32);
903                let result = value * factor;
904                if !result.is_finite() || result < 0.0 {
905                    return Err("raw_amount result is not finite".into());
906                }
907                let rounded = result.round();
908                if rounded > u64::MAX as f64 {
909                    return Err("raw_amount result exceeds u64".into());
910                }
911                Ok(Value::Number(serde_json::Number::from(rounded as u64)))
912            }
913            _ => Ok(Value::Null),
914        }
915    }
916}
917
918impl ResolverDefinition for TokenMetadataResolver {
919    fn name(&self) -> &'static str {
920        "TokenMetadata"
921    }
922
923    fn output_type(&self) -> &'static str {
924        "TokenMetadata"
925    }
926
927    fn computed_methods(&self) -> &'static [ResolverComputedMethod] {
928        TOKEN_METADATA_METHODS
929    }
930
931    fn evaluate_computed(
932        &self,
933        method: &str,
934        args: &[Value],
935    ) -> std::result::Result<Value, Box<dyn std::error::Error>> {
936        match method {
937            "ui_amount" => Self::evaluate_ui_amount(args),
938            "raw_amount" => Self::evaluate_raw_amount(args),
939            _ => Err(format!("Unknown TokenMetadata method '{}'", method).into()),
940        }
941    }
942
943    fn typescript_interface(&self) -> Option<&'static str> {
944        Some(
945            r#"export interface TokenMetadata {
946  mint: string;
947  name?: string | null;
948  symbol?: string | null;
949  decimals?: number | null;
950  logo_uri?: string | null;
951}"#,
952        )
953    }
954
955    fn typescript_schema(&self) -> Option<ResolverTypeScriptSchema> {
956        Some(ResolverTypeScriptSchema {
957            name: "TokenMetadataSchema",
958            definition: r#"export const TokenMetadataSchema = z.object({
959  mint: z.string(),
960  name: z.string().nullable().optional(),
961  symbol: z.string().nullable().optional(),
962  decimals: z.number().nullable().optional(),
963  logo_uri: z.string().nullable().optional(),
964});"#,
965        })
966    }
967}
968
969impl<'a> InstructionContext<'a> {
970    pub fn new(
971        accounts: HashMap<String, String>,
972        state_id: u32,
973        reverse_lookup_tx: &'a mut dyn ReverseLookupUpdater,
974    ) -> Self {
975        Self {
976            accounts,
977            state_id,
978            reverse_lookup_tx,
979            pending_updates: Vec::new(),
980            registers: None,
981            state_reg: None,
982            compiled_paths: None,
983            instruction_data: None,
984            slot: None,
985            signature: None,
986            timestamp: None,
987            dirty_tracker: crate::vm::DirtyTracker::new(),
988        }
989    }
990
991    #[allow(clippy::too_many_arguments)]
992    pub fn with_metrics(
993        accounts: HashMap<String, String>,
994        state_id: u32,
995        reverse_lookup_tx: &'a mut dyn ReverseLookupUpdater,
996        registers: &'a mut Vec<crate::vm::RegisterValue>,
997        state_reg: crate::vm::Register,
998        compiled_paths: &'a HashMap<String, crate::metrics_context::CompiledPath>,
999        instruction_data: &'a serde_json::Value,
1000        slot: Option<u64>,
1001        signature: Option<String>,
1002        timestamp: i64,
1003    ) -> Self {
1004        Self {
1005            accounts,
1006            state_id,
1007            reverse_lookup_tx,
1008            pending_updates: Vec::new(),
1009            registers: Some(registers),
1010            state_reg: Some(state_reg),
1011            compiled_paths: Some(compiled_paths),
1012            instruction_data: Some(instruction_data),
1013            slot,
1014            signature,
1015            timestamp: Some(timestamp),
1016            dirty_tracker: crate::vm::DirtyTracker::new(),
1017        }
1018    }
1019
1020    /// Get an account address by its name from the instruction
1021    pub fn account(&self, name: &str) -> Option<String> {
1022        self.accounts.get(name).cloned()
1023    }
1024
1025    /// Register a reverse lookup: PDA address -> seed value
1026    /// This also flushes any pending account updates for this PDA
1027    ///
1028    /// The pending account updates are accumulated internally and can be retrieved
1029    /// via `take_pending_updates()` after all hooks have executed.
1030    pub fn register_pda_reverse_lookup(&mut self, pda_address: &str, seed_value: &str) {
1031        let pending = self
1032            .reverse_lookup_tx
1033            .update(pda_address.to_string(), seed_value.to_string());
1034        self.pending_updates.extend(pending);
1035    }
1036
1037    /// Take all accumulated pending updates
1038    ///
1039    /// This should be called after all instruction hooks have executed to retrieve
1040    /// any pending account updates that need to be reprocessed.
1041    pub fn take_pending_updates(&mut self) -> Vec<crate::vm::PendingAccountUpdate> {
1042        std::mem::take(&mut self.pending_updates)
1043    }
1044
1045    pub fn dirty_tracker(&self) -> &crate::vm::DirtyTracker {
1046        &self.dirty_tracker
1047    }
1048
1049    pub fn dirty_tracker_mut(&mut self) -> &mut crate::vm::DirtyTracker {
1050        &mut self.dirty_tracker
1051    }
1052
1053    /// Get the current state register value (for generating mutations)
1054    pub fn state_value(&self) -> Option<&serde_json::Value> {
1055        if let (Some(registers), Some(state_reg)) = (self.registers.as_ref(), self.state_reg) {
1056            Some(&registers[state_reg])
1057        } else {
1058            None
1059        }
1060    }
1061
1062    /// Get a field value from the entity state
1063    /// This allows reading aggregated values or other entity fields
1064    pub fn get<T: serde::de::DeserializeOwned>(&self, field_path: &str) -> Option<T> {
1065        if let (Some(registers), Some(state_reg)) = (self.registers.as_ref(), self.state_reg) {
1066            let state = &registers[state_reg];
1067            self.get_nested_value(state, field_path)
1068                .and_then(|v| serde_json::from_value(v.clone()).ok())
1069        } else {
1070            None
1071        }
1072    }
1073
1074    pub fn set<T: serde::Serialize>(&mut self, field_path: &str, value: T) {
1075        if let (Some(registers), Some(state_reg)) = (self.registers.as_mut(), self.state_reg) {
1076            let serialized = serde_json::to_value(value).ok();
1077            if let Some(val) = serialized {
1078                Self::set_nested_value_static(&mut registers[state_reg], field_path, val);
1079                self.dirty_tracker.mark_replaced(field_path);
1080                println!("      ✓ Set field '{}' and marked as dirty", field_path);
1081            }
1082        } else {
1083            println!("      ⚠️  Cannot set field '{}': metrics not configured (registers={}, state_reg={:?})", 
1084                field_path, self.registers.is_some(), self.state_reg);
1085        }
1086    }
1087
1088    pub fn increment(&mut self, field_path: &str, amount: i64) {
1089        let current = self.get::<i64>(field_path).unwrap_or(0);
1090        self.set(field_path, current + amount);
1091    }
1092
1093    pub fn append<T: serde::Serialize>(&mut self, field_path: &str, value: T) {
1094        if let (Some(registers), Some(state_reg)) = (self.registers.as_mut(), self.state_reg) {
1095            let serialized = serde_json::to_value(&value).ok();
1096            if let Some(val) = serialized {
1097                Self::append_to_array_static(&mut registers[state_reg], field_path, val.clone());
1098                self.dirty_tracker.mark_appended(field_path, val);
1099                println!(
1100                    "      ✓ Appended to '{}' and marked as appended",
1101                    field_path
1102                );
1103            }
1104        } else {
1105            println!(
1106                "      ⚠️  Cannot append to '{}': metrics not configured",
1107                field_path
1108            );
1109        }
1110    }
1111
1112    fn append_to_array_static(
1113        value: &mut serde_json::Value,
1114        path: &str,
1115        new_value: serde_json::Value,
1116    ) {
1117        let segments: Vec<&str> = path.split('.').collect();
1118        if segments.is_empty() {
1119            return;
1120        }
1121
1122        let mut current = value;
1123        for segment in &segments[..segments.len() - 1] {
1124            if !current.is_object() {
1125                *current = serde_json::json!({});
1126            }
1127            let obj = current.as_object_mut().unwrap();
1128            current = obj
1129                .entry(segment.to_string())
1130                .or_insert(serde_json::json!({}));
1131        }
1132
1133        let last_segment = segments[segments.len() - 1];
1134        if !current.is_object() {
1135            *current = serde_json::json!({});
1136        }
1137        let obj = current.as_object_mut().unwrap();
1138        let arr = obj
1139            .entry(last_segment.to_string())
1140            .or_insert_with(|| serde_json::json!([]));
1141        if let Some(arr) = arr.as_array_mut() {
1142            arr.push(new_value);
1143        }
1144    }
1145
1146    fn get_nested_value<'b>(
1147        &self,
1148        value: &'b serde_json::Value,
1149        path: &str,
1150    ) -> Option<&'b serde_json::Value> {
1151        let mut current = value;
1152        for segment in path.split('.') {
1153            current = current.get(segment)?;
1154        }
1155        Some(current)
1156    }
1157
1158    fn set_nested_value_static(
1159        value: &mut serde_json::Value,
1160        path: &str,
1161        new_value: serde_json::Value,
1162    ) {
1163        let segments: Vec<&str> = path.split('.').collect();
1164        if segments.is_empty() {
1165            return;
1166        }
1167
1168        let mut current = value;
1169        for segment in &segments[..segments.len() - 1] {
1170            if !current.is_object() {
1171                *current = serde_json::json!({});
1172            }
1173            let obj = current.as_object_mut().unwrap();
1174            current = obj
1175                .entry(segment.to_string())
1176                .or_insert(serde_json::json!({}));
1177        }
1178
1179        if !current.is_object() {
1180            *current = serde_json::json!({});
1181        }
1182        if let Some(obj) = current.as_object_mut() {
1183            obj.insert(segments[segments.len() - 1].to_string(), new_value);
1184        }
1185    }
1186
1187    /// Access instruction data field
1188    pub fn data<T: serde::de::DeserializeOwned>(&self, field: &str) -> Option<T> {
1189        self.instruction_data
1190            .and_then(|data| data.get(field))
1191            .and_then(|v| serde_json::from_value(v.clone()).ok())
1192    }
1193
1194    /// Get the current timestamp
1195    pub fn timestamp(&self) -> i64 {
1196        self.timestamp.unwrap_or(0)
1197    }
1198
1199    /// Get the current slot
1200    pub fn slot(&self) -> Option<u64> {
1201        self.slot
1202    }
1203
1204    /// Get the current signature
1205    pub fn signature(&self) -> Option<&str> {
1206        self.signature.as_deref()
1207    }
1208}