Solana Quick Start
Solana Quick Start
The goal of this quick start guide is to index checked token transfers from the RNDR token.
In the earlier Quickstart section , you should have taken note of three crucial files. To initiate the setup of a project from scratch, you can proceed to follow the steps outlined in the initialisation description.
As a prerequisite, you will need to generate types from the IDL files of each program.
Note
The final code of this project can be found here.
Your Project Manifest File
The Project Manifest file is an entry point to your project. It defines most of the details on how SubQuery will index and transform the chain data.
For Solana, there are four types of mapping handlers (and you can have more than one in each project):
- BlockHandlers: On each and every block, run a mapping function
- TransactionHandlers: On each and every transaction that matches optional filter criteria, run a mapping function
- InstructionHandlers: On each and every instruction that matches optional filter criteria, run a mapping function
- LogHandlers: On each and every log that matches optional filter criteria, run a mapping function
We are indexing actions from the RNDR token, first you will need to import the Token Program IDL definition from here. You can copy the entire JSON and save as a file tokenprogram.idl.json
in the /idls
directory.
This section in the Project Manifest now imports all the correct definitions and lists the triggers that we look for on the blockchain when indexing.
Since you are going to index checked token transfers, you need to update the datasources
section as follows:
{
dataSources: [
{
kind: SolanaDatasourceKind.Runtime,
startBlock: 336382792,
assets: new Map([["TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA", { file: "./idls/tokenprogram.idl.json" }]]),
mapping: {
file: "./dist/index.js",
handlers: [
{
kind: SolanaHandlerKind.Instruction,
handler: "handleCheckedTransfer",
filter: {
programId: "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA",
discriminator: "transferChecked",
accounts: [
null,
['rndrizKT3MK1iimdxRdWabcF7Zg7AR5T4nud4EkHBof'],
]
},
},
],
},
},
],
}
The above code indicates that you will be running a handleCheckedTransfer
mapping function whenever there is a transferChecked
instruction on any transaction from the RNDR token.
Check out our Manifest File documentation to get more information about the Project Manifest (project.ts
) file.
Update Your GraphQL Schema File
The schema.graphql
file determines the shape of your data from SubQuery due to the mechanism of the GraphQL query language. Hence, updating the GraphQL Schema file is the perfect place to start. It allows you to define your end goal right at the start.
Remove all existing entities and update the schema.graphql
file as follows. Here you can see we are indexing one entity, a Transfer
.
type Transfer @entity {
id: ID!
from: String!
to: String!
amount: BigInt!
blockNumber: BigInt!
transactionHash: String!
date: Date!
}
Note
Importantly, these relationships can not only establish one-to-many connections but also extend to include many-to-many associations. To delve deeper into entity relationships, you can refer to this section. If you prefer a more example-based approach, our dedicated Hero Course Module can provide further insights.
import { Transfer } from "../types";
import { TransferCheckedInstruction } from '../types/handler-inputs/TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA';
Check out the GraphQL Schema documentation to get in-depth information on schema.graphql
file.
Now that you have made essential changes to the GraphQL Schema file, let’s proceed ahead with the Mapping Function’s configuration.
Add a Mapping Function
Mapping functions define how blockchain data is transformed into the optimised GraphQL entities that we previously defined in the schema.graphql
file.
Follow these steps to add a mapping function:
Navigate to the default mapping function in the src/mappings
directory. You will be able to see three exported functions: handleBlock
, handleLog
, and handleTransaction
. Replace these functions with the following code (note the additional imports):
import assert from 'node:assert';
import { TransferCheckedInstruction } from '../types/handler-inputs/TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA';
import { SolanaInstruction } from '@subql/types-solana';
import { TransactionForFullJson } from '@solana/kit';
import { Transfer } from '../types/models';
function allAccounts(
transaction: TransactionForFullJson<0>,
) {
return [
...transaction.transaction.message.accountKeys,
...(transaction.meta?.loadedAddresses.writable ?? []),
...(transaction.meta?.loadedAddresses.readonly ?? []),
];
}
const TOKEN_ADDR = 'rndrizKT3MK1iimdxRdWabcF7Zg7AR5T4nud4EkHBof';
export function getAccountByIndex(
instruction: SolanaInstruction,
index: number,
): string {
return allAccounts(instruction.transaction)[index];
}
export async function handleCheckedTransfer(instruction: TransferCheckedInstruction) {
const source = getAccountByIndex(instruction, instruction.accounts[0]);
const mint = getAccountByIndex(instruction, instruction.accounts[1]);
const dest = getAccountByIndex(instruction, instruction.accounts[2]);
if (mint !== TOKEN_ADDR) {
return;
}
const decoded = await instruction.decodedData;
assert(decoded, "Expected decoded value");
const transfer = Transfer.create({
id: `${instruction.transaction.transaction.signatures[0]}-${instruction.index.join('.')}`,
amount: BigInt(decoded.data.amount),
from: source,
to: dest,
blockNumber: instruction.block.blockHeight,
transactionHash: instruction.transaction.transaction.signatures[0],
date: new Date(Number(instruction.block.blockTime) * 1000),
});
await transfer.save();
}
Let’s understand how the above code works.
For handleCheckedTransfer
, the function here receives an TransferCheckedInstruction
which includes instruction data in the payload. We extract the relevant accounts and confirm the mint is for the RNDR token. We then create a new Transfer
entity that we defined in our schema.graphql
and then save this to the store using the .save()
function (Note that SubQuery will automatically save this to the database).
Note
For more information on mapping functions, please refer to our Mappings documentation.
Build Your Project
Next, build your work to run your new SubQuery project. Run the build command from the project's root directory as given here:
yarn build
npm run-script build
Important
Whenever you make changes to your mapping functions, you must rebuild your project.
Now, you are ready to run your first SubQuery project. Let’s check out the process of running your project in detail.
Whenever you create a new SubQuery Project, first, you must run it locally on your computer and test it and using Docker is the easiest and quickiest way to do this.
Run Your Project Locally with Docker
The docker-compose.yml
file defines all the configurations that control how a SubQuery node runs. For a new project, which you have just initialised, you won't need to change anything.
However, visit the Running SubQuery Locally to get more information on the file and the settings.
Run the following command under the project directory:
yarn start:docker
npm run-script start:docker
Note
It may take a few minutes to download the required images and start the various nodes and Postgres databases.
Query your Project
Next, let's query our project. Follow these three simple steps to query your SubQuery project:
Open your browser and head to
http://localhost:3000
.You will see a GraphQL playground in the browser and the schemas which are ready to query.
Find the Docs tab on the right side of the playground which should open a documentation drawer. This documentation is automatically generated and it helps you find what entities and methods you can query.
Try the following queries to understand how it works for your new SubQuery starter project. Don’t forget to learn more about the GraphQL Query language.
query {
transfers(first: 5, orderBy: AMOUNT_DESC) {
nodes {
id
from
to
amount
blockNumber
}
}
}
You will see the result similar to below:
{
"data": {
"transfers": {
"nodes": [
{
"id": "5kA8Hsch2tsCEBduKdi9LmLF1Jpdx93eaXzXcxkdexGMUdjSzRz994oNQQAb9vX4ZRQEmFdgupVPs9RiTsi5SWtP-3.1",
"from": "AyzyikXL9kKs2cwyHsWLEe22aRYAvhbWwFn9TKrgmMx",
"to": "7nAXsw5ZSGBmC3xECDL26FeVfaWKccQHCDfqoCNAnR9B",
"amount": "200000000000000",
"blockNumber": "314765468"
},
{
"id": "BiiEoNiHmPgWZGZHAq8Qs6zRfnv7AjCd75e66RrVNpxzFz7XdydyrJXfcNoxHzqUUCLu6njGso4HUdjydGEBzZ4-2",
"from": "GvpfztSKEi1xa5b48W7xvnZCNTZDSP4A4rS1HfiBs7RB",
"to": "7JJ17zbcUfgrCyZK77aax2YYx9CyqdBW2kou1euNyhec",
"amount": "178136424747427",
"blockNumber": "315018963"
},
{
"id": "5m8dqwmBGgWGUa57k99FtHo3qJu9GYCFFtDBE82zdgSx4Yhd6vdgZFuBcPcuD9ZkZjyrNMkwSrq3pVinUHdCd2aU-4",
"from": "Azq8XAqwJj2nedMMtiH4fgmtoPpy3XR7HZRB32MnpE1E",
"to": "BCLkJ8As4jb6iRzhTdxLaVRj8cjUxrDPfPXzZXZ5TjU5",
"amount": "70859502000000",
"blockNumber": "314982009"
},
{
"id": "4Tc7FmDP3qyw9KnxebQVT8kTf6z8mxQRKGTA7gUXvcz3oCVUCCsQCFAyCa3eqK582qnqEiGV9ynMBCswTxNDM2vW-2",
"from": "DHK6wAbfKTmnQ878GDmPnfjLfQLFPXVURKfDgUAsKZbz",
"to": "GkrdqdHMNvb9mpL51UmGKX3bUAtcbjtoTAvwFGHiCyb6",
"amount": "49997500000004",
"blockNumber": "316298108"
},
{
"id": "4SugdVF6j4WVsCjxLxAnZRNdPtU3sttx1oHy19KjuWhtf5LarWPEBoZsUHteUJad5sijY8r5LdxTzxhJayXuZLXG-2",
"from": "ECKa34RVAo5Fvwkp1uEedh6jkM5o4CThvJeShysqJgQs",
"to": "4PcC3r3yfAJHJJ4WFjhuBcZDX38RNTvDCFLTJZF2cWxY",
"amount": "48944100000000",
"blockNumber": "314859767"
}
]
}
}
}
Note
The final code of this project can be found here.
What's next?
Congratulations! You have now a locally running SubQuery project that accepts GraphQL API requests for transferring data.
Tip
Find out how to build a performant SubQuery project and avoid common mistakes in Project Optimisation.
Click here to learn what should be your next step in your SubQuery journey.