@bosonprotocol/x402-evm 0.1.0-alpha-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 reasonable and customary use in describing the
141
+ origin of the Work and 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 Additional Liability. 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 additional liability.
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 Boson Protocol
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,83 @@
1
+ # @bosonprotocol/x402-evm
2
+
3
+ EVM-specific calldata builders for the Boson Protocol [`escrow`](https://github.com/bosonprotocol/x402-escrow-schema)
4
+ scheme — the EVM half of the
5
+ [x402B](https://github.com/bosonprotocol/x402B) implementation.
6
+
7
+ See `docs/boson-impl-00-overview.md` in the monorepo root for context.
8
+
9
+ ## Scope
10
+
11
+ This package ships **only** what the x402B escrow scheme needs beyond
12
+ what [`@bosonprotocol/core-sdk`](https://github.com/bosonprotocol/core-components)
13
+ already provides:
14
+
15
+ | Subpath | Purpose |
16
+ |---|---|
17
+ | `./actions` | Inner-action ABI encoding for the commit step. `buildCreateOfferAndCommitCalldata` (Flow A, deferred-redeem) and `buildCreateOfferCommitAndRedeemCalldata` (Flow B, atomic commit+redeem) each return the `{ functionName, functionSignature }` pair that feeds the meta-tx typed-data the buyer signs. Both delegate to `metaTx.handler.signMetaTx*({ returnTypedDataToSign: true })` in core-sdk so the selector literal and ABI encoding come from the same source the buyer signs against — no drift between signing and verification. |
18
+ | `./adapters` | viem ↔ `Web3LibAdapter` bridges. `walletClientToWeb3LibAdapter` wraps a viem `WalletClient` + `PublicClient` so `coreSdk.executeMetaTransaction(...)` (the unified entrypoint for the outer envelope) can submit through viem-configured transports. Submission failures surface as a tagged `RelayerSubmitError` so callers can preserve precise error codes (`INSUFFICIENT_FUNDS_FOR_GAS`, `ONCHAIN_REVERT`, `INTERNAL_ERROR`). |
19
+
20
+ The outer meta-tx envelope (`executeMetaTransaction` /
21
+ `executeMetaTransactionWithTokenTransferAuthorization`) is **not**
22
+ re-implemented here. Submit through core-sdk's
23
+ `coreSdk.executeMetaTransaction(metaTxParams)`, which accepts an
24
+ optional `transferAuthorizations` array and routes to the right
25
+ on-chain entrypoint internally.
26
+
27
+ ## What this package deliberately does NOT ship
28
+
29
+ Boson's meta-tx and direct-call flows for every other action are
30
+ already fully covered by `@bosonprotocol/core-sdk`. Reach for it
31
+ directly:
32
+
33
+ ### Meta-tx signing (default) — `coreSdk.signMetaTxXxx`
34
+
35
+ Each `signMetaTxXxx` method on a configured `CoreSDK` instance uses the
36
+ bespoke EIP-712 type the protocol's `MetaTransactionsHandlerFacet`
37
+ expects for that action family (`MetaTxExchange` for
38
+ `redeem/complete/cancel/revoke/raise/retract/escalate`,
39
+ `MetaTxDisputeResolution` for `resolveDispute`, generic
40
+ `MetaTransaction` for `createOfferAndCommit` and friends). It returns
41
+ `SignedMetaTx = { functionName, functionSignature, r, s, v }` — exactly
42
+ the buyer-side payload the `X-PAYMENT` header carries, ready for the
43
+ facilitator to submit via `coreSdk.executeMetaTransaction(metaTxParams)`.
44
+
45
+ ```ts
46
+ const signed = await coreSdk.signMetaTxRedeemVoucher({ nonce, exchangeId });
47
+ // signed = { functionName: "redeemVoucher(uint256)", functionSignature, r, s, v }
48
+ ```
49
+
50
+ `coreSdk` fills `web3Lib`, `metaTxHandlerAddress`, and `chainId` from
51
+ the SDK instance, so the call site stays minimal. The standalone
52
+ `metaTx.handler.signMetaTxXxx` exports are also available if you need
53
+ them without a `CoreSDK` instance.
54
+
55
+ ### Direct on-chain submission — `coreSdk.xxx`
56
+
57
+ For the on-chain channel (buyer paying their own gas, or the
58
+ "onchain" fallback in `nextActions[i].channels`), use the same `CoreSDK`
59
+ mixin methods that handle signing and submission in one call:
60
+
61
+ ```ts
62
+ const tx = await coreSdk.redeemVoucher(exchangeId);
63
+ // → also: completeExchange, cancelVoucher, revokeVoucher,
64
+ // raiseDispute, retractDispute, escalateDispute, resolveDispute
65
+ await tx.wait();
66
+ ```
67
+
68
+ Pass `returnTxInfo: true` to get back a `TransactionRequest` for manual
69
+ submission (e.g. when handing it to a relayer or batcher) instead of
70
+ broadcasting through the SDK's `web3Lib`.
71
+
72
+ ### Token-side `approve` / Permit2 approval
73
+
74
+ Calldata builders for the buyer's pre-approval transaction (used by
75
+ `tokenAuthStrategy: "none"`) and the one-time Permit2 contract approval
76
+ live in [`@bosonprotocol/x402-core`](../core):
77
+
78
+ ```ts
79
+ import {
80
+ createErc20ApprovalTx,
81
+ createPermit2ApprovalTx,
82
+ } from "@bosonprotocol/x402-core/eip712/token-auth";
83
+ ```
@@ -0,0 +1,61 @@
1
+ import { Hex, Address } from 'viem';
2
+ import { FullOfferArgs } from '@bosonprotocol/common';
3
+
4
+ /**
5
+ * Minimal calldata payload for a `MetaTransactionsHandlerFacet.executeMetaTransaction`
6
+ * inner action — what the buyer signs over inside the meta-tx envelope.
7
+ *
8
+ * - `functionName` is the Solidity function selector string the protocol uses
9
+ * when recovering the buyer's signature (e.g.
10
+ * `"createOfferAndCommit((... long tuple ...),address,address,bytes,uint256,...)"`).
11
+ * Must match byte-for-byte the literal core-sdk's
12
+ * `meta-tx/handler.ts` uses for the same action, since the meta-tx
13
+ * typed-data hashes it as a `string`.
14
+ * - `functionSignature` is the ABI-encoded call data (selector + args) for
15
+ * the action itself.
16
+ */
17
+ interface InnerActionCalldata {
18
+ functionName: string;
19
+ functionSignature: Hex;
20
+ }
21
+ /** Minimal viem-style transaction request that any wallet client can submit. */
22
+ interface TxRequest {
23
+ to: Address;
24
+ data: Hex;
25
+ /** Optional ETH value attached to the call. Defaults to 0n; only present for `payable` functions. */
26
+ value?: bigint;
27
+ }
28
+
29
+ interface BuildCreateOfferAndCommitCalldataArgs {
30
+ /**
31
+ * Full BPIP-10 offer payload, identical in shape to what core-sdk's
32
+ * `exchanges.iface.encodeCreateOfferAndCommit` accepts. The seller's
33
+ * `signature` field is embedded inside this struct and is verified
34
+ * on-chain by `verifyOffer`.
35
+ */
36
+ fullOffer: FullOfferArgs;
37
+ }
38
+ /**
39
+ * Build the `{ functionName, functionSignature }` calldata pair for the
40
+ * `createOfferAndCommit` inner action. The result feeds
41
+ * `@bosonprotocol/x402-core/eip712`'s `metaTransactionTypedData`
42
+ * builder to produce the EIP-712 typed-data the buyer signs.
43
+ */
44
+ declare function buildCreateOfferAndCommitCalldata(args: BuildCreateOfferAndCommitCalldataArgs): Promise<InnerActionCalldata>;
45
+
46
+ interface BuildCreateOfferCommitAndRedeemCalldataArgs {
47
+ /**
48
+ * Full BPIP-10 offer payload, identical in shape to what core-sdk's
49
+ * `orchestration.iface.encodeCreateOfferCommitAndRedeem` accepts. The
50
+ * seller's `signature` field is embedded inside this struct and is
51
+ * verified on-chain by `verifyOffer`.
52
+ */
53
+ fullOffer: FullOfferArgs;
54
+ }
55
+ /**
56
+ * Build the `{ functionName, functionSignature }` calldata pair for the
57
+ * `createOfferCommitAndRedeem` inner action.
58
+ */
59
+ declare function buildCreateOfferCommitAndRedeemCalldata(args: BuildCreateOfferCommitAndRedeemCalldataArgs): Promise<InnerActionCalldata>;
60
+
61
+ export { type BuildCreateOfferAndCommitCalldataArgs, type BuildCreateOfferCommitAndRedeemCalldataArgs, type InnerActionCalldata, type TxRequest, buildCreateOfferAndCommitCalldata, buildCreateOfferCommitAndRedeemCalldata };
@@ -0,0 +1,70 @@
1
+ 'use strict';
2
+
3
+ var coreSdk = require('@bosonprotocol/core-sdk');
4
+
5
+ // src/actions/create-offer-and-commit.ts
6
+
7
+ // src/internal/metatx-calldata-constants.ts
8
+ var DUMMY_CHAIN_ID = 1;
9
+ var DUMMY_METATX_HANDLER_ADDRESS = "0x0000000000000000000000000000000000000000";
10
+ var DUMMY_NONCE = "0";
11
+
12
+ // src/internal/web3lib-stub.ts
13
+ var DUMMY_SIGNER_ADDRESS = "0x0000000000000000000000000000000000000001";
14
+ function unreachable(callerTag, method) {
15
+ return new Error(
16
+ `${callerTag}: stub Web3LibAdapter.${method}() should never be called. If you see this, core-sdk changed its typed-data-only behavior.`
17
+ );
18
+ }
19
+ function createCalldataOnlyWeb3LibAdapter(callerTag) {
20
+ return {
21
+ uuid: `${callerTag}:stub`,
22
+ getSignerAddress: () => Promise.resolve(DUMMY_SIGNER_ADDRESS),
23
+ isSignerContract: () => Promise.resolve(false),
24
+ getChainId: () => Promise.reject(unreachable(callerTag, "getChainId")),
25
+ getBalance: () => Promise.reject(unreachable(callerTag, "getBalance")),
26
+ estimateGas: () => Promise.reject(unreachable(callerTag, "estimateGas")),
27
+ sendTransaction: () => Promise.reject(unreachable(callerTag, "sendTransaction")),
28
+ call: () => Promise.reject(unreachable(callerTag, "call")),
29
+ send: () => Promise.reject(unreachable(callerTag, "send")),
30
+ getTransactionReceipt: () => Promise.reject(unreachable(callerTag, "getTransactionReceipt")),
31
+ getCurrentTimeMs: () => Promise.reject(unreachable(callerTag, "getCurrentTimeMs"))
32
+ };
33
+ }
34
+
35
+ // src/actions/create-offer-and-commit.ts
36
+ var STUB_CALLER_TAG = "@bosonprotocol/x402-evm:create-offer-and-commit";
37
+ async function buildCreateOfferAndCommitCalldata(args) {
38
+ const result = await coreSdk.metaTx.handler.signMetaTxCreateOfferAndCommit({
39
+ web3Lib: createCalldataOnlyWeb3LibAdapter(STUB_CALLER_TAG),
40
+ metaTxHandlerAddress: DUMMY_METATX_HANDLER_ADDRESS,
41
+ chainId: DUMMY_CHAIN_ID,
42
+ nonce: DUMMY_NONCE,
43
+ createOfferAndCommitArgs: args.fullOffer,
44
+ returnTypedDataToSign: true
45
+ });
46
+ return {
47
+ functionName: result.functionName,
48
+ functionSignature: result.functionSignature
49
+ };
50
+ }
51
+ var STUB_CALLER_TAG2 = "@bosonprotocol/x402-evm:create-offer-commit-and-redeem";
52
+ async function buildCreateOfferCommitAndRedeemCalldata(args) {
53
+ const result = await coreSdk.metaTx.handler.signMetaTxCreateOfferCommitAndRedeem({
54
+ web3Lib: createCalldataOnlyWeb3LibAdapter(STUB_CALLER_TAG2),
55
+ metaTxHandlerAddress: DUMMY_METATX_HANDLER_ADDRESS,
56
+ chainId: DUMMY_CHAIN_ID,
57
+ nonce: DUMMY_NONCE,
58
+ createOfferAndCommitArgs: args.fullOffer,
59
+ returnTypedDataToSign: true
60
+ });
61
+ return {
62
+ functionName: result.functionName,
63
+ functionSignature: result.functionSignature
64
+ };
65
+ }
66
+
67
+ exports.buildCreateOfferAndCommitCalldata = buildCreateOfferAndCommitCalldata;
68
+ exports.buildCreateOfferCommitAndRedeemCalldata = buildCreateOfferCommitAndRedeemCalldata;
69
+ //# sourceMappingURL=index.js.map
70
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../src/internal/metatx-calldata-constants.ts","../../../src/internal/web3lib-stub.ts","../../../src/actions/create-offer-and-commit.ts","../../../src/actions/create-offer-commit-and-redeem.ts"],"names":["metaTx","STUB_CALLER_TAG"],"mappings":";;;;;;;AAUO,IAAM,cAAA,GAAiB,CAAA;AACvB,IAAM,4BAAA,GAA+B,4CAAA;AACrC,IAAM,WAAA,GAAc,GAAA;;;ACA3B,IAAM,oBAAA,GAAuB,4CAAA;AAE7B,SAAS,WAAA,CAAY,WAAmB,MAAA,EAAuB;AAC7D,EAAA,OAAO,IAAI,KAAA;AAAA,IACT,CAAA,EAAG,SAAS,CAAA,sBAAA,EAAyB,MAAM,CAAA,0FAAA;AAAA,GAE7C;AACF;AAEO,SAAS,iCAAiC,SAAA,EAAmC;AAClF,EAAA,OAAO;AAAA,IACL,IAAA,EAAM,GAAG,SAAS,CAAA,KAAA,CAAA;AAAA,IAClB,gBAAA,EAAkB,MAAM,OAAA,CAAQ,OAAA,CAAQ,oBAAoB,CAAA;AAAA,IAC5D,gBAAA,EAAkB,MAAM,OAAA,CAAQ,OAAA,CAAQ,KAAK,CAAA;AAAA,IAC7C,YAAY,MAAM,OAAA,CAAQ,OAAO,WAAA,CAAY,SAAA,EAAW,YAAY,CAAC,CAAA;AAAA,IACrE,YAAY,MAAM,OAAA,CAAQ,OAAO,WAAA,CAAY,SAAA,EAAW,YAAY,CAAC,CAAA;AAAA,IACrE,aAAa,MAAM,OAAA,CAAQ,OAAO,WAAA,CAAY,SAAA,EAAW,aAAa,CAAC,CAAA;AAAA,IACvE,iBAAiB,MAAM,OAAA,CAAQ,OAAO,WAAA,CAAY,SAAA,EAAW,iBAAiB,CAAC,CAAA;AAAA,IAC/E,MAAM,MAAM,OAAA,CAAQ,OAAO,WAAA,CAAY,SAAA,EAAW,MAAM,CAAC,CAAA;AAAA,IACzD,MAAM,MAAM,OAAA,CAAQ,OAAO,WAAA,CAAY,SAAA,EAAW,MAAM,CAAC,CAAA;AAAA,IACzD,uBAAuB,MAAM,OAAA,CAAQ,OAAO,WAAA,CAAY,SAAA,EAAW,uBAAuB,CAAC,CAAA;AAAA,IAC3F,kBAAkB,MAAM,OAAA,CAAQ,OAAO,WAAA,CAAY,SAAA,EAAW,kBAAkB,CAAC;AAAA,GACnF;AACF;;;ACKA,IAAM,eAAA,GAAkB,iDAAA;AAQxB,eAAsB,kCACpB,IAAA,EAC8B;AAC9B,EAAA,MAAM,MAAA,GAAS,MAAMA,cAAA,CAAO,OAAA,CAAQ,8BAAA,CAA+B;AAAA,IACjE,OAAA,EAAS,iCAAiC,eAAe,CAAA;AAAA,IACzD,oBAAA,EAAsB,4BAAA;AAAA,IACtB,OAAA,EAAS,cAAA;AAAA,IACT,KAAA,EAAO,WAAA;AAAA,IACP,0BAA0B,IAAA,CAAK,SAAA;AAAA,IAC/B,qBAAA,EAAuB;AAAA,GACxB,CAAA;AAED,EAAA,OAAO;AAAA,IACL,cAAc,MAAA,CAAO,YAAA;AAAA,IACrB,mBAAmB,MAAA,CAAO;AAAA,GAC5B;AACF;ACzBA,IAAMC,gBAAAA,GAAkB,wDAAA;AAMxB,eAAsB,wCACpB,IAAA,EAC8B;AAC9B,EAAA,MAAM,MAAA,GAAS,MAAMD,cAAAA,CAAO,OAAA,CAAQ,oCAAA,CAAqC;AAAA,IACvE,OAAA,EAAS,iCAAiCC,gBAAe,CAAA;AAAA,IACzD,oBAAA,EAAsB,4BAAA;AAAA,IACtB,OAAA,EAAS,cAAA;AAAA,IACT,KAAA,EAAO,WAAA;AAAA,IACP,0BAA0B,IAAA,CAAK,SAAA;AAAA,IAC/B,qBAAA,EAAuB;AAAA,GACxB,CAAA;AAED,EAAA,OAAO;AAAA,IACL,cAAc,MAAA,CAAO,YAAA;AAAA,IACrB,mBAAmB,MAAA,CAAO;AAAA,GAC5B;AACF","file":"index.js","sourcesContent":["// Placeholder values for the meta-tx fields the SDK's `signMetaTx*` helpers\n// require but the calldata-builder modules don't care about.\n//\n// The builders delegate the `{ functionName, functionSignature }` pair to\n// `metaTx.handler.signMetaTx*({ returnTypedDataToSign: true })`. The SDK\n// requires `chainId`, `metaTxHandlerAddress`, and `nonce` to build the\n// meta-tx typed-data domain, but those affect only the typed-data portion\n// of the response; the selector literal and ABI-encoded calldata we read\n// back are independent of all three.\n\nexport const DUMMY_CHAIN_ID = 1;\nexport const DUMMY_METATX_HANDLER_ADDRESS = \"0x0000000000000000000000000000000000000000\";\nexport const DUMMY_NONCE = \"0\";\n","// Calldata-only `Web3LibAdapter` for the calldata-builder modules.\n//\n// Core-sdk's `signMetaTx` calls `web3Lib.getSignerAddress()` even in\n// `returnTypedDataToSign: true` mode to fill the message's `from` field.\n// We return a deterministic dummy address; the typed-data message is\n// discarded and only `{ functionName, functionSignature }` is consumed.\n//\n// All signing and transaction methods reject so the stub fails loudly if\n// it ever leaks into a path that needs more than typed-data construction.\n\nimport type { Web3LibAdapter } from \"@bosonprotocol/common\";\n\nconst DUMMY_SIGNER_ADDRESS = \"0x0000000000000000000000000000000000000001\";\n\nfunction unreachable(callerTag: string, method: string): Error {\n return new Error(\n `${callerTag}: stub Web3LibAdapter.${method}() should never be called. ` +\n \"If you see this, core-sdk changed its typed-data-only behavior.\",\n );\n}\n\nexport function createCalldataOnlyWeb3LibAdapter(callerTag: string): Web3LibAdapter {\n return {\n uuid: `${callerTag}:stub`,\n getSignerAddress: () => Promise.resolve(DUMMY_SIGNER_ADDRESS),\n isSignerContract: () => Promise.resolve(false),\n getChainId: () => Promise.reject(unreachable(callerTag, \"getChainId\")),\n getBalance: () => Promise.reject(unreachable(callerTag, \"getBalance\")),\n estimateGas: () => Promise.reject(unreachable(callerTag, \"estimateGas\")),\n sendTransaction: () => Promise.reject(unreachable(callerTag, \"sendTransaction\")),\n call: () => Promise.reject(unreachable(callerTag, \"call\")),\n send: () => Promise.reject(unreachable(callerTag, \"send\")),\n getTransactionReceipt: () => Promise.reject(unreachable(callerTag, \"getTransactionReceipt\")),\n getCurrentTimeMs: () => Promise.reject(unreachable(callerTag, \"getCurrentTimeMs\")),\n };\n}\n","// Calldata builder for `ExchangeCommitFacet.createOfferAndCommit` —\n// the \"deferred-redemption\" Boson action (Flow A in\n// docs/boson-impl-02-flows.md).\n//\n// Returns the `{ functionName, functionSignature }` pair the buyer's\n// meta-tx typed-data is built over — same pair the on-chain\n// `MetaTransactionsHandlerFacet` recovers signatures against.\n//\n// Implementation note: rather than hand-pin the `functionName` selector\n// string and call `exchanges.iface.encodeCreateOfferAndCommit` here\n// directly, we delegate the whole pair to\n// `@bosonprotocol/core-sdk`'s `metaTx.handler.signMetaTxCreateOfferAndCommit`\n// in `returnTypedDataToSign: true` mode. That's the same helper the\n// client uses to sign, so signing and verification source the\n// `functionName` literal + `functionSignature` bytes from one place.\n// If a future SDK release changes either, both paths track the change\n// automatically.\n\nimport type { FullOfferArgs } from \"@bosonprotocol/common\";\nimport { metaTx } from \"@bosonprotocol/core-sdk\";\nimport type { Hex } from \"viem\";\n\nimport {\n DUMMY_CHAIN_ID,\n DUMMY_METATX_HANDLER_ADDRESS,\n DUMMY_NONCE,\n} from \"../internal/metatx-calldata-constants.js\";\nimport { createCalldataOnlyWeb3LibAdapter } from \"../internal/web3lib-stub.js\";\nimport type { InnerActionCalldata } from \"../types.js\";\n\nexport interface BuildCreateOfferAndCommitCalldataArgs {\n /**\n * Full BPIP-10 offer payload, identical in shape to what core-sdk's\n * `exchanges.iface.encodeCreateOfferAndCommit` accepts. The seller's\n * `signature` field is embedded inside this struct and is verified\n * on-chain by `verifyOffer`.\n */\n fullOffer: FullOfferArgs;\n}\n\nconst STUB_CALLER_TAG = \"@bosonprotocol/x402-evm:create-offer-and-commit\";\n\n/**\n * Build the `{ functionName, functionSignature }` calldata pair for the\n * `createOfferAndCommit` inner action. The result feeds\n * `@bosonprotocol/x402-core/eip712`'s `metaTransactionTypedData`\n * builder to produce the EIP-712 typed-data the buyer signs.\n */\nexport async function buildCreateOfferAndCommitCalldata(\n args: BuildCreateOfferAndCommitCalldataArgs,\n): Promise<InnerActionCalldata> {\n const result = await metaTx.handler.signMetaTxCreateOfferAndCommit({\n web3Lib: createCalldataOnlyWeb3LibAdapter(STUB_CALLER_TAG),\n metaTxHandlerAddress: DUMMY_METATX_HANDLER_ADDRESS,\n chainId: DUMMY_CHAIN_ID,\n nonce: DUMMY_NONCE,\n createOfferAndCommitArgs: args.fullOffer,\n returnTypedDataToSign: true,\n });\n\n return {\n functionName: result.functionName,\n functionSignature: result.functionSignature as Hex,\n };\n}\n","// Calldata builder for `OrchestrationHandlerFacet2.createOfferCommitAndRedeem` —\n// the atomic \"create offer + commit + redeem\" Boson action (Flow B in\n// docs/boson-impl-02-flows.md).\n//\n// Same delegation pattern as `./create-offer-and-commit.ts`: rather than\n// hand-pin the `functionName` selector here, we route the whole\n// `{ functionName, functionSignature }` pair through\n// `@bosonprotocol/core-sdk`'s `metaTx.handler.signMetaTxCreateOfferCommitAndRedeem`\n// in `returnTypedDataToSign: true` mode. That's the same helper the\n// client uses to sign, so signing and verification share one source of\n// truth.\n//\n// Note: the function-argument arity differs from `createOfferAndCommit`\n// (this variant takes `(fullOfferStruct, address offerCreator, bytes\n// sellerSig, uint256 conditionalTokenId)` rather than the\n// deferred-redeem path's longer signature).\n\nimport type { FullOfferArgs } from \"@bosonprotocol/common\";\nimport { metaTx } from \"@bosonprotocol/core-sdk\";\nimport type { Hex } from \"viem\";\n\nimport {\n DUMMY_CHAIN_ID,\n DUMMY_METATX_HANDLER_ADDRESS,\n DUMMY_NONCE,\n} from \"../internal/metatx-calldata-constants.js\";\nimport { createCalldataOnlyWeb3LibAdapter } from \"../internal/web3lib-stub.js\";\nimport type { InnerActionCalldata } from \"../types.js\";\n\nexport interface BuildCreateOfferCommitAndRedeemCalldataArgs {\n /**\n * Full BPIP-10 offer payload, identical in shape to what core-sdk's\n * `orchestration.iface.encodeCreateOfferCommitAndRedeem` accepts. The\n * seller's `signature` field is embedded inside this struct and is\n * verified on-chain by `verifyOffer`.\n */\n fullOffer: FullOfferArgs;\n}\n\nconst STUB_CALLER_TAG = \"@bosonprotocol/x402-evm:create-offer-commit-and-redeem\";\n\n/**\n * Build the `{ functionName, functionSignature }` calldata pair for the\n * `createOfferCommitAndRedeem` inner action.\n */\nexport async function buildCreateOfferCommitAndRedeemCalldata(\n args: BuildCreateOfferCommitAndRedeemCalldataArgs,\n): Promise<InnerActionCalldata> {\n const result = await metaTx.handler.signMetaTxCreateOfferCommitAndRedeem({\n web3Lib: createCalldataOnlyWeb3LibAdapter(STUB_CALLER_TAG),\n metaTxHandlerAddress: DUMMY_METATX_HANDLER_ADDRESS,\n chainId: DUMMY_CHAIN_ID,\n nonce: DUMMY_NONCE,\n createOfferAndCommitArgs: args.fullOffer,\n returnTypedDataToSign: true,\n });\n\n return {\n functionName: result.functionName,\n functionSignature: result.functionSignature as Hex,\n };\n}\n"]}
@@ -0,0 +1,50 @@
1
+ import { Web3LibAdapter } from '@bosonprotocol/common';
2
+ import { WalletClient, PublicClient } from 'viem';
3
+
4
+ /** Tagged error thrown by the adapter when `walletClient.sendTransaction` rejects. */
5
+ declare class RelayerSubmitError extends Error {
6
+ readonly code: RelayerSubmitErrorCode;
7
+ constructor(code: RelayerSubmitErrorCode, message: string, options?: {
8
+ cause?: unknown;
9
+ });
10
+ }
11
+ /** Stable identifiers callers can map to their own error-code vocabulary. */
12
+ type RelayerSubmitErrorCode = "INSUFFICIENT_FUNDS_FOR_GAS" | "ONCHAIN_REVERT" | "INTERNAL_ERROR";
13
+ /**
14
+ * Build the `Web3LibAdapter` that `@bosonprotocol/core-sdk`'s `CoreSDK`
15
+ * accepts for relayer-driven flows.
16
+ *
17
+ * - Writes flow through `walletClient.sendTransaction`; viem errors are
18
+ * re-thrown as a tagged `RelayerSubmitError` so the caller can keep
19
+ * precise classification (insufficient gas funds vs. on-chain revert
20
+ * vs. transport failure).
21
+ * - Reads (`call`, `getBalance`, `estimateGas`, `getTransactionReceipt`)
22
+ * flow through `publicClient`.
23
+ * - `send` rejects: the relayer never signs typed data through the
24
+ * adapter (the buyer already signed off-chain).
25
+ *
26
+ * If either client carries a `chain` (viem populates it when the client
27
+ * was built with an explicit chain) the factory cross-checks its id
28
+ * against the supplied `chainId` and rejects mismatches up-front, so a
29
+ * misconfigured pair fails loudly rather than silently targeting the
30
+ * wrong network.
31
+ */
32
+ declare function walletClientToWeb3LibAdapter(params: {
33
+ walletClient: WalletClient;
34
+ publicClient: PublicClient;
35
+ chainId: number;
36
+ /**
37
+ * Per-call timeout (ms) passed to `publicClient.waitForTransactionReceipt`
38
+ * inside the adapter's `wait()` method, so callers that route through
39
+ * core-sdk's `TransactionResponse.wait()` don't hang indefinitely on a
40
+ * stalled RPC. Defaults to 60s. Direct callers that drive their own
41
+ * receipt polling can ignore it.
42
+ */
43
+ receiptTimeoutMs?: number;
44
+ }): Web3LibAdapter;
45
+ /** Classify a viem error thrown by `walletClient.sendTransaction`. */
46
+ declare function classifyViemSendError(e: unknown): RelayerSubmitError;
47
+
48
+ declare function createCalldataOnlyWeb3LibAdapter(callerTag: string): Web3LibAdapter;
49
+
50
+ export { RelayerSubmitError, type RelayerSubmitErrorCode, classifyViemSendError, createCalldataOnlyWeb3LibAdapter, walletClientToWeb3LibAdapter };
@@ -0,0 +1,165 @@
1
+ 'use strict';
2
+
3
+ var viem = require('viem');
4
+
5
+ // src/adapters/viem-relayer.ts
6
+ var RelayerSubmitError = class extends Error {
7
+ constructor(code, message, options) {
8
+ super(message, options);
9
+ this.name = "RelayerSubmitError";
10
+ this.code = code;
11
+ }
12
+ };
13
+ var DEFAULT_RECEIPT_TIMEOUT_MS = 6e4;
14
+ function walletClientToWeb3LibAdapter(params) {
15
+ const { walletClient, publicClient, chainId } = params;
16
+ const receiptTimeoutMs = params.receiptTimeoutMs ?? DEFAULT_RECEIPT_TIMEOUT_MS;
17
+ if (walletClient.chain && walletClient.chain.id !== chainId) {
18
+ throw new RelayerSubmitError(
19
+ "INTERNAL_ERROR",
20
+ `walletClient.chain.id (${walletClient.chain.id}) does not match adapter chainId (${chainId})`
21
+ );
22
+ }
23
+ if (publicClient.chain && publicClient.chain.id !== chainId) {
24
+ throw new RelayerSubmitError(
25
+ "INTERNAL_ERROR",
26
+ `publicClient.chain.id (${publicClient.chain.id}) does not match adapter chainId (${chainId})`
27
+ );
28
+ }
29
+ return {
30
+ uuid: "x402-evm:viem-relayer-adapter",
31
+ getSignerAddress: async () => {
32
+ const account = walletClient.account;
33
+ if (!account) {
34
+ throw new RelayerSubmitError(
35
+ "INTERNAL_ERROR",
36
+ "walletClient has no account; cannot resolve signer address"
37
+ );
38
+ }
39
+ return account.address;
40
+ },
41
+ isSignerContract: async () => false,
42
+ getChainId: async () => chainId,
43
+ getBalance: async (addressOrName) => {
44
+ const balance = await publicClient.getBalance({ address: addressOrName });
45
+ return balance;
46
+ },
47
+ estimateGas: async (req) => {
48
+ const account = walletClient.account;
49
+ const gas = await publicClient.estimateGas({
50
+ account: account ?? void 0,
51
+ to: req.to,
52
+ data: req.data,
53
+ value: req.value === void 0 ? void 0 : BigInt(req.value.toString())
54
+ });
55
+ return gas;
56
+ },
57
+ sendTransaction: async (req) => {
58
+ const account = walletClient.account;
59
+ if (!account) {
60
+ throw new RelayerSubmitError(
61
+ "INTERNAL_ERROR",
62
+ "walletClient has no account; cannot send transaction"
63
+ );
64
+ }
65
+ let hash;
66
+ try {
67
+ hash = await walletClient.sendTransaction({
68
+ account,
69
+ chain: walletClient.chain ?? null,
70
+ to: req.to,
71
+ data: req.data,
72
+ value: req.value === void 0 ? 0n : BigInt(req.value.toString())
73
+ });
74
+ } catch (e) {
75
+ throw classifyViemSendError(e);
76
+ }
77
+ return {
78
+ hash,
79
+ wait: async (confirmations) => {
80
+ const receipt = await publicClient.waitForTransactionReceipt({
81
+ hash,
82
+ confirmations,
83
+ timeout: receiptTimeoutMs
84
+ });
85
+ return mapReceipt(receipt);
86
+ }
87
+ };
88
+ },
89
+ call: async (req) => {
90
+ const result = await publicClient.call({
91
+ to: req.to,
92
+ data: req.data
93
+ });
94
+ return result.data ?? "0x";
95
+ },
96
+ send: async (method) => {
97
+ throw new RelayerSubmitError(
98
+ "INTERNAL_ERROR",
99
+ `x402-evm: relayer adapter does not support RPC method '${method}'; the relayer never signs typed data`
100
+ );
101
+ },
102
+ getTransactionReceipt: async (txHash) => {
103
+ const receipt = await publicClient.getTransactionReceipt({ hash: txHash });
104
+ return mapReceipt(receipt);
105
+ },
106
+ getCurrentTimeMs: async () => Date.now()
107
+ };
108
+ }
109
+ function mapReceipt(receipt) {
110
+ return {
111
+ from: receipt.from,
112
+ to: receipt.to ?? "",
113
+ status: receipt.status === "success" ? 1 : 0,
114
+ logs: receipt.logs.map((log) => ({ data: log.data, topics: [...log.topics] })),
115
+ transactionHash: receipt.transactionHash,
116
+ effectiveGasPrice: receipt.effectiveGasPrice,
117
+ blockNumber: Number(receipt.blockNumber),
118
+ gasUsed: receipt.gasUsed
119
+ };
120
+ }
121
+ function classifyViemSendError(e) {
122
+ const reason = e instanceof Error ? `sendTransaction failed: ${e.message}` : "sendTransaction failed";
123
+ if (hasViemCause(e, viem.InsufficientFundsError)) {
124
+ return new RelayerSubmitError("INSUFFICIENT_FUNDS_FOR_GAS", reason, { cause: e });
125
+ }
126
+ if (hasViemCause(e, viem.ExecutionRevertedError) || hasViemCause(e, viem.ContractFunctionRevertedError) || hasViemCause(e, viem.RawContractError)) {
127
+ return new RelayerSubmitError("ONCHAIN_REVERT", reason, { cause: e });
128
+ }
129
+ return new RelayerSubmitError("INTERNAL_ERROR", reason, { cause: e });
130
+ }
131
+ function hasViemCause(e, ctor) {
132
+ if (e instanceof ctor) return true;
133
+ if (!(e instanceof viem.BaseError)) return false;
134
+ return e.walk((err) => err instanceof ctor) !== null;
135
+ }
136
+
137
+ // src/internal/web3lib-stub.ts
138
+ var DUMMY_SIGNER_ADDRESS = "0x0000000000000000000000000000000000000001";
139
+ function unreachable(callerTag, method) {
140
+ return new Error(
141
+ `${callerTag}: stub Web3LibAdapter.${method}() should never be called. If you see this, core-sdk changed its typed-data-only behavior.`
142
+ );
143
+ }
144
+ function createCalldataOnlyWeb3LibAdapter(callerTag) {
145
+ return {
146
+ uuid: `${callerTag}:stub`,
147
+ getSignerAddress: () => Promise.resolve(DUMMY_SIGNER_ADDRESS),
148
+ isSignerContract: () => Promise.resolve(false),
149
+ getChainId: () => Promise.reject(unreachable(callerTag, "getChainId")),
150
+ getBalance: () => Promise.reject(unreachable(callerTag, "getBalance")),
151
+ estimateGas: () => Promise.reject(unreachable(callerTag, "estimateGas")),
152
+ sendTransaction: () => Promise.reject(unreachable(callerTag, "sendTransaction")),
153
+ call: () => Promise.reject(unreachable(callerTag, "call")),
154
+ send: () => Promise.reject(unreachable(callerTag, "send")),
155
+ getTransactionReceipt: () => Promise.reject(unreachable(callerTag, "getTransactionReceipt")),
156
+ getCurrentTimeMs: () => Promise.reject(unreachable(callerTag, "getCurrentTimeMs"))
157
+ };
158
+ }
159
+
160
+ exports.RelayerSubmitError = RelayerSubmitError;
161
+ exports.classifyViemSendError = classifyViemSendError;
162
+ exports.createCalldataOnlyWeb3LibAdapter = createCalldataOnlyWeb3LibAdapter;
163
+ exports.walletClientToWeb3LibAdapter = walletClientToWeb3LibAdapter;
164
+ //# sourceMappingURL=index.js.map
165
+ //# sourceMappingURL=index.js.map