pinoc 0.3.4

A CLI tool for setting up pinocchio program project
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
438
439
440
441
442
443
444
445
446
mod common;

use common::{pinoc, stderr, stdout, temp_copy};
use std::path::Path;
use std::process::Command;

/// A git repo holding a fixture with its IDL already generated.
fn project_with_idl() -> std::path::PathBuf {
    let dir = temp_copy("client_program");
    std::fs::write(dir.join(".gitignore"), "/target\n").unwrap();
    assert!(pinoc(&dir, &["idl"]).status.success());
    let git = |args: &[&str]| {
        let ok = Command::new("git")
            .args(args)
            .current_dir(&dir)
            .output()
            .expect("git is required for this test")
            .status
            .success();
        assert!(ok, "git {args:?}");
    };
    git(&["init", "-q"]);
    git(&["add", "-A"]);
    git(&[
        "-c",
        "user.email=t@t",
        "-c",
        "user.name=t",
        "commit",
        "-qm",
        "init",
    ]);
    dir
}

fn git_status(dir: &Path) -> String {
    let out = Command::new("git")
        .args(["status", "--short"])
        .current_dir(dir)
        .output()
        .unwrap();
    String::from_utf8_lossy(&out.stdout).into_owned()
}

#[test]
fn codama_without_deps_fails_and_leaves_the_tree_clean() {
    let dir = project_with_idl();
    for language in ["rust", "ts"] {
        let out = pinoc(
            &dir,
            &[
                "client",
                "generate",
                "--generator",
                "codama",
                "-y",
                "--language",
                language,
            ],
        );
        assert!(!out.status.success(), "{language}");
        assert_eq!(git_status(&dir), "", "{language}: {}", stderr(&out));
        assert_eq!(
            std::fs::read_to_string(dir.join(".gitignore")).unwrap(),
            "/target\n"
        );
        assert!(!dir.join("clients").exists(), "{language}");
    }
}

#[test]
fn typescript_needs_the_codama_generator() {
    let dir = project_with_idl();
    let out = pinoc(
        &dir,
        &[
            "client",
            "generate",
            "--generator",
            "shank",
            "--language",
            "ts",
        ],
    );
    assert!(!out.status.success());
    assert!(stderr(&out).contains("--language ts needs --generator codama"));
    assert_eq!(git_status(&dir), "");
}

#[test]
fn shank_rust_client_is_the_default() {
    let dir = project_with_idl();
    let out = pinoc(&dir, &["client", "generate", "--generator", "shank"]);
    assert!(out.status.success(), "{}", stderr(&out));
    assert!(stdout(&out).contains("Rust client written to clients/rust-shank/"));
    assert!(dir.join("clients/rust-shank/src/lib.rs").exists());
}

/// Installs npm packages, so it needs Node.js and network access:
/// `cargo test -- --ignored`.
#[test]
#[ignore]
fn codama_renders_typescript_and_rust() {
    let dir = project_with_idl();
    let generate = |language: &str| {
        let out = pinoc(
            &dir,
            &[
                "client",
                "generate",
                "--language",
                language,
                "--generator",
                "codama",
                "-y",
                "--auto-install",
            ],
        );
        assert!(out.status.success(), "{language}: {}", stderr(&out));
    };

    generate("ts");
    let gitignore = std::fs::read_to_string(dir.join(".gitignore")).unwrap();
    assert!(
        gitignore.lines().any(|l| l == ".pinoc-codama/"),
        "{gitignore}"
    );
    let instructions = dir.join("clients/ts/src/generated/instructions");
    let idl = common::read_json(&dir.join("target/idl/client_program.json"));
    let index = std::fs::read_to_string(instructions.join("index.ts")).unwrap();
    let idl_instructions = idl["instructions"].as_array().unwrap();
    assert_eq!(idl_instructions.len(), 2);
    for ix in idl_instructions {
        let name = ix["name"].as_str().unwrap();
        let file = format!("{}{}", name[..1].to_lowercase(), &name[1..]);
        assert!(
            instructions.join(format!("{file}.ts")).exists(),
            "{file}.ts"
        );
        assert!(index.contains(&format!("./{file}")), "{index}");
    }
    assert!(dir
        .join("clients/ts/src/generated/errors/index.ts")
        .exists());
    assert!(dir.join("clients/ts/package.json").exists());

    generate("rust");
    assert!(dir.join("clients/rust-codama/Cargo.toml").exists());
    assert!(dir
        .join("clients/rust-codama/src/generated/errors/mod.rs")
        .exists());
}

/// Needs Node.js and network access: `cargo test -- --ignored`.
#[test]
#[ignore]
fn codama_rust_client_handles_an_instruction_without_accounts() {
    let dir = temp_copy("idl_codama_tail");
    assert!(pinoc(&dir, &["idl"]).status.success());
    let out = pinoc(
        &dir,
        &[
            "client",
            "generate",
            "--generator",
            "codama",
            "--auto-install",
        ],
    );
    assert!(out.status.success(), "{}", stderr(&out));
    let ping =
        std::fs::read_to_string(dir.join("clients/rust-codama/src/generated/instructions/ping.rs"))
            .unwrap();
    assert!(!ping.contains("NaN"), "{ping}");

    let out = pinoc(
        &dir,
        &["client", "generate", "--language", "ts", "--auto-install"],
    );
    assert!(out.status.success(), "{}", stderr(&out));
    let settle =
        std::fs::read_to_string(dir.join("clients/ts/src/generated/instructions/settle.ts"))
            .unwrap();
    assert!(settle.contains("positions: Array<"), "{settle}");
}

const USE_DISCRIMINANT: &str = "#[borsh(use_discriminant = true)]";

#[test]
fn shank_client_keeps_explicit_enum_discriminants() {
    let dir = temp_copy("client_enum_values");
    assert!(pinoc(&dir, &["idl", "--idl-generator", "shank"])
        .status
        .success());
    let out = pinoc(&dir, &["client", "generate", "--generator", "shank", "-y"]);
    assert!(out.status.success(), "{}", stderr(&out));
    assert!(stdout(&out).contains("Enums with explicit discriminants (`Status`)"));

    let types = dir.join("clients/rust-shank/src/generated/types");
    let status = std::fs::read_to_string(types.join("status.rs")).unwrap();
    assert!(
        status.contains(&format!(
            "{USE_DISCRIMINANT}\npub enum Status {{\n    Open = 1,\n    Active = 2,\n    Closed = 5,\n}}"
        )),
        "{status}"
    );
    // An enum without explicit values is rendered as before.
    let plain = std::fs::read_to_string(types.join("plain.rs")).unwrap();
    assert!(
        plain.contains("pub enum Plain {\n    A,\n    B,\n}"),
        "{plain}"
    );
    assert!(!plain.contains(USE_DISCRIMINANT));
}

#[test]
fn enums_that_cannot_be_corrected_stop_the_codama_client() {
    for (source, expected) in [
        (
            "#[derive(codama_macros::CodamaType)]\npub enum Shape { Circle { r: u8 } = 3, Square = 7 }",
            "enum `shape` has variants with data and explicit discriminators (3, 7)",
        ),
        (
            "#[derive(codama_macros::CodamaAccount)]\npub struct Holder {\n    #[codama(type = enum(variant(name = \"a\", discriminator = 4)))]\n    pub kind: u8,\n}",
            "declared inline",
        ),
    ] {
        let dir = temp_copy("client_enum_values");
        let header = "pinocchio::address::declare_id!(\"EfPyA5fx11YAY9XwmrWVddcQe5bBZeNsKA8avqYUH6Qr\");\n";
        std::fs::write(dir.join("src/lib.rs"), format!("{header}{source}\n")).unwrap();
        let idl = pinoc(&dir, &["idl", "--idl-generator", "codama"]);
        if !idl.status.success() {
            // The attribute form is not available in this Codama release.
            assert!(expected == "declared inline", "{}", stderr(&idl));
            continue;
        }
        let out = pinoc(&dir, &["client", "generate", "--generator", "codama", "-y"]);
        assert!(!out.status.success(), "{source}");
        assert!(stderr(&out).contains(expected), "{}", stderr(&out));
        assert!(!dir.join("clients").exists(), "{source}");
    }
}

/// Needs Node.js and network access: `cargo test -- --ignored`.
#[test]
#[ignore]
fn codama_clients_keep_explicit_enum_discriminants() {
    let dir = temp_copy("client_enum_values");
    assert!(pinoc(&dir, &["idl"]).status.success());
    for language in ["ts", "rust"] {
        let out = pinoc(
            &dir,
            &[
                "client",
                "generate",
                "--generator",
                "codama",
                "--language",
                language,
                "--auto-install",
            ],
        );
        assert!(out.status.success(), "{language}: {}", stderr(&out));
        assert!(stdout(&out).contains("Enums with explicit discriminants (`status`)"));
    }

    let ts = dir.join("clients/ts/src/generated/types");
    let status = std::fs::read_to_string(ts.join("status.ts")).unwrap();
    assert!(
        status.contains("export enum Status {\n  Open = 1,\n  Active = 2,\n  Closed = 5,\n}"),
        "{status}"
    );
    for codec in ["getEnumEncoder", "getEnumDecoder"] {
        assert!(
            status.contains(&format!(
                "{codec}(Status, {{ useValuesAsDiscriminators: true }})"
            )),
            "{status}"
        );
    }
    let plain = std::fs::read_to_string(ts.join("plain.ts")).unwrap();
    assert!(plain.contains("getEnumEncoder(Plain)"), "{plain}");

    let rust = dir.join("clients/rust-codama/src/generated/types");
    let status = std::fs::read_to_string(rust.join("status.rs")).unwrap();
    assert!(
        status.contains(&format!(
            "{USE_DISCRIMINANT}\npub enum Status {{\nOpen = 1,\nActive = 2,\nClosed = 5,\n}}"
        )),
        "{status}"
    );
    let plain = std::fs::read_to_string(rust.join("plain.rs")).unwrap();
    assert!(!plain.contains(USE_DISCRIMINANT), "{plain}");
}

/// Needs Node.js and network access: `cargo test -- --ignored`.
#[test]
#[ignore]
fn codama_clients_for_a_program_with_pdas_and_constants() {
    let dir = temp_copy("idl_constants_pda");
    assert!(pinoc(&dir, &["idl"]).status.success());
    for language in ["rust", "ts"] {
        let out = pinoc(
            &dir,
            &[
                "client",
                "generate",
                "--generator",
                "codama",
                "--language",
                language,
                "--auto-install",
            ],
        );
        assert!(out.status.success(), "{language}: {}", stderr(&out));
    }

    // The PDA helpers need `curve25519`, which solana-pubkey does not enable by default.
    let rust = dir.join("clients/rust-codama");
    let vault = std::fs::read_to_string(rust.join("src/generated/accounts/vault.rs")).unwrap();
    assert!(vault.contains("find_program_address"), "{vault}");
    let manifest = std::fs::read_to_string(rust.join("Cargo.toml")).unwrap();
    assert!(
        manifest.contains(r#"solana-pubkey = { version = "4.2", features = ["curve25519"] }"#),
        "{manifest}"
    );

    let constants =
        std::fs::read_to_string(dir.join("clients/ts/src/generated/constants/idlConstantsPda.ts"))
            .unwrap();
    assert!(
        constants.contains("export const MAX_ATAS: number = 12;"),
        "{constants}"
    );
    assert!(
        constants.contains("export const MAX_RESERVE_FLOOR: bigint = 100000000000000n;"),
        "{constants}"
    );

    // A client with no PDA keeps the plain dependency.
    let dir = temp_copy("client_enum_values");
    assert!(pinoc(&dir, &["idl"]).status.success());
    let out = pinoc(
        &dir,
        &[
            "client",
            "generate",
            "--generator",
            "codama",
            "--auto-install",
        ],
    );
    assert!(out.status.success(), "{}", stderr(&out));
    let manifest = std::fs::read_to_string(dir.join("clients/rust-codama/Cargo.toml")).unwrap();
    assert!(manifest.contains("solana-pubkey = \"4.2\"\n"), "{manifest}");
}

/// Needs Node.js and network access: `cargo test -- --ignored`.
#[test]
#[ignore]
fn codama_tooling_is_installed_from_the_built_in_lock() {
    let dir = project_with_idl();
    let tooling = dir.join("clients/ts/.pinoc-codama");
    let generate = |args: &[&str]| {
        let mut all = vec!["client", "generate", "--language", "ts"];
        all.extend(args);
        pinoc(&dir, &all)
    };

    let out = generate(&["--auto-install"]);
    assert!(out.status.success(), "{}", stderr(&out));
    let versions = "📦 @codama/nodes-from-anchor 1.5.6, @codama/renderers-js 2.5.0, codama 1.11.0";
    assert!(stdout(&out).contains(versions), "{}", stdout(&out));
    let lock = std::fs::read_to_string(tooling.join("package-lock.json")).unwrap();
    assert_eq!(
        std::fs::read_to_string(tooling.join("installed-lock.json")).unwrap(),
        lock
    );
    let manifest = std::fs::read_to_string(tooling.join("package.json")).unwrap();
    assert!(
        !manifest.contains('^') && !manifest.contains('~'),
        "{manifest}"
    );

    // Installed once, later runs need no flag and report the same versions.
    let out = generate(&[]);
    assert!(out.status.success(), "{}", stderr(&out));
    assert!(stdout(&out).contains(versions));
    let client = std::fs::read_to_string(dir.join("clients/ts/src/generated/index.ts")).unwrap();

    // A hand-run `npm ci` restores the same tree, so it stays accepted.
    let ci = Command::new("npm")
        .args(["ci", "--silent"])
        .current_dir(&tooling)
        .output()
        .unwrap();
    assert!(ci.status.success());
    assert!(generate(&[]).status.success());

    // A tree that did not come from this lock, or was changed since, is not used.
    const FOREIGN: &str = "were not installed from this pinoc's lock file";
    const CHANGED: &str = "were changed after pinoc installed them";
    for (tamper, from, to, expected) in [
        ("installed-lock.json", "2.5.0", "2.6.0", FOREIGN),
        (
            "node_modules/@codama/renderers-js/package.json",
            "\"version\": \"2.5.0\"",
            "\"version\": \"2.6.0\"",
            FOREIGN,
        ),
        // The renderer's code edited, every version string left alone.
        (
            "node_modules/@codama/renderers-js/dist/index.node.mjs",
            "getEnumEncoder",
            "getEnumEncoder /* edited */",
            CHANGED,
        ),
        ("installed-tree", "fnv1a64", "fnv1a64 0", CHANGED),
    ] {
        let path = tooling.join(tamper);
        let original = std::fs::read_to_string(&path).unwrap();
        let edited = original.replace(from, to);
        assert_ne!(edited, original, "{tamper}");
        std::fs::write(&path, edited).unwrap();
        let refused = generate(&[]);
        assert!(!refused.status.success(), "{tamper}");
        assert!(
            stderr(&refused).contains(expected),
            "{tamper}: {}",
            stderr(&refused)
        );
        assert_eq!(
            std::fs::read_to_string(dir.join("clients/ts/src/generated/index.ts")).unwrap(),
            client,
            "{tamper}: a refused run must not touch the client"
        );
        let out = generate(&["--auto-install"]);
        assert!(out.status.success(), "{tamper}: {}", stderr(&out));
        assert!(stdout(&out).contains(versions), "{tamper}");
        assert_eq!(
            std::fs::read_to_string(dir.join("clients/ts/src/generated/index.ts")).unwrap(),
            client,
            "{tamper}"
        );
    }
}