@ftptech/x402-canton-client 0.1.0

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/LICENSE ADDED
@@ -0,0 +1,201 @@
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
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for describing the origin of the Work and
141
+ reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Support. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or support.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 FTP Team
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,64 @@
1
+ # @ftptech/x402-canton-client
2
+
3
+ Payer-side SDK for Canton x402. Lets an autonomous agent pay for
4
+ x402-gated HTTP resources using a `CantonSigner` that submits a CIP-56
5
+ `TransferFactory_Transfer` from the agent's Canton participant.
6
+
7
+ ## Install
8
+
9
+ ```bash
10
+ npm i @ftptech/x402-canton-client
11
+ ```
12
+
13
+ > Note: the `@ftp` npm scope is not final — it may change before the
14
+ > first public release (see [`docs/PUBLISHING.md`](https://github.com/sunstrike228/canton-x402/blob/main/docs/PUBLISHING.md)).
15
+ > Pin the version you install and check the README for the current
16
+ > package name.
17
+
18
+ ## What's in here
19
+
20
+ - `CantonSigner` interface — abstracts how a CIP-56 transfer is
21
+ signed and submitted (real participant via `Cip56KeyfileSigner`,
22
+ mock for tests, hosted-party variants).
23
+ - `Cip56KeyfileSigner` + `makeCip56KeyfileSigner(config)` — production
24
+ signer that loads an Ed25519 key from a PEM file (or env-var PEM
25
+ string) and drives the participant's interactive-submission
26
+ prepare/sign/execute flow for `TransferFactory_Transfer`.
27
+ - `ExactCantonScheme` — builds x402 v2 PaymentPayload envelopes
28
+ from PaymentRequirements + a signer.
29
+ - `wrapFetchWithCantonPayment(fetch, signer)` — drop-in fetch
30
+ replacement that detects 402, decodes `PAYMENT-REQUIRED`, calls
31
+ the signer, retries with `PAYMENT-SIGNATURE`, throws
32
+ `X402PaymentError` with a stable `code` field on failure.
33
+ - `readPaymentResponseHeader(response)` — decodes the v2
34
+ `PAYMENT-RESPONSE` settlement header.
35
+
36
+ ## Quick example
37
+
38
+ ```ts
39
+ import {
40
+ wrapFetchWithCantonPayment,
41
+ readPaymentResponseHeader,
42
+ makeCip56KeyfileSigner,
43
+ } from "@ftptech/x402-canton-client";
44
+
45
+ const signer = makeCip56KeyfileSigner({
46
+ participantUrl: "https://your-participant/ledger-api",
47
+ participantToken: "<bearer>",
48
+ scanUrl: "https://scan.your-sv/api/scan",
49
+ party: "agent_party::1220...",
50
+ keyPath: "/run/secrets/agent.pem",
51
+ });
52
+
53
+ const fetchWithPay = wrapFetchWithCantonPayment(fetch, signer);
54
+ const res = await fetchWithPay("https://api.example.com/data");
55
+ const settle = readPaymentResponseHeader(res);
56
+ ```
57
+
58
+ See [`docs/quickstart.md`](https://github.com/sunstrike228/canton-x402/blob/main/docs/quickstart.md)
59
+ for the full demo flow and `examples/agent-buyer/` for a runnable
60
+ agent.
61
+
62
+ ## Project
63
+
64
+ [github.com/sunstrike228/canton-x402](https://github.com/sunstrike228/canton-x402).
@@ -0,0 +1,82 @@
1
+ /**
2
+ * `Cip56KeyfileSigner` — production CantonSigner implementation
3
+ * for the CIP-56 Token Standard path.
4
+ *
5
+ * Mirrors `KeyfileSigner` (which targets the Splice TransferCommand
6
+ * path for Canton Coin) but exercises `TransferFactory_Transfer`
7
+ * via interactive-submission/prepare+execute. The factory
8
+ * implementation can be from ANY token issuer that conforms to
9
+ * Splice's CIP-56 — USDC, EURC, the splice-token-test-dummy-holding,
10
+ * custom institutional stablecoins, etc.
11
+ *
12
+ * Flow per `signCip56Transfer`:
13
+ *
14
+ * 1. Build the `TransferFactory_Transfer` choice argument using
15
+ * the merchant-supplied factory cid, instrumentId,
16
+ * facilitator, and the caller's transferMeta (with x402
17
+ * paymentId).
18
+ * 2. Wrap as a JsCommand with the factory's templateId.
19
+ * 3. `CantonExternalPartySigner.prepareSignAndExecute` lands the
20
+ * submission; returns the updateId.
21
+ * 4. Read the transaction tree by updateId to find the
22
+ * TransferInstructionResult — was it Completed (synchronous)
23
+ * or Pending (instruction cid returned)?
24
+ * 5. Return `{updateId, transferInstructionCid?}` for the caller
25
+ * to wrap in the PaymentPayload.
26
+ *
27
+ * Resolving `transferFactoryTemplateId`: the caller must supply
28
+ * it. Either:
29
+ * - The merchant publishes it in `extra.transferFactoryTemplateId`
30
+ * (we don't currently put it in the spec; merchant SDK should
31
+ * resolve via Scan's CIP-56 registry endpoint at startup).
32
+ * - The signer fetches it from `/v2/state/active-contracts`
33
+ * filtered to the factory cid.
34
+ *
35
+ * For v0.1 we make the caller pass it through; future versions can
36
+ * add an automatic resolver.
37
+ */
38
+ import { CantonClient, CantonExternalPartySigner, ScanClient, type ExternalPartyKey, type ScanFlavor } from "@ftptech/x402-canton-ledger";
39
+ import type { CantonSigner, SignCip56TransferInput, SignedCip56Transfer } from "./signer.js";
40
+ export interface Cip56KeyfileSignerDeps {
41
+ /** Wraps interactive-submission/prepare + execute. */
42
+ signer: CantonExternalPartySigner;
43
+ /** ACS lookup to extract TransferInstruction cid from result. */
44
+ client: CantonClient;
45
+ /** Optional: Scan client for future factory-lookup automation. */
46
+ scan?: ScanClient;
47
+ /** The Ed25519 keypair this signer signs with. */
48
+ key: ExternalPartyKey;
49
+ /** The agent's Canton party id. */
50
+ party: string;
51
+ /** Ledger user id submitted in the JsCommands envelope. */
52
+ userId?: string;
53
+ /** Default Transfer.executeBefore window in seconds. Default 60. */
54
+ defaultExpirySeconds?: number;
55
+ }
56
+ export declare class Cip56KeyfileSigner implements CantonSigner {
57
+ private readonly deps;
58
+ readonly party: string;
59
+ constructor(deps: Cip56KeyfileSignerDeps);
60
+ signCip56Transfer(input: SignCip56TransferInput): Promise<SignedCip56Transfer>;
61
+ }
62
+ export interface MakeCip56KeyfileSignerConfig {
63
+ keyPath?: string;
64
+ keyPem?: string;
65
+ fingerprint?: string;
66
+ party: string;
67
+ participantUrl: string;
68
+ participantToken: string;
69
+ packageName?: string;
70
+ scanUrl?: string;
71
+ scanToken?: string;
72
+ scanFlavor?: ScanFlavor;
73
+ userId?: string;
74
+ defaultExpirySeconds?: number;
75
+ timeoutMs?: number;
76
+ }
77
+ /**
78
+ * Convenience builder mirroring `makeKeyfileSigner` but constructing
79
+ * the CIP-56 variant.
80
+ */
81
+ export declare function makeCip56KeyfileSigner(config: MakeCip56KeyfileSignerConfig): Cip56KeyfileSigner;
82
+ //# sourceMappingURL=cip56-signer.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cip56-signer.d.ts","sourceRoot":"","sources":["../src/cip56-signer.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAoCG;AAIH,OAAO,EACL,YAAY,EACZ,yBAAyB,EACzB,UAAU,EAIV,KAAK,gBAAgB,EACrB,KAAK,UAAU,EAGhB,MAAM,6BAA6B,CAAC;AACrC,OAAO,KAAK,EACV,YAAY,EACZ,sBAAsB,EACtB,mBAAmB,EACpB,MAAM,aAAa,CAAC;AAErB,MAAM,WAAW,sBAAsB;IACrC,sDAAsD;IACtD,MAAM,EAAE,yBAAyB,CAAC;IAClC,iEAAiE;IACjE,MAAM,EAAE,YAAY,CAAC;IACrB,kEAAkE;IAClE,IAAI,CAAC,EAAE,UAAU,CAAC;IAClB,kDAAkD;IAClD,GAAG,EAAE,gBAAgB,CAAC;IACtB,mCAAmC;IACnC,KAAK,EAAE,MAAM,CAAC;IACd,2DAA2D;IAC3D,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,oEAAoE;IACpE,oBAAoB,CAAC,EAAE,MAAM,CAAC;CAC/B;AAED,qBAAa,kBAAmB,YAAW,YAAY;IAGzC,OAAO,CAAC,QAAQ,CAAC,IAAI;IAFjC,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;gBAEM,IAAI,EAAE,sBAAsB;IAInD,iBAAiB,CACrB,KAAK,EAAE,sBAAsB,GAC5B,OAAO,CAAC,mBAAmB,CAAC;CA0GhC;AAED,MAAM,WAAW,4BAA4B;IAC3C,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,KAAK,EAAE,MAAM,CAAC;IACd,cAAc,EAAE,MAAM,CAAC;IACvB,gBAAgB,EAAE,MAAM,CAAC;IACzB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,UAAU,CAAC,EAAE,UAAU,CAAC;IACxB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,oBAAoB,CAAC,EAAE,MAAM,CAAC;IAC9B,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB;AAED;;;GAGG;AACH,wBAAgB,sBAAsB,CACpC,MAAM,EAAE,4BAA4B,GACnC,kBAAkB,CAgDpB"}
@@ -0,0 +1,183 @@
1
+ /**
2
+ * `Cip56KeyfileSigner` — production CantonSigner implementation
3
+ * for the CIP-56 Token Standard path.
4
+ *
5
+ * Mirrors `KeyfileSigner` (which targets the Splice TransferCommand
6
+ * path for Canton Coin) but exercises `TransferFactory_Transfer`
7
+ * via interactive-submission/prepare+execute. The factory
8
+ * implementation can be from ANY token issuer that conforms to
9
+ * Splice's CIP-56 — USDC, EURC, the splice-token-test-dummy-holding,
10
+ * custom institutional stablecoins, etc.
11
+ *
12
+ * Flow per `signCip56Transfer`:
13
+ *
14
+ * 1. Build the `TransferFactory_Transfer` choice argument using
15
+ * the merchant-supplied factory cid, instrumentId,
16
+ * facilitator, and the caller's transferMeta (with x402
17
+ * paymentId).
18
+ * 2. Wrap as a JsCommand with the factory's templateId.
19
+ * 3. `CantonExternalPartySigner.prepareSignAndExecute` lands the
20
+ * submission; returns the updateId.
21
+ * 4. Read the transaction tree by updateId to find the
22
+ * TransferInstructionResult — was it Completed (synchronous)
23
+ * or Pending (instruction cid returned)?
24
+ * 5. Return `{updateId, transferInstructionCid?}` for the caller
25
+ * to wrap in the PaymentPayload.
26
+ *
27
+ * Resolving `transferFactoryTemplateId`: the caller must supply
28
+ * it. Either:
29
+ * - The merchant publishes it in `extra.transferFactoryTemplateId`
30
+ * (we don't currently put it in the spec; merchant SDK should
31
+ * resolve via Scan's CIP-56 registry endpoint at startup).
32
+ * - The signer fetches it from `/v2/state/active-contracts`
33
+ * filtered to the factory cid.
34
+ *
35
+ * For v0.1 we make the caller pass it through; future versions can
36
+ * add an automatic resolver.
37
+ */
38
+ import { readFileSync } from "node:fs";
39
+ import { createPrivateKey, createPublicKey } from "node:crypto";
40
+ import { CantonClient, CantonExternalPartySigner, ScanClient, ed25519KeyFromNodeKeyPair, CIP56_CHOICES, CIP56_TEMPLATE_SUFFIXES, } from "@ftptech/x402-canton-ledger";
41
+ export class Cip56KeyfileSigner {
42
+ deps;
43
+ party;
44
+ constructor(deps) {
45
+ this.deps = deps;
46
+ this.party = deps.party;
47
+ }
48
+ async signCip56Transfer(input) {
49
+ if (!input.transferFactoryTemplateId) {
50
+ throw new Error("Cip56KeyfileSigner.signCip56Transfer: transferFactoryTemplateId required (resolve from Scan or merchant config)");
51
+ }
52
+ const nowMs = Date.now();
53
+ const defaultExpiry = (this.deps.defaultExpirySeconds ?? 60) * 1000;
54
+ const executeBeforeMs = input.executeBeforeMs ?? nowMs + defaultExpiry;
55
+ const transfer = {
56
+ sender: this.party,
57
+ receiver: input.receiver,
58
+ amount: input.amount,
59
+ instrumentId: input.instrumentId,
60
+ // requestedAt MUST be in the past at submit time — backstop
61
+ // by 1s so clock skew doesn't fail the check.
62
+ requestedAt: new Date(nowMs - 1000).toISOString(),
63
+ executeBefore: new Date(executeBeforeMs).toISOString(),
64
+ inputHoldingCids: [],
65
+ meta: {
66
+ values: input.transferMeta ?? {},
67
+ },
68
+ };
69
+ const choiceArgument = {
70
+ expectedAdmin: input.factoryAdmin,
71
+ transfer,
72
+ extraArgs: input.extraArgs ?? {
73
+ context: { values: {} },
74
+ meta: { values: {} },
75
+ },
76
+ };
77
+ const commandId = `xfer-cip56-${nowMs}-${Math.random()
78
+ .toString(36)
79
+ .slice(2, 10)}`;
80
+ const userId = this.deps.userId ?? "x402-agent";
81
+ const result = await this.deps.signer.prepareSignAndExecute({
82
+ userId,
83
+ commandId,
84
+ actAs: [this.party],
85
+ synchronizerId: input.synchronizerId,
86
+ // The factory contract is DSO-signed (or issuer-signed);
87
+ // typically already visible to the sender's participant.
88
+ // If not, caller must include a disclosedContracts entry —
89
+ // future API addition.
90
+ disclosedContracts: [],
91
+ commands: [
92
+ {
93
+ ExerciseCommand: {
94
+ templateId: input.transferFactoryTemplateId,
95
+ contractId: input.transferFactoryCid,
96
+ choice: CIP56_CHOICES.transferFactoryTransfer,
97
+ choiceArgument: choiceArgument,
98
+ },
99
+ },
100
+ ],
101
+ }, this.deps.key);
102
+ // Inspect THIS specific transaction (by updateId) to find the
103
+ // TransferInstruction CreatedEvent — if any — inside its
104
+ // events. ACS-scanning is unsafe: a sender with any unrelated
105
+ // outstanding TransferInstruction (e.g. from a prior pending
106
+ // transfer) would get the wrong cid picked up, and the
107
+ // facilitator's /verify would reject the wrong contract.
108
+ let transferInstructionCid = null;
109
+ try {
110
+ const tx = await this.deps.client.getTransactionById({
111
+ updateId: result.updateId,
112
+ requestingParties: [this.party],
113
+ });
114
+ for (const e of tx.events) {
115
+ const created = e.CreatedEvent;
116
+ if (created &&
117
+ created.templateId.endsWith(CIP56_TEMPLATE_SUFFIXES.transferInstruction)) {
118
+ transferInstructionCid = created.contractId;
119
+ break;
120
+ }
121
+ }
122
+ }
123
+ catch {
124
+ // Tree fetch failed (network blip, party visibility issue).
125
+ // Fall through with transferInstructionCid=null — the
126
+ // PaymentPayload will then default to the Completed variant
127
+ // and surface just the updateId. The facilitator's /verify
128
+ // accepts updateId as proof in that case.
129
+ }
130
+ return {
131
+ payerParty: this.party,
132
+ updateId: result.updateId,
133
+ transferInstructionCid,
134
+ };
135
+ }
136
+ }
137
+ /**
138
+ * Convenience builder mirroring `makeKeyfileSigner` but constructing
139
+ * the CIP-56 variant.
140
+ */
141
+ export function makeCip56KeyfileSigner(config) {
142
+ const client = new CantonClient({
143
+ participantUrl: config.participantUrl,
144
+ token: config.participantToken,
145
+ packageName: config.packageName ?? "splice-api-token-transfer-instruction-v1",
146
+ ...(config.timeoutMs !== undefined ? { timeoutMs: config.timeoutMs } : {}),
147
+ });
148
+ const scan = config.scanUrl
149
+ ? new ScanClient({
150
+ scanUrl: config.scanUrl,
151
+ ...(config.scanToken !== undefined ? { token: config.scanToken } : {}),
152
+ ...(config.scanFlavor !== undefined ? { flavor: config.scanFlavor } : {}),
153
+ ...(config.timeoutMs !== undefined ? { timeoutMs: config.timeoutMs } : {}),
154
+ })
155
+ : undefined;
156
+ const ipSigner = new CantonExternalPartySigner(client);
157
+ const pem = config.keyPem ??
158
+ (config.keyPath ? readFileSync(config.keyPath, "utf8") : null);
159
+ if (!pem) {
160
+ throw new Error("makeCip56KeyfileSigner: provide keyPath or keyPem");
161
+ }
162
+ const privateKey = createPrivateKey({ key: pem, format: "pem" });
163
+ const publicKey = createPublicKey(privateKey);
164
+ const key = ed25519KeyFromNodeKeyPair({
165
+ privateKey,
166
+ publicKey,
167
+ ...(config.fingerprint !== undefined
168
+ ? { fingerprint: config.fingerprint }
169
+ : {}),
170
+ });
171
+ return new Cip56KeyfileSigner({
172
+ signer: ipSigner,
173
+ client,
174
+ ...(scan !== undefined ? { scan } : {}),
175
+ key,
176
+ party: config.party,
177
+ ...(config.userId !== undefined ? { userId: config.userId } : {}),
178
+ ...(config.defaultExpirySeconds !== undefined
179
+ ? { defaultExpirySeconds: config.defaultExpirySeconds }
180
+ : {}),
181
+ });
182
+ }
183
+ //# sourceMappingURL=cip56-signer.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cip56-signer.js","sourceRoot":"","sources":["../src/cip56-signer.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAoCG;AAEH,OAAO,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AACvC,OAAO,EAAE,gBAAgB,EAAE,eAAe,EAAkB,MAAM,aAAa,CAAC;AAChF,OAAO,EACL,YAAY,EACZ,yBAAy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AAC,MAAM,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QACjE,GAAG,CAAC,MAAM,CAAC,oBAAoB,KAAK,SAAS;YAC3C,CAAC,CAAC,EAAE,oBAAoB,EAAE,MAAM,CAAC,oBAAoB,EAAE;YACvD,CAAC,CAAC,EAAE,CAAC;KACR,CAAC,CAAC;AACL,CAAC"}
@@ -0,0 +1,51 @@
1
+ /**
2
+ * wrapFetchWithCantonPayment — automate the x402 v2 "detect 402 →
3
+ * pay → retry" flow against any Canton-aware facilitator.
4
+ *
5
+ * Usage:
6
+ *
7
+ * const fetchWithPay = wrapFetchWithCantonPayment(globalThis.fetch, signer);
8
+ * const res = await fetchWithPay("https://api.example.com/data");
9
+ * const settle = readPaymentResponseHeader(res);
10
+ *
11
+ * Wire format: x402 v2 only. v1 fallback is tracked in BACKLOG.md
12
+ * and lands when an older facilitator demands it.
13
+ *
14
+ * Limitations:
15
+ * - The original request body must be replayable (e.g. JSON string,
16
+ * Uint8Array, FormData). Streaming bodies will fail on retry.
17
+ * - Idempotency: callers should treat the wrapped fetch as
18
+ * at-most-twice. If the second response is still 402 we throw —
19
+ * no infinite-loop retries.
20
+ */
21
+ import { type PaymentRequirements, type X402ResourceInfo, type CantonNetwork } from "@ftptech/x402-canton-core";
22
+ import type { CantonSigner } from "./signer.js";
23
+ export interface X402PaymentRequired {
24
+ x402Version: number;
25
+ error?: string;
26
+ resource: X402ResourceInfo;
27
+ accepts: PaymentRequirements[];
28
+ extensions?: Record<string, unknown>;
29
+ }
30
+ export interface WrapFetchOptions {
31
+ /** Restrict which Canton networks this client will pay on.
32
+ * Default: any `canton:*`. */
33
+ networkFilter?: (network: CantonNetwork) => boolean;
34
+ /** Tiebreaker among multiple exact-canton accepts. Default: first
35
+ * matching entry. */
36
+ selectRequirements?: (candidates: PaymentRequirements[]) => PaymentRequirements;
37
+ }
38
+ export declare class X402PaymentError extends Error {
39
+ readonly code: X402PaymentErrorCode;
40
+ constructor(message: string, code: X402PaymentErrorCode);
41
+ }
42
+ export type X402PaymentErrorCode = "MISSING_PAYMENT_REQUIRED_HEADER" | "MALFORMED_PAYMENT_REQUIRED" | "NO_ACCEPTABLE_SCHEME" | "PAYMENT_REJECTED";
43
+ export declare function wrapFetchWithCantonPayment(fetch: typeof globalThis.fetch, signer: CantonSigner, options?: WrapFetchOptions): typeof globalThis.fetch;
44
+ /**
45
+ * Decode the `PAYMENT-RESPONSE` header (x402 v2) attached to a
46
+ * response that came back through wrapFetchWithCantonPayment.
47
+ * Returns null when the header is absent (e.g. response unrelated to
48
+ * x402).
49
+ */
50
+ export declare function readPaymentResponseHeader<T = unknown>(response: Response): T | null;
51
+ //# sourceMappingURL=fetch.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fetch.d.ts","sourceRoot":"","sources":["../src/fetch.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AAEH,OAAO,EAML,KAAK,mBAAmB,EACxB,KAAK,gBAAgB,EACrB,KAAK,aAAa,EACnB,MAAM,2BAA2B,CAAC;AACnC,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAWhD,MAAM,WAAW,mBAAmB;IAClC,WAAW,EAAE,MAAM,CAAC;IACpB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,QAAQ,EAAE,gBAAgB,CAAC;IAC3B,OAAO,EAAE,mBAAmB,EAAE,CAAC;IAC/B,UAAU,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CACtC;AAED,MAAM,WAAW,gBAAgB;IAC/B;mCAC+B;IAC/B,aAAa,CAAC,EAAE,CAAC,OAAO,EAAE,aAAa,KAAK,OAAO,CAAC;IACpD;0BACsB;IACtB,kBAAkB,CAAC,EAAE,CAAC,UAAU,EAAE,mBAAmB,EAAE,KAAK,mBAAmB,CAAC;CACjF;AAED,qBAAa,gBAAiB,SAAQ,KAAK;aACI,IAAI,EAAE,oBAAoB;gBAA3D,OAAO,EAAE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