Logo

dev-resources.site

for different kinds of informations.

A Guide to Quickly Deploying and Interacting with Smart Contracts Using the Stellar CLI

Published at
8/17/2024
Categories
devchallenge
stellarchallenge
blockchain
web3
Author
chielokacodes
Author
13 person written this
chielokacodes
open
A Guide to Quickly Deploying and Interacting with Smart Contracts Using the Stellar CLI

This is a submission for the Build Better on Stellar: Smart Contract Challenge : Create a Tutorial

Table Of Contents

Overview

My Submission will explain in depth on how to properly use the Stellar CLI Commands to build, deploy and Interact with the smart contracts.
The Stellar CLI is the command line interface to Soroban smart contracts. It allows you to build, deploy, and interact with smart contracts; configure identities; generate key pairs; manage networks; and more.

For this Tutorial, i will take you by the hand as a complete beginner to coding to deploying and interacting with the smart contract via command line

Tools to have before coding

  1. Install Node latest version or v18
  2. Install Visual Studio Code
  3. Have a good Internet Connection
  4. Install Rust


curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -(Mac Os)

download and run rustup-init.exe -(Windows)


Enter fullscreen mode Exit fullscreen mode
  • Install target


rustup target add wasm32-unknown-unknown



Enter fullscreen mode Exit fullscreen mode
  • Install Cargo


brew install cargo-c


Enter fullscreen mode Exit fullscreen mode
  • Install Stella CLI


cargo install --locked stellar-cli --features opt


Enter fullscreen mode Exit fullscreen mode

Goal for this Tutorial

Implementing a transfer_xlm function - to transfer native XLM token from a public address to another contract address or public address

Picture Representation of the transaction in Stellar Expert

Image description

Glossary

  1. XLM - is the native cryptocurrency of the Stellar network. This is the token used to paying small transaction fees, creating new accounts. XLM can also be bought, sold, or traded like other cryptocurrencies.

  2. Public Address/Key: This is like your email address in the Stellar world. It's a unique string of letters and numbers that identifies your account on the Stellar network. You can share this freely with others when you want to receive funds or interact with the network. It always starts with a 'G' and looks something like "GBYUHQVNEEOXYXJTONRDFRMBZYXGB3SXOITQ2WMDZ44DEAKYSBYL4JZF"

  3. Secret Address/Key: This is like the password to your Stellar account. It's a private string that should never be shared with anyone. With this key, you can access and control your account, send funds, and sign transactions. It always starts with an 'S' and looks similar to the public key: "SBCVMMCBEDB64ZDTSFLBDBO6UIFRS4JQWHXQYP6ABLSOZXMZNXJB7OVU"

  4. KeyPair: A keypair is simply the combination of your public key and secret key. It's like having both your email address and password together. When you create a Stellar account, you're essentially generating a keypair. The public part of this pair becomes your account address, while the secret part is used to control the account.

  5. Stellar Smart contract: A Stellar smart contract is like a set of rules or instructions that automatically do things on the Stellar network. In our case, we are going to be creating the "transfer_xlm" function within our smart contract

  6. Soroban: Stellar's smart contract system is called "Soroban".

Now back to the good Stuff, the below picture shows the goal of this tutorial, but with the above knowledge this should get you excited for what is to come

Programming Language used

  • Rust

We are using Rust for the below reasons, Stellar chose Rust because:

  • It's very secure, which is important when dealing with financial transactions
  • It's fast, so contracts can run efficiently
  • It helps prevent common coding mistakes

STEPS to follow

  • Open VS Code, and create a new Folder, Make sure the name of the folder is separated by "_" or "-". Never use space in a folder name

  • Open Terminal, the terminal will open your root directory that is all commands you write here will be applied to this folder.

  • We are going to run the command below on the terminal to create a react-next app project



npx create-soroban-dapp@latest


Enter fullscreen mode Exit fullscreen mode

This will create our project and install the neccessary dependencies

You will be asked some questions below

  • What will be the name of your project? your-project-name
  • Please select your favourite package manager: choose npm
  • Do you want us to install dependencies for you? Y
  • Should we continue and set up the dapp? Y


cd your-project-name
npm run dev


Enter fullscreen mode Exit fullscreen mode

Now the installations is complete, "npm run dev" will start a local server for your dApp. Copy the link (localhost:3000) and paste on your Browser preferably Chrome

Image description

We will be focusing on the "contracts" folder in your project.

  • Navigate to contracts, then greetings folder, then src, then lib.rs (this is where we are to implement our functions). So the greetings folder is the smart contract. We can choose to rename the greetings folder, but i will leave it as it is.
    Remove the default functions and replace with the transfer_xlm() function below

  • We will implement the "transfer_xlm()" function

Image description

I will explain the concepts here:

  • This imports the necessary dependencies, the "#![no_std]" removes the big library tools from the project making the project light and small

The "use soroban_sdk" is using specific tools from the Soroban toolkit." Each item in the curly braces is a tool we might need for our smart contract.



#![no_std]
use soroban_sdk::{contract, contractimpl, contracttype, Address, Env, String, Symbol, Vec};
use soroban_sdk::token::TokenClient;


Enter fullscreen mode Exit fullscreen mode
  • DataKey are like special containers for information that you want to use in your smart contract. For example, we are going to store the result of our xlm token into the Datakey "Token".


#[derive(Clone)]
#[contracttype]
pub enum DataKey {
    Token
}


Enter fullscreen mode Exit fullscreen mode
  • In the transfer_xlm function, "env", "from", "to", and "amount" are parameters. The "env" typically represents the environment in which Soroban smart contracts execute.

  • from.require_auth() - it's used to ensure that certain operations within a smart contract are only performed by authorized parties. it does this by requesting for the secret key to authenticate the transaction.

  • This holds and store the xlm contract address, the contract address here is the XLM testnet address. Then, we save this into the DataKey Token.




assert!(amount > 0, "amount must be positive");
let xlm_address_str = String::from_str(&env,
       "CDLZFC3SYJYDZT7K67VZ75HPJVIEUVNIXF47ZG2FB2RMQQVU2HHGCYSC",
        );
let xlm_address = Address::from_string(&xlm_address_str);
env.storage().persistent().set(&DataKey::Token, &xlm_address);



Enter fullscreen mode Exit fullscreen mode
  • TokenClient then creates the token and using the .transfer() function it transfers the token from the "from" address to the "to" address, the "amount" of tokens. Now XLM smallest unit is stroops which is 10^7 so to get 1XLM token, 1 XLM (Lumen) = 10,000,000 stroops.


let token = TokenClient::new(&env, &xlm_address);
token.transfer(&from, &to, &amount);
true


Enter fullscreen mode Exit fullscreen mode
  • Finally, we send true representing a successful transfer.

  • Navigate to greeting folder, Run the command in the terminal, to build the contract



cd my-project-name
cd contracts
cd greeting
stellar contract build


Enter fullscreen mode Exit fullscreen mode
  • Go back to root directory using "cd ./" multiple times


npm i @stellar/stellar-sdk


Enter fullscreen mode Exit fullscreen mode
  • Configure the CLI for Testnet, for Windows remove the "\" and replace with "`"


stellar network add \
--global testnet \
--rpc-url https://soroban-testnet.stellar.org:443 \
--network-passphrase "Test SDF Network ; September 2015"

  • Configure an Identity, thats the "token-admin" will be used as sourceAccount


stellar keys generate --global token-admin --network testnet
stellar keys address token-admin - (To see the Public key of token-
admin)

  • By default "stellar keys generate" will fund our token-admin with 10,000XLM by the Friendbot

  • Navigate back into "greeting" folder using "cd", Run the command to install


stellar contract install \
--network testnet \
--source token-admin \
--wasm target/wasm32-unknown-unknown/release/greeting.wasm

A WASM HASH (WebAssembly) will be generated here, input it into the next step in the "(--wasm-hash)

  • Now we are going to deploy the smart contract using this command.


stellar contract deploy \
--wasm-hash
f02ce4b958e5e5d426e40787486d6c46fdc4826c874b93e307dac74f1191f1db \
--source token-admin \
--network testnet

  • At this point our smart contract is deployed, you should now see the contract address. For example "CA4KNSGXAI47V7AQLIOAXZ7FX4V4HLS6QNYFGRNFZM2UEOJTYFNM6OKC"

  • Go on to Stella Expert, at the top-right side of the screen, select Network: testnet and paste your contract address to view the deployed address

Image description

  • Now, you can see the transfer function in the contract by clicking "interface"

Image description

  • To interact with the deployed smart contract, run this command.


stellar contract invoke \
--network testnet --source token-admin \
--id CA4KNSGXAI47V7AQLIOAXZ7FX4V4HLS6QNYFGRNFZM2UEOJTYFNM6OKC \
-- \
transfer_xlm \
--from token-admin \
--to "CA4KNSGXAI47V7AQLIOAXZ7FX4V4HLS6QNYFGRNFZM2UEOJTYFNM6OKC" \
--amount "10000000000"

Here, we run the "transfer_xlm", we are transfering 1000XLM from the token-admin address to our deployed contract address. Its worthy to note that you can transfer from another public address not a must it should be from "token-admin".

View this post to understand in depth the various attribute used in the transfer_xlm() function: View Post here

  • At this point, you should get "true" showing a successful transfer of 1000XLM to your contract address. You can view the recent transaction at stellar expert.

Image description

I hope you learnt a lot.

GitHub link: Github Repo

Video Explanation

smart_contract_explained

What I Created

My Submission is a walk through showing a complete beginner how to start from an empty folder to deploying a smart contract and interacting with it. This supports developers in showing them how to deploy their smart contracts quickly in one page instead of looking through different pages online to get this information. They can quickly hit the ground running with this tutorial.

Journey

I am particularly proud of participating in this challenge as it has helped me into understanding the basics of blockchain, cryptocurrency and decentralised applications. It is a wonderful experience but really tough when you have no experience, thats the major reason i created this tutorial to show beginner developers the easier way.

Most of my research came from Stellar documentation, Google and Stellar Discord channel.

stellarchallenge Article's
30 articles in total
Favicon
Stellar (XLM) Price Predictions,2025 to 2030
Favicon
πŸš€ FASTBUKA: Transforming Food Delivery in Nigeria!
Favicon
Yes, I'm in
Favicon
Stellar Wallet
Favicon
ASAWAVE TUTORIAL ON STELLAR
Favicon
Step-by-Step Guide to Perform a Token Swap on Soroswap.Finance
Favicon
Dev challenge
Favicon
Deuces9ersgold
Favicon
Startup on the Stellar network
Favicon
Stellar Wallet For Indian Audience With Soroban Integration For Coupon Distribution
Favicon
kosmos
Favicon
Congrats to the Build Better on Stellar: Smart Contract Challenge Winners!
Favicon
Blue
Favicon
HelpChain: Securely Empowering Change with Stellar Blockchain, Transparent Donations, and Carbon Offset NFTs
Favicon
Navigating the crowd funding smart contract workflow in an open financial network - stellar
Favicon
Decentralized Wallet dApp for Stellar Blockchain
Favicon
Pay Picker: Fun way to decide who's paying | #BuildBetterOnStellar
Favicon
Silicore -- Dev.to's Smart Contract Challenge
Favicon
Non-Custodial Smart Wallet dApp
Favicon
Step-by-Step Guide to Creating a Donations dApp with Stellar SDK
Favicon
Soroban by Example
Favicon
Entryβ€’X | Decentralized Ticketing Platform
Favicon
A Guide to Quickly Deploying and Interacting with Smart Contracts Using the Stellar CLI
Favicon
stellar-TUI a terminal user interface for Horizon Stellar
Favicon
The Ultimate Stellar Supreme Tutorial
Favicon
Next.js + tRPC: Best practices for dApp development. Issuing new Assets + Freighter Wallet integration
Favicon
Hermes: Decentralized Perpetual Exchange on Stellar
Favicon
Stellar Wallet App: A Step-by-Step Guide from Zero to Hero
Favicon
Stellar Wallet App: A Step-by-Step Guide : Smart Contract Challenge
Favicon
Integrating Stellar Payments into a Django Web Application

Featured ones: