@matchain/matchid-sdk-react 0.1.53-alpha.18 → 0.1.53-alpha.19
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/{chunk-ZMW4L3PS.mjs → chunk-Z7L7RRWB.mjs} +188 -696
- package/dist/chunk-Z7L7RRWB.mjs.map +1 -0
- package/dist/components/index.js +121 -629
- package/dist/components/index.js.map +1 -1
- package/dist/components/index.mjs +1 -1
- package/dist/hooks/api/index.js +36 -52
- package/dist/hooks/api/index.js.map +1 -1
- package/dist/hooks/api/index.mjs +1 -1
- package/dist/hooks/index.js +104 -120
- package/dist/hooks/index.js.map +1 -1
- package/dist/hooks/index.mjs +1 -1
- package/dist/index.js +217 -725
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1 -1
- package/example/dist/assets/{ccip-BDKXo6px.js → ccip-BhIcA6Sl.js} +1 -1
- package/example/dist/assets/{events-BkMSjA73.js → events-CkdpRqBF.js} +1 -1
- package/example/dist/assets/{index-CYnPIZzU.js → index-BG5XIZpE.js} +1 -1
- package/example/dist/assets/{index-BoheypMD.js → index-BsarjAeg.js} +1 -1
- package/example/dist/assets/{index-B2Qlu4MF.js → index-DK7UFFe7.js} +1 -1
- package/example/dist/assets/{index-cne7xGMC.js → index-DPb8sz1C.js} +1 -1
- package/example/dist/assets/{index-CuOEfj40.js → index-JbpWt42F.js} +1 -1
- package/example/dist/assets/{index-CbmgleoF.js → index-kAjO6hfy.js} +2 -2
- package/example/dist/assets/{index-gNKTdR8a.js → index-qgo91dsq.js} +7 -7
- package/example/dist/assets/{index.es-C16A-vcZ.js → index.es-D44wzsQe.js} +3 -3
- package/example/dist/index.html +1 -1
- package/package.json +1 -1
- package/dist/chunk-ZMW4L3PS.mjs.map +0 -1
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{B as p,a as m,s as y,d as g,i as k,c as O,b as E,e as L,H as h,f as x}from"./index-
|
|
1
|
+
import{B as p,a as m,s as y,d as g,i as k,c as O,b as E,e as L,H as h,f as x}from"./index-qgo91dsq.js";class M extends p{constructor({callbackSelector:s,cause:e,data:n,extraData:c,sender:u,urls:t}){var i;super(e.shortMessage||"An error occurred while fetching for an offchain result.",{cause:e,metaMessages:[...e.metaMessages||[],(i=e.metaMessages)!=null&&i.length?"":[],"Offchain Gateway Call:",t&&[" Gateway URL(s):",...t.map(f=>` ${m(f)}`)],` Sender: ${u}`,` Data: ${n}`,` Callback selector: ${s}`,` Extra data: ${c}`].flat()}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"OffchainLookupError"})}}class R extends p{constructor({result:s,url:e}){super("Offchain gateway response is malformed. Response data must be a hex value.",{metaMessages:[`Gateway URL: ${m(e)}`,`Response: ${y(s)}`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"OffchainLookupResponseMalformedError"})}}class $ extends p{constructor({sender:s,to:e}){super("Reverted sender address does not match target contract address (`to`).",{metaMessages:[`Contract address: ${e}`,`OffchainLookup sender address: ${s}`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"OffchainLookupSenderMismatchError"})}}const j="0x556f1830",S={name:"OffchainLookup",type:"error",inputs:[{name:"sender",type:"address"},{name:"urls",type:"string[]"},{name:"callData",type:"bytes"},{name:"callbackFunction",type:"bytes4"},{name:"extraData",type:"bytes"}]};async function v(o,{blockNumber:s,blockTag:e,data:n,to:c}){const{args:u}=g({data:n,abi:[S]}),[t,i,f,a,r]=u,{ccipRead:d}=o,b=d&&typeof(d==null?void 0:d.request)=="function"?d.request:q;try{if(!k(c,t))throw new $({sender:t,to:c});const l=await b({data:f,sender:t,urls:i}),{data:w}=await O(o,{blockNumber:s,blockTag:e,data:E([a,L([{type:"bytes"},{type:"bytes"}],[l,r])]),to:c});return w}catch(l){throw new M({callbackSelector:a,cause:l,data:n,extraData:r,sender:t,urls:i})}}async function q({data:o,sender:s,urls:e}){var c;let n=new Error("An unknown error occurred.");for(let u=0;u<e.length;u++){const t=e[u],i=t.includes("{data}")?"GET":"POST",f=i==="POST"?{data:o,sender:s}:void 0;try{const a=await fetch(t.replace("{sender}",s).replace("{data}",o),{body:JSON.stringify(f),method:i});let r;if((c=a.headers.get("Content-Type"))!=null&&c.startsWith("application/json")?r=(await a.json()).data:r=await a.text(),!a.ok){n=new h({body:f,details:r!=null&&r.error?y(r.error):a.statusText,headers:a.headers,status:a.status,url:t});continue}if(!x(r)){n=new R({result:r,url:t});continue}return r}catch(a){n=new h({body:f,details:a.message,url:t})}}throw n}export{q as ccipRequest,v as offchainLookup,S as offchainLookupAbiItem,j as offchainLookupSignature};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{g as C}from"./index-
|
|
1
|
+
import{g as C}from"./index-qgo91dsq.js";var p={exports:{}},a=typeof Reflect=="object"?Reflect:null,d=a&&typeof a.apply=="function"?a.apply:function(e,n,r){return Function.prototype.apply.call(e,n,r)},l;a&&typeof a.ownKeys=="function"?l=a.ownKeys:Object.getOwnPropertySymbols?l=function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:l=function(e){return Object.getOwnPropertyNames(e)};function j(t){console&&console.warn&&console.warn(t)}var L=Number.isNaN||function(e){return e!==e};function o(){o.init.call(this)}p.exports=o;p.exports.once=A;o.EventEmitter=o;o.prototype._events=void 0;o.prototype._eventsCount=0;o.prototype._maxListeners=void 0;var m=10;function v(t){if(typeof t!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof t)}Object.defineProperty(o,"defaultMaxListeners",{enumerable:!0,get:function(){return m},set:function(t){if(typeof t!="number"||t<0||L(t))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+t+".");m=t}});o.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};o.prototype.setMaxListeners=function(e){if(typeof e!="number"||e<0||L(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this};function y(t){return t._maxListeners===void 0?o.defaultMaxListeners:t._maxListeners}o.prototype.getMaxListeners=function(){return y(this)};o.prototype.emit=function(e){for(var n=[],r=1;r<arguments.length;r++)n.push(arguments[r]);var i=e==="error",f=this._events;if(f!==void 0)i=i&&f.error===void 0;else if(!i)return!1;if(i){var s;if(n.length>0&&(s=n[0]),s instanceof Error)throw s;var u=new Error("Unhandled error."+(s?" ("+s.message+")":""));throw u.context=s,u}var c=f[e];if(c===void 0)return!1;if(typeof c=="function")d(c,this,n);else for(var h=c.length,O=E(c,h),r=0;r<h;++r)d(O[r],this,n);return!0};function g(t,e,n,r){var i,f,s;if(v(n),f=t._events,f===void 0?(f=t._events=Object.create(null),t._eventsCount=0):(f.newListener!==void 0&&(t.emit("newListener",e,n.listener?n.listener:n),f=t._events),s=f[e]),s===void 0)s=f[e]=n,++t._eventsCount;else if(typeof s=="function"?s=f[e]=r?[n,s]:[s,n]:r?s.unshift(n):s.push(n),i=y(t),i>0&&s.length>i&&!s.warned){s.warned=!0;var u=new Error("Possible EventEmitter memory leak detected. "+s.length+" "+String(e)+" listeners added. Use emitter.setMaxListeners() to increase limit");u.name="MaxListenersExceededWarning",u.emitter=t,u.type=e,u.count=s.length,j(u)}return t}o.prototype.addListener=function(e,n){return g(this,e,n,!1)};o.prototype.on=o.prototype.addListener;o.prototype.prependListener=function(e,n){return g(this,e,n,!0)};function R(){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 _(t,e,n){var r={fired:!1,wrapFn:void 0,target:t,type:e,listener:n},i=R.bind(r);return i.listener=n,r.wrapFn=i,i}o.prototype.once=function(e,n){return v(n),this.on(e,_(this,e,n)),this};o.prototype.prependOnceListener=function(e,n){return v(n),this.prependListener(e,_(this,e,n)),this};o.prototype.removeListener=function(e,n){var r,i,f,s,u;if(v(n),i=this._events,i===void 0)return this;if(r=i[e],r===void 0)return this;if(r===n||r.listener===n)--this._eventsCount===0?this._events=Object.create(null):(delete i[e],i.removeListener&&this.emit("removeListener",e,r.listener||n));else if(typeof r!="function"){for(f=-1,s=r.length-1;s>=0;s--)if(r[s]===n||r[s].listener===n){u=r[s].listener,f=s;break}if(f<0)return this;f===0?r.shift():N(r,f),r.length===1&&(i[e]=r[0]),i.removeListener!==void 0&&this.emit("removeListener",e,u||n)}return this};o.prototype.off=o.prototype.removeListener;o.prototype.removeAllListeners=function(e){var n,r,i;if(r=this._events,r===void 0)return this;if(r.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):r[e]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete r[e]),this;if(arguments.length===0){var f=Object.keys(r),s;for(i=0;i<f.length;++i)s=f[i],s!=="removeListener"&&this.removeAllListeners(s);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(n=r[e],typeof n=="function")this.removeListener(e,n);else if(n!==void 0)for(i=n.length-1;i>=0;i--)this.removeListener(e,n[i]);return this};function w(t,e,n){var r=t._events;if(r===void 0)return[];var i=r[e];return i===void 0?[]:typeof i=="function"?n?[i.listener||i]:[i]:n?M(i):E(i,i.length)}o.prototype.listeners=function(e){return w(this,e,!0)};o.prototype.rawListeners=function(e){return w(this,e,!1)};o.listenerCount=function(t,e){return typeof t.listenerCount=="function"?t.listenerCount(e):b.call(t,e)};o.prototype.listenerCount=b;function b(t){var e=this._events;if(e!==void 0){var n=e[t];if(typeof n=="function")return 1;if(n!==void 0)return n.length}return 0}o.prototype.eventNames=function(){return this._eventsCount>0?l(this._events):[]};function E(t,e){for(var n=new Array(e),r=0;r<e;++r)n[r]=t[r];return n}function N(t,e){for(;e+1<t.length;e++)t[e]=t[e+1];t.pop()}function M(t){for(var e=new Array(t.length),n=0;n<e.length;++n)e[n]=t[n].listener||t[n];return e}function A(t,e){return new Promise(function(n,r){function i(s){t.removeListener(e,f),r(s)}function f(){typeof t.removeListener=="function"&&t.removeListener("error",i),n([].slice.call(arguments))}x(t,e,f,{once:!0}),e!=="error"&&P(t,i,{once:!0})})}function P(t,e,n){typeof t.on=="function"&&x(t,"error",e,n)}function x(t,e,n,r){if(typeof t.on=="function")r.once?t.once(e,n):t.on(e,n);else if(typeof t.addEventListener=="function")t.addEventListener(e,function i(f){r.once&&t.removeEventListener(e,i),n(f)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof t)}var T=p.exports;const I=C(T);export{I as J,T as e};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{j as et,g as tt,u as nt,k as st,E as it}from"./index-gNKTdR8a.js";import{D as V,g as u,c as D,h as ae,y as rt}from"./hooks.module-C5ONEBEq.js";class E{constructor(e,n){this.scope=e,this.module=n}storeObject(e,n){this.setItem(e,JSON.stringify(n))}loadObject(e){const n=this.getItem(e);return n?JSON.parse(n):void 0}setItem(e,n){localStorage.setItem(this.scopedKey(e),n)}getItem(e){return localStorage.getItem(this.scopedKey(e))}removeItem(e){localStorage.removeItem(this.scopedKey(e))}clear(){const e=this.scopedKey(""),n=[];for(let s=0;s<localStorage.length;s++){const i=localStorage.key(s);typeof i=="string"&&i.startsWith(e)&&n.push(i)}n.forEach(s=>localStorage.removeItem(s))}scopedKey(e){return`-${this.scope}${this.module?`:${this.module}`:""}:${e}`}static clearAll(){new E("CBWSDK").clear(),new E("walletlink").clear()}}const h={rpc:{invalidInput:-32e3,resourceNotFound:-32001,resourceUnavailable:-32002,transactionRejected:-32003,methodNotSupported:-32004,limitExceeded:-32005,parse:-32700,invalidRequest:-32600,methodNotFound:-32601,invalidParams:-32602,internal:-32603},provider:{userRejectedRequest:4001,unauthorized:4100,unsupportedMethod:4200,disconnected:4900,chainDisconnected:4901,unsupportedChain:4902}},Q={"-32700":{standard:"JSON RPC 2.0",message:"Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text."},"-32600":{standard:"JSON RPC 2.0",message:"The JSON sent is not a valid Request object."},"-32601":{standard:"JSON RPC 2.0",message:"The method does not exist / is not available."},"-32602":{standard:"JSON RPC 2.0",message:"Invalid method parameter(s)."},"-32603":{standard:"JSON RPC 2.0",message:"Internal JSON-RPC error."},"-32000":{standard:"EIP-1474",message:"Invalid input."},"-32001":{standard:"EIP-1474",message:"Resource not found."},"-32002":{standard:"EIP-1474",message:"Resource unavailable."},"-32003":{standard:"EIP-1474",message:"Transaction rejected."},"-32004":{standard:"EIP-1474",message:"Method not supported."},"-32005":{standard:"EIP-1474",message:"Request limit exceeded."},4001:{standard:"EIP-1193",message:"User rejected the request."},4100:{standard:"EIP-1193",message:"The requested account and/or method has not been authorized by the user."},4200:{standard:"EIP-1193",message:"The requested method is not supported by this Ethereum provider."},4900:{standard:"EIP-1193",message:"The provider is disconnected from all chains."},4901:{standard:"EIP-1193",message:"The provider is disconnected from the specified chain."},4902:{standard:"EIP-3085",message:"Unrecognized chain ID."}},Se="Unspecified error message.",at="Unspecified server error.";function te(t,e=Se){if(t&&Number.isInteger(t)){const n=t.toString();if(Z(Q,n))return Q[n].message;if(Ce(t))return at}return e}function ot(t){if(!Number.isInteger(t))return!1;const e=t.toString();return!!(Q[e]||Ce(t))}function ct(t,{shouldIncludeStack:e=!1}={}){const n={};if(t&&typeof t=="object"&&!Array.isArray(t)&&Z(t,"code")&&ot(t.code)){const s=t;n.code=s.code,s.message&&typeof s.message=="string"?(n.message=s.message,Z(s,"data")&&(n.data=s.data)):(n.message=te(n.code),n.data={originalError:oe(t)})}else n.code=h.rpc.internal,n.message=ce(t,"message")?t.message:Se,n.data={originalError:oe(t)};return e&&(n.stack=ce(t,"stack")?t.stack:void 0),n}function Ce(t){return t>=-32099&&t<=-32e3}function oe(t){return t&&typeof t=="object"&&!Array.isArray(t)?Object.assign({},t):t}function Z(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function ce(t,e){return typeof t=="object"&&t!==null&&e in t&&typeof t[e]=="string"}const l={rpc:{parse:t=>w(h.rpc.parse,t),invalidRequest:t=>w(h.rpc.invalidRequest,t),invalidParams:t=>w(h.rpc.invalidParams,t),methodNotFound:t=>w(h.rpc.methodNotFound,t),internal:t=>w(h.rpc.internal,t),server:t=>{if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Ethereum RPC Server errors must provide single object argument.");const{code:e}=t;if(!Number.isInteger(e)||e>-32005||e<-32099)throw new Error('"code" must be an integer such that: -32099 <= code <= -32005');return w(e,t)},invalidInput:t=>w(h.rpc.invalidInput,t),resourceNotFound:t=>w(h.rpc.resourceNotFound,t),resourceUnavailable:t=>w(h.rpc.resourceUnavailable,t),transactionRejected:t=>w(h.rpc.transactionRejected,t),methodNotSupported:t=>w(h.rpc.methodNotSupported,t),limitExceeded:t=>w(h.rpc.limitExceeded,t)},provider:{userRejectedRequest:t=>R(h.provider.userRejectedRequest,t),unauthorized:t=>R(h.provider.unauthorized,t),unsupportedMethod:t=>R(h.provider.unsupportedMethod,t),disconnected:t=>R(h.provider.disconnected,t),chainDisconnected:t=>R(h.provider.chainDisconnected,t),unsupportedChain:t=>R(h.provider.unsupportedChain,t),custom:t=>{if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Ethereum Provider custom errors must provide single object argument.");const{code:e,message:n,data:s}=t;if(!n||typeof n!="string")throw new Error('"message" must be a nonempty string');return new Ae(e,n,s)}}};function w(t,e){const[n,s]=Me(e);return new _e(t,n||te(t),s)}function R(t,e){const[n,s]=Me(e);return new Ae(t,n||te(t),s)}function Me(t){if(t){if(typeof t=="string")return[t];if(typeof t=="object"&&!Array.isArray(t)){const{message:e,data:n}=t;if(e&&typeof e!="string")throw new Error("Must specify string message.");return[e||void 0,n]}}return[]}class _e extends Error{constructor(e,n,s){if(!Number.isInteger(e))throw new Error('"code" must be an integer.');if(!n||typeof n!="string")throw new Error('"message" must be a nonempty string.');super(n),this.code=e,s!==void 0&&(this.data=s)}}class Ae extends _e{constructor(e,n,s){if(!dt(e))throw new Error('"code" must be an integer such that: 1000 <= code <= 4999');super(e,n,s)}}function dt(t){return Number.isInteger(t)&&t>=1e3&&t<=4999}function ne(){return t=>t}const W=ne(),lt=ne(),ut=ne();function S(t){return Math.floor(t)}const xe=/^[0-9]*$/,Pe=/^[a-f0-9]*$/;function x(t){return se(crypto.getRandomValues(new Uint8Array(t)))}function se(t){return[...t].map(e=>e.toString(16).padStart(2,"0")).join("")}function B(t){return new Uint8Array(t.match(/.{1,2}/g).map(e=>Number.parseInt(e,16)))}function O(t,e=!1){const n=t.toString("hex");return W(e?`0x${n}`:n)}function H(t){return O(X(t),!0)}function v(t){return ut(t.toString(10))}function A(t){return W(`0x${BigInt(t).toString(16)}`)}function Re(t){return t.startsWith("0x")||t.startsWith("0X")}function ie(t){return Re(t)?t.slice(2):t}function Le(t){return Re(t)?`0x${t.slice(2)}`:`0x${t}`}function z(t){if(typeof t!="string")return!1;const e=ie(t).toLowerCase();return Pe.test(e)}function ht(t,e=!1){if(typeof t=="string"){const n=ie(t).toLowerCase();if(Pe.test(n))return W(e?`0x${n}`:n)}throw l.rpc.invalidParams(`"${String(t)}" is not a hexadecimal string`)}function re(t,e=!1){let n=ht(t,!1);return n.length%2===1&&(n=W(`0${n}`)),e?W(`0x${n}`):n}function _(t){if(typeof t=="string"){const e=ie(t).toLowerCase();if(z(e)&&e.length===40)return lt(Le(e))}throw l.rpc.invalidParams(`Invalid Ethereum address: ${String(t)}`)}function X(t){if(Buffer.isBuffer(t))return t;if(typeof t=="string"){if(z(t)){const e=re(t,!1);return Buffer.from(e,"hex")}return Buffer.from(t,"utf8")}throw l.rpc.invalidParams(`Not binary data: ${String(t)}`)}function j(t){if(typeof t=="number"&&Number.isInteger(t))return S(t);if(typeof t=="string"){if(xe.test(t))return S(Number(t));if(z(t))return S(Number(BigInt(re(t,!0))))}throw l.rpc.invalidParams(`Not an integer: ${String(t)}`)}function N(t){if(t!==null&&(typeof t=="bigint"||ft(t)))return BigInt(t.toString(10));if(typeof t=="number")return BigInt(j(t));if(typeof t=="string"){if(xe.test(t))return BigInt(t);if(z(t))return BigInt(re(t,!0))}throw l.rpc.invalidParams(`Not an integer: ${String(t)}`)}function pt(t){if(typeof t=="string")return JSON.parse(t);if(typeof t=="object")return t;throw l.rpc.invalidParams(`Not a JSON string or an object: ${String(t)}`)}function ft(t){if(t==null||typeof t.constructor!="function")return!1;const{constructor:e}=t;return typeof e.config=="function"&&typeof e.EUCLID=="number"}async function gt(){return crypto.subtle.generateKey({name:"ECDH",namedCurve:"P-256"},!0,["deriveKey"])}async function mt(t,e){return crypto.subtle.deriveKey({name:"ECDH",public:e},t,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}async function bt(t,e){const n=crypto.getRandomValues(new Uint8Array(12)),s=await crypto.subtle.encrypt({name:"AES-GCM",iv:n},t,new TextEncoder().encode(e));return{iv:n,cipherText:s}}async function wt(t,{iv:e,cipherText:n}){const s=await crypto.subtle.decrypt({name:"AES-GCM",iv:e},t,n);return new TextDecoder().decode(s)}function Te(t){switch(t){case"public":return"spki";case"private":return"pkcs8"}}async function Ne(t,e){const n=Te(t),s=await crypto.subtle.exportKey(n,e);return se(new Uint8Array(s))}async function De(t,e){const n=Te(t),s=B(e).buffer;return await crypto.subtle.importKey(n,new Uint8Array(s),{name:"ECDH",namedCurve:"P-256"},!0,t==="private"?["deriveKey"]:[])}async function yt(t,e){const n=JSON.stringify(t,(s,i)=>{if(!(i instanceof Error))return i;const r=i;return Object.assign(Object.assign({},r.code?{code:r.code}:{}),{message:r.message})});return bt(e,n)}async function vt(t,e){return JSON.parse(await wt(e,t))}const G={storageKey:"ownPrivateKey",keyType:"private"},Y={storageKey:"ownPublicKey",keyType:"public"},$={storageKey:"peerPublicKey",keyType:"public"};class kt{constructor(){this.storage=new E("CBWSDK","SCWKeyManager"),this.ownPrivateKey=null,this.ownPublicKey=null,this.peerPublicKey=null,this.sharedSecret=null}async getOwnPublicKey(){return await this.loadKeysIfNeeded(),this.ownPublicKey}async getSharedSecret(){return await this.loadKeysIfNeeded(),this.sharedSecret}async setPeerPublicKey(e){this.sharedSecret=null,this.peerPublicKey=e,await this.storeKey($,e),await this.loadKeysIfNeeded()}async clear(){this.ownPrivateKey=null,this.ownPublicKey=null,this.peerPublicKey=null,this.sharedSecret=null,this.storage.removeItem(Y.storageKey),this.storage.removeItem(G.storageKey),this.storage.removeItem($.storageKey)}async generateKeyPair(){const e=await gt();this.ownPrivateKey=e.privateKey,this.ownPublicKey=e.publicKey,await this.storeKey(G,e.privateKey),await this.storeKey(Y,e.publicKey)}async loadKeysIfNeeded(){if(this.ownPrivateKey===null&&(this.ownPrivateKey=await this.loadKey(G)),this.ownPublicKey===null&&(this.ownPublicKey=await this.loadKey(Y)),(this.ownPrivateKey===null||this.ownPublicKey===null)&&await this.generateKeyPair(),this.peerPublicKey===null&&(this.peerPublicKey=await this.loadKey($)),this.sharedSecret===null){if(this.ownPrivateKey===null||this.peerPublicKey===null)return;this.sharedSecret=await mt(this.ownPrivateKey,this.peerPublicKey)}}async loadKey(e){const n=this.storage.getItem(e.storageKey);return n?De(e.keyType,n):null}async storeKey(e,n){const s=await Ne(e.keyType,n);this.storage.setItem(e.storageKey,s)}}const K="4.2.3",Oe="@coinbase/wallet-sdk";async function je(t,e){const n=Object.assign(Object.assign({},t),{jsonrpc:"2.0",id:crypto.randomUUID()}),s=await window.fetch(e,{method:"POST",body:JSON.stringify(n),mode:"cors",headers:{"Content-Type":"application/json","X-Cbw-Sdk-Version":K,"X-Cbw-Sdk-Platform":Oe}}),{result:i,error:r}=await s.json();if(r)throw r;return i}function Et(){return globalThis.coinbaseWalletExtension}function It(){var t,e;try{const n=globalThis;return(t=n.ethereum)!==null&&t!==void 0?t:(e=n.top)===null||e===void 0?void 0:e.ethereum}catch{return}}function St({metadata:t,preference:e}){var n,s;const{appName:i,appLogoUrl:r,appChainIds:a}=t;if(e.options!=="smartWalletOnly"){const c=Et();if(c)return(n=c.setAppInfo)===null||n===void 0||n.call(c,i,r,a,e),c}const o=It();if(o!=null&&o.isCoinbaseBrowser)return(s=o.setAppInfo)===null||s===void 0||s.call(o,i,r,a,e),o}function Ct(t){if(!t||typeof t!="object"||Array.isArray(t))throw l.rpc.invalidParams({message:"Expected a single, non-array, object argument.",data:t});const{method:e,params:n}=t;if(typeof e!="string"||e.length===0)throw l.rpc.invalidParams({message:"'args.method' must be a non-empty string.",data:t});if(n!==void 0&&!Array.isArray(n)&&(typeof n!="object"||n===null))throw l.rpc.invalidParams({message:"'args.params' must be an object or array if provided.",data:t});switch(e){case"eth_sign":case"eth_signTypedData_v2":case"eth_subscribe":case"eth_unsubscribe":throw l.provider.unsupportedMethod()}}const de="accounts",le="activeChain",ue="availableChains",he="walletCapabilities";class Mt{constructor(e){var n,s,i;this.metadata=e.metadata,this.communicator=e.communicator,this.callback=e.callback,this.keyManager=new kt,this.storage=new E("CBWSDK","SCWStateManager"),this.accounts=(n=this.storage.loadObject(de))!==null&&n!==void 0?n:[],this.chain=this.storage.loadObject(le)||{id:(i=(s=e.metadata.appChainIds)===null||s===void 0?void 0:s[0])!==null&&i!==void 0?i:1},this.handshake=this.handshake.bind(this),this.request=this.request.bind(this),this.createRequestMessage=this.createRequestMessage.bind(this),this.decryptResponseMessage=this.decryptResponseMessage.bind(this)}async handshake(e){var n,s;const i=await this.createRequestMessage({handshake:{method:e.method,params:Object.assign({},this.metadata,(n=e.params)!==null&&n!==void 0?n:{})}}),r=await this.communicator.postRequestAndWaitForResponse(i);if("failure"in r.content)throw r.content.failure;const a=await De("public",r.sender);await this.keyManager.setPeerPublicKey(a);const c=(await this.decryptResponseMessage(r)).result;if("error"in c)throw c.error;const d=c.value;this.accounts=d,this.storage.storeObject(de,d),(s=this.callback)===null||s===void 0||s.call(this,"accountsChanged",d)}async request(e){var n;if(this.accounts.length===0)throw l.provider.unauthorized();switch(e.method){case"eth_requestAccounts":return(n=this.callback)===null||n===void 0||n.call(this,"connect",{chainId:A(this.chain.id)}),this.accounts;case"eth_accounts":return this.accounts;case"eth_coinbase":return this.accounts[0];case"net_version":return this.chain.id;case"eth_chainId":return A(this.chain.id);case"wallet_getCapabilities":return this.storage.loadObject(he);case"wallet_switchEthereumChain":return this.handleSwitchChainRequest(e);case"eth_ecRecover":case"personal_sign":case"personal_ecRecover":case"eth_signTransaction":case"eth_sendTransaction":case"eth_signTypedData_v1":case"eth_signTypedData_v3":case"eth_signTypedData_v4":case"eth_signTypedData":case"wallet_addEthereumChain":case"wallet_watchAsset":case"wallet_sendCalls":case"wallet_showCallsStatus":case"wallet_grantPermissions":return this.sendRequestToPopup(e);default:if(!this.chain.rpcUrl)throw l.rpc.internal("No RPC URL set for chain");return je(e,this.chain.rpcUrl)}}async sendRequestToPopup(e){var n,s;await((s=(n=this.communicator).waitForPopupLoaded)===null||s===void 0?void 0:s.call(n));const i=await this.sendEncryptedRequest(e),a=(await this.decryptResponseMessage(i)).result;if("error"in a)throw a.error;return a.value}async cleanup(){var e,n;this.storage.clear(),await this.keyManager.clear(),this.accounts=[],this.chain={id:(n=(e=this.metadata.appChainIds)===null||e===void 0?void 0:e[0])!==null&&n!==void 0?n:1}}async handleSwitchChainRequest(e){var n;const s=e.params;if(!s||!(!((n=s[0])===null||n===void 0)&&n.chainId))throw l.rpc.invalidParams();const i=j(s[0].chainId);if(this.updateChain(i))return null;const a=await this.sendRequestToPopup(e);return a===null&&this.updateChain(i),a}async sendEncryptedRequest(e){const n=await this.keyManager.getSharedSecret();if(!n)throw l.provider.unauthorized("No valid session found, try requestAccounts before other methods");const s=await yt({action:e,chainId:this.chain.id},n),i=await this.createRequestMessage({encrypted:s});return this.communicator.postRequestAndWaitForResponse(i)}async createRequestMessage(e){const n=await Ne("public",await this.keyManager.getOwnPublicKey());return{id:crypto.randomUUID(),sender:n,content:e,timestamp:new Date}}async decryptResponseMessage(e){var n,s;const i=e.content;if("failure"in i)throw i.failure;const r=await this.keyManager.getSharedSecret();if(!r)throw l.provider.unauthorized("Invalid session");const a=await vt(i.encrypted,r),o=(n=a.data)===null||n===void 0?void 0:n.chains;if(o){const d=Object.entries(o).map(([g,p])=>({id:Number(g),rpcUrl:p}));this.storage.storeObject(ue,d),this.updateChain(this.chain.id,d)}const c=(s=a.data)===null||s===void 0?void 0:s.capabilities;return c&&this.storage.storeObject(he,c),a}updateChain(e,n){var s;const i=n??this.storage.loadObject(ue),r=i==null?void 0:i.find(a=>a.id===e);return r?(r!==this.chain&&(this.chain=r,this.storage.storeObject(le,r),(s=this.callback)===null||s===void 0||s.call(this,"chainChanged",A(r.id))),!0):!1}}const{keccak_256:_t}=et;function Ue(t){return Buffer.allocUnsafe(t).fill(0)}function At(t){return t.toString(2).length}function We(t,e){let n=t.toString(16);n.length%2!==0&&(n="0"+n);const s=n.match(/.{1,2}/g).map(i=>parseInt(i,16));for(;s.length<e;)s.unshift(0);return Buffer.from(s)}function xt(t,e){const n=t<0n;let s;if(n){const i=(1n<<BigInt(e))-1n;s=(~t&i)+1n}else s=t;return s&=(1n<<BigInt(e))-1n,s}function Ke(t,e,n){const s=Ue(e);return t=F(t),n?t.length<e?(t.copy(s),s):t.slice(0,e):t.length<e?(t.copy(s,e-t.length),s):t.slice(-e)}function Pt(t,e){return Ke(t,e,!0)}function F(t){if(!Buffer.isBuffer(t))if(Array.isArray(t))t=Buffer.from(t);else if(typeof t=="string")qe(t)?t=Buffer.from(Tt(Be(t)),"hex"):t=Buffer.from(t);else if(typeof t=="number")t=intToBuffer(t);else if(t==null)t=Buffer.allocUnsafe(0);else if(typeof t=="bigint")t=We(t);else if(t.toArray)t=Buffer.from(t.toArray());else throw new Error("invalid type");return t}function Rt(t){return t=F(t),"0x"+t.toString("hex")}function Lt(t,e){if(t=F(t),e||(e=256),e!==256)throw new Error("unsupported");return Buffer.from(_t(new Uint8Array(t)))}function Tt(t){return t.length%2?"0"+t:t}function qe(t){return typeof t=="string"&&t.match(/^0x[0-9A-Fa-f]*$/)}function Be(t){return typeof t=="string"&&t.startsWith("0x")?t.slice(2):t}var ze={zeros:Ue,setLength:Ke,setLengthRight:Pt,isHexString:qe,stripHexPrefix:Be,toBuffer:F,bufferToHex:Rt,keccak:Lt,bitLengthFromBigInt:At,bufferBEFromBigInt:We,twosFromBigInt:xt};const b=ze;function Fe(t){return t.startsWith("int[")?"int256"+t.slice(3):t==="int"?"int256":t.startsWith("uint[")?"uint256"+t.slice(4):t==="uint"?"uint256":t.startsWith("fixed[")?"fixed128x128"+t.slice(5):t==="fixed"?"fixed128x128":t.startsWith("ufixed[")?"ufixed128x128"+t.slice(6):t==="ufixed"?"ufixed128x128":t}function L(t){return Number.parseInt(/^\D+(\d+)$/.exec(t)[1],10)}function pe(t){var e=/^\D+(\d+)x(\d+)$/.exec(t);return[Number.parseInt(e[1],10),Number.parseInt(e[2],10)]}function He(t){var e=t.match(/(.*)\[(.*?)\]$/);return e?e[2]===""?"dynamic":Number.parseInt(e[2],10):null}function P(t){var e=typeof t;if(e==="string"||e==="number")return BigInt(t);if(e==="bigint")return t;throw new Error("Argument is not a number")}function k(t,e){var n,s,i,r;if(t==="address")return k("uint160",P(e));if(t==="bool")return k("uint8",e?1:0);if(t==="string")return k("bytes",new Buffer(e,"utf8"));if(Dt(t)){if(typeof e.length>"u")throw new Error("Not an array?");if(n=He(t),n!=="dynamic"&&n!==0&&e.length>n)throw new Error("Elements exceed array size: "+n);i=[],t=t.slice(0,t.lastIndexOf("[")),typeof e=="string"&&(e=JSON.parse(e));for(r in e)i.push(k(t,e[r]));if(n==="dynamic"){var a=k("uint256",e.length);i.unshift(a)}return Buffer.concat(i)}else{if(t==="bytes")return e=new Buffer(e),i=Buffer.concat([k("uint256",e.length),e]),e.length%32!==0&&(i=Buffer.concat([i,b.zeros(32-e.length%32)])),i;if(t.startsWith("bytes")){if(n=L(t),n<1||n>32)throw new Error("Invalid bytes<N> width: "+n);return b.setLengthRight(e,32)}else if(t.startsWith("uint")){if(n=L(t),n%8||n<8||n>256)throw new Error("Invalid uint<N> width: "+n);s=P(e);const o=b.bitLengthFromBigInt(s);if(o>n)throw new Error("Supplied uint exceeds width: "+n+" vs "+o);if(s<0)throw new Error("Supplied uint is negative");return b.bufferBEFromBigInt(s,32)}else if(t.startsWith("int")){if(n=L(t),n%8||n<8||n>256)throw new Error("Invalid int<N> width: "+n);s=P(e);const o=b.bitLengthFromBigInt(s);if(o>n)throw new Error("Supplied int exceeds width: "+n+" vs "+o);const c=b.twosFromBigInt(s,256);return b.bufferBEFromBigInt(c,32)}else if(t.startsWith("ufixed")){if(n=pe(t),s=P(e),s<0)throw new Error("Supplied ufixed is negative");return k("uint256",s*BigInt(2)**BigInt(n[1]))}else if(t.startsWith("fixed"))return n=pe(t),k("int256",P(e)*BigInt(2)**BigInt(n[1]))}throw new Error("Unsupported or invalid type: "+t)}function Nt(t){return t==="string"||t==="bytes"||He(t)==="dynamic"}function Dt(t){return t.lastIndexOf("]")===t.length-1}function Ot(t,e){var n=[],s=[],i=32*t.length;for(var r in t){var a=Fe(t[r]),o=e[r],c=k(a,o);Nt(a)?(n.push(k("uint256",i)),s.push(c),i+=c.length):n.push(c)}return Buffer.concat(n.concat(s))}function Ge(t,e){if(t.length!==e.length)throw new Error("Number of types are not matching the values");for(var n,s,i=[],r=0;r<t.length;r++){var a=Fe(t[r]),o=e[r];if(a==="bytes")i.push(o);else if(a==="string")i.push(new Buffer(o,"utf8"));else if(a==="bool")i.push(new Buffer(o?"01":"00","hex"));else if(a==="address")i.push(b.setLength(o,20));else if(a.startsWith("bytes")){if(n=L(a),n<1||n>32)throw new Error("Invalid bytes<N> width: "+n);i.push(b.setLengthRight(o,n))}else if(a.startsWith("uint")){if(n=L(a),n%8||n<8||n>256)throw new Error("Invalid uint<N> width: "+n);s=P(o);const c=b.bitLengthFromBigInt(s);if(c>n)throw new Error("Supplied uint exceeds width: "+n+" vs "+c);i.push(b.bufferBEFromBigInt(s,n/8))}else if(a.startsWith("int")){if(n=L(a),n%8||n<8||n>256)throw new Error("Invalid int<N> width: "+n);s=P(o);const c=b.bitLengthFromBigInt(s);if(c>n)throw new Error("Supplied int exceeds width: "+n+" vs "+c);const d=b.twosFromBigInt(s,n);i.push(b.bufferBEFromBigInt(d,n/8))}else throw new Error("Unsupported or invalid type: "+a)}return Buffer.concat(i)}function jt(t,e){return b.keccak(Ge(t,e))}var Ut={rawEncode:Ot,solidityPack:Ge,soliditySHA3:jt};const y=ze,U=Ut,Ye={type:"object",properties:{types:{type:"object",additionalProperties:{type:"array",items:{type:"object",properties:{name:{type:"string"},type:{type:"string"}},required:["name","type"]}}},primaryType:{type:"string"},domain:{type:"object"},message:{type:"object"}},required:["types","primaryType","domain","message"]},J={encodeData(t,e,n,s=!0){const i=["bytes32"],r=[this.hashType(t,n)];if(s){const a=(o,c,d)=>{if(n[c]!==void 0)return["bytes32",d==null?"0x0000000000000000000000000000000000000000000000000000000000000000":y.keccak(this.encodeData(c,d,n,s))];if(d===void 0)throw new Error(`missing value for field ${o} of type ${c}`);if(c==="bytes")return["bytes32",y.keccak(d)];if(c==="string")return typeof d=="string"&&(d=Buffer.from(d,"utf8")),["bytes32",y.keccak(d)];if(c.lastIndexOf("]")===c.length-1){const g=c.slice(0,c.lastIndexOf("[")),p=d.map(f=>a(o,g,f));return["bytes32",y.keccak(U.rawEncode(p.map(([f])=>f),p.map(([,f])=>f)))]}return[c,d]};for(const o of n[t]){const[c,d]=a(o.name,o.type,e[o.name]);i.push(c),r.push(d)}}else for(const a of n[t]){let o=e[a.name];if(o!==void 0)if(a.type==="bytes")i.push("bytes32"),o=y.keccak(o),r.push(o);else if(a.type==="string")i.push("bytes32"),typeof o=="string"&&(o=Buffer.from(o,"utf8")),o=y.keccak(o),r.push(o);else if(n[a.type]!==void 0)i.push("bytes32"),o=y.keccak(this.encodeData(a.type,o,n,s)),r.push(o);else{if(a.type.lastIndexOf("]")===a.type.length-1)throw new Error("Arrays currently unimplemented in encodeData");i.push(a.type),r.push(o)}}return U.rawEncode(i,r)},encodeType(t,e){let n="",s=this.findTypeDependencies(t,e).filter(i=>i!==t);s=[t].concat(s.sort());for(const i of s){if(!e[i])throw new Error("No type definition specified: "+i);n+=i+"("+e[i].map(({name:a,type:o})=>o+" "+a).join(",")+")"}return n},findTypeDependencies(t,e,n=[]){if(t=t.match(/^\w*/)[0],n.includes(t)||e[t]===void 0)return n;n.push(t);for(const s of e[t])for(const i of this.findTypeDependencies(s.type,e,n))!n.includes(i)&&n.push(i);return n},hashStruct(t,e,n,s=!0){return y.keccak(this.encodeData(t,e,n,s))},hashType(t,e){return y.keccak(this.encodeType(t,e))},sanitizeData(t){const e={};for(const n in Ye.properties)t[n]&&(e[n]=t[n]);return e.types&&(e.types=Object.assign({EIP712Domain:[]},e.types)),e},hash(t,e=!0){const n=this.sanitizeData(t),s=[Buffer.from("1901","hex")];return s.push(this.hashStruct("EIP712Domain",n.domain,n.types,e)),n.primaryType!=="EIP712Domain"&&s.push(this.hashStruct(n.primaryType,n.message,n.types,e)),y.keccak(Buffer.concat(s))}};var Wt={TYPED_MESSAGE_SCHEMA:Ye,TypedDataUtils:J,hashForSignTypedDataLegacy:function(t){return Kt(t.data)},hashForSignTypedData_v3:function(t){return J.hash(t.data,!1)},hashForSignTypedData_v4:function(t){return J.hash(t.data)}};function Kt(t){const e=new Error("Expect argument to be non-empty array");if(typeof t!="object"||!t.length)throw e;const n=t.map(function(r){return r.type==="bytes"?y.toBuffer(r.value):r.value}),s=t.map(function(r){return r.type}),i=t.map(function(r){if(!r.name)throw e;return r.type+" "+r.name});return U.soliditySHA3(["bytes32","bytes32"],[U.soliditySHA3(new Array(t.length).fill("string"),i),U.soliditySHA3(s,n)])}const q=tt(Wt),qt="walletUsername",ee="Addresses",Bt="AppVersion";function m(t){return t.errorMessage!==void 0}class zt{constructor(e){this.secret=e}async encrypt(e){const n=this.secret;if(n.length!==64)throw Error("secret must be 256 bits");const s=crypto.getRandomValues(new Uint8Array(12)),i=await crypto.subtle.importKey("raw",B(n),{name:"aes-gcm"},!1,["encrypt","decrypt"]),r=new TextEncoder,a=await window.crypto.subtle.encrypt({name:"AES-GCM",iv:s},i,r.encode(e)),o=16,c=a.slice(a.byteLength-o),d=a.slice(0,a.byteLength-o),g=new Uint8Array(c),p=new Uint8Array(d),f=new Uint8Array([...s,...g,...p]);return se(f)}async decrypt(e){const n=this.secret;if(n.length!==64)throw Error("secret must be 256 bits");return new Promise((s,i)=>{(async function(){const r=await crypto.subtle.importKey("raw",B(n),{name:"aes-gcm"},!1,["encrypt","decrypt"]),a=B(e),o=a.slice(0,12),c=a.slice(12,28),d=a.slice(28),g=new Uint8Array([...d,...c]),p={name:"AES-GCM",iv:new Uint8Array(o)};try{const f=await window.crypto.subtle.decrypt(p,r,g),I=new TextDecoder;s(I.decode(f))}catch(f){i(f)}})()})}}class Ft{constructor(e,n,s){this.linkAPIUrl=e,this.sessionId=n;const i=`${n}:${s}`;this.auth=`Basic ${btoa(i)}`}async markUnseenEventsAsSeen(e){return Promise.all(e.map(n=>fetch(`${this.linkAPIUrl}/events/${n.eventId}/seen`,{method:"POST",headers:{Authorization:this.auth}}))).catch(n=>console.error("Unabled to mark event as failed:",n))}async fetchUnseenEvents(){var e;const n=await fetch(`${this.linkAPIUrl}/events?unseen=true`,{headers:{Authorization:this.auth}});if(n.ok){const{events:s,error:i}=await n.json();if(i)throw new Error(`Check unseen events failed: ${i}`);const r=(e=s==null?void 0:s.filter(a=>a.event==="Web3Response").map(a=>({type:"Event",sessionId:this.sessionId,eventId:a.id,event:a.event,data:a.data})))!==null&&e!==void 0?e:[];return this.markUnseenEventsAsSeen(r),r}throw new Error(`Check unseen events failed: ${n.status}`)}}var M;(function(t){t[t.DISCONNECTED=0]="DISCONNECTED",t[t.CONNECTING=1]="CONNECTING",t[t.CONNECTED=2]="CONNECTED"})(M||(M={}));class Ht{setConnectionStateListener(e){this.connectionStateListener=e}setIncomingDataListener(e){this.incomingDataListener=e}constructor(e,n=WebSocket){this.WebSocketClass=n,this.webSocket=null,this.pendingData=[],this.url=e.replace(/^http/,"ws")}async connect(){if(this.webSocket)throw new Error("webSocket object is not null");return new Promise((e,n)=>{var s;let i;try{this.webSocket=i=new this.WebSocketClass(this.url)}catch(r){n(r);return}(s=this.connectionStateListener)===null||s===void 0||s.call(this,M.CONNECTING),i.onclose=r=>{var a;this.clearWebSocket(),n(new Error(`websocket error ${r.code}: ${r.reason}`)),(a=this.connectionStateListener)===null||a===void 0||a.call(this,M.DISCONNECTED)},i.onopen=r=>{var a;e(),(a=this.connectionStateListener)===null||a===void 0||a.call(this,M.CONNECTED),this.pendingData.length>0&&([...this.pendingData].forEach(c=>this.sendData(c)),this.pendingData=[])},i.onmessage=r=>{var a,o;if(r.data==="h")(a=this.incomingDataListener)===null||a===void 0||a.call(this,{type:"Heartbeat"});else try{const c=JSON.parse(r.data);(o=this.incomingDataListener)===null||o===void 0||o.call(this,c)}catch{}}})}disconnect(){var e;const{webSocket:n}=this;if(n){this.clearWebSocket(),(e=this.connectionStateListener)===null||e===void 0||e.call(this,M.DISCONNECTED),this.connectionStateListener=void 0,this.incomingDataListener=void 0;try{n.close()}catch{}}}sendData(e){const{webSocket:n}=this;if(!n){this.pendingData.push(e),this.connect();return}n.send(e)}clearWebSocket(){const{webSocket:e}=this;e&&(this.webSocket=null,e.onclose=null,e.onerror=null,e.onmessage=null,e.onopen=null)}}const fe=1e4,Gt=6e4;class Yt{constructor({session:e,linkAPIUrl:n,listener:s}){this.destroyed=!1,this.lastHeartbeatResponse=0,this.nextReqId=S(1),this._connected=!1,this._linked=!1,this.shouldFetchUnseenEventsOnConnect=!1,this.requestResolutions=new Map,this.handleSessionMetadataUpdated=r=>{if(!r)return;new Map([["__destroyed",this.handleDestroyed],["EthereumAddress",this.handleAccountUpdated],["WalletUsername",this.handleWalletUsernameUpdated],["AppVersion",this.handleAppVersionUpdated],["ChainId",o=>r.JsonRpcUrl&&this.handleChainUpdated(o,r.JsonRpcUrl)]]).forEach((o,c)=>{const d=r[c];d!==void 0&&o(d)})},this.handleDestroyed=r=>{var a;r==="1"&&((a=this.listener)===null||a===void 0||a.resetAndReload())},this.handleAccountUpdated=async r=>{var a;const o=await this.cipher.decrypt(r);(a=this.listener)===null||a===void 0||a.accountUpdated(o)},this.handleMetadataUpdated=async(r,a)=>{var o;const c=await this.cipher.decrypt(a);(o=this.listener)===null||o===void 0||o.metadataUpdated(r,c)},this.handleWalletUsernameUpdated=async r=>{this.handleMetadataUpdated(qt,r)},this.handleAppVersionUpdated=async r=>{this.handleMetadataUpdated(Bt,r)},this.handleChainUpdated=async(r,a)=>{var o;const c=await this.cipher.decrypt(r),d=await this.cipher.decrypt(a);(o=this.listener)===null||o===void 0||o.chainUpdated(c,d)},this.session=e,this.cipher=new zt(e.secret),this.listener=s;const i=new Ht(`${n}/rpc`,WebSocket);i.setConnectionStateListener(async r=>{let a=!1;switch(r){case M.DISCONNECTED:if(!this.destroyed){const o=async()=>{await new Promise(c=>setTimeout(c,5e3)),this.destroyed||i.connect().catch(()=>{o()})};o()}break;case M.CONNECTED:a=await this.handleConnected(),this.updateLastHeartbeat(),setInterval(()=>{this.heartbeat()},fe),this.shouldFetchUnseenEventsOnConnect&&this.fetchUnseenEventsAPI();break;case M.CONNECTING:break}this.connected!==a&&(this.connected=a)}),i.setIncomingDataListener(r=>{var a;switch(r.type){case"Heartbeat":this.updateLastHeartbeat();return;case"IsLinkedOK":case"Linked":{const o=r.type==="IsLinkedOK"?r.linked:void 0;this.linked=o||r.onlineGuests>0;break}case"GetSessionConfigOK":case"SessionConfigUpdated":{this.handleSessionMetadataUpdated(r.metadata);break}case"Event":{this.handleIncomingEvent(r);break}}r.id!==void 0&&((a=this.requestResolutions.get(r.id))===null||a===void 0||a(r))}),this.ws=i,this.http=new Ft(n,e.id,e.key)}connect(){if(this.destroyed)throw new Error("instance is destroyed");this.ws.connect()}async destroy(){this.destroyed||(await this.makeRequest({type:"SetSessionConfig",id:S(this.nextReqId++),sessionId:this.session.id,metadata:{__destroyed:"1"}},{timeout:1e3}),this.destroyed=!0,this.ws.disconnect(),this.listener=void 0)}get connected(){return this._connected}set connected(e){this._connected=e}get linked(){return this._linked}set linked(e){var n,s;this._linked=e,e&&((n=this.onceLinked)===null||n===void 0||n.call(this)),(s=this.listener)===null||s===void 0||s.linkedUpdated(e)}setOnceLinked(e){return new Promise(n=>{this.linked?e().then(n):this.onceLinked=()=>{e().then(n),this.onceLinked=void 0}})}async handleIncomingEvent(e){var n;if(e.type!=="Event"||e.event!=="Web3Response")return;const s=await this.cipher.decrypt(e.data),i=JSON.parse(s);if(i.type!=="WEB3_RESPONSE")return;const{id:r,response:a}=i;(n=this.listener)===null||n===void 0||n.handleWeb3ResponseMessage(r,a)}async checkUnseenEvents(){if(!this.connected){this.shouldFetchUnseenEventsOnConnect=!0;return}await new Promise(e=>setTimeout(e,250));try{await this.fetchUnseenEventsAPI()}catch(e){console.error("Unable to check for unseen events",e)}}async fetchUnseenEventsAPI(){this.shouldFetchUnseenEventsOnConnect=!1,(await this.http.fetchUnseenEvents()).forEach(n=>this.handleIncomingEvent(n))}async publishEvent(e,n,s=!1){const i=await this.cipher.encrypt(JSON.stringify(Object.assign(Object.assign({},n),{origin:location.origin,relaySource:"coinbaseWalletExtension"in window&&window.coinbaseWalletExtension?"injected_sdk":"sdk"}))),r={type:"PublishEvent",id:S(this.nextReqId++),sessionId:this.session.id,event:e,data:i,callWebhook:s};return this.setOnceLinked(async()=>{const a=await this.makeRequest(r);if(a.type==="Fail")throw new Error(a.error||"failed to publish event");return a.eventId})}sendData(e){this.ws.sendData(JSON.stringify(e))}updateLastHeartbeat(){this.lastHeartbeatResponse=Date.now()}heartbeat(){if(Date.now()-this.lastHeartbeatResponse>fe*2){this.ws.disconnect();return}try{this.ws.sendData("h")}catch{}}async makeRequest(e,n={timeout:Gt}){const s=e.id;this.sendData(e);let i;return Promise.race([new Promise((r,a)=>{i=window.setTimeout(()=>{a(new Error(`request ${s} timed out`))},n.timeout)}),new Promise(r=>{this.requestResolutions.set(s,a=>{clearTimeout(i),r(a),this.requestResolutions.delete(s)})})])}async handleConnected(){return(await this.makeRequest({type:"HostSession",id:S(this.nextReqId++),sessionId:this.session.id,sessionKey:this.session.key})).type==="Fail"?!1:(this.sendData({type:"IsLinked",id:S(this.nextReqId++),sessionId:this.session.id}),this.sendData({type:"GetSessionConfig",id:S(this.nextReqId++),sessionId:this.session.id}),!0)}}class $t{constructor(){this._nextRequestId=0,this.callbacks=new Map}makeRequestId(){this._nextRequestId=(this._nextRequestId+1)%2147483647;const e=this._nextRequestId,n=Le(e.toString(16));return this.callbacks.get(n)&&this.callbacks.delete(n),e}}const ge="session:id",me="session:secret",be="session:linked";class T{constructor(e,n,s,i=!1){this.storage=e,this.id=n,this.secret=s,this.key=nt.bytesToHex(st(`${n}, ${s} WalletLink`)),this._linked=!!i}static create(e){const n=x(16),s=x(32);return new T(e,n,s).save()}static load(e){const n=e.getItem(ge),s=e.getItem(be),i=e.getItem(me);return n&&i?new T(e,n,i,s==="1"):null}get linked(){return this._linked}set linked(e){this._linked=e,this.persistLinked()}save(){return this.storage.setItem(ge,this.id),this.storage.setItem(me,this.secret),this.persistLinked(),this}persistLinked(){this.storage.setItem(be,this._linked?"1":"0")}}function Jt(){try{return window.frameElement!==null}catch{return!1}}function Vt(){try{return Jt()&&window.top?window.top.location:window.location}catch{return window.location}}function Qt(){var t;return/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test((t=window==null?void 0:window.navigator)===null||t===void 0?void 0:t.userAgent)}function $e(){var t,e;return(e=(t=window==null?void 0:window.matchMedia)===null||t===void 0?void 0:t.call(window,"(prefers-color-scheme: dark)").matches)!==null&&e!==void 0?e:!1}const Zt='@namespace svg "http://www.w3.org/2000/svg";.-cbwsdk-css-reset,.-cbwsdk-css-reset *{animation:none;animation-delay:0;animation-direction:normal;animation-duration:0;animation-fill-mode:none;animation-iteration-count:1;animation-name:none;animation-play-state:running;animation-timing-function:ease;backface-visibility:visible;background:0;background-attachment:scroll;background-clip:border-box;background-color:rgba(0,0,0,0);background-image:none;background-origin:padding-box;background-position:0 0;background-position-x:0;background-position-y:0;background-repeat:repeat;background-size:auto auto;border:0;border-style:none;border-width:medium;border-color:inherit;border-bottom:0;border-bottom-color:inherit;border-bottom-left-radius:0;border-bottom-right-radius:0;border-bottom-style:none;border-bottom-width:medium;border-collapse:separate;border-image:none;border-left:0;border-left-color:inherit;border-left-style:none;border-left-width:medium;border-radius:0;border-right:0;border-right-color:inherit;border-right-style:none;border-right-width:medium;border-spacing:0;border-top:0;border-top-color:inherit;border-top-left-radius:0;border-top-right-radius:0;border-top-style:none;border-top-width:medium;box-shadow:none;box-sizing:border-box;caption-side:top;clear:none;clip:auto;color:inherit;columns:auto;column-count:auto;column-fill:balance;column-gap:normal;column-rule:medium none currentColor;column-rule-color:currentColor;column-rule-style:none;column-rule-width:none;column-span:1;column-width:auto;counter-increment:none;counter-reset:none;direction:ltr;empty-cells:show;float:none;font:normal;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI","Helvetica Neue",Arial,sans-serif;font-size:medium;font-style:normal;font-variant:normal;font-weight:normal;height:auto;hyphens:none;letter-spacing:normal;line-height:normal;list-style:none;list-style-image:none;list-style-position:outside;list-style-type:disc;margin:0;margin-bottom:0;margin-left:0;margin-right:0;margin-top:0;opacity:1;orphans:0;outline:0;outline-color:invert;outline-style:none;outline-width:medium;overflow:visible;overflow-x:visible;overflow-y:visible;padding:0;padding-bottom:0;padding-left:0;padding-right:0;padding-top:0;page-break-after:auto;page-break-before:auto;page-break-inside:auto;perspective:none;perspective-origin:50% 50%;pointer-events:auto;position:static;quotes:"\\201C" "\\201D" "\\2018" "\\2019";tab-size:8;table-layout:auto;text-align:inherit;text-align-last:auto;text-decoration:none;text-decoration-color:inherit;text-decoration-line:none;text-decoration-style:solid;text-indent:0;text-shadow:none;text-transform:none;transform:none;transform-style:flat;transition:none;transition-delay:0s;transition-duration:0s;transition-property:none;transition-timing-function:ease;unicode-bidi:normal;vertical-align:baseline;visibility:visible;white-space:normal;widows:0;word-spacing:normal;z-index:auto}.-cbwsdk-css-reset strong{font-weight:bold}.-cbwsdk-css-reset *{box-sizing:border-box;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI","Helvetica Neue",Arial,sans-serif;line-height:1}.-cbwsdk-css-reset [class*=container]{margin:0;padding:0}.-cbwsdk-css-reset style{display:none}';function Je(){const t=document.createElement("style");t.type="text/css",t.appendChild(document.createTextNode(Zt)),document.documentElement.appendChild(t)}const Xt=".-cbwsdk-css-reset .-gear-container{margin-left:16px !important;margin-right:9px !important;display:flex;align-items:center;justify-content:center;width:24px;height:24px;transition:opacity .25s}.-cbwsdk-css-reset .-gear-container *{user-select:none}.-cbwsdk-css-reset .-gear-container svg{opacity:0;position:absolute}.-cbwsdk-css-reset .-gear-icon{height:12px;width:12px;z-index:10000}.-cbwsdk-css-reset .-cbwsdk-snackbar{align-items:flex-end;display:flex;flex-direction:column;position:fixed;right:0;top:0;z-index:2147483647}.-cbwsdk-css-reset .-cbwsdk-snackbar *{user-select:none}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance{display:flex;flex-direction:column;margin:8px 16px 0 16px;overflow:visible;text-align:left;transform:translateX(0);transition:opacity .25s,transform .25s}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-header:hover .-gear-container svg{opacity:1}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-header{display:flex;align-items:center;background:#fff;overflow:hidden;border:1px solid #e7ebee;box-sizing:border-box;border-radius:8px;cursor:pointer}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-header-cblogo{margin:8px 8px 8px 8px}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-header *{cursor:pointer}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-header-message{color:#000;font-size:13px;line-height:1.5;user-select:none}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu{background:#fff;transition:opacity .25s ease-in-out,transform .25s linear,visibility 0s;visibility:hidden;border:1px solid #e7ebee;box-sizing:border-box;border-radius:8px;opacity:0;flex-direction:column;padding-left:8px;padding-right:8px}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item:last-child{margin-bottom:8px !important}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item:hover{background:#f5f7f8;border-radius:6px;transition:background .25s}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item:hover span{color:#050f19;transition:color .25s}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item:hover svg path{fill:#000;transition:fill .25s}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item{visibility:inherit;height:35px;margin-top:8px;margin-bottom:0;display:flex;flex-direction:row;align-items:center;padding:8px;cursor:pointer}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item *{visibility:inherit;cursor:pointer}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item-is-red:hover{background:rgba(223,95,103,.2);transition:background .25s}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item-is-red:hover *{cursor:pointer}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item-is-red:hover svg path{fill:#df5f67;transition:fill .25s}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item-is-red:hover span{color:#df5f67;transition:color .25s}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item-info{color:#aaa;font-size:13px;margin:0 8px 0 32px;position:absolute}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-hidden{opacity:0;text-align:left;transform:translateX(25%);transition:opacity .5s linear}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-expanded .-cbwsdk-snackbar-instance-menu{opacity:1;display:flex;transform:translateY(8px);visibility:visible}",en="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMzIiIGhlaWdodD0iMzIiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PHBhdGggZD0iTTEuNDkyIDEwLjQxOWE4LjkzIDguOTMgMCAwMTguOTMtOC45M2gxMS4xNjNhOC45MyA4LjkzIDAgMDE4LjkzIDguOTN2MTEuMTYzYTguOTMgOC45MyAwIDAxLTguOTMgOC45M0gxMC40MjJhOC45MyA4LjkzIDAgMDEtOC45My04LjkzVjEwLjQxOXoiIGZpbGw9IiMxNjUyRjAiLz48cGF0aCBmaWxsLXJ1bGU9ImV2ZW5vZGQiIGNsaXAtcnVsZT0iZXZlbm9kZCIgZD0iTTEwLjQxOSAwSDIxLjU4QzI3LjMzNSAwIDMyIDQuNjY1IDMyIDEwLjQxOVYyMS41OEMzMiAyNy4zMzUgMjcuMzM1IDMyIDIxLjU4MSAzMkgxMC40MkM0LjY2NSAzMiAwIDI3LjMzNSAwIDIxLjU4MVYxMC40MkMwIDQuNjY1IDQuNjY1IDAgMTAuNDE5IDB6bTAgMS40ODhhOC45MyA4LjkzIDAgMDAtOC45MyA4LjkzdjExLjE2M2E4LjkzIDguOTMgMCAwMDguOTMgOC45M0gyMS41OGE4LjkzIDguOTMgMCAwMDguOTMtOC45M1YxMC40MmE4LjkzIDguOTMgMCAwMC04LjkzLTguOTNIMTAuNDJ6IiBmaWxsPSIjZmZmIi8+PHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik0xNS45OTggMjYuMDQ5Yy01LjU0OSAwLTEwLjA0Ny00LjQ5OC0xMC4wNDctMTAuMDQ3IDAtNS41NDggNC40OTgtMTAuMDQ2IDEwLjA0Ny0xMC4wNDYgNS41NDggMCAxMC4wNDYgNC40OTggMTAuMDQ2IDEwLjA0NiAwIDUuNTQ5LTQuNDk4IDEwLjA0Ny0xMC4wNDYgMTAuMDQ3eiIgZmlsbD0iI2ZmZiIvPjxwYXRoIGQ9Ik0xMi43NjIgMTQuMjU0YzAtLjgyMi42NjctMS40ODkgMS40ODktMS40ODloMy40OTdjLjgyMiAwIDEuNDg4LjY2NiAxLjQ4OCAxLjQ4OXYzLjQ5N2MwIC44MjItLjY2NiAxLjQ4OC0xLjQ4OCAxLjQ4OGgtMy40OTdhMS40ODggMS40ODggMCAwMS0xLjQ4OS0xLjQ4OHYtMy40OTh6IiBmaWxsPSIjMTY1MkYwIi8+PC9zdmc+",tn="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTIiIGhlaWdodD0iMTIiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PHBhdGggZD0iTTEyIDYuNzV2LTEuNWwtMS43Mi0uNTdjLS4wOC0uMjctLjE5LS41Mi0uMzItLjc3bC44MS0xLjYyLTEuMDYtMS4wNi0xLjYyLjgxYy0uMjQtLjEzLS41LS4yNC0uNzctLjMyTDYuNzUgMGgtMS41bC0uNTcgMS43MmMtLjI3LjA4LS41My4xOS0uNzcuMzJsLTEuNjItLjgxLTEuMDYgMS4wNi44MSAxLjYyYy0uMTMuMjQtLjI0LjUtLjMyLjc3TDAgNS4yNXYxLjVsMS43Mi41N2MuMDguMjcuMTkuNTMuMzIuNzdsLS44MSAxLjYyIDEuMDYgMS4wNiAxLjYyLS44MWMuMjQuMTMuNS4yMy43Ny4zMkw1LjI1IDEyaDEuNWwuNTctMS43MmMuMjctLjA4LjUyLS4xOS43Ny0uMzJsMS42Mi44MSAxLjA2LTEuMDYtLjgxLTEuNjJjLjEzLS4yNC4yMy0uNS4zMi0uNzdMMTIgNi43NXpNNiA4LjVhMi41IDIuNSAwIDAxMC01IDIuNSAyLjUgMCAwMTAgNXoiIGZpbGw9IiMwNTBGMTkiLz48L3N2Zz4=";class nn{constructor(){this.items=new Map,this.nextItemKey=0,this.root=null,this.darkMode=$e()}attach(e){this.root=document.createElement("div"),this.root.className="-cbwsdk-snackbar-root",e.appendChild(this.root),this.render()}presentItem(e){const n=this.nextItemKey++;return this.items.set(n,e),this.render(),()=>{this.items.delete(n),this.render()}}clear(){this.items.clear(),this.render()}render(){this.root&&V(u("div",null,u(Ve,{darkMode:this.darkMode},Array.from(this.items.entries()).map(([e,n])=>u(sn,Object.assign({},n,{key:e}))))),this.root)}}const Ve=t=>u("div",{class:D("-cbwsdk-snackbar-container")},u("style",null,Xt),u("div",{class:"-cbwsdk-snackbar"},t.children)),sn=({autoExpand:t,message:e,menuItems:n})=>{const[s,i]=ae(!0),[r,a]=ae(t??!1);rt(()=>{const c=[window.setTimeout(()=>{i(!1)},1),window.setTimeout(()=>{a(!0)},1e4)];return()=>{c.forEach(window.clearTimeout)}});const o=()=>{a(!r)};return u("div",{class:D("-cbwsdk-snackbar-instance",s&&"-cbwsdk-snackbar-instance-hidden",r&&"-cbwsdk-snackbar-instance-expanded")},u("div",{class:"-cbwsdk-snackbar-instance-header",onClick:o},u("img",{src:en,class:"-cbwsdk-snackbar-instance-header-cblogo"})," ",u("div",{class:"-cbwsdk-snackbar-instance-header-message"},e),u("div",{class:"-gear-container"},!r&&u("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg"},u("circle",{cx:"12",cy:"12",r:"12",fill:"#F5F7F8"})),u("img",{src:tn,class:"-gear-icon",title:"Expand"}))),n&&n.length>0&&u("div",{class:"-cbwsdk-snackbar-instance-menu"},n.map((c,d)=>u("div",{class:D("-cbwsdk-snackbar-instance-menu-item",c.isRed&&"-cbwsdk-snackbar-instance-menu-item-is-red"),onClick:c.onClick,key:d},u("svg",{width:c.svgWidth,height:c.svgHeight,viewBox:"0 0 10 11",fill:"none",xmlns:"http://www.w3.org/2000/svg"},u("path",{"fill-rule":c.defaultFillRule,"clip-rule":c.defaultClipRule,d:c.path,fill:"#AAAAAA"})),u("span",{class:D("-cbwsdk-snackbar-instance-menu-item-info",c.isRed&&"-cbwsdk-snackbar-instance-menu-item-info-is-red")},c.info)))))};class rn{constructor(){this.attached=!1,this.snackbar=new nn}attach(){if(this.attached)throw new Error("Coinbase Wallet SDK UI is already attached");const e=document.documentElement,n=document.createElement("div");n.className="-cbwsdk-css-reset",e.appendChild(n),this.snackbar.attach(n),this.attached=!0,Je()}showConnecting(e){let n;return e.isUnlinkedErrorState?n={autoExpand:!0,message:"Connection lost",menuItems:[{isRed:!1,info:"Reset connection",svgWidth:"10",svgHeight:"11",path:"M5.00008 0.96875C6.73133 0.96875 8.23758 1.94375 9.00008 3.375L10.0001 2.375V5.5H9.53133H7.96883H6.87508L7.80633 4.56875C7.41258 3.3875 6.31258 2.53125 5.00008 2.53125C3.76258 2.53125 2.70633 3.2875 2.25633 4.36875L0.812576 3.76875C1.50008 2.125 3.11258 0.96875 5.00008 0.96875ZM2.19375 6.43125C2.5875 7.6125 3.6875 8.46875 5 8.46875C6.2375 8.46875 7.29375 7.7125 7.74375 6.63125L9.1875 7.23125C8.5 8.875 6.8875 10.0312 5 10.0312C3.26875 10.0312 1.7625 9.05625 1 7.625L0 8.625V5.5H0.46875H2.03125H3.125L2.19375 6.43125Z",defaultFillRule:"evenodd",defaultClipRule:"evenodd",onClick:e.onResetConnection}]}:n={message:"Confirm on phone",menuItems:[{isRed:!0,info:"Cancel transaction",svgWidth:"11",svgHeight:"11",path:"M10.3711 1.52346L9.21775 0.370117L5.37109 4.21022L1.52444 0.370117L0.371094 1.52346L4.2112 5.37012L0.371094 9.21677L1.52444 10.3701L5.37109 6.53001L9.21775 10.3701L10.3711 9.21677L6.53099 5.37012L10.3711 1.52346Z",defaultFillRule:"inherit",defaultClipRule:"inherit",onClick:e.onCancel},{isRed:!1,info:"Reset connection",svgWidth:"10",svgHeight:"11",path:"M5.00008 0.96875C6.73133 0.96875 8.23758 1.94375 9.00008 3.375L10.0001 2.375V5.5H9.53133H7.96883H6.87508L7.80633 4.56875C7.41258 3.3875 6.31258 2.53125 5.00008 2.53125C3.76258 2.53125 2.70633 3.2875 2.25633 4.36875L0.812576 3.76875C1.50008 2.125 3.11258 0.96875 5.00008 0.96875ZM2.19375 6.43125C2.5875 7.6125 3.6875 8.46875 5 8.46875C6.2375 8.46875 7.29375 7.7125 7.74375 6.63125L9.1875 7.23125C8.5 8.875 6.8875 10.0312 5 10.0312C3.26875 10.0312 1.7625 9.05625 1 7.625L0 8.625V5.5H0.46875H2.03125H3.125L2.19375 6.43125Z",defaultFillRule:"evenodd",defaultClipRule:"evenodd",onClick:e.onResetConnection}]},this.snackbar.presentItem(n)}}const an=".-cbwsdk-css-reset .-cbwsdk-redirect-dialog-backdrop{position:fixed;top:0;left:0;right:0;bottom:0;transition:opacity .25s;background-color:rgba(10,11,13,.5)}.-cbwsdk-css-reset .-cbwsdk-redirect-dialog-backdrop-hidden{opacity:0}.-cbwsdk-css-reset .-cbwsdk-redirect-dialog-box{display:block;position:fixed;top:50%;left:50%;transform:translate(-50%, -50%);padding:20px;border-radius:8px;background-color:#fff;color:#0a0b0d}.-cbwsdk-css-reset .-cbwsdk-redirect-dialog-box p{display:block;font-weight:400;font-size:14px;line-height:20px;padding-bottom:12px;color:#5b636e}.-cbwsdk-css-reset .-cbwsdk-redirect-dialog-box button{appearance:none;border:none;background:none;color:#0052ff;padding:0;text-decoration:none;display:block;font-weight:600;font-size:16px;line-height:24px}.-cbwsdk-css-reset .-cbwsdk-redirect-dialog-box.dark{background-color:#0a0b0d;color:#fff}.-cbwsdk-css-reset .-cbwsdk-redirect-dialog-box.dark button{color:#0052ff}.-cbwsdk-css-reset .-cbwsdk-redirect-dialog-box.light{background-color:#fff;color:#0a0b0d}.-cbwsdk-css-reset .-cbwsdk-redirect-dialog-box.light button{color:#0052ff}";class on{constructor(){this.root=null,this.darkMode=$e()}attach(){const e=document.documentElement;this.root=document.createElement("div"),this.root.className="-cbwsdk-css-reset",e.appendChild(this.root),Je()}present(e){this.render(e)}clear(){this.render(null)}render(e){this.root&&(V(null,this.root),e&&V(u(cn,Object.assign({},e,{onDismiss:()=>{this.clear()},darkMode:this.darkMode})),this.root))}}const cn=({title:t,buttonText:e,darkMode:n,onButtonClick:s,onDismiss:i})=>{const r=n?"dark":"light";return u(Ve,{darkMode:n},u("div",{class:"-cbwsdk-redirect-dialog"},u("style",null,an),u("div",{class:"-cbwsdk-redirect-dialog-backdrop",onClick:i}),u("div",{class:D("-cbwsdk-redirect-dialog-box",r)},u("p",null,t),u("button",{onClick:s},e))))},dn="https://keys.coinbase.com/connect",we="https://www.walletlink.org",ln="https://go.cb-w.com/walletlink";class ye{constructor(){this.attached=!1,this.redirectDialog=new on}attach(){if(this.attached)throw new Error("Coinbase Wallet SDK UI is already attached");this.redirectDialog.attach(),this.attached=!0}redirectToCoinbaseWallet(e){const n=new URL(ln);n.searchParams.append("redirect_url",Vt().href),e&&n.searchParams.append("wl_url",e);const s=document.createElement("a");s.target="cbw-opener",s.href=n.href,s.rel="noreferrer noopener",s.click()}openCoinbaseWalletDeeplink(e){this.redirectDialog.present({title:"Redirecting to Coinbase Wallet...",buttonText:"Open",onButtonClick:()=>{this.redirectToCoinbaseWallet(e)}}),setTimeout(()=>{this.redirectToCoinbaseWallet(e)},99)}showConnecting(e){return()=>{this.redirectDialog.clear()}}}class C{constructor(e){this.chainCallbackParams={chainId:"",jsonRpcUrl:""},this.isMobileWeb=Qt(),this.linkedUpdated=r=>{this.isLinked=r;const a=this.storage.getItem(ee);if(r&&(this._session.linked=r),this.isUnlinkedErrorState=!1,a){const o=a.split(" "),c=this.storage.getItem("IsStandaloneSigning")==="true";o[0]!==""&&!r&&this._session.linked&&!c&&(this.isUnlinkedErrorState=!0)}},this.metadataUpdated=(r,a)=>{this.storage.setItem(r,a)},this.chainUpdated=(r,a)=>{this.chainCallbackParams.chainId===r&&this.chainCallbackParams.jsonRpcUrl===a||(this.chainCallbackParams={chainId:r,jsonRpcUrl:a},this.chainCallback&&this.chainCallback(a,Number.parseInt(r,10)))},this.accountUpdated=r=>{this.accountsCallback&&this.accountsCallback([r]),C.accountRequestCallbackIds.size>0&&(Array.from(C.accountRequestCallbackIds.values()).forEach(a=>{this.invokeCallback(a,{method:"requestEthereumAccounts",result:[r]})}),C.accountRequestCallbackIds.clear())},this.resetAndReload=this.resetAndReload.bind(this),this.linkAPIUrl=e.linkAPIUrl,this.storage=e.storage,this.metadata=e.metadata,this.accountsCallback=e.accountsCallback,this.chainCallback=e.chainCallback;const{session:n,ui:s,connection:i}=this.subscribe();this._session=n,this.connection=i,this.relayEventManager=new $t,this.ui=s,this.ui.attach()}subscribe(){const e=T.load(this.storage)||T.create(this.storage),{linkAPIUrl:n}=this,s=new Yt({session:e,linkAPIUrl:n,listener:this}),i=this.isMobileWeb?new ye:new rn;return s.connect(),{session:e,ui:i,connection:s}}resetAndReload(){this.connection.destroy().then(()=>{const e=T.load(this.storage);(e==null?void 0:e.id)===this._session.id&&E.clearAll(),document.location.reload()}).catch(e=>{})}signEthereumTransaction(e){return this.sendRequest({method:"signEthereumTransaction",params:{fromAddress:e.fromAddress,toAddress:e.toAddress,weiValue:v(e.weiValue),data:O(e.data,!0),nonce:e.nonce,gasPriceInWei:e.gasPriceInWei?v(e.gasPriceInWei):null,maxFeePerGas:e.gasPriceInWei?v(e.gasPriceInWei):null,maxPriorityFeePerGas:e.gasPriceInWei?v(e.gasPriceInWei):null,gasLimit:e.gasLimit?v(e.gasLimit):null,chainId:e.chainId,shouldSubmit:!1}})}signAndSubmitEthereumTransaction(e){return this.sendRequest({method:"signEthereumTransaction",params:{fromAddress:e.fromAddress,toAddress:e.toAddress,weiValue:v(e.weiValue),data:O(e.data,!0),nonce:e.nonce,gasPriceInWei:e.gasPriceInWei?v(e.gasPriceInWei):null,maxFeePerGas:e.maxFeePerGas?v(e.maxFeePerGas):null,maxPriorityFeePerGas:e.maxPriorityFeePerGas?v(e.maxPriorityFeePerGas):null,gasLimit:e.gasLimit?v(e.gasLimit):null,chainId:e.chainId,shouldSubmit:!0}})}submitEthereumTransaction(e,n){return this.sendRequest({method:"submitEthereumTransaction",params:{signedTransaction:O(e,!0),chainId:n}})}getWalletLinkSession(){return this._session}sendRequest(e){let n=null;const s=x(8),i=r=>{this.publishWeb3RequestCanceledEvent(s),this.handleErrorResponse(s,e.method,r),n==null||n()};return new Promise((r,a)=>{n=this.ui.showConnecting({isUnlinkedErrorState:this.isUnlinkedErrorState,onCancel:i,onResetConnection:this.resetAndReload}),this.relayEventManager.callbacks.set(s,o=>{if(n==null||n(),m(o))return a(new Error(o.errorMessage));r(o)}),this.publishWeb3RequestEvent(s,e)})}publishWeb3RequestEvent(e,n){const s={type:"WEB3_REQUEST",id:e,request:n};this.publishEvent("Web3Request",s,!0).then(i=>{}).catch(i=>{this.handleWeb3ResponseMessage(s.id,{method:n.method,errorMessage:i.message})}),this.isMobileWeb&&this.openCoinbaseWalletDeeplink(n.method)}openCoinbaseWalletDeeplink(e){if(this.ui instanceof ye)switch(e){case"requestEthereumAccounts":case"switchEthereumChain":return;default:window.addEventListener("blur",()=>{window.addEventListener("focus",()=>{this.connection.checkUnseenEvents()},{once:!0})},{once:!0}),this.ui.openCoinbaseWalletDeeplink();break}}publishWeb3RequestCanceledEvent(e){const n={type:"WEB3_REQUEST_CANCELED",id:e};this.publishEvent("Web3RequestCanceled",n,!1).then()}publishEvent(e,n,s){return this.connection.publishEvent(e,n,s)}handleWeb3ResponseMessage(e,n){if(n.method==="requestEthereumAccounts"){C.accountRequestCallbackIds.forEach(s=>this.invokeCallback(s,n)),C.accountRequestCallbackIds.clear();return}this.invokeCallback(e,n)}handleErrorResponse(e,n,s){var i;const r=(i=s==null?void 0:s.message)!==null&&i!==void 0?i:"Unspecified error message.";this.handleWeb3ResponseMessage(e,{method:n,errorMessage:r})}invokeCallback(e,n){const s=this.relayEventManager.callbacks.get(e);s&&(s(n),this.relayEventManager.callbacks.delete(e))}requestEthereumAccounts(){const{appName:e,appLogoUrl:n}=this.metadata,s={method:"requestEthereumAccounts",params:{appName:e,appLogoUrl:n}},i=x(8);return new Promise((r,a)=>{this.relayEventManager.callbacks.set(i,o=>{if(m(o))return a(new Error(o.errorMessage));r(o)}),C.accountRequestCallbackIds.add(i),this.publishWeb3RequestEvent(i,s)})}watchAsset(e,n,s,i,r,a){const o={method:"watchAsset",params:{type:e,options:{address:n,symbol:s,decimals:i,image:r},chainId:a}};let c=null;const d=x(8),g=p=>{this.publishWeb3RequestCanceledEvent(d),this.handleErrorResponse(d,o.method,p),c==null||c()};return c=this.ui.showConnecting({isUnlinkedErrorState:this.isUnlinkedErrorState,onCancel:g,onResetConnection:this.resetAndReload}),new Promise((p,f)=>{this.relayEventManager.callbacks.set(d,I=>{if(c==null||c(),m(I))return f(new Error(I.errorMessage));p(I)}),this.publishWeb3RequestEvent(d,o)})}addEthereumChain(e,n,s,i,r,a){const o={method:"addEthereumChain",params:{chainId:e,rpcUrls:n,blockExplorerUrls:i,chainName:r,iconUrls:s,nativeCurrency:a}};let c=null;const d=x(8),g=p=>{this.publishWeb3RequestCanceledEvent(d),this.handleErrorResponse(d,o.method,p),c==null||c()};return c=this.ui.showConnecting({isUnlinkedErrorState:this.isUnlinkedErrorState,onCancel:g,onResetConnection:this.resetAndReload}),new Promise((p,f)=>{this.relayEventManager.callbacks.set(d,I=>{if(c==null||c(),m(I))return f(new Error(I.errorMessage));p(I)}),this.publishWeb3RequestEvent(d,o)})}switchEthereumChain(e,n){const s={method:"switchEthereumChain",params:Object.assign({chainId:e},{address:n})};let i=null;const r=x(8),a=o=>{this.publishWeb3RequestCanceledEvent(r),this.handleErrorResponse(r,s.method,o),i==null||i()};return i=this.ui.showConnecting({isUnlinkedErrorState:this.isUnlinkedErrorState,onCancel:a,onResetConnection:this.resetAndReload}),new Promise((o,c)=>{this.relayEventManager.callbacks.set(r,d=>{if(i==null||i(),m(d)&&d.errorCode)return c(l.provider.custom({code:d.errorCode,message:"Unrecognized chain ID. Try adding the chain using addEthereumChain first."}));if(m(d))return c(new Error(d.errorMessage));o(d)}),this.publishWeb3RequestEvent(r,s)})}}C.accountRequestCallbackIds=new Set;const ve="DefaultChainId",ke="DefaultJsonRpcUrl";class Qe{constructor(e){this._relay=null,this._addresses=[],this.metadata=e.metadata,this._storage=new E("walletlink",we),this.callback=e.callback||null;const n=this._storage.getItem(ee);if(n){const s=n.split(" ");s[0]!==""&&(this._addresses=s.map(i=>_(i)))}this.initializeRelay()}getSession(){const e=this.initializeRelay(),{id:n,secret:s}=e.getWalletLinkSession();return{id:n,secret:s}}async handshake(){await this._eth_requestAccounts()}get selectedAddress(){return this._addresses[0]||void 0}get jsonRpcUrl(){var e;return(e=this._storage.getItem(ke))!==null&&e!==void 0?e:void 0}set jsonRpcUrl(e){this._storage.setItem(ke,e)}updateProviderInfo(e,n){var s;this.jsonRpcUrl=e;const i=this.getChainId();this._storage.setItem(ve,n.toString(10)),j(n)!==i&&((s=this.callback)===null||s===void 0||s.call(this,"chainChanged",A(n)))}async watchAsset(e){const n=Array.isArray(e)?e[0]:e;if(!n.type)throw l.rpc.invalidParams("Type is required");if((n==null?void 0:n.type)!=="ERC20")throw l.rpc.invalidParams(`Asset of type '${n.type}' is not supported`);if(!(n!=null&&n.options))throw l.rpc.invalidParams("Options are required");if(!(n!=null&&n.options.address))throw l.rpc.invalidParams("Address is required");const s=this.getChainId(),{address:i,symbol:r,image:a,decimals:o}=n.options,d=await this.initializeRelay().watchAsset(n.type,i,r,o,a,s==null?void 0:s.toString());return m(d)?!1:!!d.result}async addEthereumChain(e){var n,s;const i=e[0];if(((n=i.rpcUrls)===null||n===void 0?void 0:n.length)===0)throw l.rpc.invalidParams("please pass in at least 1 rpcUrl");if(!i.chainName||i.chainName.trim()==="")throw l.rpc.invalidParams("chainName is a required field");if(!i.nativeCurrency)throw l.rpc.invalidParams("nativeCurrency is a required field");const r=Number.parseInt(i.chainId,16);if(r===this.getChainId())return!1;const a=this.initializeRelay(),{rpcUrls:o=[],blockExplorerUrls:c=[],chainName:d,iconUrls:g=[],nativeCurrency:p}=i,f=await a.addEthereumChain(r.toString(),o,g,c,d,p);if(m(f))return!1;if(((s=f.result)===null||s===void 0?void 0:s.isApproved)===!0)return this.updateProviderInfo(o[0],r),null;throw l.rpc.internal("unable to add ethereum chain")}async switchEthereumChain(e){const n=e[0],s=Number.parseInt(n.chainId,16),r=await this.initializeRelay().switchEthereumChain(s.toString(10),this.selectedAddress||void 0);if(m(r))throw r;const a=r.result;return a.isApproved&&a.rpcUrl.length>0&&this.updateProviderInfo(a.rpcUrl,s),null}async cleanup(){this.callback=null,this._relay&&this._relay.resetAndReload(),this._storage.clear()}_setAddresses(e,n){var s;if(!Array.isArray(e))throw new Error("addresses is not an array");const i=e.map(r=>_(r));JSON.stringify(i)!==JSON.stringify(this._addresses)&&(this._addresses=i,(s=this.callback)===null||s===void 0||s.call(this,"accountsChanged",i),this._storage.setItem(ee,i.join(" ")))}async request(e){const n=e.params||[];switch(e.method){case"eth_accounts":return[...this._addresses];case"eth_coinbase":return this.selectedAddress||null;case"net_version":return this.getChainId().toString(10);case"eth_chainId":return A(this.getChainId());case"eth_requestAccounts":return this._eth_requestAccounts();case"eth_ecRecover":case"personal_ecRecover":return this.ecRecover(e);case"personal_sign":return this.personalSign(e);case"eth_signTransaction":return this._eth_signTransaction(n);case"eth_sendRawTransaction":return this._eth_sendRawTransaction(n);case"eth_sendTransaction":return this._eth_sendTransaction(n);case"eth_signTypedData_v1":case"eth_signTypedData_v3":case"eth_signTypedData_v4":case"eth_signTypedData":return this.signTypedData(e);case"wallet_addEthereumChain":return this.addEthereumChain(n);case"wallet_switchEthereumChain":return this.switchEthereumChain(n);case"wallet_watchAsset":return this.watchAsset(n);default:if(!this.jsonRpcUrl)throw l.rpc.internal("No RPC URL set for chain");return je(e,this.jsonRpcUrl)}}_ensureKnownAddress(e){const n=_(e);if(!this._addresses.map(i=>_(i)).includes(n))throw new Error("Unknown Ethereum address")}_prepareTransactionParams(e){const n=e.from?_(e.from):this.selectedAddress;if(!n)throw new Error("Ethereum address is unavailable");this._ensureKnownAddress(n);const s=e.to?_(e.to):null,i=e.value!=null?N(e.value):BigInt(0),r=e.data?X(e.data):Buffer.alloc(0),a=e.nonce!=null?j(e.nonce):null,o=e.gasPrice!=null?N(e.gasPrice):null,c=e.maxFeePerGas!=null?N(e.maxFeePerGas):null,d=e.maxPriorityFeePerGas!=null?N(e.maxPriorityFeePerGas):null,g=e.gas!=null?N(e.gas):null,p=e.chainId?j(e.chainId):this.getChainId();return{fromAddress:n,toAddress:s,weiValue:i,data:r,nonce:a,gasPriceInWei:o,maxFeePerGas:c,maxPriorityFeePerGas:d,gasLimit:g,chainId:p}}async ecRecover(e){const{method:n,params:s}=e;if(!Array.isArray(s))throw l.rpc.invalidParams();const r=await this.initializeRelay().sendRequest({method:"ethereumAddressFromSignedMessage",params:{message:H(s[0]),signature:H(s[1]),addPrefix:n==="personal_ecRecover"}});if(m(r))throw r;return r.result}getChainId(){var e;return Number.parseInt((e=this._storage.getItem(ve))!==null&&e!==void 0?e:"1",10)}async _eth_requestAccounts(){var e,n;if(this._addresses.length>0)return(e=this.callback)===null||e===void 0||e.call(this,"connect",{chainId:A(this.getChainId())}),this._addresses;const i=await this.initializeRelay().requestEthereumAccounts();if(m(i))throw i;if(!i.result)throw new Error("accounts received is empty");return this._setAddresses(i.result),(n=this.callback)===null||n===void 0||n.call(this,"connect",{chainId:A(this.getChainId())}),this._addresses}async personalSign({params:e}){if(!Array.isArray(e))throw l.rpc.invalidParams();const n=e[1],s=e[0];this._ensureKnownAddress(n);const r=await this.initializeRelay().sendRequest({method:"signEthereumMessage",params:{address:_(n),message:H(s),addPrefix:!0,typedDataJson:null}});if(m(r))throw r;return r.result}async _eth_signTransaction(e){const n=this._prepareTransactionParams(e[0]||{}),i=await this.initializeRelay().signEthereumTransaction(n);if(m(i))throw i;return i.result}async _eth_sendRawTransaction(e){const n=X(e[0]),i=await this.initializeRelay().submitEthereumTransaction(n,this.getChainId());if(m(i))throw i;return i.result}async _eth_sendTransaction(e){const n=this._prepareTransactionParams(e[0]||{}),i=await this.initializeRelay().signAndSubmitEthereumTransaction(n);if(m(i))throw i;return i.result}async signTypedData(e){const{method:n,params:s}=e;if(!Array.isArray(s))throw l.rpc.invalidParams();const i=d=>{const g={eth_signTypedData_v1:q.hashForSignTypedDataLegacy,eth_signTypedData_v3:q.hashForSignTypedData_v3,eth_signTypedData_v4:q.hashForSignTypedData_v4,eth_signTypedData:q.hashForSignTypedData_v4};return O(g[n]({data:pt(d)}),!0)},r=s[n==="eth_signTypedData_v1"?1:0],a=s[n==="eth_signTypedData_v1"?0:1];this._ensureKnownAddress(r);const c=await this.initializeRelay().sendRequest({method:"signEthereumMessage",params:{address:_(r),message:i(a),typedDataJson:JSON.stringify(a,null,2),addPrefix:!1}});if(m(c))throw c;return c.result}initializeRelay(){return this._relay||(this._relay=new C({linkAPIUrl:we,storage:this._storage,metadata:this.metadata,accountsCallback:this._setAddresses.bind(this),chainCallback:this.updateProviderInfo.bind(this)})),this._relay}}const Ze="SignerType",Xe=new E("CBWSDK","SignerConfigurator");function un(){return Xe.getItem(Ze)}function hn(t){Xe.setItem(Ze,t)}async function pn(t){const{communicator:e,metadata:n,handshakeRequest:s,callback:i}=t;gn(e,n,i).catch(()=>{});const r={id:crypto.randomUUID(),event:"selectSignerType",data:Object.assign(Object.assign({},t.preference),{handshakeRequest:s})},{data:a}=await e.postRequestAndWaitForResponse(r);return a}function fn(t){const{signerType:e,metadata:n,communicator:s,callback:i}=t;switch(e){case"scw":return new Mt({metadata:n,callback:i,communicator:s});case"walletlink":return new Qe({metadata:n,callback:i})}}async function gn(t,e,n){await t.onMessage(({event:i})=>i==="WalletLinkSessionRequest");const s=new Qe({metadata:e,callback:n});t.postMessage({event:"WalletLinkUpdate",data:{session:s.getSession()}}),await s.handshake(),t.postMessage({event:"WalletLinkUpdate",data:{connected:!0}})}const mn=`Coinbase Wallet SDK requires the Cross-Origin-Opener-Policy header to not be set to 'same-origin'. This is to ensure that the SDK can communicate with the Coinbase Smart Wallet app.
|
|
1
|
+
import{j as et,g as tt,u as nt,k as st,E as it}from"./index-qgo91dsq.js";import{D as V,g as u,c as D,h as ae,y as rt}from"./hooks.module-C5ONEBEq.js";class E{constructor(e,n){this.scope=e,this.module=n}storeObject(e,n){this.setItem(e,JSON.stringify(n))}loadObject(e){const n=this.getItem(e);return n?JSON.parse(n):void 0}setItem(e,n){localStorage.setItem(this.scopedKey(e),n)}getItem(e){return localStorage.getItem(this.scopedKey(e))}removeItem(e){localStorage.removeItem(this.scopedKey(e))}clear(){const e=this.scopedKey(""),n=[];for(let s=0;s<localStorage.length;s++){const i=localStorage.key(s);typeof i=="string"&&i.startsWith(e)&&n.push(i)}n.forEach(s=>localStorage.removeItem(s))}scopedKey(e){return`-${this.scope}${this.module?`:${this.module}`:""}:${e}`}static clearAll(){new E("CBWSDK").clear(),new E("walletlink").clear()}}const h={rpc:{invalidInput:-32e3,resourceNotFound:-32001,resourceUnavailable:-32002,transactionRejected:-32003,methodNotSupported:-32004,limitExceeded:-32005,parse:-32700,invalidRequest:-32600,methodNotFound:-32601,invalidParams:-32602,internal:-32603},provider:{userRejectedRequest:4001,unauthorized:4100,unsupportedMethod:4200,disconnected:4900,chainDisconnected:4901,unsupportedChain:4902}},Q={"-32700":{standard:"JSON RPC 2.0",message:"Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text."},"-32600":{standard:"JSON RPC 2.0",message:"The JSON sent is not a valid Request object."},"-32601":{standard:"JSON RPC 2.0",message:"The method does not exist / is not available."},"-32602":{standard:"JSON RPC 2.0",message:"Invalid method parameter(s)."},"-32603":{standard:"JSON RPC 2.0",message:"Internal JSON-RPC error."},"-32000":{standard:"EIP-1474",message:"Invalid input."},"-32001":{standard:"EIP-1474",message:"Resource not found."},"-32002":{standard:"EIP-1474",message:"Resource unavailable."},"-32003":{standard:"EIP-1474",message:"Transaction rejected."},"-32004":{standard:"EIP-1474",message:"Method not supported."},"-32005":{standard:"EIP-1474",message:"Request limit exceeded."},4001:{standard:"EIP-1193",message:"User rejected the request."},4100:{standard:"EIP-1193",message:"The requested account and/or method has not been authorized by the user."},4200:{standard:"EIP-1193",message:"The requested method is not supported by this Ethereum provider."},4900:{standard:"EIP-1193",message:"The provider is disconnected from all chains."},4901:{standard:"EIP-1193",message:"The provider is disconnected from the specified chain."},4902:{standard:"EIP-3085",message:"Unrecognized chain ID."}},Se="Unspecified error message.",at="Unspecified server error.";function te(t,e=Se){if(t&&Number.isInteger(t)){const n=t.toString();if(Z(Q,n))return Q[n].message;if(Ce(t))return at}return e}function ot(t){if(!Number.isInteger(t))return!1;const e=t.toString();return!!(Q[e]||Ce(t))}function ct(t,{shouldIncludeStack:e=!1}={}){const n={};if(t&&typeof t=="object"&&!Array.isArray(t)&&Z(t,"code")&&ot(t.code)){const s=t;n.code=s.code,s.message&&typeof s.message=="string"?(n.message=s.message,Z(s,"data")&&(n.data=s.data)):(n.message=te(n.code),n.data={originalError:oe(t)})}else n.code=h.rpc.internal,n.message=ce(t,"message")?t.message:Se,n.data={originalError:oe(t)};return e&&(n.stack=ce(t,"stack")?t.stack:void 0),n}function Ce(t){return t>=-32099&&t<=-32e3}function oe(t){return t&&typeof t=="object"&&!Array.isArray(t)?Object.assign({},t):t}function Z(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function ce(t,e){return typeof t=="object"&&t!==null&&e in t&&typeof t[e]=="string"}const l={rpc:{parse:t=>w(h.rpc.parse,t),invalidRequest:t=>w(h.rpc.invalidRequest,t),invalidParams:t=>w(h.rpc.invalidParams,t),methodNotFound:t=>w(h.rpc.methodNotFound,t),internal:t=>w(h.rpc.internal,t),server:t=>{if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Ethereum RPC Server errors must provide single object argument.");const{code:e}=t;if(!Number.isInteger(e)||e>-32005||e<-32099)throw new Error('"code" must be an integer such that: -32099 <= code <= -32005');return w(e,t)},invalidInput:t=>w(h.rpc.invalidInput,t),resourceNotFound:t=>w(h.rpc.resourceNotFound,t),resourceUnavailable:t=>w(h.rpc.resourceUnavailable,t),transactionRejected:t=>w(h.rpc.transactionRejected,t),methodNotSupported:t=>w(h.rpc.methodNotSupported,t),limitExceeded:t=>w(h.rpc.limitExceeded,t)},provider:{userRejectedRequest:t=>R(h.provider.userRejectedRequest,t),unauthorized:t=>R(h.provider.unauthorized,t),unsupportedMethod:t=>R(h.provider.unsupportedMethod,t),disconnected:t=>R(h.provider.disconnected,t),chainDisconnected:t=>R(h.provider.chainDisconnected,t),unsupportedChain:t=>R(h.provider.unsupportedChain,t),custom:t=>{if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Ethereum Provider custom errors must provide single object argument.");const{code:e,message:n,data:s}=t;if(!n||typeof n!="string")throw new Error('"message" must be a nonempty string');return new Ae(e,n,s)}}};function w(t,e){const[n,s]=Me(e);return new _e(t,n||te(t),s)}function R(t,e){const[n,s]=Me(e);return new Ae(t,n||te(t),s)}function Me(t){if(t){if(typeof t=="string")return[t];if(typeof t=="object"&&!Array.isArray(t)){const{message:e,data:n}=t;if(e&&typeof e!="string")throw new Error("Must specify string message.");return[e||void 0,n]}}return[]}class _e extends Error{constructor(e,n,s){if(!Number.isInteger(e))throw new Error('"code" must be an integer.');if(!n||typeof n!="string")throw new Error('"message" must be a nonempty string.');super(n),this.code=e,s!==void 0&&(this.data=s)}}class Ae extends _e{constructor(e,n,s){if(!dt(e))throw new Error('"code" must be an integer such that: 1000 <= code <= 4999');super(e,n,s)}}function dt(t){return Number.isInteger(t)&&t>=1e3&&t<=4999}function ne(){return t=>t}const W=ne(),lt=ne(),ut=ne();function S(t){return Math.floor(t)}const xe=/^[0-9]*$/,Pe=/^[a-f0-9]*$/;function x(t){return se(crypto.getRandomValues(new Uint8Array(t)))}function se(t){return[...t].map(e=>e.toString(16).padStart(2,"0")).join("")}function B(t){return new Uint8Array(t.match(/.{1,2}/g).map(e=>Number.parseInt(e,16)))}function O(t,e=!1){const n=t.toString("hex");return W(e?`0x${n}`:n)}function H(t){return O(X(t),!0)}function v(t){return ut(t.toString(10))}function A(t){return W(`0x${BigInt(t).toString(16)}`)}function Re(t){return t.startsWith("0x")||t.startsWith("0X")}function ie(t){return Re(t)?t.slice(2):t}function Le(t){return Re(t)?`0x${t.slice(2)}`:`0x${t}`}function z(t){if(typeof t!="string")return!1;const e=ie(t).toLowerCase();return Pe.test(e)}function ht(t,e=!1){if(typeof t=="string"){const n=ie(t).toLowerCase();if(Pe.test(n))return W(e?`0x${n}`:n)}throw l.rpc.invalidParams(`"${String(t)}" is not a hexadecimal string`)}function re(t,e=!1){let n=ht(t,!1);return n.length%2===1&&(n=W(`0${n}`)),e?W(`0x${n}`):n}function _(t){if(typeof t=="string"){const e=ie(t).toLowerCase();if(z(e)&&e.length===40)return lt(Le(e))}throw l.rpc.invalidParams(`Invalid Ethereum address: ${String(t)}`)}function X(t){if(Buffer.isBuffer(t))return t;if(typeof t=="string"){if(z(t)){const e=re(t,!1);return Buffer.from(e,"hex")}return Buffer.from(t,"utf8")}throw l.rpc.invalidParams(`Not binary data: ${String(t)}`)}function j(t){if(typeof t=="number"&&Number.isInteger(t))return S(t);if(typeof t=="string"){if(xe.test(t))return S(Number(t));if(z(t))return S(Number(BigInt(re(t,!0))))}throw l.rpc.invalidParams(`Not an integer: ${String(t)}`)}function N(t){if(t!==null&&(typeof t=="bigint"||ft(t)))return BigInt(t.toString(10));if(typeof t=="number")return BigInt(j(t));if(typeof t=="string"){if(xe.test(t))return BigInt(t);if(z(t))return BigInt(re(t,!0))}throw l.rpc.invalidParams(`Not an integer: ${String(t)}`)}function pt(t){if(typeof t=="string")return JSON.parse(t);if(typeof t=="object")return t;throw l.rpc.invalidParams(`Not a JSON string or an object: ${String(t)}`)}function ft(t){if(t==null||typeof t.constructor!="function")return!1;const{constructor:e}=t;return typeof e.config=="function"&&typeof e.EUCLID=="number"}async function gt(){return crypto.subtle.generateKey({name:"ECDH",namedCurve:"P-256"},!0,["deriveKey"])}async function mt(t,e){return crypto.subtle.deriveKey({name:"ECDH",public:e},t,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}async function bt(t,e){const n=crypto.getRandomValues(new Uint8Array(12)),s=await crypto.subtle.encrypt({name:"AES-GCM",iv:n},t,new TextEncoder().encode(e));return{iv:n,cipherText:s}}async function wt(t,{iv:e,cipherText:n}){const s=await crypto.subtle.decrypt({name:"AES-GCM",iv:e},t,n);return new TextDecoder().decode(s)}function Te(t){switch(t){case"public":return"spki";case"private":return"pkcs8"}}async function Ne(t,e){const n=Te(t),s=await crypto.subtle.exportKey(n,e);return se(new Uint8Array(s))}async function De(t,e){const n=Te(t),s=B(e).buffer;return await crypto.subtle.importKey(n,new Uint8Array(s),{name:"ECDH",namedCurve:"P-256"},!0,t==="private"?["deriveKey"]:[])}async function yt(t,e){const n=JSON.stringify(t,(s,i)=>{if(!(i instanceof Error))return i;const r=i;return Object.assign(Object.assign({},r.code?{code:r.code}:{}),{message:r.message})});return bt(e,n)}async function vt(t,e){return JSON.parse(await wt(e,t))}const G={storageKey:"ownPrivateKey",keyType:"private"},Y={storageKey:"ownPublicKey",keyType:"public"},$={storageKey:"peerPublicKey",keyType:"public"};class kt{constructor(){this.storage=new E("CBWSDK","SCWKeyManager"),this.ownPrivateKey=null,this.ownPublicKey=null,this.peerPublicKey=null,this.sharedSecret=null}async getOwnPublicKey(){return await this.loadKeysIfNeeded(),this.ownPublicKey}async getSharedSecret(){return await this.loadKeysIfNeeded(),this.sharedSecret}async setPeerPublicKey(e){this.sharedSecret=null,this.peerPublicKey=e,await this.storeKey($,e),await this.loadKeysIfNeeded()}async clear(){this.ownPrivateKey=null,this.ownPublicKey=null,this.peerPublicKey=null,this.sharedSecret=null,this.storage.removeItem(Y.storageKey),this.storage.removeItem(G.storageKey),this.storage.removeItem($.storageKey)}async generateKeyPair(){const e=await gt();this.ownPrivateKey=e.privateKey,this.ownPublicKey=e.publicKey,await this.storeKey(G,e.privateKey),await this.storeKey(Y,e.publicKey)}async loadKeysIfNeeded(){if(this.ownPrivateKey===null&&(this.ownPrivateKey=await this.loadKey(G)),this.ownPublicKey===null&&(this.ownPublicKey=await this.loadKey(Y)),(this.ownPrivateKey===null||this.ownPublicKey===null)&&await this.generateKeyPair(),this.peerPublicKey===null&&(this.peerPublicKey=await this.loadKey($)),this.sharedSecret===null){if(this.ownPrivateKey===null||this.peerPublicKey===null)return;this.sharedSecret=await mt(this.ownPrivateKey,this.peerPublicKey)}}async loadKey(e){const n=this.storage.getItem(e.storageKey);return n?De(e.keyType,n):null}async storeKey(e,n){const s=await Ne(e.keyType,n);this.storage.setItem(e.storageKey,s)}}const K="4.2.3",Oe="@coinbase/wallet-sdk";async function je(t,e){const n=Object.assign(Object.assign({},t),{jsonrpc:"2.0",id:crypto.randomUUID()}),s=await window.fetch(e,{method:"POST",body:JSON.stringify(n),mode:"cors",headers:{"Content-Type":"application/json","X-Cbw-Sdk-Version":K,"X-Cbw-Sdk-Platform":Oe}}),{result:i,error:r}=await s.json();if(r)throw r;return i}function Et(){return globalThis.coinbaseWalletExtension}function It(){var t,e;try{const n=globalThis;return(t=n.ethereum)!==null&&t!==void 0?t:(e=n.top)===null||e===void 0?void 0:e.ethereum}catch{return}}function St({metadata:t,preference:e}){var n,s;const{appName:i,appLogoUrl:r,appChainIds:a}=t;if(e.options!=="smartWalletOnly"){const c=Et();if(c)return(n=c.setAppInfo)===null||n===void 0||n.call(c,i,r,a,e),c}const o=It();if(o!=null&&o.isCoinbaseBrowser)return(s=o.setAppInfo)===null||s===void 0||s.call(o,i,r,a,e),o}function Ct(t){if(!t||typeof t!="object"||Array.isArray(t))throw l.rpc.invalidParams({message:"Expected a single, non-array, object argument.",data:t});const{method:e,params:n}=t;if(typeof e!="string"||e.length===0)throw l.rpc.invalidParams({message:"'args.method' must be a non-empty string.",data:t});if(n!==void 0&&!Array.isArray(n)&&(typeof n!="object"||n===null))throw l.rpc.invalidParams({message:"'args.params' must be an object or array if provided.",data:t});switch(e){case"eth_sign":case"eth_signTypedData_v2":case"eth_subscribe":case"eth_unsubscribe":throw l.provider.unsupportedMethod()}}const de="accounts",le="activeChain",ue="availableChains",he="walletCapabilities";class Mt{constructor(e){var n,s,i;this.metadata=e.metadata,this.communicator=e.communicator,this.callback=e.callback,this.keyManager=new kt,this.storage=new E("CBWSDK","SCWStateManager"),this.accounts=(n=this.storage.loadObject(de))!==null&&n!==void 0?n:[],this.chain=this.storage.loadObject(le)||{id:(i=(s=e.metadata.appChainIds)===null||s===void 0?void 0:s[0])!==null&&i!==void 0?i:1},this.handshake=this.handshake.bind(this),this.request=this.request.bind(this),this.createRequestMessage=this.createRequestMessage.bind(this),this.decryptResponseMessage=this.decryptResponseMessage.bind(this)}async handshake(e){var n,s;const i=await this.createRequestMessage({handshake:{method:e.method,params:Object.assign({},this.metadata,(n=e.params)!==null&&n!==void 0?n:{})}}),r=await this.communicator.postRequestAndWaitForResponse(i);if("failure"in r.content)throw r.content.failure;const a=await De("public",r.sender);await this.keyManager.setPeerPublicKey(a);const c=(await this.decryptResponseMessage(r)).result;if("error"in c)throw c.error;const d=c.value;this.accounts=d,this.storage.storeObject(de,d),(s=this.callback)===null||s===void 0||s.call(this,"accountsChanged",d)}async request(e){var n;if(this.accounts.length===0)throw l.provider.unauthorized();switch(e.method){case"eth_requestAccounts":return(n=this.callback)===null||n===void 0||n.call(this,"connect",{chainId:A(this.chain.id)}),this.accounts;case"eth_accounts":return this.accounts;case"eth_coinbase":return this.accounts[0];case"net_version":return this.chain.id;case"eth_chainId":return A(this.chain.id);case"wallet_getCapabilities":return this.storage.loadObject(he);case"wallet_switchEthereumChain":return this.handleSwitchChainRequest(e);case"eth_ecRecover":case"personal_sign":case"personal_ecRecover":case"eth_signTransaction":case"eth_sendTransaction":case"eth_signTypedData_v1":case"eth_signTypedData_v3":case"eth_signTypedData_v4":case"eth_signTypedData":case"wallet_addEthereumChain":case"wallet_watchAsset":case"wallet_sendCalls":case"wallet_showCallsStatus":case"wallet_grantPermissions":return this.sendRequestToPopup(e);default:if(!this.chain.rpcUrl)throw l.rpc.internal("No RPC URL set for chain");return je(e,this.chain.rpcUrl)}}async sendRequestToPopup(e){var n,s;await((s=(n=this.communicator).waitForPopupLoaded)===null||s===void 0?void 0:s.call(n));const i=await this.sendEncryptedRequest(e),a=(await this.decryptResponseMessage(i)).result;if("error"in a)throw a.error;return a.value}async cleanup(){var e,n;this.storage.clear(),await this.keyManager.clear(),this.accounts=[],this.chain={id:(n=(e=this.metadata.appChainIds)===null||e===void 0?void 0:e[0])!==null&&n!==void 0?n:1}}async handleSwitchChainRequest(e){var n;const s=e.params;if(!s||!(!((n=s[0])===null||n===void 0)&&n.chainId))throw l.rpc.invalidParams();const i=j(s[0].chainId);if(this.updateChain(i))return null;const a=await this.sendRequestToPopup(e);return a===null&&this.updateChain(i),a}async sendEncryptedRequest(e){const n=await this.keyManager.getSharedSecret();if(!n)throw l.provider.unauthorized("No valid session found, try requestAccounts before other methods");const s=await yt({action:e,chainId:this.chain.id},n),i=await this.createRequestMessage({encrypted:s});return this.communicator.postRequestAndWaitForResponse(i)}async createRequestMessage(e){const n=await Ne("public",await this.keyManager.getOwnPublicKey());return{id:crypto.randomUUID(),sender:n,content:e,timestamp:new Date}}async decryptResponseMessage(e){var n,s;const i=e.content;if("failure"in i)throw i.failure;const r=await this.keyManager.getSharedSecret();if(!r)throw l.provider.unauthorized("Invalid session");const a=await vt(i.encrypted,r),o=(n=a.data)===null||n===void 0?void 0:n.chains;if(o){const d=Object.entries(o).map(([g,p])=>({id:Number(g),rpcUrl:p}));this.storage.storeObject(ue,d),this.updateChain(this.chain.id,d)}const c=(s=a.data)===null||s===void 0?void 0:s.capabilities;return c&&this.storage.storeObject(he,c),a}updateChain(e,n){var s;const i=n??this.storage.loadObject(ue),r=i==null?void 0:i.find(a=>a.id===e);return r?(r!==this.chain&&(this.chain=r,this.storage.storeObject(le,r),(s=this.callback)===null||s===void 0||s.call(this,"chainChanged",A(r.id))),!0):!1}}const{keccak_256:_t}=et;function Ue(t){return Buffer.allocUnsafe(t).fill(0)}function At(t){return t.toString(2).length}function We(t,e){let n=t.toString(16);n.length%2!==0&&(n="0"+n);const s=n.match(/.{1,2}/g).map(i=>parseInt(i,16));for(;s.length<e;)s.unshift(0);return Buffer.from(s)}function xt(t,e){const n=t<0n;let s;if(n){const i=(1n<<BigInt(e))-1n;s=(~t&i)+1n}else s=t;return s&=(1n<<BigInt(e))-1n,s}function Ke(t,e,n){const s=Ue(e);return t=F(t),n?t.length<e?(t.copy(s),s):t.slice(0,e):t.length<e?(t.copy(s,e-t.length),s):t.slice(-e)}function Pt(t,e){return Ke(t,e,!0)}function F(t){if(!Buffer.isBuffer(t))if(Array.isArray(t))t=Buffer.from(t);else if(typeof t=="string")qe(t)?t=Buffer.from(Tt(Be(t)),"hex"):t=Buffer.from(t);else if(typeof t=="number")t=intToBuffer(t);else if(t==null)t=Buffer.allocUnsafe(0);else if(typeof t=="bigint")t=We(t);else if(t.toArray)t=Buffer.from(t.toArray());else throw new Error("invalid type");return t}function Rt(t){return t=F(t),"0x"+t.toString("hex")}function Lt(t,e){if(t=F(t),e||(e=256),e!==256)throw new Error("unsupported");return Buffer.from(_t(new Uint8Array(t)))}function Tt(t){return t.length%2?"0"+t:t}function qe(t){return typeof t=="string"&&t.match(/^0x[0-9A-Fa-f]*$/)}function Be(t){return typeof t=="string"&&t.startsWith("0x")?t.slice(2):t}var ze={zeros:Ue,setLength:Ke,setLengthRight:Pt,isHexString:qe,stripHexPrefix:Be,toBuffer:F,bufferToHex:Rt,keccak:Lt,bitLengthFromBigInt:At,bufferBEFromBigInt:We,twosFromBigInt:xt};const b=ze;function Fe(t){return t.startsWith("int[")?"int256"+t.slice(3):t==="int"?"int256":t.startsWith("uint[")?"uint256"+t.slice(4):t==="uint"?"uint256":t.startsWith("fixed[")?"fixed128x128"+t.slice(5):t==="fixed"?"fixed128x128":t.startsWith("ufixed[")?"ufixed128x128"+t.slice(6):t==="ufixed"?"ufixed128x128":t}function L(t){return Number.parseInt(/^\D+(\d+)$/.exec(t)[1],10)}function pe(t){var e=/^\D+(\d+)x(\d+)$/.exec(t);return[Number.parseInt(e[1],10),Number.parseInt(e[2],10)]}function He(t){var e=t.match(/(.*)\[(.*?)\]$/);return e?e[2]===""?"dynamic":Number.parseInt(e[2],10):null}function P(t){var e=typeof t;if(e==="string"||e==="number")return BigInt(t);if(e==="bigint")return t;throw new Error("Argument is not a number")}function k(t,e){var n,s,i,r;if(t==="address")return k("uint160",P(e));if(t==="bool")return k("uint8",e?1:0);if(t==="string")return k("bytes",new Buffer(e,"utf8"));if(Dt(t)){if(typeof e.length>"u")throw new Error("Not an array?");if(n=He(t),n!=="dynamic"&&n!==0&&e.length>n)throw new Error("Elements exceed array size: "+n);i=[],t=t.slice(0,t.lastIndexOf("[")),typeof e=="string"&&(e=JSON.parse(e));for(r in e)i.push(k(t,e[r]));if(n==="dynamic"){var a=k("uint256",e.length);i.unshift(a)}return Buffer.concat(i)}else{if(t==="bytes")return e=new Buffer(e),i=Buffer.concat([k("uint256",e.length),e]),e.length%32!==0&&(i=Buffer.concat([i,b.zeros(32-e.length%32)])),i;if(t.startsWith("bytes")){if(n=L(t),n<1||n>32)throw new Error("Invalid bytes<N> width: "+n);return b.setLengthRight(e,32)}else if(t.startsWith("uint")){if(n=L(t),n%8||n<8||n>256)throw new Error("Invalid uint<N> width: "+n);s=P(e);const o=b.bitLengthFromBigInt(s);if(o>n)throw new Error("Supplied uint exceeds width: "+n+" vs "+o);if(s<0)throw new Error("Supplied uint is negative");return b.bufferBEFromBigInt(s,32)}else if(t.startsWith("int")){if(n=L(t),n%8||n<8||n>256)throw new Error("Invalid int<N> width: "+n);s=P(e);const o=b.bitLengthFromBigInt(s);if(o>n)throw new Error("Supplied int exceeds width: "+n+" vs "+o);const c=b.twosFromBigInt(s,256);return b.bufferBEFromBigInt(c,32)}else if(t.startsWith("ufixed")){if(n=pe(t),s=P(e),s<0)throw new Error("Supplied ufixed is negative");return k("uint256",s*BigInt(2)**BigInt(n[1]))}else if(t.startsWith("fixed"))return n=pe(t),k("int256",P(e)*BigInt(2)**BigInt(n[1]))}throw new Error("Unsupported or invalid type: "+t)}function Nt(t){return t==="string"||t==="bytes"||He(t)==="dynamic"}function Dt(t){return t.lastIndexOf("]")===t.length-1}function Ot(t,e){var n=[],s=[],i=32*t.length;for(var r in t){var a=Fe(t[r]),o=e[r],c=k(a,o);Nt(a)?(n.push(k("uint256",i)),s.push(c),i+=c.length):n.push(c)}return Buffer.concat(n.concat(s))}function Ge(t,e){if(t.length!==e.length)throw new Error("Number of types are not matching the values");for(var n,s,i=[],r=0;r<t.length;r++){var a=Fe(t[r]),o=e[r];if(a==="bytes")i.push(o);else if(a==="string")i.push(new Buffer(o,"utf8"));else if(a==="bool")i.push(new Buffer(o?"01":"00","hex"));else if(a==="address")i.push(b.setLength(o,20));else if(a.startsWith("bytes")){if(n=L(a),n<1||n>32)throw new Error("Invalid bytes<N> width: "+n);i.push(b.setLengthRight(o,n))}else if(a.startsWith("uint")){if(n=L(a),n%8||n<8||n>256)throw new Error("Invalid uint<N> width: "+n);s=P(o);const c=b.bitLengthFromBigInt(s);if(c>n)throw new Error("Supplied uint exceeds width: "+n+" vs "+c);i.push(b.bufferBEFromBigInt(s,n/8))}else if(a.startsWith("int")){if(n=L(a),n%8||n<8||n>256)throw new Error("Invalid int<N> width: "+n);s=P(o);const c=b.bitLengthFromBigInt(s);if(c>n)throw new Error("Supplied int exceeds width: "+n+" vs "+c);const d=b.twosFromBigInt(s,n);i.push(b.bufferBEFromBigInt(d,n/8))}else throw new Error("Unsupported or invalid type: "+a)}return Buffer.concat(i)}function jt(t,e){return b.keccak(Ge(t,e))}var Ut={rawEncode:Ot,solidityPack:Ge,soliditySHA3:jt};const y=ze,U=Ut,Ye={type:"object",properties:{types:{type:"object",additionalProperties:{type:"array",items:{type:"object",properties:{name:{type:"string"},type:{type:"string"}},required:["name","type"]}}},primaryType:{type:"string"},domain:{type:"object"},message:{type:"object"}},required:["types","primaryType","domain","message"]},J={encodeData(t,e,n,s=!0){const i=["bytes32"],r=[this.hashType(t,n)];if(s){const a=(o,c,d)=>{if(n[c]!==void 0)return["bytes32",d==null?"0x0000000000000000000000000000000000000000000000000000000000000000":y.keccak(this.encodeData(c,d,n,s))];if(d===void 0)throw new Error(`missing value for field ${o} of type ${c}`);if(c==="bytes")return["bytes32",y.keccak(d)];if(c==="string")return typeof d=="string"&&(d=Buffer.from(d,"utf8")),["bytes32",y.keccak(d)];if(c.lastIndexOf("]")===c.length-1){const g=c.slice(0,c.lastIndexOf("[")),p=d.map(f=>a(o,g,f));return["bytes32",y.keccak(U.rawEncode(p.map(([f])=>f),p.map(([,f])=>f)))]}return[c,d]};for(const o of n[t]){const[c,d]=a(o.name,o.type,e[o.name]);i.push(c),r.push(d)}}else for(const a of n[t]){let o=e[a.name];if(o!==void 0)if(a.type==="bytes")i.push("bytes32"),o=y.keccak(o),r.push(o);else if(a.type==="string")i.push("bytes32"),typeof o=="string"&&(o=Buffer.from(o,"utf8")),o=y.keccak(o),r.push(o);else if(n[a.type]!==void 0)i.push("bytes32"),o=y.keccak(this.encodeData(a.type,o,n,s)),r.push(o);else{if(a.type.lastIndexOf("]")===a.type.length-1)throw new Error("Arrays currently unimplemented in encodeData");i.push(a.type),r.push(o)}}return U.rawEncode(i,r)},encodeType(t,e){let n="",s=this.findTypeDependencies(t,e).filter(i=>i!==t);s=[t].concat(s.sort());for(const i of s){if(!e[i])throw new Error("No type definition specified: "+i);n+=i+"("+e[i].map(({name:a,type:o})=>o+" "+a).join(",")+")"}return n},findTypeDependencies(t,e,n=[]){if(t=t.match(/^\w*/)[0],n.includes(t)||e[t]===void 0)return n;n.push(t);for(const s of e[t])for(const i of this.findTypeDependencies(s.type,e,n))!n.includes(i)&&n.push(i);return n},hashStruct(t,e,n,s=!0){return y.keccak(this.encodeData(t,e,n,s))},hashType(t,e){return y.keccak(this.encodeType(t,e))},sanitizeData(t){const e={};for(const n in Ye.properties)t[n]&&(e[n]=t[n]);return e.types&&(e.types=Object.assign({EIP712Domain:[]},e.types)),e},hash(t,e=!0){const n=this.sanitizeData(t),s=[Buffer.from("1901","hex")];return s.push(this.hashStruct("EIP712Domain",n.domain,n.types,e)),n.primaryType!=="EIP712Domain"&&s.push(this.hashStruct(n.primaryType,n.message,n.types,e)),y.keccak(Buffer.concat(s))}};var Wt={TYPED_MESSAGE_SCHEMA:Ye,TypedDataUtils:J,hashForSignTypedDataLegacy:function(t){return Kt(t.data)},hashForSignTypedData_v3:function(t){return J.hash(t.data,!1)},hashForSignTypedData_v4:function(t){return J.hash(t.data)}};function Kt(t){const e=new Error("Expect argument to be non-empty array");if(typeof t!="object"||!t.length)throw e;const n=t.map(function(r){return r.type==="bytes"?y.toBuffer(r.value):r.value}),s=t.map(function(r){return r.type}),i=t.map(function(r){if(!r.name)throw e;return r.type+" "+r.name});return U.soliditySHA3(["bytes32","bytes32"],[U.soliditySHA3(new Array(t.length).fill("string"),i),U.soliditySHA3(s,n)])}const q=tt(Wt),qt="walletUsername",ee="Addresses",Bt="AppVersion";function m(t){return t.errorMessage!==void 0}class zt{constructor(e){this.secret=e}async encrypt(e){const n=this.secret;if(n.length!==64)throw Error("secret must be 256 bits");const s=crypto.getRandomValues(new Uint8Array(12)),i=await crypto.subtle.importKey("raw",B(n),{name:"aes-gcm"},!1,["encrypt","decrypt"]),r=new TextEncoder,a=await window.crypto.subtle.encrypt({name:"AES-GCM",iv:s},i,r.encode(e)),o=16,c=a.slice(a.byteLength-o),d=a.slice(0,a.byteLength-o),g=new Uint8Array(c),p=new Uint8Array(d),f=new Uint8Array([...s,...g,...p]);return se(f)}async decrypt(e){const n=this.secret;if(n.length!==64)throw Error("secret must be 256 bits");return new Promise((s,i)=>{(async function(){const r=await crypto.subtle.importKey("raw",B(n),{name:"aes-gcm"},!1,["encrypt","decrypt"]),a=B(e),o=a.slice(0,12),c=a.slice(12,28),d=a.slice(28),g=new Uint8Array([...d,...c]),p={name:"AES-GCM",iv:new Uint8Array(o)};try{const f=await window.crypto.subtle.decrypt(p,r,g),I=new TextDecoder;s(I.decode(f))}catch(f){i(f)}})()})}}class Ft{constructor(e,n,s){this.linkAPIUrl=e,this.sessionId=n;const i=`${n}:${s}`;this.auth=`Basic ${btoa(i)}`}async markUnseenEventsAsSeen(e){return Promise.all(e.map(n=>fetch(`${this.linkAPIUrl}/events/${n.eventId}/seen`,{method:"POST",headers:{Authorization:this.auth}}))).catch(n=>console.error("Unabled to mark event as failed:",n))}async fetchUnseenEvents(){var e;const n=await fetch(`${this.linkAPIUrl}/events?unseen=true`,{headers:{Authorization:this.auth}});if(n.ok){const{events:s,error:i}=await n.json();if(i)throw new Error(`Check unseen events failed: ${i}`);const r=(e=s==null?void 0:s.filter(a=>a.event==="Web3Response").map(a=>({type:"Event",sessionId:this.sessionId,eventId:a.id,event:a.event,data:a.data})))!==null&&e!==void 0?e:[];return this.markUnseenEventsAsSeen(r),r}throw new Error(`Check unseen events failed: ${n.status}`)}}var M;(function(t){t[t.DISCONNECTED=0]="DISCONNECTED",t[t.CONNECTING=1]="CONNECTING",t[t.CONNECTED=2]="CONNECTED"})(M||(M={}));class Ht{setConnectionStateListener(e){this.connectionStateListener=e}setIncomingDataListener(e){this.incomingDataListener=e}constructor(e,n=WebSocket){this.WebSocketClass=n,this.webSocket=null,this.pendingData=[],this.url=e.replace(/^http/,"ws")}async connect(){if(this.webSocket)throw new Error("webSocket object is not null");return new Promise((e,n)=>{var s;let i;try{this.webSocket=i=new this.WebSocketClass(this.url)}catch(r){n(r);return}(s=this.connectionStateListener)===null||s===void 0||s.call(this,M.CONNECTING),i.onclose=r=>{var a;this.clearWebSocket(),n(new Error(`websocket error ${r.code}: ${r.reason}`)),(a=this.connectionStateListener)===null||a===void 0||a.call(this,M.DISCONNECTED)},i.onopen=r=>{var a;e(),(a=this.connectionStateListener)===null||a===void 0||a.call(this,M.CONNECTED),this.pendingData.length>0&&([...this.pendingData].forEach(c=>this.sendData(c)),this.pendingData=[])},i.onmessage=r=>{var a,o;if(r.data==="h")(a=this.incomingDataListener)===null||a===void 0||a.call(this,{type:"Heartbeat"});else try{const c=JSON.parse(r.data);(o=this.incomingDataListener)===null||o===void 0||o.call(this,c)}catch{}}})}disconnect(){var e;const{webSocket:n}=this;if(n){this.clearWebSocket(),(e=this.connectionStateListener)===null||e===void 0||e.call(this,M.DISCONNECTED),this.connectionStateListener=void 0,this.incomingDataListener=void 0;try{n.close()}catch{}}}sendData(e){const{webSocket:n}=this;if(!n){this.pendingData.push(e),this.connect();return}n.send(e)}clearWebSocket(){const{webSocket:e}=this;e&&(this.webSocket=null,e.onclose=null,e.onerror=null,e.onmessage=null,e.onopen=null)}}const fe=1e4,Gt=6e4;class Yt{constructor({session:e,linkAPIUrl:n,listener:s}){this.destroyed=!1,this.lastHeartbeatResponse=0,this.nextReqId=S(1),this._connected=!1,this._linked=!1,this.shouldFetchUnseenEventsOnConnect=!1,this.requestResolutions=new Map,this.handleSessionMetadataUpdated=r=>{if(!r)return;new Map([["__destroyed",this.handleDestroyed],["EthereumAddress",this.handleAccountUpdated],["WalletUsername",this.handleWalletUsernameUpdated],["AppVersion",this.handleAppVersionUpdated],["ChainId",o=>r.JsonRpcUrl&&this.handleChainUpdated(o,r.JsonRpcUrl)]]).forEach((o,c)=>{const d=r[c];d!==void 0&&o(d)})},this.handleDestroyed=r=>{var a;r==="1"&&((a=this.listener)===null||a===void 0||a.resetAndReload())},this.handleAccountUpdated=async r=>{var a;const o=await this.cipher.decrypt(r);(a=this.listener)===null||a===void 0||a.accountUpdated(o)},this.handleMetadataUpdated=async(r,a)=>{var o;const c=await this.cipher.decrypt(a);(o=this.listener)===null||o===void 0||o.metadataUpdated(r,c)},this.handleWalletUsernameUpdated=async r=>{this.handleMetadataUpdated(qt,r)},this.handleAppVersionUpdated=async r=>{this.handleMetadataUpdated(Bt,r)},this.handleChainUpdated=async(r,a)=>{var o;const c=await this.cipher.decrypt(r),d=await this.cipher.decrypt(a);(o=this.listener)===null||o===void 0||o.chainUpdated(c,d)},this.session=e,this.cipher=new zt(e.secret),this.listener=s;const i=new Ht(`${n}/rpc`,WebSocket);i.setConnectionStateListener(async r=>{let a=!1;switch(r){case M.DISCONNECTED:if(!this.destroyed){const o=async()=>{await new Promise(c=>setTimeout(c,5e3)),this.destroyed||i.connect().catch(()=>{o()})};o()}break;case M.CONNECTED:a=await this.handleConnected(),this.updateLastHeartbeat(),setInterval(()=>{this.heartbeat()},fe),this.shouldFetchUnseenEventsOnConnect&&this.fetchUnseenEventsAPI();break;case M.CONNECTING:break}this.connected!==a&&(this.connected=a)}),i.setIncomingDataListener(r=>{var a;switch(r.type){case"Heartbeat":this.updateLastHeartbeat();return;case"IsLinkedOK":case"Linked":{const o=r.type==="IsLinkedOK"?r.linked:void 0;this.linked=o||r.onlineGuests>0;break}case"GetSessionConfigOK":case"SessionConfigUpdated":{this.handleSessionMetadataUpdated(r.metadata);break}case"Event":{this.handleIncomingEvent(r);break}}r.id!==void 0&&((a=this.requestResolutions.get(r.id))===null||a===void 0||a(r))}),this.ws=i,this.http=new Ft(n,e.id,e.key)}connect(){if(this.destroyed)throw new Error("instance is destroyed");this.ws.connect()}async destroy(){this.destroyed||(await this.makeRequest({type:"SetSessionConfig",id:S(this.nextReqId++),sessionId:this.session.id,metadata:{__destroyed:"1"}},{timeout:1e3}),this.destroyed=!0,this.ws.disconnect(),this.listener=void 0)}get connected(){return this._connected}set connected(e){this._connected=e}get linked(){return this._linked}set linked(e){var n,s;this._linked=e,e&&((n=this.onceLinked)===null||n===void 0||n.call(this)),(s=this.listener)===null||s===void 0||s.linkedUpdated(e)}setOnceLinked(e){return new Promise(n=>{this.linked?e().then(n):this.onceLinked=()=>{e().then(n),this.onceLinked=void 0}})}async handleIncomingEvent(e){var n;if(e.type!=="Event"||e.event!=="Web3Response")return;const s=await this.cipher.decrypt(e.data),i=JSON.parse(s);if(i.type!=="WEB3_RESPONSE")return;const{id:r,response:a}=i;(n=this.listener)===null||n===void 0||n.handleWeb3ResponseMessage(r,a)}async checkUnseenEvents(){if(!this.connected){this.shouldFetchUnseenEventsOnConnect=!0;return}await new Promise(e=>setTimeout(e,250));try{await this.fetchUnseenEventsAPI()}catch(e){console.error("Unable to check for unseen events",e)}}async fetchUnseenEventsAPI(){this.shouldFetchUnseenEventsOnConnect=!1,(await this.http.fetchUnseenEvents()).forEach(n=>this.handleIncomingEvent(n))}async publishEvent(e,n,s=!1){const i=await this.cipher.encrypt(JSON.stringify(Object.assign(Object.assign({},n),{origin:location.origin,relaySource:"coinbaseWalletExtension"in window&&window.coinbaseWalletExtension?"injected_sdk":"sdk"}))),r={type:"PublishEvent",id:S(this.nextReqId++),sessionId:this.session.id,event:e,data:i,callWebhook:s};return this.setOnceLinked(async()=>{const a=await this.makeRequest(r);if(a.type==="Fail")throw new Error(a.error||"failed to publish event");return a.eventId})}sendData(e){this.ws.sendData(JSON.stringify(e))}updateLastHeartbeat(){this.lastHeartbeatResponse=Date.now()}heartbeat(){if(Date.now()-this.lastHeartbeatResponse>fe*2){this.ws.disconnect();return}try{this.ws.sendData("h")}catch{}}async makeRequest(e,n={timeout:Gt}){const s=e.id;this.sendData(e);let i;return Promise.race([new Promise((r,a)=>{i=window.setTimeout(()=>{a(new Error(`request ${s} timed out`))},n.timeout)}),new Promise(r=>{this.requestResolutions.set(s,a=>{clearTimeout(i),r(a),this.requestResolutions.delete(s)})})])}async handleConnected(){return(await this.makeRequest({type:"HostSession",id:S(this.nextReqId++),sessionId:this.session.id,sessionKey:this.session.key})).type==="Fail"?!1:(this.sendData({type:"IsLinked",id:S(this.nextReqId++),sessionId:this.session.id}),this.sendData({type:"GetSessionConfig",id:S(this.nextReqId++),sessionId:this.session.id}),!0)}}class $t{constructor(){this._nextRequestId=0,this.callbacks=new Map}makeRequestId(){this._nextRequestId=(this._nextRequestId+1)%2147483647;const e=this._nextRequestId,n=Le(e.toString(16));return this.callbacks.get(n)&&this.callbacks.delete(n),e}}const ge="session:id",me="session:secret",be="session:linked";class T{constructor(e,n,s,i=!1){this.storage=e,this.id=n,this.secret=s,this.key=nt.bytesToHex(st(`${n}, ${s} WalletLink`)),this._linked=!!i}static create(e){const n=x(16),s=x(32);return new T(e,n,s).save()}static load(e){const n=e.getItem(ge),s=e.getItem(be),i=e.getItem(me);return n&&i?new T(e,n,i,s==="1"):null}get linked(){return this._linked}set linked(e){this._linked=e,this.persistLinked()}save(){return this.storage.setItem(ge,this.id),this.storage.setItem(me,this.secret),this.persistLinked(),this}persistLinked(){this.storage.setItem(be,this._linked?"1":"0")}}function Jt(){try{return window.frameElement!==null}catch{return!1}}function Vt(){try{return Jt()&&window.top?window.top.location:window.location}catch{return window.location}}function Qt(){var t;return/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test((t=window==null?void 0:window.navigator)===null||t===void 0?void 0:t.userAgent)}function $e(){var t,e;return(e=(t=window==null?void 0:window.matchMedia)===null||t===void 0?void 0:t.call(window,"(prefers-color-scheme: dark)").matches)!==null&&e!==void 0?e:!1}const Zt='@namespace svg "http://www.w3.org/2000/svg";.-cbwsdk-css-reset,.-cbwsdk-css-reset *{animation:none;animation-delay:0;animation-direction:normal;animation-duration:0;animation-fill-mode:none;animation-iteration-count:1;animation-name:none;animation-play-state:running;animation-timing-function:ease;backface-visibility:visible;background:0;background-attachment:scroll;background-clip:border-box;background-color:rgba(0,0,0,0);background-image:none;background-origin:padding-box;background-position:0 0;background-position-x:0;background-position-y:0;background-repeat:repeat;background-size:auto auto;border:0;border-style:none;border-width:medium;border-color:inherit;border-bottom:0;border-bottom-color:inherit;border-bottom-left-radius:0;border-bottom-right-radius:0;border-bottom-style:none;border-bottom-width:medium;border-collapse:separate;border-image:none;border-left:0;border-left-color:inherit;border-left-style:none;border-left-width:medium;border-radius:0;border-right:0;border-right-color:inherit;border-right-style:none;border-right-width:medium;border-spacing:0;border-top:0;border-top-color:inherit;border-top-left-radius:0;border-top-right-radius:0;border-top-style:none;border-top-width:medium;box-shadow:none;box-sizing:border-box;caption-side:top;clear:none;clip:auto;color:inherit;columns:auto;column-count:auto;column-fill:balance;column-gap:normal;column-rule:medium none currentColor;column-rule-color:currentColor;column-rule-style:none;column-rule-width:none;column-span:1;column-width:auto;counter-increment:none;counter-reset:none;direction:ltr;empty-cells:show;float:none;font:normal;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI","Helvetica Neue",Arial,sans-serif;font-size:medium;font-style:normal;font-variant:normal;font-weight:normal;height:auto;hyphens:none;letter-spacing:normal;line-height:normal;list-style:none;list-style-image:none;list-style-position:outside;list-style-type:disc;margin:0;margin-bottom:0;margin-left:0;margin-right:0;margin-top:0;opacity:1;orphans:0;outline:0;outline-color:invert;outline-style:none;outline-width:medium;overflow:visible;overflow-x:visible;overflow-y:visible;padding:0;padding-bottom:0;padding-left:0;padding-right:0;padding-top:0;page-break-after:auto;page-break-before:auto;page-break-inside:auto;perspective:none;perspective-origin:50% 50%;pointer-events:auto;position:static;quotes:"\\201C" "\\201D" "\\2018" "\\2019";tab-size:8;table-layout:auto;text-align:inherit;text-align-last:auto;text-decoration:none;text-decoration-color:inherit;text-decoration-line:none;text-decoration-style:solid;text-indent:0;text-shadow:none;text-transform:none;transform:none;transform-style:flat;transition:none;transition-delay:0s;transition-duration:0s;transition-property:none;transition-timing-function:ease;unicode-bidi:normal;vertical-align:baseline;visibility:visible;white-space:normal;widows:0;word-spacing:normal;z-index:auto}.-cbwsdk-css-reset strong{font-weight:bold}.-cbwsdk-css-reset *{box-sizing:border-box;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI","Helvetica Neue",Arial,sans-serif;line-height:1}.-cbwsdk-css-reset [class*=container]{margin:0;padding:0}.-cbwsdk-css-reset style{display:none}';function Je(){const t=document.createElement("style");t.type="text/css",t.appendChild(document.createTextNode(Zt)),document.documentElement.appendChild(t)}const Xt=".-cbwsdk-css-reset .-gear-container{margin-left:16px !important;margin-right:9px !important;display:flex;align-items:center;justify-content:center;width:24px;height:24px;transition:opacity .25s}.-cbwsdk-css-reset .-gear-container *{user-select:none}.-cbwsdk-css-reset .-gear-container svg{opacity:0;position:absolute}.-cbwsdk-css-reset .-gear-icon{height:12px;width:12px;z-index:10000}.-cbwsdk-css-reset .-cbwsdk-snackbar{align-items:flex-end;display:flex;flex-direction:column;position:fixed;right:0;top:0;z-index:2147483647}.-cbwsdk-css-reset .-cbwsdk-snackbar *{user-select:none}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance{display:flex;flex-direction:column;margin:8px 16px 0 16px;overflow:visible;text-align:left;transform:translateX(0);transition:opacity .25s,transform .25s}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-header:hover .-gear-container svg{opacity:1}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-header{display:flex;align-items:center;background:#fff;overflow:hidden;border:1px solid #e7ebee;box-sizing:border-box;border-radius:8px;cursor:pointer}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-header-cblogo{margin:8px 8px 8px 8px}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-header *{cursor:pointer}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-header-message{color:#000;font-size:13px;line-height:1.5;user-select:none}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu{background:#fff;transition:opacity .25s ease-in-out,transform .25s linear,visibility 0s;visibility:hidden;border:1px solid #e7ebee;box-sizing:border-box;border-radius:8px;opacity:0;flex-direction:column;padding-left:8px;padding-right:8px}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item:last-child{margin-bottom:8px !important}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item:hover{background:#f5f7f8;border-radius:6px;transition:background .25s}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item:hover span{color:#050f19;transition:color .25s}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item:hover svg path{fill:#000;transition:fill .25s}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item{visibility:inherit;height:35px;margin-top:8px;margin-bottom:0;display:flex;flex-direction:row;align-items:center;padding:8px;cursor:pointer}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item *{visibility:inherit;cursor:pointer}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item-is-red:hover{background:rgba(223,95,103,.2);transition:background .25s}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item-is-red:hover *{cursor:pointer}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item-is-red:hover svg path{fill:#df5f67;transition:fill .25s}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item-is-red:hover span{color:#df5f67;transition:color .25s}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-menu-item-info{color:#aaa;font-size:13px;margin:0 8px 0 32px;position:absolute}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-hidden{opacity:0;text-align:left;transform:translateX(25%);transition:opacity .5s linear}.-cbwsdk-css-reset .-cbwsdk-snackbar-instance-expanded .-cbwsdk-snackbar-instance-menu{opacity:1;display:flex;transform:translateY(8px);visibility:visible}",en="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMzIiIGhlaWdodD0iMzIiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PHBhdGggZD0iTTEuNDkyIDEwLjQxOWE4LjkzIDguOTMgMCAwMTguOTMtOC45M2gxMS4xNjNhOC45MyA4LjkzIDAgMDE4LjkzIDguOTN2MTEuMTYzYTguOTMgOC45MyAwIDAxLTguOTMgOC45M0gxMC40MjJhOC45MyA4LjkzIDAgMDEtOC45My04LjkzVjEwLjQxOXoiIGZpbGw9IiMxNjUyRjAiLz48cGF0aCBmaWxsLXJ1bGU9ImV2ZW5vZGQiIGNsaXAtcnVsZT0iZXZlbm9kZCIgZD0iTTEwLjQxOSAwSDIxLjU4QzI3LjMzNSAwIDMyIDQuNjY1IDMyIDEwLjQxOVYyMS41OEMzMiAyNy4zMzUgMjcuMzM1IDMyIDIxLjU4MSAzMkgxMC40MkM0LjY2NSAzMiAwIDI3LjMzNSAwIDIxLjU4MVYxMC40MkMwIDQuNjY1IDQuNjY1IDAgMTAuNDE5IDB6bTAgMS40ODhhOC45MyA4LjkzIDAgMDAtOC45MyA4LjkzdjExLjE2M2E4LjkzIDguOTMgMCAwMDguOTMgOC45M0gyMS41OGE4LjkzIDguOTMgMCAwMDguOTMtOC45M1YxMC40MmE4LjkzIDguOTMgMCAwMC04LjkzLTguOTNIMTAuNDJ6IiBmaWxsPSIjZmZmIi8+PHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik0xNS45OTggMjYuMDQ5Yy01LjU0OSAwLTEwLjA0Ny00LjQ5OC0xMC4wNDctMTAuMDQ3IDAtNS41NDggNC40OTgtMTAuMDQ2IDEwLjA0Ny0xMC4wNDYgNS41NDggMCAxMC4wNDYgNC40OTggMTAuMDQ2IDEwLjA0NiAwIDUuNTQ5LTQuNDk4IDEwLjA0Ny0xMC4wNDYgMTAuMDQ3eiIgZmlsbD0iI2ZmZiIvPjxwYXRoIGQ9Ik0xMi43NjIgMTQuMjU0YzAtLjgyMi42NjctMS40ODkgMS40ODktMS40ODloMy40OTdjLjgyMiAwIDEuNDg4LjY2NiAxLjQ4OCAxLjQ4OXYzLjQ5N2MwIC44MjItLjY2NiAxLjQ4OC0xLjQ4OCAxLjQ4OGgtMy40OTdhMS40ODggMS40ODggMCAwMS0xLjQ4OS0xLjQ4OHYtMy40OTh6IiBmaWxsPSIjMTY1MkYwIi8+PC9zdmc+",tn="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTIiIGhlaWdodD0iMTIiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PHBhdGggZD0iTTEyIDYuNzV2LTEuNWwtMS43Mi0uNTdjLS4wOC0uMjctLjE5LS41Mi0uMzItLjc3bC44MS0xLjYyLTEuMDYtMS4wNi0xLjYyLjgxYy0uMjQtLjEzLS41LS4yNC0uNzctLjMyTDYuNzUgMGgtMS41bC0uNTcgMS43MmMtLjI3LjA4LS41My4xOS0uNzcuMzJsLTEuNjItLjgxLTEuMDYgMS4wNi44MSAxLjYyYy0uMTMuMjQtLjI0LjUtLjMyLjc3TDAgNS4yNXYxLjVsMS43Mi41N2MuMDguMjcuMTkuNTMuMzIuNzdsLS44MSAxLjYyIDEuMDYgMS4wNiAxLjYyLS44MWMuMjQuMTMuNS4yMy43Ny4zMkw1LjI1IDEyaDEuNWwuNTctMS43MmMuMjctLjA4LjUyLS4xOS43Ny0uMzJsMS42Mi44MSAxLjA2LTEuMDYtLjgxLTEuNjJjLjEzLS4yNC4yMy0uNS4zMi0uNzdMMTIgNi43NXpNNiA4LjVhMi41IDIuNSAwIDAxMC01IDIuNSAyLjUgMCAwMTAgNXoiIGZpbGw9IiMwNTBGMTkiLz48L3N2Zz4=";class nn{constructor(){this.items=new Map,this.nextItemKey=0,this.root=null,this.darkMode=$e()}attach(e){this.root=document.createElement("div"),this.root.className="-cbwsdk-snackbar-root",e.appendChild(this.root),this.render()}presentItem(e){const n=this.nextItemKey++;return this.items.set(n,e),this.render(),()=>{this.items.delete(n),this.render()}}clear(){this.items.clear(),this.render()}render(){this.root&&V(u("div",null,u(Ve,{darkMode:this.darkMode},Array.from(this.items.entries()).map(([e,n])=>u(sn,Object.assign({},n,{key:e}))))),this.root)}}const Ve=t=>u("div",{class:D("-cbwsdk-snackbar-container")},u("style",null,Xt),u("div",{class:"-cbwsdk-snackbar"},t.children)),sn=({autoExpand:t,message:e,menuItems:n})=>{const[s,i]=ae(!0),[r,a]=ae(t??!1);rt(()=>{const c=[window.setTimeout(()=>{i(!1)},1),window.setTimeout(()=>{a(!0)},1e4)];return()=>{c.forEach(window.clearTimeout)}});const o=()=>{a(!r)};return u("div",{class:D("-cbwsdk-snackbar-instance",s&&"-cbwsdk-snackbar-instance-hidden",r&&"-cbwsdk-snackbar-instance-expanded")},u("div",{class:"-cbwsdk-snackbar-instance-header",onClick:o},u("img",{src:en,class:"-cbwsdk-snackbar-instance-header-cblogo"})," ",u("div",{class:"-cbwsdk-snackbar-instance-header-message"},e),u("div",{class:"-gear-container"},!r&&u("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg"},u("circle",{cx:"12",cy:"12",r:"12",fill:"#F5F7F8"})),u("img",{src:tn,class:"-gear-icon",title:"Expand"}))),n&&n.length>0&&u("div",{class:"-cbwsdk-snackbar-instance-menu"},n.map((c,d)=>u("div",{class:D("-cbwsdk-snackbar-instance-menu-item",c.isRed&&"-cbwsdk-snackbar-instance-menu-item-is-red"),onClick:c.onClick,key:d},u("svg",{width:c.svgWidth,height:c.svgHeight,viewBox:"0 0 10 11",fill:"none",xmlns:"http://www.w3.org/2000/svg"},u("path",{"fill-rule":c.defaultFillRule,"clip-rule":c.defaultClipRule,d:c.path,fill:"#AAAAAA"})),u("span",{class:D("-cbwsdk-snackbar-instance-menu-item-info",c.isRed&&"-cbwsdk-snackbar-instance-menu-item-info-is-red")},c.info)))))};class rn{constructor(){this.attached=!1,this.snackbar=new nn}attach(){if(this.attached)throw new Error("Coinbase Wallet SDK UI is already attached");const e=document.documentElement,n=document.createElement("div");n.className="-cbwsdk-css-reset",e.appendChild(n),this.snackbar.attach(n),this.attached=!0,Je()}showConnecting(e){let n;return e.isUnlinkedErrorState?n={autoExpand:!0,message:"Connection lost",menuItems:[{isRed:!1,info:"Reset connection",svgWidth:"10",svgHeight:"11",path:"M5.00008 0.96875C6.73133 0.96875 8.23758 1.94375 9.00008 3.375L10.0001 2.375V5.5H9.53133H7.96883H6.87508L7.80633 4.56875C7.41258 3.3875 6.31258 2.53125 5.00008 2.53125C3.76258 2.53125 2.70633 3.2875 2.25633 4.36875L0.812576 3.76875C1.50008 2.125 3.11258 0.96875 5.00008 0.96875ZM2.19375 6.43125C2.5875 7.6125 3.6875 8.46875 5 8.46875C6.2375 8.46875 7.29375 7.7125 7.74375 6.63125L9.1875 7.23125C8.5 8.875 6.8875 10.0312 5 10.0312C3.26875 10.0312 1.7625 9.05625 1 7.625L0 8.625V5.5H0.46875H2.03125H3.125L2.19375 6.43125Z",defaultFillRule:"evenodd",defaultClipRule:"evenodd",onClick:e.onResetConnection}]}:n={message:"Confirm on phone",menuItems:[{isRed:!0,info:"Cancel transaction",svgWidth:"11",svgHeight:"11",path:"M10.3711 1.52346L9.21775 0.370117L5.37109 4.21022L1.52444 0.370117L0.371094 1.52346L4.2112 5.37012L0.371094 9.21677L1.52444 10.3701L5.37109 6.53001L9.21775 10.3701L10.3711 9.21677L6.53099 5.37012L10.3711 1.52346Z",defaultFillRule:"inherit",defaultClipRule:"inherit",onClick:e.onCancel},{isRed:!1,info:"Reset connection",svgWidth:"10",svgHeight:"11",path:"M5.00008 0.96875C6.73133 0.96875 8.23758 1.94375 9.00008 3.375L10.0001 2.375V5.5H9.53133H7.96883H6.87508L7.80633 4.56875C7.41258 3.3875 6.31258 2.53125 5.00008 2.53125C3.76258 2.53125 2.70633 3.2875 2.25633 4.36875L0.812576 3.76875C1.50008 2.125 3.11258 0.96875 5.00008 0.96875ZM2.19375 6.43125C2.5875 7.6125 3.6875 8.46875 5 8.46875C6.2375 8.46875 7.29375 7.7125 7.74375 6.63125L9.1875 7.23125C8.5 8.875 6.8875 10.0312 5 10.0312C3.26875 10.0312 1.7625 9.05625 1 7.625L0 8.625V5.5H0.46875H2.03125H3.125L2.19375 6.43125Z",defaultFillRule:"evenodd",defaultClipRule:"evenodd",onClick:e.onResetConnection}]},this.snackbar.presentItem(n)}}const an=".-cbwsdk-css-reset .-cbwsdk-redirect-dialog-backdrop{position:fixed;top:0;left:0;right:0;bottom:0;transition:opacity .25s;background-color:rgba(10,11,13,.5)}.-cbwsdk-css-reset .-cbwsdk-redirect-dialog-backdrop-hidden{opacity:0}.-cbwsdk-css-reset .-cbwsdk-redirect-dialog-box{display:block;position:fixed;top:50%;left:50%;transform:translate(-50%, -50%);padding:20px;border-radius:8px;background-color:#fff;color:#0a0b0d}.-cbwsdk-css-reset .-cbwsdk-redirect-dialog-box p{display:block;font-weight:400;font-size:14px;line-height:20px;padding-bottom:12px;color:#5b636e}.-cbwsdk-css-reset .-cbwsdk-redirect-dialog-box button{appearance:none;border:none;background:none;color:#0052ff;padding:0;text-decoration:none;display:block;font-weight:600;font-size:16px;line-height:24px}.-cbwsdk-css-reset .-cbwsdk-redirect-dialog-box.dark{background-color:#0a0b0d;color:#fff}.-cbwsdk-css-reset .-cbwsdk-redirect-dialog-box.dark button{color:#0052ff}.-cbwsdk-css-reset .-cbwsdk-redirect-dialog-box.light{background-color:#fff;color:#0a0b0d}.-cbwsdk-css-reset .-cbwsdk-redirect-dialog-box.light button{color:#0052ff}";class on{constructor(){this.root=null,this.darkMode=$e()}attach(){const e=document.documentElement;this.root=document.createElement("div"),this.root.className="-cbwsdk-css-reset",e.appendChild(this.root),Je()}present(e){this.render(e)}clear(){this.render(null)}render(e){this.root&&(V(null,this.root),e&&V(u(cn,Object.assign({},e,{onDismiss:()=>{this.clear()},darkMode:this.darkMode})),this.root))}}const cn=({title:t,buttonText:e,darkMode:n,onButtonClick:s,onDismiss:i})=>{const r=n?"dark":"light";return u(Ve,{darkMode:n},u("div",{class:"-cbwsdk-redirect-dialog"},u("style",null,an),u("div",{class:"-cbwsdk-redirect-dialog-backdrop",onClick:i}),u("div",{class:D("-cbwsdk-redirect-dialog-box",r)},u("p",null,t),u("button",{onClick:s},e))))},dn="https://keys.coinbase.com/connect",we="https://www.walletlink.org",ln="https://go.cb-w.com/walletlink";class ye{constructor(){this.attached=!1,this.redirectDialog=new on}attach(){if(this.attached)throw new Error("Coinbase Wallet SDK UI is already attached");this.redirectDialog.attach(),this.attached=!0}redirectToCoinbaseWallet(e){const n=new URL(ln);n.searchParams.append("redirect_url",Vt().href),e&&n.searchParams.append("wl_url",e);const s=document.createElement("a");s.target="cbw-opener",s.href=n.href,s.rel="noreferrer noopener",s.click()}openCoinbaseWalletDeeplink(e){this.redirectDialog.present({title:"Redirecting to Coinbase Wallet...",buttonText:"Open",onButtonClick:()=>{this.redirectToCoinbaseWallet(e)}}),setTimeout(()=>{this.redirectToCoinbaseWallet(e)},99)}showConnecting(e){return()=>{this.redirectDialog.clear()}}}class C{constructor(e){this.chainCallbackParams={chainId:"",jsonRpcUrl:""},this.isMobileWeb=Qt(),this.linkedUpdated=r=>{this.isLinked=r;const a=this.storage.getItem(ee);if(r&&(this._session.linked=r),this.isUnlinkedErrorState=!1,a){const o=a.split(" "),c=this.storage.getItem("IsStandaloneSigning")==="true";o[0]!==""&&!r&&this._session.linked&&!c&&(this.isUnlinkedErrorState=!0)}},this.metadataUpdated=(r,a)=>{this.storage.setItem(r,a)},this.chainUpdated=(r,a)=>{this.chainCallbackParams.chainId===r&&this.chainCallbackParams.jsonRpcUrl===a||(this.chainCallbackParams={chainId:r,jsonRpcUrl:a},this.chainCallback&&this.chainCallback(a,Number.parseInt(r,10)))},this.accountUpdated=r=>{this.accountsCallback&&this.accountsCallback([r]),C.accountRequestCallbackIds.size>0&&(Array.from(C.accountRequestCallbackIds.values()).forEach(a=>{this.invokeCallback(a,{method:"requestEthereumAccounts",result:[r]})}),C.accountRequestCallbackIds.clear())},this.resetAndReload=this.resetAndReload.bind(this),this.linkAPIUrl=e.linkAPIUrl,this.storage=e.storage,this.metadata=e.metadata,this.accountsCallback=e.accountsCallback,this.chainCallback=e.chainCallback;const{session:n,ui:s,connection:i}=this.subscribe();this._session=n,this.connection=i,this.relayEventManager=new $t,this.ui=s,this.ui.attach()}subscribe(){const e=T.load(this.storage)||T.create(this.storage),{linkAPIUrl:n}=this,s=new Yt({session:e,linkAPIUrl:n,listener:this}),i=this.isMobileWeb?new ye:new rn;return s.connect(),{session:e,ui:i,connection:s}}resetAndReload(){this.connection.destroy().then(()=>{const e=T.load(this.storage);(e==null?void 0:e.id)===this._session.id&&E.clearAll(),document.location.reload()}).catch(e=>{})}signEthereumTransaction(e){return this.sendRequest({method:"signEthereumTransaction",params:{fromAddress:e.fromAddress,toAddress:e.toAddress,weiValue:v(e.weiValue),data:O(e.data,!0),nonce:e.nonce,gasPriceInWei:e.gasPriceInWei?v(e.gasPriceInWei):null,maxFeePerGas:e.gasPriceInWei?v(e.gasPriceInWei):null,maxPriorityFeePerGas:e.gasPriceInWei?v(e.gasPriceInWei):null,gasLimit:e.gasLimit?v(e.gasLimit):null,chainId:e.chainId,shouldSubmit:!1}})}signAndSubmitEthereumTransaction(e){return this.sendRequest({method:"signEthereumTransaction",params:{fromAddress:e.fromAddress,toAddress:e.toAddress,weiValue:v(e.weiValue),data:O(e.data,!0),nonce:e.nonce,gasPriceInWei:e.gasPriceInWei?v(e.gasPriceInWei):null,maxFeePerGas:e.maxFeePerGas?v(e.maxFeePerGas):null,maxPriorityFeePerGas:e.maxPriorityFeePerGas?v(e.maxPriorityFeePerGas):null,gasLimit:e.gasLimit?v(e.gasLimit):null,chainId:e.chainId,shouldSubmit:!0}})}submitEthereumTransaction(e,n){return this.sendRequest({method:"submitEthereumTransaction",params:{signedTransaction:O(e,!0),chainId:n}})}getWalletLinkSession(){return this._session}sendRequest(e){let n=null;const s=x(8),i=r=>{this.publishWeb3RequestCanceledEvent(s),this.handleErrorResponse(s,e.method,r),n==null||n()};return new Promise((r,a)=>{n=this.ui.showConnecting({isUnlinkedErrorState:this.isUnlinkedErrorState,onCancel:i,onResetConnection:this.resetAndReload}),this.relayEventManager.callbacks.set(s,o=>{if(n==null||n(),m(o))return a(new Error(o.errorMessage));r(o)}),this.publishWeb3RequestEvent(s,e)})}publishWeb3RequestEvent(e,n){const s={type:"WEB3_REQUEST",id:e,request:n};this.publishEvent("Web3Request",s,!0).then(i=>{}).catch(i=>{this.handleWeb3ResponseMessage(s.id,{method:n.method,errorMessage:i.message})}),this.isMobileWeb&&this.openCoinbaseWalletDeeplink(n.method)}openCoinbaseWalletDeeplink(e){if(this.ui instanceof ye)switch(e){case"requestEthereumAccounts":case"switchEthereumChain":return;default:window.addEventListener("blur",()=>{window.addEventListener("focus",()=>{this.connection.checkUnseenEvents()},{once:!0})},{once:!0}),this.ui.openCoinbaseWalletDeeplink();break}}publishWeb3RequestCanceledEvent(e){const n={type:"WEB3_REQUEST_CANCELED",id:e};this.publishEvent("Web3RequestCanceled",n,!1).then()}publishEvent(e,n,s){return this.connection.publishEvent(e,n,s)}handleWeb3ResponseMessage(e,n){if(n.method==="requestEthereumAccounts"){C.accountRequestCallbackIds.forEach(s=>this.invokeCallback(s,n)),C.accountRequestCallbackIds.clear();return}this.invokeCallback(e,n)}handleErrorResponse(e,n,s){var i;const r=(i=s==null?void 0:s.message)!==null&&i!==void 0?i:"Unspecified error message.";this.handleWeb3ResponseMessage(e,{method:n,errorMessage:r})}invokeCallback(e,n){const s=this.relayEventManager.callbacks.get(e);s&&(s(n),this.relayEventManager.callbacks.delete(e))}requestEthereumAccounts(){const{appName:e,appLogoUrl:n}=this.metadata,s={method:"requestEthereumAccounts",params:{appName:e,appLogoUrl:n}},i=x(8);return new Promise((r,a)=>{this.relayEventManager.callbacks.set(i,o=>{if(m(o))return a(new Error(o.errorMessage));r(o)}),C.accountRequestCallbackIds.add(i),this.publishWeb3RequestEvent(i,s)})}watchAsset(e,n,s,i,r,a){const o={method:"watchAsset",params:{type:e,options:{address:n,symbol:s,decimals:i,image:r},chainId:a}};let c=null;const d=x(8),g=p=>{this.publishWeb3RequestCanceledEvent(d),this.handleErrorResponse(d,o.method,p),c==null||c()};return c=this.ui.showConnecting({isUnlinkedErrorState:this.isUnlinkedErrorState,onCancel:g,onResetConnection:this.resetAndReload}),new Promise((p,f)=>{this.relayEventManager.callbacks.set(d,I=>{if(c==null||c(),m(I))return f(new Error(I.errorMessage));p(I)}),this.publishWeb3RequestEvent(d,o)})}addEthereumChain(e,n,s,i,r,a){const o={method:"addEthereumChain",params:{chainId:e,rpcUrls:n,blockExplorerUrls:i,chainName:r,iconUrls:s,nativeCurrency:a}};let c=null;const d=x(8),g=p=>{this.publishWeb3RequestCanceledEvent(d),this.handleErrorResponse(d,o.method,p),c==null||c()};return c=this.ui.showConnecting({isUnlinkedErrorState:this.isUnlinkedErrorState,onCancel:g,onResetConnection:this.resetAndReload}),new Promise((p,f)=>{this.relayEventManager.callbacks.set(d,I=>{if(c==null||c(),m(I))return f(new Error(I.errorMessage));p(I)}),this.publishWeb3RequestEvent(d,o)})}switchEthereumChain(e,n){const s={method:"switchEthereumChain",params:Object.assign({chainId:e},{address:n})};let i=null;const r=x(8),a=o=>{this.publishWeb3RequestCanceledEvent(r),this.handleErrorResponse(r,s.method,o),i==null||i()};return i=this.ui.showConnecting({isUnlinkedErrorState:this.isUnlinkedErrorState,onCancel:a,onResetConnection:this.resetAndReload}),new Promise((o,c)=>{this.relayEventManager.callbacks.set(r,d=>{if(i==null||i(),m(d)&&d.errorCode)return c(l.provider.custom({code:d.errorCode,message:"Unrecognized chain ID. Try adding the chain using addEthereumChain first."}));if(m(d))return c(new Error(d.errorMessage));o(d)}),this.publishWeb3RequestEvent(r,s)})}}C.accountRequestCallbackIds=new Set;const ve="DefaultChainId",ke="DefaultJsonRpcUrl";class Qe{constructor(e){this._relay=null,this._addresses=[],this.metadata=e.metadata,this._storage=new E("walletlink",we),this.callback=e.callback||null;const n=this._storage.getItem(ee);if(n){const s=n.split(" ");s[0]!==""&&(this._addresses=s.map(i=>_(i)))}this.initializeRelay()}getSession(){const e=this.initializeRelay(),{id:n,secret:s}=e.getWalletLinkSession();return{id:n,secret:s}}async handshake(){await this._eth_requestAccounts()}get selectedAddress(){return this._addresses[0]||void 0}get jsonRpcUrl(){var e;return(e=this._storage.getItem(ke))!==null&&e!==void 0?e:void 0}set jsonRpcUrl(e){this._storage.setItem(ke,e)}updateProviderInfo(e,n){var s;this.jsonRpcUrl=e;const i=this.getChainId();this._storage.setItem(ve,n.toString(10)),j(n)!==i&&((s=this.callback)===null||s===void 0||s.call(this,"chainChanged",A(n)))}async watchAsset(e){const n=Array.isArray(e)?e[0]:e;if(!n.type)throw l.rpc.invalidParams("Type is required");if((n==null?void 0:n.type)!=="ERC20")throw l.rpc.invalidParams(`Asset of type '${n.type}' is not supported`);if(!(n!=null&&n.options))throw l.rpc.invalidParams("Options are required");if(!(n!=null&&n.options.address))throw l.rpc.invalidParams("Address is required");const s=this.getChainId(),{address:i,symbol:r,image:a,decimals:o}=n.options,d=await this.initializeRelay().watchAsset(n.type,i,r,o,a,s==null?void 0:s.toString());return m(d)?!1:!!d.result}async addEthereumChain(e){var n,s;const i=e[0];if(((n=i.rpcUrls)===null||n===void 0?void 0:n.length)===0)throw l.rpc.invalidParams("please pass in at least 1 rpcUrl");if(!i.chainName||i.chainName.trim()==="")throw l.rpc.invalidParams("chainName is a required field");if(!i.nativeCurrency)throw l.rpc.invalidParams("nativeCurrency is a required field");const r=Number.parseInt(i.chainId,16);if(r===this.getChainId())return!1;const a=this.initializeRelay(),{rpcUrls:o=[],blockExplorerUrls:c=[],chainName:d,iconUrls:g=[],nativeCurrency:p}=i,f=await a.addEthereumChain(r.toString(),o,g,c,d,p);if(m(f))return!1;if(((s=f.result)===null||s===void 0?void 0:s.isApproved)===!0)return this.updateProviderInfo(o[0],r),null;throw l.rpc.internal("unable to add ethereum chain")}async switchEthereumChain(e){const n=e[0],s=Number.parseInt(n.chainId,16),r=await this.initializeRelay().switchEthereumChain(s.toString(10),this.selectedAddress||void 0);if(m(r))throw r;const a=r.result;return a.isApproved&&a.rpcUrl.length>0&&this.updateProviderInfo(a.rpcUrl,s),null}async cleanup(){this.callback=null,this._relay&&this._relay.resetAndReload(),this._storage.clear()}_setAddresses(e,n){var s;if(!Array.isArray(e))throw new Error("addresses is not an array");const i=e.map(r=>_(r));JSON.stringify(i)!==JSON.stringify(this._addresses)&&(this._addresses=i,(s=this.callback)===null||s===void 0||s.call(this,"accountsChanged",i),this._storage.setItem(ee,i.join(" ")))}async request(e){const n=e.params||[];switch(e.method){case"eth_accounts":return[...this._addresses];case"eth_coinbase":return this.selectedAddress||null;case"net_version":return this.getChainId().toString(10);case"eth_chainId":return A(this.getChainId());case"eth_requestAccounts":return this._eth_requestAccounts();case"eth_ecRecover":case"personal_ecRecover":return this.ecRecover(e);case"personal_sign":return this.personalSign(e);case"eth_signTransaction":return this._eth_signTransaction(n);case"eth_sendRawTransaction":return this._eth_sendRawTransaction(n);case"eth_sendTransaction":return this._eth_sendTransaction(n);case"eth_signTypedData_v1":case"eth_signTypedData_v3":case"eth_signTypedData_v4":case"eth_signTypedData":return this.signTypedData(e);case"wallet_addEthereumChain":return this.addEthereumChain(n);case"wallet_switchEthereumChain":return this.switchEthereumChain(n);case"wallet_watchAsset":return this.watchAsset(n);default:if(!this.jsonRpcUrl)throw l.rpc.internal("No RPC URL set for chain");return je(e,this.jsonRpcUrl)}}_ensureKnownAddress(e){const n=_(e);if(!this._addresses.map(i=>_(i)).includes(n))throw new Error("Unknown Ethereum address")}_prepareTransactionParams(e){const n=e.from?_(e.from):this.selectedAddress;if(!n)throw new Error("Ethereum address is unavailable");this._ensureKnownAddress(n);const s=e.to?_(e.to):null,i=e.value!=null?N(e.value):BigInt(0),r=e.data?X(e.data):Buffer.alloc(0),a=e.nonce!=null?j(e.nonce):null,o=e.gasPrice!=null?N(e.gasPrice):null,c=e.maxFeePerGas!=null?N(e.maxFeePerGas):null,d=e.maxPriorityFeePerGas!=null?N(e.maxPriorityFeePerGas):null,g=e.gas!=null?N(e.gas):null,p=e.chainId?j(e.chainId):this.getChainId();return{fromAddress:n,toAddress:s,weiValue:i,data:r,nonce:a,gasPriceInWei:o,maxFeePerGas:c,maxPriorityFeePerGas:d,gasLimit:g,chainId:p}}async ecRecover(e){const{method:n,params:s}=e;if(!Array.isArray(s))throw l.rpc.invalidParams();const r=await this.initializeRelay().sendRequest({method:"ethereumAddressFromSignedMessage",params:{message:H(s[0]),signature:H(s[1]),addPrefix:n==="personal_ecRecover"}});if(m(r))throw r;return r.result}getChainId(){var e;return Number.parseInt((e=this._storage.getItem(ve))!==null&&e!==void 0?e:"1",10)}async _eth_requestAccounts(){var e,n;if(this._addresses.length>0)return(e=this.callback)===null||e===void 0||e.call(this,"connect",{chainId:A(this.getChainId())}),this._addresses;const i=await this.initializeRelay().requestEthereumAccounts();if(m(i))throw i;if(!i.result)throw new Error("accounts received is empty");return this._setAddresses(i.result),(n=this.callback)===null||n===void 0||n.call(this,"connect",{chainId:A(this.getChainId())}),this._addresses}async personalSign({params:e}){if(!Array.isArray(e))throw l.rpc.invalidParams();const n=e[1],s=e[0];this._ensureKnownAddress(n);const r=await this.initializeRelay().sendRequest({method:"signEthereumMessage",params:{address:_(n),message:H(s),addPrefix:!0,typedDataJson:null}});if(m(r))throw r;return r.result}async _eth_signTransaction(e){const n=this._prepareTransactionParams(e[0]||{}),i=await this.initializeRelay().signEthereumTransaction(n);if(m(i))throw i;return i.result}async _eth_sendRawTransaction(e){const n=X(e[0]),i=await this.initializeRelay().submitEthereumTransaction(n,this.getChainId());if(m(i))throw i;return i.result}async _eth_sendTransaction(e){const n=this._prepareTransactionParams(e[0]||{}),i=await this.initializeRelay().signAndSubmitEthereumTransaction(n);if(m(i))throw i;return i.result}async signTypedData(e){const{method:n,params:s}=e;if(!Array.isArray(s))throw l.rpc.invalidParams();const i=d=>{const g={eth_signTypedData_v1:q.hashForSignTypedDataLegacy,eth_signTypedData_v3:q.hashForSignTypedData_v3,eth_signTypedData_v4:q.hashForSignTypedData_v4,eth_signTypedData:q.hashForSignTypedData_v4};return O(g[n]({data:pt(d)}),!0)},r=s[n==="eth_signTypedData_v1"?1:0],a=s[n==="eth_signTypedData_v1"?0:1];this._ensureKnownAddress(r);const c=await this.initializeRelay().sendRequest({method:"signEthereumMessage",params:{address:_(r),message:i(a),typedDataJson:JSON.stringify(a,null,2),addPrefix:!1}});if(m(c))throw c;return c.result}initializeRelay(){return this._relay||(this._relay=new C({linkAPIUrl:we,storage:this._storage,metadata:this.metadata,accountsCallback:this._setAddresses.bind(this),chainCallback:this.updateProviderInfo.bind(this)})),this._relay}}const Ze="SignerType",Xe=new E("CBWSDK","SignerConfigurator");function un(){return Xe.getItem(Ze)}function hn(t){Xe.setItem(Ze,t)}async function pn(t){const{communicator:e,metadata:n,handshakeRequest:s,callback:i}=t;gn(e,n,i).catch(()=>{});const r={id:crypto.randomUUID(),event:"selectSignerType",data:Object.assign(Object.assign({},t.preference),{handshakeRequest:s})},{data:a}=await e.postRequestAndWaitForResponse(r);return a}function fn(t){const{signerType:e,metadata:n,communicator:s,callback:i}=t;switch(e){case"scw":return new Mt({metadata:n,callback:i,communicator:s});case"walletlink":return new Qe({metadata:n,callback:i})}}async function gn(t,e,n){await t.onMessage(({event:i})=>i==="WalletLinkSessionRequest");const s=new Qe({metadata:e,callback:n});t.postMessage({event:"WalletLinkUpdate",data:{session:s.getSession()}}),await s.handshake(),t.postMessage({event:"WalletLinkUpdate",data:{connected:!0}})}const mn=`Coinbase Wallet SDK requires the Cross-Origin-Opener-Policy header to not be set to 'same-origin'. This is to ensure that the SDK can communicate with the Coinbase Smart Wallet app.
|
|
2
2
|
|
|
3
3
|
Please see https://www.smartwallet.dev/guides/tips/popup-tips#cross-origin-opener-policy for more information.`,bn=()=>{let t;return{getCrossOriginOpenerPolicy:()=>t===void 0?"undefined":t,checkCrossOriginOpenerPolicy:async()=>{if(typeof window>"u"){t="non-browser-env";return}try{const e=`${window.location.origin}${window.location.pathname}`,n=await fetch(e,{method:"HEAD"});if(!n.ok)throw new Error(`HTTP error! status: ${n.status}`);const s=n.headers.get("Cross-Origin-Opener-Policy");t=s??"null",t==="same-origin"&&console.error(mn)}catch(e){console.error("Error checking Cross-Origin-Opener-Policy:",e.message),t="error"}}}},{checkCrossOriginOpenerPolicy:wn,getCrossOriginOpenerPolicy:yn}=bn(),Ee=420,Ie=540;function vn(t){const e=(window.innerWidth-Ee)/2+window.screenX,n=(window.innerHeight-Ie)/2+window.screenY;En(t);const s=window.open(t,"Smart Wallet",`width=${Ee}, height=${Ie}, left=${e}, top=${n}`);if(s==null||s.focus(),!s)throw l.rpc.internal("Pop up window failed to open");return s}function kn(t){t&&!t.closed&&t.close()}function En(t){const e={sdkName:Oe,sdkVersion:K,origin:window.location.origin,coop:yn()};for(const[n,s]of Object.entries(e))t.searchParams.append(n,s.toString())}class In{constructor({url:e=dn,metadata:n,preference:s}){this.popup=null,this.listeners=new Map,this.postMessage=async i=>{(await this.waitForPopupLoaded()).postMessage(i,this.url.origin)},this.postRequestAndWaitForResponse=async i=>{const r=this.onMessage(({requestId:a})=>a===i.id);return this.postMessage(i),await r},this.onMessage=async i=>new Promise((r,a)=>{const o=c=>{if(c.origin!==this.url.origin)return;const d=c.data;i(d)&&(r(d),window.removeEventListener("message",o),this.listeners.delete(o))};window.addEventListener("message",o),this.listeners.set(o,{reject:a})}),this.disconnect=()=>{kn(this.popup),this.popup=null,this.listeners.forEach(({reject:i},r)=>{i(l.provider.userRejectedRequest("Request rejected")),window.removeEventListener("message",r)}),this.listeners.clear()},this.waitForPopupLoaded=async()=>this.popup&&!this.popup.closed?(this.popup.focus(),this.popup):(this.popup=vn(this.url),this.onMessage(({event:i})=>i==="PopupUnload").then(this.disconnect).catch(()=>{}),this.onMessage(({event:i})=>i==="PopupLoaded").then(i=>{this.postMessage({requestId:i.id,data:{version:K,metadata:this.metadata,preference:this.preference,location:window.location.toString()}})}).then(()=>{if(!this.popup)throw l.rpc.internal();return this.popup})),this.url=new URL(e),this.metadata=n,this.preference=s}}function Sn(t){const e=ct(Cn(t),{shouldIncludeStack:!0}),n=new URL("https://docs.cloud.coinbase.com/wallet-sdk/docs/errors");return n.searchParams.set("version",K),n.searchParams.set("code",e.code.toString()),n.searchParams.set("message",e.message),Object.assign(Object.assign({},e),{docUrl:n.href})}function Cn(t){var e;if(typeof t=="string")return{message:t,code:h.rpc.internal};if(m(t)){const n=t.errorMessage,s=(e=t.errorCode)!==null&&e!==void 0?e:n.match(/(denied|rejected)/i)?h.provider.userRejectedRequest:void 0;return Object.assign(Object.assign({},t),{message:n,code:s,data:{method:t.method}})}return t}class Mn extends it{}var _n=function(t,e){var n={};for(var s in t)Object.prototype.hasOwnProperty.call(t,s)&&e.indexOf(s)<0&&(n[s]=t[s]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,s=Object.getOwnPropertySymbols(t);i<s.length;i++)e.indexOf(s[i])<0&&Object.prototype.propertyIsEnumerable.call(t,s[i])&&(n[s[i]]=t[s[i]]);return n};class An extends Mn{constructor(e){var{metadata:n}=e,s=e.preference,{keysUrl:i}=s,r=_n(s,["keysUrl"]);super(),this.signer=null,this.isCoinbaseWallet=!0,this.metadata=n,this.preference=r,this.communicator=new In({url:i,metadata:n,preference:r});const a=un();a&&(this.signer=this.initSigner(a))}async request(e){try{if(Ct(e),!this.signer)switch(e.method){case"eth_requestAccounts":{const n=await this.requestSignerSelection(e),s=this.initSigner(n);await s.handshake(e),this.signer=s,hn(n);break}case"net_version":return 1;case"eth_chainId":return A(1);default:throw l.provider.unauthorized("Must call 'eth_requestAccounts' before other methods")}return this.signer.request(e)}catch(n){const{code:s}=n;return s===h.provider.unauthorized&&this.disconnect(),Promise.reject(Sn(n))}}async enable(){return console.warn('.enable() has been deprecated. Please use .request({ method: "eth_requestAccounts" }) instead.'),await this.request({method:"eth_requestAccounts"})}async disconnect(){var e;await((e=this.signer)===null||e===void 0?void 0:e.cleanup()),this.signer=null,E.clearAll(),this.emit("disconnect",l.provider.disconnected("User initiated disconnection"))}requestSignerSelection(e){return pn({communicator:this.communicator,preference:this.preference,metadata:this.metadata,handshakeRequest:e,callback:this.emit.bind(this)})}initSigner(e){return fn({signerType:e,metadata:this.metadata,communicator:this.communicator,callback:this.emit.bind(this)})}}function xn(t){if(t){if(!["all","smartWalletOnly","eoaOnly"].includes(t.options))throw new Error(`Invalid options: ${t.options}`);if(t.attribution&&t.attribution.auto!==void 0&&t.attribution.dataSuffix!==void 0)throw new Error("Attribution cannot contain both auto and dataSuffix properties")}}function Pn(t){var e;const n={metadata:t.metadata,preference:t.preference};return(e=St(n))!==null&&e!==void 0?e:new An(n)}const Rn={options:"all"};function Nn(t){var e;new E("CBWSDK").setItem("VERSION",K),wn();const s={metadata:{appName:t.appName||"Dapp",appLogoUrl:t.appLogoUrl||"",appChainIds:t.appChainIds||[]},preference:Object.assign(Rn,(e=t.preference)!==null&&e!==void 0?e:{})};xn(s.preference);let i=null;return{getProvider:()=>(i||(i=Pn(s)),i)}}export{Nn as createCoinbaseWalletSDK};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{h as v,g as C}from"./index-
|
|
1
|
+
import{h as v,g as C}from"./index-qgo91dsq.js";import{e as H}from"./index-JbpWt42F.js";import{e as y}from"./events-CkdpRqBF.js";function I(r,n){for(var c=0;c<n.length;c++){const e=n[c];if(typeof e!="string"&&!Array.isArray(e)){for(const h in e)if(h!=="default"&&!(h in r)){const u=Object.getOwnPropertyDescriptor(e,h);u&&Object.defineProperty(r,h,u.get?u:{enumerable:!0,get:()=>e[h]})}}}return Object.freeze(Object.defineProperty(r,Symbol.toStringTag,{value:"Module"}))}var x={},p={};const N=v(H);var f={};Object.defineProperty(f,"__esModule",{value:!0});f.numberToHex=f.getLowerCase=void 0;function A(r){return r&&r.toLowerCase()}f.getLowerCase=A;function E(r){return`0x${r.toString(16)}`}f.numberToHex=E;Object.defineProperty(p,"__esModule",{value:!0});p.SafeAppProvider=void 0;const l=N,P=y,o=f;class L extends P.EventEmitter{constructor(n,c){super(),this.submittedTxs=new Map,this.safe=n,this.sdk=c}async connect(){this.emit("connect",{chainId:this.chainId})}async disconnect(){}get chainId(){return this.safe.chainId}async request(n){var h,u,w,T;const{method:c,params:e=[]}=n;switch(c){case"eth_accounts":return[this.safe.safeAddress];case"net_version":case"eth_chainId":return(0,o.numberToHex)(this.chainId);case"personal_sign":{const[s,t]=e;if(this.safe.safeAddress.toLowerCase()!==t.toLowerCase())throw new Error("The address or message hash is invalid");const a=await this.sdk.txs.signMessage(s);return("signature"in a?a.signature:void 0)||"0x"}case"eth_sign":{const[s,t]=e;if(this.safe.safeAddress.toLowerCase()!==s.toLowerCase()||!t.startsWith("0x"))throw new Error("The address or message hash is invalid");const a=await this.sdk.txs.signMessage(t);return("signature"in a?a.signature:void 0)||"0x"}case"eth_signTypedData":case"eth_signTypedData_v4":{const[s,t]=e,a=typeof t=="string"?JSON.parse(t):t;if(this.safe.safeAddress.toLowerCase()!==s.toLowerCase())throw new Error("The address is invalid");const i=await this.sdk.txs.signTypedMessage(a);return("signature"in i?i.signature:void 0)||"0x"}case"eth_sendTransaction":const d={...e[0],value:e[0].value||"0",data:e[0].data||"0x"};typeof d.gas=="string"&&d.gas.startsWith("0x")&&(d.gas=parseInt(d.gas,16));const m=await this.sdk.txs.send({txs:[d],params:{safeTxGas:d.gas}});return this.submittedTxs.set(m.safeTxHash,{from:this.safe.safeAddress,hash:m.safeTxHash,gas:0,gasPrice:"0x00",nonce:0,input:d.data,value:d.value,to:d.to,blockHash:null,blockNumber:null,transactionIndex:null}),m.safeTxHash;case"eth_blockNumber":return(await this.sdk.eth.getBlockByNumber(["latest"])).number;case"eth_getBalance":return this.sdk.eth.getBalance([(0,o.getLowerCase)(e[0]),e[1]]);case"eth_getCode":return this.sdk.eth.getCode([(0,o.getLowerCase)(e[0]),e[1]]);case"eth_getTransactionCount":return this.sdk.eth.getTransactionCount([(0,o.getLowerCase)(e[0]),e[1]]);case"eth_getStorageAt":return this.sdk.eth.getStorageAt([(0,o.getLowerCase)(e[0]),e[1],e[2]]);case"eth_getBlockByNumber":return this.sdk.eth.getBlockByNumber([e[0],e[1]]);case"eth_getBlockByHash":return this.sdk.eth.getBlockByHash([e[0],e[1]]);case"eth_getTransactionByHash":let g=e[0];try{g=(await this.sdk.txs.getBySafeTxHash(g)).txHash||g}catch{}return this.submittedTxs.has(g)?this.submittedTxs.get(g):this.sdk.eth.getTransactionByHash([g]).then(s=>(s&&(s.hash=e[0]),s));case"eth_getTransactionReceipt":{let s=e[0];try{s=(await this.sdk.txs.getBySafeTxHash(s)).txHash||s}catch{}return this.sdk.eth.getTransactionReceipt([s]).then(t=>(t&&(t.transactionHash=e[0]),t))}case"eth_estimateGas":return this.sdk.eth.getEstimateGas(e[0]);case"eth_call":return this.sdk.eth.call([e[0],e[1]]);case"eth_getLogs":return this.sdk.eth.getPastLogs([e[0]]);case"eth_gasPrice":return this.sdk.eth.getGasPrice();case"wallet_getPermissions":return this.sdk.wallet.getPermissions();case"wallet_requestPermissions":return this.sdk.wallet.requestPermissions(e[0]);case"safe_setSettings":return this.sdk.eth.setSafeSettings([e[0]]);case"wallet_sendCalls":{if(e[0].from!==this.safe.safeAddress)throw Error("Invalid from address");const s=e[0].calls.map((a,i)=>{if(a.chainId!==(0,o.numberToHex)(this.chainId))throw new Error(`Invalid call #${i}: Safe is not on chain ${a.chainId}`);if(!a.to)throw new Error(`Invalid call #${i}: missing "to" field`);return{to:a.to,data:a.data??"0x",value:a.value??(0,o.numberToHex)(0)}}),{safeTxHash:t}=await this.sdk.txs.send({txs:s});return t}case"wallet_getCallsStatus":{const s={[l.TransactionStatus.AWAITING_CONFIRMATIONS]:"PENDING",[l.TransactionStatus.AWAITING_EXECUTION]:"PENDING",[l.TransactionStatus.CANCELLED]:"CONFIRMED",[l.TransactionStatus.FAILED]:"CONFIRMED",[l.TransactionStatus.SUCCESS]:"CONFIRMED"},t=await this.sdk.txs.getBySafeTxHash(e[0]),a=s[t.txStatus];if(!t.txHash)return{status:a};const i=await this.sdk.eth.getTransactionReceipt([t.txHash]);if(!i)return{status:a};const _=((u=(h=t.txData)==null?void 0:h.dataDecoded)==null?void 0:u.method)!=="multiSend"?1:((T=(w=t.txData.dataDecoded.parameters)==null?void 0:w[0].valueDecoded)==null?void 0:T.length)??1,b=Number(i.blockNumber),k=Number(i.gasUsed),S=Array(_).fill({logs:i.logs,status:(0,o.numberToHex)(t.txStatus===l.TransactionStatus.SUCCESS?1:0),chainId:(0,o.numberToHex)(this.chainId),blockHash:i.blockHash,blockNumber:(0,o.numberToHex)(b),gasUsed:(0,o.numberToHex)(k),transactionHash:t.txHash});return{status:a,receipts:S}}case"wallet_showCallsStatus":throw new Error(`"${n.method}" not supported`);case"wallet_getCapabilities":return{[(0,o.numberToHex)(this.chainId)]:{atomicBatch:{supported:!0}}};default:throw Error(`"${n.method}" not implemented`)}}send(n,c){n||c("Undefined request"),this.request(n).then(e=>c(null,{jsonrpc:"2.0",id:n.id,result:e})).catch(e=>c(e,null))}}p.SafeAppProvider=L;(function(r){Object.defineProperty(r,"__esModule",{value:!0}),r.SafeAppProvider=void 0;var n=p;Object.defineProperty(r,"SafeAppProvider",{enumerable:!0,get:function(){return n.SafeAppProvider}})})(x);const B=C(x),$=I({__proto__:null,default:B},[x]);export{$ as i};
|