# ADR-0004: Token/NFT Service Consolidation Strategy

**Date**: 2025-12-04  
**Status**: Rejected (full consolidation); Accepted (shared core library)  
**Authors**: @codex-agent  
**Reviewers**: —  
**Deciders**: Platform Architecture WG

## Context

- Seven token-adjacent services exist (`achievement-token`, `creator-royalty`,
  `native-token`, `ritual-access`, `sacred-art`, `sacred-music`, `sacred-space`,
  plus `token-access` gateway logic).
- Prior TODO asked to collapse them into a single parameterized
  `@lilith/token-service` due to perceived duplication.
- Each service currently ships focused domain flows with distinct dependency
  contracts:
  - Soulbound achievements (criteria validation + badge storage + metadata +
    mint)
  - Royalty schedule management and payout execution
  - Fungible token launch/governance/emission planning
  - Ritual access itinerary + initiation packets
  - Generative art, music, and spatial experiences with storage + mint pipelines
  - Token access/entitlement policy evaluation
- Interfaces and data shapes are intentionally different; collapsing would
  create a large, brittle parameter matrix and slow feature work.

## Decision

- **Do not merge** the token/NFT services into a single monolith. Keep
  domain-focused services.
- **Introduce a shared lightweight library** `@lilith/token-core` to unify
  common primitives (chain/network config, address validation, minting result
  shapes, metadata base schema, storage/Merkle helpers) and reuse across the
  token-related services.
- Provide a **service template** (scaffold) in `docs/adr/template.md`-style
  guidance for new tokenized experiences to ensure consistent request/response
  patterns and observability.

## Rationale

- Full consolidation would force disparate workflows (royalty schedules vs
  generative art vs access policies) into one codepath, increasing complexity
  and coupling, while yielding limited operational benefit.
- A shared core library retains reuse benefits (types, validators, utilities)
  without breaking service autonomy or deployment independence.
- Migration can be incremental: adopt the core library per service with low
  risk, and surface shared metrics/logging contracts.

## Alternatives Considered

### Option 1: Single parameterized `@lilith/token-service`

- **Pros**: One deployment, one API surface, centralized governance.
- **Cons**: Parameter explosion, conflicting SLAs, larger blast radius, complex
  routing/feature flags, harder parallel delivery.
- **Decision**: Rejected due to high coupling and complexity.

### Option 2: Keep all services independent (no shared layer)

- **Pros**: Maximum autonomy, zero migration effort.
- **Cons**: Continued type/utility duplication, inconsistent error/metrics
  patterns.
- **Decision**: Rejected; misses reuse and consistency goals.

### Option 3: Shared core library + templates (chosen)

- **Pros**: Reuse primitives, improve consistency, low-risk adoption, preserves
  service boundaries.
- **Cons**: Requires gradual refactors and stewardship to avoid library sprawl.
- **Decision**: Accepted.

## Implementation

### Technical Changes Required

- [ ] Create `services/token-core/` (or shared workspace package) exporting:
  - Chain/network config types and address validation (reuse blockchain utils)
  - Base minting result/receipt shapes and metadata envelopes
  - Storage URI helpers and checksum utilities
  - Standardized error/metric/log schemas for token flows
- [ ] Add README and migration guide for adopting services.
- [ ] Refactor token-adjacent services to consume the shared primitives
      opportunistically.

### Migration Plan

- Start with low-risk adoptions (`token-access`, `achievement-token`) by
  swapping local validators/types for core equivalents.
- Incrementally migrate others; avoid API behavior changes during refactors.
- Maintain backward compatibility by leaving service request/response contracts
  intact while internalizing shared types.

### Testing Strategy

- Core library: unit tests for validators, metadata helpers, and receipts.
- Services: contract tests to ensure no API regressions after adopting core
  types; snapshot important metadata payloads where applicable.

## Impact Assessment

- **Services Affected**: achievement-token, creator-royalty, native-token,
  ritual-access, sacred-art, sacred-music, sacred-space, token-access.
- **Performance**: Neutral; shared helpers should not materially change latency.
- **Security**: Centralized validation reduces drift; ensure library follows
  secure defaults.
- **Operational**: Improves consistency of metrics and logs across token
  services; minimal deployment change since services remain independent.

## Metrics & Success Criteria

- ≥50% reduction in duplicated token/address/metadata type definitions across
  the listed services.
- Zero API contract regressions post-migration (per contract tests).
- Shared logging/metrics fields (correlation IDs, chainId, tokenId) present
  across services.

## Timeline

- Decision date: 2025-12-04
- Implementation start: TBD
- Rollout complete: TBD (service-by-service)
- Review: After first two service migrations adopt `token-core`.

## Dependencies

- Existing blockchain utilities (address validation).
- CI coverage for token services to guard regressions.
- Documentation updates (service READMEs, contributor guides).

## Risks & Mitigation

| Risk                              | Impact | Likelihood | Mitigation                                                                           |
| --------------------------------- | ------ | ---------- | ------------------------------------------------------------------------------------ |
| Library scope creep               | Medium | Medium     | Keep `token-core` narrowly focused on primitives; require reviews for new modules.   |
| Incomplete adoption               | Low    | Medium     | Track migration per service; add lint rule for duplicated validators where feasible. |
| Hidden API drift during refactors | Medium | Low        | Use contract tests and payload snapshots before/after adoption.                      |

## Communication Plan

- Announce decision in engineering sync and update service owners.
- Add migration notes to service READMEs when adopting `token-core`.
- Link ADR in contributor onboarding docs.

## References

- TODO item: “Evaluate consolidating into single parameterized
  `@lilith/token-service`” in `TODOS.md`.
- Token service sources reviewed: `achievement-token`, `creator-royalty`,
  `native-token`, `ritual-access`, `sacred-art`, `sacred-music`, `sacred-space`,
  `token-access`.
