Introduction
Contracts are binding and have been around for a long time. Until the internet revolution in the 1990s, contracts were only enforceable by the action of a third party. For example, if you had an agreement with someone who sells fashion clothes, and part of the agreement was that you paid an advance to receive it at a decided date where you would also pay up the remaining cash.
And for some reason, the other party doesn’t hold their end of the bargain; the third party makes this enforceable, usually using force.
In contracts, you hope and trust that the other party comes through, and there won’t have to be a need for the enforceable actions of a third party, which brings up unfavorable situations.
What are Smart Contracts?
Smart contracts are programmed agreements written in code, which executes the programmed command when all agreement conditions are met.
To break down this understanding, let’s use the analogy of the workings of a vending machine:
A young man Bobby visits his friend in a hospital and is exhausted and needs to have a carbonated drink, Coke. Bobby decides to use a vending machine he finds in the vicinity, he walks up to the device and chooses Coke, and the engine returns the amount he needs to release the drink.
He inserts the required amount, and the vending machine verifies the correct amount. Afterward, it dispenses the carbonated drink to Bobby.
From the analogy, Bobby couldn’t have committed any fraud to get the carbonated drink because the vending machine is programmed only to dispense when the other party has inputted the correct amount required for a product.
Another example would be the use of an escrow service. Alice is a woman who lives in California, USA, and goes on a trip to Europe, and unfortunately runs out of dollars. She needs it and decides to use an escrow to exchange her dollars for euro with a local she met, whose name is Isaac.
Alice sends the amount she wants to exchange to the digital escrow, and Isaac sends an equivalent of the euros to the same digital escrow. After the program verifies that both have sent the required amount for the transaction to happen, it releases the euros to Alice and the dollars to Isaac.
Here there is no requirement for using a third party to enforce the agreement between both parties, and the smart contract program handles that, which makes the transaction more credible and boosts trust.
I. - Getting Started with Blockchain Smart Contract Development
Blockchain smart contract development is the programming and deploying of agreements in code to the blockchain where it is transparent for all to check and which executes agreements on the blockchain.
Here is a guide on getting started with Blockchain smart contract development:
1. Install Solidity
To install solidity, we will use an easy approach. First, you have to install Visual Studio Code on your system. To download Visual Studio Code:
Head over to the website to download the software; depending on the operating system you use, as shown in the diagram below, choose your operating system, download, and run.
After downloading and running Visual Studio Code, head over to this part of the software as highlighted below:
- When there, input “solidity” in the search bar as seen below:
- Afterward, click on the first result shown below, and click install:
- To confirm you have installed solidity correctly, you should check this part of the picture highlighted below:
You are good to go now that solidity is installed in your Visual Studio Code.
2. Choose an Integrated Development Environment (IDE) like Remix
For easy coding, deploying, and debugging of smart contracts for Ethereum and EVM-compatible chains, Remix online Integrated Development Environment (IDE) is the safest and fastest option you could go with.
To use Remix IDE, head over to the website and launch it. When you do this, this is what you should see on your screen:
Now that you have this, let’s create our first contract.
3. Write and Compile your First Smart Contract
To write your first contract, we need to create a file for the solidity in its format or extension, which is .sol
. To do this, head to the contracts folder.
When you do, right-click on the folder and create a new file using the name you want your file to be, ending it with .sol
. I called mine Django_App
:
You must understand the basic syntax and style guide to write your first solidity code. For consistency, the style guide requires four spaces for indentation; for declarations, you should surround them with two blank lines. When declaring functions, they should have an empty line space.
Let us write a simple, smart contract. To do this, open the file you created earlier, ending with the .sol
extension. Next, we need an SPDX license identifier comment at the top of the code; this helps trust and makes source code available. Note that in solidity, every comment begins with //
.
Write your first line of code, which is the comment:
// SPDX-License-Identifier: GPL-3.0
Next, we use the pragma
keyword, as this helps the compiler we use to run specific features and checks. To prevent future problems with compilation incompatibility, we use a version pragma
. Here we use:
pragma solidity >=0.7.0 <0.9.0;
This means this code is written for solidity version 0.7.0 up till 0.9.0 and no more. Subsequently, we create a contract and name it App:
contract App {
}
The contract we have created so far is empty because it doesn’t contain codes that tell the contract to perform a specific action.
To compile your contract, click on compile interface highlighted below:
When you do so, and there are no syntax errors in your code, you should click here to compile your contract:
4.Testing your Smart Contract Using Ganache and Metamask
Now that you have written your first smart contract using an IDE named Remix and have complied with it let’s test it.
To do so, we will use Ganache, a personal Ethereum blockchain that provides you with virtual accounts and test Ethereum tokens to test your smart contracts before deploying to the mainnet.
To set up your Ganache, head to the website, choose your operating system, download it, and then run the application. To set up your account with Metamask, do this:
- First, choose the quickstart option; you will see this interface below. All you have to do is choose an account you will use:
- Next, you need to connect Ganache to your Metamask. If you don’t have it installed, use this guide and get started. To connect with Ganache, head to the settings display on your Metamask:
- Next, copy the RPC from your Ganache desktop application:
- After you have, you should input it in Metamask to connect it. In the settings area, choose networks. After you have chosen networks, proceed to add the network you want. And manually input the network, placing the right answers in the necessary sections below. However, note that in the RPC server section, you should paste the one you copied:
After putting the required information, save it.
- You need to import any of the Ganache accounts into your Metamask so you can easily deploy and test your contract. Choose any account and tap on the key icon and copy the private key:
- After you have copied the private key, go into your Metamask and import it:
- If you did so correctly, this is what you would have on your screen:
- After you have followed all the steps outlined and have correctly done so, You need to connect your Metamask wallet to Remix IDE. To do this, head to Remix and choose the deploy and run option. After you have done so, choose “injected provider-Metamask” and connect your wallet. Next, choose a contract, in this case, the
Django_App
contract we created earlier, and deploy:
- Afterward, confirm the transaction on your Metamask:
- If the contract deployed successfully, you should get this:
If you got the notification, congratulations! Your contract worked, and you are good to go.
II. - Integrating Smart Contracts in a Django App
Django is a framework that helps Python developers build scalable web applications. And in this section, you will learn how to integrate a smart contract in a Django app.
1. Create a Django Project
Since the installation we ran applies to all the systems, we should create a Django application to perform further activities. After you have completed creating a Django project following this guide, you should install the necessary packages we need.
Get into your terminal, still in the virtual environment you had begun to create your Django project, and run this command:
pip install web3
You will see an output as this after you have successfully installed the package:
2. Connecting to a Blockchain Network Using Django
To connect to the Django framework, you first need to choose the network you wish to connect to, and for this guide, we will connect to the Ethereum Blockchain; to do so, we will use the web3.py
library.
Create an app within your Django project and create an eth.py
file within your designed app, and import web3
there:
from web3 import Web3, AsyncWeb3
Since we need to connect to a blockchain network and have decided it will be Ethereum, we will use Infura provider. Open an account and copy the API keys:
And head over to the eth.py
file of your Django app and input this there:
infura_url = "https://mainnet.infura.io/v3/78955d8b4dde48dbbc963ac94fce1b92"
It helps us specify our provider, which is in HTTPProvider
. Also, note that you must assign your URL to a variable; here, you assign your API to the infura_url
variable. Next, instantiate a connection using this:
web3 = Web3(Web3.HTTPProvider(infura_url))
To check if your connection worked, add this line of code:
print(web3.is_connected())
If it is connected, you will get a true
statement in your terminal when you run the code.
So far, you should have something like this:
from web3 import Web3, AsyncWeb3
infura_url = "https://mainnet.infura.io/v3/78955d8b4dde48dbbc963ac94fce1b92"
web3 = Web3(Web3.HTTPProvider(infura_url))
print(web3.is_connected())
3. Sending a Transaction Using web3.py
in your Django Project
You can send eth using web3.py
from your Django app. To do this, get into the views.py
file in your Django app and import web3
, views:
from web3 import Web3
As we did with Infura earlier, specify the ganache API within a variable; here, we use ganache_url
, given as:
ganache_url = (YOUR_API_KEY/RPC)
Next, instantiate the connection using this:
web3 = Web3(Web3.HTTPProvider(ganache_url))
Next, you load your account via the eth account:
acct1= w3.eth.account.from_key(pk)
From your Ganache account, let's choose the first account, get the private key, and put it in place of pk
in the line of code above. What this does is load the account's data into variable acct1
.
Next, we assign the address we want to send eth to a variable:
some_address = "0xe1488a47b923aD2FC150Ac4DeE4dcE5605Ed5fce"
For the address to assign to some_address
, use the second account or any of your choice in your ganache.
Next, we need to build out the transaction to send eth. To do this:
transaction = {
'from': acct1.address,
'to': some_address,
'value': 1000000000,
'nonce': web3.eth.get_transaction_count(acct1.address),
'gas': 250000,
'gasPrice': web3.to_wei(8,'gwei'),
}
In the code, from
specifies the account you are sending the eth from to
identifies the receiving address. The value
is the amount of eth you wish to send, the nonce
is put to ensure it sends once, gas
specifies how much you want to send, and gasPrice
is the gas price for the gas
you wish to pay for the transaction.
Next, you should sign the transaction using the private key of acc1. Here's how to do it:
signed = w3.eth.account.sign_transaction(Transaction, private key)
Lastly, we send the signed transaction:
tx_hash = w3.eth.send_raw_transaction(signed.rawTransaction)
tx = w3.eth.get_transaction(tx_hash)
assert tx[" from'] == acct1.address
Here's the full code:
from web3 import Web3
ganache_url = "HTTP://127.0.0.1:7545"
web3 = Web3(Web3.HTTPProvider(ganache_url))
acct1 = web3.eth.account.from_key("0xc1bf30defcd506bc3692de90ac0295763c29e79eb92c81bbcf78378d50a76db3")
some_address = "0xe1488a47b923aD2FC150Ac4DeE4dcE5605Ed5fce"
transaction = {
'from': acct1.address,
'to': some_address,
'value': 1000000000,
'nonce': web3.eth.get_transaction_count(acct1.address),
'gas': 250000,
'gasPrice': web3.to_wei(8,'gwei'),
}
signed = web3.eth.account.sign_transaction(transaction, "0xc1bf30defcd506bc3692de90ac0295763c29e79eb92c81bbcf78378d50a76db3")
tx_hash = web3.eth.send_raw_transaction(signed.rawTransaction)
tx = web3.eth.get_transaction(tx_hash)
assert tx['from'] == acct1.address
To send the eth, run the file in your terminal. To confirm it worked, check your Ganache and your transactions. You should find this:
4. Deploying a Smart Contract from your Django Project using web3.py
Earlier, we had created a smart contract and deployed it using injected Web3 provider in Remix IDE; this time, we will be deploying the smart contract from our Django project using web3.py
.
As we had done earlier, create a new file, name it deploy.py
, open it, and initiate a connection to Ganache:
from web3 import Web3
ganache_url = ()
web3 = Web3(Web3.HTTPProvider(ganache_url))
Next, using the contract we had created earlier. Head on to your remix, and get the abi
and bytecode
of the contract. After you have done so, head over to the deploy.py file and write this:
bytecode = contract_interface['bin']
abi = contract_interface['abi']
Input your contract’s bytecode and abi into ‘bin’ and ‘abi’. The bytecode
allows us to execute the code, and the abi
lets us interact with the executed code.
Next, we have to set the pre-funded account as the sender. Here’s how to do it:
web3.eth.default_account = web3.eth.accounts[0]
After you have done this, to instantiate it in Python and deploy we do this:
App = web3.eth.contract(abi=abi, bytecode=bytecode)
Where App is the name of the contract we had created earlier, after deploying to get the transaction hash and receipt, we write this code:
tx_hash = App.constructor().transact()
tx_receipt = web3.eth.wait_for_transaction_receipt(tx_hash)
Here is the full code:
from web3 import Web3
ganache_url = "HTTP://127.0.0.1:7545"
web3 = Web3(Web3.HTTPProvider(ganache_url))
bytecode = '6080604052348015600f57600080fd5b50603f80601d6000396000f3fe6080604052600080fdfea2646970667358221220a2bebf97e45daed66e8c174b0fd5f4b9a2c72e36e6e3f6a7da610f0fa2a8fdc364736f6c63430008120033'
abi = '[]'
web3.eth.default_account = web3.eth.accounts[0]
App = web3.eth.contract(abi=abi, bytecode=bytecode)
tx_hash = App.constructor().transact()
tx_receipt = web3.eth.wait_for_transaction_receipt(tx_hash)
Congrats! You have deployed your contract from Django. To get your contract, go into your Ganache app, and check the transactions. You should find this:
Conclusion
Django is a Python web development framework you can use to carry out Web3 operations when you have web3.py installed. You have learned the concept of smart contracts and how to create and deploy one.
In addition, there are different considerations when it comes to smart contracts. Due to its nature, there are security vulnerabilities to watch out for, testing, auditing, and upgrading. Luckily, you have learned how to build smart contracts for Django Applications.
Top comments (1)
Nice work.