1use arete_idl::{
2 normalize_idl_snapshot_v1, IdlAmountDecimalsSource, IdlAmountHint, IdlErrorSnapshot,
3 IdlSnapshotV1, IdlSpec, IdlType, IdlTypeArrayElement, IdlTypeDefinedInner,
4};
5use serde::{Deserialize, Serialize};
6use serde_json::Value;
7use std::collections::{BTreeMap, BTreeSet};
8
9use crate::{
10 canonicalize_jcs, hash_jcs, hash_raw_bytes, HashError, HashId, IdlContent, IdlNormalized,
11 IdlPortable, IdlSource, OssGeneratedProgramReleaseV1, ProgramRelease, ProgramSpec,
12};
13
14pub const PROGRAM_SPEC_SCHEMA_V1: &str = "arete.program-spec/v1";
15
16#[derive(Debug, Clone)]
17pub struct IdlHashes {
18 pub source: HashId<IdlSource>,
19 pub content: HashId<IdlContent>,
20 pub portable: HashId<IdlPortable>,
21 pub normalized: HashId<IdlNormalized>,
22}
23
24#[derive(Debug, Clone)]
26pub struct CanonicalIdlDocument {
27 source_bytes: Vec<u8>,
28 content: Value,
29 portable: Value,
30 idl: IdlSpec,
31 program_id: String,
32 snapshot: IdlSnapshotV1,
33 hashes: IdlHashes,
34}
35
36impl CanonicalIdlDocument {
37 pub fn parse(bytes: &[u8], explicit_program_id: Option<&str>) -> Result<Self, HashError> {
38 let mut content = crate::parse_json_bytes_strict(bytes)?;
39 let source_program_ids = collect_program_ids(&content)?;
40 let source_has_program_id = !source_program_ids.is_empty();
41 let program_id = resolve_program_id(source_program_ids, explicit_program_id)?;
42
43 if !source_has_program_id {
44 content
45 .as_object_mut()
46 .ok_or_else(|| HashError::InvalidIdl("IDL root must be an object".to_string()))?
47 .insert("address".to_string(), Value::String(program_id.clone()));
48 }
49
50 let parser_input = serde_json::to_string(&content)
51 .map_err(|error| HashError::Serialization(error.to_string()))?;
52 let mut idl =
53 arete_idl::parse::parse_idl_content(&parser_input).map_err(HashError::InvalidIdl)?;
54 idl.address = Some(program_id.clone());
55
56 let mut snapshot = normalize_idl_snapshot_v1(&idl);
57 snapshot.snapshot.program_id = Some(program_id.clone());
58 let portable = portable_idl_projection(&content)?;
59 let hashes = IdlHashes {
60 source: hash_raw_bytes(bytes)?,
61 content: hash_jcs(&content)?,
62 portable: hash_jcs(&portable)?,
63 normalized: hash_jcs(&snapshot)?,
64 };
65
66 Ok(Self {
67 source_bytes: bytes.to_vec(),
68 content,
69 portable,
70 idl,
71 program_id,
72 snapshot,
73 hashes,
74 })
75 }
76
77 pub fn source_bytes(&self) -> &[u8] {
78 &self.source_bytes
79 }
80
81 pub fn content_projection(&self) -> &Value {
82 &self.content
83 }
84
85 pub fn portable_projection(&self) -> &Value {
86 &self.portable
87 }
88
89 pub fn parsed_idl(&self) -> &IdlSpec {
90 &self.idl
91 }
92
93 pub fn program_id(&self) -> &str {
94 &self.program_id
95 }
96
97 pub fn normalized_snapshot(&self) -> &IdlSnapshotV1 {
98 &self.snapshot
99 }
100
101 pub fn hashes(&self) -> &IdlHashes {
102 &self.hashes
103 }
104
105 pub fn content_payload(&self) -> Result<Vec<u8>, HashError> {
106 canonicalize_jcs(&self.content)
107 }
108
109 pub fn portable_payload(&self) -> Result<Vec<u8>, HashError> {
110 canonicalize_jcs(&self.portable)
111 }
112
113 pub fn normalized_payload(&self) -> Result<Vec<u8>, HashError> {
114 canonicalize_jcs(&self.snapshot)
115 }
116}
117
118pub fn portable_idl_projection(source: &Value) -> Result<Value, HashError> {
119 let mut portable = source.clone();
120 let object = portable
121 .as_object_mut()
122 .ok_or_else(|| HashError::InvalidIdl("IDL root must be an object".to_string()))?;
123 object.remove("address");
124 object.remove("program_id");
125 if let Some(metadata) = object.get_mut("metadata").and_then(Value::as_object_mut) {
126 metadata.remove("address");
127 }
128 if let Some(program) = object.get_mut("program").and_then(Value::as_object_mut) {
129 program.remove("publicKey");
130 }
131 Ok(portable)
132}
133
134fn collect_program_ids(value: &Value) -> Result<Vec<(&'static str, String)>, HashError> {
135 let object = value
136 .as_object()
137 .ok_or_else(|| HashError::InvalidIdl("IDL root must be an object".to_string()))?;
138 let mut values = Vec::new();
139 collect_program_id(&mut values, "address", object.get("address"))?;
140 collect_program_id(&mut values, "program_id", object.get("program_id"))?;
141 collect_nested_program_id(
142 &mut values,
143 "metadata.address",
144 object.get("metadata"),
145 "address",
146 )?;
147 collect_nested_program_id(
148 &mut values,
149 "program.publicKey",
150 object.get("program"),
151 "publicKey",
152 )?;
153 Ok(values)
154}
155
156fn collect_nested_program_id(
157 output: &mut Vec<(&'static str, String)>,
158 location: &'static str,
159 parent: Option<&Value>,
160 key: &str,
161) -> Result<(), HashError> {
162 match parent {
163 None | Some(Value::Null) => Ok(()),
164 Some(Value::Object(object)) => collect_program_id(output, location, object.get(key)),
165 Some(_) => Err(HashError::InvalidProgramIdLocation { location }),
166 }
167}
168
169fn collect_program_id(
170 output: &mut Vec<(&'static str, String)>,
171 location: &'static str,
172 value: Option<&Value>,
173) -> Result<(), HashError> {
174 match value {
175 None | Some(Value::Null) => Ok(()),
176 Some(Value::String(value)) if value.is_empty() => Ok(()),
177 Some(Value::String(value)) => {
178 output.push((location, value.clone()));
179 Ok(())
180 }
181 Some(_) => Err(HashError::InvalidProgramIdLocation { location }),
182 }
183}
184
185fn resolve_program_id(
186 mut values: Vec<(&'static str, String)>,
187 explicit: Option<&str>,
188) -> Result<String, HashError> {
189 if let Some(explicit) = explicit {
190 if explicit.is_empty() {
191 return Err(HashError::MissingProgramId);
192 }
193 values.push(("explicit", explicit.to_string()));
194 }
195 if values.is_empty() {
196 return Err(HashError::MissingProgramId);
197 }
198
199 let distinct: BTreeSet<&str> = values.iter().map(|(_, value)| value.as_str()).collect();
200 if distinct.len() != 1 {
201 let detail = values
202 .iter()
203 .map(|(location, value)| format!("{location}={value}"))
204 .collect::<Vec<_>>()
205 .join(", ");
206 return Err(HashError::ConflictingProgramIds(detail));
207 }
208 Ok(values.remove(0).1)
209}
210
211#[derive(Debug, Clone, Serialize, Deserialize)]
212#[serde(rename_all = "camelCase")]
213pub struct ProgramSpecV1 {
214 pub schema: String,
215 pub program_id: String,
216 pub idl_content_hash: HashId<IdlContent>,
217 pub portable_idl_hash: HashId<IdlPortable>,
218 pub normalized_idl_hash: HashId<IdlNormalized>,
219 pub idl_snapshot: IdlSnapshotV1,
220 pub pdas: BTreeMap<String, PdaDefinitionV1>,
221 pub instructions: Vec<InstructionDefinitionV1>,
222}
223
224impl ProgramSpecV1 {
225 pub fn from_document(document: &CanonicalIdlDocument) -> Self {
226 let pdas = extract_pdas(document.parsed_idl());
227 let instructions =
228 extract_instructions(document.parsed_idl(), &pdas, document.program_id());
229 Self {
230 schema: PROGRAM_SPEC_SCHEMA_V1.to_string(),
231 program_id: document.program_id.clone(),
232 idl_content_hash: document.hashes.content,
233 portable_idl_hash: document.hashes.portable,
234 normalized_idl_hash: document.hashes.normalized,
235 idl_snapshot: document.snapshot.clone(),
236 pdas,
237 instructions,
238 }
239 }
240
241 pub fn hash(&self) -> Result<HashId<ProgramSpec>, HashError> {
242 self.validate()?;
243 hash_jcs(self)
244 }
245
246 pub fn validate(&self) -> Result<(), HashError> {
247 if self.schema != PROGRAM_SPEC_SCHEMA_V1 {
248 return Err(HashError::UnknownVersion(self.schema.clone()));
249 }
250 if self.idl_snapshot.normalization_version != arete_idl::IDL_NORMALIZATION_VERSION {
251 return Err(HashError::UnknownVersion(format!(
252 "IDL normalization version {}",
253 self.idl_snapshot.normalization_version
254 )));
255 }
256 if self.program_id.is_empty() {
257 return Err(HashError::MissingProgramId);
258 }
259 if self.idl_snapshot.snapshot.program_id.as_deref() != Some(self.program_id.as_str()) {
260 return Err(HashError::InvalidProjection {
261 projection: "program spec",
262 reason: "programId must match idlSnapshot.program_id".to_string(),
263 });
264 }
265 Ok(())
266 }
267
268 pub fn oss_release(&self) -> Result<OssGeneratedProgramReleaseV1, HashError> {
269 Ok(OssGeneratedProgramReleaseV1::new(
270 self.program_id.clone(),
271 self.hash()?,
272 self.idl_content_hash,
273 self.normalized_idl_hash,
274 ))
275 }
276
277 pub fn oss_release_hash(&self) -> Result<HashId<crate::ProgramRelease>, HashError> {
278 self.oss_release()?.hash()
279 }
280
281 pub fn oss_identity(&self) -> Result<OssProgramIdentityV1, HashError> {
282 OssProgramIdentityV1::new(self.clone())
283 }
284}
285
286#[derive(Debug, Clone)]
287pub struct OssProgramIdentityV1 {
288 pub program_spec: ProgramSpecV1,
289 pub program_spec_hash: HashId<ProgramSpec>,
290 pub release: OssGeneratedProgramReleaseV1,
291 pub release_hash: HashId<ProgramRelease>,
292}
293
294impl OssProgramIdentityV1 {
295 pub fn new(program_spec: ProgramSpecV1) -> Result<Self, HashError> {
296 let program_spec_hash = program_spec.hash()?;
297 let release = OssGeneratedProgramReleaseV1::new(
298 program_spec.program_id.clone(),
299 program_spec_hash,
300 program_spec.idl_content_hash,
301 program_spec.normalized_idl_hash,
302 );
303 let release_hash = release.hash()?;
304 Ok(Self {
305 program_spec,
306 program_spec_hash,
307 release,
308 release_hash,
309 })
310 }
311
312 pub fn from_document(document: &CanonicalIdlDocument) -> Result<Self, HashError> {
313 Self::new(ProgramSpecV1::from_document(document))
314 }
315}
316
317pub fn build_program_spec_v1_from_bytes(
318 bytes: &[u8],
319 explicit_program_id: Option<&str>,
320) -> Result<ProgramSpecV1, HashError> {
321 let document = CanonicalIdlDocument::parse(bytes, explicit_program_id)?;
322 Ok(ProgramSpecV1::from_document(&document))
323}
324
325pub fn build_oss_program_identity_v1_from_bytes(
326 bytes: &[u8],
327 explicit_program_id: Option<&str>,
328) -> Result<OssProgramIdentityV1, HashError> {
329 OssProgramIdentityV1::new(build_program_spec_v1_from_bytes(
330 bytes,
331 explicit_program_id,
332 )?)
333}
334
335pub fn build_program_spec_v1_from_idl(
340 idl: &IdlSpec,
341 explicit_program_id: Option<&str>,
342) -> Result<ProgramSpecV1, HashError> {
343 let bytes =
344 serde_json::to_vec(idl).map_err(|error| HashError::Serialization(error.to_string()))?;
345 build_program_spec_v1_from_bytes(&bytes, explicit_program_id)
346}
347
348#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
349pub struct PdaDefinitionV1 {
350 pub name: String,
351 pub seeds: Vec<PdaSeedV1>,
352 #[serde(default, skip_serializing_if = "Option::is_none")]
355 pub program_id: Option<String>,
356 #[serde(default, skip_serializing_if = "Option::is_none")]
359 pub program: Option<PdaProgramV1>,
360}
361
362#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
363#[serde(tag = "type", rename_all = "camelCase")]
364pub enum PdaProgramV1 {
365 AccountRef { account_name: String },
366 ArgRef { arg_name: String },
367}
368
369#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
370#[serde(tag = "type", rename_all = "camelCase")]
371pub enum PdaSeedV1 {
372 Literal {
373 value: String,
374 },
375 Bytes {
376 value: Vec<u8>,
377 },
378 ArgRef {
379 arg_name: String,
380 #[serde(default, skip_serializing_if = "Option::is_none")]
381 arg_type: Option<String>,
382 },
383 AccountRef {
384 account_name: String,
385 },
386}
387
388#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
389#[serde(tag = "category", rename_all = "camelCase")]
390pub enum AccountResolutionV1 {
391 Signer,
392 Known {
393 address: String,
394 },
395 PdaRef {
396 pda_name: String,
397 },
398 PdaInline {
399 seeds: Vec<PdaSeedV1>,
400 #[serde(default, skip_serializing_if = "Option::is_none")]
401 program_id: Option<String>,
402 #[serde(default, skip_serializing_if = "Option::is_none")]
403 program: Option<PdaProgramV1>,
404 },
405 UserProvided,
406}
407
408#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
409pub struct InstructionAccountV1 {
410 pub name: String,
411 #[serde(default)]
412 pub is_signer: bool,
413 #[serde(default)]
414 pub is_writable: bool,
415 pub resolution: AccountResolutionV1,
416 #[serde(default)]
417 pub is_optional: bool,
418 #[serde(default, skip_serializing_if = "Vec::is_empty")]
419 pub docs: Vec<String>,
420}
421
422#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
423#[serde(rename_all = "camelCase")]
424pub struct InstructionAmountHintV1 {
425 pub decimals_source: AmountDecimalsSourceV1,
426}
427
428#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
429#[serde(
430 tag = "kind",
431 rename_all = "camelCase",
432 rename_all_fields = "camelCase"
433)]
434pub enum AmountDecimalsSourceV1 {
435 ArgMint { arg_name: String },
436 ArgDecimals { arg_name: String },
437 KnownAccount { account_name: String },
438 Constant { decimals: u8 },
439}
440
441#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
442pub struct InstructionArgumentV1 {
443 pub name: String,
444 #[serde(rename = "type")]
445 pub arg_type: String,
446 #[serde(default, skip_serializing_if = "Vec::is_empty")]
447 pub docs: Vec<String>,
448 #[serde(default, skip_serializing_if = "Option::is_none")]
449 pub amount_hint: Option<InstructionAmountHintV1>,
450}
451
452fn default_discriminator_size() -> usize {
453 8
454}
455
456#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
457pub struct InstructionDefinitionV1 {
458 pub name: String,
459 pub discriminator: Vec<u8>,
460 #[serde(default = "default_discriminator_size")]
461 pub discriminator_size: usize,
462 pub accounts: Vec<InstructionAccountV1>,
463 pub args: Vec<InstructionArgumentV1>,
464 #[serde(default, skip_serializing_if = "Vec::is_empty")]
465 pub errors: Vec<IdlErrorSnapshot>,
466 #[serde(default, skip_serializing_if = "Option::is_none")]
467 pub program_id: Option<String>,
468 #[serde(default, skip_serializing_if = "Vec::is_empty")]
469 pub docs: Vec<String>,
470}
471
472fn extract_pdas(idl: &IdlSpec) -> BTreeMap<String, PdaDefinitionV1> {
473 let mut pdas = BTreeMap::new();
474 let mut named_pdas = BTreeSet::new();
475 for pda in &idl.pdas {
476 let name = sanitize_identifier(&pda.name);
477 named_pdas.insert(name.clone());
478 pdas.insert(
479 name.clone(),
480 convert_pda(&name, &pda.seeds, pda.program.as_ref()),
481 );
482 }
483 let mut conflicting_account_pdas = BTreeSet::new();
484 for instruction in &idl.instructions {
485 for account in instruction.flattened_accounts() {
486 if let Some(pda) = &account.pda {
487 let name = sanitize_identifier(pda.name.as_deref().unwrap_or(&account.name));
488 if named_pdas.contains(&name) || conflicting_account_pdas.contains(&name) {
489 continue;
490 }
491 let candidate = convert_pda(&name, &pda.seeds, pda.program.as_ref());
492 match pdas.get(&name) {
493 None => {
494 pdas.insert(name, candidate);
495 }
496 Some(existing) if existing == &candidate => {}
497 Some(_) => {
498 pdas.remove(&name);
502 conflicting_account_pdas.insert(name);
503 }
504 }
505 }
506 }
507 }
508 pdas
509}
510
511fn extract_instructions(
512 idl: &IdlSpec,
513 pdas: &BTreeMap<String, PdaDefinitionV1>,
514 program_id: &str,
515) -> Vec<InstructionDefinitionV1> {
516 let uses_steel = idl.instructions.iter().any(|instruction| {
517 instruction.discriminant.is_some() && instruction.discriminator.is_empty()
518 });
519 let discriminator_size = if uses_steel { 1 } else { 8 };
520
521 idl.instructions
522 .iter()
523 .map(|instruction| InstructionDefinitionV1 {
524 name: instruction.name.clone(),
525 discriminator: instruction.get_discriminator(),
526 discriminator_size,
527 accounts: instruction
528 .flattened_accounts()
529 .iter()
530 .map(|account| convert_account(account, pdas))
531 .collect(),
532 args: instruction
533 .args
534 .iter()
535 .map(|argument| InstructionArgumentV1 {
536 name: argument.name.clone(),
537 arg_type: idl_type_to_rust_string(&argument.type_),
538 docs: Vec::new(),
539 amount_hint: argument.amount_hint.as_ref().map(convert_amount_hint),
540 })
541 .collect(),
542 errors: Vec::new(),
543 program_id: Some(program_id.to_string()),
544 docs: instruction.docs.clone(),
545 })
546 .collect()
547}
548
549fn convert_pda(
550 name: &str,
551 seeds: &[arete_idl::IdlPdaSeed],
552 program: Option<&arete_idl::IdlPdaProgram>,
553) -> PdaDefinitionV1 {
554 let seeds = seeds
555 .iter()
556 .map(|seed| match seed {
557 arete_idl::IdlPdaSeed::Const { value } => {
558 if let Ok(value) = String::from_utf8(value.clone()) {
559 PdaSeedV1::Literal { value }
560 } else {
561 PdaSeedV1::Bytes {
562 value: value.clone(),
563 }
564 }
565 }
566 arete_idl::IdlPdaSeed::Account { path, .. } => PdaSeedV1::AccountRef {
567 account_name: sanitize_seed_path(path),
568 },
569 arete_idl::IdlPdaSeed::Arg { path, arg_type } => PdaSeedV1::ArgRef {
570 arg_name: sanitize_seed_path(path),
571 arg_type: arg_type.clone(),
572 },
573 })
574 .collect();
575 let (program_id, program) = match program {
576 Some(arete_idl::IdlPdaProgram::Literal { value, .. }) => (Some(value.clone()), None),
577 Some(arete_idl::IdlPdaProgram::Const { value, .. }) => {
578 (Some(bs58::encode(value).into_string()), None)
579 }
580 Some(arete_idl::IdlPdaProgram::Account { path, .. }) => (
581 None,
582 Some(PdaProgramV1::AccountRef {
583 account_name: sanitize_seed_path(path),
584 }),
585 ),
586 None => (None, None),
587 };
588 PdaDefinitionV1 {
589 name: name.to_string(),
590 seeds,
591 program_id,
592 program,
593 }
594}
595
596fn convert_account(
597 account: &arete_idl::IdlAccountArg,
598 pdas: &BTreeMap<String, PdaDefinitionV1>,
599) -> InstructionAccountV1 {
600 let resolution = if account.is_signer && account.address.is_none() && account.pda.is_none() {
601 AccountResolutionV1::Signer
602 } else if let Some(address) = &account.address {
603 AccountResolutionV1::Known {
604 address: address.clone(),
605 }
606 } else if let Some(pda) = &account.pda {
607 let name = sanitize_identifier(pda.name.as_deref().unwrap_or(&account.name));
608 let converted = convert_pda(&name, &pda.seeds, pda.program.as_ref());
609 if pdas.get(&name) == Some(&converted) {
610 AccountResolutionV1::PdaRef { pda_name: name }
611 } else {
612 AccountResolutionV1::PdaInline {
613 seeds: converted.seeds,
614 program_id: converted.program_id,
615 program: converted.program,
616 }
617 }
618 } else {
619 let name = sanitize_identifier(&account.name);
620 if pdas.contains_key(&name) {
621 AccountResolutionV1::PdaRef { pda_name: name }
622 } else {
623 AccountResolutionV1::UserProvided
624 }
625 };
626 InstructionAccountV1 {
627 name: sanitize_identifier(&account.name),
628 is_signer: account.is_signer,
629 is_writable: account.is_mut,
630 resolution,
631 is_optional: account.optional,
632 docs: account.docs.clone(),
633 }
634}
635
636fn convert_amount_hint(hint: &IdlAmountHint) -> InstructionAmountHintV1 {
637 InstructionAmountHintV1 {
638 decimals_source: match &hint.decimals_source {
639 IdlAmountDecimalsSource::ArgMint { arg_name } => AmountDecimalsSourceV1::ArgMint {
640 arg_name: arg_name.clone(),
641 },
642 IdlAmountDecimalsSource::ArgDecimals { arg_name } => {
643 AmountDecimalsSourceV1::ArgDecimals {
644 arg_name: arg_name.clone(),
645 }
646 }
647 IdlAmountDecimalsSource::KnownAccount { account_name } => {
648 AmountDecimalsSourceV1::KnownAccount {
649 account_name: account_name.clone(),
650 }
651 }
652 IdlAmountDecimalsSource::Constant { decimals } => AmountDecimalsSourceV1::Constant {
653 decimals: *decimals,
654 },
655 },
656 }
657}
658
659fn sanitize_identifier(name: &str) -> String {
660 let mut sanitized = String::new();
661 for character in name.chars() {
662 if character.is_ascii_alphanumeric() || character == '_' {
663 sanitized.push(character);
664 } else if !sanitized.ends_with('_') {
665 sanitized.push('_');
666 }
667 }
668 let sanitized = sanitized.trim_matches('_').to_string();
669 if sanitized.is_empty() {
670 return "value".to_string();
671 }
672 if sanitized
673 .chars()
674 .next()
675 .is_some_and(|character| character.is_ascii_digit())
676 {
677 return format!("_{sanitized}");
678 }
679 sanitized
680}
681
682fn sanitize_seed_path(path: &str) -> String {
683 path.split('.')
684 .map(sanitize_identifier)
685 .collect::<Vec<_>>()
686 .join(".")
687}
688
689fn idl_type_to_rust_string(idl_type: &IdlType) -> String {
690 match idl_type {
691 IdlType::Simple(simple) => match simple.as_str() {
692 "string" => "String".to_string(),
693 "publicKey" | "pubkey" => "solana_pubkey::Pubkey".to_string(),
694 "bytes" => "Vec<u8>".to_string(),
695 other => other.to_string(),
696 },
697 IdlType::Array(array) if array.array.len() == 2 => {
698 match (&array.array[0], &array.array[1]) {
699 (IdlTypeArrayElement::Type(name), IdlTypeArrayElement::Size(size)) => {
700 format!(
701 "[{}; {size}]",
702 idl_type_to_rust_string(&IdlType::Simple(name.clone()))
703 )
704 }
705 (IdlTypeArrayElement::Nested(ty), IdlTypeArrayElement::Size(size)) => {
706 format!("[{}; {size}]", idl_type_to_rust_string(ty))
707 }
708 _ => "Vec<u8>".to_string(),
709 }
710 }
711 IdlType::Array(_) => "Vec<u8>".to_string(),
712 IdlType::Option(option) => format!("Option<{}>", idl_type_to_rust_string(&option.option)),
713 IdlType::Vec(vec_type) => format!("Vec<{}>", idl_type_to_rust_string(&vec_type.vec)),
714 IdlType::HashMap(hash_map) => format!(
715 "std::collections::HashMap<{}, {}>",
716 idl_type_to_rust_string(&hash_map.hash_map.0),
717 idl_type_to_rust_string(&hash_map.hash_map.1)
718 ),
719 IdlType::Defined(defined) => match &defined.defined {
720 IdlTypeDefinedInner::Named { name } => name.clone(),
721 IdlTypeDefinedInner::Simple(simple) => simple.clone(),
722 },
723 }
724}
725
726#[cfg(test)]
727mod tests {
728 use super::*;
729
730 #[test]
731 fn preserves_account_selected_pda_programs() {
732 let definition = convert_pda(
733 "metadata",
734 &[arete_idl::IdlPdaSeed::Const {
735 value: b"metadata".to_vec(),
736 }],
737 Some(&arete_idl::IdlPdaProgram::Account {
738 kind: "account".to_string(),
739 path: "metadata_program".to_string(),
740 }),
741 );
742
743 assert_eq!(definition.program_id, None);
744 assert_eq!(
745 definition.program,
746 Some(PdaProgramV1::AccountRef {
747 account_name: "metadata_program".to_string(),
748 })
749 );
750 }
751
752 #[test]
753 fn keeps_conflicting_account_pdas_inline_per_instruction() {
754 let source = br#"{
755 "address":"11111111111111111111111111111111",
756 "metadata":{"name":"demo","version":"0.1.0","spec":"0.1.0"},
757 "instructions":[
758 {"name":"create","discriminator":[1,0,0,0,0,0,0,0],"accounts":[
759 {"name":"state","pda":{"seeds":[{"kind":"const","value":[99,114,101,97,116,101]}]}}
760 ],"args":[]},
761 {"name":"update","discriminator":[2,0,0,0,0,0,0,0],"accounts":[
762 {"name":"state","pda":{"seeds":[{"kind":"const","value":[117,112,100,97,116,101]}]}}
763 ],"args":[]}
764 ],
765 "accounts":[],"types":[],"events":[],"errors":[]
766 }"#;
767 let document = CanonicalIdlDocument::parse(source, None).unwrap();
768 let spec = ProgramSpecV1::from_document(&document);
769
770 assert!(!spec.pdas.contains_key("state"));
771 for instruction in &spec.instructions {
772 assert!(matches!(
773 &instruction.accounts[0].resolution,
774 AccountResolutionV1::PdaInline { .. }
775 ));
776 }
777 }
778}