Skip to main content

txtx_addon_network_svm/
functions.rs

1use std::path::PathBuf;
2
3use crate::{codec::utils::get_seeds_from_value, typing::anchor::types::Idl};
4
5use crate::constants::{DEFAULT_NATIVE_TARGET_PATH, DEFAULT_SHANK_IDL_PATH};
6use solana_pubkey::Pubkey;
7use solana_sdk_ids::system_program;
8use spl_associated_token_account_interface::instruction::create_associated_token_account_idempotent;
9use spl_token_2022_interface::inline_spl_token;
10use txtx_addon_kit::types::{
11    diagnostics::Diagnostic,
12    functions::{
13        arg_checker_with_ctx, fn_diag_with_ctx, FunctionImplementation, FunctionSpecification,
14    },
15    types::{ObjectType, Type, Value},
16    AuthorizationContext,
17};
18
19use crate::{
20    codec::{anchor::AnchorProgramArtifacts, idl::IdlRef, native::NativeProgramArtifacts},
21    constants::{DEFAULT_ANCHOR_TARGET_PATH, NAMESPACE},
22    typing::{
23        SvmValue, ANCHOR_PROGRAM_ARTIFACTS, CLASSIC_RUST_PROGRAM_ARTIFACTS, PDA_RESULT, SVM_IDL,
24        SVM_PUBKEY,
25    },
26};
27
28pub const LAMPORTS_PER_SOL: u64 = 1_000_000_000;
29
30const LAMPORTS_PER_SOL_F64: f64 = LAMPORTS_PER_SOL as f64;
31
32pub fn sol_to_lamports(sol: f64) -> u64 {
33    (sol * LAMPORTS_PER_SOL_F64).round() as u64
34}
35
36pub fn lamports_to_sol(lamports: u64) -> f64 {
37    lamports as f64 / LAMPORTS_PER_SOL_F64
38}
39
40pub fn arg_checker(fn_spec: &FunctionSpecification, args: &Vec<Value>) -> Result<(), Diagnostic> {
41    let checker = arg_checker_with_ctx(NAMESPACE.to_string());
42    checker(fn_spec, args)
43}
44pub fn to_diag<T: ToString>(fn_spec: &FunctionSpecification, e: T) -> Diagnostic {
45    let error_fn = fn_diag_with_ctx(NAMESPACE.to_string());
46    error_fn(fn_spec, e.to_string())
47}
48
49lazy_static! {
50    pub static ref FUNCTIONS: Vec<FunctionSpecification> = vec![
51        define_function! {
52            SystemProgramId => {
53                name: "system_program_id",
54                documentation: "`svm::system_program_id` returns the id of the system program, `11111111111111111111111111111111`.",
55                example: indoc! {r#"
56                    output "system_program_id" { 
57                        value = svm::system_program_id()
58                    }
59                    // > 11111111111111111111111111111111
60                "#},
61                inputs: [
62                ],
63                output: {
64                    documentation: "The system program id.",
65                    typing: Type::addon(SVM_PUBKEY.into())
66                },
67            }
68        },
69        define_function! {
70            DefaultPubkey => {
71                name: "default_pubkey",
72                documentation: "`svm::default_pubkey` returns a default public key, `11111111111111111111111111111111`.",
73                example: indoc! {r#"
74                    output "default_pubkey" { 
75                        value = svm::default_pubkey()
76                    }
77                    // > 11111111111111111111111111111111
78                "#},
79                inputs: [
80                ],
81                output: {
82                    documentation: "The default public key, `11111111111111111111111111111111`",
83                    typing: Type::addon(SVM_PUBKEY.into())
84                },
85            }
86        },
87        define_function! {
88            GetInstructionDataFromIdlPath => {
89                name: "get_instruction_data_from_idl_path",
90                documentation: "`svm::get_instruction_data_from_idl_path` creates encoded instruction data for a program invocation, providing type checking and serialization based on the provided IDL file.",
91                example: indoc! {r#"
92                    output "data" {
93                        value = svm::get_instruction_data_from_idl("/path/to/idl.json", "my_instruction", ["arg1", "arg2"])
94                    }
95                    // > data: 0x95763bdcc47fa1b305000000776f726c64
96                "#},
97                inputs: [
98                    idl_path: {
99                        documentation: "The path, relative to the txtx.yml, to the IDL `.json` file.",
100                        typing: vec![Type::string()],
101                        optional: false
102                    },
103                    instruction_name: {
104                        documentation: "The name of the instruction to generate data for, as indexed by the IDL.",
105                        typing: vec![Type::string()],
106                        optional: false
107                    },
108                    arguments: {
109                        documentation: "The instruction arguments to generate data for.",
110                        typing: vec![Type::array(Type::string())],
111                        optional: true
112                    }
113                ],
114                output: {
115                    documentation: "The encoded instruction data.",
116                    typing: Type::buffer()
117                },
118            }
119        },
120        define_function! {
121            GetInstructionDataFromIdl => {
122                name: "get_instruction_data_from_idl",
123                documentation: "`svm::get_instruction_data_from_idl_path` creates encoded instruction data for a program invocation, providing type checking and serialization based on the provided IDL data.",
124                example: indoc! {r#"
125                    output "data" {
126                        value = svm::get_instruction_data_from_idl(variable.idl, "my_instruction", ["arg1", "arg2"])
127                    }
128                    // > data: 0x95763bdcc47fa1b305000000776f726c64
129                "#},
130                inputs: [
131                    idl: {
132                        documentation: "The program IDL.",
133                        typing: vec![Type::addon(SVM_IDL), Type::string()],
134                        optional: false
135                    },
136                    instruction_name: {
137                        documentation: "The name of the instruction to generate data for, as indexed by the IDL.",
138                        typing: vec![Type::string()],
139                        optional: false
140                    },
141                    arguments: {
142                        documentation: "The instruction arguments to generate data for.",
143                        typing: vec![Type::array(Type::string())],
144                        optional: true
145                    }
146                ],
147                output: {
148                    documentation: "The encoded instruction data.",
149                    typing: Type::buffer()
150                },
151            }
152        },
153        define_function! {
154            GetProgramFromAnchorProject => {
155                name: "get_program_from_anchor_project",
156                documentation: "`svm::get_program_from_anchor_project` retrieves the program deployment artifacts for a program in an Anchor project.",
157                example: indoc! {r#"
158                    variable "contract" {
159                        value = svm::get_program_from_anchor_project("my_program")
160                    }
161                    output "idl" {
162                        value = variable.contract.idl
163                    }    
164                "#},
165                inputs: [
166                    program_name: {
167                        documentation: "The name of the program being deployed.",
168                        typing: vec![Type::string()],
169                        optional: false
170                    },
171                    keypair_path: {
172                        documentation: "The location of the program keypair file. Defaults to `./target/deploy/<program_name>-keypair.json`.",
173                        typing: vec![Type::string(), Type::null()],
174                        optional: true
175                    },
176                    idl_path: {
177                        documentation: "The location of the program IDL file. Defaults to `./target/idl/<program_name>.json`.",
178                        typing: vec![Type::string(), Type::null()],
179                        optional: true
180                    },
181                    bin_path: {
182                        documentation: "The location of the program binary file. Defaults to `./target/deploy/<program_name>.so`.",
183                        typing: vec![Type::string(), Type::null()],
184                        optional: true
185                    }
186                ],
187                output: {
188                    documentation: "An object containing the anchor program artifacts.",
189                    typing: ANCHOR_PROGRAM_ARTIFACTS.clone()
190                },
191            }
192        },
193        define_function! {
194            GetProgramFromNativeProject => {
195                name: "get_program_from_native_project",
196                documentation: "`svm::get_program_from_native_project` retrieves the program deployment artifacts for a non-Anchor program.",
197                example: indoc! {r#"
198                    variable "contract" {
199                        value = svm::get_program_from_native_project("my_program")
200                    }
201                    output "idl" {
202                        value = variable.contract.idl
203                    }
204                "#},
205                inputs: [
206                    program_name: {
207                        documentation: "The name of the program being deployed.",
208                        typing: vec![Type::string()],
209                        optional: false
210                    },
211                    keypair_path: {
212                        documentation: "The location of the program keypair file. Defaults to `./target/deploy/<program_name>-keypair.json`.",
213                        typing: vec![Type::string(), Type::null()],
214                        optional: true
215                    },
216                    idl_path: {
217                        documentation: "The location of the program IDL file. Defaults to `./idl/<program_name>.json`.",
218                        typing: vec![Type::string(), Type::null()],
219                        optional: true
220                    },
221                    bin_path: {
222                        documentation: "The location of the program binary file. Defaults to `./target/deploy/<program_name>.so`.",
223                        typing: vec![Type::string(), Type::null()],
224                        optional: true
225                    }
226                ],
227                output: {
228                    documentation: "An object containing the native program artifacts.",
229                    typing: CLASSIC_RUST_PROGRAM_ARTIFACTS.clone()
230                },
231            }
232        },
233        define_function! {
234            SolToLamports => {
235                name: "sol_to_lamports",
236                documentation: "`svm::sol_to_lamports` converts the provided SOL amount to lamports.",
237                example: indoc! {r#"
238                    output "lamports" {
239                        value = svm::sol_to_lamports(1.1)
240                    }
241                    // lamports: 1100000000
242                "#},
243                inputs: [
244                    sol_amount: {
245                        documentation: "The amount of SOL to convert to lamports.",
246                        typing: vec![Type::integer(), Type::float()],
247                        optional: false
248                    }
249                ],
250                output: {
251                    documentation: "The amount of SOL provided, represented as lamports.",
252                    typing: Type::integer()
253                },
254            }
255        },
256        define_function! {
257            LamportsToSol => {
258                name: "lamports_to_sol",
259                documentation: "`svm::lamports_to_sol` converts the provided number of lamports amount to SOL.",
260                example: indoc! {r#"
261                    output "sol" {
262                        value = svm::lamports_to_sol(1100000000)
263                    }
264                    // sol: 1.1
265                "#},
266                inputs: [
267                    lamports_amount: {
268                        documentation: "The amount of lamports to convert to SOL.",
269                        typing: vec![Type::integer()],
270                        optional: false
271                    }
272                ],
273                output: {
274                    documentation: "The number of lamports provided, represented as SOL.",
275                    typing: Type::float()
276                },
277            }
278        },
279        define_function! {
280            FindPda => {
281                name: "find_pda",
282                documentation: "`svm::find_pda` finds a valid pda using the provided program id and seeds.",
283                example: indoc! {r#"
284                    variable "pda" {
285                        value = svm::find_pda("3bv3j4GvMPjvvBX9QdoX27pVoWhDSXpwKZipFF1QiVr6", ["data"])
286                    }
287                    output "pda" {
288                        value = std::encode_base58(variable.pda.pda)
289                    }
290                    output "bump" {
291                        value = variable.pda.bump_seed
292                    }
293                    // > pda: 4amHoWMBgLkPfM8Nq9ZP33Liq9FCuqrLoU1feejkdsUJ
294                    // > bump: 252
295                "#},
296                inputs: [
297                    program_id: {
298                        documentation: "The address of the program the PDA is derived from.",
299                        typing: vec![Type::string(), Type::addon(SVM_PUBKEY.into())],
300                        optional: false
301                    },
302                    seeds: {
303                        documentation: "An optional array of seeds that will be used to derive the PDA. A maximum of 16 seeds can be used, and each seed can have a maximum length of 32 bytes.",
304                        typing: vec![Type::array(Type::string())],
305                        optional: true
306                    }
307                ],
308                output: {
309                    documentation: "An object containing the PDA address and associated bump seed.",
310                    typing: PDA_RESULT.clone()
311                },
312            }
313        },
314        define_function! {
315            GetAssociatedTokenAccount => {
316                name: "get_associated_token_account",
317                documentation: "`svm::get_associated_token_account` computes the address of the associated token account for the provided wallet and token mint addresses.",
318                example: indoc! {r#"
319                    variable "token_account" {
320                        value = svm::get_associated_token_account(signer.caller.address, "So11111111111111111111111111111111111111112", "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA")
321                    }
322                "#},
323                inputs: [
324                    wallet_address: {
325                        documentation: "The address of the wallet to compute the associated token account for.",
326                        typing: vec![Type::string(), Type::addon(SVM_PUBKEY.into())],
327                        optional: false
328                    },
329                    token_mint_address: {
330                        documentation: "The address of the token mint used to compute the token account.",
331                        typing: vec![Type::string(), Type::addon(SVM_PUBKEY.into())],
332                        optional: false
333                    },
334                    token_program_id: {
335                        documentation: "The address of the token program used to compute the token account.",
336                        typing: vec![Type::string(), Type::addon(SVM_PUBKEY.into())],
337                        optional: true
338                    }
339                ],
340                output: {
341                    documentation: "The address of the associated token account.",
342                    typing: Type::addon(SVM_PUBKEY.into())
343                },
344            }
345        },
346        define_function! {
347            CreateTokenAccountInstruction => {
348                name: "create_token_account_instruction",
349                documentation: "`svm::create_token_account_instruction` creates raw instruction bytes to create an associated token account.",
350                example: indoc! {r#"
351                    action "call" "svm::process_instructions" {
352                        signers = [signer.caller]
353
354                        instruction { 
355                            raw_bytes = svm::create_token_account_instruction(
356                                signer.caller.address, // funding address
357                                signer.caller.address, // wallet address
358                                variable.token_mint, // token mint address
359                                variable.token_program // token program id
360                            )
361                        }
362                    }
363                "#},
364                inputs: [
365                    funding_address: {
366                        documentation: "The address of the funding account.",
367                        typing: vec![Type::string(), Type::addon(SVM_PUBKEY.into())],
368                        optional: false
369                    },
370                    wallet_address: {
371                        documentation: "The address of the wallet to compute the associated token account for.",
372                        typing: vec![Type::string(), Type::addon(SVM_PUBKEY.into())],
373                        optional: false
374                    },
375                    token_mint_address: {
376                        documentation: "The address of the token mint used to compute the token account.",
377                        typing: vec![Type::string(), Type::addon(SVM_PUBKEY.into())],
378                        optional: false
379                    },
380                    token_program_id: {
381                        documentation: "The address of the token program used to compute the token account.",
382                        typing: vec![Type::string(), Type::addon(SVM_PUBKEY.into())],
383                        optional: false
384                    }
385                ],
386                output: {
387                    documentation: "The serialized instruction bytes.",
388                    typing: Type::addon(SVM_PUBKEY.into())
389                },
390            }
391        },
392        define_function! {
393            SvmU64 => {
394                name: "u64",
395                documentation: "`svm::u64` creates a byte array representation of a u64 integer, suitable for use as a seed in PDA derivation.",
396                example: indoc! {r#"
397                    variable "u64" {
398                        value = svm::u64(1000000000)
399                    }
400                "#},
401                inputs: [
402                    value: {
403                        documentation: "The u64 integer to convert to a byte array.",
404                        typing: vec![Type::integer()],
405                        optional: false
406                    }
407                ],
408                output: {
409                    documentation: "The byte array representation of the provided u64 integer.",
410                    typing: Type::buffer()
411                },
412            }
413        },
414        define_function! {
415            SvmI64 => {
416                name: "i64",
417                documentation: "`svm::i64` creates a byte array representation of a i64 integer, suitable for use as a seed in PDA derivation.",
418                example: indoc! {r#"
419                    variable "i64" {
420                        value = svm::i64(-1000000000)
421                    }
422                "#},
423                inputs: [
424                    value: {
425                        documentation: "The i64 integer to convert to a byte array.",
426                        typing: vec![Type::integer()],
427                        optional: false
428                    }
429                ],
430                output: {
431                    documentation: "The byte array representation of the provided i64 integer.",
432                    typing: Type::buffer()
433                },
434            }
435        }
436    ];
437}
438
439pub struct SystemProgramId;
440impl FunctionImplementation for SystemProgramId {
441    fn check_instantiability(
442        _fn_spec: &FunctionSpecification,
443        _auth_ctx: &AuthorizationContext,
444        _args: &Vec<Type>,
445    ) -> Result<Type, Diagnostic> {
446        unimplemented!()
447    }
448
449    fn run(
450        fn_spec: &FunctionSpecification,
451        _auth_ctx: &AuthorizationContext,
452        args: &Vec<Value>,
453    ) -> Result<Value, Diagnostic> {
454        arg_checker(fn_spec, args)?;
455        Ok(SvmValue::pubkey(system_program::id().to_bytes().to_vec()))
456    }
457}
458pub struct DefaultPubkey;
459impl FunctionImplementation for DefaultPubkey {
460    fn check_instantiability(
461        _fn_spec: &FunctionSpecification,
462        _auth_ctx: &AuthorizationContext,
463        _args: &Vec<Type>,
464    ) -> Result<Type, Diagnostic> {
465        unimplemented!()
466    }
467
468    fn run(
469        fn_spec: &FunctionSpecification,
470        _auth_ctx: &AuthorizationContext,
471        args: &Vec<Value>,
472    ) -> Result<Value, Diagnostic> {
473        arg_checker(fn_spec, args)?;
474        Ok(SvmValue::pubkey(Pubkey::default().to_bytes().to_vec()))
475    }
476}
477pub struct GetInstructionDataFromIdl;
478impl FunctionImplementation for GetInstructionDataFromIdl {
479    fn check_instantiability(
480        _fn_spec: &FunctionSpecification,
481        _auth_ctx: &AuthorizationContext,
482        _args: &Vec<Type>,
483    ) -> Result<Type, Diagnostic> {
484        unimplemented!()
485    }
486
487    fn run(
488        fn_spec: &FunctionSpecification,
489        _auth_ctx: &AuthorizationContext,
490        args: &Vec<Value>,
491    ) -> Result<Value, Diagnostic> {
492        arg_checker(fn_spec, args)?;
493        // let idl_bytes = &args.get(0).unwrap().as_addon_data().unwrap().bytes;
494        let idl_str = args.get(0).unwrap().as_string().unwrap();
495        let instruction_name = args.get(1).unwrap().as_string().unwrap();
496        let arguments =
497            args.get(2).and_then(|a| Some(a.as_array().unwrap().to_vec())).unwrap_or(vec![]);
498
499        // let idl: Idl = serde_json::from_slice(&idl_bytes)
500        //     .map_err(|e| to_diag(fn_spec, format!("invalid idl: {e}")))?;
501        let idl: Idl = serde_json::from_str(idl_str)
502            .map_err(|e| to_diag(fn_spec, format!("invalid idl: {e}")))?;
503
504        let idl_ref = IdlRef::from_idl(idl);
505
506        let mut data =
507            idl_ref.get_discriminator(&instruction_name).map_err(|e| to_diag(fn_spec, e))?;
508        let mut encoded_args = idl_ref
509            .get_encoded_args(&instruction_name, arguments)
510            .map_err(|e| to_diag(fn_spec, e))?;
511        data.append(&mut encoded_args);
512
513        Ok(Value::buffer(data))
514    }
515}
516
517pub struct GetInstructionDataFromIdlPath;
518impl FunctionImplementation for GetInstructionDataFromIdlPath {
519    fn check_instantiability(
520        _fn_spec: &FunctionSpecification,
521        _auth_ctx: &AuthorizationContext,
522        _args: &Vec<Type>,
523    ) -> Result<Type, Diagnostic> {
524        unimplemented!()
525    }
526
527    fn run(
528        fn_spec: &FunctionSpecification,
529        auth_ctx: &AuthorizationContext,
530        args: &Vec<Value>,
531    ) -> Result<Value, Diagnostic> {
532        arg_checker(fn_spec, args)?;
533        let idl_path_str = args.get(0).unwrap().as_string().unwrap();
534        let instruction_name = args.get(1).unwrap().as_string().unwrap();
535        let arguments =
536            args.get(2).and_then(|a| Some(a.as_array().unwrap().to_vec())).unwrap_or(vec![]);
537
538        let idl_path = auth_ctx
539            .get_file_location_from_path_buf(&PathBuf::from(idl_path_str))
540            .map_err(|e| to_diag(fn_spec, format!("failed to get idl: {e}")))?;
541
542        let idl_ref = IdlRef::from_location(idl_path).map_err(|e| to_diag(fn_spec, e))?;
543        let mut data =
544            idl_ref.get_discriminator(&instruction_name).map_err(|e| to_diag(fn_spec, e))?;
545        let mut encoded_args = idl_ref
546            .get_encoded_args(&instruction_name, arguments)
547            .map_err(|e| to_diag(fn_spec, e))?;
548        data.append(&mut encoded_args);
549
550        Ok(Value::buffer(data))
551    }
552}
553
554pub struct GetProgramFromAnchorProject;
555impl FunctionImplementation for GetProgramFromAnchorProject {
556    fn check_instantiability(
557        _fn_spec: &FunctionSpecification,
558        _auth_ctx: &AuthorizationContext,
559        _args: &Vec<Type>,
560    ) -> Result<Type, Diagnostic> {
561        unimplemented!()
562    }
563
564    fn run(
565        fn_spec: &FunctionSpecification,
566        auth_ctx: &AuthorizationContext,
567        args: &Vec<Value>,
568    ) -> Result<Value, Diagnostic> {
569        arg_checker(fn_spec, args)?;
570        let program_name = args.get(0).unwrap().as_string().unwrap();
571
572        let keypair_path_buf = match args.get(1) {
573            Some(Value::Null) | None => PathBuf::from(DEFAULT_ANCHOR_TARGET_PATH)
574                .join("deploy")
575                .join(format!("{}-keypair.json", program_name)),
576            Some(Value::String(s)) => PathBuf::from(s),
577            _ => unreachable!(),
578        };
579
580        let keypair_path =
581            auth_ctx.get_file_location_from_path_buf(&keypair_path_buf).map_err(|e| {
582                to_diag(fn_spec, format!("failed to get anchor program keypair path: {e}"))
583            })?;
584
585        let idl_path_buf = match args.get(2) {
586            Some(Value::Null) | None => PathBuf::from(DEFAULT_ANCHOR_TARGET_PATH)
587                .join("idl")
588                .join(format!("{}.json", program_name)),
589            Some(Value::String(s)) => PathBuf::from(s),
590            _ => unreachable!(),
591        };
592
593        let idl_path = auth_ctx
594            .get_file_location_from_path_buf(&idl_path_buf)
595            .map_err(|e| to_diag(fn_spec, format!("failed to get anchor program idl path: {e}")))?;
596
597        let bin_path_buf = match args.get(3) {
598            Some(Value::Null) | None => PathBuf::from(DEFAULT_ANCHOR_TARGET_PATH)
599                .join("deploy")
600                .join(format!("{}.so", program_name)),
601            Some(Value::String(s)) => PathBuf::from(s),
602            _ => unreachable!(),
603        };
604
605        let bin_path = auth_ctx.get_file_location_from_path_buf(&bin_path_buf).map_err(|e| {
606            to_diag(fn_spec, format!("failed to get anchor program binary path: {e}"))
607        })?;
608
609        let anchor_program_artifacts = AnchorProgramArtifacts::new(
610            keypair_path.expect_path_buf(),
611            idl_path.expect_path_buf(),
612            bin_path.expect_path_buf(),
613        )
614        .map_err(|e| to_diag(fn_spec, e))?;
615
616        let value = anchor_program_artifacts.to_value().map_err(|e| to_diag(fn_spec, e))?;
617        Ok(value)
618    }
619}
620
621pub struct GetProgramFromNativeProject;
622impl FunctionImplementation for GetProgramFromNativeProject {
623    fn check_instantiability(
624        _fn_spec: &FunctionSpecification,
625        _auth_ctx: &AuthorizationContext,
626        _args: &Vec<Type>,
627    ) -> Result<Type, Diagnostic> {
628        unimplemented!()
629    }
630
631    fn run(
632        fn_spec: &FunctionSpecification,
633        auth_ctx: &AuthorizationContext,
634        args: &Vec<Value>,
635    ) -> Result<Value, Diagnostic> {
636        arg_checker(fn_spec, args)?;
637        let program_name = args.get(0).unwrap().as_string().unwrap();
638
639        let keypair_path_buf = match args.get(1) {
640            Some(Value::Null) | None => PathBuf::from(DEFAULT_NATIVE_TARGET_PATH)
641                .join("deploy")
642                .join(format!("{}-keypair.json", program_name)),
643            Some(Value::String(s)) => PathBuf::from(s),
644            _ => unreachable!(),
645        };
646
647        let keypair_path = auth_ctx
648            .get_file_location_from_path_buf(&keypair_path_buf)
649            .map_err(|e| to_diag(fn_spec, format!("failed to get program keypair path: {e}")))?;
650
651        let mut did_user_provide_idl_path = false;
652
653        let idl_path_buf = match args.get(2) {
654            Some(Value::Null) | None => PathBuf::from(DEFAULT_SHANK_IDL_PATH)
655                .join("idl")
656                .join(format!("{}.json", program_name)),
657            Some(Value::String(s)) => {
658                did_user_provide_idl_path = true;
659                PathBuf::from(s)
660            }
661            _ => unreachable!(),
662        };
663
664        let idl_path = auth_ctx
665            .get_file_location_from_path_buf(&idl_path_buf)
666            .map_err(|e| to_diag(fn_spec, format!("failed to get shank idl path: {e}")))?;
667
668        if did_user_provide_idl_path && !idl_path.exists() {
669            return Err(to_diag(
670                fn_spec,
671                format!("invalid program idl path; no idl found at: {}", idl_path_buf.display()),
672            ));
673        }
674
675        let bin_path_buf = match args.get(3) {
676            Some(Value::Null) | None => PathBuf::from(DEFAULT_NATIVE_TARGET_PATH)
677                .join("deploy")
678                .join(format!("{}.so", program_name)),
679            Some(Value::String(s)) => PathBuf::from(s),
680            _ => unreachable!(),
681        };
682
683        let bin_path = auth_ctx
684            .get_file_location_from_path_buf(&bin_path_buf)
685            .map_err(|e| to_diag(fn_spec, format!("failed to get program binary path: {e}")))?;
686
687        let classic_program_artifacts =
688            NativeProgramArtifacts::new(keypair_path, idl_path, bin_path)
689                .map_err(|e| to_diag(fn_spec, e.message))?;
690
691        classic_program_artifacts.to_value()
692    }
693}
694
695pub struct SolToLamports;
696impl FunctionImplementation for SolToLamports {
697    fn check_instantiability(
698        _fn_spec: &FunctionSpecification,
699        _auth_ctx: &AuthorizationContext,
700        _args: &Vec<Type>,
701    ) -> Result<Type, Diagnostic> {
702        unimplemented!()
703    }
704
705    fn run(
706        fn_spec: &FunctionSpecification,
707        _auth_ctx: &AuthorizationContext,
708        args: &Vec<Value>,
709    ) -> Result<Value, Diagnostic> {
710        arg_checker(fn_spec, args)?;
711        let sol = args.get(0).unwrap();
712        let sol = match sol {
713            Value::Integer(i) => {
714                if *i < 0 {
715                    return Err(to_diag(fn_spec, "SOL amount cannot be negative"));
716                }
717                if *i > (1u64 << 53) as i128 {
718                    return Err(to_diag(fn_spec, "SOL amount too large for precise conversion"));
719                }
720                *i as f64
721            }
722            Value::Float(f) => {
723                if *f < 0.0 {
724                    return Err(to_diag(fn_spec, "SOL amount cannot be negative"));
725                }
726                *f
727            }
728            _ => unreachable!(),
729        };
730        let lamports = sol_to_lamports(sol);
731        Ok(Value::integer(lamports as i128))
732    }
733}
734
735pub struct LamportsToSol;
736impl FunctionImplementation for LamportsToSol {
737    fn check_instantiability(
738        _fn_spec: &FunctionSpecification,
739        _auth_ctx: &AuthorizationContext,
740        _args: &Vec<Type>,
741    ) -> Result<Type, Diagnostic> {
742        unimplemented!()
743    }
744
745    fn run(
746        fn_spec: &FunctionSpecification,
747        _auth_ctx: &AuthorizationContext,
748        args: &Vec<Value>,
749    ) -> Result<Value, Diagnostic> {
750        arg_checker(fn_spec, args)?;
751        let lamports = args.get(0).unwrap().as_uint().unwrap().map_err(|e| to_diag(fn_spec, e))?;
752
753        let sol = lamports_to_sol(lamports);
754        Ok(Value::float(sol))
755    }
756}
757
758pub struct FindPda;
759impl FunctionImplementation for FindPda {
760    fn check_instantiability(
761        _fn_spec: &FunctionSpecification,
762        _auth_ctx: &AuthorizationContext,
763        _args: &Vec<Type>,
764    ) -> Result<Type, Diagnostic> {
765        unimplemented!()
766    }
767
768    fn run(
769        fn_spec: &FunctionSpecification,
770        _auth_ctx: &AuthorizationContext,
771        args: &Vec<Value>,
772    ) -> Result<Value, Diagnostic> {
773        arg_checker(fn_spec, args)?;
774        let program_id = SvmValue::to_pubkey(args.get(0).unwrap())
775            .map_err(|e| to_diag(fn_spec, format!("invalid program id for finding pda: {e}")))?;
776
777        let seeds = if let Some(val) = args.get(1) {
778            get_seeds_from_value(val).map_err(|diag| to_diag(fn_spec, diag))?
779        } else {
780            vec![]
781        };
782
783        let seed_refs: Vec<&[u8]> = seeds.iter().map(|s| s.as_slice()).collect();
784        let (pda, bump) = Pubkey::try_find_program_address(&seed_refs, &program_id)
785            .ok_or(to_diag(fn_spec, "failed to find pda".to_string()))?;
786        let obj = ObjectType::from(vec![
787            ("pda", Value::string(pda.to_string())),
788            ("bump_seed", Value::integer(bump as i128)),
789        ])
790        .to_value();
791        Ok(obj)
792    }
793}
794
795pub struct GetAssociatedTokenAccount;
796impl FunctionImplementation for GetAssociatedTokenAccount {
797    fn check_instantiability(
798        _fn_spec: &FunctionSpecification,
799        _auth_ctx: &AuthorizationContext,
800        _args: &Vec<Type>,
801    ) -> Result<Type, Diagnostic> {
802        unimplemented!()
803    }
804
805    fn run(
806        fn_spec: &FunctionSpecification,
807        _auth_ctx: &AuthorizationContext,
808        args: &Vec<Value>,
809    ) -> Result<Value, Diagnostic> {
810        arg_checker(fn_spec, args)?;
811        let wallet_address = SvmValue::to_pubkey(args.get(0).unwrap()).map_err(|e| {
812            to_diag(
813                fn_spec,
814                format!("invalid wallet address for getting associated token account: {e}"),
815            )
816        })?;
817
818        let token_mint_address = SvmValue::to_pubkey(args.get(1).unwrap()).map_err(|e| {
819            to_diag(
820                fn_spec,
821                format!("invalid token mint address for getting associated token account: {e}"),
822            )
823        })?;
824
825        let token_program_id = if let Some(val) = args.get(2) {
826            SvmValue::to_pubkey(val).map_err(|e| {
827                to_diag(
828                    fn_spec,
829                    format!("invalid token program id for getting associated token account: {e}"),
830                )
831            })?
832        } else {
833            inline_spl_token::id()
834        };
835
836        let spl_associated_token_account =
837            spl_associated_token_account_interface::address::get_associated_token_address_with_program_id(
838                &wallet_address,
839                &token_mint_address,
840                &token_program_id,
841            );
842
843        Ok(SvmValue::pubkey(spl_associated_token_account.to_bytes().to_vec()))
844    }
845}
846
847pub struct CreateTokenAccountInstruction;
848impl FunctionImplementation for CreateTokenAccountInstruction {
849    fn check_instantiability(
850        _fn_spec: &FunctionSpecification,
851        _auth_ctx: &AuthorizationContext,
852        _args: &Vec<Type>,
853    ) -> Result<Type, Diagnostic> {
854        unimplemented!()
855    }
856
857    fn run(
858        fn_spec: &FunctionSpecification,
859        _auth_ctx: &AuthorizationContext,
860        args: &Vec<Value>,
861    ) -> Result<Value, Diagnostic> {
862        arg_checker(fn_spec, args)?;
863        let funding_address = SvmValue::to_pubkey(args.get(0).unwrap()).map_err(|e| {
864            to_diag(fn_spec, format!("invalid funding address for creating token account: {e}"))
865        })?;
866
867        let wallet_address = SvmValue::to_pubkey(args.get(1).unwrap()).map_err(|e| {
868            to_diag(fn_spec, format!("invalid wallet address for creating token account: {e}"))
869        })?;
870
871        let token_mint_address = SvmValue::to_pubkey(args.get(2).unwrap()).map_err(|e| {
872            to_diag(fn_spec, format!("invalid token mint address for creating token account: {e}"))
873        })?;
874
875        let token_program_id = SvmValue::to_pubkey(args.get(3).unwrap()).map_err(|e| {
876            to_diag(fn_spec, format!("invalid token program id for creating token account: {e}"))
877        })?;
878
879        let instruction = create_associated_token_account_idempotent(
880            &funding_address,
881            &wallet_address,
882            &token_mint_address,
883            &token_program_id,
884        );
885        let bytes = serde_json::to_vec(&instruction).map_err(|e| {
886            to_diag(fn_spec, format!("failed to serialize create token account instruction: {e}"))
887        })?;
888
889        Ok(SvmValue::instruction(bytes))
890    }
891}
892
893pub struct SvmU64;
894impl FunctionImplementation for SvmU64 {
895    fn check_instantiability(
896        _fn_spec: &FunctionSpecification,
897        _auth_ctx: &AuthorizationContext,
898        _args: &Vec<Type>,
899    ) -> Result<Type, Diagnostic> {
900        unimplemented!()
901    }
902
903    fn run(
904        fn_spec: &FunctionSpecification,
905        _auth_ctx: &AuthorizationContext,
906        args: &Vec<Value>,
907    ) -> Result<Value, Diagnostic> {
908        arg_checker(fn_spec, args)?;
909        let value = args.get(0).unwrap().as_uint().unwrap().map_err(|e| to_diag(fn_spec, e))?;
910        Ok(SvmValue::u64(value))
911    }
912}
913pub struct SvmI64;
914impl FunctionImplementation for SvmI64 {
915    fn check_instantiability(
916        _fn_spec: &FunctionSpecification,
917        _auth_ctx: &AuthorizationContext,
918        _args: &Vec<Type>,
919    ) -> Result<Type, Diagnostic> {
920        unimplemented!()
921    }
922
923    fn run(
924        fn_spec: &FunctionSpecification,
925        _auth_ctx: &AuthorizationContext,
926        args: &Vec<Value>,
927    ) -> Result<Value, Diagnostic> {
928        arg_checker(fn_spec, args)?;
929        let value = args.get(0).unwrap().as_integer().unwrap();
930        let value: i64 =
931            value.try_into().map_err(|_| to_diag(fn_spec, "i64 value out of range"))?;
932        Ok(SvmValue::i64(value))
933    }
934}