@walletconnect/pos-client 1.0.7 → 1.0.8
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 +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/index.umd.js +13 -14
- package/dist/index.umd.js.map +1 -1
- package/dist/tsconfig.tsbuildinfo +1 -1
- package/package.json +6 -6
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{SignClient as ie}from"@walletconnect/sign-client";import{payloadId as L}from"@walletconnect/jsonrpc-utils";import{isValidChainId as re,parseChainId as b}from"@walletconnect/utils";import{pino as oe}from"@walletconnect/logger";var P={exports:{}},I=typeof Reflect=="object"?Reflect:null,$=I&&typeof I.apply=="function"?I.apply:function(n,s,e){return Function.prototype.apply.call(n,s,e)},E;I&&typeof I.ownKeys=="function"?E=I.ownKeys:Object.getOwnPropertySymbols?E=function(n){return Object.getOwnPropertyNames(n).concat(Object.getOwnPropertySymbols(n))}:E=function(n){return Object.getOwnPropertyNames(n)};function ae(r){console&&console.warn&&console.warn(r)}var x=Number.isNaN||function(n){return n!==n};function u(){u.init.call(this)}P.exports=u,P.exports.once=pe,u.EventEmitter=u,u.prototype._events=void 0,u.prototype._eventsCount=0,u.prototype._maxListeners=void 0;var F=10;function C(r){if(typeof r!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof r)}Object.defineProperty(u,"defaultMaxListeners",{enumerable:!0,get:function(){return F},set:function(r){if(typeof r!="number"||r<0||x(r))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+r+".");F=r}}),u.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},u.prototype.setMaxListeners=function(n){if(typeof n!="number"||n<0||x(n))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+n+".");return this._maxListeners=n,this};function W(r){return r._maxListeners===void 0?u.defaultMaxListeners:r._maxListeners}u.prototype.getMaxListeners=function(){return W(this)},u.prototype.emit=function(n){for(var s=[],e=1;e<arguments.length;e++)s.push(arguments[e]);var t=n==="error",i=this._events;if(i!==void 0)t=t&&i.error===void 0;else if(!t)return!1;if(t){var o;if(s.length>0&&(o=s[0]),o instanceof Error)throw o;var a=new Error("Unhandled error."+(o?" ("+o.message+")":""));throw a.context=o,a}var l=i[n];if(l===void 0)return!1;if(typeof l=="function")$(l,this,s);else for(var c=l.length,m=D(l,c),e=0;e<c;++e)$(m[e],this,s);return!0};function q(r,n,s,e){var t,i,o;if(C(s),i=r._events,i===void 0?(i=r._events=Object.create(null),r._eventsCount=0):(i.newListener!==void 0&&(r.emit("newListener",n,s.listener?s.listener:s),i=r._events),o=i[n]),o===void 0)o=i[n]=s,++r._eventsCount;else if(typeof o=="function"?o=i[n]=e?[s,o]:[o,s]:e?o.unshift(s):o.push(s),t=W(r),t>0&&o.length>t&&!o.warned){o.warned=!0;var a=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(n)+" listeners added. Use emitter.setMaxListeners() to increase limit");a.name="MaxListenersExceededWarning",a.emitter=r,a.type=n,a.count=o.length,ae(a)}return r}u.prototype.addListener=function(n,s){return q(this,n,s,!1)},u.prototype.on=u.prototype.addListener,u.prototype.prependListener=function(n,s){return q(this,n,s,!0)};function ce(){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 M(r,n,s){var e={fired:!1,wrapFn:void 0,target:r,type:n,listener:s},t=ce.bind(e);return t.listener=s,e.wrapFn=t,t}u.prototype.once=function(n,s){return C(s),this.on(n,M(this,n,s)),this},u.prototype.prependOnceListener=function(n,s){return C(s),this.prependListener(n,M(this,n,s)),this},u.prototype.removeListener=function(n,s){var e,t,i,o,a;if(C(s),t=this._events,t===void 0)return this;if(e=t[n],e===void 0)return this;if(e===s||e.listener===s)--this._eventsCount===0?this._events=Object.create(null):(delete t[n],t.removeListener&&this.emit("removeListener",n,e.listener||s));else if(typeof e!="function"){for(i=-1,o=e.length-1;o>=0;o--)if(e[o]===s||e[o].listener===s){a=e[o].listener,i=o;break}if(i<0)return this;i===0?e.shift():le(e,i),e.length===1&&(t[n]=e[0]),t.removeListener!==void 0&&this.emit("removeListener",n,a||s)}return this},u.prototype.off=u.prototype.removeListener,u.prototype.removeAllListeners=function(n){var s,e,t;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[n]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete e[n]),this;if(arguments.length===0){var i=Object.keys(e),o;for(t=0;t<i.length;++t)o=i[t],o!=="removeListener"&&this.removeAllListeners(o);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(s=e[n],typeof s=="function")this.removeListener(n,s);else if(s!==void 0)for(t=s.length-1;t>=0;t--)this.removeListener(n,s[t]);return this};function U(r,n,s){var e=r._events;if(e===void 0)return[];var t=e[n];return t===void 0?[]:typeof t=="function"?s?[t.listener||t]:[t]:s?de(t):D(t,t.length)}u.prototype.listeners=function(n){return U(this,n,!0)},u.prototype.rawListeners=function(n){return U(this,n,!1)},u.listenerCount=function(r,n){return typeof r.listenerCount=="function"?r.listenerCount(n):V.call(r,n)},u.prototype.listenerCount=V;function V(r){var n=this._events;if(n!==void 0){var s=n[r];if(typeof s=="function")return 1;if(s!==void 0)return s.length}return 0}u.prototype.eventNames=function(){return this._eventsCount>0?E(this._events):[]};function D(r,n){for(var s=new Array(n),e=0;e<n;++e)s[e]=r[e];return s}function le(r,n){for(;n+1<r.length;n++)r[n]=r[n+1];r.pop()}function de(r){for(var n=new Array(r.length),s=0;s<n.length;++s)n[s]=r[s].listener||r[s];return n}function pe(r,n){return new Promise(function(s,e){function t(o){r.removeListener(n,i),e(o)}function i(){typeof r.removeListener=="function"&&r.removeListener("error",t),s([].slice.call(arguments))}G(r,n,i,{once:!0}),n!=="error"&&ue(r,t,{once:!0})})}function ue(r,n,s){typeof r.on=="function"&&G(r,"error",n,s)}function G(r,n,s,e){if(typeof r.on=="function")e.once?r.once(n,s):r.on(n,s);else if(typeof r.addEventListener=="function")r.addEventListener(n,function t(i){e.once&&r.removeEventListener(n,t),s(i)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof r)}const J="wc",he=2,N="POSClient",me=`${J}@2:${N}:`,O={database:":memory:",customStoragePrefix:"@walletconnect/pos-client"},K="1.0.0",z=50,k="error",H=[{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"}],X=({projectId:r,deviceId:n})=>`https://rpc.walletconnect.org/v1/json-rpc?projectId=${r}&st=node&sv=js-pos-${K}&deviceId=${n}`,R={"-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 B{constructor(n){this.opts=n}}class Q{constructor(n){this.client=n}}const Y=r=>{const{supportedNamespaces:n,token:s}=r,{network:e,symbol:t,standard:i,address:o}=s;if(!e||!t||!i||!o||!re(e?.chainId))return!1;const{namespace:a}=b(e.chainId),l=n.find(c=>c.name.toLowerCase()===a.toLowerCase());if(!l)throw new Error(`Unsupported token namespace: ${a}`);if(!l.assetNamespaces.map(c=>c.toLowerCase()).includes(i?.toLowerCase()))throw new Error(`Unsupported token standard: ${i} for namespace: ${a}`);return!0},ge=r=>{const{supportedNamespaces:n,paymentIntent:s}=r,{token:e,amount:t,recipient:i}=s;return!(!e||!t||!i||!Y({supportedNamespaces:n,token:e}))},Z=r=>{let n,s;return async()=>n!==void 0?n:s||(s=r(),n=await s,n)};var fe=Object.defineProperty,ve=(r,n,s)=>n in r?fe(r,n,{enumerable:!0,configurable:!0,writable:!0,value:s}):r[n]=s,p=(r,n,s)=>ve(r,typeof n!="symbol"?n+"":n,s);class ye extends Q{constructor(n){var s;super(n),p(this,"signClient"),p(this,"logger"),p(this,"tokens",[]),p(this,"supportedNamespaces",H),p(this,"paymentIntents",{}),p(this,"transactions",{}),p(this,"paymentsSendingInProgress",{}),p(this,"manualControl",{}),p(this,"init",async()=>{var e,t;this.signClient=await ie.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:((t=this.client.opts.loggerOptions)==null?void 0:t.signLevel)||k}),this.signClient.events.on("session_delete",({topic:i})=>{this.cleanup({sessionTopic:i}),this.emit("disconnected",{sessionTopic:i})});try{this.logger.debug("Fetching supported namespaces/networks");const i=await this.fetchRpcRequest({payload:JSON.stringify({id:L(),jsonrpc:"2.0",method:"wc_pos_supportedNetworks",params:{}}),userId:""});this.logger.debug({supportedNamespaces:i.result.namespaces},"Received supported namespaces/networks"),this.supportedNamespaces=i.result.namespaces}catch(i){this.logger.error(i,"Failed to fetch supported namespaces/networks")}}),p(this,"setTokens",async e=>{const{tokens:t}=e;this.logger.debug({tokens:t},"Setting tokens"),t.forEach(i=>{if(!Y({token:i,supportedNamespaces:this.supportedNamespaces}))throw new Error(`Invalid token: ${JSON.stringify(i)}`)}),await new Promise(i=>{this.tokens=t,i()}),this.logger.debug({tokens:t},"Tokens set")}),p(this,"createPaymentIntent",async e=>{const{paymentIntents:t,sessionTopic:i,userId:o}=e;this.logger.debug({paymentIntents:t,userId:o},"Creating payment intent");const a=e.manualControl||!1;if(t.length===0)throw new Error("No payment intents provided");for(const h of t)if(!ge({paymentIntent:h,supportedNamespaces:this.supportedNamespaces}))throw new Error(`Invalid payment intent: ${JSON.stringify(h)}`);if(this.logger.debug({paymentIntents:t,userId:o},"Payment intent validation success"),i){this.manualControl[i]=a;try{this.setPaymentIntents({sessionTopic:i,paymentIntents:t,userId:o}),this.validateApprovedNamespacesWithPaymentIntents(i),a||await this.sendPaymentsToWallet({sessionTopic:i,userId:o});return}catch(h){this.logger.error(h),await this.disconnect({sessionTopic:i})}}const l=this.composeNamespacesFromPaymentIntents(t),{uri:c,approval:m}=await this.signClient.connect({optionalNamespaces:l});if(this.logger.debug({uri:c,userId:o},"Connected to the WalletConnect network"),!c)throw this.client.events.emit("connection_failed",{error:{message:"Failed to connect to the WalletConnect network",code:4001},userId:o}),new Error("Failed to connect to the WalletConnect network");const d=Z(m);if(this.emit("await_approval",{approval:d,paymentIntents:t,userId:o,manualControl:a}),this.logger.debug("Emitted await_approval event"),this.emit("qr_ready",{uri:c,userId:o}),this.logger.debug({uri:c,userId:o},"Emitted qr_ready event"),a){const h=await d();this.manualControl[h.topic]=a}}),p(this,"restart",async e=>{this.logger.debug({params:e},"Restarting");const{reinit:t,sessionTopic:i,userId:o}=e||{};if(t){this.tokens=[],await this.disconnect({sessionTopic:i}),this.logger.debug("Restarted: Cleared payment intents, transactions and disconnected");return}const a=this.getSessionTopic(i),l=this.manualControl[a],c=this.paymentIntents[a];if(!c||!(c!=null&&c.length))throw new Error("No payment intents found for session topic: "+a);await this.createPaymentIntent({paymentIntents:c,manualControl:l,userId:o,sessionTopic:a}),this.logger.debug({paymentIntents:c,userId:o},"Restarted: Created payment intent flow from the beginning")}),p(this,"connect",async e=>{const{userId:t}=e,i=!0,o=this.composeNamespacesFromTokens(),{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},userId:t}),new Error("Failed to connect to the WalletConnect network");const c=Z(l);this.emit("await_approval",{approval:c,manualControl:i,paymentIntents:[],userId:t}),this.logger.debug({userId:t},"Emitted await_approval event"),this.emit("qr_ready",{uri:a,userId:t}),this.logger.debug({uri:a,userId:t},"Emitted qr_ready event");const m=await c();return this.manualControl[m.topic]=i,m}),p(this,"emit",(e,t)=>(this.logger.debug({event:e,args:t},"Emit"),this.client.events.emit(e,t))),p(this,"on",(e,t)=>(this.logger.debug({event:e,listener:t},"On"),this.client.events.on(e,t))),p(this,"once",(e,t)=>(this.logger.debug({event:e,listener:t},"Once"),this.client.events.once(e,t))),p(this,"off",(e,t)=>(this.logger.debug({event:e,listener:t},"Off"),this.client.events.off(e,t))),p(this,"removeListener",(e,t)=>(this.logger.debug({event:e,listener:t},"Remove listener"),this.client.events.removeListener(e,t))),p(this,"prepareTransactionsFromPaymentIntents",async e=>{var t,i,o,a,l,c;const{sessionTopic:m,userId:d}=e,h=this.getSessionTopic(m),g=this.paymentIntents[h];if(!g)throw new Error("No payment intents found for session topic: "+h);const f=this.signClient.session.get(h);this.logger.debug({sessionTopic:h,userId:d},"Preparing transactions from payment intents");const y=[];for(const ee of g){const{token:w,amount:te,recipient:ne}=ee,{namespace:A}=b(w.network.chainId),j=(o=(i=(t=f.namespaces)==null?void 0:t[A])==null?void 0:i.accounts)==null?void 0:o.find(se=>se.includes(`${w.network.chainId}:`));if(!j)throw new Error(`Address not found in session for chain id: ${w.network.chainId}, approved addresses: ${(c=(l=(a=f.namespaces)==null?void 0:a[A])==null?void 0:l.accounts)==null?void 0:c.join(", ")}`);y.push({asset:`${w.network.chainId}/${w.standard.toLowerCase()}:${w.address}`,recipient:ne,amount:te,sender:j})}this.logger.debug({sessionTopic:f.topic,transactions:y,userId:d},"Prepared transactions from payment intents");const T={id:L(),jsonrpc:"2.0",method:"wc_pos_buildTransactions",params:{paymentIntents:y}};this.logger.debug({payload:T,userId:d},"Fetching wc_pos_buildTransactions");const S=await this.fetchRpcRequest({payload:JSON.stringify(T),userId:d});this.logger.debug({response:S,userId:d},"Received wc_pos_buildTransactions"),this.transactions[f.topic]=S.result.transactions,this.logger.debug({transactions:this.transactions[f.topic],userId:d},"Payment intent to transactions map set")}),p(this,"sendPaymentsToWallet",async(e={})=>{const{sessionTopic:t,userId:i}=e,o=this.getSessionTopic(t);if(!o)throw new Error("No session topic found, call createPaymentIntent() first");if(this.paymentsSendingInProgress[o])throw new Error("Payments are already being sent, please wait for them to complete");this.paymentsSendingInProgress[o]=!0;try{await this.prepareTransactionsFromPaymentIntents({sessionTopic:o,userId:i}),await this.sendTransactionsToWallet({sessionTopic:o,userId:i})}catch(a){throw this.logger.error(a,"Error while sending payments to wallet"),this.paymentsSendingInProgress[o]=!1,a}this.paymentsSendingInProgress[o]=!1}),p(this,"sendTransactionsToWallet",async e=>{const{sessionTopic:t,userId:i}=e,o=this.transactions[t],a=this.paymentIntents[t];if(!o||!a)throw new Error("No transactions or payment intents to send, call createPaymentIntent() first");if(o.length!==a.length)throw new Error(`Mismatch between transactions (${o.length}) and payment intents (${a.length}). The RPC response returned an unexpected number of transactions.`);this.logger.debug({transactions:o,sessionTopic:t,userId:i},"Sending transactions to wallet");for(let l=0;l<o.length;l++){const c=o[l],m=a[l];try{this.emit("payment_requested",{paymentIntent:m,transaction:c,sessionTopic:t,userId:i}),this.logger.debug({transactionId:c.id,userId:i},"Emitted payment_requested event");let d;try{d=await this.signClient.request({topic:t,request:{method:c.method,params:c.params},chainId:c.chainId}),this.logger.debug({transactionId:c.id,result:d,userId:i},"Wallet responded to payment request")}catch(h){throw this.logger.error(h,"Error while sending payment request"),this.emit("payment_rejected",{error:{message:h?.message,code:4001},paymentIntent:m,sessionTopic:t,userId:i}),h}this.emit("payment_broadcasted",{paymentIntent:m,transaction:c,result:d,sessionTopic:t,userId:i}),this.logger.debug({transactionId:c.id,userId:i},"Emitted payment_broadcasted event"),await this.awaitPaymentConfirmed({transaction:c,result:d,sessionTopic:t,userId:i}),await new Promise(h=>setTimeout(h,1e3))}catch(d){this.logger.error(d,"Error while awaiting payment confirmed")}}this.manualControl[t]!==!0&&await this.disconnect({sessionTopic:t})}),p(this,"awaitPaymentConfirmed",async e=>{const{transaction:t,result:i,sessionTopic:o,userId:a}=e;try{this.logger.debug({transactionId:t.id,result:i},"Awaiting payment confirmed");const l={id:L(),jsonrpc:"2.0",method:"wc_pos_checkTransaction",params:{id:t.id,sendResult:typeof i=="string"?i:JSON.stringify(i)}};let c=0,m;for(;!m;){if(c>=z)throw new Error(`Transaction status not found for id: ${t.id}`);c++;const d=await this.fetchRpcRequest({payload:JSON.stringify(l),userId:a});if(this.logger.debug({transactionId:t.id,response:d},"Received wc_pos_checkTransaction"),d.result.status==="CONFIRMED"){this.logger.debug({response:d,userId:a},"Transaction status confirmed"),this.emit("payment_successful",{transaction:t,result:i,sessionTopic:o,userId:a}),m=d.result;break}else if(d.result.status==="FAILED"){this.logger.debug({response:d},"Transaction failed"),this.emit("payment_failed",{error:{message:d.result.error,code:4001},transaction:i,sessionTopic:o,userId:a}),m=d.result;break}else d.result.status==="PENDING"&&(this.logger.debug({response:d,userId:a},"Transaction pending"),await new Promise(h=>setTimeout(h,d.result.checkIn||1e3)))}}catch(l){this.logger.error(l,"Error while awaiting payment confirmations"),this.emit("payment_failed",{error:{message:l?.message,code:4001},transaction:t,sessionTopic:o,userId:a})}}),p(this,"setupEventHandlers",()=>{this.on("await_approval",async({approval:e,paymentIntents:t,userId:i,manualControl:o})=>{try{this.logger.debug("On await_approval");const a=await e();this.setPaymentIntents({sessionTopic:a.topic,paymentIntents:t}),await this.onSessionConnected({session:a,userId:i,manualControl:o})}catch(a){this.logger.error(a,"Error while awaiting approval"),this.emit("connection_rejected",{error:{message:a?.message,code:4001},userId:i})}})}),p(this,"onSessionConnected",async e=>{const{session:t,userId:i,manualControl:o}=e;this.logger.debug({sessionTopic:t.topic,userId:i},"On session connected"),this.emit("connected",{session:t,userId:i}),await this.signClient.session.update(t.topic,{sessionConfig:{disableDeepLink:!0}}),this.logger.debug({sessionTopic:t.topic,userId:i},"Disabled deep links for session"),this.logger.debug({sessionTopic:t.topic,userId:i},"Emitted connected event"),o!==!0&&await this.sendPaymentsToWallet({sessionTopic:t.topic,userId:i})}),p(this,"disconnect",async(e={})=>{try{const{sessionTopic:t}=e,i=this.getSessionTopic(t);if(!i)return;this.cleanup({sessionTopic:i}),await this.signClient.disconnect({topic:i,reason:{code:4001,message:"User disconnected"}})}catch(t){this.logger.error(t,"Error while disconnecting")}}),p(this,"fetchRpcRequest",async e=>{var t,i,o,a,l,c;const{payload:m,userId:d}=e;this.logger.debug({url:this.getRpcUrl(),payload:m,userId:d},"Fetching RPC request");const h=await fetch(this.getRpcUrl(),{method:"POST",body:m});let g;try{g=await h.json()}catch(f){this.logger.error(f,"Error while getting json data from RPC response")}if(this.logger.debug({data:g},"Received RPC request response"),!h.ok||!g||g!=null&&g.error){const f=((t=g?.error)==null?void 0:t.code)||-18900,y=(i=R)!=null&&i[f]?`${(o=R)==null?void 0:o[f]}: ${(a=g?.error)==null?void 0:a.message}`:((l=g?.error)==null?void 0:l.message)||"Failed to parse RPC response";throw this.emit("payment_failed",{error:{message:y,code:f},transaction:"",sessionTopic:((c=this.client.session)==null?void 0:c.topic)||"",userId:d}),new Error(y)}return g}),p(this,"validateApprovedNamespacesWithPaymentIntents",e=>{var t,i,o,a,l,c,m;this.validateSessionTopic(e);const d=this.signClient.session.get(e),h=(t=this.paymentIntents)==null?void 0:t[e];if(!d||!h)throw new Error("No session or payment intents found");for(const g of h){const{token:f}=g,{namespace:y}=b(f.network.chainId);if(!((a=(o=(i=d.namespaces)==null?void 0:i[y])==null?void 0:o.accounts)!=null&&a.find(T=>T.includes(`${f.network.chainId}:`))))throw new Error(`Address not found in session for chain id: ${f.network.chainId}, approved addresses: ${(m=(c=(l=d.namespaces)==null?void 0:l[y])==null?void 0:c.accounts)==null?void 0:m.join(", ")}`)}}),p(this,"setPaymentIntents",e=>{const{sessionTopic:t,paymentIntents:i,userId:o}=e;this.paymentIntents[t]=i,this.logger.debug({paymentIntents:i,userId:o},"Payment intents set")}),p(this,"cleanup",(e={})=>{const{sessionTopic:t}=e;t&&(delete this.paymentIntents[t],delete this.transactions[t],delete this.manualControl[t],delete this.paymentsSendingInProgress[t],this.logger.debug({sessionTopic:t},"Cleaned up payment intents and transactions"))}),p(this,"getRpcUrl",()=>X({projectId:this.client.opts.projectId,deviceId:this.client.opts.deviceId})),p(this,"validateSessionTopic",e=>{if(e)try{this.signClient.session.get(e)}catch(t){throw this.logger.error(t,`No session found for topic: ${e}`),new Error(`No session found for topic: ${e}`)}}),p(this,"getSessionTopic",e=>{var t;if(!e&&this.client.sessions.length>1)throw new Error("Multiple sessions found, please specify the session topic in the params: { sessionTopic: '...' }");const i=e||((t=this.client.session)==null?void 0:t.topic);if(!i)throw new Error("No session topic found. Please provide a sessionTopic or establish a session first.");return this.validateSessionTopic(i),i}),this.signClient={},this.logger=oe({name:this.client.name,level:((s=this.client.opts.loggerOptions)==null?void 0:s.posLevel)||k}),this.setupEventHandlers()}composeNamespacesFromTokens(){const n=this.tokens;if(this.logger.debug({tokens:n},"Composing namespaces from tokens"),n.length===0)throw new Error("No set tokens to compose namespaces from, call setTokens() first");const s={};return n.forEach(e=>{var t;const{network:i}=e,{namespace:o}=b(i.chainId),a=this.supportedNamespaces.find(l=>l.name===o);if(!a)throw new Error(`Namespace not supported: ${o}`);s[o]={methods:a.methods,chains:[...((t=s[o])==null?void 0:t.chains)||[],i.chainId],events:a.events}}),this.logger.debug({namespaces:s},"Composed namespaces"),s}composeNamespacesFromPaymentIntents(n){this.logger.debug({paymentIntents:n},"Composing namespaces");const s={};return n.forEach(e=>{var t;const{token:{network:i}}=e,{namespace:o}=b(i.chainId),a=this.supportedNamespaces.find(l=>l.name===o);if(!a)throw new Error(`Namespace not supported: ${o}`);s[o]={methods:a.methods,chains:[...((t=s[o])==null?void 0:t.chains)||[],i.chainId],events:a.events}}),this.logger.debug({namespaces:s},"Composed namespaces"),s}}var we=Object.defineProperty,Ie=(r,n,s)=>n in r?we(r,n,{enumerable:!0,configurable:!0,writable:!0,value:s}):r[n]=s,v=(r,n,s)=>Ie(r,typeof n!="symbol"?n+"":n,s);class _ extends B{constructor(n){super(n),v(this,"name"),v(this,"events",new P.exports),v(this,"engine"),v(this,"metadata"),v(this,"on",(s,e)=>this.engine.on(s,e)),v(this,"once",(s,e)=>this.engine.once(s,e)),v(this,"off",(s,e)=>this.engine.off(s,e)),v(this,"removeListener",(s,e)=>this.engine.removeListener(s,e)),v(this,"setTokens",async s=>{try{return await this.engine.setTokens(s)}catch(e){throw this.engine.logger.error(e.message),e}}),v(this,"createPaymentIntent",async s=>{try{return await this.engine.createPaymentIntent(s)}catch(e){throw this.engine.logger.error(e.message),e}}),v(this,"restart",async s=>{try{return await this.engine.restart(s)}catch(e){throw this.engine.logger.error(e.message),e}}),v(this,"sendPaymentsToWallet",async s=>{try{return await this.engine.sendPaymentsToWallet(s)}catch(e){throw this.engine.logger.error(e.message),e}}),v(this,"disconnect",async s=>{try{return await this.engine.disconnect(s)}catch(e){throw this.engine.logger.error(e.message),e}}),v(this,"connect",async s=>{try{return await this.engine.connect(s)}catch(e){throw this.engine.logger.error(e.message),e}}),this.metadata=n.metadata,this.name=N,this.engine=new ye(this)}static async init(n){const s=new _(n);return await s.initialize(),s}get sessions(){return this.engine.signClient.session.getAll()}get session(){return this.sessions[0]}async initialize(){try{await this.engine.init(),this.engine.logger.info("POSClient Initialization Success")}catch(n){throw this.engine.logger.info("POSClient Initialization Failure"),this.engine.logger.error(n.message),n}}}const be=_;export{N as CLIENT_CONTEXT,O as CLIENT_STORAGE_OPTIONS,me as CLIENT_STORAGE_PREFIX,k as DEFAULT_LOGGER_LEVEL,H as DEFAULT_NAMESPACES,B as IPOSClient,Q as IPOSClientEngine,z as MAX_TRANSACTION_STATUS_CHECKS,be as POSClient,K as POS_CLIENT_VERSION,J as PROTOCOL,he as PROTOCOL_VERSION,R as RPC_ERROR_CODES,X as RPC_URL,_ as default};
|
|
1
|
+
import{SignClient as B}from"@walletconnect/sign-client";import{payloadId as O}from"@walletconnect/jsonrpc-utils";import{isValidChainId as Q,parseChainId as T}from"@walletconnect/utils";import{pino as Y}from"@walletconnect/logger";function Z(f){return f&&f.__esModule&&Object.prototype.hasOwnProperty.call(f,"default")?f.default:f}var P={exports:{}},x;function ee(){if(x)return P.exports;x=1;var f=typeof Reflect=="object"?Reflect:null,u=f&&typeof f.apply=="function"?f.apply:function(s,o,c){return Function.prototype.apply.call(s,o,c)},t;f&&typeof f.ownKeys=="function"?t=f.ownKeys:Object.getOwnPropertySymbols?t=function(s){return Object.getOwnPropertyNames(s).concat(Object.getOwnPropertySymbols(s))}:t=function(s){return Object.getOwnPropertyNames(s)};function e(r){console&&console.warn&&console.warn(r)}var i=Number.isNaN||function(s){return s!==s};function n(){n.init.call(this)}P.exports=n,P.exports.once=N,n.EventEmitter=n,n.prototype._events=void 0,n.prototype._eventsCount=0,n.prototype._maxListeners=void 0;var a=10;function d(r){if(typeof r!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof r)}Object.defineProperty(n,"defaultMaxListeners",{enumerable:!0,get:function(){return a},set:function(r){if(typeof r!="number"||r<0||i(r))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+r+".");a=r}}),n.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},n.prototype.setMaxListeners=function(s){if(typeof s!="number"||s<0||i(s))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+s+".");return this._maxListeners=s,this};function l(r){return r._maxListeners===void 0?n.defaultMaxListeners:r._maxListeners}n.prototype.getMaxListeners=function(){return l(this)},n.prototype.emit=function(s){for(var o=[],c=1;c<arguments.length;c++)o.push(arguments[c]);var p=s==="error",m=this._events;if(m!==void 0)p=p&&m.error===void 0;else if(!p)return!1;if(p){var h;if(o.length>0&&(h=o[0]),h instanceof Error)throw h;var w=new Error("Unhandled error."+(h?" ("+h.message+")":""));throw w.context=h,w}var E=m[s];if(E===void 0)return!1;if(typeof E=="function")u(E,this,o);else for(var $=E.length,X=C(E,$),c=0;c<$;++c)u(X[c],this,o);return!0};function y(r,s,o,c){var p,m,h;if(d(o),m=r._events,m===void 0?(m=r._events=Object.create(null),r._eventsCount=0):(m.newListener!==void 0&&(r.emit("newListener",s,o.listener?o.listener:o),m=r._events),h=m[s]),h===void 0)h=m[s]=o,++r._eventsCount;else if(typeof h=="function"?h=m[s]=c?[o,h]:[h,o]:c?h.unshift(o):h.push(o),p=l(r),p>0&&h.length>p&&!h.warned){h.warned=!0;var w=new Error("Possible EventEmitter memory leak detected. "+h.length+" "+String(s)+" listeners added. Use emitter.setMaxListeners() to increase limit");w.name="MaxListenersExceededWarning",w.emitter=r,w.type=s,w.count=h.length,e(w)}return r}n.prototype.addListener=function(s,o){return y(this,s,o,!1)},n.prototype.on=n.prototype.addListener,n.prototype.prependListener=function(s,o){return y(this,s,o,!0)};function g(){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 v(r,s,o){var c={fired:!1,wrapFn:void 0,target:r,type:s,listener:o},p=g.bind(c);return p.listener=o,c.wrapFn=p,p}n.prototype.once=function(s,o){return d(o),this.on(s,v(this,s,o)),this},n.prototype.prependOnceListener=function(s,o){return d(o),this.prependListener(s,v(this,s,o)),this},n.prototype.removeListener=function(s,o){var c,p,m,h,w;if(d(o),p=this._events,p===void 0)return this;if(c=p[s],c===void 0)return this;if(c===o||c.listener===o)--this._eventsCount===0?this._events=Object.create(null):(delete p[s],p.removeListener&&this.emit("removeListener",s,c.listener||o));else if(typeof c!="function"){for(m=-1,h=c.length-1;h>=0;h--)if(c[h]===o||c[h].listener===o){w=c[h].listener,m=h;break}if(m<0)return this;m===0?c.shift():_(c,m),c.length===1&&(p[s]=c[0]),p.removeListener!==void 0&&this.emit("removeListener",s,w||o)}return this},n.prototype.off=n.prototype.removeListener,n.prototype.removeAllListeners=function(s){var o,c,p;if(c=this._events,c===void 0)return this;if(c.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):c[s]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete c[s]),this;if(arguments.length===0){var m=Object.keys(c),h;for(p=0;p<m.length;++p)h=m[p],h!=="removeListener"&&this.removeAllListeners(h);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(o=c[s],typeof o=="function")this.removeListener(s,o);else if(o!==void 0)for(p=o.length-1;p>=0;p--)this.removeListener(s,o[p]);return this};function I(r,s,o){var c=r._events;if(c===void 0)return[];var p=c[s];return p===void 0?[]:typeof p=="function"?o?[p.listener||p]:[p]:o?L(p):C(p,p.length)}n.prototype.listeners=function(s){return I(this,s,!0)},n.prototype.rawListeners=function(s){return I(this,s,!1)},n.listenerCount=function(r,s){return typeof r.listenerCount=="function"?r.listenerCount(s):b.call(r,s)},n.prototype.listenerCount=b;function b(r){var s=this._events;if(s!==void 0){var o=s[r];if(typeof o=="function")return 1;if(o!==void 0)return o.length}return 0}n.prototype.eventNames=function(){return this._eventsCount>0?t(this._events):[]};function C(r,s){for(var o=new Array(s),c=0;c<s;++c)o[c]=r[c];return o}function _(r,s){for(;s+1<r.length;s++)r[s]=r[s+1];r.pop()}function L(r){for(var s=new Array(r.length),o=0;o<s.length;++o)s[o]=r[o].listener||r[o];return s}function N(r,s){return new Promise(function(o,c){function p(h){r.removeListener(s,m),c(h)}function m(){typeof r.removeListener=="function"&&r.removeListener("error",p),o([].slice.call(arguments))}A(r,s,m,{once:!0}),s!=="error"&&H(r,p,{once:!0})})}function H(r,s,o){typeof r.on=="function"&&A(r,"error",s,o)}function A(r,s,o,c){if(typeof r.on=="function")c.once?r.once(s,o):r.on(s,o);else if(typeof r.addEventListener=="function")r.addEventListener(s,function p(m){c.once&&r.removeEventListener(s,p),o(m)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof r)}return P.exports}var te=ee(),ne=Z(te);const F="wc",se=2,k="POSClient",ie=`${F}@2:${k}:`,R={database:":memory:",customStoragePrefix:"@walletconnect/pos-client"},W="1.0.0",q=50,S="error",M=[{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"}],U=({projectId:f,deviceId:u})=>`https://rpc.walletconnect.org/v1/json-rpc?projectId=${f}&st=node&sv=js-pos-${W}&deviceId=${u}`,j={"-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 V{constructor(u){this.opts=u}}class D{constructor(u){this.client=u}}const G=f=>{const{supportedNamespaces:u,token:t}=f,{network:e,symbol:i,standard:n,address:a}=t;if(!e||!i||!n||!a||!Q(e?.chainId))return!1;const{namespace:d}=T(e.chainId),l=u.find(y=>y.name.toLowerCase()===d.toLowerCase());if(!l)throw new Error(`Unsupported token namespace: ${d}`);if(!l.assetNamespaces.map(y=>y.toLowerCase()).includes(n?.toLowerCase()))throw new Error(`Unsupported token standard: ${n} for namespace: ${d}`);return!0},re=f=>{const{supportedNamespaces:u,paymentIntent:t}=f,{token:e,amount:i,recipient:n}=t;return!(!e||!i||!n||!G({supportedNamespaces:u,token:e}))},J=f=>{let u,t;return async()=>u!==void 0?u:t||(t=f(),u=await t,u)};class oe extends D{constructor(u){super(u),this.tokens=[],this.supportedNamespaces=M,this.paymentIntents={},this.transactions={},this.paymentsSendingInProgress={},this.manualControl={},this.init=async()=>{this.signClient=await B.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:this.client.opts.storageOptions?.databaseName||R.database},customStoragePrefix:R.customStoragePrefix,logger:this.client.opts.loggerOptions?.signLevel||S}),this.signClient.events.on("session_delete",({topic:t})=>{this.cleanup({sessionTopic:t}),this.emit("disconnected",{sessionTopic:t})});try{this.logger.debug("Fetching supported namespaces/networks");const t=await this.fetchRpcRequest({payload:JSON.stringify({id:O(),jsonrpc:"2.0",method:"wc_pos_supportedNetworks",params:{}}),userId:""});this.logger.debug({supportedNamespaces:t.result.namespaces},"Received supported namespaces/networks"),this.supportedNamespaces=t.result.namespaces}catch(t){this.logger.error(t,"Failed to fetch supported namespaces/networks")}},this.setTokens=async t=>{const{tokens:e}=t;this.logger.debug({tokens:e},"Setting tokens"),e.forEach(i=>{if(!G({token:i,supportedNamespaces:this.supportedNamespaces}))throw new Error(`Invalid token: ${JSON.stringify(i)}`)}),await new Promise(i=>{this.tokens=e,i()}),this.logger.debug({tokens:e},"Tokens set")},this.createPaymentIntent=async t=>{const{paymentIntents:e,sessionTopic:i,userId:n}=t;this.logger.debug({paymentIntents:e,userId:n},"Creating payment intent");const a=t.manualControl||!1;if(e.length===0)throw new Error("No payment intents provided");for(const v of e)if(!re({paymentIntent:v,supportedNamespaces:this.supportedNamespaces}))throw new Error(`Invalid payment intent: ${JSON.stringify(v)}`);if(this.logger.debug({paymentIntents:e,userId:n},"Payment intent validation success"),i){this.manualControl[i]=a;try{this.setPaymentIntents({sessionTopic:i,paymentIntents:e,userId:n}),this.validateApprovedNamespacesWithPaymentIntents(i),a||await this.sendPaymentsToWallet({sessionTopic:i,userId:n});return}catch(v){this.logger.error(v),await this.disconnect({sessionTopic:i})}}const d=this.composeNamespacesFromPaymentIntents(e),{uri:l,approval:y}=await this.signClient.connect({optionalNamespaces:d});if(this.logger.debug({uri:l,userId:n},"Connected to the WalletConnect network"),!l)throw this.client.events.emit("connection_failed",{error:{message:"Failed to connect to the WalletConnect network",code:4001},userId:n}),new Error("Failed to connect to the WalletConnect network");const g=J(y);if(this.emit("await_approval",{approval:g,paymentIntents:e,userId:n,manualControl:a}),this.logger.debug("Emitted await_approval event"),this.emit("qr_ready",{uri:l,userId:n}),this.logger.debug({uri:l,userId:n},"Emitted qr_ready event"),a){const v=await g();this.manualControl[v.topic]=a}},this.restart=async t=>{this.logger.debug({params:t},"Restarting");const{reinit:e,sessionTopic:i,userId:n}=t||{};if(e){this.tokens=[],await this.disconnect({sessionTopic:i}),this.logger.debug("Restarted: Cleared payment intents, transactions and disconnected");return}const a=this.getSessionTopic(i),d=this.manualControl[a],l=this.paymentIntents[a];if(!l||!l?.length)throw new Error("No payment intents found for session topic: "+a);await this.createPaymentIntent({paymentIntents:l,manualControl:d,userId:n,sessionTopic:a}),this.logger.debug({paymentIntents:l,userId:n},"Restarted: Created payment intent flow from the beginning")},this.connect=async t=>{const{userId:e}=t,i=!0,n=this.composeNamespacesFromTokens(),{uri:a,approval:d}=await this.signClient.connect({optionalNamespaces:n});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},userId:e}),new Error("Failed to connect to the WalletConnect network");const l=J(d);this.emit("await_approval",{approval:l,manualControl:i,paymentIntents:[],userId:e}),this.logger.debug({userId:e},"Emitted await_approval event"),this.emit("qr_ready",{uri:a,userId:e}),this.logger.debug({uri:a,userId:e},"Emitted qr_ready event");const y=await l();return this.manualControl[y.topic]=i,y},this.emit=(t,e)=>(this.logger.debug({event:t,args:e},"Emit"),this.client.events.emit(t,e)),this.on=(t,e)=>(this.logger.debug({event:t,listener:e},"On"),this.client.events.on(t,e)),this.once=(t,e)=>(this.logger.debug({event:t,listener:e},"Once"),this.client.events.once(t,e)),this.off=(t,e)=>(this.logger.debug({event:t,listener:e},"Off"),this.client.events.off(t,e)),this.removeListener=(t,e)=>(this.logger.debug({event:t,listener:e},"Remove listener"),this.client.events.removeListener(t,e)),this.prepareTransactionsFromPaymentIntents=async t=>{const{sessionTopic:e,userId:i}=t,n=this.getSessionTopic(e),a=this.paymentIntents[n];if(!a)throw new Error("No payment intents found for session topic: "+n);const d=this.signClient.session.get(n);this.logger.debug({sessionTopic:n,userId:i},"Preparing transactions from payment intents");const l=[];for(const v of a){const{token:I,amount:b,recipient:C}=v,{namespace:_}=T(I.network.chainId),L=d.namespaces?.[_]?.accounts?.find(N=>N.includes(`${I.network.chainId}:`));if(!L)throw new Error(`Address not found in session for chain id: ${I.network.chainId}, approved addresses: ${d.namespaces?.[_]?.accounts?.join(", ")}`);l.push({asset:`${I.network.chainId}/${I.standard.toLowerCase()}:${I.address}`,recipient:C,amount:b,sender:L})}this.logger.debug({sessionTopic:d.topic,transactions:l,userId:i},"Prepared transactions from payment intents");const y={id:O(),jsonrpc:"2.0",method:"wc_pos_buildTransactions",params:{paymentIntents:l}};this.logger.debug({payload:y,userId:i},"Fetching wc_pos_buildTransactions");const g=await this.fetchRpcRequest({payload:JSON.stringify(y),userId:i});this.logger.debug({response:g,userId:i},"Received wc_pos_buildTransactions"),this.transactions[d.topic]=g.result.transactions,this.logger.debug({transactions:this.transactions[d.topic],userId:i},"Payment intent to transactions map set")},this.sendPaymentsToWallet=async(t={})=>{const{sessionTopic:e,userId:i}=t,n=this.getSessionTopic(e);if(!n)throw new Error("No session topic found, call createPaymentIntent() first");if(this.paymentsSendingInProgress[n])throw new Error("Payments are already being sent, please wait for them to complete");this.paymentsSendingInProgress[n]=!0;try{await this.prepareTransactionsFromPaymentIntents({sessionTopic:n,userId:i}),await this.sendTransactionsToWallet({sessionTopic:n,userId:i})}catch(a){throw this.logger.error(a,"Error while sending payments to wallet"),this.paymentsSendingInProgress[n]=!1,a}this.paymentsSendingInProgress[n]=!1},this.sendTransactionsToWallet=async t=>{const{sessionTopic:e,userId:i}=t,n=this.transactions[e],a=this.paymentIntents[e];if(!n||!a)throw new Error("No transactions or payment intents to send, call createPaymentIntent() first");if(n.length!==a.length)throw new Error(`Mismatch between transactions (${n.length}) and payment intents (${a.length}). The RPC response returned an unexpected number of transactions.`);this.logger.debug({transactions:n,sessionTopic:e,userId:i},"Sending transactions to wallet");for(let d=0;d<n.length;d++){const l=n[d],y=a[d];try{this.emit("payment_requested",{paymentIntent:y,transaction:l,sessionTopic:e,userId:i}),this.logger.debug({transactionId:l.id,userId:i},"Emitted payment_requested event");let g;try{g=await this.signClient.request({topic:e,request:{method:l.method,params:l.params},chainId:l.chainId}),this.logger.debug({transactionId:l.id,result:g,userId:i},"Wallet responded to payment request")}catch(v){throw this.logger.error(v,"Error while sending payment request"),this.emit("payment_rejected",{error:{message:v?.message,code:4001},paymentIntent:y,sessionTopic:e,userId:i}),v}this.emit("payment_broadcasted",{paymentIntent:y,transaction:l,result:g,sessionTopic:e,userId:i}),this.logger.debug({transactionId:l.id,userId:i},"Emitted payment_broadcasted event"),await this.awaitPaymentConfirmed({transaction:l,result:g,sessionTopic:e,userId:i}),await new Promise(v=>setTimeout(v,1e3))}catch(g){this.logger.error(g,"Error while awaiting payment confirmed")}}this.manualControl[e]!==!0&&await this.disconnect({sessionTopic:e})},this.awaitPaymentConfirmed=async t=>{const{transaction:e,result:i,sessionTopic:n,userId:a}=t;try{this.logger.debug({transactionId:e.id,result:i},"Awaiting payment confirmed");const d={id:O(),jsonrpc:"2.0",method:"wc_pos_checkTransaction",params:{id:e.id,sendResult:typeof i=="string"?i:JSON.stringify(i)}};let l=0,y;for(;!y;){if(l>=q)throw new Error(`Transaction status not found for id: ${e.id}`);l++;const g=await this.fetchRpcRequest({payload:JSON.stringify(d),userId:a});if(this.logger.debug({transactionId:e.id,response:g},"Received wc_pos_checkTransaction"),g.result.status==="CONFIRMED"){this.logger.debug({response:g,userId:a},"Transaction status confirmed"),this.emit("payment_successful",{transaction:e,result:i,sessionTopic:n,userId:a}),y=g.result;break}else if(g.result.status==="FAILED"){this.logger.debug({response:g},"Transaction failed"),this.emit("payment_failed",{error:{message:g.result.error,code:4001},transaction:i,sessionTopic:n,userId:a}),y=g.result;break}else g.result.status==="PENDING"&&(this.logger.debug({response:g,userId:a},"Transaction pending"),await new Promise(v=>setTimeout(v,g.result.checkIn||1e3)))}}catch(d){this.logger.error(d,"Error while awaiting payment confirmations"),this.emit("payment_failed",{error:{message:d?.message,code:4001},transaction:e,sessionTopic:n,userId:a})}},this.setupEventHandlers=()=>{this.on("await_approval",async({approval:t,paymentIntents:e,userId:i,manualControl:n})=>{try{this.logger.debug("On await_approval");const a=await t();this.setPaymentIntents({sessionTopic:a.topic,paymentIntents:e}),await this.onSessionConnected({session:a,userId:i,manualControl:n})}catch(a){this.logger.error(a,"Error while awaiting approval"),this.emit("connection_rejected",{error:{message:a?.message,code:4001},userId:i})}})},this.onSessionConnected=async t=>{const{session:e,userId:i,manualControl:n}=t;this.logger.debug({sessionTopic:e.topic,userId:i},"On session connected"),this.emit("connected",{session:e,userId:i}),await this.signClient.session.update(e.topic,{sessionConfig:{disableDeepLink:!0}}),this.logger.debug({sessionTopic:e.topic,userId:i},"Disabled deep links for session"),this.logger.debug({sessionTopic:e.topic,userId:i},"Emitted connected event"),n!==!0&&await this.sendPaymentsToWallet({sessionTopic:e.topic,userId:i})},this.disconnect=async(t={})=>{try{const{sessionTopic:e}=t,i=this.getSessionTopic(e);if(!i)return;this.cleanup({sessionTopic:i}),await this.signClient.disconnect({topic:i,reason:{code:4001,message:"User disconnected"}})}catch(e){this.logger.error(e,"Error while disconnecting")}},this.fetchRpcRequest=async t=>{const{payload:e,userId:i}=t;this.logger.debug({url:this.getRpcUrl(),payload:e,userId:i},"Fetching RPC request");const n=await fetch(this.getRpcUrl(),{method:"POST",body:e});let a;try{a=await n.json()}catch(d){this.logger.error(d,"Error while getting json data from RPC response")}if(this.logger.debug({data:a},"Received RPC request response"),!n.ok||!a||a?.error){const d=a?.error?.code||-18900,l=j?.[d]?`${j?.[d]}: ${a?.error?.message}`:a?.error?.message||"Failed to parse RPC response";throw this.emit("payment_failed",{error:{message:l,code:d},transaction:"",sessionTopic:this.client.session?.topic||"",userId:i}),new Error(l)}return a},this.validateApprovedNamespacesWithPaymentIntents=t=>{this.validateSessionTopic(t);const e=this.signClient.session.get(t),i=this.paymentIntents?.[t];if(!e||!i)throw new Error("No session or payment intents found");for(const n of i){const{token:a}=n,{namespace:d}=T(a.network.chainId);if(!e.namespaces?.[d]?.accounts?.find(l=>l.includes(`${a.network.chainId}:`)))throw new Error(`Address not found in session for chain id: ${a.network.chainId}, approved addresses: ${e.namespaces?.[d]?.accounts?.join(", ")}`)}},this.setPaymentIntents=t=>{const{sessionTopic:e,paymentIntents:i,userId:n}=t;this.paymentIntents[e]=i,this.logger.debug({paymentIntents:i,userId:n},"Payment intents set")},this.cleanup=(t={})=>{const{sessionTopic:e}=t;e&&(delete this.paymentIntents[e],delete this.transactions[e],delete this.manualControl[e],delete this.paymentsSendingInProgress[e],this.logger.debug({sessionTopic:e},"Cleaned up payment intents and transactions"))},this.getRpcUrl=()=>U({projectId:this.client.opts.projectId,deviceId:this.client.opts.deviceId}),this.validateSessionTopic=t=>{if(t)try{this.signClient.session.get(t)}catch(e){throw this.logger.error(e,`No session found for topic: ${t}`),new Error(`No session found for topic: ${t}`)}},this.getSessionTopic=t=>{if(!t&&this.client.sessions.length>1)throw new Error("Multiple sessions found, please specify the session topic in the params: { sessionTopic: '...' }");const e=t||this.client.session?.topic;if(!e)throw new Error("No session topic found. Please provide a sessionTopic or establish a session first.");return this.validateSessionTopic(e),e},this.signClient={},this.logger=Y({name:this.client.name,level:this.client.opts.loggerOptions?.posLevel||S}),this.setupEventHandlers()}composeNamespacesFromTokens(){const u=this.tokens;if(this.logger.debug({tokens:u},"Composing namespaces from tokens"),u.length===0)throw new Error("No set tokens to compose namespaces from, call setTokens() first");const t={};return u.forEach(e=>{const{network:i}=e,{namespace:n}=T(i.chainId),a=this.supportedNamespaces.find(d=>d.name===n);if(!a)throw new Error(`Namespace not supported: ${n}`);t[n]={methods:a.methods,chains:[...t[n]?.chains||[],i.chainId],events:a.events}}),this.logger.debug({namespaces:t},"Composed namespaces"),t}composeNamespacesFromPaymentIntents(u){this.logger.debug({paymentIntents:u},"Composing namespaces");const t={};return u.forEach(e=>{const{token:{network:i}}=e,{namespace:n}=T(i.chainId),a=this.supportedNamespaces.find(d=>d.name===n);if(!a)throw new Error(`Namespace not supported: ${n}`);t[n]={methods:a.methods,chains:[...t[n]?.chains||[],i.chainId],events:a.events}}),this.logger.debug({namespaces:t},"Composed namespaces"),t}}let K=class z extends V{constructor(u){super(u),this.events=new ne,this.on=(t,e)=>this.engine.on(t,e),this.once=(t,e)=>this.engine.once(t,e),this.off=(t,e)=>this.engine.off(t,e),this.removeListener=(t,e)=>this.engine.removeListener(t,e),this.setTokens=async t=>{try{return await this.engine.setTokens(t)}catch(e){throw this.engine.logger.error(e.message),e}},this.createPaymentIntent=async t=>{try{return await this.engine.createPaymentIntent(t)}catch(e){throw this.engine.logger.error(e.message),e}},this.restart=async t=>{try{return await this.engine.restart(t)}catch(e){throw this.engine.logger.error(e.message),e}},this.sendPaymentsToWallet=async t=>{try{return await this.engine.sendPaymentsToWallet(t)}catch(e){throw this.engine.logger.error(e.message),e}},this.disconnect=async t=>{try{return await this.engine.disconnect(t)}catch(e){throw this.engine.logger.error(e.message),e}},this.connect=async t=>{try{return await this.engine.connect(t)}catch(e){throw this.engine.logger.error(e.message),e}},this.metadata=u.metadata,this.name=k,this.engine=new oe(this)}static async init(u){const t=new z(u);return await t.initialize(),t}get sessions(){return this.engine.signClient.session.getAll()}get session(){return this.sessions[0]}async initialize(){try{await this.engine.init(),this.engine.logger.info("POSClient Initialization Success")}catch(u){throw this.engine.logger.info("POSClient Initialization Failure"),this.engine.logger.error(u.message),u}}};const ae=K;export{k as CLIENT_CONTEXT,R as CLIENT_STORAGE_OPTIONS,ie as CLIENT_STORAGE_PREFIX,S as DEFAULT_LOGGER_LEVEL,M as DEFAULT_NAMESPACES,V as IPOSClient,D as IPOSClientEngine,q as MAX_TRANSACTION_STATUS_CHECKS,ae as POSClient,W as POS_CLIENT_VERSION,F as PROTOCOL,se as PROTOCOL_VERSION,j as RPC_ERROR_CODES,U as RPC_URL,K as default};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|