{"version":3,"sources":["../../../../src/exact/facilitator/scheme.ts","../../../../src/exact/facilitator/register.ts"],"sourcesContent":["import {\n  PaymentPayload,\n  PaymentRequirements,\n  SchemeNetworkFacilitator,\n  SettleResponse,\n  VerifyResponse,\n} from \"@aeon-ai-pay/core/types\";\nimport {\n  encodeFunctionData,\n  getAddress,\n  Hex,\n  isAddressEqual,\n  parseErc6492Signature,\n  parseSignature,\n} from \"viem\";\nimport {\n  aeonAuthorizationPrimaryType,\n  aeonAuthorizationTypes,\n  authorizationTypes,\n  eip3009ABI,\n} from \"../../constants\";\nimport { FacilitatorEvmSigner } from \"../../signer\";\nimport { ExactEvmPayloadV2 } from \"../../types\";\nimport { ReadContractClient, verifyTransferWithAuthorizationSupport } from \"../../contractUtils\";\nimport * as console from \"node:console\";\nimport { ZeroGasTool } from \"./utils/ZeroGasTool\";\nimport { TokenSymbolUtil } from \"./utils/TokenSymbolUtil\";\nconst facilitatorId = 1;\n\nexport interface ExactEvmSchemeConfig {\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.\n */\nexport class ExactEvmScheme implements SchemeNetworkFacilitator {\n  readonly scheme = \"exact\";\n  readonly caipFamily = \"eip155:*\";\n  private readonly config: Required<ExactEvmSchemeConfig>;\n\n  /**\n   * Creates a new ExactEvmFacilitator 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?: ExactEvmSchemeConfig,\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  private getNetworkIdFromNetwork(network: string): string {\n    // 1. 校验输入非空\n    if (!network || network.trim().length === 0) {\n      throw new Error(\"无效的网络字符串：输入为空或null\");\n    }\n\n    // 2. 拆分并校验 EIP-155 格式\n    const parts = network.split(\":\");\n    if (parts.length !== 2 || parts[0] !== \"eip155\") {\n      throw new Error(\n        `无效的网络格式：必须是 \"eip155:数字\" 格式，当前输入为 \"${network}\"`\n      );\n    }\n\n    // 3. 校验后缀为纯数字\n    const networkId = parts[1];\n    if (!/^\\d+$/.test(networkId)) {\n      throw new Error(\n        `无效的网络ID：后缀必须是纯数字，当前为 \"${networkId}\"`\n      );\n    }\n\n    return networkId;\n  }\n  /**\n   * 获取代币的精度（decimals）\n   * 通过调用ERC20合约的decimals()函数来获取代币精度\n   *\n   * @param tokenAddress - 代币合约地址\n   * @returns Promise<number> - 代币精度（通常为6或18）\n   */\n  private async getAssetDecimals(tokenAddress: string): Promise<number> {\n    try {\n      // ERC20标准的decimals()函数ABI\n      const ERC20_DECIMALS_ABI = [\n        {\n          type: \"function\",\n          name: \"decimals\",\n          inputs: [],\n          outputs: [{ name: \"\", type: \"uint8\" }],\n          stateMutability: \"view\",\n        },\n      ] as const;\n\n      // 调用合约的decimals()函数\n      const decimals = (await this.signer.readContract({\n        address: getAddress(tokenAddress) as Hex,\n        abi: ERC20_DECIMALS_ABI,\n        functionName: \"decimals\",\n        args: [],\n      })) as number;\n\n      return decimals;\n    } catch (error) {\n      // 如果调用失败，记录错误并返回默认值（USDC通常是6）\n      console.warn(\n        `[WARN] Failed to get decimals for token ${tokenAddress}, using default 6:`,\n        error instanceof Error ? error.message : String(error),\n      );\n      return 6; // 默认返回6（USDC的精度）\n    }\n  }\n\n  /**\n   * Verifies a payment payload.\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 exactEvmPayload = payload.payload as ExactEvmPayloadV2;\n\n    // Verify scheme matches\n    if (payload.accepted.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    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 (payload.accepted.network !== requirements.network) {\n      return {\n        isValid: false,\n        invalidReason: \"network_mismatch\",\n        payer: exactEvmPayload.authorization.from,\n      };\n    }\n    const supportEip3009 = await verifyTransferWithAuthorizationSupport(\n      this.signer,\n      requirements.asset,\n    );\n    console.log(\"[DEBUG] tokenAddress:\", requirements.asset);\n    console.log(\"[DEBUG] supportEip3009:\", supportEip3009);\n    // let permitTypedData;\n    // if (supportEip3009) {\n    //   permitTypedData = {\n    //     types: authorizationTypes,\n    //     primaryType: \"TransferWithAuthorization\" as const,\n    //     domain: {\n    //       name,\n    //       version,\n    //       chainId: parseInt(requirements.network.split(\":\")[1]),\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    // } else {\n    //   const verifyingContract = \"0x555e3311a9893c9B17444C1Ff0d88192a57Ef13e\";\n    //   permitTypedData = {\n    //     types: aeonAuthorizationTypes,\n    //     primaryType: aeonAuthorizationPrimaryType,\n    //     domain: {\n    //       name: \"Facilitator\",\n    //       version: \"1\",\n    //       chainId: parseInt(requirements.network.split(\":\")[1]),\n    //       verifyingContract: verifyingContract,\n    //     },\n    //     message: {\n    //       token: getAddress(requirements.asset),\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    //       needApprove: true,\n    //     },\n    //   };\n    // }\n    // Verify signature\n    // try {\n    //   const recoveredAddress = await this.signer.verifyTypedData({\n    //     address: exactEvmPayload.authorization.from,\n    //     ...(permitTypedData as any),\n    //     signature: exactEvmPayload.signature!,\n    //   });\n\n    const funData = {\n      abi: [\n        {\n          name: \"tokenTransferWithAuthorization\",\n          type: \"function\",\n          inputs: [\n            { name: \"token\", type: \"address\" },\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: \"needApprove\", type: \"bool\" },\n            { name: \"signature\", type: \"bytes\" },\n          ],\n          outputs: [],\n          stateMutability: \"nonpayable\",\n        },\n      ],\n      functionName: \"tokenTransferWithAuthorization\",\n      args: [\n        getAddress(requirements.asset),\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 as Hex,\n        !supportEip3009,\n        exactEvmPayload.signature as Hex,\n      ],\n    };\n    const data = encodeFunctionData(funData);\n    const to = \"0x555e3311a9893c9B17444C1Ff0d88192a57Ef13e\";\n    try {\n      // Optional: estimate gas (useful for debugging / logging)\n      const [account] = await this.signer.getAddresses();\n      await this.signer.estimateGas({\n        // account: client.account!,\n        account: account,\n        // account: payload.authorization.from as Hex,\n        to: to as Hex,\n        data,\n      });\n    } catch (error) {\n      let errorMessage = \"\";\n\n      if (error instanceof Error) {\n        const errorStr = error.message;\n\n        // Check for specific revert reasons\n        if (errorStr.includes(\"0x13be252b\")) {\n          const ERC20_ABI = [\n            {\n              type: \"function\",\n              name: \"approve\",\n              inputs: [\n                { name: \"spender\", type: \"address\" },\n                { name: \"amount\", type: \"uint256\" },\n              ],\n              outputs: [{ name: \"success\", type: \"bool\" }],\n              stateMutability: \"nonpayable\",\n            },\n            {\n              type: \"function\",\n              name: \"allowance\",\n              inputs: [\n                { name: \"owner\", type: \"address\" },\n                { name: \"spender\", type: \"address\" },\n              ],\n              outputs: [{ name: \"remaining\", type: \"uint256\" }],\n              stateMutability: \"view\",\n            },\n          ] as const;\n          const from = getAddress(exactEvmPayload.authorization.from);\n          const facilitatorAddress = getAddress(\"0x555e3311a9893c9B17444C1Ff0d88192a57Ef13e\");\n\n          // Read current allowance and auto-approve if needed\n          const currentAllowance = (await this.signer.readContract({\n            address: getAddress(requirements.asset) as Hex,\n            abi: ERC20_ABI,\n            functionName: \"allowance\",\n            args: [from, facilitatorAddress],\n          })) as bigint;\n          console.log(\"currentAllowance:\", currentAllowance);\n\n          errorMessage =\n            \"Insufficient token allowance. Please approve the facilitator contract to spend your tokens before making the payment.\";\n        } else if (errorStr.includes(\"0xccea9e6f\")) {\n          errorMessage =\n            \"Invalid operator. The caller is not authorized to perform this operation.\";\n        } else if (errorStr.includes(\"0xdf8e4372\")) {\n          errorMessage =\n            \"Authorization not yet valid. The payment authorization is not yet active.\";\n        } else if (errorStr.includes(\"0x0f05f5bf\")) {\n          errorMessage = \"Authorization expired. The payment authorization has expired.\";\n        } else if (errorStr.includes(\"0x1f6d5aef\")) {\n          errorMessage = \"Nonce already used. This authorization has already been used.\";\n        } else if (errorStr.includes(\"0x8baa579f\")) {\n          errorMessage = \"Invalid signature. The payment authorization signature is invalid.\";\n        } else {\n          errorMessage = \"Failed to estimate gas: \" + errorStr;\n        }\n        return {\n          isValid: false,\n          invalidReason: errorMessage,\n          payer: exactEvmPayload.authorization.from,\n        };\n      } else {\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\")\n          ? signature.length - 2\n          : 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\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(requirements.amount)) {\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(requirements.amount)) {\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.\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 exactEvmPayload = payload.payload as ExactEvmPayloadV2;\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: payload.accepted.network,\n    //     transaction: \"\",\n    //     errorReason: valid.invalidReason ?? \"invalid_scheme\",\n    //     payer: exactEvmPayload.authorization.from,\n    //   };\n    // }\n\n    let tx;\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      const supportEip3009 = await verifyTransferWithAuthorizationSupport(\n        this.signer,\n        requirements.asset,\n      );\n\n      const funData = {\n        abi: [\n          {\n            name: \"tokenTransferWithAuthorization\",\n            type: \"function\",\n            inputs: [\n              { name: \"token\", type: \"address\" },\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: \"needApprove\", type: \"bool\" },\n              { name: \"signature\", type: \"bytes\" },\n            ],\n            outputs: [],\n            stateMutability: \"nonpayable\",\n          },\n        ],\n        functionName: \"tokenTransferWithAuthorization\",\n        args: [\n          getAddress(requirements.asset),\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 as Hex,\n          !supportEip3009,\n          exactEvmPayload.signature as Hex,\n        ],\n      };\n      let networkId = \"\";\n      try {\n        networkId = this.getNetworkIdFromNetwork(payload.accepted.network);\n      } catch (error) {\n        // 先校验 error 类型，再访问 message 属性\n        const errorMsg = error instanceof Error ? error.message : String(error);\n        console.error(\"[ERROR] 解析 networkId 失败:\", errorMsg);\n        throw new Error(`网络格式错误：${errorMsg}`);\n      }\n\n      const resource = payload.resource?.url || \"\";\n      const payToAddress = getAddress(exactEvmPayload.authorization.to);\n      const tokenAddress = getAddress(payload.accepted.asset);\n      const tokenDecimals = await this.getAssetDecimals(payload.accepted.asset);\n      const amountRequired = Number(requirements.amount);\n      const value = Number(exactEvmPayload.authorization.value);\n      const tokenSymbol = TokenSymbolUtil.getTokenSymbolByAddress(payload.accepted.asset);\n\n      let next = true;\n      if (parseInt(requirements.network.split(\":\")[1]) == 56) {\n        console.log(\"使用 ZeroGasTool 代付\");\n        try {\n          // 创建 ZeroGasTool 实例\n          const tool = new ZeroGasTool();\n          const validateResult = await tool.validateGaslessWithdraw2(funData);\n\n          if (validateResult && validateResult.isValid) {\n            // 执行交易\n            tx = (await tool.executeGaslessWithdraw(validateResult.txConfig)) as `0x${string}`;\n            // 等待交易确认\n            const receipt = await this.signer.waitForTransactionReceipt({\n              hash: tx as Hex,\n            });\n\n            if (receipt.status === \"success\") {\n              console.log(\"使用 ZeroGasTool 代付成功\");\n              next = false;\n              const resource = payload.resource.url;\n              console.log(\"resource:\", resource);\n              const txHash = tx;\n              const sendData = {\n                facilitatorId,\n                ...exactEvmPayload.authorization,\n                ...requirements,\n                payToAddress,\n                tokenAddress,\n                resource,\n                tokenDecimals,\n                txHash,\n                amountRequired,\n                networkId,\n                value,\n                tokenSymbol,\n                time: new Date().toISOString(),\n              };\n              // Post settlement log asynchronously (fire and forget)\n              postSettleLog(sendData).catch(logErr => {\n                console.error(\"[ERROR] Settlement log failed:\", logErr);\n                // Log error but don't affect main settlement flow\n              });\n            } else {\n              // 如果校验结果不支持赞助，继续执行原有的普通交易流程\n              next = false;\n            }\n          }\n        } catch (zeroGasError) {\n          // 如果 ZeroGasTool 处理失败，静默失败并使用原有的普通交易流程\n          // 不抛出错误，确保不影响原有逻辑\n          console.warn(\n            \"[ZEROGAS] Error or not applicable, using original transaction flow:\",\n            zeroGasError instanceof Error ? zeroGasError.message : String(zeroGasError),\n          );\n        }\n      }\n\n      if (next) {\n        const data = encodeFunctionData(funData);\n        const to = \"0x555e3311a9893c9B17444C1Ff0d88192a57Ef13e\";\n        // Send settlement transaction (must assign tx hash for receipt waiting)\n        tx = await this.signer.sendTransaction({\n          to: to as Hex,\n          data,\n        });\n\n        // Wait for  transaction to be confirmed\n        const approvalReceipt = await this.signer.waitForTransactionReceipt({\n          hash: tx,\n        });\n\n        if (approvalReceipt.status !== \"success\") {\n          return {\n            success: false,\n            errorReason: \"invalid_transaction_state\",\n            transaction: tx,\n            network: payload.accepted.network,\n            payer: exactEvmPayload.authorization.from,\n          };\n        }\n      }\n\n      // 获取代币精度\n      console.log(\"resource:\", resource);\n\n      const txHash = tx;\n      const sendData = {\n        facilitatorId,\n        ...exactEvmPayload.authorization,\n        ...requirements,\n        payToAddress,\n        tokenAddress,\n        resource,\n        tokenDecimals,\n        txHash,\n        networkId,\n        amountRequired,\n        value,\n        tokenSymbol,\n        time: new Date().toISOString(),\n      };\n      // Post settlement log asynchronously (fire and forget)\n      postSettleLog(sendData).catch(logErr => {\n        console.error(\"[ERROR] Settlement log failed:\", logErr);\n        // Log error but don't affect main settlement flow\n      });\n\n\n      return {\n        success: true,\n        transaction: tx as string,\n        network: payload.accepted.network,\n        payer: exactEvmPayload.authorization.from,\n      };\n    } catch (error) {\n      // Keep tx hash if we already broadcasted, so callers can track it even on timeout/failure.\n      const txHashFromError =\n        error instanceof Error\n          ? (error.message.match(/hash\\s+\"(0x[0-9a-fA-F]{64})\"/)?.[1] as `0x${string}` | undefined)\n          : undefined;\n\n      let errorMessage = \"Failed to settle transaction\";\n      if (error instanceof Error) {\n        const errorStr = error.message;\n        // Check for specific revert reasons\n        if (errorStr.includes(\"0x13be252b\")) {\n          errorMessage =\n            \"Insufficient token allowance. Please approve the facilitator contract to spend your tokens before making the payment.\";\n        } else if (errorStr.includes(\"0xccea9e6f\")) {\n          errorMessage =\n            \"Invalid operator. The caller is not authorized to perform this operation.\";\n        } else if (errorStr.includes(\"0xdf8e4372\")) {\n          errorMessage =\n            \"Authorization not yet valid. The payment authorization is not yet active.\";\n        } else if (errorStr.includes(\"0x0f05f5bf\")) {\n          errorMessage = \"Authorization expired. The payment authorization has expired.\";\n        } else if (errorStr.includes(\"0x1f6d5aef\")) {\n          errorMessage = \"Nonce already used. This authorization has already been used.\";\n        } else if (errorStr.includes(\"0x8baa579f\")) {\n          errorMessage = \"Invalid signature. The payment authorization signature is invalid.\";\n        } else if (errorStr.includes(\"Timed out while waiting for transaction\")) {\n          // viem timeout waiting for receipt (tx may still confirm later)\n          errorMessage = errorStr;\n        } else {\n          errorMessage = \"Failed to settle transaction: \" + errorStr;\n        }\n      } else {\n        errorMessage = \"Failed to settle transaction: \" + String(error);\n      }\n\n      console.error(\"Failed to settle transaction:\", error);\n      return {\n        success: false,\n        errorReason: errorMessage,\n        transaction: tx || txHashFromError || \"\",\n        network: payload.accepted.network,\n        payer: exactEvmPayload.authorization.from,\n      };\n    }\n  }\n}\n\nasync function postSettleLog(dataToSend: any) {\n  try {\n    console.log(\"[DEBUG] Posting settlement log...\");\n    const resp = await fetch(\"https://x402-scan-api.aeon.xyz/api/scan/manager/createTransaction\", {\n      method: \"POST\",\n      headers: { \"Content-Type\": \"application/json\" },\n      body: JSON.stringify(dataToSend),\n    });\n    console.log(\"[DEBUG] Settlement log posted body:\", JSON.stringify(dataToSend));\n    if (!resp.ok) {\n      throw new Error(`HTTP ${resp.status}: ${resp.statusText}`);\n    }\n\n    const logResp = await resp.text();\n    console.log(\"[DEBUG] Settlement log posted successfully:\", logResp);\n    return logResp;\n  } catch (logErr) {\n    console.error(\"[ERROR] Failed to post settlement log:\", logErr);\n    throw logErr; // Re-throw so the caller's .catch() can handle it\n  }\n}\n\n","import { x402Facilitator } from \"@aeon-ai-pay/core/facilitator\";\nimport { Network } from \"@aeon-ai-pay/core/types\";\nimport { FacilitatorEvmSigner } from \"../../signer\";\nimport { ExactEvmScheme } from \"./scheme\";\nimport { ExactEvmSchemeV1 } from \"../v1/facilitator/scheme\";\nimport { NETWORKS } from \"../../v1\";\n\n/**\n * Configuration options for registering EVM schemes to an x402Facilitator\n */\nexport interface EvmFacilitatorConfig {\n  /**\n   * The EVM signer for facilitator operations (verify and settle)\n   */\n  signer: FacilitatorEvmSigner;\n\n  /**\n   * Networks to register (single network or array of networks)\n   * Examples: \"eip155:84532\", [\"eip155:84532\", \"eip155:1\"]\n   */\n  networks: Network | Network[];\n\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 * Registers EVM exact payment schemes to an x402Facilitator instance.\n *\n * This function registers:\n * - V2: Specified networks with ExactEvmScheme\n * - V1: All supported EVM networks with ExactEvmSchemeV1\n *\n * @param facilitator - The x402Facilitator instance to register schemes to\n * @param config - Configuration for EVM facilitator registration\n * @returns The facilitator instance for chaining\n *\n * @example\n * ```typescript\n * import { registerExactEvmScheme } from \"@aeon-ai-pay/evm/exact/facilitator/register\";\n * import { x402Facilitator } from \"@aeon-ai-pay/core/facilitator\";\n * import { createPublicClient, createWalletClient } from \"viem\";\n *\n * const facilitator = new x402Facilitator();\n *\n * // Single network\n * registerExactEvmScheme(facilitator, {\n *   signer: combinedClient,\n *   networks: \"eip155:84532\"  // Base Sepolia\n * });\n *\n * // Multiple networks (will auto-derive eip155:* pattern)\n * registerExactEvmScheme(facilitator, {\n *   signer: combinedClient,\n *   networks: [\"eip155:84532\", \"eip155:1\"]  // Base Sepolia and Mainnet\n * });\n * ```\n */\nexport function registerExactEvmScheme(\n  facilitator: x402Facilitator,\n  config: EvmFacilitatorConfig,\n): x402Facilitator {\n  // Register V2 scheme with specified networks\n  facilitator.register(\n    config.networks,\n    new ExactEvmScheme(config.signer, {\n      deployERC4337WithEIP6492: config.deployERC4337WithEIP6492,\n    }),\n  );\n\n  // Register all V1 networks\n  facilitator.registerV1(\n    NETWORKS as Network[],\n    new ExactEvmSchemeV1(config.signer, {\n      deployERC4337WithEIP6492: config.deployERC4337WithEIP6492,\n    }),\n  );\n\n  return facilitator;\n}\n"],"mappings":";;;;;;;;;;;;;;;AAOA;AAAA,EACE;AAAA,EACA;AAAA,EAEA;AAAA,EACA;AAAA,OAEK;AAUP,YAAY,aAAa;AAGzB,IAAM,gBAAgB;AAef,IAAM,iBAAN,MAAyD;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAW9D,YACmB,QACjB,QACA;AAFiB;A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