odra-casper-client 3.0.2

A client library and binary for interacting with the Casper network
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
#[cfg(feature = "std-fs-io")]
use crate::read_transaction_file;
#[cfg(feature = "std-fs-io")]
use crate::rpcs::v2_0_0::speculative_exec_transaction::SpeculativeExecTxnResult;
#[cfg(feature = "std-fs-io")]
use crate::speculative_exec_txn;
use crate::{
    cli::{parse, CliError, TransactionBuilderParams, TransactionStrParams, TransactionV1Builder},
    put_transaction as put_transaction_rpc_handler,
    rpcs::results::PutTransactionResult,
    SuccessResponse,
};
use casper_types::{
    Digest, InitiatorAddr, SecretKey, Transaction, TransactionArgs, TransactionEntryPoint,
    TransactionRuntimeParams,
};

pub fn create_transaction(
    builder_params: TransactionBuilderParams,
    transaction_params: TransactionStrParams,
    allow_unsigned_transaction: bool,
) -> Result<Transaction, CliError> {
    let chain_name = transaction_params.chain_name.to_string();

    let maybe_secret_key = get_maybe_secret_key(
        transaction_params.secret_key,
        allow_unsigned_transaction,
        "create_transaction",
    )?;

    let timestamp = parse::timestamp(transaction_params.timestamp)?;
    let ttl = parse::ttl(transaction_params.ttl)?;
    let maybe_session_account = parse::session_account(&transaction_params.initiator_addr)?;

    let is_v2_wasm = matches!(&builder_params, TransactionBuilderParams::Session { runtime, .. } if matches!(runtime, &TransactionRuntimeParams::VmCasperV2 { .. }));

    let mut transaction_builder = make_transaction_builder(builder_params)?;

    transaction_builder = transaction_builder
        .with_timestamp(timestamp)
        .with_ttl(ttl)
        .with_chain_name(chain_name);

    if transaction_params.pricing_mode.is_empty() {
        return Err(CliError::InvalidArgument {
            context: "create_transaction (pricing_mode)",
            error: "pricing_mode is required to be non empty".to_string(),
        });
    }

    let pricing_mode = if transaction_params.pricing_mode.to_lowercase().as_str() == "reserved" {
        let digest = Digest::from_hex(transaction_params.receipt).map_err(|error| {
            CliError::FailedToParseDigest {
                context: "pricing_digest",
                error,
            }
        })?;

        parse::pricing_mode(
            transaction_params.pricing_mode,
            transaction_params.payment_amount,
            transaction_params.gas_price_tolerance,
            transaction_params.additional_computation_factor,
            transaction_params.standard_payment,
            Some(digest),
        )?
    } else {
        parse::pricing_mode(
            transaction_params.pricing_mode,
            transaction_params.payment_amount,
            transaction_params.gas_price_tolerance,
            transaction_params.additional_computation_factor,
            transaction_params.standard_payment,
            None,
        )?
    };

    transaction_builder = transaction_builder.with_pricing_mode(pricing_mode);

    let maybe_json_args = parse::args_json::session::parse(transaction_params.session_args_json)?;
    let maybe_simple_args =
        parse::arg_simple::session::parse(&transaction_params.session_args_simple)?;
    let chunked = transaction_params.chunked_args;

    let args = parse::args_from_simple_or_json(maybe_simple_args, maybe_json_args, chunked);
    match args {
        TransactionArgs::Named(named_args) => {
            if !named_args.is_empty() {
                transaction_builder = transaction_builder.with_runtime_args(named_args);
            }
        }
        TransactionArgs::Bytesrepr(chunked_args) => {
            transaction_builder = transaction_builder.with_chunked_args(chunked_args);
        }
    }

    if is_v2_wasm {
        if let Some(entry_point) = transaction_params.session_entry_point {
            transaction_builder = transaction_builder
                .with_entry_point(TransactionEntryPoint::Custom(entry_point.to_owned()));
        }
    }

    if let Some(secret_key) = &maybe_secret_key {
        transaction_builder = transaction_builder.with_secret_key(secret_key);
    }

    if let Some(account) = maybe_session_account {
        transaction_builder =
            transaction_builder.with_initiator_addr(InitiatorAddr::PublicKey(account));
    }

    let txn = transaction_builder.build().map_err(crate::Error::from)?;
    Ok(Transaction::V1(txn))
}

/// Creates a [`Transaction`] and outputs it to a file or stdout if the `std-fs-io` feature is enabled.
///
/// As a file, the `Transaction` can subsequently be signed by other parties using [`sign_transaction_file`]
/// and then sent to the network for execution using [`send_transaction_file`].
///
/// If the `std-fs-io` feature is NOT enabled, `maybe_output_path` and `force` are ignored.
/// Otherwise, `maybe_output_path` specifies the output file path, or if empty, will print it to
/// `stdout`.  If `force` is true, and a file exists at `maybe_output_path`, it will be
/// overwritten.  If `force` is false and a file exists at `maybe_output_path`,
/// [`crate::Error::FileAlreadyExists`] is returned and the file will not be written.
pub fn make_transaction(
    builder_params: TransactionBuilderParams,
    transaction_params: TransactionStrParams<'_>,
    #[allow(unused_variables)] force: bool,
) -> Result<Transaction, CliError> {
    let transaction = create_transaction(builder_params, transaction_params.clone(), true)?;
    #[cfg(feature = "std-fs-io")]
    {
        let output = parse::output_kind(transaction_params.output_path, force);
        crate::output_transaction(output, &transaction).map_err(CliError::from)?;
    }
    Ok(transaction)
}

/// Creates a [`Transaction`] and sends it to the network for execution.
///
/// `rpc_id_str` is the RPC ID to use for this request.
/// `node_address` is the address of the node to send the request to.
/// `verbosity_level` is the level of verbosity to use when outputting the response.
pub async fn put_transaction(
    rpc_id_str: &str,
    node_address: &str,
    verbosity_level: u64,
    builder_params: TransactionBuilderParams<'_>,
    transaction_params: TransactionStrParams<'_>,
) -> Result<SuccessResponse<PutTransactionResult>, CliError> {
    let rpc_id = parse::rpc_id(rpc_id_str);
    let verbosity_level = parse::verbosity(verbosity_level);
    let transaction = create_transaction(builder_params, transaction_params, false)?;
    put_transaction_rpc_handler(rpc_id, node_address, verbosity_level, transaction)
        .await
        .map_err(CliError::from)
}
///
/// Reads a previously-saved [`TransactionV1`] from a file and sends it to the network for execution.
///
/// `rpc_id_str` is the RPC ID to use for this request. node_address is the address of the node to send the request to.
/// verbosity_level is the level of verbosity to use when outputting the response.
/// the input path is the path to the file containing the transaction to send.
#[cfg(feature = "std-fs-io")]
pub async fn send_transaction_file(
    rpc_id_str: &str,
    node_address: &str,
    verbosity_level: u64,
    input_path: &str,
) -> Result<SuccessResponse<PutTransactionResult>, CliError> {
    let rpc_id = parse::rpc_id(rpc_id_str);
    let verbosity_level = parse::verbosity(verbosity_level);
    let transaction = read_transaction_file(input_path)?;
    put_transaction_rpc_handler(rpc_id, node_address, verbosity_level, transaction)
        .await
        .map_err(CliError::from)
}

///
/// Reads a previously-saved [`TransactionV1`] from a file and sends it to the network for execution.
///
/// `rpc_id_str` is the RPC ID to use for this request. node_address is the address of the node to send the request to.
/// verbosity_level is the level of verbosity to use when outputting the response.
///  the input path is the path to the file containing the transaction to send.
#[cfg(feature = "std-fs-io")]
pub async fn speculative_send_transaction_file(
    rpc_id_str: &str,
    node_address: &str,
    verbosity_level: u64,
    input_path: &str,
) -> Result<SuccessResponse<SpeculativeExecTxnResult>, CliError> {
    let rpc_id = parse::rpc_id(rpc_id_str);
    let verbosity_level = parse::verbosity(verbosity_level);
    let transaction = read_transaction_file(input_path).unwrap();
    speculative_exec_txn(rpc_id, node_address, verbosity_level, transaction)
        .await
        .map_err(CliError::from)
}

/// Reads a previously-saved [`TransactionV1`] from a file, cryptographically signs it, and outputs it to a
/// file or stdout.
///
/// `maybe_output_path` specifies the output file path, or if empty, will print it to `stdout`.  If
/// `force` is true, and a file exists at `maybe_output_path`, it will be overwritten.  If `force`
/// is false and a file exists at `maybe_output_path`, [`crate::Error::FileAlreadyExists`] is returned
/// and the file will not be written.
#[cfg(feature = "std-fs-io")]
pub fn sign_transaction_file(
    input_path: &str,
    secret_key_path: &str,
    maybe_output_path: Option<&str>,
    force: bool,
) -> Result<(), CliError> {
    let output = parse::output_kind(maybe_output_path.unwrap_or(""), force);
    let secret_key = parse::secret_key_from_file(secret_key_path)?;
    crate::sign_transaction_file(input_path, &secret_key, output).map_err(CliError::from)
}

pub fn make_transaction_builder(
    transaction_builder_params: TransactionBuilderParams,
) -> Result<TransactionV1Builder, CliError> {
    match transaction_builder_params {
        TransactionBuilderParams::AddBid {
            public_key,
            delegation_rate,
            amount,
            minimum_delegation_amount,
            maximum_delegation_amount,
            reserved_slots,
        } => {
            let transaction_builder = TransactionV1Builder::new_add_bid(
                public_key,
                delegation_rate,
                amount,
                minimum_delegation_amount,
                maximum_delegation_amount,
                reserved_slots,
            )?;
            Ok(transaction_builder)
        }
        TransactionBuilderParams::Delegate {
            delegator,
            validator,
            amount,
        } => {
            let transaction_builder =
                TransactionV1Builder::new_delegate(delegator, validator, amount)?;
            Ok(transaction_builder)
        }
        TransactionBuilderParams::Undelegate {
            delegator,
            validator,
            amount,
        } => {
            let transaction_builder =
                TransactionV1Builder::new_undelegate(delegator, validator, amount)?;
            Ok(transaction_builder)
        }
        TransactionBuilderParams::Redelegate {
            delegator,
            validator,
            amount,
            new_validator,
        } => {
            let transaction_builder =
                TransactionV1Builder::new_redelegate(delegator, validator, amount, new_validator)?;
            Ok(transaction_builder)
        }
        TransactionBuilderParams::InvocableEntity {
            entity_hash,
            entry_point,
            runtime,
        } => {
            let transaction_builder = TransactionV1Builder::new_targeting_invocable_entity(
                entity_hash,
                entry_point,
                runtime,
            );
            Ok(transaction_builder)
        }
        TransactionBuilderParams::InvocableEntityAlias {
            entity_alias,
            entry_point,
            runtime,
        } => {
            let transaction_builder =
                TransactionV1Builder::new_targeting_invocable_entity_via_alias(
                    entity_alias,
                    entry_point,
                    runtime,
                );
            Ok(transaction_builder)
        }
        TransactionBuilderParams::Package {
            package_hash,
            maybe_entity_version,
            entry_point,
            runtime,
        } => {
            let transaction_builder = TransactionV1Builder::new_targeting_package(
                package_hash,
                maybe_entity_version,
                entry_point,
                runtime,
            );
            Ok(transaction_builder)
        }
        TransactionBuilderParams::PackageWithVersionKey {
            package_hash,
            maybe_entity_version_key,
            entry_point,
            runtime,
        } => {
            let transaction_builder = TransactionV1Builder::new_targeting_package_with_version_key(
                package_hash,
                maybe_entity_version_key,
                entry_point,
                runtime,
            );
            Ok(transaction_builder)
        }
        TransactionBuilderParams::PackageAlias {
            package_alias,
            maybe_entity_version,
            entry_point,
            runtime,
        } => {
            let new_targeting_package_via_alias =
                TransactionV1Builder::new_targeting_package_via_alias(
                    package_alias,
                    maybe_entity_version,
                    entry_point,
                    runtime,
                );
            let transaction_builder = new_targeting_package_via_alias;
            Ok(transaction_builder)
        }
        TransactionBuilderParams::PackageAliasWithVersionKey {
            package_alias,
            maybe_entity_version_key,
            entry_point,
            runtime,
        } => {
            let new_targeting_package_via_alias =
                TransactionV1Builder::new_targeting_package_via_alias_with_version_key(
                    package_alias,
                    maybe_entity_version_key,
                    entry_point,
                    runtime,
                );
            let transaction_builder = new_targeting_package_via_alias;
            Ok(transaction_builder)
        }
        TransactionBuilderParams::Session {
            is_install_upgrade,
            transaction_bytes,
            runtime,
        } => {
            let transaction_builder =
                TransactionV1Builder::new_session(is_install_upgrade, transaction_bytes, runtime);
            Ok(transaction_builder)
        }
        TransactionBuilderParams::Transfer {
            maybe_source,
            target,
            amount,
            maybe_id,
        } => {
            let transaction_builder =
                TransactionV1Builder::new_transfer(amount, maybe_source, target, maybe_id)?;

            Ok(transaction_builder)
        }
        TransactionBuilderParams::WithdrawBid {
            public_key, amount, ..
        } => {
            let transaction_builder = TransactionV1Builder::new_withdraw_bid(public_key, amount)?;
            Ok(transaction_builder)
        }
        TransactionBuilderParams::ActivateBid { validator } => {
            let transaction_builder = TransactionV1Builder::new_activate_bid(validator)?;
            Ok(transaction_builder)
        }
        TransactionBuilderParams::ChangeBidPublicKey {
            public_key,
            new_public_key,
        } => {
            let transaction_builder =
                TransactionV1Builder::new_change_bid_public_key(public_key, new_public_key)?;
            Ok(transaction_builder)
        }
        TransactionBuilderParams::AddReservations { reservations } => {
            let transaction_builder = TransactionV1Builder::new_add_reservations(reservations)?;
            Ok(transaction_builder)
        }
        TransactionBuilderParams::CancelReservations {
            validator,
            delegators,
        } => {
            let transaction_builder =
                TransactionV1Builder::new_cancel_reservations(validator, delegators)?;
            Ok(transaction_builder)
        }
    }
}

/// Retrieves a `SecretKey` based on the provided secret key string and configuration options.
///
/// * `secret_key` - A string representing the secret key. This can result in three outcomes:
///     - If a valid secret key is provided and the `std-fs-io` feature is enabled, the `Result` contains `Some(SecretKey)`.
///     - If `secret_key` is empty and `allow_unsigned_deploy` is `true`, the `Result` contains `None`.
///     - If `secret_key` is empty and `allow_unsigned_deploy` is `false`, the `Result` contains an `Err` variant with `CliError::InvalidArgument`.
/// * `allow_unsigned_deploy` - A boolean indicating whether unsigned deploys are allowed.
///
/// # Returns
///
/// Returns a `Result` containing an `Option<SecretKey>`.
/// * If a valid secret key is provided and the `std-fs-io` feature is enabled, the `Result` contains `Some(SecretKey)`.
/// * If the `std-fs-io` feature is disabled, the `Result` contains `Some(SecretKey)` parsed from the provided file.
/// * If `secret_key` is empty and `allow_unsigned_deploy` is `true`, the `Result` contains `None`.
/// * If `secret_key` is empty and `allow_unsigned_deploy` is `false`, an `Err` variant with `CliError::InvalidArgument` is returned.
///
/// # Errors
///
/// Returns an `Err` variant with a `CliError::Core` or `CliError::InvalidArgument` if there are issues with parsing the secret key.
pub fn get_maybe_secret_key(
    secret_key: &str,
    allow_unsigned_deploy: bool,
    context: &'static str,
) -> Result<Option<SecretKey>, CliError> {
    match (secret_key.is_empty(), allow_unsigned_deploy) {
        (false, _) => {
            #[cfg(feature = "std-fs-io")]
            {
                Ok(Some(parse::secret_key_from_file(secret_key)?))
            }
            #[cfg(not(feature = "std-fs-io"))]
            {
                let secret_key = SecretKey::from_pem(secret_key).map_err(|error| {
                    CliError::Core(crate::Error::CryptoError { context, error })
                })?;
                Ok(Some(secret_key))
            }
        }
        (true, true) => Ok(None),
        (true, false) => Err(CliError::InvalidArgument {
            context,
            error: "No secret key provided and unsigned deploys are not allowed".to_string(),
        }),
    }
}