diff --git a/contracts/Cargo.toml b/contracts/Cargo.toml index 823e8708..0e211980 100644 --- a/contracts/Cargo.toml +++ b/contracts/Cargo.toml @@ -1,27 +1,25 @@ -[package] + +[package] name = "splitnaira-contracts" version = "0.1.0" edition = "2021" -description = "Soroban smart contracts for SplitNaira — royalty splitting on Stellar" +description = "Soroban smart contracts for SplitNaira — royalty splitting on Stellar" license = "MIT" repository = "https://github.com/Split-Naira/SplitNaira" [lib] -crate-type = ["cdylib", "rlib"] name = "splitnaira_contract" -path = "lib.rs" +crate-type = ["cdylib", "rlib"] -# reliability_tests.rs is registered via #[cfg(test)] mod in lib.rs -# and is automatically included in: cargo test --features testutils +# reliability_tests.rs is registered through #[cfg(test)] in lib.rs. +# Run tests with: cargo test --features testutils [features] testutils = ["soroban-sdk/testutils"] [dependencies] -# Pinned to an exact version to prevent silent breakage from minor/patch bumps. -# Soroban minor versions can change storage cost models, instruction limits, or -# XDR encoding in ways that break deployed contracts. -# To upgrade: test on testnet, update both entries below and Cargo.lock, then -# document the new version in contracts/README.md. +# Keep Soroban SDK pinned to an exact version to avoid unexpected changes +# to contract behavior, storage costs, instruction limits, or XDR encoding. +# When upgrading, update Cargo.lock and validate against testnet. soroban-sdk = { version = "=20.5.0" } [dev-dependencies] @@ -42,4 +40,3 @@ lto = true [profile.release-with-logs] inherits = "release" debug-assertions = true - diff --git a/contracts/scripts/analyze-contract.mjs b/contracts/scripts/analyze-contract.mjs index ccd889a0..4a0edd79 100644 --- a/contracts/scripts/analyze-contract.mjs +++ b/contracts/scripts/analyze-contract.mjs @@ -1,35 +1,55 @@ + #!/usr/bin/env node + /** * Lightweight static analysis for the SplitNaira Soroban contract. - * Reports public function count, error codes, and event types without - * requiring a live Soroban node. * - * Usage: node contracts/scripts/analyze-contract.mjs + * Reports the number of public functions, error codes, and event types + * without requiring a live Soroban node. + * + * Usage: + * node contracts/scripts/analyze-contract.mjs */ + import { readFileSync } from "node:fs"; -import { resolve, dirname } from "node:path"; +import { dirname, resolve } from "node:path"; import { fileURLToPath } from "node:url"; -const root = resolve(dirname(fileURLToPath(import.meta.url)), ".."); +const SCRIPT_DIR = dirname(fileURLToPath(import.meta.url)); +const CONTRACT_ROOT = resolve(SCRIPT_DIR, ".."); -function read(file) { - return readFileSync(resolve(root, file), "utf8"); +/** + * Reads a contract file relative to the contracts directory. + * + * @param {string} file - Relative path to the file to read. + * @returns {string} The file contents as UTF-8 text. + */ +function readContractFile(file) { + const filePath = resolve(CONTRACT_ROOT, file); + return readFileSync(filePath, "utf8"); } -function count(src, re) { - return (src.match(re) ?? []).length; +/** + * Counts matches of a regular expression in a source string. + * + * @param {string} source - Source text to analyze. + * @param {RegExp} pattern - Pattern used to identify matching occurrences. + * @returns {number} The total number of matches. + */ +function countMatches(source, pattern) { + return (source.match(pattern) ?? []).length; } -const lib = read("lib.rs"); -const errors = read("errors.rs"); -const events = read("events.rs"); +const contractSource = readContractFile("lib.rs"); +const errorSource = readContractFile("errors.rs"); +const eventSource = readContractFile("events.rs"); -const fns = count(lib, /pub fn /g); -const errCodes = count(errors, /= \d+,/g); -const evTypes = count(events, /pub struct /g); +const publicFunctionCount = countMatches(contractSource, /pub fn /g); +const errorCodeCount = countMatches(errorSource, /= \d+,/g); +const eventTypeCount = countMatches(eventSource, /pub struct /g); -console.log("Contract surface analysis"); +console.log("Contract Surface Analysis"); console.log("--------------------------"); -console.log(`Public functions : ${fns}`); -console.log(`Error codes : ${errCodes}`); -console.log(`Event types : ${evTypes}`); +console.log(`Public functions : ${publicFunctionCount}`); +console.log(`Error codes : ${errorCodeCount}`); +console.log(`Event types : ${eventTypeCount}`); diff --git a/contracts/scripts/check-event-contract.mjs b/contracts/scripts/check-event-contract.mjs index 0ac3b2ce..5d0c75ec 100644 --- a/contracts/scripts/check-event-contract.mjs +++ b/contracts/scripts/check-event-contract.mjs @@ -1,25 +1,33 @@ + #!/usr/bin/env node + /** - * Contract event integration-contract guard. + * Contract event integration guard. * * Usage: * node contracts/scripts/check-event-contract.mjs - * Extract events from contracts/events.rs and compare them with the - * committed snapshot (contracts/interface/events.contract.json). - * Fails on any drift. + * Extracts events from contracts/events.rs and compares them with the + * committed snapshot (contracts/interface/events.contract.json). + * Fails if the event contract has drifted. * * node contracts/scripts/check-event-contract.mjs --update [--allow-breaking] - * Rewrite the snapshot from source and bump its version - * (breaking -> major, additive -> minor, informational -> patch). - * Refuses breaking changes unless --allow-breaking is passed. + * Regenerates the snapshot from source and bumps its version: + * breaking -> major + * additive -> minor + * informational -> patch + * Refuses breaking changes unless --allow-breaking is provided. * * node contracts/scripts/check-event-contract.mjs --base - * Compare the committed snapshot with a base snapshot (e.g. from - * origin/main) and fail if the version bump is too small for the - * classified changes. A missing base file is treated as first adoption. + * Compares the committed snapshot against a base snapshot and validates + * that the version bump matches the classified changes. + * A missing base file is treated as first adoption. * - * Exit codes: 0 ok, 1 contract violation, 2 usage/environment error. + * Exit codes: + * 0 - Check passed + * 1 - Contract violation + * 2 - Usage or environment error */ + import { existsSync, readFileSync, writeFileSync } from "node:fs"; import { dirname, resolve } from "node:path"; import { fileURLToPath } from "node:url"; @@ -33,101 +41,267 @@ import { extractEventContract, } from "./event-contract.mjs"; -const contractDir = resolve(dirname(fileURLToPath(import.meta.url)), ".."); -const eventsPath = resolve(contractDir, "events.rs"); -const snapshotPath = resolve(contractDir, "interface", "events.contract.json"); +const SCRIPT_DIR = dirname(fileURLToPath(import.meta.url)); +const CONTRACT_DIR = resolve(SCRIPT_DIR, ".."); + +const EVENTS_PATH = resolve(CONTRACT_DIR, "events.rs"); +const LIB_PATH = resolve(CONTRACT_DIR, "lib.rs"); +const SNAPSHOT_PATH = resolve( + CONTRACT_DIR, + "interface", + "events.contract.json", +); const args = process.argv.slice(2); -const flag = (name) => args.includes(name); -const option = (name) => { - const i = args.indexOf(name); - return i === -1 ? undefined : args[i + 1]; -}; -function fail(code, message) { +/** + * Checks whether a command-line flag is present. + * + * @param {string} name - Flag to check. + * @returns {boolean} Whether the flag exists in the arguments. + */ +function hasFlag(name) { + return args.includes(name); +} + +/** + * Retrieves the value associated with a command-line option. + * + * @param {string} name - Option name. + * @returns {string | undefined} Option value, if present. + */ +function getOption(name) { + const index = args.indexOf(name); + return index === -1 ? undefined : args[index + 1]; +} + +/** + * Prints an error message and terminates the process. + * + * @param {number} code - Exit code. + * @param {string} message - Error message to display. + */ +function exitWithError(code, message) { console.error(message); process.exit(code); } -function readSnapshot(path) { - const snapshot = JSON.parse(readFileSync(path, "utf8")); +/** + * Reads and validates an event-contract snapshot. + * + * @param {string} filePath - Snapshot file path. + * @returns {object} Validated snapshot. + * @throws {Error} If the snapshot is invalid or unreadable. + */ +function readSnapshot(filePath) { + const snapshot = JSON.parse(readFileSync(filePath, "utf8")); + if (snapshot.schema !== EVENT_CONTRACT_SCHEMA) { - throw new Error(`${path}: expected schema "${EVENT_CONTRACT_SCHEMA}", got "${snapshot.schema}"`); + throw new Error( + `${filePath}: expected schema "${EVENT_CONTRACT_SCHEMA}", ` + + `got "${snapshot.schema}"`, + ); } + return snapshot; } +/** + * Prints classified event-contract changes. + * + * @param {object} diff - Event-contract diff result. + */ function printChanges(diff) { - for (const c of diff.changes) console.log(` [${c.level}] ${c.event}: ${c.message}`); + for (const change of diff.changes) { + console.log( + ` [${change.level}] ${change.event}: ${change.message}`, + ); + } } +/** + * Writes the updated event-contract snapshot to disk. + * + * @param {object} snapshot - Snapshot to persist. + */ function writeSnapshot(snapshot) { - writeFileSync(snapshotPath, `${JSON.stringify(snapshot, null, 2)}\n`); + const serializedSnapshot = `${JSON.stringify(snapshot, null, 2)}\n`; + writeFileSync(SNAPSHOT_PATH, serializedSnapshot); } -try { - const baseOpt = option("--base"); - - if (baseOpt !== undefined) { - if (!existsSync(baseOpt)) { - console.log(`No base event contract at ${baseOpt}; treating as first adoption.`); - process.exit(0); - } - const base = readSnapshot(baseOpt); - const head = readSnapshot(snapshotPath); - const diff = diffEventContracts(base.events, head.events); - if (diff.level === "none") { - console.log(`Event contract unchanged (v${head.version}).`); - process.exit(0); - } - console.log(`Event contract changes v${base.version} -> v${head.version} (${diff.level}):`); - printChanges(diff); - const error = checkVersionBump(base.version, head.version, diff.level); - if (error) fail(1, `\n✖ ${error}. See docs/contract-events.md#compatibility-policy.`); - console.log("\n✔ Version bump matches the change level."); +/** + * Validates the version bump against the classified contract changes. + * + * @param {object} base - Base snapshot. + * @param {object} head - Current snapshot. + * @param {object} diff - Event-contract diff. + */ +function validateBaseVersion(base, head, diff) { + if (diff.level === "none") { + console.log(`Event contract unchanged (v${head.version}).`); process.exit(0); } - // Events published outside events.rs would bypass the contract entirely. - const libSource = readFileSync(resolve(contractDir, "lib.rs"), "utf8"); - if (/\.events\(\)\s*\.publish\s*\(/.test(libSource)) { - fail(1, "✖ contracts/lib.rs publishes events directly. Define them in contracts/events.rs so they are covered by the event contract."); + console.log( + `Event contract changes v${base.version} -> v${head.version} (${diff.level}):`, + ); + + printChanges(diff); + + const versionError = checkVersionBump( + base.version, + head.version, + diff.level, + ); + + if (versionError) { + exitWithError( + 1, + `\n✖ ${versionError}. See docs/contract-events.md#compatibility-policy.`, + ); } - const extracted = extractEventContract(readFileSync(eventsPath, "utf8")); + console.log("\n✔ Version bump matches the change level."); + process.exit(0); +} - if (flag("--update")) { - if (!existsSync(snapshotPath)) { - writeSnapshot(buildSnapshot(extracted, "1.0.0")); - console.log("Created event contract snapshot v1.0.0."); - process.exit(0); - } - const current = readSnapshot(snapshotPath); - const diff = diffEventContracts(current.events, extracted); - if (diff.level === "none") { - console.log(`Event contract already up to date (v${current.version}).`); - process.exit(0); - } - printChanges(diff); - if (diff.level === "breaking" && !flag("--allow-breaking")) { - fail(1, "\n✖ Breaking event changes. Re-run with --allow-breaking after coordinating consumers (docs/contract-events.md)."); - } - const version = bumpVersion(current.version, diff.level); - writeSnapshot(buildSnapshot(extracted, version)); - console.log(`\nUpdated event contract v${current.version} -> v${version}.`); +/** + * Checks for direct event publishing in lib.rs. + * + * Events published outside events.rs would bypass the event contract. + */ +function checkDirectEventPublishing() { + const libSource = readFileSync(LIB_PATH, "utf8"); + + if (/events\(\)\.publish\(/.test(libSource)) { + exitWithError( + 1, + "✖ contracts/lib.rs publishes events directly. Define them in " + + "contracts/events.rs so they are covered by the event contract.", + ); + } +} + +/** + * Creates the initial snapshot or updates an existing snapshot. + */ +function updateSnapshot(extractedEvents) { + if (!existsSync(SNAPSHOT_PATH)) { + writeSnapshot(buildSnapshot(extractedEvents, "1.0.0")); + console.log("Created event contract snapshot v1.0.0."); process.exit(0); } - if (!existsSync(snapshotPath)) fail(2, `Missing ${snapshotPath}; run with --update to create it.`); - const committed = readSnapshot(snapshotPath); - const diff = diffEventContracts(committed.events, extracted); + const currentSnapshot = readSnapshot(SNAPSHOT_PATH); + const diff = diffEventContracts(currentSnapshot.events, extractedEvents); + if (diff.level === "none") { - console.log(`✔ contracts/events.rs matches event contract v${committed.version}.`); + console.log( + `Event contract already up to date (v${currentSnapshot.version}).`, + ); process.exit(0); } - console.log(`contracts/events.rs drifted from event contract v${committed.version} (${diff.level}):`); + printChanges(diff); - fail(1, "\n✖ Run `npm run events:update` (add --allow-breaking for breaking changes) and commit the snapshot."); + + if (diff.level === "breaking" && !hasFlag("--allow-breaking")) { + exitWithError( + 1, + "\n✖ Breaking event changes. Re-run with --allow-breaking after " + + "coordinating consumers (docs/contract-events.md).", + ); + } + + const nextVersion = bumpVersion(currentSnapshot.version, diff.level); + + writeSnapshot(buildSnapshot(extractedEvents, nextVersion)); + + console.log( + `\nUpdated event contract v${currentSnapshot.version} -> v${nextVersion}.`, + ); + + process.exit(0); +} + +/** + * Verifies that the current event definitions match the committed snapshot. + */ +function checkSnapshot(extractedEvents) { + if (!existsSync(SNAPSHOT_PATH)) { + exitWithError( + 2, + `Missing ${SNAPSHOT_PATH}; run with --update to create it.`, + ); + } + + const committedSnapshot = readSnapshot(SNAPSHOT_PATH); + const diff = diffEventContracts( + committedSnapshot.events, + extractedEvents, + ); + + if (diff.level === "none") { + console.log( + `✔ contracts/events.rs matches event contract v${committedSnapshot.version}.`, + ); + process.exit(0); + } + + console.log( + `contracts/events.rs drifted from event contract ` + + `v${committedSnapshot.version} (${diff.level}):`, + ); + + printChanges(diff); + + exitWithError( + 1, + "\n✖ Run `npm run events:update` (add --allow-breaking for breaking " + + "changes) and commit the snapshot.", + ); +} + +try { + const basePath = getOption("--base"); + + // Validate the contract version against a base snapshot when requested. + if (basePath !== undefined) { + if (!existsSync(basePath)) { + console.log( + `No base event contract at ${basePath}; treating as first adoption.`, + ); + process.exit(0); + } + + const baseSnapshot = readSnapshot(basePath); + const headSnapshot = readSnapshot(SNAPSHOT_PATH); + + const diff = diffEventContracts( + baseSnapshot.events, + headSnapshot.events, + ); + + validateBaseVersion(baseSnapshot, headSnapshot, diff); + } + + checkDirectEventPublishing(); + + const extractedEvents = extractEventContract( + readFileSync(EVENTS_PATH, "utf8"), + ); + + // Regenerate the committed snapshot when --update is provided. + if (hasFlag("--update")) { + updateSnapshot(extractedEvents); + } + + // Otherwise, validate the current source against the committed snapshot. + checkSnapshot(extractedEvents); } catch (error) { - fail(2, `Event contract check failed: ${error instanceof Error ? error.message : String(error)}`); + exitWithError( + 2, + `Event contract check failed: ${ + error instanceof Error ? error.message : String(error) + }`, + ); }