mkdir alchemy-solana-api cd alchemy-solana-api npm init --yes
3. 安装 Solana Web3.js 库
运行以下命令使用 npm 或 yarn 安装 Solana Web3.js 库。
npm install --save @solana/web3.js
4. 提出第一个请求
现在,您已准备好使用 Solana API 并发出第一个请求。例如,让我们向 发出请求。创建一个文件并将以下代码片段粘贴到文件中。get latest slotindex.js
const solanaWeb3 = require("@solana/web3.js"); const main = async () => { rpc = "https://solana-mainnet.g.alchemy.com/v2/<Your-Alchemy-API-Key>"; // RPC URL for connecting with a Solana node connection = new solanaWeb3.Connection(rpc, "confirmed"); // confirming the connection let slot = await connection.getSlot(); // getting the most recent slot number console.log("The latest slot number is", slot); // logging the most recent slot number }; main();
const axios = require("axios"); function getProgramAccountsExample() { let gPAExampleRequest = { "method": "alchemy_getProgramAccounts", "params": [ "ZETAxsqBRek56DhiGXrn75yj2NHU3aYUnxvHXpkf3aD", { "encoding": "base64", "withContext": true, "order": "desc" } ], "id": 0, "jsonrpc": "2.0" } let programAccounts = [] const alchemyRPCUrl = "https://solana-mainnet.g.alchemy.com/v2/<YOUR-API-KEY>" try { let response = await axios.post(url, gPAExampleRequest); let responseData = response.data["result"] // continue aggregating if there's a new pageKey present in the latest response while (responseData["pageKey"]) { programAccounts = programAccounts.concat(responseData["value"]); // place the pagekey within the optional config object // (you may need to create that config object if you didn't have it originally) gPAExampleRequest["params"][1]["pageKey"] = responseData["pageKey"]; // make another call to getProgramAccounts with the pageKey response = await axios.post(url, gPAExampleRequest); responseData = response.data["result"] } programAccounts = programAccounts.concat(responseData["value"]); return programAccounts; } catch (err) { console.error(`Error in Response, Data is: ${err.data}`); return []; } }