Skip to content

Commit

Permalink
feat(torii/graphql): cleanup names and add imagePath and metadata to …
Browse files Browse the repository at this point in the history
…erc_token

commit-id:21a1c0a5
  • Loading branch information
lambda-0x committed Oct 25, 2024
1 parent 5c702b8 commit 43a3c23
Show file tree
Hide file tree
Showing 14 changed files with 106 additions and 79 deletions.
3 changes: 3 additions & 0 deletions crates/torii/core/src/constants.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
pub const TOKEN_BALANCE_TABLE: &str = "token_balances";
pub const TOKEN_TRANSFER_TABLE: &str = "token_transfers";
pub const TOKENS_TABLE: &str = "tokens";
17 changes: 9 additions & 8 deletions crates/torii/core/src/executor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ use tokio::task::JoinSet;
use tokio::time::Instant;
use tracing::{debug, error, trace};

use crate::constants::{TOKENS_TABLE, TOKEN_BALANCE_TABLE};
use crate::simple_broker::SimpleBroker;
use crate::sql::utils::{felt_to_sql_string, sql_string_to_u256, u256_to_sql_string, I256};
use crate::sql::FELT_DELIMITER;
Expand Down Expand Up @@ -563,9 +564,9 @@ impl<'c, P: Provider + Sync + Send + 'static> Executor<'c, P> {
let semaphore = self.semaphore.clone();
let artifacts_path = self.artifacts_path.clone();
let provider = self.provider.clone();
let res = sqlx::query_as::<_, (String, String)>(
"SELECT name, symbol FROM tokens WHERE contract_address = ?",
)
let res = sqlx::query_as::<_, (String, String)>(&format!(
"SELECT name, symbol FROM {TOKENS_TABLE} WHERE contract_address = ?"
))

Check warning on line 569 in crates/torii/core/src/executor.rs

View check run for this annotation

Codecov / codecov/patch

crates/torii/core/src/executor.rs#L567-L569

Added lines #L567 - L569 were not covered by tests
.bind(felt_to_sql_string(&register_erc721_token.contract_address))
.fetch_one(&mut **tx)
.await;
Expand Down Expand Up @@ -801,7 +802,7 @@ impl<'c, P: Provider + Sync + Send + 'static> Executor<'c, P> {
) -> Result<()> {
let tx = &mut self.transaction;
let balance: Option<(String,)> =
sqlx::query_as("SELECT balance FROM balances WHERE id = ?")
sqlx::query_as(&format!("SELECT balance FROM {TOKEN_BALANCE_TABLE} WHERE id = ?"))

Check warning on line 805 in crates/torii/core/src/executor.rs

View check run for this annotation

Codecov / codecov/patch

crates/torii/core/src/executor.rs#L805

Added line #L805 was not covered by tests
.bind(id)
.fetch_optional(&mut **tx)
.await?;
Expand All @@ -822,10 +823,10 @@ impl<'c, P: Provider + Sync + Send + 'static> Executor<'c, P> {
}

// write the new balance to the database
sqlx::query(
"INSERT OR REPLACE INTO balances (id, contract_address, account_address, token_id, \
balance) VALUES (?, ?, ?, ?, ?)",
)
sqlx::query(&format!(
"INSERT OR REPLACE INTO {TOKEN_BALANCE_TABLE} (id, contract_address, account_address, \
token_id, balance) VALUES (?, ?, ?, ?, ?)",
))

Check warning on line 829 in crates/torii/core/src/executor.rs

View check run for this annotation

Codecov / codecov/patch

crates/torii/core/src/executor.rs#L826-L829

Added lines #L826 - L829 were not covered by tests
.bind(id)
.bind(contract_address)
.bind(account_address)
Expand Down
1 change: 1 addition & 0 deletions crates/torii/core/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
#![warn(unused_crate_dependencies)]

pub mod constants;
pub mod engine;
pub mod error;
pub mod executor;
Expand Down
10 changes: 6 additions & 4 deletions crates/torii/core/src/sql/cache.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ use sqlx::{Pool, Sqlite, SqlitePool};
use starknet_crypto::Felt;
use tokio::sync::RwLock;

use crate::constants::TOKEN_BALANCE_TABLE;
use crate::error::{Error, ParseError, QueryError};
use crate::model::{parse_sql_model_members, SqlModelMember};
use crate::sql::utils::I256;
Expand Down Expand Up @@ -140,10 +141,11 @@ impl Clone for LocalCache {
impl LocalCache {
pub async fn new(pool: Pool<Sqlite>) -> Self {
// read existing token_id's from balances table and cache them
let token_id_registry: Vec<(String,)> = sqlx::query_as("SELECT token_id FROM balances")
.fetch_all(&pool)
.await
.expect("Should be able to read token_id's from blances table");
let token_id_registry: Vec<(String,)> =
sqlx::query_as(&format!("SELECT token_id FROM {TOKEN_BALANCE_TABLE}"))
.fetch_all(&pool)
.await
.expect("Should be able to read token_id's from blances table");

let token_id_registry = token_id_registry.into_iter().map(|token_id| token_id.0).collect();

Expand Down
8 changes: 5 additions & 3 deletions crates/torii/core/src/sql/erc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ use starknet::providers::Provider;

use super::utils::{u256_to_sql_string, I256};
use super::{Sql, FELT_DELIMITER};
use crate::constants::TOKEN_TRANSFER_TABLE;
use crate::executor::{
ApplyBalanceDiffQuery, Argument, QueryMessage, QueryType, RegisterErc20TokenQuery,
RegisterErc721TokenQuery,
Expand Down Expand Up @@ -249,9 +250,10 @@ impl Sql {
block_timestamp: u64,
event_id: &str,
) -> Result<()> {
let insert_query = "INSERT INTO erc_transfers (id, contract_address, from_address, \
to_address, amount, token_id, executed_at) VALUES (?, ?, ?, ?, ?, ?, \
?)";
let insert_query = format!(
"INSERT INTO {TOKEN_TRANSFER_TABLE} (id, contract_address, from_address, to_address, \
amount, token_id, executed_at) VALUES (?, ?, ?, ?, ?, ?, ?)"
);

Check warning on line 256 in crates/torii/core/src/sql/erc.rs

View check run for this annotation

Codecov / codecov/patch

crates/torii/core/src/sql/erc.rs#L253-L256

Added lines #L253 - L256 were not covered by tests

self.executor.send(QueryMessage::new(
insert_query.to_string(),
Expand Down
15 changes: 6 additions & 9 deletions crates/torii/graphql/src/constants.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,6 @@ pub const EVENT_MESSAGE_TABLE: &str = "event_messages";
pub const MODEL_TABLE: &str = "models";
pub const TRANSACTION_TABLE: &str = "transactions";
pub const METADATA_TABLE: &str = "metadata";
pub const ERC_BALANCE_TABLE: &str = "balances";
pub const ERC_TRANSFER_TABLE: &str = "erc_transfers";

pub const ID_COLUMN: &str = "id";
pub const EVENT_ID_COLUMN: &str = "event_id";
Expand All @@ -35,9 +33,9 @@ pub const QUERY_TYPE_NAME: &str = "World__Query";
pub const SUBSCRIPTION_TYPE_NAME: &str = "World__Subscription";
pub const MODEL_ORDER_TYPE_NAME: &str = "World__ModelOrder";
pub const MODEL_ORDER_FIELD_TYPE_NAME: &str = "World__ModelOrderField";
pub const ERC_BALANCE_TYPE_NAME: &str = "ERC__Balance";
pub const ERC_TRANSFER_TYPE_NAME: &str = "ERC__Transfer";
pub const ERC_TOKEN_TYPE_NAME: &str = "ERC__Token";
pub const TOKEN_BALANCE_TYPE_NAME: &str = "Token__Balance";
pub const TOKEN_TRANSFER_TYPE_NAME: &str = "Token__Transfer";
pub const TOKEN_TYPE_NAME: &str = "ERC__Token";

// objects' single and plural names
pub const ENTITY_NAMES: (&str, &str) = ("entity", "entities");
Expand All @@ -49,10 +47,9 @@ pub const CONTENT_NAMES: (&str, &str) = ("content", "contents");
pub const METADATA_NAMES: (&str, &str) = ("metadata", "metadatas");
pub const TRANSACTION_NAMES: (&str, &str) = ("transaction", "transactions");
pub const PAGE_INFO_NAMES: (&str, &str) = ("pageInfo", "");

pub const ERC_BALANCE_NAME: (&str, &str) = ("ercBalance", "");
pub const ERC_TOKEN_NAME: (&str, &str) = ("ercToken", "");
pub const ERC_TRANSFER_NAME: (&str, &str) = ("ercTransfer", "");
pub const TOKEN_NAME: (&str, &str) = ("token", "tokens");
pub const TOKEN_BALANCE_NAME: (&str, &str) = ("", "tokenBalances");
pub const TOKEN_TRANSFER_NAME: (&str, &str) = ("", "tokenTransfers");

// misc
pub const ORDER_DIR_TYPE_NAME: &str = "OrderDirection";
Expand Down
14 changes: 8 additions & 6 deletions crates/torii/graphql/src/mapping.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use async_graphql::Name;
use dojo_types::primitive::Primitive;
use lazy_static::lazy_static;

use crate::constants::{CONTENT_TYPE_NAME, ERC_TOKEN_TYPE_NAME, SOCIAL_TYPE_NAME};
use crate::constants::{CONTENT_TYPE_NAME, SOCIAL_TYPE_NAME, TOKEN_TYPE_NAME};
use crate::types::{GraphqlType, TypeData, TypeMapping};

lazy_static! {
Expand Down Expand Up @@ -145,27 +145,29 @@ lazy_static! {
),
]);

pub static ref ERC_BALANCE_TYPE_MAPPING: TypeMapping = IndexMap::from([
pub static ref TOKEN_BALANCE_TYPE_MAPPING: TypeMapping = IndexMap::from([
(Name::new("balance"), TypeData::Simple(TypeRef::named_nn(TypeRef::STRING))),
(Name::new("type"), TypeData::Simple(TypeRef::named_nn(TypeRef::STRING))),
(Name::new("tokenMetadata"), TypeData::Simple(TypeRef::named_nn(ERC_TOKEN_TYPE_NAME))),
(Name::new("tokenMetadata"), TypeData::Simple(TypeRef::named_nn(TOKEN_TYPE_NAME))),
]);

pub static ref ERC_TRANSFER_TYPE_MAPPING: TypeMapping = IndexMap::from([
pub static ref TOKEN_TRANSFER_TYPE_MAPPING: TypeMapping = IndexMap::from([
(Name::new("from"), TypeData::Simple(TypeRef::named_nn(TypeRef::STRING))),
(Name::new("to"), TypeData::Simple(TypeRef::named_nn(TypeRef::STRING))),
(Name::new("amount"), TypeData::Simple(TypeRef::named_nn(TypeRef::STRING))),
(Name::new("type"), TypeData::Simple(TypeRef::named_nn(TypeRef::STRING))),
(Name::new("executedAt"), TypeData::Simple(TypeRef::named_nn(TypeRef::STRING))),
(Name::new("tokenMetadata"), TypeData::Simple(TypeRef::named_nn(ERC_TOKEN_TYPE_NAME))),
(Name::new("tokenMetadata"), TypeData::Simple(TypeRef::named_nn(TOKEN_TYPE_NAME))),
(Name::new("transactionHash"), TypeData::Simple(TypeRef::named_nn(TypeRef::STRING))),
]);

pub static ref ERC_TOKEN_TYPE_MAPPING: TypeMapping = IndexMap::from([
pub static ref TOKEN_TYPE_MAPPING: TypeMapping = IndexMap::from([
(Name::new("name"), TypeData::Simple(TypeRef::named_nn(TypeRef::STRING))),
(Name::new("symbol"), TypeData::Simple(TypeRef::named_nn(TypeRef::STRING))),
(Name::new("tokenId"), TypeData::Simple(TypeRef::named_nn(TypeRef::STRING))),
(Name::new("decimals"), TypeData::Simple(TypeRef::named_nn(TypeRef::STRING))),
(Name::new("contractAddress"), TypeData::Simple(TypeRef::named_nn(TypeRef::STRING))),
(Name::new("imagePath"), TypeData::Simple(TypeRef::named_nn(TypeRef::STRING))),
(Name::new("metadata"), TypeData::Simple(TypeRef::named_nn(TypeRef::STRING))),
]);
}
10 changes: 5 additions & 5 deletions crates/torii/graphql/src/object/erc/erc_token.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use crate::constants::{ERC_TOKEN_NAME, ERC_TOKEN_TYPE_NAME};
use crate::mapping::ERC_TOKEN_TYPE_MAPPING;
use crate::constants::{TOKEN_NAME, TOKEN_TYPE_NAME};
use crate::mapping::TOKEN_TYPE_MAPPING;
use crate::object::BasicObject;
use crate::types::TypeMapping;

Expand All @@ -8,14 +8,14 @@ pub struct ErcTokenObject;

impl BasicObject for ErcTokenObject {
fn name(&self) -> (&str, &str) {
ERC_TOKEN_NAME
TOKEN_NAME

Check warning on line 11 in crates/torii/graphql/src/object/erc/erc_token.rs

View check run for this annotation

Codecov / codecov/patch

crates/torii/graphql/src/object/erc/erc_token.rs#L11

Added line #L11 was not covered by tests
}

fn type_name(&self) -> &str {
ERC_TOKEN_TYPE_NAME
TOKEN_TYPE_NAME
}

fn type_mapping(&self) -> &TypeMapping {
&ERC_TOKEN_TYPE_MAPPING
&TOKEN_TYPE_MAPPING
}
}
4 changes: 2 additions & 2 deletions crates/torii/graphql/src/object/erc/mod.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
use super::connection::cursor;
use crate::query::order::CursorDirection;

pub mod erc_balance;
pub mod erc_token;
pub mod erc_transfer;
pub mod token_balance;
pub mod token_transfer;

fn handle_cursor(
cursor: &str,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,13 @@ use serde::Deserialize;
use sqlx::sqlite::SqliteRow;
use sqlx::{FromRow, Pool, Row, Sqlite, SqliteConnection};
use starknet_crypto::Felt;
use torii_core::constants::TOKEN_BALANCE_TABLE;
use torii_core::sql::utils::felt_to_sql_string;
use tracing::warn;

use super::handle_cursor;
use crate::constants::{
DEFAULT_LIMIT, ERC_BALANCE_NAME, ERC_BALANCE_TABLE, ERC_BALANCE_TYPE_NAME, ID_COLUMN,
};
use crate::mapping::ERC_BALANCE_TYPE_MAPPING;
use crate::constants::{DEFAULT_LIMIT, ID_COLUMN, TOKEN_BALANCE_NAME, TOKEN_BALANCE_TYPE_NAME};
use crate::mapping::TOKEN_BALANCE_TYPE_MAPPING;
use crate::object::connection::page_info::PageInfoObject;
use crate::object::connection::{
connection_arguments, cursor, parse_connection_arguments, ConnectionArguments,
Expand All @@ -30,15 +29,15 @@ pub struct ErcBalanceObject;

impl BasicObject for ErcBalanceObject {
fn name(&self) -> (&str, &str) {
ERC_BALANCE_NAME
TOKEN_BALANCE_NAME
}

fn type_name(&self) -> &str {
ERC_BALANCE_TYPE_NAME
TOKEN_BALANCE_TYPE_NAME
}

fn type_mapping(&self) -> &TypeMapping {
&ERC_BALANCE_TYPE_MAPPING
&TOKEN_BALANCE_TYPE_MAPPING
}
}

Expand All @@ -51,7 +50,7 @@ impl ResolvableObject for ErcBalanceObject {
);

let mut field = Field::new(
self.name().0,
self.name().1,
TypeRef::named(format!("{}Connection", self.type_name())),
move |ctx| {
FieldFuture::new(async move {
Expand All @@ -69,12 +68,12 @@ impl ResolvableObject for ErcBalanceObject {
}];

let total_count =
count_rows(&mut conn, ERC_BALANCE_TABLE, &None, &Some(filter)).await?;
count_rows(&mut conn, TOKEN_BALANCE_TABLE, &None, &Some(filter)).await?;

Check warning on line 71 in crates/torii/graphql/src/object/erc/token_balance.rs

View check run for this annotation

Codecov / codecov/patch

crates/torii/graphql/src/object/erc/token_balance.rs#L71

Added line #L71 was not covered by tests

let (data, page_info) =
fetch_erc_balances(&mut conn, address, &connection, total_count).await?;
fetch_token_balances(&mut conn, address, &connection, total_count).await?;

Check warning on line 74 in crates/torii/graphql/src/object/erc/token_balance.rs

View check run for this annotation

Codecov / codecov/patch

crates/torii/graphql/src/object/erc/token_balance.rs#L74

Added line #L74 was not covered by tests

let results = erc_balance_connection_output(&data, total_count, page_info)?;
let results = token_balances_connection_output(&data, total_count, page_info)?;

Check warning on line 76 in crates/torii/graphql/src/object/erc/token_balance.rs

View check run for this annotation

Codecov / codecov/patch

crates/torii/graphql/src/object/erc/token_balance.rs#L76

Added line #L76 was not covered by tests

Ok(Some(Value::Object(results)))
})
Expand All @@ -87,18 +86,18 @@ impl ResolvableObject for ErcBalanceObject {
}
}

async fn fetch_erc_balances(
async fn fetch_token_balances(

Check warning on line 89 in crates/torii/graphql/src/object/erc/token_balance.rs

View check run for this annotation

Codecov / codecov/patch

crates/torii/graphql/src/object/erc/token_balance.rs#L89

Added line #L89 was not covered by tests
conn: &mut SqliteConnection,
address: Felt,
connection: &ConnectionArguments,
total_count: i64,
) -> sqlx::Result<(Vec<SqliteRow>, PageInfo)> {
let table_name = ERC_BALANCE_TABLE;
let table_name = TOKEN_BALANCE_TABLE;

Check warning on line 95 in crates/torii/graphql/src/object/erc/token_balance.rs

View check run for this annotation

Codecov / codecov/patch

crates/torii/graphql/src/object/erc/token_balance.rs#L95

Added line #L95 was not covered by tests
let id_column = format!("b.{}", ID_COLUMN);

let mut query = format!(
"SELECT b.id, t.contract_address, t.name, t.symbol, t.decimals, b.balance, b.token_id, \
c.contract_type
t.metadata, c.contract_type

Check warning on line 100 in crates/torii/graphql/src/object/erc/token_balance.rs

View check run for this annotation

Codecov / codecov/patch

crates/torii/graphql/src/object/erc/token_balance.rs#L100

Added line #L100 was not covered by tests
FROM {table_name} b
JOIN tokens t ON b.token_id = t.id
JOIN contracts c ON t.contract_address = c.contract_address"
Expand Down Expand Up @@ -207,7 +206,7 @@ async fn fetch_erc_balances(
}
}

fn erc_balance_connection_output(
fn token_balances_connection_output(

Check warning on line 209 in crates/torii/graphql/src/object/erc/token_balance.rs

View check run for this annotation

Codecov / codecov/patch

crates/torii/graphql/src/object/erc/token_balance.rs#L209

Added line #L209 was not covered by tests
data: &[SqliteRow],
total_count: i64,
page_info: PageInfo,
Expand All @@ -226,6 +225,9 @@ fn erc_balance_connection_output(
(Name::new("tokenId"), Value::Null),
(Name::new("decimals"), Value::String(row.decimals.to_string())),
(Name::new("contractAddress"), Value::String(row.contract_address.clone())),
// for erc20 there is no image_path and metadata
(Name::new("imagePath"), Value::Null),
(Name::new("metadata"), Value::Null),

Check warning on line 230 in crates/torii/graphql/src/object/erc/token_balance.rs

View check run for this annotation

Codecov / codecov/patch

crates/torii/graphql/src/object/erc/token_balance.rs#L228-L230

Added lines #L228 - L230 were not covered by tests
]));

Value::Object(ValueMapping::from([
Expand All @@ -239,12 +241,15 @@ fn erc_balance_connection_output(
let token_id = row.token_id.split(':').collect::<Vec<&str>>();
assert!(token_id.len() == 2);

let image_path = format!("{}/{}", token_id.join("/"), "image");

Check warning on line 244 in crates/torii/graphql/src/object/erc/token_balance.rs

View check run for this annotation

Codecov / codecov/patch

crates/torii/graphql/src/object/erc/token_balance.rs#L244

Added line #L244 was not covered by tests
let token_metadata = Value::Object(ValueMapping::from([
(Name::new("contractAddress"), Value::String(row.contract_address.clone())),
(Name::new("name"), Value::String(row.name)),
(Name::new("symbol"), Value::String(row.symbol)),
(Name::new("tokenId"), Value::String(token_id[1].to_string())),
(Name::new("decimals"), Value::String(row.decimals.to_string())),
(Name::new("imagePath"), Value::String(image_path)),
(Name::new("metadata"), Value::String(row.metadata)),

Check warning on line 252 in crates/torii/graphql/src/object/erc/token_balance.rs

View check run for this annotation

Codecov / codecov/patch

crates/torii/graphql/src/object/erc/token_balance.rs#L251-L252

Added lines #L251 - L252 were not covered by tests
]));

Value::Object(ValueMapping::from([
Expand Down Expand Up @@ -291,4 +296,5 @@ struct BalanceQueryResultRaw {
pub token_id: String,
pub balance: String,
pub contract_type: String,
pub metadata: String,
}
Loading

0 comments on commit 43a3c23

Please sign in to comment.