arete-interpreter 0.52.0

AST transformation runtime and VM for Arete streaming pipelines
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
use crate::ast::{
    IdlArrayElementSnapshot, IdlArrayTypeSnapshot, IdlDefinedInnerSnapshot, IdlDefinedTypeSnapshot,
    IdlHashMapTypeSnapshot, IdlOptionTypeSnapshot, IdlSnapshot, IdlTupleTypeSnapshot,
    IdlTypeSnapshot, IdlVecTypeSnapshot, InstructionDef, PdaDefinition, SerializableStackSpec,
    CURRENT_AST_VERSION,
};
use arete_idl as idl_parser;
use std::collections::BTreeMap;

/// What an account read says in an SDK generated offline without a read
/// endpoint: where account reads come from instead.
pub fn offline_program_read_message(program: &str) -> String {
    format!(
        "Program '{program}' has no account read endpoint: this SDK was generated offline. \
         Install the program from the registry (`a4 install program <package>`) and use \
         `a4 dev` for a dev environment, or regenerate with \
         `a4 sdk create --read-endpoint <url>` to read a self-hosted Arete server"
    )
}

/// The wire read descriptor of a program in an SDK generated offline:
/// `local-http` naming `read_endpoint` when one is given, otherwise
/// `unavailable` with [`offline_program_read_message`].
pub fn offline_program_read_descriptor(
    program: &str,
    program_release_hash: &str,
    program_spec_hash: &str,
    read_endpoint: Option<&str>,
) -> serde_json::Value {
    let transport = match read_endpoint {
        Some(endpoint) => serde_json::json!({
            "kind": "local-http",
            "endpointSource": "explicit",
            "endpoint": endpoint,
        }),
        None => serde_json::json!({
            "kind": "unavailable",
            "message": offline_program_read_message(program),
        }),
    };
    serde_json::json!({
        "release": {
            "programReleaseHash": program_release_hash,
            "programSpecHash": program_spec_hash,
        },
        "transport": transport,
    })
}

pub fn build_program_only_stack_spec_from_idl(
    idl: &idl_parser::IdlSpec,
    stack_name: &str,
) -> SerializableStackSpec {
    let program_spec = build_program_spec_v1_from_idl(idl)
        .expect("IDL program identity must be valid for ProgramSpecV1");
    build_program_only_stack_spec_from_program_spec(program_spec, stack_name)
}

pub fn build_program_spec_v1_from_idl(
    idl: &idl_parser::IdlSpec,
) -> Result<arete_hash::ProgramSpecV1, arete_hash::HashError> {
    arete_hash::build_program_spec_v1_from_idl(idl, None)
}

pub fn build_program_spec_v1_from_idl_bytes(
    bytes: &[u8],
    explicit_program_id: Option<&str>,
) -> Result<arete_hash::ProgramSpecV1, arete_hash::HashError> {
    arete_hash::build_program_spec_v1_from_bytes(bytes, explicit_program_id)
}

pub fn build_oss_program_identity_v1_from_idl(
    idl: &idl_parser::IdlSpec,
) -> Result<arete_hash::OssProgramIdentityV1, arete_hash::HashError> {
    arete_hash::OssProgramIdentityV1::new(build_program_spec_v1_from_idl(idl)?)
}

pub fn build_oss_program_identity_v1_from_idl_bytes(
    bytes: &[u8],
    explicit_program_id: Option<&str>,
) -> Result<arete_hash::OssProgramIdentityV1, arete_hash::HashError> {
    arete_hash::build_oss_program_identity_v1_from_bytes(bytes, explicit_program_id)
}

pub fn build_program_only_stack_spec_from_idl_bytes(
    bytes: &[u8],
    explicit_program_id: Option<&str>,
    stack_name: &str,
) -> Result<SerializableStackSpec, arete_hash::HashError> {
    let program_spec = build_program_spec_v1_from_idl_bytes(bytes, explicit_program_id)?;
    Ok(build_program_only_stack_spec_from_program_spec(
        program_spec,
        stack_name,
    ))
}

pub fn build_program_only_stack_spec_from_program_spec(
    program_spec: arete_hash::ProgramSpecV1,
    stack_name: &str,
) -> SerializableStackSpec {
    build_program_only_stack_spec_from_program_spec_ref(&program_spec, stack_name)
}

pub fn build_program_only_stack_spec_from_identity(
    identity: &arete_hash::OssProgramIdentityV1,
    stack_name: &str,
) -> SerializableStackSpec {
    build_program_only_stack_spec_from_program_spec_ref(&identity.program_spec, stack_name)
}

fn build_program_only_stack_spec_from_program_spec_ref(
    program_spec: &arete_hash::ProgramSpecV1,
    stack_name: &str,
) -> SerializableStackSpec {
    let snapshot = program_spec.idl_snapshot.clone().into_legacy_snapshot();
    let program_id = Some(program_spec.program_id.clone());
    let pdas: BTreeMap<String, PdaDefinition> =
        transcode_program_projection(program_spec.pdas.clone());
    let instructions: Vec<InstructionDef> =
        transcode_program_projection(program_spec.instructions.clone());

    let mut grouped_pdas = BTreeMap::new();
    if !pdas.is_empty() {
        grouped_pdas.insert(snapshot.name.clone(), pdas);
    }

    SerializableStackSpec {
        ast_version: CURRENT_AST_VERSION.to_string(),
        stack_name: stack_name.to_string(),
        program_ids: program_id.into_iter().collect(),
        idls: vec![snapshot],
        program_specs: vec![program_spec.clone()],
        entities: vec![],
        pdas: grouped_pdas,
        instructions,
        content_hash: None,
    }
    .with_content_hash()
}

/// The PDAs a ProgramSpec declares, in the generator's AST shape.
pub(crate) fn program_spec_pdas(
    program_spec: &arete_hash::ProgramSpecV1,
) -> BTreeMap<String, PdaDefinition> {
    transcode_program_projection(program_spec.pdas.clone())
}

fn transcode_program_projection<T, U>(value: T) -> U
where
    T: serde::Serialize,
    U: serde::de::DeserializeOwned,
{
    serde_json::from_value(
        serde_json::to_value(value).expect("shared ProgramSpec projection must serialize"),
    )
    .expect("shared ProgramSpec projection must match the legacy AST adapter")
}

pub fn convert_idl_to_snapshot(idl: &idl_parser::IdlSpec) -> IdlSnapshot {
    arete_idl::normalize_idl_snapshot(idl)
}

pub fn convert_idl_type(idl_type: &idl_parser::IdlType) -> IdlTypeSnapshot {
    match idl_type {
        idl_parser::IdlType::Simple(simple) => IdlTypeSnapshot::Simple(simple.clone()),
        idl_parser::IdlType::Array(array) => IdlTypeSnapshot::Array(IdlArrayTypeSnapshot {
            array: array
                .array
                .iter()
                .map(|element| match element {
                    idl_parser::IdlTypeArrayElement::Nested(ty) => {
                        IdlArrayElementSnapshot::Type(convert_idl_type(ty))
                    }
                    idl_parser::IdlTypeArrayElement::Type(type_name) => {
                        IdlArrayElementSnapshot::TypeName(type_name.clone())
                    }
                    idl_parser::IdlTypeArrayElement::Size(size) => {
                        IdlArrayElementSnapshot::Size(*size)
                    }
                })
                .collect(),
        }),
        idl_parser::IdlType::Option(option) => IdlTypeSnapshot::Option(IdlOptionTypeSnapshot {
            option: Box::new(convert_idl_type(&option.option)),
        }),
        idl_parser::IdlType::Vec(vec_type) => IdlTypeSnapshot::Vec(IdlVecTypeSnapshot {
            vec: Box::new(convert_idl_type(&vec_type.vec)),
            length_prefix: vec_type.length_prefix,
        }),
        idl_parser::IdlType::String(string) => {
            IdlTypeSnapshot::String(arete_idl::snapshot::IdlStringTypeSnapshot {
                string: string.string,
                length_prefix: string.length_prefix,
            })
        }
        idl_parser::IdlType::Defined(defined) => IdlTypeSnapshot::Defined(IdlDefinedTypeSnapshot {
            defined: match &defined.defined {
                idl_parser::IdlTypeDefinedInner::Named { name } => {
                    IdlDefinedInnerSnapshot::Named { name: name.clone() }
                }
                idl_parser::IdlTypeDefinedInner::Simple(simple) => {
                    IdlDefinedInnerSnapshot::Simple(simple.clone())
                }
            },
        }),
        idl_parser::IdlType::HashMap(hash_map) => {
            IdlTypeSnapshot::HashMap(IdlHashMapTypeSnapshot {
                hash_map: (
                    Box::new(convert_idl_type(&hash_map.hash_map.0)),
                    Box::new(convert_idl_type(&hash_map.hash_map.1)),
                ),
            })
        }
        idl_parser::IdlType::Tuple(tuple) => IdlTypeSnapshot::Tuple(IdlTupleTypeSnapshot {
            tuple: tuple.tuple.iter().map(convert_idl_type).collect(),
        }),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::ast::{AmountDecimalsSource, InstructionAmountHint, PdaSeedDef};

    #[test]
    fn builds_program_only_stack_spec_from_raw_idl() {
        let idl = arete_idl::parse::parse_idl_content(
            r#"{
              "address": "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA",
              "version": "0.0.0",
              "name": "token",
              "instructions": [
                {
                  "name": "InitializeMint2",
                  "accounts": [
                    { "name": "mint", "isMut": true, "isSigner": false }
                  ],
                  "args": [
                    { "name": "decimals", "type": "u8" },
                    { "name": "mintAuthority", "type": "publicKey" }
                  ],
                  "discriminant": { "type": "u8", "value": 20 }
                }
              ],
              "accounts": [],
              "types": [],
              "events": [],
              "errors": []
            }"#,
        )
        .expect("IDL should parse");

        let spec = build_program_only_stack_spec_from_idl(&idl, "SplToken");
        assert_eq!(spec.stack_name, "SplToken");
        assert!(spec.entities.is_empty());
        assert_eq!(spec.idls.len(), 1);
        assert_eq!(spec.instructions.len(), 1);
        assert_eq!(spec.instructions[0].name, "InitializeMint2");
        assert_eq!(spec.instructions[0].discriminator, vec![20]);
        assert_eq!(spec.instructions[0].discriminator_size, 1);
        assert_eq!(
            spec.instructions[0].program_id.as_deref(),
            Some("TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA")
        );
        assert_eq!(
            spec.instructions[0].args[1].arg_type,
            "solana_pubkey::Pubkey"
        );
        assert!(spec.content_hash.is_some());
    }

    #[test]
    fn preserves_nested_seed_paths_when_building_program_only_specs() {
        let idl = arete_idl::parse::parse_idl_content(
            r#"{
              "address": "Prog111111111111111111111111111111111111111",
              "version": "0.0.0",
              "name": "demo",
              "instructions": [
                {
                  "name": "proposalCreate",
                  "accounts": [
                    {
                      "name": "proposal",
                      "isMut": true,
                      "isSigner": false,
                      "pda": {
                        "name": "proposal",
                        "seeds": [
                          {
                            "kind": "arg",
                            "path": "args.transactionIndex",
                            "type": "u64"
                          }
                        ]
                      }
                    }
                  ],
                  "args": [
                    {
                      "name": "args",
                      "type": {
                        "defined": {
                          "name": "ProposalArgs"
                        }
                      }
                    }
                  ],
                  "discriminant": { "type": "u8", "value": 3 }
                }
              ],
              "accounts": [],
              "types": [
                {
                  "name": "ProposalArgs",
                  "type": {
                    "kind": "struct",
                    "fields": [
                      { "name": "transactionIndex", "type": "u64" }
                    ]
                  }
                }
              ],
              "events": [],
              "errors": []
            }"#,
        )
        .expect("IDL should parse");

        let spec = build_program_only_stack_spec_from_idl(&idl, "Demo");
        let pda = spec
            .pdas
            .get("demo")
            .and_then(|program| program.get("proposal"))
            .expect("proposal PDA should be present");
        assert_eq!(
            pda.seeds,
            vec![PdaSeedDef::ArgRef {
                arg_name: "args.transactionIndex".to_string(),
                arg_type: Some("u64".to_string()),
            }]
        );
    }

    #[test]
    fn preserves_amount_hints_from_idl_args() {
        let idl = arete_idl::parse::parse_idl_content(
            r#"{
              "address": "Prog111111111111111111111111111111111111111",
              "version": "0.0.0",
              "name": "demo",
              "instructions": [
                {
                  "name": "deposit",
                  "accounts": [],
                  "args": [
                    {
                      "name": "amount",
                      "type": "u64",
                      "amountHint": {
                        "decimalsSource": {
                          "kind": "argMint",
                          "argName": "mint"
                        }
                      }
                    },
                    {
                      "name": "mint",
                      "type": "publicKey"
                    }
                  ],
                  "discriminant": { "type": "u8", "value": 7 }
                }
              ],
              "accounts": [],
              "types": [],
              "events": [],
              "errors": []
            }"#,
        )
        .expect("IDL should parse");

        let spec = build_program_only_stack_spec_from_idl(&idl, "Demo");
        assert_eq!(
            spec.instructions[0].args[0].amount_hint,
            Some(InstructionAmountHint {
                decimals_source: AmountDecimalsSource::ArgMint {
                    arg_name: "mint".to_string(),
                },
            })
        );
        assert!(spec.idls[0].instructions[0].args[0].amount_hint.is_some());
    }

    #[test]
    fn derives_the_checked_in_program_and_release_identities() {
        let corpus: serde_json::Value =
            serde_json::from_str(include_str!("../../test-vectors/hash-v1.json"))
                .expect("vector corpus");
        let vector = corpus["idlVectors"]
            .as_array()
            .unwrap()
            .iter()
            .find(|vector| vector["id"] == "idl-primary")
            .expect("primary IDL vector");
        let source = vector["input"]["data"].as_str().unwrap().as_bytes();

        let identity = build_oss_program_identity_v1_from_idl_bytes(source, None)
            .expect("interpreter identity");
        let stack_spec = build_program_only_stack_spec_from_identity(&identity, "Demo");

        assert_eq!(
            identity.program_spec_hash.to_string(),
            vector["expected"]["programSpecIdentity"]["hashId"]
        );
        assert_eq!(
            identity.release_hash.to_string(),
            vector["expected"]["ossReleaseIdentity"]["hashId"]
        );
        assert_eq!(stack_spec.content_hash.as_deref().unwrap().len(), 64);
        assert_eq!(stack_spec.program_specs.len(), 1);
        assert_eq!(
            stack_spec.program_specs[0].hash().unwrap(),
            identity.program_spec_hash
        );
        assert!(stack_spec
            .content_hash
            .as_deref()
            .unwrap()
            .bytes()
            .all(|byte| byte.is_ascii_hexdigit() && !byte.is_ascii_uppercase()));
        assert_eq!(
            stack_spec.content_hash.as_deref(),
            Some(stack_spec.compute_content_hash().as_str())
        );
    }
}