|
| 1 | +# light-instruction-decoder-derive |
| 2 | + |
| 3 | +Procedural macros for generating `InstructionDecoder` implementations. |
| 4 | + |
| 5 | +## Overview |
| 6 | + |
| 7 | +This crate provides two macros for generating instruction decoders: |
| 8 | + |
| 9 | +| Macro | Type | Purpose | |
| 10 | +|-------|------|---------| |
| 11 | +| `#[derive(InstructionDecoder)]` | Derive | Generate decoder for instruction enums | |
| 12 | +| `#[instruction_decoder]` | Attribute | Auto-generate from Anchor program modules | |
| 13 | + |
| 14 | +## Module Structure |
| 15 | + |
| 16 | +``` |
| 17 | +src/ |
| 18 | +├── lib.rs # Macro entry points only (~100 lines) |
| 19 | +├── utils.rs # Case conversion, discriminator, error handling |
| 20 | +├── parsing.rs # Darling-based attribute parsing structs |
| 21 | +├── builder.rs # InstructionDecoderBuilder (code generation) |
| 22 | +├── derive_impl.rs # #[derive(InstructionDecoder)] implementation |
| 23 | +├── attribute_impl.rs # #[instruction_decoder] attribute implementation |
| 24 | +└── crate_context.rs # Recursive crate parsing for Accounts struct discovery |
| 25 | +``` |
| 26 | + |
| 27 | +## Key Features |
| 28 | + |
| 29 | +### Multiple Discriminator Sizes |
| 30 | + |
| 31 | +- **1 byte**: Native programs with simple instruction indices |
| 32 | +- **4 bytes**: System-style programs (little-endian u32) |
| 33 | +- **8 bytes**: Anchor programs (SHA256 prefix, default) |
| 34 | + |
| 35 | +### Explicit Discriminators |
| 36 | + |
| 37 | +Two syntax forms for specifying explicit discriminators: |
| 38 | + |
| 39 | +1. **Integer**: `#[discriminator = 5]` - for 1-byte and 4-byte modes |
| 40 | +2. **Array**: `#[discriminator(26, 16, 169, 7, 21, 202, 242, 25)]` - for 8-byte mode with custom discriminators |
| 41 | + |
| 42 | +### Account Names Extraction |
| 43 | + |
| 44 | +Two ways to specify account names: |
| 45 | + |
| 46 | +1. **Accounts type reference**: `accounts = MyAccountsStruct` - extracts field names at compile time |
| 47 | +2. **Inline names**: Direct array `["source", "dest", "authority"]` |
| 48 | + |
| 49 | +When using `accounts = SomeType`, the macro uses `CrateContext` to parse the crate at macro expansion time and extract field names from the struct definition. This works for any struct with named fields (including standard Anchor `#[derive(Accounts)]` structs) without requiring any special trait implementation. |
| 50 | + |
| 51 | +### Off-chain Only |
| 52 | + |
| 53 | +All generated code is gated with `#[cfg(not(target_os = "solana"))]` since instruction decoding is only needed for logging/debugging. |
| 54 | + |
| 55 | +## Usage Examples |
| 56 | + |
| 57 | +### Derive Macro |
| 58 | + |
| 59 | +```rust |
| 60 | +use light_instruction_decoder_derive::InstructionDecoder; |
| 61 | + |
| 62 | +#[derive(InstructionDecoder)] |
| 63 | +#[instruction_decoder( |
| 64 | + program_id = "MyProgramId111111111111111111111111111111111", |
| 65 | + program_name = "My Program", // optional |
| 66 | + discriminator_size = 8 // optional: 1, 4, or 8 |
| 67 | +)] |
| 68 | +pub enum MyInstruction { |
| 69 | + // Reference Accounts struct for account names |
| 70 | + #[instruction_decoder(accounts = CreateRecord, params = CreateRecordParams)] |
| 71 | + CreateRecord, |
| 72 | + |
| 73 | + // Inline account names |
| 74 | + #[instruction_decoder(account_names = ["source", "dest"])] |
| 75 | + Transfer, |
| 76 | + |
| 77 | + // Explicit integer discriminator (for 1-byte or 4-byte modes) |
| 78 | + #[discriminator = 5] |
| 79 | + Close, |
| 80 | + |
| 81 | + // Explicit array discriminator (for 8-byte mode with custom discriminators) |
| 82 | + #[discriminator(26, 16, 169, 7, 21, 202, 242, 25)] |
| 83 | + #[instruction_decoder(account_names = ["fee_payer", "authority"])] |
| 84 | + CustomInstruction, |
| 85 | +} |
| 86 | +``` |
| 87 | + |
| 88 | +### Attribute Macro (Anchor Programs) |
| 89 | + |
| 90 | +```rust |
| 91 | +use light_instruction_decoder_derive::instruction_decoder; |
| 92 | + |
| 93 | +#[instruction_decoder] // or #[instruction_decoder(program_id = crate::ID)] |
| 94 | +#[program] |
| 95 | +pub mod my_program { |
| 96 | + pub fn create_record(ctx: Context<CreateRecord>, params: CreateParams) -> Result<()> { ... } |
| 97 | + pub fn transfer(ctx: Context<Transfer>) -> Result<()> { ... } |
| 98 | +} |
| 99 | +``` |
| 100 | + |
| 101 | +This generates `MyProgramInstructionDecoder` that: |
| 102 | +- Gets program_id from `crate::ID` (or `declare_id!` if found) |
| 103 | +- Extracts function names and converts to discriminators |
| 104 | +- Discovers Accounts struct field names from the crate |
| 105 | +- Decodes params using borsh if specified |
| 106 | + |
| 107 | +## Architecture |
| 108 | + |
| 109 | +### Darling-Based Parsing |
| 110 | + |
| 111 | +Attributes are parsed using the `darling` crate for: |
| 112 | +- Declarative struct-based definitions |
| 113 | +- Automatic validation |
| 114 | +- Better error messages with span preservation |
| 115 | + |
| 116 | +### Builder Pattern |
| 117 | + |
| 118 | +`InstructionDecoderBuilder` separates: |
| 119 | +- **Parsing**: Extract and validate attributes |
| 120 | +- **Code Generation**: Produce TokenStream output |
| 121 | + |
| 122 | +This follows the pattern from `sdk-libs/macros`. |
| 123 | + |
| 124 | +### Crate Context |
| 125 | + |
| 126 | +`CrateContext` recursively parses all module files at macro expansion time to discover structs by name. This enables both macros to automatically find field names: |
| 127 | + |
| 128 | +- **Derive macro**: When `accounts = SomeType` is specified, extracts struct field names |
| 129 | +- **Attribute macro**: Discovers Accounts structs from `Context<T>` parameters |
| 130 | + |
| 131 | +The struct lookup finds any struct with named fields - no special trait implementation required. This makes the macro completely independent and works with any Anchor program. |
| 132 | + |
| 133 | +## Testing |
| 134 | + |
| 135 | +```bash |
| 136 | +# Unit tests |
| 137 | +cargo test -p light-instruction-decoder-derive |
| 138 | + |
| 139 | +# Integration tests (verifies generated code compiles and works) |
| 140 | +cargo test-sbf -p csdk-anchor-full-derived-test --test instruction_decoder_test |
| 141 | +``` |
| 142 | + |
| 143 | +## Dependencies |
| 144 | + |
| 145 | +- `darling`: Attribute parsing |
| 146 | +- `syn/quote/proc-macro2`: Token manipulation |
| 147 | +- `sha2`: Anchor discriminator computation |
| 148 | +- `bs58`: Program ID encoding |
0 commit comments