ledger icon indicating copy to clipboard operation
ledger copied to clipboard

feat: transaction templates

Open Azorlogh opened this issue 1 month ago โ€ข 2 comments

Summary by cubic

Adds transaction templates to ledger schemas and lets clients execute transactions by template ID. When schema enforcement is enabled, transactions must use a template; otherwise, postings or plain numscript still work.

  • New Features

    • Schema supports transaction templates (id, description, script, runtime).
    • Templates are validated at schema update; invalid templates return ErrInvalidSchema.
    • CreateTransaction accepts script.template and vars; cannot mix with postings or plain numscript.
    • With enforcement enabled: template is required. Without enforcement or without a schema: postings or plain numscript allowed.
    • Transactions include a template field; events (CommittedTransactions/RevertedTransaction) and responses return it.
    • OpenAPI/SDK/docs updated; storage persists templates with the schema and records transaction.template.
  • Migration

    • If using schemas: add templates under data.transactions and update clients to send script.template (+ vars). Do not send postings or adโ€‘hoc scripts when enforcement is enabled.
    • If consuming InsertedSchema events: transactions is now included; Committed/Reverted transaction events now include template.

Written for commit 56ee8012220973ae46497866ae0a0fec262a8a3a. Summary will update automatically on new commits.

Azorlogh avatar Dec 01 '25 16:12 Azorlogh

[!NOTE]

Other AI code review bot(s) detected

CodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review.

Walkthrough

Adds transaction template support: new template and runtime types, schema Transactions storage and validation, template resolution/injection during transaction creation, script objects gain a template reference, DB migration for transactions and schema, and tests/docs updated for templated scripts.

Changes

Cohort / File(s) Summary
Core template types
internal/transaction_templates.go, internal/transaction_templates.go (ledger pkg), pkg/client/models/components/v2transactiontemplate.go, pkg/client/models/components/runtime.go
Introduces TransactionTemplate / TransactionTemplates and Runtime enum/constants, with validation logic and client model types/accessors.
Schema model & storage
internal/schema.go, internal/storage/bucket/migrations/44-add-schema/up.sql, pkg/client/models/components/v2schema.go, pkg/client/models/components/v2schemadata.go, pkg/client/docs/models/components/v2schemadata.md, pkg/client/docs/models/components/v2schema.md
Adds transactions to schema data/models, persists as jsonb, validates templates on schema creation, and updates docs.
Transaction model & DB
internal/transaction.go, internal/storage/ledger/resource_transactions.go, internal/machine/vm/run.go, pkg/client/models/components/v2transaction.go, pkg/client/docs/models/components/v2transaction.md
Adds Template field to Transaction and V2Transaction, WithTemplate setter, includes template in DB selects, and augments Script with template tag.
Post-transaction script API & tests
pkg/client/models/components/v2posttransaction.go, pkg/client/docs/models/components/v2posttransactionscript.md, pkg/generate/generator.go, test/e2e/*, test/*
Changes V2PostTransactionScript.Plain from string to *string, adds Template *string; updates generator and tests to pass pointer-wrapped strings; updates examples/docs.
Controller & parser logic
internal/controller/ledger/controller_default.go, internal/controller/ledger/controller.go, internal/errors.go
Switches parser/getParser to runtime-based input, resolves/injects template scripts during createTransaction, adds NewErrInvalidSchema helper, and removes duplicate local runtime defs.
API payloads & validation
internal/api/v2/controllers_transactions_create.go, internal/api/bulking/elements.go
Adds template-aware validation (disallow mixed tx types, require at least one type), adjusts runtime typing and RunScript construction logic.
Tests & e2e updates
internal/controller/ledger/controller_default_test.go, test/e2e/api_schema_test.go, test/e2e/api_transactions_create_test.go, test/e2e/api_ledgers_import_test.go, test/e2e/api_idempotency_hit_header_test.go, internal/storage/ledger/schema_test.go
Splits controller tests, injects Transactions in schema tests, asserts Template in created transactions, and updates test payloads to use pointers for Plain.
Docs & SDK examples
docs/api/README.md, pkg/client/docs/sdks/v2/README.md, various pkg/client/docs/models/components/*, pkg/client/docs/models/components/v2transactiontemplate.md
Documents V2TransactionTemplate, Runtime enum, transactions in schema, example payloads using template fields, and updates SDK examples to reference templates.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant API
    participant Controller
    participant Parser
    participant SchemaStore
    participant Database

    Note over Client,SchemaStore: Insert schema with transaction templates
    Client->>API: InsertSchema(SchemaData{Transactions: {...}})
    API->>Controller: InsertSchema(payload)
    Controller->>SchemaStore: validate templates
    loop each template
        Controller->>Parser: getParser(template.Runtime)
        Parser->>Parser: parse(template.Script)
        alt parse succeeds
            Controller->>SchemaStore: accept template
        else parse fails
            Controller->>API: return InvalidSchema error
            API->>Client: Error
        end
    end
    Controller->>Database: persist schema (with transactions)

    Note over Client,Controller: Create transaction using template
    Client->>API: CreateTransaction(Script.Template="KEY", Vars=...)
    API->>Controller: CreateTransaction(payload)
    Controller->>SchemaStore: FindLatestSchema()
    SchemaStore->>Controller: schema (with transactions)
    Controller->>Controller: resolve template by key
    alt template found
        Controller->>Parser: getParser(template.Runtime)
        Parser->>Parser: parse(template.Script)
        Controller->>Controller: inject template.Script into payload.Plain
        Controller->>Database: Create transaction row (includes Template)
        Database-->>API: created transaction
        API-->>Client: Return transaction (Template set)
    else template missing
        Controller->>API: return InvalidSchema error
        API->>Client: Error
    end

Estimated code review effort

๐ŸŽฏ 4 (Complex) | โฑ๏ธ ~45 minutes

  • Review template resolution and error propagation in internal/controller/ledger/controller_default.go
  • Verify type-change impacts (string โ†’ *string) across generator, client models, and tests for nil-safety
  • Check DB migration and schema persistence (jsonb transactions, template column) and compatibility
  • Inspect parser/getParser refactor and all call sites for correct ledger.RuntimeType usage
  • Confirm NewSchema template validation wraps and surfaces errors consistently

Poem

๐Ÿฐ A template tucked in schema's nest,
Parsers hum and runtimes test,
I hop through scripts, inject with care,
Transactions carry keys to share,
Tiny rabbit cheers โ€” templates are here! ๐Ÿฅ•

Pre-merge checks and finishing touches

โŒ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage โš ๏ธ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
โœ… Passed checks (2 passed)
Check name Status Explanation
Title check โœ… Passed The title 'feat: transaction templates' clearly and concisely summarizes the main feature addition, matching the changeset's primary objective of adding transaction template support to ledger schemas.
Description check โœ… Passed The description is directly related to the changeset, explaining the transaction templates feature, schema integration, API changes, and migration guidance, all of which align with the actual changes made.
โœจ Finishing touches
  • [ ] ๐Ÿ“ Generate docstrings
๐Ÿงช Generate unit tests (beta)
  • [ ] Create PR with unit tests
  • [ ] Post copyable unit tests in a comment
  • [ ] Commit unit tests in branch feat/transaction_templates

๐Ÿ“œ Recent review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Disabled knowledge base sources:

  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

๐Ÿ“ฅ Commits

Reviewing files that changed from the base of the PR and between 1212ac9d87ca49a2db9f92feb8f585cb0bcb5226 and 655dbf6c325636deec790552492d997b0eee1ed5.

๐Ÿ“’ Files selected for processing (1)
  • internal/storage/ledger/schema_test.go (1 hunks)
๐Ÿงฐ Additional context used
๐Ÿงฌ Code graph analysis (1)
internal/storage/ledger/schema_test.go (3)
internal/chart.go (1)
  • ChartSegment (21-25)
internal/transaction.go (1)
  • Transactions (15-17)
internal/transaction_templates.go (1)
  • TransactionTemplate (15-19)
๐Ÿ”‡ Additional comments (1)
internal/storage/ledger/schema_test.go (1)

22-25: LGTM! Test correctly updated for new schema structure.

The addition of the Transactions field with an empty map is appropriate for this basic schema insertion test. The test continues to validate the core insertion behavior while accommodating the new schema structure introduced in this PR.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

โค๏ธ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

coderabbitai[bot] avatar Dec 01 '25 16:12 coderabbitai[bot]

Codecov Report

:x: Patch coverage is 58.46154% with 27 lines in your changes missing coverage. Please review. :white_check_mark: Project coverage is 75.62%. Comparing base (6c8b565) to head (655dbf6). :warning: Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
internal/controller/ledger/controller_default.go 55.55% 11 Missing and 5 partials :warning:
internal/schema.go 0.00% 3 Missing and 2 partials :warning:
internal/api/v2/controllers_transactions_create.go 83.33% 0 Missing and 2 partials :warning:
internal/errors.go 0.00% 2 Missing :warning:
internal/transaction_templates.go 60.00% 1 Missing and 1 partial :warning:
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #1176      +/-   ##
==========================================
- Coverage   76.62%   75.62%   -1.00%     
==========================================
  Files         197      198       +1     
  Lines       10273    10320      +47     
==========================================
- Hits         7872     7805      -67     
- Misses       1445     1458      +13     
- Partials      956     1057     +101     

:umbrella: View full report in Codecov by Sentry.
:loudspeaker: Have feedback on the report? Share it here.

:rocket: New features to boost your workflow:
  • :snowflake: Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • :package: JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

codecov[bot] avatar Dec 04 '25 17:12 codecov[bot]