Skip to content

Commit 63b8426

Browse files
committed
feat(erc1155): refac to use dbpool
1 parent 641be8a commit 63b8426

15 files changed

Lines changed: 664 additions & 760 deletions

File tree

‎Cargo.lock‎

Lines changed: 5 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎bins/torii-arcade/src/main.rs‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -559,7 +559,8 @@ async fn run_indexer(config: Config) -> Result<()> {
559559
}
560560

561561
if install_erc1155 {
562-
let storage = Arc::new(Erc1155Storage::new(&erc1155_db_url).await?);
562+
let erc1155_pool = DbPoolOptions::new().connect_any(&erc1155_db_url).await?;
563+
let storage = Arc::new(Erc1155Storage::new(erc1155_pool, &erc1155_db_url).await?);
563564
let grpc_service = Erc1155Service::new(storage.clone());
564565
let mut sink = Erc1155Sink::new(storage.clone())
565566
.with_grpc_service(grpc_service.clone())

‎bins/torii-introspect-bin/src/main.rs‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,7 @@ use torii_runtime_common::database::{
5151
resolve_token_db_setup, TokenDbSetup, DEFAULT_SQLITE_MAX_CONNECTIONS,
5252
};
5353
use torii_runtime_common::token_support::{resolve_installed_token_support, InstalledTokenSupport};
54-
use torii_sql::DbBackend;
54+
use torii_sql::{DbBackend, DbPoolOptions};
5555

5656
use crate::config::parse_historical_models;
5757

@@ -418,7 +418,10 @@ async fn configure_token_support(
418418
}
419419

420420
if installed_token_support.erc1155 {
421-
let storage = Arc::new(Erc1155Storage::new(&db_setup.erc1155_url).await?);
421+
let erc1155_pool = DbPoolOptions::new()
422+
.connect_any(&db_setup.erc1155_url)
423+
.await?;
424+
let storage = Arc::new(Erc1155Storage::new(erc1155_pool, &db_setup.erc1155_url).await?);
422425
tracing::info!("ERC1155 database initialized: {}", db_setup.erc1155_url);
423426

424427
let decoder: Arc<dyn torii::etl::Decoder> = Arc::new(Erc1155Decoder::new());

‎bins/torii-tokens-synth/src/main.rs‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ use torii_erc721::{
3030
Erc721Decoder, Erc721Sink, Erc721Storage, SyntheticErc721Config, SyntheticErc721Extractor,
3131
};
3232
use torii_runtime_common::sink::{drop_postgres_schemas, initialize_sink_with_command_handlers};
33+
use torii_sql::DbPoolOptions;
3334

3435
const SYNTH_COMMAND_QUEUE_SIZE: usize = 4096;
3536
const SYNTH_METADATA_COMMAND_PARALLELISM: usize = 1;
@@ -780,7 +781,10 @@ async fn run_erc1155_profile(config: Erc1155ProfileConfig) -> Result<()> {
780781
fs::create_dir_all(&output_dir)
781782
.with_context(|| format!("failed to create output dir {}", output_dir.display()))?;
782783

783-
let storage = Arc::new(Erc1155Storage::new(&config.common.db_url).await?);
784+
let erc1155_pool = DbPoolOptions::new()
785+
.connect_any(&config.common.db_url)
786+
.await?;
787+
let storage = Arc::new(Erc1155Storage::new(erc1155_pool, &config.common.db_url).await?);
784788

785789
let mut sink = Erc1155Sink::new(storage.clone())
786790
.with_metadata_commands()

‎bins/torii-tokens/src/main.rs‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,7 @@ use torii_config_common::apply_observability_env;
6262
use torii_runtime_common::database::resolve_token_db_setup;
6363
#[cfg(feature = "profiling")]
6464
use torii_sql::DbBackend;
65+
use torii_sql::DbPoolOptions;
6566

6667
// Import from ERC20 library crate
6768
use torii_erc20::proto::erc20_server::Erc20Server;
@@ -641,7 +642,10 @@ async fn run_indexer(config: Config) -> Result<()> {
641642
if create_erc1155 {
642643
enabled_types.push("ERC1155");
643644

644-
let storage = Arc::new(Erc1155Storage::new(&db_setup.erc1155_url).await?);
645+
let erc1155_pool = DbPoolOptions::new()
646+
.connect_any(&db_setup.erc1155_url)
647+
.await?;
648+
let storage = Arc::new(Erc1155Storage::new(erc1155_pool, &db_setup.erc1155_url).await?);
645649
tracing::info!("ERC1155 database initialized: {}", db_setup.erc1155_url);
646650

647651
let decoder = Arc::new(Erc1155Decoder::new());

‎crates/torii-erc1155/Cargo.toml‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,13 +8,16 @@ description = "ERC1155 semi-fungible token indexer library for Torii"
88
# Torii core
99
torii = { path = "../.." }
1010
torii-common = { path = "../torii-common" }
11+
torii-types = { path = "../types" }
12+
torii-sql = { workspace = true, features = ["postgres", "sqlite"] }
1113

1214
# Async
1315
tokio = { version = "1", features = ["full"] }
1416
async-trait = "0.1"
1517

1618
# Starknet
1719
starknet = "0.17"
20+
starknet-types-raw.workspace = true
1821

1922
# Storage
2023
rusqlite = { version = "0.32", features = ["bundled"] }
@@ -26,6 +29,7 @@ serde_json = "1.0"
2629

2730
# Encoding
2831
hex = "0.4"
32+
primitive-types.workspace = true
2933

3034
# gRPC/Protobuf
3135
prost = "0.13"
@@ -43,6 +47,7 @@ axum = "0.7"
4347
# Utilities
4448
anyhow = "1.0"
4549
tracing = "0.1"
50+
thiserror.workspace = true
4651

4752
[build-dependencies]
4853
tonic-build = "0.12"

‎crates/torii-erc1155/src/balance_fetcher.rs‎

Lines changed: 38 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -6,11 +6,14 @@
66
//! ERC1155 has a different signature: balance_of(account, token_id)
77
88
use anyhow::{Context, Result};
9-
use starknet::core::types::{requests::CallRequest, BlockId, Felt, FunctionCall, U256};
9+
use primitive_types::U256;
10+
use starknet::core::types::{requests::CallRequest, BlockId, FunctionCall};
1011
use starknet::macros::selector;
1112
use starknet::providers::jsonrpc::{HttpTransport, JsonRpcClient};
1213
use starknet::providers::{Provider, ProviderRequestData, ProviderResponseData};
14+
use starknet_types_raw::Felt;
1315
use std::sync::Arc;
16+
use torii_common::utils::{felt_pair_to_u256, felt_to_u256};
1417

1518
/// Request for fetching an ERC1155 balance at a specific block
1619
#[derive(Debug, Clone)]
@@ -54,15 +57,20 @@ impl Erc1155BalanceFetcher {
5457
let calldata = build_balance_of_calldata(wallet, token_id);
5558

5659
let call = FunctionCall {
57-
contract_address: contract,
60+
contract_address: to_starknet_felt(contract),
5861
entry_point_selector: selector!("balance_of"),
59-
calldata,
62+
calldata: calldata.into_iter().map(to_starknet_felt).collect(),
6063
};
6164

6265
let block_id = BlockId::Number(block_number);
6366

6467
match self.provider.call(call, block_id).await {
65-
Ok(result) => Ok(parse_u256_result(&result)),
68+
Ok(result) => Ok(parse_u256_result(
69+
&result
70+
.into_iter()
71+
.map(from_starknet_felt)
72+
.collect::<Vec<_>>(),
73+
)),
6674
Err(e) => {
6775
tracing::warn!(
6876
target: "torii_erc1155::balance_fetcher",
@@ -98,9 +106,9 @@ impl Erc1155BalanceFetcher {
98106
let calldata = build_balance_of_calldata(req.wallet, req.token_id);
99107
ProviderRequestData::Call(CallRequest {
100108
request: FunctionCall {
101-
contract_address: req.contract,
109+
contract_address: to_starknet_felt(req.contract),
102110
entry_point_selector: selector!("balance_of"),
103-
calldata,
111+
calldata: calldata.into_iter().map(to_starknet_felt).collect(),
104112
},
105113
block_id: BlockId::Number(req.block_number),
106114
})
@@ -119,7 +127,12 @@ impl Erc1155BalanceFetcher {
119127
for (idx, response) in responses.into_iter().enumerate() {
120128
let req = &requests[idx];
121129
let balance = if let ProviderResponseData::Call(felts) = response {
122-
parse_u256_result(&felts)
130+
parse_u256_result(
131+
&felts
132+
.into_iter()
133+
.map(from_starknet_felt)
134+
.collect::<Vec<_>>(),
135+
)
123136
} else {
124137
tracing::warn!(
125138
target: "torii_erc1155::balance_fetcher",
@@ -147,9 +160,7 @@ impl Erc1155BalanceFetcher {
147160
/// Build calldata for balance_of(account, token_id)
148161
/// ERC1155 expects: [account, token_id_low, token_id_high]
149162
fn build_balance_of_calldata(wallet: Felt, token_id: U256) -> Vec<Felt> {
150-
// Convert U256 to two Felts (low, high)
151-
let low = Felt::from(token_id.low());
152-
let high = Felt::from(token_id.high());
163+
let (low, high) = u256_low_high(token_id);
153164
vec![wallet, low, high]
154165
}
155166

@@ -161,23 +172,25 @@ fn build_balance_of_calldata(wallet: Felt, token_id: U256) -> Vec<Felt> {
161172
fn parse_u256_result(result: &[Felt]) -> U256 {
162173
match result.len() {
163174
0 => U256::from(0u64),
164-
1 => {
165-
// Single felt - convert to U256
166-
let bytes = result[0].to_bytes_be();
167-
let low = u128::from_be_bytes(bytes[16..32].try_into().unwrap());
168-
U256::from_words(low, 0)
169-
}
170-
_ => {
171-
// Two felts: [low, high] for u256
172-
let low_bytes = result[0].to_bytes_be();
173-
let high_bytes = result[1].to_bytes_be();
175+
1 => felt_to_u256(result[0]),
176+
_ => felt_pair_to_u256(result[0], result[1]),
177+
}
178+
}
179+
180+
fn to_starknet_felt(value: Felt) -> starknet::core::types::Felt {
181+
starknet::core::types::Felt::from_bytes_be(&value.to_be_bytes())
182+
}
174183

175-
let low = u128::from_be_bytes(low_bytes[16..32].try_into().unwrap());
176-
let high = u128::from_be_bytes(high_bytes[16..32].try_into().unwrap());
184+
fn from_starknet_felt(value: starknet::core::types::Felt) -> Felt {
185+
Felt::from_be_bytes_slice(&value.to_bytes_be()).unwrap_or(Felt::ZERO)
186+
}
177187

178-
U256::from_words(low, high)
179-
}
180-
}
188+
fn u256_low_high(value: U256) -> (Felt, Felt) {
189+
let [l0, l1, h0, h1] = value.0;
190+
(
191+
Felt::from_le_words([l0, l1, 0, 0]),
192+
Felt::from_le_words([h0, h1, 0, 0]),
193+
)
181194
}
182195

183196
#[cfg(test)]

0 commit comments

Comments
 (0)