@walletconnect/ethereum-provider 2.23.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,667 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var j=require("events"),w=require("@walletconnect/utils"),N=require("@walletconnect/universal-provider");function W(n){if(n&&n.__esModule)return n;var t=Object.create(null);return n&&Object.keys(n).forEach(function(e){if(e!=="default"){var s=Object.getOwnPropertyDescriptor(n,e);Object.defineProperty(t,e,s.get?s:{enumerable:!0,get:function(){return n[e]}})}}),t.default=n,Object.freeze(t)}const x="wc",q="ethereum_provider",$=`${x}@2:${q}:`,D="https://rpc.walletconnect.org/v1/",I=["eth_sendTransaction","personal_sign"],_=["eth_accounts","eth_requestAccounts","eth_sendRawTransaction","eth_sign","eth_signTransaction","eth_signTypedData","eth_signTypedData_v3","eth_signTypedData_v4","eth_sendTransaction","personal_sign","wallet_switchEthereumChain","wallet_addEthereumChain","wallet_getPermissions","wallet_requestPermissions","wallet_registerOnboarding","wallet_watchAsset","wallet_scanQRCode","wallet_sendCalls","wallet_getCapabilities","wallet_getCallsStatus","wallet_showCallsStatus"],C=["chainChanged","accountsChanged"],P=["chainChanged","accountsChanged","message","disconnect","connect"],U=async()=>{const{createAppKit:n}=await Promise.resolve().then(function(){return W(require("@reown/appkit/core"))});return n};var k=Object.defineProperty,z=Object.defineProperties,L=Object.getOwnPropertyDescriptors,A=Object.getOwnPropertySymbols,Q=Object.prototype.hasOwnProperty,K=Object.prototype.propertyIsEnumerable,O=(n,t,e)=>t in n?k(n,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):n[t]=e,v=(n,t)=>{for(var e in t||(t={}))Q.call(t,e)&&O(n,e,t[e]);if(A)for(var e of A(t))K.call(t,e)&&O(n,e,t[e]);return n},f=(n,t)=>z(n,L(t)),p=(n,t,e)=>O(n,typeof t!="symbol"?t+"":t,e);function E(n){return Number(n[0].split(":")[1])}function b(n){return`0x${n.toString(16)}`}function V(n){const{chains:t,optionalChains:e,methods:s,optionalMethods:i,events:a,optionalEvents:r,rpcMap:u}=n;if(!w.isValidArray(t))throw new Error("Invalid chains");const c={chains:t,methods:s||I,events:a||C,rpcMap:v({},t.length?{[E(t)]:u[E(t)]}:{})},l=a?.filter(d=>!C.includes(d)),o=s?.filter(d=>!I.includes(d));if(!e&&!r&&!i&&!(l!=null&&l.length)&&!(o!=null&&o.length))return{required:t.length?c:void 0};const m=l?.length&&o?.length||!e,h={chains:[...new Set(m?c.chains.concat(e||[]):e)],methods:[...new Set(c.methods.concat(i!=null&&i.length?i:_))],events:[...new Set(c.events.concat(r!=null&&r.length?r:P))],rpcMap:u};return{required:t.length?c:void 0,optional:e.length?h:void 0}}class y{constructor(){p(this,"events",new j.EventEmitter),p(this,"namespace","eip155"),p(this,"accounts",[]),p(this,"signer"),p(this,"chainId",1),p(this,"modal"),p(this,"rpc"),p(this,"STORAGE_KEY",$),p(this,"on",(t,e)=>(this.events.on(t,e),this)),p(this,"once",(t,e)=>(this.events.once(t,e),this)),p(this,"removeListener",(t,e)=>(this.events.removeListener(t,e),this)),p(this,"off",(t,e)=>(this.events.off(t,e),this)),p(this,"parseAccount",t=>this.isCompatibleChainId(t)?this.parseAccountId(t).address:t),this.signer={},this.rpc={}}static async init(t){const e=new y;return await e.initialize(t),e}async request(t,e){return await this.signer.request(t,this.formatChainId(this.chainId),e)}sendAsync(t,e,s){this.signer.sendAsync(t,e,this.formatChainId(this.chainId),s)}get connected(){return this.signer.client?this.signer.client.core.relayer.connected:!1}get connecting(){return this.signer.client?this.signer.client.core.relayer.connecting:!1}async enable(){return this.session||await this.connect(),await this.request({method:"eth_requestAccounts"})}async connect(t){var e;if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts(t);const{required:s,optional:i}=V(this.rpc);try{const a=await new Promise(async(u,c)=>{var l,o;this.rpc.showQrModal&&((l=this.modal)==null||l.open(),(o=this.modal)==null||o.subscribeState(h=>{!h.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),c(new Error("Connection request reset. Please try again.")))}));const m=t!=null&&t.scopedProperties?{[this.namespace]:t.scopedProperties}:void 0;await this.signer.connect(f(v({namespaces:v({},s&&{[this.namespace]:s})},i&&{optionalNamespaces:{[this.namespace]:i}}),{pairingTopic:t?.pairingTopic,scopedProperties:m})).then(h=>{u(h)}).catch(h=>{var d;(d=this.modal)==null||d.showErrorMessage("Unable to connect"),c(new Error(h.message))})});if(!a)return;const r=w.getAccountsFromNamespaces(a.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:r),this.setAccounts(r),this.events.emit("connect",{chainId:b(this.chainId)})}catch(a){throw this.signer.logger.error(a),a}finally{(e=this.modal)==null||e.close()}}async authenticate(t,e){var s;if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts({chains:t?.chains});try{const i=await new Promise(async(r,u)=>{var c,l;this.rpc.showQrModal&&((c=this.modal)==null||c.open(),(l=this.modal)==null||l.subscribeState(o=>{!o.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),u(new Error("Connection request reset. Please try again.")))})),await this.signer.authenticate(f(v({},t),{chains:this.rpc.chains}),e).then(o=>{r(o)}).catch(o=>{var m;(m=this.modal)==null||m.showErrorMessage("Unable to connect"),u(new Error(o.message))})}),a=i.session;if(a){const r=w.getAccountsFromNamespaces(a.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:r),this.setAccounts(r),this.events.emit("connect",{chainId:b(this.chainId)})}return i}catch(i){throw this.signer.logger.error(i),i}finally{(s=this.modal)==null||s.close()}}async disconnect(){this.session&&await this.signer.disconnect(),this.reset()}get isWalletConnect(){return!0}get session(){return this.signer.session}registerEventListeners(){this.signer.on("session_event",t=>{const{params:e}=t,{event:s}=e;s.name==="accountsChanged"?(this.accounts=this.parseAccounts(s.data),this.events.emit("accountsChanged",this.accounts)):s.name==="chainChanged"?this.setChainId(this.formatChainId(s.data)):this.events.emit(s.name,s.data),this.events.emit("session_event",t)}),this.signer.on("accountsChanged",t=>{this.accounts=this.parseAccounts(t),this.events.emit("accountsChanged",this.accounts)}),this.signer.on("chainChanged",t=>{const e=parseInt(t);this.chainId=e,this.events.emit("chainChanged",b(this.chainId)),this.persist()}),this.signer.on("session_update",t=>{this.events.emit("session_update",t)}),this.signer.on("session_delete",t=>{this.reset(),this.events.emit("session_delete",t),this.events.emit("disconnect",f(v({},w.getSdkError("USER_DISCONNECTED")),{data:t.topic,name:"USER_DISCONNECTED"}))}),this.signer.on("display_uri",t=>{this.events.emit("display_uri",t)})}switchEthereumChain(t){this.request({method:"wallet_switchEthereumChain",params:[{chainId:t.toString(16)}]})}isCompatibleChainId(t){return typeof t=="string"?t.startsWith(`${this.namespace}:`):!1}formatChainId(t){return`${this.namespace}:${t}`}parseChainId(t){return Number(t.split(":")[1])}setChainIds(t){const e=t.filter(s=>this.isCompatibleChainId(s)).map(s=>this.parseChainId(s));e.length&&(this.chainId=e[0],this.events.emit("chainChanged",b(this.chainId)),this.persist())}setChainId(t){if(this.isCompatibleChainId(t)){const e=this.parseChainId(t);this.chainId=e,this.switchEthereumChain(e)}}parseAccountId(t){const[e,s,i]=t.split(":");return{chainId:`${e}:${s}`,address:i}}setAccounts(t){this.accounts=t.filter(e=>this.parseChainId(this.parseAccountId(e).chainId)===this.chainId).map(e=>this.parseAccountId(e).address),this.events.emit("accountsChanged",this.accounts)}getRpcConfig(t){var e,s;const i=(e=t?.chains)!=null?e:[],a=(s=t?.optionalChains)!=null?s:[],r=i.concat(a);if(!r.length)throw new Error("No chains specified in either `chains` or `optionalChains`");const u=i.length?t?.methods||I:[],c=i.length?t?.events||C:[],l=t?.optionalMethods||[],o=t?.optionalEvents||[],m=t?.rpcMap||this.buildRpcMap(r,t.projectId),h=t?.qrModalOptions||void 0;return{chains:i?.map(d=>this.formatChainId(d)),optionalChains:a.map(d=>this.formatChainId(d)),methods:u,events:c,optionalMethods:l,optionalEvents:o,rpcMap:m,showQrModal:!!(t!=null&&t.showQrModal),qrModalOptions:h,projectId:t.projectId,metadata:t.metadata}}buildRpcMap(t,e){const s={};return t.forEach(i=>{s[i]=this.getRpcUrl(i,e)}),s}async initialize(t){var e;if(this.rpc=this.getRpcConfig(t),this.chainId=this.rpc.chains.length?E(this.rpc.chains):E(this.rpc.optionalChains),this.signer=await N.UniversalProvider.init({projectId:this.rpc.projectId,metadata:this.rpc.metadata,disableProviderPing:t.disableProviderPing,relayUrl:t.relayUrl,storage:t.storage,storageOptions:t.storageOptions,customStoragePrefix:t.customStoragePrefix,telemetryEnabled:t.telemetryEnabled,logger:t.logger}),this.registerEventListeners(),await this.loadPersistedSession(),this.rpc.showQrModal){let s;try{const i=await U(),{convertWCMToAppKitOptions:a}=await Promise.resolve().then(function(){return nt}),r=a(f(v({},this.rpc.qrModalOptions),{chains:[...new Set([...this.rpc.chains,...this.rpc.optionalChains])],metadata:this.rpc.metadata,projectId:this.rpc.projectId}));if(!r.networks.length)throw new Error("No networks found for WalletConnect");s=i(f(v({},r),{universalProvider:this.signer,manualWCControl:!0,enableMobileFullScreen:((e=this.rpc.qrModalOptions)==null?void 0:e.enableMobileFullScreen)===!0}))}catch(i){throw console.warn(i),new Error("To use QR modal, please install @reown/appkit package")}if(s)try{this.modal=s}catch(i){throw this.signer.logger.error(i),new Error("Could not generate WalletConnectModal Instance")}}}loadConnectOpts(t){if(!t)return;const{chains:e,optionalChains:s,rpcMap:i}=t;e&&w.isValidArray(e)&&(this.rpc.chains=e.map(a=>this.formatChainId(a)),e.forEach(a=>{this.rpc.rpcMap[a]=i?.[a]||this.getRpcUrl(a)})),s&&w.isValidArray(s)&&(this.rpc.optionalChains=[],this.rpc.optionalChains=s?.map(a=>this.formatChainId(a)),s.forEach(a=>{this.rpc.rpcMap[a]=i?.[a]||this.getRpcUrl(a)}))}getRpcUrl(t,e){var s;return((s=this.rpc.rpcMap)==null?void 0:s[t])||`${D}?chainId=eip155:${t}&projectId=${e||this.rpc.projectId}`}async loadPersistedSession(){if(this.session)try{const t=await this.signer.client.core.storage.getItem(`${this.STORAGE_KEY}/chainId`),e=this.session.namespaces[`${this.namespace}:${t}`]?this.session.namespaces[`${this.namespace}:${t}`]:this.session.namespaces[this.namespace];this.setChainIds(t?[this.formatChainId(t)]:e?.accounts),this.setAccounts(e?.accounts)}catch(t){this.signer.logger.error("Failed to load persisted session, clearing state..."),this.signer.logger.error(t),await this.disconnect().catch(e=>this.signer.logger.warn(e))}}reset(){this.chainId=1,this.accounts=[]}persist(){this.session&&this.signer.client.core.storage.setItem(`${this.STORAGE_KEY}/chainId`,this.chainId)}parseAccounts(t){return typeof t=="string"||t instanceof String?[this.parseAccount(t)]:t.map(e=>this.parseAccount(e))}}const F=y;var H=Object.defineProperty,G=Object.defineProperties,Y=Object.getOwnPropertyDescriptors,M=Object.getOwnPropertySymbols,B=Object.prototype.hasOwnProperty,X=Object.prototype.propertyIsEnumerable,S=(n,t,e)=>t in n?H(n,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):n[t]=e,T=(n,t)=>{for(var e in t||(t={}))B.call(t,e)&&S(n,e,t[e]);if(M)for(var e of M(t))X.call(t,e)&&S(n,e,t[e]);return n},J=(n,t)=>G(n,Y(t));function Z(n){if(n)return{"--w3m-font-family":n["--wcm-font-family"],"--w3m-accent":n["--wcm-accent-color"],"--w3m-color-mix":n["--wcm-background-color"],"--w3m-z-index":n["--wcm-z-index"]?Number(n["--wcm-z-index"]):void 0,"--w3m-qr-color":n["--wcm-accent-color"],"--w3m-font-size-master":n["--wcm-text-medium-regular-size"],"--w3m-border-radius-master":n["--wcm-container-border-radius"],"--w3m-color-mix-strength":0}}const tt=n=>{const[t,e]=n.split(":");return R({id:e,caipNetworkId:n,chainNamespace:t,name:"",nativeCurrency:{name:"",symbol:"",decimals:8},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}}})};function et(n){var t,e,s,i,a,r,u;const c=(t=n.chains)==null?void 0:t.map(tt).filter(Boolean);if(c.length===0)throw new Error("At least one chain must be specified");const l=c.find(m=>{var h;return m.id===((h=n.defaultChain)==null?void 0:h.id)}),o={projectId:n.projectId,networks:c,themeMode:n.themeMode,themeVariables:Z(n.themeVariables),chainImages:n.chainImages,connectorImages:n.walletImages,defaultNetwork:l,metadata:J(T({},n.metadata),{name:((e=n.metadata)==null?void 0:e.name)||"WalletConnect",description:((s=n.metadata)==null?void 0:s.description)||"Connect to WalletConnect-compatible wallets",url:((i=n.metadata)==null?void 0:i.url)||"https://walletconnect.org",icons:((a=n.metadata)==null?void 0:a.icons)||["https://walletconnect.org/walletconnect-logo.png"]}),showWallets:!0,featuredWalletIds:n.explorerRecommendedWalletIds==="NONE"?[]:Array.isArray(n.explorerRecommendedWalletIds)?n.explorerRecommendedWalletIds:[],excludeWalletIds:n.explorerExcludedWalletIds==="ALL"?[]:Array.isArray(n.explorerExcludedWalletIds)?n.explorerExcludedWalletIds:[],enableEIP6963:!1,enableInjected:!1,enableCoinbase:!0,enableWalletConnect:!0,features:{email:!1,socials:!1}};if((r=n.mobileWallets)!=null&&r.length||(u=n.desktopWallets)!=null&&u.length){const m=[...(n.mobileWallets||[]).map(g=>({id:g.id,name:g.name,links:g.links})),...(n.desktopWallets||[]).map(g=>({id:g.id,name:g.name,links:{native:g.links.native,universal:g.links.universal}}))],h=[...o.featuredWalletIds||[],...o.excludeWalletIds||[]],d=m.filter(g=>!h.includes(g.id));d.length&&(o.customWallets=d)}return o}function R(n){return T({formatters:void 0,fees:void 0,serializers:void 0},n)}var nt=Object.freeze({__proto__:null,convertWCMToAppKitOptions:et,defineChain:R});exports.EthereumProvider=F,exports.OPTIONAL_EVENTS=P,exports.OPTIONAL_METHODS=_,exports.REQUIRED_EVENTS=C,exports.REQUIRED_METHODS=I,exports.default=y;
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ var events = require('events');
6
+ var utils = require('@walletconnect/utils');
7
+ var universalProvider = require('@walletconnect/universal-provider');
8
+
9
+ function _interopNamespace(e) {
10
+ if (e && e.__esModule) return e;
11
+ var n = Object.create(null);
12
+ if (e) {
13
+ Object.keys(e).forEach(function (k) {
14
+ if (k !== 'default') {
15
+ var d = Object.getOwnPropertyDescriptor(e, k);
16
+ Object.defineProperty(n, k, d.get ? d : {
17
+ enumerable: true,
18
+ get: function () { return e[k]; }
19
+ });
20
+ }
21
+ });
22
+ }
23
+ n["default"] = e;
24
+ return Object.freeze(n);
25
+ }
26
+
27
+ const PROTOCOL = "wc";
28
+ const WC_VERSION = 2;
29
+ const CONTEXT = "ethereum_provider";
30
+ const STORAGE_KEY = `${PROTOCOL}@${WC_VERSION}:${CONTEXT}:`;
31
+ const RPC_URL = "https://rpc.walletconnect.org/v1/";
32
+
33
+ const REQUIRED_METHODS = ["eth_sendTransaction", "personal_sign"];
34
+ const OPTIONAL_METHODS = [
35
+ "eth_accounts",
36
+ "eth_requestAccounts",
37
+ "eth_sendRawTransaction",
38
+ "eth_sign",
39
+ "eth_signTransaction",
40
+ "eth_signTypedData",
41
+ "eth_signTypedData_v3",
42
+ "eth_signTypedData_v4",
43
+ "eth_sendTransaction",
44
+ "personal_sign",
45
+ "wallet_switchEthereumChain",
46
+ "wallet_addEthereumChain",
47
+ "wallet_getPermissions",
48
+ "wallet_requestPermissions",
49
+ "wallet_registerOnboarding",
50
+ "wallet_watchAsset",
51
+ "wallet_scanQRCode",
52
+ "wallet_sendCalls",
53
+ "wallet_getCapabilities",
54
+ "wallet_getCallsStatus",
55
+ "wallet_showCallsStatus"
56
+ ];
57
+ const REQUIRED_EVENTS = ["chainChanged", "accountsChanged"];
58
+ const OPTIONAL_EVENTS = [
59
+ "chainChanged",
60
+ "accountsChanged",
61
+ "message",
62
+ "disconnect",
63
+ "connect"
64
+ ];
65
+
66
+ const getAppkit = async () => {
67
+ const { createAppKit } = await Promise.resolve().then(function () { return /*#__PURE__*/_interopNamespace(require('@reown/appkit/core')); });
68
+ return createAppKit;
69
+ };
70
+
71
+ var __defProp$1 = Object.defineProperty;
72
+ var __defProps$1 = Object.defineProperties;
73
+ var __getOwnPropDescs$1 = Object.getOwnPropertyDescriptors;
74
+ var __getOwnPropSymbols$1 = Object.getOwnPropertySymbols;
75
+ var __hasOwnProp$1 = Object.prototype.hasOwnProperty;
76
+ var __propIsEnum$1 = Object.prototype.propertyIsEnumerable;
77
+ var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
78
+ var __spreadValues$1 = (a, b) => {
79
+ for (var prop in b || (b = {}))
80
+ if (__hasOwnProp$1.call(b, prop))
81
+ __defNormalProp$1(a, prop, b[prop]);
82
+ if (__getOwnPropSymbols$1)
83
+ for (var prop of __getOwnPropSymbols$1(b)) {
84
+ if (__propIsEnum$1.call(b, prop))
85
+ __defNormalProp$1(a, prop, b[prop]);
86
+ }
87
+ return a;
88
+ };
89
+ var __spreadProps$1 = (a, b) => __defProps$1(a, __getOwnPropDescs$1(b));
90
+ var __publicField = (obj, key, value) => __defNormalProp$1(obj, typeof key !== "symbol" ? key + "" : key, value);
91
+ function getEthereumChainId(chains) {
92
+ return Number(chains[0].split(":")[1]);
93
+ }
94
+ function toHexChainId(chainId) {
95
+ return `0x${chainId.toString(16)}`;
96
+ }
97
+ function buildNamespaces(params) {
98
+ const { chains, optionalChains, methods, optionalMethods, events, optionalEvents, rpcMap } = params;
99
+ if (!utils.isValidArray(chains)) {
100
+ throw new Error("Invalid chains");
101
+ }
102
+ const required = {
103
+ chains,
104
+ methods: methods || REQUIRED_METHODS,
105
+ events: events || REQUIRED_EVENTS,
106
+ rpcMap: __spreadValues$1({}, chains.length ? { [getEthereumChainId(chains)]: rpcMap[getEthereumChainId(chains)] } : {})
107
+ };
108
+ const eventsRequiringPermissions = events == null ? void 0 : events.filter((event) => !REQUIRED_EVENTS.includes(event));
109
+ const methodsRequiringPermissions = methods == null ? void 0 : methods.filter((event) => !REQUIRED_METHODS.includes(event));
110
+ if (!optionalChains && !optionalEvents && !optionalMethods && !(eventsRequiringPermissions == null ? void 0 : eventsRequiringPermissions.length) && !(methodsRequiringPermissions == null ? void 0 : methodsRequiringPermissions.length)) {
111
+ return { required: chains.length ? required : void 0 };
112
+ }
113
+ const shouldIncludeRequiredChains = (eventsRequiringPermissions == null ? void 0 : eventsRequiringPermissions.length) && (methodsRequiringPermissions == null ? void 0 : methodsRequiringPermissions.length) || !optionalChains;
114
+ const optional = {
115
+ chains: [
116
+ ...new Set(
117
+ shouldIncludeRequiredChains ? required.chains.concat(optionalChains || []) : optionalChains
118
+ )
119
+ ],
120
+ methods: [
121
+ ...new Set(
122
+ required.methods.concat((optionalMethods == null ? void 0 : optionalMethods.length) ? optionalMethods : OPTIONAL_METHODS)
123
+ )
124
+ ],
125
+ events: [
126
+ ...new Set(required.events.concat((optionalEvents == null ? void 0 : optionalEvents.length) ? optionalEvents : OPTIONAL_EVENTS))
127
+ ],
128
+ rpcMap
129
+ };
130
+ return {
131
+ required: chains.length ? required : void 0,
132
+ optional: optionalChains.length ? optional : void 0
133
+ };
134
+ }
135
+ class EthereumProvider$1 {
136
+ constructor() {
137
+ __publicField(this, "events", new events.EventEmitter());
138
+ __publicField(this, "namespace", "eip155");
139
+ __publicField(this, "accounts", []);
140
+ __publicField(this, "signer");
141
+ __publicField(this, "chainId", 1);
142
+ __publicField(this, "modal");
143
+ __publicField(this, "rpc");
144
+ __publicField(this, "STORAGE_KEY", STORAGE_KEY);
145
+ __publicField(this, "on", (event, listener) => {
146
+ this.events.on(event, listener);
147
+ return this;
148
+ });
149
+ __publicField(this, "once", (event, listener) => {
150
+ this.events.once(event, listener);
151
+ return this;
152
+ });
153
+ __publicField(this, "removeListener", (event, listener) => {
154
+ this.events.removeListener(event, listener);
155
+ return this;
156
+ });
157
+ __publicField(this, "off", (event, listener) => {
158
+ this.events.off(event, listener);
159
+ return this;
160
+ });
161
+ __publicField(this, "parseAccount", (payload) => {
162
+ return this.isCompatibleChainId(payload) ? this.parseAccountId(payload).address : payload;
163
+ });
164
+ this.signer = {};
165
+ this.rpc = {};
166
+ }
167
+ static async init(opts) {
168
+ const provider = new EthereumProvider$1();
169
+ await provider.initialize(opts);
170
+ return provider;
171
+ }
172
+ async request(args, expiry) {
173
+ return await this.signer.request(args, this.formatChainId(this.chainId), expiry);
174
+ }
175
+ sendAsync(args, callback, expiry) {
176
+ this.signer.sendAsync(args, callback, this.formatChainId(this.chainId), expiry);
177
+ }
178
+ get connected() {
179
+ if (!this.signer.client) return false;
180
+ return this.signer.client.core.relayer.connected;
181
+ }
182
+ get connecting() {
183
+ if (!this.signer.client) return false;
184
+ return this.signer.client.core.relayer.connecting;
185
+ }
186
+ async enable() {
187
+ if (!this.session) await this.connect();
188
+ const accounts = await this.request({ method: "eth_requestAccounts" });
189
+ return accounts;
190
+ }
191
+ async connect(opts) {
192
+ var _a;
193
+ if (!this.signer.client) {
194
+ throw new Error("Provider not initialized. Call init() first");
195
+ }
196
+ this.loadConnectOpts(opts);
197
+ const { required, optional } = buildNamespaces(this.rpc);
198
+ try {
199
+ const session = await new Promise(
200
+ async (resolve, reject) => {
201
+ var _a2, _b;
202
+ if (this.rpc.showQrModal) {
203
+ (_a2 = this.modal) == null ? void 0 : _a2.open();
204
+ (_b = this.modal) == null ? void 0 : _b.subscribeState((state) => {
205
+ if (!state.open && !this.signer.session) {
206
+ this.signer.abortPairingAttempt();
207
+ reject(new Error("Connection request reset. Please try again."));
208
+ }
209
+ });
210
+ }
211
+ const scopedProperties = (opts == null ? void 0 : opts.scopedProperties) ? { [this.namespace]: opts.scopedProperties } : void 0;
212
+ await this.signer.connect(__spreadProps$1(__spreadValues$1({
213
+ namespaces: __spreadValues$1({}, required && {
214
+ [this.namespace]: required
215
+ })
216
+ }, optional && {
217
+ optionalNamespaces: {
218
+ [this.namespace]: optional
219
+ }
220
+ }), {
221
+ pairingTopic: opts == null ? void 0 : opts.pairingTopic,
222
+ scopedProperties
223
+ })).then((session2) => {
224
+ resolve(session2);
225
+ }).catch((error) => {
226
+ var _a3;
227
+ (_a3 = this.modal) == null ? void 0 : _a3.showErrorMessage("Unable to connect");
228
+ reject(new Error(error.message));
229
+ });
230
+ }
231
+ );
232
+ if (!session) return;
233
+ const accounts = utils.getAccountsFromNamespaces(session.namespaces, [this.namespace]);
234
+ this.setChainIds(this.rpc.chains.length ? this.rpc.chains : accounts);
235
+ this.setAccounts(accounts);
236
+ this.events.emit("connect", { chainId: toHexChainId(this.chainId) });
237
+ } catch (error) {
238
+ this.signer.logger.error(error);
239
+ throw error;
240
+ } finally {
241
+ (_a = this.modal) == null ? void 0 : _a.close();
242
+ }
243
+ }
244
+ async authenticate(params, walletUniversalLink) {
245
+ var _a;
246
+ if (!this.signer.client) {
247
+ throw new Error("Provider not initialized. Call init() first");
248
+ }
249
+ this.loadConnectOpts({
250
+ chains: params == null ? void 0 : params.chains
251
+ });
252
+ try {
253
+ const result = await new Promise(
254
+ async (resolve, reject) => {
255
+ var _a2, _b;
256
+ if (this.rpc.showQrModal) {
257
+ (_a2 = this.modal) == null ? void 0 : _a2.open();
258
+ (_b = this.modal) == null ? void 0 : _b.subscribeState((state) => {
259
+ if (!state.open && !this.signer.session) {
260
+ this.signer.abortPairingAttempt();
261
+ reject(new Error("Connection request reset. Please try again."));
262
+ }
263
+ });
264
+ }
265
+ await this.signer.authenticate(
266
+ __spreadProps$1(__spreadValues$1({}, params), {
267
+ chains: this.rpc.chains
268
+ }),
269
+ walletUniversalLink
270
+ ).then((result2) => {
271
+ resolve(result2);
272
+ }).catch((error) => {
273
+ var _a3;
274
+ (_a3 = this.modal) == null ? void 0 : _a3.showErrorMessage("Unable to connect");
275
+ reject(new Error(error.message));
276
+ });
277
+ }
278
+ );
279
+ const session = result.session;
280
+ if (session) {
281
+ const accounts = utils.getAccountsFromNamespaces(session.namespaces, [this.namespace]);
282
+ this.setChainIds(this.rpc.chains.length ? this.rpc.chains : accounts);
283
+ this.setAccounts(accounts);
284
+ this.events.emit("connect", { chainId: toHexChainId(this.chainId) });
285
+ }
286
+ return result;
287
+ } catch (error) {
288
+ this.signer.logger.error(error);
289
+ throw error;
290
+ } finally {
291
+ (_a = this.modal) == null ? void 0 : _a.close();
292
+ }
293
+ }
294
+ async disconnect() {
295
+ if (this.session) {
296
+ await this.signer.disconnect();
297
+ }
298
+ this.reset();
299
+ }
300
+ get isWalletConnect() {
301
+ return true;
302
+ }
303
+ get session() {
304
+ return this.signer.session;
305
+ }
306
+ // ---------- Protected --------------------------------------------- //
307
+ registerEventListeners() {
308
+ this.signer.on("session_event", (payload) => {
309
+ const { params } = payload;
310
+ const { event } = params;
311
+ if (event.name === "accountsChanged") {
312
+ this.accounts = this.parseAccounts(event.data);
313
+ this.events.emit("accountsChanged", this.accounts);
314
+ } else if (event.name === "chainChanged") {
315
+ this.setChainId(this.formatChainId(event.data));
316
+ } else {
317
+ this.events.emit(event.name, event.data);
318
+ }
319
+ this.events.emit("session_event", payload);
320
+ });
321
+ this.signer.on("accountsChanged", (accounts) => {
322
+ this.accounts = this.parseAccounts(accounts);
323
+ this.events.emit("accountsChanged", this.accounts);
324
+ });
325
+ this.signer.on("chainChanged", (chainId) => {
326
+ const chain = parseInt(chainId);
327
+ this.chainId = chain;
328
+ this.events.emit("chainChanged", toHexChainId(this.chainId));
329
+ this.persist();
330
+ });
331
+ this.signer.on(
332
+ "session_update",
333
+ (payload) => {
334
+ this.events.emit("session_update", payload);
335
+ }
336
+ );
337
+ this.signer.on(
338
+ "session_delete",
339
+ (payload) => {
340
+ this.reset();
341
+ this.events.emit("session_delete", payload);
342
+ this.events.emit("disconnect", __spreadProps$1(__spreadValues$1({}, utils.getSdkError("USER_DISCONNECTED")), {
343
+ data: payload.topic,
344
+ name: "USER_DISCONNECTED"
345
+ }));
346
+ }
347
+ );
348
+ this.signer.on("display_uri", (uri) => {
349
+ this.events.emit("display_uri", uri);
350
+ });
351
+ }
352
+ switchEthereumChain(chainId) {
353
+ this.request({
354
+ method: "wallet_switchEthereumChain",
355
+ params: [{ chainId: chainId.toString(16) }]
356
+ });
357
+ }
358
+ isCompatibleChainId(chainId) {
359
+ return typeof chainId === "string" ? chainId.startsWith(`${this.namespace}:`) : false;
360
+ }
361
+ formatChainId(chainId) {
362
+ return `${this.namespace}:${chainId}`;
363
+ }
364
+ parseChainId(chainId) {
365
+ return Number(chainId.split(":")[1]);
366
+ }
367
+ setChainIds(chains) {
368
+ const compatible = chains.filter((x) => this.isCompatibleChainId(x));
369
+ const chainIds = compatible.map((c) => this.parseChainId(c));
370
+ if (chainIds.length) {
371
+ this.chainId = chainIds[0];
372
+ this.events.emit("chainChanged", toHexChainId(this.chainId));
373
+ this.persist();
374
+ }
375
+ }
376
+ setChainId(chain) {
377
+ if (this.isCompatibleChainId(chain)) {
378
+ const chainId = this.parseChainId(chain);
379
+ this.chainId = chainId;
380
+ this.switchEthereumChain(chainId);
381
+ }
382
+ }
383
+ parseAccountId(account) {
384
+ const [namespace, reference, address] = account.split(":");
385
+ const chainId = `${namespace}:${reference}`;
386
+ return { chainId, address };
387
+ }
388
+ setAccounts(accounts) {
389
+ this.accounts = accounts.filter((x) => this.parseChainId(this.parseAccountId(x).chainId) === this.chainId).map((x) => this.parseAccountId(x).address);
390
+ this.events.emit("accountsChanged", this.accounts);
391
+ }
392
+ getRpcConfig(opts) {
393
+ var _a, _b;
394
+ const requiredChains = (_a = opts == null ? void 0 : opts.chains) != null ? _a : [];
395
+ const optionalChains = (_b = opts == null ? void 0 : opts.optionalChains) != null ? _b : [];
396
+ const allChains = requiredChains.concat(optionalChains);
397
+ if (!allChains.length)
398
+ throw new Error("No chains specified in either `chains` or `optionalChains`");
399
+ const requiredMethods = requiredChains.length ? (opts == null ? void 0 : opts.methods) || REQUIRED_METHODS : [];
400
+ const requiredEvents = requiredChains.length ? (opts == null ? void 0 : opts.events) || REQUIRED_EVENTS : [];
401
+ const optionalMethods = (opts == null ? void 0 : opts.optionalMethods) || [];
402
+ const optionalEvents = (opts == null ? void 0 : opts.optionalEvents) || [];
403
+ const rpcMap = (opts == null ? void 0 : opts.rpcMap) || this.buildRpcMap(allChains, opts.projectId);
404
+ const qrModalOptions = (opts == null ? void 0 : opts.qrModalOptions) || void 0;
405
+ return {
406
+ chains: requiredChains == null ? void 0 : requiredChains.map((chain) => this.formatChainId(chain)),
407
+ optionalChains: optionalChains.map((chain) => this.formatChainId(chain)),
408
+ methods: requiredMethods,
409
+ events: requiredEvents,
410
+ optionalMethods,
411
+ optionalEvents,
412
+ rpcMap,
413
+ showQrModal: Boolean(opts == null ? void 0 : opts.showQrModal),
414
+ qrModalOptions,
415
+ projectId: opts.projectId,
416
+ metadata: opts.metadata
417
+ };
418
+ }
419
+ buildRpcMap(chains, projectId) {
420
+ const map = {};
421
+ chains.forEach((chain) => {
422
+ map[chain] = this.getRpcUrl(chain, projectId);
423
+ });
424
+ return map;
425
+ }
426
+ async initialize(opts) {
427
+ var _a;
428
+ this.rpc = this.getRpcConfig(opts);
429
+ this.chainId = this.rpc.chains.length ? getEthereumChainId(this.rpc.chains) : getEthereumChainId(this.rpc.optionalChains);
430
+ this.signer = await universalProvider.UniversalProvider.init({
431
+ projectId: this.rpc.projectId,
432
+ metadata: this.rpc.metadata,
433
+ disableProviderPing: opts.disableProviderPing,
434
+ relayUrl: opts.relayUrl,
435
+ storage: opts.storage,
436
+ storageOptions: opts.storageOptions,
437
+ customStoragePrefix: opts.customStoragePrefix,
438
+ telemetryEnabled: opts.telemetryEnabled,
439
+ logger: opts.logger
440
+ });
441
+ this.registerEventListeners();
442
+ await this.loadPersistedSession();
443
+ if (this.rpc.showQrModal) {
444
+ let appKit;
445
+ try {
446
+ const createAppKit = await getAppkit();
447
+ const { convertWCMToAppKitOptions } = await Promise.resolve().then(function () { return wcmToAppKit; });
448
+ const options = convertWCMToAppKitOptions(__spreadProps$1(__spreadValues$1({}, this.rpc.qrModalOptions), {
449
+ chains: [.../* @__PURE__ */ new Set([...this.rpc.chains, ...this.rpc.optionalChains])],
450
+ metadata: this.rpc.metadata,
451
+ projectId: this.rpc.projectId
452
+ }));
453
+ if (!options.networks.length) {
454
+ throw new Error("No networks found for WalletConnect");
455
+ }
456
+ appKit = createAppKit(__spreadProps$1(__spreadValues$1({}, options), {
457
+ universalProvider: this.signer,
458
+ manualWCControl: true,
459
+ enableMobileFullScreen: ((_a = this.rpc.qrModalOptions) == null ? void 0 : _a.enableMobileFullScreen) === true
460
+ }));
461
+ } catch (e) {
462
+ console.warn(e);
463
+ throw new Error("To use QR modal, please install @reown/appkit package");
464
+ }
465
+ if (appKit) {
466
+ try {
467
+ this.modal = appKit;
468
+ } catch (e) {
469
+ this.signer.logger.error(e);
470
+ throw new Error("Could not generate WalletConnectModal Instance");
471
+ }
472
+ }
473
+ }
474
+ }
475
+ loadConnectOpts(opts) {
476
+ if (!opts) return;
477
+ const { chains, optionalChains, rpcMap } = opts;
478
+ if (chains && utils.isValidArray(chains)) {
479
+ this.rpc.chains = chains.map((chain) => this.formatChainId(chain));
480
+ chains.forEach((chain) => {
481
+ this.rpc.rpcMap[chain] = (rpcMap == null ? void 0 : rpcMap[chain]) || this.getRpcUrl(chain);
482
+ });
483
+ }
484
+ if (optionalChains && utils.isValidArray(optionalChains)) {
485
+ this.rpc.optionalChains = [];
486
+ this.rpc.optionalChains = optionalChains == null ? void 0 : optionalChains.map((chain) => this.formatChainId(chain));
487
+ optionalChains.forEach((chain) => {
488
+ this.rpc.rpcMap[chain] = (rpcMap == null ? void 0 : rpcMap[chain]) || this.getRpcUrl(chain);
489
+ });
490
+ }
491
+ }
492
+ getRpcUrl(chainId, projectId) {
493
+ var _a;
494
+ const providedRpc = (_a = this.rpc.rpcMap) == null ? void 0 : _a[chainId];
495
+ return providedRpc || `${RPC_URL}?chainId=eip155:${chainId}&projectId=${projectId || this.rpc.projectId}`;
496
+ }
497
+ async loadPersistedSession() {
498
+ if (!this.session) return;
499
+ try {
500
+ const chainId = await this.signer.client.core.storage.getItem(`${this.STORAGE_KEY}/chainId`);
501
+ const namespace = this.session.namespaces[`${this.namespace}:${chainId}`] ? this.session.namespaces[`${this.namespace}:${chainId}`] : this.session.namespaces[this.namespace];
502
+ this.setChainIds(chainId ? [this.formatChainId(chainId)] : namespace == null ? void 0 : namespace.accounts);
503
+ this.setAccounts(namespace == null ? void 0 : namespace.accounts);
504
+ } catch (error) {
505
+ this.signer.logger.error("Failed to load persisted session, clearing state...");
506
+ this.signer.logger.error(error);
507
+ await this.disconnect().catch((error2) => this.signer.logger.warn(error2));
508
+ }
509
+ }
510
+ reset() {
511
+ this.chainId = 1;
512
+ this.accounts = [];
513
+ }
514
+ persist() {
515
+ if (!this.session) return;
516
+ this.signer.client.core.storage.setItem(`${this.STORAGE_KEY}/chainId`, this.chainId);
517
+ }
518
+ parseAccounts(payload) {
519
+ if (typeof payload === "string" || payload instanceof String) {
520
+ return [this.parseAccount(payload)];
521
+ }
522
+ return payload.map((account) => this.parseAccount(account));
523
+ }
524
+ }
525
+
526
+ const EthereumProvider = EthereumProvider$1;
527
+
528
+ var __defProp = Object.defineProperty;
529
+ var __defProps = Object.defineProperties;
530
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
531
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
532
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
533
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
534
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
535
+ var __spreadValues = (a, b) => {
536
+ for (var prop in b || (b = {}))
537
+ if (__hasOwnProp.call(b, prop))
538
+ __defNormalProp(a, prop, b[prop]);
539
+ if (__getOwnPropSymbols)
540
+ for (var prop of __getOwnPropSymbols(b)) {
541
+ if (__propIsEnum.call(b, prop))
542
+ __defNormalProp(a, prop, b[prop]);
543
+ }
544
+ return a;
545
+ };
546
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
547
+ function convertThemeVariables(wcmTheme) {
548
+ if (!wcmTheme) return void 0;
549
+ return {
550
+ "--w3m-font-family": wcmTheme["--wcm-font-family"],
551
+ "--w3m-accent": wcmTheme["--wcm-accent-color"],
552
+ "--w3m-color-mix": wcmTheme["--wcm-background-color"],
553
+ "--w3m-z-index": wcmTheme["--wcm-z-index"] ? Number(wcmTheme["--wcm-z-index"]) : void 0,
554
+ "--w3m-qr-color": wcmTheme["--wcm-accent-color"],
555
+ "--w3m-font-size-master": wcmTheme["--wcm-text-medium-regular-size"],
556
+ "--w3m-border-radius-master": wcmTheme["--wcm-container-border-radius"],
557
+ "--w3m-color-mix-strength": 0
558
+ };
559
+ }
560
+ const mapCaipIdToAppKitCaipNetwork = (caipId) => {
561
+ const [namespace, chainId] = caipId.split(":");
562
+ const chain = defineChain({
563
+ id: chainId,
564
+ caipNetworkId: caipId,
565
+ chainNamespace: namespace,
566
+ name: "",
567
+ nativeCurrency: {
568
+ name: "",
569
+ symbol: "",
570
+ decimals: 8
571
+ },
572
+ rpcUrls: {
573
+ default: { http: ["https://rpc.walletconnect.org/v1"] }
574
+ }
575
+ });
576
+ return chain;
577
+ };
578
+ function convertWCMToAppKitOptions(wcmConfig) {
579
+ var _a, _b, _c, _d, _e, _f, _g;
580
+ const networks = (_a = wcmConfig.chains) == null ? void 0 : _a.map(mapCaipIdToAppKitCaipNetwork).filter(Boolean);
581
+ if (networks.length === 0) {
582
+ throw new Error("At least one chain must be specified");
583
+ }
584
+ const defaultNetwork = networks.find((network) => {
585
+ var _a2;
586
+ return network.id === ((_a2 = wcmConfig.defaultChain) == null ? void 0 : _a2.id);
587
+ });
588
+ const appKitOptions = {
589
+ projectId: wcmConfig.projectId,
590
+ networks,
591
+ themeMode: wcmConfig.themeMode,
592
+ themeVariables: convertThemeVariables(wcmConfig.themeVariables),
593
+ chainImages: wcmConfig.chainImages,
594
+ connectorImages: wcmConfig.walletImages,
595
+ defaultNetwork,
596
+ metadata: __spreadProps(__spreadValues({}, wcmConfig.metadata), {
597
+ name: ((_b = wcmConfig.metadata) == null ? void 0 : _b.name) || "WalletConnect",
598
+ description: ((_c = wcmConfig.metadata) == null ? void 0 : _c.description) || "Connect to WalletConnect-compatible wallets",
599
+ url: ((_d = wcmConfig.metadata) == null ? void 0 : _d.url) || "https://walletconnect.org",
600
+ icons: ((_e = wcmConfig.metadata) == null ? void 0 : _e.icons) || ["https://walletconnect.org/walletconnect-logo.png"]
601
+ }),
602
+ showWallets: true,
603
+ // Explorer options mapping
604
+ featuredWalletIds: wcmConfig.explorerRecommendedWalletIds === "NONE" ? [] : Array.isArray(wcmConfig.explorerRecommendedWalletIds) ? wcmConfig.explorerRecommendedWalletIds : [],
605
+ excludeWalletIds: wcmConfig.explorerExcludedWalletIds === "ALL" ? [] : Array.isArray(wcmConfig.explorerExcludedWalletIds) ? wcmConfig.explorerExcludedWalletIds : [],
606
+ // Additional AppKit-specific options that don't have direct WCM equivalents
607
+ enableEIP6963: false,
608
+ // Disable 6963 by default
609
+ enableInjected: false,
610
+ // Disable injected by default
611
+ enableCoinbase: true,
612
+ // Default to true
613
+ enableWalletConnect: true,
614
+ // Default to true,
615
+ features: {
616
+ email: false,
617
+ socials: false
618
+ }
619
+ };
620
+ if (((_f = wcmConfig.mobileWallets) == null ? void 0 : _f.length) || ((_g = wcmConfig.desktopWallets) == null ? void 0 : _g.length)) {
621
+ const customWallets = [
622
+ ...(wcmConfig.mobileWallets || []).map((wallet) => ({
623
+ id: wallet.id,
624
+ name: wallet.name,
625
+ links: wallet.links
626
+ })),
627
+ ...(wcmConfig.desktopWallets || []).map((wallet) => ({
628
+ id: wallet.id,
629
+ name: wallet.name,
630
+ links: {
631
+ native: wallet.links.native,
632
+ universal: wallet.links.universal
633
+ }
634
+ }))
635
+ ];
636
+ const allWallets = [
637
+ ...appKitOptions.featuredWalletIds || [],
638
+ ...appKitOptions.excludeWalletIds || []
639
+ ];
640
+ const uniqueCustomWallets = customWallets.filter((wallet) => !allWallets.includes(wallet.id));
641
+ if (uniqueCustomWallets.length) {
642
+ appKitOptions.customWallets = uniqueCustomWallets;
643
+ }
644
+ }
645
+ return appKitOptions;
646
+ }
647
+ function defineChain(chain) {
648
+ return __spreadValues({
649
+ formatters: void 0,
650
+ fees: void 0,
651
+ serializers: void 0
652
+ }, chain);
653
+ }
654
+
655
+ var wcmToAppKit = /*#__PURE__*/Object.freeze({
656
+ __proto__: null,
657
+ convertWCMToAppKitOptions: convertWCMToAppKitOptions,
658
+ defineChain: defineChain
659
+ });
660
+
661
+ exports.EthereumProvider = EthereumProvider;
662
+ exports.OPTIONAL_EVENTS = OPTIONAL_EVENTS;
663
+ exports.OPTIONAL_METHODS = OPTIONAL_METHODS;
664
+ exports.REQUIRED_EVENTS = REQUIRED_EVENTS;
665
+ exports.REQUIRED_METHODS = REQUIRED_METHODS;
666
+ exports["default"] = EthereumProvider$1;
2
667
  //# sourceMappingURL=index.cjs.map