diff --git a/.specs/client-module-workflow.md b/.specs/client-module-workflow.md
new file mode 100644
index 00000000..855c9dcb
--- /dev/null
+++ b/.specs/client-module-workflow.md
@@ -0,0 +1,212 @@
+# Evolution SDK Client Module
+
+## Abstract
+
+This document specifies the Evolution SDK client architecture and normative behaviors for composing provider and wallet capabilities in TypeScript applications. It defines client roles, available operations, upgrade semantics, transaction building constraints, and the error model. Examples illustrate key usage patterns; detailed feature matrices are provided in the Appendix.
+
+## Purpose and Scope
+
+This specification describes how clients are constructed and enhanced with providers and wallets, what operations are available for each client role, and how transaction building and submission behave. It does not define provider-specific protocols, CIP-30 details, or internal implementation; those are covered by code and provider-specific documents. Multi-provider behavior is specified at a high level here and in detail in the Provider Failover specification. For Effect-based vs Promise-based usage, see the [Effect-Promise Architecture Guide](./effect-promise-architecture.md).
+
+## Introduction
+
+The Evolution SDK offers a progressive client model: start with a minimal client and add a provider and/or wallet to unlock read, sign, and submit capabilities. The goal is clear separation of concerns and compile-time safety for what a given client can do.
+
+```mermaid
+graph TD
+ A[MinimalClient] -->|Add Provider| B[ProviderOnlyClient]
+ A -->|Add Signing Wallet| C[SigningWalletClient]
+ A -->|Add ReadOnly Wallet| D[ReadOnlyWalletClient]
+ A -->|Add API Wallet| E[ApiWalletClient]
+ B -->|Add Signing Wallet| F[SigningClient]
+ B -->|Add ReadOnly Wallet| G[ReadOnlyClient]
+ C -->|Add Provider| F
+ D -->|Add Provider| G
+ E -->|Add Provider| F
+
+ classDef minimal fill:#3b82f6,stroke:#1e3a8a,stroke-width:3px,color:#ffffff,font-weight:bold,font-size:14px
+ classDef provider fill:#8b5cf6,stroke:#4c1d95,stroke-width:3px,color:#ffffff,font-weight:bold,font-size:14px
+ classDef signingWallet fill:#f59e0b,stroke:#92400e,stroke-width:3px,color:#ffffff,font-weight:bold,font-size:14px
+ classDef readOnlyWallet fill:#10b981,stroke:#065f46,stroke-width:3px,color:#ffffff,font-weight:bold,font-size:14px
+ classDef apiWallet fill:#f97316,stroke:#9a3412,stroke-width:3px,color:#ffffff,font-weight:bold,font-size:14px
+ classDef readOnlyClient fill:#06b6d4,stroke:#0e7490,stroke-width:3px,color:#ffffff,font-weight:bold,font-size:14px
+ classDef signingClient fill:#ef4444,stroke:#991b1b,stroke-width:3px,color:#ffffff,font-weight:bold,font-size:14px
+
+ class A minimal
+ class B provider
+ class C signingWallet
+ class D readOnlyWallet
+ class E apiWallet
+ class F signingClient
+ class G readOnlyClient
+```
+
+Summary:
+- MinimalClient: no read/sign/submit
+- ProviderOnlyClient: read and submit (where applicable), no signing
+- SigningWalletClient: sign only
+- ReadOnlyWalletClient: address/rewardAddress only
+- ApiWalletClient: CIP-30 sign and submit via wallet API
+- ReadOnlyClient: provider + read-only wallet; can query wallet data
+- SigningClient: provider + signing wallet or API wallet; full capability
+
+Matrices summarizing exact method availability appear in the Appendix.
+
+## Functional Specification (Normative)
+
+Requirements language: The key words MUST, MUST NOT, SHOULD, SHOULD NOT, and MAY are to be interpreted as described in RFC 2119 and RFC 8174 when, and only when, they appear in all capitals.
+
+### 1. Client roles and conformance
+
+An Evolution SDK client instance conforms to exactly one role at a time:
+- MinimalClient
+- ProviderOnlyClient
+- SigningWalletClient
+- ReadOnlyWalletClient
+- ApiWalletClient
+- ReadOnlyClient
+- SigningClient
+
+For each role, the following MUST hold:
+- MinimalClient MUST NOT expose provider or wallet operations; it MAY be upgraded.
+- ProviderOnlyClient MUST expose provider operations and MAY submit transactions if the provider supports submission; it MUST NOT expose signing.
+- SigningWalletClient MUST expose signing and message signing; it MUST NOT expose submission or provider queries.
+- ReadOnlyWalletClient MUST expose address() and rewardAddress(); it MUST NOT expose signing, provider queries, or submission.
+- ApiWalletClient MUST expose signing and MAY expose submission via the wallet API; it MUST NOT expose provider queries unless upgraded with a provider.
+- ReadOnlyClient MUST expose provider queries scoped to the configured address and MUST NOT expose signing.
+- SigningClient MUST expose provider queries, transaction building, signing, and submission.
+
+### 2. Network and provider operations
+
+- A client configured with a provider (ProviderOnlyClient, ReadOnlyClient, SigningClient) MUST provide `networkId` and provider query methods (e.g., `getProtocolParameters`, `getUtxos`, `awaitTx`, `evaluateTx`) as listed in the Appendix.
+- `submitTx` MUST be available on clients with a provider or API wallet capable of submission (ProviderOnlyClient, ReadOnlyClient, SigningClient, ApiWalletClient).
+- Provider implementations and their supported operations are out of scope here; see provider-specific docs. A multi-provider MUST follow the strategy defined in the [Provider Failover specification](./provider-failover.md).
+
+### 3. Wallet operations
+
+- A client configured with a wallet MUST provide `address()` and `rewardAddress()` where the wallet type supports them.
+- SigningWalletClient and SigningClient MUST provide `signTx(tx)` and `signMessage(address, payload)`.
+- ReadOnlyWalletClient and ReadOnlyClient MUST NOT provide signing methods.
+- ApiWalletClient MUST provide signTx and SHOULD provide submitTx if the wallet API supports submission.
+
+### 4. Transaction building
+
+- `newTx()` MUST be exposed only on clients that have a provider (ReadOnlyClient, SigningClient).
+- Building a transaction MUST require provider protocol parameters.
+- `build()`/`complete()` on ReadOnlyClient MUST produce an unsigned `Transaction`.
+- `build()`/`complete()` on SigningClient MUST produce a `SignBuilder` (or equivalent) that can be signed and submitted.
+- ApiWalletClient MUST be upgraded to SigningClient (by attaching a provider) before it can build transactions.
+
+### 5. Attachment and upgrade semantics
+
+- `createClient()` without arguments MUST return a MinimalClient.
+- `attachProvider(provider)` and `attachWallet(wallet)` MUST return new client instances (i.e., the API is immutable) with upgraded roles as per the Introduction diagram.
+- `createClient({ network, provider })` MUST produce a ProviderOnlyClient.
+- `createClient({ network, wallet })` MUST produce SigningWalletClient, ReadOnlyWalletClient, or ApiWalletClient depending on wallet type.
+- `createClient({ network, provider, wallet })` MUST produce ReadOnlyClient or SigningClient depending on wallet type.
+
+### 6. Error model and effect semantics
+
+- Methods that interact with external systems MUST reject/raise with typed errors: ProviderError for provider failures, WalletError for wallet failures, MultiProviderError for strategy/exhaustion failures, and TransactionBuilderError for builder validation issues.
+- The Effect API MUST preserve the same error categories as typed causes; callers MAY use retries, timeouts, and fallbacks. The Promise API MUST be semantically equivalent to running the corresponding Effect program to completion.
+- Multi-provider failover MUST adhere to the [Provider Failover specification](./provider-failover.md).
+
+### 7. API equivalence (Effect vs Promise)
+
+For every Promise-returning method, an equivalent Effect program MUST exist under the `client.Effect` namespace with identical semantics regarding success values and error categories.
+
+### 8. Examples (Informative)
+
+Simple creation and upgrade:
+```typescript
+const client = createClient()
+const providerClient = client.attachProvider({ type: "blockfrost", apiKey: "your-key" })
+const signingClient = providerClient.attachWallet({ type: "seed", mnemonic: "your mnemonic" })
+```
+
+Direct creation:
+```typescript
+const client = createClient({
+ network: "mainnet",
+ provider: { type: "blockfrost", apiKey: "your-key" },
+ wallet: { type: "seed", mnemonic: "your mnemonic" }
+})
+```
+
+Browser wallet (CIP-30) with upgrade:
+```typescript
+const apiClient = createClient({ network: "mainnet", wallet: { type: "api", api: window.cardano.nami } })
+const fullClient = apiClient.attachProvider({ type: "blockfrost", apiKey: "your-key" })
+```
+
+Signing-only wallet (no submit without provider):
+```typescript
+const signingWallet = createClient({ network: "mainnet", wallet: { type: "seed", mnemonic: "your mnemonic" } })
+// await signingWallet.submitTx(...) // not available
+```
+
+Effect usage (retries, timeouts):
+```typescript
+const program = client.Effect.signTx(tx).pipe(Effect.retry({ times: 3 }), Effect.timeout(30000))
+const signed = await Effect.runPromise(program)
+```
+
+## Appendix (Informative)
+
+### A. Core methods by role
+
+| Method/Capability | MinimalClient | ProviderOnlyClient | SigningWalletClient | ReadOnlyWalletClient | ApiWalletClient | ReadOnlyClient | SigningClient |
+|-------------------|---------------|--------------------|---------------------|----------------------|-----------------|----------------|---------------|
+| **Network Access** |
+| `networkId` | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
+| **Provider Operations** |
+| `getProtocolParameters()` | ❌ | ✅ | ❌ | ❌ | ❌ | ✅ | ✅ |
+| `getUtxos(address)` | ❌ | ✅ | ❌ | ❌ | ❌ | ✅ | ✅ |
+| `getUtxosWithUnit(address, unit)` | ❌ | ✅ | ❌ | ❌ | ❌ | ✅ | ✅ |
+| `getUtxoByUnit(unit)` | ❌ | ✅ | ❌ | ❌ | ❌ | ✅ | ✅ |
+| `getUtxosByOutRef(outRefs)` | ❌ | ✅ | ❌ | ❌ | ❌ | ✅ | ✅ |
+| `getDelegation(rewardAddress)` | ❌ | ✅ | ❌ | ❌ | ❌ | ✅ | ✅ |
+| `getDatum(datumHash)` | ❌ | ✅ | ❌ | ❌ | ❌ | ✅ | ✅ |
+| `awaitTx(txHash)` | ❌ | ✅ | ❌ | ❌ | ❌ | ✅ | ✅ |
+| `evaluateTx(tx)` | ❌ | ✅ | ❌ | ❌ | ❌ | ✅ | ✅ |
+| `submitTx(tx)` | ❌ | ✅ | ❌ | ❌ | ✅ | ✅ | ✅ |
+| **Wallet Operations** |
+| `address()` | ❌ | ❌ | ✅ | ✅ | ✅ | ✅ | ✅ |
+| `rewardAddress()` | ❌ | ❌ | ✅ | ✅ | ✅ | ✅ | ✅ |
+| `getWalletUtxos()` | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | ✅ |
+| `getWalletDelegation()` | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | ✅ |
+| `signTx(tx)` | ❌ | ❌ | ✅ | ❌ | ✅ | ❌ | ✅ |
+| `signMessage(address, payload)` | ❌ | ❌ | ✅ | ❌ | ✅ | ❌ | ✅ |
+| **Transaction Building** |
+| `newTx()` | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | ✅ |
+| **Client Composition** |
+| `attachProvider()` | ✅ | ❌ | ✅ | ✅ | ✅ | ❌ | ❌ |
+| `attachWallet()` | ❌ | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ |
+| `attach(provider, wallet)` | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ |
+
+### B. Transaction builder capabilities
+
+| Builder Method | ReadOnlyClient | SigningClient | Notes |
+|----------------|----------------|---------------|--------|
+| `build()` | ✅ → `Transaction` | ✅ → `SignBuilder` | ReadOnlyClient returns unsigned transaction; SigningClient returns a builder with signing capabilities |
+
+Note: Transaction building requires protocol parameters from a provider. ApiWalletClient MUST be upgraded before building.
+
+### C. Provider support (categories)
+
+| Category | Description | Supported Operations |
+|----------|-------------|---------------------|
+| REST API provider | External REST service | All provider operations |
+| Node-backed stack | Local/remote node stack (e.g., indexer + node) | All provider operations |
+| Cloud API provider | Managed blockchain API | All provider operations |
+| Alternative REST provider | Another REST-based service | All provider operations |
+| Multi-provider (strategy) | Failover/hedged strategy | All provider operations with redundancy (see [Provider Failover Specification](./provider-failover.md)) |
+
+### D. Wallet support
+
+| Wallet Type | Client Types | Description | Capabilities |
+|-------------|-------------|-------------|--------------|
+| **Seed Wallet** | SigningWalletClient, SigningClient | HD wallet from mnemonic | Sign only (no submit without provider) |
+| **Private Key** | SigningWalletClient, SigningClient | Single key wallet | Sign only (no submit without provider) |
+| **Read-Only** | ReadOnlyWalletClient, ReadOnlyClient | Address monitoring | Query only, no signing |
+| **API Wallet (CIP-30)** | ApiWalletClient, SigningClient | Browser extension | Sign + submit via extension |
diff --git a/.specs/complete-tx-builder-workflow-diagram.md b/.specs/complete-tx-builder-workflow-diagram.md
new file mode 100644
index 00000000..7b272c4a
--- /dev/null
+++ b/.specs/complete-tx-builder-workflow-diagram.md
@@ -0,0 +1,177 @@
+# CompleteTxBuilder Workflow Diagram
+
+```mermaid
+graph TD
+ A["Start: complete() Function"] --> B["Phase 1: Setup & Validation"]
+ B --> B1["Fetch Wallet UTxOs"]
+ B --> B2["Derive Change Address"]
+ B --> B3["Validate Options"]
+
+ B1 --> C["Phase 2: Initial Coin Selection"]
+ B2 --> C
+ B3 --> C
+
+ C --> C1["Calculate Asset Delta
outputs + fee - collected - minted"]
+ C1 --> C2["Filter Required Assets
positive amounts only"]
+ C2 --> C3["Recursive UTxO Selection
largest-first strategy"]
+
+ C3 --> D{"Has Plutus Scripts?"}
+
+ D -->|No| F["Phase 5: Skip Script Evaluation"]
+ D -->|Yes| E["Phase 3: Script Evaluation"]
+
+ E --> E1["Build Evaluation Transaction
CML.build_for_evaluation()"]
+ E1 --> E2{"Local UPLC?"}
+
+ E2 -->|Yes| E3["WASM UPLC Evaluation
evalTransaction()"]
+ E2 -->|No| E4["Provider Evaluation
evalTransactionProvider()"]
+
+ E3 --> E5["Apply UPLC Results
applyUPLCEval()"]
+ E4 --> E6["Apply Provider Results
applyUPLCEvalProvider()"]
+
+ E5 --> G["Phase 4: Refined Coin Selection"]
+ E6 --> G
+
+ G --> G1["Recalculate Fee with Script Costs"]
+ G1 --> G2["Check if Additional UTxOs Needed"]
+ G2 --> G3{"Need More UTxOs?"}
+
+ G3 -->|Yes| G4["Select Additional UTxOs"]
+ G3 -->|No| H["Phase 5: Collateral Management"]
+
+ G4 --> G5{"Script Budget Changed?"}
+ G5 -->|Yes| E1
+ G5 -->|No| H
+
+ H --> H1["Calculate Collateral Amount
150% of estimated fee"]
+ H1 --> H2["Find Collateral UTxOs
ADA-only, max 3"]
+ H2 --> H3["Apply Collateral to Transaction"]
+
+ H3 --> I["Phase 6: Final Assembly"]
+
+ I --> I1["Complete Partial Programs
Build redeemers with indices"]
+ I1 --> I2["Final CML Transaction Build"]
+ I2 --> I3["Apply Final ExUnits"]
+
+ I3 --> J["Return Built Transaction"]
+
+ F --> I
+
+ style A fill:#4a90e2,color:#ffffff,stroke:#2171b5,stroke-width:3px
+ style B fill:#9b59b6,color:#ffffff,stroke:#8e44ad,stroke-width:3px
+ style C fill:#27ae60,color:#ffffff,stroke:#229954,stroke-width:3px
+ style D fill:#f39c12,color:#ffffff,stroke:#e67e22,stroke-width:3px
+ style E fill:#e74c3c,color:#ffffff,stroke:#c0392b,stroke-width:3px
+ style F fill:#95a5a6,color:#ffffff,stroke:#7f8c8d,stroke-width:3px
+ style G fill:#1abc9c,color:#ffffff,stroke:#16a085,stroke-width:3px
+ style H fill:#f1c40f,color:#2c3e50,stroke:#f39c12,stroke-width:3px
+ style I fill:#34495e,color:#ffffff,stroke:#2c3e50,stroke-width:3px
+ style J fill:#2ecc71,color:#ffffff,stroke:#27ae60,stroke-width:4px
+
+ classDef phaseBox fill:#ecf0f1,stroke:#34495e,stroke-width:3px,color:#2c3e50
+ classDef decision fill:#fff3cd,stroke:#856404,stroke-width:3px,color:#856404
+ classDef subprocess fill:#e8f4f8,stroke:#2980b9,stroke-width:2px,color:#2c3e50
+ classDef success fill:#d4edda,stroke:#155724,stroke-width:3px,color:#155724
+
+ class B,C,E,G,H,I phaseBox
+ class D,E2,G3,G5 decision
+ class B1,B2,B3,C1,C2,C3,E1,E3,E4,E5,E6,G1,G2,G4,H1,H2,H3,I1,I2,I3 subprocess
+ class J success
+```
+
+## Detailed Flow Explanation
+
+### Phase Transitions and Decision Points
+
+1. **Setup → Initial Selection**: Always proceeds after validation
+2. **Initial Selection → Script Check**: Determines if script evaluation needed
+3. **Script Evaluation → Refined Selection**: Only for Plutus script transactions
+4. **Refined Selection Loop**: Continues until stable UTxO selection achieved
+5. **Collateral Management**: Only applies to script transactions
+6. **Final Assembly**: Always completes the transaction building
+
+### Critical Decision Points
+
+#### Script Detection (`Has Plutus Scripts?`)
+```typescript
+// Determines evaluation path
+if (hasPlutusScriptExecutions) {
+ // Proceed to script evaluation
+} else {
+ // Skip to collateral/final assembly
+}
+```
+
+#### UPLC vs Provider Evaluation (`Local UPLC?`)
+```typescript
+if (localUPLCEval !== false) {
+ // Use WASM UPLC evaluation
+ applyUPLCEval(uplcResults, txBuilder)
+} else {
+ // Use external provider evaluation
+ applyUPLCEvalProvider(providerResults, txBuilder)
+}
+```
+
+#### UTxO Selection Stability (`Need More UTxOs?`)
+```typescript
+// Check if script costs require additional funds
+if (newEstimatedFee > currentCapacity) {
+ // Select more UTxOs and potentially re-evaluate scripts
+ return selectAdditionalUTxOs()
+}
+```
+
+#### Script Budget Changes (`Script Budget Changed?`)
+```typescript
+// If new inputs change script execution context
+if (inputSetChanged && hasSignificantBudgetChange) {
+ // Re-evaluate scripts with new input context
+ return reEvaluateScripts()
+}
+```
+
+### Error Paths (Not Shown in Diagram)
+
+Each phase can fail with specific error types:
+- **Phase 1**: Wallet access errors, configuration validation errors
+- **Phase 2**: Insufficient funds errors, UTxO availability errors
+- **Phase 3**: Script evaluation errors, UPLC compilation errors
+- **Phase 4**: Fee calculation errors, UTxO selection errors
+- **Phase 5**: Collateral selection errors, protocol limit errors
+- **Phase 6**: Redeemer building errors, transaction assembly errors
+
+### Performance Considerations
+
+#### Iterative Loops
+- **Coin Selection Loop**: May iterate multiple times for complex asset requirements
+- **Script Evaluation Loop**: May re-evaluate if input set changes significantly
+- **Minimum ADA Loop**: Continues until change outputs meet minimum requirements
+
+#### Expensive Operations
+- **Script Evaluation**: Most expensive operation, especially for complex scripts
+- **UTxO Sorting**: O(n log n) for large UTxO sets
+- **Recursive Selection**: May examine many UTxO combinations
+
+### State Dependencies
+
+```mermaid
+graph LR
+ A[Wallet UTxOs] --> B[Available Inputs]
+ B --> C[Selected UTxOs]
+ C --> D[Draft Transaction]
+ D --> E[Script Evaluation]
+ E --> F[Final Transaction]
+
+ G[Protocol Parameters] --> B
+ G --> E
+ G --> F
+
+ H[Transaction Outputs] --> C
+ H --> D
+
+ I[Minted Assets] --> C
+ I --> D
+```
+
+This workflow represents one of the most complex transaction building systems in the Cardano ecosystem, with sophisticated handling of script evaluation, UTxO management, and fee calculation.
\ No newline at end of file
diff --git a/.specs/effect-promise-architecture.md b/.specs/effect-promise-architecture.md
new file mode 100644
index 00000000..f0f2919f
--- /dev/null
+++ b/.specs/effect-promise-architecture.md
@@ -0,0 +1,255 @@
+# Evolution SDK Effect-Promise Dual Interface Specification
+
+## Abstract
+
+The Evolution SDK implements a dual interface architecture providing both Effect-based and Promise-based APIs for all I/O operations and resource management. This specification defines the architectural requirements ensuring consistent execution semantics, safe resource handling, and compositional program construction while maintaining familiar Promise interfaces for traditional async/await patterns.
+
+## Purpose and Scope
+
+**Purpose**: Establish architectural requirements for dual Effect/Promise interfaces that ensure consistent execution semantics, centralized policy application, and safe resource handling across all SDK modules.
+
+**Scope**: Applies to all publicly exported SDK modules that perform I/O, resource acquisition, computation orchestration, or policy-controlled execution. Excludes purely synchronous utility functions with no side effects or Effect runtime dependencies.
+
+**Target Architecture**: Dual-layer interface design where Effect programs serve as the primary composable API with Promise wrappers providing convenience access for immediate execution patterns.
+
+## Introduction
+
+The Effect-Promise dual interface architecture addresses the need for both composable functional programming patterns and familiar async/await integration within the Evolution SDK. The system maintains a strict separation where Effect programs remain lazy descriptions until interpretation, while Promise methods provide immediate execution semantics.
+
+```mermaid
+graph TB
+ subgraph "Effect Layer (Primary)"
+ E1[Effect Programs]
+ E2["• Lazy evaluation
• Execute at edge
• Composable
• Resource safe"]
+ end
+ subgraph "Promise Layer (Convenience)"
+ P1[Promise Methods]
+ P2["• Eager execution
• Immediate results
• Familiar patterns
• Simple usage"]
+ end
+ subgraph "Conversion Bridge"
+ Bridge[Effect.runPromise]
+ Bridge2["• Executes Effect program
• Converts to Promise
• Preserves error types
• Ensures cleanup"]
+ end
+ E1 --> Bridge
+ Bridge --> P1
+ E1 --> E2
+ P1 --> P2
+ Bridge --> Bridge2
+
+ classDef effect fill:#89b4fa,stroke:#74c7ec,stroke-width:3px,color:#11111b
+ classDef promise fill:#a6e3a1,stroke:#94e2d5,stroke-width:3px,color:#11111b
+ classDef bridge fill:#f38ba8,stroke:#fab387,stroke-width:3px,color:#11111b
+
+ class E1,E2 effect
+ class P1,P2 promise
+ class Bridge,Bridge2 bridge
+```
+
+The architecture enables hybrid composition where Effect-based modules can build upon other Effect modules while still providing Promise convenience APIs for non-Effect developers.
+
+## Functional Specification (Normative)
+
+The following requirements are specified using RFC 2119/8174 keywords: MUST (absolute requirement), SHOULD (recommended), MAY (optional).
+
+### 1. Interface Architecture
+
+**1.1**: The primary API **MUST** consist solely of functions that return Effect program descriptions.
+
+**1.2**: Each Promise wrapper **MUST** correspond exactly to one primary function differing only in return type.
+
+**1.3**: The Promise layer **MUST NOT** introduce additional business logic beyond delegation and interpretation.
+
+**1.4**: All external side effects **MUST** occur only during interpretation at execution edges.
+
+### 2. Execution semantics
+
+**2.1**: Effect construction **MUST** be side-effect free with respect to external systems.
+
+**2.2**: Observable external interactions **MUST** be deferred until interpretation at execution edges.
+
+**2.3**: Promise wrappers **MUST** invoke exactly one interpreter call per user invocation.
+
+**2.4**: Error propagation **MUST** preserve both success values and classified errors without modification.
+
+**2.5**: Effect programs **MUST** be lazy descriptions that defer execution until interpretation.
+
+**2.6**: Promise wrappers **MUST** execute immediately upon invocation.
+
+**2.7**: Effect programs **MUST** be composable without triggering side effects during composition.
+
+**2.8**: Both interfaces **MUST** preserve identical business logic and error semantics.
+
+**2.9**: Effect programs **MUST** support compositional reasoning without external dependencies.
+
+**2.10**: Promise wrappers **MUST** maintain referential transparency for the same Effect program.
+
+### 3. Interface contracts
+
+**3.1**: The dual interface **SHALL** follow the canonical structure defined in the Appendix (A.1).
+
+**3.2**: The `Effect` property **MUST** be immutable after construction.
+
+**3.3**: Promise wrappers **MUST** retain original parameter ordering and count.
+
+**3.4**: The mapping **MUST** be total for all public Effect methods (no omissions).
+
+### 4. Resource management and reliability
+
+**4.1**: Interpretation **MAY** occur only at explicitly designated execution edges.
+
+**4.2**: Implementations **MUST** support Effect runtime cancellation semantics.
+
+**4.3**: Timeouts, retries, and circuit breakers **MUST** be Effect-level combinators, not Promise logic.
+
+**4.4**: Resource acquisition **MUST** use Effect scopes ensuring deterministic finalization.
+
+**4.5**: Promise wrappers **MUST NOT** leak resources after resolution or rejection.
+
+**4.6**: Parallelism **MUST** use Effect concurrency combinators with explicit options.
+
+### 5. Security constraints
+
+**5.1**: Effect construction **MUST NOT** perform network or filesystem I/O.
+
+**5.2**: Secrets **MUST** be injected through Effect services, not module-level state.
+
+**5.3**: Implementations **SHOULD** isolate nondeterminism behind Effect services.
+
+**5.4**: Promise wrappers **MUST NOT** cache mutable shared results without explicit policy.
+
+### 6. Error handling
+
+**6.1**: Effect functions **SHOULD** model domain and infrastructure failures via typed error channels.
+
+**6.2**: Promise wrappers **MUST** surface failures as Promise rejections preserving error discriminability.
+
+**6.3**: Wrappers **MUST NOT** swallow or transform errors except for Promise rejection semantics.
+
+**6.4**: Implementations **SHOULD** avoid synchronous throws in Promise wrappers.
+
+**6.5**: Structured logging, metrics, and tracing **SHOULD** be implemented as Effect layers.
+
+**6.6**: Promise wrappers **MAY** add tracing context only if transparent and non-invasive.
+
+**6.7**: Error context **MUST** preserve original failure source and execution path.
+
+## Appendix (Informative) {#appendix}
+
+### A.1. Canonical Interface Structure
+
+```typescript
+interface ModuleEffect {
+ /* Effect-returning functions only */
+}
+
+type EffectToPromiseAPI = {
+ readonly [K in keyof T]: T[K] extends (...a: infer P) => Effect.Effect
+ ? (...a: P) => Promise
+ : never
+}
+
+interface Module extends EffectToPromiseAPI {
+ readonly Effect: ModuleEffect
+}
+```
+
+### A.2. Hybrid Module Composition Flow
+
+```mermaid
+flowchart TD
+ subgraph CompositionLayer["⚡ Effect Composition Layer"]
+ direction LR
+ A_Module["🔵 Module A
Effect<User, UserError>
Effect<Valid, ValidationError>
Effect<void, StoreError>
📝 Typed error channels"]
+
+ B_Module["🔵 Module B
Effect<User, RegisterError>
Effect<Profile, UpdateError>
Effect<void, DeactivateError>
🔗 Composes A's errors"]
+
+ C_Module["🔵 Module C
Effect<Results, BulkError>
Effect<Audit, AuditError>
🔗 Composes A+B errors"]
+
+ A_Module ===|"Compose & Chain"| B_Module
+ B_Module ===|"Compose & Chain"| C_Module
+
+ Composition["🔗 Composition Logic
registerUser =
validateUser >>=
storeUser >>=
sendWelcomeEmail
🚫 No execution until interpreted
✅ Errors as typed values
🔧 Compile-time guarantees"]
+ A_Module -.-> Composition
+ B_Module --> Composition
+ end
+
+ subgraph ExecutionLayer["🎯 Promise Execution Layer"]
+ direction TB
+ Interface_A["🟢 Interface A
Promise<User>
Promise<Valid>
Promise<void>
⚡ Execute Immediately
❌ Runtime exceptions
🚨 try/catch required"]
+
+ Interface_B["🟢 Interface B
Promise<User>
Promise<Profile>
Promise<void>
⚡ Execute Immediately
❌ Runtime exceptions
🚨 try/catch required"]
+
+ Interface_C["🟢 Interface C
Promise<Results>
Promise<Audit>
⚡ Execute Immediately
❌ Runtime exceptions
🚨 try/catch required"]
+ end
+
+ subgraph Developers["👥 Developer Approaches"]
+ Effect_Path["🎯 Effect-Based Development
━━━━━━━━━━━━━
• Errors as typed values
• Compile-time guarantees
• Compose error handling
• No runtime surprises
• Control execution timing
• Resource safety
• Cancellation support"]
+
+ Promise_Path["⚡ Promise-Based Development
- - - - - - - - - - - - -
• Runtime exceptions
• try/catch everywhere
• Immediate execution
• Familiar async/await
• Simple integration
• No composition control
• Runtime error handling"]
+ end
+
+ %% Layer connections
+ A_Module ===> Interface_A
+ B_Module ===> Interface_B
+ C_Module ===> Interface_C
+
+ %% Developer paths
+ CompositionLayer -.->|"Use Effect namespace"| Effect_Path
+ ExecutionLayer -.->|"Use Promise methods"| Promise_Path
+
+ classDef compositionLayer fill:#89b4fa,stroke:#74c7ec,stroke-width:3px,color:#11111b
+ classDef executionLayer fill:#a6e3a1,stroke:#94e2d5,stroke-width:3px,color:#11111b
+ classDef module fill:#313244,stroke:#89b4fa,stroke-width:2px,color:#cdd6f4
+ classDef interface fill:#313244,stroke:#a6e3a1,stroke-width:2px,color:#cdd6f4
+ classDef composition fill:#f9e2af,stroke:#fab387,stroke-width:2px,color:#11111b
+ classDef developerPath fill:#cba6f7,stroke:#f38ba8,stroke-width:2px,color:#11111b
+
+ class CompositionLayer compositionLayer
+ class ExecutionLayer executionLayer
+ class A_Module,B_Module,C_Module module
+ class Interface_A,Interface_B,Interface_C interface
+ class Composition composition
+ class Effect_Path,Promise_Path developerPath
+```
+
+### A.3. Key Architectural Benefits
+
+- **Composability**: Effect namespaces enable modules to build upon each other's functionality without execution boundaries
+- **Lazy Evaluation**: Effect programs are constructed but not executed until interpretation, allowing complex composition without side effects
+- **Developer Choice**: Promise APIs provide immediate execution for developers who don't need Effect's advanced composition features
+- **Resource Control**: Effect composition maintains proper resource scoping and cleanup across module boundaries
+
+### A.4. System Responsibilities Matrix
+
+| Component | Responsibilities |
+|-----------|------------------|
+| **Module** | Expose both Effect and Promise interfaces with 1:1 mapping; Ensure Effect programs remain lazy until interpretation; Implement proper resource scoping and cleanup; Maintain consistent error handling across both interfaces |
+| **Effect Layer** | Provide composable, lazy program descriptions; Handle resource acquisition with automatic finalization; Implement cancellation and interruption semantics; Support structured concurrency and policy application |
+| **Promise Layer** | Delegate to Effect programs via single interpreter calls; Preserve error taxonomy in Promise rejection channels; Avoid introducing additional business logic or side effects; Maintain parameter compatibility with Effect counterparts |
+
+### A.5. Key Abstractions
+
+**Effect Program**: Lazy description of a computation that produces no external side effects until interpreted. Programs are composable and resource-safe by construction.
+
+**Execution Edge**: Deliberate boundary where Effect programs are interpreted (CLI entry points, HTTP handlers, worker loops). External side effects occur only at these boundaries.
+
+**Promise Wrapper**: Eager adapter method that invokes corresponding Effect programs via interpreter, returning native Promises. Maintains 1:1 mapping with Effect methods.
+
+**Primary API**: The `Effect` namespace containing Effect-returning functions. This is the authoritative interface for all module operations.
+
+**Interpreter**: Approved runtime function (e.g. `Effect.runPromise`) that executes Effect programs and handles resource management, error propagation, and cleanup.
+
+### A.6. Error Classification and Behavior
+
+**Typed Error Channels**: Effect programs use tagged error types to distinguish between domain failures, infrastructure failures, and system errors.
+
+**Promise Error Mapping**: Promise wrappers preserve error taxonomy through Promise rejection channels using tagged object instances or error subclasses.
+
+**Error Preservation**: System maintains complete error context and classification through the Effect-Promise boundary without loss of diagnostic information.
+
+**Validation Handling**: Input validation occurs either lazily within Effect programs or eagerly in wrappers without side effects.
+
+**Resource Error Recovery**: Failed resource acquisition triggers automatic cleanup through Effect scoped combinators.
+
+**Cancellation Errors**: System properly handles and propagates Effect runtime cancellation and interruption signals through Promise interfaces.
+
diff --git a/.specs/legacy-complete-tx-builder-analysis.md b/.specs/legacy-complete-tx-builder-analysis.md
new file mode 100644
index 00000000..e2f1a49c
--- /dev/null
+++ b/.specs/legacy-complete-tx-builder-analysis.md
@@ -0,0 +1,532 @@
+# Legacy CompleteTxBuilder Analysis & Migration Guide
+
+**Version**: 1.0.0
+**Created**: September 24, 2025
+**Purpose**: Analyze the legacy Lucid Evolution CompleteTxBuilder for migration to Evolution SDK
+
+---
+
+## Executive Summary
+
+The legacy `CompleteTxBuilder` implements a sophisticated multi-phase transaction building workflow with hybrid CML (Cardano Multiplatform Library) integration and native TypeScript coin selection. This analysis breaks down the complex build process to guide migration to the new Evolution SDK architecture.
+
+**Key Characteristics**:
+- **Hybrid Architecture**: Uses CML for low-level transaction building with custom TypeScript coin selection
+- **Multi-Phase Build Process**: Iterative coin selection with script evaluation integration
+- **Complex State Management**: Manages UTxO sets, script evaluation, and collateral across multiple phases
+- **Effect-ts Integration**: Uses Effect monad for error handling and composable operations
+
+---
+
+## High-Level Architecture Overview
+
+The CompleteTxBuilder follows a **6-phase iterative workflow** with sophisticated error handling and resource management:
+
+```
+Phase 1: Setup & Validation
+ ↓
+Phase 2: Initial Coin Selection (No Script Costs)
+ ↓
+Phase 3: Script Evaluation & ExUnits Calculation
+ ↓
+Phase 4: Refined Coin Selection (With Script Costs)
+ ↓
+Phase 5: Collateral Selection & Management
+ ↓
+Phase 6: Final Transaction Assembly & Redeemer Building
+```
+
+### Core Components Integration
+
+```
+┌─────────────────┐ ┌──────────────────┐ ┌─────────────────┐
+│ Wallet │ │ TxBuilder │ │ CML Layer │
+│ (UTxO Fetch) │◄──►│ (Orchestrator) │◄──►│ (Transaction │
+│ │ │ │ │ Assembly) │
+└─────────────────┘ └──────────────────┘ └─────────────────┘
+ │ │ │
+ │ ┌───────▼────────┐ │
+ │ │ Coin Selection │ │
+ │ │ (TypeScript │ │
+ │ │ Native) │ │
+ │ └────────────────┘ │
+ │ │ │
+ └───────────────────────┼───────────────────────┘
+ ▼
+ ┌──────────────────┐
+ │ UPLC Evaluation │
+ │ (WASM/Provider) │
+ └──────────────────┘
+```
+
+---
+
+## Detailed Phase-by-Phase Workflow Analysis
+
+### Phase 1: Setup & Validation
+
+**Responsibilities**:
+- Validate build configuration and options
+- Fetch wallet UTxOs if not preset
+- Initialize transaction builder state
+
+**Key Operations**:
+```typescript
+// Wallet UTxO fetching with fallback
+const wallet: Wallet = yield* Effect.fromNullable(config.lucidConfig.wallet)
+const walletInputs = options.presetWalletInputs ??
+ (yield* wallet.utxos()).filter(hasNoRefScript)
+
+// Change address derivation
+const changeAddress = options.changeAddress ??
+ (yield* wallet.address()).toBech32()
+```
+
+**Critical Insights**:
+- UTxOs with reference scripts are excluded from coin selection
+- Change address defaults to wallet's primary address
+- Wallet instance is required (no read-only building support)
+
+### Phase 2: Initial Coin Selection (Without Script Costs)
+
+**Purpose**: Select UTxOs to cover basic transaction requirements excluding script execution costs.
+
+**Workflow**:
+1. **Asset Delta Calculation**:
+ ```typescript
+ // Calculate required assets: outputs + estimatedFee - collected - minted
+ const assetsDelta = pipe(
+ config.totalOutputAssets,
+ Record.union(estimatedFee, BigInt.sum),
+ Record.union(negatedCollectedAssets, BigInt.sum),
+ Record.union(negatedMintedAssets, BigInt.sum)
+ )
+ ```
+
+2. **Recursive UTxO Selection**:
+ ```typescript
+ // Select UTxOs using custom algorithm
+ const { selected } = yield* recursive(
+ sortUTxOs(availableInputs),
+ requiredAssets,
+ coinsPerUtxoByte,
+ notRequiredAssets,
+ includeLeftoverLovelaceAsFee
+ )
+ ```
+
+**Algorithm Details**:
+- **Sorting Strategy**: Largest UTxOs first for optimal selection
+- **Recursive Selection**: Iterative UTxO selection until all requirements met
+- **Minimum ADA Handling**: Ensures change outputs meet minimum ADA requirements
+- **Reference Script Exclusion**: Filters out UTxOs containing reference scripts
+
+### Phase 3: Script Evaluation & ExUnits Calculation
+
+**Purpose**: Determine actual script execution costs for accurate fee calculation.
+
+**Two-Track Evaluation Process**:
+
+#### Track A: WASM UPLC Evaluation (Local)
+```typescript
+if (localUPLCEval !== false) {
+ // Local UPLC evaluation using WASM
+ const uplcResults = yield* evalTransaction(config, txRedeemerBuilder, walletInputs)
+ applyUPLCEval(uplcResults, config.txBuilder)
+}
+```
+
+#### Track B: Provider Evaluation (Remote)
+```typescript
+else {
+ // External provider evaluation
+ const providerResults = yield* evalTransactionProvider(
+ config, txRedeemerBuilder, walletInputs
+ )
+ applyUPLCEvalProvider(providerResults, config.txBuilder)
+}
+```
+
+**Critical Implementation Details**:
+- Uses CML's `build_for_evaluation()` to create evaluation transaction
+- Evaluation transaction has dummy ExUnits and invalid script_data_hash
+- Results applied via `applyUPLCEval()` for CBOR bytes or `applyUPLCEvalProvider()` for structured data
+- **Safety Mechanism**: Evaluation transaction would fail if accidentally submitted
+
+### Phase 4: Refined Coin Selection (With Script Costs)
+
+**Purpose**: Adjust UTxO selection to account for actual script execution costs.
+
+**Workflow**:
+```typescript
+// Second round of coin selection including script execution costs
+yield* selectionAndEvaluation(
+ walletInputs,
+ changeAddress,
+ coinSelection,
+ localUPLCEval,
+ includeLeftoverLovelaceAsFee,
+ true // script_calculation = true
+)
+```
+
+**Key Considerations**:
+- **Fee Recalculation**: Includes script execution costs in total fee
+- **UTxO Re-evaluation**: May select additional UTxOs if script costs exceed initial estimates
+- **Script Budget Changes**: New inputs may change script execution budgets, requiring re-evaluation
+- **Iterative Process**: Continues until stable UTxO selection achieved
+
+### Phase 5: Collateral Selection & Management
+
+**Purpose**: Set up collateral for Plutus script transaction safety.
+
+**Collateral Calculation Logic**:
+```typescript
+const totalCollateral = BigInt(
+ Math.ceil(
+ Math.max(
+ (protocolParameters.collateralPercentage * Number(estimatedFee)) / 100,
+ Number(setCollateral)
+ )
+ )
+)
+```
+
+**Selection Criteria**:
+- **ADA-Only UTxOs**: No native tokens allowed in collateral
+- **No Reference Scripts**: UTxOs with reference scripts excluded
+- **Maximum 3 UTxOs**: Protocol limit for collateral inputs
+- **Sufficient Value**: Must cover calculated collateral amount
+
+**Error Handling**:
+- Comprehensive error messages for insufficient collateral
+- Specific handling for UTxOs with reference scripts
+- Clear indication when collateral limits exceeded
+
+### Phase 6: Final Assembly & Redeemer Building
+
+**Purpose**: Complete transaction assembly with proper redeemer indices and witness preparation.
+
+**Redeemer Building Process**:
+```typescript
+// Build redeemers with correct indices
+yield* completePartialPrograms()
+
+// Create final transaction with CML
+const txRedeemerBuilder = yield* Effect.try({
+ try: () => config.txBuilder.build_for_evaluation(
+ 0,
+ CML.Address.from_bech32(changeAddress)
+ ),
+ catch: (error) => completeTxError(error)
+})
+```
+
+**Index Management**:
+- **Input Mapping**: Maps UTxOs to their transaction input indices
+- **Redeemer Types**: Handles both "shared" (one per script) and "self" (one per UTxO) redeemers
+- **Index Validation**: Ensures redeemer indices match CML transaction structure
+
+---
+
+## Core Algorithms Deep Dive
+
+### Recursive Coin Selection Algorithm
+
+The `recursive()` function implements a sophisticated UTxO selection algorithm:
+
+```typescript
+export const recursive = (
+ inputs: UTxO[],
+ requiredAssets: Assets,
+ coinsPerUtxoByte: bigint,
+ externalAssets: Assets = {},
+ includeLeftoverLovelaceAsFee?: boolean
+): Effect
+```
+
+**Algorithm Steps**:
+1. **Initial Selection**: Select UTxOs to cover `requiredAssets`
+2. **Change Calculation**: Calculate available assets after selection
+3. **Minimum ADA Check**: Verify change outputs meet minimum ADA requirements
+4. **Recursive Iteration**: Select additional UTxOs if minimum ADA not met
+5. **Termination**: Continue until no additional ADA required
+
+**Key Features**:
+- **Largest-First Strategy**: Sorts UTxOs by value (descending)
+- **Iterative Refinement**: Handles complex minimum ADA scenarios
+- **External Asset Support**: Accounts for assets from minting/burning
+- **Comprehensive Error Handling**: Clear messages for insufficient funds
+
+### UTxO Selection Logic (`selectUTxOs`)
+
+**Selection Strategy**:
+```typescript
+// Conceptual implementation (actual logic in separate module)
+const selectUTxOs = (inputs: UTxO[], required: Assets, allowOverspend: boolean) => {
+ // 1. Filter UTxOs that can contribute to required assets
+ // 2. Sort by value (largest first) for optimal selection
+ // 3. Greedy selection until requirements met
+ // 4. Handle multi-asset requirements with asset-specific logic
+}
+```
+
+**Filtering Criteria**:
+- **No Reference Scripts**: Excludes UTxOs containing reference scripts
+- **Asset Availability**: Must contain required asset types
+- **Value Threshold**: Prioritizes larger UTxOs for efficiency
+
+### Fee Estimation Algorithm
+
+**Multi-Component Fee Calculation**:
+```typescript
+const estimateFee = (config: TxBuilderConfig, script_calculation: boolean) => {
+ const minFee = config.txBuilder.min_fee(script_calculation) // CML calculation
+ const refScriptFee = yield* calculateMinRefScriptFee(config) // Custom calculation
+ let estimatedFee = minFee + refScriptFee
+
+ // Apply custom minimum fee if higher
+ if (customMinFee > estimatedFee) {
+ estimatedFee = customMinFee
+ config.txBuilder.set_fee(estimatedFee)
+ }
+
+ return estimatedFee
+}
+```
+
+**Fee Components**:
+1. **Base Fee**: CML `min_fee()` based on transaction size
+2. **Reference Script Fee**: Custom calculation for reference script costs
+3. **Script Execution Fee**: Added during refined coin selection phase
+4. **Custom Minimum**: User-specified minimum fee override
+
+---
+
+## State Management & Dependencies
+
+### Configuration State (`TxBuilderConfig`)
+
+**Key State Components**:
+- `txBuilder: CML.TransactionBuilder` - Core CML transaction builder
+- `totalOutputAssets: Assets` - Accumulated output requirements
+- `mintedAssets: Assets` - Assets created through minting
+- `collectedInputs: UTxO[]` - Explicitly specified input UTxOs
+- `partialPrograms: Map` - Redeemer builders for scripts
+
+### Dependency Chain
+
+```
+Wallet → UTxOs → Coin Selection → CML TxBuilder → Script Evaluation → Final Transaction
+ ↓ ↓ ↓ ↓ ↓ ↓
+Address UTxO Set Selected UTxOs Draft Tx ExUnits Applied Submittable Tx
+```
+
+**Critical Dependencies**:
+1. **Wallet Required**: Cannot build without wallet instance
+2. **Provider Access**: Required for script evaluation (if not using local UPLC)
+3. **Protocol Parameters**: Essential for fee calculation and minimum ADA
+4. **CML Integration**: Heavy dependency on CML for transaction assembly
+
+---
+
+## Error Handling Strategy
+
+### Error Categories
+
+1. **Insufficient Funds Errors**:
+ ```typescript
+ completeTxError(
+ `Your wallet does not have enough funds to cover the required assets: ${requiredAssets}`
+ )
+ ```
+
+2. **Collateral Errors**:
+ ```typescript
+ completeTxError(
+ `Selected ${selected.length} inputs as collateral, but max collateral inputs is 3`
+ )
+ ```
+
+3. **Script Evaluation Errors**:
+ ```typescript
+ completeTxError(
+ `UPLC evaluation failed for script: ${scriptHash}`
+ )
+ ```
+
+4. **Index Management Errors**:
+ ```typescript
+ completeTxError(
+ `Index not found for input: ${input}`
+ )
+ ```
+
+### Error Recovery Strategies
+
+- **Graceful Degradation**: Fallback to provider evaluation if WASM fails
+- **Retry Logic**: Multiple attempts for network-dependent operations
+- **Clear Messaging**: Detailed error descriptions with context
+- **State Cleanup**: Proper resource cleanup on errors
+
+---
+
+## Migration Path to Evolution SDK
+
+### Architecture Transformation Required
+
+#### 1. CML Dependency Removal
+**Current**: Heavy reliance on CML for transaction building
+**Target**: Pure TypeScript implementation with optional CML interop
+
+**Migration Strategy**:
+```typescript
+// Current CML-dependent approach
+const txBuilder = CML.TransactionBuilder.new(protocolParams)
+const tx = txBuilder.build()
+
+// Evolution SDK native approach
+const signBuilder = await client.newTx()
+ .payToAddress(address, assets)
+ .build() // Pure TypeScript implementation
+```
+
+#### 2. Progressive Builder Pattern Adoption
+**Current**: Monolithic `complete()` function with all phases
+**Target**: Progressive TransactionBuilder → SignBuilder → SubmitBuilder
+
+**Migration Strategy**:
+```typescript
+// Current approach
+const completedTx = yield* complete({ changeAddress, coinSelection })
+
+// Evolution SDK approach
+const signBuilder = await client.newTx()
+ .payToAddress(address, assets)
+ .build({ coinSelection })
+
+const submitBuilder = await signBuilder.sign()
+const txHash = await submitBuilder.submit()
+```
+
+#### 3. UTxO State Management Modernization
+**Current**: Implicit wallet UTxO fetching with filtering
+**Target**: Explicit UTxO management with chaining support
+
+**Migration Strategy**:
+```typescript
+// Current implicit approach
+const walletInputs = (yield* wallet.utxos()).filter(hasNoRefScript)
+
+// Evolution SDK explicit approach
+const utxos = await client.getWalletUtxos()
+const chainResult = await client.newTx(utxos)
+ .payToAddress(address, assets)
+ .chain()
+```
+
+### Component Migration Priorities
+
+#### Phase 1: Core Algorithm Extraction
+1. **Coin Selection Logic**: Extract `recursive()` and `selectUTxOs()` algorithms
+2. **Fee Calculation**: Migrate `estimateFee()` and `calculateMinRefScriptFee()`
+3. **UTxO Management**: Extract filtering and sorting utilities
+
+#### Phase 2: Script Evaluation Modernization
+1. **Two-Phase Building**: Implement `buildForEvaluation()` pattern
+2. **UPLC Integration**: Port WASM UPLC evaluation logic
+3. **Provider Evaluation**: Modernize provider-based script evaluation
+
+#### Phase 3: Progressive Builder Implementation
+1. **TransactionBuilder**: Implement intent accumulation pattern
+2. **SignBuilder**: Create signing abstraction with partial signature support
+3. **SubmitBuilder**: Implement submission and simulation capabilities
+
+#### Phase 4: Integration & Testing
+1. **Wallet Integration**: Connect with Evolution SDK wallet system
+2. **Provider Integration**: Integrate with Evolution SDK provider architecture
+3. **Comprehensive Testing**: Migrate test suites and add new test coverage
+
+### Key Challenges & Solutions
+
+#### Challenge 1: CML Dependency Removal
+**Complexity**: Deep integration with CML for transaction assembly
+**Solution**:
+- Phase 1: Wrap CML operations in Evolution SDK interfaces
+- Phase 2: Implement native TypeScript transaction building
+- Phase 3: Remove CML dependencies entirely
+
+#### Challenge 2: State Management Complexity
+**Complexity**: Complex state management across multiple phases
+**Solution**:
+- Use Effect-ts for state management and error handling
+- Implement immutable state transitions
+- Clear separation of concerns between phases
+
+#### Challenge 3: Backward Compatibility
+**Complexity**: Existing applications depend on current API
+**Solution**:
+- Provide compatibility layer during transition
+- Gradual migration path with deprecation warnings
+- Comprehensive migration documentation
+
+---
+
+## Recommended Migration Strategy
+
+### Step 1: Algorithm Extraction (Week 1-2)
+```typescript
+// Extract core algorithms to Evolution SDK
+export const recursiveCoinSelection = (/* ... */) => { /* ... */ }
+export const calculateTransactionFee = (/* ... */) => { /* ... */ }
+export const selectOptimalUTxOs = (/* ... */) => { /* ... */ }
+```
+
+### Step 2: Interface Compatibility (Week 3-4)
+```typescript
+// Create compatibility layer
+export const complete = (options: CompleteOptions) =>
+ client.newTx()
+ ./* accumulate operations */
+ .build(options)
+ .then(signBuilder => signBuilder.sign())
+ .then(submitBuilder => submitBuilder.submit())
+```
+
+### Step 3: Progressive Enhancement (Week 5-8)
+```typescript
+// Implement progressive builder pattern
+const builder = client.newTx(utxos)
+ .payToAddress(address, assets)
+ .mintTokens(policy, tokens)
+
+const signBuilder = await builder.build(options)
+const submitBuilder = await signBuilder.sign()
+const txHash = await submitBuilder.submit()
+```
+
+### Step 4: Full Migration (Week 9-12)
+```typescript
+// Complete Evolution SDK native implementation
+const client = createClient({ provider, wallet, network })
+
+const chainResult = await client.newTx()
+ .payToAddress(address, assets)
+ .chain({ coinSelection: "largest-first" })
+
+await client.submitTx(chainResult.transaction)
+```
+
+---
+
+## Conclusion
+
+The legacy CompleteTxBuilder implements a sophisticated transaction building system with complex multi-phase workflows and hybrid CML integration. Migration to the Evolution SDK requires careful extraction of core algorithms while modernizing the architecture to support progressive builders, explicit UTxO management, and pure TypeScript implementation.
+
+**Key Success Factors**:
+1. **Incremental Migration**: Gradual transition with compatibility layers
+2. **Algorithm Preservation**: Maintain proven coin selection and fee calculation logic
+3. **Architecture Modernization**: Adopt progressive builder patterns and explicit state management
+4. **Comprehensive Testing**: Extensive testing during each migration phase
+
+The migration will result in a more maintainable, type-safe, and flexible transaction building system while preserving the sophisticated logic that makes the current implementation robust and reliable.
\ No newline at end of file
diff --git a/.specs/provider-failover.md b/.specs/provider-failover.md
new file mode 100644
index 00000000..5781478f
--- /dev/null
+++ b/.specs/provider-failover.md
@@ -0,0 +1,334 @@
+# Evolution SDK Provider Failover Specification
+
+## Abstract
+
+The Evolution SDK implements a multi-provider failover system enabling resilient blockchain interactions through automatic provider switching when failures occur. This specification defines the architecture, strategies, and error handling mechanisms for orchestrating failover between multiple Cardano data providers, supporting both priority-based and round-robin selection strategies with comprehensive error accumulation and debugging capabilities.
+
+## Purpose and Scope
+
+**Purpose**: Enable resilient blockchain interactions by automatically switching between multiple data providers when failures occur, ensuring high availability and fault tolerance for critical blockchain operations.
+
+**Scope**: Defines the architecture, behavioral contracts, and technical requirements for multi-provider failover system within Evolution SDK. Covers MultiProvider controller, failover strategies, error handling mechanisms, and integration contracts between providers and client applications.
+
+**Target Architecture**: Multi-provider orchestration system with pluggable failover strategies, immediate error-based switching, and comprehensive error accumulation for debugging and observability.
+
+## Introduction
+
+The provider failover system addresses the inherent unreliability of individual blockchain data providers by orchestrating requests across multiple providers with automatic failover on errors. The system supports multiple failover strategies optimized for different operational goals while maintaining comprehensive error tracking for debugging purposes.
+
+```mermaid
+graph TB
+ Client[Client Application] --> MultiProvider[MultiProvider Controller]
+ MultiProvider --> FailoverStrategy[Failover Strategy Engine]
+
+ FailoverStrategy --> Priority[Priority Strategy]
+ FailoverStrategy --> RoundRobin[Round Robin Strategy]
+
+ MultiProvider --> P1[Provider 1]
+ MultiProvider --> P2[Provider 2]
+ MultiProvider --> P3[Provider 3]
+ MultiProvider --> P4[Provider 4]
+
+ P1 --> CardanoNetwork[Cardano Network]
+ P2 --> CardanoNetwork
+ P3 --> CardanoNetwork
+ P4 --> CardanoNetwork
+
+ classDef client fill:#3b82f6,stroke:#1e40af,stroke-width:2px,color:#ffffff
+ classDef controller fill:#8b5cf6,stroke:#5b21b6,stroke-width:2px,color:#ffffff
+ classDef strategy fill:#f59e0b,stroke:#d97706,stroke-width:2px,color:#ffffff
+ classDef provider fill:#10b981,stroke:#065f46,stroke-width:2px,color:#ffffff
+ classDef network fill:#ef4444,stroke:#b91c1c,stroke-width:2px,color:#ffffff
+
+ class Client client
+ class MultiProvider controller
+ class FailoverStrategy,Priority,RoundRobin strategy
+ class P1,P2,P3,P4 provider
+ class CardanoNetwork network
+```
+
+The system provides immediate failover on provider errors while preserving comprehensive error context for debugging and maintains strategy-specific state for consistent provider selection patterns.
+
+## Functional Specification (Normative)
+
+The following requirements are specified using RFC 2119/8174 keywords: MUST (absolute requirement), SHOULD (recommended), MAY (optional).
+
+### 1. Failover strategies
+
+**1.1**: Priority strategy **MUST** attempt providers in strict priority order (lowest priority number first).
+
+**1.2**: Applications **SHOULD** use priority strategy when providers have different cost, reliability, or feature characteristics.
+
+**1.3**: Priority configuration **MUST** assign unique priority numbers to avoid ambiguous ordering.
+
+**1.4**: Round-robin strategy **MUST** distribute requests evenly across all configured providers.
+
+**1.5**: Applications **SHOULD** use round-robin strategy for load balancing when all providers have equivalent capabilities.
+
+**1.6**: Round-robin **MAY** be preferred in high-throughput scenarios to prevent provider overload.
+
+**1.7**: Priority strategy **MUST** support arbitrary priority ordering with numerical priority values.
+
+**1.8**: Round-robin strategy **MUST** maintain equal distribution across all providers over time.
+
+**1.9**: Strategy selection **MUST** be determined at MultiProvider construction time and remain immutable.
+
+### 2. Request flow and failover orchestration
+
+**2.1**: MultiProvider **MUST** attempt immediate failover when a provider returns a `ProviderError`.
+
+**2.2**: Individual providers **SHOULD** handle internal retries before returning errors to MultiProvider.
+
+**2.3**: Error accumulation **MUST** preserve all provider failure details for debugging purposes.
+
+**2.4**: MultiProviderError **MUST** contain details from all failed provider attempts.
+
+**2.5**: Error timestamps **SHOULD** enable debugging of timing-related issues.
+
+**2.6**: Applications **MAY** use provider error details to implement custom recovery logic.
+
+**2.7**: Retry policies **MUST** be configured at provider construction time and remain immutable.
+
+**2.8**: Applications **SHOULD** tune retry policies based on provider characteristics and SLA requirements.
+
+### 3. Interface contracts and integration
+
+**3.1**: MultiProvider **MUST** implement the complete Provider interface while managing multiple underlying providers.
+
+**3.2**: MultiProvider **MUST** maintain immutable configuration after construction.
+
+**3.3**: MultiProvider state transitions **MUST** be thread-safe and deterministic.
+
+**3.4**: All providers **MUST** implement consistent error handling with `ProviderError` types.
+
+**3.5**: Provider methods **MUST** complete internal retries before returning to MultiProvider.
+
+**3.6**: Providers **SHOULD** implement Effect-based APIs with Promise adapters for compatibility.
+
+**3.7**: FailoverStrategy implementations **MUST** be deterministic for identical input sequences.
+
+**3.8**: Strategy state mutations **MUST** be isolated per MultiProvider instance.
+
+**3.9**: Strategy selection algorithms **MUST** complete in O(1) time complexity.
+
+### 4. Performance and reliability constraints
+
+**4.1**: Failover operations **MUST** complete within 100ms excluding network operations.
+
+**4.2**: Strategy selection **MUST** not block concurrent requests to different MultiProvider instances.
+
+**4.3**: Memory usage **SHOULD** remain constant regardless of error accumulation count.
+
+**4.4**: Provider configurations **MUST** be validated at construction time, not runtime.
+
+### 5. Error handling and classification
+
+**5.1**: MultiProviderError **MUST** distinguish between network failures, authentication failures, and provider unavailability.
+
+**5.2**: Error propagation **MUST** preserve original error context while adding failover metadata.
+
+**5.3**: System **MUST** continue failover attempts until all providers exhausted, regardless of error types.
+
+## Appendix (Informative) {#appendix}
+
+### A.1. Strategy Configuration Workflows
+
+```mermaid
+graph TD
+ MultiProvider[MultiProvider Construction] --> StrategyType{Strategy Type}
+ StrategyType -->|Priority| PriorityReqs[Priority Strategy Requirements:
- Numerical priority ordering
- Strict precedence rules
- Deterministic selection]
+ StrategyType -->|RoundRobin| RoundRobinReqs[Round-Robin Strategy Requirements:
- Equal distribution guarantee
- Cyclic provider iteration
- Stateful index management]
+
+ PriorityReqs --> Validation[Configuration Validation:
- Unique priorities
- Valid provider configs
- Retry policy compliance]
+ RoundRobinReqs --> Validation
+
+ classDef system fill:#3b82f6,stroke:#1e40af,stroke-width:2px,color:#ffffff
+ classDef requirements fill:#10b981,stroke:#065f46,stroke-width:2px,color:#ffffff
+ classDef validation fill:#f59e0b,stroke:#d97706,stroke-width:2px,color:#ffffff
+
+ class MultiProvider system
+ class StrategyType,PriorityReqs,RoundRobinReqs requirements
+ class Validation validation
+```
+
+### A.2. Priority Strategy Flow
+
+```mermaid
+graph TD
+ Start([Request]) --> P1{Try Priority 1 Provider}
+ P1 -->|Success| Success1[Return Result]
+ P1 -->|ProviderError| P2{Try Priority 2 Provider}
+ P2 -->|Success| Success2[Return Result]
+ P2 -->|ProviderError| P3{Try Priority 3 Provider}
+ P3 -->|Success| Success3[Return Result]
+ P3 -->|ProviderError| Error[All Providers Failed - MultiProviderError]
+
+ classDef success fill:#10b981,stroke:#065f46,stroke-width:2px,color:#ffffff
+ classDef failure fill:#ef4444,stroke:#b91c1c,stroke-width:2px,color:#ffffff
+ classDef process fill:#3b82f6,stroke:#1e40af,stroke-width:2px,color:#ffffff
+
+ class Success1,Success2,Success3 success
+ class Error failure
+ class Start,P1,P2,P3 process
+```
+
+### A.3. Round Robin Strategy Flow
+
+```mermaid
+graph TD
+ Start([Request]) --> Check{Current Index}
+ Check -->|Index 0| P1{Try Provider 1}
+ Check -->|Index 1| P2{Try Provider 2}
+ Check -->|Index 2| P3{Try Provider 3}
+
+ P1 -->|Success| Success1[Return Result
Next: Index 1]
+ P1 -->|ProviderError| Acc1[Accumulate Error
Try Provider 2]
+ Acc1 --> P2
+
+ P2 -->|Success| Success2[Return Result
Next: Index 2]
+ P2 -->|ProviderError| Acc2[Accumulate Error
Try Provider 3]
+ Acc2 --> P3
+
+ P3 -->|Success| Success3[Return Result
Next: Index 0]
+ P3 -->|ProviderError| Error[All Providers Failed
MultiProviderError]
+
+ classDef success fill:#10b981,stroke:#065f46,stroke-width:2px,color:#ffffff
+ classDef failure fill:#ef4444,stroke:#b91c1c,stroke-width:2px,color:#ffffff
+ classDef process fill:#3b82f6,stroke:#1e40af,stroke-width:2px,color:#ffffff
+ classDef decision fill:#f59e0b,stroke:#d97706,stroke-width:2px,color:#ffffff
+
+ class Success1,Success2,Success3 success
+ class Error,Acc1,Acc2 failure
+ class Start process
+ class Check,P1,P2,P3 decision
+```
+
+### A.4. High-Level Request Flow
+
+```mermaid
+graph TD
+ Start([Client Request]) --> Select[Select Provider by Strategy]
+ Select --> Invoke[Call Provider Method]
+ Invoke --> Success{Success?}
+ Success -->|Yes| Return[Return Result]
+ Success -->|No ProviderError| Accumulate[Add Error to Accumulated Errors]
+ Accumulate --> CheckNext{More Providers Available?}
+ CheckNext -->|Yes| NextProvider[Select Next Provider]
+ CheckNext -->|No| ThrowMulti[Throw MultiProviderError with All Errors]
+ NextProvider --> Invoke
+
+ classDef success fill:#10b981,stroke:#065f46,stroke-width:2px,color:#ffffff
+ classDef failure fill:#ef4444,stroke:#b91c1c,stroke-width:2px,color:#ffffff
+ classDef process fill:#3b82f6,stroke:#1e40af,stroke-width:2px,color:#ffffff
+ classDef decision fill:#f59e0b,stroke:#d97706,stroke-width:2px,color:#ffffff
+
+ class Return success
+ class Accumulate,ThrowMulti failure
+ class Start,Select,Invoke,NextProvider process
+ class Success,CheckNext decision
+```
+
+### A.5. Provider Ecosystem Matrix
+
+| Provider | Network Support | API Key Required | Pagination | Cost Model | Reliability Notes |
+|----------|-----------------|------------------|------------|------------|------------------|
+| **Blockfrost** | Mainnet, Preprod, Preview | ✅ | Cursor-based | Freemium | High SLA on paid tiers |
+| **Kupmios** | Mainnet, Preprod, Preview | ❌ (self-hosted) | Offset-based | Free | Variable, depends on host |
+| **Maestro** | Mainnet, Preprod | ✅ | Cursor-based | Subscription | Enterprise-grade |
+| **Koios** | Mainnet, Preprod, Preview | Optional | Offset-based | Donation-based | Community-maintained |
+
+### A.6. Interface Definitions
+
+```typescript
+interface PriorityStrategy {
+ type: "priority"
+ providers: Array<{
+ provider: ProviderConfig
+ priority: number // Lower number = higher priority (1 = highest)
+ }>
+}
+
+interface RoundRobinStrategy {
+ type: "round-robin"
+ providers: Array
+}
+
+interface MultiProviderContract extends Provider {
+ readonly getCurrentProviderIndex: () => number
+ readonly getFailoverStrategy: () => FailoverStrategy
+ readonly getProviderConfigurations: () => ReadonlyArray
+}
+
+interface FailoverStrategyContract {
+ readonly selectProvider: (
+ providers: ReadonlyArray,
+ currentIndex: number,
+ previousErrors: ReadonlyArray
+ ) => number
+
+ readonly updateState: (
+ selectedIndex: number,
+ result: Either
+ ) => FailoverStrategyState
+}
+
+interface RetryConfig {
+ maxRetries: number // Configured at provider construction time
+ retryDelayMs: number // Base delay between retries
+ backoffMultiplier: number // Exponential backoff multiplier
+ maxRetryDelayMs: number // Maximum delay cap
+}
+```
+
+### A.7. System Responsibilities Matrix
+
+| Component | Responsibilities |
+|-----------|------------------|
+| **MultiProvider** | Provider selection and failover orchestration; Error accumulation and MultiProviderError construction; Strategy state management and coordination; Request routing and response aggregation |
+| **Provider** | Internal retry logic and backoff handling; Network communication and protocol implementation; Provider-specific error classification and reporting; Resource management and connection pooling |
+| **Strategy** | Provider selection algorithm implementation; Internal state management for selection logic; Deterministic behavior for identical input sequences |
+
+### A.8. Key Abstractions
+
+**Provider failover** is an automatic mechanism that switches between multiple blockchain data providers when one becomes unavailable or returns errors. Think of it as having multiple routes to the same destination - if one route is blocked, you automatically take an alternative path.
+
+**MultiProvider**: A controller that manages multiple individual providers and orchestrates failover logic. It presents a single interface while internally handling provider selection and error recovery.
+
+**Failover Strategy**: The algorithm that determines which provider to try next when the current one fails. Each strategy optimizes for different goals:
+- **Priority Strategy**: Optimizes for provider preference (cost, reliability, features)
+- **Round-Robin Strategy**: Optimizes for load distribution across providers
+
+**Retry vs Failover**:
+- **Retry**: Attempting the same request on the same provider multiple times with delays
+- **Failover**: Switching to a different provider immediately when the current one fails
+
+### A.9. Essential Workflows
+
+**Request Lifecycle**: Request → Provider Selection → Execution → Success/Error → (Failover if needed) → Final Result
+
+**Error Accumulation**: When providers fail, their errors are collected rather than discarded, providing complete debugging information in the final `MultiProviderError`.
+
+**State Management**: Each strategy maintains internal state (current provider index) that evolves with each request, enabling consistent provider selection patterns.
+
+### A.10. Implementation Architecture Notes
+
+**State Management**: MultiProvider maintains internal provider state and selection logic. See `MultiProvider` implementation in `src/sdk/provider/MultiProvider.ts` for complete interface definitions.
+
+**Provider Configuration**: Each provider is configured with retry policies at construction time. Provider configurations are immutable after creation. See `ProviderConfig` and related types in `src/sdk/provider/Provider.ts`.
+
+**Error Accumulation**: Failed provider attempts are accumulated with timestamps and retry counts, enabling comprehensive debugging information. See `MultiProviderError` and error types in `src/sdk/provider/MultiProvider.ts`.
+
+**Failover Logic**: The system uses immediate failover on `ProviderError` - no additional retry logic at the MultiProvider level. Individual providers handle internal retries using Effect.retry patterns.
+
+### A.11. Error Recovery Patterns
+
+**Immediate Failover**: Configure `maxRetries: 0` for fast switching between providers without individual retry delays.
+
+**Retry with Backoff**: Configure exponential backoff parameters for providers that may have transient failures. See `RetryConfig` interface in `src/sdk/provider/Provider.ts` for configuration options.
+
+**Network Error Handling**: System continues failover on connectivity issues without modification to retry policies.
+
+**Authentication Error Handling**: Provider authentication failures trigger immediate failover without retries on that specific provider.
+
+**Rate Limiting Behavior**: Provider rate limit responses trigger failover and mark provider temporarily unavailable per retry policy configuration.
+
diff --git a/.specs/transaction-build-process-specification.md b/.specs/transaction-build-process-specification.md
new file mode 100644
index 00000000..4e33d839
--- /dev/null
+++ b/.specs/transaction-build-process-specification.md
@@ -0,0 +1,1163 @@
+# Transaction Build Process Specification
+
+**Version**: 1.0.0
+**Status**: DRAFT
+**Created**: September 24, 2025
+**Authors**: Evolution SDK Team
+**Reviewers**: [To be assigned]
+
+---
+
+## Abstract
+
+This specification defines the comprehensive transaction build process for the Evolution SDK, establishing the normative requirements for constructing valid Cardano transactions. The build process implements a sophisticated multi-phase workflow that coordinates UTxO selection, script evaluation, fee calculation, collateral management, and transaction assembly. Key innovations include iterative coin selection with script cost integration, dual UPLC/provider evaluation strategies, automatic collateral selection, and comprehensive error recovery mechanisms. The specification ensures deterministic transaction construction while maintaining flexibility for complex use cases including multi-signature workflows, script interactions, and transaction chaining.
+
+---
+
+## Purpose and Scope
+
+This specification establishes the authoritative requirements for transaction building within the Evolution SDK ecosystem. It serves as the definitive reference for implementers of the build process and provides behavioral contracts for developers using the transaction building system.
+
+**Target Audience**: Core SDK maintainers, transaction builder implementers, DApp developers integrating with the build system, and auditors reviewing transaction construction logic.
+
+**Scope**: This specification covers the complete transaction build workflow from intent accumulation through final transaction assembly. It includes coin selection algorithms, script evaluation protocols, fee calculation methods, collateral management, UTxO state transitions, and error handling strategies. It does not cover wallet-specific signing processes, network submission protocols, or provider-specific data access patterns.
+
+---
+
+## Introduction
+
+Transaction building in Cardano requires sophisticated coordination between multiple subsystems to produce valid, optimized transactions. The Evolution SDK build process addresses the inherent complexity through a carefully orchestrated multi-phase approach that ensures correctness while maintaining performance and usability.
+
+### Fundamental Challenges Addressed
+
+1. **Chicken-and-Egg Problem**: Script evaluation requires a complete transaction, but building a transaction requires knowing script execution costs
+2. **UTxO Selection Optimization**: Selecting optimal UTxO sets while satisfying minimum ADA requirements and protocol constraints
+3. **Fee Calculation Complexity**: Accurately estimating fees across base transaction costs, script execution costs, and reference script fees
+4. **Script Evaluation Integration**: Supporting both local WASM evaluation and external provider evaluation with consistent results
+5. **State Management**: Maintaining consistent state across multiple build phases with proper error recovery
+
+### Design Philosophy
+
+The build process follows these core principles:
+
+1. **Deterministic Construction**: Given identical inputs, the build process produces identical transactions
+2. **Progressive Refinement**: Start with estimates, refine through evaluation, converge on optimal solution
+3. **Fail-Fast Validation**: Detect and report errors as early as possible in the build process
+4. **Resource Efficiency**: Minimize computational overhead while ensuring correctness
+5. **Composable Architecture**: Enable complex workflows through well-defined phase boundaries
+
+### Integration Context
+
+The build process integrates with the Evolution SDK architecture through:
+- **Intent Accumulation**: Collects transaction operations from the fluent API
+- **UTxO Management**: Coordinates with wallet and provider systems for UTxO access
+- **Script System**: Manages Plutus script evaluation and witness generation
+- **Fee System**: Calculates comprehensive fee estimates including all cost components
+- **Error System**: Provides detailed error information with recovery guidance
+
+### Transaction Build Process Workflow
+
+```mermaid
+graph TD
+ A[Start: Build Process] --> B[Phase 1: Setup & Validation]
+
+ B --> B1[Validate Build Options]
+ B --> B2[Fetch Wallet UTxOs]
+ B --> B3[Derive Change Address]
+ B --> B4[Initialize Build State]
+
+ B1 --> C[Phase 2: Intent Execution]
+ B2 --> C
+ B3 --> C
+ B4 --> C
+
+ C --> C1[Process Payment Intents]
+ C1 --> C2[Process Input Collection]
+ C2 --> C3[Process Minting Operations]
+ C3 --> C4[Calculate Asset Delta
Outputs + Fee - Inputs - Minted]
+ C4 --> C5[Detect Script Usage]
+
+ C5 --> D[Phase 3: Initial Coin Selection]
+
+ D --> D1[Apply Coin Selection Algorithm
Largest-First / Random-Improve / Custom]
+ D1 --> D2[Recursive UTxO Selection]
+ D2 --> D3[Handle Minimum ADA Requirements]
+ D3 --> D4{Selection
Successful?}
+
+ D4 -->|No| D5[Insufficient Funds Error]
+ D4 -->|Yes| E{Has Plutus
Scripts?}
+
+ E -->|No| I[Phase 5: Skip Script Evaluation]
+ E -->|Yes| F[Phase 4: Script Evaluation]
+
+ F --> F1[Build Evaluation Transaction
Dummy ExUnits & Invalid Hash]
+ F1 --> F2{Evaluation
Strategy?}
+
+ F2 -->|WASM| F3[Local UPLC Evaluation]
+ F2 -->|Provider| F4[External Provider Evaluation]
+
+ F3 --> F5[Apply UPLC Results
Update ExUnits & Script Hash]
+ F4 --> F5
+
+ F5 --> G[Phase 5: Refined Resource Management]
+
+ G --> G1[Recalculate Fee with Script Costs]
+ G1 --> G2[Check Current UTxO Coverage]
+ G2 --> G3{Need Additional
UTxOs?}
+
+ G3 -->|Yes| G4[Select Additional UTxOs]
+ G3 -->|No| G7[Calculate Collateral Requirements]
+
+ G4 --> G5{Script Budget
Changed?}
+ G5 -->|Yes| G6[Re-evaluate Scripts]
+ G5 -->|No| G7
+
+ G6 --> F1
+
+ G7 --> G8[Select Collateral UTxOs
ADA-only, Max 3]
+ G8 --> G9[Apply Collateral to Transaction]
+
+ G9 --> H[Phase 6: Transaction Assembly]
+
+ H --> H1[Complete Partial Programs]
+ H1 --> H2[Build Redeemers with Correct Indices]
+ H2 --> H3[Calculate Final Fee & Change]
+ H3 --> H4[Construct Transaction Body]
+ H4 --> H5[Build Witness Set Structure]
+ H5 --> H6[Final Validation
Size, Balance, Protocol]
+
+ H6 --> J[Return SignBuilder]
+
+ I --> G7
+
+ D5 --> K[Build Error]
+ F5 --> L{Evaluation
Failed?}
+ L -->|Yes| K
+ L -->|No| G
+
+ G8 --> M{Collateral
Available?}
+ M -->|No| K
+ M -->|Yes| G9
+
+ H6 --> N{Validation
Passed?}
+ N -->|No| K
+ N -->|Yes| J
+
+ style A fill:#4a90e2,color:#ffffff,stroke:#2171b5,stroke-width:3px
+ style B fill:#9b59b6,color:#ffffff,stroke:#8e44ad,stroke-width:3px
+ style C fill:#27ae60,color:#ffffff,stroke:#229954,stroke-width:3px
+ style D fill:#f39c12,color:#ffffff,stroke:#e67e22,stroke-width:3px
+ style E fill:#f1c40f,color:#2c3e50,stroke:#f39c12,stroke-width:3px
+ style F fill:#e74c3c,color:#ffffff,stroke:#c0392b,stroke-width:3px
+ style G fill:#1abc9c,color:#ffffff,stroke:#16a085,stroke-width:3px
+ style H fill:#34495e,color:#ffffff,stroke:#2c3e50,stroke-width:3px
+ style I fill:#95a5a6,color:#ffffff,stroke:#7f8c8d,stroke-width:3px
+ style J fill:#2ecc71,color:#ffffff,stroke:#27ae60,stroke-width:4px
+ style K fill:#e74c3c,color:#ffffff,stroke:#c0392b,stroke-width:4px
+
+ classDef phaseBox fill:#ecf0f1,stroke:#34495e,stroke-width:3px,color:#2c3e50
+ classDef decision fill:#fff3cd,stroke:#856404,stroke-width:3px,color:#856404
+ classDef error fill:#f8d7da,stroke:#721c24,stroke-width:3px,color:#721c24
+ classDef success fill:#d4edda,stroke:#155724,stroke-width:3px,color:#155724
+
+ class B,C,D,F,G,H,I phaseBox
+ class E,D4,F2,G3,G5,L,M,N decision
+ class D5,K error
+ class J success
+```
+
+### Build Process State Flow
+
+```mermaid
+stateDiagram-v2
+ [*] --> Setup: Start Build
+
+ Setup --> Validation: Validate Options
+ Validation --> UTxOFetch: Fetch UTxOs
+ UTxOFetch --> IntentExec: Process Intents
+
+ IntentExec --> CoinSelection: Calculate Requirements
+ CoinSelection --> ScriptCheck: UTxOs Selected
+
+ ScriptCheck --> ScriptEval: Has Scripts
+ ScriptCheck --> ResourceMgmt: No Scripts
+
+ ScriptEval --> WasmEval: Local UPLC
+ ScriptEval --> ProviderEval: Remote Provider
+
+ WasmEval --> ApplyResults: UPLC Complete
+ ProviderEval --> ApplyResults: Provider Response
+
+ ApplyResults --> ResourceMgmt: ExUnits Applied
+
+ ResourceMgmt --> RefinedSelection: Recalculate Costs
+ RefinedSelection --> CollateralCheck: Check Coverage
+ RefinedSelection --> ReEvaluate: Need More UTxOs
+
+ ReEvaluate --> ScriptEval: Budget Changed
+ ReEvaluate --> CollateralCheck: Selection Stable
+
+ CollateralCheck --> Assembly: Collateral Set
+
+ Assembly --> RedeemerBuild: Build Components
+ RedeemerBuild --> FinalValidation: Complete Assembly
+
+ FinalValidation --> [*]: SignBuilder Ready
+
+ Setup --> [*]: Configuration Error
+ UTxOFetch --> [*]: Wallet Error
+ CoinSelection --> [*]: Insufficient Funds
+ ScriptEval --> [*]: Evaluation Error
+ CollateralCheck --> [*]: Collateral Error
+ FinalValidation --> [*]: Validation Error
+```
+
+---
+
+## Functional Specification
+
+### Build Process Architecture (Normative)
+
+The transaction build process SHALL implement a six-phase workflow with well-defined phase boundaries, state transitions, and error handling protocols.
+
+#### Phase Overview
+
+The build process MUST execute the following phases in order:
+
+1. **Setup and Validation Phase**: Initialize build environment and validate configuration
+2. **Intent Execution Phase**: Process accumulated transaction intents into concrete requirements
+3. **Initial Coin Selection Phase**: Select UTxOs without script execution costs
+4. **Script Evaluation Phase**: Determine script execution costs and apply to transaction
+5. **Refined Resource Management Phase**: Adjust coin selection and collateral for final costs
+6. **Transaction Assembly Phase**: Construct final transaction with all components
+
+Each phase MUST complete successfully before proceeding to the next phase. Phase failures MUST trigger appropriate error handling with detailed diagnostics.
+
+### Phase 1: Setup and Validation (Normative)
+
+#### Purpose
+Initialize the build environment, validate configuration parameters, and establish the foundation for transaction construction.
+
+#### Required Operations
+
+The setup phase MUST perform the following operations:
+
+1. **Configuration Validation**:
+ ```typescript
+ // Validate build options
+ if (options.coinSelection && typeof options.coinSelection === 'object') {
+ validateCoinSelectionOptions(options.coinSelection)
+ }
+
+ if (options.collateral && options.collateral.length > 3) {
+ throw new BuildError("Collateral inputs cannot exceed 3 UTxOs")
+ }
+
+ if (options.uplcEval?.type === "wasm" && !options.uplcEval.wasmModule) {
+ throw new BuildError("WASM module required for WASM UPLC evaluation")
+ }
+ ```
+
+2. **UTxO Set Acquisition**:
+ ```typescript
+ // Automatic UTxO fetching if not provided
+ const availableUtxos = providedUtxos ?? await wallet.getUtxos()
+
+ // Filter out UTxOs with reference scripts (excluded from coin selection)
+ const coinSelectionUtxos = availableUtxos.filter(utxo =>
+ !hasReferenceScript(utxo)
+ )
+
+ if (coinSelectionUtxos.length === 0) {
+ throw new BuildError("No UTxOs available for coin selection")
+ }
+ ```
+
+3. **Address Resolution**:
+ ```typescript
+ // Derive change address
+ const changeAddress = options.changeAddress ??
+ await wallet.getChangeAddress() ??
+ await wallet.getAddress()
+
+ // Validate address format and network compatibility
+ validateAddressNetwork(changeAddress, network)
+ ```
+
+4. **State Initialization**:
+ ```typescript
+ interface BuildState {
+ availableUtxos: UTxO[]
+ changeAddress: Address
+ selectedUtxos: UTxO[]
+ requiredAssets: Assets
+ estimatedFee: Coin
+ hasScripts: boolean
+ scriptEvaluationResults?: EvaluationResults
+ collateralUtxos?: UTxO[]
+ }
+ ```
+
+#### Error Conditions
+
+The setup phase MUST fail with specific error types for the following conditions:
+- Invalid build options configuration
+- Wallet access failures
+- Network compatibility errors
+- Insufficient UTxO availability
+
+### Phase 2: Intent Execution (Normative)
+
+#### Purpose
+Process all accumulated transaction intents into concrete transaction requirements including outputs, inputs, minting operations, and metadata.
+
+#### Required Processing
+
+The intent execution phase MUST process intents in the following order:
+
+1. **Output Requirements Calculation**:
+ ```typescript
+ // Process all payToAddress intents
+ const outputRequirements = intents
+ .filter(intent => intent.type === 'payToAddress')
+ .reduce((total, intent) => mergeAssets(total, intent.assets), emptyAssets())
+
+ // Add minimum ADA requirements for each output
+ const outputsWithMinAda = outputs.map(output =>
+ ensureMinimumAda(output, protocolParameters.coinsPerUtxoByte)
+ )
+ ```
+
+2. **Input Commitments Processing**:
+ ```typescript
+ // Process collectFrom intents
+ const explicitInputs = intents
+ .filter(intent => intent.type === 'collectFrom')
+ .flatMap(intent => intent.inputs)
+
+ // Calculate assets provided by explicit inputs
+ const explicitInputAssets = sumAssetsFromInputs(explicitInputs)
+ ```
+
+3. **Minting/Burning Operations**:
+ ```typescript
+ // Process mint/burn intents
+ const mintingOperations = intents
+ .filter(intent => intent.type === 'mintTokens' || intent.type === 'burnTokens')
+
+ // Calculate net asset changes from minting/burning
+ const netMintedAssets = calculateNetMinting(mintingOperations)
+ ```
+
+4. **Script Detection**:
+ ```typescript
+ // Detect Plutus script usage
+ const hasPlutusScripts = intents.some(intent =>
+ intent.type === 'spendFromScript' ||
+ (intent.type === 'mintTokens' && intent.redeemer) ||
+ (intent.type === 'payToScript')
+ )
+ ```
+
+#### Asset Delta Calculation
+
+The phase MUST calculate the net asset requirements using the formula:
+
+```
+Required Assets = Outputs + Estimated Fee - Explicit Inputs - Net Minted Assets
+```
+
+Where:
+- **Outputs**: Total assets required by all transaction outputs
+- **Estimated Fee**: Initial fee estimate without script costs
+- **Explicit Inputs**: Assets provided by explicitly specified inputs
+- **Net Minted Assets**: Net assets created through minting minus burning
+
+#### Validation Requirements
+
+The intent execution phase MUST validate:
+- All required parameters are present for each intent type
+- Asset amounts are non-negative and within protocol limits
+- Script references are valid and accessible
+- Metadata conforms to protocol standards
+
+### Phase 3: Initial Coin Selection (Normative)
+
+#### Purpose
+Select UTxOs to satisfy transaction requirements without considering script execution costs. This provides the foundation for script evaluation in subsequent phases.
+
+#### Coin Selection Algorithm Requirements
+
+The coin selection implementation MUST support the following algorithms:
+
+1. **Largest-First Algorithm**:
+ ```typescript
+ interface LargestFirstStrategy {
+ // Sort UTxOs by total value in descending order
+ sortBy: (utxo: UTxO) => bigint // Total ADA value
+
+ // Select UTxOs until requirements met
+ selectUntil: (accumulated: Assets, required: Assets) => boolean
+
+ // Handle multi-asset requirements
+ assetPriority: "ada" | "required" // Prioritize ADA or required assets
+ }
+ ```
+
+2. **Random-Improve Algorithm**:
+ ```typescript
+ interface RandomImproveStrategy {
+ // Initial random selection
+ initialSelection: (utxos: UTxO[], required: Assets) => UTxO[]
+
+ // Improvement iterations
+ maxIterations: number // Default: 20
+
+ // Improvement criteria
+ improvementThreshold: number // Minimum improvement to accept change
+ }
+ ```
+
+3. **Custom Selection Function**:
+ ```typescript
+ type CoinSelectionFunction = (
+ availableUtxos: ReadonlyArray,
+ requiredAssets: Assets,
+ options: CoinSelectionOptions
+ ) => Effect
+ ```
+
+#### Recursive Selection Protocol
+
+The coin selection MUST implement recursive selection to handle minimum ADA requirements:
+
+```typescript
+interface RecursiveSelectionProtocol {
+ // Phase 1: Select for required assets
+ initialSelection(required: Assets): UTxO[]
+
+ // Phase 2: Calculate minimum ADA for change
+ calculateMinimumAda(changeAssets: Assets): Coin
+
+ // Phase 3: Select additional UTxOs if needed
+ selectForMinimumAda(additionalRequired: Coin): UTxO[]
+
+ // Phase 4: Iterate until stable
+ iterateUntilStable(): CoinSelectionResult
+}
+```
+
+#### Selection Criteria
+
+The coin selection algorithm MUST apply the following filtering criteria:
+
+1. **Reference Script Exclusion**:
+ ```typescript
+ const eligibleUtxos = availableUtxos.filter(utxo =>
+ !hasReferenceScript(utxo)
+ )
+ ```
+
+2. **Asset Availability Filtering**:
+ ```typescript
+ const relevantUtxos = eligibleUtxos.filter(utxo =>
+ hasRequiredAssets(utxo, requiredAssets) ||
+ hasAda(utxo) // Always include ADA-bearing UTxOs
+ )
+ ```
+
+3. **Maximum Input Limit**:
+ ```typescript
+ if (selectedUtxos.length > (options.maxInputs ?? 50)) {
+ throw new CoinSelectionError("Maximum input limit exceeded")
+ }
+ ```
+
+#### Minimum ADA Calculation
+
+The coin selection MUST implement accurate minimum ADA calculation:
+
+```typescript
+const calculateMinimumAda = (
+ assets: Assets,
+ coinsPerUtxoByte: bigint,
+ hasScriptRef?: boolean
+): Coin => {
+ // Create temporary output to calculate size
+ const tempOutput = createTransactionOutput({
+ address: dummyAddress,
+ assets,
+ scriptRef: hasScriptRef ? dummyScriptRef : undefined
+ })
+
+ // Calculate CBOR size
+ const cborSize = calculateCborSize(tempOutput)
+
+ // Apply minimum ADA formula
+ return coinsPerUtxoByte * BigInt(cborSize)
+}
+```
+
+### Phase 4: Script Evaluation (Normative)
+
+#### Purpose
+Evaluate Plutus scripts to determine execution units and associated costs, enabling accurate fee calculation and refined coin selection.
+
+#### Two-Phase Script Evaluation Protocol
+
+The script evaluation MUST implement a two-phase protocol to handle the chicken-and-egg problem:
+
+#### Phase 4A: Evaluation Transaction Construction
+
+```typescript
+interface EvaluationTransactionRequirements {
+ // MUST create transaction with dummy ExUnits
+ createWithDummyExUnits(): Transaction
+
+ // MUST set invalid script_data_hash to prevent submission
+ setDummyScriptDataHash(): void
+
+ // MUST include all transaction components for evaluation
+ includeAllComponents(): void
+
+ // MUST be suitable for script evaluation but invalid for submission
+ ensureEvaluationOnly(): boolean
+}
+```
+
+The evaluation transaction construction MUST:
+1. Use placeholder ExUnits for all redeemers: `{ cpu: 0, memory: 0 }`
+2. Set `script_data_hash` to all zeros to invalidate submission
+3. Include all inputs, outputs, and redeemers required for evaluation
+4. Calculate temporary fee estimate for transaction size
+
+#### Phase 4B: Script Execution and Results Application
+
+The script evaluation MUST support dual evaluation strategies:
+
+1. **WASM UPLC Evaluation**:
+ ```typescript
+ interface WasmUplcEvaluation {
+ // Execute scripts locally using WASM UPLC interpreter
+ evaluate(
+ transaction: Transaction,
+ wasmModule: UplcWasmModule,
+ timeout?: number
+ ): Promise
+
+ // Apply results to transaction builder
+ applyResults(results: UplcEvaluationResult[]): void
+ }
+ ```
+
+2. **Provider Evaluation**:
+ ```typescript
+ interface ProviderEvaluation {
+ // Submit to external provider for evaluation
+ evaluate(
+ transaction: Transaction,
+ additionalUtxos?: UTxO[]
+ ): Promise
+
+ // Apply structured results
+ applyResults(results: ProviderEvaluationResult): void
+ }
+ ```
+
+#### Evaluation Result Processing
+
+The evaluation results MUST be processed according to the following protocol:
+
+```typescript
+interface EvaluationResultProcessing {
+ // Validate evaluation results
+ validateResults(results: EvaluationResult[]): void
+
+ // Apply ExUnits to corresponding redeemers
+ applyExUnitsToRedeemers(results: EvaluationResult[]): void
+
+ // Calculate script execution costs
+ calculateScriptCosts(results: EvaluationResult[]): Coin
+
+ // Update transaction with real ExUnits
+ updateTransactionExUnits(): void
+
+ // Recalculate script_data_hash
+ recalculateScriptDataHash(): ScriptDataHash
+}
+```
+
+#### Error Recovery Protocol
+
+Script evaluation failures MUST be handled according to the following protocol:
+
+1. **Evaluation Timeout**: Retry with increased timeout or fallback to provider
+2. **Script Failure**: Provide detailed error with script context and input data
+3. **Provider Unavailable**: Fallback to local evaluation if WASM module available
+4. **Invalid Results**: Validate ExUnits are within protocol limits
+
+### Phase 5: Refined Resource Management (Normative)
+
+#### Purpose
+Adjust coin selection and resource allocation based on actual script execution costs and finalize collateral requirements.
+
+#### Refined Coin Selection Protocol
+
+After script evaluation, the build process MUST perform refined coin selection:
+
+```typescript
+interface RefinedCoinSelectionProtocol {
+ // Recalculate total fee with script costs
+ calculateFinalFee(
+ baseFee: Coin,
+ scriptCosts: Coin,
+ referenceScriptFees: Coin
+ ): Coin
+
+ // Check if current UTxOs cover final costs
+ validateCurrentSelection(
+ selectedUtxos: UTxO[],
+ finalRequirements: Assets
+ ): boolean
+
+ // Select additional UTxOs if needed
+ selectAdditionalUtxos(
+ remainingUtxos: UTxO[],
+ additionalRequired: Assets
+ ): UTxO[]
+
+ // Validate final selection stability
+ validateSelectionStability(): boolean
+}
+```
+
+#### Script Budget Recalculation
+
+The refined selection MUST handle script budget changes:
+
+```typescript
+interface ScriptBudgetManagement {
+ // Detect if new inputs affect script execution
+ detectBudgetChanges(
+ originalInputs: UTxO[],
+ newInputs: UTxO[]
+ ): boolean
+
+ // Re-evaluate scripts if significant changes
+ requiresReEvaluation(budgetChange: BudgetChange): boolean
+
+ // Implement re-evaluation protocol
+ reEvaluateScripts(
+ newInputSet: UTxO[]
+ ): Promise
+}
+```
+
+#### Collateral Selection Protocol
+
+For transactions with Plutus scripts, the build process MUST implement collateral selection:
+
+```typescript
+interface CollateralSelectionProtocol {
+ // Calculate required collateral amount
+ calculateCollateralAmount(
+ estimatedFee: Coin,
+ collateralPercentage: number,
+ minimumCollateral?: Coin
+ ): Coin
+
+ // Select suitable collateral UTxOs
+ selectCollateralUtxos(
+ availableUtxos: UTxO[],
+ requiredAmount: Coin
+ ): UTxO[]
+
+ // Validate collateral requirements
+ validateCollateral(
+ collateralUtxos: UTxO[],
+ requirements: CollateralRequirements
+ ): boolean
+}
+```
+
+#### Collateral Selection Criteria
+
+Collateral UTxOs MUST meet the following requirements:
+
+1. **ADA-Only Constraint**:
+ ```typescript
+ const isAdaOnly = (utxo: UTxO): boolean =>
+ Object.keys(utxo.output.amount).length === 1 &&
+ utxo.output.amount.lovelace > 0n
+ ```
+
+2. **No Reference Scripts**:
+ ```typescript
+ const hasNoReferenceScript = (utxo: UTxO): boolean =>
+ !utxo.output.scriptRef
+ ```
+
+3. **Maximum Count Limit**:
+ ```typescript
+ if (collateralUtxos.length > 3) {
+ throw new BuildError("Collateral cannot exceed 3 UTxOs")
+ }
+ ```
+
+4. **Sufficient Value**:
+ ```typescript
+ const totalCollateralValue = collateralUtxos.reduce(
+ (sum, utxo) => sum + utxo.output.amount.lovelace, 0n
+ )
+
+ if (totalCollateralValue < requiredCollateralAmount) {
+ throw new BuildError("Insufficient collateral value")
+ }
+ ```
+
+### Phase 6: Transaction Assembly (Normative)
+
+#### Purpose
+Construct the final transaction with all components including inputs, outputs, witnesses, metadata, and proper fee allocation.
+
+#### Assembly Protocol
+
+The transaction assembly MUST follow this protocol:
+
+```typescript
+interface TransactionAssemblyProtocol {
+ // Build transaction body with all components
+ buildTransactionBody(): TransactionBody
+
+ // Calculate final fee and change outputs
+ calculateFinalFeeAndChange(): { fee: Coin, changeOutputs: TransactionOutput[] }
+
+ // Apply final fee to transaction
+ applyFinalFee(fee: Coin): void
+
+ // Build complete witness set structure
+ buildWitnessSet(): TransactionWitnessSet
+
+ // Construct final transaction
+ assembleTransaction(): Transaction
+}
+```
+
+#### Redeemer Index Management
+
+The assembly process MUST implement accurate redeemer index management:
+
+```typescript
+interface RedeemerIndexManagement {
+ // Map UTxOs to their transaction input indices
+ createInputIndexMap(
+ inputs: UTxO[]
+ ): Map // UTxO ID -> Input Index
+
+ // Build redeemers with correct indices
+ buildRedeemers(
+ partialPrograms: PartialProgram[],
+ inputIndexMap: Map
+ ): Redeemer[]
+
+ // Validate redeemer indices are unique and valid
+ validateRedeemerIndices(redeemers: Redeemer[]): void
+}
+```
+
+#### Change Output Calculation
+
+The assembly process MUST implement comprehensive change calculation:
+
+```typescript
+interface ChangeCalculationProtocol {
+ // Calculate total available assets
+ calculateTotalAvailable(
+ selectedUtxos: UTxO[],
+ mintedAssets: Assets
+ ): Assets
+
+ // Calculate total required assets
+ calculateTotalRequired(
+ outputs: TransactionOutput[],
+ fee: Coin,
+ burnedAssets: Assets
+ ): Assets
+
+ // Calculate change assets
+ calculateChange(
+ available: Assets,
+ required: Assets
+ ): Assets
+
+ // Create change outputs with minimum ADA
+ createChangeOutputs(
+ changeAssets: Assets,
+ changeAddress: Address,
+ coinsPerUtxoByte: bigint
+ ): TransactionOutput[]
+}
+```
+
+#### Final Validation Protocol
+
+Before returning the built transaction, the assembly MUST perform final validation:
+
+```typescript
+interface FinalValidationProtocol {
+ // Validate transaction size limits
+ validateTransactionSize(transaction: Transaction): void
+
+ // Validate input/output balance
+ validateAssetBalance(transaction: Transaction): void
+
+ // Validate script data hash consistency
+ validateScriptDataHash(transaction: Transaction): void
+
+ // Validate protocol parameter compliance
+ validateProtocolCompliance(
+ transaction: Transaction,
+ protocolParameters: ProtocolParameters
+ ): void
+}
+```
+
+### Error Handling and Recovery (Normative)
+
+#### Error Classification
+
+The build process MUST classify errors into specific categories with appropriate recovery strategies:
+
+```typescript
+interface BuildErrorTypes {
+ // Configuration and setup errors (non-recoverable)
+ ConfigurationError: {
+ invalidOptions: BuildOptionsError
+ walletAccessError: WalletError
+ networkMismatch: NetworkError
+ }
+
+ // Resource availability errors (potentially recoverable)
+ ResourceError: {
+ insufficientFunds: InsufficientFundsError
+ noSuitableUtxos: UTxOAvailabilityError
+ collateralUnavailable: CollateralError
+ }
+
+ // Script evaluation errors (context-dependent)
+ ScriptError: {
+ evaluationTimeout: TimeoutError
+ evaluationFailure: ExecutionError
+ invalidExUnits: ValidationError
+ }
+
+ // Protocol compliance errors (non-recoverable)
+ ProtocolError: {
+ transactionTooLarge: SizeError
+ invalidTransaction: StructureError
+ protocolLimitExceeded: LimitError
+ }
+}
+```
+
+#### Recovery Strategies
+
+Each error category MUST implement appropriate recovery strategies:
+
+1. **Resource Errors**: Provide detailed asset breakdown and suggestions
+2. **Script Errors**: Fallback evaluation strategies and timeout adjustments
+3. **Protocol Errors**: Clear guidance on limit violations and corrections
+4. **Network Errors**: Retry logic with exponential backoff
+
+#### Error Context Preservation
+
+All errors MUST preserve context for debugging:
+
+```typescript
+interface ErrorContext {
+ phase: BuildPhase
+ selectedUtxos: UTxO[]
+ requiredAssets: Assets
+ availableAssets: Assets
+ scriptEvaluationResults?: EvaluationResult[]
+ partialTransaction?: Transaction
+}
+```
+
+### Performance and Resource Management (Normative)
+
+#### Performance Requirements
+
+The build process MUST meet the following performance requirements:
+
+1. **Coin Selection Time**: O(n log n) where n is the number of available UTxOs
+2. **Script Evaluation Timeout**: Configurable with default 30 seconds per script
+3. **Memory Usage**: Bounded by UTxO set size and transaction complexity
+4. **Network Calls**: Minimized through efficient provider interaction
+
+#### Resource Limits
+
+The build process MUST enforce the following resource limits:
+
+1. **Maximum Inputs**: Default 50, configurable up to protocol limit
+2. **Maximum Outputs**: Unlimited but subject to transaction size limits
+3. **Maximum Transaction Size**: 16KB as per protocol parameters
+4. **Maximum Script Size**: 25KB per reference script as per protocol
+
+#### Optimization Strategies
+
+The build process SHOULD implement the following optimizations:
+
+1. **UTxO Set Filtering**: Pre-filter UTxOs by relevance to reduce search space
+2. **Parallel Script Evaluation**: Evaluate independent scripts concurrently
+3. **Caching**: Cache evaluation results for identical script/input combinations
+4. **Early Termination**: Stop coin selection when requirements are met
+
+### Integration Contracts (Normative)
+
+#### Wallet Integration
+
+The build process MUST interact with wallets through the following interface:
+
+```typescript
+interface WalletBuildInterface {
+ // UTxO access
+ getUtxos(): Promise
+
+ // Address derivation
+ getAddress(): Promise
+ getChangeAddress(): Promise
+
+ // Network information
+ getNetwork(): Network
+
+ // Signing preparation (for SignBuilder)
+ prepareSigningContext(transaction: Transaction): SigningContext
+}
+```
+
+#### Provider Integration
+
+The build process MUST interact with providers through the following interface:
+
+```typescript
+interface ProviderBuildInterface {
+ // Protocol parameters
+ getProtocolParameters(): Promise
+
+ // Script evaluation
+ evaluateTransaction(
+ transaction: Transaction,
+ additionalUtxos?: UTxO[]
+ ): Promise
+
+ // UTxO queries (for explicit input validation)
+ getUtxosByOutRef(outRefs: OutRef[]): Promise
+}
+```
+
+#### Effect-Promise Bridge
+
+All build operations MUST provide both Effect and Promise interfaces:
+
+```typescript
+interface BuildInterface {
+ // Promise-based interface
+ build(options?: BuildOptions): Promise
+
+ // Effect-based interface
+ Effect: {
+ build(options?: BuildOptions): Effect
+ }
+}
+```
+
+---
+
+## Appendix
+
+### Build Phase Transition Matrix
+
+| From Phase | To Phase | Conditions | Possible Failures |
+|------------|----------|------------|------------------|
+| Setup → Intent Execution | Always | Configuration valid | Wallet errors, validation failures |
+| Intent Execution → Initial Coin Selection | Always | Intents processed | Asset calculation errors |
+| Initial Coin Selection → Script Evaluation | Has Plutus scripts | UTxOs selected | Insufficient funds |
+| Initial Coin Selection → Refined Management | No scripts | UTxOs selected | Skip script evaluation |
+| Script Evaluation → Refined Management | Always | Scripts evaluated | Evaluation failures |
+| Refined Management → Assembly | Always | Resources allocated | Collateral failures |
+
+### Coin Selection Algorithm Comparison
+
+| Algorithm | Time Complexity | Space Complexity | Best Use Case | Limitations |
+|-----------|----------------|------------------|---------------|-------------|
+| Largest-First | O(n log n) | O(1) | Simple payments | May not minimize inputs |
+| Random-Improve | O(n²) | O(n) | Privacy-focused | Slower convergence |
+| Optimal | O(2ⁿ) | O(n) | Fee optimization | Exponential worst case |
+| Custom | Variable | Variable | Specialized needs | Implementation dependent |
+
+### Script Evaluation Workflow States
+
+```mermaid
+stateDiagram-v2
+ [*] --> NoScripts: No Plutus scripts detected
+ [*] --> HasScripts: Plutus scripts detected
+
+ NoScripts --> FinalAssembly: Skip evaluation
+
+ HasScripts --> EvalPrep: Build evaluation transaction
+ EvalPrep --> LocalEval: Local UPLC available
+ EvalPrep --> ProviderEval: Provider evaluation
+
+ LocalEval --> ApplyResults: WASM evaluation complete
+ ProviderEval --> ApplyResults: Provider response received
+
+ ApplyResults --> RefinedSelection: ExUnits applied
+ RefinedSelection --> ReEvaluate: Input set changed
+ RefinedSelection --> FinalAssembly: Selection stable
+
+ ReEvaluate --> EvalPrep: Re-evaluate with new inputs
+
+ FinalAssembly --> [*]: Transaction built
+```
+
+### Error Recovery Decision Tree
+
+```
+Build Error Occurs
+├── Configuration Error
+│ ├── Invalid Options → Fail with guidance
+│ └── Wallet Access → Retry with backoff
+├── Resource Error
+│ ├── Insufficient Funds → Detailed breakdown
+│ ├── No Suitable UTxOs → Filter adjustment suggestions
+│ └── Collateral Unavailable → Manual collateral guidance
+├── Script Error
+│ ├── Evaluation Timeout → Increase timeout or fallback
+│ ├── Execution Failure → Script debug information
+│ └── Invalid ExUnits → Protocol limit guidance
+└── Protocol Error
+ ├── Transaction Too Large → Size optimization suggestions
+ ├── Invalid Structure → Specific validation failures
+ └── Limit Exceeded → Protocol parameter guidance
+```
+
+### Build Configuration Examples
+
+#### Basic Configuration
+```typescript
+const basicBuild = await client.newTx()
+ .payToAddress(recipient, { coin: 1000000n })
+ .build() // Uses default options
+```
+
+#### Advanced Configuration
+```typescript
+const advancedBuild = await client.newTx()
+ .payToAddress(recipient, { coin: 1000000n })
+ .build({
+ coinSelection: "random-improve",
+ coinSelectionOptions: {
+ maxInputs: 10,
+ excludeUtxos: [reservedUtxo]
+ },
+ uplcEval: {
+ type: "wasm",
+ wasmModule: aikenUplc,
+ timeout: 45000
+ },
+ collateral: manualCollateral,
+ feeMultiplier: 1.2
+ })
+```
+
+#### Custom Coin Selection
+```typescript
+const customSelector: CoinSelectionFunction = (utxos, required, options) => {
+ // Prefer UTxOs without native tokens
+ const adaOnlyUtxos = utxos.filter(isAdaOnly)
+
+ // Select largest UTxOs first
+ const sorted = adaOnlyUtxos.sort((a, b) =>
+ Number(b.output.amount.coin - a.output.amount.coin)
+ )
+
+ let selected: UTxO[] = []
+ let accumulated = emptyAssets()
+
+ for (const utxo of sorted) {
+ selected.push(utxo)
+ accumulated = mergeAssets(accumulated, utxo.output.amount)
+
+ if (satisfiesRequirements(accumulated, required)) {
+ break
+ }
+ }
+
+ return Effect.succeed({
+ selectedUtxos: selected,
+ changeOutput: calculateChange(accumulated, required),
+ totalFee: estimateFee(selected.length)
+ })
+}
+```
+
+### Performance Benchmarks
+
+#### Target Performance Metrics
+
+| Operation | Target Time | Acceptable Time | Failure Time |
+|-----------|-------------|-----------------|--------------|
+| Simple payment build | < 100ms | < 500ms | > 2s |
+| Script transaction build | < 2s | < 10s | > 30s |
+| Large UTxO set (1000+) | < 1s | < 5s | > 15s |
+| Multi-script evaluation | < 5s | < 20s | > 60s |
+
+#### Resource Usage Guidelines
+
+| Resource | Target Usage | Maximum Usage |
+|----------|-------------|---------------|
+| Memory | < 50MB per build | < 200MB |
+| CPU | < 80% single core | < 100% |
+| Network calls | < 5 per build | < 20 |
+| Disk I/O | Minimal | < 10MB |
+
+### Implementation Validation Checklist
+
+#### Phase 1 Validation
+- [ ] Configuration validation covers all option combinations
+- [ ] UTxO filtering excludes reference scripts correctly
+- [ ] Address validation checks network compatibility
+- [ ] Error messages provide actionable guidance
+
+#### Phase 2 Validation
+- [ ] Intent processing handles all supported operations
+- [ ] Asset delta calculation accounts for all sources/sinks
+- [ ] Script detection covers all script usage patterns
+- [ ] Validation catches malformed intents early
+
+#### Phase 3 Validation
+- [ ] Coin selection algorithms meet complexity requirements
+- [ ] Recursive selection handles minimum ADA correctly
+- [ ] UTxO filtering applies all required criteria
+- [ ] Error handling provides detailed asset breakdowns
+
+#### Phase 4 Validation
+- [ ] Evaluation transaction has dummy ExUnits and hash
+- [ ] WASM and provider evaluation produce consistent results
+- [ ] ExUnits application updates all redeemers correctly
+- [ ] Error recovery handles evaluation failures gracefully
+
+#### Phase 5 Validation
+- [ ] Refined selection adjusts for script costs accurately
+- [ ] Collateral selection meets protocol requirements
+- [ ] Budget change detection triggers re-evaluation appropriately
+- [ ] Resource allocation is stable and optimal
+
+#### Phase 6 Validation
+- [ ] Transaction assembly includes all required components
+- [ ] Redeemer indices match transaction input order
+- [ ] Change calculation handles all asset types correctly
+- [ ] Final validation catches protocol violations
+
+This specification establishes the complete requirements for implementing a robust, efficient, and correct transaction build process that can handle the full complexity of Cardano transactions while maintaining usability and performance.
\ No newline at end of file
diff --git a/.specs/transaction-building-specification.md b/.specs/transaction-building-specification.md
new file mode 100644
index 00000000..686f4158
--- /dev/null
+++ b/.specs/transaction-building-specification.md
@@ -0,0 +1,611 @@
+# Transaction Building Specification
+
+**Version**: 1.0.0
+**Status**: DRAFT
+**Created**: September 24, 2025
+**Authors**: Evolution SDK Team
+**Reviewers**: [To be assigned]
+
+---
+
+## Abstract
+
+This specification defines the transaction building architecture for the Evolution SDK, providing a comprehensive framework for constructing, validating, and submitting Cardano transactions. The system implements a progressive builder pattern that separates transaction construction, script evaluation, signing, and submission into distinct, composable phases. Core features include intelligent coin selection algorithms, dual UPLC/provider script evaluation, automatic collateral management, and explicit UTxO state management for transaction chaining. The architecture ensures type safety through progressive builder interfaces while maintaining compatibility with both Effect-based and Promise-based programming paradigms.
+
+---
+
+## Purpose and Scope
+
+This specification establishes the architectural requirements and behavioral contracts for transaction building within the Evolution SDK ecosystem. It serves as the authoritative reference for developers implementing transaction construction logic and for teams integrating with the transaction building system.
+
+**Target Audience**: SDK maintainers, DApp developers, wallet integrators, and contributors implementing transaction-related functionality.
+
+**Scope**: This specification covers transaction construction patterns, coin selection algorithms, script evaluation workflows, progressive builder interfaces, UTxO management strategies, and integration contracts. It does not cover wallet implementation details, provider-specific protocols, or low-level CBOR serialization formats.
+
+---
+
+## Introduction
+
+Transaction building in Cardano requires sophisticated coordination between UTxO selection, script evaluation, fee calculation, and network submission. The Evolution SDK addresses these challenges through a multi-phase architecture that provides both simplicity for common operations and flexibility for complex workflows.
+
+### Key Design Principles
+
+1. **Progressive Enhancement**: Start simple, add complexity as needed through builder progression
+2. **UTxO Transparency**: Make UTxO state management explicit and predictable
+3. **Script Integration**: Native support for Plutus script evaluation and execution
+4. **Type Safety**: Compile-time guarantees for transaction builder capabilities
+5. **Dual API Support**: Compatible with both Effect-ts and Promise-based programming
+
+### Architectural Overview
+
+The transaction building system consists of three primary builder types that form a progressive enhancement chain:
+
+- **TransactionBuilder**: Accumulates transaction intents and builds unsigned transactions
+- **SignBuilder**: Handles transaction signing with support for partial signatures and witness accumulation
+- **SubmitBuilder**: Manages transaction submission and network interaction
+
+This progression ensures that operations are only available when appropriate (e.g., signing requires a built transaction, submission requires signatures).
+
+### Integration Context
+
+Transaction building integrates with the broader Evolution SDK architecture through:
+- **Provider System**: Protocol parameter queries and UTxO data access
+- **Wallet System**: Address derivation, UTxO management, and transaction signing
+- **Effect-Promise Bridge**: Dual API surface supporting multiple programming paradigms
+
+---
+
+## Functional Specification
+
+### Progressive Builder Architecture (Normative)
+
+The transaction building system MUST implement a progressive builder pattern with three distinct phases, each providing specific capabilities and enforcing appropriate constraints.
+
+#### TransactionBuilder Interface
+
+The `TransactionBuilder` interface SHALL provide methods for accumulating transaction intents through a fluent API. All methods MUST return the same `TransactionBuilder` instance to enable method chaining.
+
+**Required Operations**:
+- Payment operations: `payToAddress()`, `payToScript()`
+- UTxO collection: `collectFrom()`, `addInput()`
+- Token operations: `mintTokens()`, `burnTokens()`
+- Staking operations: `delegateStake()`, `withdrawRewards()`
+- Script operations: `attachScript()`, `attachDatum()`
+- Metadata operations: `addMetadata()`, `setValidityInterval()`
+
+**Build Methods**:
+- `build(options?: BuildOptions): Promise` - Complete transaction construction
+- `buildForEvaluation(collateralAmount: Coin, changeAddress: Address): Promise` - Script evaluation preparation
+- `chain(options?: BuildOptions): Promise` - UTxO state management for transaction sequences
+
+**Intent Accumulation Pattern**:
+```typescript
+// Operations accumulate intents without immediate execution
+const builder = client.newTx()
+ .payToAddress({ address: alice, assets: { coin: 1000000n } }) // Intent 1
+ .mintTokens({ assets: { [tokenUnit]: 100n } }) // Intent 2
+ .addMetadata(1, { message: "Batch operation" }) // Intent 3
+
+// All intents execute atomically during build()
+const signBuilder = await builder.build()
+```
+
+#### SignBuilder Interface
+
+The `SignBuilder` interface SHALL handle transaction signing with support for single signatures, partial signatures, and multi-signature assembly.
+
+**Required Properties**:
+- `transaction: Transaction` - The built, unsigned transaction
+- `cost: TransactionEstimate` - Fee and execution unit estimates
+
+**Signing Operations**:
+- `sign(): Promise` - Complete transaction signing
+- `partialSign(): Promise` - Partial signature for multi-sig workflows
+- `assemble(witnesses: TransactionWitnessSet[]): Promise` - Multi-signature assembly
+- `signWithWitness(witnessSet: TransactionWitnessSet): Promise` - External witness integration
+
+#### SubmitBuilder Interface
+
+The `SubmitBuilder` interface SHALL manage transaction submission and network interaction.
+
+**Required Properties**:
+- `transaction: Transaction` - The fully signed transaction
+- `witnessSet: TransactionWitnessSet` - Complete witness set
+- `cbor: string` - Serialized transaction for network submission
+
+**Submission Operations**:
+- `submit(): Promise` - Submit transaction and return hash
+- `simulate(): Promise` - Simulate execution without submission
+
+### UTxO Management and Transaction Chaining (Normative)
+
+The transaction building system MUST support both automatic and explicit UTxO management to accommodate different use case requirements.
+
+#### Automatic UTxO Management
+
+When no UTxOs are provided to `newTx()`, the builder SHALL automatically fetch available UTxOs from the associated wallet:
+
+```typescript
+// Automatic UTxO fetching
+const builder = client.newTx() // Internally calls wallet.getUtxos()
+```
+
+#### Explicit UTxO Management
+
+When UTxOs are explicitly provided, the builder SHALL operate exclusively on the provided set without additional wallet queries:
+
+```typescript
+// Explicit UTxO management
+const builder = client.newTx(specificUtxos) // Uses only provided UTxOs
+```
+
+#### Transaction Chaining Protocol
+
+The `chain()` method SHALL return a `ChainResult` that provides complete UTxO state transformation information:
+
+```typescript
+interface ChainResult {
+ readonly transaction: Transaction // The constructed transaction
+ readonly spentUtxos: UTxO[] // UTxOs consumed as inputs
+ readonly newOutputs: UTxO[] // UTxOs created as outputs
+ readonly updatedUtxos: UTxO[] // Available UTxOs for next transaction
+ readonly cost: TransactionEstimate // Fee and execution costs
+}
+```
+
+**Chaining Workflow**:
+```typescript
+// Sequential transaction chain
+let currentUtxos = await client.getWalletUtxos()
+
+const step1 = await client.newTx(currentUtxos)
+ .payToAddress(alice, { coin: 2000000n })
+ .chain()
+
+const step2 = await client.newTx(step1.updatedUtxos)
+ .mintTokens({ assets: tokenMap })
+ .chain()
+
+// Submit transactions in dependency order
+await client.submitTx(step1.transaction)
+await client.submitTx(step2.transaction)
+```
+
+### Coin Selection Algorithms (Normative)
+
+Coin selection has a **single responsibility**: select which UTxOs from available inputs should be spent to satisfy the transaction's asset requirements.
+
+Coin selection does NOT handle:
+- Fee calculation
+- Change output creation
+- Minimum ADA requirements
+- Transaction assembly
+- Script evaluation
+
+#### Algorithm Implementation
+
+Each coin selection function embeds its own algorithm. The system provides:
+
+1. **Largest-First Function**: `largestFirstSelection` - Select largest UTxOs first until requirements are met
+2. **Random-Improve Function**: `randomImproveSelection` - Random selection with improvement heuristics following CIP-2
+3. **Optimal Function**: `optimalSelection` - Minimize input count through optimization
+4. **Custom Functions**: User-provided functions implementing any selection algorithm
+
+#### Coin Selection Interface
+
+```typescript
+interface CoinSelectionResult {
+ readonly selectedUtxos: ReadonlyArray // ONLY the selected UTxOs
+}
+
+type CoinSelectionFunction = (
+ availableUtxos: ReadonlyArray,
+ requiredAssets: Assets
+) => CoinSelectionResult
+```
+
+#### Two-Phase Selection Process
+
+The transaction builder MAY call coin selection multiple times to handle script execution costs:
+
+1. **Initial Selection**: Select UTxOs based on estimated asset requirements
+2. **Refined Selection**: Re-run selection with updated requirements after script evaluation
+
+```typescript
+// Phase 1: Select with estimated requirements
+const { selectedUtxos: initial } = coinSelection(utxos, estimatedRequirements)
+
+// Phase 2: Calculate actual costs and re-select if needed
+const actualRequirements = baseRequirements + scriptCosts + fees
+const { selectedUtxos: final } = coinSelection(utxos, actualRequirements)
+```
+
+Note: Coin selection itself remains stateless - it just selects UTxOs for given requirements. The transaction builder orchestrates multiple selections as needed.
+
+### Script Evaluation Workflows (Normative)
+
+The system MUST support dual evaluation strategies for Plutus scripts with appropriate cost calculation and error handling.
+
+#### Evaluation Strategy Options
+
+1. **WASM UPLC Evaluation**: Local evaluation using WebAssembly UPLC interpreter
+2. **Provider Evaluation**: External evaluation through blockchain data providers
+
+#### Two-Phase Building Process
+
+For transactions containing Plutus scripts, the system SHALL implement a two-phase building process:
+
+**Phase 1: Evaluation Preparation**
+```typescript
+// Build transaction with dummy ExUnits for evaluation
+const evalBuilder = await txBuilder.buildForEvaluation(0n, changeAddress)
+
+// Extract draft transaction for script evaluation
+const draftTx = await evalBuilder.draftTx()
+```
+
+**Phase 2: Execution Unit Application**
+```typescript
+// Apply evaluation results
+if (uplcEvaluation) {
+ await evalBuilder.applyUplcEval(uplcResults)
+} else {
+ await evalBuilder.applyProviderEval(providerResults)
+}
+
+// Build final transaction with correct ExUnits
+const signBuilder = await evalBuilder.build()
+```
+
+#### Script Evaluation Safety
+
+Evaluation transactions MUST include safety mechanisms to prevent accidental submission:
+- Dummy `script_data_hash` (all zeros) to invalidate premature submission
+- Placeholder ExUnits that would cause script failures if submitted
+- Clear separation between evaluation and submission transactions
+
+### Build Configuration Options (Normative)
+
+The `BuildOptions` interface SHALL provide comprehensive configuration for transaction construction:
+
+```typescript
+interface BuildOptions {
+ // Coin selection configuration
+ readonly coinSelection?: CoinSelectionAlgorithm | CoinSelectionFunction
+ readonly coinSelectionOptions?: CoinSelectionOptions
+
+ // Script evaluation configuration
+ readonly uplcEval?: UplcEvaluationOptions
+
+ // Collateral configuration
+ readonly collateral?: ReadonlyArray // Manual collateral (max 3)
+ readonly autoCollateral?: boolean // Default: true for script transactions
+
+ // UTXO defragmentation strategies
+ readonly defragmentation?: UtxoDefragmentationOptions
+
+ // Fee configuration
+ readonly minFee?: Coin
+ readonly feeMultiplier?: number // Default: 1.0
+}
+```
+
+#### UplcEvaluationOptions
+
+```typescript
+interface UplcEvaluationOptions {
+ readonly type: "wasm" | "provider"
+ readonly wasmModule?: WasmUplcModule // WASM UPLC interpreter instance
+ readonly timeout?: number // Evaluation timeout in milliseconds
+ readonly maxMemory?: number // Memory limit for evaluation
+ readonly maxCpu?: number // CPU step limit for evaluation
+}
+```
+
+#### UtxoDefragmentationOptions
+
+The `UtxoDefragmentationOptions` interface enables intelligent UTXO set optimization strategies to maintain transaction efficiency and reduce fees:
+
+```typescript
+interface UtxoDefragmentationOptions {
+ // Split oversized UTXOs into multiple outputs to change address
+ readonly unfrack?: {
+ readonly enabled: boolean
+ // Maximum number of assets per UTXO before splitting
+ readonly maxAssetsPerUtxo?: number
+ // Maximum ADA value per UTXO before splitting
+ readonly maxAdaPerUtxo?: Coin
+ }
+ // Consolidate many small UTXOs into fewer, larger ones
+ readonly consolidate?: {
+ readonly enabled: boolean
+ // Minimum ADA value to consider for consolidation
+ readonly minAdaThreshold?: Coin
+ // Maximum number of UTXOs to consolidate in one transaction
+ readonly maxUtxosToConsolidate?: number
+ }
+}
+```
+
+**Unfracking Strategy**: When a UTXO contains too many assets or excessive ADA value, the system automatically splits the UTXO by creating additional change outputs. This prevents individual UTXOs from becoming too large, which can cause transaction size issues and higher fees.
+
+**Consolidation Strategy**: When the wallet contains many small UTXOs with minimal ADA values, the system combines them into fewer, larger UTXOs. This reduces the complexity of future transactions and minimizes fees by reducing the number of inputs required.
+
+Both strategies operate transparently during the transaction building process, creating optimal UTXO distributions without requiring manual intervention from developers.
+
+### Multi-Phase Build Process (Normative)
+
+The `build()` method SHALL execute a comprehensive multi-phase process ensuring transaction validity and optimal resource utilization.
+
+#### Phase 1: Setup and Validation
+- Validate build options and configuration parameters
+- Fetch wallet UTxOs if not explicitly provided
+- Execute accumulated transaction intents
+
+#### Phase 2: Asset Requirements Calculation
+- Calculate total output requirements including estimated fees
+- Account for minted assets and collected inputs
+- Determine net asset requirements for coin selection
+
+#### Phase 3: Initial Coin Selection
+- Apply specified coin selection algorithm
+- Select UTxOs to cover basic transaction requirements
+- Calculate initial fee estimates without script costs
+
+#### Phase 4: Script Evaluation (if applicable)
+- Detect Plutus script usage in transaction intents
+- Build evaluation transaction with dummy ExUnits
+- Execute script evaluation using WASM or provider
+- Apply real ExUnits to transaction redeemers
+
+#### Phase 5: Refined Resource Management
+- Recalculate fees with script execution costs
+- Perform refined coin selection if additional funds needed
+- Select and validate collateral UTxOs for script transactions
+
+#### Phase 6: Transaction Finalization
+- Build complete transaction with all components
+- Calculate final fees and change outputs
+- Create SignBuilder instance with built transaction
+
+### Error Handling and Recovery (Normative)
+
+The transaction building system MUST provide comprehensive error handling with specific error types for different failure scenarios.
+
+#### Required Error Types
+
+```typescript
+interface TransactionBuilderError {
+ readonly _tag: "TransactionBuilderError"
+ readonly message: string
+ readonly cause?: unknown
+}
+
+interface CoinSelectionError {
+ readonly _tag: "CoinSelectionError"
+ readonly insufficientFunds?: { required: Assets, available: Assets }
+ readonly maxInputsExceeded?: { requested: number, maximum: number }
+}
+
+interface ScriptEvaluationError {
+ readonly _tag: "ScriptEvaluationError"
+ readonly scriptHash?: string
+ readonly evaluationFailure?: string
+}
+```
+
+#### Recovery Strategies
+
+- **Insufficient Funds**: Provide clear breakdown of required vs available assets
+- **Script Evaluation Failures**: Include detailed script execution logs
+- **Network Errors**: Implement automatic retry with exponential backoff
+- **Validation Errors**: Return specific validation failure messages
+
+### Effect-Promise API Bridge (Normative)
+
+All transaction builder interfaces MUST provide both Effect-based and Promise-based APIs to support different programming paradigms.
+
+#### Dual API Pattern
+
+```typescript
+interface TransactionBuilder extends EffectToPromiseAPI {
+ readonly Effect: TransactionBuilderEffect
+}
+
+interface TransactionBuilderEffect {
+ readonly build: (options?: BuildOptions) => Effect
+ readonly chain: (options?: BuildOptions) => Effect
+ // ... other operations
+}
+```
+
+#### Usage Examples
+
+```typescript
+// Promise-based usage
+const signBuilder = await client.newTx()
+ .payToAddress(address, value)
+ .build()
+
+// Effect-based usage
+const signBuilder = await Effect.runPromise(
+ client.Effect.newTx()
+ .payToAddress(address, value)
+ .build()
+)
+```
+
+---
+
+## Appendix
+
+### Operation Parameter Matrices
+
+#### PayToAddress Parameters
+| Parameter | Type | Required | Description |
+|-----------|------|----------|-------------|
+| `address` | `Address` | Yes | Recipient address |
+| `assets` | `Assets` | Yes | ADA and native tokens to send |
+| `datum` | `Data` | No | Inline datum for script addresses |
+| `scriptRef` | `Script` | No | Reference script to attach |
+
+#### MintTokens Parameters
+| Parameter | Type | Required | Description |
+|-----------|------|----------|-------------|
+| `assets` | `Assets` | Yes | Tokens to mint (excluding ADA) |
+| `redeemer` | `Redeemer` | No | Redeemer for minting script |
+
+#### CollectFrom Parameters
+| Parameter | Type | Required | Description |
+|-----------|------|----------|-------------|
+| `inputs` | `UTxO[]` | Yes | UTxOs to consume as inputs |
+| `redeemer` | `Redeemer` | No | Redeemer for script inputs |
+
+### Coin Selection Algorithm Comparison
+
+| Algorithm | Best For | Pros | Cons |
+|-----------|----------|------|------|
+| Largest-First | Simple payments | Fast execution, predictable | May not minimize change |
+| Random-Improve | Privacy-focused | Better UTxO distribution | More complex computation |
+| Optimal | Fee optimization | Minimizes inputs and change | Slower for large UTxO sets |
+| Custom | Specialized needs | Full control over selection | Requires custom implementation |
+
+### Script Evaluation Workflow Diagram
+
+```
+┌─────────────────┐ ┌──────────────────┐ ┌─────────────────┐
+│ Transaction │ │ Evaluation │ │ Final │
+│ Builder │───▶│ Transaction │───▶│ Transaction │
+│ (intents) │ │ (dummy ExUnits)│ │ (real ExUnits)│
+└─────────────────┘ └──────────────────┘ └─────────────────┘
+ │ │ │
+ │ ▼ │
+ │ ┌──────────────────┐ │
+ │ │ Script │ │
+ │ │ Evaluation │ │
+ │ │ (WASM/Provider) │ │
+ │ └──────────────────┘ │
+ │ │ │
+ └───────────────────────┼───────────────────────┘
+ ▼
+ ┌──────────────────┐
+ │ Apply ExUnits │
+ │ to Transaction │
+ └──────────────────┘
+```
+
+### Integration Examples
+
+#### Basic Payment Transaction
+```typescript
+// Automatic UTxO management
+const txHash = await client
+ .newTx()
+ .payToAddress({
+ address: "addr1...",
+ assets: { coin: 1000000n }
+ })
+ .buildSignAndSubmit()
+```
+
+#### Multi-Asset Transfer with Script
+```typescript
+// Custom coin selection with script interaction
+const signBuilder = await client
+ .newTx(selectedUtxos)
+ .payToScript({
+ scriptHash: plutusScriptHash,
+ assets: { coin: 5000000n, [tokenUnit]: 100n },
+ datum: { action: "deposit", amount: 100n }
+ })
+ .mintTokens({
+ assets: { [policyUnit]: 50n },
+ redeemer: { action: "mint" }
+ })
+ .build({
+ coinSelection: "largest-first",
+ uplcEval: { type: "wasm", wasmModule: uplcWasm }
+ })
+```
+
+#### Transaction Chaining Workflow
+```typescript
+// UTxO state management across transaction chain
+const utxos = await client.getWalletUtxos()
+
+const step1 = await client.newTx(utxos)
+ .payToAddress(alice, { coin: 2000000n })
+ .chain()
+
+const step2 = await client.newTx(step1.updatedUtxos)
+ .collectFrom({ inputs: [step1.newOutputs[0]] })
+ .mintTokens({ assets: { [tokenUnit]: 1000n } })
+ .chain()
+
+// Submit in dependency order
+await client.submitTx(step1.transaction)
+await client.submitTx(step2.transaction)
+```
+
+### Configuration Examples
+
+#### Advanced Build Options
+```typescript
+const buildOptions: BuildOptions = {
+ coinSelection: "random-improve",
+ coinSelectionOptions: {
+ maxInputs: 5,
+ excludeUtxos: [reservedUtxo],
+ allowPartialSpend: true
+ },
+ uplcEval: {
+ type: "wasm",
+ wasmModule: aikenUplc,
+ timeout: 30000,
+ maxMemory: 14000000,
+ maxCpu: 10000000000
+ },
+ autoCollateral: true,
+ feeMultiplier: 1.1
+}
+
+const signBuilder = await client
+ .newTx()
+ .payToAddress(address, assets)
+ .build(buildOptions)
+```
+
+#### Custom Coin Selection Function
+```typescript
+const customSelector: CoinSelectionFunction = (utxos, required, options) => {
+ // Prefer UTxOs without native tokens for simple payments
+ const adaOnlyUtxos = utxos.filter(utxo =>
+ Object.keys(utxo.output.amount).length === 1
+ )
+
+ // Select largest UTxOs first up to maxInputs
+ const selected = adaOnlyUtxos
+ .sort((a, b) => Number(b.output.amount.coin - a.output.amount.coin))
+ .slice(0, options.maxInputs || 10)
+
+ return Effect.succeed({
+ selectedUtxos: selected,
+ totalFee: calculateFee(selected.length),
+ changeOutput: calculateChange(selected, required)
+ })
+}
+```
+
+### Performance Considerations
+
+#### Optimization Guidelines
+1. **UTxO Set Size**: Large UTxO sets may require pagination or filtering
+2. **Script Evaluation**: WASM evaluation is faster but requires module loading
+3. **Coin Selection**: Optimal algorithms are slower for large UTxO sets
+4. **Network Calls**: Minimize provider calls through intelligent caching
+
+#### Resource Limits
+- **Maximum Inputs**: Protocol limit of ~1000 inputs per transaction
+- **Collateral UTxOs**: Maximum of 3 UTxOs for collateral
+- **Transaction Size**: ~16KB maximum transaction size
+- **Script Evaluation**: Memory and CPU limits defined by protocol parameters
\ No newline at end of file
diff --git a/docs/content/docs/getting-started/data/basic-construction.mdx b/docs/content/docs/getting-started/data/basic-construction.mdx
index 19d3a197..47d2bb42 100644
--- a/docs/content/docs/getting-started/data/basic-construction.mdx
+++ b/docs/content/docs/getting-started/data/basic-construction.mdx
@@ -5,7 +5,7 @@ description: "Learn how to create fundamental Data types using constructors."
```typescript
import assert from "node:assert/strict"
-import { Data } from "@evolution-sdk/evolution"
+import { Bytes, Data } from "@evolution-sdk/evolution"
// Create a simple constructor with no fields
const unit = new Data.Constr({ index: 0n, fields: [] })
@@ -14,7 +14,7 @@ console.log("Unit constructor:", unit)
// Create a constructor with primitive fields
const person = new Data.Constr({
index: 1n,
- fields: ["416c696365", 30n] // 'Alice' as hex and age
+ fields: [Bytes.fromHexUnsafe("416c696365"), 30n] // 'Alice' as bytes and age
})
console.log("Person constructor:", person)
@@ -22,7 +22,7 @@ console.log("Person constructor:", person)
const record = new Data.Constr({
index: 2n,
fields: [
- "deadbeef", // bytes as hex string (ByteArray)
+ Bytes.fromHexUnsafe("deadbeef"), // bytes as Uint8Array (ByteArray)
42n, // big integer (Int)
[1n, 2n, 3n], // array of big integers (List)
new Data.Constr({ index: 0n, fields: [] }) // nested constructor
@@ -32,7 +32,7 @@ const record = new Data.Constr({
// Verify the construction worked
assert.equal(person.index, 1n)
assert.equal(person.fields.length, 2)
-assert.equal(person.fields[0], "416c696365") // 'Alice' in hex
+assert.deepEqual(person.fields[0], Bytes.fromHexUnsafe("416c696365")) // 'Alice' in hex
assert.equal(person.fields[1], 30n)
```
diff --git a/docs/content/docs/getting-started/data/bytes-validate.mdx b/docs/content/docs/getting-started/data/bytes-validate.mdx
index 01ab11fa..c1c5d97e 100644
--- a/docs/content/docs/getting-started/data/bytes-validate.mdx
+++ b/docs/content/docs/getting-started/data/bytes-validate.mdx
@@ -1,16 +1,16 @@
---
title: "Validate bytes"
-description: "Quick check for hex-like bytes strings using Data.isBytes."
+description: "Quick check for Uint8Array bytes using Data.isBytes."
---
```typescript
import assert from "node:assert/strict"
-import { Data } from "@evolution-sdk/evolution"
+import { Bytes, Data } from "@evolution-sdk/evolution"
-const hex = "deadbeef"
-assert.equal(Data.isBytes(hex), true)
+const bytes = Bytes.fromHexUnsafe("deadbeef")
+assert.equal(Data.isBytes(bytes), true)
-const invalid = "not-hex"
+const invalid = "not-bytes"
assert.equal(Data.isBytes(invalid), false)
```
diff --git a/docs/content/docs/getting-started/data/cbor-encoding-options.mdx b/docs/content/docs/getting-started/data/cbor-encoding-options.mdx
index 807740b6..491805c9 100644
--- a/docs/content/docs/getting-started/data/cbor-encoding-options.mdx
+++ b/docs/content/docs/getting-started/data/cbor-encoding-options.mdx
@@ -5,13 +5,13 @@ description: "Compare different CBOR encoding strategies for the same data."
```typescript
import assert from "node:assert/strict"
-import { CBOR, Data } from "@evolution-sdk/evolution"
+import { Bytes, CBOR, Data } from "@evolution-sdk/evolution"
// Create complex data with unsorted elements (Maps should be standalone, not in constructor fields)
const unsortedMap = new Map([
- ["7a65627261", 1n], // 'zebra' in hex
- ["6170706c65", 2n], // 'apple' in hex
- ["62616e616e61", 3n] // 'banana' in hex
+ [Bytes.fromHexUnsafe("7a65627261"), 1n], // 'zebra' in hex
+ [Bytes.fromHexUnsafe("6170706c65"), 2n], // 'apple' in hex
+ [Bytes.fromHexUnsafe("62616e616e61"), 3n] // 'banana' in hex
])
// Create a constructor with only valid field types
@@ -20,7 +20,7 @@ const complexData = new Data.Constr({
fields: [
// List with mixed order
[100n, 1n, 50n, 25n],
- "deadbeef",
+ Bytes.fromHexUnsafe("deadbeef"),
42n // additional data
]
})
diff --git a/docs/content/docs/getting-started/data/complex-nested-structures.mdx b/docs/content/docs/getting-started/data/complex-nested-structures.mdx
index 342fb562..4956651b 100644
--- a/docs/content/docs/getting-started/data/complex-nested-structures.mdx
+++ b/docs/content/docs/getting-started/data/complex-nested-structures.mdx
@@ -5,18 +5,18 @@ description: "Build sophisticated nested data structures with multiple levels an
```typescript
import assert from "node:assert/strict"
-import { Data } from "@evolution-sdk/evolution"
+import { Bytes, Data } from "@evolution-sdk/evolution"
// Create a complex user profile with nested data using only valid Data types
const userProfile = new Data.Constr({
index: 0n, // User constructor
fields: [
- "616c696365", // username 'alice' in hex
+ Bytes.fromHexUnsafe("616c696365"), // username 'alice' in hex
new Data.Constr({
index: 1n, // Profile constructor
fields: [
25n, // age
- "deadbeef", // some profile data as hex
+ Bytes.fromHexUnsafe("deadbeef"), // some profile data as hex
// Nested preferences constructor
new Data.Constr({
index: 2n, // Preferences constructor
@@ -35,18 +35,18 @@ const userProfile = new Data.Constr({
const transaction = new Data.Constr({
index: 10n, // Transaction constructor
fields: [
- "deadbeef1234", // transaction hash
+ Bytes.fromHexUnsafe("deadbeef1234"), // transaction hash
1000000n, // amount in microADA
new Data.Constr({
index: 11n, // Address constructor
- fields: ["616464723174657374"] // address data in hex
+ fields: [Bytes.fromHexUnsafe("616464723174657374")] // address data in hex
}),
// Simple metadata as nested constructor
new Data.Constr({
index: 12n, // Metadata constructor
fields: [
1640995200n, // timestamp
- "7061796d656e74", // 'payment' as hex string
+ Bytes.fromHexUnsafe("7061796d656e74"), // 'payment' as hex string
1n // status code
]
})
@@ -55,7 +55,7 @@ const transaction = new Data.Constr({
// Test deep structure access
assert.equal(userProfile.index, 0n)
-assert.equal(userProfile.fields[0], "616c696365") // alice in hex
+assert.deepEqual(userProfile.fields[0], Bytes.fromHexUnsafe("616c696365")) // alice in hex
// Verify nested constructor
const profileData = userProfile.fields[1] as Data.Constr
diff --git a/docs/content/docs/getting-started/data/data.mdx b/docs/content/docs/getting-started/data/data.mdx
index 96ba76b2..1eb61e61 100644
--- a/docs/content/docs/getting-started/data/data.mdx
+++ b/docs/content/docs/getting-started/data/data.mdx
@@ -7,7 +7,7 @@ title: "Data"
// #region data-nested-canonical
import assert from "node:assert/strict"
-import { CBOR, Data } from "@evolution-sdk/evolution"
+import { Bytes, CBOR, Data } from "@evolution-sdk/evolution"
// Create a complex nested data structure with:
// - Constructor with index 1 containing multiple fields
// - Nested constructors with different indices
@@ -28,9 +28,9 @@ const nestedUnsortedData = new Data.Constr({
}),
// Map with unsorted keys (will be sorted in canonical mode)
new Map([
- ["deadbeef01", new Data.Constr({ index: 0n, fields: [] })],
- ["beef", 19n],
- ["deadbeef03", new Data.Constr({ index: 1n, fields: [] })]
+ [Bytes.fromHexUnsafe("deadbeef01"), new Data.Constr({ index: 0n, fields: [] })],
+ [Bytes.fromHexUnsafe("beef"), 19n],
+ [Bytes.fromHexUnsafe("deadbeef03"), new Data.Constr({ index: 1n, fields: [] })]
]),
// Array of numbers
[10n, 5n, 2n, 3n, 1n, 4n]
diff --git a/docs/content/docs/getting-started/data/error-handling-patterns.mdx b/docs/content/docs/getting-started/data/error-handling-patterns.mdx
index 2363f58a..9cc1ec92 100644
--- a/docs/content/docs/getting-started/data/error-handling-patterns.mdx
+++ b/docs/content/docs/getting-started/data/error-handling-patterns.mdx
@@ -5,10 +5,10 @@ description: "Use Either patterns for safe data operations with proper error han
```typescript
import assert from "node:assert/strict"
-import { Data, Either, pipe } from "@evolution-sdk/evolution"
+import { Bytes, Data, Either, pipe } from "@evolution-sdk/evolution"
// Use built-in Either-based functions for safe operations
-const safeData = new Data.Constr({ index: 0n, fields: ["74657374", 42n] }) // 'test' as hex
+const safeData = new Data.Constr({ index: 0n, fields: [Bytes.fromHexUnsafe("74657374"), 42n] }) // 'test' as hex
// Safe encoding using Data.Either namespace
const encodingResult = Data.Either.toCBORHex(safeData)
diff --git a/docs/content/docs/getting-started/data/nested-canonical.mdx b/docs/content/docs/getting-started/data/nested-canonical.mdx
index d85a8369..7eb466de 100644
--- a/docs/content/docs/getting-started/data/nested-canonical.mdx
+++ b/docs/content/docs/getting-started/data/nested-canonical.mdx
@@ -5,7 +5,7 @@ description: "Complex nested Data encoding with canonical CBOR options."
```typescript
import assert from "node:assert/strict"
-import { CBOR, Data } from "@evolution-sdk/evolution"
+import { Bytes, CBOR, Data } from "@evolution-sdk/evolution"
const nestedUnsortedData = new Data.Constr({
index: 1n,
@@ -15,9 +15,9 @@ const nestedUnsortedData = new Data.Constr({
fields: [new Data.Constr({ index: 2n, fields: [] })]
}),
new Map([
- ["deadbeef01", new Data.Constr({ index: 0n, fields: [] })],
- ["beef", 19n],
- ["deadbeef03", new Data.Constr({ index: 1n, fields: [] })]
+ [Bytes.fromHexUnsafe("deadbeef01"), new Data.Constr({ index: 0n, fields: [] })],
+ [Bytes.fromHexUnsafe("beef"), 19n],
+ [Bytes.fromHexUnsafe("deadbeef03"), new Data.Constr({ index: 1n, fields: [] })]
]),
[10n, 5n, 2n, 3n, 1n, 4n]
]
diff --git a/docs/content/docs/getting-started/data/roundtrip.mdx b/docs/content/docs/getting-started/data/roundtrip.mdx
index 86a7a46b..61ad0d7f 100644
--- a/docs/content/docs/getting-started/data/roundtrip.mdx
+++ b/docs/content/docs/getting-started/data/roundtrip.mdx
@@ -5,9 +5,9 @@ description: "Encode a Data value to CBOR hex and decode back."
```typescript
import assert from "node:assert/strict"
-import { CBOR, Data } from "@evolution-sdk/evolution"
+import { Bytes, CBOR, Data } from "@evolution-sdk/evolution"
-const original = new Data.Constr({ index: 0n, fields: ["beef", 19n] })
+const original = new Data.Constr({ index: 0n, fields: [Bytes.fromHexUnsafe("beef"), 19n] })
const hexCbor = Data.toCBORHex(original, CBOR.CANONICAL_OPTIONS)
const back = Data.fromCBORHex(hexCbor)
assert.deepStrictEqual(back, original)
diff --git a/docs/content/docs/getting-started/data/working-with-maps.mdx b/docs/content/docs/getting-started/data/working-with-maps.mdx
index 35a374f5..176bf637 100644
--- a/docs/content/docs/getting-started/data/working-with-maps.mdx
+++ b/docs/content/docs/getting-started/data/working-with-maps.mdx
@@ -5,39 +5,50 @@ description: "Create and manipulate Data Maps with key-value pairs."
```typescript
import assert from "node:assert/strict"
-import { Data } from "@evolution-sdk/evolution"
+import { Bytes, Data } from "@evolution-sdk/evolution"
-// Create a simple map with hex string keys and integer values
+// Create byte keys to use consistently
+const aliceKey = Bytes.fromHexUnsafe("616c696365") // 'alice' in hex
+const bobKey = Bytes.fromHexUnsafe("626f62") // 'bob' in hex
+const charlieKey = Bytes.fromHexUnsafe("636861726c6965") // 'charlie' in hex
+
+// Create a simple map with byte keys and integer values
const userAges = new Map([
- ["616c696365", 25n], // 'alice' in hex
- ["626f62", 30n], // 'bob' in hex
- ["636861726c6965", 35n] // 'charlie' in hex
+ [aliceKey, 25n],
+ [bobKey, 30n],
+ [charlieKey, 35n]
])
console.log("User ages map:", userAges)
-// Create a map with constructor keys and hex string values
+// Create constructor keys to use consistently
+const pendingKey = new Data.Constr({ index: 0n, fields: [] })
+const approvedKey = new Data.Constr({ index: 1n, fields: [] })
+const rejectedKey = new Data.Constr({ index: 2n, fields: [] })
+
+// Create a map with constructor keys and byte values
const statusMap = new Map([
- [new Data.Constr({ index: 0n, fields: [] }), "70656e64696e67"], // 'pending' in hex
- [new Data.Constr({ index: 1n, fields: [] }), "617070726f766564"], // 'approved' in hex
- [new Data.Constr({ index: 2n, fields: [] }), "72656a6563746564"] // 'rejected' in hex
+ [pendingKey, Bytes.fromHexUnsafe("70656e64696e67")], // 'pending' in hex
+ [approvedKey, Bytes.fromHexUnsafe("617070726f766564")], // 'approved' in hex
+ [rejectedKey, Bytes.fromHexUnsafe("72656a6563746564")] // 'rejected' in hex
])
-// Demonstrate map usage - Maps are Data types themselves, not constructor fields
-console.log("Status for constructor 0:", statusMap.get(new Data.Constr({ index: 0n, fields: [] })))
+// Demonstrate map usage - use the same key reference for lookups
+console.log("Alice's age:", userAges.get(aliceKey))
+console.log("Status for pending:", statusMap.get(pendingKey))
-// Create a constructor that references the maps via indexes or simple structure
+// Create a constructor that contains Data values
const dataRecord = new Data.Constr({
index: 1n,
fields: [
25n, // alice's age directly
- "deadbeef", // some data
+ Bytes.fromHexUnsafe("deadbeef"), // some data
42n // more data
]
})
-// Verify map operations
-assert.equal(userAges.get("616c696365"), 25n) // alice's age
+// Verify map operations - use same key references
+assert.deepEqual(userAges.get(aliceKey), 25n) // alice's age
assert.equal(userAges.size, 3)
assert.equal(dataRecord.fields.length, 3)
diff --git a/docs/content/docs/modules/Transaction.mdx b/docs/content/docs/modules/Transaction.mdx
deleted file mode 100644
index f680da31..00000000
--- a/docs/content/docs/modules/Transaction.mdx
+++ /dev/null
@@ -1,33 +0,0 @@
----
-title: Transaction.ts
-nav_order: 106
-parent: Modules
----
-
-## Transaction overview
-
----
-
-Table of contents
-
-- [model](#model)
- - [Transaction (class)](#transaction-class)
-
----
-
-# model
-
-## Transaction (class)
-
-Transaction based on Conway CDDL specification
-
-CDDL: transaction =
-[transaction_body, transaction_witness_set, bool, auxiliary_data / nil]
-
-**Signature**
-
-```ts
-export declare class Transaction
-```
-
-Added in v2.0.0
diff --git a/docs/content/docs/modules/TransactionWitnessSet.mdx b/docs/content/docs/modules/TransactionWitnessSet.mdx
deleted file mode 100644
index b998b5a6..00000000
--- a/docs/content/docs/modules/TransactionWitnessSet.mdx
+++ /dev/null
@@ -1,728 +0,0 @@
----
-title: TransactionWitnessSet.ts
-nav_order: 114
-parent: Modules
----
-
-## TransactionWitnessSet overview
-
----
-
-Table of contents
-
-- [arbitrary](#arbitrary)
- - [arbitrary](#arbitrary-1)
-- [constructors](#constructors)
- - [empty](#empty)
- - [fromNativeScripts](#fromnativescripts)
- - [fromVKeyWitnesses](#fromvkeywitnesses)
- - [make](#make)
-- [effect](#effect)
- - [Either (namespace)](#either-namespace)
-- [encoding](#encoding)
- - [toCBORBytes](#tocborbytes)
- - [toCBORHex](#tocborhex)
-- [equality](#equality)
- - [equals](#equals)
-- [errors](#errors)
- - [TransactionWitnessSetError (class)](#transactionwitnessseterror-class)
-- [model](#model)
- - [PlutusScript](#plutusscript)
- - [TransactionWitnessSet (class)](#transactionwitnessset-class)
- - [VKeyWitness (class)](#vkeywitness-class)
-- [parsing](#parsing)
- - [fromCBORBytes](#fromcborbytes)
- - [fromCBORHex](#fromcborhex)
-- [schemas](#schemas)
- - [CDDLSchema](#cddlschema)
- - [FromCDDL](#fromcddl)
-- [utils](#utils)
- - [FromCBORBytes](#fromcborbytes-1)
- - [FromCBORHex](#fromcborhex-1)
- - [PlutusScript (type alias)](#plutusscript-type-alias)
-
----
-
-# arbitrary
-
-## arbitrary
-
-FastCheck arbitrary for generating random TransactionWitnessSet instances.
-
-**Signature**
-
-```ts
-export declare const arbitrary: FastCheck.Arbitrary
-```
-
-Added in v2.0.0
-
-# constructors
-
-## empty
-
-Create an empty TransactionWitnessSet.
-
-**Signature**
-
-```ts
-export declare const empty: () => TransactionWitnessSet
-```
-
-Added in v2.0.0
-
-## fromNativeScripts
-
-Create a TransactionWitnessSet with only native scripts.
-
-**Signature**
-
-```ts
-export declare const fromNativeScripts: (scripts: Array) => TransactionWitnessSet
-```
-
-Added in v2.0.0
-
-## fromVKeyWitnesses
-
-Create a TransactionWitnessSet with only VKey witnesses.
-
-**Signature**
-
-```ts
-export declare const fromVKeyWitnesses: (witnesses: Array) => TransactionWitnessSet
-```
-
-Added in v2.0.0
-
-## make
-
-Smart constructor for TransactionWitnessSet that validates and applies branding.
-
-**Signature**
-
-```ts
-export declare const make: (
- props?:
- | void
- | {
- readonly vkeyWitnesses?: readonly VKeyWitness[] | undefined
- readonly nativeScripts?: readonly NativeScripts.Native[] | undefined
- readonly bootstrapWitnesses?: readonly Bootstrap.BootstrapWitness[] | undefined
- readonly plutusV1Scripts?: readonly PlutusV1.PlutusV1[] | undefined
- readonly plutusData?: readonly PlutusData.Data[] | undefined
- readonly redeemers?: readonly Redeemer.Redeemer[] | undefined
- readonly plutusV2Scripts?: readonly PlutusV2.PlutusV2[] | undefined
- readonly plutusV3Scripts?: readonly PlutusV3.PlutusV3[] | undefined
- }
- | undefined,
- options?: Schema.MakeOptions | undefined
-) => TransactionWitnessSet
-```
-
-Added in v2.0.0
-
-# effect
-
-## Either (namespace)
-
-Effect-based error handling variants for functions that can fail.
-
-Added in v2.0.0
-
-# encoding
-
-## toCBORBytes
-
-Convert a TransactionWitnessSet to CBOR bytes.
-
-**Signature**
-
-```ts
-export declare const toCBORBytes: (input: TransactionWitnessSet, options?: CBOR.CodecOptions) => Uint8Array
-```
-
-Added in v2.0.0
-
-## toCBORHex
-
-Convert a TransactionWitnessSet to CBOR hex string.
-
-**Signature**
-
-```ts
-export declare const toCBORHex: (input: TransactionWitnessSet, options?: CBOR.CodecOptions) => string
-```
-
-Added in v2.0.0
-
-# equality
-
-## equals
-
-Check if two TransactionWitnessSet instances are equal.
-
-**Signature**
-
-```ts
-export declare const equals: (a: TransactionWitnessSet, b: TransactionWitnessSet) => boolean
-```
-
-Added in v2.0.0
-
-# errors
-
-## TransactionWitnessSetError (class)
-
-Error class for TransactionWitnessSet related operations.
-
-**Signature**
-
-```ts
-export declare class TransactionWitnessSetError
-```
-
-Added in v2.0.0
-
-# model
-
-## PlutusScript
-
-Plutus script reference with version tag.
-
-```
-CDDL: plutus_script =
- [ 0, plutus_v1_script ]
-/ [ 1, plutus_v2_script ]
-/ [ 2, plutus_v3_script ]
-```
-
-**Signature**
-
-```ts
-export declare const PlutusScript: Schema.Union<
- [typeof PlutusV1.PlutusV1, typeof PlutusV2.PlutusV2, typeof PlutusV3.PlutusV3]
->
-```
-
-Added in v2.0.0
-
-## TransactionWitnessSet (class)
-
-TransactionWitnessSet based on Conway CDDL specification.
-
-```
-CDDL: transaction_witness_set = {
- ? 0 : nonempty_set
- ? 1 : nonempty_set
- ? 2 : nonempty_set
- ? 3 : nonempty_set
- ? 4 : nonempty_set
- ? 5 : redeemers
- ? 6 : nonempty_set
- ? 7 : nonempty_set
-}
-
-nonempty_set = #6.258([+ a0])/ [+ a0]
-```
-
-**Signature**
-
-```ts
-export declare class TransactionWitnessSet
-```
-
-Added in v2.0.0
-
-## VKeyWitness (class)
-
-VKey witness for Ed25519 signatures.
-
-CDDL: vkeywitness = [ vkey, ed25519_signature ]
-
-**Signature**
-
-```ts
-export declare class VKeyWitness
-```
-
-Added in v2.0.0
-
-# parsing
-
-## fromCBORBytes
-
-Parse a TransactionWitnessSet from CBOR bytes.
-
-**Signature**
-
-```ts
-export declare const fromCBORBytes: (bytes: Uint8Array, options?: CBOR.CodecOptions) => TransactionWitnessSet
-```
-
-Added in v2.0.0
-
-## fromCBORHex
-
-Parse a TransactionWitnessSet from CBOR hex string.
-
-**Signature**
-
-```ts
-export declare const fromCBORHex: (hex: string, options?: CBOR.CodecOptions) => TransactionWitnessSet
-```
-
-Added in v2.0.0
-
-# schemas
-
-## CDDLSchema
-
-CDDL schema for TransactionWitnessSet as struct/record structure.
-Supports both tagged (CBOR tag 258) and untagged arrays for nonempty_set.
-Uses number keys to leverage CBOR Record encoding with proper integer key handling.
-
-**Signature**
-
-```ts
-export declare const CDDLSchema: Schema.Struct<{
- 0: Schema.optional<
- Schema.TaggedStruct<
- "Tag",
- {
- tag: Schema.Literal<[258]>
- value: Schema.Array$>
- }
- >
- >
- 1: Schema.optional<
- Schema.TaggedStruct<
- "Tag",
- {
- tag: Schema.Literal<[258]>
- value: Schema.Array$<
- Schema.Union<
- [
- Schema.Tuple2, typeof Schema.Uint8ArrayFromSelf>,
- Schema.Tuple2<
- Schema.Literal<[1n]>,
- Schema.Array$>
- >,
- Schema.Tuple2<
- Schema.Literal<[2n]>,
- Schema.Array$>
- >,
- Schema.Tuple<
- [
- Schema.Literal<[3n]>,
- typeof Schema.BigIntFromSelf,
- Schema.Array$>
- ]
- >,
- Schema.Tuple2, typeof Schema.BigIntFromSelf>,
- Schema.Tuple2, typeof Schema.BigIntFromSelf>
- ]
- >
- >
- }
- >
- >
- 2: Schema.optional<
- Schema.TaggedStruct<
- "Tag",
- {
- tag: Schema.Literal<[258]>
- value: Schema.Array$<
- Schema.Tuple<
- [
- typeof Schema.Uint8ArrayFromSelf,
- typeof Schema.Uint8ArrayFromSelf,
- typeof Schema.Uint8ArrayFromSelf,
- typeof Schema.Uint8ArrayFromSelf
- ]
- >
- >
- }
- >
- >
- 3: Schema.optional<
- Schema.TaggedStruct<"Tag", { tag: Schema.Literal<[258]>; value: Schema.Array$ }>
- >
- 4: Schema.optional<
- Schema.TaggedStruct<
- "Tag",
- { tag: Schema.Literal<[258]>; value: Schema.Array$> }
- >
- >
- 5: Schema.optional<
- Schema.Array$<
- Schema.Tuple<
- [
- Schema.SchemaClass,
- Schema.SchemaClass,
- Schema.Schema,
- Schema.Tuple2
- ]
- >
- >
- >
- 6: Schema.optional<
- Schema.TaggedStruct<"Tag", { tag: Schema.Literal<[258]>; value: Schema.Array$ }>
- >
- 7: Schema.optional<
- Schema.TaggedStruct<"Tag", { tag: Schema.Literal<[258]>; value: Schema.Array$ }>
- >
-}>
-```
-
-Added in v2.0.0
-
-## FromCDDL
-
-CDDL transformation schema for TransactionWitnessSet.
-
-**Signature**
-
-```ts
-export declare const FromCDDL: Schema.transformOrFail<
- Schema.Struct<{
- 0: Schema.optional<
- Schema.TaggedStruct<
- "Tag",
- {
- tag: Schema.Literal<[258]>
- value: Schema.Array$>
- }
- >
- >
- 1: Schema.optional<
- Schema.TaggedStruct<
- "Tag",
- {
- tag: Schema.Literal<[258]>
- value: Schema.Array$<
- Schema.Union<
- [
- Schema.Tuple2, typeof Schema.Uint8ArrayFromSelf>,
- Schema.Tuple2<
- Schema.Literal<[1n]>,
- Schema.Array$>
- >,
- Schema.Tuple2<
- Schema.Literal<[2n]>,
- Schema.Array$>
- >,
- Schema.Tuple<
- [
- Schema.Literal<[3n]>,
- typeof Schema.BigIntFromSelf,
- Schema.Array$>
- ]
- >,
- Schema.Tuple2, typeof Schema.BigIntFromSelf>,
- Schema.Tuple2, typeof Schema.BigIntFromSelf>
- ]
- >
- >
- }
- >
- >
- 2: Schema.optional<
- Schema.TaggedStruct<
- "Tag",
- {
- tag: Schema.Literal<[258]>
- value: Schema.Array$<
- Schema.Tuple<
- [
- typeof Schema.Uint8ArrayFromSelf,
- typeof Schema.Uint8ArrayFromSelf,
- typeof Schema.Uint8ArrayFromSelf,
- typeof Schema.Uint8ArrayFromSelf
- ]
- >
- >
- }
- >
- >
- 3: Schema.optional<
- Schema.TaggedStruct<"Tag", { tag: Schema.Literal<[258]>; value: Schema.Array$ }>
- >
- 4: Schema.optional<
- Schema.TaggedStruct<
- "Tag",
- { tag: Schema.Literal<[258]>; value: Schema.Array$> }
- >
- >
- 5: Schema.optional<
- Schema.Array$<
- Schema.Tuple<
- [
- Schema.SchemaClass,
- Schema.SchemaClass,
- Schema.Schema,
- Schema.Tuple2
- ]
- >
- >
- >
- 6: Schema.optional<
- Schema.TaggedStruct<"Tag", { tag: Schema.Literal<[258]>; value: Schema.Array$ }>
- >
- 7: Schema.optional<
- Schema.TaggedStruct<"Tag", { tag: Schema.Literal<[258]>; value: Schema.Array$ }>
- >
- }>,
- Schema.SchemaClass,
- never
->
-```
-
-Added in v2.0.0
-
-# utils
-
-## FromCBORBytes
-
-**Signature**
-
-```ts
-export declare const FromCBORBytes: (
- options?: CBOR.CodecOptions
-) => Schema.transform<
- Schema.transformOrFail<
- typeof Schema.Uint8ArrayFromSelf,
- Schema.declare,
- never
- >,
- Schema.transformOrFail<
- Schema.Struct<{
- 0: Schema.optional<
- Schema.TaggedStruct<
- "Tag",
- {
- tag: Schema.Literal<[258]>
- value: Schema.Array$>
- }
- >
- >
- 1: Schema.optional<
- Schema.TaggedStruct<
- "Tag",
- {
- tag: Schema.Literal<[258]>
- value: Schema.Array$<
- Schema.Union<
- [
- Schema.Tuple2, typeof Schema.Uint8ArrayFromSelf>,
- Schema.Tuple2<
- Schema.Literal<[1n]>,
- Schema.Array$>
- >,
- Schema.Tuple2<
- Schema.Literal<[2n]>,
- Schema.Array$>
- >,
- Schema.Tuple<
- [
- Schema.Literal<[3n]>,
- typeof Schema.BigIntFromSelf,
- Schema.Array$>
- ]
- >,
- Schema.Tuple2, typeof Schema.BigIntFromSelf>,
- Schema.Tuple2, typeof Schema.BigIntFromSelf>
- ]
- >
- >
- }
- >
- >
- 2: Schema.optional<
- Schema.TaggedStruct<
- "Tag",
- {
- tag: Schema.Literal<[258]>
- value: Schema.Array$<
- Schema.Tuple<
- [
- typeof Schema.Uint8ArrayFromSelf,
- typeof Schema.Uint8ArrayFromSelf,
- typeof Schema.Uint8ArrayFromSelf,
- typeof Schema.Uint8ArrayFromSelf
- ]
- >
- >
- }
- >
- >
- 3: Schema.optional<
- Schema.TaggedStruct<
- "Tag",
- { tag: Schema.Literal<[258]>; value: Schema.Array$ }
- >
- >
- 4: Schema.optional<
- Schema.TaggedStruct<
- "Tag",
- { tag: Schema.Literal<[258]>; value: Schema.Array$> }
- >
- >
- 5: Schema.optional<
- Schema.Array$<
- Schema.Tuple<
- [
- Schema.SchemaClass,
- Schema.SchemaClass,
- Schema.Schema,
- Schema.Tuple2
- ]
- >
- >
- >
- 6: Schema.optional<
- Schema.TaggedStruct<
- "Tag",
- { tag: Schema.Literal<[258]>; value: Schema.Array$ }
- >
- >
- 7: Schema.optional<
- Schema.TaggedStruct<
- "Tag",
- { tag: Schema.Literal<[258]>; value: Schema.Array$ }
- >
- >
- }>,
- Schema.SchemaClass,
- never
- >
->
-```
-
-## FromCBORHex
-
-**Signature**
-
-```ts
-export declare const FromCBORHex: (
- options?: CBOR.CodecOptions
-) => Schema.transform<
- Schema.transform<
- Schema.transform, Schema.Schema>,
- Schema.transformOrFail<
- typeof Schema.Uint8ArrayFromSelf,
- Schema.declare,
- never
- >
- >,
- Schema.transformOrFail<
- Schema.Struct<{
- 0: Schema.optional<
- Schema.TaggedStruct<
- "Tag",
- {
- tag: Schema.Literal<[258]>
- value: Schema.Array$>
- }
- >
- >
- 1: Schema.optional<
- Schema.TaggedStruct<
- "Tag",
- {
- tag: Schema.Literal<[258]>
- value: Schema.Array$<
- Schema.Union<
- [
- Schema.Tuple2, typeof Schema.Uint8ArrayFromSelf>,
- Schema.Tuple2<
- Schema.Literal<[1n]>,
- Schema.Array$>
- >,
- Schema.Tuple2<
- Schema.Literal<[2n]>,
- Schema.Array$>
- >,
- Schema.Tuple<
- [
- Schema.Literal<[3n]>,
- typeof Schema.BigIntFromSelf,
- Schema.Array$>
- ]
- >,
- Schema.Tuple2, typeof Schema.BigIntFromSelf>,
- Schema.Tuple2, typeof Schema.BigIntFromSelf>
- ]
- >
- >
- }
- >
- >
- 2: Schema.optional<
- Schema.TaggedStruct<
- "Tag",
- {
- tag: Schema.Literal<[258]>
- value: Schema.Array$<
- Schema.Tuple<
- [
- typeof Schema.Uint8ArrayFromSelf,
- typeof Schema.Uint8ArrayFromSelf,
- typeof Schema.Uint8ArrayFromSelf,
- typeof Schema.Uint8ArrayFromSelf
- ]
- >
- >
- }
- >
- >
- 3: Schema.optional<
- Schema.TaggedStruct<
- "Tag",
- { tag: Schema.Literal<[258]>; value: Schema.Array$ }
- >
- >
- 4: Schema.optional<
- Schema.TaggedStruct<
- "Tag",
- { tag: Schema.Literal<[258]>; value: Schema.Array$> }
- >
- >
- 5: Schema.optional<
- Schema.Array$<
- Schema.Tuple<
- [
- Schema.SchemaClass,
- Schema.SchemaClass,
- Schema.Schema,
- Schema.Tuple2
- ]
- >
- >
- >
- 6: Schema.optional<
- Schema.TaggedStruct<
- "Tag",
- { tag: Schema.Literal<[258]>; value: Schema.Array$ }
- >
- >
- 7: Schema.optional<
- Schema.TaggedStruct<
- "Tag",
- { tag: Schema.Literal<[258]>; value: Schema.Array$ }
- >
- >
- }>,
- Schema.SchemaClass,
- never
- >
->
-```
-
-## PlutusScript (type alias)
-
-**Signature**
-
-```ts
-export type PlutusScript = typeof PlutusScript.Type
-```
diff --git a/docs/content/docs/modules/_meta.json b/docs/content/docs/modules/_meta.json
index 538008a6..9e26dfee 100644
--- a/docs/content/docs/modules/_meta.json
+++ b/docs/content/docs/modules/_meta.json
@@ -1,124 +1 @@
-{
- "Address": "Address",
- "AddressDetails": "AddressDetails",
- "AddressTag": "AddressTag",
- "Anchor": "Anchor",
- "AssetName": "AssetName",
- "AuxiliaryData": "AuxiliaryData",
- "AuxiliaryDataHash": "AuxiliaryDataHash",
- "BaseAddress": "BaseAddress",
- "Bech32": "Bech32",
- "BigInt": "BigInt",
- "Bip32PrivateKey": "Bip32PrivateKey",
- "Bip32PublicKey": "Bip32PublicKey",
- "Block": "Block",
- "BlockBodyHash": "BlockBodyHash",
- "BlockHeaderHash": "BlockHeaderHash",
- "BootstrapWitness": "BootstrapWitness",
- "BoundedBytes": "BoundedBytes",
- "ByronAddress": "ByronAddress",
- "Bytes": "Bytes",
- "Bytes128": "Bytes128",
- "Bytes16": "Bytes16",
- "Bytes29": "Bytes29",
- "Bytes32": "Bytes32",
- "Bytes4": "Bytes4",
- "Bytes448": "Bytes448",
- "Bytes57": "Bytes57",
- "Bytes64": "Bytes64",
- "Bytes80": "Bytes80",
- "Bytes96": "Bytes96",
- "CBOR": "CBOR",
- "Certificate": "Certificate",
- "Codec": "Codec",
- "Coin": "Coin",
- "Combinator": "Combinator",
- "CommitteeColdCredential": "CommitteeColdCredential",
- "CommitteeHotCredential": "CommitteeHotCredential",
- "Constitution": "Constitution",
- "CostModel": "CostModel",
- "Credential": "Credential",
- "DRep": "DRep",
- "DRepCredential": "DRepCredential",
- "Data": "Data",
- "DataJson": "DataJson",
- "DatumOption": "DatumOption",
- "DnsName": "DnsName",
- "Ed25519Signature": "Ed25519Signature",
- "EnterpriseAddress": "EnterpriseAddress",
- "EpochNo": "EpochNo",
- "FormatError": "FormatError",
- "Function": "Function",
- "GovernanceAction": "GovernanceAction",
- "Hash28": "Hash28",
- "Header": "Header",
- "HeaderBody": "HeaderBody",
- "IPv4": "IPv4",
- "IPv6": "IPv6",
- "KESVkey": "KESVkey",
- "KesSignature": "KesSignature",
- "KeyHash": "KeyHash",
- "Language": "Language",
- "Metadata": "Metadata",
- "Mint": "Mint",
- "MultiAsset": "MultiAsset",
- "MultiHostName": "MultiHostName",
- "NativeScriptJSON": "NativeScriptJSON",
- "NativeScripts": "NativeScripts",
- "Natural": "Natural",
- "Network": "Network",
- "NetworkId": "NetworkId",
- "NonZeroInt64": "NonZeroInt64",
- "NonnegativeInterval": "NonnegativeInterval",
- "Numeric": "Numeric",
- "OperationalCert": "OperationalCert",
- "PaymentAddress": "PaymentAddress",
- "PlutusV1": "PlutusV1",
- "PlutusV2": "PlutusV2",
- "PlutusV3": "PlutusV3",
- "Pointer": "Pointer",
- "PointerAddress": "PointerAddress",
- "PolicyId": "PolicyId",
- "PoolKeyHash": "PoolKeyHash",
- "PoolMetadata": "PoolMetadata",
- "PoolParams": "PoolParams",
- "Port": "Port",
- "PositiveCoin": "PositiveCoin",
- "PrivateKey": "PrivateKey",
- "ProposalProcedure": "ProposalProcedure",
- "ProposalProcedures": "ProposalProcedures",
- "ProtocolParamUpdate": "ProtocolParamUpdate",
- "ProtocolVersion": "ProtocolVersion",
- "Redeemer": "Redeemer",
- "Relay": "Relay",
- "RewardAccount": "RewardAccount",
- "RewardAddress": "RewardAddress",
- "Script": "Script",
- "ScriptDataHash": "ScriptDataHash",
- "ScriptHash": "ScriptHash",
- "ScriptRef": "ScriptRef",
- "SingleHostAddr": "SingleHostAddr",
- "SingleHostName": "SingleHostName",
- "StakeReference": "StakeReference",
- "TSchema": "TSchema",
- "Text": "Text",
- "Text128": "Text128",
- "Transaction": "Transaction",
- "TransactionBody": "TransactionBody",
- "TransactionHash": "TransactionHash",
- "TransactionIndex": "TransactionIndex",
- "TransactionInput": "TransactionInput",
- "TransactionMetadatum": "TransactionMetadatum",
- "TransactionMetadatumLabels": "TransactionMetadatumLabels",
- "TransactionOutput": "TransactionOutput",
- "TransactionWitnessSet": "TransactionWitnessSet",
- "UnitInterval": "UnitInterval",
- "Url": "Url",
- "VKey": "VKey",
- "Value": "Value",
- "VotingProcedures": "VotingProcedures",
- "VrfCert": "VrfCert",
- "VrfKeyHash": "VrfKeyHash",
- "VrfVkey": "VrfVkey",
- "Withdrawals": "Withdrawals"
-}
\ No newline at end of file
+{}
\ No newline at end of file
diff --git a/docs/content/docs/modules/AddressDetails.mdx b/docs/content/docs/modules/core/AddressDetails.mdx
similarity index 88%
rename from docs/content/docs/modules/AddressDetails.mdx
rename to docs/content/docs/modules/core/AddressDetails.mdx
index 8942fa4d..0cf91a69 100644
--- a/docs/content/docs/modules/AddressDetails.mdx
+++ b/docs/content/docs/modules/core/AddressDetails.mdx
@@ -1,6 +1,6 @@
---
-title: AddressDetails.ts
-nav_order: 2
+title: core/AddressDetails.ts
+nav_order: 1
parent: Modules
---
@@ -57,7 +57,7 @@ Create AddressDetails from an Address.
**Signature**
```ts
-export declare const fromAddress: (address: Address.Address) => AddressDetails
+export declare const fromAddress: (address: AddressEras.AddressEras) => AddressDetails
```
Added in v2.0.0
@@ -178,7 +178,11 @@ export declare class AddressDetailsError
**Signature**
```ts
-export declare const FromBech32: Schema.transformOrFail
+export declare const FromBech32: Schema.transformOrFail<
+ typeof Schema.String,
+ Schema.SchemaClass,
+ never
+>
```
## FromHex
@@ -188,7 +192,7 @@ export declare const FromBech32: Schema.transformOrFail,
- typeof AddressDetails,
+ Schema.SchemaClass,
never
>
```
diff --git a/docs/content/docs/modules/Address.mdx b/docs/content/docs/modules/core/AddressEras.mdx
similarity index 70%
rename from docs/content/docs/modules/Address.mdx
rename to docs/content/docs/modules/core/AddressEras.mdx
index 663c09a1..73ec7192 100644
--- a/docs/content/docs/modules/Address.mdx
+++ b/docs/content/docs/modules/core/AddressEras.mdx
@@ -1,10 +1,10 @@
---
-title: Address.ts
-nav_order: 1
+title: core/AddressEras.ts
+nav_order: 2
parent: Modules
---
-## Address overview
+## AddressEras overview
---
@@ -19,8 +19,8 @@ parent: Modules
- [toBytes](#tobytes)
- [toHex](#tohex)
- [model](#model)
- - [Address](#address)
- - [Address (type alias)](#address-type-alias)
+ - [AddressEras](#addresseras)
+ - [AddressEras (type alias)](#addresseras-type-alias)
- [AddressError (class)](#addresserror-class)
- [parsing](#parsing)
- [fromBech32](#frombech32)
@@ -32,6 +32,7 @@ parent: Modules
- [FromHex](#fromhex-1)
- [utils](#utils)
- [equals](#equals)
+ - [isAddress](#isaddress)
---
@@ -123,14 +124,14 @@ Added in v2.0.0
# model
-## Address
+## AddressEras
Union type representing all possible address types.
**Signature**
```ts
-export declare const Address: Schema.Union<
+export declare const AddressEras: Schema.Union<
[
typeof BaseAddress.BaseAddress,
typeof EnterpriseAddress.EnterpriseAddress,
@@ -143,14 +144,14 @@ export declare const Address: Schema.Union<
Added in v2.0.0
-## Address (type alias)
+## AddressEras (type alias)
Type representing an address.
**Signature**
```ts
-export type Address = typeof Address.Type
+export type AddressEras = typeof AddressEras.Type
```
Added in v2.0.0
@@ -237,14 +238,18 @@ Schema for encoding/decoding addresses as Bech32 strings.
```ts
export declare const FromBech32: Schema.transformOrFail<
typeof Schema.String,
- Schema.Union<
- [
- typeof BaseAddress.BaseAddress,
- typeof EnterpriseAddress.EnterpriseAddress,
- typeof PointerAddress.PointerAddress,
- typeof RewardAccount.RewardAccount,
- typeof ByronAddress.ByronAddress
- ]
+ Schema.SchemaClass<
+ | RewardAccount.RewardAccount
+ | BaseAddress.BaseAddress
+ | EnterpriseAddress.EnterpriseAddress
+ | PointerAddress.PointerAddress
+ | ByronAddress.ByronAddress,
+ | RewardAccount.RewardAccount
+ | BaseAddress.BaseAddress
+ | EnterpriseAddress.EnterpriseAddress
+ | PointerAddress.PointerAddress
+ | ByronAddress.ByronAddress,
+ never
>,
never
>
@@ -261,14 +266,18 @@ Schema for encoding/decoding addresses as bytes.
```ts
export declare const FromBytes: Schema.transformOrFail<
typeof Schema.Uint8ArrayFromSelf,
- Schema.Union<
- [
- typeof BaseAddress.BaseAddress,
- typeof EnterpriseAddress.EnterpriseAddress,
- typeof PointerAddress.PointerAddress,
- typeof RewardAccount.RewardAccount,
- typeof ByronAddress.ByronAddress
- ]
+ Schema.SchemaClass<
+ | RewardAccount.RewardAccount
+ | BaseAddress.BaseAddress
+ | EnterpriseAddress.EnterpriseAddress
+ | PointerAddress.PointerAddress
+ | ByronAddress.ByronAddress,
+ | RewardAccount.RewardAccount
+ | BaseAddress.BaseAddress
+ | EnterpriseAddress.EnterpriseAddress
+ | PointerAddress.PointerAddress
+ | ByronAddress.ByronAddress,
+ never
>,
never
>
@@ -287,14 +296,18 @@ export declare const FromHex: Schema.transform<
Schema.transform, Schema.Schema>,
Schema.transformOrFail<
typeof Schema.Uint8ArrayFromSelf,
- Schema.Union<
- [
- typeof BaseAddress.BaseAddress,
- typeof EnterpriseAddress.EnterpriseAddress,
- typeof PointerAddress.PointerAddress,
- typeof RewardAccount.RewardAccount,
- typeof ByronAddress.ByronAddress
- ]
+ Schema.SchemaClass<
+ | RewardAccount.RewardAccount
+ | BaseAddress.BaseAddress
+ | EnterpriseAddress.EnterpriseAddress
+ | PointerAddress.PointerAddress
+ | ByronAddress.ByronAddress,
+ | RewardAccount.RewardAccount
+ | BaseAddress.BaseAddress
+ | EnterpriseAddress.EnterpriseAddress
+ | PointerAddress.PointerAddress
+ | ByronAddress.ByronAddress,
+ never
>,
never
>
@@ -312,7 +325,23 @@ Checks if two addresses are equal.
**Signature**
```ts
-export declare const equals: (a: Address, b: Address) => boolean
+export declare const equals: (a: AddressEras, b: AddressEras) => boolean
```
Added in v2.0.0
+
+## isAddress
+
+**Signature**
+
+```ts
+export declare const isAddress: (
+ u: unknown,
+ overrideOptions?: ParseOptions | number
+) => u is
+ | RewardAccount.RewardAccount
+ | BaseAddress.BaseAddress
+ | EnterpriseAddress.EnterpriseAddress
+ | PointerAddress.PointerAddress
+ | ByronAddress.ByronAddress
+```
diff --git a/docs/content/docs/modules/core/AddressStructure.mdx b/docs/content/docs/modules/core/AddressStructure.mdx
new file mode 100644
index 00000000..e652b71d
--- /dev/null
+++ b/docs/content/docs/modules/core/AddressStructure.mdx
@@ -0,0 +1,253 @@
+---
+title: core/AddressStructure.ts
+nav_order: 3
+parent: Modules
+---
+
+## AddressStructure overview
+
+Added in v1.0.0
+
+---
+
+Table of contents
+
+- [Arbitrary](#arbitrary)
+ - [arbitrary](#arbitrary-1)
+- [Functions](#functions)
+ - [fromBech32](#frombech32)
+- [Schema](#schema)
+ - [AddressStructure (class)](#addressstructure-class)
+ - [toString (method)](#tostring-method)
+ - [[Symbol.for("nodejs.util.inspect.custom")] (method)](#symbolfornodejsutilinspectcustom-method)
+- [Transformations](#transformations)
+ - [FromBech32](#frombech32-1)
+ - [FromBytes](#frombytes)
+ - [FromHex](#fromhex)
+- [Utils](#utils)
+ - [equals](#equals)
+ - [getNetworkId](#getnetworkid)
+ - [hasStakingCredential](#hasstakingcredential)
+ - [isEnterprise](#isenterprise)
+- [utils](#utils-1)
+ - [AddressStructureError (class)](#addressstructureerror-class)
+ - [Either (namespace)](#either-namespace)
+ - [fromBytes](#frombytes-1)
+ - [fromHex](#fromhex-1)
+ - [toBech32](#tobech32)
+ - [toBytes](#tobytes)
+ - [toHex](#tohex)
+
+---
+
+# Arbitrary
+
+## arbitrary
+
+FastCheck arbitrary generator for testing
+
+**Signature**
+
+```ts
+export declare const arbitrary: FastCheck.Arbitrary
+```
+
+Added in v1.0.0
+
+# Functions
+
+## fromBech32
+
+Sync functions using Function module utilities
+
+**Signature**
+
+```ts
+export declare const fromBech32: (input: string) => AddressStructure
+```
+
+Added in v1.0.0
+
+# Schema
+
+## AddressStructure (class)
+
+**Signature**
+
+```ts
+export declare class AddressStructure
+```
+
+Added in v1.0.0
+
+### toString (method)
+
+**Signature**
+
+```ts
+toString(): string
+```
+
+### [Symbol.for("nodejs.util.inspect.custom")] (method)
+
+**Signature**
+
+```ts
+[Symbol.for("nodejs.util.inspect.custom")](): string
+```
+
+# Transformations
+
+## FromBech32
+
+Transform from Bech32 string to AddressStructure
+
+**Signature**
+
+```ts
+export declare const FromBech32: Schema.transformOrFail<
+ typeof Schema.String,
+ Schema.SchemaClass,
+ never
+>
+```
+
+Added in v1.0.0
+
+## FromBytes
+
+Transform from bytes to AddressStructure
+Handles both BaseAddress (57 bytes) and EnterpriseAddress (29 bytes)
+
+**Signature**
+
+```ts
+export declare const FromBytes: Schema.transformOrFail<
+ Schema.Union<[Schema.filter, Schema.filter]>,
+ Schema.SchemaClass,
+ never
+>
+```
+
+Added in v1.0.0
+
+## FromHex
+
+Transform from hex string to AddressStructure
+
+**Signature**
+
+```ts
+export declare const FromHex: Schema.transform<
+ Schema.transform, Schema.Schema>,
+ Schema.transformOrFail<
+ Schema.Union<[Schema.filter, Schema.filter]>,
+ Schema.SchemaClass,
+ never
+ >
+>
+```
+
+Added in v1.0.0
+
+# Utils
+
+## equals
+
+Check if two AddressStructure instances are equal.
+
+**Signature**
+
+```ts
+export declare const equals: (a: AddressStructure, b: AddressStructure) => boolean
+```
+
+Added in v1.0.0
+
+## getNetworkId
+
+Get network ID from AddressStructure
+
+**Signature**
+
+```ts
+export declare const getNetworkId: (address: AddressStructure) => NetworkId.NetworkId
+```
+
+Added in v1.0.0
+
+## hasStakingCredential
+
+Check if AddressStructure has staking credential (BaseAddress-like)
+
+**Signature**
+
+```ts
+export declare const hasStakingCredential: (address: AddressStructure) => boolean
+```
+
+Added in v1.0.0
+
+## isEnterprise
+
+Check if AddressStructure is enterprise-like (no staking credential)
+
+**Signature**
+
+```ts
+export declare const isEnterprise: (address: AddressStructure) => boolean
+```
+
+Added in v1.0.0
+
+# utils
+
+## AddressStructureError (class)
+
+**Signature**
+
+```ts
+export declare class AddressStructureError
+```
+
+## Either (namespace)
+
+## fromBytes
+
+**Signature**
+
+```ts
+export declare const fromBytes: (input: any) => AddressStructure
+```
+
+## fromHex
+
+**Signature**
+
+```ts
+export declare const fromHex: (input: string) => AddressStructure
+```
+
+## toBech32
+
+**Signature**
+
+```ts
+export declare const toBech32: (input: AddressStructure) => string
+```
+
+## toBytes
+
+**Signature**
+
+```ts
+export declare const toBytes: (input: AddressStructure) => any
+```
+
+## toHex
+
+**Signature**
+
+```ts
+export declare const toHex: (input: AddressStructure) => string
+```
diff --git a/docs/content/docs/modules/AddressTag.mdx b/docs/content/docs/modules/core/AddressTag.mdx
similarity index 94%
rename from docs/content/docs/modules/AddressTag.mdx
rename to docs/content/docs/modules/core/AddressTag.mdx
index 03bbe158..44e5a172 100644
--- a/docs/content/docs/modules/AddressTag.mdx
+++ b/docs/content/docs/modules/core/AddressTag.mdx
@@ -1,6 +1,6 @@
---
-title: AddressTag.ts
-nav_order: 3
+title: core/AddressTag.ts
+nav_order: 4
parent: Modules
---
diff --git a/docs/content/docs/modules/Anchor.mdx b/docs/content/docs/modules/core/Anchor.mdx
similarity index 98%
rename from docs/content/docs/modules/Anchor.mdx
rename to docs/content/docs/modules/core/Anchor.mdx
index 4f678bbc..e7d26960 100644
--- a/docs/content/docs/modules/Anchor.mdx
+++ b/docs/content/docs/modules/core/Anchor.mdx
@@ -1,6 +1,6 @@
---
-title: Anchor.ts
-nav_order: 4
+title: core/Anchor.ts
+nav_order: 5
parent: Modules
---
@@ -60,7 +60,7 @@ Create an Anchor from a URL string and hash string.
```ts
export declare const make: (
- props: { readonly anchorUrl: Url.Url; readonly anchorDataHash: any },
+ props: { readonly anchorUrl: Url.Url; readonly anchorDataHash: Uint8Array },
options?: Schema.MakeOptions | undefined
) => Anchor
```
diff --git a/docs/content/docs/modules/AssetName.mdx b/docs/content/docs/modules/core/AssetName.mdx
similarity index 77%
rename from docs/content/docs/modules/AssetName.mdx
rename to docs/content/docs/modules/core/AssetName.mdx
index fae8ece1..0d3b2566 100644
--- a/docs/content/docs/modules/AssetName.mdx
+++ b/docs/content/docs/modules/core/AssetName.mdx
@@ -1,6 +1,6 @@
---
-title: AssetName.ts
-nav_order: 5
+title: core/AssetName.ts
+nav_order: 6
parent: Modules
---
@@ -25,8 +25,6 @@ parent: Modules
- [AssetNameError (class)](#assetnameerror-class)
- [model](#model)
- [AssetName (class)](#assetname-class)
- - [toJSON (method)](#tojson-method)
- - [toString (method)](#tostring-method)
- [parsing](#parsing)
- [fromBytes](#frombytes)
- [fromHex](#fromhex)
@@ -61,7 +59,10 @@ Smart constructor for AssetName that validates and applies branding.
**Signature**
```ts
-export declare const make: (props: { readonly bytes: any }, options?: Schema.MakeOptions | undefined) => AssetName
+export declare const make: (
+ props: { readonly bytes: Uint8Array },
+ options?: Schema.MakeOptions | undefined
+) => AssetName
```
Added in v2.0.0
@@ -83,7 +84,7 @@ Encode AssetName to bytes.
**Signature**
```ts
-export declare const toBytes: (input: AssetName) => any
+export declare const toBytes: (input: AssetName) => Uint8Array
```
Added in v2.0.0
@@ -143,22 +144,6 @@ export declare class AssetName
Added in v2.0.0
-### toJSON (method)
-
-**Signature**
-
-```ts
-toJSON(): string
-```
-
-### toString (method)
-
-**Signature**
-
-```ts
-toString(): string
-```
-
# parsing
## fromBytes
@@ -168,7 +153,7 @@ Parse AssetName from bytes.
**Signature**
```ts
-export declare const fromBytes: (input: any) => AssetName
+export declare const fromBytes: (input: Uint8Array) => AssetName
```
Added in v2.0.0
@@ -208,7 +193,10 @@ Schema for encoding/decoding AssetName as bytes.
**Signature**
```ts
-export declare const FromBytes: Schema.transform, typeof AssetName>
+export declare const FromBytes: Schema.transform<
+ Schema.SchemaClass,
+ Schema.SchemaClass
+>
```
Added in v2.0.0
@@ -221,8 +209,8 @@ Schema for encoding/decoding AssetName as hex strings.
```ts
export declare const FromHex: Schema.transform<
- Schema.transform, Schema.Schema>,
- Schema.transform, typeof AssetName>
+ Schema.filter>,
+ Schema.transform, Schema.SchemaClass>
>
```
diff --git a/docs/content/docs/modules/AuxiliaryData.mdx b/docs/content/docs/modules/core/AuxiliaryData.mdx
similarity index 58%
rename from docs/content/docs/modules/AuxiliaryData.mdx
rename to docs/content/docs/modules/core/AuxiliaryData.mdx
index ab87163e..c4315236 100644
--- a/docs/content/docs/modules/AuxiliaryData.mdx
+++ b/docs/content/docs/modules/core/AuxiliaryData.mdx
@@ -1,6 +1,6 @@
---
-title: AuxiliaryData.ts
-nav_order: 6
+title: core/AuxiliaryData.ts
+nav_order: 7
parent: Modules
---
@@ -87,7 +87,7 @@ Create a Conway-era AuxiliaryData instance.
```ts
export declare const conway: (input: {
metadata?: Metadata.Metadata
- nativeScripts?: Array
+ nativeScripts?: Array
plutusV1Scripts?: Array
plutusV2Scripts?: Array
plutusV3Scripts?: Array
@@ -129,7 +129,7 @@ Create a ShelleyMA-era AuxiliaryData instance.
```ts
export declare const shelleyMA: (input: {
metadata?: Metadata.Metadata
- nativeScripts?: Array
+ nativeScripts?: Array
}) => AuxiliaryData
```
@@ -338,38 +338,7 @@ export declare const CDDLSchema: Schema.TaggedStruct<
"Tag",
{
tag: Schema.Literal<[259]>
- value: Schema.Struct<{
- 0: Schema.optional>>
- 1: Schema.optional<
- Schema.Array$<
- Schema.Union<
- [
- Schema.Tuple2, typeof Schema.Uint8ArrayFromSelf>,
- Schema.Tuple2<
- Schema.Literal<[1n]>,
- Schema.Array$>
- >,
- Schema.Tuple2<
- Schema.Literal<[2n]>,
- Schema.Array$>
- >,
- Schema.Tuple<
- [
- Schema.Literal<[3n]>,
- typeof Schema.BigIntFromSelf,
- Schema.Array$>
- ]
- >,
- Schema.Tuple2, typeof Schema.BigIntFromSelf>,
- Schema.Tuple2, typeof Schema.BigIntFromSelf>
- ]
- >
- >
- >
- 2: Schema.optional>
- 3: Schema.optional>
- 4: Schema.optional>
- }>
+ value: Schema.MapFromSelf>
}
>
```
@@ -399,40 +368,7 @@ export declare const FromCBORBytes: (
"Tag",
{
tag: Schema.Literal<[259]>
- value: Schema.Struct<{
- 0: Schema.optional<
- Schema.MapFromSelf>
- >
- 1: Schema.optional<
- Schema.Array$<
- Schema.Union<
- [
- Schema.Tuple2, typeof Schema.Uint8ArrayFromSelf>,
- Schema.Tuple2<
- Schema.Literal<[1n]>,
- Schema.Array$>
- >,
- Schema.Tuple2<
- Schema.Literal<[2n]>,
- Schema.Array$>
- >,
- Schema.Tuple<
- [
- Schema.Literal<[3n]>,
- typeof Schema.BigIntFromSelf,
- Schema.Array$>
- ]
- >,
- Schema.Tuple2, typeof Schema.BigIntFromSelf>,
- Schema.Tuple2, typeof Schema.BigIntFromSelf>
- ]
- >
- >
- >
- 2: Schema.optional>
- 3: Schema.optional>
- 4: Schema.optional>
- }>
+ value: Schema.MapFromSelf>
}
>,
Schema.Array$>,
@@ -476,40 +412,7 @@ export declare const FromCBORHex: (
"Tag",
{
tag: Schema.Literal<[259]>
- value: Schema.Struct<{
- 0: Schema.optional<
- Schema.MapFromSelf>
- >
- 1: Schema.optional<
- Schema.Array$<
- Schema.Union<
- [
- Schema.Tuple2, typeof Schema.Uint8ArrayFromSelf>,
- Schema.Tuple2<
- Schema.Literal<[1n]>,
- Schema.Array$>
- >,
- Schema.Tuple2<
- Schema.Literal<[2n]>,
- Schema.Array$>
- >,
- Schema.Tuple<
- [
- Schema.Literal<[3n]>,
- typeof Schema.BigIntFromSelf,
- Schema.Array$>
- ]
- >,
- Schema.Tuple2, typeof Schema.BigIntFromSelf>,
- Schema.Tuple2, typeof Schema.BigIntFromSelf>
- ]
- >
- >
- >
- 2: Schema.optional>
- 3: Schema.optional>
- 4: Schema.optional>
- }>
+ value: Schema.MapFromSelf>
}
>,
Schema.Array$>,
@@ -543,40 +446,7 @@ export declare const FromCDDL: Schema.transformOrFail<
"Tag",
{
tag: Schema.Literal<[259]>
- value: Schema.Struct<{
- 0: Schema.optional<
- Schema.MapFromSelf>
- >
- 1: Schema.optional<
- Schema.Array$<
- Schema.Union<
- [
- Schema.Tuple2, typeof Schema.Uint8ArrayFromSelf>,
- Schema.Tuple2<
- Schema.Literal<[1n]>,
- Schema.Array$>
- >,
- Schema.Tuple2<
- Schema.Literal<[2n]>,
- Schema.Array$>
- >,
- Schema.Tuple<
- [
- Schema.Literal<[3n]>,
- typeof Schema.BigIntFromSelf,
- Schema.Array$>
- ]
- >,
- Schema.Tuple2, typeof Schema.BigIntFromSelf>,
- Schema.Tuple2, typeof Schema.BigIntFromSelf>
- ]
- >
- >
- >
- 2: Schema.optional>
- 3: Schema.optional>
- 4: Schema.optional>
- }>
+ value: Schema.MapFromSelf>
}
>,
Schema.Array$>,
diff --git a/docs/content/docs/modules/AuxiliaryDataHash.mdx b/docs/content/docs/modules/core/AuxiliaryDataHash.mdx
similarity index 79%
rename from docs/content/docs/modules/AuxiliaryDataHash.mdx
rename to docs/content/docs/modules/core/AuxiliaryDataHash.mdx
index c7addf63..8c3225a9 100644
--- a/docs/content/docs/modules/AuxiliaryDataHash.mdx
+++ b/docs/content/docs/modules/core/AuxiliaryDataHash.mdx
@@ -1,6 +1,6 @@
---
-title: AuxiliaryDataHash.ts
-nav_order: 7
+title: core/AuxiliaryDataHash.ts
+nav_order: 8
parent: Modules
---
@@ -68,7 +68,7 @@ Smart constructor for AuxiliaryDataHash that validates and applies branding.
```ts
export declare const make: (
- props: { readonly bytes: any },
+ props: { readonly bytes: Uint8Array },
options?: Schema.MakeOptions | undefined
) => AuxiliaryDataHash
```
@@ -84,7 +84,7 @@ Encode AuxiliaryDataHash to bytes.
**Signature**
```ts
-export declare const toBytes: (input: AuxiliaryDataHash) => any
+export declare const toBytes: (input: AuxiliaryDataHash) => Uint8Array
```
Added in v2.0.0
@@ -153,7 +153,7 @@ Parse AuxiliaryDataHash from bytes.
**Signature**
```ts
-export declare const fromBytes: (input: any) => AuxiliaryDataHash
+export declare const fromBytes: (input: Uint8Array) => AuxiliaryDataHash
```
Added in v2.0.0
@@ -195,8 +195,8 @@ Added in v2.0.0
```ts
export declare const BytesSchema: Schema.transform<
- Schema.filter,
- typeof AuxiliaryDataHash
+ Schema.SchemaClass,
+ Schema.SchemaClass
>
```
@@ -208,8 +208,8 @@ export declare const BytesSchema: Schema.transform<
```ts
export declare const FromBytes: Schema.transform<
- Schema.filter,
- typeof AuxiliaryDataHash
+ Schema.SchemaClass,
+ Schema.SchemaClass
>
```
@@ -219,8 +219,11 @@ export declare const FromBytes: Schema.transform<
```ts
export declare const FromHex: Schema.transform<
- Schema.transform, Schema.Schema>,
- Schema.transform, typeof AuxiliaryDataHash>
+ Schema.filter>,
+ Schema.transform<
+ Schema.SchemaClass,
+ Schema.SchemaClass
+ >
>
```
@@ -230,7 +233,10 @@ export declare const FromHex: Schema.transform<
```ts
export declare const HexSchema: Schema.transform<
- Schema.transform, Schema.Schema>,
- Schema.transform, typeof AuxiliaryDataHash>
+ Schema.filter>,
+ Schema.transform<
+ Schema.SchemaClass,
+ Schema.SchemaClass
+ >
>
```
diff --git a/docs/content/docs/modules/BaseAddress.mdx b/docs/content/docs/modules/core/BaseAddress.mdx
similarity index 86%
rename from docs/content/docs/modules/BaseAddress.mdx
rename to docs/content/docs/modules/core/BaseAddress.mdx
index febb61eb..4ecc4f0c 100644
--- a/docs/content/docs/modules/BaseAddress.mdx
+++ b/docs/content/docs/modules/core/BaseAddress.mdx
@@ -1,6 +1,6 @@
---
-title: BaseAddress.ts
-nav_order: 8
+title: core/BaseAddress.ts
+nav_order: 9
parent: Modules
---
@@ -60,14 +60,14 @@ Smart constructor for BaseAddress.
```ts
export declare const make: (
i: {
+ readonly _tag: "BaseAddress"
readonly networkId: number
readonly stakeCredential:
- | { readonly hash: any; readonly _tag: "KeyHash" }
- | { readonly hash: any; readonly _tag: "ScriptHash" }
- readonly _tag: "BaseAddress"
+ | { readonly _tag: "KeyHash"; readonly hash: string }
+ | { readonly _tag: "ScriptHash"; readonly hash: string }
readonly paymentCredential:
- | { readonly hash: any; readonly _tag: "KeyHash" }
- | { readonly hash: any; readonly _tag: "ScriptHash" }
+ | { readonly _tag: "KeyHash"; readonly hash: string }
+ | { readonly _tag: "ScriptHash"; readonly hash: string }
},
overrideOptions?: ParseOptions
) => BaseAddress
@@ -196,7 +196,7 @@ export declare class BaseAddressError
```ts
export declare const FromBytes: Schema.transformOrFail<
Schema.filter,
- typeof BaseAddress,
+ Schema.SchemaClass,
never
>
```
@@ -208,6 +208,10 @@ export declare const FromBytes: Schema.transformOrFail<
```ts
export declare const FromHex: Schema.transform<
Schema.transform, Schema.Schema>,
- Schema.transformOrFail, typeof BaseAddress, never>
+ Schema.transformOrFail<
+ Schema.filter,
+ Schema.SchemaClass,
+ never
+ >
>
```
diff --git a/docs/content/docs/modules/Bech32.mdx b/docs/content/docs/modules/core/Bech32.mdx
similarity index 96%
rename from docs/content/docs/modules/Bech32.mdx
rename to docs/content/docs/modules/core/Bech32.mdx
index 0d57c177..8ba7cfa5 100644
--- a/docs/content/docs/modules/Bech32.mdx
+++ b/docs/content/docs/modules/core/Bech32.mdx
@@ -1,6 +1,6 @@
---
-title: Bech32.ts
-nav_order: 9
+title: core/Bech32.ts
+nav_order: 10
parent: Modules
---
diff --git a/docs/content/docs/modules/BigInt.mdx b/docs/content/docs/modules/core/BigInt.mdx
similarity index 98%
rename from docs/content/docs/modules/BigInt.mdx
rename to docs/content/docs/modules/core/BigInt.mdx
index 5fa93f72..901ecf54 100644
--- a/docs/content/docs/modules/BigInt.mdx
+++ b/docs/content/docs/modules/core/BigInt.mdx
@@ -1,6 +1,6 @@
---
-title: BigInt.ts
-nav_order: 10
+title: core/BigInt.ts
+nav_order: 11
parent: Modules
---
diff --git a/docs/content/docs/modules/Bip32PrivateKey.mdx b/docs/content/docs/modules/core/Bip32PrivateKey.mdx
similarity index 99%
rename from docs/content/docs/modules/Bip32PrivateKey.mdx
rename to docs/content/docs/modules/core/Bip32PrivateKey.mdx
index 1de59b20..89501cff 100644
--- a/docs/content/docs/modules/Bip32PrivateKey.mdx
+++ b/docs/content/docs/modules/core/Bip32PrivateKey.mdx
@@ -1,6 +1,6 @@
---
-title: Bip32PrivateKey.ts
-nav_order: 11
+title: core/Bip32PrivateKey.ts
+nav_order: 12
parent: Modules
---
diff --git a/docs/content/docs/modules/Bip32PublicKey.mdx b/docs/content/docs/modules/core/Bip32PublicKey.mdx
similarity index 85%
rename from docs/content/docs/modules/Bip32PublicKey.mdx
rename to docs/content/docs/modules/core/Bip32PublicKey.mdx
index fe8cb535..2711f41d 100644
--- a/docs/content/docs/modules/Bip32PublicKey.mdx
+++ b/docs/content/docs/modules/core/Bip32PublicKey.mdx
@@ -1,6 +1,6 @@
---
-title: Bip32PublicKey.ts
-nav_order: 12
+title: core/Bip32PublicKey.ts
+nav_order: 13
parent: Modules
---
@@ -90,7 +90,10 @@ Smart constructor for Bip32PublicKey that validates and applies branding.
**Signature**
```ts
-export declare const make: (props: { readonly bytes: any }, options?: Schema.MakeOptions | undefined) => Bip32PublicKey
+export declare const make: (
+ props: { readonly bytes: Uint8Array },
+ options?: Schema.MakeOptions | undefined
+) => Bip32PublicKey
```
Added in v2.0.0
@@ -126,7 +129,7 @@ Convert a Bip32PublicKey to raw bytes (64 bytes).
**Signature**
```ts
-export declare const toBytes: (input: Bip32PublicKey) => any
+export declare const toBytes: (input: Bip32PublicKey) => Uint8Array
```
Added in v2.0.0
@@ -192,7 +195,7 @@ Create a BIP32 public key from public key and chain code bytes.
**Signature**
```ts
-export declare const fromBytes: (input: any) => Bip32PublicKey
+export declare const fromBytes: (input: Uint8Array) => Bip32PublicKey
```
Added in v2.0.0
@@ -249,7 +252,10 @@ Schema for transforming between Uint8Array and Bip32PublicKey.
**Signature**
```ts
-export declare const FromBytes: Schema.transform, typeof Bip32PublicKey>
+export declare const FromBytes: Schema.transform<
+ Schema.SchemaClass,
+ Schema.SchemaClass
+>
```
Added in v2.0.0
@@ -262,8 +268,11 @@ Schema for transforming between hex string and Bip32PublicKey.
```ts
export declare const FromHex: Schema.transform<
- Schema.transform, Schema.Schema>,
- Schema.transform, typeof Bip32PublicKey>
+ Schema.filter>,
+ Schema.transform<
+ Schema.SchemaClass,
+ Schema.SchemaClass
+ >
>
```
diff --git a/docs/content/docs/modules/Block.mdx b/docs/content/docs/modules/core/Block.mdx
similarity index 96%
rename from docs/content/docs/modules/Block.mdx
rename to docs/content/docs/modules/core/Block.mdx
index 3613135c..707e6cd3 100644
--- a/docs/content/docs/modules/Block.mdx
+++ b/docs/content/docs/modules/core/Block.mdx
@@ -1,6 +1,6 @@
---
-title: Block.ts
-nav_order: 13
+title: core/Block.ts
+nav_order: 14
parent: Modules
---
diff --git a/docs/content/docs/modules/BlockBodyHash.mdx b/docs/content/docs/modules/core/BlockBodyHash.mdx
similarity index 80%
rename from docs/content/docs/modules/BlockBodyHash.mdx
rename to docs/content/docs/modules/core/BlockBodyHash.mdx
index 83aef95a..685aaa9c 100644
--- a/docs/content/docs/modules/BlockBodyHash.mdx
+++ b/docs/content/docs/modules/core/BlockBodyHash.mdx
@@ -1,6 +1,6 @@
---
-title: BlockBodyHash.ts
-nav_order: 14
+title: core/BlockBodyHash.ts
+nav_order: 15
parent: Modules
---
@@ -59,7 +59,10 @@ Smart constructor for BlockBodyHash that validates and applies branding.
**Signature**
```ts
-export declare const make: (props: { readonly bytes: any }, options?: Schema.MakeOptions | undefined) => BlockBodyHash
+export declare const make: (
+ props: { readonly bytes: Uint8Array },
+ options?: Schema.MakeOptions | undefined
+) => BlockBodyHash
```
Added in v2.0.0
@@ -73,7 +76,7 @@ Encode BlockBodyHash to bytes.
**Signature**
```ts
-export declare const toBytes: (input: BlockBodyHash) => any
+export declare const toBytes: (input: BlockBodyHash) => Uint8Array
```
Added in v2.0.0
@@ -143,7 +146,7 @@ Parse BlockBodyHash from bytes.
**Signature**
```ts
-export declare const fromBytes: (input: any) => BlockBodyHash
+export declare const fromBytes: (input: Uint8Array) => BlockBodyHash
```
Added in v2.0.0
@@ -183,7 +186,10 @@ Schema for transforming between Uint8Array and BlockBodyHash.
**Signature**
```ts
-export declare const FromBytes: Schema.transform, typeof BlockBodyHash>
+export declare const FromBytes: Schema.transform<
+ Schema.SchemaClass,
+ Schema.SchemaClass
+>
```
Added in v2.0.0
@@ -196,8 +202,11 @@ Schema for transforming between hex string and BlockBodyHash.
```ts
export declare const FromHex: Schema.transform<
- Schema.transform, Schema.Schema>,
- Schema.transform, typeof BlockBodyHash>
+ Schema.filter>,
+ Schema.transform<
+ Schema.SchemaClass,
+ Schema.SchemaClass
+ >
>
```
diff --git a/docs/content/docs/modules/BlockHeaderHash.mdx b/docs/content/docs/modules/core/BlockHeaderHash.mdx
similarity index 81%
rename from docs/content/docs/modules/BlockHeaderHash.mdx
rename to docs/content/docs/modules/core/BlockHeaderHash.mdx
index 8677aaf6..e5bd6e5b 100644
--- a/docs/content/docs/modules/BlockHeaderHash.mdx
+++ b/docs/content/docs/modules/core/BlockHeaderHash.mdx
@@ -1,6 +1,6 @@
---
-title: BlockHeaderHash.ts
-nav_order: 15
+title: core/BlockHeaderHash.ts
+nav_order: 16
parent: Modules
---
@@ -59,7 +59,10 @@ Smart constructor for BlockHeaderHash.
**Signature**
```ts
-export declare const make: (props: { readonly bytes: any }, options?: Schema.MakeOptions | undefined) => BlockHeaderHash
+export declare const make: (
+ props: { readonly bytes: Uint8Array },
+ options?: Schema.MakeOptions | undefined
+) => BlockHeaderHash
```
Added in v2.0.0
@@ -73,7 +76,7 @@ Encode BlockHeaderHash to bytes.
**Signature**
```ts
-export declare const toBytes: (input: BlockHeaderHash) => any
+export declare const toBytes: (input: BlockHeaderHash) => Uint8Array
```
Added in v2.0.0
@@ -143,7 +146,7 @@ Parse BlockHeaderHash from bytes.
**Signature**
```ts
-export declare const fromBytes: (input: any) => BlockHeaderHash
+export declare const fromBytes: (input: Uint8Array) => BlockHeaderHash
```
Added in v2.0.0
@@ -184,8 +187,8 @@ Schema for transforming between Uint8Array and BlockHeaderHash.
```ts
export declare const FromBytes: Schema.transform<
- Schema.filter,
- typeof BlockHeaderHash
+ Schema.SchemaClass,
+ Schema.SchemaClass
>
```
@@ -199,8 +202,11 @@ Schema for transforming between hex string and BlockHeaderHash.
```ts
export declare const FromHex: Schema.transform<
- Schema.transform, Schema.Schema>,
- Schema.transform, typeof BlockHeaderHash>
+ Schema.filter>,
+ Schema.transform<
+ Schema.SchemaClass,
+ Schema.SchemaClass