Showing posts with label ledger. Show all posts
Showing posts with label ledger. Show all posts

Friday, December 30, 2022

7 Easy Steps to Setup and program a Ledger Smartcontract using Python Language

7 Easy Steps to Setup and program a Ledger Smartcontract using Python Language

From the analysis performed by Precedence Research, the blockchain technology market size is expected to reach USD 69.7 Billion by 2025 and USD 1593.8 Billion by 2030. Demand of the blockchain developers are increasing day by day. 

Growth Analysis of Blockchain Market:

Ledger - Growth Analysis of Blockchain Market

Image Source: Precedence Research

People coming from any Industry be it Electronics, Software, Medical, Mechanical… “You need to keep learning to stay up to date in the current market”. Being a software engineer, new programming languages or tools change very frequently, but today we are not going to learn any new programming language considering that you are aware of Python programming.

 

This post will explain the steps of deploying smart contracts using Python and make you understand on how to do it independently and concisely. Before we dig into the article, we need to understand few things explained below:

 

        - Python pre-requisites to deploy ledger Smartcontract 

        - About the libraries installation

        - Details of the Platform for performing blockchain operations


Python pre-requisites to deploy ledger Smartcontract:

About the libraries Installation:

 

Run the following commands to install:

  • Web3.py:  $ pip install web3
  • Solcx:       $ pip install py-solc-x
  • Eth_Utils:  $ pip install eth-utils==1.1.2
  • Dotenv:     $ pip install python-dotenv

 

Note: When installing you might find issues related to library version. If you observe, try with below to resolve:


$ pip install web3==4.1.9

$ pip install eth-utils==1.10.0

 

Details of the Platform for performing blockchain operations:

 

No need to worry if you do not have prior experience or knowledge on Solidity, I have an article on this and it a “16 Step Guide to Setup and program a Ledger Smartcontract using Solidity” will help you understand step by step, till then you can use the sample file “SimpleStorage.sol” – Download

 

We will be using “Gananche” tool to perform blockchain operations locally before deploying. This tool is used to test blockchain transactions, inspect changes etc.. (Tool has both CLI and GUI)

 

 

7 Steps to Setup and program Smartcontract:

 

STEP – 1: Importing Libraries

 

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: Reading the .SOL file using python

 

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

    simple_storage_file = file.read()

 

STEP – 3: Compiling the Smartcontract

 

For this Step we use “py_solc_x” library to use standard compile function. This is used to break the code into Assembly Language, which is much closer to Machine Language for execution.

 

Before going into code, we need to understand 4 parameters used to compile Smartcontracts:

 

lauguage: Solidaty language to understand the details of the Smartcontract

 

sources: Smartcontract file, content and variables used to store information of Smartcontract

 

outputSelection: To get information related to ABI, Metadata, Bytecode and its sourcemap.

 

solc_version: This is the version used in the Smartcontract code

 

Once we understand the above information, Open the file and save it into JSON formatted file:

 

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: Extraction (ABI & Bytecode from Solidity Smartcontract)

 

Bytecode contains the 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 other words, this is the code that is executed by Ethereum Virtual Machine (EVM) and which governs the working of the smart contract file.

 

Below code is in JSON format, this is from the compiled contract file

 

# get bytecode

bytecode = compiled_sol["contracts"]["SimpleStorage.sol"]["SimpleStorage"]["evm"][

    "bytecode"

]["object"]

 

Besides, ABI is “Application Binary Interface” this is also an important piece of information for a Smartcontract.

 

ABI in Smartcontract is responsible for interaction between methods and structures, it is similar to Application Programming Interface (API). In the above compiled JSON object if you print the data, you will find ABI with Smartcontract file inputs, names, rdata types and outputs etc..

 

# get abi

abi = json.loads(

    compiled_sol["contracts"]["SimpleStorage.sol"]["SimpleStorage"]["metadata"]

)["output"]["abi"]


STEP – 5: Local Ethereum Blockchain connection using Ganache

 

Install Ganache tool, use Quick Start and get the information from the tool.


Ledger Ganache - Transaction


w3 = Web3(

    Web3.HTTPProvider("HTTP://127.0.0.1:7545")

)

chain_id = 1337

my_address = "0x23959D4e00640f2D152dA3F96474504e63Aa6d2D"

# private_key = os.getenv("PRIVATE_KEY")

private_key = "0x4d08735ff981fa51e9c56c79c99d121c9f66754c27926ca5014fdaa2d71e904f"

 

Few things to consider here:

  • Add a 0x before pasting the private key from Ganache.
  • It is 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.
  • To find out the Chain IDs of different blockchains, head here.

 

STEP – 6: Performing Smartcontract Transaction using Python 

 

This is the part where you need to keeps your eyes wide open and do not get disturbed. 

 

initialize the smart contract in Python by setting parameters for ABI and Bytecode

 

# initialize contract

SimpleStorage = w3.eth.contract(abi=abi, bytecode=bytecode)

 

Next it is important to know about Nonce - it’s an arbitrary number that can be used once in blockchain communication. Nonce tracks the number of transactions with help of function – “getTransactionCount” on the addressed used.

 

nonce = w3.eth.getTransactionCount(my_address)

 

Few things to consider here:


After creating Smartcontract in Python, there are 3 more things to do – 

Ø  Build the transaction

Ø  Sign the transaction

Ø  Send the transaction

 

Build the Ledger Transaction:

 

Web3.py has information we passed related to chainid, address of sender, and a nonce. Pass this information as variables so we can use it when required

 

tx = SimpleStorage.constructor().buildTransaction(

    {

        "chainId": chain_id,

        "gasPrice": w3.eth.gas_price,

        "from": my_address,

        "nonce": nonce,

    }

)

 

Sign the Ledger Transaction:

 

To sign the transaction we need to use the private key of the address of the sender, hence it is advised to store the private key separately instead of using directly in the code. Here we use the transaction build and private key as show below:

 

signed_tx = w3.eth.account.signTransaction(tx, private_key=private_key)

 

Send the Ledger Transaction:

 

This step uses the send_raw_transaction function with signed transaction parameter as shown below:

 

tx_hash = w3.eth.sendRawTransaction(signed_tx.rawTransaction)

tx_receipt = w3.eth.waitForTransactionReceipt(tx_hash)

print(f"Contract deployed to Infura at address {tx_receipt.contractAddress}")

 

Ledger - Ganache - Transaction 2

STEP – 7: Deploying Smartcontract using Python

 

We have arrived to last step which we are waiting from the starting of this article, but all the above steps are mandatory to get to this point.

 

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


Ledger Ganache transaction created

There are 2 ways to interact with blockchains – call and transact

 

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

 

Transact: The function in smart contracts that do make state changes.


Ledger Pycharm code execution

To make a state change, you must:

  1. First build a transaction,
  2. Then sign the transaction
  3. Then send the transaction
  4. Once the store function has been “transacted,” 

call the retrieve function to fetch the value, function is used in below code to work with deployed contracts

 

simple_storage = w3.eth.contract(address=tx_receipt.contractAddress, abi=abi)

print(f"Initial stored value at Retrieve {simple_storage.functions.retrieve().call()}")

new_transaction = simple_storage.functions.store(25).buildTransaction(

    {

        "chainId": chain_id,

        "gasPrice": w3.eth.gasPrice,

        "from": my_address,

        "nonce": nonce + 1,

    }

)

signed_new_txn = w3.eth.account.signTransaction(

    new_transaction, private_key=private_key

)

tx_new_hash = w3.eth.sendRawTransaction(signed_new_txn.rawTransaction)

print("Sending new transaction...")

tx_new_receipt = w3.eth.waitForTransactionReceipt(tx_new_hash)

 

print(f"New stored value at Retrieve {simple_storage.functions.retrieve().call()}") 


Print Friendly and PDF

Sunday, December 25, 2022

Ledger: Top Blockchain Smartcontract Platforms And Their Differences From One Another - Articles

Ledger: Top Blockchain Smartcontract Platforms And Their Differences From One Another - Articles

Top 5 SmartContract Ledger Development Platforms:


Top 5 SmartContract Ledger Development Platforms


The five most popular smartcontract platforms, Ethereum, Hyperledger Fabric, Corda, Stellar, and Rootstock, are discussed in this section. Ethereum, Hyperledger Fabric, and RSK have Turing-complete smartcontracts; however, Corda and Stellar have Turing-incomplete smartcontracts. Ethereum and RSK are public smartcontract platforms (i.e., permissionless), meaning anyone can join the network at any time.


8 Key Distinctions Between The Major Blockchain Ledger Platforms:


Corda has permissioned type of ledger, and supports smartcontract function, meaning you can write and deploy smartcontracts in Corda Blockchain. Corda is an open-source blockchain platform for developers to create permissioned distributed solutions. Tezos is an open-source blockchain platform used worldwide to build decentralized blockchain networks.

 

Hyperledger Hub is a project developed by The Linux Foundation to openly develop centralised and decentralized blockchain platforms. Hyperledger Sawtooth is another scalable blockchain platform in the Hyperledger Hub, designed to develop distributed ledger applications and networks. Enterprises are using Hyperledger Sawtooth to create systems that are both scalable and reliable, as well as deploy blockchain solutions that are highly secure.

 

This platform provides users with a safe, scalable platform for supporting their confidential contracts and private transactions. Hyperledger users can build secret channels to specific members of a network, which allows the transaction data to be seen by only selected participants. Hyperledger Fabric also supports the Open SmartContract Model, which can support a variety of data models, such as Accounts and Unspent Transaction Output, or UTXO, models (see the sidebar).

 

Unlike Ethereum, which uses Virtual Machines (VMs) to execute smartcontracts (i.e., EVMs), Hyperledger Fabric smartcontracts utilize Docker containers to execute the code. EVM is compatible with other blockchains like Solana and Avalanche, which allows developers to migrate their smartcontracts across platforms. With well-written rules, well-defined development guidelines, and Ethereums native coding language called Solidity, it has proven comparatively simple to deploy smartcontracts and Dapps to the platform.

 

Ethereum is also better than any other smartcontract platform when it comes to developer numbers (200,000), making its developer community one of the most vibrant and responsive. The Ethereum network envisions using blockchain technology to not only support a decentralized payments network, but to also store computer code that could be used to fuel decentralized, tamper-proof, financial contracts and applications.

 

Ethereum is yet another blockchain use-case which supports bitcoin (BTC) and in theory, it is not supposed to actually compete with bitcoin. BTC and ETH are both digital currencies, but Ethers primary goal (ETH) is not to establish itself as an alternative monetary system, but rather to facilitate and monetize operations on the Ethereum networks smartcontracts and decentralized applications (dapps) platform. Tezos In development since 2014, Tezos is a more mature platform supporting decentralized applications, smartcontracts, and newer financial instruments like NFTs, which can be thought of as a modern variant on trading cards tied to a digital asset.

 

Cited Sources:


https://www.itransition.com/blog/smart-contract-platforms 

https://geekflare.com/blockchain-platforms-for-finance-applications/ 

https://pixelplex.io/blog/smart-contract-platforms/ 

https://cointelegraph.com/blockchain-for-beginners/smart-contract-development-platforms 

https://www.investopedia.com/articles/investing/031416/bitcoin-vs-ethereum-driven-different-purposes.asp 

https://www.cronj.com/blog/smart-contracts-platforms/ 

https://www.techtarget.com/searchcio/feature/Top-9-blockchain-platforms-to-consider 

https://www.blockchain-council.org/blockchain/top-10-blockchain-platforms-you-need-to-know-about/ 

https://blog.logrocket.com/top-blockchain-development-frameworks/ 


 Print Friendly and PDF

Friday, December 23, 2022

Ledger: Can a Power Systems Rely on Blockchain Technology? - Articles

Ledger: Can a Power Systems Rely on Blockchain Technology? - Articles

Power Systems Rely on Blockchain Technology
Source: https://www.cigre.org/article/GB/the-application-of-blockchain-technology-in-power-systems


Existing system challenges can be resolved by using the Blockchain digital ledger technology to assist multiple power applications at the generation, transmission, distribution, and consumption stages. Trading renewable energy certificates and credits based on actual energy usage can be automated using blockchain ledger technology.


Context:


Blockchain “Distributed Ledger Technology” (DLT) is capable of managing and storing transactions involving numerous parties. DLT can be used for any multi-step transaction-based application that demands securitytraceability, and visibility because of its immutablesecure, and transparent nature. By removing the need for a middleman and connecting the buyer and seller directly, blockchain technology lowers the expenses and fees associated with transactions.


In the P2P network, blocks that are identically stored for each market participant are used to store any transactions. The owner's digital signature authorises each transaction in this digital ledger, ensuring its authenticity and protecting it from fraud. Based on who may add data to the chain and access the distributed ledger, there are three different types of blockchain platforms: PublicPrivate, and Consortium.


Can blockchain be implemented in power grids? - Articlesonblockchain


Using blockchain digital ledger has many advantages, few of them are securetransparent, and robust network with a tamper-proof data record accessible to all participants in the network. With these features, the existing difficulties in the power system can be addressed in the production, transmission, distribution, and consumption phases.


How does blockchain help renewable energy? - Articlesonblockchain

  • The actual transactions between the producer and consumer for consuming the renewable energy can be automated.
  • Payments in the P2P microgrids can be created through Blockchain smartcontracts.
  • For coordination of wholesale power trading, blockchain removes the necessity of middle man management like brokers, indexing agencies, specialised energy trading, or risk-management software.
  • Interactive dashboards on customer utility, grid interactions, payment information, and energy consumption can be managed efficiently using the blockchain distributed ledger technology.


What Infrastructure used in blockchain technology for energy trading? -Articlesonblockchain


The critical components for implementing blockchain technology are full nodes (computers), partial nodes (smartphones or smart meters), a communication network, and a software platform.


Conclusion:


Blockchain digital ledger technology has the potential to drastically improve energy markets. However, because present implementations are on a small scale, extensive work is required before any wider implementation can be a serious disruptive force in this field.


Note: For case studies on Power Systems Rely on Blockchain Technology refer to below links:


[0] - https://www.cigre.org/article/GB/the-application-of-blockchain-technology-in-power-systems

[1] - https://www.ceew.in/cef/masterclass/explains/the-role-of-blockchain-technology-in-the-power-sector


Print Friendly and PDF

Ledger: Blockchain Smartcontract Ledger Platforms - Article

Ledger: Blockchain Smartcontract Ledger Platforms - Article

ledger list of Blockchain Smartcontract Platforms
Source: DCX Learn

Here are some of the blockchain smartcontract development platform list and explained about it concisely: 

Ethereum

Due to its peak in popularity, Ethereum is currently in second position on the cryptocurrency market and practically rules the field of smartcontracts. Ethereum will be at the core of everything if decentralisation and Dapps start to dominate the current world.


The Ethereum Virtual Machine (EVM), a comprehensive 256-bit virtual machine that is strong but easy to use, is responsible for the Ethereum smart contract functionality. The Ethereum smartcontract's use of the solidity programming language is another noteworthy feature. The ERC20 token smartcontract, ERC721 smartcontract, ERC1400 smartcontract, and other Ethereum standards are just a few examples of how this smartcontract might be created.


Hyperledger


The Linux foundation introduced Ethereum, and Hyperledger is the next in line. This hyperledger has a number of frameworks, including hyperledger burrow, hyperledger fabric, hyperledger sawtooth, and hyperledger indy.


The fact that many programming languages may be used to create a smart contract on this platform, which is open-source and supported by IBM, led developers to choose it. Both plugin modules and high performance are supported by this Hyperledger platform. Go language is used to construct smartcontracts in one of hyperledger fabric's well-known frameworks.


Cardano


Smartcontracts are also developed using this Cardano platform. Cardano's primary goal, however, is to guarantee security and, through its innovative methodology, aims to deliver great scalability. The Plutus programming language, which is based on Haskell and functions as a functional programming language on this platform, is used to create smartcontracts.


EOS


The ultimate goal of the EOS is to facilitate industrial-scale decentralised apps by becoming the hub of decentralised operating systems. The most alluring feature of this platform's promise is its ability to: 


* Remove transaction fee 

* Conduct millions of transactions per second


In this case, WASM language is utilised to code in this platform, which helps to boost scalability. Speed, efficiency, safety, openness, and debugability are provided by this language tool.


TRON


The TRON platform's solidity language-written smartcontract may be implemented for enterprise-grade applications in any public or private network. Due to its high performance, increased scalability, high-performance storage, compatibility with EVM, multilingual support, and transaction as PoS capabilities, this platform is widely utilised.


NEM


The NEM platform uses code written in the popular JAVA programming language, which is convenient for many developers. This common programming language feature makes it less vulnerable than other coding-based smartcontracts.


A new version of NEM has been published to enhance blockchain functionality.


NEM's Mijin v.2 upgrade strengthened the security of the NEM blockchain. Since etherum can only process about 15 transactions per second, but NEM can handle about 100 transactions per second, this functionality freed up capacity for many additional capabilities in the NEM blockchain.


Stellar


Due to its simplicity and ease of use when compared to Ethereum and NEM, Stellar is thought of as one of the best blockchain platforms to develop smartcontracts. This platform is used by many businesses since it makes international payments easier. This platform is the oldest because it was introduced in 2014, according to some sources. Later, in 2017, it worked along with IBM and KlickEx to offer a cheap way to conduct international business.


Waves


The Waves platform, which was introduced in 2016, offers a way to apply blockchain technology. Additionally, it simplifies the creation and execution of smartcontracts. Although this platform's community is still modest compared to others', it is particularly ideal for crowd sales and ICO. And even if the platform isn't very customizable, it requires the creation of tokens and smartcontracts even though there won't be much need for technical terminology. The transaction procedure on the Waves platform is extremely quick and scalable.


NEO


NEO was created by "OnChain," a blockchain R&D business with offices in Shanghai, and is also referred to as the "Ethereum of China." NEO's mission is to spread the "Smart economy" network. Digital assets, digital identity, and smartcontracts all add up to a smart economy.

The NEO platform smartcontract, commonly known as "The SmartContract 2.0," is composed of three pieces and is written in Javascript and Solidity.


They are:

  • NeoVM
  • InteropService
  • DevPack

Tezos


Because they are written in the Michelson programming language, Tezos smartcontracts are distinctive. The Tezos project increases the security and dependability of smart contracts by employing formal verification on this platform, where the smartcontract code can be mathematically shown to adhere to specific criteria.


The unique benefit of this Tezos platform is that no specialised tools are required to construct business-oriented DApps, compilers won't be required to convert programmes into unintelligible bytecode, and it's simple to examine the smartcontract code.


Minter


The use of the Telegram Open Network's smartcontract is enabled via transactions involving the mint coin on the minter platform. A Telegram project is Telegram Open Network (TON). The TON Virtual Machine (TVM) technology is employed in TON smartcontracts, and ICOs are the primary technical instrument on this platform. Well, there are three distinct levels of language that this TON SmartContract can be written in: 


They are, 

  • Func - a high-level smart contract language similar to C++.
  • Fift - a stack-based prefix notation language.
  • Fift assembly - a low-level language that Func programs are compiled to.

Counterparty


This platform incorporates data into Bitcoin transactions, i.e. it uses the cryptocurrency's blockchain and allows contracts to be developed on it.


Polkadot 

It is an alternative to blockchain and is famous for its ability to host parachains, chains within chains, allowing more transactions than usual.


Print Friendly and PDF