@odatano/x402 0.3.1 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/.env ADDED
File without changes
@@ -46,4 +46,13 @@ jobs:
46
46
  run: npm run build
47
47
 
48
48
  - name: Run tests
49
- run: npm test
49
+ run: npm run test:coverage
50
+
51
+ - name: Upload coverage to Codecov
52
+ # Only upload once per CI run — pick a single Node version.
53
+ if: matrix.node == '22.x'
54
+ uses: codecov/codecov-action@v4
55
+ with:
56
+ files: ./coverage/lcov.info
57
+ token: ${{ secrets.CODECOV_TOKEN }}
58
+ fail_ci_if_error: false
package/CHANGELOG.md CHANGED
@@ -4,6 +4,19 @@ All notable changes to `@odatano/x402` are documented here. The format follows [
4
4
 
5
5
  **Pre-1.0 caveat:** minor versions may include breaking changes until `1.0.0`.
6
6
 
7
+ ## [0.4.0] - 2026-06-19
8
+
9
+ ### Changed (breaking)
10
+ - **Dropped the direct `@emurgo/cardano-serialization-lib-nodejs` (CSL) dependency.** x402 no longer carries a CBOR/transaction library of its own; all tx parsing and building now go through `@odatano/core`'s Buildooor stack (CSL-free since core `1.8.0`). **The `@odatano/core` peer requirement is now `>=1.9.1`** (was `>=1.7.8`). Upgrade `@odatano/core` in the same step.
11
+ - **`buildUnsignedPaymentTx` now delegates to core's tx-builder.** UTxO selection, change, min-ADA and fee are handled by core (Buildooor `keepRelevant`) instead of x402's own CSL coin-selection. Consequences: the v2 `nonceRef` is now the built tx's first input (was x402's largest-UTxO pick); the validity-range upper bound is derived from a POSIX deadline and read back from the built tx, so `ttlSlot` reflects what the builder set (and may be `null` if unset) rather than a value x402 computed. The result shape (`unsignedTxCborHex`, `txHashHex`, `requiredSignerHex`, `nonceRef`, `inputs`, `ttlSlot`) and the `BuildUnsignedTxArgs` (`buyerBech32`, `requirements`, `ttlSlotsFromNow`) are unchanged. This helper is browser-buyer convenience only; it is not on the facilitator/validation path.
12
+
13
+ ### Added
14
+ - `bech32` runtime dependency, for CSL-free Shelley address introspection (`srv/helpers/address.ts`) used to derive `requiredSignerHex` and validate Base/Enterprise key-cred addresses.
15
+
16
+ ### Internal
17
+ - `srv/core/decode.ts` parses via core's pure `parseTransaction`; `srv/bridge.ts` gained typed `parseTransaction` and `buildUnsignedTransfer` wrappers (single coupling point preserved).
18
+ - Test fixtures (`test/fixtures/{constants,build-tx}.ts`) rebuilt on `@harmoniclabs/buildooor` (dev-only); shared `core-parse-mock` stubs the core barrel down to its pure parser so decode-exercising suites don't load uncompiled `@cds-models` sources. Suite: 317 tests across 25 suites, all green.
19
+
7
20
  ## [0.3.1] - 2026-05-15
8
21
 
9
22
  ### Fixed
@@ -35,7 +48,7 @@ All notable changes to `@odatano/x402` are documented here. The format follows [
35
48
  - `PaymentClaim.payTo` , verified recipient address now populated on the claim (was previously only on the requirements entry). Useful for `onAccepted` audit and receipts.
36
49
 
37
50
  ### Changed
38
- - Test count: 177 → 230 (HTTP-server round-trips, multi-accept + dynamic-pricing across `requirements`/`validate`/`verify`/`cap`/`express`, 4 receipts cases, 5 grants cases, 13 client-error cases).
51
+ - Test count: 177 → 236 (HTTP-server round-trips, multi-accept + dynamic-pricing across `requirements`/`validate`/`verify`/`cap`/`express`, 4 receipts cases, 5 grants cases, 13 client-error cases).
39
52
  - `srv/middleware/{cap,express}.ts` now emit `accepts[]` via `buildPaymentRequirementsMulti()`; single-entry callers are unaffected (one-entry array produces a body byte-identical to v0.2).
40
53
  - `srv/facilitator/verify.ts` decodes the envelope BEFORE selecting a requirements entry; multi-accept depends on knowing which `(payTo, asset)` the tx actually credited.
41
54
 
package/LICENSE CHANGED
@@ -1,21 +1,169 @@
1
- MIT License
2
-
3
- Copyright (c) 2026 ODATANO
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
124
+ any Contribution intentionally submitted for inclusion in the Work
125
+ by You to the Licensor shall be under the terms and conditions of
126
+ this License, without any additional terms or conditions.
127
+ Notwithstanding the above, nothing herein shall supersede or modify
128
+ the terms of any separate license agreement you may have executed
129
+ with Licensor regarding such Contributions.
130
+
131
+ 6. Trademarks. This License does not grant permission to use the trade
132
+ names, trademarks, service marks, or product names of the Licensor,
133
+ except as required for reasonable and customary use in describing the
134
+ origin of the Work and reproducing the content of the NOTICE file.
135
+
136
+ 7. Disclaimer of Warranty. Unless required by applicable law or
137
+ agreed to in writing, Licensor provides the Work (and each
138
+ Contributor provides its Contributions) on an "AS IS" BASIS,
139
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
140
+ implied, including, without limitation, any warranties or conditions
141
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
142
+ PARTICULAR PURPOSE. You are solely responsible for determining the
143
+ appropriateness of using or redistributing the Work and assume any
144
+ risks associated with Your exercise of permissions under this License.
145
+
146
+ 8. Limitation of Liability. In no event and under no legal theory,
147
+ whether in tort (including negligence), contract, or otherwise,
148
+ unless required by applicable law (such as deliberate and grossly
149
+ negligent acts) or agreed to in writing, shall any Contributor be
150
+ liable to You for damages, including any direct, indirect, special,
151
+ incidental, or consequential damages of any character arising as a
152
+ result of this License or out of the use or inability to use the
153
+ Work (including but not limited to damages for loss of goodwill,
154
+ work stoppage, computer failure or malfunction, or any and all
155
+ other commercial damages or losses), even if such Contributor
156
+ has been advised of the possibility of such damages.
157
+
158
+ 9. Accepting Warranty or Additional Liability. While redistributing
159
+ the Work or Derivative Works thereof, You may choose to offer,
160
+ and charge a fee for, acceptance of support, warranty, indemnity,
161
+ or other liability obligations and/or rights consistent with this
162
+ License. However, in accepting such obligations, You may act only
163
+ on Your own behalf and on Your sole responsibility, not on behalf
164
+ of any other Contributor, and only if You agree to indemnify,
165
+ defend, and hold each Contributor harmless for any liability
166
+ incurred by, or claims asserted against, such Contributor by reason
167
+ of your accepting any such warranty or additional liability.
168
+
169
+ Copyright [16.05.2026] [Maximilian Weber]
package/README.md CHANGED
@@ -1,9 +1,12 @@
1
+ ![PDATANOX402](datano-x402.png)
1
2
  # @odatano/x402
2
3
 
3
- [![npm](https://img.shields.io/npm/v/@odatano/x402?color=cb3837&logo=npm)](https://www.npmjs.com/package/@odatano/x402)
4
- [![tests](https://github.com/ODATANO/x402/actions/workflows/test.yaml/badge.svg)](https://github.com/ODATANO/x402/actions/workflows/test.yaml)
5
- [![@odatano/core](https://img.shields.io/github/package-json/dependency-version/ODATANO/x402/peer/@odatano/core?label=%40odatano%2Fcore&color=0e7c66)](https://www.npmjs.com/package/@odatano/core)
6
- [![spec](https://img.shields.io/badge/Cardano--x402-v2-blueviolet)](https://github.com/masumi-network/x402-cardano)
4
+ [![Tests](https://github.com/ODATANO/x402/actions/workflows/test.yaml/badge.svg)](https://github.com/ODATANO/x402/actions/workflows/test.yaml)
5
+ [![Coverage](https://codecov.io/gh/ODATANO/x402/branch/main/graph/badge.svg)](https://codecov.io/gh/ODATANO/x402)
6
+ [![@odatano/core](https://img.shields.io/badge/@odatano/core-1.9.1-blue)](https://www.npmjs.com/package/@odatano/core)
7
+ [![npm](https://img.shields.io/npm/v/@odatano/x402?color=blue&logo=npm)](https://www.npmjs.com/package/@odatano/x402)
8
+ [![npm downloads](https://img.shields.io/npm/dt/@odatano/x402?logo=npm&label=downloads&color=blue)](https://www.npmjs.com/package/@odatano/x402)
9
+ [![License](https://img.shields.io/badge/license-Apache%202.0-yellow)](LICENSE)
7
10
 
8
11
  x402 payment gating for SAP CAP applications, backed by Cardano.
9
12
 
@@ -17,7 +20,7 @@ Implements the **Cardano-x402-v2** spec on top of [`@odatano/core`](https://www.
17
20
  npm install @odatano/x402 @odatano/core
18
21
  ```
19
22
 
20
- `@odatano/core` (the Cardano bridge) is a peer dependency. Install whichever version meets `>=1.7.8`.
23
+ `@odatano/core` (the Cardano bridge) is a peer dependency. Install whichever version meets `>=1.9.1`.
21
24
 
22
25
  ## Quick Start
23
26
 
@@ -81,7 +84,7 @@ Configure the Cardano backend in `package.json`:
81
84
 
82
85
  - Node.js 22+
83
86
  - `@sap/cds >= 9` (peer)
84
- - `@odatano/core >= 1.7.8` (peer)
87
+ - `@odatano/core >= 1.9.1` (peer)
85
88
  - `express ^4` (peer), only if you use `x402Middleware`
86
89
  - A Cardano backend reachable via `@odatano/core` (Blockfrost / Koios / Ogmios)
87
90
 
@@ -90,9 +93,9 @@ Configure the Cardano backend in `package.json`:
90
93
  ```bash
91
94
  npm install # Workspace install: covers root + examples/*
92
95
  npm run build # tsc, emits .js/.d.ts next to .ts (outDir: .)
93
- npm test # 177 tests, ~13s
96
+ npm test # 232 tests, ~13s
94
97
  ```
95
98
 
96
99
  ## License
97
100
 
98
- Apache-2.0.
101
+ Apache-2.0 (see [LICENSE](LICENSE))
Binary file
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@odatano/x402",
3
- "version": "0.3.1",
3
+ "version": "0.4.1",
4
4
  "description": "x402 Cardano-v2 payment library for SAP CAP applications",
5
5
  "license": "Apache-2.0",
6
6
  "main": "srv/index.js",
@@ -23,11 +23,11 @@
23
23
  "test:coverage": "jest --coverage"
24
24
  },
25
25
  "dependencies": {
26
- "@emurgo/cardano-serialization-lib-nodejs": "^15.0.3"
26
+ "bech32": "^2.0.0"
27
27
  },
28
28
  "peerDependencies": {
29
29
  "@cap-js/cds-types": ">=0.15",
30
- "@odatano/core": ">=1.7.8",
30
+ "@odatano/core": ">=1.9.1",
31
31
  "@sap/cds": ">=9",
32
32
  "express": "^4"
33
33
  },
@@ -37,10 +37,11 @@
37
37
  }
38
38
  },
39
39
  "devDependencies": {
40
+ "@harmoniclabs/buildooor": "^0.2.6",
40
41
  "@cap-js/cds-typer": "^0.38.0",
41
42
  "@cap-js/cds-types": "^0.15.0",
42
43
  "@cap-js/sqlite": "^2",
43
- "@odatano/core": "^1.7.8",
44
+ "@odatano/core": "^1.9.1",
44
45
  "@odatano/x402": ".",
45
46
  "@sap/cds": "^9",
46
47
  "@sap/cds-dk": "^9.4.3",
@@ -56,4 +57,4 @@
56
57
  "typescript": "^5",
57
58
  "typescript-eslint": "^8.59.3"
58
59
  }
59
- }
60
+ }
@@ -0,0 +1,58 @@
1
+ # @odatano/x402 0.4.0
2
+
3
+ **Drop CSL, route all tx parsing/building through `@odatano/core`.**
4
+
5
+ x402 no longer carries its own CBOR/transaction library. Both former CSL
6
+ call sites now go through `@odatano/core`'s Buildooor stack (CSL-free since
7
+ core `1.8.0`).
8
+
9
+ ## Highlights
10
+
11
+ - **`decode.ts`** parses via core's pure `parseTransaction` instead of CSL
12
+ `Transaction`/`FixedTransaction`. The byte-stable tx hash is preserved.
13
+ - **`buildUnsignedPaymentTx`** delegates UTxO selection, change, min-ADA and
14
+ fee to core's tx-builder. The v2 `nonceRef` and `ttlSlot` are read back
15
+ from the built tx rather than computed locally.
16
+ - **New CSL-free Shelley address parser** (`srv/helpers/address.ts`, via
17
+ `bech32`) derives `requiredSignerHex` and validates Base/Enterprise
18
+ key-cred addresses.
19
+ - **`bridge.ts`** gains typed `parseTransaction` + `buildUnsignedTransfer`
20
+ wrappers, keeping the single coupling point to core.
21
+
22
+ ## Breaking changes
23
+
24
+ - **`@odatano/core` peer requirement raised `>=1.7.8` → `>=1.9.1`.** Upgrade
25
+ core in the same step.
26
+ - **`buildUnsignedPaymentTx` now uses core's coin-selection.** The nonce is
27
+ the built tx's first input (was x402's largest-UTxO pick), and `ttlSlot`
28
+ reflects what the builder set (may be `null`) instead of a value x402
29
+ computed. The result shape (`unsignedTxCborHex`, `txHashHex`,
30
+ `requiredSignerHex`, `nonceRef`, `inputs`, `ttlSlot`) and the
31
+ `BuildUnsignedTxArgs` (`buyerBech32`, `requirements`, `ttlSlotsFromNow`)
32
+ are unchanged. This helper is browser-buyer convenience only; it is not on
33
+ the facilitator/validation path.
34
+
35
+ ## Dependencies
36
+
37
+ - Removed: `@emurgo/cardano-serialization-lib-nodejs` (CSL).
38
+ - Added: `bech32` (runtime), `@harmoniclabs/buildooor` (dev, test fixtures only).
39
+
40
+ ## Internal / tests
41
+
42
+ - Test fixtures (`test/fixtures/{constants,build-tx}.ts`) rebuilt on
43
+ `@harmoniclabs/buildooor`. Shared `core-parse-mock` stubs the core barrel
44
+ down to its pure parser so decode-exercising suites don't load uncompiled
45
+ `@cds-models` sources.
46
+ - **317 tests across 25 suites pass; `tsc` and `eslint` clean.**
47
+
48
+ ## Upgrade notes
49
+
50
+ Bump both packages together:
51
+
52
+ ```bash
53
+ npm install @odatano/x402@^0.4.0 @odatano/core@^1.9.1
54
+ ```
55
+
56
+ If you call `buildUnsignedPaymentTx` directly, re-validate the browser-buyer
57
+ signing path on a testnet (preprod): it is the one flow where an external
58
+ wallet re-hashes the tx that core built.
package/srv/bridge.d.ts CHANGED
@@ -61,5 +61,89 @@ export declare function getCurrentSlot(): Promise<number>;
61
61
  * caller's perspective.
62
62
  */
63
63
  export declare function isUtxoUnspent(txHash: string, outputIndex: number): Promise<boolean>;
64
- export declare const parseTransaction: ((cborHex: string) => unknown) | undefined;
64
+ /** One output of a parsed tx. `assets[].unit` is `policyId+nameHex`. */
65
+ export interface ParsedTxOutput {
66
+ address: string;
67
+ lovelace: string;
68
+ assets: Array<{
69
+ unit: string;
70
+ quantity: string;
71
+ }>;
72
+ datumHash: string | null;
73
+ inlineDatumHex: string | null;
74
+ referenceScriptHex: string | null;
75
+ }
76
+ /** Structured shape returned by `@odatano/core`'s `parseTransaction`. */
77
+ export interface ParsedTx {
78
+ txHash: string;
79
+ network: 'mainnet' | 'testnet' | null;
80
+ inputs: Array<{
81
+ txHash: string;
82
+ outputIndex: number;
83
+ }>;
84
+ outputs: ParsedTxOutput[];
85
+ /** Validity-range lower bound in slots (decimal string) or null. */
86
+ validityStart: string | null;
87
+ /** Validity-range upper bound (TTL) in slots (decimal string) or null. */
88
+ validityEnd: string | null;
89
+ fee: string;
90
+ mint: Array<{
91
+ unit: string;
92
+ quantity: string;
93
+ }>;
94
+ requiredSigners: string[];
95
+ scriptDataHash: string | null;
96
+ witnesses: {
97
+ vkeyCount: number;
98
+ nativeScripts: number;
99
+ plutusScripts: number;
100
+ plutusData: number;
101
+ redeemers: number;
102
+ };
103
+ }
104
+ /**
105
+ * Parse signed-or-unsigned tx CBOR (hex) into structured fields. Pure,
106
+ * no init / no chain call. Throws `X402Error(INVALID_CBOR)` on malformed
107
+ * input so callers in the decode path get a precise, surfaceable code.
108
+ */
109
+ export declare function parseTransaction(cborHex: string): ParsedTx;
110
+ /** Request shape accepted by core's `build{Simple,MultiAsset}Transaction`. */
111
+ export interface CoreTransferReq {
112
+ /** Buyer's bech32 — UTxO source and default change address. */
113
+ senderAddress: string;
114
+ /** Bech32 recipient (`payTo`). */
115
+ recipientAddress: string;
116
+ /** Defaults to `senderAddress`. */
117
+ changeAddress?: string;
118
+ /** Output ADA in lovelace (decimal string). For token outputs this is the riding min-ADA. */
119
+ lovelaceAmount: string;
120
+ /** Native assets on the output. `unit` = `policyId+assetNameHex`. Omit/empty for pure ADA. */
121
+ assets?: Array<{
122
+ unit: string;
123
+ quantity: string;
124
+ }>;
125
+ /** Validity-range upper bound as POSIX ms; core converts to a slot. */
126
+ validityEndMs?: number;
127
+ }
128
+ /** Subset of core's `TxBuildResult` that x402 consumes. */
129
+ export interface CoreTxBuildResult {
130
+ unsignedTxCbor: string;
131
+ txBodyHash: string;
132
+ inputs: Array<{
133
+ txHash: string;
134
+ index: number;
135
+ lovelace: string;
136
+ }>;
137
+ outputs: Array<{
138
+ address: string;
139
+ lovelace: string;
140
+ }>;
141
+ feeLovelace: string;
142
+ }
143
+ /**
144
+ * Build an unsigned transfer tx via core's Buildooor builder. Routes to
145
+ * the multi-asset entry point when `assets` is non-empty (it rejects an
146
+ * empty asset list), otherwise the plain-ADA one.
147
+ */
148
+ export declare function buildUnsignedTransfer(req: CoreTransferReq): Promise<CoreTxBuildResult>;
65
149
  //# sourceMappingURL=bridge.d.ts.map
package/srv/bridge.js CHANGED
@@ -15,7 +15,6 @@
15
15
  * Both are called through directly here; no shim layer remains.
16
16
  */
17
17
  Object.defineProperty(exports, "__esModule", { value: true });
18
- exports.parseTransaction = void 0;
19
18
  exports.init = init;
20
19
  exports.shutdown = shutdown;
21
20
  exports.getUtxosAtAddress = getUtxosAtAddress;
@@ -24,6 +23,8 @@ exports.getProtocolParameters = getProtocolParameters;
24
23
  exports.submitTransaction = submitTransaction;
25
24
  exports.getCurrentSlot = getCurrentSlot;
26
25
  exports.isUtxoUnspent = isUtxoUnspent;
26
+ exports.parseTransaction = parseTransaction;
27
+ exports.buildUnsignedTransfer = buildUnsignedTransfer;
27
28
  const errors_1 = require("./core/errors");
28
29
  // eslint-disable-next-line @typescript-eslint/no-require-imports
29
30
  const od = require('@odatano/core');
@@ -143,10 +144,35 @@ async function isUtxoUnspent(txHash, outputIndex) {
143
144
  await ensureInit();
144
145
  return od.getCardanoClient().isUtxoUnspent(txHash, outputIndex);
145
146
  }
146
- // ─── Re-export pure CBOR utilities (no bridge round-trip) ─────────────
147
- // parseTransaction is exported from @odatano/core's barrel and runs
148
- // entirely client-side. Re-export so x402 users don't need a second
149
- // import for tx introspection. We declare the type loosely (unknown
150
- // CBOR-parsed shape), consumers cast to ODATANO's `ParsedTransaction`
151
- // from `@odatano/core` directly if they need the structured fields.
152
- exports.parseTransaction = od ? od.parseTransaction : undefined;
147
+ const odParseTransaction = od.parseTransaction;
148
+ /**
149
+ * Parse signed-or-unsigned tx CBOR (hex) into structured fields. Pure,
150
+ * no init / no chain call. Throws `X402Error(INVALID_CBOR)` on malformed
151
+ * input so callers in the decode path get a precise, surfaceable code.
152
+ */
153
+ function parseTransaction(cborHex) {
154
+ if (typeof odParseTransaction !== 'function') {
155
+ throw new errors_1.X402Error(errors_1.Codes.BRIDGE_UNAVAILABLE, '@odatano/core does not export parseTransaction (need >= 1.9.1)');
156
+ }
157
+ try {
158
+ return odParseTransaction(cborHex);
159
+ }
160
+ catch (err) {
161
+ throw new errors_1.X402Error(errors_1.Codes.INVALID_CBOR, `transaction CBOR did not decode: ${err?.message ?? err}`);
162
+ }
163
+ }
164
+ /**
165
+ * Build an unsigned transfer tx via core's Buildooor builder. Routes to
166
+ * the multi-asset entry point when `assets` is non-empty (it rejects an
167
+ * empty asset list), otherwise the plain-ADA one.
168
+ */
169
+ async function buildUnsignedTransfer(req) {
170
+ await ensureInit();
171
+ const builder = od.getCardanoTxBuilder();
172
+ // Core's builder expects core's own protocol-parameter shape, so source
173
+ // it from the same client rather than re-deriving it here.
174
+ const params = await od.getCardanoClient().getProtocolParameters();
175
+ return req.assets && req.assets.length > 0
176
+ ? builder.buildMultiAssetTransaction(req, params)
177
+ : builder.buildSimpleAdaTransaction(req, params);
178
+ }
@@ -17,42 +17,9 @@
17
17
  * `DecodedPayment` that downstream `validate.ts` checks against
18
18
  * `PaymentRequirementEntry` (the 6 mandatory checks).
19
19
  */
20
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
21
- if (k2 === undefined) k2 = k;
22
- var desc = Object.getOwnPropertyDescriptor(m, k);
23
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
24
- desc = { enumerable: true, get: function() { return m[k]; } };
25
- }
26
- Object.defineProperty(o, k2, desc);
27
- }) : (function(o, m, k, k2) {
28
- if (k2 === undefined) k2 = k;
29
- o[k2] = m[k];
30
- }));
31
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
32
- Object.defineProperty(o, "default", { enumerable: true, value: v });
33
- }) : function(o, v) {
34
- o["default"] = v;
35
- });
36
- var __importStar = (this && this.__importStar) || (function () {
37
- var ownKeys = function(o) {
38
- ownKeys = Object.getOwnPropertyNames || function (o) {
39
- var ar = [];
40
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
41
- return ar;
42
- };
43
- return ownKeys(o);
44
- };
45
- return function (mod) {
46
- if (mod && mod.__esModule) return mod;
47
- var result = {};
48
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
49
- __setModuleDefault(result, mod);
50
- return result;
51
- };
52
- })();
53
20
  Object.defineProperty(exports, "__esModule", { value: true });
54
21
  exports.decode = decode;
55
- const CSL = __importStar(require("@emurgo/cardano-serialization-lib-nodejs"));
22
+ const bridge_1 = require("../bridge");
56
23
  const errors_1 = require("./errors");
57
24
  const SUPPORTED_VERSION = 2;
58
25
  const SUPPORTED_SCHEME = 'exact';
@@ -68,90 +35,45 @@ function decodeBase64ToBuffer(s, errCode) {
68
35
  }
69
36
  return buf;
70
37
  }
71
- function extractOutputs(txBody) {
72
- const out = txBody.outputs();
73
- const result = [];
74
- for (let i = 0; i < out.len(); i++) {
75
- const o = out.get(i);
76
- const addr = o.address().to_bech32();
77
- const value = o.amount();
78
- const lovelace = value.coin().to_str();
79
- const assets = [];
80
- const ma = value.multiasset();
81
- if (ma) {
82
- const policies = ma.keys();
83
- for (let p = 0; p < policies.len(); p++) {
84
- const policy = policies.get(p);
85
- const policyHex = Buffer.from(policy.to_bytes()).toString('hex').toLowerCase();
86
- const assetMap = ma.get(policy);
87
- if (!assetMap)
88
- continue;
89
- const names = assetMap.keys();
90
- for (let n = 0; n < names.len(); n++) {
91
- const name = names.get(n);
92
- const nameHex = Buffer.from(name.name()).toString('hex').toLowerCase();
93
- const qty = assetMap.get(name);
94
- if (!qty)
95
- continue;
96
- assets.push({
97
- unit: (policyHex + nameHex),
98
- policyId: policyHex,
99
- assetNameHex: nameHex,
100
- quantity: qty.to_str(),
101
- });
102
- }
103
- }
104
- }
105
- result.push({ outputIndex: i, address: addr, lovelace, assets });
106
- }
107
- return result;
108
- }
109
- function extractInputs(txBody) {
110
- const ins = txBody.inputs();
111
- const result = [];
112
- for (let i = 0; i < ins.len(); i++) {
113
- const inp = ins.get(i);
114
- result.push({
115
- txHash: Buffer.from(inp.transaction_id().to_bytes()).toString('hex').toLowerCase(),
116
- outputIndex: inp.index(),
38
+ function extractOutputs(outputs) {
39
+ return outputs.map((o, i) => {
40
+ const assets = o.assets.map(a => {
41
+ // core gives `unit` = policyId(56 hex) + assetNameHex; split it back
42
+ // into the (policyId, assetNameHex) pair x402's validate.ts expects.
43
+ const unit = a.unit.toLowerCase();
44
+ return {
45
+ unit,
46
+ policyId: unit.slice(0, 56),
47
+ assetNameHex: unit.slice(56),
48
+ quantity: a.quantity,
49
+ };
117
50
  });
118
- }
119
- return result;
51
+ return { outputIndex: i, address: o.address, lovelace: o.lovelace, assets };
52
+ });
53
+ }
54
+ function extractInputs(inputs) {
55
+ return inputs.map(inp => ({
56
+ txHash: inp.txHash.toLowerCase(),
57
+ outputIndex: inp.outputIndex,
58
+ }));
120
59
  }
121
60
  /**
122
- * Pull validity range bounds. CSL exposes `ttl()` (upper) since Shelley
123
- * and `validity_start_interval_bignum()` (lower) since Allegra. Both can
124
- * be absent, in which case we return null and the TTL check is skipped
125
- * (per v2 spec: only validate TTL if buyer set one).
61
+ * Convert core's decimal-string slot bounds to numbers. Both bounds can
62
+ * be null, in which case the downstream TTL check is skipped (per v2
63
+ * spec: only validate TTL if the buyer set one). Slots fit comfortably
64
+ * in a JS number (current preprod ~85M, max safe int 9e15).
126
65
  */
127
- function extractValidityRange(txBody) {
128
- let ttlSlot = null;
129
- let validityStartSlot = null;
130
- try {
131
- const ttl = txBody.ttl_bignum();
132
- if (ttl) {
133
- // BigNum → string → number; slots fit comfortably in JS number
134
- // (current preprod ~85M, max safe int 9e15).
135
- ttlSlot = Number(ttl.to_str());
136
- if (!Number.isFinite(ttlSlot))
137
- ttlSlot = null;
138
- }
139
- }
140
- catch {
141
- ttlSlot = null;
142
- }
143
- try {
144
- const start = txBody.validity_start_interval_bignum();
145
- if (start) {
146
- validityStartSlot = Number(start.to_str());
147
- if (!Number.isFinite(validityStartSlot))
148
- validityStartSlot = null;
149
- }
150
- }
151
- catch {
152
- validityStartSlot = null;
153
- }
154
- return { ttlSlot, validityStartSlot };
66
+ function extractValidityRange(parsed) {
67
+ const toSlot = (s) => {
68
+ if (s == null)
69
+ return null;
70
+ const n = Number(s);
71
+ return Number.isFinite(n) ? n : null;
72
+ };
73
+ return {
74
+ ttlSlot: toSlot(parsed.validityEnd),
75
+ validityStartSlot: toSlot(parsed.validityStart),
76
+ };
155
77
  }
156
78
  function parseNonceRef(nonce) {
157
79
  const m = NONCE_RE.exec(nonce);
@@ -200,28 +122,17 @@ function decode(paymentHeader) {
200
122
  if (typeof payload.nonce !== 'string' || payload.nonce.length === 0) {
201
123
  throw new errors_1.X402Error(errors_1.Codes.MISSING_FIELD, 'payload.nonce is required (v2 UTxO-ref)');
202
124
  }
203
- // 3. Tx CBOR → CSL Transaction (parses both `transaction` and `fixed`
204
- // representation; we need both, Transaction for body access,
205
- // FixedTransaction for byte-stable hash).
125
+ // 3. Tx CBOR → structured fields via @odatano/core's pure Buildooor
126
+ // parser. `parseTransaction` throws X402Error(INVALID_CBOR) on
127
+ // malformed input, and its `txHash` (= body.hash) is byte-preserving,
128
+ // the property the old CSL `FixedTransaction` path provided.
206
129
  const txBuf = decodeBase64ToBuffer(payload.transaction, errors_1.Codes.INVALID_CBOR);
207
- let tx;
208
- try {
209
- tx = CSL.Transaction.from_bytes(txBuf);
210
- }
211
- catch {
212
- throw new errors_1.X402Error(errors_1.Codes.INVALID_CBOR, 'transaction CBOR did not decode');
213
- }
130
+ const txCborHex = txBuf.toString('hex');
131
+ const parsed = (0, bridge_1.parseTransaction)(txCborHex);
214
132
  // 4. Diagnostics
215
- const txBody = tx.body();
216
- const wits = tx.witness_set();
217
- const vkeys = wits.vkeys();
218
- const vkeyWitnessCount = vkeys ? vkeys.len() : 0;
219
- const txHashBytes = CSL.FixedTransaction
220
- .from_bytes(txBuf)
221
- .transaction_hash()
222
- .to_bytes();
223
- const txHash = Buffer.from(txHashBytes).toString('hex').toLowerCase();
224
- const validity = extractValidityRange(txBody);
133
+ const txHash = parsed.txHash.toLowerCase();
134
+ const vkeyWitnessCount = parsed.witnesses.vkeyCount;
135
+ const validity = extractValidityRange(parsed);
225
136
  const nonce = parseNonceRef(payload.nonce);
226
137
  const envelope = {
227
138
  x402Version: SUPPORTED_VERSION,
@@ -231,10 +142,10 @@ function decode(paymentHeader) {
231
142
  };
232
143
  return {
233
144
  envelope,
234
- txCborHex: Buffer.from(txBuf).toString('hex'),
145
+ txCborHex,
235
146
  txHash,
236
- outputs: extractOutputs(txBody),
237
- inputs: extractInputs(txBody),
147
+ outputs: extractOutputs(parsed.outputs),
148
+ inputs: extractInputs(parsed.inputs),
238
149
  vkeyWitnessCount,
239
150
  ttlSlot: validity.ttlSlot,
240
151
  validityStartSlot: validity.validityStartSlot,
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Minimal, CSL-free Shelley address introspection.
3
+ *
4
+ * The unsigned-tx builder needs two things from the buyer's bech32
5
+ * address that the (Buildooor-based) @odatano/core builder doesn't hand
6
+ * back: the payment-credential VKey hash (returned to the wallet as the
7
+ * `requiredSignerHex`), and a guard that the address is a Base/Enterprise
8
+ * key-cred address (script-cred and reward/stake addresses can't sign a
9
+ * normal spend). Rather than pull in a CBOR/address library, we decode
10
+ * the bech32 payload and read the 1-byte Shelley header directly.
11
+ *
12
+ * Shelley address header (CIP-19): the top nibble is the address type,
13
+ * the bottom nibble the network id. Payment credential is the 28 bytes
14
+ * following the header. Payment-cred kind by type:
15
+ * 0,2 base / 6 enterprise → key hash (signable)
16
+ * 1,3 base / 7 enterprise → script hash (not signable)
17
+ * 4,5 pointer → unsupported here
18
+ * 14,15 reward/stake → not a payment address
19
+ */
20
+ export interface ParsedPaymentAddress {
21
+ /** Buyer's payment-credential VKey hash (lowercase hex, 56 chars). */
22
+ paymentKeyHashHex: string;
23
+ }
24
+ /**
25
+ * Decode a bech32 Cardano address and extract its payment-credential
26
+ * VKey hash. Throws (with the same messages the old CSL path used) for
27
+ * malformed bech32, script-cred payment, or non-payment (reward/pointer)
28
+ * addresses.
29
+ */
30
+ export declare function parsePaymentAddress(bech32Addr: string): ParsedPaymentAddress;
31
+ //# sourceMappingURL=address.d.ts.map
@@ -0,0 +1,57 @@
1
+ "use strict";
2
+ /**
3
+ * Minimal, CSL-free Shelley address introspection.
4
+ *
5
+ * The unsigned-tx builder needs two things from the buyer's bech32
6
+ * address that the (Buildooor-based) @odatano/core builder doesn't hand
7
+ * back: the payment-credential VKey hash (returned to the wallet as the
8
+ * `requiredSignerHex`), and a guard that the address is a Base/Enterprise
9
+ * key-cred address (script-cred and reward/stake addresses can't sign a
10
+ * normal spend). Rather than pull in a CBOR/address library, we decode
11
+ * the bech32 payload and read the 1-byte Shelley header directly.
12
+ *
13
+ * Shelley address header (CIP-19): the top nibble is the address type,
14
+ * the bottom nibble the network id. Payment credential is the 28 bytes
15
+ * following the header. Payment-cred kind by type:
16
+ * 0,2 base / 6 enterprise → key hash (signable)
17
+ * 1,3 base / 7 enterprise → script hash (not signable)
18
+ * 4,5 pointer → unsupported here
19
+ * 14,15 reward/stake → not a payment address
20
+ */
21
+ Object.defineProperty(exports, "__esModule", { value: true });
22
+ exports.parsePaymentAddress = parsePaymentAddress;
23
+ const bech32_1 = require("bech32");
24
+ const PAYMENT_KEY_HASH_TYPES = new Set([0, 2, 6]); // base-key, base-key/script-stake, enterprise-key
25
+ const SCRIPT_PAYMENT_TYPES = new Set([1, 3, 7]); // base-script*, enterprise-script
26
+ /** Bech32 limit well above Cardano's longest (~103-char mainnet base addr). */
27
+ const BECH32_LIMIT = 1023;
28
+ /**
29
+ * Decode a bech32 Cardano address and extract its payment-credential
30
+ * VKey hash. Throws (with the same messages the old CSL path used) for
31
+ * malformed bech32, script-cred payment, or non-payment (reward/pointer)
32
+ * addresses.
33
+ */
34
+ function parsePaymentAddress(bech32Addr) {
35
+ let bytes;
36
+ try {
37
+ const decoded = bech32_1.bech32.decode(bech32Addr, BECH32_LIMIT);
38
+ bytes = Uint8Array.from(bech32_1.bech32.fromWords(decoded.words));
39
+ }
40
+ catch {
41
+ throw new Error(`buildUnsignedPaymentTx: invalid bech32 address: ${bech32Addr}`);
42
+ }
43
+ // header (1 byte) + 28-byte payment credential.
44
+ if (bytes.length < 29) {
45
+ throw new Error(`buildUnsignedPaymentTx: invalid bech32 address: ${bech32Addr}`);
46
+ }
47
+ const addrType = bytes[0] >> 4;
48
+ if (SCRIPT_PAYMENT_TYPES.has(addrType)) {
49
+ throw new Error('buildUnsignedPaymentTx: payment credential must be a VKey hash, not a script');
50
+ }
51
+ if (!PAYMENT_KEY_HASH_TYPES.has(addrType)) {
52
+ // pointer (4,5), reward/stake (14,15), Byron-via-bech32, etc.
53
+ throw new Error('buildUnsignedPaymentTx: only Base / Enterprise addresses are supported');
54
+ }
55
+ const keyHash = bytes.slice(1, 29);
56
+ return { paymentKeyHashHex: Buffer.from(keyHash).toString('hex') };
57
+ }
@@ -1,26 +1,27 @@
1
1
  /**
2
2
  * Server-side unsigned payment-tx builder for browser-buyer flows.
3
3
  *
4
- * The browser knows the buyer's bech32 (via CIP-30) but not the
5
- * signing keys. Replicating CSL coin-selection + protocol-params
6
- * fetch in the browser would mean shipping ~2 MB of WASM. So we
7
- * build the unsigned tx server-side, return the CBOR for the
8
- * wallet to sign, and let the browser submit the signed CBOR as
9
- * `payload.transaction` in the PAYMENT-SIGNATURE envelope.
4
+ * The browser knows the buyer's bech32 (via CIP-30) but not the signing
5
+ * keys, and shipping coin-selection + protocol-params logic to the
6
+ * browser would mean megabytes of WASM. So we build the unsigned tx
7
+ * server-side, return the CBOR for the wallet to sign, and let the
8
+ * browser submit the signed CBOR as `payload.transaction` in the
9
+ * PAYMENT-SIGNATURE envelope.
10
10
  *
11
- * Diff vs v1 of CHAINFEED's same-named helper:
12
- * - Asset-agnostic, parses requirements.asset as a v2 string
13
- * (`'lovelace'` or `'<policy>.<nameHex>'`).
14
- * - Returns `nonceRef` alongside the unsigned CBOR, the server
15
- * picks one of the buyer's chosen inputs as the v2 nonce UTxO,
16
- * so the browser doesn't have to reason about it.
11
+ * The build itself (UTxO fetch, coin selection, change, min-ADA, fee) is
12
+ * delegated wholesale to `@odatano/core`'s Buildooor builder via
13
+ * `bridge.buildUnsignedTransfer`, x402 owns no tx-construction library.
14
+ * We add only the two x402-specific pieces core doesn't:
15
+ * - the `requiredSignerHex` (buyer's payment-cred VKey hash), parsed
16
+ * from the bech32 address (see `./address`);
17
+ * - the v2 `nonceRef`, read back from the built tx's first input so it
18
+ * is guaranteed to reference a UTxO the tx actually spends.
17
19
  *
18
- * **x402-spec deviation:** strict v2 has the buyer construct the
19
- * tx end-to-end. This helper is a "self-facilitator" pattern: the
20
- * server builds, the buyer signs, the server still validates the
21
- * signed tx against requirements before settling. Same security
22
- * model (the buyer's signature still authorises the spend), easier
23
- * browser ergonomics.
20
+ * **x402-spec deviation:** strict v2 has the buyer construct the tx
21
+ * end-to-end. This is the "self-facilitator" pattern: the server builds,
22
+ * the buyer signs, the server still validates the signed tx against
23
+ * requirements before settling. Same security model (the buyer's
24
+ * signature still authorises the spend), easier browser ergonomics.
24
25
  */
25
26
  import type { PaymentRequirementEntry } from '../core/types';
26
27
  export interface BuildUnsignedTxArgs {
@@ -29,7 +30,7 @@ export interface BuildUnsignedTxArgs {
29
30
  /** A single accepts[] entry, call `flatRequirements(body)` to extract. */
30
31
  requirements: PaymentRequirementEntry;
31
32
  /**
32
- * Optional TTL in slots from "now" (= current chain tip slot).
33
+ * Optional TTL in slots from "now" (= current chain tip).
33
34
  * Default 1800 (≈30 min on Cardano's 1s-slot networks).
34
35
  */
35
36
  ttlSlotsFromNow?: number;
@@ -41,16 +42,16 @@ export interface UnsignedTxResult {
41
42
  txHashHex: string;
42
43
  /** Buyer's payment-cred VKey hash, wallet must sign for this. */
43
44
  requiredSignerHex: string;
44
- /** v2 nonce reference `<txHash>#<index>`, picked from the buyer's chosen inputs. */
45
+ /** v2 nonce reference `<txHash>#<index>`, the tx's first spent input. */
45
46
  nonceRef: string;
46
- /** Echo of the inputs chosen so the buyer's UI can show "spends these UTxOs". */
47
+ /** Echo of the inputs the builder selected so the buyer's UI can show "spends these UTxOs". */
47
48
  inputs: Array<{
48
49
  txHash: string;
49
50
  outputIndex: number;
50
51
  lovelace: string;
51
52
  }>;
52
- /** TTL slot used for the validity-range upper bound. */
53
- ttlSlot: number;
53
+ /** TTL slot used for the validity-range upper bound (as set by the builder). */
54
+ ttlSlot: number | null;
54
55
  }
55
56
  export declare function buildUnsignedPaymentTx(args: BuildUnsignedTxArgs): Promise<UnsignedTxResult>;
56
57
  //# sourceMappingURL=build-unsigned-tx.d.ts.map
@@ -2,26 +2,27 @@
2
2
  /**
3
3
  * Server-side unsigned payment-tx builder for browser-buyer flows.
4
4
  *
5
- * The browser knows the buyer's bech32 (via CIP-30) but not the
6
- * signing keys. Replicating CSL coin-selection + protocol-params
7
- * fetch in the browser would mean shipping ~2 MB of WASM. So we
8
- * build the unsigned tx server-side, return the CBOR for the
9
- * wallet to sign, and let the browser submit the signed CBOR as
10
- * `payload.transaction` in the PAYMENT-SIGNATURE envelope.
5
+ * The browser knows the buyer's bech32 (via CIP-30) but not the signing
6
+ * keys, and shipping coin-selection + protocol-params logic to the
7
+ * browser would mean megabytes of WASM. So we build the unsigned tx
8
+ * server-side, return the CBOR for the wallet to sign, and let the
9
+ * browser submit the signed CBOR as `payload.transaction` in the
10
+ * PAYMENT-SIGNATURE envelope.
11
11
  *
12
- * Diff vs v1 of CHAINFEED's same-named helper:
13
- * - Asset-agnostic, parses requirements.asset as a v2 string
14
- * (`'lovelace'` or `'<policy>.<nameHex>'`).
15
- * - Returns `nonceRef` alongside the unsigned CBOR, the server
16
- * picks one of the buyer's chosen inputs as the v2 nonce UTxO,
17
- * so the browser doesn't have to reason about it.
12
+ * The build itself (UTxO fetch, coin selection, change, min-ADA, fee) is
13
+ * delegated wholesale to `@odatano/core`'s Buildooor builder via
14
+ * `bridge.buildUnsignedTransfer`, x402 owns no tx-construction library.
15
+ * We add only the two x402-specific pieces core doesn't:
16
+ * - the `requiredSignerHex` (buyer's payment-cred VKey hash), parsed
17
+ * from the bech32 address (see `./address`);
18
+ * - the v2 `nonceRef`, read back from the built tx's first input so it
19
+ * is guaranteed to reference a UTxO the tx actually spends.
18
20
  *
19
- * **x402-spec deviation:** strict v2 has the buyer construct the
20
- * tx end-to-end. This helper is a "self-facilitator" pattern: the
21
- * server builds, the buyer signs, the server still validates the
22
- * signed tx against requirements before settling. Same security
23
- * model (the buyer's signature still authorises the spend), easier
24
- * browser ergonomics.
21
+ * **x402-spec deviation:** strict v2 has the buyer construct the tx
22
+ * end-to-end. This is the "self-facilitator" pattern: the server builds,
23
+ * the buyer signs, the server still validates the signed tx against
24
+ * requirements before settling. Same security model (the buyer's
25
+ * signature still authorises the spend), easier browser ergonomics.
25
26
  */
26
27
  var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
27
28
  if (k2 === undefined) k2 = k;
@@ -58,146 +59,60 @@ var __importStar = (this && this.__importStar) || (function () {
58
59
  })();
59
60
  Object.defineProperty(exports, "__esModule", { value: true });
60
61
  exports.buildUnsignedPaymentTx = buildUnsignedPaymentTx;
61
- const CSL = __importStar(require("@emurgo/cardano-serialization-lib-nodejs"));
62
62
  const bridge = __importStar(require("../bridge"));
63
63
  const asset_1 = require("../core/asset");
64
+ const address_1 = require("./address");
65
+ /** ADA (lovelace) attached to a native-asset output to satisfy min-ADA. */
66
+ const TOKEN_OUTPUT_LOVELACE = 2000000n;
67
+ /** Cardano networks run 1-second slots, so TTL slots ≈ TTL seconds. */
68
+ const SLOT_MS = 1000;
64
69
  async function buildUnsignedPaymentTx(args) {
65
70
  const { buyerBech32, requirements } = args;
66
- // 1. Decode buyer address; derive payment-cred VKey hash.
67
- let buyerAddress;
68
- try {
69
- buyerAddress = CSL.Address.from_bech32(buyerBech32);
70
- }
71
- catch {
72
- throw new Error(`buildUnsignedPaymentTx: invalid bech32 address: ${buyerBech32}`);
73
- }
74
- const baseAddr = CSL.BaseAddress.from_address(buyerAddress);
75
- const enterpriseAddr = CSL.EnterpriseAddress.from_address(buyerAddress);
76
- const paymentCred = baseAddr?.payment_cred() ?? enterpriseAddr?.payment_cred();
77
- if (!paymentCred) {
78
- throw new Error('buildUnsignedPaymentTx: only Base / Enterprise addresses are supported');
79
- }
80
- const buyerVkeyHash = paymentCred.to_keyhash();
81
- if (!buyerVkeyHash) {
82
- throw new Error('buildUnsignedPaymentTx: payment credential must be a VKey hash, not a script');
83
- }
84
- const requiredSignerHex = Buffer.from(buyerVkeyHash.to_bytes()).toString('hex');
85
- // 2. Fetch buyer UTxOs + protocol params + current slot in parallel.
86
- const [utxos, params, currentSlot] = await Promise.all([
87
- bridge.getUtxosAtAddress(buyerBech32),
88
- bridge.getProtocolParameters(),
89
- bridge.getCurrentSlot(),
90
- ]);
91
- if (utxos.length === 0) {
92
- throw new Error(`buildUnsignedPaymentTx: no UTxOs at ${buyerBech32}`);
93
- }
94
- // 3. Pick the input(s) for coin-selection.
95
- // Strategy:
96
- // - If lovelace asset: pick largest-ADA UTxO; add second-largest as padding if first < 3 ADA.
97
- // - If native asset: pick largest-ADA UTxO that ALSO holds enough of the asset;
98
- // add padding the same way.
71
+ // 1. Validate the buyer address shape and derive the required signer.
72
+ // Throws for bad bech32 / script-cred / non-payment addresses.
73
+ const { paymentKeyHashHex } = (0, address_1.parsePaymentAddress)(buyerBech32);
74
+ // 2. Translate the v2 requirement into a core transfer request.
99
75
  const parsedAsset = (0, asset_1.parseAsset)(requirements.asset);
100
76
  const required = BigInt(requirements.amount);
101
- const sortedByAda = [...utxos].sort((a, b) => (BigInt(b.lovelace) - BigInt(a.lovelace) > 0n ? 1 : -1));
102
- let inputs;
103
- if (parsedAsset.isLovelace) {
104
- // ADA payment: largest UTxO must cover required + fees + min-ADA change.
105
- // Heuristic: required + 2_000_000 (≈2 ADA fee+change headroom).
106
- const headroom = required + 2000000n;
107
- const ok = sortedByAda.find(u => BigInt(u.lovelace) >= headroom);
108
- if (!ok) {
109
- throw new Error(`buildUnsignedPaymentTx: no UTxO at ${buyerBech32} with ≥ ${headroom} lovelace`);
110
- }
111
- inputs = [ok];
112
- }
113
- else {
114
- const candidates = sortedByAda.filter(u => u.assets.some(a => a.unit === parsedAsset.unit && BigInt(a.quantity) >= required));
115
- if (candidates.length === 0) {
116
- throw new Error(`buildUnsignedPaymentTx: no UTxO at ${buyerBech32} holds ≥ ${required} of ${parsedAsset.unit}`);
77
+ const validityEndMs = Date.now() + (args.ttlSlotsFromNow ?? 1800) * SLOT_MS;
78
+ const req = parsedAsset.isLovelace
79
+ ? {
80
+ senderAddress: buyerBech32,
81
+ recipientAddress: requirements.payTo,
82
+ changeAddress: buyerBech32,
83
+ lovelaceAmount: required.toString(),
84
+ validityEndMs,
117
85
  }
118
- const tokenInput = candidates[0];
119
- inputs = [tokenInput];
120
- if (BigInt(tokenInput.lovelace) < 3000000n) {
121
- const padding = sortedByAda.find(u => u !== tokenInput);
122
- if (!padding) {
123
- throw new Error('buildUnsignedPaymentTx: no second UTxO available to fund fees');
124
- }
125
- inputs.push(padding);
126
- }
127
- }
128
- // 4. Configure CSL TransactionBuilder from live protocol params.
129
- const builder = CSL.TransactionBuilder.new(CSL.TransactionBuilderConfigBuilder.new()
130
- .fee_algo(CSL.LinearFee.new(CSL.BigNum.from_str(String(params.minFeeA)), CSL.BigNum.from_str(String(params.minFeeB))))
131
- .pool_deposit(CSL.BigNum.from_str(String(params.poolDeposit)))
132
- .key_deposit(CSL.BigNum.from_str(String(params.keyDeposit)))
133
- .max_value_size(Number(params.maxValSize))
134
- .max_tx_size(Number(params.maxTxSize))
135
- .coins_per_utxo_byte(CSL.BigNum.from_str(String(params.coinsPerUtxoSize)))
136
- .build());
137
- // 5. Wire inputs (preserve full multi-asset payload).
138
- for (const u of inputs) {
139
- const inMa = CSL.MultiAsset.new();
140
- const byPolicy = new Map();
141
- for (const a of u.assets) {
142
- const arr = byPolicy.get(a.policyId) ?? [];
143
- arr.push({ name: a.assetNameHex, qty: a.quantity });
144
- byPolicy.set(a.policyId, arr);
145
- }
146
- for (const [policyHex, items] of byPolicy) {
147
- const policyHash = CSL.ScriptHash.from_bytes(Buffer.from(policyHex, 'hex'));
148
- const assetMap = CSL.Assets.new();
149
- for (const { name, qty } of items) {
150
- assetMap.insert(CSL.AssetName.new(Buffer.from(name, 'hex')), CSL.BigNum.from_str(qty));
151
- }
152
- inMa.insert(policyHash, assetMap);
153
- }
154
- const inV = CSL.Value.new(CSL.BigNum.from_str(u.lovelace));
155
- if (u.assets.length)
156
- inV.set_multiasset(inMa);
157
- builder.add_key_input(buyerVkeyHash, CSL.TransactionInput.new(CSL.TransactionHash.from_bytes(Buffer.from(u.txHash, 'hex')), u.outputIndex), inV);
158
- }
159
- // 6. Output to payTo.
160
- const payToAddr = CSL.Address.from_bech32(requirements.payTo);
161
- let payOut;
162
- if (parsedAsset.isLovelace) {
163
- const v = CSL.Value.new(CSL.BigNum.from_str(required.toString()));
164
- payOut = CSL.TransactionOutput.new(payToAddr, v);
165
- }
166
- else {
167
- const payOutMa = CSL.MultiAsset.new();
168
- const payAssets = CSL.Assets.new();
169
- const policyHash = CSL.ScriptHash.from_bytes(Buffer.from(parsedAsset.policyId, 'hex'));
170
- payAssets.insert(CSL.AssetName.new(Buffer.from(parsedAsset.assetNameHex, 'hex')), CSL.BigNum.from_str(required.toString()));
171
- payOutMa.insert(policyHash, payAssets);
172
- const payOutV = CSL.Value.new(CSL.BigNum.from_str('0'));
173
- payOutV.set_multiasset(payOutMa);
174
- const provisional = CSL.TransactionOutput.new(payToAddr, payOutV);
175
- const minAda = CSL.min_ada_for_output(provisional, CSL.DataCost.new_coins_per_byte(CSL.BigNum.from_str(String(params.coinsPerUtxoSize))));
176
- payOutV.set_coin(minAda);
177
- payOut = CSL.TransactionOutput.new(payToAddr, payOutV);
86
+ : {
87
+ senderAddress: buyerBech32,
88
+ recipientAddress: requirements.payTo,
89
+ changeAddress: buyerBech32,
90
+ // Native-asset output rides a fixed min-ADA; change reconciles the rest.
91
+ lovelaceAmount: TOKEN_OUTPUT_LOVELACE.toString(),
92
+ assets: [{ unit: parsedAsset.unit, quantity: required.toString() }],
93
+ validityEndMs,
94
+ };
95
+ // 3. Delegate the build (UTxO fetch + coin selection + change + fee).
96
+ const result = await bridge.buildUnsignedTransfer(req);
97
+ // 4. Read the built tx back to recover the v2 nonce (first spent input,
98
+ // guaranteed present) and the TTL slot the builder actually set.
99
+ const parsed = bridge.parseTransaction(result.unsignedTxCbor);
100
+ const nonceInput = parsed.inputs[0];
101
+ if (!nonceInput) {
102
+ throw new Error('buildUnsignedPaymentTx: builder produced a tx with no inputs');
178
103
  }
179
- builder.add_output(payOut);
180
- // 7. TTL (slot of upper bound). Default 1800 slots ≈ 30 min.
181
- const ttlSlot = currentSlot + (args.ttlSlotsFromNow ?? 1800);
182
- builder.set_ttl_bignum(CSL.BigNum.from_str(String(ttlSlot)));
183
- // 8. Change to buyer.
184
- builder.add_change_if_needed(buyerAddress);
185
- // 9. Build body, compute hash, return unsigned tx.
186
- const txBody = builder.build();
187
- const txHash = CSL.FixedTransaction.new_from_body_bytes(txBody.to_bytes()).transaction_hash();
188
- const emptyWits = CSL.TransactionWitnessSet.new();
189
- const unsigned = CSL.Transaction.new(txBody, emptyWits);
190
- // Pick the first input as the v2 nonce UTxO.
191
- // It MUST appear in tx.inputs (which it does by construction) and be
192
- // unspent (which it is, we just queried it from the buyer's UTxO set).
193
- const nonceInput = inputs[0];
194
104
  const nonceRef = `${nonceInput.txHash}#${nonceInput.outputIndex}`;
105
+ const ttlSlot = parsed.validityEnd != null ? Number(parsed.validityEnd) : null;
195
106
  return {
196
- unsignedTxCborHex: Buffer.from(unsigned.to_bytes()).toString('hex'),
197
- txHashHex: Buffer.from(txHash.to_bytes()).toString('hex').toLowerCase(),
198
- requiredSignerHex,
107
+ unsignedTxCborHex: result.unsignedTxCbor,
108
+ txHashHex: result.txBodyHash.toLowerCase(),
109
+ requiredSignerHex: paymentKeyHashHex,
199
110
  nonceRef,
200
- inputs: inputs.map(i => ({ txHash: i.txHash, outputIndex: i.outputIndex, lovelace: i.lovelace })),
111
+ inputs: result.inputs.map(i => ({
112
+ txHash: i.txHash,
113
+ outputIndex: i.index,
114
+ lovelace: i.lovelace,
115
+ })),
201
116
  ttlSlot,
202
117
  };
203
118
  }