x402-evm-mantle 2.1.1-mantle
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 +183 -0
- package/dist/cjs/exact/client/index.d.ts +53 -0
- package/dist/cjs/exact/client/index.js +270 -0
- package/dist/cjs/exact/client/index.js.map +1 -0
- package/dist/cjs/exact/facilitator/index.d.ts +118 -0
- package/dist/cjs/exact/facilitator/index.js +735 -0
- package/dist/cjs/exact/facilitator/index.js.map +1 -0
- package/dist/cjs/exact/server/index.d.ts +140 -0
- package/dist/cjs/exact/server/index.js +247 -0
- package/dist/cjs/exact/server/index.js.map +1 -0
- package/dist/cjs/exact/v1/client/index.d.ts +37 -0
- package/dist/cjs/exact/v1/client/index.js +147 -0
- package/dist/cjs/exact/v1/client/index.js.map +1 -0
- package/dist/cjs/exact/v1/facilitator/index.d.ts +62 -0
- package/dist/cjs/exact/v1/facilitator/index.js +401 -0
- package/dist/cjs/exact/v1/facilitator/index.js.map +1 -0
- package/dist/cjs/index.d.ts +36 -0
- package/dist/cjs/index.js +148 -0
- package/dist/cjs/index.js.map +1 -0
- package/dist/cjs/signer-5OVDxViv.d.ts +79 -0
- package/dist/cjs/v1/index.d.ts +7 -0
- package/dist/cjs/v1/index.js +171 -0
- package/dist/cjs/v1/index.js.map +1 -0
- package/dist/esm/chunk-CYGMVQCG.mjs +88 -0
- package/dist/esm/chunk-CYGMVQCG.mjs.map +1 -0
- package/dist/esm/chunk-DI3EK7PR.mjs +305 -0
- package/dist/esm/chunk-DI3EK7PR.mjs.map +1 -0
- package/dist/esm/chunk-QLXM7BIB.mjs +23 -0
- package/dist/esm/chunk-QLXM7BIB.mjs.map +1 -0
- package/dist/esm/chunk-S5OEANGR.mjs +92 -0
- package/dist/esm/chunk-S5OEANGR.mjs.map +1 -0
- package/dist/esm/chunk-T3FPOH7F.mjs +88 -0
- package/dist/esm/chunk-T3FPOH7F.mjs.map +1 -0
- package/dist/esm/exact/client/index.d.mts +53 -0
- package/dist/esm/exact/client/index.mjs +36 -0
- package/dist/esm/exact/client/index.mjs.map +1 -0
- package/dist/esm/exact/facilitator/index.d.mts +118 -0
- package/dist/esm/exact/facilitator/index.mjs +324 -0
- package/dist/esm/exact/facilitator/index.mjs.map +1 -0
- package/dist/esm/exact/server/index.d.mts +140 -0
- package/dist/esm/exact/server/index.mjs +219 -0
- package/dist/esm/exact/server/index.mjs.map +1 -0
- package/dist/esm/exact/v1/client/index.d.mts +37 -0
- package/dist/esm/exact/v1/client/index.mjs +8 -0
- package/dist/esm/exact/v1/client/index.mjs.map +1 -0
- package/dist/esm/exact/v1/facilitator/index.d.mts +62 -0
- package/dist/esm/exact/v1/facilitator/index.mjs +8 -0
- package/dist/esm/exact/v1/facilitator/index.mjs.map +1 -0
- package/dist/esm/index.d.mts +36 -0
- package/dist/esm/index.mjs +21 -0
- package/dist/esm/index.mjs.map +1 -0
- package/dist/esm/signer-5OVDxViv.d.mts +79 -0
- package/dist/esm/v1/index.d.mts +7 -0
- package/dist/esm/v1/index.mjs +13 -0
- package/dist/esm/v1/index.mjs.map +1 -0
- package/package.json +127 -0
package/README.md
ADDED
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
# @x402/evm
|
|
2
|
+
|
|
3
|
+
EVM (Ethereum Virtual Machine) implementation of the x402 payment protocol using the **Exact** payment scheme with EIP-3009 TransferWithAuthorization.
|
|
4
|
+
|
|
5
|
+
## Installation
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
npm install @x402/evm
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
## Overview
|
|
12
|
+
|
|
13
|
+
This package provides three main components for handling x402 payments on EVM-compatible blockchains:
|
|
14
|
+
|
|
15
|
+
- **Client** - For applications that need to make payments (have wallets/signers)
|
|
16
|
+
- **Facilitator** - For payment processors that verify and execute on-chain transactions
|
|
17
|
+
- **Service** - For resource servers that accept payments and build payment requirements
|
|
18
|
+
|
|
19
|
+
## Package Exports
|
|
20
|
+
|
|
21
|
+
### Main Package (`@x402/evm`)
|
|
22
|
+
|
|
23
|
+
**V2 Protocol Support** - Modern x402 protocol with CAIP-2 network identifiers
|
|
24
|
+
|
|
25
|
+
**Client:**
|
|
26
|
+
- `ExactEvmClient` - V2 client implementation using EIP-3009
|
|
27
|
+
- `toClientEvmSigner(account)` - Converts viem accounts to x402 signers
|
|
28
|
+
- `ClientEvmSigner` - TypeScript type for client signers
|
|
29
|
+
|
|
30
|
+
**Facilitator:**
|
|
31
|
+
- `ExactEvmFacilitator` - V2 facilitator for payment verification and settlement
|
|
32
|
+
- `toFacilitatorEvmSigner(wallet)` - Converts viem wallets to facilitator signers
|
|
33
|
+
- `FacilitatorEvmSigner` - TypeScript type for facilitator signers
|
|
34
|
+
|
|
35
|
+
**Service:**
|
|
36
|
+
- `ExactEvmServer` - V2 service for building payment requirements
|
|
37
|
+
|
|
38
|
+
### V1 Package (`@x402/evm/v1`)
|
|
39
|
+
|
|
40
|
+
**V1 Protocol Support** - Legacy x402 protocol with simple network names
|
|
41
|
+
|
|
42
|
+
**Exports:**
|
|
43
|
+
- `ExactEvmClientV1` - V1 client implementation
|
|
44
|
+
- `ExactEvmFacilitatorV1` - V1 facilitator implementation
|
|
45
|
+
- `NETWORKS` - Array of all supported V1 network names
|
|
46
|
+
|
|
47
|
+
**Supported V1 Networks:**
|
|
48
|
+
```typescript
|
|
49
|
+
[
|
|
50
|
+
"abstract", "abstract-testnet",
|
|
51
|
+
"base-sepolia", "base",
|
|
52
|
+
"avalanche-fuji", "avalanche",
|
|
53
|
+
"iotex", "sei", "sei-testnet",
|
|
54
|
+
"polygon", "polygon-amoy",
|
|
55
|
+
"peaq", "story", "educhain",
|
|
56
|
+
"skale-base-sepolia"
|
|
57
|
+
]
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
### Client Builder (`@x402/evm/client`)
|
|
61
|
+
|
|
62
|
+
**Convenience builder** for creating fully-configured EVM clients
|
|
63
|
+
|
|
64
|
+
**Exports:**
|
|
65
|
+
- `createEvmClient(config)` - Creates x402Client with EVM support
|
|
66
|
+
- `EvmClientConfig` - Configuration interface
|
|
67
|
+
|
|
68
|
+
**What it does:**
|
|
69
|
+
- Automatically registers V2 wildcard scheme (`eip155:*`)
|
|
70
|
+
- Automatically registers all V1 networks from `NETWORKS`
|
|
71
|
+
- Optionally applies payment policies
|
|
72
|
+
- Optionally uses custom payment selector
|
|
73
|
+
|
|
74
|
+
**Example:**
|
|
75
|
+
```typescript
|
|
76
|
+
import { createEvmClient } from "@x402/evm/client";
|
|
77
|
+
import { toClientEvmSigner } from "@x402/evm";
|
|
78
|
+
import { privateKeyToAccount } from "viem/accounts";
|
|
79
|
+
|
|
80
|
+
const account = privateKeyToAccount("0x...");
|
|
81
|
+
const signer = toClientEvmSigner(account);
|
|
82
|
+
|
|
83
|
+
const client = createEvmClient({ signer });
|
|
84
|
+
// Ready to use with both V1 and V2!
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
## Version Differences
|
|
88
|
+
|
|
89
|
+
### V2 (Main Package)
|
|
90
|
+
- Network format: CAIP-2 (`eip155:8453`)
|
|
91
|
+
- Wildcard support: Yes (`eip155:*`)
|
|
92
|
+
- Payload structure: Partial (core wraps with metadata)
|
|
93
|
+
- Extensions: Full support
|
|
94
|
+
- Validity window: 1 hour (default)
|
|
95
|
+
|
|
96
|
+
### V1 (V1 Package)
|
|
97
|
+
- Network format: Simple names (`base-sepolia`)
|
|
98
|
+
- Wildcard support: No (fixed list)
|
|
99
|
+
- Payload structure: Complete
|
|
100
|
+
- Extensions: Limited
|
|
101
|
+
- Validity window: 10 minutes with buffer
|
|
102
|
+
|
|
103
|
+
## Usage Patterns
|
|
104
|
+
|
|
105
|
+
### 1. Using Pre-built Builder (Recommended)
|
|
106
|
+
|
|
107
|
+
```typescript
|
|
108
|
+
import { createEvmClient } from "@x402/evm/client";
|
|
109
|
+
import { wrapFetchWithPayment } from "@x402/fetch";
|
|
110
|
+
|
|
111
|
+
const client = createEvmClient({ signer: myEvmSigner });
|
|
112
|
+
const paidFetch = wrapFetchWithPayment(fetch, client);
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
### 2. Direct Registration (Full Control)
|
|
116
|
+
|
|
117
|
+
```typescript
|
|
118
|
+
import { x402Client } from "@x402/core/client";
|
|
119
|
+
import { ExactEvmClient } from "@x402/evm";
|
|
120
|
+
import { ExactEvmClientV1 } from "@x402/evm/v1";
|
|
121
|
+
|
|
122
|
+
const client = new x402Client()
|
|
123
|
+
.register("eip155:*", new ExactEvmClient(signer))
|
|
124
|
+
.registerSchemeV1("base-sepolia", new ExactEvmClientV1(signer))
|
|
125
|
+
.registerSchemeV1("base", new ExactEvmClientV1(signer));
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
### 3. Using Config (Flexible)
|
|
129
|
+
|
|
130
|
+
```typescript
|
|
131
|
+
import { x402Client } from "@x402/core/client";
|
|
132
|
+
import { ExactEvmClient } from "@x402/evm";
|
|
133
|
+
|
|
134
|
+
const client = x402Client.fromConfig({
|
|
135
|
+
schemes: [
|
|
136
|
+
{ network: "eip155:*", client: new ExactEvmClient(signer) },
|
|
137
|
+
{ network: "base-sepolia", client: new ExactEvmClientV1(signer), x402Version: 1 }
|
|
138
|
+
],
|
|
139
|
+
policies: [myCustomPolicy]
|
|
140
|
+
});
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
## Supported Networks
|
|
144
|
+
|
|
145
|
+
**V2 Networks** (via CAIP-2):
|
|
146
|
+
- `eip155:1` - Ethereum Mainnet
|
|
147
|
+
- `eip155:8453` - Base Mainnet
|
|
148
|
+
- `eip155:84532` - Base Sepolia
|
|
149
|
+
- `eip155:*` - Wildcard (matches all EVM chains)
|
|
150
|
+
- Any `eip155:<chainId>` network
|
|
151
|
+
|
|
152
|
+
**V1 Networks** (simple names):
|
|
153
|
+
See `NETWORKS` constant in `@x402/evm/v1`
|
|
154
|
+
|
|
155
|
+
## Asset Support
|
|
156
|
+
|
|
157
|
+
Supports any ERC-3009 compatible token:
|
|
158
|
+
- USDC (primary)
|
|
159
|
+
- EURC
|
|
160
|
+
- Any token implementing `transferWithAuthorization()`
|
|
161
|
+
|
|
162
|
+
## Development
|
|
163
|
+
|
|
164
|
+
```bash
|
|
165
|
+
# Build
|
|
166
|
+
npm run build
|
|
167
|
+
|
|
168
|
+
# Test
|
|
169
|
+
npm run test
|
|
170
|
+
|
|
171
|
+
# Integration tests
|
|
172
|
+
npm run test:integration
|
|
173
|
+
|
|
174
|
+
# Lint & Format
|
|
175
|
+
npm run lint
|
|
176
|
+
npm run format
|
|
177
|
+
```
|
|
178
|
+
|
|
179
|
+
## Related Packages
|
|
180
|
+
|
|
181
|
+
- `@x402/core` - Core protocol types and client
|
|
182
|
+
- `@x402/fetch` - HTTP wrapper with automatic payment handling
|
|
183
|
+
- `@x402/svm` - Solana/SVM implementation
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
export { ExactEvmScheme } from '../../index.js';
|
|
2
|
+
import { x402Client, SelectPaymentRequirements, PaymentPolicy } from 'x402-core-mantle/client';
|
|
3
|
+
import { Network } from 'x402-core-mantle/types';
|
|
4
|
+
import { C as ClientEvmSigner } from '../../signer-5OVDxViv.js';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Configuration options for registering EVM schemes to an x402Client
|
|
8
|
+
*/
|
|
9
|
+
interface EvmClientConfig {
|
|
10
|
+
/**
|
|
11
|
+
* The EVM signer to use for creating payment payloads
|
|
12
|
+
*/
|
|
13
|
+
signer: ClientEvmSigner;
|
|
14
|
+
/**
|
|
15
|
+
* Optional payment requirements selector function
|
|
16
|
+
* If not provided, uses the default selector (first available option)
|
|
17
|
+
*/
|
|
18
|
+
paymentRequirementsSelector?: SelectPaymentRequirements;
|
|
19
|
+
/**
|
|
20
|
+
* Optional policies to apply to the client
|
|
21
|
+
*/
|
|
22
|
+
policies?: PaymentPolicy[];
|
|
23
|
+
/**
|
|
24
|
+
* Optional specific networks to register
|
|
25
|
+
* If not provided, registers wildcard support (eip155:*)
|
|
26
|
+
*/
|
|
27
|
+
networks?: Network[];
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Registers EVM exact payment schemes to an x402Client instance.
|
|
31
|
+
*
|
|
32
|
+
* This function registers:
|
|
33
|
+
* - V2: eip155:* wildcard scheme with ExactEvmScheme (or specific networks if provided)
|
|
34
|
+
* - V1: All supported EVM networks with ExactEvmSchemeV1
|
|
35
|
+
*
|
|
36
|
+
* @param client - The x402Client instance to register schemes to
|
|
37
|
+
* @param config - Configuration for EVM client registration
|
|
38
|
+
* @returns The client instance for chaining
|
|
39
|
+
*
|
|
40
|
+
* @example
|
|
41
|
+
* ```typescript
|
|
42
|
+
* import { registerExactEvmScheme } from "@x402/evm/exact/client/register";
|
|
43
|
+
* import { x402Client } from "x402-core-mantle/client";
|
|
44
|
+
* import { privateKeyToAccount } from "viem/accounts";
|
|
45
|
+
*
|
|
46
|
+
* const account = privateKeyToAccount("0x...");
|
|
47
|
+
* const client = new x402Client();
|
|
48
|
+
* registerExactEvmScheme(client, { signer: account });
|
|
49
|
+
* ```
|
|
50
|
+
*/
|
|
51
|
+
declare function registerExactEvmScheme(client: x402Client, config: EvmClientConfig): x402Client;
|
|
52
|
+
|
|
53
|
+
export { type EvmClientConfig, registerExactEvmScheme };
|
|
@@ -0,0 +1,270 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/exact/client/index.ts
|
|
21
|
+
var client_exports = {};
|
|
22
|
+
__export(client_exports, {
|
|
23
|
+
ExactEvmScheme: () => ExactEvmScheme,
|
|
24
|
+
registerExactEvmScheme: () => registerExactEvmScheme
|
|
25
|
+
});
|
|
26
|
+
module.exports = __toCommonJS(client_exports);
|
|
27
|
+
|
|
28
|
+
// src/exact/client/scheme.ts
|
|
29
|
+
var import_viem2 = require("viem");
|
|
30
|
+
|
|
31
|
+
// src/constants.ts
|
|
32
|
+
var authorizationTypes = {
|
|
33
|
+
TransferWithAuthorization: [
|
|
34
|
+
{ name: "from", type: "address" },
|
|
35
|
+
{ name: "to", type: "address" },
|
|
36
|
+
{ name: "value", type: "uint256" },
|
|
37
|
+
{ name: "validAfter", type: "uint256" },
|
|
38
|
+
{ name: "validBefore", type: "uint256" },
|
|
39
|
+
{ name: "nonce", type: "bytes32" }
|
|
40
|
+
]
|
|
41
|
+
};
|
|
42
|
+
|
|
43
|
+
// src/utils.ts
|
|
44
|
+
var import_viem = require("viem");
|
|
45
|
+
function getEvmChainId(network) {
|
|
46
|
+
const networkMap = {
|
|
47
|
+
base: 8453,
|
|
48
|
+
"base-sepolia": 84532,
|
|
49
|
+
ethereum: 1,
|
|
50
|
+
sepolia: 11155111,
|
|
51
|
+
polygon: 137,
|
|
52
|
+
"polygon-amoy": 80002
|
|
53
|
+
};
|
|
54
|
+
return networkMap[network] || 1;
|
|
55
|
+
}
|
|
56
|
+
function createNonce() {
|
|
57
|
+
const cryptoObj = typeof globalThis.crypto !== "undefined" ? globalThis.crypto : globalThis.crypto;
|
|
58
|
+
if (!cryptoObj) {
|
|
59
|
+
throw new Error("Crypto API not available");
|
|
60
|
+
}
|
|
61
|
+
return (0, import_viem.toHex)(cryptoObj.getRandomValues(new Uint8Array(32)));
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
// src/exact/client/scheme.ts
|
|
65
|
+
var ExactEvmScheme = class {
|
|
66
|
+
/**
|
|
67
|
+
* Creates a new ExactEvmClient instance.
|
|
68
|
+
*
|
|
69
|
+
* @param signer - The EVM signer for client operations
|
|
70
|
+
*/
|
|
71
|
+
constructor(signer) {
|
|
72
|
+
this.signer = signer;
|
|
73
|
+
this.scheme = "exact";
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* Creates a payment payload for the Exact scheme.
|
|
77
|
+
*
|
|
78
|
+
* @param x402Version - The x402 protocol version
|
|
79
|
+
* @param paymentRequirements - The payment requirements
|
|
80
|
+
* @returns Promise resolving to a payment payload
|
|
81
|
+
*/
|
|
82
|
+
async createPaymentPayload(x402Version, paymentRequirements) {
|
|
83
|
+
const nonce = createNonce();
|
|
84
|
+
const now = Math.floor(Date.now() / 1e3);
|
|
85
|
+
const authorization = {
|
|
86
|
+
from: this.signer.address,
|
|
87
|
+
to: (0, import_viem2.getAddress)(paymentRequirements.payTo),
|
|
88
|
+
value: paymentRequirements.amount,
|
|
89
|
+
validAfter: (now - 600).toString(),
|
|
90
|
+
// 10 minutes before
|
|
91
|
+
validBefore: (now + paymentRequirements.maxTimeoutSeconds).toString(),
|
|
92
|
+
nonce
|
|
93
|
+
};
|
|
94
|
+
const signature = await this.signAuthorization(authorization, paymentRequirements);
|
|
95
|
+
const payload = {
|
|
96
|
+
authorization,
|
|
97
|
+
signature
|
|
98
|
+
};
|
|
99
|
+
return {
|
|
100
|
+
x402Version,
|
|
101
|
+
payload
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* Sign the EIP-3009 authorization using EIP-712
|
|
106
|
+
*
|
|
107
|
+
* @param authorization - The authorization to sign
|
|
108
|
+
* @param requirements - The payment requirements
|
|
109
|
+
* @returns Promise resolving to the signature
|
|
110
|
+
*/
|
|
111
|
+
async signAuthorization(authorization, requirements) {
|
|
112
|
+
const chainId = parseInt(requirements.network.split(":")[1]);
|
|
113
|
+
if (!requirements.extra?.name || !requirements.extra?.version) {
|
|
114
|
+
throw new Error(
|
|
115
|
+
`EIP-712 domain parameters (name, version) are required in payment requirements for asset ${requirements.asset}`
|
|
116
|
+
);
|
|
117
|
+
}
|
|
118
|
+
const { name, version } = requirements.extra;
|
|
119
|
+
const domain = {
|
|
120
|
+
name,
|
|
121
|
+
version,
|
|
122
|
+
chainId,
|
|
123
|
+
verifyingContract: (0, import_viem2.getAddress)(requirements.asset)
|
|
124
|
+
};
|
|
125
|
+
const message = {
|
|
126
|
+
from: (0, import_viem2.getAddress)(authorization.from),
|
|
127
|
+
to: (0, import_viem2.getAddress)(authorization.to),
|
|
128
|
+
value: BigInt(authorization.value),
|
|
129
|
+
validAfter: BigInt(authorization.validAfter),
|
|
130
|
+
validBefore: BigInt(authorization.validBefore),
|
|
131
|
+
nonce: authorization.nonce
|
|
132
|
+
};
|
|
133
|
+
return await this.signer.signTypedData({
|
|
134
|
+
domain,
|
|
135
|
+
types: authorizationTypes,
|
|
136
|
+
primaryType: "TransferWithAuthorization",
|
|
137
|
+
message
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
};
|
|
141
|
+
|
|
142
|
+
// src/exact/v1/client/scheme.ts
|
|
143
|
+
var import_viem3 = require("viem");
|
|
144
|
+
var ExactEvmSchemeV1 = class {
|
|
145
|
+
/**
|
|
146
|
+
* Creates a new ExactEvmClientV1 instance.
|
|
147
|
+
*
|
|
148
|
+
* @param signer - The EVM signer for client operations
|
|
149
|
+
*/
|
|
150
|
+
constructor(signer) {
|
|
151
|
+
this.signer = signer;
|
|
152
|
+
this.scheme = "exact";
|
|
153
|
+
}
|
|
154
|
+
/**
|
|
155
|
+
* Creates a payment payload for the Exact scheme (V1).
|
|
156
|
+
*
|
|
157
|
+
* @param x402Version - The x402 protocol version
|
|
158
|
+
* @param paymentRequirements - The payment requirements
|
|
159
|
+
* @returns Promise resolving to a payment payload
|
|
160
|
+
*/
|
|
161
|
+
async createPaymentPayload(x402Version, paymentRequirements) {
|
|
162
|
+
const selectedV1 = paymentRequirements;
|
|
163
|
+
const nonce = createNonce();
|
|
164
|
+
const now = Math.floor(Date.now() / 1e3);
|
|
165
|
+
const authorization = {
|
|
166
|
+
from: this.signer.address,
|
|
167
|
+
to: (0, import_viem3.getAddress)(selectedV1.payTo),
|
|
168
|
+
value: selectedV1.maxAmountRequired,
|
|
169
|
+
validAfter: (now - 600).toString(),
|
|
170
|
+
// 10 minutes before
|
|
171
|
+
validBefore: (now + selectedV1.maxTimeoutSeconds).toString(),
|
|
172
|
+
nonce
|
|
173
|
+
};
|
|
174
|
+
const signature = await this.signAuthorization(authorization, selectedV1);
|
|
175
|
+
const payload = {
|
|
176
|
+
authorization,
|
|
177
|
+
signature
|
|
178
|
+
};
|
|
179
|
+
return {
|
|
180
|
+
x402Version,
|
|
181
|
+
scheme: selectedV1.scheme,
|
|
182
|
+
network: selectedV1.network,
|
|
183
|
+
payload
|
|
184
|
+
};
|
|
185
|
+
}
|
|
186
|
+
/**
|
|
187
|
+
* Sign the EIP-3009 authorization using EIP-712
|
|
188
|
+
*
|
|
189
|
+
* @param authorization - The authorization to sign
|
|
190
|
+
* @param requirements - The payment requirements
|
|
191
|
+
* @returns Promise resolving to the signature
|
|
192
|
+
*/
|
|
193
|
+
async signAuthorization(authorization, requirements) {
|
|
194
|
+
const chainId = getEvmChainId(requirements.network);
|
|
195
|
+
if (!requirements.extra?.name || !requirements.extra?.version) {
|
|
196
|
+
throw new Error(
|
|
197
|
+
`EIP-712 domain parameters (name, version) are required in payment requirements for asset ${requirements.asset}`
|
|
198
|
+
);
|
|
199
|
+
}
|
|
200
|
+
const { name, version } = requirements.extra;
|
|
201
|
+
const domain = {
|
|
202
|
+
name,
|
|
203
|
+
version,
|
|
204
|
+
chainId,
|
|
205
|
+
verifyingContract: (0, import_viem3.getAddress)(requirements.asset)
|
|
206
|
+
};
|
|
207
|
+
const message = {
|
|
208
|
+
from: (0, import_viem3.getAddress)(authorization.from),
|
|
209
|
+
to: (0, import_viem3.getAddress)(authorization.to),
|
|
210
|
+
value: BigInt(authorization.value),
|
|
211
|
+
validAfter: BigInt(authorization.validAfter),
|
|
212
|
+
validBefore: BigInt(authorization.validBefore),
|
|
213
|
+
nonce: authorization.nonce
|
|
214
|
+
};
|
|
215
|
+
return await this.signer.signTypedData({
|
|
216
|
+
domain,
|
|
217
|
+
types: authorizationTypes,
|
|
218
|
+
primaryType: "TransferWithAuthorization",
|
|
219
|
+
message
|
|
220
|
+
});
|
|
221
|
+
}
|
|
222
|
+
};
|
|
223
|
+
|
|
224
|
+
// src/exact/v1/facilitator/scheme.ts
|
|
225
|
+
var import_viem4 = require("viem");
|
|
226
|
+
|
|
227
|
+
// src/v1/index.ts
|
|
228
|
+
var NETWORKS = [
|
|
229
|
+
"abstract",
|
|
230
|
+
"abstract-testnet",
|
|
231
|
+
"base-sepolia",
|
|
232
|
+
"base",
|
|
233
|
+
"avalanche-fuji",
|
|
234
|
+
"avalanche",
|
|
235
|
+
"iotex",
|
|
236
|
+
"sei",
|
|
237
|
+
"sei-testnet",
|
|
238
|
+
"polygon",
|
|
239
|
+
"polygon-amoy",
|
|
240
|
+
"peaq",
|
|
241
|
+
"story",
|
|
242
|
+
"educhain",
|
|
243
|
+
"skale-base-sepolia"
|
|
244
|
+
];
|
|
245
|
+
|
|
246
|
+
// src/exact/client/register.ts
|
|
247
|
+
function registerExactEvmScheme(client, config) {
|
|
248
|
+
if (config.networks && config.networks.length > 0) {
|
|
249
|
+
config.networks.forEach((network) => {
|
|
250
|
+
client.register(network, new ExactEvmScheme(config.signer));
|
|
251
|
+
});
|
|
252
|
+
} else {
|
|
253
|
+
client.register("eip155:*", new ExactEvmScheme(config.signer));
|
|
254
|
+
}
|
|
255
|
+
NETWORKS.forEach((network) => {
|
|
256
|
+
client.registerV1(network, new ExactEvmSchemeV1(config.signer));
|
|
257
|
+
});
|
|
258
|
+
if (config.policies) {
|
|
259
|
+
config.policies.forEach((policy) => {
|
|
260
|
+
client.registerPolicy(policy);
|
|
261
|
+
});
|
|
262
|
+
}
|
|
263
|
+
return client;
|
|
264
|
+
}
|
|
265
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
266
|
+
0 && (module.exports = {
|
|
267
|
+
ExactEvmScheme,
|
|
268
|
+
registerExactEvmScheme
|
|
269
|
+
});
|
|
270
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../src/exact/client/index.ts","../../../../src/exact/client/scheme.ts","../../../../src/constants.ts","../../../../src/utils.ts","../../../../src/exact/v1/client/scheme.ts","../../../../src/exact/v1/facilitator/scheme.ts","../../../../src/v1/index.ts","../../../../src/exact/client/register.ts"],"sourcesContent":["export { ExactEvmScheme } from \"./scheme\";\nexport { registerExactEvmScheme } from \"./register\";\nexport type { EvmClientConfig } from \"./register\";\n","import { PaymentPayload, PaymentRequirements, SchemeNetworkClient } from \"x402-core-mantle/types\";\nimport { getAddress } from \"viem\";\nimport { authorizationTypes } from \"../../constants\";\nimport { ClientEvmSigner } from \"../../signer\";\nimport { ExactEvmPayloadV2 } from \"../../types\";\nimport { createNonce } from \"../../utils\";\n\n/**\n * EVM client implementation for the Exact payment scheme.\n *\n */\nexport class ExactEvmScheme implements SchemeNetworkClient {\n readonly scheme = \"exact\";\n\n /**\n * Creates a new ExactEvmClient instance.\n *\n * @param signer - The EVM signer for client operations\n */\n constructor(private readonly signer: ClientEvmSigner) {}\n\n /**\n * Creates a payment payload for the Exact scheme.\n *\n * @param x402Version - The x402 protocol version\n * @param paymentRequirements - The payment requirements\n * @returns Promise resolving to a payment payload\n */\n async createPaymentPayload(\n x402Version: number,\n paymentRequirements: PaymentRequirements,\n ): Promise<Pick<PaymentPayload, \"x402Version\" | \"payload\">> {\n const nonce = createNonce();\n const now = Math.floor(Date.now() / 1000);\n\n const authorization: ExactEvmPayloadV2[\"authorization\"] = {\n from: this.signer.address,\n to: getAddress(paymentRequirements.payTo),\n value: paymentRequirements.amount,\n validAfter: (now - 600).toString(), // 10 minutes before\n validBefore: (now + paymentRequirements.maxTimeoutSeconds).toString(),\n nonce,\n };\n\n // Sign the authorization\n const signature = await this.signAuthorization(authorization, paymentRequirements);\n\n const payload: ExactEvmPayloadV2 = {\n authorization,\n signature,\n };\n\n return {\n x402Version,\n payload,\n };\n }\n\n /**\n * Sign the EIP-3009 authorization using EIP-712\n *\n * @param authorization - The authorization to sign\n * @param requirements - The payment requirements\n * @returns Promise resolving to the signature\n */\n private async signAuthorization(\n authorization: ExactEvmPayloadV2[\"authorization\"],\n requirements: PaymentRequirements,\n ): Promise<`0x${string}`> {\n const chainId = parseInt(requirements.network.split(\":\")[1]);\n\n if (!requirements.extra?.name || !requirements.extra?.version) {\n throw new Error(\n `EIP-712 domain parameters (name, version) are required in payment requirements for asset ${requirements.asset}`,\n );\n }\n\n const { name, version } = requirements.extra;\n\n const domain = {\n name,\n version,\n chainId,\n verifyingContract: getAddress(requirements.asset),\n };\n\n const message = {\n from: getAddress(authorization.from),\n to: getAddress(authorization.to),\n value: BigInt(authorization.value),\n validAfter: BigInt(authorization.validAfter),\n validBefore: BigInt(authorization.validBefore),\n nonce: authorization.nonce,\n };\n\n return await this.signer.signTypedData({\n domain,\n types: authorizationTypes,\n primaryType: \"TransferWithAuthorization\",\n message,\n });\n }\n}\n","// EIP-3009 TransferWithAuthorization types for EIP-712 signing\nexport const authorizationTypes = {\n TransferWithAuthorization: [\n { name: \"from\", type: \"address\" },\n { name: \"to\", type: \"address\" },\n { name: \"value\", type: \"uint256\" },\n { name: \"validAfter\", type: \"uint256\" },\n { name: \"validBefore\", type: \"uint256\" },\n { name: \"nonce\", type: \"bytes32\" },\n ],\n} as const;\n\n// EIP3009 ABI for transferWithAuthorization function\nexport const eip3009ABI = [\n {\n inputs: [\n { name: \"from\", type: \"address\" },\n { name: \"to\", type: \"address\" },\n { name: \"value\", type: \"uint256\" },\n { name: \"validAfter\", type: \"uint256\" },\n { name: \"validBefore\", type: \"uint256\" },\n { name: \"nonce\", type: \"bytes32\" },\n { name: \"v\", type: \"uint8\" },\n { name: \"r\", type: \"bytes32\" },\n { name: \"s\", type: \"bytes32\" },\n ],\n name: \"transferWithAuthorization\",\n outputs: [],\n stateMutability: \"nonpayable\",\n type: \"function\",\n },\n {\n inputs: [\n { name: \"from\", type: \"address\" },\n { name: \"to\", type: \"address\" },\n { name: \"value\", type: \"uint256\" },\n { name: \"validAfter\", type: \"uint256\" },\n { name: \"validBefore\", type: \"uint256\" },\n { name: \"nonce\", type: \"bytes32\" },\n { name: \"signature\", type: \"bytes\" },\n ],\n name: \"transferWithAuthorization\",\n outputs: [],\n stateMutability: \"nonpayable\",\n type: \"function\",\n },\n {\n inputs: [{ name: \"account\", type: \"address\" }],\n name: \"balanceOf\",\n outputs: [{ name: \"\", type: \"uint256\" }],\n stateMutability: \"view\",\n type: \"function\",\n },\n {\n inputs: [],\n name: \"version\",\n outputs: [{ name: \"\", type: \"string\" }],\n stateMutability: \"view\",\n type: \"function\",\n },\n] as const;\n","import { toHex } from \"viem\";\nimport { Network } from \"x402-core-mantle/types\";\n\n/**\n * Extract chain ID from network string (e.g., \"base-sepolia\" -> 84532)\n * Used by v1 implementations\n *\n * @param network - The network identifier\n * @returns The numeric chain ID\n */\nexport function getEvmChainId(network: Network): number {\n const networkMap: Record<string, number> = {\n base: 8453,\n \"base-sepolia\": 84532,\n ethereum: 1,\n sepolia: 11155111,\n polygon: 137,\n \"polygon-amoy\": 80002,\n };\n return networkMap[network] || 1;\n}\n\n/**\n * Create a random 32-byte nonce for authorization\n *\n * @returns A hex-encoded 32-byte nonce\n */\nexport function createNonce(): `0x${string}` {\n // Use dynamic import to avoid require() in ESM context\n const cryptoObj =\n typeof globalThis.crypto !== \"undefined\"\n ? globalThis.crypto\n : (globalThis as { crypto?: Crypto }).crypto;\n\n if (!cryptoObj) {\n throw new Error(\"Crypto API not available\");\n }\n\n return toHex(cryptoObj.getRandomValues(new Uint8Array(32)));\n}\n","import {\n Network,\n PaymentPayload,\n PaymentRequirements,\n SchemeNetworkClient,\n} from \"x402-core-mantle/types\";\nimport { PaymentRequirementsV1 } from \"x402-core-mantle/types/v1\";\nimport { getAddress } from \"viem\";\nimport { authorizationTypes } from \"../../../constants\";\nimport { ClientEvmSigner } from \"../../../signer\";\nimport { ExactEvmPayloadV1 } from \"../../../types\";\nimport { createNonce, getEvmChainId } from \"../../../utils\";\n\n/**\n * EVM client implementation for the Exact payment scheme (V1).\n */\nexport class ExactEvmSchemeV1 implements SchemeNetworkClient {\n readonly scheme = \"exact\";\n\n /**\n * Creates a new ExactEvmClientV1 instance.\n *\n * @param signer - The EVM signer for client operations\n */\n constructor(private readonly signer: ClientEvmSigner) {}\n\n /**\n * Creates a payment payload for the Exact scheme (V1).\n *\n * @param x402Version - The x402 protocol version\n * @param paymentRequirements - The payment requirements\n * @returns Promise resolving to a payment payload\n */\n async createPaymentPayload(\n x402Version: number,\n paymentRequirements: PaymentRequirements,\n ): Promise<\n Pick<PaymentPayload, \"x402Version\" | \"payload\"> & { scheme: string; network: Network }\n > {\n const selectedV1 = paymentRequirements as unknown as PaymentRequirementsV1;\n const nonce = createNonce();\n const now = Math.floor(Date.now() / 1000);\n\n const authorization: ExactEvmPayloadV1[\"authorization\"] = {\n from: this.signer.address,\n to: getAddress(selectedV1.payTo),\n value: selectedV1.maxAmountRequired,\n validAfter: (now - 600).toString(), // 10 minutes before\n validBefore: (now + selectedV1.maxTimeoutSeconds).toString(),\n nonce,\n };\n\n // Sign the authorization\n const signature = await this.signAuthorization(authorization, selectedV1);\n\n const payload: ExactEvmPayloadV1 = {\n authorization,\n signature,\n };\n\n return {\n x402Version,\n scheme: selectedV1.scheme,\n network: selectedV1.network,\n payload,\n };\n }\n\n /**\n * Sign the EIP-3009 authorization using EIP-712\n *\n * @param authorization - The authorization to sign\n * @param requirements - The payment requirements\n * @returns Promise resolving to the signature\n */\n private async signAuthorization(\n authorization: ExactEvmPayloadV1[\"authorization\"],\n requirements: PaymentRequirementsV1,\n ): Promise<`0x${string}`> {\n const chainId = getEvmChainId(requirements.network);\n\n if (!requirements.extra?.name || !requirements.extra?.version) {\n throw new Error(\n `EIP-712 domain parameters (name, version) are required in payment requirements for asset ${requirements.asset}`,\n );\n }\n\n const { name, version } = requirements.extra;\n\n const domain = {\n name,\n version,\n chainId,\n verifyingContract: getAddress(requirements.asset),\n };\n\n const message = {\n from: getAddress(authorization.from),\n to: getAddress(authorization.to),\n value: BigInt(authorization.value),\n validAfter: BigInt(authorization.validAfter),\n validBefore: BigInt(authorization.validBefore),\n nonce: authorization.nonce,\n };\n\n return await this.signer.signTypedData({\n domain,\n types: authorizationTypes,\n primaryType: \"TransferWithAuthorization\",\n message,\n });\n }\n}\n","import {\n PaymentPayload,\n PaymentPayloadV1,\n PaymentRequirements,\n SchemeNetworkFacilitator,\n SettleResponse,\n VerifyResponse,\n} from \"x402-core-mantle/types\";\nimport { PaymentRequirementsV1 } from \"x402-core-mantle/types/v1\";\nimport { getAddress, Hex, isAddressEqual, parseErc6492Signature, parseSignature } from \"viem\";\nimport { authorizationTypes, eip3009ABI } from \"../../../constants\";\nimport { FacilitatorEvmSigner } from \"../../../signer\";\nimport { ExactEvmPayloadV1 } from \"../../../types\";\nimport { getEvmChainId } from \"../../../utils\";\n\nexport interface ExactEvmSchemeV1Config {\n /**\n * If enabled, the facilitator will deploy ERC-4337 smart wallets\n * via EIP-6492 when encountering undeployed contract signatures.\n *\n * @default false\n */\n deployERC4337WithEIP6492?: boolean;\n}\n\n/**\n * EVM facilitator implementation for the Exact payment scheme (V1).\n */\nexport class ExactEvmSchemeV1 implements SchemeNetworkFacilitator {\n readonly scheme = \"exact\";\n readonly caipFamily = \"eip155:*\";\n private readonly config: Required<ExactEvmSchemeV1Config>;\n\n /**\n * Creates a new ExactEvmFacilitatorV1 instance.\n *\n * @param signer - The EVM signer for facilitator operations\n * @param config - Optional configuration for the facilitator\n */\n constructor(\n private readonly signer: FacilitatorEvmSigner,\n config?: ExactEvmSchemeV1Config,\n ) {\n this.config = {\n deployERC4337WithEIP6492: config?.deployERC4337WithEIP6492 ?? false,\n };\n }\n\n /**\n * Get mechanism-specific extra data for the supported kinds endpoint.\n * For EVM, no extra data is needed.\n *\n * @param _ - The network identifier (unused for EVM)\n * @returns undefined (EVM has no extra data)\n */\n getExtra(_: string): Record<string, unknown> | undefined {\n return undefined;\n }\n\n /**\n * Get signer addresses used by this facilitator.\n * Returns all addresses this facilitator can use for signing/settling transactions.\n *\n * @param _ - The network identifier (unused for EVM, addresses are network-agnostic)\n * @returns Array of facilitator wallet addresses\n */\n getSigners(_: string): string[] {\n return [...this.signer.getAddresses()];\n }\n\n /**\n * Verifies a payment payload (V1).\n *\n * @param payload - The payment payload to verify\n * @param requirements - The payment requirements\n * @returns Promise resolving to verification response\n */\n async verify(\n payload: PaymentPayload,\n requirements: PaymentRequirements,\n ): Promise<VerifyResponse> {\n const requirementsV1 = requirements as unknown as PaymentRequirementsV1;\n const payloadV1 = payload as unknown as PaymentPayloadV1;\n const exactEvmPayload = payload.payload as ExactEvmPayloadV1;\n\n // Verify scheme matches\n if (payloadV1.scheme !== \"exact\" || requirements.scheme !== \"exact\") {\n return {\n isValid: false,\n invalidReason: \"unsupported_scheme\",\n payer: exactEvmPayload.authorization.from,\n };\n }\n\n // Get chain configuration\n const chainId = getEvmChainId(payloadV1.network);\n\n if (!requirements.extra?.name || !requirements.extra?.version) {\n return {\n isValid: false,\n invalidReason: \"missing_eip712_domain\",\n payer: exactEvmPayload.authorization.from,\n };\n }\n\n const { name, version } = requirements.extra;\n const erc20Address = getAddress(requirements.asset);\n\n // Verify network matches\n if (payloadV1.network !== requirements.network) {\n return {\n isValid: false,\n invalidReason: \"network_mismatch\",\n payer: exactEvmPayload.authorization.from,\n };\n }\n\n // Build typed data for signature verification\n const permitTypedData = {\n types: authorizationTypes,\n primaryType: \"TransferWithAuthorization\" as const,\n domain: {\n name,\n version,\n chainId,\n verifyingContract: erc20Address,\n },\n message: {\n from: exactEvmPayload.authorization.from,\n to: exactEvmPayload.authorization.to,\n value: BigInt(exactEvmPayload.authorization.value),\n validAfter: BigInt(exactEvmPayload.authorization.validAfter),\n validBefore: BigInt(exactEvmPayload.authorization.validBefore),\n nonce: exactEvmPayload.authorization.nonce,\n },\n };\n\n // Verify signature\n try {\n const recoveredAddress = await this.signer.verifyTypedData({\n address: exactEvmPayload.authorization.from,\n ...permitTypedData,\n signature: exactEvmPayload.signature!,\n });\n\n if (!recoveredAddress) {\n return {\n isValid: false,\n invalidReason: \"invalid_exact_evm_payload_signature\",\n payer: exactEvmPayload.authorization.from,\n };\n }\n } catch {\n // Signature verification failed - could be an undeployed smart wallet\n // Check if smart wallet is deployed\n const signature = exactEvmPayload.signature!;\n const signatureLength = signature.startsWith(\"0x\") ? signature.length - 2 : signature.length;\n const isSmartWallet = signatureLength > 130; // 65 bytes = 130 hex chars for EOA\n\n if (isSmartWallet) {\n const payerAddress = exactEvmPayload.authorization.from;\n const bytecode = await this.signer.getCode({ address: payerAddress });\n\n if (!bytecode || bytecode === \"0x\") {\n // Wallet is not deployed. Check if it's EIP-6492 with deployment info.\n // EIP-6492 signatures contain factory address and calldata needed for deployment.\n // Non-EIP-6492 undeployed wallets cannot succeed (no way to deploy them).\n const erc6492Data = parseErc6492Signature(signature);\n const hasDeploymentInfo =\n erc6492Data.address &&\n erc6492Data.data &&\n !isAddressEqual(erc6492Data.address, \"0x0000000000000000000000000000000000000000\");\n\n if (!hasDeploymentInfo) {\n // Non-EIP-6492 undeployed smart wallet - will always fail at settlement\n // since EIP-3009 requires on-chain EIP-1271 validation\n return {\n isValid: false,\n invalidReason: \"invalid_exact_evm_payload_undeployed_smart_wallet\",\n payer: payerAddress,\n };\n }\n // EIP-6492 signature with deployment info - allow through\n // Facilitators with sponsored deployment support can handle this in settle()\n } else {\n // Wallet is deployed but signature still failed - invalid signature\n return {\n isValid: false,\n invalidReason: \"invalid_exact_evm_payload_signature\",\n payer: exactEvmPayload.authorization.from,\n };\n }\n } else {\n // EOA signature failed\n return {\n isValid: false,\n invalidReason: \"invalid_exact_evm_payload_signature\",\n payer: exactEvmPayload.authorization.from,\n };\n }\n }\n\n // Verify payment recipient matches\n if (getAddress(exactEvmPayload.authorization.to) !== getAddress(requirements.payTo)) {\n return {\n isValid: false,\n invalidReason: \"invalid_exact_evm_payload_recipient_mismatch\",\n payer: exactEvmPayload.authorization.from,\n };\n }\n\n // Verify validBefore is in the future (with 6 second buffer for block time)\n const now = Math.floor(Date.now() / 1000);\n if (BigInt(exactEvmPayload.authorization.validBefore) < BigInt(now + 6)) {\n return {\n isValid: false,\n invalidReason: \"invalid_exact_evm_payload_authorization_valid_before\",\n payer: exactEvmPayload.authorization.from,\n };\n }\n\n // Verify validAfter is not in the future\n if (BigInt(exactEvmPayload.authorization.validAfter) > BigInt(now)) {\n return {\n isValid: false,\n invalidReason: \"invalid_exact_evm_payload_authorization_valid_after\",\n payer: exactEvmPayload.authorization.from,\n };\n }\n\n // Check balance\n try {\n const balance = (await this.signer.readContract({\n address: erc20Address,\n abi: eip3009ABI,\n functionName: \"balanceOf\",\n args: [exactEvmPayload.authorization.from],\n })) as bigint;\n\n if (BigInt(balance) < BigInt(requirementsV1.maxAmountRequired)) {\n return {\n isValid: false,\n invalidReason: \"insufficient_funds\",\n payer: exactEvmPayload.authorization.from,\n };\n }\n } catch {\n // If we can't check balance, continue with other validations\n }\n\n // Verify amount is sufficient\n if (BigInt(exactEvmPayload.authorization.value) < BigInt(requirementsV1.maxAmountRequired)) {\n return {\n isValid: false,\n invalidReason: \"invalid_exact_evm_payload_authorization_value\",\n payer: exactEvmPayload.authorization.from,\n };\n }\n\n return {\n isValid: true,\n invalidReason: undefined,\n payer: exactEvmPayload.authorization.from,\n };\n }\n\n /**\n * Settles a payment by executing the transfer (V1).\n *\n * @param payload - The payment payload to settle\n * @param requirements - The payment requirements\n * @returns Promise resolving to settlement response\n */\n async settle(\n payload: PaymentPayload,\n requirements: PaymentRequirements,\n ): Promise<SettleResponse> {\n const payloadV1 = payload as unknown as PaymentPayloadV1;\n const exactEvmPayload = payload.payload as ExactEvmPayloadV1;\n\n // Re-verify before settling\n const valid = await this.verify(payload, requirements);\n if (!valid.isValid) {\n return {\n success: false,\n network: payloadV1.network,\n transaction: \"\",\n errorReason: valid.invalidReason ?? \"invalid_scheme\",\n payer: exactEvmPayload.authorization.from,\n };\n }\n\n try {\n // Parse ERC-6492 signature if applicable\n const parseResult = parseErc6492Signature(exactEvmPayload.signature!);\n const { signature, address: factoryAddress, data: factoryCalldata } = parseResult;\n\n // Deploy ERC-4337 smart wallet via EIP-6492 if configured and needed\n if (\n this.config.deployERC4337WithEIP6492 &&\n factoryAddress &&\n factoryCalldata &&\n !isAddressEqual(factoryAddress, \"0x0000000000000000000000000000000000000000\")\n ) {\n // Check if smart wallet is already deployed\n const payerAddress = exactEvmPayload.authorization.from;\n const bytecode = await this.signer.getCode({ address: payerAddress });\n\n if (!bytecode || bytecode === \"0x\") {\n // Wallet not deployed - attempt deployment\n try {\n console.log(`Deploying ERC-4337 smart wallet for ${payerAddress} via EIP-6492`);\n\n // Send the factory calldata directly as a transaction\n // The factoryCalldata already contains the complete encoded function call\n const deployTx = await this.signer.sendTransaction({\n to: factoryAddress as Hex,\n data: factoryCalldata as Hex,\n });\n\n // Wait for deployment transaction\n await this.signer.waitForTransactionReceipt({ hash: deployTx });\n console.log(`Successfully deployed smart wallet for ${payerAddress}`);\n } catch (deployError) {\n console.error(\"Smart wallet deployment failed:\", deployError);\n // Deployment failed - cannot proceed\n throw deployError;\n }\n } else {\n console.log(`Smart wallet for ${payerAddress} already deployed, skipping deployment`);\n }\n }\n\n // Determine if this is an ECDSA signature (EOA) or smart wallet signature\n // ECDSA signatures are exactly 65 bytes (130 hex chars without 0x)\n const signatureLength = signature.startsWith(\"0x\") ? signature.length - 2 : signature.length;\n const isECDSA = signatureLength === 130;\n\n let tx: Hex;\n if (isECDSA) {\n // For EOA wallets, parse signature into v, r, s and use that overload\n const parsedSig = parseSignature(signature);\n\n tx = await this.signer.writeContract({\n address: getAddress(requirements.asset),\n abi: eip3009ABI,\n functionName: \"transferWithAuthorization\",\n args: [\n getAddress(exactEvmPayload.authorization.from),\n getAddress(exactEvmPayload.authorization.to),\n BigInt(exactEvmPayload.authorization.value),\n BigInt(exactEvmPayload.authorization.validAfter),\n BigInt(exactEvmPayload.authorization.validBefore),\n exactEvmPayload.authorization.nonce,\n (parsedSig.v as number | undefined) || parsedSig.yParity,\n parsedSig.r,\n parsedSig.s,\n ],\n });\n } else {\n // For smart wallets, use the bytes signature overload\n // The signature contains WebAuthn/P256 or other ERC-1271 compatible signature data\n tx = await this.signer.writeContract({\n address: getAddress(requirements.asset),\n abi: eip3009ABI,\n functionName: \"transferWithAuthorization\",\n args: [\n getAddress(exactEvmPayload.authorization.from),\n getAddress(exactEvmPayload.authorization.to),\n BigInt(exactEvmPayload.authorization.value),\n BigInt(exactEvmPayload.authorization.validAfter),\n BigInt(exactEvmPayload.authorization.validBefore),\n exactEvmPayload.authorization.nonce,\n signature,\n ],\n });\n }\n\n // Wait for transaction confirmation\n const receipt = await this.signer.waitForTransactionReceipt({ hash: tx });\n\n if (receipt.status !== \"success\") {\n return {\n success: false,\n errorReason: \"invalid_transaction_state\",\n transaction: tx,\n network: payloadV1.network,\n payer: exactEvmPayload.authorization.from,\n };\n }\n\n return {\n success: true,\n transaction: tx,\n network: payloadV1.network,\n payer: exactEvmPayload.authorization.from,\n };\n } catch (error) {\n console.error(\"Failed to settle transaction:\", error);\n return {\n success: false,\n errorReason: \"transaction_failed\",\n transaction: \"\",\n network: payloadV1.network,\n payer: exactEvmPayload.authorization.from,\n };\n }\n }\n}\n","export { ExactEvmSchemeV1 } from \"../exact/v1\";\n\nexport const NETWORKS: string[] = [\n \"abstract\",\n \"abstract-testnet\",\n \"base-sepolia\",\n \"base\",\n \"avalanche-fuji\",\n \"avalanche\",\n \"iotex\",\n \"sei\",\n \"sei-testnet\",\n \"polygon\",\n \"polygon-amoy\",\n \"peaq\",\n \"story\",\n \"educhain\",\n \"skale-base-sepolia\",\n];\n","import { x402Client, SelectPaymentRequirements, PaymentPolicy } from \"x402-core-mantle/client\";\nimport { Network } from \"x402-core-mantle/types\";\nimport { ClientEvmSigner } from \"../../signer\";\nimport { ExactEvmScheme } from \"./scheme\";\nimport { ExactEvmSchemeV1 } from \"../v1/client/scheme\";\nimport { NETWORKS } from \"../../v1\";\n\n/**\n * Configuration options for registering EVM schemes to an x402Client\n */\nexport interface EvmClientConfig {\n /**\n * The EVM signer to use for creating payment payloads\n */\n signer: ClientEvmSigner;\n\n /**\n * Optional payment requirements selector function\n * If not provided, uses the default selector (first available option)\n */\n paymentRequirementsSelector?: SelectPaymentRequirements;\n\n /**\n * Optional policies to apply to the client\n */\n policies?: PaymentPolicy[];\n\n /**\n * Optional specific networks to register\n * If not provided, registers wildcard support (eip155:*)\n */\n networks?: Network[];\n}\n\n/**\n * Registers EVM exact payment schemes to an x402Client instance.\n *\n * This function registers:\n * - V2: eip155:* wildcard scheme with ExactEvmScheme (or specific networks if provided)\n * - V1: All supported EVM networks with ExactEvmSchemeV1\n *\n * @param client - The x402Client instance to register schemes to\n * @param config - Configuration for EVM client registration\n * @returns The client instance for chaining\n *\n * @example\n * ```typescript\n * import { registerExactEvmScheme } from \"@x402/evm/exact/client/register\";\n * import { x402Client } from \"x402-core-mantle/client\";\n * import { privateKeyToAccount } from \"viem/accounts\";\n *\n * const account = privateKeyToAccount(\"0x...\");\n * const client = new x402Client();\n * registerExactEvmScheme(client, { signer: account });\n * ```\n */\nexport function registerExactEvmScheme(client: x402Client, config: EvmClientConfig): x402Client {\n // Register V2 scheme\n if (config.networks && config.networks.length > 0) {\n // Register specific networks\n config.networks.forEach(network => {\n client.register(network, new ExactEvmScheme(config.signer));\n });\n } else {\n // Register wildcard for all EVM chains\n client.register(\"eip155:*\", new ExactEvmScheme(config.signer));\n }\n\n // Register all V1 networks\n NETWORKS.forEach(network => {\n client.registerV1(network as Network, new ExactEvmSchemeV1(config.signer));\n });\n\n // Apply policies if provided\n if (config.policies) {\n config.policies.forEach(policy => {\n client.registerPolicy(policy);\n });\n }\n\n return client;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACCA,IAAAA,eAA2B;;;ACApB,IAAM,qBAAqB;AAAA,EAChC,2BAA2B;AAAA,IACzB,EAAE,MAAM,QAAQ,MAAM,UAAU;AAAA,IAChC,EAAE,MAAM,MAAM,MAAM,UAAU;AAAA,IAC9B,EAAE,MAAM,SAAS,MAAM,UAAU;AAAA,IACjC,EAAE,MAAM,cAAc,MAAM,UAAU;AAAA,IACtC,EAAE,MAAM,eAAe,MAAM,UAAU;AAAA,IACvC,EAAE,MAAM,SAAS,MAAM,UAAU;AAAA,EACnC;AACF;;;ACVA,kBAAsB;AAUf,SAAS,cAAc,SAA0B;AACtD,QAAM,aAAqC;AAAA,IACzC,MAAM;AAAA,IACN,gBAAgB;AAAA,IAChB,UAAU;AAAA,IACV,SAAS;AAAA,IACT,SAAS;AAAA,IACT,gBAAgB;AAAA,EAClB;AACA,SAAO,WAAW,OAAO,KAAK;AAChC;AAOO,SAAS,cAA6B;AAE3C,QAAM,YACJ,OAAO,WAAW,WAAW,cACzB,WAAW,SACV,WAAmC;AAE1C,MAAI,CAAC,WAAW;AACd,UAAM,IAAI,MAAM,0BAA0B;AAAA,EAC5C;AAEA,aAAO,mBAAM,UAAU,gBAAgB,IAAI,WAAW,EAAE,CAAC,CAAC;AAC5D;;;AF5BO,IAAM,iBAAN,MAAoD;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQzD,YAA6B,QAAyB;AAAzB;AAP7B,SAAS,SAAS;AAAA,E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