koios-sdk 0.1.1

A Rust SDK for the Koios Cardano API
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
// tests/script_tests.rs

use koios_sdk::{
    models::script::{RedeemerPurpose, ScriptType},
    types::{Extended, ScriptHash},
    Client,
};
use pretty_assertions::assert_eq;
use serde_json::json;
use wiremock::{
    matchers::{body_json, header, method, path, query_param},
    Mock, MockServer, ResponseTemplate,
};

// Helper function to create test client with mock server
async fn setup_test_client() -> (MockServer, Client) {
    let mock_server = MockServer::start().await;
    let client = Client::builder()
        .base_url(mock_server.uri())
        .build()
        .unwrap();
    (mock_server, client)
}

#[tokio::test]
async fn test_get_script_info() {
    let (mock_server, client) = setup_test_client().await;

    let script_hashes =
        vec!["67f33146617a5e61936081db3b2117cbf59bd2123748f58ac9678656".to_string()];

    let mock_response = json!([{
        "script_hash": "67f33146617a5e61936081db3b2117cbf59bd2123748f58ac9678656",
        "creation_tx_hash": "6ed09ba58a56c6e946668038ba4d3cef8eb97a20cbf76c5970e1402e8a8d6541",
        "type": "plutusv1",
        "value": {
            "constructor": 0,
            "fields": []
        },
        "bytes": "4e4d01000033222220051200120011",
        "size": 42
    }]);

    Mock::given(method("POST"))
        .and(path("/script_info"))
        .and(header("Content-Type", "application/json"))
        .and(body_json(json!({
            "_script_hashes": script_hashes
        })))
        .respond_with(ResponseTemplate::new(200).set_body_json(&mock_response))
        .mount(&mock_server)
        .await;

    let response = client.get_script_info(&script_hashes).await.unwrap();
    assert_eq!(response.len(), 1);
    assert_eq!(
        response[0].script_hash.as_ref().unwrap(),
        "67f33146617a5e61936081db3b2117cbf59bd2123748f58ac9678656"
    );
    assert_eq!(
        response[0].creation_tx_hash,
        "6ed09ba58a56c6e946668038ba4d3cef8eb97a20cbf76c5970e1402e8a8d6541"
    );
    assert_eq!(response[0].script_type, ScriptType::PlutusV1);
    assert_eq!(response[0].size, 42);
}

#[tokio::test]
async fn test_get_native_script_list() {
    let (mock_server, client) = setup_test_client().await;

    let mock_response = json!([{
        "script_hash": "67f33146617a5e61936081db3b2117cbf59bd2123748f58ac9678656",
        "creation_tx_hash": "6ed09ba58a56c6e946668038ba4d3cef8eb97a20cbf76c5970e1402e8a8d6541",
        "type": "timelock",
        "size": 42
    }]);

    Mock::given(method("GET"))
        .and(path("/native_script_list"))
        .respond_with(ResponseTemplate::new(200).set_body_json(&mock_response))
        .mount(&mock_server)
        .await;

    let response = client.get_native_script_list().await.unwrap();
    assert_eq!(response.len(), 1);
    assert_eq!(
        response[0].script_hash,
        "67f33146617a5e61936081db3b2117cbf59bd2123748f58ac9678656"
    );
    assert_eq!(response[0].script_type, ScriptType::Timelock);
}

#[tokio::test]
async fn test_get_plutus_script_list() {
    let (mock_server, client) = setup_test_client().await;

    let mock_response = json!([{
        "script_hash": "67f33146617a5e61936081db3b2117cbf59bd2123748f58ac9678656",
        "creation_tx_hash": "6ed09ba58a56c6e946668038ba4d3cef8eb97a20cbf76c5970e1402e8a8d6541",
        "type": "plutusv1",
        "size": 42
    }]);

    Mock::given(method("GET"))
        .and(path("/plutus_script_list"))
        .respond_with(ResponseTemplate::new(200).set_body_json(&mock_response))
        .mount(&mock_server)
        .await;

    let response = client.get_plutus_script_list().await.unwrap();
    assert_eq!(response.len(), 1);
    assert_eq!(
        response[0].script_hash,
        "67f33146617a5e61936081db3b2117cbf59bd2123748f58ac9678656"
    );
    assert_eq!(response[0].script_type, ScriptType::PlutusV1);
}

#[tokio::test]
async fn test_get_script_redeemers() {
    let (mock_server, client) = setup_test_client().await;

    let script_hash = "67f33146617a5e61936081db3b2117cbf59bd2123748f58ac9678656";

    let mock_response = json!([{
        "script_hash": script_hash,
        "redeemers": [{
            "tx_hash": "6ed09ba58a56c6e946668038ba4d3cef8eb97a20cbf76c5970e1402e8a8d6541",
            "tx_index": 0,
            "unit_mem": "1000",
            "unit_steps": "500",
            "fee": "500000",
            "purpose": "spend",
            "datum_hash": "ab01cd23",
            "datum_value": {
                "constructor": 0,
                "fields": []
            }
        }]
    }]);

    Mock::given(method("GET"))
        .and(path("/script_redeemers"))
        .and(query_param("_script_hash", script_hash))
        .respond_with(ResponseTemplate::new(200).set_body_json(&mock_response))
        .mount(&mock_server)
        .await;

    let response = client
        .get_script_redeemers(&ScriptHash::new(script_hash))
        .await
        .unwrap();
    assert_eq!(response.len(), 1);
    assert_eq!(response[0].script_hash, script_hash);
    assert_eq!(response[0].redeemers.len(), 1);

    let redeemer = &response[0].redeemers[0];
    assert_eq!(
        redeemer.tx_hash,
        "6ed09ba58a56c6e946668038ba4d3cef8eb97a20cbf76c5970e1402e8a8d6541"
    );
    assert_eq!(redeemer.fee, "500000");
    assert_eq!(redeemer.purpose, RedeemerPurpose::Spend);
    assert_eq!(redeemer.datum_hash.as_ref().unwrap(), "ab01cd23");
}

#[tokio::test]
async fn test_get_script_utxos() {
    let (mock_server, client) = setup_test_client().await;

    let script_hash = ScriptHash::new("67f33146617a5e61936081db3b2117cbf59bd2123748f58ac9678656");

    let mock_response = json!([{
        "tx_hash": "6ed09ba58a56c6e946668038ba4d3cef8eb97a20cbf76c5970e1402e8a8d6541",
        "tx_index": 0,
        "address": "addr1qxqs59lphg8g6qndelq8xwqn60ag3aeyfcp33c2kdp46a09re5df3pzwwmyq946axfcejy5n4x0y99wqpgtp2gd0k09qsgy6pz",
        "value": "12345678",
        "stake_address": "stake1u9ylzsgxaa6xctf4juup682ar3juj85n8tx3hthnljg47zctvm3rc",
        "payment_cred": "a2944a17b8d8b7ede6e365432cf59ff5276c7c3a99e2b89d47c87661",
        "epoch_no": 321,
        "block_height": 7017300,
        "block_time": 1630106091,
        "datum_hash": null,
        "inline_datum": null,
        "reference_script": null,
        "asset_list": [],
        "is_spent": false
    }]);

    Mock::given(method("GET"))
        .and(path("/script_utxos"))
        .and(query_param("_script_hash", script_hash.value()))
        .and(query_param("_extended", "true"))
        .respond_with(ResponseTemplate::new(200).set_body_json(&mock_response))
        .mount(&mock_server)
        .await;

    let response = client
        .get_script_utxos(&script_hash, Some(Extended(true)))
        .await
        .unwrap();
    assert_eq!(response.len(), 1);
    assert_eq!(
        response[0].tx_hash,
        "6ed09ba58a56c6e946668038ba4d3cef8eb97a20cbf76c5970e1402e8a8d6541"
    );
    assert_eq!(response[0].value, "12345678");
    assert!(!response[0].is_spent);
}

// Error handling tests
#[tokio::test]
async fn test_invalid_script_hash() {
    let (mock_server, client) = setup_test_client().await;

    let script_hashes = vec!["invalid_script_hash".to_string()];

    Mock::given(method("POST"))
        .and(path("/script_info"))
        .and(header("Content-Type", "application/json"))
        .and(body_json(json!({
            "_script_hashes": script_hashes
        })))
        .respond_with(ResponseTemplate::new(400).set_body_string("Invalid script hash format"))
        .mount(&mock_server)
        .await;

    let error = client.get_script_info(&script_hashes).await.unwrap_err();
    match error {
        koios_sdk::error::Error::Api { status, message } => {
            assert_eq!(status, 400);
            assert_eq!(message, "Invalid script hash format");
        }
        _ => panic!("Expected API error"),
    }
}

#[tokio::test]
async fn test_script_not_found() {
    let (mock_server, client) = setup_test_client().await;

    let script_hash = ScriptHash::new("67f33146617a5e61936081db3b2117cbf59bd2123748f58ac9678656");

    Mock::given(method("GET"))
        .and(path("/script_utxos"))
        .and(query_param("_script_hash", script_hash.value()))
        .respond_with(ResponseTemplate::new(404).set_body_string("Script not found"))
        .mount(&mock_server)
        .await;

    let error = client
        .get_script_utxos(&script_hash, None)
        .await
        .unwrap_err();
    match error {
        koios_sdk::error::Error::Api { status, message } => {
            assert_eq!(status, 404);
            assert_eq!(message, "Script not found");
        }
        _ => panic!("Expected API error"),
    }
}

// Integration test
#[tokio::test]
async fn test_script_info_and_redeemers_integration() {
    let (mock_server, client) = setup_test_client().await;

    let script_hash = "67f33146617a5e61936081db3b2117cbf59bd2123748f58ac9678656";
    let script_hashes = vec![script_hash.to_string()];

    // Mock script info response
    let info_response = json!([{
        "script_hash": script_hash,
        "creation_tx_hash": "6ed09ba58a56c6e946668038ba4d3cef8eb97a20cbf76c5970e1402e8a8d6541",
        "type": "plutusv1",
        "value": {
            "constructor": 0,
            "fields": []
        },
        "bytes": "4e4d01000033222220051200120011",
        "size": 42
    }]);

    Mock::given(method("POST"))
        .and(path("/script_info"))
        .and(header("Content-Type", "application/json"))
        .and(body_json(json!({
            "_script_hashes": script_hashes
        })))
        .respond_with(ResponseTemplate::new(200).set_body_json(&info_response))
        .mount(&mock_server)
        .await;

    // Mock script redeemers response
    let redeemers_response = json!([{
        "script_hash": script_hash,
        "redeemers": [{
            "tx_hash": "6ed09ba58a56c6e946668038ba4d3cef8eb97a20cbf76c5970e1402e8a8d6541",
            "tx_index": 0,
            "unit_mem": "1000",
            "unit_steps": "500",
            "fee": "500000",
            "purpose": "spend",
            "datum_hash": "ab01cd23",
            "datum_value": null
        }]
    }]);

    Mock::given(method("GET"))
        .and(path("/script_redeemers"))
        .and(query_param("_script_hash", script_hash))
        .respond_with(ResponseTemplate::new(200).set_body_json(&redeemers_response))
        .mount(&mock_server)
        .await;

    // Create ScriptHash instance before join
    let script_hash = ScriptHash::new(script_hash);

    // Execute both requests concurrently
    let (info, redeemers) = tokio::join!(
        client.get_script_info(&script_hashes),
        client.get_script_redeemers(&script_hash)
    );

    let info = info.unwrap();
    let redeemers = redeemers.unwrap();

    // Verify data consistency between responses
    assert_eq!(info.len(), 1);
    assert_eq!(redeemers.len(), 1);
    assert_eq!(info[0].script_hash.as_ref().unwrap(), script_hash.value());
    assert_eq!(redeemers[0].script_hash, script_hash.value());
    assert_eq!(
        redeemers[0].redeemers[0].tx_hash,
        "6ed09ba58a56c6e946668038ba4d3cef8eb97a20cbf76c5970e1402e8a8d6541"
    );
}

// Batch operation tests
#[tokio::test]
async fn test_batch_script_info() {
    let (mock_server, client) = setup_test_client().await;

    let script_hashes = vec![
        "67f33146617a5e61936081db3b2117cbf59bd2123748f58ac9678656".to_string(),
        "77f33146617a5e61936081db3b2117cbf59bd2123748f58ac9678657".to_string(),
    ];

    let mock_response = json!([
        {
            "script_hash": "67f33146617a5e61936081db3b2117cbf59bd2123748f58ac9678656",
            "creation_tx_hash": "6ed09ba58a56c6e946668038ba4d3cef8eb97a20cbf76c5970e1402e8a8d6541",
            "type": "plutusv1",
            "value": {
                "constructor": 0,
                "fields": []
            },
            "bytes": "4e4d01000033222220051200120011",
            "size": 42
        },
        {
            "script_hash": "77f33146617a5e61936081db3b2117cbf59bd2123748f58ac9678657",
            "creation_tx_hash": "7ed09ba58a56c6e946668038ba4d3cef8eb97a20cbf76c5970e1402e8a8d6542",
            "type": "plutusv2",
            "value": {
                "constructor": 1,
                "fields": []
            },
            "bytes": "4e4d01000033222220051200120012",
            "size": 42
        }
    ]);

    Mock::given(method("POST"))
        .and(path("/script_info"))
        .and(header("Content-Type", "application/json"))
        .and(body_json(json!({
            "_script_hashes": script_hashes
        })))
        .respond_with(ResponseTemplate::new(200).set_body_json(&mock_response))
        .mount(&mock_server)
        .await;

    let response = client.get_script_info(&script_hashes).await.unwrap();
    assert_eq!(response.len(), 2);

    // Verify first script
    assert_eq!(
        response[0].script_hash.as_ref().unwrap(),
        "67f33146617a5e61936081db3b2117cbf59bd2123748f58ac9678656"
    );
    assert_eq!(response[0].script_type, ScriptType::PlutusV1);

    // Verify second script
    assert_eq!(
        response[1].script_hash.as_ref().unwrap(),
        "77f33146617a5e61936081db3b2117cbf59bd2123748f58ac9678657"
    );
    assert_eq!(response[1].script_type, ScriptType::PlutusV2);
}

// Extended tests for specific functionality
#[tokio::test]
async fn test_script_redeemer_with_inline_datum() {
    let (mock_server, client) = setup_test_client().await;

    let script_hash = "67f33146617a5e61936081db3b2117cbf59bd2123748f58ac9678656";

    // Fixed: Changed unit_mem and unit_steps format to match RedeemerUnitValue enum
    let mock_response = json!([{
        "script_hash": script_hash,
        "redeemers": [{
            "tx_hash": "6ed09ba58a56c6e946668038ba4d3cef8eb97a20cbf76c5970e1402e8a8d6541",
            "tx_index": 0,
            "unit_mem": 1000,  // Changed from object to direct number
            "unit_steps": 500, // Changed from object to direct number
            "fee": "500000",
            "purpose": "mint",
            "datum_hash": null,
            "datum_value": {
                "constructor": 0,
                "fields": [
                    {"bytes": "48656c6c6f20576f726c64"},
                    {"int": 42}
                ]
            }
        }]
    }]);

    Mock::given(method("GET"))
        .and(path("/script_redeemers"))
        .and(query_param("_script_hash", script_hash))
        .respond_with(ResponseTemplate::new(200).set_body_json(&mock_response))
        .mount(&mock_server)
        .await;

    let response = client
        .get_script_redeemers(&ScriptHash::new(script_hash))
        .await
        .unwrap();
    assert_eq!(response.len(), 1);

    let redeemer = &response[0].redeemers[0];
    assert_eq!(redeemer.purpose, RedeemerPurpose::Mint);
    assert!(redeemer.datum_hash.is_none());
    assert!(redeemer.datum_value.is_some());
}

#[tokio::test]
async fn test_script_utxos_with_reference_script() {
    let (mock_server, client) = setup_test_client().await;

    let script_hash = ScriptHash::new("67f33146617a5e61936081db3b2117cbf59bd2123748f58ac9678656");

    let mock_response = json!([{
        "tx_hash": "6ed09ba58a56c6e946668038ba4d3cef8eb97a20cbf76c5970e1402e8a8d6541",
        "tx_index": 0,
        "address": "addr1qxqs59lphg8g6qndelq8xwqn60ag3aeyfcp33c2kdp46a09re5df3pzwwmyq946axfcejy5n4x0y99wqpgtp2gd0k09qsgy6pz",
        "value": "12345678",
        "stake_address": "stake1u9ylzsgxaa6xctf4juup682ar3juj85n8tx3hthnljg47zctvm3rc",
        "payment_cred": "a2944a17b8d8b7ede6e365432cf59ff5276c7c3a99e2b89d47c87661",
        "epoch_no": 321,
        "block_height": 7017300,
        "block_time": 1630106091,
        "datum_hash": null,
        "inline_datum": null,
        "reference_script": {
            "hash": "67f33146617a5e61936081db3b2117cbf59bd2123748f58ac9678656",
            "type": "plutusv1",
            "bytes": "4e4d01000033222220051200120011"
        },
        "asset_list": [],
        "is_spent": false
    }]);

    Mock::given(method("GET"))
        .and(path("/script_utxos"))
        .and(query_param("_script_hash", script_hash.value()))
        .and(query_param("_extended", "true"))
        .respond_with(ResponseTemplate::new(200).set_body_json(&mock_response))
        .mount(&mock_server)
        .await;

    let response = client
        .get_script_utxos(&script_hash, Some(Extended(true)))
        .await
        .unwrap();
    assert_eq!(response.len(), 1);
    assert!(response[0].reference_script.is_some());
    let reference_script = response[0].reference_script.as_ref().unwrap();
    assert_eq!(
        reference_script.get("hash").unwrap().as_str().unwrap(),
        script_hash.value()
    );
}

#[tokio::test]
async fn test_script_types_validation() {
    let (mock_server, client) = setup_test_client().await;

    let script_hashes =
        vec!["67f33146617a5e61936081db3b2117cbf59bd2123748f58ac9678656".to_string()];

    // Test each script type separately to avoid mock interference
    let script_types = vec![
        ("plutusv1", ScriptType::PlutusV1),
        ("plutusv2", ScriptType::PlutusV2),
        ("timelock", ScriptType::Timelock),
        ("multisig", ScriptType::Multisig),
    ];

    for (type_str, expected_type) in script_types {
        let mock_response = json!([{
            "script_hash": "67f33146617a5e61936081db3b2117cbf59bd2123748f58ac9678656",
            "creation_tx_hash": "6ed09ba58a56c6e946668038ba4d3cef8eb97a20cbf76c5970e1402e8a8d6541",
            "type": type_str,
            "value": {
                "constructor": 0,
                "fields": []
            },
            "bytes": "4e4d01000033222220051200120011",
            "size": 42
        }]);

        // Create a new mock for each iteration
        let _mock = Mock::given(method("POST"))
            .and(path("/script_info"))
            .and(header("Content-Type", "application/json"))
            .and(body_json(json!({
                "_script_hashes": &script_hashes
            })))
            .respond_with(ResponseTemplate::new(200).set_body_json(&mock_response))
            .expect(1) // Expect exactly one call
            .mount_as_scoped(&mock_server)
            .await;

        let response = client.get_script_info(&script_hashes).await.unwrap();
        assert_eq!(response.len(), 1);
        assert_eq!(
            response[0].script_type, expected_type,
            "Script type mismatch for input '{}': expected {:?}, got {:?}",
            type_str, expected_type, response[0].script_type
        );
    }
}