odra-casper-rpc-client 2.9.0

RPC Client for the Casper Node.
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
//! Transaction building and deployment methods.

use crate::casper_client::Result;
use crate::error::LivenetError;
use crate::log;
use casper_client::cli::TransactionV1Builder;
use casper_client::put_transaction;
use casper_types::bytesrepr::{Bytes, ToBytes};
use casper_types::execution::ExecutionResultV1::{Failure, Success};
use casper_types::{
    execution::ExecutionResult, runtime_args, PricingMode, RuntimeArgs, Timestamp, Transaction,
    TransactionHash, TransactionRuntimeParams, TransferTarget, U512
};
use odra_core::consts::{
    AMOUNT_ARG, ARGS_ARG, ATTACHED_VALUE_ARG, ENTRY_POINT_ARG, PACKAGE_HASH_ARG,
    PACKAGE_HASH_KEY_NAME_ARG
};
use odra_core::prelude::*;
use odra_core::CallDef;

/// Gas amount used for native transfers.
const NATIVE_TRANSFER_GAS: u64 = 100_000_000u64;

/// Transaction methods implementation for CasperClient.
impl super::CasperClient {
    /// Transfers the specified number of tokens to the given address.
    pub fn transfer(
        &self,
        to: Address,
        amount: U512,
        timestamp: Timestamp
    ) -> Result<TransactionHash> {
        let rt = self.runtime();
        rt.block_on(self.transfer_async(to, amount, timestamp))
    }

    /// Transfers the specified number of tokens to the given address.
    async fn transfer_async(
        &self,
        to: Address,
        amount: U512,
        timestamp: Timestamp
    ) -> Result<TransactionHash> {
        let transaction = self.new_transfer_transaction(to, amount, timestamp)?;
        log::debug(serde_json::to_string_pretty(&transaction).unwrap());
        self.put_transaction(transaction).await
    }

    /// Deploy the contract.
    pub fn deploy_wasm(
        &mut self,
        contract_name: &str,
        args: RuntimeArgs,
        timestamp: Timestamp,
        wasm_bytes: Vec<u8>
    ) -> Result<Address> {
        let rt = self.runtime();
        rt.block_on(self.deploy_wasm_async(contract_name, args, timestamp, wasm_bytes))
    }

    /// Deploy the contract.
    async fn deploy_wasm_async(
        &mut self,
        contract_name: &str,
        args: RuntimeArgs,
        timestamp: Timestamp,
        wasm_bytes: Vec<u8>
    ) -> Result<Address> {
        log::info(format!("Deploying \"{}\".", contract_name));

        let package_hash_key_name: String = args
            .get(PACKAGE_HASH_KEY_NAME_ARG)
            .ok_or_else(|| {
                LivenetError::ExecutionError(format!(
                    "Missing required argument: {}",
                    PACKAGE_HASH_KEY_NAME_ARG
                ))
            })?
            .clone()
            .into_t()
            .map_err(|e| {
                LivenetError::ExecutionError(format!(
                    "Failed to parse {} argument: {:?}",
                    PACKAGE_HASH_KEY_NAME_ARG, e
                ))
            })?;

        if self.gas.is_zero() {
            return Err(LivenetError::GasNotSet);
        }

        let transaction =
            self.new_wasm_deploy_transaction(Bytes::from(wasm_bytes), args, timestamp)?;
        log::debug(serde_json::to_string_pretty(&transaction).unwrap());
        self.put_transaction(transaction).await?;

        let address = self.get_contract_address(&package_hash_key_name).await?;
        log::info(format!(
            "Contract {:?} deployed.",
            &address.to_formatted_string()
        ));

        Ok(address)
    }

    /// Deploy the entrypoint call using getter_proxy.
    /// It runs the getter_proxy contract in an account context and stores the return value of the call
    /// in under the key RESULT_KEY.
    pub fn deploy_entrypoint_call_with_proxy(
        &self,
        address: Address,
        call_def: CallDef,
        timestamp: Timestamp
    ) -> Result<Bytes> {
        let rt = self.runtime();
        rt.block_on(self.deploy_entrypoint_call_with_proxy_async(address, call_def, timestamp))
    }

    /// Deploy the entrypoint call using getter_proxy.
    /// It runs the getter_proxy contract in an account context and stores the return value of the call
    /// in under the key RESULT_KEY.
    async fn deploy_entrypoint_call_with_proxy_async(
        &self,
        address: Address,
        call_def: CallDef,
        timestamp: Timestamp
    ) -> Result<Bytes> {
        log::info(format!(
            "Calling {:?} with entrypoint \"{}\" through proxy.",
            address.to_formatted_string(),
            call_def.entry_point()
        ));

        let hash = address.as_contract_package_hash().ok_or_else(|| {
            LivenetError::ExecutionError(format!(
                "Address {:?} is not a contract package hash. Expected contract address.",
                address.to_formatted_string()
            ))
        })?;
        let args_bytes: Vec<u8> = call_def
            .args()
            .to_bytes()
            .expect("Should serialize to bytes");
        let entry_point = call_def.entry_point();
        let args = runtime_args! {
            PACKAGE_HASH_ARG => hash,
            ENTRY_POINT_ARG => entry_point,
            ARGS_ARG => Bytes::from(args_bytes),
            ATTACHED_VALUE_ARG => call_def.amount(),
            AMOUNT_ARG => call_def.amount(),
        };

        let module_bytes = include_bytes!("../../resources/proxy_caller_with_return.wasm")
            .to_vec()
            .into();

        let transaction = self.new_wasm_deploy_transaction(module_bytes, args, timestamp)?;
        log::debug(serde_json::to_string_pretty(&transaction).unwrap());
        let watch = self.watcher.start_watching().await?;

        let response = put_transaction(
            self.rpc_id_typed(),
            self.configuration.node_address(),
            self.configuration.verbosity_typed(),
            transaction
        )
        .await
        .map_err(|e| match e {
            casper_client::Error::ResponseIsRpcError {
                rpc_method, error, ..
            } => LivenetError::RpcRequestError(
                rpc_method.to_string(),
                error
                    .data
                    .map_or_else(|| "No data".to_string(), |d| d.to_string())
            ),
            _ => LivenetError::ExecutionError(format!("Failed to put transaction: {}", e))
        })?;
        let transaction_hash = response.result.transaction_hash;
        let result = watch.wait_for_transaction_hash(&transaction_hash).await?;
        self.process_transaction(result, transaction_hash)?;
        Ok(self.get_proxy_result().await)
    }

    /// Deploy the entrypoint call.
    pub fn deploy_entrypoint_call(
        &self,
        addr: Address,
        call_def: CallDef,
        timestamp: Timestamp
    ) -> Result<Bytes> {
        let rt = self.runtime();
        rt.block_on(self.deploy_entrypoint_call_async(addr, call_def, timestamp))
    }

    /// Deploy the entrypoint call.
    async fn deploy_entrypoint_call_async(
        &self,
        addr: Address,
        call_def: CallDef,
        timestamp: Timestamp
    ) -> Result<Bytes> {
        log::info(format!(
            "Calling {:?} directly with entrypoint \"{}\".",
            addr.to_formatted_string(),
            call_def.entry_point()
        ));

        let transaction = self.new_call_transaction(addr, call_def, timestamp)?;
        log::debug(serde_json::to_string_pretty(&transaction).unwrap());
        let watch = self.watcher.start_watching().await?;

        let response = put_transaction(
            self.rpc_id_typed(),
            self.configuration.node_address(),
            self.configuration.verbosity_typed(),
            transaction
        )
        .await;
        let transaction_hash = match response {
            Ok(r) => r.result.transaction_hash,
            Err(e) => {
                return match e {
                    casper_client::Error::ResponseIsRpcError {
                        rpc_method, error, ..
                    } => Err(LivenetError::RpcRequestError(
                        rpc_method.to_string(),
                        error
                            .data
                            .map_or_else(|| "No data".to_string(), |d| d.to_string())
                    )),
                    _ => Err(LivenetError::ExecutionError(e.to_string()))
                }
            }
        };
        let result = watch.wait_for_transaction_hash(&transaction_hash).await?;
        self.process_transaction(result, transaction_hash).map(|_| {
            ().to_bytes()
                .expect("Couldn't serialize (). This shouldn't happen.")
                .into()
        })
    }

    async fn put_transaction(&self, transaction: Transaction) -> Result<TransactionHash> {
        log::debug("[TX] Starting event watcher before sending transaction...");
        let watch = self.watcher.start_watching().await?;
        log::debug("[TX] Event watcher ready, now sending transaction...");

        let response = put_transaction(
            self.rpc_id_typed(),
            self.configuration.node_address(),
            self.configuration.verbosity_typed(),
            transaction
        )
        .await
        .map_err(|e| match e {
            casper_client::Error::ResponseIsRpcError {
                rpc_method, error, ..
            } => LivenetError::RpcRequestError(
                rpc_method.to_string(),
                error
                    .data
                    .map_or_else(|| "No data".to_string(), |d| d.to_string())
            ),
            _ => LivenetError::ExecutionError(format!("Failed to put transaction: {}", e))
        })?;
        let transaction_hash = response.result.transaction_hash;
        log::debug(format!(
            "[TX] Transaction sent with hash: {}",
            transaction_hash.to_hex_string()
        ));
        let result = watch.wait_for_transaction_hash(&transaction_hash).await?;
        self.process_transaction(result, transaction_hash)?;
        Ok(transaction_hash)
    }

    fn process_transaction(
        &self,
        result: ExecutionResult,
        transaction_hash: TransactionHash
    ) -> Result<()> {
        let deploy_hash_str = transaction_hash.to_hex_string();
        match result {
            ExecutionResult::V1(r) => match r {
                Failure { error_message, .. } => {
                    log::error(format!(
                        "Deploy V1 {:?} failed with error: {:?}.",
                        deploy_hash_str, error_message
                    ));
                    Err(LivenetError::ExecutionError(error_message.to_string()))
                }
                Success { .. } => {
                    log::info(format!(
                        "Deploy {:?} successfully executed.",
                        deploy_hash_str
                    ));
                    Ok(())
                }
            },
            ExecutionResult::V2(r) => match r.error_message {
                None => {
                    log::info(format!(
                        "Transaction {:?} successfully executed.",
                        &deploy_hash_str,
                    ));
                    if let Some(url) = self.configuration.transaction_url(&deploy_hash_str) {
                        log::link(url);
                    }
                    Ok(())
                }
                Some(error_message) => {
                    log::error(format!(
                        "Transaction {:?} failed with error: {:?}.",
                        deploy_hash_str, error_message,
                    ));
                    if let Some(url) = self.configuration.transaction_url(&deploy_hash_str) {
                        log::link(url);
                    }
                    Err(LivenetError::ExecutionError(error_message.to_string()))
                }
            }
        }
    }

    fn new_wasm_deploy_transaction(
        &self,
        transaction_bytes: Bytes,
        args: RuntimeArgs,
        timestamp: Timestamp
    ) -> Result<Transaction> {
        let transaction_builder = TransactionV1Builder::new_session(
            true,
            transaction_bytes,
            TransactionRuntimeParams::VmCasperV1
        );
        Ok(Transaction::V1(
            transaction_builder
                .with_runtime_args(args)
                .with_ttl(self.configuration.ttl())
                .with_chain_name(self.configuration.chain_name())
                .with_pricing_mode(self.pricing_mode())
                .with_secret_key(self.secret_key())
                .with_timestamp(timestamp)
                .build()
                .map_err(|_| LivenetError::InvalidTransaction)?
        ))
    }

    fn new_transfer_transaction(
        &self,
        to: Address,
        amount: U512,
        timestamp: Timestamp
    ) -> Result<Transaction> {
        let target = TransferTarget::AccountHash(
            *to.as_account_hash()
                .ok_or(LivenetError::InvalidTransferTarget(to))?
        );
        let transaction_builder = TransactionV1Builder::new_transfer(amount, None, target, None)
            .map_err(|_| LivenetError::SerializationError)?;
        Ok(Transaction::V1(
            transaction_builder
                .with_ttl(self.configuration.ttl())
                .with_chain_name(self.configuration.chain_name())
                .with_pricing_mode(PricingMode::PaymentLimited {
                    payment_amount: NATIVE_TRANSFER_GAS,
                    gas_price_tolerance: self.configuration.gas_price_tolerance(),
                    standard_payment: true
                })
                .with_secret_key(self.secret_key())
                .with_timestamp(timestamp)
                .build()
                .map_err(|_| LivenetError::InvalidTransaction)?
        ))
    }

    fn new_call_transaction(
        &self,
        to: Address,
        call_def: CallDef,
        timestamp: Timestamp
    ) -> Result<Transaction> {
        let package_hash = to
            .as_package_hash()
            .ok_or(LivenetError::InvalidTransferTarget(to))?;
        let transaction_builder = TransactionV1Builder::new_targeting_package(
            package_hash,
            None,
            call_def.entry_point(),
            TransactionRuntimeParams::VmCasperV1
        );
        let transaction_v1 = transaction_builder
            .with_ttl(self.configuration.ttl())
            .with_chain_name(self.configuration.chain_name())
            .with_pricing_mode(PricingMode::PaymentLimited {
                payment_amount: call_def.amount().as_u64() + self.gas.as_u64(),
                gas_price_tolerance: self.configuration.gas_price_tolerance(),
                standard_payment: true
            })
            .with_secret_key(self.secret_key())
            .with_timestamp(timestamp)
            .with_runtime_args(call_def.args().clone())
            .build()
            .map_err(|_| LivenetError::InvalidTransaction)?;
        Ok(Transaction::V1(transaction_v1))
    }

    fn pricing_mode(&self) -> PricingMode {
        PricingMode::PaymentLimited {
            payment_amount: self.gas.as_u64(),
            gas_price_tolerance: self.configuration.gas_price_tolerance(),
            standard_payment: true
        }
    }
}