Web3 Solidity Connector

Overview

Web3 Solidity Connector

With this project, you can compile your sol files and create new transactions including creating contract and calling the state changer functions. You can integrate integrate your sol files with Python and you can call functions with using Python.

Program Life Cycle

  1. Compile the Solidity(.sol) file
  2. Deploy the contract which is in Solidity file
  3. Manipulate the main.py file for calling and executing relevant functions in contract even with parameters via the help of Web3

Folder Structure

To assure the program is working, there are folder structure rules to follow.

  1. This projects points to sol_files folder for your Solidity files. This means sol_files folder must contain your .sol extensioned files. You should select one of the sol file in this directory to be compiled.

  2. After you execute compile.py, "compilation_files_out" folder will be created which contains your output files. "compiled_abi.json" and "compiled_bytecode.txt" files should not be deleted or overwritten! You can examine your compiled code in "compiled_code.json" file.

  3. global_variables.py file contains your default paths for compilation files and the sol files that will be compiled. You can change this structure any way you want.

GLOBAL_COMPILATION_PATH = "./compilation_files_out"  # folder that contains output files
GLOBAL_SOL_PATH = "./sol_files"  # folder that contains sol file

Running the Program

  1. Clone the repository
git clone https://github.com/TekyaygilFethi/ContractDeploment.git
  1. Create an .env file on current folder that contains your address(with MY_ADDRESS key), private key(with PRIVATE_KEY key), rinkeby rpc url(with RINKEBY_RPC_URL key) and chain id(with CHAIN_ID key) values. Your .env file should look like this:
PRIVATE_KEY ="0x{YOUR PRIVATE KEY}"
RINKEBY_RPC_URL = "{YOUR RINKEBY RPC URL}"
MY_ADDRESS = "{YOUR ADDRESS}"
CHAIN_ID = "{YOUR CHAIN ID}"
  1. Install the dependencies from requirements.txt file.
pip install -r requirements.txt
  1. After setting the .env file, to run the program, you first need to go to the project directory and run:
python compile.py {YOUR_SOL_FILE} // python compile.py SimpleContract.sol

! Please note that your sol files must be in the folder sol_files folder by default or in the folder you specified custom in global_variables.py file by assigning to GLOBAL_SOL_PATH.

  1. After compilation you should see screen like this:
Compilation folder created!
Compiled successfully!
  1. When you check your folders, you can see compilation_files_out folder is created. If you changed the folder path and name from global_variables you may see different folder. This folder be based on when deploying your contracts and running your Solidity functions!

  2. For next step, you must deploy your compiled contract. To do this, you must run:

python deploy.py

This command will creates a transaction for contract creation based on your compiled Solidity file. This command will output the success message, transaction receipt and contract address. To use this deployed contract and it's functions, you must copy the address of this deployed contract. You should see response like this (Please note that receipt and address may differ)

New Contract Transaction has been created!

AttributeDict({'transactionHash': HexBytes('0x19f1237cd0bf13bf1112f7e60b9dd7570dcca38c18718368e09c462e01482272'), 'transactionIndex': 0, 'blockHash': HexBytes('0xa47912b38dec2fdecfed283da5fd6a7d778def3f62bc2c629373903cbd5f59bc'), 'blockNumber': 34, 'from': '0x2DAc2487DD401D9E5C757eb03B8928b70FFaFe6e', 'to': None, 'gasUsed': 640222, 'cumulativeGasUsed': 640222, 'contractAddress': '0x874E06Aff5a1031Bd5AE07100A7A518D0C72b8E2', 'logs': [], 'status': 1, 'logsBloom': HexBytes('0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000')})

Contract Address: 0x874E06Aff5a1031Bd5AE07100A7A518D0C72b8E2 //This address you should copy.
  1. Edit your main.py content according to your functions. For example, I have addHero function in my compiled Solidity:
struct Hero {
    string name;
    string lightsaberColor;
    uint256 age;
}

Hero[] heroes;

function addHero(
        string memory _name,
        string memory _lightsaberColor,
        uint256 _age
    ) public {
        heroes.push(Hero(_name, _lightsaberColor, _age));
        uint256 idx = heroes.length - 1;
        nameToIndex[_name] = idx;
    }

You can call this function from my main.py file with parameters like this:

# write functions with their parameters if any after this line inside of executeContractFunction method.
contractOps.executeContractFunction(
    # write your contract functions as contract.functions.{your function}, your private key
    contract.functions.addHero("Obi-Wan Kenobi", "Blue", 29),
    private_key,
)

Here, contractOps is an object that allows you to perform contract operations such as creating, deploying, gathering contracts or executing a function inside a contract. And executeContractFunction is a special function that allow you to execute a functions. It creates, signs, sends and gets the receipt for transaction automatically.

  • If you have a function that is not changing a state in Solidity file you also can call it. For example here's the function that is not changing state in my Solidity file:
function getInfoByName(string memory name)
        public
        view
        returns (Hero memory)
    {
        uint256 idx = nameToIndex[name];
        return heroes[idx];
    }

function getAllHeroes() public view returns (Hero[] memory) {
        return heroes;
    }

You can call the getAllHeroes function like this:

print(contract.functions.getAllHeroes().call())

You can call the getInfoByName function which takes parameter like this:

print(contract.functions.getInfoByName("Obi-Wan Kenobi").call())

Please note that we had to use .call() at the end of the function call to gather response and make the function call.

  1. To run main.py file, you need to supply contract address. You should use the contracty address you copied at Step 6.
python main.py {ContractAddress}

Here is an example:

python main.py 0x874E06Aff5a1031Bd5AE07100A7A518D0C72b8E2

And you can see the results when you execute this command: Result

And you're done! Congratulations!

Owner
Fethi Tekyaygil
.NET Core Backend & @google Certified #tensorflow Developer - Flutter & Solidity #padawan - Animal Person
Fethi Tekyaygil
to learn how to do pull request and do contribution to other's repo

Hacktoberfest-2021 - open-source-contribution An Open Source repository to Teach people How to contribute to open sources. 💥 🔥 JOIN PVX PROGRAMMING

Shubham Rawat 82 Dec 26, 2022
Empresas do Brasil (CNPJs)

Biblioteca em Python que coleta informações cadastrais de empresas do Brasil (CNPJ) obtidas de fontes oficiais (Receita Federal) e exporta para um formato legível por humanos (CSV ou JSON).

BR-API: Democratizando dados do Brasil. 8 Aug 17, 2022
ThinkPHP全日志扫描工具,命令行版和BurpSuite插件版

ThinkPHP3和5日志扫描工具,提供命令行版和BurpSuite插件版,尽可能全的发掘网站日志信息 命令行版 安装 git clone https://github.com/r3change/TPLogScan.git cd TPLogScan/ pip install -r requireme

119 Dec 27, 2022
The Doodle Master seeks to turn your UI mockups into real code.

Doodle Master The Doodle Master seeks to turn your UI mockups into real code. Currently this repository just serves to demonstrate a Proof Of Concept

Karanbir Chahal 2.4k Dec 09, 2022
A faster Python generator that get function results from multi-process workers

multiyield This package implements a Python generator that get function results from multi-process workers. The faster_fifo Queue (instead of the stan

Xin Du 1 Nov 18, 2021
Цифрова збрoя проти xуйлoвської пропаганди.

Паляниця Цифрова зброя проти xуйлoвської пропаганди. Щоб негайно почати шкварити рашистські сайти – мерщій у швидкий старт! ⚡️ А коли ворожі сервери в

8 Mar 22, 2022
Traductor de webs desde consola usando el servicio de Google Traductor.

proxiGG Traductor de webs desde consola usando el servicio de Google Traductor. Se adjunta el código fuente para Python3 y un binario compilado en C p

@as_informatico 2 Oct 20, 2021
A script to automatically update bot status at GitHub as well as in Telegram channel.

A simple & short repository to show your bot's status in your GitHub README.md file as well as in you channel.

Jainam Oswal 55 Dec 13, 2022
Medical appointments No-Show classifier

Medical Appointments No-shows Why do 20% of patients miss their scheduled appointments? A person makes a doctor appointment, receives all the instruct

4 Apr 20, 2022
Transparently load variables from environment or JSON/YAML file.

A thin wrapper over Pydantic's settings management. Allows you to define configuration variables and load them from environment or JSON/YAML file. Also generates initial configuration files and docum

Lincoln Loop 90 Dec 14, 2022
Better Giveaways is a bot that will change the experience of using a giveaway bot forever.

Better-Giveaways Better Giveaways is a bot that will change the experience of using a giveaway bot forever. VoxelBotUtils/Novus, latest PyPi releases

Lightning 2 Jan 12, 2022
Test pour savoir si je suis capable de paratger une lib avec le monde entier !!

Data analysis Document here the project: MLproject Description: Project Description Data Source: Type of analysis: Please document the project the bet

Lucas_Penarrubia 0 Jan 18, 2022
The program calculates the BMI of people

Programmieren Einleitung: Das Programm berechnet den BMI von Menschen. Es ist sehr einfach zu handhaben, so können alle Menschen ihren BMI berechnen.

2 Dec 16, 2021
Some shitty programs just to brush up on my understanding of binary conversions.

Binary Converters Some shitty programs just to brush up on my understanding of binary conversions. Supported conversions formats = "unsigned-binary" |

Tim 2 Jan 09, 2022
Mechanized literally means automation.

Mechanized literally means automation. And this branch which you are now observing is automated by the python script. This python project actually automates my workflow related to Git & Github.

Shreejan Dolai 4 Nov 11, 2022
An event-based script that is designed to improve your aim

Aim-Trainer Info: This is an event-based script that is designed to improve a user's aim. It was built using Python Turtle and the Random library. Ins

Ethan Francolla 4 Feb 17, 2022
A tool that bootstraps your dotfiles ⚡️

Dotbot Dotbot makes installing your dotfiles as easy as git clone $url && cd dotfiles && ./install, even on a freshly installed system! Rationale Gett

Anish Athalye 5.9k Jan 07, 2023
A simple Programming Language

R.S.O.C. A custom built programming language About The Project R.S.O.C. is a custom built programming language very similar to a low-level 8085 progra

Ravi Maurya 17 Sep 13, 2022
This is a multi-app executor that it used when we have some different task in a our applications and want to run them at the same time

This is a multi-app executor that it used when we have some different task in a our applications and want to run them at the same time. It uses SQLAlchemy for ORM and Alembic for database migrations.

Majid Iranpour 5 Apr 16, 2022
DOP-Tuning(Domain-Oriented Prefix-tuning model)

DOP-Tuning DOP-Tuning(Domain-Oriented Prefix-tuning model)代码基于Prefix-Tuning改进. Files ├── seq2seq # Code for encoder-decoder arch

Andrew Zeng 5 Nov 02, 2022