@dexterai/x402 3.7.1 → 3.7.3

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 CHANGED
@@ -214,12 +214,32 @@ const { closed } = await channel.close();
214
214
  // refunds the rest of your escrow automatically on the normal path.
215
215
  ```
216
216
 
217
+ Each `openBatchChannel` call opens a **new** channel: a fresh random
218
+ channel-config salt is generated, so a buyer can hold several independent
219
+ channels with the same seller over time. The salt is exposed as
220
+ `channel.salt` — persist it if you will later need to resume that exact
221
+ channel.
222
+
223
+ To resume a channel after a process restart, call `resumeBatchChannel` with
224
+ the wallet, network, and the **salt** of the channel being resumed (the
225
+ `channelId` alone is not enough — it cannot be reversed to a salt):
226
+
227
+ ```ts
228
+ import { resumeBatchChannel } from '@dexterai/x402/batch-settlement';
229
+
230
+ const channel = await resumeBatchChannel({
231
+ wallet: evmWallet,
232
+ network: 'eip155:8453',
233
+ salt: savedSalt, // channel.salt captured at open time
234
+ });
235
+ ```
236
+
217
237
  Channel state auto-persists (localStorage in the browser, a file under
218
- `~/.dexter-x402/channels` in Node). If the process restarts mid-session,
219
- calling `openBatchChannel` again with the same wallet, network, and store
220
- transparently resumes the open channel the channel's state is recovered from
221
- storage, or from on-chain state if storage was lost. Pass a custom `store` (any
222
- `ChannelStore`) to persist elsewhere.
238
+ `~/.dexter-x402/channels` in Node); the resumed channel's accounting is
239
+ recovered from storage, or from on-chain state if storage was lost. Pass a
240
+ custom `store` (any `ChannelStore`) to persist elsewhere. To deterministically
241
+ reopen a specific channel instead of getting a fresh one, pass an explicit
242
+ `salt` to `openBatchChannel`.
223
243
 
224
244
  #### Escape hatch — `forceWithdraw()` / `finalizeWithdraw()`
225
245
 
@@ -1 +1 @@
1
- "use strict";var T=Object.defineProperty;var et=Object.getOwnPropertyDescriptor;var nt=Object.getOwnPropertyNames;var at=Object.prototype.hasOwnProperty;var rt=(t,e)=>{for(var n in e)T(t,n,{get:e[n],enumerable:!0})},it=(t,e,n,a)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of nt(e))!at.call(t,r)&&r!==n&&T(t,r,{get:()=>e[r],enumerable:!(a=et(e,r))||a.enumerable});return t};var ot=t=>it(T({},"__esModule",{value:!0}),t);var mt={};rt(mt,{InsufficientBalanceError:()=>k,UnsupportedNetworkError:()=>f,WithdrawNotReadyError:()=>y,createFileChannelStore:()=>P,createLocalStorageChannelStore:()=>B,getDefaultChannelStore:()=>W,openBatchChannel:()=>K,resumeBatchChannel:()=>Q});module.exports=ot(mt);var s=require("viem"),C=require("viem/chains"),V=require("@x402/evm"),v=require("@x402/evm/batch-settlement/client"),I=require("@x402/core/client");var $=require("os"),O=require("path"),N=require("@x402/evm/batch-settlement/client");function P(t){return new N.FileClientChannelStorage({directory:t})}var E="dexter-x402-channel:";function B(t){return{async get(e){let n=t.getItem(E+e);return n?JSON.parse(n):void 0},async set(e,n){t.setItem(E+e,JSON.stringify(n))},async delete(e){t.removeItem(E+e)}}}function W(){let t=globalThis.localStorage;return t?B(t):P((0,O.join)((0,$.homedir)(),".dexter-x402","channels"))}var k=class extends Error{constructor(e){super(e),this.name="InsufficientBalanceError"}},f=class extends Error{constructor(e){super(e),this.name="UnsupportedNetworkError"}};var H=require("viem"),z=require("@x402/evm/batch-settlement/client"),g=require("@x402/evm"),y=class extends Error{constructor(e){super(e),this.name="WithdrawNotReadyError"}};function L(t,e){return t===0?0:t+e}var st=6,j=[{name:"payer",type:"address"},{name:"payerAuthorizer",type:"address"},{name:"receiver",type:"address"},{name:"receiverAuthorizer",type:"address"},{name:"token",type:"address"},{name:"withdrawDelay",type:"uint40"},{name:"salt",type:"bytes32"}],R=[{type:"function",name:"initiateWithdraw",inputs:[{name:"config",type:"tuple",components:j},{name:"amount",type:"uint128"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"finalizeWithdraw",inputs:[{name:"config",type:"tuple",components:j}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"pendingWithdrawals",inputs:[{name:"channelId",type:"bytes32"}],outputs:[{name:"amount",type:"uint128"},{name:"initiatedAt",type:"uint40"}],stateMutability:"view"},{type:"function",name:"channels",inputs:[{name:"channelId",type:"bytes32"}],outputs:[{name:"balance",type:"uint128"},{name:"totalClaimed",type:"uint128"}],stateMutability:"view"}];function lt(t){if(Array.isArray(t))return{balance:BigInt(t[0]),totalClaimed:BigInt(t[1])};let e=t;return{balance:BigInt(e.balance),totalClaimed:BigInt(e.totalClaimed)}}function M(t){if(Array.isArray(t))return{amount:BigInt(t[0]),initiatedAt:Number(t[1])};let e=t;return{amount:BigInt(e.amount),initiatedAt:Number(e.initiatedAt)}}async function q(t){let{config:e,network:n,client:a,withdrawDelaySecs:r}=t,i=(0,z.computeChannelId)(e,n),l=t.amountAtomic;l===void 0&&(l=lt(await a.readContract({address:g.BATCH_SETTLEMENT_ADDRESS,abi:R,functionName:"channels",args:[i]})).balance);let c=await a.writeContract({address:g.BATCH_SETTLEMENT_ADDRESS,abi:R,functionName:"initiateWithdraw",args:[e,l]});await a.waitForTransactionReceipt({hash:c});let d=M(await a.readContract({address:g.BATCH_SETTLEMENT_ADDRESS,abi:R,functionName:"pendingWithdrawals",args:[i]}));return{initiateTx:c,finalizableAt:L(d.initiatedAt,r)}}async function _(t){let{config:e,network:n,client:a,withdrawDelaySecs:r}=t,i=(0,z.computeChannelId)(e,n),l=M(await a.readContract({address:g.BATCH_SETTLEMENT_ADDRESS,abi:R,functionName:"pendingWithdrawals",args:[i]}));if(l.initiatedAt===0)throw new y(`no withdrawal is pending for channel ${i} \u2014 call forceWithdraw first`);let c=L(l.initiatedAt,r),d=Math.floor(Date.now()/1e3);if(d<c)throw new y(`withdrawal for channel ${i} is not finalizable until ${c} (unix seconds) \u2014 ${c-d}s remaining`);let o=await a.writeContract({address:g.BATCH_SETTLEMENT_ADDRESS,abi:R,functionName:"finalizeWithdraw",args:[e]});return await a.waitForTransactionReceipt({hash:o}),{finalizeTx:o,withdrawnAmount:(0,H.formatUnits)(l.amount,st)}}var J={"eip155:8453":{chain:C.base,defaultRpc:"https://mainnet.base.org"},"eip155:42161":{chain:C.arbitrum,defaultRpc:"https://arb1.arbitrum.io/rpc"},"eip155:137":{chain:C.polygon,defaultRpc:"https://polygon-rpc.com"}};function X(t){let e=J[t.network];if(!e)throw new f(`batch-settlement is not available on network "${t.network}" \u2014 supported: ${Object.keys(J).join(", ")}`);let n=t.rpcUrl??e.defaultRpc,a=t.wallet.signTypedData;if(typeof a!="function")throw new Error("batch-settlement requires an EvmWallet that supports signTypedData (EIP-712)");let r=(0,s.createWalletClient)({account:{address:t.wallet.address,type:"json-rpc"},chain:e.chain,transport:(0,s.http)(n)}).extend(s.publicActions),i=t.wallet.sendTransaction,l=typeof i=="function",c=async u=>{let b=u.to??void 0;if(!b)throw new Error("batch-settlement escape hatch: transaction is missing a `to` address");let m=u.data??"0x";if(typeof i=="function")return await i.call(t.wallet,{to:b,data:m,value:u.value});throw new Error("batch-settlement: wallet has no sendTransaction")},d=Object.assign(r,{address:t.wallet.address,signTypedData:u=>a.call(t.wallet,u),sendTransaction:c}),o=(0,V.toClientEvmSigner)(d),p=new v.BatchSettlementEvmScheme(o,{storage:t.store,depositPolicy:{depositMultiplier:4},depositStrategy:()=>t.depositAtomic,salt:t.salt}),h=new I.x402Client;h.register(t.network,p);let w=new I.x402HTTPClient(h);return{scheme:p,x402Cli:h,httpClient:w,rpcUrl:n,withdrawClient:d,canSubmitTransactions:l}}var A=6;function ct(t,e){let n=e>t?0n:t-e;return{deposited:(0,s.formatUnits)(t,A),spent:(0,s.formatUnits)(e,A),remaining:(0,s.formatUnits)(n,A)}}function dt(t){let e=t.payload;if(!e||typeof e!="object")return"";let n=e.voucher;if(!n||typeof n!="object")return"";let a=n.channelId;return typeof a=="string"?a:""}function ht(t){let e=t.payload;if(!e||typeof e!="object")return;let n=e.channelConfig;if(!(!n||typeof n!="object"))return n}function G(t){let{stack:e,store:n,network:a}=t,r="",i,l=t.depositedAtomic,c=0n;async function d(){if(!r)return;let o=await(0,v.getChannel)(n,r);o&&(o.chargedCumulativeAmount!==void 0&&(c=BigInt(o.chargedCumulativeAmount)),l===0n&&o.balance!==void 0&&(l=BigInt(o.balance)))}return{get channelId(){return r},get salt(){return t.salt},get network(){return a},get state(){return ct(l,c)},async fetch(o,p){let{httpClient:h}=e,w=await fetch(o,p);if(w.status!==402)return w;let F=h.getPaymentRequiredResponse(m=>w.headers.get(m),await w.clone().json().catch(()=>{})),u=2,b;for(let m=1;m<=u;m+=1){let S=await h.createPaymentPayload(F),D=dt(S);D&&(r=D);let U=ht(S);U&&(i=U);let Y=h.encodePaymentSignatureHeader(S),x=await fetch(o,{...p,headers:{...p?.headers??{},...Y}});b=x;let{recovered:Z}=await h.processPaymentResult(S,tt=>x.headers.get(tt),x.status);if(await d(),!(x.status===402&&Z&&m<u))return x}return b},async close(){return r&&await n.delete(r.toLowerCase()),{closed:!0}},async forceWithdraw(){if(!e.canSubmitTransactions)throw new Error("batch-settlement forceWithdraw requires a wallet with a sendTransaction method (the withdrawal escape hatch submits an on-chain transaction and the buyer pays gas; a signature-only wallet cannot use it).");if(!i)throw new Error("forceWithdraw is unavailable until the channel has resolved on-chain \u2014 make at least one fetch() against the channel first");return q({config:i,network:a,client:e.withdrawClient,withdrawDelaySecs:i.withdrawDelay})},async finalizeWithdraw(){if(!e.canSubmitTransactions)throw new Error("batch-settlement finalizeWithdraw requires a wallet with a sendTransaction method (the withdrawal escape hatch submits an on-chain transaction and the buyer pays gas; a signature-only wallet cannot use it).");if(!i)throw new Error("finalizeWithdraw is unavailable until the channel has resolved on-chain \u2014 make at least one fetch() against the channel first");return _({config:i,network:a,client:e.withdrawClient,withdrawDelaySecs:i.withdrawDelay})}}}function ut(){let t=new Uint8Array(32);return crypto.getRandomValues(t),(0,s.toHex)(t)}async function K(t){let e=t.store??W(),n=t.salt??ut(),a;try{a=(0,s.parseUnits)(t.deposit,A)}catch{throw new Error(`deposit must be a valid USDC amount in decimal units (e.g. "0.30"), got "${t.deposit}"`)}if(a<=0n)throw new Error(`deposit must be a positive amount, got "${t.deposit}"`);let r=X({wallet:t.wallet,network:t.network,rpcUrl:t.rpcUrl,store:e,depositAtomic:a.toString(),salt:n});return G({stack:r,store:e,network:t.network,depositedAtomic:a,salt:n})}async function Q(t){let e=t.store??W(),n=X({wallet:t.wallet,network:t.network,rpcUrl:t.rpcUrl,store:e,depositAtomic:"0",salt:t.salt});return G({stack:n,store:e,network:t.network,depositedAtomic:0n,salt:t.salt})}0&&(module.exports={InsufficientBalanceError,UnsupportedNetworkError,WithdrawNotReadyError,createFileChannelStore,createLocalStorageChannelStore,getDefaultChannelStore,openBatchChannel,resumeBatchChannel});
1
+ "use strict";var nt=Object.create;var k=Object.defineProperty;var at=Object.getOwnPropertyDescriptor;var rt=Object.getOwnPropertyNames;var it=Object.getPrototypeOf,ot=Object.prototype.hasOwnProperty;var st=(t,e)=>{for(var n in e)k(t,n,{get:e[n],enumerable:!0})},$=(t,e,n,a)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of rt(e))!ot.call(t,r)&&r!==n&&k(t,r,{get:()=>e[r],enumerable:!(a=at(e,r))||a.enumerable});return t};var lt=(t,e,n)=>(n=t!=null?nt(it(t)):{},$(e||!t||!t.__esModule?k(n,"default",{value:t,enumerable:!0}):n,t)),ct=t=>$(k({},"__esModule",{value:!0}),t);var ft={};st(ft,{InsufficientBalanceError:()=>A,UnsupportedNetworkError:()=>f,WithdrawNotReadyError:()=>y,createFileChannelStore:()=>P,createLocalStorageChannelStore:()=>B,getDefaultChannelStore:()=>W,openBatchChannel:()=>Q,resumeBatchChannel:()=>Y});module.exports=ct(ft);var s=require("viem"),C=require("viem/chains"),X=require("@x402/evm"),I=require("@x402/evm/batch-settlement/client"),T=require("@x402/core/client");var O=require("os"),N=require("path"),j=require("@x402/evm/batch-settlement/client");function P(t){return new j.FileClientChannelStorage({directory:t})}var E="dexter-x402-channel:";function B(t){return{async get(e){let n=t.getItem(E+e);return n?JSON.parse(n):void 0},async set(e,n){t.setItem(E+e,JSON.stringify(n))},async delete(e){t.removeItem(E+e)}}}function W(){let t=globalThis.localStorage;return t?B(t):P((0,N.join)((0,O.homedir)(),".dexter-x402","channels"))}var A=class extends Error{constructor(e){super(e),this.name="InsufficientBalanceError"}},f=class extends Error{constructor(e){super(e),this.name="UnsupportedNetworkError"}};var L=require("viem"),z=require("@x402/evm/batch-settlement/client"),g=require("@x402/evm"),y=class extends Error{constructor(e){super(e),this.name="WithdrawNotReadyError"}};function M(t,e){return t===0?0:t+e}var dt=6,H=[{name:"payer",type:"address"},{name:"payerAuthorizer",type:"address"},{name:"receiver",type:"address"},{name:"receiverAuthorizer",type:"address"},{name:"token",type:"address"},{name:"withdrawDelay",type:"uint40"},{name:"salt",type:"bytes32"}],R=[{type:"function",name:"initiateWithdraw",inputs:[{name:"config",type:"tuple",components:H},{name:"amount",type:"uint128"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"finalizeWithdraw",inputs:[{name:"config",type:"tuple",components:H}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"pendingWithdrawals",inputs:[{name:"channelId",type:"bytes32"}],outputs:[{name:"amount",type:"uint128"},{name:"initiatedAt",type:"uint40"}],stateMutability:"view"},{type:"function",name:"channels",inputs:[{name:"channelId",type:"bytes32"}],outputs:[{name:"balance",type:"uint128"},{name:"totalClaimed",type:"uint128"}],stateMutability:"view"}];function ht(t){if(Array.isArray(t))return{balance:BigInt(t[0]),totalClaimed:BigInt(t[1])};let e=t;return{balance:BigInt(e.balance),totalClaimed:BigInt(e.totalClaimed)}}function q(t){if(Array.isArray(t))return{amount:BigInt(t[0]),initiatedAt:Number(t[1])};let e=t;return{amount:BigInt(e.amount),initiatedAt:Number(e.initiatedAt)}}async function _(t){let{config:e,network:n,client:a,withdrawDelaySecs:r}=t,i=(0,z.computeChannelId)(e,n),l=t.amountAtomic;l===void 0&&(l=ht(await a.readContract({address:g.BATCH_SETTLEMENT_ADDRESS,abi:R,functionName:"channels",args:[i]})).balance);let c=await a.writeContract({address:g.BATCH_SETTLEMENT_ADDRESS,abi:R,functionName:"initiateWithdraw",args:[e,l]});await a.waitForTransactionReceipt({hash:c});let d=q(await a.readContract({address:g.BATCH_SETTLEMENT_ADDRESS,abi:R,functionName:"pendingWithdrawals",args:[i]}));return{initiateTx:c,finalizableAt:M(d.initiatedAt,r)}}async function J(t){let{config:e,network:n,client:a,withdrawDelaySecs:r}=t,i=(0,z.computeChannelId)(e,n),l=q(await a.readContract({address:g.BATCH_SETTLEMENT_ADDRESS,abi:R,functionName:"pendingWithdrawals",args:[i]}));if(l.initiatedAt===0)throw new y(`no withdrawal is pending for channel ${i} \u2014 call forceWithdraw first`);let c=M(l.initiatedAt,r),d=Math.floor(Date.now()/1e3);if(d<c)throw new y(`withdrawal for channel ${i} is not finalizable until ${c} (unix seconds) \u2014 ${c-d}s remaining`);let o=await a.writeContract({address:g.BATCH_SETTLEMENT_ADDRESS,abi:R,functionName:"finalizeWithdraw",args:[e]});return await a.waitForTransactionReceipt({hash:o}),{finalizeTx:o,withdrawnAmount:(0,L.formatUnits)(l.amount,dt)}}var V={"eip155:8453":{chain:C.base,defaultRpc:"https://mainnet.base.org"},"eip155:42161":{chain:C.arbitrum,defaultRpc:"https://arb1.arbitrum.io/rpc"},"eip155:137":{chain:C.polygon,defaultRpc:"https://polygon-rpc.com"}};function G(t){let e=V[t.network];if(!e)throw new f(`batch-settlement is not available on network "${t.network}" \u2014 supported: ${Object.keys(V).join(", ")}`);let n=t.rpcUrl??e.defaultRpc,a=t.wallet.signTypedData;if(typeof a!="function")throw new Error("batch-settlement requires an EvmWallet that supports signTypedData (EIP-712)");let r=(0,s.createWalletClient)({account:{address:t.wallet.address,type:"json-rpc"},chain:e.chain,transport:(0,s.http)(n)}).extend(s.publicActions),i=t.wallet.sendTransaction,l=typeof i=="function",c=async u=>{let b=u.to??void 0;if(!b)throw new Error("batch-settlement escape hatch: transaction is missing a `to` address");let m=u.data??"0x";if(typeof i=="function")return await i.call(t.wallet,{to:b,data:m,value:u.value});throw new Error("batch-settlement: wallet has no sendTransaction")},d=Object.assign(r,{address:t.wallet.address,signTypedData:u=>a.call(t.wallet,u),sendTransaction:c}),o=(0,X.toClientEvmSigner)(d),p=new I.BatchSettlementEvmScheme(o,{storage:t.store,depositPolicy:{depositMultiplier:4},depositStrategy:()=>t.depositAtomic,salt:t.salt}),h=new T.x402Client;h.register(t.network,p);let w=new T.x402HTTPClient(h);return{scheme:p,x402Cli:h,httpClient:w,rpcUrl:n,withdrawClient:d,canSubmitTransactions:l}}var v=6;function ut(t,e){let n=e>t?0n:t-e;return{deposited:(0,s.formatUnits)(t,v),spent:(0,s.formatUnits)(e,v),remaining:(0,s.formatUnits)(n,v)}}function mt(t){let e=t.payload;if(!e||typeof e!="object")return"";let n=e.voucher;if(!n||typeof n!="object")return"";let a=n.channelId;return typeof a=="string"?a:""}function pt(t){let e=t.payload;if(!e||typeof e!="object")return;let n=e.channelConfig;if(!(!n||typeof n!="object"))return n}function K(t){let{stack:e,store:n,network:a}=t,r="",i,l=t.depositedAtomic,c=0n;async function d(){if(!r)return;let o=await(0,I.getChannel)(n,r);o&&(o.chargedCumulativeAmount!==void 0&&(c=BigInt(o.chargedCumulativeAmount)),l===0n&&o.balance!==void 0&&(l=BigInt(o.balance)))}return{get channelId(){return r},get salt(){return t.salt},get network(){return a},get state(){return ut(l,c)},async fetch(o,p){let{httpClient:h}=e,w=await fetch(o,p);if(w.status!==402)return w;let F=h.getPaymentRequiredResponse(m=>w.headers.get(m),await w.clone().json().catch(()=>{})),u=2,b;for(let m=1;m<=u;m+=1){let S=await h.createPaymentPayload(F),D=mt(S);D&&(r=D);let U=pt(S);U&&(i=U);let Z=h.encodePaymentSignatureHeader(S),x=await fetch(o,{...p,headers:{...p?.headers??{},...Z}});b=x;let{recovered:tt}=await h.processPaymentResult(S,et=>x.headers.get(et),x.status);if(await d(),!(x.status===402&&tt&&m<u))return x}return b},async close(){return r&&await n.delete(r.toLowerCase()),{closed:!0}},async forceWithdraw(){if(!e.canSubmitTransactions)throw new Error("batch-settlement forceWithdraw requires a wallet with a sendTransaction method (the withdrawal escape hatch submits an on-chain transaction and the buyer pays gas; a signature-only wallet cannot use it).");if(!i)throw new Error("forceWithdraw is unavailable until the channel has resolved on-chain \u2014 make at least one fetch() against the channel first");return _({config:i,network:a,client:e.withdrawClient,withdrawDelaySecs:i.withdrawDelay})},async finalizeWithdraw(){if(!e.canSubmitTransactions)throw new Error("batch-settlement finalizeWithdraw requires a wallet with a sendTransaction method (the withdrawal escape hatch submits an on-chain transaction and the buyer pays gas; a signature-only wallet cannot use it).");if(!i)throw new Error("finalizeWithdraw is unavailable until the channel has resolved on-chain \u2014 make at least one fetch() against the channel first");return J({config:i,network:a,client:e.withdrawClient,withdrawDelaySecs:i.withdrawDelay})}}}async function wt(){let t=globalThis.crypto??(await import("crypto")).webcrypto,e=new Uint8Array(32);return t.getRandomValues(e),(0,s.toHex)(e)}async function Q(t){let e=t.store??W(),n=t.salt??await wt(),a;try{a=(0,s.parseUnits)(t.deposit,v)}catch{throw new Error(`deposit must be a valid USDC amount in decimal units (e.g. "0.30"), got "${t.deposit}"`)}if(a<=0n)throw new Error(`deposit must be a positive amount, got "${t.deposit}"`);let r=G({wallet:t.wallet,network:t.network,rpcUrl:t.rpcUrl,store:e,depositAtomic:a.toString(),salt:n});return K({stack:r,store:e,network:t.network,depositedAtomic:a,salt:n})}async function Y(t){let e=t.store??W(),n=G({wallet:t.wallet,network:t.network,rpcUrl:t.rpcUrl,store:e,depositAtomic:"0",salt:t.salt});return K({stack:n,store:e,network:t.network,depositedAtomic:0n,salt:t.salt})}0&&(module.exports={InsufficientBalanceError,UnsupportedNetworkError,WithdrawNotReadyError,createFileChannelStore,createLocalStorageChannelStore,getDefaultChannelStore,openBatchChannel,resumeBatchChannel});
@@ -1 +1 @@
1
- import{createWalletClient as K,http as Q,publicActions as Y,parseUnits as Z,formatUnits as A,toHex as tt}from"viem";import{base as et,arbitrum as nt,polygon as at}from"viem/chains";import{toClientEvmSigner as rt}from"@x402/evm";import{BatchSettlementEvmScheme as it,getChannel as ot}from"@x402/evm/batch-settlement/client";import{x402Client as st,x402HTTPClient as lt}from"@x402/core/client";import{homedir as q}from"os";import{join as _}from"path";import{FileClientChannelStorage as J}from"@x402/evm/batch-settlement/client";function E(t){return new J({directory:t})}var R="dexter-x402-channel:";function P(t){return{async get(e){let n=t.getItem(R+e);return n?JSON.parse(n):void 0},async set(e,n){t.setItem(R+e,JSON.stringify(n))},async delete(e){t.removeItem(R+e)}}}function x(){let t=globalThis.localStorage;return t?P(t):E(_(q(),".dexter-x402","channels"))}var k=class extends Error{constructor(e){super(e),this.name="InsufficientBalanceError"}},y=class extends Error{constructor(e){super(e),this.name="UnsupportedNetworkError"}};import{formatUnits as V}from"viem";import{computeChannelId as z}from"@x402/evm/batch-settlement/client";import{BATCH_SETTLEMENT_ADDRESS as C}from"@x402/evm";var S=class extends Error{constructor(e){super(e),this.name="WithdrawNotReadyError"}};function F(t,e){return t===0?0:t+e}var X=6,B=[{name:"payer",type:"address"},{name:"payerAuthorizer",type:"address"},{name:"receiver",type:"address"},{name:"receiverAuthorizer",type:"address"},{name:"token",type:"address"},{name:"withdrawDelay",type:"uint40"},{name:"salt",type:"bytes32"}],b=[{type:"function",name:"initiateWithdraw",inputs:[{name:"config",type:"tuple",components:B},{name:"amount",type:"uint128"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"finalizeWithdraw",inputs:[{name:"config",type:"tuple",components:B}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"pendingWithdrawals",inputs:[{name:"channelId",type:"bytes32"}],outputs:[{name:"amount",type:"uint128"},{name:"initiatedAt",type:"uint40"}],stateMutability:"view"},{type:"function",name:"channels",inputs:[{name:"channelId",type:"bytes32"}],outputs:[{name:"balance",type:"uint128"},{name:"totalClaimed",type:"uint128"}],stateMutability:"view"}];function G(t){if(Array.isArray(t))return{balance:BigInt(t[0]),totalClaimed:BigInt(t[1])};let e=t;return{balance:BigInt(e.balance),totalClaimed:BigInt(e.totalClaimed)}}function D(t){if(Array.isArray(t))return{amount:BigInt(t[0]),initiatedAt:Number(t[1])};let e=t;return{amount:BigInt(e.amount),initiatedAt:Number(e.initiatedAt)}}async function U(t){let{config:e,network:n,client:a,withdrawDelaySecs:i}=t,r=z(e,n),s=t.amountAtomic;s===void 0&&(s=G(await a.readContract({address:C,abi:b,functionName:"channels",args:[r]})).balance);let l=await a.writeContract({address:C,abi:b,functionName:"initiateWithdraw",args:[e,s]});await a.waitForTransactionReceipt({hash:l});let c=D(await a.readContract({address:C,abi:b,functionName:"pendingWithdrawals",args:[r]}));return{initiateTx:l,finalizableAt:F(c.initiatedAt,i)}}async function $(t){let{config:e,network:n,client:a,withdrawDelaySecs:i}=t,r=z(e,n),s=D(await a.readContract({address:C,abi:b,functionName:"pendingWithdrawals",args:[r]}));if(s.initiatedAt===0)throw new S(`no withdrawal is pending for channel ${r} \u2014 call forceWithdraw first`);let l=F(s.initiatedAt,i),c=Math.floor(Date.now()/1e3);if(c<l)throw new S(`withdrawal for channel ${r} is not finalizable until ${l} (unix seconds) \u2014 ${l-c}s remaining`);let o=await a.writeContract({address:C,abi:b,functionName:"finalizeWithdraw",args:[e]});return await a.waitForTransactionReceipt({hash:o}),{finalizeTx:o,withdrawnAmount:V(s.amount,X)}}var O={"eip155:8453":{chain:et,defaultRpc:"https://mainnet.base.org"},"eip155:42161":{chain:nt,defaultRpc:"https://arb1.arbitrum.io/rpc"},"eip155:137":{chain:at,defaultRpc:"https://polygon-rpc.com"}};function N(t){let e=O[t.network];if(!e)throw new y(`batch-settlement is not available on network "${t.network}" \u2014 supported: ${Object.keys(O).join(", ")}`);let n=t.rpcUrl??e.defaultRpc,a=t.wallet.signTypedData;if(typeof a!="function")throw new Error("batch-settlement requires an EvmWallet that supports signTypedData (EIP-712)");let i=K({account:{address:t.wallet.address,type:"json-rpc"},chain:e.chain,transport:Q(n)}).extend(Y),r=t.wallet.sendTransaction,s=typeof r=="function",l=async h=>{let w=h.to??void 0;if(!w)throw new Error("batch-settlement escape hatch: transaction is missing a `to` address");let u=h.data??"0x";if(typeof r=="function")return await r.call(t.wallet,{to:w,data:u,value:h.value});throw new Error("batch-settlement: wallet has no sendTransaction")},c=Object.assign(i,{address:t.wallet.address,signTypedData:h=>a.call(t.wallet,h),sendTransaction:l}),o=rt(c),m=new it(o,{storage:t.store,depositPolicy:{depositMultiplier:4},depositStrategy:()=>t.depositAtomic,salt:t.salt}),d=new st;d.register(t.network,m);let p=new lt(d);return{scheme:m,x402Cli:d,httpClient:p,rpcUrl:n,withdrawClient:c,canSubmitTransactions:s}}var W=6;function ct(t,e){let n=e>t?0n:t-e;return{deposited:A(t,W),spent:A(e,W),remaining:A(n,W)}}function dt(t){let e=t.payload;if(!e||typeof e!="object")return"";let n=e.voucher;if(!n||typeof n!="object")return"";let a=n.channelId;return typeof a=="string"?a:""}function ht(t){let e=t.payload;if(!e||typeof e!="object")return;let n=e.channelConfig;if(!(!n||typeof n!="object"))return n}function j(t){let{stack:e,store:n,network:a}=t,i="",r,s=t.depositedAtomic,l=0n;async function c(){if(!i)return;let o=await ot(n,i);o&&(o.chargedCumulativeAmount!==void 0&&(l=BigInt(o.chargedCumulativeAmount)),s===0n&&o.balance!==void 0&&(s=BigInt(o.balance)))}return{get channelId(){return i},get salt(){return t.salt},get network(){return a},get state(){return ct(s,l)},async fetch(o,m){let{httpClient:d}=e,p=await fetch(o,m);if(p.status!==402)return p;let v=d.getPaymentRequiredResponse(u=>p.headers.get(u),await p.clone().json().catch(()=>{})),h=2,w;for(let u=1;u<=h;u+=1){let f=await d.createPaymentPayload(v),I=dt(f);I&&(i=I);let T=ht(f);T&&(r=T);let H=d.encodePaymentSignatureHeader(f),g=await fetch(o,{...m,headers:{...m?.headers??{},...H}});w=g;let{recovered:L}=await d.processPaymentResult(f,M=>g.headers.get(M),g.status);if(await c(),!(g.status===402&&L&&u<h))return g}return w},async close(){return i&&await n.delete(i.toLowerCase()),{closed:!0}},async forceWithdraw(){if(!e.canSubmitTransactions)throw new Error("batch-settlement forceWithdraw requires a wallet with a sendTransaction method (the withdrawal escape hatch submits an on-chain transaction and the buyer pays gas; a signature-only wallet cannot use it).");if(!r)throw new Error("forceWithdraw is unavailable until the channel has resolved on-chain \u2014 make at least one fetch() against the channel first");return U({config:r,network:a,client:e.withdrawClient,withdrawDelaySecs:r.withdrawDelay})},async finalizeWithdraw(){if(!e.canSubmitTransactions)throw new Error("batch-settlement finalizeWithdraw requires a wallet with a sendTransaction method (the withdrawal escape hatch submits an on-chain transaction and the buyer pays gas; a signature-only wallet cannot use it).");if(!r)throw new Error("finalizeWithdraw is unavailable until the channel has resolved on-chain \u2014 make at least one fetch() against the channel first");return $({config:r,network:a,client:e.withdrawClient,withdrawDelaySecs:r.withdrawDelay})}}}function ut(){let t=new Uint8Array(32);return crypto.getRandomValues(t),tt(t)}async function mt(t){let e=t.store??x(),n=t.salt??ut(),a;try{a=Z(t.deposit,W)}catch{throw new Error(`deposit must be a valid USDC amount in decimal units (e.g. "0.30"), got "${t.deposit}"`)}if(a<=0n)throw new Error(`deposit must be a positive amount, got "${t.deposit}"`);let i=N({wallet:t.wallet,network:t.network,rpcUrl:t.rpcUrl,store:e,depositAtomic:a.toString(),salt:n});return j({stack:i,store:e,network:t.network,depositedAtomic:a,salt:n})}async function pt(t){let e=t.store??x(),n=N({wallet:t.wallet,network:t.network,rpcUrl:t.rpcUrl,store:e,depositAtomic:"0",salt:t.salt});return j({stack:n,store:e,network:t.network,depositedAtomic:0n,salt:t.salt})}export{k as InsufficientBalanceError,y as UnsupportedNetworkError,S as WithdrawNotReadyError,E as createFileChannelStore,P as createLocalStorageChannelStore,x as getDefaultChannelStore,mt as openBatchChannel,pt as resumeBatchChannel};
1
+ import{createWalletClient as K,http as Q,publicActions as Y,parseUnits as Z,formatUnits as A,toHex as tt}from"viem";import{base as et,arbitrum as nt,polygon as at}from"viem/chains";import{toClientEvmSigner as rt}from"@x402/evm";import{BatchSettlementEvmScheme as it,getChannel as ot}from"@x402/evm/batch-settlement/client";import{x402Client as st,x402HTTPClient as lt}from"@x402/core/client";import{homedir as q}from"os";import{join as _}from"path";import{FileClientChannelStorage as J}from"@x402/evm/batch-settlement/client";function E(t){return new J({directory:t})}var R="dexter-x402-channel:";function P(t){return{async get(e){let n=t.getItem(R+e);return n?JSON.parse(n):void 0},async set(e,n){t.setItem(R+e,JSON.stringify(n))},async delete(e){t.removeItem(R+e)}}}function x(){let t=globalThis.localStorage;return t?P(t):E(_(q(),".dexter-x402","channels"))}var k=class extends Error{constructor(e){super(e),this.name="InsufficientBalanceError"}},y=class extends Error{constructor(e){super(e),this.name="UnsupportedNetworkError"}};import{formatUnits as V}from"viem";import{computeChannelId as z}from"@x402/evm/batch-settlement/client";import{BATCH_SETTLEMENT_ADDRESS as C}from"@x402/evm";var S=class extends Error{constructor(e){super(e),this.name="WithdrawNotReadyError"}};function F(t,e){return t===0?0:t+e}var X=6,B=[{name:"payer",type:"address"},{name:"payerAuthorizer",type:"address"},{name:"receiver",type:"address"},{name:"receiverAuthorizer",type:"address"},{name:"token",type:"address"},{name:"withdrawDelay",type:"uint40"},{name:"salt",type:"bytes32"}],b=[{type:"function",name:"initiateWithdraw",inputs:[{name:"config",type:"tuple",components:B},{name:"amount",type:"uint128"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"finalizeWithdraw",inputs:[{name:"config",type:"tuple",components:B}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"pendingWithdrawals",inputs:[{name:"channelId",type:"bytes32"}],outputs:[{name:"amount",type:"uint128"},{name:"initiatedAt",type:"uint40"}],stateMutability:"view"},{type:"function",name:"channels",inputs:[{name:"channelId",type:"bytes32"}],outputs:[{name:"balance",type:"uint128"},{name:"totalClaimed",type:"uint128"}],stateMutability:"view"}];function G(t){if(Array.isArray(t))return{balance:BigInt(t[0]),totalClaimed:BigInt(t[1])};let e=t;return{balance:BigInt(e.balance),totalClaimed:BigInt(e.totalClaimed)}}function D(t){if(Array.isArray(t))return{amount:BigInt(t[0]),initiatedAt:Number(t[1])};let e=t;return{amount:BigInt(e.amount),initiatedAt:Number(e.initiatedAt)}}async function U(t){let{config:e,network:n,client:a,withdrawDelaySecs:i}=t,r=z(e,n),s=t.amountAtomic;s===void 0&&(s=G(await a.readContract({address:C,abi:b,functionName:"channels",args:[r]})).balance);let l=await a.writeContract({address:C,abi:b,functionName:"initiateWithdraw",args:[e,s]});await a.waitForTransactionReceipt({hash:l});let c=D(await a.readContract({address:C,abi:b,functionName:"pendingWithdrawals",args:[r]}));return{initiateTx:l,finalizableAt:F(c.initiatedAt,i)}}async function $(t){let{config:e,network:n,client:a,withdrawDelaySecs:i}=t,r=z(e,n),s=D(await a.readContract({address:C,abi:b,functionName:"pendingWithdrawals",args:[r]}));if(s.initiatedAt===0)throw new S(`no withdrawal is pending for channel ${r} \u2014 call forceWithdraw first`);let l=F(s.initiatedAt,i),c=Math.floor(Date.now()/1e3);if(c<l)throw new S(`withdrawal for channel ${r} is not finalizable until ${l} (unix seconds) \u2014 ${l-c}s remaining`);let o=await a.writeContract({address:C,abi:b,functionName:"finalizeWithdraw",args:[e]});return await a.waitForTransactionReceipt({hash:o}),{finalizeTx:o,withdrawnAmount:V(s.amount,X)}}var O={"eip155:8453":{chain:et,defaultRpc:"https://mainnet.base.org"},"eip155:42161":{chain:nt,defaultRpc:"https://arb1.arbitrum.io/rpc"},"eip155:137":{chain:at,defaultRpc:"https://polygon-rpc.com"}};function N(t){let e=O[t.network];if(!e)throw new y(`batch-settlement is not available on network "${t.network}" \u2014 supported: ${Object.keys(O).join(", ")}`);let n=t.rpcUrl??e.defaultRpc,a=t.wallet.signTypedData;if(typeof a!="function")throw new Error("batch-settlement requires an EvmWallet that supports signTypedData (EIP-712)");let i=K({account:{address:t.wallet.address,type:"json-rpc"},chain:e.chain,transport:Q(n)}).extend(Y),r=t.wallet.sendTransaction,s=typeof r=="function",l=async h=>{let w=h.to??void 0;if(!w)throw new Error("batch-settlement escape hatch: transaction is missing a `to` address");let u=h.data??"0x";if(typeof r=="function")return await r.call(t.wallet,{to:w,data:u,value:h.value});throw new Error("batch-settlement: wallet has no sendTransaction")},c=Object.assign(i,{address:t.wallet.address,signTypedData:h=>a.call(t.wallet,h),sendTransaction:l}),o=rt(c),m=new it(o,{storage:t.store,depositPolicy:{depositMultiplier:4},depositStrategy:()=>t.depositAtomic,salt:t.salt}),d=new st;d.register(t.network,m);let p=new lt(d);return{scheme:m,x402Cli:d,httpClient:p,rpcUrl:n,withdrawClient:c,canSubmitTransactions:s}}var W=6;function ct(t,e){let n=e>t?0n:t-e;return{deposited:A(t,W),spent:A(e,W),remaining:A(n,W)}}function dt(t){let e=t.payload;if(!e||typeof e!="object")return"";let n=e.voucher;if(!n||typeof n!="object")return"";let a=n.channelId;return typeof a=="string"?a:""}function ht(t){let e=t.payload;if(!e||typeof e!="object")return;let n=e.channelConfig;if(!(!n||typeof n!="object"))return n}function j(t){let{stack:e,store:n,network:a}=t,i="",r,s=t.depositedAtomic,l=0n;async function c(){if(!i)return;let o=await ot(n,i);o&&(o.chargedCumulativeAmount!==void 0&&(l=BigInt(o.chargedCumulativeAmount)),s===0n&&o.balance!==void 0&&(s=BigInt(o.balance)))}return{get channelId(){return i},get salt(){return t.salt},get network(){return a},get state(){return ct(s,l)},async fetch(o,m){let{httpClient:d}=e,p=await fetch(o,m);if(p.status!==402)return p;let v=d.getPaymentRequiredResponse(u=>p.headers.get(u),await p.clone().json().catch(()=>{})),h=2,w;for(let u=1;u<=h;u+=1){let f=await d.createPaymentPayload(v),I=dt(f);I&&(i=I);let T=ht(f);T&&(r=T);let H=d.encodePaymentSignatureHeader(f),g=await fetch(o,{...m,headers:{...m?.headers??{},...H}});w=g;let{recovered:L}=await d.processPaymentResult(f,M=>g.headers.get(M),g.status);if(await c(),!(g.status===402&&L&&u<h))return g}return w},async close(){return i&&await n.delete(i.toLowerCase()),{closed:!0}},async forceWithdraw(){if(!e.canSubmitTransactions)throw new Error("batch-settlement forceWithdraw requires a wallet with a sendTransaction method (the withdrawal escape hatch submits an on-chain transaction and the buyer pays gas; a signature-only wallet cannot use it).");if(!r)throw new Error("forceWithdraw is unavailable until the channel has resolved on-chain \u2014 make at least one fetch() against the channel first");return U({config:r,network:a,client:e.withdrawClient,withdrawDelaySecs:r.withdrawDelay})},async finalizeWithdraw(){if(!e.canSubmitTransactions)throw new Error("batch-settlement finalizeWithdraw requires a wallet with a sendTransaction method (the withdrawal escape hatch submits an on-chain transaction and the buyer pays gas; a signature-only wallet cannot use it).");if(!r)throw new Error("finalizeWithdraw is unavailable until the channel has resolved on-chain \u2014 make at least one fetch() against the channel first");return $({config:r,network:a,client:e.withdrawClient,withdrawDelaySecs:r.withdrawDelay})}}}async function ut(){let t=globalThis.crypto??(await import("crypto")).webcrypto,e=new Uint8Array(32);return t.getRandomValues(e),tt(e)}async function mt(t){let e=t.store??x(),n=t.salt??await ut(),a;try{a=Z(t.deposit,W)}catch{throw new Error(`deposit must be a valid USDC amount in decimal units (e.g. "0.30"), got "${t.deposit}"`)}if(a<=0n)throw new Error(`deposit must be a positive amount, got "${t.deposit}"`);let i=N({wallet:t.wallet,network:t.network,rpcUrl:t.rpcUrl,store:e,depositAtomic:a.toString(),salt:n});return j({stack:i,store:e,network:t.network,depositedAtomic:a,salt:n})}async function pt(t){let e=t.store??x(),n=N({wallet:t.wallet,network:t.network,rpcUrl:t.rpcUrl,store:e,depositAtomic:"0",salt:t.salt});return j({stack:n,store:e,network:t.network,depositedAtomic:0n,salt:t.salt})}export{k as InsufficientBalanceError,y as UnsupportedNetworkError,S as WithdrawNotReadyError,E as createFileChannelStore,P as createLocalStorageChannelStore,x as getDefaultChannelStore,mt as openBatchChannel,pt as resumeBatchChannel};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dexterai/x402",
3
- "version": "3.7.1",
3
+ "version": "3.7.3",
4
4
  "description": "Full-stack x402 SDK - add paid API monetization to any endpoint. Express middleware, React hooks, Access Pass, dynamic pricing. Solana, Base, Polygon, Arbitrum, Optimism, Avalanche, SKALE.",
5
5
  "author": "Dexter",
6
6
  "license": "MIT",