ethereum – Sesame Disk https://sesamedisk.com Tue, 26 Apr 2022 07:55:09 +0000 en-US hourly 1 https://wordpress.org/?v=6.4.3 https://sesamedisk.com/wp-content/uploads/2020/05/cropped-favicon-transparent-32x32.png ethereum – Sesame Disk https://sesamedisk.com 32 32 Smart Contracts in Python: Complete Guide https://sesamedisk.com/smart-contracts-in-python-complete-guide/ https://sesamedisk.com/smart-contracts-in-python-complete-guide/#comments Mon, 25 Apr 2022 23:16:04 +0000 https://sesamedisk.com/?p=4842 smart conrtacts in python

Smart contracts in Python? Don’t worry if that line doesn’t make sense. So, this post will explore the steps of deploying smart contracts in Python and help you understand how to do it independently and concisely. Like my previous one, where I discussed how to Write Your First Smart Contract || Blockchain, I will break everything down before diving into deploying smart contracts in Python. For now, know that a “smart contract” doesn’t mean a contract that can adapt or change itself, like AI, haha. As long as you know that, you’re good to go.

Check that article out if you still haven’t provided some essential context for this article. Moreover, the goal of this article is to be a complete guide for smart contracts in Python– your one-stop place.

The GitHub repo containing the complete code used and the Python file to deploy Solidity smart contracts is essential to share here. Head over to access/edit it to your liking.

Another thing that I want to recommend is to make a habit of reading the docs. For instance, the Web3.py documentation helps understand how to interact with deploying smart contracts in Python.

Here are a few limitations to that approach and the reasons to deploy the smart contracts in Python:

Limitations of Solidity on Remix IDE:

  • Can’t integrate with large projects
  • Limited support for testing or custom deployment
  • Cannot save plugins

Okay then, what do you need before starting? Here are a few necessary prerequisites.

Prerequisites to Deploying Smart Contracts in Python

Why Python?

Python is perhaps the most versatile and most used programming language in 2022. Its popularity is expected to grow further, heading into 2022 and beyond. Hence, it should not be surprising that Python is also one of the languages for blockchain development. My reason for choosing Python for Web 3.0 purposes instead of Javascript is quite simple. I have been coding in Python for a couple of years now, and I finally feel like I have found a language that allows me to express myself without clawing my hair out at every obstacle.

In other words, I enjoy coding in Python. You can use the respective Web3 libraries on both Python and Javascript to interact with and deploy your smart contracts– as per your preference.

What is the Web3.py library?

Web3.py is a Python library that provides the tools necessary to interact with and manipulate smart contracts in Python. In other words, Web3.py allows interaction with Ethereum VM (virtual machine) using Python. This leads to its use in dApps, or decentralized applications, for interacting with smart contracts, sending transactions, reading block data, and other cool use-cases.

Web3

Run the following command in the terminal to install Web3.py on your system:

$ pip install web3

Solcx

Run the following command in the terminal to install Solcx on your system:

$ pip install py-solc-x

Eth_utils

Run the following command in the terminal to install Eth_utils on your system:

$ pip install eth-utils==1.1.2

Dotenv

Run the following command in the terminal to install dotenv on your system:

$ pip install python-dotenv

How to get Solidity Smart Contracts to Deploy in Python?

If you have been following our blog, you know I wrote a post on Writing a Smart Contract in Solidity not too long ago. But if you have no prior experience, you can first follow that post and write your first smart contract in Solidity. However, it doesn’t mean you won’t learn anything from this post; you’ll only have a more challenging time unless you get back to this later.

On the other hand, if you have a little experience but still need help, that post will be helpful. But if you want to follow along with this post, you can find a lot of open-source smart contract files on Github.

I have also uploaded the smart contract file that I’ll use in this tutorial. Okay, now a few more things before diving into the steps to deploy a smart contract in Python.

What is Ganache?

Ganache is a platform to perform blockchain operations locally on our machine before deploying a not-perfect file or how we want it to be. In other words, it’s a test blockchain where you can track transactions, inspect changes, and, most importantly– do it locally by creating your own Ethereum blockchain.

Depending on whether you like a UI or CLI, you can use Ganache CLI or Ganache.

Deploying Smart Contracts in Python: Complete and Comprehensive guide

With all the essential information done, let’s start the real stuff. I’ve divided it into some steps to make it easy for you to follow along.

Step 1: Import Necessary Libraries in Python

Here are some useful libraries for this project:

from eth_utils import address
from web3 import Web3
import os
from solc import compile_standard, install_solc
from dotenv import load_dotenv
import json

Step 2: Read the Smart Contract file in Python

Let’s get groovy, then, shall we?

In the beginning, you must read the smart contracts that you have written or downloaded for the project in Python. The smart contract I am using is “SimpleStorage.sol“.

I am sure you already know about the “with open() as file” syntax from the os library to read/write/append files in Python, but let me clarify.

“r” means “read-only.” The reason for using read-only is simple: you only need to access the contents of the solidity smart contract file and not write or append it.

Use “as file” to assign the file after reading its content to a new variable “simple_storage_file” to read a little later on.

with open("./SimpleStorage.sol", "r") as file:
    simple_storage_file = file.read()

Step 3: Compiling Solidity Smart Contracts in Python

A library called py-solc-x needed to compile the smart contract before it was ready to be used with Python. The benefit of using py-solc-x over py-solc is that the former is maintained.

The purpose of installing and importing py-solc-x is to use the compile standard function. This function does the behind-the-scenes work of compiling as done by the solidity compiler on the remix. This breaks everything down into assembly language, which is much closer to machine language for execution, and this is what governs how the code works.

Let’s understand the four parameters that the compile standard function uses to compile smart contracts in Python.

  • language: obviously- Solidity as its the language used for the smart contract
  • sources: refers to the smart contract file, and content which takes the variable used to store the contents of the smart contract file in Pyrhon on reading it above.
  • outputSelection: Without going into too much detail here, I’ll let you know this is important to get the output informatino required, namely– ABI, Metadata, Bytecode and its sourcemap.
  • solc_version: I have used 0.6.0 here because I used 0.6.0 in the smart contract. You may use a later version but this is the most stable version yet.

After compilation, open the file and dump it into a JSON-formatted file. This is the reason I imported JSON above.

compiled_sol = compile_standard(
    {
        "language": "Solidity",
        "sources": {"SimpleStorage.sol": {"content": simple_storage_file}},
        "settings": {
            "outputSelection": {
                "*": {
                    "*": ["abi", "metadata", "evm.bytecode", "evm.bytecode.sourceMap"]
                }
            }
        },
    },
    solc_version="0.6.0",
)

with open("compiled_code.json", "w") as file:
    json.dump(compiled_sol, file)

Step 4: Extracting the ABI and Bytecode from Solidity Smart Contracts in Python

It’s essential to know about ABIs and Bytecode in Solidity to understand how to interact with compiled smart contracts in Python.

Bytecode

Bytecode refers to the roasted meat of smart contracts. It contains the necessary information for code execution. It includes the key commands in assembly language that are executed at low-level or machine-level instead of the whole smart contract. In simple words, this is the code that is executed and which governs the working of the smart contract file.

Notice that the following code is in JSON format.

It’s also interesting if you browse to object, in the JSON directory of compiled contract file, to see that this is really low-level stuff.

# get bytecode
bytecode = compiled_sol["contracts"]["SimpleStorage.sol"]["SimpleStorage"]["evm"][
    "bytecode"
]["object"]

ABI: Application Binary Interface

Application Binary Interfaces are vital pieces of information for a smart contract.

What does it do, though? Why should you care?

ABI is quite similar to API (Application Programming Interface), a term I am sure you are familiar with and you probably thought of based on the similar initialism. ABI is responsible for the interaction between methods and structures in the smart contract.

If you print out the compiled JSON file, you will notice that the ABI includes the smart contract files’ inputs, names, and outputs– or the bare bones of it. Basically, it includes the stripped-down smart contract file with important information about a function’s inputs, name, outputs,r data types, etc.

# get abi
abi = json.loads(
    compiled_sol["contracts"]["SimpleStorage.sol"]["SimpleStorage"]["metadata"]
)["output"]["abi"]

Step 4: Connect using Ganache- Local Ethereum Blockchain to deploy Smart Contracts in Python

This is the part it starts to get real fun– or depressing, depending on who you ask. The truth lies somewhere in the middle, as with most things.

ganache local ethereum blockchain for Python

Okay, Web3 is used to connect with this local Ethereum blockchain on Ganache using the HTTP/RPC provider. But that’s not all! You also need the chain id, address of the blockchain, and its private key to sign the transactions. You can get all of this information from the following part of the screen on your Ganache app.

connecting to blockchain Smart Contracts in Python
# set up connection
w3 = Web3(Web3.HTTPProvider("HTTP://127.0.0.1:7545"))
chain_id = 1337
my_address = "0x22d9529aa7b67b2738d4B082Bf4074758D04b0ff"
#private_key = os.getenv("PRIVATE_KEY")
private_key = "0xafb98d224dcc7768934bee92d8b6c330b06ff88a5e12b9cfb629bc30323b6547"

Remember to add a 0x before pasting the private key from Ganache, as Python looks for it when it parses. One peculiar thing for you might be the getenv function above instead of pasting the private key directly. This is because of security concerns. It’s good practice not to leave your private key in the code. Instead, create a new file–.env. In this file, write “PRIVATE_KEY=0x,” and after 0x, paste in the private key.

Ensure you don’t add any spaces whatsoever. However, I commented this line for simplicity and instead pasted the private key as a string in the source file.

Okay, that leaves writing the os dot getenv function and then writing the text on the left side of the assignment operator, that is, “PRIVATE_KEY.”

Note: Never share your private keys with anyone. This has been used only for developmental purposes so that I can share it with you, but if you hold any funds, please encrypt it.

Step 5: Transactions using Smart Contracts in Python

In this step, let’s learn to interact with smart contracts in Python. This is the main gravy so let’s get groovy. Haha, jokes aside, this is where it gets interesting, and you can do pretty much anything here with smart contracts in Python in terms of transactions.

Now that the basics are done, the first step to deploying the smart contracts in Python is to initialize the smart contract in Python.

Use the eth dot contract function and set in the ABI and bytecode parameters equal to the variable names that store them. It essentially creates or initializes the smart contract in Python. For this, it’s important to know about nonce. For our purposes, it’s an arbitrary number that can be used once in blockchain communication. Note that is different than the nonce that “answers’ a blockchain “problem.” This none tracks the number of transactions. Get it by using the getTransactionCount function on the address used above. It is 0 if there are no transactions at the address.

There are three more things to do after creating smart contracts in Python:

  • Build the transaction: In web3.py, you always need to pass the parameters of chainid, address of sender, and a nonce. It’s best to pass these in as variables.
  • Sign the transaction: This is where you will use your private key stored above to sign the transaction. Anyone else will be able to confirm who made the transaction, as a result. The parameters here are the transaction built and the private key.
  • Send the transaction: This step uses the send_raw_transactions function which uses the signed transaction parameter.

To confirm the transaction was sent, wait for a transaction receipt.

ganache deploy Smart Contracts in Python

Congratulations! You just sent your first transaction on a local blockchain!

# initialize contract
SimpleStorage = w3.eth.contract(abi=abi, bytecode=bytecode)
nonce = w3.eth.getTransactionCount(my_address)
# set up transaction from constructor which executes when firstly
transaction = SimpleStorage.constructor().buildTransaction(
    {"chainId": chain_id, "from": my_address, "nonce": nonce}
)
signed_tx = w3.eth.account.signTransaction(transaction, private_key=private_key)
tx_hash = w3.eth.account.send_raw_transaction(signed_tx.rawTransaction)
tx_receipt = w3.eth.wait_for_transaction_receipt(tx_hash)

Step 6: Deploying Smart Contracts in Python

In this step, you will finally deploy smart contracts in Python.

I know you have been waiting for this but all of the previous steps were necessary to get to the point of deploying smart contracts in Python.

To work with or interact with smart contracts in Python, you need ABI and address.

 interact with smart contracts in Python

There are two different ways to interact with blockchains: call and transact.

Call refers to the functions in smart contracts that don’t make state changes or the view functions.

Transact refers to the function in smart contracts that do make state changes.

Transact refers to the function in smart contracts

To make a state change, you must build a transaction and then sign and send it to make state changes. Once the store function has been “transacted,” call the retrieve function to fetch the value.

# calling functions in contract block
# to work with a contract, you need abi and address

storage_sol = w3.eth.contract(abi=abi, address=tx_receipt.contractAddress)
call_fun = storage_sol.functions.store(5).buildTransaction(
    {"chainId": chain_id, "from": my_address, "nonce": nonce + 1}
)
sign_call_fun = w3.eth.account.signTransaction(call_fun, private_key=private_key)
tx_call_fun_hash = w3.eth.send_raw_transaction(sign_call_fun.rawTransaction)
tx_call_fun_receipt = w3.eth.wait_for_transaction_receipt(tx_call_fun_hash)

print(storage_sol.functions.retrieve().call())

Bonus: Deploy Smart Contracts in Python using Infura

Note: To view the full Python source file, head to the Deploy Smart Contracts in Python Github Repository which includes all the source files, including the smart contract and the Python files to deploy locally and using Infura.

What is Infura?

Infura is a third-party Blockchain-as-a-Service (BaaS) platform that allows you access to their node network and gives a blockchain URL to deploy on the main net or test nets like Rinkeby. Moreover, using Infura means an easier way of testing your code on a blockchain, instead of an offline one. Infura is really intuitive and simple to use.

Another BaaS is Alchemy. However, I haven’t tried it myself.

chain id for deploying smart contracts in pyhon

To find out the Chain IDs of different blockchains, head here.

After that, open your Metamask wallet and copy the wallet address to my address variable in the code. For the private key, head to account details and private key, enter your passcode, and copy the private key to the smart contract code in Python.

Everything else remains the same.

smart contract code in Python

Sign up on Infura, create a new project and then under the “<strong>Keys</strong>” section, search for endpoints. Use the dropdown to select any test net server– I used Rinkeby. I have explained in depth the reason to work with Testnets at this point. Copy the Rinkeby endpoint URL and paste it inside the Web 3 HTTP Provider function

The following is the piece of code that must be updated to deploy smart contracts in Python on Infura:

Web3( Web3.HTTPProvider("https://rinkeby.infura.io/v3/222c8aa6fd6b4f77a4e9c410a094e3f8")
chain_id = 4	 
my_address = "0x227709345A77707D85FdF03279350f929A5eb953"
# private_key = os.getenv("PRIVATE_KEY")
private_key = "0xc5de9f897b6222bdf25f8ada4bd1f349cbc0f8dcb7163636917ede59ff97838d"

Conclusion

In conclusion, you deployed your smart contract files in Python locally and on a test net, like Rinkeby, using Infura. I hope following this tutorial was fun for you to follow along.

I love developing in Python, so that’s the route I use. However, you can do the same things in Javascript (JS), with some minor changes. Javascript possesses a Web3.js library for Web 3.0-related tasks. Furthermore, Python is also a language for deploying smart contracts n.

Solidity or Vyper both provide a decent-only package. Vyper resembles Python syntax, while Solidiry follows Javascript and a little bit of C++. Access all source code files on this Github repo.

I hope you found this post to be informative and that it was easy to follow. But if you face any issues or problems, let me know below. Don’t forget to like the article if you learned anything useful here.

]]>
https://sesamedisk.com/smart-contracts-in-python-complete-guide/feed/ 6
Write First Smart Contract in Solidity | Blockchain https://sesamedisk.com/write-first-smart-contract-in-solidity-blockchain-web/ https://sesamedisk.com/write-first-smart-contract-in-solidity-blockchain-web/#comments Fri, 17 Dec 2021 04:26:08 +0000 https://sesamedisk.com/?p=4569 Getting Started With Smart Contracts in Solidity | Web 3.0

Skeptical about the insane blockchain hype? Maybe you don’t know what a smart contract does? Are you feeling lost regarding NFTs and how blockchains work? Perhaps you’re unsure where to start in the sea of immense knowledge? This is it. Trust me; you’re going to want to read and learn why web 3.0 and blockchains are the future– this is the post for you.

This is the post you are looking for. In this article, you will learn how to create your first-ever smart contract (yay!), compile and then deploy it! For this post, I will use Solidity to write the smart contract (you may also use something like Vyper, which shares its syntax with Python).

blockchain that incorporates cryptocurrency and much more

Let’s dive right into the technical scope and introduction for blockchain– the future of the Internet (web 3.0).

What is a Blockchain?

What is a blockchain, you may wonder? 

Honestly, I remember being a bit confused about the concept. I wasn’t sure what the lingo meant despite understanding what it was about. Until I decided to explore the blockchain world, and I realized the greatness of this idea.

Technically, a blockchain is a decentralized, digitally distributed database to store transactions across a vast network of systems or nodes. A blockchain consists of countless peers of blocks; blocks are a list of mined transactions. In simple terms, a blockchain is an immutable digital ledger.

Why is That Useful For You?

Blockchains are essentially based on these properties:

  • Immutable: this means no changes can be made to a block after creation– its nonce changes once a modification is made to the original data or transactions.
  • Secure: immutability and use of consensus helps with security
  • Decentralized: no central entity controls access
  • Deterministic: the same function run across different nodes returns the same result
  • Trustless: contract agreements don’t have to be trusted upon to fulfil them; instead, they are always fulfilled when the conditions are met.

Therefore, blockchain technology is not a part of a Ponzi scheme or a scam; this technology is legit revolutionary. Moreover, blockchains operate using either a Proof of Work or Proof of Stake.

What is a Cryptocurrency?

What is a cryptocurrency, and why is it suddenly the most incredible thing? Let’s explore this below. Cryptocurrency is a digital payment system that requires verification from a third party, like a bank or other institution. To make transactions, you exchange digital assets with a peer.

bitcoin and cryptocurrency, proof of work, mining, ditgital assets

Cryptocurrency is widely hailed as the future currency because of its independent nature. Cryptocurrency consists of many coins or digital currencies like Bitcoin, Ethereum, Dai, USDT, etc.

Bitcoin is worth a whopping $58k, while Ethereum is worth $5k a coin.

The benefits offered by cryptocurrencies consist of:

  • Faster international payments
  • Freedom of monetary choices
  • 24/7 access to your digital assets
  • Stronger security

However, some people– a minority– still perceive cryptocurrency as a pyramid scheme or a fraud. Its volatile nature is particularly highlighted with coins like Bitcoin that suffer heavy dips and exponentially stark peaks in a short period. This is especially dangerous if you’re using a cryptocurrency like Bitcoin for your business as the prices of goods will vary dramatically from day to day– sometimes even hourly.

What is a Smart Contract?

Smart contracts are akin to real-life contracts; they execute automatically when certain conditions fulfil. They are instrumental and widely used today in blockchain implementation. 

blockchain smart contract

Often, smart contracts pair with an oracle network, an operator that provides off-chain data from the real world securely to the blockchain. The data received is from multiple sources to ensure the blockchain doesn’t violate its core principle– decentralized nature.

Don’t be intimidated– a few months ago, I had no clue about what any of this meant, honestly. Not a blockchain, smart contract. However, I spent the following weeks exploring and learning this fantastic futuristic solution. It can be hard to figure out where to start, but I recommend diving into smart contracts. 

Why? Smart contracts are the building blocks of the blockchain world, no pun intended.

In addition, a smart contract is a solution to trust violations from people you expect to hold up their end of the agreement. They ensure you never have to trust someone– hence blockchain can be trust-less.

Setting Up Your Development Environment For Smart Contract in Solidity

  • REMIX: an IDE for Ethereum development.
  • Metamask: a digital wallet; commonly used for all Ethereum applications.

One of the first things you need to set up before writing your first smart contract in Ethereum is to get Metamask. It’s an app on your phone or a browser extension to create an account. You must never share the secret seed phrase key with anyone else and secure it safely. This is essential if you wish to keep your funds. However, we recommend you do not deposit any real money in this account for development purposes. The beauty of Metamask is that you can create multiple accounts with their private keys secured by your seed phrase key. Create a new account on Metamask and name it something related to development, so you don’t forget the purpose and accidentally deposit tangible digital assets to that account.

metamask smart contract test net amount in ethereum

Installing Solidity(MacOS)

Copy and paste this command in your ssh terminal on macOS to install the Solidity Compiler:


brew update

brew upgrade

brew tap ethereum/ethereum

brew install solidity

Prerequisites: Install Homebrew with this command:

mkdir homebrew && curl -L https://github.com/Homebrew/brew/tarball/master | tar xz --strip 1 -C homebrew

After that, do this:

eval "$(homebrew/bin/brew shellenv)"

brew update --force --quiet

That’s it! You have successfully begun writing your first smart contract! Pat yourselves if you made it this far. You have earned it!

Setting up REMIX IDE:

REMIX is an Integrated Development Environment (IDE) to code your logic. These logics are necessary to develop to understand the levers of blockchains. In other words, REMIX is a tool you will use to write your smart contracts for various applications such as DAPPs, DEXs, DEFIs, etc.

Hence, you can download the application or open it in your browser to start using Remix. I prefer to download and use it locally. 

Test Net

A test net is like the Ethereum main net, but instead of making changes to the actual Ethereum blockchain, you can test the smart contracts safely on a test net first. Consequently, you don’t pay gas fees, and you’ve not incurred any extra cost in case the smart contract doesn’t work as intended.

There are various types of test net- Rinkeby, Kovan, etc.

Using a test net is helpful because this is a smart demo contract, and we don’t want to post it on the Ethereum blockchain. Instead, a test net allows the freedom to play with the code and learn from it without having to pay the enormously high Ethereum transactional gas fees. Hence, you can deploy the smart contract for free.

Rinkeby Faucet:

For development purposes, it is recommended that you work with a test net not to post any gas fees and prevent making changes to blockchain. Head to a working Rinkeby faucet, and request some Ethereum onto your Rinkeby test net.

Writing Your First Smart Contract

Smart contracts are primarily written in Solidity, but another language is still in infancy– Vyper, which resembles Python. All Vyper code must be syntactically Pyrhon3 code while the other way is not necessary.

We will use Solidity for writing the smart contract on Remix IDE for this tutorial.

Let’s write a simple contract that stores a number to be retrieved later.

How To Write A Smart Contract: Simple Storage

When you open Remix IDE, click on Solidity to select the compiler.

After that, create a new file with a .sol extension (.sol for Solidity; Solidity is used to deploy or execute smart contracts).

Name this “SimpleStorage.sol”. Note that the file type for smart contracts written in Solidity is “.sol”.

Then, the first thing you need to do before beginning to write the smart contract is declared the license.

license to write a smart contract in solidity

Afterwards, define the solidity version for the smart contract. Usually, in newer versions, some functionalities may break, so it is recommended to strictly define the versions your smart contract will support strictly.

// all solidity versions from 0.6.0 to 0.9.0
pragma solidity >= 0.6.0 <= 0.9.0

// all solidity versions of 0.6.x
pragma solidity ^0.6.0
declare solidity version for smart contract

After that, it’s time to declare your first contract in Solidity. A contract is similar to a class in Object-Oriented Programming (OOP). Contracts contain data as state variables and functions to modify them.

The use of contract keyword in Solidity is quite similar to how a class may be used; name this contract aptly for readability purposes.

It is good practice to write camel-case for the contract names here.

first smart contract in solidity SimpleStorage to store number

Note: the closing curly braces at the end are for the struct, not contract. The contract will be used till the end of this smart contract.

Variables in Solidity: First Smart Contract

A variable stores the reference to a specific address in the memory to make it easier to reuse. Variables are used to store data; they may be of several types.

General Syntax for Variables in Solidity

The following is the general syntax for defining variables in Solidity:

// data_type scope variable_name
uint256 public favoriteNumber

Moreover, by default, the scope is internal— if not specified.

Types of Variables Scopes:

The following list contains the types of scopes:

  • public: accessed via contract and through messages
  • internal: accessed only from inside agreements and contracts derived from it
  • private: accessed only from inside contract
  • external: accessed only from outside, smart contract

uint256 specifies that the value can only be positive and of the length 256 bits. Moreover, this variable is public, which means the following functions can access it.

The next step is not mandatory unless you want to explore the possibilities of this smart contract, SimpleStorage. In other words, a struct is a user-defined datatype to create records; it’s like an array, but instead, you can group items or properties for a particular object. Let me explain with an apt example: imagine you own a library full of books, right? Now, you may wish to note down the title, book id, author name, release year for all books. This is where a strut or structure comes into play. Define a struct named People. Inside this, define two variables; favorite number and name for the people.

struct People {
uint256 favoriteNumber;
string name;
}

Therefore, now we have created a data type defined as People, which will be helpful a little later on.

How will we use this new data type?

Arrays in Solidity

Arrays store lists of objects. In other words, arrays are used to multiple values. The way to link this with struct is by initializing an array or collection of data type People.

People[] public person;

An array of struct data types allows us to store its containing variables for multiple people’s data. In turn, this will enable us to store data for the smart contract categorically.

Functions in Solidity

Functions or methods are self-contained modules in Solidity that execute the defined tasks.

This is the general syntax for defining a function in Solidity:

// function func_name(variables passed) scope

Now, it’s time to create a function to store numbers from people.

smart and retrieve functions in solidity smart contract

Hence, define the function store (which stores someone’s favourite number), passing a variable to store a number input from the user. Assign the favourite number variable created above (with public scope) to the local variable passed in the function.

This is great, but how can we return this number to see if stored correctly?

Retrieve() Function

After that, create another function. Let’s call this retrieve since the purpose of this function is to get the stored number. However, there is no need to pass a parameter in this function. Furthermore, it’s pretty interesting that this is a view; a view is a non-state changing function. In other words, views don’t make state changes and hence don’t affect the blockchain. Lastly, a return type of uint256 (same as the datatype stored) must be defined explicitly.

In the body of this function, return the favorite number.

Bonus Content:

Hooray! You have made it this far. Incredible. Doesn’t this rush feel great? You wrote your first smart contract. However, if you want to keep going, let’s do that– you can skip it for now if you’re going to grab a coffee or something.

After that, create a new function addPerson, while passing two parameters; name and favourite number. Set the scope to public and inside the body of this function, use the “push()” function for arrays to push values into the People array for favourite number and name.

addPerson function in smart contract

The last line is a mapping; write this code above the function.

mapping (string=> uint256) public nameToFavNum;
mappnig syntax eg in smart contract

A mapping converts one data type to another, using it for reference.

The line converts the user’s name to the favourite number in the smart contract above.

Compiling Smart Contracts in REMIX IDE

Since Solidity is a compiled language, it is essential to compile the smart contract before proceeding. This means converting the code you just wrote into machine code (even containing some assembly language).

This is an essential prerequisite for deploying a smart contract.

compile smart contrsct in solidity

Deploying Smart Contract in EVM

Deploying a smart contract means running it no a VM or live connection. It means the smart contract is enabled, and the user may work with it. Smart contracts are initially deployed on test-nets to check for bugs and avoid unnecessary costs.

To deploy, head over to the sidebar on REMIX IDE and click on the icon in the purple box:

Smart Contract in EVM

After that, click the deploy button. 

Then, scroll down and click on the deployed contracts to see a droppable of all the states.

deploying smart contract in solidity remix ide

To demonstrate the work, enter a random value in the store field and click on the orange button (orange implies a state change– a transaction). Subsequently, click on the blue retrieve button (no state change). You will see the same number you entered if you did everything right.

Note: the colors of these buttons are crucial.

  • A blue button indicates no state change or no transaction made on the blockchain on a function call.
  • An orange button indicates a state change or transaction made on the blockchain on a function call.

There you go! You’ve successfully managed to write your smart contract!

Conclusion:

I hope you found this post helpful in helping you write your first smart contract in Solidity. Be proud of yourself for accomplishing this. You’re one step closer to becoming a blockchain developer.

After following this post, I recommend exploring Solidity and writing a smart contract on your own.

Drop a like and let us know if you like this type of content in the comments so we can create more. We’d love to hear if you want to see similar stuff in the future and explore this fantastic path ahead that we call Web 3.0– the revolution. If you’re going to explore more posts, go here.

]]>
https://sesamedisk.com/write-first-smart-contract-in-solidity-blockchain-web/feed/ 2