Smart Contracts on the MultiversX (Elrond) blockchain
Tags: blockchain, rust, tutorial
Published: 2021-08-07 16:49:00

_Are you interested in NFTs on the MultiversX (Elrond) blockchain? Check out open source tools that will help you with running and selling your collection: [Elven Tools - MultiversX NFT](https://www.elven.tools)_

Lately, I started to explore through docs of many different blockchain protocols out there to find the quickest and simplest entry point to learn how to write Smart Contracts using Rust language. There are fantastic tools from the [Polkadot](https://polkadot.network/) ecosystem. [Solana](https://solana.com/) and [Terra](https://www.terra.money/) also look great, and I will for sure take a closer look at these later. But I found that [MultiversX (Elrond)](https://multiversx.com/) blockchain has many simple examples of straightforward code. The tooling is also quite impressive, so I decided to spend some time with it first. 

### I want to do a quick introduction here. The main points:

1. How to write a Smart Contract on the MultiversX (Elrond) blockchain
2. How to interact with such Smart Contract

Let's look at how we can start to write Smart Contracts on the MultiversX (Elrond) blockchain. There are [pretty good docs](https://docs.multiversx.com/developers/tutorials/crowdfunding-p1/) on how to start. They use an example of a Crowdfunding Smart Contract. But let's leave it for a moment. You can always read it later. For now, let's jump into the code. I prepared a custom Smart Contract that has all dependencies up to date and is so simple that you will learn a lot by just reading the code. It is a simple PiggyBank Smart Contract. The functionality is basic for now. You can create a Piggy, add tokens, lock them, and claim them when the lock time will expire. You can clone it from Github here: [PiggyBank Smart Contract](https://github.com/xdevguild/multiversx-simple-sc).

### As you will see, there are three main concepts. 

The first one is on-chain [storage](https://docs.multiversx.com/developers/developer-reference/wasm-annotations#storage). It is a kind of simple key-value storage with which you can interact using annotations that manage and serialize the keys and values behind the scenes. An example could be the storage for the lock time in our PiggyBank Smart Contract:

```rust
#[view(getLockTime)]
#[storage_mapper("lockTime")]
fn lock_time(&self, piggy_owner: &Address) -> SingleValueMapper<u64>;
```

It is as simple as that. You don't have to manage all serialization and all other stuff. The second important concept is [`#[endpoint]`](https://docs.multiversx.com/developers/developer-reference/wasm-annotations#endpoint-and-view) annotation which will expose the function, and users will be able to call it in transactions. For example the `pay_out` function looks like:

```rust
#[endpoint(payOut)]
  fn pay_out(&self) {
    let caller = &self.blockchain().get_caller();
    let caller_address = caller.to_address();
    require!(
      self.lock_time(&caller_address).get() < self.get_current_time(),
      "You can't withdraw your money yet"
    );
    require!(self.locked_amount(&caller_address).get() > 0, "There is nothing to withdraw");
    self.send()
      .direct_egld(caller, &self.locked_amount(&caller_address).get(), &[]);

    self.locked_amount(&caller_address).clear();
    self.lock_time(&caller_address).clear();
  }
```

We will see how to call such a function very soon. So keep reading.

The last and essential concept is the [`#[init]`](https://docs.multiversx.com/developers/developer-reference/wasm-annotations#init) annotation, which will set the function as initialization process. The function will trigger only when the owner will deploy the contract. IT is necessary, for example, when we need to set up some ownership logic, etc.

So you see how the contract's code looks like, you'll also find the links to the docs if needed. 

### Ok, so how to interact with such a Smart Contract. 

In the case of the MultiversX (Elrond) Blockchain, there is a couple of options. You can use [JavaScript SDK](https://github.com/multiversx/mx-sdk-js-core), but you can also use a Python-based CLI tool called [erdpy](https://docs.multiversx.com/sdk-and-tools/erdpy/). It is what we will use here for now. Later I plan to write a frontend app for it, so I'll use JavaScript SDK.

You would, of course, need to install the erdpy tools. Docs are here: [Installing erdpy](https://docs.multiversx.com/sdk-and-tools/erdpy/installing-erdpy). Installation is straightforward, so hopefully, you won't have any problems with that. You can also check my [walkthrough video](https://youtu.be/mIsNI7ZxQRM) (uses the testnet and older names for functions, new ones are camel cased).

Let's start with the deployment. We need to place the Smart Contract somewhere on the blockchain. We will need a wallet for that. All is going to happen on the devnet, so that you would need the devnet wallet. Go and get one here: [devnet-wallet.multiversx.com](https://devnet-wallet.multiversx.com/).

Then you would need to derive the pem key file. Check how to do this in the [docs](https://docs.multiversx.com/sdk-and-tools/erdpy/deriving-the-wallet-pem-file) or my walkthrough video linked above.

Remember to build the contract using `erdpy contract build`. You would need to do this in the cloned PiggyBank directory.

**Important!**
Last but not least, you need to fund your account. Because this is a devnet wallet, you can use [faucet](https://r3d4.fr/faucet) to claim some tokens. Without any tokens, you won't be able to finish any transaction. You can also use the official faucet built into the devnet's web wallet.

After that, let's see the first command:

```bash
erdpy --verbose contract deploy --chain="D" --project=multiversx-simple-sc --pem="wallets/test.pem" --gas-limit=80000000 --proxy="https://devnet-gateway.multiversx.com" --recall-nonce --send
```

Chain D means that we will deploy to the devnet. It will deploy the contract using your wallet, wallet key from the pem file. You need to pass an exact path to this file. You also need to pass the path to the project. After that, you'll get the PiggyBank smart contract address. It is required for later interaction.

Ok, so now we can use the same or another wallet key and interact with the contract. For example, let's see how to create a Piggy.

```bash
erdpy --verbose contract call <smart_contract_address_here> --chain="D" --pem="wallets/test.pem" --gas-limit=5000000 --function="createPiggy" --arguments 1628619457 --proxy="https://devnet-gateway.multiversx.com" --recall-nonce --send
```

It is similar, but now we need to pass the smart contract address, and we are calling the `createPiggy` function, which you'll find [here](https://github.com/xdevguild/multiversx-simple-sc/blob/master/src/lib.rs) in the code. We need to pass the Unix time number for the lock deadline date.

### Summary

I've done a quick intro of how an example Smart Contract on MultiversX (Elrond) Blockchain looks like and how you can interact with deployed smart contracts. I won't paste all possible calls here and all configuration details. You'll find them in my detailed article: [Smart Contract for MultiversX (Elrond)](https://www.julian.io/articles/elrond-smart-contracts.html). And of course, I encourage you to watch the [walkthrough video](https://youtu.be/mIsNI7ZxQRM), which details what I was doing step by step. You can always clone the [PiggyBank](https://github.com/xdevguild/elrond-simple-sc). You'll find all interaction calls using erdpy in the repository readme file.

Let me know what you would like to know about it. I don't understand all yet, I'm still learning, but I am sure that I will help with your first steps. Please follow me on [Twitter](https://twitter.com/theJulianIo) and [GitHub](https://github.com/juliancwirko). I plan to write some other articles that will introduce more functions for our PiggyBank and frontend app.

More links:
- [Buildo.dev is a MultiversX app that helps with blockchain interactions](https://www.buildo.dev)
- [Elven Tools - Open Source toolset for launching NFTs collections on the MultiversX (Elrond) blockchain](https://www.elven.tools/)
- [Simple Smart Contract for learning purposes](https://github.com/xdevguild/multiversx-simple-sc)
- [MultiversX (Elrond) NFT minter Smart Contract](https://github.com/ElvenTools/elven-nft-minter-sc)
- [MultiversX (Elrond) Minter Dapp demo](https://dapp-demo.elven.tools/)
- [xdevguild - add links, add articles, join with repository!](https://github.com/xdevguild)