[2] Unveiling The Blockchain: Testing Our Smart Contracts Locally With MetaMask

Abstract

Scroll for the English version of the article.

Nel seguente articolo, che prosegue la nostra serie riguardo lo sviluppo e l'integrazione di contratti intelligenti nella rete Blockchain Ethereum, ci preoccupiamo di interrogare il contratto distribuito nel precedente articolo con il Web Wallet MetaMask. Consigliamo vivamente la lettura dell'articolo precedente [https://neuralepisteme.blogspot.com/2024/08/unveiling-blockchain-1-lets-program.html].
 

Prepariamo l'ambiente locale

Procediamo da dove eravamo rimasti. spostiamoci, una volta aperto il terminale, nella cartella precedentemente creata con 
~cd Desktop/TruffleProject
 E assicuriamoci, su distrò Arch Based, che il sistema e i suoi pacchetti siano aggiornati, per non creare conflitti tra le versioni o errori di sicurezza con
~sudo pacman -Syu
~(password for admin required)
Nel precedente articolo abbiamo anche migrato il nostro contratto con truffle. Ma questo non è sufficiente per lavorare con più strumenti assieme come faremo oggi. Dunque compiliamolo con
~truffle compile
una volta che ci siamo assicurati di essere nella nostra cartella.

Differenze tra compilazione di un contratto e migrazione.
 Compilazione e migrazione sono due fasi distinte nel processo di sviluppo di un contratto intelligente su Ethereum.
1. Compilazione: È il processo di conversione del codice sorgente del contratto intelligente scritto in Solidity (o un altro linguaggio di programmazione per contratti) nel bytecode. Questo bytecode è eseguibile sulla Ethereum Virtual Machine (EVM). Durante la compilazione, viene anche generato l'ABI, che descrive come interagire con il contratto.
2.Migrazione: È il processo di distribuzione del bytecode compilato sulla blockchain Ethereum. La migrazione comporta l'invio di una transazione alla rete, che include il bytecode del contratto e può anche includere l'esecuzione iniziale di funzioni per configurare lo stato del contratto. Il contratto viene così distribuito sulla rete.

MetaMask.

Nel campo dello scambio di criptovalute, strumenti come MetaMask sono indispensabili. Lo presentiamo qui per comodità. MetaMask è un software utilizzato prevalentemente come estensione del nostro Browser o Mobile Appe che ci permette di avere un portafoglio virtuale dal quale intereagire con le criptovalute all'interno della rete Blockchain Ethereum, rete sulla quale stiamo sviluppando i nostri contratti.
L'applicativo, utilizzando una libreria JavaScript particolare (web3.js, per i nostri appassionati di JS), permette l'accesso alla rete di transazione decentralizzata; una sorta di banca online su rete decentralizzata. E' opportuno far notare che questa banca virtuale ha però una commissione abbastanza alta, per compensare infrastrutture e costi energetici di transazione estremamente alti, Dalla sua parte ha l'estrema sicurezza delle transazioni: oltre a trattarsi di commissioni già crittografate essendo su una rete blockchain, queste sono salvate univocamente sulla rete e la chiave asimmetrica al nostro portafoglio è univoca, questo significa che non sarà possibile collegarla a due dispositivi contemporaneamente. Notiamo inoltre che questa chiave può essere settata una sola e unica volta, quindi non ci sarà possibile accedere nuovamente al conto una volta smarrita la nostra chiave di accesso, poiché la chiave viene crittografata per sempre.

Installazione
Potete decidere se insallare Metamask come estensione del Browser (visitando la pagina ufficiale MetaMask o visitando lo store delle estensioni del Browser che state utilizzando) oppure dallo Store del vostro Smartphone. Fatto quest, configuratelo creando un nuovo portafoglio, accettando i termini e le condizioni di servizio e impostando una password (che si consiglia essere articolata per aumentarne la sicurezza). Fatto ciò annotate la frase di backup in un luogo sicuro, che vi permetterà di recuperare il fondo totale del portafoglio qualora doveste per qualche motivo smarrirne le chiavi di accesso.
Per seguire questo tutorial sarà necessario installare MetaMask come estensione del vostro browser, poiché stiamo lavorando in locale, evitandoci spese di Gas Fee.

Colleghiamo i nostri strumenti.

Ora che tutto è sistemato, preoccupiamoci di collegare le varie strumentazioni messe in campo. Se l'ultima volta avete distribuito il contratto correttamente dovreste essere riusciti a interrrograrlo con il programma API.py ricavato dalla repository, o ancora meglio con il vostro personalizzato.
Avviate Ganache e MetaMask. Da qui, connettetevi a una nuova rete, cliccando su rete personalizzata e usando l'URL RCP di Ganache https://127.0.0.1:7545] per connettervi all'HTTP Provider locale.
Scegliete ora, dall'interfaccia di Ganache, un account qualsiasi, da cui importare la chiave privata per il vostro portafoglio online. Non si tratta dell'address sulla sinistra, ma dell'icona a forma di chiave sulla destra di ogni account. Ottenuta la chiave potrete inserirla all'interno del vostro wallet e collegarvi definitivamente alla rete Locale Ganache.

Interroghiamo il contratto

Spostiamoci nella sezione "Importa Token" di MetaMask e inseriamo l'indirizzo del contratto intelligente distribuito tramite Ganache. Questo indirizzo, come prima specificato, può essere trovato nell'interfaccia di Ganache sotto la sezione "Contracts" dopo aver distribuito il contratto.
Se avete seguito completamente il tutorial con i file importati dalle repository github, rimandiamo nuovamente ad un applicativo sviluppato ad hoc per il tutorial: INT_CONTRACT.py [https://github.com/ZanelloG/migration-files/tree/main]. Lanciatelo sulla vostra riga di comando una volta copiato correttamente nella cartella GanacheProject e potrete, tramite la schermata, scegliere quale azione testare sul contratto intelligente. MetaMask si occuperà di gestire le transazioni, e non dovrete preoccuparvi dei costi poiché come detto si tratta di una rete di test locale. Se le funzioni sono state chiamate correttamente e il contratto efficacemente migrato e compilato, vedrete le interazioni con questo dalla vostra interazione INT_CONTRACT al portafoglio MetaMask, e potrete verificare da voi le poerazioni con il contatore

Conclusioni

Il seguente articolo ci ha mostrato come settare MetaMask per intereagire con i nostri contratti intelligenti e come un semplice applicativo python può gestirli. L'intera serie può essere replicata sull'ambiente Ethereum, ma prima di farlo assicuratevi di aver testato i contratti su Ganache come abbiamo visto oggi e che i costi di rete non siano insormontabili. Nei prossimi articoli approfondiremo la questione e ci occuperemo di scrivere diversi tipi di contratti intelligenti, compresi quelli per i vostri personali NFT. 

English Version.

In this article, which continues our series on the development and integration of smart contracts on the Ethereum Blockchain network, we will look into how to interact with the contract deployed in the previous article using the MetaMask Web Wallet. We highly recommend reading the previous article [https://neuralepisteme.blogspot.com/2024/08/unveiling-blockchain-1-lets-program.html].

 

Setting Up the Local Environment

Let’s pick up where we left off. Once you open the terminal, move to the folder created earlier with the command:  
 ~cd Desktop/TruffleProject
Make sure, if you’re using an Arch-Based distro, that the system and its packages are up-to-date to avoid version conflicts or security errors with:  
 ~sudo pacman -Syu
~(password for admin required)
In the previous article, we also migrated our contract using Truffle. But this is not enough when working with multiple tools simultaneously, as we will do today. So, let’s compile it with:  
~truffle compile
once we are in the correct folder.

Differences Between Compiling and Migrating a Contract

Compilation and migration are two distinct phases in the development process of a smart contract on Ethereum.

1. Compilation: This is the process of converting the source code of the smart contract, written in Solidity (or another contract programming language), into bytecode. This bytecode is executable on the Ethereum Virtual Machine (EVM). During compilation, an ABI (Application Binary Interface) is also generated, which describes how to interact with the contract.
   
2. Migration: This is the process of deploying the compiled bytecode onto the Ethereum blockchain. Migration involves sending a transaction to the network, which includes the contract bytecode and may also include the initial execution of functions to set up the contract’s state. The contract is thus deployed on the network.
 

MetaMask

In the field of cryptocurrency exchange, tools like MetaMask are essential. We introduce it here for convenience. MetaMask is a software primarily used as a browser extension or mobile app, allowing us to have a virtual wallet from which to interact with cryptocurrencies on the Ethereum Blockchain network, the network on which we are developing our contracts.  
The application, using a specific JavaScript library (web3.js, for our JS enthusiasts), provides access to the decentralized transaction network; a sort of online bank on a decentralized network. It's worth noting that this virtual bank has a fairly high fee to compensate for infrastructure and extremely high transaction energy costs. On the plus side, the transactions are extremely secure: in addition to the fact that these transactions are already encrypted being on a blockchain network, they are uniquely saved on the network, and the asymmetric key to our wallet is unique. This means that it cannot be linked to two devices simultaneously. Additionally, this key can only be set once, so if you lose your access key, you will not be able to access your account again, as the key is encrypted forever.
 

Installation

You can choose to install MetaMask as a browser extension (by visiting the official MetaMask page or the browser's extension store) or from your smartphone's app store. Once installed, set it up by creating a new wallet, accepting the terms and conditions of service, and setting a password (which should be complex to increase security). After this, write down the backup phrase in a safe place, as it will allow you to recover the total balance of your wallet in case you lose your access keys.  
To follow this tutorial, you will need to install MetaMask as a browser extension, as we are working locally, avoiding gas fee expenses.

Connecting Our Tools

Now that everything is set up, let’s connect the various tools we are using. If you have deployed the contract correctly last time, you should have been able to interact with it using the API.py program obtained from the repository, or even better, your customized version.  
Start Ganache and MetaMask. From here, connect to a new network by clicking on "Custom RPC" and using Ganache's RPC URL `https://127.0.0.1:7545` to connect to the local HTTP provider.  
Now, choose any account from Ganache's interface from which to import the private key for your online wallet. This is not the address on the left but the key icon on the right of each account. Once you have obtained the key, you can enter it into your wallet and connect to the local Ganache network.

 

Interacting with the Contract

Go to the "Import Token" section of MetaMask and enter the address of the smart contract deployed through Ganache. This address, as specified earlier, can be found in Ganache's interface under the "Contracts" section after deploying the contract.  
If you have fully followed the tutorial with the files imported from the GitHub repositories, we refer again to an application developed specifically for the tutorial: INT_CONTRACT.py [https://github.com/ZanelloG/migration-files/tree/main]. Run it on your command line once it is correctly copied into the GanacheProject folder, and you will be able to select which action to test on the smart contract through the screen. MetaMask will handle the transactions, and you won't have to worry about costs since it is a local test network. If the functions have been correctly called and the contract effectively migrated and compiled, you will see the interactions with it from your INT_CONTRACT interface to the MetaMask wallet, and you will be able to verify the operations with the counter.
 

Conclusions

This article showed us how to set up MetaMask to interact with our smart contracts and how a simple Python application can manage them. The entire series can be replicated on the Ethereum environment, but before doing so, make sure to have tested the contracts on Ganache as we saw today, and that the network costs are not prohibitive. In the upcoming articles, we will delve deeper into the topic and write different types of smart contracts, including those for your personal NFTs.

Commenti