neo-devpack-solidity 0.22.0

Production-focused Solidity-to-NeoVM compilation system
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
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
fn resolve_builtin_call(expr: &Expression) -> Option<BuiltinCall> {
    if let Expression::MemberAccess(_, inner, member) = expr {
        if let Expression::Variable(base) = inner.as_ref() {
            let member_name = member.name.as_str();
            match base.name.as_str() {
                "Runtime" => return resolve_runtime_member(member_name),
                "abi" => return resolve_abi_member(member_name),
                "Storage" => return resolve_storage_member(member_name),
                "Syscalls" => return resolve_syscalls_member(member_name),
                "NativeCalls" => return resolve_native_calls_member(member_name),
                "Neo" => return resolve_neo_member(member_name),
                // Task — `StdLib.<method>(...)` and `CryptoLib.<method>(...)`
                // in Solidity source must lower to a `BuiltinCall::NativeCall`
                // to the matching Neo N3 native contract. Before this was
                // wired, the compiler fell through to the generic function-
                // call handler, which evaluated and dropped the args then
                // pushed PUSH0 as the result. Fuzz regression: the
                // Solidity→bytecode path for `StdLib.itoa(12345, 10)` and
                // `CryptoLib.sha256(bytes)` returned zeros at runtime even
                // though the underlying native implementations are correct
                // (see baseline_tests.rs::callt_stdlib_itoa_roundtrip_via_token).
                "StdLib" => return resolve_stdlib_member(member_name),
                "CryptoLib" => return resolve_cryptolib_member(member_name),
                _ => {}
            }
        }
    }

    if let Expression::Variable(identifier) = expr {
        if identifier.name == "ecrecover" {
            return Some(BuiltinCall::Ecrecover);
        }
        if identifier.name == "keccak256" {
            return Some(BuiltinCall::Keccak256);
        }
        // Solidity exposes `sha256(bytes)` and `ripemd160(bytes)` as
        // global built-in hashers (EVM precompiles 0x02 and 0x03). Route
        // them to the CryptoLib native contract's `sha256`/`ripemd160`
        // methods. Before this wiring the compiler fell through to the
        // generic function-call handler, which evaluated and dropped the
        // argument and pushed 0 — so `sha256(b"abc")` returned 8 zero
        // bytes at runtime instead of the canonical digest. `keccak256`
        // already has a dedicated `BuiltinCall::Keccak256` variant
        // because its EVM semantics differ from Neo's default; `sha256`
        // and `ripemd160` have a direct 1:1 native mapping.
        if identifier.name == "sha256" {
            return Some(BuiltinCall::NativeCall {
                contract: NativeContract::CryptoLib,
                method: "sha256".to_string(),
            });
        }
        if identifier.name == "ripemd160" {
            return Some(BuiltinCall::NativeCall {
                contract: NativeContract::CryptoLib,
                method: "ripemd160".to_string(),
            });
        }
        if identifier.name == "type" {
            return Some(BuiltinCall::TypeOf);
        }
    }

    None
}

/// The builtin-library base names the compiler lowers as intrinsics
/// (their devpack Solidity bodies are never compiled).
pub const BUILTIN_LIBRARY_BASES: &[&str] =
    &["Runtime", "abi", "Storage", "Syscalls", "NativeCalls", "Neo"];

/// Introspection over the complete builtin intrinsic surface:
/// `(base, supported members)` for every builtin library base.
///
/// INVARIANT (pinned by `tests/gap_hasrole_tests.rs`): every member listed
/// here MUST actually lower — either via the `resolve_*_member` table in this
/// file / `syscalls.rs` / `native_calls.rs`, or via a bespoke handler in
/// `src/ir/expressions/calls/builtins/member_*.rs`. A whitelisted member
/// without a lowering is an uncallable intrinsic: the diagnostic for
/// `Base.member(...)` would then claim the member is supported while every
/// call fails (this happened with `Syscalls.hasRole`, which resolved to
/// `None` while being advertised). Add new members here only together with
/// their lowering.
pub fn builtin_intrinsic_surface() -> Vec<(&'static str, &'static [&'static str])> {
    BUILTIN_LIBRARY_BASES
        .iter()
        .map(|base| {
            (
                *base,
                builtin_library_supported_members(base)
                    .expect("every builtin library base has a member whitelist"),
            )
        })
        .collect()
}

fn builtin_library_supported_members(base: &str) -> Option<&'static [&'static str]> {
    match base {
        "Runtime" => Some(&[
            "notify",
            "notifyIndexed",
            "checkWitness",
            "requireWitness",
            "checkAnyWitness",
            "checkAllWitnesses",
            "checkMultiSigWitness",
            "gasLeft",
            "burnGas",
            "log",
            "getTime",
            "getTrigger",
            "getInvocationCounter",
            "getCurrentSigners",
            "getCallFlags",
            "getScriptContainer",
            "loadScript",
            "initializeServices",
            "getNetwork",
            "getPlatform",
            "getAddressVersion",
            "getRandom",
            "getExecutingScriptHash",
            "getCallingScriptHash",
            "getEntryScriptHash",
        ]),
        "abi" => Some(&[
            "encode",
            "encodePacked",
            "encodeCall",
            "encodeWithSignature",
            "encodeWithSelector",
            "decode",
        ]),
        // Only members with faithful Neo N3 lowerings are listed here. The
        // former `*Local` family lowered to fictional `System.Storage.Local.*`
        // syscalls that do not exist in Neo N3's interop table (instant FAULT
        // on real nodes), and convenience helpers such as `batchPut`,
        // `batchGet`, `batchDelete`, `count`, `findValues`, `findKeys`,
        // `clearPrefix`, `exists`, `isValidKey`, and `getUsage` silently
        // miscompiled to single raw syscalls with the wrong arity/semantics.
        // All of them now fail compilation with a loud diagnostic instead.
        "Storage" => Some(&[
            "find",
            "put",
            "get",
            "remove",
            "asReadOnly",
            "initializeContext",
            "getContext",
            "getReadOnlyContext",
            "putContractMetadata",
        ]),
        "Syscalls" => Some(&[
            "contractCall",
            "contractCallWithFlags",
            "getCallFlags",
            "contractCreate",
            "contractUpdate",
            "contractDestroy",
            "createStandardAccount",
            "createMultisigAccount",
            "notify",
            "getCurrentIndex",
            "getCurrentHash",
            "getBlock",
            "getTransaction",
            "getTransactionHeight",
            "getTransactionFromBlock",
            "getTransactionSigners",
            "getTransactionVMState",
            "getExecutingScriptHash",
            "getCallingScriptHash",
            "getEntryScriptHash",
            "getScriptContainer",
            "loadScript",
            "getStorageContext",
            "getReadOnlyStorageContext",
            "storageAsReadOnly",
            "storageGet",
            "storagePut",
            "storageDelete",
            "storageFind",
            "checkWitness",
            "getTime",
            "gasLeft",
            "getPlatform",
            "getTrigger",
            "getNotifications",
            "log",
            "getCurrentSigners",
            "checkSig",
            "checkMultisig",
            "sha256",
            "ripemd160",
            "verifyWithECDsa",
            "murmur32",
            "keccak256",
            "recoverSecp256K1",
            "verifyWithEd25519",
            "bls12381Serialize",
            "bls12381Deserialize",
            "bls12381Equal",
            "bls12381Add",
            "bls12381Mul",
            "bls12381Pairing",
            // G1/G2 affine ops mirror the CryptoLib.* path resolver at
            // roughly line 585. Keeping them out of the Syscalls whitelist
            // would make `Syscalls.bls12381G1Add(...)` fail with an
            // "unsupported builtin library call" diagnostic even though the
            // CryptoLib side accepts the call — the audit agent flagged
            // this asymmetry.
            "bls12381G1Add",
            "bls12381G1Mul",
            "bls12381G1Neg",
            "bls12381G2Add",
            "bls12381G2Mul",
            "bls12381G2Neg",
            // Alias for `keccak256` — the devpack's `Syscalls.sol` exposes
            // it as `neoKeccak256` so the name doesn't shadow Solidity's
            // bare `keccak256` intrinsic. Unwired here before the audit.
            "neoKeccak256",
            "serialize",
            "deserialize",
            "itoa",
            "atoi",
            "jsonSerialize",
            "jsonDeserialize",
            "base64Encode",
            "base64Decode",
            "base64UrlEncode",
            "base64UrlDecode",
            "base58Encode",
            "base58Decode",
            "base58CheckEncode",
            "base58CheckDecode",
            "hexEncode",
            "hexDecode",
            "memoryCompare",
            "memorySearch",
            "stringSplit",
            "strLen",
            "iteratorNext",
            "iteratorValue",
            "getCurrentRandom",
            "getNetwork",
            "getAddressVersion",
            "burnGas",
            "getInvocationCounter",
            "getFeePerByte",
            "getExecFeeFactor",
            "getExecPicoFeeFactor",
            "getStoragePrice",
            "getMillisecondsPerBlock",
            "getMaxValidUntilBlockIncrement",
            "getMaxTraceableBlocks",
            "getAttributeFee",
            "isBlocked",
            "oracleRequest",
            "getOraclePrice",
            "getDesignatedByRole",
            "scriptHashToAddress",
            "addressToScriptHash",
            "isValidAddress",
            "getContractScript",
            "contractExists",
        ]),
        "NativeCalls" => Some(&[
            "neoTotalSupply",
            "neoBalanceOf",
            "neoTransfer",
            "neoDecimals",
            "neoSymbol",
            "neoName",
            "vote",
            "getCandidates",
            "registerCandidate",
            "unregisterCandidate",
            "getGasPerBlock",
            "getRegisterPrice",
            "setRegisterPrice",
            "setGasPerBlock",
            "getAccountState",
            "unclaimedGas",
            "getCandidateVote",
            "getCommittee",
            "getCommitteeAddress",
            "isCommittee",
            "getNextBlockValidators",
            "getAllCandidates",
            "isValidator",
            "gasTotalSupply",
            "gasBalanceOf",
            "gasTransfer",
            "gasDecimals",
            "gasSymbol",
            "gasName",
            "deployContract",
            "updateContract",
            "destroyContract",
            "getContract",
            "listContracts",
            "hasMethod",
            "getMinimumDeploymentFee",
            "setMinimumDeploymentFee",
            "getContractById",
            "isContract",
            "getFeePerByte",
            "setFeePerByte",
            "getExecFeeFactor",
            "getExecPicoFeeFactor",
            "setExecFeeFactor",
            "getStoragePrice",
            "getMillisecondsPerBlock",
            "setMillisecondsPerBlock",
            "getMaxValidUntilBlockIncrement",
            "setMaxValidUntilBlockIncrement",
            "getMaxTraceableBlocks",
            "setMaxTraceableBlocks",
            "getAttributeFee",
            "setAttributeFee",
            "setStoragePrice",
            "blockAccount",
            "unblockAccount",
            "isBlocked",
            "getBlockedAccounts",
            "recoverFund",
            "setWhitelistFeeContract",
            "removeWhitelistFeeContract",
            "getWhitelistFeeContracts",
            "requestOracleData",
            "getOraclePrice",
            "setOraclePrice",
            "oracleFinish",
            "oracleVerify",
            "oracleRequest",
            "designateAsRole",
            "getDesignatedByRole",
            "currentIndex",
            "currentHash",
            "getBlock",
            "getBlockHash",
            "getBlockByIndex",
            "getBlockByHash",
            "getTransaction",
            "getTransactionHeight",
            "getTransactionFromBlock",
            "getTransactionSigners",
            "getTransactionVMState",
            "getBlockSystemFee",
            "notaryVerify",
            "notaryBalanceOf",
            "notaryExpirationOf",
            "notaryLockDepositUntil",
            "notaryWithdraw",
            "notaryGetMaxNotValidBeforeDelta",
            "notarySetMaxNotValidBeforeDelta",
            "notaryOnNEP17Payment",
            "treasuryVerify",
            "treasuryOnNEP17Payment",
            "treasuryOnNEP11Payment",
            "isNativeContract",
            "getNativeContractName",
            "getAllNativeContracts",
            "estimateNativeCallGas",
            "batchNativeCalls",
            "getNetworkConfiguration",
            "getNativeContractManifest",
            "safeNativeCall",
            "externalNativeCall",
        ]),
        "Neo" => Some(&[
            "verifySignature",
            "callContract",
            "deployContract",
            "getNeoBalance",
            "getGasBalance",
            "getGasPrice",
            "getStoragePrice",
            "getCommittee",
            "getValidators",
            "isCommittee",
            "isValidator",
            "getRandom",
            "getBlockHeight",
            "getCurrentBlock",
            "getBlockByIndex",
            "getBlockTime",
            "getTransaction",
            "getTransactionHeight",
            "transactionExists",
            "getNetworkMagic",
            "verifyWithWitness",
            "sha256Hash",
            "ripemd160Hash",
            // `transferNeo`/`transferGas` are lowered by
            // `try_lower_value_transfer_helpers` (value_transfer.rs) to the
            // NEO/GAS native `transfer` methods rather than via
            // `resolve_neo_member`, but they are part of the supported
            // devpack surface and belong in this diagnostic list.
            "transferNeo",
            "transferGas",
        ]),
        _ => None,
    }
}

fn resolve_runtime_member(member: &str) -> Option<BuiltinCall> {
    match member {
        "notify" => Some(BuiltinCall::RuntimeNotify),
        "checkWitness" => Some(BuiltinCall::RuntimeCheckWitness),
        "gasLeft" => Some(BuiltinCall::Syscall("System.Runtime.GasLeft".to_string())),
        "burnGas" => Some(BuiltinCall::Syscall("System.Runtime.BurnGas".to_string())),
        "log" => Some(BuiltinCall::Syscall("System.Runtime.Log".to_string())),
        "getTime" => Some(BuiltinCall::Syscall("System.Runtime.GetTime".to_string())),
        "getTrigger" => Some(BuiltinCall::Syscall(
            "System.Runtime.GetTrigger".to_string(),
        )),
        "getInvocationCounter" => Some(BuiltinCall::Syscall(
            "System.Runtime.GetInvocationCounter".to_string(),
        )),
        "getCurrentSigners" => Some(BuiltinCall::Syscall(
            "System.Runtime.CurrentSigners".to_string(),
        )),
        "getCallFlags" => Some(BuiltinCall::Syscall(
            "System.Contract.GetCallFlags".to_string(),
        )),
        "getScriptContainer" => Some(BuiltinCall::Syscall(
            "System.Runtime.GetScriptContainer".to_string(),
        )),
        "loadScript" => Some(BuiltinCall::Syscall(
            "System.Runtime.LoadScript".to_string(),
        )),
        "getNetwork" => Some(BuiltinCall::Syscall(
            "System.Runtime.GetNetwork".to_string(),
        )),
        "getPlatform" => Some(BuiltinCall::Syscall("System.Runtime.Platform".to_string())),
        "getAddressVersion" => Some(BuiltinCall::Syscall(
            "System.Runtime.GetAddressVersion".to_string(),
        )),
        "getRandom" => Some(BuiltinCall::Syscall("System.Runtime.GetRandom".to_string())),
        "getExecutingScriptHash" => Some(BuiltinCall::Syscall(
            "System.Runtime.GetExecutingScriptHash".to_string(),
        )),
        "getCallingScriptHash" => Some(BuiltinCall::Syscall(
            "System.Runtime.GetCallingScriptHash".to_string(),
        )),
        "getEntryScriptHash" => Some(BuiltinCall::Syscall(
            "System.Runtime.GetEntryScriptHash".to_string(),
        )),
        _ => None,
    }
}

fn resolve_abi_member(member: &str) -> Option<BuiltinCall> {
    match member {
        "encode" => Some(BuiltinCall::AbiEncode),
        "encodePacked" => Some(BuiltinCall::AbiEncodePacked),
        "encodeCall" => Some(BuiltinCall::AbiEncodeCall),
        "encodeWithSignature" => Some(BuiltinCall::AbiEncodeWithSignature),
        "encodeWithSelector" => Some(BuiltinCall::AbiEncodeWithSignature),
        "decode" => Some(BuiltinCall::AbiDecode),
        _ => None,
    }
}

fn resolve_storage_member(member: &str) -> Option<BuiltinCall> {
    // Note: every mapping here must target a syscall that exists in Neo N3's
    // ApplicationEngine interop table. The former `*Local` family lowered to
    // fictional `System.Storage.Local.*` names (sha256-hashed interop IDs that
    // no real node registers → unknown-syscall FAULT at runtime), and helpers
    // like `batchPut`/`count`/`exists`/`clearPrefix` were lowered to a single
    // raw syscall with the wrong arity and semantics. They were removed so
    // calls fail at compile time via the "unsupported builtin library call"
    // diagnostic instead of corrupting state or faulting on-chain.
    match member {
        "find" => Some(BuiltinCall::StorageFind),
        "put" => Some(BuiltinCall::StoragePut),
        "get" => Some(BuiltinCall::StorageGet),
        "remove" => Some(BuiltinCall::StorageDelete),
        "initializeContext" => Some(BuiltinCall::Syscall(
            "System.Storage.GetContext".to_string(),
        )),
        "getContext" => Some(BuiltinCall::Syscall(
            "System.Storage.GetContext".to_string(),
        )),
        "getReadOnlyContext" => Some(BuiltinCall::Syscall(
            "System.Storage.GetReadOnlyContext".to_string(),
        )),
        "asReadOnly" => Some(BuiltinCall::Syscall(
            "System.Storage.AsReadOnly".to_string(),
        )),
        _ => None,
    }
}

fn resolve_neo_member(member: &str) -> Option<BuiltinCall> {
    match member {
        "verifySignature" => Some(BuiltinCall::VerifySignature),
        "callContract" => Some(BuiltinCall::ContractCall),
        "deployContract" => Some(BuiltinCall::DeployContract),
        "getNeoBalance" => Some(BuiltinCall::NativeCall {
            contract: NativeContract::Neo,
            method: "balanceOf".to_string(),
        }),
        "getGasBalance" => Some(BuiltinCall::NativeCall {
            contract: NativeContract::Gas,
            method: "balanceOf".to_string(),
        }),
        "getGasPrice" => Some(BuiltinCall::NativeCall {
            contract: NativeContract::Policy,
            method: "getFeePerByte".to_string(),
        }),
        "getStoragePrice" => Some(BuiltinCall::NativeCall {
            contract: NativeContract::Policy,
            method: "getStoragePrice".to_string(),
        }),
        "getCommittee" => Some(BuiltinCall::NativeCall {
            contract: NativeContract::Neo,
            method: "getCommittee".to_string(),
        }),
        "getValidators" => Some(BuiltinCall::NativeCall {
            contract: NativeContract::Neo,
            method: "getNextBlockValidators".to_string(),
        }),
        "isCommittee" => Some(BuiltinCall::NativeCall {
            contract: NativeContract::Neo,
            method: "getCommittee".to_string(),
        }),
        "isValidator" => Some(BuiltinCall::NativeCall {
            contract: NativeContract::Neo,
            method: "getNextBlockValidators".to_string(),
        }),
        "getRandom" => Some(BuiltinCall::Syscall("System.Runtime.GetRandom".to_string())),
        "getBlockHeight" => Some(BuiltinCall::NativeCall {
            contract: NativeContract::Ledger,
            method: "currentIndex".to_string(),
        }),
        "getCurrentBlock" => Some(BuiltinCall::NativeCall {
            contract: NativeContract::Ledger,
            method: "currentIndex".to_string(),
        }),
        "transactionExists" => Some(BuiltinCall::NativeCall {
            contract: NativeContract::Ledger,
            method: "getTransaction".to_string(),
        }),
        "getNetworkMagic" => Some(BuiltinCall::Syscall(
            "System.Runtime.GetNetwork".to_string(),
        )),
        "getBlockByIndex" => Some(BuiltinCall::NativeCall {
            contract: NativeContract::Ledger,
            method: "getBlock".to_string(),
        }),
        "getBlockTime" => Some(BuiltinCall::Syscall("System.Runtime.GetTime".to_string())),
        "getTransaction" => Some(BuiltinCall::NativeCall {
            contract: NativeContract::Ledger,
            method: "getTransaction".to_string(),
        }),
        "getTransactionHeight" => Some(BuiltinCall::NativeCall {
            contract: NativeContract::Ledger,
            method: "getTransactionHeight".to_string(),
        }),
        "verifyWithWitness" => Some(BuiltinCall::Syscall(
            "System.Runtime.CheckWitness".to_string(),
        )),
        "sha256Hash" => Some(BuiltinCall::NativeCall {
            contract: NativeContract::CryptoLib,
            method: "sha256".to_string(),
        }),
        "ripemd160Hash" => Some(BuiltinCall::NativeCall {
            contract: NativeContract::CryptoLib,
            method: "ripemd160".to_string(),
        }),
        _ => None,
    }
}

/// `StdLib.<method>(...)` — resolve bare member-access into a NativeCall to
/// the StdLib native contract (hash c0ef39cee0e4e925c6c2a06a79e1440dd86fceac).
/// Solidity source can write either `StdLib.itoa(v, 10)` or the devpack's
/// `Syscalls.itoa(v, 10)`; both must land at the same CALLT. See
/// `resolve_syscalls_member` for the sibling dispatch.
fn resolve_stdlib_member(member: &str) -> Option<BuiltinCall> {
    match member {
        "serialize" | "deserialize" | "jsonSerialize" | "jsonDeserialize" | "itoa" | "atoi"
        | "base64Encode" | "base64Decode" | "base64UrlEncode" | "base64UrlDecode"
        | "base58Encode" | "base58Decode" | "base58CheckEncode" | "base58CheckDecode"
        | "hexEncode" | "hexDecode" | "memoryCompare" | "memorySearch" | "stringSplit"
        | "strLen" => Some(BuiltinCall::NativeCall {
            contract: NativeContract::StdLib,
            method: member.to_string(),
        }),
        _ => None,
    }
}

/// `CryptoLib.<method>(...)` — resolve bare member-access into a NativeCall
/// to the CryptoLib native contract (hash 1bf575ab11896884136110a35a12886cde0b66c72).
/// Keeps parity with `Syscalls.sha256` / `Syscalls.ripemd160` / etc.
fn resolve_cryptolib_member(member: &str) -> Option<BuiltinCall> {
    match member {
        "sha256" | "ripemd160" | "verifyWithECDsa" | "murmur32" | "keccak256"
        | "recoverSecp256K1" | "verifyWithEd25519" | "bls12381Serialize"
        | "bls12381Deserialize" | "bls12381Equal" | "bls12381Add" | "bls12381Mul"
        | "bls12381Pairing" | "bls12381G1Add" | "bls12381G1Mul" | "bls12381G2Add"
        | "bls12381G2Mul" | "bls12381G1Neg" | "bls12381G2Neg" => {
            Some(BuiltinCall::NativeCall {
                contract: NativeContract::CryptoLib,
                method: member.to_string(),
            })
        }
        _ => None,
    }
}

/// CI probe (devpack agent): the devpack `Runtime`/`Storage`/`Neo` libraries
/// are compiler intrinsics whose Solidity bodies are never compiled, so every
/// non-private function they declare MUST have an intrinsic lowering —
/// otherwise the shipped sources advertise an API that hard-fails at compile
/// time (or worse, used to silently miscompile, e.g. the fictional
/// `System.Storage.Local.*` syscall family). These tests keep the `.sol`
/// surface, the `builtin_library_supported_members` diagnostic whitelist, and
/// the actual lowerings in sync.
#[cfg(test)]
mod devpack_intrinsic_surface_tests {
    use super::*;
    use std::path::PathBuf;

    /// Members lowered by dedicated expansion handlers rather than
    /// `resolve_*_member`:
    /// - Runtime: `try_lower_runtime_member_builtin`
    ///   (src/ir/expressions/calls/builtins/member_runtime.rs)
    /// - Storage: `try_lower_storage_member_builtin`
    ///   (src/ir/expressions/calls/builtins/member_storage.rs)
    /// - Neo: `try_lower_neo_member_builtin`
    ///   (src/ir/expressions/calls/builtins/member_neo.rs) and
    ///   `try_lower_value_transfer_helpers`
    ///   (src/ir/expressions/calls/value_transfer.rs for
    ///   `transferGas`/`transferNeo`)
    fn special_case_lowerings(base: &str) -> &'static [&'static str] {
        match base {
            "Runtime" => &[
                "initializeServices",
                "notifyIndexed",
                "notify",
                "requireWitness",
                "checkAnyWitness",
                "checkAllWitnesses",
                "checkMultiSigWitness",
            ],
            "Storage" => &["putContractMetadata"],
            "Neo" => &[
                "isCommittee",
                "getCommittee",
                "getValidators",
                "isValidator",
                "transferGas",
                "transferNeo",
            ],
            _ => &[],
        }
    }

    fn has_lowering(base: &str, member: &str) -> bool {
        let resolved = match base {
            "Runtime" => resolve_runtime_member(member).is_some(),
            "Storage" => resolve_storage_member(member).is_some(),
            "Neo" => resolve_neo_member(member).is_some(),
            other => panic!("unexpected library base '{other}'"),
        };
        resolved || special_case_lowerings(base).contains(&member)
    }

    fn devpack_library_path(base: &str) -> PathBuf {
        PathBuf::from(env!("CARGO_MANIFEST_DIR"))
            .join("devpack")
            .join("libraries")
            .join(format!("{base}.sol"))
    }

    /// Extract the names of all non-private function declarations from a
    /// devpack library source. Private helpers (declared `private` or named
    /// with a leading underscore) are not part of the public surface.
    fn declared_public_functions(source: &str) -> Vec<String> {
        let mut names = Vec::new();
        for line in source.lines() {
            let trimmed = line.trim_start();
            let Some(rest) = trimmed.strip_prefix("function ") else {
                continue;
            };
            let Some(name) = rest.split('(').next() else {
                continue;
            };
            let name = name.trim();
            if name.is_empty() || name.starts_with('_') {
                continue;
            }
            // The visibility keyword may appear on the declaration line or a
            // follow-up line; devpack sources keep `private` on the same line.
            if trimmed.contains(" private ") || trimmed.ends_with(" private") {
                continue;
            }
            names.push(name.to_string());
        }
        names
    }

    #[test]
    fn every_declared_devpack_library_function_has_an_intrinsic_lowering() {
        for base in ["Runtime", "Storage", "Neo"] {
            let path = devpack_library_path(base);
            let source = std::fs::read_to_string(&path)
                .unwrap_or_else(|e| panic!("failed to read {}: {e}", path.display()));
            let declared = declared_public_functions(&source);
            assert!(
                !declared.is_empty(),
                "no function declarations found in {} — extraction regressed?",
                path.display()
            );

            let missing: Vec<&String> = declared
                .iter()
                .filter(|name| !has_lowering(base, name))
                .collect();
            assert!(
                missing.is_empty(),
                "devpack/libraries/{base}.sol declares functions with no compiler \
                 lowering (calls would hard-fail; prune them or add a lowering): {missing:?}"
            );
        }
    }

    #[test]
    fn every_declared_devpack_library_function_is_whitelisted() {
        // The "supported intrinsics" diagnostic emitted for unsupported
        // members lists `builtin_library_supported_members`; everything the
        // shipped sources declare should appear there.
        for base in ["Runtime", "Storage", "Neo"] {
            let path = devpack_library_path(base);
            let source = std::fs::read_to_string(&path)
                .unwrap_or_else(|e| panic!("failed to read {}: {e}", path.display()));
            let whitelist =
                builtin_library_supported_members(base).expect("builtin library whitelist");
            let missing: Vec<String> = declared_public_functions(&source)
                .into_iter()
                .filter(|name| !whitelist.contains(&name.as_str()))
                .collect();
            assert!(
                missing.is_empty(),
                "devpack/libraries/{base}.sol declares functions missing from \
                 builtin_library_supported_members: {missing:?}"
            );
        }
    }

    #[test]
    fn every_whitelisted_member_has_an_intrinsic_lowering() {
        // The converse direction: the whitelist is what the compiler prints
        // as "supported intrinsics", so a whitelisted member without a
        // lowering would advertise an API that still hard-fails.
        for base in ["Runtime", "Storage", "Neo"] {
            let whitelist =
                builtin_library_supported_members(base).expect("builtin library whitelist");
            let missing: Vec<&&str> = whitelist
                .iter()
                .filter(|member| !has_lowering(base, member))
                .collect();
            assert!(
                missing.is_empty(),
                "builtin_library_supported_members(\"{base}\") lists members \
                 with no compiler lowering: {missing:?}"
            );
        }
    }

    #[test]
    fn fictional_local_storage_syscalls_are_not_resolvable() {
        // Regression: `Storage.putLocal`/`getLocal`/`removeLocal`/`findLocal`
        // and the matching `Syscalls.storage*Local` wrappers lowered to
        // `System.Storage.Local.*` — syscalls that do not exist in Neo N3's
        // interop table, so compiled contracts faulted on real nodes. They
        // must stay unresolvable (callers now get the loud "unsupported
        // builtin library call" diagnostic).
        for member in ["putLocal", "getLocal", "removeLocal", "findLocal"] {
            assert!(
                resolve_storage_member(member).is_none(),
                "Storage.{member} must not resolve to an intrinsic"
            );
            assert!(
                !builtin_library_supported_members("Storage")
                    .expect("Storage whitelist")
                    .contains(&member),
                "Storage.{member} must not be whitelisted"
            );
        }
        for member in [
            "storageGetLocal",
            "storagePutLocal",
            "storageDeleteLocal",
            "storageFindLocal",
        ] {
            assert!(
                resolve_syscalls_member(member).is_none(),
                "Syscalls.{member} must not resolve to an intrinsic"
            );
            assert!(
                !builtin_library_supported_members("Syscalls")
                    .expect("Syscalls whitelist")
                    .contains(&member),
                "Syscalls.{member} must not be whitelisted"
            );
        }
    }

    #[test]
    fn miscompiling_storage_helpers_are_not_resolvable() {
        // Regression: these documented helpers used to lower to a single raw
        // syscall with the wrong arity/semantics (e.g. `count` returned an
        // iterator handle, `batchPut` issued one put with the arrays as
        // key/value, `getUsage` was a hardcoded PUSH0 stub). They must stay
        // unresolvable until faithful expansions exist.
        for member in [
            "batchPut",
            "batchGet",
            "batchDelete",
            "count",
            "countLocal",
            "findValues",
            "findLocalValues",
            "findKeys",
            "findLocalKeys",
            "clearPrefix",
            "exists",
            "isValidKey",
            "getUsage",
        ] {
            assert!(
                resolve_storage_member(member).is_none(),
                "Storage.{member} must not resolve to an intrinsic"
            );
            assert!(
                !builtin_library_supported_members("Storage")
                    .expect("Storage whitelist")
                    .contains(&member),
                "Storage.{member} must not be whitelisted"
            );
        }
    }

    #[test]
    fn no_resolver_emits_syscalls_outside_the_neo_n3_interop_table() {
        // Every BuiltinCall::Syscall name produced by the resolvers must be a
        // real Neo N3 ApplicationEngine interop. Guards against reintroducing
        // fictional names like System.Storage.Local.* or
        // System.Storage.GetUsage (interop IDs are sha256-derived, so an
        // unknown name compiles fine and FAULTs on real nodes).
        const CANONICAL: &[&str] = &[
            "System.Contract.Call",
            "System.Contract.CallNative",
            "System.Contract.CreateMultisigAccount",
            "System.Contract.CreateStandardAccount",
            "System.Contract.GetCallFlags",
            "System.Contract.NativeOnPersist",
            "System.Contract.NativePostPersist",
            "System.Crypto.CheckMultisig",
            "System.Crypto.CheckSig",
            "System.Iterator.Next",
            "System.Iterator.Value",
            "System.Runtime.BurnGas",
            "System.Runtime.CheckWitness",
            "System.Runtime.CurrentSigners",
            "System.Runtime.GasLeft",
            "System.Runtime.GetAddressVersion",
            "System.Runtime.GetCallingScriptHash",
            "System.Runtime.GetEntryScriptHash",
            "System.Runtime.GetExecutingScriptHash",
            "System.Runtime.GetInvocationCounter",
            "System.Runtime.GetNetwork",
            "System.Runtime.GetNotifications",
            "System.Runtime.GetRandom",
            "System.Runtime.GetScriptContainer",
            "System.Runtime.GetTime",
            "System.Runtime.GetTrigger",
            "System.Runtime.LoadScript",
            "System.Runtime.Log",
            "System.Runtime.Notify",
            "System.Runtime.Platform",
            "System.Storage.AsReadOnly",
            "System.Storage.Delete",
            "System.Storage.Find",
            "System.Storage.Get",
            "System.Storage.GetContext",
            "System.Storage.GetReadOnlyContext",
            "System.Storage.Put",
        ];

        let probe = |label: &str, builtin: Option<BuiltinCall>| {
            if let Some(BuiltinCall::Syscall(name)) = builtin {
                assert!(
                    CANONICAL.contains(&name.as_str()),
                    "{label} lowers to syscall '{name}' which is not in the \
                     Neo N3 interop table"
                );
            }
        };

        for base in ["Runtime", "Storage", "Syscalls", "Neo"] {
            let members = builtin_library_supported_members(base).expect("whitelist");
            for member in members {
                let builtin = match base {
                    "Runtime" => resolve_runtime_member(member),
                    "Storage" => resolve_storage_member(member),
                    "Syscalls" => resolve_syscalls_member(member),
                    "Neo" => resolve_neo_member(member),
                    _ => unreachable!(),
                };
                probe(&format!("{base}.{member}"), builtin);
            }
        }
    }
}