Icon LinkHello World

Below is a simple "Hello World" Sway contract that we want to index. This contract has a function called new_greeting that logs a Greeting and a Person.

contract;
 
use std::logging::log;
 
struct Person {
    name: str[32],
}
 
struct Greeting {
    id: u64,
    greeting: str[32],
    person: Person,
}
 
abi Greet {
    fn new_greeting(id: u64, greeting: str[32], person_name: str[32]);
}
 
impl Greet for Contract {
    fn new_greeting(id: u64, greeting: str[32], person_name: str[32]) {
log(Greeting{ id, greeting, person: Person{ name: person_name }});
    }
}
 

We can define our schema like this in the schema file:

# Calling this `Greeter` so as to not clash with `Person` in the contract
type Greeter @entity {
  id: ID!
  name: Charfield!
  first_seen: UInt4!
  last_seen: UInt4!
  visits: Blob!
}
 
# Calling this `Salutation` so as to not clash with `Greeting` in the contract
type Salutation @entity {
  id: ID!
  message_hash: Bytes32!
  message: Charfield!
  greeter: Greeter!
  first_seen: UInt4!
  last_seen: UInt4!
}
 

Now that our schema is defined, here is how we can implement the WASM module in our lib.rs file:

//! A "Hello World" type of program for the Fuel Indexer service.
//!
//! Build this example's WASM module using the following command. Note that a
//! wasm32-unknown-unknown target will be required.
//!
//! ```bash
//! cargo build -p hello-indexer --release --target wasm32-unknown-unknown
//! ```
//!
//! Start a local test Fuel node.
//!
//! ```bash
//! cargo run -p hello-world-node --bin hello-world-node
//! ```
//!
//! With your database backend set up, now start your fuel-indexer binary using the
//! assets from this example:
//!
//! ```bash
//! cargo run --bin fuel-indexer -- run --manifest examples/hello-world/hello-indexer/hello_indexer.manifest.yaml --run-migrations
//! ```
//!
//! Now trigger an event.
//!
//! ```bash
//! cargo run -p hello-world-data --bin hello-world-data
//! ```
 
extern crate alloc;
use fuel_indexer_utils::prelude::*;
 
#[indexer(manifest = "examples/hello-world/hello-indexer/hello_indexer.manifest.yaml")]
mod hello_world_indexer {
 
    fn index_logged_greeting(event: Greeting, block: BlockData) {
let greeter = Greeter::new(
    event.person.name.to_right_trimmed_str().into(),
    block.height,
    block.height,
    vec![1u8, 2, 3, 4, 5, 6, 7, 8].into(),
)
.get_or_create();
 
let message = format!(
    "{} 👋, my name is {}",
    event.greeting.to_right_trimmed_str(),
    event.person.name.to_right_trimmed_str(),
);
let message_hash = bytes32(&message);
 
let salutation = Salutation::new(
    message_hash,
    message,
    greeter.id.clone(),
    block.height,
    block.height,
)
.get_or_create();
 
greeter.save();
salutation.save();
    }
}