Gli sviluppatori di Ethereum di solito si basano su Infura o Alchemy per un facile accesso ai nodi di Ethereum. GetBlock è un'alternativa attraente che fornisce supporto multi-chain, un livello gratuito generoso e un'eccellente stabilità. In questo tutorial, scoprirai come migrare un backend Truffle + web3.js da Infura/Alchemy a GetBlock. Iscriversi a GetBlock, per ottenere un endpoint RPC, Ripristinare il trucco, test di connettività web3, eseguire il distacco, e confronto dei limiti di interesse e monitoraggio delle differenze. Hai bisogno di un progetto Ethereum DApp esistente con Truffle, e Node.js installato. Suppongo che tu abbia usato Infura o Alchemy (con un ID del progetto o una chiave API) e abbia una chiave mnemonica o privata disponibile per la distribuzione. Prerequisites: Perché passare da Infura o Alchemy a GetBlock? GetBlock allows you to connect to not just Ethereum but 55+ blockchain networks using JSON-RPC, REST, and WebSocket APIs. This allows you to use Ethereum, Bitcoin, BNB Smart Chain, Polygon, Solana, and a lot of others with one platform. Infura and Alchemy, meanwhile, have a shorter list of networks supported (Infura supports Ethereum primarily and some networks like IPFS or certain L2s, and Alchemy supports Ethereum and some chains but not BSC specifically). If your DApp can be more than Ethereum, the broad multi-chain support of GetBlock is a huge plus. Multi-chain support. Each of these providers has free plans, but their limitations and models are different. Infura's free plan conventionally provided around 50,000 requests per day (now measured as 3 million daily credits with some rate limiting). Alchemy's free tier offers up to 100 million compute units a month (Alchemy measures different RPC calls as different "compute units"). GetBlock's free tier is very developer-friendly: it offers 50,000 requests a day (reset daily) with a limit of 5 requests a second. Practically, 50k daily calls are sufficient for development and small DApps, and you can always upgrade in case you need more. The free plan is indeed free ("zero fees") and still allows access to all supported chains. The key takeaway here is that GetBlock's free plan should be more than sufficient for typical dev and testing demands. Generous free tier. GetBlock offers a 99.9% uptime guarantee with a stable 24/7 connection to blockchain networks. That is, you can expect a highly stable service for your DApp backend. Stability is also what Infura and Alchemy are famous for, but GetBlock's infrastructure is built to be rock-solid and scalable. Many developers appreciate the fact that GetBlock provides both shared nodes (with usage limits) and dedicated nodes for heavier workloads, so you have a way to scale up. The correct answer is that the platform is highly reliable, so you won't see variations in network uptime when you switch over – possibly except for better performance in certain instances. Stability and uptime. Infine, il dashboard di GetBlock ha alcune grandi capacità di monitoraggio e analisi, che arriveremo presto. Passo 1: Registrati per un account GetBlock Il primo passo è registrarsi per un account GetBlock gratuito: Navigate to the GetBlock website and click on "Sign Up" (or directly visit the GetBlock dashboard sign-up page). You have a few sign-up options: Email/Password. Sign up using email and choose a password. Social Login. Use Google or GitHub to sign up immediately. Web3 Wallet. You can even sign up by connecting a MetaMask wallet (no email required). This is a great option for developers who are already set up on MetaMask. Scegli il tuo metodo preferito e procedi con le istruzioni (ad esempio, verifica la tua e-mail se hai scelto di iscriversi all'e-mail). Dovresti avere il tuo account GetBlock in un minuto o due. Nota: il dashboard GetBlock è dove gestirai i tuoi endpoint API, monitorerai l'utilizzo e regolerai le impostazioni. Andare avanti e guardarti intorno una volta registrato. Vedrai il tuo ID utente nelle impostazioni dell'account (utile se hai mai bisogno di supporto), ma più importante, configurerai i endpoint del progetto successivamente. Passo 2: Ottieni il tuo GetBlock RPC Endpoint (API Key e URL) L'account creato, ora avrai bisogno di creare un endpoint RPC per la rete Ethereum (o qualunque rete avrai bisogno). Questo ti fornirà un URL HTTP (e l'URL WebSocket corrispondente se necessario) che utilizzerai al posto di Infura/Alchemy. Creare un nuovo endpoint: Nel GetBlock Dashboard, trovare il pulsante "Create Endpoint" o "Add New Endpoint". Select the blockchain network. As in our case, choose Ethereum from the list of available protocols. Then select the network type: For Ethereum Mainnet, choose Mainnet. For a testnet, choose the specific test network (GetBlock now supports Ethereum Sepolia). Opzionalmente fornire un nome / etichetta per questo endpoint (ad esempio, "MyDApp Ethereum Mainnet") per rendere più facile per voi di tenere traccia nel caso in cui si configurano più di un endpoint. Fare clic su Creare o confermare. Il pannello di controllo genererà i dettagli del tuo endpoint. Dopo la creazione, dovresti vedere un URL RPC per il tuo endpoint. Copia questo URL; lo passerai nella tua configurazione Truffle. GetBlock può mostrarti un URL WebSocket (cominciando con wss://) per lo stesso endpoint, e quando la tua applicazione richiede WebSockets (per abbonamenti o eventi dal vivo), puoi utilizzarlo. Conservare la chiave API GetBlock in modo sicuro. Non impegnarla in un repos pubblico o in un codice client. La migliore pratica è memorizzarla come variabile ambientale o configurare il file al di fuori del controllo sorgente. di importante. Ora hai un URL di endpoint GetBlock e una chiave API pronta per l'uso. Passo 3: Cambiare la configurazione di Truffle per utilizzare GetBlock Il tuo (o di Se si utilizza Infura o Alchemy, la configurazione potrebbe avere un aspetto simile per una rete: truffle-config.js truffle.js require('dotenv').config(); const HDWalletProvider = require('@truffle/hdwallet-provider'); const INFURA_PROJECT_ID = process.env.INFURA_PROJECT_ID; const MNEMONIC = process.env.MNEMONIC; // or a private key module.exports = { networks: { ropsten: { provider: () => new HDWalletProvider(MNEMONIC, `https://ropsten.infura.io/v3/${INFURA_PROJECT_ID}`), network_id: 3, gas: 5500000, confirmations: 2, timeoutBlocks: 200, skipDryRun: true }, // ... other networks ... }, // ... other Truffle config ... }; Il nostro obiettivo è quello di sostituire l'URL Infura con l'URL GetBlock (e in modo simile per qualsiasi URL Alchemy).La buona notizia è che il RPC di GetBlock funziona allo stesso modo - fornisci un URL di endpoint e il tuo fornitore di portafoglio. Se il tuo progetto Truffle non è già in uso (è probabile che, se è stato implementato tramite Infura/Alchemy), installarlo con Questa libreria consente a Truffle di firmare transazioni con le tue chiavi e inviarle attraverso il nodo remoto. Installazione di HDWalletProvider. @truffle/hdwallet-provider npm install @truffle/hdwallet-provider Modifica Aggiungi la chiave API GetBlock alle variabili ambientali (ad esempio, in File di set Inoltre, assicurarsi che la chiave mnemonica o privata sia in un env var (ad es. o Ad esempio, per utilizzare Ethereum Sepolia testnet tramite GetBlock: truffle-config.js .env GETBLOCK_API_KEY=<your_key_here> MNEMONIC PRIVATE_KEY require('dotenv').config(); const HDWalletProvider = require('@truffle/hdwallet-provider'); const PRIVATE_KEY = process.env.PRIVATE_KEY; // your wallet private key (hex string, no 0x) const GETBLOCK_KEY = process.env.GETBLOCK_API_KEY; // your GetBlock API key module.exports = { networks: { sepolia: { provider: () => new HDWalletProvider( PRIVATE_KEY, `https://eth.getblock.io/sepolia/?api_key=${GETBLOCK_KEY}` ), network_id: 11155111, // Sepolia network ID gas: 5500000, // Gas limit, adjust as needed confirmations: 2, // # of blocks to wait between deployments (optional) timeoutBlocks: 200, // # of blocks before a deployment times out (optional) skipDryRun: true // Skip dry run before migrations (recommended for public nets) }, // ... other networks (mainnet, etc) ... }, // ... rest of config ... }; Il cambiamento chiave è l'URL: abbiamo usato con il nostro parametri di query. Ora, ogni volta che si esegue Truffle con la rete, sarà indirizzato attraverso GetBlock invece di Infura. Se si desidera configurare Mainnet, è possibile aggiungere una sezione simile: https://eth.getblock.io/... ?api_key= sepolia mainnet: { provider: () => new HDWalletProvider( PRIVATE_KEY, `https://eth.getblock.io/mainnet/?api_key=${GETBLOCK_KEY}` ), network_id: 1, gas: 5500000, gasPrice: 20e9, // e.g., 20 Gwei (you may adjust according to network conditions) confirmations: 2, timeoutBlocks: 200, skipDryRun: true } Assicurati di sostituire con il giusto per la tua rete (la rete principale di Ethereum è 1, Sepolia è 11155111, ecc.). network_id Il è quello che serve qui, ma GetBlock supporta anche l'incorporazione della chiave nel percorso (come potresti vedere in alcuni esempi). Entrambi sono equivalenti. È più tipico usare il parametro di query ed è facile gestire i modelli di string. di nota. https://eth.getblock.io/<network>/?api_key=.. Passo 4: Implementare e testare web3.js con GetBlock Prima di inviare i tuoi contratti, è una buona idea controllare che tutto sia configurato correttamente. Truffle Console. Run (or the name of the network you specified). This will launch a console with Web3 available interactively. Try running something as a test, such as this: . If everything is properly set up, this should display the current block number on that network via GetBlock. If you get a response, your connection is solid! truffle console --network sepolia await web3.eth.getBlockNumber() Node.js Script. Alternatively, you could test using web3.js in a standalone script. First, make sure you have web3 installed ( ), then create a simple script like below to get the latest block number: npm install web3 // test-getblock.js const Web3 = require('web3'); const RPC_URL = `https://eth.getblock.io/sepolia/?api_key=${process.env.GETBLOCK_API_KEY}`; const web3 = new Web3(RPC_URL); web3.eth.getBlockNumber() .then(num => console.log("Latest block number:", num)) .catch(err => console.error("Error connecting to GetBlock:", err)); Non dimenticare di caricare le variabili ambientali (potresti aggiungere in alto e definisci GETBLOCK_API_KEY nel tuo .env). eseguire questo script con Se stampa un numero di blocco, hai connesso con successo a GetBlock tramite web3.js. require('dotenv').config(); node test-getblock.js Il test di cui sopra utilizza una semplice chiamata di lettura ( Puoi provare di più, come recuperare un blocco o un saldo del conto, per confermare ulteriormente che le cose stanno funzionando. eth_getBlockNumber const latestBlock = await web3.eth.getBlock('latest'); console.log("Latest block info:", latestBlock); Se qualcosa non va (ad esempio, si incontra un errore di autenticazione), controllare la chiave API nell'URL è corretta e il limite libero del tuo account non è stato superato (estremamente improbabile con solo alcune richieste). If you have previously used Alchemy's or Infura's web3 provider in code (i.e., Alchemy offers a Web3 client or SDK with custom methods), switching to GetBlock will mean you'll still be using the fundamental Web3 methods. GetBlock is a regular node provider, so web3.js talks to it through the standard Ethereum JSON-RPC calls. Per il tip. Passo 5: eseguire le migrazioni e i test di Truffle su GetBlock E infine, la vera prova: implementare i tuoi contratti e ospitare il tuo DApp con GetBlock come tuo provider di backend. Implementare contratti normalmente con Truffle, ma istruirlo a implementare sulla rete che hai creato per GetBlock. Sviluppo dei contratti. truffle migrate --network sepolia Truffle compilerà i tuoi contratti (se non sono già compilati) e poi utilizzerà HDWalletProvider per trasmettere le transazioni di distribuzione sul GetBlock RPC. Dovresti essere in grado di visualizzare le uscite nella console delle transazioni inviate, le conferme ricevute, ecc. Il processo è lo stesso che era con Infura/Alchemy – l'unica differenza dietro le scene è l'URL del nodo. Quando si sviluppa su Ethereum mainnet, assicurarsi di avere una ragionevole quantità di ETH disponibile nel tuo account di sviluppatore e prestare attenzione ai prezzi del gas. (Fai il tuo L'esperienza dovrebbe essere la stessa di Infura: GetBlock sta semplicemente reindirizzando le transazioni firmate alla rete Ethereum. truffle migrate --network mainnet mainnet If you have Truffle tests or scripts that invoke your contracts, you can test them on the network offered by GetBlock as well: Test di corsa. truffle test --network sepolia Le transazioni di test (ad esempio, una chiamata alla funzione contratto sui tuoi contratti implementati) verranno trasmesse attraverso il nodo di GetBlock. Con poche eccezioni, il switching dell'endpoint RPC non dovrebbe influenzare il comportamento di Ethereum. Se le migrazioni o i test sono andati bene su Infura/Alchemy, dovrebbero funzionare bene su GetBlock. Tutte le chiamate JSON-RPC predefinite sono supportate per GetBlock (ad esempio, l'implementazione di contratti, la lettura di stato, l'invio di transazioni, le query di eventi) - è un servizio di nodo completo. Se una chiamata JSON-RPC viene rimossa per qualsiasi motivo, i doc di GetBlock lo indicano di solito, ma le chiamate semplici come l'implementazione ( Il nome della chiamata ( ), ricevere ricevute, ecc., sono tutti disponibili. Il comportamento atteso. eth_sendRawTransaction eth_call Congratulazioni! Il backend del tuo DApp è ora su GetBlock! La tua migrazione è finita. Le tue chiamate web3 utilizzano l'infrastruttura di GetBlock e i tuoi contratti intelligenti sono in vita. Gestione delle chiavi API, dei limiti dei tassi e del monitoraggio su GetBlock Cambiare provider non è solo una questione di aggiornamento degli URL – è anche necessario sapere se ci sono differenze nel modo in cui viene tracciato l'uso e monitorare le prestazioni del tuo DApp sul nuovo provider. Infura ha usato un ID di progetto nell'URL; Alchemy ha usato chiavi API piuttosto spesso nella forma incorporata nell'URL anche (o un dominio personalizzato). L'approccio di GetBlock è anche lo stesso - avrai un token di accesso (chiave API) e aggiungerai questo all'URL RPC. A livello funzionale, la tua applicazione non deve fare la tua chiave fare qualcosa di insolito se non includerla nell'URL dell'endpoint. API Key Setup. Ci sono limiti per fornitore sul livello gratuito: Limiti di percentuale e passaggio. GetBlock Free Tier. 50,000 compute units per day and max 5 requests per second. In practice, 1 simple RPC call ≈ 1 CU (more complex calls like logs could be more counted, as with Alchemy's system). The 5 RPS restriction will make you not burst more than 5 requests in the same second on free tier. If so, subsequent calls may be refused with a rate-limit response. For all but the most busy DApps, 5 RPS is fine while developing – but if your backend scripts are making lots of concurrent calls, you may need to rate-limit them or consider switching to a more expensive plan (the one after this offers 25 RPS). Infura. Infura's free tier was circa 100k requests/day historically and since their new configuration, it's 6 million credits/day throughput of up to 2,000 credits/sec (which is roughly the equivalent of perhaps ~2000 simple calls/sec). Infura's generous free plan RPS is very kind, but note the fact that not all calls are 1 credit (some big calls are more credits). Either way, if your DApp wasn't hitting Infura's limits, it likely won't hit GetBlock's either, by similar scale. Alchemy. Alchemy's 100M free tier monthly of compute units is significant as well. They have no hard RPS fee, but intense usage will consume those compute units quickly. Alchemy bills calls (e.g., a simple ETH call might be 0.5 CU, a complex one 10 CUs, etc.). If you weren’t close to 100M units, you should be fine switching to 50k/day (≈1.5M/month) on GetBlock for dev. If 50k/day is not enough (e.g., if you are running a production app on a free plan – not typical), you might have to move to GetBlock's paid plans which offer much higher monthly CUs. Un altro aspetto fantastico di GetBlock è il suo dashboard con analisi complete. Nella pagina principale del tuo dashboard, ottieni una panoramica del tuo piano corrente, dei CU rimanenti per il giorno, della tua soglia RPS corrente e delle richieste cumulative effettuate nelle ultime 24 ore. Questo ti consente di sapere immediatamente se stai raggiungendo il tuo limite giornaliero. Inoltre, nella scheda "Statistics" o "Analytics" dei tuoi endpoints, GetBlock fornisce grafici e breakdowns di: Monitoraggio dell’utilizzo. Numero di richieste nel tempo Stati di risposta (in modo da poter vedere se ci sono stati errori) Distribuzione del metodo di chiamata (quali metodi RPC stai chiamando di più) Qualsiasi rifiuto del limite di tasso (se hai colpito il limite RPS) Il monitoraggio di queste metriche è altamente raccomandato, specialmente durante la transizione. Ad esempio, se hai scritto per errore uno script che inonda la rete con le chiamate, il dashboard mostrerà un aumento del volume delle richieste o anche alcune risposte a 429 tassi di limite. Questo è dove vorresti ottimizzare le chiamate backend di DApp. Infura e Alchemy offrono anche dashboard, ma il vantaggio con GetBlock è che puoi tenere traccia di tutto il tuo utilizzo multi-chain da un unico posto. Nel caso in cui il piano gratuito non sia sufficiente (forse la tua app si sta espandendo), GetBlock ha semplici aggiornamenti – piano Starter (~50M CUs / mese, ~1.6M / giorno, 25 RPS) e piano Pro (600M / mese, 200 RPS). Puoi aggiornare direttamente dal dashboard. Ma durante lo sviluppo, probabilmente non avrai bisogno di questo. Limiti di azione. Il piano gratuito GetBlock include il supporto per fino a 2 token di accesso (endpoint). Ciò significa che puoi creare uno per mainnet, uno per testnet, cioè - tenere i tuoi progetti o ambienti isolati. Ogni endpoint avrà la propria chiave API e tracciamento dell'utilizzo. Questo è paragonabile all'approccio "Project ID per progetto" di Infura. È una buona pratica avere endpoints separati per la produzione di sviluppatori in modo da poter tracciare l'utilizzo in modo indipendente. Numerosi punti finali. Le migliori pratiche per una migrazione fluida Ecco cosa vi consiglio: Maintain environment variables. Place your API keys and secrets (mnemonic/private key) in an file or in your system environment, not in source code. This makes switching endpoints easier and more secure. .env Test on a testnet first. While switching providers, attempt to deploy on a test network (Sepolia) with the help of GetBlock before working on mainnet. This makes sure that your setup is right. After confirmation, you can shift your mainnet setup. Compare behavior. It is a good idea to do some sanity checks after migration – i.e., get a known contract's data via Infura and via GetBlock and compare that the results are identical. They should be, since both are reading from Ethereum, but this can give confidence that GetBlock is in full sync (GetBlock does run full nodes, so it should be). WebSockets (if required). If your backend relies on WebSocket subscriptions (i.e., listening to events), GetBlock does offer that too. Simply use the URL in a Web3 WebsocketProvider. Ensure that your plan covers the throughput your subscriptions require (the same RPS limits apply to websockets). The majority of developers, however, use WebSockets in the frontend (with a library like MetaMask or Alchemy's subscription API). In purely backend contexts, WebSockets are less common, but it’s good to know GetBlock has the option. wss://go.getblock.io/xxxxxxx No frontend changes. Since this migration is backend-facing, your frontend (if you have one) doesn't have to change. If you were using MetaMask to connect to a testnet using Infura, you can still do so – MetaMask does not require GetBlock for connecting users (though GetBlock can also provide custom RPC endpoints for MetaMask). The separation of concerns (frontend vs. backend) remains. Conclusione Seguendo questo tutorial, hai ora migrato il tuo backend di Ethereum DApp da Infura/Alchemy a GetBlock. La tua configurazione di Truffle ora punta al RPC di GetBlock, e puoi implementare contratti e fare chiamate web3.js attraverso GetBlock nello stesso modo in cui potresti prima. La migrazione non cambierà la funzione del tuo DApp, ma ti posiziona per aggiungere facilmente blocchi aggiuntivi o aumentare l'uso senza eseguire i tuoi nodi.