Standardize contract event schema checks#408
Open
TUPM96 wants to merge 1 commit into
Open
Conversation
|
@TUPM96 is attempting to deploy a commit to the smartdevs17's projects Team on Vercel. A member of the Team first needs to authorize it. |
There was a problem hiding this comment.
Pull request overview
Note
Copilot was unable to run its full agentic suite in this review.
Introduces a versioned “event schema” contract/indexer convention with documentation and CI enforcement to prevent drift between Soroban #[contractevent] definitions, legacy manual topics, and indexer annotations.
Changes:
- Added schema definition files (
event-schema.v1.json,event-schema.md) plus CI validation via a new Python checker. - Added
indexing_systemschema utilities to embed the JSON schema and annotate decoded event payloads with_schema_versionand_event_topic. - Added shared contract-side event schema constants in
contracts/common.
Reviewed changes
Copilot reviewed 12 out of 12 changed files in this pull request and generated 7 comments.
Show a summary per file
| File | Description |
|---|---|
| stellar-lend/scripts/check_event_schemas.py | CI checker that scans Rust sources + docs/JSON to enforce schema conventions. |
| stellar-lend/indexing_system/src/schema.rs | Adds schema types, embedded schema loading, topic normalization, and payload annotation. |
| stellar-lend/indexing_system/src/parser.rs | Annotates decoded payloads with schema metadata. |
| stellar-lend/indexing_system/src/lib.rs | Exposes the new schema module publicly and adjusts formatting. |
| stellar-lend/docs/event-schema.v1.json | Adds the machine-readable v1 schema definition. |
| stellar-lend/docs/event-schema.md | Adds human-readable schema rules and versioning notes. |
| stellar-lend/contracts/common/src/lib.rs | Exposes the new event_schema module. |
| stellar-lend/contracts/common/src/event_schema.rs | Adds shared schema constants/enums for contracts. |
| stellar-lend/Cargo.toml | Excludes indexing_system from the Rust workspace. |
| package.json | Adds an npm script to run the schema checker. |
| docs/event-indexing.md | Links to schema docs and specifies indexer annotation fields. |
| .github/workflows/ci-cd.yml | Adds a CI step to run the schema checker. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
Comment on lines
+45
to
+61
| def snake_case(name: str) -> str: | ||
| chars: list[str] = [] | ||
| previous_lower_or_digit = False | ||
| for ch in name: | ||
| if ch in {"-", " "}: | ||
| chars.append("_") | ||
| previous_lower_or_digit = False | ||
| continue | ||
| if ch.isupper(): | ||
| if previous_lower_or_digit: | ||
| chars.append("_") | ||
| chars.append(ch.lower()) | ||
| previous_lower_or_digit = False | ||
| else: | ||
| chars.append(ch) | ||
| previous_lower_or_digit = ch.islower() or ch.isdigit() | ||
| return "".join(chars) |
Comment on lines
+24
to
+28
| EVENT_STRUCT_RE = re.compile( | ||
| r"(?P<attrs>(?:#\[[^\]]+\]\s*)*)pub\s+struct\s+(?P<name>[A-Za-z0-9_]+)\s*\{(?P<body>.*?)\n\}", | ||
| re.DOTALL, | ||
| ) | ||
| FIELD_RE = re.compile(r"pub\s+(?P<name>[a-zA-Z0-9_]+)\s*:\s*(?P<ty>[^,]+),") |
Comment on lines
+80
to
+83
| def parse_event_structs() -> list[EventDef]: | ||
| events: list[EventDef] = [] | ||
| for path in sorted(CONTRACTS.rglob("*.rs")): | ||
| text = path.read_text(encoding="utf-8") |
Comment on lines
+74
to
+83
| pub fn annotate_event_payload(payload: &mut Map<String, Value>, event_name: &str) { | ||
| payload.insert( | ||
| EVENT_SCHEMA_VERSION_FIELD.to_string(), | ||
| Value::Number(STANDARD_EVENT_SCHEMA_VERSION.into()), | ||
| ); | ||
| payload.insert( | ||
| EVENT_TOPIC_FIELD.to_string(), | ||
| Value::String(normalize_event_topic(event_name)), | ||
| ); | ||
| } |
Comment on lines
+20
to
+29
| | Field | Meaning | | ||
| | --- | --- | | ||
| | `user` | End-user account that initiated or owns a position-changing action. | | ||
| | `actor` | Authorized protocol account that performed an administrative action. | | ||
| | `caller` | Authenticated account that invoked an administrative or governance entrypoint. | | ||
| | `asset` | Soroban token contract address; `None` represents native asset where supported. | | ||
| | `amount` | Raw integer amount in the asset's smallest unit. | | ||
| | `fee` | Raw integer fee in the asset's smallest unit. | | ||
| | `timestamp` | Ledger timestamp in seconds. | | ||
| | `*_bps` | Basis points; `10000` is `100%`. | |
| "deploy:verify": "bash scripts/verify-deployment.sh", | ||
| "deploy:rollback": "bash scripts/rollback.sh", | ||
| "verify:contract": "bash scripts/verify-contract.sh", | ||
| "contracts:event-schema:check": "python stellar-lend/scripts/check_event_schemas.py", |
| "contracts/migration-hub", | ||
| ] | ||
| exclude = ["fuzz"] | ||
| exclude = ["fuzz", "indexing_system"] |
Smartdevs17
pushed a commit
that referenced
this pull request
May 28, 2026
…actor, event schema standardization (#415) * feat(upgrade): add 48h standard and 4h emergency timelocks with multisig - Add STANDARD_TIMELOCK_SECS (48h) and EMERGENCY_TIMELOCK_SECS (4h) constants - Add TimelockNotElapsed and StorageLayoutMismatch error variants - Add TimelockQueued stage to UpgradeStage enum - Add execute_after and is_emergency fields to UpgradeProposal and UpgradeStatus - Add upgrade_queue_timelock() to start the standard 48h countdown post-approval - Add upgrade_propose_emergency() for 4h emergency path (admin only) - Enforce timelock in upgrade_execute() — rejects before execute_after elapses - Add UpgradeTimelockQueuedEvent and UpgradeEmergencyProposedEvent to events - Update all tests to go through queue_and_execute() helper for correct flow * feat(flash-loan): add TWAP price manipulation detection and attack prevention - Add ManipulationConfig with pool liquidity cap (50%), price impact limit, TWAP deviation threshold, and concurrent loan detection - Add TwapAccumulator/TwapState structs with time-windowed price sampling - Add check_twap_deviation(), check_liquidity_cap(), check_price_impact() - Add per-asset AssetLoanGuard to block concurrent flash loans (sandwich prevention) - Update flash_loan() signature to accept spot_price for TWAP checks - Add flash_record_price() and set_flash_manipulation_config() entrypoints - Apply same attack guards to hello-world flash_loan module - Update all tests to use new flash_loan() signature with spot_price - Add tests for liquidity cap, price impact, and TWAP deviation blocking Closes #379, #401 * feat(api): add DTO layer with structured validation for all endpoints - Add api/src/dto/ directory with TypeScript DTO classes - base.dto.ts: FieldError, ValidationResult, helper validators (isValidStellarAddress, isValidAmount, isOptionalString), MAX_I128 constant - lending.dto.ts: LendingOperationDto, PrepareRequestDto, SubmitRequestDto, RelayDelegatedDto, PrepareResponseDto, TransactionResponseDto — all with static validate() and fromBody()/fromQuery() factories + JSDoc/OpenAPI schemas - subscription.dto.ts: CreateSubscriptionDto covering all subscription fields - pagination.dto.ts: PaginationQueryDto with configurable max-limit - dto/index.ts: barrel re-export - middleware/validation.ts: add DTO-based middleware variants (validateLendingOperationDto, validatePrepareDto, validateSubmitDto, validateRelayDelegatedDto, validateCreateSubscriptionDto, validatePaginationDto) that attach typed DTOs to req for use in controllers — existing express-validator chain preserved Closes #362 * feat(events): standardize event schemas across all contracts AMM (amm.rs): - Add explicit topics attributes: amm_swap, amm_liq_add, amm_liq_rm, amm_op, amm_cb_valid - Add timestamp: u64 field to SwapExecutedEvent, LiquidityAddedEvent, LiquidityRemovedEvent, CallbackValidatedEvent (AmmOperationEvent already had it) - Update all emit helper functions to pass env.ledger().timestamp() Bridge (bridge.rs): - Add explicit topics attributes: br_reg, br_fee, br_active, br_dep, br_wdraw, br_pause, br_val_upd, br_sec_cfg, br_slash, br_ch_emrg, br_anomaly - Add timestamp: u64 to all 11 bridge event structs (previously none had it) - Update all emit call sites to include timestamp Docs: - Add docs/event-schema.md: mandatory fields spec, topic naming conventions, per-contract event catalogue, backward-compat note, PR checklist CI: - Add scripts/check_event_schema.sh: detects contractevent structs missing the required timestamp field; warns on missing explicit topics Closes #356, #408
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Closes #356
Summary
event-schema.v1.jsonregistry for typed and legacy Soroban events.stellarlend-commonso contracts and indexers have one canonical schema version.#[contractevent]structs, validates naming/topic limits, catches unexpected manualenv.events().publishtopics, and runs in CI._schema_versionand_event_topicmetadata.Validation
python stellar-lend/scripts/check_event_schemas.pycargo check -p stellarlend-commoncargo fmt -p stellarlend-common -- --checkgit diff --cached --checkNotes
cargo check --manifest-path stellar-lend/indexing_system/Cargo.tomlis now able to start as a standalone package after excluding it from the workspace, but it still exposes pre-existing prototype indexer compile issues (info!import,QueryService::new().await, private repository pool, and migrate error conversion). This PR keeps scope to schema/versioning/indexer metadata for Standardize smart contract event schemas across all contracts #356.