[go: up one dir, main page]

fuel-gql-client 0.3.1

Tx client and schema specification.
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
use chrono::Utc;
use fuel_core::{
    database::Database,
    executor::Executor,
    model::fuel_block::FuelBlock,
    service::{Config, FuelService, VMConfig},
};
use fuel_gql_client::client::types::TransactionStatus;
use fuel_gql_client::client::{FuelClient, PageDirection, PaginationRequest};
use fuel_storage::Storage;
use fuel_vm::{consts::*, prelude::*};
use itertools::Itertools;
use rand::{rngs::StdRng, Rng, SeedableRng};
use std::io;

#[test]
fn basic_script_snapshot() {
    // Since this script is referenced in docs, snapshot the byte representation in-case opcodes
    // are reassigned in the future
    let script = vec![
        Opcode::ADDI(0x10, REG_ZERO, 0xca),
        Opcode::ADDI(0x11, REG_ZERO, 0xba),
        Opcode::LOG(0x10, 0x11, REG_ZERO, REG_ZERO),
        Opcode::RET(REG_ONE),
    ];
    let script: Vec<u8> = script
        .iter()
        .map(|op| u32::from(*op).to_be_bytes())
        .flatten()
        .collect();
    insta::assert_snapshot!(format!("{:?}", script));
}

#[tokio::test]
async fn dry_run() {
    let srv = FuelService::new_node(Config::local_node()).await.unwrap();
    let client = FuelClient::from(srv.bound_address);

    let gas_price = 0;
    let gas_limit = 1_000_000;
    let byte_price = 0;
    let maturity = 0;

    let script = vec![
        Opcode::ADDI(0x10, REG_ZERO, 0xca),
        Opcode::ADDI(0x11, REG_ZERO, 0xba),
        Opcode::LOG(0x10, 0x11, REG_ZERO, REG_ZERO),
        Opcode::RET(REG_ONE),
    ];
    let script: Vec<u8> = script
        .iter()
        .map(|op| u32::from(*op).to_be_bytes())
        .flatten()
        .collect();

    let tx = fuel_tx::Transaction::script(
        gas_price,
        gas_limit,
        byte_price,
        maturity,
        script,
        vec![],
        vec![],
        vec![],
        vec![],
    );

    let log = client.dry_run(&tx).await.unwrap();
    assert_eq!(3, log.len());

    assert!(matches!(log[0],
        Receipt::Log {
            ra, rb, ..
        } if ra == 0xca && rb == 0xba));

    assert!(matches!(log[1],
        Receipt::Return {
            val, ..
        } if val == 1));
}

#[tokio::test]
async fn submit() {
    let srv = FuelService::new_node(Config::local_node()).await.unwrap();
    let client = FuelClient::from(srv.bound_address);

    let gas_price = 0;
    let gas_limit = 1_000_000;
    let byte_price = 0;
    let maturity = 0;

    let script = vec![
        Opcode::ADDI(0x10, REG_ZERO, 0xca),
        Opcode::ADDI(0x11, REG_ZERO, 0xba),
        Opcode::LOG(0x10, 0x11, REG_ZERO, REG_ZERO),
        Opcode::RET(REG_ONE),
    ];
    let script: Vec<u8> = script
        .iter()
        .map(|op| u32::from(*op).to_be_bytes())
        .flatten()
        .collect();

    let tx = fuel_tx::Transaction::script(
        gas_price,
        gas_limit,
        byte_price,
        maturity,
        script,
        vec![],
        vec![],
        vec![],
        vec![],
    );

    let id = client.submit(&tx).await.unwrap();
    // verify that the tx returned from the api matches the submitted tx
    let ret_tx = client
        .transaction(&id.0.to_string())
        .await
        .unwrap()
        .unwrap()
        .transaction;
    assert_eq!(tx, ret_tx);
}

#[tokio::test]
async fn receipts() {
    let transaction = fuel_tx::Transaction::default();
    let id = transaction.id();
    // setup server & client
    let srv = FuelService::new_node(Config::local_node()).await.unwrap();
    let client = FuelClient::from(srv.bound_address);
    // submit tx
    let result = client.submit(&transaction).await;
    assert!(result.is_ok());

    // run test
    let receipts = client.receipts(&format!("{:#x}", id)).await.unwrap();
    assert!(!receipts.is_empty());
}

#[tokio::test]
async fn get_transaction_by_id() {
    // setup test data in the node
    let transaction = fuel_tx::Transaction::default();
    let id = transaction.id();

    // setup server & client
    let srv = FuelService::new_node(Config::local_node()).await.unwrap();
    let client = FuelClient::from(srv.bound_address);
    // submit tx to api
    client.submit(&transaction).await.unwrap();

    // run test
    let transaction_response = client.transaction(&format!("{:#x}", id)).await.unwrap();
    assert!(transaction_response.is_some());
    if let Some(transaction_response) = transaction_response {
        assert!(matches!(
            transaction_response.status,
            TransactionStatus::Success { .. }
        ))
    }
}

#[tokio::test]
async fn get_transparent_transaction_by_id() {
    let transaction = fuel_tx::Transaction::default();
    let id = transaction.id();

    // setup server & client
    let srv = FuelService::new_node(Config::local_node()).await.unwrap();
    let client = FuelClient::from(srv.bound_address);

    // submit tx
    let result = client.submit(&transaction).await;
    assert!(result.is_ok());

    let opaque_tx = client
        .transaction(&format!("{:#x}", id))
        .await
        .unwrap()
        .expect("expected some result")
        .transaction;

    // run test
    let transparent_transaction = client
        .transparent_transaction(&format!("{:#x}", id))
        .await
        .unwrap()
        .expect("expected some value");

    // verify transaction round-trips via transparent graphql
    assert_eq!(opaque_tx, transparent_transaction);
}

#[tokio::test]
async fn get_transactions() {
    let alice = Address::from([0; 32]);
    let bob = Address::from([1; 32]);
    let charlie = Address::from([2; 32]);

    let mut context = TestContext::new(100).await;
    let tx1 = context.transfer(alice, charlie, 1).await.unwrap();
    let tx2 = context.transfer(charlie, bob, 2).await.unwrap();
    let tx3 = context.transfer(bob, charlie, 3).await.unwrap();
    let tx4 = context.transfer(bob, charlie, 3).await.unwrap();
    let tx5 = context.transfer(charlie, alice, 1).await.unwrap();
    let tx6 = context.transfer(alice, charlie, 1).await.unwrap();

    // there are six transactions
    // [1, 2, 3, 4, 5, 6]

    // Query for first 3: [1,2,3]
    let client = context.client;
    let page_request = PaginationRequest {
        cursor: None,
        results: 3,
        direction: PageDirection::Forward,
    };

    let response = client.transactions(page_request.clone()).await.unwrap();
    let transactions = &response
        .results
        .iter()
        .map(|tx| tx.transaction.id())
        .collect_vec();
    assert_eq!(transactions, &[tx1, tx2, tx3]);

    // Query backwards from last given cursor [3]: [1,2]
    let page_request_backwards = PaginationRequest {
        cursor: response.cursor.clone(),
        results: 3,
        direction: PageDirection::Backward,
    };

    // Query forwards from last given cursor [3]: [4,5,6]
    let page_request_forwards = PaginationRequest {
        cursor: response.cursor,
        results: 3,
        direction: PageDirection::Forward,
    };

    let response = client.transactions(page_request_backwards).await.unwrap();
    let transactions = &response
        .results
        .iter()
        .map(|tx| tx.transaction.id())
        .collect_vec();
    assert_eq!(transactions, &[tx1, tx2]);

    let response = client.transactions(page_request_forwards).await.unwrap();
    let transactions = &response
        .results
        .iter()
        .map(|tx| tx.transaction.id())
        .collect_vec();
    assert_eq!(transactions, &[tx4, tx5, tx6]);
}

#[tokio::test]
async fn get_transactions_from_manual_blcoks() {
    let (executor, mut db) = get_executor_and_db();
    // get access to a client
    let client = initialize_client(db.clone()).await;

    // create 10 txs
    let txs: Vec<Transaction> = (0..10).map(create_mock_tx).collect();

    // manually store txs in the db
    for tx in &txs {
        Storage::<Bytes32, fuel_tx::Transaction>::insert(&mut db, &tx.id(), tx).unwrap();
    }

    // make 1st test block
    let first_test_block = FuelBlock {
        fuel_height: 1u32.into(),
        // set the first 5 ids of the manually saved txs
        transactions: txs.iter().take(5).map(|tx| tx.id()).collect(),
        time: Utc::now(),
        producer: Default::default(),
    };

    // make 2nd test block
    let second_test_block = FuelBlock {
        fuel_height: 2u32.into(),
        // set the last 5 ids of the manually saved txs
        transactions: txs.iter().skip(5).take(5).map(|tx| tx.id()).collect(),
        time: Utc::now(),
        producer: Default::default(),
    };

    // process blocks and save block height
    let config = VMConfig::default();
    executor.execute(&first_test_block, &config).await.unwrap();
    executor.execute(&second_test_block, &config).await.unwrap();

    // Query for first 3: [0,1,2]
    let page_request_forwards = PaginationRequest {
        cursor: None,
        results: 3,
        direction: PageDirection::Forward,
    };
    let response = client.transactions(page_request_forwards).await.unwrap();
    let transactions = &response
        .results
        .iter()
        .map(|tx| tx.transaction.id())
        .collect_vec();
    assert_eq!(transactions, &[txs[0].id(), txs[1].id(), txs[2].id()]);

    // Query forwards from last given cursor [2]: [3,4,5,6]
    let next_page_request_forwards = PaginationRequest {
        cursor: response.cursor,
        results: 4,
        direction: PageDirection::Forward,
    };
    let response = client
        .transactions(next_page_request_forwards)
        .await
        .unwrap();
    let transactions = &response
        .results
        .iter()
        .map(|tx| tx.transaction.id())
        .collect_vec();
    assert_eq!(
        transactions,
        &[txs[3].id(), txs[4].id(), txs[5].id(), txs[6].id()]
    );

    // Query backwards from last given cursor [6]: [0,1,2,3,4,5]
    let page_request_backwards = PaginationRequest {
        cursor: response.cursor,
        results: 10,
        direction: PageDirection::Backward,
    };
    let response = client.transactions(page_request_backwards).await.unwrap();
    let transactions = &response
        .results
        .iter()
        .map(|tx| tx.transaction.id())
        .collect_vec();
    assert_eq!(
        transactions,
        &[
            txs[0].id(),
            txs[1].id(),
            txs[2].id(),
            txs[3].id(),
            txs[4].id(),
            txs[5].id()
        ]
    );
}

#[tokio::test]
async fn get_owned_transactions() {
    let alice = Address::from([0; 32]);
    let bob = Address::from([1; 32]);
    let charlie = Address::from([2; 32]);

    let mut context = TestContext::new(100).await;
    let tx1 = context.transfer(alice, charlie, 1).await.unwrap();
    let tx2 = context.transfer(charlie, bob, 2).await.unwrap();
    let tx3 = context.transfer(bob, charlie, 3).await.unwrap();

    // Query for transactions by owner, for each owner respectively
    let client = context.client;
    let page_request = PaginationRequest {
        cursor: None,
        results: 5,
        direction: PageDirection::Forward,
    };
    let alice_txs = client
        .transactions_by_owner(&format!("{:#x}", alice), page_request.clone())
        .await
        .unwrap()
        .results
        .iter()
        .map(|tx| tx.transaction.id())
        .collect_vec();

    let bob_txs = client
        .transactions_by_owner(&format!("{:#x}", bob), page_request.clone())
        .await
        .unwrap()
        .results
        .iter()
        .map(|tx| tx.transaction.id())
        .collect_vec();

    let charlie_txs = client
        .transactions_by_owner(&format!("{:#x}", charlie), page_request.clone())
        .await
        .unwrap()
        .results
        .iter()
        .map(|tx| tx.transaction.id())
        .collect_vec();

    assert_eq!(&alice_txs, &[tx1]);
    assert_eq!(&bob_txs, &[tx2, tx3]);
    assert_eq!(&charlie_txs, &[tx1, tx2, tx3]);
}

struct TestContext {
    rng: StdRng,
    pub client: FuelClient,
}

impl TestContext {
    async fn new(seed: u64) -> Self {
        let rng = StdRng::seed_from_u64(seed);
        let srv = FuelService::new_node(Config::local_node()).await.unwrap();
        let client = FuelClient::from(srv.bound_address);
        Self { rng, client }
    }

    async fn transfer(&mut self, from: Address, to: Address, amount: u64) -> io::Result<Bytes32> {
        let script = Opcode::RET(0x10).to_bytes().to_vec();
        let tx = Transaction::Script {
            gas_price: 0,
            gas_limit: 1_000_000,
            byte_price: 0,
            maturity: 0,
            receipts_root: Default::default(),
            script,
            script_data: vec![],
            inputs: vec![Input::Coin {
                utxo_id: self.rng.gen(),
                owner: from,
                amount,
                color: Default::default(),
                witness_index: 0,
                maturity: 0,
                predicate: vec![],
                predicate_data: vec![],
            }],
            outputs: vec![Output::Coin {
                amount,
                to,
                color: Default::default(),
            }],
            witnesses: vec![vec![].into()],
            metadata: None,
        };
        self.client.submit(&tx).await.map(Into::into)
    }
}

fn get_executor_and_db() -> (Executor, Database) {
    let db = Database::default();
    let executor = Executor {
        database: db.clone(),
    };

    (executor, db)
}

async fn initialize_client(db: Database) -> FuelClient {
    let config = Config::local_node();
    let service = FuelService::from_database(db, config).await.unwrap();
    FuelClient::from(service.bound_address)
}

// add random maturity for unique tx
fn create_mock_tx(maturity: u64) -> Transaction {
    fuel_tx::Transaction::script(
        0,
        0,
        0,
        maturity,
        Default::default(),
        Default::default(),
        Default::default(),
        Default::default(),
        Default::default(),
    )
}