[1] Unveiling the Blockchain: let's program a simple smart contract to deploy on a local Ethereum network.
Abstract
Scroll for the English version of the article.
Nel seguente articolo ci proponiamo di sviluppare dei semplici smart contracts per la blockchain Ethereum fornita da Ganache in modo totalmente gratuito e in locale sul nostro comupter; Ganache infatti ci permette di usufruire della tecnologia Blockchain in modo gratuito (stabilito un limite di dieci account) e senza costi di Gas che rallenterebbero le nostre esercitazioni, rendendole dispendiose.
I prerequisiti saranno un minimo di conoscenza dell’argomento blockchain (trattato anche dal punto di vista filosofico nel precedente articolo), un base solida di programmazione in python e una comprensione quanto meno generale della sintassi di Solidity, per i nostri smart contracts.
Passo primo: installiamo Ganache.
Procederemo con l’installazione di Ganache sul nostro computer collegandoci al sito ufficiale [https://archive.trufflesuite.com/ganache/] e scaricando il programma per il nostro sistema operativo. Si precisa che il tutorial seguirà su un sistema Unix (Linux) Manjaro per comodità di utilizzo dalla riga di comando e per un maggior controllo degli strumenti in campo, ma può esssere replicato su qualsiasi altro sistema operativo avendo cura di certe modifiche. Sarà innanzitutto necessario installare il programma per l’OS corrispondente. Procedete quindi pure sulla repository ufficiale GitHub di Trufflesuite Ganache [https://github.com/trufflesuite/ganache-ui/releases]e abbiate cura di scaricare il file compatibile con il vostro sistema operativo.Fatto questo, procedete al normale processo di installazione su sistemi non Linux. Per quanto riguarda questi ultimi invece, spostatevi da terminale nella directory contentente il vostro file .AppImage (si suppone quella dei Downloads) e cambiate i permessi del file in modo che sia eseguibile con il comando chmod +x, dove l’argomento x sta appunto ad indicare la possibilità del file di essere eseguito. Per semplicità di esecuzione rinomineremo il file all’interno della cartella in questo modo:
~mv /your/directory/nome_file_download.AppImage /your/directory/ganache.AppImage
e poi, quindi
~chmod +x /your/directory/ganache.AppImage
A questo punto spostiamo il file nella cartella bin, affinché sia eseguibile da ogni percorso del nostro terminale, e quindi:
~mv /your/directory/ganache.AppImage /usr/local/bin/ganache/
A questo punto il file sarà eseguibile con il semplice comando, dovunque voi vi troviate con il percorso file
~ganache
ed ecco che automaticamente si avvierà il servizio.
Sviluppiamo gli smart contracts da distrubiure
Per lo sviluppo degli smart contracts da distribuire sulla rete Ethereum ci faremo aiutare da un’altra tecnologia molto potente e versatile, ancora una volta ottimizzata grazie alla linea di comando: truffle. Questo è una serie di strumenti che consente a chiunque di sviluppare agevolmente applicazioni, come gli smart contracts, utilizzando una EVM, una Ethereum Virtual Machine, che può essere pensata come una scatola chiusa contentente in sintesi tutte le caratteristiche della rete Ethereum vera e propria. Questa suite di strumenti ci agevola anche nell’impostazione del lavoro nel modo che ora andremo ad esplorare.E’ doveroso allora installare questo strumento utilissimo. Lo faremo attraverso un gestore dei pacchetti poco differente dal pacman dei sistemi Unix Arch Based (sui Debian Base il rispettivo apt-get), nmp. Procediamo con
~sudo pacman -S nmp nodejs
per installare sia nmp che node.js, che verrà più tardi in nostro aiuto.
Fatto ciò, rispetto alla directory in cui ci troviamo con il nostro terminale (ricordandovi che è possibile ottenere tale informazione con il comando pwd, oppure cliccare con il tasto destro sull’ambiente desktop che volete visualizzare e successivamente su “Apri Terminale”), creiamo una nuova cartella per contenere i nostri file, dunque:
~mkdir TruffleProject
spostiamoci nella cartella con cd TruffleProject e avviamo il rogramma perché faccia un po’ di lavoro sporco al posto nostro:
~truffle init
Questo creerà automaticamente le dipendenze e i file utili al funzionamento delle nostre applicazioni in solidity.
Muoviamoci con cd presso la directory di nostro interesse, ossia contracts/ e nella seguente creiamo o importiamo il nostro Smart Contract file.sol. La scrittura di Solidity non si allontana molto dalla sintassi di JavaScript ed è comprensibile anche a coloro che hanno familiarità con altri linguaggi di programmazione quali Python e Java. Potete sbizzarrirvi a creare contratti Solidity a vostro piacimento, ma per non dovervi focalizzare principalmente sulla scrittura del contratto vi rimando ad una repository GitHub con semplici contratti Solidity utilizzabili ai nostri fini [https://github.com/ZanelloG/simple_contracts].
Migrazione dei contratti Solidity:
Per migrazinoe di Smart Contracts all’interno del contesto Ganache-Truffle si intende l’atto di scrittura di un file (tipicamente in linguaggio JavaScript) che indichi all’operazione truffle migrate quali contratti da noi creati vogliamo compilare e distribuire sulla rete EVM in modo tale che questi possano essere utilizzati sulla rete da altre applicazioni o utenti (si approfondisca l’attributo “public” in contesto del linguaggio Solidity per maggiore chiarezza su questo contenuto). Compilare il contratto significa inoltre tradurre il codice Solidity da noi scritto in bytecode Ethereum, linguaggio non intermedio comprensibile dalla macchina virtuale Ethereum. Questo processo produce anche l'Application Binary Interface (ABI), che è necessaria per interagire con il contratto una volta distribuito.
Spostiamoci dunque nella cartella principale TruffleProject/ e accediamo a migrations/, dove creeremo un nuovo file di migrazione riferito al nostro contratto pocanzi creato. Ancora, i file di migrazione hanno diverse specifiche che qui ora noi non tratteremo, ma potete riferirvi ancora una volta ad una repository GitHub ad hoc, premurandovi di copiare e incollare il file JavaScript “simple_migration.js” dalla repository e incollarlo nella cartella sopra citata [https://github.com/ZanelloG/migration-files]. Ricordate di sostituire SimpleStorage con il nome del file .sol da voi creato.
Fatto ciò, chiediamo a truffle di migrare il file per noi
~truffle migrate
Intereagiamo con il nostro contratto: Python.
Ora che abbiamo depositato la nostra creatura sulla complessa rete di Ethereum dobbiamo interfacciarci con lei. In questo ci viene in soccorso Python e in particolare la libreria web3, scritturata appositamente per comunicare con le reti blockchain del web di terza generazione.Installiamo dunque questa libreria Python con il nostro gestore dei pacchetti python pip
~pip install web3
Se doveste riscontrare problemi riguardo al managing dei file (ex. externally-managed-enviroment Error) basteà specificare
~pipx install web3
così da permettere a pipx di gestire automaticamente le dipendenze delle librerie python.
Controlliamo ora che web3 sia stato installato correttamente lanciado i comandi
~python3
per aprire la finestra python e poi
>>>import web3
Se non riceviamo nessun codice di errore la libreria è stata correttamente installata; usciamo pure dall’emulatore python con
>>>exit()
Sempre dalla repository [https://github.com/ZanelloG/migration-files] utilizzate il file API.py dalla vostra riga di terminale con
~python3 API.py
avendo cura di trovarvi nella cartella corretta. Inserito l’API e l’Address dello smart contracts che avete precedentemente ricavato con l’operazione di truffle migrate dovreste riuscire ad intereagire con il vostro smart contract sulla rete Ganache, se questa è avviata correttamente sul vostro computer.
Conclusioni
Ecco a voi spiegato come la tecnologia blockchain è facilmente monitorabile, nei suoi livelli basilari, con conoscenze di informatica basilari. Qualora vi doveste trovare in difficoltà siete sempre ben accolti nell’aprire un thread nei commenti e verrete presto aiutati.Nel prossimo articolo implementeremo questa struttura e la discuteremo da un punto di vista concettuale. Lasciate un commento e seguite Neural Episteme su X [https://x.com/giosue_zanello/]. Per rimanere sempre aggiornati sui vari progetti informatici e filosofici in corso iscrivetevi al Blog e restate connessi.
Key Words: Smart Contract; Ethereum; Solidity; Deployment; Blockchain; Local Network; Web3; Python
English version:
Prerequisites include a basic understanding of blockchain (discussed philosophically in the previous article), a solid foundation in Python programming, and at least a general grasp of Solidity syntax for our smart contracts.
First Step: Installing Ganache
We will start by installing Ganache on our computer. Visit the official website (https://archive.trufflesuite.com/ganache/) and download the appropriate version for your operating system. This tutorial will be demonstrated on a Unix (Linux) Manjaro system for ease of use via the command line and better control of the tools involved, but the process can be replicated on other operating systems with minor adjustments. Begin by downloading the program from the official Trufflesuite Ganache GitHub repository [https://github.com/trufflesuite/ganache-ui/releases] and ensure you download the file compatible with your OS.After downloading, follow the standard installation process for non-Linux systems. For Linux systems, navigate to the directory containing your .AppImage file (typically the Downloads folder) and change the file permissions to make it executable with the command `chmod +x`, where `x` allows the file to be executed. For simplicity, rename the file within the folder:
~mv /your/directory/filename_download.AppImage /your/directory/ganache.AppImage
Then, execute:
~chmod +x /your/directory/ganache.AppImage
Move the file to the `bin` directory so it can be run from any location in your terminal:
~mv /your/directory/ganache.AppImage /usr/local/bin/ganache/
Now, the file can be executed simply with the command:
~ganache
The service will start automatically.
Developing Smart Contracts
To develop the smart contracts for deployment on the Ethereum network, we will use another powerful and versatile tool, Truffle. Truffle is a suite of tools that facilitates the development of applications, such as smart contracts, using an Ethereum Virtual Machine (EVM), which can be thought of as a closed box containing all the features of the real Ethereum network. This suite of tools also helps in setting up the work environment.First, we need to install Truffle. We will use a package manager similar to pacman on Unix Arch-based systems (on Debian-based systems, the equivalent is apt-get), namely npm. Install npm and node.js with:
~sudo pacman -S npm nodejs
Once installed, create a new directory for your files:
~mkdir TruffleProject
Navigate into the directory with `cd TruffleProject` and initialize Truffle:
~truffle init
This will automatically create the dependencies and files needed for your Solidity applications.
Move to the `contracts/` directory and create or import your smart contract file `file.sol`. Solidity syntax is quite similar to JavaScript and is understandable for those familiar with other programming languages such as Python and Java. You can create Solidity contracts as you wish, but to avoid focusing primarily on contract writing, refer to this GitHub repository for simple Solidity contracts suitable for our purposes [https://github.com/ZanelloG/simple_contracts].
Migrating smart contracts in the Ganache-Truffle context involves writing a file (typically in JavaScript) that tells the `truffle migrate` operation which of our created contracts we want to compile and deploy on the EVM network so they can be used by other applications or users (refer to the “public” attribute in Solidity for clarity). Compiling the contract also means translating the Solidity code into Ethereum bytecode, a language understood by the Ethereum virtual machine. This process also produces the Application Binary Interface (ABI), which is necessary for interacting with the contract once deployed.
Navigate to the `TruffleProject/` directory and access `migrations/`, where you will create a new migration file for your newly created contract. Migration files have specific requirements which we won’t cover here, but you can refer to this GitHub repository for the necessary JavaScript migration file “simple_migration.js” [https://github.com/ZanelloG/migration-files]. Make sure to replace `SimpleStorage` with the name of your `.sol` file.
After creating the migration file, instruct Truffle to migrate it:
~truffle migrate
Interacting with Your Contract: Python
Now that your contract is deployed on the Ethereum network, you need to interact with it. For this, Python and the `web3` library come in handy. The `web3` library is specifically designed to communicate with third-generation blockchain networks.Install the `web3` library using pip:
~pip install web3
If you encounter issues with file management (e.g., externally-managed-environment error), use:
~pipx install web3
this will allow `pipx` to handle the library dependencies automatically.
Verify the installation by running:
~python3
>>> import web3
If no errors appear, the library is installed correctly. Exit the Python interpreter with:
>>> exit()
From the repository [https://github.com/ZanelloG/migration-files], use the `API.py` file from your terminal:
~python3 API.py
Ensure you are in the correct directory. Enter the API and the address of the smart contract obtained from the `truffle migrate` operation. You should be able to interact with your smart contract on the Ganache network if it is running correctly on your computer.
Conclusions
This guide demonstrates how blockchain technology can be easily monitored at its basic levels with fundamental computing knowledge. If you encounter difficulties, feel free to open a thread in the comments, and you will receive help promptly.In the next article, we will build on this structure and discuss it from a conceptual perspective. Leave a comment and follow Neural Episteme on X [https://x.com/giosue_zanello/]. To stay updated on ongoing IT and philosophical projects, subscribe to the blog and stay connected.

Commenti
Posta un commento