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
416
417
418
419
420
421
422
//! Query methods for interacting with Casper node state.

use crate::casper_client::Result;
use crate::error::LivenetError::{ClientError, DictQueryError};
use crate::log;
use crate::utils::extract_stored_value;
use casper_client::cli::{get_account, get_dictionary_item, DictionaryItemStrParams};
use casper_client::rpcs::results::{GetDeployResult, GetTransactionResult};
use casper_client::rpcs::GlobalStateIdentifier;
use casper_client::{get_balance, get_deploy, get_transaction, query_global_state};
use casper_types::bytesrepr::{deserialize_from_slice, Bytes};
use casper_types::StoredValue::CLValue;
use casper_types::{
    CLTyped, DeployHash, EntityAddr, Key, StoredValue, TransactionHash, URef, U512
};
use odra_core::casper_event_standard::EVENTS_LENGTH;
use odra_core::consts::{CONTRACT_MAIN_PURSE, EVENTS, RESULT_KEY, STATE_KEY};
use odra_core::prelude::*;

/// Query methods implementation for CasperClient.
impl super::CasperClient {
    /// Gets a value from the Odra storage (`state` dictionary)
    pub fn get_value(&self, address: &Address, key: &[u8]) -> Option<Bytes> {
        let rt = self.runtime();
        rt.block_on(self.get_value_async(address, key))
    }

    /// Gets a value from the Odra storage (`state` dictionary)
    async fn get_value_async(&self, address: &Address, key: &[u8]) -> Option<Bytes> {
        self.get_dictionary_value_async(address, STATE_KEY, key)
            .await
    }

    /// Gets a value from a named key of an account or a contract
    pub fn get_named_value(&self, address: &Address, name: &str) -> Option<Bytes> {
        let rt = self.runtime();
        rt.block_on(self.get_named_value_async(address, name))
    }

    /// Gets a value from a named key of an account or a contract
    async fn get_named_value_async(&self, address: &Address, name: &str) -> Option<Bytes> {
        let entity_hash = self.query_global_state_for_entity_addr(address).await;
        let stored_value = self
            .query_global_state_maybe(Key::Hash(entity_hash.value()), Some(name.to_string()))
            .await;
        match stored_value {
            None => None,
            Some(value) => match value {
                CLValue(value) => Some(Bytes::from(value.inner_bytes().as_slice())),
                _ => {
                    log::error(format!(
                        "Couldn't get {} from {:?}, instead of CLValue got {:?}",
                        name,
                        address.to_formatted_string(),
                        value
                    ));
                    None
                }
            }
        }
    }

    /// Gets a value from a result key
    pub async fn get_proxy_result(&self) -> Bytes {
        let stored_value = self
            .query_global_state_maybe(self.caller().as_key(), Some(RESULT_KEY.to_string()))
            .await;

        match stored_value {
            None => {
                log::error(format!(
                    "Couldn't query {} from {:?}, instead of CLValue got None",
                    RESULT_KEY,
                    self.caller().to_formatted_string()
                ));
                Bytes::new()
            }
            Some(sv) => extract_stored_value(sv)
        }
    }

    /// Gets a value from a named dictionary
    pub fn get_dictionary_value(
        &self,
        address: &Address,
        dictionary_name: &str,
        key: &[u8]
    ) -> Option<Bytes> {
        let rt = self.runtime();
        rt.block_on(self.get_dictionary_value_async(address, dictionary_name, key))
    }

    /// Gets a value from a named dictionary
    async fn get_dictionary_value_async(
        &self,
        address: &Address,
        dictionary_name: &str,
        key: &[u8]
    ) -> Option<Bytes> {
        let key = String::from_utf8(key.to_vec())
            .map_err(|_| {
                log::error(format!("Couldn't convert key to string: {:?}", key));
            })
            .ok()?;
        self.query_dict(address, dictionary_name.to_string(), key)
            .await
            .ok()
    }

    /// Returns the balance of the account.
    pub fn get_balance(&self, address: &Address) -> Result<U512> {
        let rt = self.runtime();
        rt.block_on(self.get_balance_async(address))
    }

    /// Returns the balance of the account.
    async fn get_balance_async(&self, address: &Address) -> Result<U512> {
        let main_purse = self.get_main_purse(address).await?;
        let response = get_balance(
            self.rpc_id_typed(),
            self.configuration.node_address(),
            self.configuration.verbosity_typed(),
            self.get_state_root_hash_digest().await?,
            main_purse
        )
        .await
        .map_err(|e| {
            ClientError(format!(
                "Couldn't get balance for address: {:?}, error: {}",
                address.to_formatted_string(),
                e
            ))
        })?;
        Ok(response.result.balance_value)
    }

    /// Gets an uref for a main purse of an account or a contract.
    pub async fn get_main_purse(&self, address: &Address) -> Result<URef> {
        let maybe_purse_uref = self.query_global_state_maybe(address.as_key(), None).await;
        let purse_uref_value = maybe_purse_uref.ok_or_else(|| {
            ClientError(format!(
                "Couldn't get purse uref for address: {:?}",
                address.to_formatted_string()
            ))
        })?;

        match purse_uref_value {
            CLValue(value) => value.into_t().map_err(|e| {
                ClientError(format!(
                    "Failed to convert CLValue to URef for address: {:?}, error: {:?}",
                    address.to_formatted_string(),
                    e
                ))
            }),
            StoredValue::AddressableEntity(entity) => Ok(entity.main_purse()),
            StoredValue::Account(account) => Ok(account.main_purse()),
            StoredValue::ContractPackage(contract_package) => {
                let last_version = contract_package.current_contract_hash().ok_or_else(|| {
                    ClientError(format!(
                        "Contract package has no current contract hash for address: {:?}",
                        address.to_formatted_string()
                    ))
                })?;
                let maybe_contract = self
                    .query_global_state_maybe(Key::Hash(last_version.value()), None)
                    .await;
                let contract_value = maybe_contract.ok_or_else(|| {
                    ClientError(format!(
                        "Couldn't get contract for address: {:?}",
                        address.to_formatted_string()
                    ))
                })?;
                match contract_value {
                    StoredValue::Contract(contract) => {
                        let purse_key =
                            contract
                                .named_keys()
                                .get(CONTRACT_MAIN_PURSE)
                                .ok_or_else(|| {
                                    ClientError(format!(
                                        "Contract missing {} named key for address: {:?}",
                                        CONTRACT_MAIN_PURSE,
                                        address.to_formatted_string()
                                    ))
                                })?;
                        purse_key.into_uref().ok_or_else(|| {
                            ClientError(format!(
                                "{} named key is not a URef for address: {:?}",
                                CONTRACT_MAIN_PURSE,
                                address.to_formatted_string()
                            ))
                        })
                    }
                    _ => Err(ClientError(format!(
                        "Couldn't get main purse for address: {:?}",
                        address.to_formatted_string()
                    )))
                }
            }
            _ => Err(ClientError(format!(
                "Getting main purse is not supported for: {:?}",
                purse_uref_value
            )))
        }
    }

    /// Get the event bytes from storage
    pub fn get_event(&self, contract_address: &Address, index: u32) -> Result<Bytes> {
        let rt = self.runtime();
        rt.block_on(self.get_event_async(contract_address, index))
    }

    /// Get the event bytes from storage
    async fn get_event_async(&self, contract_address: &Address, index: u32) -> Result<Bytes> {
        self.query_dict(contract_address, EVENTS.to_string(), index.to_string())
            .await
    }

    /// Get the events count from storage
    pub fn events_count(&self, contract_address: &Address) -> Option<u32> {
        let rt = self.runtime();
        rt.block_on(self.events_count_async(contract_address))
    }

    /// Get the events count from storage
    async fn events_count_async(&self, contract_address: &Address) -> Option<u32> {
        self.get_named_value_async(contract_address, EVENTS_LENGTH)
            .await
            .map(|bytes| {
                deserialize_from_slice(&bytes).unwrap_or_else(|_| {
                    panic!(
                        "Couldn't deserialize events count for contract: {:?}, bytes: {:?}",
                        contract_address, bytes
                    )
                })
            })
    }

    /// Query the node for the transaction state.
    pub async fn get_transaction(
        &self,
        transaction_hash: TransactionHash
    ) -> Result<GetTransactionResult> {
        let t = get_transaction(
            self.rpc_id_typed(),
            self.configuration.node_address(),
            self.configuration.verbosity_typed(),
            transaction_hash,
            true
        )
        .await
        .map_err(|e| {
            log::error(format!("Couldn't get transaction: {:?}", e));
            ClientError(format!(
                "Couldn't get transaction: {}",
                transaction_hash.to_hex_string()
            ))
        })?;
        Ok(t.result)
    }

    /// Query the node for the transaction state.
    pub async fn get_deploy(&self, deploy_hash: DeployHash) -> Result<GetDeployResult> {
        let t = get_deploy(
            self.rpc_id_typed(),
            self.configuration.node_address(),
            self.configuration.verbosity_typed(),
            deploy_hash,
            true
        )
        .await
        .map_err(|e| {
            log::error(format!("Couldn't get deploy: {:?}", e));
            ClientError(format!(
                "Couldn't get deploy: {}",
                deploy_hash.to_hex_string()
            ))
        })?;
        Ok(t.result)
    }

    /// Discover the contract address by name.
    pub(crate) async fn get_contract_address(&self, key_name: &str) -> Result<Address> {
        let result = get_account(
            &self.rpc_id(),
            self.configuration.node_address(),
            self.configuration.verbosity(),
            "",
            &self.public_key().to_hex_string()
        )
        .await
        .map_err(|e| {
            ClientError(format!(
                "Couldn't get entity for key: {:?}, reason: {}",
                key_name, e
            ))
        })?;
        let account = result.result.account;

        let key = account.named_keys().get(key_name).ok_or_else(|| {
            ClientError(format!(
                "Couldn't get named key {:?} for account: {:?}",
                key_name,
                self.public_key().to_hex_string()
            ))
        })?;

        let package_hash = key.into_package_hash().ok_or_else(|| {
            ClientError(format!(
                "Couldn't get package hash from key {:?} for account: {:?}",
                key_name,
                self.public_key().to_hex_string()
            ))
        })?;

        Ok(Address::from(package_hash))
    }

    /// Find the entity addr in global state for an address
    async fn query_global_state_for_entity_addr(&self, address: &Address) -> EntityAddr {
        let maybe_result = self.query_global_state_maybe(address.as_key(), None).await;
        let entity_addr_value = match maybe_result {
            None => panic!("Couldn't query for entity address value at {:?}", address),
            Some(entity_addr_value) => entity_addr_value
        };
        match entity_addr_value {
            StoredValue::SmartContract(package) => EntityAddr::SmartContract(
                package
                    .current_entity_hash()
                    .unwrap_or_else(|| {
                        panic!(
                            "Couldn't get entity addr for address: {:?}",
                            address.to_formatted_string()
                        )
                    })
                    .value()
            ),
            StoredValue::ContractPackage(package) => {
                let last_version = package.current_contract_hash().unwrap_or_else(|| {
                    panic!(
                        "Contract package has no current contract hash for address: {:?}",
                        address.to_formatted_string()
                    )
                });
                EntityAddr::SmartContract(last_version.value())
            }
            _ => {
                panic!(
                    "Entity addr for {:?} was incorrect: {:?}",
                    address.to_formatted_string(),
                    entity_addr_value
                )
            }
        }
    }

    /// Query the node for the dictionary item of a contract or an account.
    async fn query_dict(
        &self,
        address: &Address,
        dictionary_name: String,
        dictionary_item_key: String
    ) -> Result<Bytes> {
        let entity_addr = self.query_global_state_for_entity_addr(address).await;
        let hash_addr = Key::Hash(entity_addr.value()).to_formatted_string();
        let params = DictionaryItemStrParams::ContractNamedKey {
            hash_addr: &hash_addr,
            dictionary_name: &dictionary_name,
            dictionary_item_key: &dictionary_item_key
        };

        let r = get_dictionary_item(
            &self.rpc_id(),
            self.configuration.node_address(),
            self.configuration.verbosity(),
            &self.get_state_root_hash().await?,
            params
        )
        .await;

        let result = r.map_err(|e| ClientError(e.to_string()))?;
        let stored_value = result.result.stored_value;
        let cl_value = stored_value.into_cl_value().ok_or(DictQueryError)?;

        // Note: this is for compatibility with CEP18 named keys.
        if cl_value.cl_type() == &<Vec<u8> as CLTyped>::cl_type() {
            let bytes = cl_value.into_t().map_err(|_| DictQueryError)?;
            Ok(bytes)
        } else {
            let bytes = cl_value.inner_bytes();
            Ok(Bytes::from(bytes.to_vec()))
        }
    }

    pub(crate) async fn query_global_state_maybe(
        &self,
        key: Key,
        path: Option<String>
    ) -> Option<StoredValue> {
        let path = match path {
            None => vec![],
            Some(string) => vec![string]
        };
        let state_root_hash = match self.get_state_root_hash_digest().await {
            Ok(hash) => hash,
            Err(_) => return None
        };
        let result = query_global_state(
            self.rpc_id_typed(),
            self.configuration.node_address(),
            self.configuration.verbosity_typed(),
            GlobalStateIdentifier::StateRootHash(state_root_hash),
            key,
            path
        )
        .await;
        match result {
            Ok(r) => Some(r.result.stored_value),
            Err(_) => None
        }
    }
}