ic_web3_rs/contract/
mod.rs

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
//! Ethereum Contract Interface

use crate::{
    api::{Eth, Namespace},
    confirm,
    contract::tokens::{Detokenize, Tokenize},
    futures::Future,
    ic::KeyInfo,
    transports::ic_http_client::CallOptions,
    types::{
        AccessList, Address, BlockId, Bytes, CallRequest, FilterBuilder, TransactionCondition, TransactionParameters,
        TransactionReceipt, TransactionRequest, H256, U256, U64,
    },
    Transport,
};
use std::{collections::HashMap, hash::Hash, time};

pub mod deploy;
// pub mod ens;
mod error;
pub mod tokens;

pub use crate::contract::error::Error;

/// Contract `Result` type.
pub type Result<T> = std::result::Result<T, Error>;

/// Contract Call/Query Options
#[derive(Default, Debug, Clone, PartialEq)]
pub struct Options {
    /// Fixed gas limit
    pub gas: Option<U256>,
    /// Fixed gas price
    pub gas_price: Option<U256>,
    /// Value to transfer
    pub value: Option<U256>,
    /// Fixed transaction nonce
    pub nonce: Option<U256>,
    /// A condition to satisfy before including transaction.
    pub condition: Option<TransactionCondition>,
    /// Transaction type, Some(1) for AccessList transaction, None for Legacy
    pub transaction_type: Option<U64>,
    /// Access list
    pub access_list: Option<AccessList>,
    /// Max fee per gas
    pub max_fee_per_gas: Option<U256>,
    /// miner bribe
    pub max_priority_fee_per_gas: Option<U256>,
    pub call_options: Option<CallOptions>,
}

impl Options {
    /// Create new default `Options` object with some modifications.
    pub fn with<F>(func: F) -> Options
    where
        F: FnOnce(&mut Options),
    {
        let mut options = Options::default();
        func(&mut options);
        options
    }
}

/// Ethereum Contract Interface
#[derive(Debug, Clone)]
pub struct Contract<T: Transport> {
    address: Address,
    eth: Eth<T>,
    abi: ethabi::Contract,
}

impl<T: Transport> Contract<T> {
    // Creates deployment builder for a contract given it's ABI in JSON.
    //pub fn deploy(eth: Eth<T>, json: &[u8]) -> ethabi::Result<deploy::Builder<T>> {
    //    let abi = ethabi::Contract::load(json)?;
    //    Ok(deploy::Builder {
    //        eth,
    //        abi,
    //        options: Options::default(),
    //        confirmations: 1,
    //        poll_interval: time::Duration::from_secs(7),
    //        linker: HashMap::default(),
    //    })
    //}
    //
    ///// test
    //pub fn deploy_from_truffle<S>(
    //    eth: Eth<T>,
    //    json: &[u8],
    //    linker: HashMap<S, Address>,
    //) -> ethabi::Result<deploy::Builder<T>>
    //where
    //    S: AsRef<str> + Eq + Hash,
    //{
    //    let abi = ethabi::Contract::load(json)?;
    //    let linker: HashMap<String, Address> = linker.into_iter().map(|(s, a)| (s.as_ref().to_string(), a)).collect();
    //    Ok(deploy::Builder {
    //        eth,
    //        abi,
    //        options: Options::default(),
    //        confirmations: 1,
    //        poll_interval: time::Duration::from_secs(7),
    //        linker,
    //    })
    //}
}

impl<T: Transport> Contract<T> {
    /// Creates new Contract Interface given blockchain address and ABI
    pub fn new(eth: Eth<T>, address: Address, abi: ethabi::Contract) -> Self {
        Contract { address, eth, abi }
    }

    /// Creates new Contract Interface given blockchain address and JSON containing ABI
    pub fn from_json(eth: Eth<T>, address: Address, json: &[u8]) -> ethabi::Result<Self> {
        let abi = ethabi::Contract::load(json)?;
        Ok(Self::new(eth, address, abi))
    }

    /// Get the underlying contract ABI.
    pub fn abi(&self) -> &ethabi::Contract {
        &self.abi
    }

    /// Returns contract address
    pub fn address(&self) -> Address {
        self.address
    }

    /// Execute a contract function
    pub async fn call<P>(&self, func: &str, params: P, from: Address, options: Options) -> Result<H256>
    where
        P: Tokenize,
    {
        let data = self.abi.function(func)?.encode_input(&params.into_tokens())?;
        let Options {
            gas,
            gas_price,
            value,
            nonce,
            condition,
            transaction_type,
            access_list,
            max_fee_per_gas,
            max_priority_fee_per_gas,
            call_options,
        } = options;
        self.eth
            .send_transaction(
                TransactionRequest {
                    from,
                    to: Some(self.address),
                    gas,
                    gas_price,
                    value,
                    nonce,
                    data: Some(Bytes(data)),
                    condition,
                    transaction_type,
                    access_list,
                    max_fee_per_gas,
                    max_priority_fee_per_gas,
                },
                call_options.unwrap_or_default(),
            )
            .await
            .map_err(Error::from)
    }

    /// Execute a contract function and wait for confirmations
    pub async fn call_with_confirmations(
        &self,
        func: &str,
        params: impl Tokenize,
        from: Address,
        options: Options,
        confirmations: usize,
    ) -> crate::error::Result<TransactionReceipt> {
        let poll_interval = time::Duration::from_secs(1);

        let fn_data = self
            .abi
            .function(func)
            .and_then(|function| function.encode_input(&params.into_tokens()))
            // TODO [ToDr] SendTransactionWithConfirmation should support custom error type (so that we can return
            // `contract::Error` instead of more generic `Error`.
            .map_err(|err| crate::error::Error::Decoder(format!("{:?}", err)))?;
        let transaction_request = TransactionRequest {
            from,
            to: Some(self.address),
            gas: options.gas,
            gas_price: options.gas_price,
            value: options.value,
            nonce: options.nonce,
            data: Some(Bytes(fn_data)),
            condition: options.condition,
            transaction_type: options.transaction_type,
            access_list: options.access_list,
            max_fee_per_gas: options.max_fee_per_gas,
            max_priority_fee_per_gas: options.max_priority_fee_per_gas,
        };
        confirm::send_transaction_with_confirmation(
            self.eth.transport().clone(),
            transaction_request,
            poll_interval,
            confirmations,
            options.call_options.unwrap_or_default(),
        )
        .await
    }

    /// Estimate gas required for this function call.
    pub async fn estimate_gas<P>(&self, func: &str, params: P, from: Address, options: Options) -> Result<U256>
    where
        P: Tokenize,
    {
        let data = self.abi.function(func)?.encode_input(&params.into_tokens())?;
        self.eth
            .estimate_gas(
                CallRequest {
                    from: Some(from),
                    to: Some(self.address),
                    gas: options.gas,
                    gas_price: options.gas_price,
                    value: options.value,
                    data: Some(Bytes(data)),
                    transaction_type: options.transaction_type,
                    access_list: options.access_list,
                    max_fee_per_gas: options.max_fee_per_gas,
                    max_priority_fee_per_gas: options.max_priority_fee_per_gas,
                },
                None,
                options.call_options.unwrap_or_default(),
            )
            .await
            .map_err(Into::into)
    }
    pub async fn _estimate_gas(
        &self,
        from: Address,
        tx: &TransactionParameters,
        call_options: CallOptions,
    ) -> Result<U256> {
        self.eth
            .estimate_gas(
                CallRequest {
                    from: Some(from),
                    to: tx.to,
                    gas: None,
                    gas_price: tx.gas_price,
                    value: Some(tx.value),
                    data: Some(tx.data.clone()),
                    transaction_type: tx.transaction_type,
                    access_list: tx.access_list.clone(),
                    max_fee_per_gas: tx.max_fee_per_gas,
                    max_priority_fee_per_gas: tx.max_priority_fee_per_gas,
                },
                None,
                call_options,
            )
            .await
            .map_err(Into::into)
    }

    /// Call constant function
    pub fn query<R, A, B, P>(
        &self,
        func: &str,
        params: P,
        from: A,
        options: Options,
        block: B,
    ) -> impl Future<Output = Result<R>> + '_
    where
        R: Detokenize,
        A: Into<Option<Address>>,
        B: Into<Option<BlockId>>,
        P: Tokenize,
    {
        let result = self
            .abi
            .function(func)
            .and_then(|function| {
                function
                    .encode_input(&params.into_tokens())
                    .map(|call| (call, function))
            })
            .map(|(call, function)| {
                let call_future = self.eth.call(
                    CallRequest {
                        from: from.into(),
                        to: Some(self.address),
                        gas: options.gas,
                        gas_price: options.gas_price,
                        value: options.value,
                        data: Some(Bytes(call)),
                        transaction_type: options.transaction_type,
                        access_list: options.access_list,
                        max_fee_per_gas: options.max_fee_per_gas,
                        max_priority_fee_per_gas: options.max_priority_fee_per_gas,
                    },
                    block.into(),
                    options.call_options.unwrap_or_default(),
                );
                (call_future, function)
            });
        // NOTE for the batch transport to work correctly, we must call `transport.execute` without ever polling the future,
        // hence it cannot be a fully `async` function.
        async {
            let (call_future, function) = result?;
            let bytes = call_future.await?;
            let output = function.decode_output(&bytes.0)?;
            R::from_tokens(output)
        }
    }

    /// Find events matching the topics.
    pub async fn events<A, B, C, R>(
        &self,
        event: &str,
        topic0: A,
        topic1: B,
        topic2: C,
        options: CallOptions,
    ) -> Result<Vec<R>>
    where
        A: Tokenize,
        B: Tokenize,
        C: Tokenize,
        R: Detokenize,
    {
        fn to_topic<A: Tokenize>(x: A) -> ethabi::Topic<ethabi::Token> {
            let tokens = x.into_tokens();
            if tokens.is_empty() {
                ethabi::Topic::Any
            } else {
                tokens.into()
            }
        }

        let res = self.abi.event(event).and_then(|ev| {
            let filter = ev.filter(ethabi::RawTopicFilter {
                topic0: to_topic(topic0),
                topic1: to_topic(topic1),
                topic2: to_topic(topic2),
            })?;
            Ok((ev.clone(), filter))
        });
        let (ev, filter) = match res {
            Ok(x) => x,
            Err(e) => return Err(e.into()),
        };

        let logs = self
            .eth
            .logs(FilterBuilder::default().topic_filter(filter).build(), options)
            .await?;
        logs.into_iter()
            .map(move |l| {
                let log = ev.parse_log(ethabi::RawLog {
                    topics: l.topics,
                    data: l.data.0,
                })?;

                R::from_tokens(log.params.into_iter().map(|x| x.value).collect::<Vec<_>>())
            })
            .collect::<Result<Vec<R>>>()
    }
}

// #[cfg(feature = "signing")]
mod contract_signing {
    use std::str::FromStr;

    use super::*;
    use crate::{
        api::Accounts,
        types::{SignedTransaction, TransactionParameters},
    };

    impl<T: Transport> Contract<T> {
        pub async fn sign(
            &self,
            func: &str,
            params: impl Tokenize,
            options: Options,
            from: String,
            key_info: KeyInfo,
            chain_id: u64,
        ) -> crate::Result<SignedTransaction> {
            let fn_data = self
                .abi
                .function(func)
                .and_then(|function| function.encode_input(&params.into_tokens()))
                // TODO [ToDr] SendTransactionWithConfirmation should support custom error type (so that we can return
                // `contract::Error` instead of more generic `Error`.
                .map_err(|err| crate::error::Error::Decoder(format!("{:?}", err)))?;
            let accounts = Accounts::new(self.eth.transport().clone());
            let mut tx = TransactionParameters {
                nonce: options.nonce,
                to: Some(self.address),
                gas_price: options.gas_price,
                data: Bytes(fn_data),
                transaction_type: options.transaction_type,
                access_list: options.access_list,
                max_fee_per_gas: options.max_fee_per_gas,
                max_priority_fee_per_gas: options.max_priority_fee_per_gas,
                ..Default::default()
            };
            tx.gas = if let Some(gas) = options.gas {
                gas
            } else {
                match self
                    ._estimate_gas(
                        Address::from_str(&from.to_string().as_str()).unwrap(),
                        &tx,
                        options.call_options.unwrap_or_default(),
                    )
                    .await
                {
                    Ok(gas) => gas,
                    Err(e) => {
                        return Err(e.into());
                    }
                }
            };
            if let Some(value) = options.value {
                tx.value = value;
            }
            accounts.sign_transaction(tx, from, key_info, chain_id).await
        }

        /// Submit contract call transaction to the transaction pool.
        ///
        /// Note this function DOES NOT wait for any confirmations, so there is no guarantees that the call is actually executed.
        /// If you'd rather wait for block inclusion, please use [`signed_call_with_confirmations`] instead.
        pub async fn signed_call(
            &self,
            func: &str,
            params: impl Tokenize,
            options: Options,
            from: String,
            key_info: KeyInfo,
            chain_id: u64,
        ) -> crate::Result<H256> {
            let signed = self
                .sign(
                    func,
                    params,
                    Options {
                        call_options: None,
                        ..options.clone()
                    },
                    from,
                    key_info,
                    chain_id,
                )
                .await?;
            self.eth
                .send_raw_transaction(signed.raw_transaction, options.call_options.unwrap_or_default())
                .await?;
            Ok(signed.transaction_hash)
        }

        // Submit contract call transaction to the transaction pool and wait for the transaction to be included in a block.
        //
        // This function will wait for block inclusion of the transaction before returning.
        // If you'd rather just submit transaction and receive it's hash, please use [`signed_call`] instead.
        pub async fn signed_call_with_confirmations(
            &self,
            func: &str,
            params: impl Tokenize,
            options: Options,
            from: String,
            confirmations: usize,
            key_info: KeyInfo,
            chain_id: u64,
        ) -> crate::Result<TransactionReceipt> {
            let poll_interval = time::Duration::from_secs(1);
            let signed = self
                .sign(
                    func,
                    params,
                    Options {
                        call_options: None,
                        ..options.clone()
                    },
                    from,
                    key_info,
                    chain_id,
                )
                .await?;

            confirm::send_raw_transaction_with_confirmation(
                self.eth.transport().clone(),
                signed.raw_transaction,
                poll_interval,
                confirmations,
                options.call_options.unwrap_or_default(),
            )
            .await
        }
    }
}

#[cfg(test)]
mod tests {
    use super::{Contract, Options};
    use crate::{
        api::{self, Namespace},
        rpc,
        transports::test::TestTransport,
        types::{Address, BlockId, BlockNumber, H256, U256},
        Transport,
    };

    fn contract<T: Transport>(transport: &T) -> Contract<&T> {
        let eth = api::Eth::new(transport);
        Contract::from_json(eth, Address::from_low_u64_be(1), include_bytes!("./res/token.json")).unwrap()
    }

    #[test]
    fn should_call_constant_function() {
        // given
        let mut transport = TestTransport::default();
        transport.set_response(rpc::Value::String("0x0000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000c48656c6c6f20576f726c64210000000000000000000000000000000000000000".into()));

        let result: String = {
            let token = contract(&transport);

            // when
            futures::executor::block_on(token.query(
                "name",
                (),
                None,
                Options::default(),
                BlockId::Number(BlockNumber::Number(1.into())),
            ))
            .unwrap()
        };

        // then
        transport.assert_request(
            "eth_call",
            &[
                "{\"data\":\"0x06fdde03\",\"to\":\"0x0000000000000000000000000000000000000001\"}".into(),
                "\"0x1\"".into(),
            ],
        );
        transport.assert_no_more_requests();
        assert_eq!(result, "Hello World!".to_owned());
    }

    #[test]
    fn should_call_constant_function_by_hash() {
        // given
        let mut transport = TestTransport::default();
        transport.set_response(rpc::Value::String("0x0000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000c48656c6c6f20576f726c64210000000000000000000000000000000000000000".into()));

        let result: String = {
            let token = contract(&transport);

            // when
            futures::executor::block_on(token.query(
                "name",
                (),
                None,
                Options::default(),
                BlockId::Hash(H256::default()),
            ))
            .unwrap()
        };

        // then
        transport.assert_request(
            "eth_call",
            &[
                "{\"data\":\"0x06fdde03\",\"to\":\"0x0000000000000000000000000000000000000001\"}".into(),
                "{\"blockHash\":\"0x0000000000000000000000000000000000000000000000000000000000000000\"}".into(),
            ],
        );
        transport.assert_no_more_requests();
        assert_eq!(result, "Hello World!".to_owned());
    }

    #[test]
    fn should_query_with_params() {
        // given
        let mut transport = TestTransport::default();
        transport.set_response(rpc::Value::String("0x0000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000c48656c6c6f20576f726c64210000000000000000000000000000000000000000".into()));

        let result: String = {
            let token = contract(&transport);

            // when
            futures::executor::block_on(token.query(
                "name",
                (),
                Address::from_low_u64_be(5),
                Options::with(|options| {
                    options.gas_price = Some(10_000_000.into());
                }),
                BlockId::Number(BlockNumber::Latest),
            ))
            .unwrap()
        };

        // then
        transport.assert_request("eth_call", &["{\"data\":\"0x06fdde03\",\"from\":\"0x0000000000000000000000000000000000000005\",\"gasPrice\":\"0x989680\",\"to\":\"0x0000000000000000000000000000000000000001\"}".into(), "\"latest\"".into()]);
        transport.assert_no_more_requests();
        assert_eq!(result, "Hello World!".to_owned());
    }

    #[test]
    fn should_call_a_contract_function() {
        // given
        let mut transport = TestTransport::default();
        transport.set_response(rpc::Value::String(format!("{:?}", H256::from_low_u64_be(5))));

        let result = {
            let token = contract(&transport);

            // when
            futures::executor::block_on(token.call("name", (), Address::from_low_u64_be(5), Options::default()))
                .unwrap()
        };

        // then
        transport.assert_request("eth_sendTransaction", &["{\"data\":\"0x06fdde03\",\"from\":\"0x0000000000000000000000000000000000000005\",\"to\":\"0x0000000000000000000000000000000000000001\"}".into()]);
        transport.assert_no_more_requests();
        assert_eq!(result, H256::from_low_u64_be(5));
    }

    #[test]
    fn should_estimate_gas_usage() {
        // given
        let mut transport = TestTransport::default();
        transport.set_response(rpc::Value::String(format!("{:#x}", U256::from(5))));

        let result = {
            let token = contract(&transport);

            // when
            futures::executor::block_on(token.estimate_gas("name", (), Address::from_low_u64_be(5), Options::default()))
                .unwrap()
        };

        // then
        transport.assert_request("eth_estimateGas", &["{\"data\":\"0x06fdde03\",\"from\":\"0x0000000000000000000000000000000000000005\",\"to\":\"0x0000000000000000000000000000000000000001\"}".into()]);
        transport.assert_no_more_requests();
        assert_eq!(result, 5.into());
    }

    #[test]
    fn should_query_single_parameter_function() {
        // given
        let mut transport = TestTransport::default();
        transport.set_response(rpc::Value::String(
            "0x0000000000000000000000000000000000000000000000000000000000000020".into(),
        ));

        let result: U256 = {
            let token = contract(&transport);

            // when
            futures::executor::block_on(token.query(
                "balanceOf",
                Address::from_low_u64_be(5),
                None,
                Options::default(),
                None,
            ))
            .unwrap()
        };

        // then
        transport.assert_request("eth_call", &["{\"data\":\"0x70a082310000000000000000000000000000000000000000000000000000000000000005\",\"to\":\"0x0000000000000000000000000000000000000001\"}".into(), "\"latest\"".into()]);
        transport.assert_no_more_requests();
        assert_eq!(result, 0x20.into());
    }
}