@walletconnect/pos-client 2.23.1-canary-init.0 → 2.23.1-canary-init.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.
package/dist/index.cjs CHANGED
@@ -1,2 +1,1221 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var ee=require("@walletconnect/sign-client"),b=require("@walletconnect/jsonrpc-utils"),y=require("@walletconnect/utils"),te=require("@walletconnect/logger"),_={exports:{}},v=typeof Reflect=="object"?Reflect:null,R=v&&typeof v.apply=="function"?v.apply:function(t,n,e){return Function.prototype.apply.call(t,n,e)},I;v&&typeof v.ownKeys=="function"?I=v.ownKeys:Object.getOwnPropertySymbols?I=function(t){return Object.getOwnPropertyNames(t).concat(Object.getOwnPropertySymbols(t))}:I=function(t){return Object.getOwnPropertyNames(t)};function ne(i){console&&console.warn&&console.warn(i)}var k=Number.isNaN||function(t){return t!==t};function h(){h.init.call(this)}_.exports=h,_.exports.once=oe,h.EventEmitter=h,h.prototype._events=void 0,h.prototype._eventsCount=0,h.prototype._maxListeners=void 0;var A=10;function E(i){if(typeof i!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof i)}Object.defineProperty(h,"defaultMaxListeners",{enumerable:!0,get:function(){return A},set:function(i){if(typeof i!="number"||i<0||k(i))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+i+".");A=i}}),h.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},h.prototype.setMaxListeners=function(t){if(typeof t!="number"||t<0||k(t))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+t+".");return this._maxListeners=t,this};function j(i){return i._maxListeners===void 0?h.defaultMaxListeners:i._maxListeners}h.prototype.getMaxListeners=function(){return j(this)},h.prototype.emit=function(t){for(var n=[],e=1;e<arguments.length;e++)n.push(arguments[e]);var s=t==="error",r=this._events;if(r!==void 0)s=s&&r.error===void 0;else if(!s)return!1;if(s){var o;if(n.length>0&&(o=n[0]),o instanceof Error)throw o;var a=new Error("Unhandled error."+(o?" ("+o.message+")":""));throw a.context=o,a}var l=r[t];if(l===void 0)return!1;if(typeof l=="function")R(l,this,n);else for(var c=l.length,p=U(l,c),e=0;e<c;++e)R(p[e],this,n);return!0};function x(i,t,n,e){var s,r,o;if(E(n),r=i._events,r===void 0?(r=i._events=Object.create(null),i._eventsCount=0):(r.newListener!==void 0&&(i.emit("newListener",t,n.listener?n.listener:n),r=i._events),o=r[t]),o===void 0)o=r[t]=n,++i._eventsCount;else if(typeof o=="function"?o=r[t]=e?[n,o]:[o,n]:e?o.unshift(n):o.push(n),s=j(i),s>0&&o.length>s&&!o.warned){o.warned=!0;var a=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");a.name="MaxListenersExceededWarning",a.emitter=i,a.type=t,a.count=o.length,ne(a)}return i}h.prototype.addListener=function(t,n){return x(this,t,n,!1)},h.prototype.on=h.prototype.addListener,h.prototype.prependListener=function(t,n){return x(this,t,n,!0)};function se(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function F(i,t,n){var e={fired:!1,wrapFn:void 0,target:i,type:t,listener:n},s=se.bind(e);return s.listener=n,e.wrapFn=s,s}h.prototype.once=function(t,n){return E(n),this.on(t,F(this,t,n)),this},h.prototype.prependOnceListener=function(t,n){return E(n),this.prependListener(t,F(this,t,n)),this},h.prototype.removeListener=function(t,n){var e,s,r,o,a;if(E(n),s=this._events,s===void 0)return this;if(e=s[t],e===void 0)return this;if(e===n||e.listener===n)--this._eventsCount===0?this._events=Object.create(null):(delete s[t],s.removeListener&&this.emit("removeListener",t,e.listener||n));else if(typeof e!="function"){for(r=-1,o=e.length-1;o>=0;o--)if(e[o]===n||e[o].listener===n){a=e[o].listener,r=o;break}if(r<0)return this;r===0?e.shift():ie(e,r),e.length===1&&(s[t]=e[0]),s.removeListener!==void 0&&this.emit("removeListener",t,a||n)}return this},h.prototype.off=h.prototype.removeListener,h.prototype.removeAllListeners=function(t){var n,e,s;if(e=this._events,e===void 0)return this;if(e.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):e[t]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete e[t]),this;if(arguments.length===0){var r=Object.keys(e),o;for(s=0;s<r.length;++s)o=r[s],o!=="removeListener"&&this.removeAllListeners(o);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(n=e[t],typeof n=="function")this.removeListener(t,n);else if(n!==void 0)for(s=n.length-1;s>=0;s--)this.removeListener(t,n[s]);return this};function $(i,t,n){var e=i._events;if(e===void 0)return[];var s=e[t];return s===void 0?[]:typeof s=="function"?n?[s.listener||s]:[s]:n?re(s):U(s,s.length)}h.prototype.listeners=function(t){return $(this,t,!0)},h.prototype.rawListeners=function(t){return $(this,t,!1)},h.listenerCount=function(i,t){return typeof i.listenerCount=="function"?i.listenerCount(t):q.call(i,t)},h.prototype.listenerCount=q;function q(i){var t=this._events;if(t!==void 0){var n=t[i];if(typeof n=="function")return 1;if(n!==void 0)return n.length}return 0}h.prototype.eventNames=function(){return this._eventsCount>0?I(this._events):[]};function U(i,t){for(var n=new Array(t),e=0;e<t;++e)n[e]=i[e];return n}function ie(i,t){for(;t+1<i.length;t++)i[t]=i[t+1];i.pop()}function re(i){for(var t=new Array(i.length),n=0;n<t.length;++n)t[n]=i[n].listener||i[n];return t}function oe(i,t){return new Promise(function(n,e){function s(o){i.removeListener(t,r),e(o)}function r(){typeof i.removeListener=="function"&&i.removeListener("error",s),n([].slice.call(arguments))}W(i,t,r,{once:!0}),t!=="error"&&ae(i,s,{once:!0})})}function ae(i,t,n){typeof i.on=="function"&&W(i,"error",t,n)}function W(i,t,n,e){if(typeof i.on=="function")e.once?i.once(t,n):i.on(t,n);else if(typeof i.addEventListener=="function")i.addEventListener(t,function s(r){e.once&&i.removeEventListener(t,s),n(r)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof i)}const M="wc",ce=2,L="POSClient",V=`${M}@2:${L}:`,O={database:":memory:",customStoragePrefix:"@walletconnect/pos-client"},D="1.0.0",G=10,T="error",K=[{assetNamespaces:["erc20","slip44"],capabilities:null,events:[],methods:["eth_sendTransaction"],name:"eip155"},{assetNamespaces:["token","slip44"],capabilities:null,events:[],methods:["solana_signAndSendTransaction"],name:"solana"},{assetNamespaces:["trc20","slip44"],capabilities:null,events:[],methods:["tron_signTransaction"],name:"tron"}],J=({projectId:i})=>`https://rpc.walletconnect.org/v1/json-rpc?projectId=${i}&st=node&sv=js-pos-${D}`,P={"-18901":"ValidationError.InvalidAsset","-18902":"ValidationError.InvalidRecipient","-18903":"ValidationError.InvalidSender","-18904":"ValidationError.InvalidAmount","-18905":"ValidationError.InvalidAddress","-18906":"ValidationError.InvalidWalletResponse","-18907":"ValidationError.InvalidTransactionId","-18920":"ExecutionError.GasEstimation","-18940":"InternalError.InvalidProviderUrl","-18941":"InternalError.RpcError","-18942":"InternalError.Internal","-18970":"TransactionIdError.InvalidFormat","-18971":"TransactionIdError.InvalidChainId"};class X{constructor(t){this.opts=t}}class H{constructor(t){this.client=t}}const z=i=>{const{supportedNamespaces:t,token:n}=i,{network:e,symbol:s,standard:r,address:o}=n;if(!e||!s||!r||!o||!y.isValidChainId(e?.chainId))return!1;const{namespace:a}=y.parseChainId(e.chainId),l=t.find(c=>c.name.toLowerCase()===a.toLowerCase());if(!l)throw new Error(`Unsupported token namespace: ${a}`);if(!l.assetNamespaces.map(c=>c.toLowerCase()).includes(r?.toLowerCase()))throw new Error(`Unsupported token standard: ${r} for namespace: ${a}`);return!0},le=i=>{const{supportedNamespaces:t,paymentIntent:n}=i,{token:e,amount:s,recipient:r}=n;return!(!e||!s||!r||!z({supportedNamespaces:t,token:e}))};var de=Object.defineProperty,he=(i,t,n)=>t in i?de(i,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):i[t]=n,d=(i,t,n)=>he(i,typeof t!="symbol"?t+"":t,n);class pe extends H{constructor(t){var n;super(t),d(this,"signClient"),d(this,"logger"),d(this,"tokens",[]),d(this,"supportedNamespaces",K),d(this,"paymentIntents"),d(this,"transactions"),d(this,"paymentsSendingInProgress",!1),d(this,"manualControl",!1),d(this,"init",async()=>{var e,s;this.setupEventHandlers(),this.signClient=await ee.SignClient.init({projectId:this.client.opts.projectId,metadata:{name:this.client.metadata.merchantName,description:this.client.metadata.description,url:this.client.metadata.url,icons:[this.client.metadata.logoIcon]},storageOptions:{database:((e=this.client.opts.storageOptions)==null?void 0:e.databaseName)||O.database},customStoragePrefix:O.customStoragePrefix,logger:((s=this.client.opts.loggerOptions)==null?void 0:s.signLevel)||T}),this.fetchSupportedNamespacesInBackground()}),d(this,"setTokens",async e=>{const{tokens:s}=e;this.logger.debug({tokens:s},"Setting tokens"),s.forEach(r=>{if(!z({token:r,supportedNamespaces:this.supportedNamespaces}))throw new Error(`Invalid token: ${JSON.stringify(r)}`)}),await new Promise(r=>{this.tokens=s,r()}),this.logger.debug({tokens:s},"Tokens set")}),d(this,"createPaymentIntent",async e=>{const{paymentIntents:s,manualControl:r}=e;if(this.logger.debug({paymentIntents:s},"Creating payment intent"),s.length===0)throw new Error("No payment intents provided");this.manualControl=r||!1;for(const c of s)if(!le({paymentIntent:c,supportedNamespaces:this.supportedNamespaces}))throw new Error(`Invalid payment intent: ${JSON.stringify(c)}`);if(this.logger.debug({paymentIntents:s},"Payment intent validation success"),this.paymentIntents=s,this.logger.debug({paymentIntents:s},"Payment intents set"),this.client.session)try{this.validateApprovedNamespacesWithPaymentIntents(),this.manualControl||await this.sendPaymentsToWallet();return}catch(c){this.logger.error(c),await this.disconnect()}const o=this.composeNamespaces(s),{uri:a,approval:l}=await this.signClient.connect({optionalNamespaces:o});if(this.logger.debug({uri:a},"Connected to the WalletConnect network"),!a)throw this.client.events.emit("connection_failed",{error:{message:"Failed to connect to the WalletConnect network",code:4001}}),new Error("Failed to connect to the WalletConnect network");if(this.emit("await_approval",{approval:l}),this.logger.debug("Emitted await_approval event"),this.emit("qr_ready",{uri:a}),this.logger.debug({uri:a},"Emitted qr_ready event"),this.manualControl){const c=await l();await this.onSessionConnected({session:c})}}),d(this,"restart",async e=>{this.logger.debug({params:e},"Restarting");const s=this.manualControl;if(e!=null&&e.reinit){this.tokens=[],this.cleanup(),await this.disconnect(),this.logger.debug("Restarted: Cleared payment intents, transactions and disconnected");return}const r=this.paymentIntents;if(!r)throw new Error("No payment intents found");await this.createPaymentIntent({paymentIntents:r,manualControl:s}),this.logger.debug({paymentIntents:r},"Restarted: Created payment intent flow from the beginning")}),d(this,"emit",(e,s)=>(this.logger.debug({event:e,args:s},"Emit"),this.client.events.emit(e,s))),d(this,"on",(e,s)=>(this.logger.debug({event:e,listener:s},"On"),this.client.events.on(e,s))),d(this,"once",(e,s)=>(this.logger.debug({event:e,listener:s},"Once"),this.client.events.once(e,s))),d(this,"off",(e,s)=>(this.logger.debug({event:e,listener:s},"Off"),this.client.events.off(e,s))),d(this,"removeListener",(e,s)=>(this.logger.debug({event:e,listener:s},"Remove listener"),this.client.events.removeListener(e,s))),d(this,"prepareTransactionsFromPaymentIntents",async()=>{var e,s,r,o,a,l;const c=this.paymentIntents;if(!c)throw new Error("No payment intents found");const p=this.client.session;if(!p)throw new Error("No session found");this.logger.debug({sessionTopic:p.topic},"Preparing transactions from payment intents");const u=[];for(const B of c){const{token:m,amount:Q,recipient:Y}=B,{namespace:N}=y.parseChainId(m.network.chainId),S=(r=(s=(e=p.namespaces)==null?void 0:e[N])==null?void 0:s.accounts)==null?void 0:r.find(Z=>Z.includes(`${m.network.chainId}:`));if(!S)throw new Error(`Address not found in session for chain id: ${m.network.chainId}, approved addresses: ${(l=(a=(o=p.namespaces)==null?void 0:o[N])==null?void 0:a.accounts)==null?void 0:l.join(", ")}`);u.push({asset:`${m.network.chainId}/${m.standard.toLowerCase()}:${m.address}`,recipient:Y,amount:Q,sender:S})}this.logger.debug({sessionTopic:p.topic,transactions:u},"Prepared transactions from payment intents");const f={id:b.payloadId(),jsonrpc:"2.0",method:"wc_pos_buildTransactions",params:{paymentIntents:u}};this.logger.debug({payload:f},"Fetching wc_pos_buildTransactions");const w=await this.fetchRpcRequest(JSON.stringify(f));this.logger.debug({response:w},"Received wc_pos_buildTransactions"),this.transactions=w.result.transactions,this.logger.debug({transactions:this.transactions},"Payment intent to transactions map set")}),d(this,"sendPaymentsToWallet",async()=>{if(this.paymentsSendingInProgress)throw new Error("Payments are already being sent, please wait for them to complete");this.paymentsSendingInProgress=!0;try{await this.prepareTransactionsFromPaymentIntents(),this.sendTransactionsToWallet()}catch(e){this.logger.error(e,"Error while sending payments to wallet")}this.paymentsSendingInProgress=!1}),d(this,"sendTransactionsToWallet",async()=>{var e;const s=this.transactions,r=this.paymentIntents;if(!s||!r)throw new Error("No transactions or payment intents to send, call createPaymentIntent() first");const o=this.client.session;if(!o)throw new Error("No session found");this.logger.debug({transactions:s,sessionTopic:(e=this.client.session)==null?void 0:e.topic},"Sending transactions to wallet");for(let a=0;a<s.length;a++){const l=s[a],c=r[a];try{this.emit("payment_requested",{paymentIntent:c,transaction:l}),this.logger.debug({transactionId:l.id},"Emitted payment_requested event");let p;try{p=await this.signClient.request({topic:o.topic,request:{method:l.method,params:l.params},chainId:l.chainId}),this.logger.debug({transactionId:l.id,result:p},"Wallet responded to payment request")}catch(u){throw this.logger.error(u,"Error while sending payment request"),this.emit("payment_rejected",{error:{message:u?.message,code:4001},paymentIntent:c}),u}this.emit("payment_broadcasted",{paymentIntent:c,transaction:l,result:p}),this.logger.debug({transactionId:l.id},"Emitted payment_broadcasted event"),await this.awaitPaymentConfirmed({transaction:l,result:p}),await new Promise(u=>setTimeout(u,1e3))}catch(p){this.logger.error(p,"Error while awaiting payment confirmed")}}this.cleanup(),this.manualControl||await this.disconnect()}),d(this,"awaitPaymentConfirmed",async e=>{try{const{transaction:s,result:r}=e;this.logger.debug({transactionId:s.id,result:r},"Awaiting payment confirmed");const o={id:b.payloadId(),jsonrpc:"2.0",method:"wc_pos_checkTransaction",params:{id:s.id,sendResult:typeof r=="string"?r:JSON.stringify(r)}};let a=0,l;for(;!l;){if(a>=G)throw new Error(`Transaction status not found for id: ${s.id}`);a++;const c=await this.fetchRpcRequest(JSON.stringify(o));if(this.logger.debug({transactionId:s.id,response:c},"Received wc_pos_checkTransaction"),c.result.status==="CONFIRMED"){this.logger.debug({response:c},"Transaction status confirmed"),this.emit("payment_successful",{transaction:s,result:r}),l=c.result;break}else if(c.result.status==="FAILED"){this.logger.debug({response:c},"Transaction failed"),this.emit("payment_failed",{error:{message:c.result.error,code:4001},transaction:r}),l=c.result;break}else c.result.status==="PENDING"&&(this.logger.debug({response:c},"Transaction pending"),await new Promise(p=>setTimeout(p,c.result.checkIn||1e3)))}}catch(s){this.logger.error(s,"Error while awaiting payment confirmations")}}),d(this,"setupEventHandlers",()=>{this.on("await_approval",async({approval:e})=>{try{this.logger.debug("On await_approval");const s=await e();await this.onSessionConnected({session:s})}catch(s){this.logger.error(s,"Error while awaiting approval"),this.emit("connection_rejected",{error:{message:s?.message,code:4001}})}})}),d(this,"onSessionConnected",async e=>{const{session:s}=e;this.logger.debug({sessionTopic:s.topic},"On session connected"),await this.signClient.session.update(s.topic,{sessionConfig:{disableDeepLink:!0}}),this.logger.debug({sessionTopic:s.topic},"Disabled deep links for session"),this.client.session=this.signClient.session.get(s.topic),await this.persistSessionTopic(s.topic),this.emit("connected",{session:s}),this.logger.debug("Emitted connected event"),this.manualControl||await this.sendPaymentsToWallet()}),d(this,"disconnect",async()=>{this.client.session&&(await this.clearPersistedSessionTopic(),await this.signClient.disconnect({topic:this.client.session.topic,reason:{code:4001,message:"User disconnected"}})),this.manualControl=!1,this.client.session=void 0}),d(this,"fetchRpcRequest",async e=>{var s,r,o,a,l;this.logger.debug({url:this.getRpcUrl(),payload:e},"Fetching RPC request");const c=await fetch(this.getRpcUrl(),{method:"POST",body:e});let p;try{p=await c.json()}catch(u){this.logger.error(u,"Error while getting json data from RPC response")}if(this.logger.debug({data:p},"Received RPC request response"),!c.ok||p.error){const u=((s=p.error)==null?void 0:s.code)||-18900,f=(r=P)!=null&&r[u]?`${(o=P)==null?void 0:o[u]}: ${(a=p.error)==null?void 0:a.message}`:(l=p.error)==null?void 0:l.message;throw this.emit("payment_failed",{error:{message:f,code:u},transaction:""}),new Error(f)}return p}),d(this,"validateApprovedNamespacesWithPaymentIntents",()=>{var e,s,r;const o=this.client.session,a=this.paymentIntents;if(!o||!a)throw new Error("No session or payment intents found");const l=[];for(const c of a){const{token:p}=c,{namespace:u}=y.parseChainId(p.network.chainId),f=(r=(s=(e=o.namespaces)==null?void 0:e[u])==null?void 0:s.accounts)==null?void 0:r.find(w=>w.includes(`${p.network.chainId}:`));f&&l.push(f)}if(l.length===0)throw new Error("No approved addresses satisfying the proposed payment intents")}),d(this,"cleanup",()=>{this.paymentIntents=void 0,this.transactions=void 0,this.logger.debug("Cleaned up payment intents and transactions")}),d(this,"getRpcUrl",()=>J({projectId:this.client.opts.projectId})),d(this,"persistSessionTopic",async e=>{await this.signClient.core.storage.setItem(this.getStoragePrefix()+"sessionTopic",e)}),d(this,"getPersistedSessionTopic",async()=>await this.signClient.core.storage.getItem(this.getStoragePrefix()+"sessionTopic")),d(this,"clearPersistedSessionTopic",async()=>{await this.signClient.core.storage.removeItem(this.getStoragePrefix()+"sessionTopic")}),d(this,"getStoragePrefix",()=>V),this.signClient={},this.logger=te.pino({name:this.client.name,level:((n=this.client.opts.loggerOptions)==null?void 0:n.posLevel)||T})}async fetchSupportedNamespacesInBackground(){this.logger.debug("Fetching supported namespaces/networks in background");const t=await this.getPersistedSessionTopic();if(t)try{this.client.session=this.signClient.session.get(t)}catch(n){this.logger.error(n,"Failed to get persisted session topic")}try{this.logger.debug("Fetching supported namespaces/networks");const n=await this.fetchRpcRequest(JSON.stringify({id:b.payloadId(),jsonrpc:"2.0",method:"wc_pos_supportedNetworks",params:{}}));this.logger.debug({supportedNamespaces:n.result.namespaces},"Received supported namespaces/networks"),this.supportedNamespaces=n.result.namespaces}catch(n){this.logger.error(n,"Failed to fetch supported namespaces/networks")}}composeNamespaces(t){this.logger.debug({paymentIntents:t},"Composing namespaces");const n={};return t.forEach(e=>{var s;const{token:{network:r}}=e,{namespace:o}=y.parseChainId(r.chainId),a=this.supportedNamespaces.find(l=>l.name===o);if(!a)throw new Error(`Namespace not supported: ${o}`);n[o]={methods:a.methods,chains:[...((s=n[o])==null?void 0:s.chains)||[],r.chainId],events:a.events}}),this.logger.debug({namespaces:n},"Composed namespaces"),n}}var ue=Object.defineProperty,ge=(i,t,n)=>t in i?ue(i,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):i[t]=n,g=(i,t,n)=>ge(i,typeof t!="symbol"?t+"":t,n);class C extends X{constructor(t){super(t),g(this,"name"),g(this,"events",new _.exports),g(this,"engine"),g(this,"metadata"),g(this,"session"),g(this,"on",(n,e)=>this.engine.on(n,e)),g(this,"once",(n,e)=>this.engine.once(n,e)),g(this,"off",(n,e)=>this.engine.off(n,e)),g(this,"removeListener",(n,e)=>this.engine.removeListener(n,e)),g(this,"setTokens",async n=>{try{return await this.engine.setTokens(n)}catch(e){throw this.engine.logger.error(e.message),e}}),g(this,"createPaymentIntent",async n=>{try{return await this.engine.createPaymentIntent(n)}catch(e){throw this.engine.logger.error(e.message),e}}),g(this,"restart",async n=>{try{return await this.engine.restart(n)}catch(e){throw this.engine.logger.error(e.message),e}}),g(this,"sendPaymentsToWallet",async()=>{try{return await this.engine.sendPaymentsToWallet()}catch(n){throw this.engine.logger.error(n.message),n}}),g(this,"disconnect",async()=>{try{return await this.engine.disconnect()}catch(n){throw this.engine.logger.error(n.message),n}}),this.metadata=t.metadata,this.name=L}static async init(t){const n=new C(t);return await n.initialize(),n}async initialize(){try{this.engine=new pe(this),await this.engine.init(),this.engine.logger.info("POSClient Initialization Success")}catch(t){throw this.engine.logger.info("POSClient Initialization Failure"),this.engine.logger.error(t.message),t}}}const fe=C;exports.CLIENT_CONTEXT=L,exports.CLIENT_STORAGE_OPTIONS=O,exports.CLIENT_STORAGE_PREFIX=V,exports.DEFAULT_LOGGER_LEVEL=T,exports.DEFAULT_NAMESPACES=K,exports.IPOSClient=X,exports.IPOSClientEngine=H,exports.MAX_TRANSACTION_STATUS_CHECKS=G,exports.POSClient=fe,exports.POS_CLIENT_VERSION=D,exports.PROTOCOL=M,exports.PROTOCOL_VERSION=ce,exports.RPC_ERROR_CODES=P,exports.RPC_URL=J,exports.default=C;
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ var signClient = require('@walletconnect/sign-client');
6
+ var jsonrpcUtils = require('@walletconnect/jsonrpc-utils');
7
+ var utils = require('@walletconnect/utils');
8
+ var logger = require('@walletconnect/logger');
9
+
10
+ var events = {exports: {}};
11
+
12
+ var R = typeof Reflect === 'object' ? Reflect : null;
13
+ var ReflectApply = R && typeof R.apply === 'function'
14
+ ? R.apply
15
+ : function ReflectApply(target, receiver, args) {
16
+ return Function.prototype.apply.call(target, receiver, args);
17
+ };
18
+
19
+ var ReflectOwnKeys;
20
+ if (R && typeof R.ownKeys === 'function') {
21
+ ReflectOwnKeys = R.ownKeys;
22
+ } else if (Object.getOwnPropertySymbols) {
23
+ ReflectOwnKeys = function ReflectOwnKeys(target) {
24
+ return Object.getOwnPropertyNames(target)
25
+ .concat(Object.getOwnPropertySymbols(target));
26
+ };
27
+ } else {
28
+ ReflectOwnKeys = function ReflectOwnKeys(target) {
29
+ return Object.getOwnPropertyNames(target);
30
+ };
31
+ }
32
+
33
+ function ProcessEmitWarning(warning) {
34
+ if (console && console.warn) console.warn(warning);
35
+ }
36
+
37
+ var NumberIsNaN = Number.isNaN || function NumberIsNaN(value) {
38
+ return value !== value;
39
+ };
40
+
41
+ function EventEmitter() {
42
+ EventEmitter.init.call(this);
43
+ }
44
+ events.exports = EventEmitter;
45
+ events.exports.once = once;
46
+
47
+ // Backwards-compat with node 0.10.x
48
+ EventEmitter.EventEmitter = EventEmitter;
49
+
50
+ EventEmitter.prototype._events = undefined;
51
+ EventEmitter.prototype._eventsCount = 0;
52
+ EventEmitter.prototype._maxListeners = undefined;
53
+
54
+ // By default EventEmitters will print a warning if more than 10 listeners are
55
+ // added to it. This is a useful default which helps finding memory leaks.
56
+ var defaultMaxListeners = 10;
57
+
58
+ function checkListener(listener) {
59
+ if (typeof listener !== 'function') {
60
+ throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener);
61
+ }
62
+ }
63
+
64
+ Object.defineProperty(EventEmitter, 'defaultMaxListeners', {
65
+ enumerable: true,
66
+ get: function() {
67
+ return defaultMaxListeners;
68
+ },
69
+ set: function(arg) {
70
+ if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) {
71
+ throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + '.');
72
+ }
73
+ defaultMaxListeners = arg;
74
+ }
75
+ });
76
+
77
+ EventEmitter.init = function() {
78
+
79
+ if (this._events === undefined ||
80
+ this._events === Object.getPrototypeOf(this)._events) {
81
+ this._events = Object.create(null);
82
+ this._eventsCount = 0;
83
+ }
84
+
85
+ this._maxListeners = this._maxListeners || undefined;
86
+ };
87
+
88
+ // Obviously not all Emitters should be limited to 10. This function allows
89
+ // that to be increased. Set to zero for unlimited.
90
+ EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {
91
+ if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) {
92
+ throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + '.');
93
+ }
94
+ this._maxListeners = n;
95
+ return this;
96
+ };
97
+
98
+ function _getMaxListeners(that) {
99
+ if (that._maxListeners === undefined)
100
+ return EventEmitter.defaultMaxListeners;
101
+ return that._maxListeners;
102
+ }
103
+
104
+ EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
105
+ return _getMaxListeners(this);
106
+ };
107
+
108
+ EventEmitter.prototype.emit = function emit(type) {
109
+ var args = [];
110
+ for (var i = 1; i < arguments.length; i++) args.push(arguments[i]);
111
+ var doError = (type === 'error');
112
+
113
+ var events = this._events;
114
+ if (events !== undefined)
115
+ doError = (doError && events.error === undefined);
116
+ else if (!doError)
117
+ return false;
118
+
119
+ // If there is no 'error' event listener then throw.
120
+ if (doError) {
121
+ var er;
122
+ if (args.length > 0)
123
+ er = args[0];
124
+ if (er instanceof Error) {
125
+ // Note: The comments on the `throw` lines are intentional, they show
126
+ // up in Node's output if this results in an unhandled exception.
127
+ throw er; // Unhandled 'error' event
128
+ }
129
+ // At least give some kind of context to the user
130
+ var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : ''));
131
+ err.context = er;
132
+ throw err; // Unhandled 'error' event
133
+ }
134
+
135
+ var handler = events[type];
136
+
137
+ if (handler === undefined)
138
+ return false;
139
+
140
+ if (typeof handler === 'function') {
141
+ ReflectApply(handler, this, args);
142
+ } else {
143
+ var len = handler.length;
144
+ var listeners = arrayClone(handler, len);
145
+ for (var i = 0; i < len; ++i)
146
+ ReflectApply(listeners[i], this, args);
147
+ }
148
+
149
+ return true;
150
+ };
151
+
152
+ function _addListener(target, type, listener, prepend) {
153
+ var m;
154
+ var events;
155
+ var existing;
156
+
157
+ checkListener(listener);
158
+
159
+ events = target._events;
160
+ if (events === undefined) {
161
+ events = target._events = Object.create(null);
162
+ target._eventsCount = 0;
163
+ } else {
164
+ // To avoid recursion in the case that type === "newListener"! Before
165
+ // adding it to the listeners, first emit "newListener".
166
+ if (events.newListener !== undefined) {
167
+ target.emit('newListener', type,
168
+ listener.listener ? listener.listener : listener);
169
+
170
+ // Re-assign `events` because a newListener handler could have caused the
171
+ // this._events to be assigned to a new object
172
+ events = target._events;
173
+ }
174
+ existing = events[type];
175
+ }
176
+
177
+ if (existing === undefined) {
178
+ // Optimize the case of one listener. Don't need the extra array object.
179
+ existing = events[type] = listener;
180
+ ++target._eventsCount;
181
+ } else {
182
+ if (typeof existing === 'function') {
183
+ // Adding the second element, need to change to array.
184
+ existing = events[type] =
185
+ prepend ? [listener, existing] : [existing, listener];
186
+ // If we've already got an array, just append.
187
+ } else if (prepend) {
188
+ existing.unshift(listener);
189
+ } else {
190
+ existing.push(listener);
191
+ }
192
+
193
+ // Check for listener leak
194
+ m = _getMaxListeners(target);
195
+ if (m > 0 && existing.length > m && !existing.warned) {
196
+ existing.warned = true;
197
+ // No error code for this since it is a Warning
198
+ // eslint-disable-next-line no-restricted-syntax
199
+ var w = new Error('Possible EventEmitter memory leak detected. ' +
200
+ existing.length + ' ' + String(type) + ' listeners ' +
201
+ 'added. Use emitter.setMaxListeners() to ' +
202
+ 'increase limit');
203
+ w.name = 'MaxListenersExceededWarning';
204
+ w.emitter = target;
205
+ w.type = type;
206
+ w.count = existing.length;
207
+ ProcessEmitWarning(w);
208
+ }
209
+ }
210
+
211
+ return target;
212
+ }
213
+
214
+ EventEmitter.prototype.addListener = function addListener(type, listener) {
215
+ return _addListener(this, type, listener, false);
216
+ };
217
+
218
+ EventEmitter.prototype.on = EventEmitter.prototype.addListener;
219
+
220
+ EventEmitter.prototype.prependListener =
221
+ function prependListener(type, listener) {
222
+ return _addListener(this, type, listener, true);
223
+ };
224
+
225
+ function onceWrapper() {
226
+ if (!this.fired) {
227
+ this.target.removeListener(this.type, this.wrapFn);
228
+ this.fired = true;
229
+ if (arguments.length === 0)
230
+ return this.listener.call(this.target);
231
+ return this.listener.apply(this.target, arguments);
232
+ }
233
+ }
234
+
235
+ function _onceWrap(target, type, listener) {
236
+ var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener };
237
+ var wrapped = onceWrapper.bind(state);
238
+ wrapped.listener = listener;
239
+ state.wrapFn = wrapped;
240
+ return wrapped;
241
+ }
242
+
243
+ EventEmitter.prototype.once = function once(type, listener) {
244
+ checkListener(listener);
245
+ this.on(type, _onceWrap(this, type, listener));
246
+ return this;
247
+ };
248
+
249
+ EventEmitter.prototype.prependOnceListener =
250
+ function prependOnceListener(type, listener) {
251
+ checkListener(listener);
252
+ this.prependListener(type, _onceWrap(this, type, listener));
253
+ return this;
254
+ };
255
+
256
+ // Emits a 'removeListener' event if and only if the listener was removed.
257
+ EventEmitter.prototype.removeListener =
258
+ function removeListener(type, listener) {
259
+ var list, events, position, i, originalListener;
260
+
261
+ checkListener(listener);
262
+
263
+ events = this._events;
264
+ if (events === undefined)
265
+ return this;
266
+
267
+ list = events[type];
268
+ if (list === undefined)
269
+ return this;
270
+
271
+ if (list === listener || list.listener === listener) {
272
+ if (--this._eventsCount === 0)
273
+ this._events = Object.create(null);
274
+ else {
275
+ delete events[type];
276
+ if (events.removeListener)
277
+ this.emit('removeListener', type, list.listener || listener);
278
+ }
279
+ } else if (typeof list !== 'function') {
280
+ position = -1;
281
+
282
+ for (i = list.length - 1; i >= 0; i--) {
283
+ if (list[i] === listener || list[i].listener === listener) {
284
+ originalListener = list[i].listener;
285
+ position = i;
286
+ break;
287
+ }
288
+ }
289
+
290
+ if (position < 0)
291
+ return this;
292
+
293
+ if (position === 0)
294
+ list.shift();
295
+ else {
296
+ spliceOne(list, position);
297
+ }
298
+
299
+ if (list.length === 1)
300
+ events[type] = list[0];
301
+
302
+ if (events.removeListener !== undefined)
303
+ this.emit('removeListener', type, originalListener || listener);
304
+ }
305
+
306
+ return this;
307
+ };
308
+
309
+ EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
310
+
311
+ EventEmitter.prototype.removeAllListeners =
312
+ function removeAllListeners(type) {
313
+ var listeners, events, i;
314
+
315
+ events = this._events;
316
+ if (events === undefined)
317
+ return this;
318
+
319
+ // not listening for removeListener, no need to emit
320
+ if (events.removeListener === undefined) {
321
+ if (arguments.length === 0) {
322
+ this._events = Object.create(null);
323
+ this._eventsCount = 0;
324
+ } else if (events[type] !== undefined) {
325
+ if (--this._eventsCount === 0)
326
+ this._events = Object.create(null);
327
+ else
328
+ delete events[type];
329
+ }
330
+ return this;
331
+ }
332
+
333
+ // emit removeListener for all listeners on all events
334
+ if (arguments.length === 0) {
335
+ var keys = Object.keys(events);
336
+ var key;
337
+ for (i = 0; i < keys.length; ++i) {
338
+ key = keys[i];
339
+ if (key === 'removeListener') continue;
340
+ this.removeAllListeners(key);
341
+ }
342
+ this.removeAllListeners('removeListener');
343
+ this._events = Object.create(null);
344
+ this._eventsCount = 0;
345
+ return this;
346
+ }
347
+
348
+ listeners = events[type];
349
+
350
+ if (typeof listeners === 'function') {
351
+ this.removeListener(type, listeners);
352
+ } else if (listeners !== undefined) {
353
+ // LIFO order
354
+ for (i = listeners.length - 1; i >= 0; i--) {
355
+ this.removeListener(type, listeners[i]);
356
+ }
357
+ }
358
+
359
+ return this;
360
+ };
361
+
362
+ function _listeners(target, type, unwrap) {
363
+ var events = target._events;
364
+
365
+ if (events === undefined)
366
+ return [];
367
+
368
+ var evlistener = events[type];
369
+ if (evlistener === undefined)
370
+ return [];
371
+
372
+ if (typeof evlistener === 'function')
373
+ return unwrap ? [evlistener.listener || evlistener] : [evlistener];
374
+
375
+ return unwrap ?
376
+ unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);
377
+ }
378
+
379
+ EventEmitter.prototype.listeners = function listeners(type) {
380
+ return _listeners(this, type, true);
381
+ };
382
+
383
+ EventEmitter.prototype.rawListeners = function rawListeners(type) {
384
+ return _listeners(this, type, false);
385
+ };
386
+
387
+ EventEmitter.listenerCount = function(emitter, type) {
388
+ if (typeof emitter.listenerCount === 'function') {
389
+ return emitter.listenerCount(type);
390
+ } else {
391
+ return listenerCount.call(emitter, type);
392
+ }
393
+ };
394
+
395
+ EventEmitter.prototype.listenerCount = listenerCount;
396
+ function listenerCount(type) {
397
+ var events = this._events;
398
+
399
+ if (events !== undefined) {
400
+ var evlistener = events[type];
401
+
402
+ if (typeof evlistener === 'function') {
403
+ return 1;
404
+ } else if (evlistener !== undefined) {
405
+ return evlistener.length;
406
+ }
407
+ }
408
+
409
+ return 0;
410
+ }
411
+
412
+ EventEmitter.prototype.eventNames = function eventNames() {
413
+ return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : [];
414
+ };
415
+
416
+ function arrayClone(arr, n) {
417
+ var copy = new Array(n);
418
+ for (var i = 0; i < n; ++i)
419
+ copy[i] = arr[i];
420
+ return copy;
421
+ }
422
+
423
+ function spliceOne(list, index) {
424
+ for (; index + 1 < list.length; index++)
425
+ list[index] = list[index + 1];
426
+ list.pop();
427
+ }
428
+
429
+ function unwrapListeners(arr) {
430
+ var ret = new Array(arr.length);
431
+ for (var i = 0; i < ret.length; ++i) {
432
+ ret[i] = arr[i].listener || arr[i];
433
+ }
434
+ return ret;
435
+ }
436
+
437
+ function once(emitter, name) {
438
+ return new Promise(function (resolve, reject) {
439
+ function errorListener(err) {
440
+ emitter.removeListener(name, resolver);
441
+ reject(err);
442
+ }
443
+
444
+ function resolver() {
445
+ if (typeof emitter.removeListener === 'function') {
446
+ emitter.removeListener('error', errorListener);
447
+ }
448
+ resolve([].slice.call(arguments));
449
+ }
450
+ eventTargetAgnosticAddListener(emitter, name, resolver, { once: true });
451
+ if (name !== 'error') {
452
+ addErrorHandlerIfEventEmitter(emitter, errorListener, { once: true });
453
+ }
454
+ });
455
+ }
456
+
457
+ function addErrorHandlerIfEventEmitter(emitter, handler, flags) {
458
+ if (typeof emitter.on === 'function') {
459
+ eventTargetAgnosticAddListener(emitter, 'error', handler, flags);
460
+ }
461
+ }
462
+
463
+ function eventTargetAgnosticAddListener(emitter, name, listener, flags) {
464
+ if (typeof emitter.on === 'function') {
465
+ if (flags.once) {
466
+ emitter.once(name, listener);
467
+ } else {
468
+ emitter.on(name, listener);
469
+ }
470
+ } else if (typeof emitter.addEventListener === 'function') {
471
+ // EventTarget does not have `error` event semantics like Node
472
+ // EventEmitters, we do not listen for `error` events here.
473
+ emitter.addEventListener(name, function wrapListener(arg) {
474
+ // IE does not have builtin `{ once: true }` support so we
475
+ // have to do it manually.
476
+ if (flags.once) {
477
+ emitter.removeEventListener(name, wrapListener);
478
+ }
479
+ listener(arg);
480
+ });
481
+ } else {
482
+ throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type ' + typeof emitter);
483
+ }
484
+ }
485
+
486
+ const PROTOCOL = "wc";
487
+ const PROTOCOL_VERSION = 2;
488
+ const CLIENT_CONTEXT = "POSClient";
489
+ const CLIENT_STORAGE_PREFIX = `${PROTOCOL}@${PROTOCOL_VERSION}:${CLIENT_CONTEXT}:`;
490
+ const CLIENT_STORAGE_OPTIONS = {
491
+ database: ":memory:",
492
+ customStoragePrefix: "@walletconnect/pos-client"
493
+ };
494
+ const POS_CLIENT_VERSION = "1.0.0";
495
+ const MAX_TRANSACTION_STATUS_CHECKS = 10;
496
+ const DEFAULT_LOGGER_LEVEL = "error";
497
+
498
+ const DEFAULT_NAMESPACES = [
499
+ {
500
+ assetNamespaces: ["erc20", "slip44"],
501
+ capabilities: null,
502
+ events: [],
503
+ methods: ["eth_sendTransaction"],
504
+ name: "eip155"
505
+ },
506
+ {
507
+ assetNamespaces: ["token", "slip44"],
508
+ capabilities: null,
509
+ events: [],
510
+ methods: ["solana_signAndSendTransaction"],
511
+ name: "solana"
512
+ },
513
+ {
514
+ assetNamespaces: ["trc20", "slip44"],
515
+ capabilities: null,
516
+ events: [],
517
+ methods: ["tron_signTransaction"],
518
+ name: "tron"
519
+ }
520
+ ];
521
+
522
+ const RPC_URL = ({ projectId }) => {
523
+ return `https://rpc.walletconnect.org/v1/json-rpc?projectId=${projectId}&st=node&sv=js-pos-${POS_CLIENT_VERSION}`;
524
+ };
525
+ const RPC_ERROR_CODES = {
526
+ "-18901": "ValidationError.InvalidAsset",
527
+ "-18902": "ValidationError.InvalidRecipient",
528
+ "-18903": "ValidationError.InvalidSender",
529
+ "-18904": "ValidationError.InvalidAmount",
530
+ "-18905": "ValidationError.InvalidAddress",
531
+ "-18906": "ValidationError.InvalidWalletResponse",
532
+ "-18907": "ValidationError.InvalidTransactionId",
533
+ "-18920": "ExecutionError.GasEstimation",
534
+ "-18940": "InternalError.InvalidProviderUrl",
535
+ "-18941": "InternalError.RpcError",
536
+ "-18942": "InternalError.Internal",
537
+ "-18970": "TransactionIdError.InvalidFormat",
538
+ "-18971": "TransactionIdError.InvalidChainId"
539
+ };
540
+
541
+ class IPOSClient {
542
+ constructor(opts) {
543
+ this.opts = opts;
544
+ }
545
+ }
546
+
547
+ class IPOSClientEngine {
548
+ constructor(client) {
549
+ this.client = client;
550
+ }
551
+ }
552
+
553
+ const isValidToken = (params) => {
554
+ const { supportedNamespaces, token } = params;
555
+ const { network, symbol, standard, address } = token;
556
+ if (!network || !symbol || !standard || !address || !utils.isValidChainId(network == null ? void 0 : network.chainId)) {
557
+ return false;
558
+ }
559
+ const { namespace } = utils.parseChainId(network.chainId);
560
+ const supportedNamespaceDetails = supportedNamespaces.find(
561
+ (ns) => ns.name.toLowerCase() === namespace.toLowerCase()
562
+ );
563
+ if (!supportedNamespaceDetails) {
564
+ throw new Error(`Unsupported token namespace: ${namespace}`);
565
+ }
566
+ const supportedStandards = supportedNamespaceDetails.assetNamespaces.map(
567
+ (ns) => ns.toLowerCase()
568
+ );
569
+ if (!supportedStandards.includes(standard == null ? void 0 : standard.toLowerCase())) {
570
+ throw new Error(`Unsupported token standard: ${standard} for namespace: ${namespace}`);
571
+ }
572
+ return true;
573
+ };
574
+ const isValidPaymentIntent = (params) => {
575
+ const { supportedNamespaces, paymentIntent } = params;
576
+ const { token, amount, recipient } = paymentIntent;
577
+ if (!token || !amount || !recipient || !isValidToken({ supportedNamespaces, token })) {
578
+ return false;
579
+ }
580
+ return true;
581
+ };
582
+
583
+ var __defProp$1 = Object.defineProperty;
584
+ var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
585
+ var __publicField$1 = (obj, key, value) => __defNormalProp$1(obj, typeof key !== "symbol" ? key + "" : key, value);
586
+ class Engine extends IPOSClientEngine {
587
+ constructor(client) {
588
+ var _a;
589
+ super(client);
590
+ __publicField$1(this, "signClient");
591
+ __publicField$1(this, "logger");
592
+ __publicField$1(this, "tokens", []);
593
+ __publicField$1(this, "supportedNamespaces", DEFAULT_NAMESPACES);
594
+ // map to keep track of pending payment intents
595
+ // private paymentIntentsMap: Map<number, POSClientTypes.PaymentIntent[]> = new Map();
596
+ __publicField$1(this, "paymentIntents");
597
+ // transactions to be submitted to the wallet
598
+ __publicField$1(this, "transactions");
599
+ __publicField$1(this, "paymentsSendingInProgress", false);
600
+ __publicField$1(this, "manualControl", false);
601
+ __publicField$1(this, "init", async () => {
602
+ var _a, _b;
603
+ this.setupEventHandlers();
604
+ this.signClient = await signClient.SignClient.init({
605
+ projectId: this.client.opts.projectId,
606
+ metadata: {
607
+ name: this.client.metadata.merchantName,
608
+ description: this.client.metadata.description,
609
+ url: this.client.metadata.url,
610
+ icons: [this.client.metadata.logoIcon]
611
+ },
612
+ storageOptions: {
613
+ database: ((_a = this.client.opts.storageOptions) == null ? void 0 : _a.databaseName) || CLIENT_STORAGE_OPTIONS.database
614
+ },
615
+ customStoragePrefix: CLIENT_STORAGE_OPTIONS.customStoragePrefix,
616
+ logger: ((_b = this.client.opts.loggerOptions) == null ? void 0 : _b.signLevel) || DEFAULT_LOGGER_LEVEL
617
+ });
618
+ this.fetchSupportedNamespacesInBackground();
619
+ });
620
+ __publicField$1(this, "setTokens", async (params) => {
621
+ const { tokens } = params;
622
+ this.logger.debug({ tokens }, "Setting tokens");
623
+ tokens.forEach((token) => {
624
+ if (!isValidToken({ token, supportedNamespaces: this.supportedNamespaces })) {
625
+ throw new Error(`Invalid token: ${JSON.stringify(token)}`);
626
+ }
627
+ });
628
+ await new Promise((resolve) => {
629
+ this.tokens = tokens;
630
+ resolve();
631
+ });
632
+ this.logger.debug({ tokens }, "Tokens set");
633
+ });
634
+ __publicField$1(this, "createPaymentIntent", async (params) => {
635
+ const { paymentIntents, manualControl } = params;
636
+ this.logger.debug({ paymentIntents }, "Creating payment intent");
637
+ if (paymentIntents.length === 0) {
638
+ throw new Error("No payment intents provided");
639
+ }
640
+ this.manualControl = manualControl || false;
641
+ for (const paymentIntent of paymentIntents) {
642
+ if (!isValidPaymentIntent({ paymentIntent, supportedNamespaces: this.supportedNamespaces })) {
643
+ throw new Error(`Invalid payment intent: ${JSON.stringify(paymentIntent)}`);
644
+ }
645
+ }
646
+ this.logger.debug({ paymentIntents }, "Payment intent validation success");
647
+ this.paymentIntents = paymentIntents;
648
+ this.logger.debug({ paymentIntents }, "Payment intents set");
649
+ if (this.client.session) {
650
+ try {
651
+ this.validateApprovedNamespacesWithPaymentIntents();
652
+ if (!this.manualControl) {
653
+ await this.sendPaymentsToWallet();
654
+ }
655
+ return;
656
+ } catch (error) {
657
+ this.logger.error(error);
658
+ await this.disconnect();
659
+ }
660
+ }
661
+ const namespaces = this.composeNamespaces(paymentIntents);
662
+ const { uri, approval } = await this.signClient.connect({
663
+ optionalNamespaces: namespaces
664
+ });
665
+ this.logger.debug({ uri }, "Connected to the WalletConnect network");
666
+ if (!uri) {
667
+ this.client.events.emit("connection_failed", {
668
+ error: {
669
+ message: "Failed to connect to the WalletConnect network",
670
+ code: 4001
671
+ }
672
+ });
673
+ throw new Error("Failed to connect to the WalletConnect network");
674
+ }
675
+ this.emit("await_approval", { approval });
676
+ this.logger.debug("Emitted await_approval event");
677
+ this.emit("qr_ready", { uri });
678
+ this.logger.debug({ uri }, "Emitted qr_ready event");
679
+ if (this.manualControl) {
680
+ const session = await approval();
681
+ await this.onSessionConnected({ session });
682
+ }
683
+ });
684
+ __publicField$1(this, "restart", async (params) => {
685
+ this.logger.debug({ params }, "Restarting");
686
+ const manualControl = this.manualControl;
687
+ if (params == null ? void 0 : params.reinit) {
688
+ this.tokens = [];
689
+ this.cleanup();
690
+ await this.disconnect();
691
+ this.logger.debug("Restarted: Cleared payment intents, transactions and disconnected");
692
+ return;
693
+ }
694
+ const paymentIntents = this.paymentIntents;
695
+ if (!paymentIntents) {
696
+ throw new Error("No payment intents found");
697
+ }
698
+ await this.createPaymentIntent({ paymentIntents, manualControl });
699
+ this.logger.debug(
700
+ { paymentIntents },
701
+ "Restarted: Created payment intent flow from the beginning"
702
+ );
703
+ });
704
+ // ---------- Event Handlers ----------------------------------------------- //
705
+ __publicField$1(this, "emit", (event, args) => {
706
+ this.logger.debug({ event, args }, "Emit");
707
+ return this.client.events.emit(event, args);
708
+ });
709
+ __publicField$1(this, "on", (event, listener) => {
710
+ this.logger.debug({ event, listener }, "On");
711
+ return this.client.events.on(event, listener);
712
+ });
713
+ __publicField$1(this, "once", (event, listener) => {
714
+ this.logger.debug({ event, listener }, "Once");
715
+ return this.client.events.once(event, listener);
716
+ });
717
+ __publicField$1(this, "off", (event, listener) => {
718
+ this.logger.debug({ event, listener }, "Off");
719
+ return this.client.events.off(event, listener);
720
+ });
721
+ __publicField$1(this, "removeListener", (event, listener) => {
722
+ this.logger.debug({ event, listener }, "Remove listener");
723
+ return this.client.events.removeListener(event, listener);
724
+ });
725
+ __publicField$1(this, "prepareTransactionsFromPaymentIntents", async () => {
726
+ var _a, _b, _c, _d, _e, _f;
727
+ const paymentIntents = this.paymentIntents;
728
+ if (!paymentIntents) {
729
+ throw new Error("No payment intents found");
730
+ }
731
+ const session = this.client.session;
732
+ if (!session) {
733
+ throw new Error("No session found");
734
+ }
735
+ this.logger.debug(
736
+ {
737
+ sessionTopic: session.topic
738
+ },
739
+ "Preparing transactions from payment intents"
740
+ );
741
+ const intents = [];
742
+ for (const paymentIntent of paymentIntents) {
743
+ const { token, amount, recipient } = paymentIntent;
744
+ const { namespace } = utils.parseChainId(token.network.chainId);
745
+ const account = (_c = (_b = (_a = session.namespaces) == null ? void 0 : _a[namespace]) == null ? void 0 : _b.accounts) == null ? void 0 : _c.find(
746
+ (account2) => account2.includes(`${token.network.chainId}:`)
747
+ );
748
+ if (!account) {
749
+ throw new Error(
750
+ `Address not found in session for chain id: ${token.network.chainId}, approved addresses: ${(_f = (_e = (_d = session.namespaces) == null ? void 0 : _d[namespace]) == null ? void 0 : _e.accounts) == null ? void 0 : _f.join(", ")}`
751
+ );
752
+ }
753
+ intents.push({
754
+ asset: `${token.network.chainId}/${token.standard.toLowerCase()}:${token.address}`,
755
+ recipient,
756
+ amount,
757
+ sender: account
758
+ });
759
+ }
760
+ this.logger.debug(
761
+ {
762
+ sessionTopic: session.topic,
763
+ transactions: intents
764
+ },
765
+ "Prepared transactions from payment intents"
766
+ );
767
+ const payload = {
768
+ id: jsonrpcUtils.payloadId(),
769
+ jsonrpc: "2.0",
770
+ method: "wc_pos_buildTransactions",
771
+ params: {
772
+ paymentIntents: intents
773
+ }
774
+ };
775
+ this.logger.debug({ payload }, "Fetching wc_pos_buildTransactions");
776
+ const response = await this.fetchRpcRequest(
777
+ JSON.stringify(payload)
778
+ );
779
+ this.logger.debug({ response }, "Received wc_pos_buildTransactions");
780
+ this.transactions = response.result.transactions;
781
+ this.logger.debug(
782
+ {
783
+ transactions: this.transactions
784
+ },
785
+ "Payment intent to transactions map set"
786
+ );
787
+ });
788
+ __publicField$1(this, "sendPaymentsToWallet", async () => {
789
+ if (this.paymentsSendingInProgress) {
790
+ throw new Error("Payments are already being sent, please wait for them to complete");
791
+ }
792
+ this.paymentsSendingInProgress = true;
793
+ try {
794
+ await this.prepareTransactionsFromPaymentIntents();
795
+ this.sendTransactionsToWallet();
796
+ } catch (error) {
797
+ this.logger.error(error, "Error while sending payments to wallet");
798
+ }
799
+ this.paymentsSendingInProgress = false;
800
+ });
801
+ __publicField$1(this, "sendTransactionsToWallet", async () => {
802
+ var _a;
803
+ const transactions = this.transactions;
804
+ const paymentIntents = this.paymentIntents;
805
+ if (!transactions || !paymentIntents) {
806
+ throw new Error(
807
+ "No transactions or payment intents to send, call createPaymentIntent() first"
808
+ );
809
+ }
810
+ const session = this.client.session;
811
+ if (!session) {
812
+ throw new Error("No session found");
813
+ }
814
+ this.logger.debug(
815
+ {
816
+ transactions,
817
+ sessionTopic: (_a = this.client.session) == null ? void 0 : _a.topic
818
+ },
819
+ "Sending transactions to wallet"
820
+ );
821
+ for (let i = 0; i < transactions.length; i++) {
822
+ const transaction = transactions[i];
823
+ const paymentIntent = paymentIntents[i];
824
+ try {
825
+ this.emit("payment_requested", { paymentIntent, transaction });
826
+ this.logger.debug(
827
+ {
828
+ transactionId: transaction.id
829
+ },
830
+ "Emitted payment_requested event"
831
+ );
832
+ let result;
833
+ try {
834
+ result = await this.signClient.request({
835
+ topic: session.topic,
836
+ request: {
837
+ method: transaction.method,
838
+ params: transaction.params
839
+ },
840
+ chainId: transaction.chainId
841
+ });
842
+ this.logger.debug(
843
+ {
844
+ transactionId: transaction.id,
845
+ result
846
+ },
847
+ "Wallet responded to payment request"
848
+ );
849
+ } catch (error) {
850
+ this.logger.error(error, "Error while sending payment request");
851
+ this.emit("payment_rejected", {
852
+ error: {
853
+ message: error == null ? void 0 : error.message,
854
+ code: 4001
855
+ },
856
+ paymentIntent
857
+ });
858
+ throw error;
859
+ }
860
+ this.emit("payment_broadcasted", { paymentIntent, transaction, result });
861
+ this.logger.debug(
862
+ {
863
+ transactionId: transaction.id
864
+ },
865
+ "Emitted payment_broadcasted event"
866
+ );
867
+ await this.awaitPaymentConfirmed({ transaction, result });
868
+ await new Promise((resolve) => setTimeout(resolve, 1e3));
869
+ } catch (error) {
870
+ this.logger.error(error, "Error while awaiting payment confirmed");
871
+ }
872
+ }
873
+ this.cleanup();
874
+ if (!this.manualControl) {
875
+ await this.disconnect();
876
+ }
877
+ });
878
+ __publicField$1(this, "awaitPaymentConfirmed", async (params) => {
879
+ try {
880
+ const { transaction, result } = params;
881
+ this.logger.debug({ transactionId: transaction.id, result }, "Awaiting payment confirmed");
882
+ const payload = {
883
+ id: jsonrpcUtils.payloadId(),
884
+ jsonrpc: "2.0",
885
+ method: "wc_pos_checkTransaction",
886
+ params: {
887
+ id: transaction.id,
888
+ sendResult: typeof result === "string" ? result : JSON.stringify(result)
889
+ }
890
+ };
891
+ let numCheckAttempts = 0;
892
+ let transactionResult;
893
+ while (!transactionResult) {
894
+ if (numCheckAttempts >= MAX_TRANSACTION_STATUS_CHECKS) {
895
+ throw new Error(`Transaction status not found for id: ${transaction.id}`);
896
+ }
897
+ numCheckAttempts++;
898
+ const response = await this.fetchRpcRequest(
899
+ JSON.stringify(payload)
900
+ );
901
+ this.logger.debug(
902
+ {
903
+ transactionId: transaction.id,
904
+ response
905
+ },
906
+ "Received wc_pos_checkTransaction"
907
+ );
908
+ if (response.result.status === "CONFIRMED") {
909
+ this.logger.debug({ response }, "Transaction status confirmed");
910
+ this.emit("payment_successful", {
911
+ transaction,
912
+ result
913
+ });
914
+ transactionResult = response.result;
915
+ break;
916
+ } else if (response.result.status === "FAILED") {
917
+ this.logger.debug({ response }, "Transaction failed");
918
+ this.emit("payment_failed", {
919
+ error: {
920
+ message: response.result.error,
921
+ code: 4001
922
+ },
923
+ transaction: result
924
+ });
925
+ transactionResult = response.result;
926
+ break;
927
+ } else if (response.result.status === "PENDING") {
928
+ this.logger.debug({ response }, "Transaction pending");
929
+ await new Promise((resolve) => setTimeout(resolve, response.result.checkIn || 1e3));
930
+ }
931
+ }
932
+ } catch (error) {
933
+ this.logger.error(error, "Error while awaiting payment confirmations");
934
+ }
935
+ });
936
+ __publicField$1(this, "setupEventHandlers", () => {
937
+ this.on("await_approval", async ({ approval }) => {
938
+ try {
939
+ this.logger.debug("On await_approval");
940
+ const session = await approval();
941
+ await this.onSessionConnected({ session });
942
+ } catch (error) {
943
+ this.logger.error(error, "Error while awaiting approval");
944
+ this.emit("connection_rejected", {
945
+ error: {
946
+ message: error == null ? void 0 : error.message,
947
+ code: 4001
948
+ }
949
+ });
950
+ }
951
+ });
952
+ });
953
+ __publicField$1(this, "onSessionConnected", async (params) => {
954
+ const { session } = params;
955
+ this.logger.debug({ sessionTopic: session.topic }, "On session connected");
956
+ await this.signClient.session.update(session.topic, {
957
+ sessionConfig: {
958
+ disableDeepLink: true
959
+ }
960
+ });
961
+ this.logger.debug({ sessionTopic: session.topic }, "Disabled deep links for session");
962
+ this.client.session = this.signClient.session.get(session.topic);
963
+ await this.persistSessionTopic(session.topic);
964
+ this.emit("connected", { session });
965
+ this.logger.debug("Emitted connected event");
966
+ if (!this.manualControl) {
967
+ await this.sendPaymentsToWallet();
968
+ }
969
+ });
970
+ __publicField$1(this, "disconnect", async () => {
971
+ if (this.client.session) {
972
+ await this.clearPersistedSessionTopic();
973
+ await this.signClient.disconnect({
974
+ topic: this.client.session.topic,
975
+ reason: { code: 4001, message: "User disconnected" }
976
+ });
977
+ }
978
+ this.manualControl = false;
979
+ this.client.session = void 0;
980
+ });
981
+ __publicField$1(this, "fetchRpcRequest", async (payload) => {
982
+ var _a, _b, _c, _d, _e;
983
+ this.logger.debug({ url: this.getRpcUrl(), payload }, "Fetching RPC request");
984
+ const result = await fetch(this.getRpcUrl(), {
985
+ method: "POST",
986
+ body: payload
987
+ });
988
+ let data;
989
+ try {
990
+ data = await result.json();
991
+ } catch (error) {
992
+ this.logger.error(error, "Error while getting json data from RPC response");
993
+ }
994
+ this.logger.debug({ data }, "Received RPC request response");
995
+ if (!result.ok || data.error) {
996
+ const code = ((_a = data.error) == null ? void 0 : _a.code) || -18900;
997
+ const message = ((_b = RPC_ERROR_CODES) == null ? void 0 : _b[code]) ? `${(_c = RPC_ERROR_CODES) == null ? void 0 : _c[code]}: ${(_d = data.error) == null ? void 0 : _d.message}` : (_e = data.error) == null ? void 0 : _e.message;
998
+ this.emit("payment_failed", {
999
+ error: {
1000
+ message,
1001
+ code
1002
+ },
1003
+ transaction: ""
1004
+ });
1005
+ throw new Error(message);
1006
+ }
1007
+ return data;
1008
+ });
1009
+ // validates that the approved namespaces contain at least one address that matches the payment intent
1010
+ __publicField$1(this, "validateApprovedNamespacesWithPaymentIntents", () => {
1011
+ var _a, _b, _c;
1012
+ const session = this.client.session;
1013
+ const paymentIntents = this.paymentIntents;
1014
+ if (!session || !paymentIntents) {
1015
+ throw new Error("No session or payment intents found");
1016
+ }
1017
+ const matchedAddresses = [];
1018
+ for (const paymentIntent of paymentIntents) {
1019
+ const { token } = paymentIntent;
1020
+ const { namespace } = utils.parseChainId(token.network.chainId);
1021
+ const account = (_c = (_b = (_a = session.namespaces) == null ? void 0 : _a[namespace]) == null ? void 0 : _b.accounts) == null ? void 0 : _c.find(
1022
+ (account2) => account2.includes(`${token.network.chainId}:`)
1023
+ );
1024
+ if (!account) {
1025
+ continue;
1026
+ }
1027
+ matchedAddresses.push(account);
1028
+ }
1029
+ if (matchedAddresses.length === 0) {
1030
+ throw new Error("No approved addresses satisfying the proposed payment intents");
1031
+ }
1032
+ });
1033
+ __publicField$1(this, "cleanup", () => {
1034
+ this.paymentIntents = void 0;
1035
+ this.transactions = void 0;
1036
+ this.logger.debug("Cleaned up payment intents and transactions");
1037
+ });
1038
+ __publicField$1(this, "getRpcUrl", () => {
1039
+ return RPC_URL({ projectId: this.client.opts.projectId });
1040
+ });
1041
+ __publicField$1(this, "persistSessionTopic", async (topic) => {
1042
+ await this.signClient.core.storage.setItem(this.getStoragePrefix() + "sessionTopic", topic);
1043
+ });
1044
+ __publicField$1(this, "getPersistedSessionTopic", async () => {
1045
+ return await this.signClient.core.storage.getItem(this.getStoragePrefix() + "sessionTopic");
1046
+ });
1047
+ __publicField$1(this, "clearPersistedSessionTopic", async () => {
1048
+ await this.signClient.core.storage.removeItem(this.getStoragePrefix() + "sessionTopic");
1049
+ });
1050
+ __publicField$1(this, "getStoragePrefix", () => {
1051
+ return CLIENT_STORAGE_PREFIX;
1052
+ });
1053
+ this.signClient = {};
1054
+ this.logger = logger.pino({
1055
+ name: this.client.name,
1056
+ level: ((_a = this.client.opts.loggerOptions) == null ? void 0 : _a.posLevel) || DEFAULT_LOGGER_LEVEL
1057
+ });
1058
+ }
1059
+ /**
1060
+ * Fetches supported namespaces in the background without blocking initialization.
1061
+ */
1062
+ async fetchSupportedNamespacesInBackground() {
1063
+ this.logger.debug("Fetching supported namespaces/networks in background");
1064
+ const persistedSessionTopic = await this.getPersistedSessionTopic();
1065
+ if (persistedSessionTopic) {
1066
+ try {
1067
+ this.client.session = this.signClient.session.get(persistedSessionTopic);
1068
+ } catch (error) {
1069
+ this.logger.error(error, "Failed to get persisted session topic");
1070
+ }
1071
+ }
1072
+ try {
1073
+ const supportedNamespaces = await this.fetchRpcRequest(
1074
+ JSON.stringify({
1075
+ id: jsonrpcUtils.payloadId(),
1076
+ jsonrpc: "2.0",
1077
+ method: "wc_pos_supportedNetworks",
1078
+ params: {}
1079
+ })
1080
+ );
1081
+ this.logger.debug(
1082
+ {
1083
+ supportedNamespaces: supportedNamespaces.result.namespaces
1084
+ },
1085
+ "Received supported namespaces/networks"
1086
+ );
1087
+ this.supportedNamespaces = supportedNamespaces.result.namespaces;
1088
+ } catch (error) {
1089
+ this.logger.error(error, "Failed to fetch supported namespaces/networks");
1090
+ }
1091
+ }
1092
+ // ---------- Private ----------------------------------------------- //
1093
+ composeNamespaces(paymentIntents) {
1094
+ this.logger.debug({ paymentIntents }, "Composing namespaces");
1095
+ const namespaces = {};
1096
+ paymentIntents.forEach((paymentIntent) => {
1097
+ var _a;
1098
+ const {
1099
+ token: { network }
1100
+ } = paymentIntent;
1101
+ const { namespace } = utils.parseChainId(network.chainId);
1102
+ const namespaceDetails = this.supportedNamespaces.find((ns) => ns.name === namespace);
1103
+ if (!namespaceDetails) {
1104
+ throw new Error(`Namespace not supported: ${namespace}`);
1105
+ }
1106
+ namespaces[namespace] = {
1107
+ methods: namespaceDetails.methods,
1108
+ chains: [...((_a = namespaces[namespace]) == null ? void 0 : _a.chains) || [], network.chainId],
1109
+ events: namespaceDetails.events
1110
+ };
1111
+ });
1112
+ this.logger.debug({ namespaces }, "Composed namespaces");
1113
+ return namespaces;
1114
+ }
1115
+ }
1116
+
1117
+ var __defProp = Object.defineProperty;
1118
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1119
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
1120
+ class POSClient$1 extends IPOSClient {
1121
+ constructor(opts) {
1122
+ super(opts);
1123
+ __publicField(this, "name");
1124
+ __publicField(this, "events", new events.exports());
1125
+ __publicField(this, "engine");
1126
+ __publicField(this, "metadata");
1127
+ __publicField(this, "session");
1128
+ // ---------- Events ----------------------------------------------- //
1129
+ __publicField(this, "on", (name, listener) => {
1130
+ return this.engine.on(name, listener);
1131
+ });
1132
+ __publicField(this, "once", (name, listener) => {
1133
+ return this.engine.once(name, listener);
1134
+ });
1135
+ __publicField(this, "off", (name, listener) => {
1136
+ return this.engine.off(name, listener);
1137
+ });
1138
+ __publicField(this, "removeListener", (name, listener) => {
1139
+ return this.engine.removeListener(name, listener);
1140
+ });
1141
+ // ---------- Engine ----------------------------------------------- //
1142
+ __publicField(this, "setTokens", async (params) => {
1143
+ try {
1144
+ return await this.engine.setTokens(params);
1145
+ } catch (error) {
1146
+ this.engine.logger.error(error.message);
1147
+ throw error;
1148
+ }
1149
+ });
1150
+ __publicField(this, "createPaymentIntent", async (params) => {
1151
+ try {
1152
+ return await this.engine.createPaymentIntent(params);
1153
+ } catch (error) {
1154
+ this.engine.logger.error(error.message);
1155
+ throw error;
1156
+ }
1157
+ });
1158
+ __publicField(this, "restart", async (params) => {
1159
+ try {
1160
+ return await this.engine.restart(params);
1161
+ } catch (error) {
1162
+ this.engine.logger.error(error.message);
1163
+ throw error;
1164
+ }
1165
+ });
1166
+ __publicField(this, "sendPaymentsToWallet", async () => {
1167
+ try {
1168
+ return await this.engine.sendPaymentsToWallet();
1169
+ } catch (error) {
1170
+ this.engine.logger.error(error.message);
1171
+ throw error;
1172
+ }
1173
+ });
1174
+ __publicField(this, "disconnect", async () => {
1175
+ try {
1176
+ return await this.engine.disconnect();
1177
+ } catch (error) {
1178
+ this.engine.logger.error(error.message);
1179
+ throw error;
1180
+ }
1181
+ });
1182
+ this.metadata = opts.metadata;
1183
+ this.name = CLIENT_CONTEXT;
1184
+ }
1185
+ static async init(opts) {
1186
+ const client = new POSClient$1(opts);
1187
+ await client.initialize();
1188
+ return client;
1189
+ }
1190
+ // ---------- Private ----------------------------------------------- //
1191
+ async initialize() {
1192
+ try {
1193
+ this.engine = new Engine(this);
1194
+ await this.engine.init();
1195
+ this.engine.logger.info(`POSClient Initialization Success`);
1196
+ } catch (error) {
1197
+ this.engine.logger.info(`POSClient Initialization Failure`);
1198
+ this.engine.logger.error(error.message);
1199
+ throw error;
1200
+ }
1201
+ }
1202
+ }
1203
+
1204
+ const POSClient = POSClient$1;
1205
+
1206
+ exports.CLIENT_CONTEXT = CLIENT_CONTEXT;
1207
+ exports.CLIENT_STORAGE_OPTIONS = CLIENT_STORAGE_OPTIONS;
1208
+ exports.CLIENT_STORAGE_PREFIX = CLIENT_STORAGE_PREFIX;
1209
+ exports.DEFAULT_LOGGER_LEVEL = DEFAULT_LOGGER_LEVEL;
1210
+ exports.DEFAULT_NAMESPACES = DEFAULT_NAMESPACES;
1211
+ exports.IPOSClient = IPOSClient;
1212
+ exports.IPOSClientEngine = IPOSClientEngine;
1213
+ exports.MAX_TRANSACTION_STATUS_CHECKS = MAX_TRANSACTION_STATUS_CHECKS;
1214
+ exports.POSClient = POSClient;
1215
+ exports.POS_CLIENT_VERSION = POS_CLIENT_VERSION;
1216
+ exports.PROTOCOL = PROTOCOL;
1217
+ exports.PROTOCOL_VERSION = PROTOCOL_VERSION;
1218
+ exports.RPC_ERROR_CODES = RPC_ERROR_CODES;
1219
+ exports.RPC_URL = RPC_URL;
1220
+ exports["default"] = POSClient$1;
2
1221
  //# sourceMappingURL=index.cjs.map