# You can get the endpoint once you have completed deploying a subgraph onto Alchemy
# Please check your Alchemy Dashboard to retrieve the endpoint
END_POINT=YOUR_ENDPOINT
Create a script to query from the Alchemy Subgraph:
Create a script file:
mkdir src && cd src
touch query.ts && open query.ts
Add the following code to the query.ts script:
import axios from "axios";
import { gql } from "graphql-tag";
import * as dotenv from "dotenv";
dotenv.config();
const END_POINT = process.env.END_POINT as string;
const GET_ACCOUNT_BALANCE = gql`
query GetAccountBalance($account: ID!) {
account(id: $account) {
id
balance
}
}
`;
const GET_ALLOWANCE_QUERY = `
query GetAllowance($account: Bytes!, $spender: Bytes!) {
approvals(where: { owner: $account, spender: $spender }) {
id
owner
spender
value
}
}
`;
export async function getAccountBalance(account: string) {
const response = await axios.post(END_POINT, {
query: GET_ACCOUNT_BALANCE.loc?.source.body,
variables: { account },
});
const result = response.data;
if (result.errors) {
throw new Error(
result.errors.map((error: any) => error.message).join(", ")
);
}
return result.data.account;
}
export async function getAllowance(account: string, spender: string) {
const response = await axios.post(END_POINT, {
query: GET_ALLOWANCE_QUERY,
variables: {
account,
spender,
},
});
const result = response.data;
if (result.errors) {
throw new Error(
result.errors.map((error: any) => error.message).join(", ")
);
}
return result.data.approvals;
}
Create main.ts to test the setup:
Create the file:
touch main.ts && open main.ts
Add the code into main.ts:
import { getAccountBalance, getAllowance } from "./query";
async function main() {
const account = "0x31003C2D5685c7D28D7174c3255307Eb9a0f3015"; // Replace with your actual address
const info = await getAccountBalance(account.toLowerCase());
console.log("Account Info: ", info);
const spender = "0x87a7A0223D6F96B3DECaAf3666d5c550b36fEfEe"; // Replace with your actual address
const approvals = await getAllowance(
account.toLowerCase(),
spender.toLowerCase()
);
console.log("Approvals: ", approvals);
}
main()
.then(() => process.exit(0))
.catch((error) => {
console.error(error);
process.exit(1);
});
Run the test:
cd .. && npx ts-node src/main.ts
After running, you should see output similar to the following: