soroban-cli 27.1.0

Soroban CLI
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
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
use std::array::TryFromSliceError;
use std::ffi::OsString;
use std::fmt::Debug;
use std::num::ParseIntError;

use clap::Parser;
use rand::Rng;
use soroban_spec_tools::contract as contract_spec;

use crate::config::address::AliasName;
use crate::resources;
use crate::tx::sim_sign_and_send_tx;
use crate::xdr::{
    AccountId, ContractExecutable, ContractIdPreimage, ContractIdPreimageFromAddress,
    CreateContractArgs, CreateContractArgsV2, Error as XdrError, Hash, HostFunction,
    InvokeContractArgs, InvokeHostFunctionOp, Limits, Memo, MuxedAccount, Operation, OperationBody,
    Preconditions, PublicKey, ScAddress, SequenceNumber, Transaction, TransactionExt, Uint256,
    VecM, WriteXdr,
};

use crate::commands::tx::fetch;
use crate::{
    commands::{
        contract::{self, arg_parsing, build, id::wasm::get_contract_id, upload},
        global,
        txn_result::{TxnEnvelopeResult, TxnResult},
        HEADING_TRANSACTION,
    },
    config::{self, data, locator, network},
    print::Print,
    rpc,
    utils::{self, rpc::get_remote_wasm_from_hash},
    wasm,
};

pub const CONSTRUCTOR_FUNCTION_NAME: &str = "__constructor";

#[derive(Parser, Debug, Clone)]
#[command(group(
    clap::ArgGroup::new("wasm_src")
        .required(false)
        .args(&["wasm", "wasm_hash"]),
))]
#[group(skip)]
pub struct Cmd {
    /// WASM file to deploy. When neither --wasm nor --wasm-hash is provided
    /// inside a Cargo workspace, builds the project automatically. One of
    /// --wasm or --wasm-hash is required when outside a Cargo workspace.
    #[arg(long, group = "wasm_src")]
    pub wasm: Option<std::path::PathBuf>,
    /// Hash of the already installed/deployed WASM file
    #[arg(long = "wasm-hash", conflicts_with = "wasm", group = "wasm_src")]
    pub wasm_hash: Option<String>,
    /// Custom salt 32-byte salt for the token id
    #[arg(long)]
    pub salt: Option<String>,
    #[command(flatten)]
    pub config: config::Args,
    #[arg(long, short = 'i', default_value = "false")]
    /// Whether to ignore safety checks when deploying contracts
    pub ignore_checks: bool,
    /// The alias that will be used to save the contract's id.
    /// Whenever used, `--alias` will always overwrite the existing contract id
    /// configuration without asking for confirmation.
    #[arg(long)]
    pub alias: Option<AliasName>,
    #[command(flatten)]
    pub resources: resources::Args,
    #[command(flatten)]
    pub auth_mode: crate::auth_mode::Args,
    /// Build the transaction and only write the base64 xdr to stdout
    #[arg(long, help_heading = HEADING_TRANSACTION)]
    pub build_only: bool,
    /// If provided, will be passed to the contract's `__constructor` function with provided arguments for that function as `--arg-name value`
    #[arg(last = true, id = "CONTRACT_CONSTRUCTOR_ARGS")]
    pub slop: Vec<OsString>,
    /// Package to build when auto-building without --wasm
    #[arg(long, help_heading = "Build Options", conflicts_with = "wasm_src")]
    pub package: Option<String>,
    #[command(flatten)]
    pub build_args: build::BuildArgs,
}

#[derive(thiserror::Error, Debug)]
pub enum Error {
    #[error(transparent)]
    Install(#[from] upload::Error),

    #[error("error parsing int: {0}")]
    ParseIntError(#[from] ParseIntError),

    #[error("internal conversion error: {0}")]
    TryFromSliceError(#[from] TryFromSliceError),

    #[error("xdr processing error: {0}")]
    Xdr(#[from] XdrError),

    #[error("cannot parse salt: {salt}")]
    CannotParseSalt { salt: String },

    #[error("cannot parse contract ID {contract_id}: {error}")]
    CannotParseContractId {
        contract_id: String,
        error: stellar_strkey::DecodeError,
    },

    #[error("cannot parse WASM hash {wasm_hash}: {error}")]
    CannotParseWasmHash {
        wasm_hash: String,
        error: stellar_strkey::DecodeError,
    },

    #[error("Must provide either --wasm or --wasm-hash")]
    WasmNotProvided,

    #[error(transparent)]
    Rpc(#[from] rpc::Error),

    #[error(transparent)]
    Config(#[from] config::Error),

    #[error(transparent)]
    StrKey(#[from] stellar_strkey::DecodeError),

    #[error(transparent)]
    Infallible(#[from] std::convert::Infallible),

    #[error(transparent)]
    WasmId(#[from] contract::id::wasm::Error),

    #[error(transparent)]
    Data(#[from] data::Error),

    #[error(transparent)]
    Network(#[from] network::Error),

    #[error(transparent)]
    Wasm(#[from] wasm::Error),

    #[error(transparent)]
    Locator(#[from] locator::Error),

    #[error(transparent)]
    ContractSpec(#[from] contract_spec::Error),

    #[error(transparent)]
    ArgParse(#[from] arg_parsing::Error),

    #[error("Only ed25519 accounts are allowed")]
    OnlyEd25519AccountsAllowed,

    #[error(transparent)]
    Fee(#[from] fetch::fee::Error),

    #[error(transparent)]
    Fetch(#[from] fetch::Error),

    #[error(transparent)]
    Build(#[from] build::Error),

    #[error(transparent)]
    AuthMode(#[from] crate::auth_mode::Error),

    #[error("no buildable contracts found in workspace (no packages with crate-type cdylib)")]
    NoBuildableContracts,

    #[error("--alias is not supported when deploying multiple contracts; aliases are derived from package names automatically")]
    AliasNotSupported,

    #[error("workspace package '{0}' resolves to the reserved contract alias '{0}'; rename the package, or deploy it on its own with `--package {0} --alias <name>`")]
    ReservedPackageAlias(String),

    #[error("--salt is not supported when deploying multiple contracts")]
    SaltNotSupported,

    #[error("constructor arguments are not supported when deploying multiple contracts")]
    ConstructorArgsNotSupported,

    #[error("--build-only is not supported without --wasm or --wasm-hash")]
    BuildOnlyNotSupported,

    #[error(
        "--wasm or --wasm-hash is required when not in a Cargo workspace; no Cargo.toml found"
    )]
    NotInCargoProject,
}

impl Cmd {
    pub async fn run(&self, global_args: &global::Args) -> Result<(), Error> {
        self.auth_mode.validate_not_enforce()?;

        if self.build_only && self.wasm.is_none() && self.wasm_hash.is_none() {
            return Err(Error::BuildOnlyNotSupported);
        }

        let built_contracts = self.resolve_contracts(global_args)?;

        // Aliases derived from workspace package names are assigned per-iteration
        // inside the deploy loop, so validate them all up front: a package named
        // after a reserved alias must fail before any contract is deployed
        // on-chain, not partway through the loop.
        if let Some(name) = reserved_package_alias(self.alias.as_ref(), &built_contracts) {
            return Err(Error::ReservedPackageAlias(name));
        }

        // When --wasm-hash is used, no built contracts are returned.
        // Deploy directly with the hash.
        if built_contracts.is_empty() {
            Self::run_single(self, global_args).await?;
        } else {
            if built_contracts.len() > 1 {
                if self.alias.is_some() {
                    return Err(Error::AliasNotSupported);
                }

                if self.salt.is_some() {
                    return Err(Error::SaltNotSupported);
                }

                if !self.slop.is_empty() {
                    return Err(Error::ConstructorArgsNotSupported);
                }
            }

            for contract in &built_contracts {
                let mut cmd = self.clone();
                cmd.wasm = Some(contract.path.clone());

                // When auto-building and no explicit --alias, use the
                // package name as alias.
                if cmd.alias.is_none() && !contract.name.is_empty() {
                    if let Ok(alias) = contract.name.parse::<AliasName>() {
                        cmd.alias = Some(alias);
                    }
                }

                Self::run_single(&cmd, global_args).await?;
            }
        }
        Ok(())
    }

    async fn run_single(cmd: &Cmd, global_args: &global::Args) -> Result<(), Error> {
        // Validate the finalized alias (explicit or package-derived) at the
        // point of use, before any on-chain work. `run` rejects a reserved
        // package name up front to avoid a partial multi-contract deploy; this
        // is the single guard for the single-contract and `--wasm-hash` paths.
        if let Some(alias) = &cmd.alias {
            crate::config::alias::validate_reserved_aliases(alias)?;
        }

        let res = cmd
            .execute(&cmd.config, global_args.quiet, global_args.no_cache)
            .await?
            .to_envelope();

        match res {
            TxnEnvelopeResult::TxnEnvelope(tx) => {
                println!("{}", tx.to_xdr_base64(Limits::none())?);
            }
            TxnEnvelopeResult::Res(contract) => {
                let network = cmd.config.get_network()?;

                if let Some(alias) = cmd.alias.clone() {
                    if let Some(existing_contract) = cmd
                        .config
                        .locator
                        .get_contract_id(&alias, &network.network_passphrase)?
                    {
                        let print = Print::new(global_args.quiet);
                        print.warnln(format!(
                            "Overwriting existing alias '{alias}' that currently links to contract ID: {existing_contract}"
                        ));
                    }

                    cmd.config.locator.save_contract_id(
                        &network.network_passphrase,
                        &contract,
                        &alias,
                    )?;
                }

                println!("{contract}");
            }
        }
        Ok(())
    }

    fn resolve_contracts(
        &self,
        global_args: &global::Args,
    ) -> Result<Vec<build::BuiltContract>, Error> {
        // If --wasm is explicitly provided, use it (no package name available)
        if let Some(wasm) = &self.wasm {
            return Ok(vec![build::BuiltContract {
                name: String::new(),
                path: wasm.clone(),
            }]);
        }

        // If --wasm-hash is provided, no WASM file paths needed
        if self.wasm_hash.is_some() {
            return Ok(vec![]);
        }

        // Neither provided: auto-build
        let build_cmd = build::Cmd {
            package: self.package.clone(),
            build_args: self.build_args.clone(),
            ..build::Cmd::default()
        };
        let contracts = build_cmd.run(global_args).map_err(|e| match e {
            build::Error::Metadata(_) => Error::NotInCargoProject,
            other => other.into(),
        })?;

        if contracts.is_empty() {
            return Err(Error::NoBuildableContracts);
        }

        Ok(contracts)
    }

    #[allow(clippy::too_many_lines)]
    #[allow(unused_variables)]
    pub async fn execute(
        &self,
        config: &config::Args,
        quiet: bool,
        no_cache: bool,
    ) -> Result<TxnResult<stellar_strkey::Contract>, Error> {
        self.auth_mode.validate_not_enforce()?;

        let print = Print::new(quiet);
        let wasm_hash = if let Some(wasm) = &self.wasm {
            let is_build = self.build_only;
            let hash = if is_build {
                wasm::Args { wasm: wasm.clone() }.hash()?
            } else {
                print.infoln("Uploading contract WASM…");
                upload::Cmd {
                    wasm: Some(wasm.clone()),
                    config: config.clone(),
                    resources: self.resources.clone(),
                    auth_mode: self.auth_mode.clone(),
                    ignore_checks: self.ignore_checks,
                    build_only: is_build,
                    package: None,
                    build_args: build::BuildArgs::default(),
                }
                .execute(config, quiet, no_cache)
                .await?
                .into_result()
                .expect("the value (hash) is expected because it should always be available since build-only is a shared parameter")
            };
            hex::encode(hash)
        } else {
            self.wasm_hash
                .as_ref()
                .ok_or(Error::WasmNotProvided)?
                .clone()
        };

        let wasm_hash = Hash(
            utils::contract_id_from_str(&wasm_hash)
                .map_err(|e| Error::CannotParseWasmHash {
                    wasm_hash: wasm_hash.clone(),
                    error: e,
                })?
                .0,
        );

        print.infoln(format!("Deploying contract using wasm hash {wasm_hash}").as_str());

        let network = config.get_network()?;
        let salt: [u8; 32] = match &self.salt {
            Some(h) => soroban_spec_tools::utils::padded_hex_from_str(h, 32)
                .map_err(|_| Error::CannotParseSalt { salt: h.clone() })?
                .try_into()
                .map_err(|_| Error::CannotParseSalt { salt: h.clone() })?,
            None => rand::thread_rng().gen::<[u8; 32]>(),
        };

        let client = network.rpc_client()?;
        let MuxedAccount::Ed25519(bytes) = config.source_account()? else {
            return Err(Error::OnlyEd25519AccountsAllowed);
        };
        let source_account = AccountId(PublicKey::PublicKeyTypeEd25519(bytes));
        let contract_id_preimage = ContractIdPreimage::Address(ContractIdPreimageFromAddress {
            address: ScAddress::Account(source_account.clone()),
            salt: Uint256(salt),
        });
        let contract_id =
            get_contract_id(contract_id_preimage.clone(), &network.network_passphrase)?;
        let raw_wasm = if let Some(wasm) = self.wasm.as_ref() {
            wasm::Args { wasm: wasm.clone() }.read()?
        } else {
            if self.build_only {
                return Err(Error::WasmNotProvided);
            }
            get_remote_wasm_from_hash(&client, &wasm_hash).await?
        };
        let entries = soroban_spec_tools::contract::Spec::new(&raw_wasm)?.spec;
        let res = soroban_spec_tools::Spec::new(entries.clone().as_slice());
        let (constructor_params, constructor_signers) =
            if let Ok(func) = res.find_function(CONSTRUCTOR_FUNCTION_NAME) {
                if func.inputs.is_empty() {
                    (None, vec![])
                } else {
                    let mut slop = vec![OsString::from(CONSTRUCTOR_FUNCTION_NAME)];
                    slop.extend_from_slice(&self.slop);
                    let (_, _, invoke_args, signers) = arg_parsing::build_constructor_parameters(
                        &stellar_strkey::Contract(contract_id.0),
                        &slop,
                        &entries,
                        config,
                    )?;
                    (Some(invoke_args), signers)
                }
            } else {
                (None, vec![])
            };

        // For network operations, verify the network passphrase
        client
            .verify_network_passphrase(Some(&network.network_passphrase))
            .await?;

        // Get the account sequence number
        let account_details = client.get_account(&source_account.to_string()).await?;
        let sequence: i64 = account_details.seq_num.into();
        let txn = Box::new(build_create_contract_tx(
            wasm_hash,
            sequence + 1,
            config.get_inclusion_fee()?,
            source_account,
            contract_id_preimage,
            constructor_params.as_ref(),
        )?);

        if self.build_only {
            print.checkln("Transaction built!");
            return Ok(TxnResult::Txn(txn));
        }

        sim_sign_and_send_tx::<Error>(
            &client,
            &txn,
            config,
            &self.resources,
            &constructor_signers,
            self.auth_mode.to_rpc(),
            quiet,
            no_cache,
        )
        .await?;

        if let Some(url) = utils::lab_url_for_contract(&network, &contract_id) {
            print.linkln(url);
        }
        print.checkln("Deployed!");

        Ok(TxnResult::Res(contract_id))
    }
}

/// Returns the name of the first built contract whose package-derived alias
/// would be reserved. Explicit `--alias` is validated separately (and rejected
/// entirely for multi-contract deploys), so an explicit alias short-circuits.
fn reserved_package_alias(
    explicit_alias: Option<&AliasName>,
    built_contracts: &[build::BuiltContract],
) -> Option<String> {
    if explicit_alias.is_some() {
        return None;
    }

    built_contracts.iter().find_map(|contract| {
        (!contract.name.is_empty() && crate::config::alias::is_reserved(&contract.name))
            .then(|| contract.name.clone())
    })
}

fn build_create_contract_tx(
    wasm_hash: Hash,
    sequence: i64,
    fee: u32,
    key: AccountId,
    contract_id_preimage: ContractIdPreimage,
    constructor_params: Option<&InvokeContractArgs>,
) -> Result<Transaction, Error> {
    let op = if let Some(InvokeContractArgs { args, .. }) = constructor_params {
        Operation {
            source_account: None,
            body: OperationBody::InvokeHostFunction(InvokeHostFunctionOp {
                host_function: HostFunction::CreateContractV2(CreateContractArgsV2 {
                    contract_id_preimage,
                    executable: ContractExecutable::Wasm(wasm_hash),
                    constructor_args: args.clone(),
                }),
                auth: VecM::default(),
            }),
        }
    } else {
        Operation {
            source_account: None,
            body: OperationBody::InvokeHostFunction(InvokeHostFunctionOp {
                host_function: HostFunction::CreateContract(CreateContractArgs {
                    contract_id_preimage,
                    executable: ContractExecutable::Wasm(wasm_hash),
                }),
                auth: VecM::default(),
            }),
        }
    };
    let tx = Transaction {
        source_account: key.into(),
        fee,
        seq_num: SequenceNumber(sequence),
        cond: Preconditions::None,
        memo: Memo::None,
        operations: vec![op].try_into()?,
        ext: TransactionExt::V0,
    };

    Ok(tx)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_build_create_contract() {
        let hash = hex::decode("0000000000000000000000000000000000000000000000000000000000000000")
            .unwrap()
            .try_into()
            .unwrap();
        let salt = [0u8; 32];
        let key =
            &utils::parse_secret_key("SBFGFF27Y64ZUGFAIG5AMJGQODZZKV2YQKAVUUN4HNE24XZXD2OEUVUP")
                .unwrap();
        let source_account = AccountId(PublicKey::PublicKeyTypeEd25519(Uint256(
            key.verifying_key().to_bytes(),
        )));

        let contract_id_preimage = ContractIdPreimage::Address(ContractIdPreimageFromAddress {
            address: ScAddress::Account(source_account.clone()),
            salt: Uint256(salt),
        });

        let result = build_create_contract_tx(
            Hash(hash),
            300,
            1,
            source_account,
            contract_id_preimage,
            None,
        );

        assert!(result.is_ok());
    }

    fn built(name: &str) -> build::BuiltContract {
        build::BuiltContract {
            name: name.to_string(),
            path: std::path::PathBuf::new(),
        }
    }

    #[test]
    fn reserved_package_alias_flags_reserved_package_before_deploy() {
        let native = crate::config::alias::NATIVE;
        let contracts = [built("adapter"), built(native), built("token")];

        assert_eq!(
            reserved_package_alias(None, &contracts),
            Some(native.to_string())
        );
    }

    #[test]
    fn reserved_package_alias_ignores_regular_packages() {
        let contracts = [built("adapter"), built("token")];

        assert_eq!(reserved_package_alias(None, &contracts), None);
    }

    #[test]
    fn reserved_package_alias_skipped_with_explicit_alias() {
        // An explicit --alias is validated on its own path; a reserved package
        // name is irrelevant because the derived alias is never used.
        let alias = "my-contract".parse::<AliasName>().unwrap();
        let contracts = [built(crate::config::alias::NATIVE)];

        assert_eq!(reserved_package_alias(Some(&alias), &contracts), None);
    }
}