ERC1155
Source: examples/erc1155/
Indexes ERC1155 multi-token events: TransferSingle, TransferBatch, and URI. Demonstrates batch event processing and iterating over arrays in event parameters.
Schema
type Token @entity {
id: ID!
uri: String
totalSupply: BigInt!
}
type Transfer @entity {
id: ID!
operator: Bytes!
from: Bytes!
to: Bytes!
tokenId: BigInt!
value: BigInt!
blockNumber: BigInt!
transactionHash: Bytes!
}
Handlers
TransferSingle: Single token transfer — straightforward.
#![allow(unused)] fn main() { #[handler] pub fn handle_transfer_single(event: &ERC1155TransferSingleEvent, ctx: &graphite::EventContext) { let id = format!("{}-{}", hex(&ctx.tx_hash), hex(&ctx.log_index)); Transfer::new(&id) .set_operator(event.operator.to_vec()) .set_from(event.from.to_vec()) .set_to(event.to.to_vec()) .set_token_id(event.id.clone()) .set_value(event.value.clone()) .set_block_number(ctx.block_number.clone()) .set_transaction_hash(ctx.tx_hash.to_vec()) .save(); } }
TransferBatch: Iterates over the ids and values arrays in the event:
#![allow(unused)] fn main() { #[handler] pub fn handle_transfer_batch(event: &ERC1155TransferBatchEvent, ctx: &graphite::EventContext) { for (i, (token_id, value)) in event.ids.iter().zip(event.values.iter()).enumerate() { let id = format!("{}-{}-{}", hex(&ctx.tx_hash), hex(&ctx.log_index), i); Transfer::new(&id) .set_operator(event.operator.to_vec()) .set_from(event.from.to_vec()) .set_to(event.to.to_vec()) .set_token_id(token_id.clone()) .set_value(value.clone()) .set_block_number(ctx.block_number.clone()) .set_transaction_hash(ctx.tx_hash.to_vec()) .save(); } } }
URI: Updates the token's metadata URI:
#![allow(unused)] fn main() { #[handler] pub fn handle_uri(event: &ERC1155URIEvent, _ctx: &graphite::EventContext) { let token_id = hex(&event.id); let token = Token::load(&token_id).unwrap_or_else(|| Token::new(&token_id)); token.set_uri(event.value.clone()).save(); } }
Key Points
- Array parameters in ERC1155
TransferBatch(ids[],values[]) are decoded asVec<Vec<u8>>— each innerVec<u8>is a little-endian BigInt. - Loop index
iin the batch handler is used to disambiguate entity IDs within a single transaction log. Token::load(...).unwrap_or_else(|| Token::new(...))is the idiomatic pattern for upsert when you want to preserve existing fields.
cd examples/erc1155
cargo test