@cardananium/cquisitor-lib 0.1.0-beta.3 → 0.1.0-beta.31

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,432 @@
1
+ # Cquisitor-lib
2
+
3
+ A Cardano transaction validation and decoding library written in Rust and compiled to WebAssembly. Provides transaction validation according to ledger rules (Phase 1 and Phase 2), universal CBOR/Cardano type decoders, Plutus script decoders, and signature verification.
4
+
5
+ ## Features
6
+
7
+ ### Transaction Validation
8
+
9
+ Phase 1 validation covers balance, fees, witnesses, collateral, certificates, outputs, and transaction limits. Phase 2 executes Plutus V1/V2/V3 scripts with detailed redeemer results.
10
+
11
+ ### Universal Decoder
12
+
13
+ Decode 152+ Cardano types from hex/bech32/base58 encoding:
14
+ - Primitive types: `Address`, `PublicKey`, `PrivateKey`, `TransactionHash`, `ScriptHash`, etc.
15
+ - Complex structures: `Transaction`, `Block`, `TransactionBody`, `TransactionWitnessSet`
16
+ - Certificates: `StakeRegistration`, `PoolRegistration`, `DRepRegistration`, governance actions
17
+ - Plutus: `PlutusScript`, `PlutusData`, `Redeemer`, `ScriptRef`
18
+ - All credential types, native scripts, metadata structures
19
+
20
+ Functions:
21
+ - `get_decodable_types()` - Returns list of all supported type names
22
+ - `decode_specific_type(hex, type_name, params)` - Decode specific Cardano type
23
+ - `get_possible_types_for_input(hex)` - Suggests types that can decode given input
24
+
25
+ ### CBOR Decoder
26
+
27
+ `cbor_to_json(cbor_hex)` - Converts raw CBOR to JSON with positional information, supporting indefinite arrays/maps and all CBOR types.
28
+
29
+ ### Plutus Script Decoder
30
+
31
+ - `decode_plutus_program_uplc_json(hex)` - Decodes Plutus script to UPLC AST JSON
32
+ - `decode_plutus_program_pretty_uplc(hex)` - Decodes to human-readable UPLC format
33
+
34
+ Handles double CBOR wrapping and normalization automatically.
35
+
36
+ ### Signature Verification
37
+
38
+ `check_block_or_tx_signatures(hex)` - Verifies all VKey and Catalyst witness signatures in transactions or entire blocks. Returns validation results with invalid signature details.
39
+
40
+ ### Script Execution
41
+
42
+ `execute_tx_scripts(tx_hex, utxos, cost_models)` - Executes all Plutus scripts in a transaction independently, returning execution units, logs, and success/failure for each redeemer.
43
+
44
+ ### Validation Coverage
45
+
46
+ **Phase 1 Validation:**
47
+ - Balance validation (inputs, outputs, fees, deposits, refunds)
48
+ - Fee calculation and validation (including script reference fees)
49
+ - Cryptographic witness validation (signatures, native scripts)
50
+ - Collateral validation for script transactions
51
+ - Certificate validation (stake registration, pool operations, DReps, governance)
52
+ - Output validation (minimum ADA, size limits)
53
+ - Transaction limits (size, execution units, reference scripts)
54
+ - Auxiliary data validation
55
+
56
+ **Phase 2 Validation:**
57
+ - Plutus V1, V2, and V3 script execution
58
+ - Redeemer validation with execution units
59
+ - Script context generation
60
+
61
+ See [WHAT-IS-COVERED.md](./WHAT-IS-COVERED.md) for a complete list of validation errors and warnings.
62
+
63
+ ## Installation
64
+
65
+ ### NPM/Yarn/PNPM
66
+
67
+ ```bash
68
+ npm install @cardananium/cquisitor-lib
69
+ ```
70
+
71
+ ```bash
72
+ yarn add @cardananium/cquisitor-lib
73
+ ```
74
+
75
+ ```bash
76
+ pnpm add @cardananium/cquisitor-lib
77
+ ```
78
+
79
+ ### Browser
80
+
81
+ For browser usage, import from the browser-specific build:
82
+
83
+ ```javascript
84
+ import { get_necessary_data_list_js, validate_transaction_js } from '@cardananium/cquisitor-lib/browser';
85
+ ```
86
+
87
+ ### Node.js
88
+
89
+ For Node.js usage:
90
+
91
+ ```javascript
92
+ import { get_necessary_data_list_js, validate_transaction_js } from '@cardananium/cquisitor-lib';
93
+ ```
94
+
95
+ ## Quick Start
96
+
97
+ ### Basic Usage
98
+
99
+ ```typescript
100
+ import {
101
+ get_necessary_data_list_js,
102
+ validate_transaction_js
103
+ } from '@cardananium/cquisitor-lib';
104
+
105
+ // Step 1: Parse transaction and identify required data
106
+ const txHex = "84a400..."; // Your transaction in hex format
107
+ const necessaryDataJson = get_necessary_data_list_js(txHex);
108
+ const necessaryData = JSON.parse(necessaryDataJson);
109
+
110
+ console.log('Required UTXOs:', necessaryData.utxos);
111
+ console.log('Required accounts:', necessaryData.accounts);
112
+ console.log('Required pools:', necessaryData.pools);
113
+
114
+ // Step 2: Fetch the required data from your blockchain indexer
115
+ // (e.g., Blockfrost, Koios, or your own node)
116
+ const utxos = await fetchUtxos(necessaryData.utxos);
117
+ const accounts = await fetchAccounts(necessaryData.accounts);
118
+ const pools = await fetchPools(necessaryData.pools);
119
+ const protocolParams = await getProtocolParameters();
120
+ const currentSlot = await getCurrentSlot();
121
+
122
+ // Step 3: Build validation context
123
+ const validationContext = {
124
+ slot: currentSlot,
125
+ networkType: "mainnet", // or "preview" or "preprod"
126
+ protocolParameters: protocolParams,
127
+ utxoSet: utxos,
128
+ accountContexts: accounts,
129
+ poolContexts: pools,
130
+ drepContexts: [],
131
+ govActionContexts: [],
132
+ lastEnactedGovAction: [],
133
+ currentCommitteeMembers: [],
134
+ potentialCommitteeMembers: [],
135
+ treasuryValue: 0n
136
+ };
137
+
138
+ // Step 4: Validate the transaction
139
+ const resultJson = validate_transaction_js(
140
+ txHex,
141
+ JSON.stringify(validationContext)
142
+ );
143
+ const result = JSON.parse(resultJson);
144
+
145
+ // Step 5: Check validation results
146
+ if (result.errors.length > 0) {
147
+ console.error('❌ Transaction validation failed:');
148
+ result.errors.forEach(err => {
149
+ console.error(`- ${err.error_message}`);
150
+ if (err.hint) {
151
+ console.error(` Hint: ${err.hint}`);
152
+ }
153
+ });
154
+ } else if (result.phase2_errors.length > 0) {
155
+ console.error('❌ Script execution failed:');
156
+ result.phase2_errors.forEach(err => {
157
+ console.error(`- ${err.error_message}`);
158
+ });
159
+ } else {
160
+ console.log('✅ Transaction is valid!');
161
+ }
162
+
163
+ // Check for warnings
164
+ if (result.warnings.length > 0) {
165
+ console.warn('⚠️ Warnings:', result.warnings);
166
+ }
167
+ ```
168
+
169
+ ### Complete Example with Error Handling
170
+
171
+ ```typescript
172
+ import {
173
+ get_necessary_data_list_js,
174
+ validate_transaction_js
175
+ } from '@cardananium/cquisitor-lib';
176
+
177
+ async function validateTransaction(txHex: string): Promise<boolean> {
178
+ try {
179
+ // Parse transaction
180
+ const necessaryDataJson = get_necessary_data_list_js(txHex);
181
+ const necessaryData = JSON.parse(necessaryDataJson);
182
+
183
+ // Fetch required blockchain data
184
+ // (Implementation depends on your data source)
185
+ const context = await buildValidationContext(necessaryData);
186
+
187
+ // Validate
188
+ const resultJson = validate_transaction_js(
189
+ txHex,
190
+ JSON.stringify(context)
191
+ );
192
+ const result = JSON.parse(resultJson);
193
+
194
+ // Log detailed results
195
+ const hasErrors = result.errors.length > 0 || result.phase2_errors.length > 0;
196
+
197
+ if (!hasErrors) {
198
+ console.log('✅ Transaction is valid!');
199
+
200
+ // Log redeemer execution details
201
+ result.eval_redeemer_results.forEach(redeemer => {
202
+ console.log(`Redeemer ${redeemer.tag}[${redeemer.index}]:`);
203
+ console.log(` Success: ${redeemer.success}`);
204
+ console.log(` Ex units: ${JSON.stringify(redeemer.calculated_ex_units)}`);
205
+ if (redeemer.logs.length > 0) {
206
+ console.log(` Logs: ${redeemer.logs.join(', ')}`);
207
+ }
208
+ });
209
+ } else {
210
+ console.error('❌ Validation failed');
211
+ [...result.errors, ...result.phase2_errors].forEach(err => {
212
+ console.error(`- ${err.error_message}`);
213
+ });
214
+ }
215
+
216
+ return !hasErrors;
217
+
218
+ } catch (error) {
219
+ console.error('Validation error:', error);
220
+ return false;
221
+ }
222
+ }
223
+ ```
224
+
225
+ ## API Reference
226
+
227
+ ### Transaction Validation
228
+
229
+ #### `get_necessary_data_list_js(tx_hex: string): string`
230
+
231
+ Extracts required blockchain data for validation.
232
+
233
+ ```typescript
234
+ const necessaryData = JSON.parse(get_necessary_data_list_js(txHex));
235
+ // Returns: { utxos, accounts, pools, dReps, govActions, ... }
236
+ ```
237
+
238
+ #### `validate_transaction_js(tx_hex: string, validation_context: string): string`
239
+
240
+ Validates transaction with full ledger rules.
241
+
242
+ ```typescript
243
+ const result = JSON.parse(validate_transaction_js(txHex, JSON.stringify(context)));
244
+ // Returns: { errors, warnings, phase2_errors, phase2_warnings, eval_redeemer_results }
245
+ ```
246
+
247
+ #### `get_utxo_list_from_tx(tx_hex: string): string[]`
248
+
249
+ Extracts all UTxO references (inputs + collateral + reference inputs) from transaction.
250
+
251
+ ### Universal Decoder
252
+
253
+ #### `get_decodable_types(): string[]`
254
+
255
+ Returns array of all 152+ decodable type names.
256
+
257
+ ```typescript
258
+ const types = get_decodable_types();
259
+ // ['Address', 'Transaction', 'PlutusScript', 'PublicKey', ...]
260
+ ```
261
+
262
+ #### `decode_specific_type(input: string, type_name: string, params: DecodingParams): any`
263
+
264
+ Decodes specific Cardano type from hex/bech32/base58.
265
+
266
+ ```typescript
267
+ const address = decode_specific_type(
268
+ "addr1...",
269
+ "Address",
270
+ { plutusDataSchema: "DetailedSchema" }
271
+ );
272
+
273
+ const tx = decode_specific_type(
274
+ "84a400...",
275
+ "Transaction",
276
+ { plutusDataSchema: "DetailedSchema" }
277
+ );
278
+ ```
279
+
280
+ #### `get_possible_types_for_input(input: string): string[]`
281
+
282
+ Suggests which types can decode the given input.
283
+
284
+ ```typescript
285
+ const possibleTypes = get_possible_types_for_input("e1a...");
286
+ // ['Address', 'BaseAddress', 'EnterpriseAddress', ...]
287
+ ```
288
+
289
+ ### CBOR Decoder
290
+
291
+ #### `cbor_to_json(cbor_hex: string): CborValue`
292
+
293
+ Converts CBOR to JSON with positional metadata.
294
+
295
+ ```typescript
296
+ const cbor = cbor_to_json("a26461646472...");
297
+ // Returns structured JSON with position info for each element
298
+ ```
299
+
300
+ ### Plutus Script Decoder
301
+
302
+ #### `decode_plutus_program_uplc_json(hex: string): ProgramJson`
303
+
304
+ Decodes Plutus script to UPLC AST in JSON format.
305
+
306
+ ```typescript
307
+ const program = decode_plutus_program_uplc_json("59012a01000...");
308
+ // Returns: { version: [1,0,0], program: { ... } }
309
+ ```
310
+
311
+ #### `decode_plutus_program_pretty_uplc(hex: string): string`
312
+
313
+ Decodes Plutus script to human-readable UPLC.
314
+
315
+ ```typescript
316
+ const code = decode_plutus_program_pretty_uplc("59012a01000...");
317
+ // Returns: "(program 1.0.0 (lam x_0 ...))"
318
+ ```
319
+
320
+ ### Signature Verification
321
+
322
+ #### `check_block_or_tx_signatures(hex: string): CheckSignaturesResult`
323
+
324
+ Verifies all signatures in transaction or block.
325
+
326
+ ```typescript
327
+ const result = check_block_or_tx_signatures(txHex);
328
+ // Returns: { valid, results: [{ valid, tx_hash, invalidVkeyWitnesses, invalidCatalystWitnesses }] }
329
+ ```
330
+
331
+ ### Script Execution
332
+
333
+ #### `execute_tx_scripts(tx_hex: string, utxos: UTxO[], cost_models: CostModels): ExecuteTxScriptsResult`
334
+
335
+ Executes all Plutus scripts in transaction.
336
+
337
+ ```typescript
338
+ const result = execute_tx_scripts(txHex, utxos, costModels);
339
+ // Returns execution units, logs, and status for each redeemer
340
+ ```
341
+
342
+ ## Data Sources
343
+
344
+ To populate the validation context, you'll need to fetch blockchain data from a Cardano indexer or node. Recommended sources:
345
+
346
+ - **[Blockfrost](https://blockfrost.io/)** - Reliable API with generous free tier
347
+ - **[Koios](https://koios.rest/)** - Community-driven API with rich queries
348
+ - **Cardano Node** - Direct access via `cardano-cli` or `cardano-db-sync`
349
+ - **Custom Indexer** - Roll your own using Pallas or similar libraries
350
+
351
+ ## Building from Source
352
+
353
+ ### Prerequisites
354
+
355
+ - Rust 1.83 or newer
356
+ - `wasm-pack`
357
+ - Node.js and npm
358
+
359
+ ### Build Steps
360
+
361
+ ```bash
362
+ # Clone the repository
363
+ git clone https://github.com/your-org/cquisitor-lib.git
364
+ cd cquisitor-lib
365
+
366
+ # Build for Node.js
367
+ npm run rust:build-wasm:node
368
+
369
+ # Build for browser
370
+ npm run rust:build-wasm:browser
371
+
372
+ # Build both targets
373
+ npm run build-all
374
+
375
+ # Generate TypeScript definitions
376
+ npm run generate-dts
377
+ ```
378
+
379
+ ## Type Definitions
380
+
381
+ Full TypeScript type definitions are available in the package and cover all input and output types. The main types include:
382
+
383
+ - `NecessaryInputData` - Required blockchain data for validation
384
+ - `ValidationInputContext` - Complete validation context structure
385
+ - `ValidationResult` - Validation results with errors and warnings
386
+ - `ProtocolParameters` - Cardano protocol parameters
387
+ - And many more detailed types for UTXOs, certificates, governance, etc.
388
+
389
+ See [types/cquisitor_lib.d.ts](./types/cquisitor_lib.d.ts) for the complete type definitions.
390
+
391
+ ## Performance
392
+
393
+ Written in Rust and compiled to WebAssembly for near-native performance in browsers and Node.js.
394
+
395
+ ## Contributing
396
+
397
+ Contributions are welcome! Please feel free to submit pull requests or open issues for bugs and feature requests.
398
+
399
+ ### Development Workflow
400
+
401
+ 1. Fork the repository
402
+ 2. Create a feature branch (`git checkout -b feature/amazing-feature`)
403
+ 3. Make your changes
404
+ 4. Run tests (`cargo test`)
405
+ 5. Commit your changes (`git commit -m 'Add amazing feature'`)
406
+ 6. Push to the branch (`git push origin feature/amazing-feature`)
407
+ 7. Open a Pull Request
408
+
409
+ ## License
410
+
411
+ This project is licensed under the Apache License 2.0 - see the [LICENSE](./LICENSE) file for details.
412
+
413
+ ## Acknowledgments
414
+
415
+ This library builds upon the excellent work of the Cardano community, particularly:
416
+
417
+ - [cardano-serialization-lib](https://github.com/Emurgo/cardano-serialization-lib) - For cardano structures deserialization
418
+ - [Pallas](https://github.com/txpipe/pallas) - Cardano primitives
419
+ - [UPLC](https://github.com/aiken-lang/uplc) - Plutus script execution
420
+ - The Cardano Ledger specification team
421
+
422
+ ## Support
423
+
424
+ For questions and support:
425
+
426
+ - 📖 Check the [API Documentation](./API_DOCUMENTATION.md)
427
+ - 🐛 Report bugs via [GitHub Issues](https://github.com/your-org/cquisitor-lib/issues)
428
+
429
+ ---
430
+
431
+ Made with ❤️ for the Cardano ecosystem
432
+