Soroban Smart Contract Quick Start
Soroban Smart Contract Quick Start
The aim of this quick start guide is to provide a brief introduction to Soroban through the hello world smart contract SubQuery indexer. The sample smart contract is designed as a simple incrementer, allowing users to input a specific value. It serves as an effective way to quickly understand the workings of Soroban through a hands-on example in the real world.
Note
The final code of this project can be found here.
Preparations
For this tutorial, we'll utilise a streamlined version of the hello world smart contract available here. We'll streamline the code by retaining only the increment()
function. The resulting smart contract code will be as follows:
#![no_std]
use soroban_sdk::{contract, contractimpl, symbol_short, Env, Symbol};
// const MESSAGE: Symbol = symbol_short!("MESSAGE");
const COUNT: Symbol = symbol_short!("COUNT");
const LAST_INCR: Symbol = symbol_short!("LAST_INCR");
// (attribute macro) Marks a type as being the type that contract functions are attached for.
#[contract]
pub struct HelloContract;
// (attribute macro) Exports the publicly accessible functions to the Soroban environment.
#[contractimpl]
/// Implementation of the HelloContract.
impl HelloContract {
/// Increments the count by the specified value.
///
/// # Arguments
///
/// * `env` - The environment object.
/// * `incr` - The value to increment the count by.
///
/// # Returns
///
/// The updated count.
pub fn increment(env: Env, incr: u32) -> u32 {
// Get the current count.
let mut count = env.storage().instance().get(&COUNT).unwrap_or(0);
// Increment the count.
count += incr;
// Save the count.
env.storage().instance().set(&COUNT, &count);
env.storage().instance().set(&LAST_INCR, &incr);
// Emit an event.
env.events()
.publish((COUNT, symbol_short!("increment")), count);
// Return the count to the caller.
count
}
}
We've deployed and published the smart contract multiple times for better illustration. The transactions involving the increment function calls can be found in the following list. Ensure to explore the details, accessible under the "Events" tab:
- https://futurenet.stellarchain.io/transactions/8cd93444c3f4f37bc38dc4701c649e45081656965b4a94b73a4de8b3cf04cc8b
- https://futurenet.stellarchain.io/transactions/8cd93444c3f4f37bc38dc4701c649e45081656965b4a94b73a4de8b3cf04cc8b
- https://futurenet.stellarchain.io/transactions/6a7ac207f3909d92d5fee04e6fb7d78640a7a7f65424a9b4d54c13d6ffcc9e58
- https://futurenet.stellarchain.io/transactions/8e288bcba7ce4e6a8b275acfea40c6787d65db27eb16d8bef559d8be3bbcef65
- https://futurenet.stellarchain.io/transactions/aa26158526795f728ff0744246b080ded772be88f7af817255782993e8809d20
- https://futurenet.stellarchain.io/transactions/205b9778c159387d2b6b70f3c39c3876d79a3496c22eab4a2c9dafac17a0fa56
Now, let's move on to configuring the indexer.
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 a single datapoint - increment.
type Increment @entity {
id: ID!
newValue: BigInt!
}
SubQuery simplifies and ensures type-safety when working with GraphQL entities, smart contracts, events, transactions, operation and effects.
yarn codegen
npm run-script codegen
This action will generate a new directory (or update the existing one) named src/types
. Inside this directory, you will find automatically generated entity classes corresponding to each type defined in your schema.graphql
. These classes facilitate type-safe operations for loading, reading, and writing entity fields. You can learn more about this process in the GraphQL Schema section.
You can conveniently import all these types:
import { Increment } from "../types";
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 Stellar, there are several types of mapping handlers (and you can have more than one in each project):
- BlockHandler: On each and every block, run a mapping function
- TransactionHandlers: On each and every Stellar/Soroban transaction that matches optional filter criteria, run a mapping function
- OperationHandler: On each and every Stellar operation action that matches optional filter criteria, run a mapping function
- EffectHandler: On each and every Stellar effect action that matches optional filter criteria, run a mapping function
- EventHandler: On each and every Soroban event action that matches optional filter criteria, run a mapping function
Since you only need to index the events, the only handler type is need is an events handler:
dataSources: [
{
kind: StellarDatasourceKind.Runtime,
startBlock: 831474,
mapping: {
file: "./dist/index.js",
handlers: [
{
handler: "handleEvent",
kind: StellarHandlerKind.Event,
filter: {
topics: [
"COUNT", // Topic signature(s) for the events, there can be up to 4
],
contractId: "CAQFKAS47DF6RBKABRLDZ5O4XJIH2DQ3RMNHFPOSGLFI6KMSSIUIGQJ6"
}
},
],
},
},
],
Here is a straightforward event handler. We establish additional filters, specifically for the topic name and contract ID, to ensure that we handle only events with a specific topic from a particular smart contract.
Note
Check out our Manifest File documentation to get more information about the Project Manifest (project.ts
) file.
Next, 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.
Navigate to the default mapping function in the src/mappings
directory. Update the mappingHandler.ts
file as follows (note the additional imports):
import { Increment } from "../types";
import { SorobanEvent } from "@subql/types-stellar";
export async function handleEvent(event: SorobanEvent): Promise<void> {
logger.warn(event.transaction.hash.toString());
if (event.type.toString() == "contract") {
logger.warn(JSON.stringify(event.value));
const increment = Increment.create({
id: event.transaction.hash,
newValue: BigInt(
JSON.parse(JSON.stringify(event.value))["_value"].toString(),
),
});
await increment.save();
}
}
Here's a brief explanation. First, the necessary types are imported. Then, a handler handleEvent
that takes a SorobanEvent
as a parameter is defined. Once the handler is triggered, it uses the logger to warn about the hash of the associated transaction. As a next step it checks if the event type is contract
: if it is a contract event, log the event's value, extract the relevant information from the event value (increment
value), and create an object of entity Increment
with the extracted information. Finally, it saves the Increment
object to the data store.
Note
Check out our Mappings documentation to get more information on mapping functions.
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.
In the following query, we will retrieve all stored objects and promptly conduct their aggregation. Specifically, we will compute the frequency of function calls grouped by a parameter in each call.
query {
increments {
nodes {
id
newValue
}
groupedAggregates(groupBy: [NEW_VALUE]) {
distinctCount {
id
}
keys
}
}
}
You will see the result similar to below:
{
"data": {
"increments": {
"nodes": [
{
"id": "8cd93444c3f4f37bc38dc4701c649e45081656965b4a94b73a4de8b3cf04cc8b",
"newValue": "7"
},
{
"id": "205b9778c159387d2b6b70f3c39c3876d79a3496c22eab4a2c9dafac17a0fa56",
"newValue": "1975"
},
{
"id": "3cf049dfaa35bfabe7574b192b691e95f462418952bf5d7028f5ffc06852eef6",
"newValue": "32"
},
{
"id": "aa26158526795f728ff0744246b080ded772be88f7af817255782993e8809d20",
"newValue": "975"
},
{
"id": "6a7ac207f3909d92d5fee04e6fb7d78640a7a7f65424a9b4d54c13d6ffcc9e58",
"newValue": "125"
},
{
"id": "8e288bcba7ce4e6a8b275acfea40c6787d65db27eb16d8bef559d8be3bbcef65",
"newValue": "275"
}
],
"groupedAggregates": [
{
"distinctCount": {
"id": "1"
},
"keys": ["7"]
},
{
"distinctCount": {
"id": "1"
},
"keys": ["32"]
},
{
"distinctCount": {
"id": "1"
},
"keys": ["125"]
},
{
"distinctCount": {
"id": "1"
},
"keys": ["275"]
},
{
"distinctCount": {
"id": "1"
},
"keys": ["975"]
},
{
"distinctCount": {
"id": "1"
},
"keys": ["1975"]
}
]
}
}
}
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.