x402-chain-eip155 1.4.1

EIP-155 (EVM) chain support for the x402 payment protocol
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
use alloy_primitives::{TxHash, U256};
use alloy_provider::bindings::IMulticall3;
use alloy_provider::{MULTICALL3_ADDRESS, MulticallItem, Provider};
use alloy_rpc_types_eth::TransactionReceipt;
use alloy_sol_types::{SolCall, SolStruct, eip712_domain};
use x402_types::chain::ChainProviderOps;
use x402_types::proto::{PaymentVerificationError, v2};
use x402_types::scheme::X402SchemeFacilitatorError;

#[cfg(feature = "telemetry")]
use tracing::Instrument;
#[cfg(feature = "telemetry")]
use tracing::instrument;

use crate::chain::erc20::IERC20;
use crate::chain::permit2::{PERMIT2_ADDRESS, UPTO_PERMIT2_PROXY_ADDRESS};
use crate::chain::{Eip155ChainReference, Eip155MetaTransactionProvider, MetaTransaction};
use crate::v1_eip155_exact::{
    Eip155ExactError, StructuredSignature, VALIDATOR_ADDRESS, Validator6492, assert_time,
    is_contract_deployed, tx_hash_from_receipt,
};
use crate::v2_eip155_exact::permit2::{assert_onchain_allowance, assert_onchain_balance};
use crate::v2_eip155_upto::types;
use crate::v2_eip155_upto::types::{
    ISignatureTransfer, Permit2PaymentPayload, Permit2PaymentRequirements,
    PermitWitnessTransferFrom, UptoSettleResponse, X402UptoPermit2Proxy, x402BasePermit2Proxy,
};

#[cfg_attr(feature = "telemetry", instrument(skip_all, err))]
pub async fn verify_permit2_payment<P: Eip155MetaTransactionProvider + ChainProviderOps>(
    provider: &P,
    payment_payload: &Permit2PaymentPayload,
    payment_requirements: &Permit2PaymentRequirements,
) -> Result<v2::VerifyResponse, Eip155ExactError> {
    // 1. Verify offchain constraints
    let required_amount = assert_offchain_valid_verify(payment_payload, payment_requirements)?;

    // 2. Verify onchain constraints
    let authorization = &payment_payload.payload.permit_2_authorization;
    let payer = authorization.from;
    assert_onchain_upto_permit2(
        provider.inner(),
        provider.chain(),
        payment_payload,
        required_amount,
    )
    .await?;

    Ok(v2::VerifyResponse::valid(payer.to_string()))
}

/// Settle a upto permit2 payment with a specific amount.
///
/// The `settle_amount` must be less than or equal to the authorized maximum amount.
/// If `settle_amount` is `None`, the full authorized amount will be used.
#[cfg_attr(feature = "telemetry", instrument(skip_all, err))]
pub async fn settle_permit2_payment<P, E>(
    provider: &P,
    payment_payload: &Permit2PaymentPayload,
    payment_requirements: &Permit2PaymentRequirements,
) -> Result<UptoSettleResponse, X402SchemeFacilitatorError>
where
    P: Eip155MetaTransactionProvider<Error = E> + ChainProviderOps,
    Eip155ExactError: From<E>,
{
    // 1. Verify offchain constraints
    let required_amount = assert_offchain_valid_settle(payment_payload, payment_requirements)?;

    let authorization = &payment_payload.payload.permit_2_authorization;
    let payer = authorization.from;

    // 2. Handle zero settlement - no on-chain transaction needed
    // Allowing $0 settlements means unused authorizations naturally expire without on-chain transactions, reducing gas costs and blockchain bloat
    // TODO Document this
    if required_amount.is_zero() {
        let network = &payment_payload.accepted.network;
        return Ok(UptoSettleResponse::success(
            payer.to_string(),
            String::new(), // Empty transaction for $0 settlement
            network.to_string(),
            "0".to_string(),
        ));
    }

    // 3. Execute settlement
    let tx_hash = settle_upto_permit2(provider, payment_payload, required_amount).await?;
    let payer = authorization.from;
    let network = &payment_payload.accepted.network;

    Ok(UptoSettleResponse::success(
        payer.to_string(),
        tx_hash.to_string(),
        network.to_string(),
        required_amount.to_string(),
    ))
}

#[cfg_attr(feature = "telemetry", instrument(skip_all, err))]
pub fn assert_offchain_valid_verify(
    payment_payload: &Permit2PaymentPayload,
    payment_requirements: &Permit2PaymentRequirements,
) -> Result<U256, PaymentVerificationError> {
    assert_offchain_valid(payment_payload, payment_requirements)?;
    // Authorized amount must EQUAL the required amount (client authorizes exact max)
    // The server can then settle for any amount <= this max
    let authorization = &payment_payload.payload.permit_2_authorization;
    let accepted_amount = payment_payload.accepted.amount;
    if authorization.permitted.amount != accepted_amount {
        return Err(PaymentVerificationError::InvalidPaymentAmount);
    }
    Ok(accepted_amount)
}

#[cfg_attr(feature = "telemetry", instrument(skip_all, err))]
pub fn assert_offchain_valid_settle(
    payment_payload: &Permit2PaymentPayload,
    payment_requirements: &Permit2PaymentRequirements,
) -> Result<U256, PaymentVerificationError> {
    assert_offchain_valid(payment_payload, payment_requirements)?;
    // Authorized amount must EQUAL the required amount (client authorizes exact max)
    // The server can then settle for any amount <= this max
    let authorization = &payment_payload.payload.permit_2_authorization;
    let permitted_amount = authorization.permitted.amount;
    let accepted = &payment_payload.accepted;
    if permitted_amount != accepted.amount {
        return Err(PaymentVerificationError::InvalidPaymentAmount);
    }
    let amount_to_settle = payment_requirements.amount;
    if permitted_amount < amount_to_settle {
        return Err(PaymentVerificationError::InvalidPaymentAmount);
    }
    Ok(amount_to_settle)
}

#[cfg_attr(feature = "telemetry", instrument(skip_all, err))]
pub fn assert_offchain_valid(
    payment_payload: &Permit2PaymentPayload,
    payment_requirements: &Permit2PaymentRequirements,
) -> Result<(), PaymentVerificationError> {
    let payload = &payment_payload.payload;
    let accepted = &payment_payload.accepted;

    // Verify scheme matches
    if accepted.scheme != types::UptoScheme {
        return Err(PaymentVerificationError::UnsupportedScheme);
    }

    // Verify network matches
    if accepted.network != payment_requirements.network {
        return Err(PaymentVerificationError::ChainIdMismatch);
    }

    // Verify asset matches
    if accepted.asset != payment_requirements.asset {
        return Err(PaymentVerificationError::AssetMismatch);
    }

    // Spender must be the x402UptoPermit2Proxy contract address
    let authorization = &payload.permit_2_authorization;
    if authorization.spender.0 != UPTO_PERMIT2_PROXY_ADDRESS {
        return Err(PaymentVerificationError::RecipientMismatch);
    }

    // Correct recipient
    let witness = &authorization.witness;
    if witness.to != accepted.pay_to {
        return Err(PaymentVerificationError::RecipientMismatch);
    }

    // Time validity
    let valid_after = witness.valid_after;
    let valid_before = authorization.deadline;
    assert_time(valid_after, valid_before)?;

    // Same token
    if authorization.permitted.token != accepted.asset {
        return Err(PaymentVerificationError::AssetMismatch);
    }
    Ok(())
}

#[cfg_attr(feature = "telemetry", instrument(skip_all, err))]
pub async fn assert_onchain_upto_permit2<P: Provider>(
    provider: &P,
    chain_reference: &Eip155ChainReference,
    payment_payload: &Permit2PaymentPayload,
    required_amount: U256,
) -> Result<(), Eip155ExactError> {
    let authorization = &payment_payload.payload.permit_2_authorization;
    let payer = authorization.from.0;
    let asset_address = payment_payload.accepted.asset.0;

    let token_contract = IERC20::new(asset_address, provider);

    // Allowance from payer to Permit2 contract is enough
    let onchain_allowance_fut = assert_onchain_allowance(&token_contract, payer, required_amount);
    // User balance is enough
    let onchain_balance_fut = assert_onchain_balance(&token_contract, payer, required_amount);
    tokio::try_join!(onchain_allowance_fut, onchain_balance_fut)?;

    // ... and below is a check if we can do the settle
    // For upto, we simulate with the max amount (worst case)

    let domain = eip712_domain! {
        name: "Permit2",
        chain_id: chain_reference.inner(),
        verifying_contract: PERMIT2_ADDRESS,
    };
    let permit_witness_transfer_from = PermitWitnessTransferFrom {
        permitted: ISignatureTransfer::TokenPermissions {
            token: authorization.permitted.token.into(),
            amount: authorization.permitted.amount,
        },
        spender: UPTO_PERMIT2_PROXY_ADDRESS,
        nonce: authorization.nonce,
        deadline: U256::from(authorization.deadline.as_secs()),
        witness: x402BasePermit2Proxy::Witness {
            to: authorization.witness.to.into(),
            validAfter: U256::from(authorization.witness.valid_after.as_secs()),
            extra: authorization.witness.extra.clone(),
        },
    };
    let eip712_hash = permit_witness_transfer_from.eip712_signing_hash(&domain);
    let structured_signature = StructuredSignature::try_from_bytes(
        payment_payload.payload.signature.clone(),
        payer,
        &eip712_hash,
    )?;

    let upto_permit2_proxy = X402UptoPermit2Proxy::new(UPTO_PERMIT2_PROXY_ADDRESS, provider);
    match structured_signature {
        StructuredSignature::EIP6492 {
            factory: _,
            factory_calldata: _,
            inner,
            original,
        } => {
            let validator6492 = Validator6492::new(VALIDATOR_ADDRESS, provider);
            let is_valid_signature_call =
                validator6492.isValidSigWithSideEffects(payer, eip712_hash, original);
            let permit_transfer_from = ISignatureTransfer::PermitTransferFrom {
                permitted: permit_witness_transfer_from.permitted,
                nonce: permit_witness_transfer_from.nonce,
                deadline: permit_witness_transfer_from.deadline,
            };
            let witness = permit_witness_transfer_from.witness;
            // For verification, simulate with max amount
            let settle_call = upto_permit2_proxy.settle(
                permit_transfer_from,
                authorization.permitted.amount,
                payer,
                witness,
                inner,
            );
            let aggregate3 = provider
                .multicall()
                .add(is_valid_signature_call)
                .add(settle_call);
            let aggregate3_call = aggregate3.aggregate3();
            #[cfg(feature = "telemetry")]
            let (is_valid_signature_result, transfer_result) = aggregate3_call
                .instrument(tracing::info_span!("multi_call_settle_upto_permit2",
                    from = %payer,
                    to = %authorization.witness.to,
                    value = %authorization.permitted.amount,
                    valid_after = %authorization.witness.valid_after,
                    valid_before = %authorization.deadline,
                    nonce = %authorization.nonce,
                    token_contract = %authorization.permitted.token,
                    otel.kind = "client",
                ))
                .await?;
            #[cfg(not(feature = "telemetry"))]
            let (is_valid_signature_result, transfer_result) = aggregate3_call.await?;
            let is_valid_signature_result = is_valid_signature_result
                .map_err(|e| PaymentVerificationError::InvalidSignature(e.to_string()))?;
            if !is_valid_signature_result {
                return Err(PaymentVerificationError::InvalidSignature(
                    "Chain reported signature to be invalid".to_string(),
                )
                .into());
            }
            transfer_result
                .map_err(|e| PaymentVerificationError::TransactionSimulation(e.to_string()))?;
            Ok(())
        }
        StructuredSignature::EOA(signature) => {
            let permit_transfer_from = ISignatureTransfer::PermitTransferFrom {
                permitted: permit_witness_transfer_from.permitted,
                nonce: permit_witness_transfer_from.nonce,
                deadline: permit_witness_transfer_from.deadline,
            };
            let witness = permit_witness_transfer_from.witness;
            let settle_call = upto_permit2_proxy.settle(
                permit_transfer_from,
                authorization.permitted.amount,
                payer,
                witness,
                signature.as_bytes().into(),
            );
            let settle_call_fut = settle_call.call().into_future();
            #[cfg(feature = "telemetry")]
            settle_call_fut
                .instrument(tracing::info_span!("call_settle_upto_permit2",
                    from = %payer,
                    to = %authorization.witness.to,
                    value = %authorization.permitted.amount,
                    valid_after = %authorization.witness.valid_after,
                    valid_before = %authorization.deadline,
                    nonce = %authorization.nonce,
                    token_contract = %authorization.permitted.token,
                    otel.kind = "client",
                ))
                .await?;
            #[cfg(not(feature = "telemetry"))]
            settle_call_fut.await?;
            Ok(())
        }
        StructuredSignature::EIP1271(signature) => {
            let permit_transfer_from = ISignatureTransfer::PermitTransferFrom {
                permitted: permit_witness_transfer_from.permitted,
                nonce: permit_witness_transfer_from.nonce,
                deadline: permit_witness_transfer_from.deadline,
            };
            let witness = permit_witness_transfer_from.witness;
            let settle_call = upto_permit2_proxy.settle(
                permit_transfer_from,
                authorization.permitted.amount,
                payer,
                witness,
                signature,
            );
            let settle_call_fut = settle_call.call().into_future();
            #[cfg(feature = "telemetry")]
            settle_call_fut
                .instrument(tracing::info_span!("call_settle_upto_permit2",
                    from = %payer,
                    to = %authorization.witness.to,
                    value = %authorization.permitted.amount,
                    valid_after = %authorization.witness.valid_after,
                    valid_before = %authorization.deadline,
                    nonce = %authorization.nonce,
                    token_contract = %authorization.permitted.token,
                    otel.kind = "client",
                ))
                .await?;
            #[cfg(not(feature = "telemetry"))]
            settle_call_fut.await?;
            Ok(())
        }
    }
}

pub async fn settle_upto_permit2<P, E>(
    provider: &P,
    payment_payload: &Permit2PaymentPayload,
    actual_amount: U256,
) -> Result<TxHash, Eip155ExactError>
where
    P: Eip155MetaTransactionProvider<Error = E> + ChainProviderOps,
    Eip155ExactError: From<E>,
{
    let authorization = &payment_payload.payload.permit_2_authorization;
    let payer = authorization.from.0;
    let domain = eip712_domain! {
        name: "Permit2",
        chain_id: provider.chain().inner(),
        verifying_contract: PERMIT2_ADDRESS,
    };
    let permit_witness_transfer_from = PermitWitnessTransferFrom {
        permitted: ISignatureTransfer::TokenPermissions {
            token: authorization.permitted.token.into(),
            amount: authorization.permitted.amount,
        },
        spender: UPTO_PERMIT2_PROXY_ADDRESS,
        nonce: authorization.nonce,
        deadline: U256::from(authorization.deadline.as_secs()),
        witness: x402BasePermit2Proxy::Witness {
            to: authorization.witness.to.into(),
            validAfter: U256::from(authorization.witness.valid_after.as_secs()),
            extra: authorization.witness.extra.clone(),
        },
    };
    let eip712_hash = permit_witness_transfer_from.eip712_signing_hash(&domain);
    let structured_signature = StructuredSignature::try_from_bytes(
        payment_payload.payload.signature.clone(),
        payer,
        &eip712_hash,
    )?;

    let upto_permit2_proxy =
        X402UptoPermit2Proxy::new(UPTO_PERMIT2_PROXY_ADDRESS, provider.inner());
    let permit_transfer_from = ISignatureTransfer::PermitTransferFrom {
        permitted: permit_witness_transfer_from.permitted,
        nonce: permit_witness_transfer_from.nonce,
        deadline: permit_witness_transfer_from.deadline,
    };
    let witness = permit_witness_transfer_from.witness;

    let receipt: TransactionReceipt = match structured_signature {
        StructuredSignature::EIP6492 {
            factory,
            factory_calldata,
            inner,
            original: _,
        } => {
            let is_contract_deployed = is_contract_deployed(provider.inner(), &payer).await?;
            let settle_call = upto_permit2_proxy.settle(
                permit_transfer_from,
                actual_amount,
                payer,
                witness,
                inner.clone(),
            );
            if is_contract_deployed {
                let tx_fut = Eip155MetaTransactionProvider::send_transaction(
                    provider,
                    MetaTransaction {
                        to: settle_call.target(),
                        calldata: settle_call.calldata().clone(),
                        confirmations: 1,
                    },
                );
                #[cfg(feature = "telemetry")]
                let receipt = tx_fut
                    .instrument(
                        tracing::info_span!("call_upto_permit2_proxy_settle.EIP6492.deployed",
                            from = %payer,
                            to = %authorization.witness.to,
                            max_value = %authorization.permitted.amount,
                            actual_value = %actual_amount,
                            valid_after = %authorization.witness.valid_after,
                            valid_before = %authorization.deadline,
                            nonce = %authorization.nonce,
                            token_contract = %authorization.permitted.token,
                            signature = %inner,
                            sig_kind="EIP6492.deployed",
                            otel.kind = "client",
                        ),
                    )
                    .await?;
                #[cfg(not(feature = "telemetry"))]
                let receipt = tx_fut.await?;
                receipt
            } else {
                // deploy the smart wallet, and settle with inner signature
                let deployment_call = IMulticall3::Call3 {
                    allowFailure: true,
                    target: factory,
                    callData: factory_calldata,
                };
                let transfer_with_authorization_call = IMulticall3::Call3 {
                    allowFailure: false,
                    target: settle_call.target(),
                    callData: settle_call.calldata().clone(),
                };
                let aggregate_call = IMulticall3::aggregate3Call {
                    calls: vec![deployment_call, transfer_with_authorization_call],
                };
                let tx_fut = Eip155MetaTransactionProvider::send_transaction(
                    provider,
                    MetaTransaction {
                        to: MULTICALL3_ADDRESS,
                        calldata: aggregate_call.abi_encode().into(),
                        confirmations: 1,
                    },
                );
                #[cfg(feature = "telemetry")]
                let receipt = tx_fut
                    .instrument(
                        tracing::info_span!("call_upto_permit2_proxy_settle.EIP6492.counterfactual",
                            from = %payer,
                            to = %authorization.witness.to,
                            max_value = %authorization.permitted.amount,
                            actual_value = %actual_amount,
                            valid_after = %authorization.witness.valid_after,
                            valid_before = %authorization.deadline,
                            nonce = %authorization.nonce,
                            token_contract = %authorization.permitted.token,
                            signature = %inner,
                            sig_kind="EIP6492.counterfactual",
                            otel.kind = "client",
                        ),
                    )
                    .await?;
                #[cfg(not(feature = "telemetry"))]
                let receipt = tx_fut.await?;
                receipt
            }
        }
        StructuredSignature::EOA(signature) => {
            let settle_call = upto_permit2_proxy.settle(
                permit_transfer_from,
                actual_amount,
                payer,
                witness,
                signature.as_bytes().into(),
            );
            let tx_fut = Eip155MetaTransactionProvider::send_transaction(
                provider,
                MetaTransaction {
                    to: settle_call.target(),
                    calldata: settle_call.calldata().clone(),
                    confirmations: 1,
                },
            );
            #[cfg(feature = "telemetry")]
            let receipt = tx_fut
                .instrument(tracing::info_span!("call_upto_permit2_proxy_settle.EOA",
                    from = %payer,
                    to = %authorization.witness.to,
                    max_value = %authorization.permitted.amount,
                    actual_value = %actual_amount,
                    valid_after = %authorization.witness.valid_after,
                    valid_before = %authorization.deadline,
                    nonce = %authorization.nonce,
                    token_contract = %authorization.permitted.token,
                    signature = %signature,
                    sig_kind="EOA",
                    otel.kind = "client",
                ))
                .await?;
            #[cfg(not(feature = "telemetry"))]
            let receipt = tx_fut.await?;
            receipt
        }
        StructuredSignature::EIP1271(signature) => {
            let settle_call = upto_permit2_proxy.settle(
                permit_transfer_from,
                actual_amount,
                payer,
                witness,
                signature.clone(),
            );
            let tx_fut = Eip155MetaTransactionProvider::send_transaction(
                provider,
                MetaTransaction {
                    to: settle_call.target(),
                    calldata: settle_call.calldata().clone(),
                    confirmations: 1,
                },
            );
            #[cfg(feature = "telemetry")]
            let receipt = tx_fut
                .instrument(
                    tracing::info_span!("call_upto_permit2_proxy_settle.EIP1271",
                        from = %payer,
                        to = %authorization.witness.to,
                        max_value = %authorization.permitted.amount,
                        actual_value = %actual_amount,
                        valid_after = %authorization.witness.valid_after,
                        valid_before = %authorization.deadline,
                        nonce = %authorization.nonce,
                        token_contract = %authorization.permitted.token,
                        signature = %signature,
                        sig_kind="EIP1271",
                        otel.kind = "client",
                    ),
                )
                .await?;
            #[cfg(not(feature = "telemetry"))]
            let receipt = tx_fut.await?;
            receipt
        }
    };
    tx_hash_from_receipt(&receipt)
}