@devlab.group/agent-commerce 2.4.1 → 2.6.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/README.md +168 -16
- package/dist/ap2.d.ts +42 -17
- package/dist/ap2.js +83 -27
- package/dist/ap2.js.map +1 -1
- package/dist/{chunk-CXWC5LWM.js → chunk-DRLBML7Z.js} +661 -75
- package/dist/chunk-DRLBML7Z.js.map +1 -0
- package/dist/{chunk-WZW5ORZH.js → chunk-G3EYYHKF.js} +3 -3
- package/dist/{chunk-WZW5ORZH.js.map → chunk-G3EYYHKF.js.map} +1 -1
- package/dist/chunk-GA3O2A7R.js +92 -0
- package/dist/chunk-GA3O2A7R.js.map +1 -0
- package/dist/{chunk-DTKU3Z2M.js → chunk-M52FBNJX.js} +36 -5
- package/dist/chunk-M52FBNJX.js.map +1 -0
- package/dist/chunk-M6BSXXTF.js +8 -0
- package/dist/chunk-M6BSXXTF.js.map +1 -0
- package/dist/{chunk-QPV3EGJO.js → chunk-M6MQ3FYS.js} +25 -4
- package/dist/chunk-M6MQ3FYS.js.map +1 -0
- package/dist/chunk-M6WW6QIT.js +18 -0
- package/dist/chunk-M6WW6QIT.js.map +1 -0
- package/dist/cli/{ap2-GWSP4LYY.js → ap2-2YMYA2H6.js} +85 -29
- package/dist/cli/ap2-2YMYA2H6.js.map +1 -0
- package/dist/cli/{chunk-OZ4LAWBK.js → chunk-3NOMLMJW.js} +29 -8
- package/dist/cli/chunk-3NOMLMJW.js.map +1 -0
- package/dist/cli/chunk-4KLYFXMW.js +8 -0
- package/dist/cli/{chunk-ITWNSS2B.js.map → chunk-4KLYFXMW.js.map} +1 -1
- package/dist/cli/chunk-663ALDZA.js +92 -0
- package/dist/cli/chunk-663ALDZA.js.map +1 -0
- package/dist/cli/chunk-6R6WJ4FD.js +18 -0
- package/dist/cli/chunk-6R6WJ4FD.js.map +1 -0
- package/dist/cli/{chunk-G2JEY7MB.js → chunk-AZL7RPFU.js} +39 -33
- package/dist/cli/chunk-AZL7RPFU.js.map +1 -0
- package/dist/cli/chunk-DHFMIBPG.js +107 -0
- package/dist/cli/chunk-DHFMIBPG.js.map +1 -0
- package/dist/cli/{chunk-QQ3WY5L3.js → chunk-GET3CZGR.js} +36 -104
- package/dist/cli/chunk-GET3CZGR.js.map +1 -0
- package/dist/cli/chunk-NSYSMDQN.js +1544 -0
- package/dist/cli/chunk-NSYSMDQN.js.map +1 -0
- package/dist/cli/{chunk-PIMFPCNZ.js → chunk-PTL7SNOI.js} +313 -138
- package/dist/cli/chunk-PTL7SNOI.js.map +1 -0
- package/dist/cli/chunk-SYQLJXIU.js +105 -0
- package/dist/cli/chunk-SYQLJXIU.js.map +1 -0
- package/dist/cli/chunk-TFV3K6YS.js +373 -0
- package/dist/cli/chunk-TFV3K6YS.js.map +1 -0
- package/dist/cli/{chunk-3MGAJ5FX.js → chunk-VJ4EO4LE.js} +3 -3
- package/dist/cli/{chunk-3MGAJ5FX.js.map → chunk-VJ4EO4LE.js.map} +1 -1
- package/dist/cli/chunk-VJH6RYRK.js +119 -0
- package/dist/cli/chunk-VJH6RYRK.js.map +1 -0
- package/dist/cli/{chunk-TNMLDPUO.js → chunk-YOF7IK4V.js} +663 -77
- package/dist/cli/chunk-YOF7IK4V.js.map +1 -0
- package/dist/cli/{chunk-WYOGIANL.js → chunk-YWG2ZN3L.js} +4 -4
- package/dist/cli/{chunk-WYOGIANL.js.map → chunk-YWG2ZN3L.js.map} +1 -1
- package/dist/cli/config-3K65QJ22.js +12 -0
- package/dist/cli/{config-UI4EDG4L.js.map → config-3K65QJ22.js.map} +1 -1
- package/dist/cli/index.js +753 -212
- package/dist/cli/index.js.map +1 -1
- package/dist/cli/{mcp-PGBRWZVA.js → mcp-6F64A7KE.js} +5 -4
- package/dist/cli/mcp-6F64A7KE.js.map +1 -0
- package/dist/cli/{near-5AY3HWYF.js → near-U6365VFX.js} +15 -4
- package/dist/cli/near-U6365VFX.js.map +1 -0
- package/dist/cli/payment-providers-2ITS6KNR.js +6 -0
- package/dist/cli/payment-providers-2ITS6KNR.js.map +1 -0
- package/dist/cli/{provider-I2ESL6RS.js → provider-5BGG5YKQ.js} +53 -24
- package/dist/cli/provider-5BGG5YKQ.js.map +1 -0
- package/dist/cli/receipts-I4IIE7U6.js +8 -0
- package/dist/cli/receipts-I4IIE7U6.js.map +1 -0
- package/dist/cli/reconcile-55WNCSFC.js +4 -0
- package/dist/cli/reconcile-55WNCSFC.js.map +1 -0
- package/dist/cli/{run-JK4ERPJV.js → run-2P6ZGFUE.js} +356 -173
- package/dist/cli/run-2P6ZGFUE.js.map +1 -0
- package/dist/cli/svm-KDSPDFJG.js +48 -0
- package/dist/cli/svm-KDSPDFJG.js.map +1 -0
- package/dist/cli/{x402-7WBFZQXV.js → x402-4LPIIELI.js} +10 -9
- package/dist/cli/x402-4LPIIELI.js.map +1 -0
- package/dist/index.d.ts +116 -113
- package/dist/index.js +1928 -351
- package/dist/index.js.map +1 -1
- package/dist/logger-CllGwQ8i.d.ts +19 -0
- package/dist/mcp.d.ts +3 -2
- package/dist/mcp.js +2 -1
- package/dist/mcp.js.map +1 -1
- package/dist/mpp.d.ts +2 -1
- package/dist/mpp.js +48 -19
- package/dist/mpp.js.map +1 -1
- package/dist/{near-D6C42VPE.js → near-FH7HPZV3.js} +15 -4
- package/dist/near-FH7HPZV3.js.map +1 -0
- package/dist/{protocol-adapter-C9odYl6l.d.ts → protocol-adapter-1WbtM3xG.d.ts} +12 -85
- package/dist/{runtime-Cl_BLVZV.d.ts → runtime-B-kARa2f.d.ts} +218 -15
- package/dist/store-kIIMpUA-.d.ts +372 -0
- package/dist/svm-KNC3PHMS.js +48 -0
- package/dist/svm-KNC3PHMS.js.map +1 -0
- package/dist/testing.d.ts +51 -0
- package/dist/testing.js +1896 -0
- package/dist/testing.js.map +1 -0
- package/dist/transaction-Dv0UFGg5.d.ts +129 -0
- package/dist/{types-j7MnUXYN.d.ts → types-DWqjz81-.d.ts} +5 -2
- package/dist/x402.d.ts +2 -1
- package/dist/x402.js +6 -5
- package/dist/x402.js.map +1 -1
- package/package.json +5 -1
- package/dist/authorization-DjAecwuW.d.ts +0 -115
- package/dist/chunk-CXWC5LWM.js.map +0 -1
- package/dist/chunk-DTKU3Z2M.js.map +0 -1
- package/dist/chunk-KA2AX5FH.js +0 -44
- package/dist/chunk-KA2AX5FH.js.map +0 -1
- package/dist/chunk-QPV3EGJO.js.map +0 -1
- package/dist/cli/ap2-GWSP4LYY.js.map +0 -1
- package/dist/cli/chunk-G2JEY7MB.js.map +0 -1
- package/dist/cli/chunk-GJIMDMYT.js +0 -639
- package/dist/cli/chunk-GJIMDMYT.js.map +0 -1
- package/dist/cli/chunk-ITWNSS2B.js +0 -8
- package/dist/cli/chunk-OSTCU6ZK.js +0 -44
- package/dist/cli/chunk-OSTCU6ZK.js.map +0 -1
- package/dist/cli/chunk-OZ4LAWBK.js.map +0 -1
- package/dist/cli/chunk-PIMFPCNZ.js.map +0 -1
- package/dist/cli/chunk-QQ3WY5L3.js.map +0 -1
- package/dist/cli/chunk-TNMLDPUO.js.map +0 -1
- package/dist/cli/config-UI4EDG4L.js +0 -11
- package/dist/cli/mcp-PGBRWZVA.js.map +0 -1
- package/dist/cli/near-5AY3HWYF.js.map +0 -1
- package/dist/cli/provider-I2ESL6RS.js.map +0 -1
- package/dist/cli/run-JK4ERPJV.js.map +0 -1
- package/dist/cli/svm-3MMYFPC7.js +0 -33
- package/dist/cli/svm-3MMYFPC7.js.map +0 -1
- package/dist/cli/x402-7WBFZQXV.js.map +0 -1
- package/dist/near-D6C42VPE.js.map +0 -1
- package/dist/svm-QEUAUNPQ.js +0 -33
- package/dist/svm-QEUAUNPQ.js.map +0 -1
|
@@ -1,9 +1,10 @@
|
|
|
1
|
-
import { isWellKnownDevKey, findX402Network, normalizeAddress, assertPayToIsNotDevAddress, resolveX402Deployment, assertDevKeyIsLocalOnly, describeRpc, X402_DEFAULT_PAYMENT_FLOW, REUSE_REJECTED_AUTHORIZATION_METADATA_KEY, SETTLE_AFTER_BACKEND_METADATA_KEY, sameAddress, LOCAL_CHAIN_ID, isTransactionReference, x402OfferName, isEvmAddress, describeDeploymentMode } from './chunk-
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
1
|
+
import { isWellKnownDevKey, findX402Network, normalizeAddress, assertPayToIsNotDevAddress, resolveX402Deployment, assertDevKeyIsLocalOnly, describeRpc, canonicalJson, X402_DEFAULT_PAYMENT_FLOW, REUSE_REJECTED_AUTHORIZATION_METADATA_KEY, SETTLE_AFTER_BACKEND_METADATA_KEY, sameAddress, LOCAL_CHAIN_ID, isTransactionReference, x402OfferName, isEvmAddress, describeDeploymentMode } from './chunk-M6MQ3FYS.js';
|
|
2
|
+
import { PACKAGE_VERSION } from './chunk-M6BSXXTF.js';
|
|
3
|
+
import { CommerceError, systemClock, NOOP_LOGGER, redactedErrorText, RECONCILIATION_METADATA_KEY, isCommerceError } from './chunk-M52FBNJX.js';
|
|
4
|
+
import { LOCATOR_VERSION, eip3009Locator, computeReplayKey, permit2Locator, computePermit2ReplayKey, isoFromSeconds } from './chunk-GA3O2A7R.js';
|
|
4
5
|
import { isRecord } from './chunk-2CJNA7MS.js';
|
|
5
|
-
import { x402ExactPermit2ProxyAddress, toFacilitatorEvmSigner, PERMIT2_ADDRESS } from '@x402/evm';
|
|
6
|
-
import { isAddress, keccak256, stringToBytes, getAddress, formatUnits, createWalletClient, http, publicActions, createPublicClient, HttpRequestError, TimeoutError, WaitForTransactionReceiptTimeoutError, BaseError, ContractFunctionRevertedError, erc20Abi } from 'viem';
|
|
6
|
+
import { x402ExactPermit2ProxyAddress, toFacilitatorEvmSigner, PERMIT2_ADDRESS, eip3009ABI, x402ExactPermit2ProxyABI } from '@x402/evm';
|
|
7
|
+
import { parseAbi, isAddress, keccak256, stringToBytes, isHash, getAddress, formatUnits, createWalletClient, http, publicActions, createPublicClient, HttpRequestError, TimeoutError, WaitForTransactionReceiptTimeoutError, BaseError, ContractFunctionRevertedError, erc20Abi, parseEventLogs, isAddressEqual, TransactionReceiptNotFoundError, decodeFunctionData } from 'viem';
|
|
7
8
|
import { privateKeyToAccount } from 'viem/accounts';
|
|
8
9
|
import { HTTPFacilitatorClient } from '@x402/core/http';
|
|
9
10
|
import { SettleError, VerifyError } from '@x402/core/types';
|
|
@@ -24,10 +25,9 @@ var DEFAULT_IDS = {
|
|
|
24
25
|
|
|
25
26
|
// src/payments/x402/provider/fee-payer.ts
|
|
26
27
|
var SUPPORTED_TTL_MS = 6e4;
|
|
27
|
-
function
|
|
28
|
+
function createSupportedSource(ctx) {
|
|
28
29
|
const { clock, remoteBinding } = ctx;
|
|
29
30
|
let supportedSnapshot;
|
|
30
|
-
const feePayers = /* @__PURE__ */ new Map();
|
|
31
31
|
function currentSupported() {
|
|
32
32
|
const now = clock.monotonicMs();
|
|
33
33
|
if (supportedSnapshot && now - supportedSnapshot.at < SUPPORTED_TTL_MS) {
|
|
@@ -42,6 +42,10 @@ function createSvmFeePayerSource(ctx) {
|
|
|
42
42
|
});
|
|
43
43
|
return response;
|
|
44
44
|
}
|
|
45
|
+
return currentSupported;
|
|
46
|
+
}
|
|
47
|
+
function createSvmFeePayerSource(currentSupported) {
|
|
48
|
+
const feePayers = /* @__PURE__ */ new Map();
|
|
45
49
|
async function svmFeePayer(offer) {
|
|
46
50
|
let supported;
|
|
47
51
|
try {
|
|
@@ -70,6 +74,43 @@ function createSvmFeePayerSource(ctx) {
|
|
|
70
74
|
}
|
|
71
75
|
return svmFeePayer;
|
|
72
76
|
}
|
|
77
|
+
function createNearRelayerSource(currentSupported, logger) {
|
|
78
|
+
return async (offer) => {
|
|
79
|
+
let supported;
|
|
80
|
+
try {
|
|
81
|
+
supported = await currentSupported();
|
|
82
|
+
} catch (err) {
|
|
83
|
+
logger.warn(
|
|
84
|
+
{ err: redactedErrorText(err) },
|
|
85
|
+
`x402 verify(): facilitator ${offer.binding.describe} did not answer /supported; the NEAR locator names no relayer`
|
|
86
|
+
);
|
|
87
|
+
return [];
|
|
88
|
+
}
|
|
89
|
+
const { signers } = supported;
|
|
90
|
+
return [.../* @__PURE__ */ new Set([...signers[offer.network] ?? [], ...signers["near:*"] ?? []])];
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
// src/payments/x402/json-rpc.ts
|
|
95
|
+
async function jsonRpc(rpcUrl, method, params, timeoutMs) {
|
|
96
|
+
const response = await fetch(rpcUrl, {
|
|
97
|
+
method: "POST",
|
|
98
|
+
headers: { "content-type": "application/json" },
|
|
99
|
+
body: JSON.stringify({ jsonrpc: "2.0", id: 1, method, params }),
|
|
100
|
+
signal: AbortSignal.timeout(timeoutMs)
|
|
101
|
+
});
|
|
102
|
+
const body = await response.json();
|
|
103
|
+
if (body.error !== void 0) {
|
|
104
|
+
throw new CommerceError(
|
|
105
|
+
"PAYMENT_PROVIDER_UNAVAILABLE",
|
|
106
|
+
`RPC ${method} failed: ${JSON.stringify(body.error)}`,
|
|
107
|
+
{ details: { rpcError: body.error } }
|
|
108
|
+
);
|
|
109
|
+
}
|
|
110
|
+
return body.result;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
// src/payments/x402/provider/health.ts
|
|
73
114
|
function createHealthCheck(ctx) {
|
|
74
115
|
const { offers, clock, deploymentMode, remoteBinding, svm, near } = ctx;
|
|
75
116
|
async function offerHealth(offer, kinds) {
|
|
@@ -143,7 +184,7 @@ function createHealthCheck(ctx) {
|
|
|
143
184
|
async function svmOfferHealth(offer, kinds) {
|
|
144
185
|
const { profile, rpcOrigin, binding } = offer;
|
|
145
186
|
const svmModule = await svm();
|
|
146
|
-
const genesis = await
|
|
187
|
+
const genesis = await rpc(offer.rpcUrl, "getGenesisHash", []);
|
|
147
188
|
const cluster = typeof genesis === "string" ? `solana:${genesis.slice(0, 32)}` : void 0;
|
|
148
189
|
if (cluster !== offer.network) {
|
|
149
190
|
return {
|
|
@@ -151,10 +192,7 @@ function createHealthCheck(ctx) {
|
|
|
151
192
|
detail: `RPC at ${rpcOrigin} serves ${cluster ?? "an unknown cluster"}, expected ${offer.network} (${profile.displayName})`
|
|
152
193
|
};
|
|
153
194
|
}
|
|
154
|
-
const mint = await
|
|
155
|
-
offer.asset,
|
|
156
|
-
{ encoding: "base64" }
|
|
157
|
-
]);
|
|
195
|
+
const mint = await rpc(offer.rpcUrl, "getAccountInfo", [offer.asset, { encoding: "base64" }]);
|
|
158
196
|
const mintInfo = readMint(mint);
|
|
159
197
|
if (mintInfo === void 0) {
|
|
160
198
|
return {
|
|
@@ -174,7 +212,7 @@ function createHealthCheck(ctx) {
|
|
|
174
212
|
offer.asset,
|
|
175
213
|
tokenProgram
|
|
176
214
|
);
|
|
177
|
-
const account = await
|
|
215
|
+
const account = await rpc(offer.rpcUrl, "getAccountInfo", [
|
|
178
216
|
payeeAccount,
|
|
179
217
|
{ encoding: "base64" }
|
|
180
218
|
]);
|
|
@@ -202,7 +240,7 @@ function createHealthCheck(ctx) {
|
|
|
202
240
|
async function nearOfferHealth(offer, kinds) {
|
|
203
241
|
const { profile, rpcOrigin, binding, rpcUrl } = offer;
|
|
204
242
|
await near();
|
|
205
|
-
const status = await
|
|
243
|
+
const status = await rpc(rpcUrl, "status", []);
|
|
206
244
|
const chainId = isRecord(status) ? status["chain_id"] : void 0;
|
|
207
245
|
const expected = offer.network.slice("near:".length);
|
|
208
246
|
if (chainId !== expected) {
|
|
@@ -211,7 +249,7 @@ function createHealthCheck(ctx) {
|
|
|
211
249
|
detail: `RPC at ${rpcOrigin} serves chain ${String(chainId ?? "unknown")}, expected ${expected} (${profile.displayName})`
|
|
212
250
|
};
|
|
213
251
|
}
|
|
214
|
-
const token = await
|
|
252
|
+
const token = await rpc(rpcUrl, "query", {
|
|
215
253
|
request_type: "view_account",
|
|
216
254
|
finality: "final",
|
|
217
255
|
account_id: offer.asset
|
|
@@ -329,24 +367,9 @@ function readMint(result) {
|
|
|
329
367
|
const decimals = bytes[44];
|
|
330
368
|
return bytes.length >= 82 && bytes[45] === 1 && decimals !== void 0 ? { decimals, tokenProgram: owner } : void 0;
|
|
331
369
|
}
|
|
332
|
-
|
|
333
|
-
const response = await fetch(rpcUrl, {
|
|
334
|
-
method: "POST",
|
|
335
|
-
headers: { "content-type": "application/json" },
|
|
336
|
-
body: JSON.stringify({ jsonrpc: "2.0", id: 1, method, params }),
|
|
337
|
-
signal: AbortSignal.timeout(HEALTH_TIMEOUT_MS)
|
|
338
|
-
});
|
|
339
|
-
const body = await response.json();
|
|
340
|
-
if (body.error !== void 0) {
|
|
341
|
-
throw new CommerceError(
|
|
342
|
-
"PAYMENT_PROVIDER_UNAVAILABLE",
|
|
343
|
-
`RPC ${method} failed: ${JSON.stringify(body.error)}`
|
|
344
|
-
);
|
|
345
|
-
}
|
|
346
|
-
return body.result;
|
|
347
|
-
}
|
|
370
|
+
var rpc = (rpcUrl, method, params) => jsonRpc(rpcUrl, method, params, HEALTH_TIMEOUT_MS);
|
|
348
371
|
async function nearView(rpcUrl, accountId, method, args) {
|
|
349
|
-
const result = await
|
|
372
|
+
const result = await rpc(rpcUrl, "query", {
|
|
350
373
|
request_type: "call_function",
|
|
351
374
|
finality: "final",
|
|
352
375
|
account_id: accountId,
|
|
@@ -391,7 +414,7 @@ function buildLocalChain(rpcUrl, chainId = LOCAL_CHAIN_ID) {
|
|
|
391
414
|
function createLocalPublicClient(rpcUrl, timeoutMs, chainId) {
|
|
392
415
|
return createPublicClient({
|
|
393
416
|
chain: buildLocalChain(rpcUrl, chainId),
|
|
394
|
-
transport: http(rpcUrl, { timeout: timeoutMs } )
|
|
417
|
+
transport: http(rpcUrl, timeoutMs !== void 0 ? { timeout: timeoutMs } : void 0)
|
|
395
418
|
});
|
|
396
419
|
}
|
|
397
420
|
function createLocalFacilitatorClient(rpcUrl, signerPrivateKey, chainId) {
|
|
@@ -770,29 +793,6 @@ function offerCurrency(offer, quoted) {
|
|
|
770
793
|
const canonical = offer.profile.canonicalAsset;
|
|
771
794
|
return canonical !== void 0 && sameAddress(offer.profile, offer.asset, canonical.address) ? canonical.symbol : quoted;
|
|
772
795
|
}
|
|
773
|
-
|
|
774
|
-
// src/core/canonical-json.ts
|
|
775
|
-
var LONE_SURROGATE = new RegExp("\\p{Cs}", "u");
|
|
776
|
-
function canonicalJson(value) {
|
|
777
|
-
if (typeof value === "string")
|
|
778
|
-
return LONE_SURROGATE.test(value) ? void 0 : JSON.stringify(value);
|
|
779
|
-
if (typeof value === "number") return Number.isFinite(value) ? JSON.stringify(value) : void 0;
|
|
780
|
-
if (value === null || typeof value === "boolean") return JSON.stringify(value);
|
|
781
|
-
if (Array.isArray(value)) {
|
|
782
|
-
const items = value.map(canonicalJson);
|
|
783
|
-
return items.includes(void 0) ? void 0 : `[${items.join(",")}]`;
|
|
784
|
-
}
|
|
785
|
-
if (typeof value !== "object") return void 0;
|
|
786
|
-
const members = [];
|
|
787
|
-
for (const key of Object.keys(value).sort()) {
|
|
788
|
-
const member = canonicalJson(value[key]);
|
|
789
|
-
if (member === void 0 || LONE_SURROGATE.test(key)) return void 0;
|
|
790
|
-
members.push(`${JSON.stringify(key)}:${member}`);
|
|
791
|
-
}
|
|
792
|
-
return `{${members.join(",")}}`;
|
|
793
|
-
}
|
|
794
|
-
|
|
795
|
-
// src/payments/x402/provider/quote.ts
|
|
796
796
|
var QUOTE_EXTENSION = "erc-8409";
|
|
797
797
|
var QUOTE_REQUEST_SCHEME = "agent-commerce/request/v1";
|
|
798
798
|
var QUOTE_DOMAIN = { name: "Signed Service Payment Quotes", version: "1" };
|
|
@@ -936,6 +936,553 @@ function quoteRequestHash(resourceId, input) {
|
|
|
936
936
|
const canonical = canonicalJson({ input, resource: resourceId });
|
|
937
937
|
return canonical === void 0 ? void 0 : keccak256(stringToBytes(canonical));
|
|
938
938
|
}
|
|
939
|
+
var EVENTS = parseAbi([
|
|
940
|
+
"event AuthorizationUsed(address indexed authorizer, bytes32 indexed nonce)",
|
|
941
|
+
"event Transfer(address indexed from, address indexed to, uint256 value)"
|
|
942
|
+
]);
|
|
943
|
+
var NONCE_BITMAP_ABI = parseAbi([
|
|
944
|
+
"function nonceBitmap(address owner, uint256 wordPosition) view returns (uint256)"
|
|
945
|
+
]);
|
|
946
|
+
var CLOCK_MARGIN_SECONDS = 900n;
|
|
947
|
+
var LOG_CHUNK_BLOCKS = 10000n;
|
|
948
|
+
var MAX_WINDOW_BLOCKS = 200000n;
|
|
949
|
+
var UINT = /^\d{1,78}$/;
|
|
950
|
+
function parseEvmLocator(locator) {
|
|
951
|
+
const address = (key) => {
|
|
952
|
+
const value = locator[key];
|
|
953
|
+
return typeof value === "string" && isAddress(value) ? value : void 0;
|
|
954
|
+
};
|
|
955
|
+
const uint = (key) => {
|
|
956
|
+
const value = locator[key];
|
|
957
|
+
return typeof value === "string" && UINT.test(value) ? BigInt(value) : void 0;
|
|
958
|
+
};
|
|
959
|
+
const expiresAt = typeof locator["expiresAt"] === "string" ? locator["expiresAt"] : void 0;
|
|
960
|
+
if (locator["method"] === "eip3009") {
|
|
961
|
+
const [asset, from, to] = [address("asset"), address("from"), address("to")];
|
|
962
|
+
const [value, validAfter, validBefore] = [
|
|
963
|
+
uint("value"),
|
|
964
|
+
uint("validAfter"),
|
|
965
|
+
uint("validBefore")
|
|
966
|
+
];
|
|
967
|
+
const nonce = locator["nonce"];
|
|
968
|
+
if (!asset || !from || !to || value === void 0 || validAfter === void 0) return void 0;
|
|
969
|
+
if (validBefore === void 0 || typeof nonce !== "string" || !isHash(nonce)) return void 0;
|
|
970
|
+
return { method: "eip3009", asset, from, to, value, nonce, validAfter, validBefore, expiresAt };
|
|
971
|
+
}
|
|
972
|
+
if (locator["method"] === "permit2") {
|
|
973
|
+
const [asset, owner, to, proxy] = [
|
|
974
|
+
address("asset"),
|
|
975
|
+
address("owner"),
|
|
976
|
+
address("to"),
|
|
977
|
+
address("proxy")
|
|
978
|
+
];
|
|
979
|
+
const [amount, nonce, deadline, validAfter] = [
|
|
980
|
+
uint("amount"),
|
|
981
|
+
uint("nonce"),
|
|
982
|
+
uint("deadline"),
|
|
983
|
+
uint("validAfter")
|
|
984
|
+
];
|
|
985
|
+
if (!asset || !owner || !to || !proxy || amount === void 0 || nonce === void 0) {
|
|
986
|
+
return void 0;
|
|
987
|
+
}
|
|
988
|
+
if (deadline === void 0 || validAfter === void 0) return void 0;
|
|
989
|
+
return {
|
|
990
|
+
method: "permit2",
|
|
991
|
+
asset,
|
|
992
|
+
owner,
|
|
993
|
+
to,
|
|
994
|
+
amount,
|
|
995
|
+
nonce,
|
|
996
|
+
deadline,
|
|
997
|
+
validAfter,
|
|
998
|
+
proxy,
|
|
999
|
+
expiresAt
|
|
1000
|
+
};
|
|
1001
|
+
}
|
|
1002
|
+
return void 0;
|
|
1003
|
+
}
|
|
1004
|
+
async function readEvmEvidence(input) {
|
|
1005
|
+
const { client, chainId, locator, attempt } = input;
|
|
1006
|
+
const reported = await client.getChainId();
|
|
1007
|
+
if (reported !== chainId) {
|
|
1008
|
+
return unknown("chain_mismatch", { chainId: reported, expectedChainId: chainId });
|
|
1009
|
+
}
|
|
1010
|
+
const finalized = await client.getBlock({ blockTag: "finalized" });
|
|
1011
|
+
const finalizedAt = isoFromSeconds(String(finalized.timestamp));
|
|
1012
|
+
const finality = {
|
|
1013
|
+
finalizedBlock: String(finalized.number),
|
|
1014
|
+
...finalizedAt !== void 0 ? { finalizedAt } : {}
|
|
1015
|
+
};
|
|
1016
|
+
const method = locator.method === "eip3009" ? eip3009(client, locator) : permit2(client, locator);
|
|
1017
|
+
const settled = (hash, block) => block <= finalized.number ? {
|
|
1018
|
+
outcome: "settled",
|
|
1019
|
+
reason: "transfer_final",
|
|
1020
|
+
externalReference: hash,
|
|
1021
|
+
evidence: { transactionHash: hash, blockNumber: String(block), ...finality }
|
|
1022
|
+
} : unknown("not_final", { transactionHash: hash, blockNumber: String(block), ...finality });
|
|
1023
|
+
const reference = attempt.externalReference;
|
|
1024
|
+
if (reference !== void 0 && isHash(reference)) {
|
|
1025
|
+
const block = await method.carries(reference);
|
|
1026
|
+
if (block !== void 0) return settled(reference, block);
|
|
1027
|
+
}
|
|
1028
|
+
if (!await method.used(finalized.number)) {
|
|
1029
|
+
if (finalized.timestamp >= method.endsAt) {
|
|
1030
|
+
return {
|
|
1031
|
+
outcome: "not-settled",
|
|
1032
|
+
reason: "expired_unused",
|
|
1033
|
+
evidence: { nonceUsed: false, ...finality }
|
|
1034
|
+
};
|
|
1035
|
+
}
|
|
1036
|
+
if (await method.used()) return unknown("not_final", finality);
|
|
1037
|
+
return {
|
|
1038
|
+
...unknown("not_expired", finality),
|
|
1039
|
+
...locator.expiresAt !== void 0 ? { retryAfter: locator.expiresAt } : {}
|
|
1040
|
+
};
|
|
1041
|
+
}
|
|
1042
|
+
const createdAt = BigInt(Math.floor(Date.parse(attempt.createdAt) / 1e3));
|
|
1043
|
+
const fromSeconds = max(method.validAfter, createdAt - CLOCK_MARGIN_SECONDS);
|
|
1044
|
+
const fromBlock = await firstBlockAt(client, fromSeconds, finalized);
|
|
1045
|
+
const endBlock = await firstBlockAt(client, method.endsAt, finalized) - 1n;
|
|
1046
|
+
const toBlock = min(endBlock, fromBlock + MAX_WINDOW_BLOCKS - 1n);
|
|
1047
|
+
const window = { fromBlock: String(fromBlock), toBlock: String(toBlock), ...finality };
|
|
1048
|
+
for (const [start, end] of logRanges(fromBlock, toBlock)) {
|
|
1049
|
+
for (const hash of await method.candidates(start, end)) {
|
|
1050
|
+
const block = await method.carries(hash);
|
|
1051
|
+
if (block !== void 0) return settled(hash, block);
|
|
1052
|
+
}
|
|
1053
|
+
}
|
|
1054
|
+
if (toBlock < endBlock) {
|
|
1055
|
+
return unknown("search_window_too_wide", { ...window, endBlock: String(endBlock) });
|
|
1056
|
+
}
|
|
1057
|
+
return unknown("used_without_record", { nonceUsed: true, ...window });
|
|
1058
|
+
}
|
|
1059
|
+
function eip3009(client, locator) {
|
|
1060
|
+
const { asset, from, to, value, nonce } = locator;
|
|
1061
|
+
return {
|
|
1062
|
+
endsAt: locator.validBefore,
|
|
1063
|
+
validAfter: locator.validAfter,
|
|
1064
|
+
used: (blockNumber) => client.readContract({
|
|
1065
|
+
address: asset,
|
|
1066
|
+
abi: eip3009ABI,
|
|
1067
|
+
functionName: "authorizationState",
|
|
1068
|
+
args: [from, nonce],
|
|
1069
|
+
...blockNumber !== void 0 ? { blockNumber } : {}
|
|
1070
|
+
}),
|
|
1071
|
+
async candidates(fromBlock, toBlock) {
|
|
1072
|
+
const logs = await client.getLogs({
|
|
1073
|
+
address: asset,
|
|
1074
|
+
event: EVENTS[0],
|
|
1075
|
+
args: { authorizer: from, nonce },
|
|
1076
|
+
fromBlock,
|
|
1077
|
+
toBlock
|
|
1078
|
+
});
|
|
1079
|
+
return logs.map((log) => log.transactionHash);
|
|
1080
|
+
},
|
|
1081
|
+
async carries(hash) {
|
|
1082
|
+
const receipt = await receiptOf(client, hash);
|
|
1083
|
+
if (receipt?.status !== "success") return void 0;
|
|
1084
|
+
const logs = parseEventLogs({ abi: EVENTS, logs: receipt.logs }).filter(
|
|
1085
|
+
(log) => isAddressEqual(log.address, asset)
|
|
1086
|
+
);
|
|
1087
|
+
const used = logs.some(
|
|
1088
|
+
(log) => log.eventName === "AuthorizationUsed" && isAddressEqual(log.args.authorizer, from) && log.args.nonce.toLowerCase() === nonce.toLowerCase()
|
|
1089
|
+
);
|
|
1090
|
+
return used && logs.some((log) => isTransfer(log, from, to, value)) ? receipt.blockNumber : void 0;
|
|
1091
|
+
}
|
|
1092
|
+
};
|
|
1093
|
+
}
|
|
1094
|
+
function permit2(client, locator) {
|
|
1095
|
+
const { asset, owner, to, amount, nonce, proxy } = locator;
|
|
1096
|
+
return {
|
|
1097
|
+
// Permit2 accepts a transfer while the timestamp is at most the deadline
|
|
1098
|
+
endsAt: locator.deadline + 1n,
|
|
1099
|
+
validAfter: locator.validAfter,
|
|
1100
|
+
async used(blockNumber) {
|
|
1101
|
+
const bitmap = await client.readContract({
|
|
1102
|
+
address: PERMIT2_ADDRESS,
|
|
1103
|
+
abi: NONCE_BITMAP_ABI,
|
|
1104
|
+
functionName: "nonceBitmap",
|
|
1105
|
+
args: [owner, nonce >> 8n],
|
|
1106
|
+
...blockNumber !== void 0 ? { blockNumber } : {}
|
|
1107
|
+
});
|
|
1108
|
+
return (bitmap >> (nonce & 0xffn) & 1n) === 1n;
|
|
1109
|
+
},
|
|
1110
|
+
// Match the nonce in proxy calldata to distinguish transfers with the
|
|
1111
|
+
// same owner, recipient and amount
|
|
1112
|
+
async candidates(fromBlock, toBlock) {
|
|
1113
|
+
const logs = await client.getLogs({
|
|
1114
|
+
address: asset,
|
|
1115
|
+
event: EVENTS[1],
|
|
1116
|
+
args: { from: owner, to },
|
|
1117
|
+
fromBlock,
|
|
1118
|
+
toBlock
|
|
1119
|
+
});
|
|
1120
|
+
return [...new Set(logs.map((log) => log.transactionHash))];
|
|
1121
|
+
},
|
|
1122
|
+
async carries(hash) {
|
|
1123
|
+
const receipt = await receiptOf(client, hash);
|
|
1124
|
+
if (receipt?.status !== "success" || !receipt.to || !isAddressEqual(receipt.to, proxy)) {
|
|
1125
|
+
return void 0;
|
|
1126
|
+
}
|
|
1127
|
+
const call = proxyCall((await client.getTransaction({ hash })).input);
|
|
1128
|
+
const named = call !== void 0 && isAddressEqual(call.owner, owner) && call.nonce === nonce && isAddressEqual(call.asset, asset) && isAddressEqual(call.to, to);
|
|
1129
|
+
const transferred = parseEventLogs({ abi: EVENTS, logs: receipt.logs }).some(
|
|
1130
|
+
(log) => isAddressEqual(log.address, asset) && isTransfer(log, owner, to, amount)
|
|
1131
|
+
);
|
|
1132
|
+
return named && transferred ? receipt.blockNumber : void 0;
|
|
1133
|
+
}
|
|
1134
|
+
};
|
|
1135
|
+
}
|
|
1136
|
+
function proxyCall(input) {
|
|
1137
|
+
let call;
|
|
1138
|
+
try {
|
|
1139
|
+
call = decodeProxyInput(input);
|
|
1140
|
+
} catch {
|
|
1141
|
+
return void 0;
|
|
1142
|
+
}
|
|
1143
|
+
const parts = call.functionName === "settle" ? call.args : call.functionName === "settleWithPermit" ? [call.args[1], call.args[2], call.args[3]] : void 0;
|
|
1144
|
+
if (parts === void 0) return void 0;
|
|
1145
|
+
const [permit, owner, witness] = parts;
|
|
1146
|
+
return { owner, nonce: permit.nonce, asset: permit.permitted.token, to: witness.to };
|
|
1147
|
+
}
|
|
1148
|
+
var decodeProxyInput = (data) => decodeFunctionData({ abi: x402ExactPermit2ProxyABI, data });
|
|
1149
|
+
function isTransfer(log, from, to, value) {
|
|
1150
|
+
return log.eventName === "Transfer" && isAddressEqual(log.args.from, from) && isAddressEqual(log.args.to, to) && log.args.value === value;
|
|
1151
|
+
}
|
|
1152
|
+
async function receiptOf(client, hash) {
|
|
1153
|
+
try {
|
|
1154
|
+
return await client.getTransactionReceipt({ hash });
|
|
1155
|
+
} catch (err) {
|
|
1156
|
+
if (err instanceof TransactionReceiptNotFoundError) return void 0;
|
|
1157
|
+
throw err;
|
|
1158
|
+
}
|
|
1159
|
+
}
|
|
1160
|
+
function logRanges(fromBlock, toBlock) {
|
|
1161
|
+
const ranges = [];
|
|
1162
|
+
for (let start = fromBlock; start <= toBlock; start += LOG_CHUNK_BLOCKS) {
|
|
1163
|
+
ranges.push([start, min(start + LOG_CHUNK_BLOCKS - 1n, toBlock)]);
|
|
1164
|
+
}
|
|
1165
|
+
return ranges;
|
|
1166
|
+
}
|
|
1167
|
+
async function firstBlockAt(client, seconds, finalized) {
|
|
1168
|
+
if (seconds > finalized.timestamp) return finalized.number + 1n;
|
|
1169
|
+
const timestampOf = async (blockNumber) => (await client.getBlock({ blockNumber })).timestamp;
|
|
1170
|
+
let low = 0n;
|
|
1171
|
+
let lowTime = await timestampOf(low);
|
|
1172
|
+
if (lowTime >= seconds) return 0n;
|
|
1173
|
+
let high = finalized.number;
|
|
1174
|
+
let highTime = finalized.timestamp;
|
|
1175
|
+
for (let step = 0; high - low > 1n; step++) {
|
|
1176
|
+
let middle = (low + high) / 2n;
|
|
1177
|
+
if (step % 2 === 0 && highTime > lowTime) {
|
|
1178
|
+
const guess = low + (seconds - lowTime) * (high - low) / (highTime - lowTime);
|
|
1179
|
+
middle = min(max(guess, low + 1n), high - 1n);
|
|
1180
|
+
}
|
|
1181
|
+
const timestamp = await timestampOf(middle);
|
|
1182
|
+
if (timestamp >= seconds) [high, highTime] = [middle, timestamp];
|
|
1183
|
+
else [low, lowTime] = [middle, timestamp];
|
|
1184
|
+
}
|
|
1185
|
+
return high;
|
|
1186
|
+
}
|
|
1187
|
+
function unknown(reason, evidence) {
|
|
1188
|
+
return { outcome: "unknown", reason, ...evidence !== void 0 ? { evidence } : {} };
|
|
1189
|
+
}
|
|
1190
|
+
var max = (a, b) => a > b ? a : b;
|
|
1191
|
+
var min = (a, b) => a < b ? a : b;
|
|
1192
|
+
|
|
1193
|
+
// src/payments/x402/reconcile/near.ts
|
|
1194
|
+
var UINT2 = /^\d{1,20}$/;
|
|
1195
|
+
var TX_HASH = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
|
|
1196
|
+
function parseNearLocator(locator) {
|
|
1197
|
+
const text = (key) => {
|
|
1198
|
+
const value = locator[key];
|
|
1199
|
+
return typeof value === "string" && value !== "" ? value : void 0;
|
|
1200
|
+
};
|
|
1201
|
+
const uint = (key) => {
|
|
1202
|
+
const value = text(key);
|
|
1203
|
+
return value !== void 0 && UINT2.test(value) ? value : void 0;
|
|
1204
|
+
};
|
|
1205
|
+
const [senderId, publicKey, asset, receiver] = [
|
|
1206
|
+
text("senderId"),
|
|
1207
|
+
text("publicKey"),
|
|
1208
|
+
text("asset"),
|
|
1209
|
+
text("receiver")
|
|
1210
|
+
];
|
|
1211
|
+
const [nonce, maxBlockHeight, amount] = [uint("nonce"), uint("maxBlockHeight"), uint("amount")];
|
|
1212
|
+
const relayers = locator["relayers"] ?? [];
|
|
1213
|
+
if (!senderId || !publicKey || !asset || !receiver || !nonce || !maxBlockHeight || !amount) {
|
|
1214
|
+
return void 0;
|
|
1215
|
+
}
|
|
1216
|
+
if (!Array.isArray(relayers) || !relayers.every((id) => typeof id === "string")) {
|
|
1217
|
+
return void 0;
|
|
1218
|
+
}
|
|
1219
|
+
return {
|
|
1220
|
+
senderId,
|
|
1221
|
+
publicKey,
|
|
1222
|
+
nonce: BigInt(nonce),
|
|
1223
|
+
maxBlockHeight: BigInt(maxBlockHeight),
|
|
1224
|
+
asset,
|
|
1225
|
+
receiver,
|
|
1226
|
+
amount,
|
|
1227
|
+
relayers
|
|
1228
|
+
};
|
|
1229
|
+
}
|
|
1230
|
+
async function readNearEvidence(input) {
|
|
1231
|
+
const { rpc: rpc2, network, locator, attempt } = input;
|
|
1232
|
+
const status = await rpc2("status", []);
|
|
1233
|
+
const chainId = isRecord(status) ? status["chain_id"] : void 0;
|
|
1234
|
+
const expected = network.slice("near:".length);
|
|
1235
|
+
if (chainId !== expected) {
|
|
1236
|
+
return unknown("chain_mismatch", { chainId, expectedChainId: expected });
|
|
1237
|
+
}
|
|
1238
|
+
const reference = attempt.externalReference;
|
|
1239
|
+
if (reference !== void 0 && TX_HASH.test(reference)) {
|
|
1240
|
+
for (const relayer of locator.relayers) {
|
|
1241
|
+
const outcome = await txStatus(rpc2, reference, relayer);
|
|
1242
|
+
if (outcome === void 0) continue;
|
|
1243
|
+
if (outcome.final_execution_status !== "FINAL") {
|
|
1244
|
+
return unknown("not_final", { transactionHash: reference });
|
|
1245
|
+
}
|
|
1246
|
+
if (carries(outcome, locator)) {
|
|
1247
|
+
return {
|
|
1248
|
+
outcome: "settled",
|
|
1249
|
+
reason: "transfer_final",
|
|
1250
|
+
externalReference: reference,
|
|
1251
|
+
evidence: { transactionHash: reference, relayer }
|
|
1252
|
+
};
|
|
1253
|
+
}
|
|
1254
|
+
break;
|
|
1255
|
+
}
|
|
1256
|
+
}
|
|
1257
|
+
const block = await rpc2("block", { finality: "final" });
|
|
1258
|
+
const height = block.header?.height;
|
|
1259
|
+
if (typeof height !== "number" || !Number.isSafeInteger(height)) {
|
|
1260
|
+
throw new CommerceError("PAYMENT_PROVIDER_UNAVAILABLE", "block returned no height");
|
|
1261
|
+
}
|
|
1262
|
+
const finality = { finalBlock: String(height) };
|
|
1263
|
+
let key;
|
|
1264
|
+
try {
|
|
1265
|
+
key = await rpc2("query", {
|
|
1266
|
+
request_type: "view_access_key",
|
|
1267
|
+
block_id: height,
|
|
1268
|
+
account_id: locator.senderId,
|
|
1269
|
+
public_key: locator.publicKey
|
|
1270
|
+
});
|
|
1271
|
+
} catch (err) {
|
|
1272
|
+
if (rpcErrorName(err) === "UNKNOWN_ACCESS_KEY") return unknown("access_key_missing", finality);
|
|
1273
|
+
throw err;
|
|
1274
|
+
}
|
|
1275
|
+
if (typeof key.error === "string") return unknown("access_key_missing", finality);
|
|
1276
|
+
if (typeof key.nonce !== "number" || !Number.isSafeInteger(key.nonce)) {
|
|
1277
|
+
throw new CommerceError("PAYMENT_PROVIDER_UNAVAILABLE", "view_access_key returned no nonce");
|
|
1278
|
+
}
|
|
1279
|
+
const evidence = { keyNonce: String(key.nonce), ...finality };
|
|
1280
|
+
if (BigInt(key.nonce) >= locator.nonce) return unknown("used_without_record", evidence);
|
|
1281
|
+
if (BigInt(height) > locator.maxBlockHeight) {
|
|
1282
|
+
return { outcome: "not-settled", reason: "expired_unused", evidence };
|
|
1283
|
+
}
|
|
1284
|
+
return unknown("not_expired", { maxBlockHeight: String(locator.maxBlockHeight), ...evidence });
|
|
1285
|
+
}
|
|
1286
|
+
async function txStatus(rpc2, hash, sender) {
|
|
1287
|
+
try {
|
|
1288
|
+
return await rpc2("EXPERIMENTAL_tx_status", {
|
|
1289
|
+
tx_hash: hash,
|
|
1290
|
+
sender_account_id: sender,
|
|
1291
|
+
wait_until: "NONE"
|
|
1292
|
+
});
|
|
1293
|
+
} catch (err) {
|
|
1294
|
+
if (rpcErrorName(err) === "UNKNOWN_TRANSACTION") return void 0;
|
|
1295
|
+
throw err;
|
|
1296
|
+
}
|
|
1297
|
+
}
|
|
1298
|
+
function carries(outcome, locator) {
|
|
1299
|
+
const delegated = (outcome.transaction?.actions ?? []).some((action) => {
|
|
1300
|
+
const delegate = action.Delegate?.delegate_action;
|
|
1301
|
+
return delegate?.sender_id === locator.senderId && delegate.public_key === locator.publicKey && String(delegate.nonce) === String(locator.nonce);
|
|
1302
|
+
});
|
|
1303
|
+
const succeeded = new Set(
|
|
1304
|
+
(outcome.receipts_outcome ?? []).filter((entry) => isRecord(entry.outcome?.status) && "SuccessValue" in entry.outcome.status).map((entry) => entry.id)
|
|
1305
|
+
);
|
|
1306
|
+
const transferred = (outcome.receipts ?? []).some(
|
|
1307
|
+
(receipt) => receipt.receiver_id === locator.asset && receipt.predecessor_id === locator.senderId && succeeded.has(receipt.receipt_id) && (receipt.receipt?.Action?.actions ?? []).some((action) => {
|
|
1308
|
+
const call = action.FunctionCall;
|
|
1309
|
+
if (call?.method_name !== "ft_transfer" || typeof call.args !== "string") return false;
|
|
1310
|
+
const args = parseArgs(call.args);
|
|
1311
|
+
return args?.["receiver_id"] === locator.receiver && args["amount"] === locator.amount;
|
|
1312
|
+
})
|
|
1313
|
+
);
|
|
1314
|
+
return delegated && transferred;
|
|
1315
|
+
}
|
|
1316
|
+
function parseArgs(base64) {
|
|
1317
|
+
try {
|
|
1318
|
+
const args = JSON.parse(Buffer.from(base64, "base64").toString("utf8"));
|
|
1319
|
+
return isRecord(args) ? args : void 0;
|
|
1320
|
+
} catch {
|
|
1321
|
+
return void 0;
|
|
1322
|
+
}
|
|
1323
|
+
}
|
|
1324
|
+
function rpcErrorName(err) {
|
|
1325
|
+
const rpcError = isCommerceError(err) ? err.details?.["rpcError"] : void 0;
|
|
1326
|
+
return isRecord(rpcError) && isRecord(rpcError["cause"]) ? rpcError["cause"]["name"] : void 0;
|
|
1327
|
+
}
|
|
1328
|
+
|
|
1329
|
+
// src/payments/x402/reconcile/svm.ts
|
|
1330
|
+
var CLOCK_MARGIN_SECONDS2 = 900;
|
|
1331
|
+
var HISTORY_PAGE = 1e3;
|
|
1332
|
+
var MAX_HISTORY_PAGES = 5;
|
|
1333
|
+
var BASE58 = /^[1-9A-HJ-NP-Za-km-z]+$/;
|
|
1334
|
+
var MESSAGE_HASH = /^[A-Za-z0-9+/]{43}=$/;
|
|
1335
|
+
function parseSvmLocator(locator) {
|
|
1336
|
+
const { messageHash, recentBlockhash, payer } = locator;
|
|
1337
|
+
if (typeof messageHash !== "string" || !MESSAGE_HASH.test(messageHash)) return void 0;
|
|
1338
|
+
if (!isBase58(recentBlockhash, 32, 44)) return void 0;
|
|
1339
|
+
if (payer !== void 0 && !isBase58(payer, 32, 44)) return void 0;
|
|
1340
|
+
return { messageHash, recentBlockhash, payer };
|
|
1341
|
+
}
|
|
1342
|
+
async function readSvmEvidence(input) {
|
|
1343
|
+
const { rpc: rpc2, network, locator, attempt, messageHashOf } = input;
|
|
1344
|
+
const genesis = await rpc2("getGenesisHash", []);
|
|
1345
|
+
const served = `solana:${String(genesis).slice(0, 32)}`;
|
|
1346
|
+
if (served !== network) {
|
|
1347
|
+
return unknown("chain_mismatch", { network: served, expectedNetwork: network });
|
|
1348
|
+
}
|
|
1349
|
+
const carries2 = async (id) => {
|
|
1350
|
+
const landed = await rpc2("getTransaction", [
|
|
1351
|
+
id,
|
|
1352
|
+
{ encoding: "base64", commitment: "finalized", maxSupportedTransactionVersion: 0 }
|
|
1353
|
+
]);
|
|
1354
|
+
if (landed?.meta?.err !== null || typeof landed.slot !== "number") return void 0;
|
|
1355
|
+
const [wire] = Array.isArray(landed.transaction) ? landed.transaction : [];
|
|
1356
|
+
return typeof wire === "string" && messageHashOf(wire) === locator.messageHash ? landed.slot : void 0;
|
|
1357
|
+
};
|
|
1358
|
+
const settled = (id, slot) => ({
|
|
1359
|
+
outcome: "settled",
|
|
1360
|
+
reason: "transfer_final",
|
|
1361
|
+
externalReference: id,
|
|
1362
|
+
evidence: { transactionId: id, slot: String(slot) }
|
|
1363
|
+
});
|
|
1364
|
+
const reference = attempt.externalReference;
|
|
1365
|
+
if (reference !== void 0 && isBase58(reference, 64, 88)) {
|
|
1366
|
+
const slot = await carries2(reference);
|
|
1367
|
+
if (slot !== void 0) return settled(reference, slot);
|
|
1368
|
+
}
|
|
1369
|
+
if (locator.payer !== void 0) {
|
|
1370
|
+
const createdAt = Math.floor(Date.parse(attempt.createdAt) / 1e3);
|
|
1371
|
+
const from = createdAt - CLOCK_MARGIN_SECONDS2;
|
|
1372
|
+
const to = createdAt + CLOCK_MARGIN_SECONDS2;
|
|
1373
|
+
let before;
|
|
1374
|
+
search: for (let page = 0; ; page += 1) {
|
|
1375
|
+
if (page === MAX_HISTORY_PAGES) return unknown("history_too_long", { payer: locator.payer });
|
|
1376
|
+
const entries = await rpc2("getSignaturesForAddress", [
|
|
1377
|
+
locator.payer,
|
|
1378
|
+
{
|
|
1379
|
+
commitment: "finalized",
|
|
1380
|
+
limit: HISTORY_PAGE,
|
|
1381
|
+
...before !== void 0 ? { before } : {}
|
|
1382
|
+
}
|
|
1383
|
+
]);
|
|
1384
|
+
if (!Array.isArray(entries)) {
|
|
1385
|
+
throw new CommerceError(
|
|
1386
|
+
"PAYMENT_PROVIDER_UNAVAILABLE",
|
|
1387
|
+
"getSignaturesForAddress returned no list"
|
|
1388
|
+
);
|
|
1389
|
+
}
|
|
1390
|
+
for (const entry of entries) {
|
|
1391
|
+
if (typeof entry.signature !== "string") continue;
|
|
1392
|
+
before = entry.signature;
|
|
1393
|
+
const time = typeof entry.blockTime === "number" ? entry.blockTime : void 0;
|
|
1394
|
+
if (time !== void 0 && time < from) break search;
|
|
1395
|
+
if (entry.err !== null || time !== void 0 && time > to) continue;
|
|
1396
|
+
const slot = await carries2(entry.signature);
|
|
1397
|
+
if (slot !== void 0) return settled(entry.signature, slot);
|
|
1398
|
+
}
|
|
1399
|
+
if (entries.length < HISTORY_PAGE) break;
|
|
1400
|
+
}
|
|
1401
|
+
}
|
|
1402
|
+
const validity = await rpc2("isBlockhashValid", [
|
|
1403
|
+
locator.recentBlockhash,
|
|
1404
|
+
{ commitment: "confirmed" }
|
|
1405
|
+
]);
|
|
1406
|
+
const valid = isRecord(validity) ? validity["value"] : void 0;
|
|
1407
|
+
if (typeof valid !== "boolean") {
|
|
1408
|
+
throw new CommerceError("PAYMENT_PROVIDER_UNAVAILABLE", "isBlockhashValid returned no value");
|
|
1409
|
+
}
|
|
1410
|
+
return unknown(valid ? "not_expired" : "blockhash_expired", {
|
|
1411
|
+
payerSearched: locator.payer !== void 0
|
|
1412
|
+
});
|
|
1413
|
+
}
|
|
1414
|
+
function isBase58(value, minLength, maxLength) {
|
|
1415
|
+
return typeof value === "string" && value.length >= minLength && value.length <= maxLength && BASE58.test(value);
|
|
1416
|
+
}
|
|
1417
|
+
|
|
1418
|
+
// src/payments/x402/provider/reconcile.ts
|
|
1419
|
+
var RECONCILE_TIMEOUT_MS = 3e4;
|
|
1420
|
+
function createReconcile(ctx) {
|
|
1421
|
+
const clients = /* @__PURE__ */ new Map();
|
|
1422
|
+
const evmClient = (offer) => {
|
|
1423
|
+
let client = clients.get(offer);
|
|
1424
|
+
if (client === void 0) {
|
|
1425
|
+
client = createLocalPublicClient(offer.rpcUrl, RECONCILE_TIMEOUT_MS, offer.profile.chainId);
|
|
1426
|
+
clients.set(offer, client);
|
|
1427
|
+
}
|
|
1428
|
+
return client;
|
|
1429
|
+
};
|
|
1430
|
+
const rpc2 = (offer) => (method, params) => jsonRpc(offer.rpcUrl, method, params, RECONCILE_TIMEOUT_MS);
|
|
1431
|
+
const read = async (offer, evidence) => {
|
|
1432
|
+
try {
|
|
1433
|
+
return await evidence();
|
|
1434
|
+
} catch (err) {
|
|
1435
|
+
return unknown("rpc_error", { rpc: offer.rpcOrigin, error: redactedErrorText(err) });
|
|
1436
|
+
}
|
|
1437
|
+
};
|
|
1438
|
+
return async ({ attempt, locator }) => {
|
|
1439
|
+
if (locator === void 0) return unknown("no_locator");
|
|
1440
|
+
if (locator["v"] !== LOCATOR_VERSION) return unknown("unsupported_locator_version");
|
|
1441
|
+
const network = locator["network"];
|
|
1442
|
+
if (typeof network !== "string") return unknown("unsupported_family");
|
|
1443
|
+
const offerFor = (family) => ctx.offers.find(
|
|
1444
|
+
(candidate) => candidate.family === family && candidate.network === network
|
|
1445
|
+
);
|
|
1446
|
+
const notConfigured = unknown("network_not_configured", { network });
|
|
1447
|
+
if (network.startsWith("eip155:")) {
|
|
1448
|
+
const parsed = parseEvmLocator(locator);
|
|
1449
|
+
if (parsed === void 0) return unknown("invalid_locator");
|
|
1450
|
+
const offer = offerFor("evm");
|
|
1451
|
+
if (offer === void 0) return notConfigured;
|
|
1452
|
+
return read(
|
|
1453
|
+
offer,
|
|
1454
|
+
() => readEvmEvidence({
|
|
1455
|
+
client: evmClient(offer),
|
|
1456
|
+
chainId: offer.profile.chainId,
|
|
1457
|
+
locator: parsed,
|
|
1458
|
+
attempt
|
|
1459
|
+
})
|
|
1460
|
+
);
|
|
1461
|
+
}
|
|
1462
|
+
if (network.startsWith("solana:")) {
|
|
1463
|
+
const parsed = parseSvmLocator(locator);
|
|
1464
|
+
if (parsed === void 0) return unknown("invalid_locator");
|
|
1465
|
+
const offer = offerFor("svm");
|
|
1466
|
+
if (offer === void 0) return notConfigured;
|
|
1467
|
+
const { messageHashOf } = await ctx.svm();
|
|
1468
|
+
return read(
|
|
1469
|
+
offer,
|
|
1470
|
+
() => readSvmEvidence({ rpc: rpc2(offer), network, locator: parsed, attempt, messageHashOf })
|
|
1471
|
+
);
|
|
1472
|
+
}
|
|
1473
|
+
if (network.startsWith("near:")) {
|
|
1474
|
+
const parsed = parseNearLocator(locator);
|
|
1475
|
+
if (parsed === void 0) return unknown("invalid_locator");
|
|
1476
|
+
const offer = offerFor("near");
|
|
1477
|
+
if (offer === void 0) return notConfigured;
|
|
1478
|
+
return read(
|
|
1479
|
+
offer,
|
|
1480
|
+
() => readNearEvidence({ rpc: rpc2(offer), network, locator: parsed, attempt })
|
|
1481
|
+
);
|
|
1482
|
+
}
|
|
1483
|
+
return unknown("unsupported_family");
|
|
1484
|
+
};
|
|
1485
|
+
}
|
|
939
1486
|
|
|
940
1487
|
// src/payments/x402/amount.ts
|
|
941
1488
|
var DECIMAL_STRING_PATTERN = /^\d+(?:\.\d+)?$/;
|
|
@@ -1138,12 +1685,13 @@ function readTransfer(payload, offer) {
|
|
|
1138
1685
|
from: getAddress(from2),
|
|
1139
1686
|
nonce: nonce2
|
|
1140
1687
|
}),
|
|
1688
|
+
locator: eip3009Locator(offer.network, offer.asset, authorization),
|
|
1141
1689
|
recipientMismatch: "invalid_exact_evm_payload_recipient_mismatch",
|
|
1142
1690
|
amountMismatch: "invalid_exact_evm_payload_authorization_value_mismatch"
|
|
1143
1691
|
};
|
|
1144
1692
|
}
|
|
1145
1693
|
if (!isExactPermit2Payload(payload)) return "unsupported_scheme";
|
|
1146
|
-
const { from, spender, permitted, witness, nonce } = payload.payload.permit2Authorization;
|
|
1694
|
+
const { from, spender, permitted, witness, nonce, deadline } = payload.payload.permit2Authorization;
|
|
1147
1695
|
if (getAddress(spender) !== getAddress(x402ExactPermit2ProxyAddress)) {
|
|
1148
1696
|
return "invalid_permit2_spender";
|
|
1149
1697
|
}
|
|
@@ -1153,6 +1701,16 @@ function readTransfer(payload, offer) {
|
|
|
1153
1701
|
to: getAddress(witness.to),
|
|
1154
1702
|
value: permitted.amount,
|
|
1155
1703
|
replayKey: computePermit2ReplayKey({ chainId, owner: getAddress(from), nonce }),
|
|
1704
|
+
locator: permit2Locator(offer.network, {
|
|
1705
|
+
asset: permitted.token,
|
|
1706
|
+
owner: from,
|
|
1707
|
+
to: witness.to,
|
|
1708
|
+
amount: permitted.amount,
|
|
1709
|
+
nonce,
|
|
1710
|
+
deadline,
|
|
1711
|
+
validAfter: witness.validAfter,
|
|
1712
|
+
proxy: spender
|
|
1713
|
+
}),
|
|
1156
1714
|
recipientMismatch: "invalid_permit2_recipient_mismatch",
|
|
1157
1715
|
amountMismatch: "permit2_amount_mismatch"
|
|
1158
1716
|
};
|
|
@@ -1327,7 +1885,8 @@ function createSettle(ctx) {
|
|
|
1327
1885
|
}
|
|
1328
1886
|
return settle;
|
|
1329
1887
|
}
|
|
1330
|
-
|
|
1888
|
+
var RELAYER_GRACE_MS = 1e3;
|
|
1889
|
+
function createVerify(ctx, nearRelayers) {
|
|
1331
1890
|
const { offersFor, clock, logger, svm, near } = ctx;
|
|
1332
1891
|
async function verify(context) {
|
|
1333
1892
|
const { requirement, submission } = context;
|
|
@@ -1370,11 +1929,13 @@ function createVerify(ctx) {
|
|
|
1370
1929
|
}
|
|
1371
1930
|
let transfer;
|
|
1372
1931
|
let replayKey;
|
|
1932
|
+
let locator;
|
|
1373
1933
|
let derivedPayer;
|
|
1374
1934
|
if (offer.family === "svm") {
|
|
1375
|
-
const
|
|
1376
|
-
if (typeof
|
|
1377
|
-
replayKey =
|
|
1935
|
+
const inspected = (await svm()).inspectSvmPayload(payload.payload, offer.network);
|
|
1936
|
+
if (typeof inspected === "string") return rejected(inspected);
|
|
1937
|
+
replayKey = inspected.replayKey;
|
|
1938
|
+
locator = inspected.locator;
|
|
1378
1939
|
} else if (offer.family === "near") {
|
|
1379
1940
|
const inspected = (await near()).inspectNearPayload(payload.payload, {
|
|
1380
1941
|
network: offer.network,
|
|
@@ -1384,41 +1945,45 @@ function createVerify(ctx) {
|
|
|
1384
1945
|
});
|
|
1385
1946
|
if (typeof inspected === "string") return rejected(inspected);
|
|
1386
1947
|
replayKey = inspected.replayKey;
|
|
1948
|
+
locator = inspected.locator;
|
|
1387
1949
|
derivedPayer = inspected.payer;
|
|
1388
1950
|
} else {
|
|
1389
1951
|
const read = readTransfer(payload, offer);
|
|
1390
1952
|
if (typeof read === "string") return rejected(read);
|
|
1391
1953
|
transfer = read;
|
|
1392
1954
|
replayKey = read.replayKey;
|
|
1955
|
+
locator = read.locator;
|
|
1393
1956
|
derivedPayer = read.from;
|
|
1394
1957
|
}
|
|
1958
|
+
const refused = (reason) => ({ ...rejected(reason), replayKey });
|
|
1395
1959
|
if (payload.accepted.network !== offer.network) {
|
|
1396
|
-
return
|
|
1960
|
+
return refused("invalid_network");
|
|
1397
1961
|
}
|
|
1398
1962
|
const offeredUrl = requirement.challenge.envelope?.resource?.url;
|
|
1399
1963
|
if (!acceptedMatchesOffer(requirements, payload.accepted, offer.profile) || payload.resource !== void 0 && payload.resource.url !== offeredUrl) {
|
|
1400
|
-
return
|
|
1964
|
+
return refused("invalid_payment_requirements");
|
|
1401
1965
|
}
|
|
1402
1966
|
let required;
|
|
1403
1967
|
try {
|
|
1404
1968
|
required = BigInt(requirements.amount);
|
|
1405
1969
|
} catch {
|
|
1406
|
-
return
|
|
1970
|
+
return refused("invalid_payload");
|
|
1407
1971
|
}
|
|
1408
1972
|
if (transfer) {
|
|
1409
1973
|
if (transfer.to !== getAddress(offer.payTo)) {
|
|
1410
|
-
return
|
|
1974
|
+
return refused(transfer.recipientMismatch);
|
|
1411
1975
|
}
|
|
1412
1976
|
let authorizedValue;
|
|
1413
1977
|
try {
|
|
1414
1978
|
authorizedValue = BigInt(transfer.value);
|
|
1415
1979
|
} catch {
|
|
1416
|
-
return
|
|
1980
|
+
return refused("invalid_payload");
|
|
1417
1981
|
}
|
|
1418
1982
|
if (authorizedValue !== required) {
|
|
1419
|
-
return
|
|
1983
|
+
return refused(transfer.amountMismatch);
|
|
1420
1984
|
}
|
|
1421
1985
|
}
|
|
1986
|
+
const relayers = offer.family === "near" ? nearRelayers(offer) : void 0;
|
|
1422
1987
|
const scope = offer.binding.open();
|
|
1423
1988
|
let sdkResult;
|
|
1424
1989
|
try {
|
|
@@ -1452,9 +2017,12 @@ function createVerify(ctx) {
|
|
|
1452
2017
|
"x402 verify(): facilitator rejection reason"
|
|
1453
2018
|
);
|
|
1454
2019
|
}
|
|
1455
|
-
return
|
|
2020
|
+
return refused(sanitizeReason(sdkResult.invalidReason, "invalid_payment"));
|
|
1456
2021
|
}
|
|
1457
2022
|
const payer = derivedPayer ?? (sdkResult.payer !== void 0 && normalizeAddress(offer.profile, sdkResult.payer) ? sdkResult.payer : void 0);
|
|
2023
|
+
if (offer.family === "svm" && payer !== void 0) locator = { ...locator, payer };
|
|
2024
|
+
const relayerIds = relayers !== void 0 ? await withinGrace(relayers) : [];
|
|
2025
|
+
if (relayerIds.length > 0) locator = { ...locator, relayers: relayerIds };
|
|
1458
2026
|
return {
|
|
1459
2027
|
status: "verified",
|
|
1460
2028
|
provider: "x402",
|
|
@@ -1464,10 +2032,26 @@ function createVerify(ctx) {
|
|
|
1464
2032
|
currency: offerCurrency(offer, requirement.currency),
|
|
1465
2033
|
network: payload.accepted.network,
|
|
1466
2034
|
asset: offer.family === "evm" ? getAddress(requirements.asset) : offer.asset,
|
|
1467
|
-
replayKey
|
|
2035
|
+
replayKey,
|
|
2036
|
+
metadata: { [RECONCILIATION_METADATA_KEY]: locator }
|
|
1468
2037
|
};
|
|
1469
2038
|
}
|
|
1470
2039
|
return verify;
|
|
2040
|
+
async function withinGrace(relayers) {
|
|
2041
|
+
let timer;
|
|
2042
|
+
const late = new Promise((resolve) => {
|
|
2043
|
+
timer = setTimeout(() => resolve(void 0), RELAYER_GRACE_MS);
|
|
2044
|
+
timer.unref();
|
|
2045
|
+
});
|
|
2046
|
+
const ids = await Promise.race([relayers, late]).finally(() => clearTimeout(timer));
|
|
2047
|
+
if (ids === void 0) {
|
|
2048
|
+
logger.warn(
|
|
2049
|
+
{ graceMs: RELAYER_GRACE_MS },
|
|
2050
|
+
"x402 verify(): /supported is slow; the NEAR locator names no relayer"
|
|
2051
|
+
);
|
|
2052
|
+
}
|
|
2053
|
+
return ids ?? [];
|
|
2054
|
+
}
|
|
1471
2055
|
}
|
|
1472
2056
|
|
|
1473
2057
|
// src/payments/x402/provider/index.ts
|
|
@@ -1536,8 +2120,8 @@ function createX402PaymentProvider(options) {
|
|
|
1536
2120
|
"auth-capture scheme"
|
|
1537
2121
|
]
|
|
1538
2122
|
};
|
|
1539
|
-
const svmModule = hasSvm ? loadOptionalModule(() => import('./svm-
|
|
1540
|
-
const nearModule = hasNear ? loadOptionalModule(() => import('./near-
|
|
2123
|
+
const svmModule = hasSvm ? loadOptionalModule(() => import('./svm-KNC3PHMS.js'), "Solana offers need @x402/svm and @solana/kit") : void 0;
|
|
2124
|
+
const nearModule = hasNear ? loadOptionalModule(() => import('./near-FH7HPZV3.js'), "NEAR offers need @x402/near") : void 0;
|
|
1541
2125
|
const svm = async () => {
|
|
1542
2126
|
if (!svmModule)
|
|
1543
2127
|
throw new CommerceError("INTERNAL_ERROR", "x402 provider: no Solana offer is configured");
|
|
@@ -1562,11 +2146,12 @@ function createX402PaymentProvider(options) {
|
|
|
1562
2146
|
svm,
|
|
1563
2147
|
near
|
|
1564
2148
|
};
|
|
2149
|
+
const supported = createSupportedSource(ctx);
|
|
1565
2150
|
const { createRequirement, selectRequirement } = createRequirementBuilders(
|
|
1566
2151
|
ctx,
|
|
1567
|
-
createSvmFeePayerSource(
|
|
2152
|
+
createSvmFeePayerSource(supported)
|
|
1568
2153
|
);
|
|
1569
|
-
const verify = createVerify(ctx);
|
|
2154
|
+
const verify = createVerify(ctx, createNearRelayerSource(supported, logger));
|
|
1570
2155
|
const settle = createSettle(ctx);
|
|
1571
2156
|
const health = createHealthCheck(ctx);
|
|
1572
2157
|
return {
|
|
@@ -1577,6 +2162,7 @@ function createX402PaymentProvider(options) {
|
|
|
1577
2162
|
...severalOffers ? { selectRequirement } : {},
|
|
1578
2163
|
verify,
|
|
1579
2164
|
settle,
|
|
2165
|
+
reconcile: createReconcile(ctx),
|
|
1580
2166
|
health,
|
|
1581
2167
|
...quotes ? {
|
|
1582
2168
|
quote: {
|
|
@@ -1599,5 +2185,5 @@ function loadOptionalModule(load, missing) {
|
|
|
1599
2185
|
}
|
|
1600
2186
|
|
|
1601
2187
|
export { DEFAULT_IDS, chainIdFromCaip2, createX402PaymentProvider, parseCanonicalAmount };
|
|
1602
|
-
//# sourceMappingURL=chunk-
|
|
1603
|
-
//# sourceMappingURL=chunk-
|
|
2188
|
+
//# sourceMappingURL=chunk-DRLBML7Z.js.map
|
|
2189
|
+
//# sourceMappingURL=chunk-DRLBML7Z.js.map
|