Skip to content

About

Smart Contract Contributions are here

Resources

Contributing

Security policy

Stars

1 star

Watchers

0 watching

Forks

Repository files navigation

PetChain

PetChain is a decentralized pet health record platform built on Stellar Soroban smart contracts.

Soroban Resource-Budget Regression Checks

Large workflows can stay logically correct while silently exceeding Soroban instruction, memory, or storage budgets after a feature addition. To catch this early, the contract test suite measures representative worst-case calls and compares them against documented budget snapshots.

Covered workflows

Workflow Representative worst-case call Budgeted resources
Registration Register a pet with the maximum allowed metadata fields instructions, memory, storage
Record Append a record with maximum-length text fields to a pet with 49 records instructions, memory, storage
Consent Grant consent to the maximum number of authorized parties instructions, memory, storage
Claim Submit and settle a claim with a 1,000-byte description instructions, memory, storage
Pagination Read a 50-record page instructions, memory, storage

Budget snapshots

The budget test reads one JSON snapshot per workflow from contracts/test/budgets/. Each snapshot records Soroban host instructions, memory bytes, and net ledger-entry XDR bytes added. The initial measurements are pending a buildable contract test suite.

Running the checks in CI

CI runs the budget tests on every pull request. When a workflow exceeds its snapshot, the job fails and reports the specific resource that regressed, for example:

[budget] record: instructions regressed (measured 1_240_000 > budget 1_100_000)

The failure names the workflow and the resource (instructions, memory, or storage) so the regression can be attributed without re-running the suite locally.

Updating the baseline

Budgets are intentional baselines, not auto-generated values. To update a snapshot after a reviewed change:

From the repository root, run:

UPDATE_RESOURCE_BUDGET_BASELINE=1 cargo test --locked -p petchain-stellar --lib --features budget-tests resource_budget_workflows

Review the JSON files in contracts/test/budgets/ and commit the measured values with the corresponding change.

Snapshots must only be raised deliberately; an unexplained increase should be treated as a regression and investigated before merging.

Fixtures

Fixtures use contract limits where defined and fixed sizes for unbounded inputs. The measurements cover native Soroban test-host calls.

Soroban Error Registry

Public contract errors are documented in a deterministic registry so clients can map a numeric discriminant to its meaning and recovery semantics without parsing error text. The registry is generated from the contract source (the #[contracterror] enums) rather than hand-maintained, so it stays in sync with the contracts.

Each entry records:

  • code — the stable numeric discriminant returned on-chain.
  • meaning — a human-readable description of the failure.
  • retryability — whether a client may safely retry, and under what conditions.

See Error Codes for the full registry and recovery guidance. Discriminants are treated as a stable public interface: existing codes must not change silently, duplicate codes fail CI, and any intentional change requires updating the generated snapshot and the accompanying intentional-change test.

Batch Operation Atomicity Policy

Soroban batch operations in this repository follow a single, documented atomicity model: all-or-nothing. A batch either applies every item or applies none of them. There is no partial-success mode.

  • Atomicity model. Each batch is executed as one atomic unit. If any item fails validation or execution, the entire batch is rolled back and no state change from that batch is committed. Ownership, consent, and custody records therefore never expose a partially applied batch.
  • Rollback / error behavior. On the first failing item the batch aborts and returns an error identifying the failing item index and reason. Because the whole batch is rolled back, no partial ownership or consent state is observable after a failed batch.
  • Per-item results. Per-item results are only exposed when they are safe: on full success (each item's committed result) or as a non-mutating preview that performs no writes. Failed batches do not return per-item success results, since none of the items were committed.
  • Item limits. Batch size is bounded by a documented maximum. Batches that exceed the limit are rejected before any state is touched, so oversized batches cannot partially apply.

Pagination Policy

All Stellar paginated read endpoints (pet, record, vet, consent, custody, and activity reads) share a single bounded page-size policy. The policy is centralized in the contracts crate so every endpoint validates page sizes the same way and returns identical cursor semantics.

Parameter Value
Minimum page size 1
Default page size 20
Maximum page size 100

Rules:

  • A page size of 0 (or any value below the minimum) is rejected with a deterministic error.
  • A page size above the maximum is rejected with a deterministic error.
  • Omitting the page size uses the documented default of 20.
  • Every paginated endpoint returns the same cursor semantics: the cursor is an opaque token identifying the next page, and an empty/absent cursor starts at the first page.
  • Existing callers that pass a page size within [1, 100] remain compatible.

Care-Plan Amendment History

Care plans are versioned. Every amendment is recorded as a new immutable revision rather than mutating the existing plan, so the full amendment history is auditable on-chain.

Each revision records:

  • revision id — a monotonically increasing identifier, unique per care plan.
  • author — the address that submitted the amendment (owner or co-signing vet).
  • ledger time — the ledger timestamp at which the revision was committed.
  • superseded revision id — the revision this amendment replaces, or None for the initial revision.

Rules:

  • Revisions are append-only and immutable: a committed revision is never edited or deleted.
  • The initial revision has no superseded revision id; every later revision references the revision it replaces.
  • Amendments preserve the existing authorization model: only the plan owner or an authorized co-signing vet may append a revision.
  • History reads are paginated under the shared page-size policy above, so amendment history is bounded and cannot grow an unbounded response.

Medication Refill Authorization Records

Refill requests and their veterinary approval are tracked on-chain as bounded authorization records. Only the refill authorization is recorded — no private prescription text (drug name, dosage, directions, or notes) is ever stored on-chain. The prescription itself stays off-chain; the contract stores only the opaque prescription reference and the authorization outcome.

Each refill authorization record records:

  • refill id — a monotonically increasing identifier, unique per prescription.
  • prescription ref — an opaque, bounded reference to the off-chain prescription. No prescription text is stored.
  • requester — the address that submitted the refill request.
  • approver — the authorized vet that approved the refill, or None while the request is pending.
  • status — Pending, Approved, or Rejected.
  • ledger time — the ledger timestamp at which the record was last updated.

Rules:

  • Refills are only accepted for prescriptions that are active and not expired. A refill request against an inactive or expired prescription is rejected with a deterministic error and leaves state unchanged.
  • Only an authorized vet may approve or reject a pending refill; unauthorized callers are rejected and leave state unchanged.
  • A refill request is single-use: once a refill id has been approved or rejected it cannot be replayed, and a duplicate request for the same prescription reference is rejected.
  • The prescription reference is bounded in length, and the number of refill records per prescription is bounded, so persistent state growth is capped.
  • Refill history reads are paginated under the shared page-size policy above, so refill history is bounded and cannot grow an unbounded response.

Adoption Consent Evidence Commitments

Adoption consent is recorded on-chain as a commitment, never as the underlying applicant document. The contract stores only a canonical digest of the required consent artifacts, so applicant personal documents are never persisted in plaintext.

  • Canonical digest. Each consent artifact is hashed with the contract's canonical hashing routine (SHA-256 over the artifact bytes) and the resulting digests are combined into a single commitment. The commitment is the only value written to persistent storage.
  • Required artifacts. A consent submission must bind every artifact required by the adoption policy. A submission missing a required artifact is rejected with a deterministic error and leaves state unchanged.
  • No plaintext storage. Artifact bytes are consumed for hashing only and are never written to contract storage, events, or return values. Only the commitment digest is observable on-chain.
  • Authorization. Submitting or revoking a consent commitment requires the same authorization as the existing consent flow; unauthorized callers are rejected before any state is touched.
  • Replay and expiry. A commitment is bound to the adoption and carries an expiry. Re-submitting an identical commitment for the same adoption is rejected as a replay, and an expired commitment is rejected; both failures leave state unchanged.
  • Bounds. The number of artifacts per submission and the size of each artifact are bounded by documented maxima. Oversized submissions are rejected before any state is touched.

New error codes, events, and any ABI/storage changes introduced by this feature are recorded in the Error Codes registry and the compatibility fixtures, following the existing storage-version conventions.

Medication Administration Attestation

Scheduled medication doses can be attested by an authorized caregiver as administered, skipped, or refused. Attestation is recorded on-chain so the care plan reflects what actually happened to each scheduled dose.

Authorization

Only a caregiver already authorized for the pet (via the existing consent / caregiver authorization conventions) may attest a dose. Unauthorized callers are rejected with a deterministic error and no state is written.

Inputs

Field Bound
status one of administered, skipped, refused
reason_code bounded numeric code; required for skipped and refused
idempotency_key bounded byte length; unique per attestation

Oversized or invalid inputs are rejected before any state is touched.

Idempotency and replay

Each attestation carries an idempotency key. Replaying the same key returns the previously recorded attestation without writing new state, so retries are safe. A key that has expired is rejected. Failed calls leave storage unchanged.

Storage and ABI

Attestations are stored under the existing storage-version conventions; the storage version is unchanged and no existing keys are renumbered. New error codes and the attestation event are documented in Error Codes.

Preventive-Care Schedule Records

Routine exams and preventive care (vaccinations, dental checks, wellness visits, and similar) can be recorded as owner-approved schedules. Each schedule is versioned so updates are explicit and auditable, and can be cancelled by the owner.

Authorization

Only the pet owner may create, update, or cancel a preventive-care schedule. Unauthorized callers are rejected with a deterministic error and no state is written.

Inputs

Field Bound
care_type bounded enum (e.g. exam, vaccination, dental, wellness)
interval_days bounded positive integer
next_due_at bounded ledger timestamp
notes bounded byte length

Oversized or invalid inputs are rejected before any state is touched.

Versioning

Each schedule carries an explicit version. Creating a schedule starts at version 1; every owner-approved update increments the version and records the new values. Reads return the current version so clients can detect stale copies.

Cancellation

An owner may cancel a schedule. Cancellation is terminal for that schedule version: the schedule is marked cancelled and no further updates are accepted. Cancelling an already-cancelled schedule is rejected with a deterministic error and leaves state unchanged.

Replay and expiry

Schedule mutations carry an idempotency key. Replaying the same key returns the previously recorded result without writing new state. A key that has expired is rejected. Failed calls leave storage unchanged.

Storage and ABI

Schedules are stored under the existing storage-version conventions; the storage version is unchanged and no existing keys are renumbered. New error codes and the schedule event are documented in Error Codes.

Documentation

License

MIT

Handsoff notes

  • #1305: [Contracts] Add Stellar storage-key namespace collision tests
  • #1307: [Contracts] Add cursor invalidation tests aft

Documentation

License

MIT

Handsoff notes

  • #1305: [Contracts] Add Stellar storage-key namespace collision tests
  • #1307: [Contracts] Add cursor invalidation tests after deletion and state transitions
  • #1311: [Contracts] Add emergency-contact priority and duplicate invariant tests
  • #1312: [Contracts] Add insurance claim evidence lifecycle and expiry tests
  • #1313: [Contracts] Add Soroban persistent-storage TTL extension failure handling
  • #1188: [pet-transfer-adoption] Prevent adoption of nonexistent or inactive pets
  • #1197: [stellar-contracts] Add emergency-over
  • #1200: [stellar-contracts] Minimize public emergency-profile data
  • #1212: [stellar-contracts] Add governance timelock and cancellation policy
  • #1213
  • #1223: [backend-2fa] Version encrypted TOTP secret envelopes
  • #1224: [backend-2fa] Add online key rotation for encrypted TOTP secrets
  • #1227: [backend-2fa] Enforce TOTP replay protection atomically
  • #1261: [backend-2fa] Add webhook signature key versioning
  • #1304: [Contracts] Add Celo invariant tests for registry pause and recovery behavior
  • #1320: [Contracts] Add Celo event indexing compatibility fixtures
  • #1331: [Contracts] Add Soroban event privacy regression tests
  • #1332: [Contracts] Add Soroban upgrade proposal expiry semantics
  • #1340: [Contracts] Add Soroban insurance reserve accounting audit view
  • #1401: [Contracts] Add a versioned on-chain pet health passport
  • #1405: [Contracts] Add travel certificate lifecycle
  • #1406: [Contracts] Add travel readiness evaluation for a pet
  • #1407: [Contracts] Add destination-specific travel requirement profiles
  • #1408: [Contracts] Add time-limited passport sharing grants
  • #1409: [Contracts] Add travel certificate issuer authorization
  • #1410: [Contracts] Add passport export cursor for large histories
  • #1411: [Contracts] Add cross-network passport commitment format
  • #1412: [Contracts] Add client-verifiable passport proof fixtures
  • #1416: [Contracts] Add medication refill authorization records
  • #1418: [Contracts] Add missed-dose escalation policy
  • #1419: [Contracts] Add caregiver handoff summaries
  • #1425: [Contracts] Add care-plan access purpose checks
  • #1426: [Contracts] Add care-plan deletion and retention rules
  • #1427: [Contracts] Add canonical laboratory analyte identifiers
  • #1428: [Contracts] Add species-specific laboratory reference ranges
  • #1429: [Contracts] Add explicit laboratory unit conversion rules
  • #1430: [Contracts] Add laboratory panel completeness metadata
  • #1432: [Contracts] Add laboratory result verification attestations
  • #1433: [Contracts] Add sample collection and processing timestamps
  • #1434: [Contracts] Add laboratory result provenance for imported data
  • #1435: [Contracts] Add laboratory panel trend comparison API
  • #1437: [Contracts] Add laboratory result privacy tiers
  • #1438: [Contracts] Add lab data validation fixtures across supported species
  • #1439: [Contracts] Add vaccine batch and manufacturer provenance
  • #1440: [Contracts] Add multi-dose vaccination series tracking
  • #1441: [Contracts] Add vaccine schedule policy versions
  • #1442: [Contracts] Add vaccine adverse-event reports
  • #1443: [Contracts] Add certificate replacement with supersession links
  • #1444: [Contracts] Add vaccination administration-site metadata
  • #1445: [Contracts] Add vaccination certificate offline verification payload
  • #1446: [Contracts] Add vaccination certificate batch verification
  • #1447: [Contracts] Add vaccine product registry governance
  • #1448: [Contracts] Add vaccination schedule reconciliation preview
  • #1449: [Contracts] Add foster custody agreements with automatic expiry
  • #1451: [Contracts] Add shelter intake attestation
  • #1454: [Contracts] Add adoption trial period policy
  • #1455: [Contracts] Add adoption fee accounting receipt
  • #1456: [Contracts] Add adopter eligibility attestations
  • #1457: [Contracts] Add shelter authority delegation
  • #1458: [Contracts] Add custody dispute evidence bundle references
  • #1459: [Contracts] Add ownership recovery after failed adoption
  • #1463: [Contracts] Add verified sighting reporter attestations
  • #1464: [Contracts] Add private sighting location reveal authorization
  • #1465: [Contracts] Add lost-pet alert escalation rules
  • #1466: [Contracts] Add lost-pet alert radius and scope validation
  • #1467: [Contracts] Add found-pet intake and reunification workflow
  • #1468: [Contracts] Add responder organization credentials
  • #1476: [Contracts] Add claim preauthorization workflow
  • #1477: [Contracts] Add claim line-item review decisions
  • #1478: [Contracts] Add insurance premium payment receipts
  • #1480: [Contracts] Add policy lapse and reinstatement rules
  • #1482: [Contracts] Add insurance payout reconciliation view
  • #1483: [Contracts] Add breeding program enrollment and approval
  • #1484: [Contracts] Add breeding agreement commitments
  • #1485: [Contracts] Add genetic test result issuer verification
  • #1486: [Contracts] Add genetic trait disclosure scopes
  • #1487: [Contracts] Add litter registration workflow
  • #1488: [Contracts] Add litter size and offspring linkage invariants
  • #1489: [Contracts] Add post-birth health follow-up obligations
  • #1490: [Contracts] Add breeding pair reservation and expiry
  • #1491: [Contracts] Add breeding policy exception review
  • #1492: [Contracts] Add pedigree export with consented fields
  • #1493: [Contracts] Add Celo registry pet profile versioning
  • #1495: [Contracts] Add Celo medical record amendment chain

About

Smart Contract Contributions are here

Resources

Contributing

Security policy

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages