uvd-x402-sdk 2.23.0 → 2.24.1

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.
@@ -1643,6 +1643,22 @@ interface AdvancedTransactionResult {
1643
1643
  gasUsed?: number;
1644
1644
  error?: string;
1645
1645
  }
1646
+ /**
1647
+ * Response from the facilitator's /escrow/state endpoint.
1648
+ * Represents the on-chain state of an escrow for a given paymentInfo + payer.
1649
+ */
1650
+ interface EscrowStateResponse {
1651
+ /** Whether the payment has already been collected (released) */
1652
+ hasCollectedPayment: boolean;
1653
+ /** Amount that can still be captured/released (in atomic units) */
1654
+ capturableAmount: string;
1655
+ /** Amount that can still be refunded to the payer (in atomic units) */
1656
+ refundableAmount: string;
1657
+ /** Keccak256 hash of the paymentInfo struct */
1658
+ paymentInfoHash: string;
1659
+ /** Network in CAIP-2 format (e.g., "eip155:8453") */
1660
+ network: string;
1661
+ }
1646
1662
  /**
1647
1663
  * Contract addresses configuration for AdvancedEscrowClient.
1648
1664
  *
@@ -1792,6 +1808,69 @@ declare class AdvancedEscrowClient {
1792
1808
  * @param amount - Amount to refund (defaults to maxAmount)
1793
1809
  */
1794
1810
  refundInEscrow(paymentInfo: AdvancedPaymentInfo, amount?: string): Promise<AdvancedTransactionResult>;
1811
+ /**
1812
+ * GASLESS RELEASE: Release escrowed funds via the facilitator.
1813
+ *
1814
+ * Instead of calling the PaymentOperator contract directly (which requires
1815
+ * gas), this sends a release request to the facilitator, which submits
1816
+ * the transaction on your behalf.
1817
+ *
1818
+ * @param paymentInfo - PaymentInfo from the authorize step
1819
+ * @param amount - Amount to release in atomic units (defaults to maxAmount)
1820
+ * @returns Transaction result from the facilitator
1821
+ *
1822
+ * @example
1823
+ * ```typescript
1824
+ * const pi = client.buildPaymentInfo('0xWorker...', '5000000', 'standard');
1825
+ * await client.authorize(pi);
1826
+ * // Worker completes task...
1827
+ * const result = await client.releaseViaFacilitator(pi);
1828
+ * console.log(result.transactionHash);
1829
+ * ```
1830
+ */
1831
+ releaseViaFacilitator(paymentInfo: AdvancedPaymentInfo, amount?: string): Promise<AdvancedTransactionResult>;
1832
+ /**
1833
+ * GASLESS REFUND: Refund escrowed funds via the facilitator.
1834
+ *
1835
+ * Instead of calling the PaymentOperator contract directly (which requires
1836
+ * gas), this sends a refundInEscrow request to the facilitator, which
1837
+ * submits the transaction on your behalf.
1838
+ *
1839
+ * @param paymentInfo - PaymentInfo from the authorize step
1840
+ * @param amount - Amount to refund in atomic units (defaults to maxAmount)
1841
+ * @returns Transaction result from the facilitator
1842
+ *
1843
+ * @example
1844
+ * ```typescript
1845
+ * const pi = client.buildPaymentInfo('0xWorker...', '5000000', 'standard');
1846
+ * await client.authorize(pi);
1847
+ * // Task cancelled...
1848
+ * const result = await client.refundViaFacilitator(pi);
1849
+ * console.log(result.transactionHash);
1850
+ * ```
1851
+ */
1852
+ refundViaFacilitator(paymentInfo: AdvancedPaymentInfo, amount?: string): Promise<AdvancedTransactionResult>;
1853
+ /**
1854
+ * QUERY ESCROW STATE: Read on-chain escrow state via the facilitator.
1855
+ *
1856
+ * This is a read-only operation that queries the facilitator for the
1857
+ * current escrow state without requiring gas or a signer.
1858
+ *
1859
+ * @param paymentInfo - PaymentInfo to query state for
1860
+ * @returns Escrow state including capturable/refundable amounts
1861
+ *
1862
+ * @example
1863
+ * ```typescript
1864
+ * const pi = client.buildPaymentInfo('0xWorker...', '5000000', 'standard');
1865
+ * await client.authorize(pi);
1866
+ *
1867
+ * const state = await client.queryEscrowState(pi);
1868
+ * console.log(`Capturable: ${state.capturableAmount}`);
1869
+ * console.log(`Refundable: ${state.refundableAmount}`);
1870
+ * console.log(`Already collected: ${state.hasCollectedPayment}`);
1871
+ * ```
1872
+ */
1873
+ queryEscrowState(paymentInfo: AdvancedPaymentInfo): Promise<EscrowStateResponse>;
1795
1874
  /**
1796
1875
  * CHARGE: Direct instant payment (no escrow hold).
1797
1876
  *
@@ -1825,4 +1904,4 @@ declare class AdvancedEscrowClient {
1825
1904
  refundPostEscrow(paymentInfo: AdvancedPaymentInfo, amount?: string, tokenCollector?: string, collectorData?: string): Promise<AdvancedTransactionResult>;
1826
1905
  }
1827
1906
 
1828
- export { type AdvancedAuthorizationResult, AdvancedEscrowClient, type AdvancedEscrowClientOptions, type AdvancedEscrowContracts, type AdvancedEscrowTaskTier, type AdvancedPaymentInfo, type AdvancedTransactionResult, type AgentIdentity, type AgentRegistration, type AgentRegistrationFile, type AgentService, BASE_MAINNET_CONTRACTS, type BazaarCategory, BazaarClient, type BazaarClientOptions, type BazaarDiscoverOptions, type BazaarDiscoverResponse, type BazaarNetwork, type BazaarRegisterOptions, type BazaarResource, type BazaarToken, type CreateEscrowOptions, DEPOSIT_LIMIT_USDC, type Dispute, type DisputeOutcome, ERC8004_CONTRACTS, ERC8004_EXTENSION_ID, ESCROW_CONTRACTS, Erc8004Client, type Erc8004ClientOptions, type Erc8004Network, EscrowClient, type EscrowClientOptions, type EscrowPayment, type EscrowStatus, FacilitatorClient, type FacilitatorClientOptions, type FeedbackEntry, type FeedbackParams, type FeedbackRequest, type FeedbackResponse, type IdentityMetadataResponse, type IdentityTotalSupplyResponse, type MetadataEntryParam, OPERATOR_ABI, PAYMENT_INFO_TYPEHASH, type PaymentRequirements, type PaymentRequirementsOptions, type ProofOfPayment, type RefundRequest, type RefundStatus, type RegisterAgentRequest, type RegisterAgentResponse, type ReputationResponse, type ReputationSummary, type RequestRefundOptions, type SettleRequest, type SettleResponse, type SettleResponseWithProof, TIER_TIMINGS, USDC_DOMAIN_NAME, type VerifyRequest, type VerifyResponse, X402_CORS_HEADERS, X402_HEADER_NAMES, ZERO_ADDRESS, buildErc8004PaymentRequirements, buildPaymentRequirements, buildSettleRequest, buildVerifyRequest, canRefundEscrow, canReleaseEscrow, create402Response, createPaymentMiddleware, escrowTimeRemaining, extractPaymentFromHeaders, getCorsHeaders, getEscrowContractsByChainId, getEscrowSupportedChainIds, isEscrowExpired, isEscrowSupportedOnChain, parsePaymentHeader };
1907
+ export { type AdvancedAuthorizationResult, AdvancedEscrowClient, type AdvancedEscrowClientOptions, type AdvancedEscrowContracts, type AdvancedEscrowTaskTier, type AdvancedPaymentInfo, type AdvancedTransactionResult, type AgentIdentity, type AgentRegistration, type AgentRegistrationFile, type AgentService, BASE_MAINNET_CONTRACTS, type BazaarCategory, BazaarClient, type BazaarClientOptions, type BazaarDiscoverOptions, type BazaarDiscoverResponse, type BazaarNetwork, type BazaarRegisterOptions, type BazaarResource, type BazaarToken, type CreateEscrowOptions, DEPOSIT_LIMIT_USDC, type Dispute, type DisputeOutcome, ERC8004_CONTRACTS, ERC8004_EXTENSION_ID, ESCROW_CONTRACTS, Erc8004Client, type Erc8004ClientOptions, type Erc8004Network, EscrowClient, type EscrowClientOptions, type EscrowPayment, type EscrowStateResponse, type EscrowStatus, FacilitatorClient, type FacilitatorClientOptions, type FeedbackEntry, type FeedbackParams, type FeedbackRequest, type FeedbackResponse, type IdentityMetadataResponse, type IdentityTotalSupplyResponse, type MetadataEntryParam, OPERATOR_ABI, PAYMENT_INFO_TYPEHASH, type PaymentRequirements, type PaymentRequirementsOptions, type ProofOfPayment, type RefundRequest, type RefundStatus, type RegisterAgentRequest, type RegisterAgentResponse, type ReputationResponse, type ReputationSummary, type RequestRefundOptions, type SettleRequest, type SettleResponse, type SettleResponseWithProof, TIER_TIMINGS, USDC_DOMAIN_NAME, type VerifyRequest, type VerifyResponse, X402_CORS_HEADERS, X402_HEADER_NAMES, ZERO_ADDRESS, buildErc8004PaymentRequirements, buildPaymentRequirements, buildSettleRequest, buildVerifyRequest, canRefundEscrow, canReleaseEscrow, create402Response, createPaymentMiddleware, escrowTimeRemaining, extractPaymentFromHeaders, getCorsHeaders, getEscrowContractsByChainId, getEscrowSupportedChainIds, isEscrowExpired, isEscrowSupportedOnChain, parsePaymentHeader };
@@ -1643,6 +1643,22 @@ interface AdvancedTransactionResult {
1643
1643
  gasUsed?: number;
1644
1644
  error?: string;
1645
1645
  }
1646
+ /**
1647
+ * Response from the facilitator's /escrow/state endpoint.
1648
+ * Represents the on-chain state of an escrow for a given paymentInfo + payer.
1649
+ */
1650
+ interface EscrowStateResponse {
1651
+ /** Whether the payment has already been collected (released) */
1652
+ hasCollectedPayment: boolean;
1653
+ /** Amount that can still be captured/released (in atomic units) */
1654
+ capturableAmount: string;
1655
+ /** Amount that can still be refunded to the payer (in atomic units) */
1656
+ refundableAmount: string;
1657
+ /** Keccak256 hash of the paymentInfo struct */
1658
+ paymentInfoHash: string;
1659
+ /** Network in CAIP-2 format (e.g., "eip155:8453") */
1660
+ network: string;
1661
+ }
1646
1662
  /**
1647
1663
  * Contract addresses configuration for AdvancedEscrowClient.
1648
1664
  *
@@ -1792,6 +1808,69 @@ declare class AdvancedEscrowClient {
1792
1808
  * @param amount - Amount to refund (defaults to maxAmount)
1793
1809
  */
1794
1810
  refundInEscrow(paymentInfo: AdvancedPaymentInfo, amount?: string): Promise<AdvancedTransactionResult>;
1811
+ /**
1812
+ * GASLESS RELEASE: Release escrowed funds via the facilitator.
1813
+ *
1814
+ * Instead of calling the PaymentOperator contract directly (which requires
1815
+ * gas), this sends a release request to the facilitator, which submits
1816
+ * the transaction on your behalf.
1817
+ *
1818
+ * @param paymentInfo - PaymentInfo from the authorize step
1819
+ * @param amount - Amount to release in atomic units (defaults to maxAmount)
1820
+ * @returns Transaction result from the facilitator
1821
+ *
1822
+ * @example
1823
+ * ```typescript
1824
+ * const pi = client.buildPaymentInfo('0xWorker...', '5000000', 'standard');
1825
+ * await client.authorize(pi);
1826
+ * // Worker completes task...
1827
+ * const result = await client.releaseViaFacilitator(pi);
1828
+ * console.log(result.transactionHash);
1829
+ * ```
1830
+ */
1831
+ releaseViaFacilitator(paymentInfo: AdvancedPaymentInfo, amount?: string): Promise<AdvancedTransactionResult>;
1832
+ /**
1833
+ * GASLESS REFUND: Refund escrowed funds via the facilitator.
1834
+ *
1835
+ * Instead of calling the PaymentOperator contract directly (which requires
1836
+ * gas), this sends a refundInEscrow request to the facilitator, which
1837
+ * submits the transaction on your behalf.
1838
+ *
1839
+ * @param paymentInfo - PaymentInfo from the authorize step
1840
+ * @param amount - Amount to refund in atomic units (defaults to maxAmount)
1841
+ * @returns Transaction result from the facilitator
1842
+ *
1843
+ * @example
1844
+ * ```typescript
1845
+ * const pi = client.buildPaymentInfo('0xWorker...', '5000000', 'standard');
1846
+ * await client.authorize(pi);
1847
+ * // Task cancelled...
1848
+ * const result = await client.refundViaFacilitator(pi);
1849
+ * console.log(result.transactionHash);
1850
+ * ```
1851
+ */
1852
+ refundViaFacilitator(paymentInfo: AdvancedPaymentInfo, amount?: string): Promise<AdvancedTransactionResult>;
1853
+ /**
1854
+ * QUERY ESCROW STATE: Read on-chain escrow state via the facilitator.
1855
+ *
1856
+ * This is a read-only operation that queries the facilitator for the
1857
+ * current escrow state without requiring gas or a signer.
1858
+ *
1859
+ * @param paymentInfo - PaymentInfo to query state for
1860
+ * @returns Escrow state including capturable/refundable amounts
1861
+ *
1862
+ * @example
1863
+ * ```typescript
1864
+ * const pi = client.buildPaymentInfo('0xWorker...', '5000000', 'standard');
1865
+ * await client.authorize(pi);
1866
+ *
1867
+ * const state = await client.queryEscrowState(pi);
1868
+ * console.log(`Capturable: ${state.capturableAmount}`);
1869
+ * console.log(`Refundable: ${state.refundableAmount}`);
1870
+ * console.log(`Already collected: ${state.hasCollectedPayment}`);
1871
+ * ```
1872
+ */
1873
+ queryEscrowState(paymentInfo: AdvancedPaymentInfo): Promise<EscrowStateResponse>;
1795
1874
  /**
1796
1875
  * CHARGE: Direct instant payment (no escrow hold).
1797
1876
  *
@@ -1825,4 +1904,4 @@ declare class AdvancedEscrowClient {
1825
1904
  refundPostEscrow(paymentInfo: AdvancedPaymentInfo, amount?: string, tokenCollector?: string, collectorData?: string): Promise<AdvancedTransactionResult>;
1826
1905
  }
1827
1906
 
1828
- export { type AdvancedAuthorizationResult, AdvancedEscrowClient, type AdvancedEscrowClientOptions, type AdvancedEscrowContracts, type AdvancedEscrowTaskTier, type AdvancedPaymentInfo, type AdvancedTransactionResult, type AgentIdentity, type AgentRegistration, type AgentRegistrationFile, type AgentService, BASE_MAINNET_CONTRACTS, type BazaarCategory, BazaarClient, type BazaarClientOptions, type BazaarDiscoverOptions, type BazaarDiscoverResponse, type BazaarNetwork, type BazaarRegisterOptions, type BazaarResource, type BazaarToken, type CreateEscrowOptions, DEPOSIT_LIMIT_USDC, type Dispute, type DisputeOutcome, ERC8004_CONTRACTS, ERC8004_EXTENSION_ID, ESCROW_CONTRACTS, Erc8004Client, type Erc8004ClientOptions, type Erc8004Network, EscrowClient, type EscrowClientOptions, type EscrowPayment, type EscrowStatus, FacilitatorClient, type FacilitatorClientOptions, type FeedbackEntry, type FeedbackParams, type FeedbackRequest, type FeedbackResponse, type IdentityMetadataResponse, type IdentityTotalSupplyResponse, type MetadataEntryParam, OPERATOR_ABI, PAYMENT_INFO_TYPEHASH, type PaymentRequirements, type PaymentRequirementsOptions, type ProofOfPayment, type RefundRequest, type RefundStatus, type RegisterAgentRequest, type RegisterAgentResponse, type ReputationResponse, type ReputationSummary, type RequestRefundOptions, type SettleRequest, type SettleResponse, type SettleResponseWithProof, TIER_TIMINGS, USDC_DOMAIN_NAME, type VerifyRequest, type VerifyResponse, X402_CORS_HEADERS, X402_HEADER_NAMES, ZERO_ADDRESS, buildErc8004PaymentRequirements, buildPaymentRequirements, buildSettleRequest, buildVerifyRequest, canRefundEscrow, canReleaseEscrow, create402Response, createPaymentMiddleware, escrowTimeRemaining, extractPaymentFromHeaders, getCorsHeaders, getEscrowContractsByChainId, getEscrowSupportedChainIds, isEscrowExpired, isEscrowSupportedOnChain, parsePaymentHeader };
1907
+ export { type AdvancedAuthorizationResult, AdvancedEscrowClient, type AdvancedEscrowClientOptions, type AdvancedEscrowContracts, type AdvancedEscrowTaskTier, type AdvancedPaymentInfo, type AdvancedTransactionResult, type AgentIdentity, type AgentRegistration, type AgentRegistrationFile, type AgentService, BASE_MAINNET_CONTRACTS, type BazaarCategory, BazaarClient, type BazaarClientOptions, type BazaarDiscoverOptions, type BazaarDiscoverResponse, type BazaarNetwork, type BazaarRegisterOptions, type BazaarResource, type BazaarToken, type CreateEscrowOptions, DEPOSIT_LIMIT_USDC, type Dispute, type DisputeOutcome, ERC8004_CONTRACTS, ERC8004_EXTENSION_ID, ESCROW_CONTRACTS, Erc8004Client, type Erc8004ClientOptions, type Erc8004Network, EscrowClient, type EscrowClientOptions, type EscrowPayment, type EscrowStateResponse, type EscrowStatus, FacilitatorClient, type FacilitatorClientOptions, type FeedbackEntry, type FeedbackParams, type FeedbackRequest, type FeedbackResponse, type IdentityMetadataResponse, type IdentityTotalSupplyResponse, type MetadataEntryParam, OPERATOR_ABI, PAYMENT_INFO_TYPEHASH, type PaymentRequirements, type PaymentRequirementsOptions, type ProofOfPayment, type RefundRequest, type RefundStatus, type RegisterAgentRequest, type RegisterAgentResponse, type ReputationResponse, type ReputationSummary, type RequestRefundOptions, type SettleRequest, type SettleResponse, type SettleResponseWithProof, TIER_TIMINGS, USDC_DOMAIN_NAME, type VerifyRequest, type VerifyResponse, X402_CORS_HEADERS, X402_HEADER_NAMES, ZERO_ADDRESS, buildErc8004PaymentRequirements, buildPaymentRequirements, buildSettleRequest, buildVerifyRequest, canRefundEscrow, canReleaseEscrow, create402Response, createPaymentMiddleware, escrowTimeRemaining, extractPaymentFromHeaders, getCorsHeaders, getEscrowContractsByChainId, getEscrowSupportedChainIds, isEscrowExpired, isEscrowSupportedOnChain, parsePaymentHeader };
@@ -2575,6 +2575,15 @@ var ESCROW_CONTRACTS = {
2575
2575
  protocolFeeConfig: "0xD979dBfBdA5f4b16AAF60Eaab32A44f352076838",
2576
2576
  refundRequest: "0xc1256Bb30bd0cdDa07D8C8Cf67a59105f2EA1b98",
2577
2577
  usdc: "0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E"
2578
+ },
2579
+ // Optimism (chain 10)
2580
+ 10: {
2581
+ operator: "0x32d6AC59BCe8DFB3026F10BcaDB8D00AB218f5b6",
2582
+ escrow: "0x320a3c35F131E5D2Fb36af56345726B298936037",
2583
+ tokenCollector: "0x0DdF51E62DDD41B5f67BEaF2DCE9F2e99E2C5aF5",
2584
+ protocolFeeConfig: "0xe968AA7530b9C3336FED14FD5D5D4dD3Cf82655D",
2585
+ refundRequest: "0xc1256Bb30bd0cdDa07D8C8Cf67a59105f2EA1b98",
2586
+ usdc: "0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85"
2578
2587
  }
2579
2588
  };
2580
2589
  var BASE_MAINNET_CONTRACTS = ESCROW_CONTRACTS[8453];
@@ -2864,6 +2873,206 @@ var AdvancedEscrowClient = class {
2864
2873
  return { success: false, error: e.message || String(e) };
2865
2874
  }
2866
2875
  }
2876
+ // ==========================================================================
2877
+ // GASLESS FACILITATOR METHODS
2878
+ // ==========================================================================
2879
+ /**
2880
+ * GASLESS RELEASE: Release escrowed funds via the facilitator.
2881
+ *
2882
+ * Instead of calling the PaymentOperator contract directly (which requires
2883
+ * gas), this sends a release request to the facilitator, which submits
2884
+ * the transaction on your behalf.
2885
+ *
2886
+ * @param paymentInfo - PaymentInfo from the authorize step
2887
+ * @param amount - Amount to release in atomic units (defaults to maxAmount)
2888
+ * @returns Transaction result from the facilitator
2889
+ *
2890
+ * @example
2891
+ * ```typescript
2892
+ * const pi = client.buildPaymentInfo('0xWorker...', '5000000', 'standard');
2893
+ * await client.authorize(pi);
2894
+ * // Worker completes task...
2895
+ * const result = await client.releaseViaFacilitator(pi);
2896
+ * console.log(result.transactionHash);
2897
+ * ```
2898
+ */
2899
+ async releaseViaFacilitator(paymentInfo, amount) {
2900
+ if (!this.payerAddress) await this.init();
2901
+ try {
2902
+ const payload = {
2903
+ x402Version: 2,
2904
+ scheme: "escrow",
2905
+ action: "release",
2906
+ payload: {
2907
+ paymentInfo: {
2908
+ operator: paymentInfo.operator,
2909
+ receiver: paymentInfo.receiver,
2910
+ token: paymentInfo.token,
2911
+ maxAmount: paymentInfo.maxAmount,
2912
+ preApprovalExpiry: paymentInfo.preApprovalExpiry,
2913
+ authorizationExpiry: paymentInfo.authorizationExpiry,
2914
+ refundExpiry: paymentInfo.refundExpiry,
2915
+ minFeeBps: paymentInfo.minFeeBps,
2916
+ maxFeeBps: paymentInfo.maxFeeBps,
2917
+ feeReceiver: paymentInfo.feeReceiver,
2918
+ salt: paymentInfo.salt
2919
+ },
2920
+ payer: this.payerAddress,
2921
+ amount: amount || paymentInfo.maxAmount
2922
+ },
2923
+ paymentRequirements: {
2924
+ scheme: "escrow",
2925
+ network: `eip155:${this.chainId}`,
2926
+ extra: {
2927
+ escrowAddress: this.contracts.escrow,
2928
+ operatorAddress: this.contracts.operator,
2929
+ tokenCollector: this.contracts.tokenCollector
2930
+ }
2931
+ }
2932
+ };
2933
+ const response = await fetch(`${this.facilitatorUrl}/settle`, {
2934
+ method: "POST",
2935
+ headers: { "Content-Type": "application/json" },
2936
+ body: JSON.stringify(payload)
2937
+ });
2938
+ const result = await response.json();
2939
+ if (result.success) {
2940
+ return {
2941
+ success: true,
2942
+ transactionHash: result.transaction || result.transactionHash || result.transaction_hash
2943
+ };
2944
+ }
2945
+ return { success: false, error: result.errorReason || result.error || "Release failed" };
2946
+ } catch (e) {
2947
+ return { success: false, error: e.message || String(e) };
2948
+ }
2949
+ }
2950
+ /**
2951
+ * GASLESS REFUND: Refund escrowed funds via the facilitator.
2952
+ *
2953
+ * Instead of calling the PaymentOperator contract directly (which requires
2954
+ * gas), this sends a refundInEscrow request to the facilitator, which
2955
+ * submits the transaction on your behalf.
2956
+ *
2957
+ * @param paymentInfo - PaymentInfo from the authorize step
2958
+ * @param amount - Amount to refund in atomic units (defaults to maxAmount)
2959
+ * @returns Transaction result from the facilitator
2960
+ *
2961
+ * @example
2962
+ * ```typescript
2963
+ * const pi = client.buildPaymentInfo('0xWorker...', '5000000', 'standard');
2964
+ * await client.authorize(pi);
2965
+ * // Task cancelled...
2966
+ * const result = await client.refundViaFacilitator(pi);
2967
+ * console.log(result.transactionHash);
2968
+ * ```
2969
+ */
2970
+ async refundViaFacilitator(paymentInfo, amount) {
2971
+ if (!this.payerAddress) await this.init();
2972
+ try {
2973
+ const payload = {
2974
+ x402Version: 2,
2975
+ scheme: "escrow",
2976
+ action: "refundInEscrow",
2977
+ payload: {
2978
+ paymentInfo: {
2979
+ operator: paymentInfo.operator,
2980
+ receiver: paymentInfo.receiver,
2981
+ token: paymentInfo.token,
2982
+ maxAmount: paymentInfo.maxAmount,
2983
+ preApprovalExpiry: paymentInfo.preApprovalExpiry,
2984
+ authorizationExpiry: paymentInfo.authorizationExpiry,
2985
+ refundExpiry: paymentInfo.refundExpiry,
2986
+ minFeeBps: paymentInfo.minFeeBps,
2987
+ maxFeeBps: paymentInfo.maxFeeBps,
2988
+ feeReceiver: paymentInfo.feeReceiver,
2989
+ salt: paymentInfo.salt
2990
+ },
2991
+ payer: this.payerAddress,
2992
+ amount: amount || paymentInfo.maxAmount
2993
+ },
2994
+ paymentRequirements: {
2995
+ scheme: "escrow",
2996
+ network: `eip155:${this.chainId}`,
2997
+ extra: {
2998
+ escrowAddress: this.contracts.escrow,
2999
+ operatorAddress: this.contracts.operator,
3000
+ tokenCollector: this.contracts.tokenCollector
3001
+ }
3002
+ }
3003
+ };
3004
+ const response = await fetch(`${this.facilitatorUrl}/settle`, {
3005
+ method: "POST",
3006
+ headers: { "Content-Type": "application/json" },
3007
+ body: JSON.stringify(payload)
3008
+ });
3009
+ const result = await response.json();
3010
+ if (result.success) {
3011
+ return {
3012
+ success: true,
3013
+ transactionHash: result.transaction || result.transactionHash || result.transaction_hash
3014
+ };
3015
+ }
3016
+ return { success: false, error: result.errorReason || result.error || "Refund failed" };
3017
+ } catch (e) {
3018
+ return { success: false, error: e.message || String(e) };
3019
+ }
3020
+ }
3021
+ /**
3022
+ * QUERY ESCROW STATE: Read on-chain escrow state via the facilitator.
3023
+ *
3024
+ * This is a read-only operation that queries the facilitator for the
3025
+ * current escrow state without requiring gas or a signer.
3026
+ *
3027
+ * @param paymentInfo - PaymentInfo to query state for
3028
+ * @returns Escrow state including capturable/refundable amounts
3029
+ *
3030
+ * @example
3031
+ * ```typescript
3032
+ * const pi = client.buildPaymentInfo('0xWorker...', '5000000', 'standard');
3033
+ * await client.authorize(pi);
3034
+ *
3035
+ * const state = await client.queryEscrowState(pi);
3036
+ * console.log(`Capturable: ${state.capturableAmount}`);
3037
+ * console.log(`Refundable: ${state.refundableAmount}`);
3038
+ * console.log(`Already collected: ${state.hasCollectedPayment}`);
3039
+ * ```
3040
+ */
3041
+ async queryEscrowState(paymentInfo) {
3042
+ if (!this.payerAddress) await this.init();
3043
+ const payload = {
3044
+ paymentInfo: {
3045
+ operator: paymentInfo.operator,
3046
+ receiver: paymentInfo.receiver,
3047
+ token: paymentInfo.token,
3048
+ maxAmount: paymentInfo.maxAmount,
3049
+ preApprovalExpiry: paymentInfo.preApprovalExpiry,
3050
+ authorizationExpiry: paymentInfo.authorizationExpiry,
3051
+ refundExpiry: paymentInfo.refundExpiry,
3052
+ minFeeBps: paymentInfo.minFeeBps,
3053
+ maxFeeBps: paymentInfo.maxFeeBps,
3054
+ feeReceiver: paymentInfo.feeReceiver,
3055
+ salt: paymentInfo.salt
3056
+ },
3057
+ payer: this.payerAddress,
3058
+ network: `eip155:${this.chainId}`,
3059
+ extra: {
3060
+ escrowAddress: this.contracts.escrow,
3061
+ operatorAddress: this.contracts.operator,
3062
+ tokenCollector: this.contracts.tokenCollector
3063
+ }
3064
+ };
3065
+ const response = await fetch(`${this.facilitatorUrl}/escrow/state`, {
3066
+ method: "POST",
3067
+ headers: { "Content-Type": "application/json" },
3068
+ body: JSON.stringify(payload)
3069
+ });
3070
+ if (!response.ok) {
3071
+ const errorText = await response.text();
3072
+ throw new Error(`Escrow state query failed: ${response.status} - ${errorText}`);
3073
+ }
3074
+ return await response.json();
3075
+ }
2867
3076
  /**
2868
3077
  * CHARGE: Direct instant payment (no escrow hold).
2869
3078
  *