diff --git a/.cursor/worktrees.json b/.cursor/worktrees.json index d67853824..60223f0ff 100644 --- a/.cursor/worktrees.json +++ b/.cursor/worktrees.json @@ -1,5 +1,6 @@ { "setup-worktree": [ + "cd codegenerator/cli/npm/envio && pnpm install && pnpm rescript", "cd scenarios/test_codegen && pnpm install", "pnpm codegen", "pnpm rescript", diff --git a/.github/workflows/build_and_test.yml b/.github/workflows/build_and_test.yml index 8516e0134..9df64bb97 100644 --- a/.github/workflows/build_and_test.yml +++ b/.github/workflows/build_and_test.yml @@ -125,7 +125,7 @@ jobs: if: steps.changes.outputs.testChanges == 'true' uses: actions/setup-node@v4 with: - node-version: 18.15.0 + node-version: 22.10.0 - name: test_codegen build if: steps.changes.outputs.testChanges == 'true' diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 0534c9e27..4994006a7 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -222,7 +222,7 @@ jobs: - name: Install node uses: actions/setup-node@v4 with: - node-version: "18.16.0" + node-version: 22.10.0 registry-url: "https://registry.npmjs.org" - name: Publish to NPM @@ -277,7 +277,7 @@ jobs: - name: Install Node.js uses: actions/setup-node@v4 with: - node-version: 20 + node-version: 22.10.0 registry-url: "https://registry.npmjs.org" cache: "pnpm" cache-dependency-path: codegenerator/cli/npm/envio/pnpm-lock.yaml diff --git a/.github/workflows/templates_integration_test.yml b/.github/workflows/templates_integration_test.yml index f8dd331e6..e16be9a89 100644 --- a/.github/workflows/templates_integration_test.yml +++ b/.github/workflows/templates_integration_test.yml @@ -60,7 +60,7 @@ jobs: - name: Setup Node.js uses: actions/setup-node@v4 with: - node-version: "20.x" + node-version: 22.10.0 - name: Pre-pull docker-compose images run: | cd ../cli/templates/static/codegen # we use the docker-compose.yml in the static folder diff --git a/codegenerator/cli/npm/envio/evm.schema.json b/codegenerator/cli/npm/envio/evm.schema.json index 1117e8a7b..abc00c1bf 100644 --- a/codegenerator/cli/npm/envio/evm.schema.json +++ b/codegenerator/cli/npm/envio/evm.schema.json @@ -124,6 +124,13 @@ "type": "null" } ] + }, + "handlers": { + "description": "Optional relative path to handlers directory for auto-loading. Defaults to 'src/handlers' if not specified.", + "type": [ + "string", + "null" + ] } }, "additionalProperties": false, @@ -153,8 +160,11 @@ ] }, "handler": { - "description": "The relative path to a file where handlers are registered for the given contract", - "type": "string" + "description": "Optional relative path to a file where handlers are registered for the given contract. If not provided, handlers can be auto-loaded from src directory.", + "type": [ + "string", + "null" + ] }, "events": { "description": "A list of events that should be indexed on this contract", @@ -167,7 +177,6 @@ "additionalProperties": false, "required": [ "name", - "handler", "events" ] }, @@ -611,8 +620,11 @@ ] }, "handler": { - "description": "The relative path to a file where handlers are registered for the given contract", - "type": "string" + "description": "Optional relative path to a file where handlers are registered for the given contract. If not provided, handlers can be auto-loaded from src directory.", + "type": [ + "string", + "null" + ] }, "events": { "description": "A list of events that should be indexed on this contract", diff --git a/codegenerator/cli/npm/envio/fuel.schema.json b/codegenerator/cli/npm/envio/fuel.schema.json index 4ac9c66e5..3851fd8c4 100644 --- a/codegenerator/cli/npm/envio/fuel.schema.json +++ b/codegenerator/cli/npm/envio/fuel.schema.json @@ -63,6 +63,13 @@ "boolean", "null" ] + }, + "handlers": { + "description": "Optional relative path to handlers directory for auto-loading. Defaults to 'src/handlers' if not specified.", + "type": [ + "string", + "null" + ] } }, "additionalProperties": false, @@ -90,8 +97,11 @@ "type": "string" }, "handler": { - "description": "The relative path to a file where handlers are registered for the given contract", - "type": "string" + "description": "Optional relative path to a file where handlers are registered for the given contract. If not provided, handlers can be auto-loaded from src directory.", + "type": [ + "string", + "null" + ] }, "events": { "description": "A list of events that should be indexed on this contract", @@ -105,7 +115,6 @@ "required": [ "name", "abi_file_path", - "handler", "events" ] }, @@ -238,8 +247,11 @@ "type": "string" }, "handler": { - "description": "The relative path to a file where handlers are registered for the given contract", - "type": "string" + "description": "Optional relative path to a file where handlers are registered for the given contract. If not provided, handlers can be auto-loaded from src directory.", + "type": [ + "string", + "null" + ] }, "events": { "description": "A list of events that should be indexed on this contract", diff --git a/codegenerator/cli/npm/envio/package.json b/codegenerator/cli/npm/envio/package.json index bf2f5a56b..56adc8c58 100644 --- a/codegenerator/cli/npm/envio/package.json +++ b/codegenerator/cli/npm/envio/package.json @@ -19,6 +19,9 @@ "url": "https://github.com/enviodev/hyperindex/issues" }, "homepage": "https://envio.dev", + "engines": { + "node": ">=22.0.0 <=22.10.0" + }, "dependencies": { "@clickhouse/client": "1.12.1", "@envio-dev/hypersync-client": "0.6.6", diff --git a/codegenerator/cli/npm/envio/package.json.tmpl b/codegenerator/cli/npm/envio/package.json.tmpl index 1738281d4..a74c002ee 100644 --- a/codegenerator/cli/npm/envio/package.json.tmpl +++ b/codegenerator/cli/npm/envio/package.json.tmpl @@ -24,6 +24,9 @@ "url": "https://github.com/enviodev/hyperindex/issues" }, "homepage": "https://envio.dev", + "engines": { + "node": ">=22.0.0 <=22.10.0" + }, "optionalDependencies": { "envio-linux-x64": "${version}", "envio-linux-arm64": "${version}", diff --git a/codegenerator/cli/npm/envio/src/Utils.res b/codegenerator/cli/npm/envio/src/Utils.res index 7bdcb799e..a88c3ac77 100644 --- a/codegenerator/cli/npm/envio/src/Utils.res +++ b/codegenerator/cli/npm/envio/src/Utils.res @@ -198,6 +198,8 @@ module UnsafeIntOperators = { external \"-": (int, int) => int = "%subfloat" } +type asyncIterator<'a> + module Array = { let immutableEmpty: array = [] @@ -360,6 +362,19 @@ Helper to check if a value exists in an array external copy: array<'a> => array<'a> = "slice" @send external at: (array<'a>, int) => option<'a> = "at" + + /** + Converts an async iterator to an array by iterating through all values + */ + let fromAsyncIterator: asyncIterator => promise< + array, + > = %raw(`async (iterator) => { + const result = []; + for await (const item of iterator) { + result.push(item); + } + return result; + }`) } module String = { diff --git a/codegenerator/cli/npm/envio/src/db/InternalTable.res b/codegenerator/cli/npm/envio/src/db/InternalTable.res index 422dbef11..5fb3d8271 100644 --- a/codegenerator/cli/npm/envio/src/db/InternalTable.res +++ b/codegenerator/cli/npm/envio/src/db/InternalTable.res @@ -357,7 +357,6 @@ module PersistedState = { envio_version: string, config_hash: string, schema_hash: string, - handler_files_hash: string, abi_files_hash: string, } @@ -368,7 +367,6 @@ module PersistedState = { mkField("envio_version", String, ~fieldSchema=S.string), mkField("config_hash", String, ~fieldSchema=S.string), mkField("schema_hash", String, ~fieldSchema=S.string), - mkField("handler_files_hash", String, ~fieldSchema=S.string), mkField("abi_files_hash", String, ~fieldSchema=S.string), ], ) diff --git a/codegenerator/cli/src/cli_args/init_config.rs b/codegenerator/cli/src/cli_args/init_config.rs index 0b8731b48..d4df21e05 100644 --- a/codegenerator/cli/src/cli_args/init_config.rs +++ b/codegenerator/cli/src/cli_args/init_config.rs @@ -61,40 +61,38 @@ pub mod evm { }) .collect(); - let handler = init_config.language.get_event_handler_directory(); - - let config = if is_multi_chain_contract { - //Add the contract to global contract config and return none for local contract - //config - let global_contract = GlobalContract { - name: selected_contract.name.clone(), - config: ContractConfig { - abi_file_path: None, - handler, - events, - }, - }; - - unique_hashmap::try_insert( - &mut global_contracts, - selected_contract.name.clone(), - global_contract, - ) - .context(format!( - "Unexpected, failed to add global contract {}. Contract should have \ - unique names", - selected_contract.name - ))?; - None - } else { - //Return some for local contract config - Some(ContractConfig { + let config = if is_multi_chain_contract { + //Add the contract to global contract config and return none for local contract + //config + let global_contract = GlobalContract { + name: selected_contract.name.clone(), + config: ContractConfig { abi_file_path: None, - handler, - events, - }) + handler: None, + events: events.clone(), + }, }; + unique_hashmap::try_insert( + &mut global_contracts, + selected_contract.name.clone(), + global_contract, + ) + .context(format!( + "Unexpected, failed to add global contract {}. Contract should have \ + unique names", + selected_contract.name + ))?; + None + } else { + //Return some for local contract config + Some(ContractConfig { + abi_file_path: None, + handler: None, + events, + }) + }; + for selected_network in &selected_contract.networks { let address = selected_network .addresses @@ -172,6 +170,7 @@ pub mod evm { raw_events: None, preload_handlers: Some(true), address_format: None, + handlers: None, }) } @@ -282,11 +281,11 @@ pub mod fuel { .map(|a| a.to_string()) .collect::>() .into(), - config: Some(ContractConfig { - abi_file_path: selected_contract.get_vendored_abi_file_path(), - handler: init_config.language.get_event_handler_directory(), - events: selected_contract.selected_events.clone(), - }), + config: Some(ContractConfig { + abi_file_path: selected_contract.get_vendored_abi_file_path(), + handler: None, + events: selected_contract.selected_events.clone(), + }), start_block: None, }) .collect(), @@ -304,6 +303,7 @@ pub mod fuel { raw_events: None, preload_handlers: Some(true), networks: network_configs, + handlers: None, } } } diff --git a/codegenerator/cli/src/config_parsing/graph_migration/mod.rs b/codegenerator/cli/src/config_parsing/graph_migration/mod.rs index 3a706347f..39bb9c046 100644 --- a/codegenerator/cli/src/config_parsing/graph_migration/mod.rs +++ b/codegenerator/cli/src/config_parsing/graph_migration/mod.rs @@ -1,5 +1,4 @@ use crate::{ - cli_args::init_config::Language, config_parsing::{ chain_helpers::{self, GraphNetwork}, human_config::{ @@ -111,14 +110,6 @@ pub struct BlockHandler { pub handler: String, } -// Logic to get the event handler directory based on the language -fn get_event_handler_directory(language: &Language) -> String { - match language { - Language::ReScript => "./src/EventHandlers.res.js".to_string(), - Language::TypeScript => "./src/EventHandlers.ts".to_string(), - } -} - // Function to replace unsupported field types from schema fn update_schema_with_supported_field_types(schema_str: String) -> String { schema_str.replace("BigDecimal", "Float") @@ -243,7 +234,6 @@ fn valid_ipfs_cid(cid: &str) -> bool { pub async fn generate_config_from_subgraph_id( project_root_path: &PathBuf, subgraph_id: &str, - language: &Language, ) -> anyhow::Result { if !valid_ipfs_cid(subgraph_id) { return Err(anyhow!( @@ -285,6 +275,7 @@ pub async fn generate_config_from_subgraph_id( raw_events: None, preload_handlers: Some(true), address_format: None, + handlers: None, }; let mut networks: Vec = vec![]; @@ -362,7 +353,7 @@ pub async fn generate_config_from_subgraph_id( address: vec![data_source.source.address.to_string()].into(), config: Some(ContractConfig { abi_file_path: Some(format!("abis/{}.json", data_source.name)), - handler: get_event_handler_directory(language), + handler: None, events, }), start_block: None, @@ -444,12 +435,9 @@ async fn fetch_ipfs_file_and_write_to_system( #[cfg(test)] // ignore from the compiler when it builds, only checked when we run cargo test mod test { use super::GraphManifest; - use crate::{ - cli_args::init_config::Language, - config_parsing::{ - chain_helpers::{GraphNetwork, Network}, - graph_migration::get_ipfs_id_from_file_path, - }, + use crate::config_parsing::{ + chain_helpers::{GraphNetwork, Network}, + graph_migration::get_ipfs_id_from_file_path, }; use std::{collections::HashMap, path::PathBuf}; use tempdir::TempDir; @@ -461,9 +449,8 @@ mod test { let temp_dir = TempDir::new("temp_graph_migration_folder").unwrap(); // subgraph ID of USDC on Ethereum mainnet let cid: &str = "QmU5V3jy56KnFbxX2uZagvMwocYZASzy1inX828W2XWtTd"; - let language: Language = Language::ReScript; let project_root = PathBuf::from(temp_dir.path()); - super::generate_config_from_subgraph_id(&project_root, cid, &language) + super::generate_config_from_subgraph_id(&project_root, cid) .await .unwrap(); } @@ -548,16 +535,6 @@ mod test { get_ipfs_id_from_file_path(non_unicode_string); } - // Unit test to check that the correct event handler directory is returned based on the language - #[test] - fn test_get_event_handler_directory() { - let language_1: Language = Language::ReScript; - let language_2: Language = Language::TypeScript; - let event_handler_directory_1 = super::get_event_handler_directory(&language_1); - let event_handler_directory_2 = super::get_event_handler_directory(&language_2); - assert_eq!(event_handler_directory_1, "./src/EventHandlers.res.js"); - assert_eq!(event_handler_directory_2, "./src/EventHandlers.ts"); - } // Unit test to check that the correct network contract hashmap is generated #[tokio::test] async fn test_generate_network_contract_hashmap() { diff --git a/codegenerator/cli/src/config_parsing/human_config.rs b/codegenerator/cli/src/config_parsing/human_config.rs index 2bb88ae28..4c49346d8 100644 --- a/codegenerator/cli/src/config_parsing/human_config.rs +++ b/codegenerator/cli/src/config_parsing/human_config.rs @@ -216,6 +216,12 @@ pub mod evm { #[schemars(description = "Address format for Ethereum addresses: 'checksum' or \ 'lowercase' (default: checksum)")] pub address_format: Option, + #[serde(skip_serializing_if = "Option::is_none")] + #[schemars( + description = "Optional relative path to handlers directory for auto-loading. Defaults \ + to 'src/handlers' if not specified." + )] + pub handlers: Option, } #[derive(Debug, Serialize, Deserialize, PartialEq, Clone, JsonSchema)] @@ -504,11 +510,13 @@ pub mod evm { configured event should simply be referenced by its name" )] pub abi_file_path: Option, + #[serde(skip_serializing_if = "Option::is_none")] #[schemars( - description = "The relative path to a file where handlers are registered for the \ - given contract" + description = "Optional relative path to a file where handlers are registered for the \ + given contract. If not provided, handlers can be auto-loaded from src \ + directory." )] - pub handler: String, + pub handler: Option, #[schemars(description = "A list of events that should be indexed on this contract")] pub events: Vec, } @@ -596,6 +604,12 @@ pub mod fuel { false)" )] pub preload_handlers: Option, + #[serde(skip_serializing_if = "Option::is_none")] + #[schemars( + description = "Optional relative path to handlers directory for auto-loading. Defaults \ + to 'src/handlers' if not specified." + )] + pub handlers: Option, } impl Display for HumanConfig { @@ -647,11 +661,13 @@ pub mod fuel { pub struct ContractConfig { #[schemars(description = "Relative path (from config) to a json abi.")] pub abi_file_path: String, + #[serde(skip_serializing_if = "Option::is_none")] #[schemars( - description = "The relative path to a file where handlers are registered for the \ - given contract" + description = "Optional relative path to a file where handlers are registered for the \ + given contract. If not provided, handlers can be auto-loaded from src \ + directory." )] - pub handler: String, + pub handler: Option, #[schemars(description = "A list of events that should be indexed on this contract")] pub events: Vec, } @@ -748,7 +764,7 @@ events: [] start_block: None, config: Some(ContractConfig { abi_file_path: None, - handler: "./src/EventHandler.js".to_string(), + handler: Some("./src/EventHandler.js".to_string()), events: vec![], }), }; @@ -771,7 +787,7 @@ events: [] start_block: None, config: Some(ContractConfig { abi_file_path: None, - handler: "./src/EventHandler.js".to_string(), + handler: Some("./src/EventHandler.js".to_string()), events: vec![], }), }; @@ -795,7 +811,7 @@ events: [] start_block: None, config: Some(ContractConfig { abi_file_path: None, - handler: "./src/EventHandler.js".to_string(), + handler: Some("./src/EventHandler.js".to_string()), events: vec![], }), }; @@ -904,7 +920,7 @@ address: ["0x2E645469f354BB4F5c8a05B3b30A929361cf77eC"] start_block: None, config: Some(fuel::ContractConfig { abi_file_path: "../abis/greeter-abi.json".to_string(), - handler: "./src/EventHandlers.js".to_string(), + handler: Some("./src/EventHandlers.js".to_string()), events: vec![ fuel::EventConfig { name: "NewGreeting".to_string(), @@ -920,6 +936,7 @@ address: ["0x2E645469f354BB4F5c8a05B3b30A929361cf77eC"] }), }], }], + handlers: None, }; // deserializes fuel config @@ -938,6 +955,7 @@ address: ["0x2E645469f354BB4F5c8a05B3b30A929361cf77eC"] raw_events: None, preload_handlers: None, networks: vec![], + handlers: None, }; assert_eq!( diff --git a/codegenerator/cli/src/config_parsing/system_config.rs b/codegenerator/cli/src/config_parsing/system_config.rs index fb12eec80..706447a33 100644 --- a/codegenerator/cli/src/config_parsing/system_config.rs +++ b/codegenerator/cli/src/config_parsing/system_config.rs @@ -416,6 +416,7 @@ pub struct SystemConfig { pub human_config: HumanConfig, pub lowercase_addresses: bool, pub should_use_hypersync_client_decoder: bool, + pub handlers: Option, } //Getter methods for system config @@ -499,20 +500,6 @@ impl SystemConfig { Ok(schema_path) } - pub fn get_all_paths_to_handlers(&self) -> Result> { - let mut all_paths_to_handlers = self - .get_contracts() - .into_iter() - .map(|c| c.get_path_to_handler(&self.parsed_project_paths)) - .collect::>>()? - .into_iter() - .collect::>(); - - all_paths_to_handlers.sort(); - - Ok(all_paths_to_handlers) - } - pub fn get_all_paths_to_abi_files(&self) -> Result> { let mut filtered_unique_abi_files = self .get_contracts() @@ -733,7 +720,8 @@ impl SystemConfig { true } }, - human_config, + handlers: evm_config.handlers.clone(), + human_config: human_config, }) } HumanConfig::Fuel(ref fuel_config) => { @@ -872,7 +860,8 @@ impl SystemConfig { preload_handlers: fuel_config.preload_handlers.unwrap_or(false), lowercase_addresses: false, should_use_hypersync_client_decoder: true, - human_config, + handlers: fuel_config.handlers.clone(), + human_config: human_config, }) } } @@ -1193,13 +1182,18 @@ impl Abi { #[derive(Debug, Clone, PartialEq)] pub struct Contract { pub name: ContractNameKey, - pub handler_path: String, + pub handler_path: Option, pub abi: Abi, pub events: Vec, } impl Contract { - pub fn new(name: String, handler_path: String, events: Vec, abi: Abi) -> Result { + pub fn new( + name: String, + handler_path: Option, + events: Vec, + abi: Abi, + ) -> Result { // TODO: Validatate that all event names are unique validate_names_valid_rescript( &events.iter().map(|e| e.name.clone()).collect(), @@ -1214,19 +1208,6 @@ impl Contract { }) } - pub fn get_path_to_handler(&self, project_paths: &ParsedProjectPaths) -> Result { - let handler_path = path_utils::get_config_path_relative_to_root( - project_paths, - PathBuf::from(&self.handler_path), - ) - .context(format!( - "Failed creating a relative path to handler in contract {}", - self.name - ))?; - - Ok(handler_path) - } - pub fn get_chain_ids(&self, system_config: &SystemConfig) -> Vec { system_config .get_networks() @@ -2108,6 +2089,7 @@ mod test { raw_events: None, preload_handlers: None, address_format: None, + handlers: None, }; let project_paths = ParsedProjectPaths::new(".", "generated", "config.yaml").unwrap(); @@ -2155,6 +2137,7 @@ mod test { raw_events: None, preload_handlers: None, address_format: None, + handlers: None, }; let system_config_with_output = SystemConfig::from_human_config( diff --git a/codegenerator/cli/src/executor/init.rs b/codegenerator/cli/src/executor/init.rs index 9871d3337..814b3188b 100644 --- a/codegenerator/cli/src/executor/init.rs +++ b/codegenerator/cli/src/executor/init.rs @@ -79,13 +79,10 @@ pub async fn run_init_args(init_args: InitArgs, project_paths: &ProjectPaths) -> &init_config.language, &parsed_project_paths.project_root, ))?; - let evm_config = generate_config_from_subgraph_id( - &parsed_project_paths.project_root, - cid, - &init_config.language, - ) - .await - .context("Failed generating config from subgraph")?; + let evm_config = + generate_config_from_subgraph_id(&parsed_project_paths.project_root, cid) + .await + .context("Failed generating config from subgraph")?; let system_config = SystemConfig::from_human_config( HumanConfig::Evm(evm_config), @@ -169,6 +166,7 @@ pub async fn run_init_args(init_args: InitArgs, project_paths: &ProjectPaths) -> .generate_contract_import_templates( &init_config.language, &parsed_project_paths.project_root, + true, // is_fuel ) .context( "Failed generating contract import templates for schema and event handlers.", @@ -222,6 +220,7 @@ pub async fn run_init_args(init_args: InitArgs, project_paths: &ProjectPaths) -> .generate_contract_import_templates( &init_config.language, &parsed_project_paths.project_root, + false, // is_fuel ) .context( "Failed generating contract import templates for schema and event handlers.", diff --git a/codegenerator/cli/src/hbs_templating/codegen_templates.rs b/codegenerator/cli/src/hbs_templating/codegen_templates.rs index 1358494b4..e128b30a0 100644 --- a/codegenerator/cli/src/hbs_templating/codegen_templates.rs +++ b/codegenerator/cli/src/hbs_templating/codegen_templates.rs @@ -18,10 +18,7 @@ use crate::{ }, }, persisted_state::{PersistedState, PersistedStateJsonString}, - project_paths::{ - handler_paths::HandlerPathsTemplate, path_utils::add_trailing_relative_dot, - ParsedProjectPaths, - }, + project_paths::{path_utils::add_trailing_relative_dot, ParsedProjectPaths}, rescript_types::{ RescriptRecordField, RescriptSchemaMode, RescriptTypeExpr, RescriptTypeIdent, }, @@ -807,18 +804,16 @@ pub struct ContractTemplate { pub name: CapitalizedOptions, pub codegen_events: Vec, pub module_code: String, - pub handler: HandlerPathsTemplate, + pub handler: Option, } impl ContractTemplate { fn from_config_contract( contract: &system_config::Contract, - project_paths: &ParsedProjectPaths, config: &SystemConfig, ) -> Result { let name = contract.name.to_capitalized_options(); - let handler = HandlerPathsTemplate::from_contract(contract, project_paths) - .context("Failed building handler paths template")?; + let handler = contract.handler_path.clone(); let codegen_events = contract .events .iter() @@ -1266,7 +1261,6 @@ struct SelectedFieldTemplate { pub struct ProjectTemplate { project_name: String, codegen_contracts: Vec, - has_typescript: bool, entities: Vec, gql_enums: Vec, chain_configs: Vec, @@ -1286,8 +1280,10 @@ pub struct ProjectTemplate { ts_types_code: String, //Used for the package.json reference to handlers in generated relative_path_to_root_from_generated: String, + relative_path_to_generated_from_root: String, lowercase_addresses: bool, should_use_hypersync_client_decoder: bool, + handlers_path: Option, } impl ProjectTemplate { @@ -1310,9 +1306,7 @@ impl ProjectTemplate { let codegen_contracts: Vec = cfg .get_contracts() .iter() - .map(|cfg_contract| { - ContractTemplate::from_config_contract(cfg_contract, project_paths, cfg) - }) + .map(|cfg_contract| ContractTemplate::from_config_contract(cfg_contract, cfg)) .collect::>() .context("Failed generating contract template types")?; @@ -1365,14 +1359,14 @@ impl ProjectTemplate { diff_from_current(&project_paths.project_root, &project_paths.generated) .context("Failed to get relative path from output directory to project root")?; + let relative_path_to_generated_from_root = + diff_from_current(&project_paths.generated, &project_paths.project_root) + .context("Failed to get relative path from project root to generated")?; + let global_field_selection = FieldSelection::global_selection(&cfg.field_selection); // TODO: Remove schemas for aggreaged, since they are not used in runtime let aggregated_field_selection = FieldSelection::aggregated_selection(cfg); - let has_typescript = codegen_contracts - .iter() - .any(|contract| contract.handler.relative_to_config.ends_with(".ts")); - let types_code = format!( r#"@genType type chainId = int @@ -1390,7 +1384,6 @@ type chain = [{chain_id_type}]"#, Ok(ProjectTemplate { project_name: cfg.name.clone(), - has_typescript, codegen_contracts, entities, gql_enums, @@ -1411,8 +1404,10 @@ type chain = [{chain_id_type}]"#, ts_types_code, //Used for the package.json reference to handlers in generated relative_path_to_root_from_generated, + relative_path_to_generated_from_root, lowercase_addresses: cfg.lowercase_addresses, should_use_hypersync_client_decoder: cfg.should_use_hypersync_client_decoder, + handlers_path: cfg.handlers.clone(), }) } } diff --git a/codegenerator/cli/src/hbs_templating/contract_import_templates.rs b/codegenerator/cli/src/hbs_templating/contract_import_templates.rs index 75123086b..0c9cb41bf 100644 --- a/codegenerator/cli/src/hbs_templating/contract_import_templates.rs +++ b/codegenerator/cli/src/hbs_templating/contract_import_templates.rs @@ -239,6 +239,128 @@ impl Contract { imported_events, }) } + + /// Generates TypeScript handler file content for this contract + pub fn generate_typescript_handler_content(&self, _is_fuel: bool) -> String { + let mut content = String::new(); + + // Header comment + content.push_str("/*\n"); + content.push_str(" * Please refer to https://docs.envio.dev for a thorough guide on all Envio indexer features\n"); + content.push_str(" */\n"); + + // Import statement for contract module + content.push_str(&format!( + "import {{ {} }} from \"generated\";\n", + self.name.capitalized + )); + + // Import type statement for entity types + if !self.imported_events.is_empty() { + content.push_str("import type {\n"); + for event in &self.imported_events { + content.push_str(&format!(" {}_{},\n", self.name.capitalized, event.name)); + } + content.push_str("} from \"generated\";\n"); + } + + // Handler registrations + for event in &self.imported_events { + content.push_str("\n"); + content.push_str(&format!( + "{}.{}.handler(async ({{ event, context }}) => {{\n", + self.name.capitalized, event.name + )); + content.push_str(&format!( + " const entity: {}_{} = {{\n", + self.name.capitalized, event.name + )); + content.push_str(&format!(" id: {},\n", event.entity_id_from_event_code)); + + // Add params + for param in &event.params { + content.push_str(&format!( + " {}: event.params.{}", + param.entity_key.uncapitalized, param.event_key.original + )); + + // Add tuple accessor indexes if present + if let Some(indexes) = ¶m.tuple_param_accessor_indexes { + for index in indexes { + content.push_str(&format!("[{}]", index)); + } + } + content.push_str(",\n"); + } + + content.push_str(" };\n\n"); + content.push_str(&format!( + " context.{}_{}.set(entity);\n", + self.name.capitalized, event.name + )); + content.push_str("});\n"); + } + + content + } + + /// Generates ReScript handler file content for this contract + pub fn generate_rescript_handler_content(&self, _is_fuel: bool) -> String { + let mut content = String::new(); + + // Header comment + content.push_str("/*\n"); + content.push_str(" * Please refer to https://docs.envio.dev for a thorough guide on all Envio indexer features\n"); + content.push_str(" */\n"); + + // Handler registrations + for event in &self.imported_events { + content.push_str("\n"); + content.push_str(&format!( + "Handlers.{}.{}.handler(async ({{event, context}}) => {{\n", + self.name.capitalized, event.name + )); + content.push_str(&format!( + " let entity: Types.{}_{} = {{\n", + self.name.uncapitalized, event.name + )); + content.push_str(&format!(" id: {},\n", event.entity_id_from_event_code)); + + // Add params + for param in &event.params { + content.push_str(&format!( + " {}: event.params.{}", + param.entity_key.uncapitalized, param.event_key.uncapitalized + )); + + // Add tuple accessor indexes if present + if let Some(indexes) = ¶m.tuple_param_accessor_indexes { + for index in indexes { + content.push_str(&format!( + "\n ->Utils.Tuple.get({})->Belt.Option.getUnsafe", + index + )); + } + } + + // Add address conversion if needed + if param.is_eth_address { + content.push_str("\n ->Address.toString"); + } + + content.push_str(",\n"); + } + + content.push_str(" }\n\n"); + content.push_str(&format!( + " context.{}_{}.set(entity)\n", + self.name.uncapitalized, event.name + )); + content.push_str("})\n"); + } + + content + } } #[derive(Serialize)] @@ -286,12 +408,12 @@ impl Event { }; format!( "{event_module}.mock({{data: {data_code} /* It mocks event fields with \ - default values, so you only need to provide data */}})" + default values, so you only need to provide data */}})" ) } // FIXME: Generate default data false => format!( "{event_module}.createMockEvent({{/* It mocks event fields with default values. \ - You can overwrite them if you need */}})" + You can overwrite them if you need */}})" ), } } @@ -391,10 +513,46 @@ impl AutoSchemaHandlerTemplate { }) } + /// Generates individual handler files for each contract in src/handlers/ + pub fn generate_handler_files( + &self, + lang: &Language, + project_root: &Path, + is_fuel: bool, + ) -> Result<()> { + use std::fs; + + // Create src/handlers directory + let handlers_dir = project_root.join("src").join("handlers"); + fs::create_dir_all(&handlers_dir).context(format!( + "Failed to create handlers directory at {:?}", + handlers_dir + ))?; + + // Generate a handler file for each contract + for contract in &self.imported_contracts { + let (file_extension, content) = match lang { + Language::TypeScript => { + ("ts", contract.generate_typescript_handler_content(is_fuel)) + } + Language::ReScript => ("res", contract.generate_rescript_handler_content(is_fuel)), + }; + + let file_name = format!("{}.{}", contract.name.capitalized, file_extension); + let file_path = handlers_dir.join(&file_name); + + fs::write(&file_path, content) + .context(format!("Failed to write handler file at {:?}", file_path))?; + } + + Ok(()) + } + pub fn generate_contract_import_templates( &self, lang: &Language, project_root: &Path, + is_fuel: bool, ) -> Result<()> { let template_dirs = TemplateDirs::new(); @@ -412,6 +570,11 @@ impl AutoSchemaHandlerTemplate { .extract(&project_root) .context("Failed extracting shared static files")?; + // Generate per-contract handler files in src/handlers/ + self.generate_handler_files(lang, project_root, is_fuel) + .context("Failed generating handler files")?; + + // Generate test files using Handlebars (still needed) let hbs = HandleBarsDirGenerator::new(&lang_dir, &self, project_root); let hbs_shared = HandleBarsDirGenerator::new(&shared_dir, &self, project_root); hbs.generate_hbs_templates().context(format!( @@ -568,7 +731,7 @@ mod test { assert_eq!( Event::get_entity_id_code(!IS_FUEL, &Language::ReScript), "`${event.chainId->Belt.Int.toString}_${event.block.number->Belt.Int.\ - toString}_${event.logIndex->Belt.Int.toString}`" + toString}_${event.logIndex->Belt.Int.toString}`" .to_string() ); diff --git a/codegenerator/cli/src/persisted_state/db.rs b/codegenerator/cli/src/persisted_state/db.rs index 2612f25fc..5504726cb 100644 --- a/codegenerator/cli/src/persisted_state/db.rs +++ b/codegenerator/cli/src/persisted_state/db.rs @@ -38,22 +38,19 @@ impl PersistedState { envio_version, config_hash, schema_hash, - handler_files_hash, abi_files_hash ) VALUES ( $1, $2, $3, $4, - $5, - $6 + $5 ) ON CONFLICT (id) DO UPDATE SET envio_version = EXCLUDED.envio_version, config_hash = EXCLUDED.config_hash, schema_hash = EXCLUDED.schema_hash, - handler_files_hash = EXCLUDED.handler_files_hash, abi_files_hash = EXCLUDED.abi_files_hash "#, public_schema @@ -62,7 +59,6 @@ impl PersistedState { .bind(&self.envio_version) .bind(&self.config_hash) .bind(&self.schema_hash) - .bind(&self.handler_files_hash) .bind(&self.abi_files_hash) .execute(pool) .await @@ -87,7 +83,6 @@ impl PersistedStateExists { envio_version, config_hash, schema_hash, - handler_files_hash, abi_files_hash FROM \"{}\".persisted_state WHERE id = 1", public_schema diff --git a/codegenerator/cli/src/persisted_state/mod.rs b/codegenerator/cli/src/persisted_state/mod.rs index ffcd3139b..7ef94a465 100644 --- a/codegenerator/cli/src/persisted_state/mod.rs +++ b/codegenerator/cli/src/persisted_state/mod.rs @@ -18,7 +18,6 @@ pub struct PersistedState { pub envio_version: String, pub config_hash: HashString, pub schema_hash: HashString, - pub handler_files_hash: HashString, pub abi_files_hash: HashString, } const PERSISTED_STATE_FILE_NAME: &str = "persisted_state.envio.json"; @@ -31,7 +30,6 @@ pub enum StateField { Config, Schema, AbiFiles, - HandlerFiles, } ///Gets the path to the persisted file in generated folder @@ -48,7 +46,6 @@ impl PersistedState { StateField::EnvioVersion => self.envio_version == other_state.envio_version, StateField::Schema => self.schema_hash == other_state.schema_hash, StateField::AbiFiles => self.abi_files_hash == other_state.abi_files_hash, - StateField::HandlerFiles => self.handler_files_hash == other_state.handler_files_hash, } } @@ -73,15 +70,10 @@ impl PersistedState { .get_path_to_schema() .context("Failed getting path to schema")?; - let all_handler_paths = config - .get_all_paths_to_handlers() - .context("Failed getting handler paths")?; - let all_abi_file_paths = config .get_all_paths_to_abi_files() .context("Failed getting abi file paths")?; - const HANDLER_FILES_MUST_EXIST: bool = false; const ABI_FILES_MUST_EXIST: bool = true; Ok(PersistedState { @@ -89,11 +81,6 @@ impl PersistedState { config_hash: HashString::from_string(config.human_config.to_string()), schema_hash: HashString::from_file_path(schema_path.clone()) .context("Failed hashing schema file")?, - handler_files_hash: HashString::from_file_paths( - all_handler_paths, - HANDLER_FILES_MUST_EXIST, - ) - .context("Failed hashing handler files")?, abi_files_hash: HashString::from_file_paths(all_abi_file_paths, ABI_FILES_MUST_EXIST) .context("Failed hashing abi files")?, }) @@ -188,7 +175,6 @@ mod test { "envio_version": "0.0.1", "config_hash": "", "schema_hash": "", - "handler_files_hash": "", "abi_files_hash": "", })) .unwrap(); @@ -197,7 +183,6 @@ mod test { "envio_version": "0.0.1", "config_hash": "", "schema_hash": "", - "handler_files_hash": "", "abi_files_hash": "", })) .unwrap(); @@ -217,7 +202,6 @@ mod test { "envio_version": "0.0.1", "config_hash": "", "schema_hash": "", - "handler_files_hash": "", "abi_files_hash": "", })) .unwrap(); @@ -226,7 +210,6 @@ mod test { "envio_version": "0.0.1", "config_hash": "", "schema_hash": "", - "handler_files_hash": "", "abi_files_hash": "", })) .unwrap(); @@ -236,7 +219,7 @@ mod test { assert!( !should_run_codegen, - "should run codegen should be false since only handler file changed" + "should run codegen should be false since nothing changed" ); } @@ -246,7 +229,6 @@ mod test { "envio_version": "0.0.1", "config_hash": "", "schema_hash": "", - "handler_files_hash": "", "abi_files_hash": "", })) .unwrap(); @@ -255,7 +237,6 @@ mod test { "envio_version": "0.0.1", "config_hash": "", "schema_hash": "", - "handler_files_hash": "", "abi_files_hash": "", })) .unwrap(); @@ -275,7 +256,6 @@ mod test { "envio_version": "0.0.1", "config_hash": "", "schema_hash": "", - "handler_files_hash": "", "abi_files_hash": "", })) .unwrap(); @@ -284,7 +264,6 @@ mod test { "envio_version": "0.0.1", "config_hash": "", "schema_hash": "", - "handler_files_hash": "", "abi_files_hash": "", })) .unwrap(); diff --git a/codegenerator/cli/src/project_paths/handler_paths.rs b/codegenerator/cli/src/project_paths/handler_paths.rs deleted file mode 100644 index fc545d65e..000000000 --- a/codegenerator/cli/src/project_paths/handler_paths.rs +++ /dev/null @@ -1,141 +0,0 @@ -use super::{path_utils, ParsedProjectPaths}; -use crate::config_parsing::system_config; -use anyhow::anyhow; -use pathdiff::diff_paths; -use serde::Serialize; -use std::path::PathBuf; - -#[derive(Serialize, Debug, Eq, PartialEq, Clone)] -pub struct HandlerPathsTemplate { - absolute: String, - relative_to_generated_src: String, - pub relative_to_config: String, - relative_to_project_root: String, -} - -impl HandlerPathsTemplate { - pub fn from_contract( - contract: &system_config::Contract, - project_paths: &ParsedProjectPaths, - ) -> anyhow::Result { - let config_directory = project_paths - .config - .parent() - .ok_or_else(|| anyhow!("Unexpected config file should have a parent directory"))?; - let handler_path_relative = PathBuf::from(&contract.handler_path); - let handler_path_joined = config_directory.join(handler_path_relative); - let absolute_path = path_utils::normalize_path(handler_path_joined); - - let generated_src = project_paths.generated.join("src"); - - let relative_to_generated_src = diff_paths(&absolute_path, generated_src) - .ok_or_else(|| anyhow!("could not find handler path relative to generated"))? - .to_str() - .ok_or_else(|| anyhow!("Handler path should be unicode"))? - .to_string(); - - let relative_to_config = diff_paths(&absolute_path, config_directory) - .ok_or_else(|| anyhow!("could not find handler path relative to project root"))? - .to_str() - .ok_or_else(|| anyhow!("Handler path should be unicode"))? - .to_string(); - - let relative_to_project_root = diff_paths(&absolute_path, &project_paths.project_root) - .ok_or_else(|| anyhow!("could not find handler path relative to config"))? - .to_str() - .ok_or_else(|| anyhow!("Handler path should be unicode"))? - .to_string(); - - let absolute = absolute_path - .to_str() - .ok_or_else(|| anyhow!("Handler path should be unicode"))? - .to_string(); - - Ok(HandlerPathsTemplate { - absolute, - relative_to_generated_src, - relative_to_config, - relative_to_project_root, - }) - } -} - -#[cfg(test)] -mod tests { - use crate::{config_parsing::system_config::SystemConfig, project_paths::ParsedProjectPaths}; - use pretty_assertions::assert_eq; - use std::path::PathBuf; - - #[test] - fn test_all_paths_construction_1() { - let test_dir = format!("{}/test", env!("CARGO_MANIFEST_DIR")); - let test_dir_path_buf = PathBuf::from(&test_dir); - let project_root = test_dir.as_str(); - let config_dir = "configs/config1.yaml"; - let generated = "generated/"; - let project_paths = ParsedProjectPaths::new(project_root, generated, config_dir) - .expect("Failed creating parsed_paths"); - - let config = - SystemConfig::parse_from_project_files(&project_paths).expect("Failed parsing config"); - - let expected_schema_path = test_dir_path_buf.join(PathBuf::from("schemas/schema.graphql")); - - let expected_handler_paths = - vec![test_dir_path_buf.join(PathBuf::from("configs/src/EventHandler.js"))]; - - let expected_abi_paths = vec![test_dir_path_buf.join(PathBuf::from("abis/Contract1.json"))]; - - assert_eq!( - expected_schema_path, - config - .get_path_to_schema() - .expect("failed to get schema path") - ); - assert_eq!( - expected_handler_paths, - config - .get_all_paths_to_handlers() - .expect("Failed to get hadnler paths") - ); - assert_eq!( - expected_abi_paths, - config - .get_all_paths_to_abi_files() - .expect("failed to get abi paths") - ); - } - - #[test] - fn test_get_contract_handler_path_template() { - let project_root = "test"; - let config_dir = "configs/config1.yaml"; - let generated = "generated/"; - let project_paths = ParsedProjectPaths::new(project_root, generated, config_dir) - .expect("Failed creating parsed_paths"); - - let config = - SystemConfig::parse_from_project_files(&project_paths).expect("Failed parsing config"); - - let contract_name = "Contract1".to_string(); - - let contract_handler_paths = super::HandlerPathsTemplate::from_contract( - config - .get_contract(&contract_name) - .expect("Expected contract in config"), - &project_paths, - ) - .expect("Failed getting contract handler_paths_template"); - - let expected_handler_paths = super::HandlerPathsTemplate { - absolute: "test/configs/src/EventHandler.js".to_string(), - - relative_to_generated_src: "../../configs/src/EventHandler.js".to_string(), - relative_to_config: "src/EventHandler.js".to_string(), - relative_to_project_root: "configs/src/EventHandler.js".to_string(), //Note since its - //defined in config.yaml with ./ the expected outcome should be the same dir as config - }; - - assert_eq!(expected_handler_paths, contract_handler_paths); - } -} diff --git a/codegenerator/cli/src/project_paths/mod.rs b/codegenerator/cli/src/project_paths/mod.rs index 0bf9b1dac..360e39f3a 100644 --- a/codegenerator/cli/src/project_paths/mod.rs +++ b/codegenerator/cli/src/project_paths/mod.rs @@ -8,7 +8,6 @@ use crate::{ }, }; -pub mod handler_paths; pub mod path_utils; #[derive(Debug, PartialEq, Clone)] diff --git a/codegenerator/cli/templates/dynamic/codegen/package.json.hbs b/codegenerator/cli/templates/dynamic/codegen/package.json.hbs index 814a099e4..fef7e52ac 100644 --- a/codegenerator/cli/templates/dynamic/codegen/package.json.hbs +++ b/codegenerator/cli/templates/dynamic/codegen/package.json.hbs @@ -13,13 +13,14 @@ "db-down": "node -e 'require(`./src/db/Migrations.res.js`).runDownMigrations(true)'", "db-setup": "node -e 'require(`./src/db/Migrations.res.js`).runUpMigrations(true, true)'", "print-benchmark-summary": "node -e 'require(`./src/Benchmark.res.js`).Summary.printSummary()'", - "start": "{{#if has_typescript}}ts-{{/if}}node src/Index.res.js" + {{!-- We need this to always have cwd at the root of the project --}} + "start": "cd {{relative_path_to_root_from_generated}} && ts-node {{relative_path_to_generated_from_root}}/src/Index.res.js" }, "keywords": [ "ReScript" ], "engines": { - "node": ">=18.0.0" + "node": ">=22.0.0 <=22.10.0" }, "author": "", "license": "MIT", @@ -32,9 +33,7 @@ "@fuel-ts/utils": "0.96.1", "@fuel-ts/address": "0.96.1", {{/if}} - {{#if has_typescript}} "ts-node": "10.9.1", - {{/if}} "@rescript/react": "0.12.1", "bignumber.js": "9.1.2", "date-fns": "3.3.1", diff --git a/codegenerator/cli/templates/dynamic/codegen/src/Generated.res.hbs b/codegenerator/cli/templates/dynamic/codegen/src/Generated.res.hbs index cbf8082d1..eb85c6b92 100644 --- a/codegenerator/cli/templates/dynamic/codegen/src/Generated.res.hbs +++ b/codegenerator/cli/templates/dynamic/codegen/src/Generated.res.hbs @@ -1,25 +1,54 @@ @val external require: string => unit = "require" -let registerContractHandlers = ( - ~contractName, - ~handlerPathRelativeToRoot, - ~handlerPathRelativeToConfig, -) => { - try { - require(`../${Path.relativePathToRootFromGenerated}/${handlerPathRelativeToRoot}`) - } catch { - | exn => - let params = { - "Contract Name": contractName, - "Expected Handler Path": handlerPathRelativeToConfig, - "Code": "EE500", +let registerContractHandlers = (~contractName, ~handler: option) => { + switch handler { + | None => () + | Some(handlerPath) => + try { + require(handlerPath) + } catch { + | exn => + Js.Exn.raiseError( + `Failed to load handler file for contract ${contractName}: ${handlerPath} with error: ${exn + ->Utils.prettifyExn + ->Obj.magic}`, + ) } - let logger = Logging.createChild(~params) + } +} + +@module("node:fs/promises") external globIterator: string => promise> = "glob" - let errHandler = exn->ErrorHandling.make(~msg="Failed to import handler file", ~logger) - errHandler->ErrorHandling.log - errHandler->ErrorHandling.raiseExn +let autoLoadFromSrcHandlers = async () => { + // Relatvie to cwd (project root) + let srcPattern = `./{{#if handlers_path}}{{handlers_path}}{{else}}src/handlers{{/if}}/**/*.{js,ts}` + let handlerFiles = try { + let iterator = await globIterator(srcPattern) + await iterator->Utils.Array.fromAsyncIterator + } catch { + | exn => + Js.Exn.raiseError( + `Failed to glob src/handlers directory for auto-loading handlers. Pattern: ${srcPattern}. Before continuing, check that you're using Node.js 22.10.0 version. Error: ${exn + ->Utils.prettifyExn + ->Obj.magic}`, + ) } + + handlerFiles->Js.Array2.forEach(file => { + try { + // Since srcPattern is relative to project root, + // and we require relative to the module (Generated.res) + // We need to prepend additional "../" and {{relative_path_to_root_from_generated}} to the file path + %raw(`require("../{{relative_path_to_root_from_generated}}/" + file)`) + } catch { + | exn => + Js.Exn.raiseError( + `Failed to auto-load handler file: ${file} with error: ${exn + ->Utils.prettifyExn + ->Obj.magic}`, + ) + } + }) } let makeGeneratedConfig = () => { @@ -96,18 +125,21 @@ let makeGeneratedConfig = () => { let configWithoutRegistrations = makeGeneratedConfig() -let registerAllHandlers = () => { +let registerAllHandlers = async () => { EventRegister.startRegistration( ~platform=configWithoutRegistrations.platform, ~multichain=configWithoutRegistrations.multichain, ~preloadHandlers=configWithoutRegistrations.preloadHandlers, ) + // Auto-load all .js files from src/handlers directory + await autoLoadFromSrcHandlers() + + // Load contract-specific handlers (existing behavior) {{#each codegen_contracts as |contract|}} registerContractHandlers( ~contractName="{{contract.name.capitalized}}", - ~handlerPathRelativeToRoot="{{contract.handler.relative_to_project_root}}", - ~handlerPathRelativeToConfig="{{contract.handler.relative_to_config}}", + ~handler={{#if contract.handler}}Some(`../${Path.relativePathToRootFromGenerated}/{{contract.handler}}`){{else}}None{{/if}}, ) {{/each}} @@ -193,12 +225,13 @@ let codegenPersistence = Persistence.make( ) %%private(let indexer: ref> = ref(None)) -let getIndexer = () => { +let getIndexer = async () => { switch indexer.contents { | Some(indexer) => indexer | None => + let registrations = await registerAllHandlers() let i = { - Indexer.registrations: registerAllHandlers(), + Indexer.registrations: registrations, // Need to recreate initial config one more time, // since configWithoutRegistrations called register for event // before they were ready diff --git a/codegenerator/cli/templates/dynamic/codegen/src/TestHelpers_MockDb.res.hbs b/codegenerator/cli/templates/dynamic/codegen/src/TestHelpers_MockDb.res.hbs index 37f3036aa..d349b60d2 100644 --- a/codegenerator/cli/templates/dynamic/codegen/src/TestHelpers_MockDb.res.hbs +++ b/codegenerator/cli/templates/dynamic/codegen/src/TestHelpers_MockDb.res.hbs @@ -329,7 +329,7 @@ and makeProcessEvents = (mockDb: t, ~chainId=?) => async ( ) { registrations } else { - Generated.registerAllHandlers() + await Generated.registerAllHandlers() } let config = Generated.makeGeneratedConfig() diff --git a/codegenerator/cli/templates/dynamic/contract_import_templates/rescript/src/EventHandlers.res.hbs b/codegenerator/cli/templates/dynamic/contract_import_templates/rescript/src/EventHandlers.res.hbs deleted file mode 100644 index 9846ce10d..000000000 --- a/codegenerator/cli/templates/dynamic/contract_import_templates/rescript/src/EventHandlers.res.hbs +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Please refer to https://docs.envio.dev for a thorough guide on all Envio indexer features - */ -{{#each imported_contracts as |contract|}} - {{#each contract.imported_events as |event|}} - -Handlers.{{contract.name.capitalized}}.{{event.name}}.handler(async ({event, context}) => { - let entity: Types.{{contract.name.uncapitalized}}_{{event.name}} = { - id: {{event.entity_id_from_event_code}}, - {{#each event.params as |param|}} - {{param.entity_key.uncapitalized}}: event.params.{{param.event_key.uncapitalized}} - {{#if param.tuple_param_accessor_indexes}} - {{#each param.tuple_param_accessor_indexes as |index|}} - ->Utils.Tuple.get({{index}})->Belt.Option.getUnsafe - {{/each}} - {{/if}} - {{#if param.is_eth_address}} - ->Address.toString - {{/if~}} - , - {{/each}} - } - - context.{{contract.name.uncapitalized}}_{{event.name}}.set(entity) -}) - {{/each}} -{{/each}} diff --git a/codegenerator/cli/templates/dynamic/contract_import_templates/typescript/src/EventHandlers.ts.hbs b/codegenerator/cli/templates/dynamic/contract_import_templates/typescript/src/EventHandlers.ts.hbs deleted file mode 100644 index 37971ccaf..000000000 --- a/codegenerator/cli/templates/dynamic/contract_import_templates/typescript/src/EventHandlers.ts.hbs +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Please refer to https://docs.envio.dev for a thorough guide on all Envio indexer features - */ -import { -{{#each imported_contracts as |contract|}} - {{contract.name.capitalized}}, - {{#each contract.imported_events as |event|}} - {{!--These are the entity types--}} - {{contract.name.capitalized}}_{{event.name}}, - {{/each}} -{{/each}} -} from "generated"; -{{#each imported_contracts as |contract|}} - {{#each contract.imported_events as |event|}} - -{{contract.name.capitalized}}.{{event.name}}.handler(async ({ event, context }) => { - const entity: {{contract.name.capitalized}}_{{event.name}} = { - id: {{event.entity_id_from_event_code}}, - {{#each event.params as |param|}} - {{param.entity_key.uncapitalized}}: event.params.{{param.event_key.original}}{{#if - param.tuple_param_accessor_indexes - }} - {{#each param.tuple_param_accessor_indexes as |index|}} - [{{index}}] - {{/each}} - {{/if}}, - {{/each}} - }; - - context.{{contract.name.capitalized}}_{{event.name}}.set(entity); -}); - {{/each}} -{{/each}} diff --git a/codegenerator/cli/templates/dynamic/init_templates/shared/package.json.hbs b/codegenerator/cli/templates/dynamic/init_templates/shared/package.json.hbs index c08fcfd45..ae2c21ee9 100644 --- a/codegenerator/cli/templates/dynamic/init_templates/shared/package.json.hbs +++ b/codegenerator/cli/templates/dynamic/init_templates/shared/package.json.hbs @@ -41,6 +41,6 @@ "generated": "{{relative_path_from_root_to_generated}}" }, "engines": { - "node": ">=18.0.0" + "node": ">=22.0.0 <=22.10.0" } } diff --git a/codegenerator/cli/templates/dynamic/subgraph_migration_templates/javascript/src/EventHandlers.js.hbs b/codegenerator/cli/templates/dynamic/subgraph_migration_templates/javascript/src/EventHandlers.js.hbs deleted file mode 100644 index 7a71b0146..000000000 --- a/codegenerator/cli/templates/dynamic/subgraph_migration_templates/javascript/src/EventHandlers.js.hbs +++ /dev/null @@ -1,22 +0,0 @@ -/* - *Please refer to https://docs.envio.dev for a thorough guide on all Envio indexer features* - */ - -const { -{{#each imported_contracts as |contract|}} - {{contract.name.capitalized}}{{#unless @last}},{{/unless}} -{{/each}} -} = require("../generated/src/Handlers.res.js"); - -{{#each imported_contracts as |contract|}} - {{#each contract.imported_events as |event|}} -{{contract.name.capitalized}}.{{event.name}}.loader(({event, context}) => { - // Load requiredEntities here -}); - -{{contract.name.capitalized}}.{{event.name}}.handler(({event, context}) => { - // Retrieve loaded requiredEntities and perform event handling logic here -}); - - {{/each}} -{{/each}} diff --git a/codegenerator/cli/templates/dynamic/subgraph_migration_templates/rescript/src/EventHandlers.res.hbs b/codegenerator/cli/templates/dynamic/subgraph_migration_templates/rescript/src/handlers/EventHandlers.res.hbs similarity index 100% rename from codegenerator/cli/templates/dynamic/subgraph_migration_templates/rescript/src/EventHandlers.res.hbs rename to codegenerator/cli/templates/dynamic/subgraph_migration_templates/rescript/src/handlers/EventHandlers.res.hbs diff --git a/codegenerator/cli/templates/dynamic/subgraph_migration_templates/typescript/src/EventHandlers.ts.hbs b/codegenerator/cli/templates/dynamic/subgraph_migration_templates/typescript/src/handlers/EventHandlers.ts.hbs similarity index 100% rename from codegenerator/cli/templates/dynamic/subgraph_migration_templates/typescript/src/EventHandlers.ts.hbs rename to codegenerator/cli/templates/dynamic/subgraph_migration_templates/typescript/src/handlers/EventHandlers.ts.hbs diff --git a/codegenerator/cli/templates/static/codegen/src/Index.res b/codegenerator/cli/templates/static/codegen/src/Index.res index 4fafc0a47..aaa0fc3b0 100644 --- a/codegenerator/cli/templates/static/codegen/src/Index.res +++ b/codegenerator/cli/templates/static/codegen/src/Index.res @@ -229,7 +229,7 @@ let main = async () => { // and prevent exposing the console to public, when creating a real deployment. let isDevelopmentMode = Env.Db.password === "testing" - let indexer = Generated.getIndexer() + let indexer = await Generated.getIndexer() let gsManagerRef = ref(None) diff --git a/codegenerator/cli/templates/static/codegen/src/PersistedState.res b/codegenerator/cli/templates/static/codegen/src/PersistedState.res index 72673a5b7..a82e66fd8 100644 --- a/codegenerator/cli/templates/static/codegen/src/PersistedState.res +++ b/codegenerator/cli/templates/static/codegen/src/PersistedState.res @@ -2,7 +2,6 @@ type t = { @as("envio_version") envioVersion: string, @as("config_hash") configHash: string, @as("schema_hash") schemaHash: string, - @as("handler_files_hash") handlerFilesHash: string, @as("abi_files_hash") abiFilesHash: string, } @@ -10,7 +9,6 @@ let schema = S.schema(s => { envioVersion: s.matches(S.string), configHash: s.matches(S.string), schemaHash: s.matches(S.string), - handlerFilesHash: s.matches(S.string), abiFilesHash: s.matches(S.string), }) diff --git a/codegenerator/cli/templates/static/erc20_template/typescript/config.yaml b/codegenerator/cli/templates/static/erc20_template/typescript/config.yaml index b6a406669..1aed85e2b 100644 --- a/codegenerator/cli/templates/static/erc20_template/typescript/config.yaml +++ b/codegenerator/cli/templates/static/erc20_template/typescript/config.yaml @@ -7,7 +7,6 @@ networks: contracts: - name: ERC20 address: "0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984" #UNI - handler: src/EventHandlers.ts events: - event: "Approval(address indexed owner, address indexed spender, uint256 value)" - event: "Transfer(address indexed from, address indexed to, uint256 value)" diff --git a/codegenerator/cli/templates/static/erc20_template/typescript/src/EventHandlers.ts b/codegenerator/cli/templates/static/erc20_template/typescript/src/handlers/ERC20.ts similarity index 99% rename from codegenerator/cli/templates/static/erc20_template/typescript/src/EventHandlers.ts rename to codegenerator/cli/templates/static/erc20_template/typescript/src/handlers/ERC20.ts index 2c9f833ac..5fd5b4a6e 100644 --- a/codegenerator/cli/templates/static/erc20_template/typescript/src/EventHandlers.ts +++ b/codegenerator/cli/templates/static/erc20_template/typescript/src/handlers/ERC20.ts @@ -69,3 +69,4 @@ ERC20.Transfer.handler(async ({ event, context }) => { context.Account.set(accountObject); } }); + diff --git a/codegenerator/cli/templates/static/erc20_template/typescript/test/test.ts b/codegenerator/cli/templates/static/erc20_template/typescript/test/test.ts index bb81f73d8..d5b1b709f 100644 --- a/codegenerator/cli/templates/static/erc20_template/typescript/test/test.ts +++ b/codegenerator/cli/templates/static/erc20_template/typescript/test/test.ts @@ -1,5 +1,7 @@ import assert from "assert"; -import { TestHelpers, Account } from "generated"; +import { TestHelpers } from "generated"; +import type { Account } from "generated"; + const { MockDb, ERC20, Addresses } = TestHelpers; describe("Transfers", () => { @@ -45,7 +47,7 @@ describe("Transfers", () => { assert.equal( 2n, account1Balance, - "Should have subtracted transfer amount 3 from userAddress1 balance 5", + "Should have subtracted transfer amount 3 from userAddress1 balance 5" ); //Get the balance of userAddress2 after the transfer @@ -56,7 +58,7 @@ describe("Transfers", () => { assert.equal( 3n, account2Balance, - "Should have added transfer amount 3 to userAddress2 balance 0", + "Should have added transfer amount 3 to userAddress2 balance 0" ); }); }); diff --git a/codegenerator/cli/templates/static/greeter_template/typescript/config.yaml b/codegenerator/cli/templates/static/greeter_template/typescript/config.yaml index 2bfefec71..b2b10b863 100644 --- a/codegenerator/cli/templates/static/greeter_template/typescript/config.yaml +++ b/codegenerator/cli/templates/static/greeter_template/typescript/config.yaml @@ -7,7 +7,6 @@ description: Greeter indexer contracts: - name: Greeter abi_file_path: ./abis/greeter-abi.json - handler: ./src/EventHandlers.ts events: - event: NewGreeting - event: ClearGreeting diff --git a/codegenerator/cli/templates/static/greeter_template/typescript/src/EventHandlers.ts b/codegenerator/cli/templates/static/greeter_template/typescript/src/handlers/Greeter.ts similarity index 99% rename from codegenerator/cli/templates/static/greeter_template/typescript/src/EventHandlers.ts rename to codegenerator/cli/templates/static/greeter_template/typescript/src/handlers/Greeter.ts index 3aad8469d..987104ead 100644 --- a/codegenerator/cli/templates/static/greeter_template/typescript/src/EventHandlers.ts +++ b/codegenerator/cli/templates/static/greeter_template/typescript/src/handlers/Greeter.ts @@ -38,3 +38,4 @@ Greeter.ClearGreeting.handler(async ({ event, context }) => { } }); + diff --git a/codegenerator/cli/templates/static/greeter_template/typescript/test/test.ts b/codegenerator/cli/templates/static/greeter_template/typescript/test/test.ts index 6dee830dc..6b06dc18b 100644 --- a/codegenerator/cli/templates/static/greeter_template/typescript/test/test.ts +++ b/codegenerator/cli/templates/static/greeter_template/typescript/test/test.ts @@ -1,5 +1,7 @@ import assert from "assert"; -import { TestHelpers, User } from "generated"; +import { TestHelpers } from "generated"; +import type { User } from "generated"; + const { MockDb, Greeter, Addresses } = TestHelpers; describe("Greeter template tests", () => { diff --git a/codegenerator/cli/templates/static/greeteronfuel_template/typescript/config.yaml b/codegenerator/cli/templates/static/greeteronfuel_template/typescript/config.yaml index 96cb25fb7..4ceee7269 100644 --- a/codegenerator/cli/templates/static/greeteronfuel_template/typescript/config.yaml +++ b/codegenerator/cli/templates/static/greeteronfuel_template/typescript/config.yaml @@ -8,7 +8,6 @@ networks: - name: Greeter address: 0xb9bc445e5696c966dcf7e5d1237bd03c04e3ba6929bdaedfeebc7aae784c3a0b abi_file_path: abis/greeter-abi.json - handler: ./src/EventHandlers.ts events: - name: NewGreeting - name: ClearGreeting diff --git a/codegenerator/cli/templates/static/greeteronfuel_template/typescript/src/EventHandlers.ts b/codegenerator/cli/templates/static/greeteronfuel_template/typescript/src/handlers/Greeter.ts similarity index 99% rename from codegenerator/cli/templates/static/greeteronfuel_template/typescript/src/EventHandlers.ts rename to codegenerator/cli/templates/static/greeteronfuel_template/typescript/src/handlers/Greeter.ts index 52786d49b..0adacad36 100644 --- a/codegenerator/cli/templates/static/greeteronfuel_template/typescript/src/EventHandlers.ts +++ b/codegenerator/cli/templates/static/greeteronfuel_template/typescript/src/handlers/Greeter.ts @@ -37,3 +37,4 @@ Greeter.ClearGreeting.handler(async ({ event, context }) => { }); } }); + diff --git a/codegenerator/cli/templates/static/greeteronfuel_template/typescript/test/test.ts b/codegenerator/cli/templates/static/greeteronfuel_template/typescript/test/test.ts index 8d4a658a9..15829b25f 100644 --- a/codegenerator/cli/templates/static/greeteronfuel_template/typescript/test/test.ts +++ b/codegenerator/cli/templates/static/greeteronfuel_template/typescript/test/test.ts @@ -1,5 +1,7 @@ import assert from "assert"; -import { TestHelpers, User } from "generated"; +import { TestHelpers } from "generated"; +import type { User } from "generated"; + const { MockDb, Greeter, Addresses } = TestHelpers; describe("Greeter template tests", () => { diff --git a/scenarios/erc20_multichain_factory/package.json b/scenarios/erc20_multichain_factory/package.json index 595e1bb81..7a231a745 100644 --- a/scenarios/erc20_multichain_factory/package.json +++ b/scenarios/erc20_multichain_factory/package.json @@ -20,5 +20,8 @@ }, "optionalDependencies": { "generated": "./generated" + }, + "engines": { + "node": ">=22.0.0 <=22.10.0" } } diff --git a/scenarios/fuel_test/package.json b/scenarios/fuel_test/package.json index c54543955..ae0f2ebdd 100644 --- a/scenarios/fuel_test/package.json +++ b/scenarios/fuel_test/package.json @@ -33,5 +33,8 @@ }, "optionalDependencies": { "generated": "./generated" + }, + "engines": { + "node": ">=22.0.0 <=22.10.0" } } diff --git a/scenarios/helpers/package.json b/scenarios/helpers/package.json index dfba98984..6df693895 100644 --- a/scenarios/helpers/package.json +++ b/scenarios/helpers/package.json @@ -16,5 +16,8 @@ "rescript": "11.1.3", "rescript-schema": "9.3.0", "envio": "file:../../codegenerator/cli/npm/envio" + }, + "engines": { + "node": ">=22.0.0 <=22.10.0" } } diff --git a/scenarios/test_codegen/package.json b/scenarios/test_codegen/package.json index a4a19f421..f97774941 100644 --- a/scenarios/test_codegen/package.json +++ b/scenarios/test_codegen/package.json @@ -60,5 +60,8 @@ }, "optionalDependencies": { "generated": "./generated" + }, + "engines": { + "node": ">=22.0.0 <=22.10.0" } } diff --git a/scenarios/test_codegen/pnpm-lock.yaml b/scenarios/test_codegen/pnpm-lock.yaml index d39ec6324..60f01d22d 100644 --- a/scenarios/test_codegen/pnpm-lock.yaml +++ b/scenarios/test_codegen/pnpm-lock.yaml @@ -1644,6 +1644,7 @@ packages: envio@file:../../codegenerator/cli/npm/envio: resolution: {directory: ../../codegenerator/cli/npm/envio, type: directory} + engines: {node: '>=22.0.0'} hasBin: true error-ex@1.3.2: diff --git a/scenarios/test_codegen/test/E2EEthNode_test.res b/scenarios/test_codegen/test/E2EEthNode_test.res index ef04f07c1..e09aa687b 100644 --- a/scenarios/test_codegen/test/E2EEthNode_test.res +++ b/scenarios/test_codegen/test/E2EEthNode_test.res @@ -69,7 +69,7 @@ describe("E2E Integration Test", () => { } } - let indexer = Generated.getIndexer() + let indexer = await Generated.getIndexer() let chainManager = Integration_ts_helpers.makeChainManager(localChainConfig) diff --git a/scenarios/test_codegen/test/EventHandler_test.ts b/scenarios/test_codegen/test/EventHandler_test.ts index d535cb2aa..1e55c5fe0 100644 --- a/scenarios/test_codegen/test/EventHandler_test.ts +++ b/scenarios/test_codegen/test/EventHandler_test.ts @@ -1,6 +1,7 @@ import assert from "assert"; import { it } from "mocha"; import { TestHelpers, User } from "generated"; + const { MockDb, Gravatar, EventFiltersTest } = TestHelpers; describe("Use Envio test framework to test event handlers", () => { diff --git a/scenarios/test_codegen/test/helpers/Mock.res b/scenarios/test_codegen/test/helpers/Mock.res index 2373a73b2..653baff92 100644 --- a/scenarios/test_codegen/test/helpers/Mock.res +++ b/scenarios/test_codegen/test/helpers/Mock.res @@ -259,7 +259,7 @@ module Indexer = { // TODO: Should stop using global client PromClient.defaultRegister->PromClient.resetMetrics - let registrations = Generated.registerAllHandlers() + let registrations = await Generated.registerAllHandlers() let config = { let config = Generated.makeGeneratedConfig() diff --git a/scenarios/test_codegen/test/lib_tests/PgStorage_test.res b/scenarios/test_codegen/test/lib_tests/PgStorage_test.res index 91940969e..500fa33be 100644 --- a/scenarios/test_codegen/test/lib_tests/PgStorage_test.res +++ b/scenarios/test_codegen/test/lib_tests/PgStorage_test.res @@ -166,7 +166,7 @@ GRANT ALL ON SCHEMA "test_schema" TO "postgres"; GRANT ALL ON SCHEMA "test_schema" TO public; CREATE TYPE "test_schema".ENTITY_TYPE AS ENUM('A', 'B', 'C', 'CustomSelectionTestPass', 'D', 'EntityWith63LenghtName______________________________________one', 'EntityWith63LenghtName______________________________________two', 'EntityWithAllNonArrayTypes', 'EntityWithAllTypes', 'EntityWithBigDecimal', 'EntityWithTimestamp', 'Gravatar', 'NftCollection', 'PostgresNumericPrecisionEntityTester', 'SimpleEntity', 'Token', 'User', 'dynamic_contract_registry'); CREATE TABLE IF NOT EXISTS "test_schema"."envio_chains"("id" INTEGER NOT NULL, "start_block" INTEGER NOT NULL, "end_block" INTEGER, "max_reorg_depth" INTEGER NOT NULL, "buffer_block" INTEGER NOT NULL, "source_block" INTEGER NOT NULL, "first_event_block" INTEGER, "ready_at" TIMESTAMP WITH TIME ZONE NULL, "events_processed" INTEGER NOT NULL, "_is_hyper_sync" BOOLEAN NOT NULL, "progress_block" INTEGER NOT NULL, "_num_batches_fetched" INTEGER NOT NULL, PRIMARY KEY("id")); -CREATE TABLE IF NOT EXISTS "test_schema"."persisted_state"("id" SERIAL NOT NULL, "envio_version" TEXT NOT NULL, "config_hash" TEXT NOT NULL, "schema_hash" TEXT NOT NULL, "handler_files_hash" TEXT NOT NULL, "abi_files_hash" TEXT NOT NULL, PRIMARY KEY("id")); +CREATE TABLE IF NOT EXISTS "test_schema"."persisted_state"("id" SERIAL NOT NULL, "envio_version" TEXT NOT NULL, "config_hash" TEXT NOT NULL, "schema_hash" TEXT NOT NULL, "abi_files_hash" TEXT NOT NULL, PRIMARY KEY("id")); CREATE TABLE IF NOT EXISTS "test_schema"."envio_checkpoints"("id" INTEGER NOT NULL, "chain_id" INTEGER NOT NULL, "block_number" INTEGER NOT NULL, "block_hash" TEXT, "events_processed" INTEGER NOT NULL, PRIMARY KEY("id")); CREATE TABLE IF NOT EXISTS "test_schema"."raw_events"("chain_id" INTEGER NOT NULL, "event_id" NUMERIC NOT NULL, "event_name" TEXT NOT NULL, "contract_name" TEXT NOT NULL, "block_number" INTEGER NOT NULL, "log_index" INTEGER NOT NULL, "src_address" TEXT NOT NULL, "block_hash" TEXT NOT NULL, "block_timestamp" INTEGER NOT NULL, "block_fields" JSONB NOT NULL, "transaction_fields" JSONB NOT NULL, "params" JSONB NOT NULL, "serial" SERIAL, PRIMARY KEY("serial")); CREATE TABLE IF NOT EXISTS "test_schema"."A"("b_id" TEXT NOT NULL, "id" TEXT NOT NULL, "optionalStringToTestLinkedEntities" TEXT, PRIMARY KEY("id")); @@ -245,7 +245,7 @@ CREATE SCHEMA "test_schema"; GRANT ALL ON SCHEMA "test_schema" TO "postgres"; GRANT ALL ON SCHEMA "test_schema" TO public; CREATE TABLE IF NOT EXISTS "test_schema"."envio_chains"("id" INTEGER NOT NULL, "start_block" INTEGER NOT NULL, "end_block" INTEGER, "max_reorg_depth" INTEGER NOT NULL, "buffer_block" INTEGER NOT NULL, "source_block" INTEGER NOT NULL, "first_event_block" INTEGER, "ready_at" TIMESTAMP WITH TIME ZONE NULL, "events_processed" INTEGER NOT NULL, "_is_hyper_sync" BOOLEAN NOT NULL, "progress_block" INTEGER NOT NULL, "_num_batches_fetched" INTEGER NOT NULL, PRIMARY KEY("id")); -CREATE TABLE IF NOT EXISTS "test_schema"."persisted_state"("id" SERIAL NOT NULL, "envio_version" TEXT NOT NULL, "config_hash" TEXT NOT NULL, "schema_hash" TEXT NOT NULL, "handler_files_hash" TEXT NOT NULL, "abi_files_hash" TEXT NOT NULL, PRIMARY KEY("id")); +CREATE TABLE IF NOT EXISTS "test_schema"."persisted_state"("id" SERIAL NOT NULL, "envio_version" TEXT NOT NULL, "config_hash" TEXT NOT NULL, "schema_hash" TEXT NOT NULL, "abi_files_hash" TEXT NOT NULL, PRIMARY KEY("id")); CREATE TABLE IF NOT EXISTS "test_schema"."envio_checkpoints"("id" INTEGER NOT NULL, "chain_id" INTEGER NOT NULL, "block_number" INTEGER NOT NULL, "block_hash" TEXT, "events_processed" INTEGER NOT NULL, PRIMARY KEY("id")); CREATE TABLE IF NOT EXISTS "test_schema"."raw_events"("chain_id" INTEGER NOT NULL, "event_id" NUMERIC NOT NULL, "event_name" TEXT NOT NULL, "contract_name" TEXT NOT NULL, "block_number" INTEGER NOT NULL, "log_index" INTEGER NOT NULL, "src_address" TEXT NOT NULL, "block_hash" TEXT NOT NULL, "block_timestamp" INTEGER NOT NULL, "block_fields" JSONB NOT NULL, "transaction_fields" JSONB NOT NULL, "params" JSONB NOT NULL, "serial" SERIAL, PRIMARY KEY("serial")); CREATE VIEW "test_schema"."_meta" AS @@ -327,7 +327,7 @@ CREATE SCHEMA "public"; GRANT ALL ON SCHEMA "public" TO "postgres"; GRANT ALL ON SCHEMA "public" TO public; CREATE TABLE IF NOT EXISTS "public"."envio_chains"("id" INTEGER NOT NULL, "start_block" INTEGER NOT NULL, "end_block" INTEGER, "max_reorg_depth" INTEGER NOT NULL, "buffer_block" INTEGER NOT NULL, "source_block" INTEGER NOT NULL, "first_event_block" INTEGER, "ready_at" TIMESTAMP WITH TIME ZONE NULL, "events_processed" INTEGER NOT NULL, "_is_hyper_sync" BOOLEAN NOT NULL, "progress_block" INTEGER NOT NULL, "_num_batches_fetched" INTEGER NOT NULL, PRIMARY KEY("id")); -CREATE TABLE IF NOT EXISTS "public"."persisted_state"("id" SERIAL NOT NULL, "envio_version" TEXT NOT NULL, "config_hash" TEXT NOT NULL, "schema_hash" TEXT NOT NULL, "handler_files_hash" TEXT NOT NULL, "abi_files_hash" TEXT NOT NULL, PRIMARY KEY("id")); +CREATE TABLE IF NOT EXISTS "public"."persisted_state"("id" SERIAL NOT NULL, "envio_version" TEXT NOT NULL, "config_hash" TEXT NOT NULL, "schema_hash" TEXT NOT NULL, "abi_files_hash" TEXT NOT NULL, PRIMARY KEY("id")); CREATE TABLE IF NOT EXISTS "public"."envio_checkpoints"("id" INTEGER NOT NULL, "chain_id" INTEGER NOT NULL, "block_number" INTEGER NOT NULL, "block_hash" TEXT, "events_processed" INTEGER NOT NULL, PRIMARY KEY("id")); CREATE TABLE IF NOT EXISTS "public"."raw_events"("chain_id" INTEGER NOT NULL, "event_id" NUMERIC NOT NULL, "event_name" TEXT NOT NULL, "contract_name" TEXT NOT NULL, "block_number" INTEGER NOT NULL, "log_index" INTEGER NOT NULL, "src_address" TEXT NOT NULL, "block_hash" TEXT NOT NULL, "block_timestamp" INTEGER NOT NULL, "block_fields" JSONB NOT NULL, "transaction_fields" JSONB NOT NULL, "params" JSONB NOT NULL, "serial" SERIAL, PRIMARY KEY("serial")); CREATE TABLE IF NOT EXISTS "public"."A"("b_id" TEXT NOT NULL, "id" TEXT NOT NULL, "optionalStringToTestLinkedEntities" TEXT, PRIMARY KEY("id")); diff --git a/scenarios/test_codegen/test/rollback/ChainDataHelpers.res b/scenarios/test_codegen/test/rollback/ChainDataHelpers.res index ab571b70f..8fbdd69d1 100644 --- a/scenarios/test_codegen/test/rollback/ChainDataHelpers.res +++ b/scenarios/test_codegen/test/rollback/ChainDataHelpers.res @@ -14,7 +14,7 @@ let makeTransaction = (~transactionIndex, ~transactionHash) => module Gravatar = { let contractName = "Gravatar" - let chainConfig = Generated.getIndexer().config.chainMap->ChainMap.get(MockConfig.chain1337) + let chainConfig = Generated.makeGeneratedConfig().chainMap->ChainMap.get(MockConfig.chain1337) let contract = chainConfig.contracts->Js.Array2.find(c => c.name == contractName)->Option.getExn let defaultAddress = contract.addresses[0]->Option.getExn diff --git a/scenarios/test_codegen/test/rollback/MockChainData_test.res b/scenarios/test_codegen/test/rollback/MockChainData_test.res index bde923850..2618ba932 100644 --- a/scenarios/test_codegen/test/rollback/MockChainData_test.res +++ b/scenarios/test_codegen/test/rollback/MockChainData_test.res @@ -3,7 +3,7 @@ open RescriptMocha describe("Check that MockChainData works as expected", () => { let mockChainDataInit = MockChainData.make( - ~chainConfig=Generated.getIndexer().config.chainMap->ChainMap.get(MockConfig.chain1337), + ~chainConfig=Generated.makeGeneratedConfig().chainMap->ChainMap.get(MockConfig.chain1337), ~maxBlocksReturned=3, ~blockTimestampInterval=25, )