51: Add exact-input Jupiter Swap V2 service
This commit is contained in:
+2
@@ -0,0 +1,2 @@
|
||||
schema: spec-driven
|
||||
created: 2026-08-10
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
## Context
|
||||
|
||||
See `proposal.md` for motivation. Issues #48 through #50 already established `SolanaBlockChain` for RPC-backed account and mint metadata, and `SolanaWallet` for isolated transaction signing. The Swap V2 integration must compose these APIs with Jupiter's `/order` and `/execute` endpoints while retaining module-oriented API and implementation package boundaries.
|
||||
|
||||
Jupiter's `/execute` manages transaction landing and can return actual wallet-level totals. Once an execution request has left this process, a transport failure cannot distinguish an unexecuted request from a completed swap whose response was lost.
|
||||
|
||||
## Goals / Non-Goals
|
||||
|
||||
**Goals:**
|
||||
|
||||
- Keep the public API expressed in human-readable ValueTagged amounts while using raw integer units at the Jupiter boundary.
|
||||
- Validate all locally knowable invariants before wallet signing and execution submission.
|
||||
- Share the required order pacing across every reference-implementation instance in one JVM.
|
||||
- Preserve interruption and expose actionable endpoint and response failures through the declared checked exceptions.
|
||||
|
||||
**Non-Goals:**
|
||||
|
||||
- Exact-output swaps, JupiterZ/RFQ, API-key configuration, retries, direct DEX integration, or a reusable throttling subsystem.
|
||||
- Constructing an Evelyn burner or changing existing Solana wallet/blockchain responsibilities.
|
||||
- Adding automated tests in this change; the existing repository verification suites will still be run.
|
||||
|
||||
## Decisions
|
||||
|
||||
### Compose the established Solana APIs
|
||||
|
||||
`JupiterSwapServiceImpl` receives `SolanaBlockChain` and `SolanaWallet`. It obtains the wallet address from the wallet, loads each mint account and supply from the blockchain, and passes Jupiter's Base64 transaction through `SolanaWallet.signTransaction`. Duplicating RPC or signing logic inside the Jupiter implementation was rejected because it would bypass the module contracts established by issues #48 through #50.
|
||||
|
||||
### Detect each mint's token program independently
|
||||
|
||||
For both input and output, the implementation reads the mint account owner and matches it against `SolanaSPLTokenProgram`. It then requests supply metadata with that program. This supports legacy SPL Token and Token-2022 pairs in any combination and prevents assumptions based on one side of the pair.
|
||||
|
||||
### Use exact decimal conversion at the boundary
|
||||
|
||||
The requested `BigDecimal` is shifted by the input mint's decimal count and converted with `toBigIntegerExact()`. Actual raw execution totals are parsed as non-negative integers and shifted left with their respective decimal counts. Rounding was rejected because it would silently change the amount authorized by the caller.
|
||||
|
||||
### Keep wire types private to the reference implementation
|
||||
|
||||
Small private records model only the `/order` and `/execute` fields needed for validation and results. Jackson ignores additional response fields, allowing Jupiter to add metadata without expanding the public API. The stable API package contains only `JupiterSwapService` and `JupiterSwapResult`.
|
||||
|
||||
### Use the keyless Swap V2 endpoint and explicitly exclude JupiterZ
|
||||
|
||||
The reference implementation calls `https://api.jup.ag/swap/v2/order` and `/execute` without API-key headers. Every order includes `swapMode=ExactIn` and `excludeRouters=jupiterz`; relying on a router default was rejected because JupiterZ/RFQ support is explicitly deferred to issue #66.
|
||||
|
||||
### Serialize only order-request starts with a JVM-wide gate
|
||||
|
||||
A private static monitor and monotonic timestamp separate request starts by two seconds. Callers wait interruptibly while holding the gate, and the gate remains held for that order exchange so a delayed thread cannot begin out of its reserved sequence. A generalized limiter was rejected as unnecessary scope, and `/execute` bypasses this gate.
|
||||
|
||||
### Treat execution submission as a non-retry boundary
|
||||
|
||||
The implementation performs one `HttpClient.send` for `/execute` and contains no retry loop around it or the whole swap. Any failure after submission propagates, with a message warning that execution may be unknown and balances must be reloaded. Retrying was rejected because it can duplicate a financially consequential action.
|
||||
|
||||
### Validate response integrity in phases
|
||||
|
||||
Mint and amount checks occur before `/order`; order identity, taker, slippage, Base64 transaction content, and transaction metadata checks occur before signing; execution status and explicit result code, signature, and actual totals are checked before constructing the public result. Numeric wire fields that must distinguish an absent value from zero use nullable DTO types. Non-2xx responses retain status and body context, while malformed JSON is wrapped as `IOException`.
|
||||
|
||||
## Risks / Trade-offs
|
||||
|
||||
- [Jupiter may change its wire schema or endpoint behavior] → Decode a minimal tolerant DTO set, but strictly validate every field used for signing and result construction.
|
||||
- [A submitted execution can succeed despite a local timeout or interruption] → Never retry and report the outcome as unknown so callers reload balances before deciding what to do.
|
||||
- [A slow order exchange serializes later order callers] → This intentionally small implementation-specific gate prioritizes strict JVM-wide start spacing and remains completely separate from execution requests.
|
||||
- [Keyless service availability or limits can change] → Surface HTTP response status/body clearly; API-key configuration remains intentionally out of scope.
|
||||
|
||||
## Migration Plan
|
||||
|
||||
This is an additive API and implementation. Downstream composition can instantiate the reference implementation with its existing blockchain and wallet instances. Rollback consists of removing the new package because no existing API or persisted data is changed.
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
## Why
|
||||
|
||||
Nenjim needs a reusable service that can exchange an exact, human-readable SPL-token amount through Jupiter while preserving the repository's existing Solana wallet and blockchain boundaries. Jupiter Swap V2 supplies the quote, transaction construction, and managed execution required for this flow.
|
||||
|
||||
## What Changes
|
||||
|
||||
- Add a public `JupiterSwapService` API and immutable `JupiterSwapResult` value describing the confirmed transaction and actual amounts spent and received.
|
||||
- Add a reference implementation for exact-input Jupiter Swap V2 `/order`, wallet signing, and `/execute` processing.
|
||||
- Resolve both mint programs and decimal precision through `SolanaBlockChain`, supporting the legacy SPL Token Program and Token-2022.
|
||||
- Validate caller input, mint metadata, order integrity, transaction metadata, and execution results before returning success.
|
||||
- Exclude the `jupiterz` router from every order while JupiterZ/RFQ support remains deferred.
|
||||
- Enforce a small JVM-wide two-second minimum interval between `/order` requests, without delaying `/execute` or automatically retrying submitted executions.
|
||||
|
||||
## Capabilities
|
||||
|
||||
### New Capabilities
|
||||
|
||||
- `jupiter-swap-service`: Exact-input SPL-token swaps through Jupiter Swap V2, including validation, signing, managed execution, throttling, and failure semantics.
|
||||
|
||||
### Modified Capabilities
|
||||
|
||||
None.
|
||||
|
||||
## Impact
|
||||
|
||||
This adds public API types under `com.r35157.libs.jupiter.swap` and a reference implementation under `com.r35157.libs.jupiter.swap.impl.ref`. It depends on the existing `SolanaBlockChain` and `SolanaWallet` APIs and Jupiter's keyless Swap V2 HTTP endpoints; it does not add API-key configuration, Evelyn burning, RFQ/JupiterZ support, or a general throttling framework.
|
||||
+94
@@ -0,0 +1,94 @@
|
||||
## Purpose
|
||||
|
||||
Defines safe exact-input SPL-token swaps through Jupiter Swap V2 using human-readable amounts and an existing Solana wallet.
|
||||
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: Public exact-input swap contract
|
||||
The service SHALL accept distinct input and output SPL mint addresses, a positive human-readable input amount, and a maximum slippage in basis points. It SHALL return the confirmed Solana transaction signature together with the actual human-readable input amount spent and output amount received.
|
||||
|
||||
#### Scenario: Successful exact-input swap
|
||||
- **WHEN** a caller requests a valid exact-input swap that Jupiter executes successfully
|
||||
- **THEN** the result contains the confirmed signature and the actual spent and received amounts converted with their respective mint decimal precision
|
||||
|
||||
#### Scenario: Invalid caller input
|
||||
- **WHEN** either mint is blank, both mints are equal, the amount is null or non-positive, or the maximum slippage is outside 0 through 10000 basis points
|
||||
- **THEN** the service rejects the request before requesting a Jupiter order
|
||||
|
||||
### Requirement: On-chain mint validation and exact amount conversion
|
||||
Before requesting an order, the service SHALL load both mint accounts through the Solana blockchain, require each mint to exist and be owned by either the legacy SPL Token Program or Token-2022, and resolve each mint's decimal precision. The service SHALL convert the input amount exactly to a positive raw integer and SHALL reject values that cannot be represented with the input mint's precision.
|
||||
|
||||
#### Scenario: Supported legacy and Token-2022 mints
|
||||
- **WHEN** the input and output mint accounts are owned by either supported SPL token program and their supplies provide valid decimal precision
|
||||
- **THEN** the service uses those independently resolved precisions for raw request and human-readable result amounts
|
||||
|
||||
#### Scenario: Missing or unsupported mint
|
||||
- **WHEN** either mint account is absent or is owned by an unsupported program
|
||||
- **THEN** the service fails before requesting an order or signing a transaction
|
||||
|
||||
#### Scenario: Fraction smaller than the mint unit
|
||||
- **WHEN** the requested input amount has a non-zero fraction beyond the input mint's decimal precision
|
||||
- **THEN** the service rejects the amount rather than rounding it
|
||||
|
||||
### Requirement: Safe Jupiter order acquisition
|
||||
The service SHALL use Jupiter's keyless Swap V2 order endpoint in `ExactIn` mode with the wallet as taker, the caller's slippage limit, and `excludeRouters=jupiterz`. Across all reference-implementation instances in one JVM, starts of order HTTP requests SHALL be separated by at least two seconds. This limiter SHALL remain local to the implementation and SHALL NOT delay execution requests.
|
||||
|
||||
#### Scenario: Every order excludes JupiterZ
|
||||
- **WHEN** the service requests an order
|
||||
- **THEN** the request identifies the exact input and output mints, raw input amount, wallet taker, exact-input mode, slippage limit, and excludes the `jupiterz` router
|
||||
|
||||
#### Scenario: Concurrent service instances request orders
|
||||
- **WHEN** multiple reference-implementation instances concurrently need Jupiter orders
|
||||
- **THEN** their order HTTP requests begin at least two seconds apart JVM-wide while execution requests remain unthrottled
|
||||
|
||||
#### Scenario: Order wait is interrupted
|
||||
- **WHEN** a caller is interrupted while waiting for its permitted order-request time
|
||||
- **THEN** the service propagates interruption without sending that order request
|
||||
|
||||
### Requirement: Order integrity validation before signing
|
||||
Before signing, the service SHALL require a successful HTTP response containing a well-formed order whose input mint, output mint, raw input amount, exact-input mode, and taker match the request. The returned slippage SHALL be present, valid, and no greater than the caller's maximum. The service SHALL also require a non-blank, valid Base64 unsigned transaction that decodes to at least one byte, a non-blank request identifier, and a positive valid last block height. Any order build error, malformed body, mismatch, or missing required value SHALL fail before signing.
|
||||
|
||||
#### Scenario: Valid matching order
|
||||
- **WHEN** Jupiter returns a well-formed order matching both requested mints, the exact raw input amount, wallet taker, and permitted slippage with all required transaction metadata
|
||||
- **THEN** the service passes the returned unsigned transaction to the configured Solana wallet for signing
|
||||
|
||||
#### Scenario: Mismatching or incomplete order
|
||||
- **WHEN** an order changes a mint, amount, swap mode, or taker; returns missing, invalid, or excessive slippage; or lacks a valid non-empty Base64 transaction, request identifier, or last valid block height
|
||||
- **THEN** the service rejects the order without signing or executing it
|
||||
|
||||
#### Scenario: Jupiter order HTTP or decoding failure
|
||||
- **WHEN** the order endpoint returns a non-success status or malformed JSON
|
||||
- **THEN** the service reports an I/O failure with useful endpoint response context and does not sign a transaction
|
||||
|
||||
### Requirement: Single-attempt managed execution
|
||||
After successful signing, the service SHALL reject a blank signed transaction and submit exactly one Swap V2 execution request containing the signed transaction, order request identifier, and last valid block height. The service SHALL never automatically retry after the execution request has been submitted, because transport failure, timeout, or interruption can leave the execution outcome unknown.
|
||||
|
||||
#### Scenario: Signed transaction is executed once
|
||||
- **WHEN** wallet signing returns a non-blank transaction
|
||||
- **THEN** the service sends one execution request without applying the order limiter
|
||||
|
||||
#### Scenario: Execution outcome is unknown
|
||||
- **WHEN** the execution HTTP exchange times out, is interrupted, loses its response, or otherwise fails after submission
|
||||
- **THEN** the service reports the failure and does not automatically request another order or resubmit execution
|
||||
|
||||
#### Scenario: Blank signed transaction
|
||||
- **WHEN** wallet signing returns a blank serialized transaction
|
||||
- **THEN** the service fails without submitting an execution request
|
||||
|
||||
### Requirement: Confirmed execution result validation
|
||||
The service SHALL return success only when the execution response has status `Success`, explicitly has result code `0`, contains a non-blank transaction signature, and contains positive valid actual total input and output raw amounts. It SHALL convert each actual amount using the independently resolved precision of its mint. Non-success HTTP responses, malformed responses, expired or rejected swaps, failed or contradictory status/code combinations, missing result codes, blank signatures, and invalid result amounts SHALL be reported as failures.
|
||||
|
||||
#### Scenario: Successful execution response
|
||||
- **WHEN** Jupiter reports status `Success`, code `0`, a signature, and valid actual total input and output amounts
|
||||
- **THEN** the service returns those actual amounts in human-readable units and the reported transaction signature
|
||||
|
||||
#### Scenario: Jupiter rejects or fails execution
|
||||
- **WHEN** Jupiter returns a failed status, a missing or non-zero result code, a contradictory status/code combination, expiration, rejection, non-success HTTP status, malformed body, blank signature, or invalid actual amount
|
||||
- **THEN** the service reports an I/O failure and does not represent the swap as successful
|
||||
|
||||
### Requirement: API and implementation separation
|
||||
The stable service interface and result value SHALL reside in the Jupiter swap API package, while HTTP DTOs, endpoint handling, throttling, and the reference implementation SHALL remain in the reference-implementation package.
|
||||
|
||||
#### Scenario: Downstream API consumer
|
||||
- **WHEN** downstream code depends only on the Jupiter swap API package
|
||||
- **THEN** it can invoke swaps and inspect results without depending on private wire DTOs or reference-implementation mechanics
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
## 1. Public API
|
||||
|
||||
- [x] 1.1 Add the ValueTagged `JupiterSwapService` exact-input method with complete public Javadoc and validation/failure contracts.
|
||||
- [x] 1.2 Add the immutable `JupiterSwapResult` value containing the signature and actual human-readable amounts.
|
||||
|
||||
## 2. Reference Implementation
|
||||
|
||||
- [x] 2.1 Add the reference implementation with injected `SolanaBlockChain` and `SolanaWallet` dependencies and private Swap V2 wire DTOs.
|
||||
- [x] 2.2 Validate arguments, both on-chain mint accounts and programs, mint decimal metadata, and exact raw input conversion before order acquisition.
|
||||
- [x] 2.3 Implement keyless `/order` acquisition in exact-input mode, always excluding JupiterZ, with JVM-wide interruptible two-second request-start pacing.
|
||||
- [x] 2.4 Validate order identity and transaction metadata before signing through `SolanaWallet`.
|
||||
- [x] 2.5 Submit a signed transaction once through `/execute`, without retries or order throttling, and validate the confirmed result and actual amounts.
|
||||
|
||||
## 3. Verification
|
||||
|
||||
- [x] 3.1 Compile Detag-generated main and test source sets and run the repository's existing test/check tasks without adding automated tests.
|
||||
- [x] 3.2 Run strict OpenSpec validation and `git diff --check`.
|
||||
- [x] 3.3 Review the complete diff for stale imports, generated-file edits, unrelated refactors, tests, and any implementation that violates the module or retry boundaries.
|
||||
|
||||
## 4. Review Follow-up Validation
|
||||
|
||||
- [x] 4.1 Validate the returned taker and nullable slippage before signing.
|
||||
- [x] 4.2 Base64-decode the returned transaction and reject invalid or empty decoded content before signing.
|
||||
- [x] 4.3 Require both execution status `Success` and an explicit result code `0`.
|
||||
- [x] 4.4 Re-run compilation, Detag, existing tests, strict OpenSpec validation, and diff checks without adding tests.
|
||||
@@ -0,0 +1,96 @@
|
||||
# jupiter-swap-service Specification
|
||||
|
||||
## Purpose
|
||||
|
||||
Defines safe exact-input SPL-token swaps through Jupiter Swap V2 using human-readable amounts and an existing Solana wallet.
|
||||
|
||||
## Requirements
|
||||
|
||||
### Requirement: Public exact-input swap contract
|
||||
The service SHALL accept distinct input and output SPL mint addresses, a positive human-readable input amount, and a maximum slippage in basis points. It SHALL return the confirmed Solana transaction signature together with the actual human-readable input amount spent and output amount received.
|
||||
|
||||
#### Scenario: Successful exact-input swap
|
||||
- **WHEN** a caller requests a valid exact-input swap that Jupiter executes successfully
|
||||
- **THEN** the result contains the confirmed signature and the actual spent and received amounts converted with their respective mint decimal precision
|
||||
|
||||
#### Scenario: Invalid caller input
|
||||
- **WHEN** either mint is blank, both mints are equal, the amount is null or non-positive, or the maximum slippage is outside 0 through 10000 basis points
|
||||
- **THEN** the service rejects the request before requesting a Jupiter order
|
||||
|
||||
### Requirement: On-chain mint validation and exact amount conversion
|
||||
Before requesting an order, the service SHALL load both mint accounts through the Solana blockchain, require each mint to exist and be owned by either the legacy SPL Token Program or Token-2022, and resolve each mint's decimal precision. The service SHALL convert the input amount exactly to a positive raw integer and SHALL reject values that cannot be represented with the input mint's precision.
|
||||
|
||||
#### Scenario: Supported legacy and Token-2022 mints
|
||||
- **WHEN** the input and output mint accounts are owned by either supported SPL token program and their supplies provide valid decimal precision
|
||||
- **THEN** the service uses those independently resolved precisions for raw request and human-readable result amounts
|
||||
|
||||
#### Scenario: Missing or unsupported mint
|
||||
- **WHEN** either mint account is absent or is owned by an unsupported program
|
||||
- **THEN** the service fails before requesting an order or signing a transaction
|
||||
|
||||
#### Scenario: Fraction smaller than the mint unit
|
||||
- **WHEN** the requested input amount has a non-zero fraction beyond the input mint's decimal precision
|
||||
- **THEN** the service rejects the amount rather than rounding it
|
||||
|
||||
### Requirement: Safe Jupiter order acquisition
|
||||
The service SHALL use Jupiter's keyless Swap V2 order endpoint in `ExactIn` mode with the wallet as taker, the caller's slippage limit, and `excludeRouters=jupiterz`. Across all reference-implementation instances in one JVM, starts of order HTTP requests SHALL be separated by at least two seconds. This limiter SHALL remain local to the implementation and SHALL NOT delay execution requests.
|
||||
|
||||
#### Scenario: Every order excludes JupiterZ
|
||||
- **WHEN** the service requests an order
|
||||
- **THEN** the request identifies the exact input and output mints, raw input amount, wallet taker, exact-input mode, slippage limit, and excludes the `jupiterz` router
|
||||
|
||||
#### Scenario: Concurrent service instances request orders
|
||||
- **WHEN** multiple reference-implementation instances concurrently need Jupiter orders
|
||||
- **THEN** their order HTTP requests begin at least two seconds apart JVM-wide while execution requests remain unthrottled
|
||||
|
||||
#### Scenario: Order wait is interrupted
|
||||
- **WHEN** a caller is interrupted while waiting for its permitted order-request time
|
||||
- **THEN** the service propagates interruption without sending that order request
|
||||
|
||||
### Requirement: Order integrity validation before signing
|
||||
Before signing, the service SHALL require a successful HTTP response containing a well-formed order whose input mint, output mint, raw input amount, exact-input mode, and taker match the request. The returned slippage SHALL be present, valid, and no greater than the caller's maximum. The service SHALL also require a non-blank, valid Base64 unsigned transaction that decodes to at least one byte, a non-blank request identifier, and a positive valid last block height. Any order build error, malformed body, mismatch, or missing required value SHALL fail before signing.
|
||||
|
||||
#### Scenario: Valid matching order
|
||||
- **WHEN** Jupiter returns a well-formed order matching both requested mints, the exact raw input amount, wallet taker, and permitted slippage with all required transaction metadata
|
||||
- **THEN** the service passes the returned unsigned transaction to the configured Solana wallet for signing
|
||||
|
||||
#### Scenario: Mismatching or incomplete order
|
||||
- **WHEN** an order changes a mint, amount, swap mode, or taker; returns missing, invalid, or excessive slippage; or lacks a valid non-empty Base64 transaction, request identifier, or last valid block height
|
||||
- **THEN** the service rejects the order without signing or executing it
|
||||
|
||||
#### Scenario: Jupiter order HTTP or decoding failure
|
||||
- **WHEN** the order endpoint returns a non-success status or malformed JSON
|
||||
- **THEN** the service reports an I/O failure with useful endpoint response context and does not sign a transaction
|
||||
|
||||
### Requirement: Single-attempt managed execution
|
||||
After successful signing, the service SHALL reject a blank signed transaction and submit exactly one Swap V2 execution request containing the signed transaction, order request identifier, and last valid block height. The service SHALL never automatically retry after the execution request has been submitted, because transport failure, timeout, or interruption can leave the execution outcome unknown.
|
||||
|
||||
#### Scenario: Signed transaction is executed once
|
||||
- **WHEN** wallet signing returns a non-blank transaction
|
||||
- **THEN** the service sends one execution request without applying the order limiter
|
||||
|
||||
#### Scenario: Execution outcome is unknown
|
||||
- **WHEN** the execution HTTP exchange times out, is interrupted, loses its response, or otherwise fails after submission
|
||||
- **THEN** the service reports the failure and does not automatically request another order or resubmit execution
|
||||
|
||||
#### Scenario: Blank signed transaction
|
||||
- **WHEN** wallet signing returns a blank serialized transaction
|
||||
- **THEN** the service fails without submitting an execution request
|
||||
|
||||
### Requirement: Confirmed execution result validation
|
||||
The service SHALL return success only when the execution response has status `Success`, explicitly has result code `0`, contains a non-blank transaction signature, and contains positive valid actual total input and output raw amounts. It SHALL convert each actual amount using the independently resolved precision of its mint. Non-success HTTP responses, malformed responses, expired or rejected swaps, failed or contradictory status/code combinations, missing result codes, blank signatures, and invalid result amounts SHALL be reported as failures.
|
||||
|
||||
#### Scenario: Successful execution response
|
||||
- **WHEN** Jupiter reports status `Success`, code `0`, a signature, and valid actual total input and output amounts
|
||||
- **THEN** the service returns those actual amounts in human-readable units and the reported transaction signature
|
||||
|
||||
#### Scenario: Jupiter rejects or fails execution
|
||||
- **WHEN** Jupiter returns a failed status, a missing or non-zero result code, a contradictory status/code combination, expiration, rejection, non-success HTTP status, malformed body, blank signature, or invalid actual amount
|
||||
- **THEN** the service reports an I/O failure and does not represent the swap as successful
|
||||
|
||||
### Requirement: API and implementation separation
|
||||
The stable service interface and result value SHALL reside in the Jupiter swap API package, while HTTP DTOs, endpoint handling, throttling, and the reference implementation SHALL remain in the reference-implementation package.
|
||||
|
||||
#### Scenario: Downstream API consumer
|
||||
- **WHEN** downstream code depends only on the Jupiter swap API package
|
||||
- **THEN** it can invoke swaps and inspect results without depending on private wire DTOs or reference-implementation mechanics
|
||||
Reference in New Issue
Block a user