You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
@@ -5,7 +5,7 @@ title: Deploy a SC in 5 minutes - SpaceCraft interactors
5
5
6
6
[comment]: #(mx-abstract)
7
7
8
-
This short guide demonstrates how to deploy and interact with a smart contract on MultiversX using the SpaceCraft interactors. We will cover essential topics such as the SC framework, integration tests, sc-meta, and interactors (devtools).
8
+
This short guide demonstrates how to deploy and interact with a smart contract (SC) on MultiversX using the SpaceCraft interactors. We will cover essential topics such as the SC framework, integration tests, `sc-meta`, and interactors (devtools).
9
9
10
10
[comment]: #(mx-context-auto)
11
11
@@ -14,23 +14,24 @@ This short guide demonstrates how to deploy and interact with a smart contract o
14
14
Building smart contracts involves complex tasks. Beyond the syntax, a smart contract acts as a public server where users pay for actions. Enforcing rules to ensure safety (treating possible exploits) and efficiency (timewise - transaction speed, costwise - gas fees) for all users interacting with the contract is crucial.
15
15
16
16
In order to make sure that the smart contract works as expected, there are at least three stages of testing that we recommend to be performed before live deployment:
17
-
- unit testing ([SpaceCraft testing framework](https://docs.multiversx.com/developers/testing/rust/sc-test-overview#overview) - Rust unit tests, RustVM)
18
-
- scenarios ([mandos](https://docs.multiversx.com/developers/testing/scenario/concept#what-is-mandos) - json files, can be generated from Rust unit tests). Mandos can be used to test the logic on the [GoVM](https://docs.multiversx.com/technology/the-wasm-vm) as well, which is the actual VM running on the node
19
-
- integration testing ([SpaceCraft Rust interactors](https://docs.multiversx.com/developers/interactor/interactors-overview/#overview) - testing on the blockchain). Integration tests cover real life scenarios across the different MultiversX blockchain environments - devnet/testnet/mainnet
17
+
18
+
- unit testing ([SpaceCraft testing framework](/docs/developers/testing/rust/sc-test-overview.md#overview) - Rust unit tests, RustVM)
19
+
- scenarios ([mandos](/docs/developers/testing/scenario/concept.md#what-is-mandos) - json files, can be generated from Rust unit tests). Mandos can be used to test the logic on the [GoVM](/docs/learn/space-vm.md) as well, which is the actual VM running on the node
20
+
- integration testing ([SpaceCraft Rust interactors](/docs/developers/meta/interactor/interactors-overview.md#overview) - testing on the blockchain). Integration tests cover real life scenarios across the different MultiversX blockchain environments - devnet/testnet/mainnet
20
21
21
22
In this tutorial we will focus on integration testing using the interactors made available by the SpaceCraft smart contract framework.
22
23
23
24
::::important Prerequisites
24
25
25
-
-`stable` Rust version `1.78.0 or above` (install via [rustup](/docs/developers/toolchain-setup.md#installing-rust-and-sc-meta)):
26
-
-`multiversx-sc-meta`version `0.50.0 or above`(cargo install [multiversx-sc-meta](/docs/developers/meta/sc-meta-cli.md))
26
+
-`stable` Rust version `≥1.83.0` (install via [rustup](/docs/developers/toolchain-setup.md#installing-rust-and-sc-meta)):
Get a headstart by using sc-meta to generate one of our smart contract templates as a starting point for your smart contract. Let’s say we start from the `empty` template contract and name it `my-contract`.
34
+
Get a headstart by using `sc-meta` to generate one of our smart contract templates as a starting point for your smart contract. Let’s say we start from the `empty` template contract and name it `my-contract`.
34
35
35
36
```bash
36
37
sc-meta new --template empty --name my-contract
@@ -111,21 +112,22 @@ sc-meta all snippets
111
112
112
113
This command compiled the contract and generated a new folder called `interactor`. The interactor is by default a Rust CLI program that uses the smart contract proxy to send calls to the contract.
113
114
114
-
Inside the source folder *(interactor/src)*, we should find the newly generated proxy of the contract *(proxy.rs)* and the `interactor_main.rs` file, which is the main file of the project. A *sc-config.toml* file has also been created (if not existent) containing the path of the proxy file.
115
+
Inside the source folder *(my-contract/interactor/src)*, we should find the newly generated proxy of the contract *(my_contract_proxy.rs)* and the `interactor_main.rs` file, which is the main file of the project. A *sc-config.toml* file has also been created (if not existent) in the contract root containing the path of the proxy file.
115
116
116
-
If we navigate to *interactor/src/interactor_main.rs*, inside the `main` function, we can find all the CLI command available to us:
117
+
If we navigate to *interactor/src/interact.rs*, inside the `my_contract_cli()` function, we can find all the CLI command available to us:
117
118
118
-
```rust title=interactor_main.rs
119
-
#[tokio::main]
120
-
asyncfnmain() {
119
+
```rust title=interact.rs
120
+
pubasyncfnmy_contract_cli() {
121
121
env_logger::init();
122
122
123
123
letmutargs=std::env::args();
124
124
let_=args.next();
125
125
letcmd=args.next().expect("at least one argument required");
As you can see, `sc-meta` automatically generated all the logic behind calling the smart contract endpoints. The interactor uses asynchronous Rust, so all the functions are marked as `async` and need to be awaited to get a result.
138
140
139
-
In order to compile the project, we need to include it in the project tree. In this case, we have to add the interactor project to the smart contract’s workspaces, in the *Cargo.toml* file:
141
+
In order to compile the project, we need to include it in the project tree. In this case, we have to add the interactor project to the smart contract’s workspaces, in the *my-contract/Cargo.toml* file:
140
142
141
143
```toml title=Cargo.toml
142
144
[workspace]
@@ -151,7 +153,7 @@ members = [
151
153
152
154
## Step 5: Create scenarios & run
153
155
154
-
Now the setup is complete, it’s time to create some scenarios to test. For our use-case, the perfect scenario is: deploy the contract, register from a user and deregister from the same user. Anything else should result in an error.
156
+
Now the setup is complete, it’s time to create some scenarios to test. For our use-case, the perfect scenario is: **deploy the contract**, **register from a user** and **deregister from the same user**. Anything else should result in an error.
155
157
156
158
In order to test the perfect scenario first, we will first deploy the contract:
157
159
@@ -160,24 +162,30 @@ cd interactor
160
162
cargo run deploy
161
163
```
162
164
163
-
After deploying the contract, a new file named *state.toml* will be created, which contains the newly deployed sc address. For each deploy, a new address will be printed into the file.
165
+
After deploying the contract, a new file named *state.toml* will be created in the `interactor` directory, which contains the newly deployed SC address. For each deploy, a new address will be printed into the file.
These commands will send two transactions to the newly deployed contract from the `test_wallets::alice()` wallet, each of them calling one endpoint of the contract in the specified order.
199
207
200
-
```bash
201
-
you@PC interactor % cargo run register_me
208
+
```bash title=register_me
209
+
interactor % cargo run register_me
202
210
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.35s
Using the functions generated by `sc-meta`, we can extend the interactor to cover a series of integration tests. Organized tests help with maintenance and long-term testing.
222
233
223
234
We can create a quick integration test as such:
224
-
```rust title=interactor_main.rs
235
+
236
+
Inside the `tests` directory of the `interactor`, you can add integration tests that run either on the **chain simulator** or on the **gateway** configured in `config.toml`.
237
+
238
+
For this example, we can create an integration test that runs on `devnet`, starting with the template provided in the file `my-contract/interactor/interact_tests.rs`:
239
+
240
+
```rust title=interact_tests.rs
225
241
#[tokio::test]
226
242
async fn integration_test() {
227
-
let mut interact = ContractInteract::new().await;
243
+
let mut interactor = ContractInteract::new(Config::new()).await;
228
244
229
-
interact.deploy().await;
230
-
interact.register_me().await;
231
-
interact.deregister_me().await;
245
+
interactor.deploy().await;
246
+
interactor.register_me().await;
247
+
interactor.deregister_me().await;
232
248
}
233
249
```
234
250
235
-
Running this test will perform the previous CLI actions in the same order, on the real blockchain. The console will show all the intermediate actions at the end of the test, as such:
251
+
Alternatively, we can create an integration test that runs only on the [chain simulator](/docs/developers/tutorials/chain-simulator-adder.md):
let mut interactor = ContractInteract::new(Config::chain_simulator_config()).await;
258
+
259
+
interactor.deploy().await;
260
+
interactor.register_me().await;
261
+
interactor.deregister_me().await;
262
+
}
263
+
```
264
+
265
+
Running `integration_test()` will perform the previous CLI actions in the same order, on the real blockchain. The console will show all the intermediate actions at the end of the test, as such:
236
266
237
267
```bash
238
268
running 1 test
@@ -264,101 +294,6 @@ test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; fini
264
294
265
295
[comment]: # (mx-context-auto)
266
296
267
-
## Improvements
268
-
269
-
This setup can be used for extensive testing, but also as a tool for live deployment on mainnet, tracking and interaction. In a multi-contract setup, one can, for example, create different modules for specific interactions with each contract and development environment and further structure all the interactions into different integration tests.
270
-
271
-
Let’s take the example of the [DEX smart contract interactors](https://github.com/multiversx/mx-exchange-sc/tree/feat/unified/dex/interactor). Here, all the proxy files are organized in a different crate for easier access.
272
-
273
-

274
-
275
-
Furthermore, all the contracts that are part of the DEX flow have separate interaction modules, so we can easily keep track of the flow when writing complex tests.
276
-
277
-
This is the `energy_factory` file, containing only interactions with the `energy factory smart contract`, using the specific proxy and contract address:
let (_, _, lp_token) = pair::add_liquidity(self, args).await.0;
313
-
// enters farm in the farm locked SC
314
-
let _result = farm_locked::enter_farm(self, lp_token).await;
315
-
// query the energy factory SC
316
-
let _query = energy_factory::get_energy_amount_for_user(self, Address::zero()).await;
317
-
// stake farm tokens in the farm staking proxy SC
318
-
let _farm_token = farm_staking_proxy::stake_farm_tokens(self, Vec::new(), None).await;
319
-
// more logic
320
-
}
321
-
}
322
-
323
-
#[cfg(test)]
324
-
pub mod integration_tests {
325
-
use multiversx_sc_snippets::tokio;
326
-
327
-
use crate::{dex_interact_cli::SwapArgs, pair, DexInteract};
328
-
329
-
#[tokio::test]
330
-
async fn test_swap() {
331
-
// initialize interactor
332
-
let mut dex_interact = DexInteract::init().await;
333
-
// test users
334
-
dex_interact.register_wallets();
335
-
// mock arguments
336
-
let args = SwapArgs::default();
337
-
338
-
// swap tokens with the pair SC
339
-
let result = pair::swap_tokens_fixed_input(&mut dex_interact, &args).await;
340
-
println!("result {:#?}", result);
341
-
}
342
-
343
-
#[tokio::test]
344
-
async fn test_full_farm_scenario() {
345
-
// initialize interactor
346
-
let mut dex_interact = DexInteract::init().await;
347
-
// test users
348
-
dex_interact.register_wallets();
349
-
// mock arguments
350
-
let args = AddArgs::default();
351
-
352
-
// runs a full farm scenario
353
-
dex_interact.full_farm_scenario(args).await;
354
-
}
355
-
}
356
-
```
357
-
358
-
Organizing the code this way streamlines the process even further. Now, it is just a matter of using a different datatype or a different module in order to keep track of the various contracts and development environments and be able to rerun everything quickly if needed.
359
-
360
-
[comment]: # (mx-context-auto)
361
-
362
297
## Conclusion
363
298
364
299
The interactors are a versatile tool that greatly simplifies various processes around a smart contract, including deployment, upgrades, interaction, and testing. These tools not only save time but also offer a robust starting codebase for Rust developers. They also provide a valuable learning opportunity for non-Rust developers to explore asynchronous Rust and other advanced features.
0 commit comments