From 21f84edc41d21f086026de0e9218b9af7b22886d Mon Sep 17 00:00:00 2001 From: thekiba Date: Tue, 19 Dec 2023 22:05:49 +0400 Subject: [PATCH] chore: rebuild --- docs/assets/{index-62e4ddea.js => index-3cff0461.js} | 6 +++--- docs/index.html | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) rename docs/assets/{index-62e4ddea.js => index-3cff0461.js} (95%) diff --git a/docs/assets/index-62e4ddea.js b/docs/assets/index-3cff0461.js similarity index 95% rename from docs/assets/index-62e4ddea.js rename to docs/assets/index-3cff0461.js index 1a59a9c..3e89ef3 100644 --- a/docs/assets/index-62e4ddea.js +++ b/docs/assets/index-3cff0461.js @@ -56,7 +56,7 @@ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ***************************************************************************** */function __rest(b,_){var d={};for(var k in b)Object.prototype.hasOwnProperty.call(b,k)&&_.indexOf(k)<0&&(d[k]=b[k]);if(b!=null&&typeof Object.getOwnPropertySymbols=="function")for(var j=0,k=Object.getOwnPropertySymbols(b);j{const et=_!=null&&_.openingDeadlineMS?setTimeout(()=>{var tt;((tt=this.eventSource)===null||tt===void 0?void 0:tt.readyState)!==EventSource.OPEN&&($(new TonConnectError("Bridge connection timeout")),this.close())},_.openingDeadlineMS):void 0;this.eventSource.onerror=()=>$,this.eventSource.onopen=()=>{clearTimeout(et),this.isClosed=!1,this.eventSource.onerror=this.errorsHandler.bind(this),this.eventSource.onmessage=this.messagesHandler.bind(this),j()}})})}send(_,d,k,j){return __awaiter(this,void 0,void 0,function*(){const $=new URL(addPathToUrl(this.bridgeUrl,this.postPath));$.searchParams.append("client_id",this.sessionId),$.searchParams.append("to",d),$.searchParams.append("ttl",(j||this.defaultTtl).toString()),$.searchParams.append("topic",k);const et=yield fetch($,{method:"post",body:Base64.encode(_)});if(!et.ok)throw new TonConnectError(`Bridge send failed, status ${et.status}`)})}pause(){var _;(_=this.eventSource)===null||_===void 0||_.close()}unPause(){return this.registerSession()}close(){var _;this.isClosed=!0,(_=this.eventSource)===null||_===void 0||_.close()}setListener(_){this.listener=_}setErrorsListener(_){this.errorsListener=_}errorsHandler(_){var d,k;if(!this.isClosed){if(((d=this.eventSource)===null||d===void 0?void 0:d.readyState)===EventSource.CLOSED){this.eventSource.close(),this.registerSession();return}if(((k=this.eventSource)===null||k===void 0?void 0:k.readyState)===EventSource.CONNECTING){console.debug("[TON_CONNET_SDK_ERROR]: Bridge error",JSON.stringify(_));return}this.errorsListener(_)}}messagesHandler(_){return __awaiter(this,void 0,void 0,function*(){if(_.data!==this.heartbeatMessage&&(yield this.bridgeGatewayStorage.storeLastEventId(_.lastEventId),!this.isClosed)){let d;try{d=JSON.parse(_.data)}catch(k){throw new TonConnectError(`Bridge message parse failed, message ${k.data}`)}this.listener(d)}})}}function isPendingConnectionHttp(b){return!("connectEvent"in b)}class BridgeConnectionStorage{constructor(_){this.storage=_,this.storeKey="ton-connect-storage_bridge-connection"}storeConnection(_){return __awaiter(this,void 0,void 0,function*(){if(_.type==="injected")return this.storage.setItem(this.storeKey,JSON.stringify(_));if(!isPendingConnectionHttp(_)){const k={sessionKeyPair:_.session.sessionCrypto.stringifyKeypair(),walletPublicKey:_.session.walletPublicKey,bridgeUrl:_.session.bridgeUrl},j={type:"http",connectEvent:_.connectEvent,session:k,lastWalletEventId:_.lastWalletEventId,nextRpcRequestId:_.nextRpcRequestId};return this.storage.setItem(this.storeKey,JSON.stringify(j))}const d={type:"http",connectionSource:_.connectionSource,sessionCrypto:_.sessionCrypto.stringifyKeypair()};return this.storage.setItem(this.storeKey,JSON.stringify(d))})}removeConnection(){return __awaiter(this,void 0,void 0,function*(){return this.storage.removeItem(this.storeKey)})}getConnection(){return __awaiter(this,void 0,void 0,function*(){const _=yield this.storage.getItem(this.storeKey);if(!_)return null;const d=JSON.parse(_);if(d.type==="injected")return d;if("connectEvent"in d){const k=new SessionCrypto(d.session.sessionKeyPair);return{type:"http",connectEvent:d.connectEvent,lastWalletEventId:d.lastWalletEventId,nextRpcRequestId:d.nextRpcRequestId,session:{sessionCrypto:k,bridgeUrl:d.session.bridgeUrl,walletPublicKey:d.session.walletPublicKey}}}return{type:"http",sessionCrypto:new SessionCrypto(d.sessionCrypto),connectionSource:d.connectionSource}})}getHttpConnection(){return __awaiter(this,void 0,void 0,function*(){const _=yield this.getConnection();if(!_)throw new TonConnectError("Trying to read HTTP connection source while nothing is stored");if(_.type==="injected")throw new TonConnectError("Trying to read HTTP connection source while injected connection is stored");return _})}getHttpPendingConnection(){return __awaiter(this,void 0,void 0,function*(){const _=yield this.getConnection();if(!_)throw new TonConnectError("Trying to read HTTP connection source while nothing is stored");if(_.type==="injected")throw new TonConnectError("Trying to read HTTP connection source while injected connection is stored");if(!isPendingConnectionHttp(_))throw new TonConnectError("Trying to read HTTP-pending connection while http connection is stored");return _})}getInjectedConnection(){return __awaiter(this,void 0,void 0,function*(){const _=yield this.getConnection();if(!_)throw new TonConnectError("Trying to read Injected bridge connection source while nothing is stored");if((_==null?void 0:_.type)==="http")throw new TonConnectError("Trying to read Injected bridge connection source while HTTP connection is stored");return _})}storedConnectionType(){return __awaiter(this,void 0,void 0,function*(){const _=yield this.storage.getItem(this.storeKey);return _?JSON.parse(_).type:null})}storeLastWalletEventId(_){return __awaiter(this,void 0,void 0,function*(){const d=yield this.getConnection();if(d&&d.type==="http"&&!isPendingConnectionHttp(d))return d.lastWalletEventId=_,this.storeConnection(d)})}getLastWalletEventId(){return __awaiter(this,void 0,void 0,function*(){const _=yield this.getConnection();if(_&&"lastWalletEventId"in _)return _.lastWalletEventId})}increaseNextRpcRequestId(){return __awaiter(this,void 0,void 0,function*(){const _=yield this.getConnection();if(_&&"nextRpcRequestId"in _){const d=_.nextRpcRequestId||0;return _.nextRpcRequestId=d+1,this.storeConnection(_)}})}getNextRpcRequestId(){return __awaiter(this,void 0,void 0,function*(){const _=yield this.getConnection();return _&&"nextRpcRequestId"in _&&_.nextRpcRequestId||0})}}const PROTOCOL_VERSION=2;function logDebug(...b){try{console.debug("[TON_CONNECT_SDK]",...b)}catch{}}function logError$1(...b){try{console.error("[TON_CONNECT_SDK]",...b)}catch{}}function logWarning$1(...b){try{console.warn("[TON_CONNECT_SDK]",...b)}catch{}}class BridgeProvider{constructor(_,d){this.storage=_,this.walletConnectionSource=d,this.type="http",this.standardUniversalLink="tc://",this.pendingRequests=new Map,this.session=null,this.gateway=null,this.pendingGateways=[],this.listeners=[],this.connectionStorage=new BridgeConnectionStorage(_)}static fromStorage(_){return __awaiter(this,void 0,void 0,function*(){const k=yield new BridgeConnectionStorage(_).getHttpConnection();return isPendingConnectionHttp(k)?new BridgeProvider(_,k.connectionSource):new BridgeProvider(_,{bridgeUrl:k.session.bridgeUrl})})}connect(_){this.closeGateways();const d=new SessionCrypto;this.session={sessionCrypto:d,bridgeUrl:"bridgeUrl"in this.walletConnectionSource?this.walletConnectionSource.bridgeUrl:""},this.connectionStorage.storeConnection({type:"http",connectionSource:this.walletConnectionSource,sessionCrypto:d}).then(()=>this.openGateways(d));const k="universalLink"in this.walletConnectionSource&&this.walletConnectionSource.universalLink?this.walletConnectionSource.universalLink:this.standardUniversalLink;return this.generateUniversalLink(k,_)}restoreConnection(){return __awaiter(this,void 0,void 0,function*(){this.closeGateways();const _=yield this.connectionStorage.getHttpConnection();if(_){if(isPendingConnectionHttp(_))return this.session={sessionCrypto:_.sessionCrypto,bridgeUrl:"bridgeUrl"in this.walletConnectionSource?this.walletConnectionSource.bridgeUrl:""},this.openGateways(_.sessionCrypto,{openingDeadlineMS:5e3});if(Array.isArray(this.walletConnectionSource))throw new TonConnectError("Internal error. Connection source is array while WalletConnectionSourceHTTP was expected.");this.session=_.session,this.gateway=new BridgeGateway(this.storage,this.walletConnectionSource.bridgeUrl,_.session.sessionCrypto.sessionId,this.gatewayListener.bind(this),this.gatewayErrorsListener.bind(this));try{yield this.gateway.registerSession({openingDeadlineMS:5e3})}catch{yield this.disconnect();return}this.listeners.forEach(d=>d(_.connectEvent))}})}sendRequest(_,d){return new Promise((k,j)=>__awaiter(this,void 0,void 0,function*(){if(!this.gateway||!this.session||!("walletPublicKey"in this.session))throw new TonConnectError("Trying to send bridge request without session");const $=(yield this.connectionStorage.getNextRpcRequestId()).toString();yield this.connectionStorage.increaseNextRpcRequestId(),logDebug("Send http-bridge request:",Object.assign(Object.assign({},_),{id:$}));const et=this.session.sessionCrypto.encrypt(JSON.stringify(Object.assign(Object.assign({},_),{id:$})),hexToByteArray(this.session.walletPublicKey));try{yield this.gateway.send(et,this.session.walletPublicKey,_.method),d==null||d(),this.pendingRequests.set($.toString(),k)}catch(tt){j(tt)}}))}closeConnection(){this.closeGateways(),this.listeners=[],this.session=null,this.gateway=null}disconnect(){return __awaiter(this,void 0,void 0,function*(){return new Promise(_=>__awaiter(this,void 0,void 0,function*(){let d=!1;const k=()=>{d=!0,this.removeBridgeAndSession().then(_)};try{yield this.sendRequest({method:"disconnect",params:[]},k)}catch(j){console.debug(j),d||this.removeBridgeAndSession().then(_)}}))})}listen(_){return this.listeners.push(_),()=>this.listeners=this.listeners.filter(d=>d!==_)}pause(){var _;(_=this.gateway)===null||_===void 0||_.pause(),this.pendingGateways.forEach(d=>d.pause())}unPause(){return __awaiter(this,void 0,void 0,function*(){const _=this.pendingGateways.map(d=>d.unPause());this.gateway&&_.push(this.gateway.unPause()),yield Promise.all(_)})}pendingGatewaysListener(_,d,k){return __awaiter(this,void 0,void 0,function*(){if(!this.pendingGateways.includes(_)){_.close();return}return this.closeGateways({except:_}),this.session.bridgeUrl=d,this.gateway=_,this.gateway.setErrorsListener(this.gatewayErrorsListener.bind(this)),this.gateway.setListener(this.gatewayListener.bind(this)),this.gatewayListener(k)})}gatewayListener(_){return __awaiter(this,void 0,void 0,function*(){const d=JSON.parse(this.session.sessionCrypto.decrypt(Base64.decode(_.message).toUint8Array(),hexToByteArray(_.from)));if(logDebug("Wallet message received:",d),!("event"in d)){const j=d.id.toString(),$=this.pendingRequests.get(j);if(!$){logDebug(`Response id ${j} doesn't match any request's id`);return}$(d),this.pendingRequests.delete(j);return}if(d.id!==void 0){const j=yield this.connectionStorage.getLastWalletEventId();if(j!==void 0&&d.id<=j){logError$1(`Received event id (=${d.id}) must be greater than stored last wallet event id (=${j}) `);return}d.event!=="connect"&&(yield this.connectionStorage.storeLastWalletEventId(d.id))}const k=this.listeners;d.event==="connect"&&(yield this.updateSession(d,_.from)),d.event==="disconnect"&&(yield this.removeBridgeAndSession()),k.forEach(j=>j(d))})}gatewayErrorsListener(_){return __awaiter(this,void 0,void 0,function*(){throw new TonConnectError(`Bridge error ${JSON.stringify(_)}`)})}updateSession(_,d){return __awaiter(this,void 0,void 0,function*(){this.session=Object.assign(Object.assign({},this.session),{walletPublicKey:d});const k=_.payload.items.find($=>$.name==="ton_addr"),j=Object.assign(Object.assign({},_),{payload:Object.assign(Object.assign({},_.payload),{items:[k]})});yield this.connectionStorage.storeConnection({type:"http",session:this.session,lastWalletEventId:_.id,connectEvent:j,nextRpcRequestId:0})})}removeBridgeAndSession(){return __awaiter(this,void 0,void 0,function*(){this.closeConnection(),yield this.connectionStorage.removeConnection()})}generateUniversalLink(_,d){return isTelegramUrl(_)?this.generateTGUniversalLink(_,d):this.generateRegularUniversalLink(_,d)}generateRegularUniversalLink(_,d){const k=new URL(_);return k.searchParams.append("v",PROTOCOL_VERSION.toString()),k.searchParams.append("id",this.session.sessionCrypto.sessionId),k.searchParams.append("r",JSON.stringify(d)),k.toString()}generateTGUniversalLink(_,d){const j=this.generateRegularUniversalLink("about:blank",d).split("?")[1],$="tonconnect-"+encodeTelegramUrlParameters(j),et=this.convertToDirectLink(_),tt=new URL(et);return tt.searchParams.append("startapp",$),tt.toString()}convertToDirectLink(_){const d=new URL(_);return d.searchParams.has("attach")&&(d.searchParams.delete("attach"),d.pathname+="/start"),d.toString()}openGateways(_,d){return __awaiter(this,void 0,void 0,function*(){if(Array.isArray(this.walletConnectionSource)){this.pendingGateways=this.walletConnectionSource.map(k=>{const j=new BridgeGateway(this.storage,k.bridgeUrl,_.sessionId,()=>{},$=>{console.error($)});return j.setListener($=>this.pendingGatewaysListener(j,k.bridgeUrl,$)),j}),yield Promise.allSettled(this.pendingGateways.map(k=>k.registerSession(d)));return}else return this.gateway=new BridgeGateway(this.storage,this.walletConnectionSource.bridgeUrl,_.sessionId,this.gatewayListener.bind(this),this.gatewayErrorsListener.bind(this)),this.gateway.registerSession(d)})}closeGateways(_){var d;(d=this.gateway)===null||d===void 0||d.close(),this.pendingGateways.filter(k=>k!==(_==null?void 0:_.except)).forEach(k=>k.close()),this.pendingGateways=[]}}function hasProperty(b,_){return hasProperties(b,[_])}function hasProperties(b,_){return!b||typeof b!="object"?!1:_.every(d=>d in b)}function isJSBridgeWithMetadata(b){try{return!hasProperty(b,"tonconnect")||!hasProperty(b.tonconnect,"walletInfo")?!1:hasProperties(b.tonconnect.walletInfo,["name","app_name","image","about_url","platforms"])}catch{return!1}}let InMemoryStorage$1=class Jo{constructor(){this.storage={}}static getInstance(){return Jo.instance||(Jo.instance=new Jo),Jo.instance}get length(){return Object.keys(this.storage).length}clear(){this.storage={}}getItem(_){var d;return(d=this.storage[_])!==null&&d!==void 0?d:null}key(_){var d;const k=Object.keys(this.storage);return _<0||_>=k.length?null:(d=k[_])!==null&&d!==void 0?d:null}removeItem(_){delete this.storage[_]}setItem(_,d){this.storage[_]=d}};function getWindow$2(){if(!(typeof window>"u"))return window}function tryGetWindowKeys(){const b=getWindow$2();if(!b)return[];try{return Object.keys(b)}catch{return[]}}function getDocument(){if(!(typeof document>"u"))return document}function getWebPageManifest(){var b;const _=(b=getWindow$2())===null||b===void 0?void 0:b.location.origin;return _?_+"/tonconnect-manifest.json":""}function tryGetLocalStorage$1(){if(isLocalStorageAvailable$1())return localStorage;if(isNodeJs$1())throw new TonConnectError("`localStorage` is unavailable, but it is required for TonConnect. For more details, see https://github.com/ton-connect/sdk/tree/main/packages/sdk#init-connector");return InMemoryStorage$1.getInstance()}function isLocalStorageAvailable$1(){try{return typeof localStorage<"u"}catch{return!1}}function isNodeJs$1(){return typeof process<"u"&&process.versions!=null&&process.versions.node!=null}class InjectedProvider{constructor(_,d){this.injectedWalletKey=d,this.type="injected",this.unsubscribeCallback=null,this.listenSubscriptions=!1,this.listeners=[];const k=InjectedProvider.window;if(!InjectedProvider.isWindowContainsWallet(k,d))throw new WalletNotInjectedError;this.connectionStorage=new BridgeConnectionStorage(_),this.injectedWallet=k[d].tonconnect}static fromStorage(_){return __awaiter(this,void 0,void 0,function*(){const k=yield new BridgeConnectionStorage(_).getInjectedConnection();return new InjectedProvider(_,k.jsBridgeKey)})}static isWalletInjected(_){return InjectedProvider.isWindowContainsWallet(this.window,_)}static isInsideWalletBrowser(_){return InjectedProvider.isWindowContainsWallet(this.window,_)?this.window[_].tonconnect.isWalletBrowser:!1}static getCurrentlyInjectedWallets(){return this.window?tryGetWindowKeys().filter(([k,j])=>isJSBridgeWithMetadata(j)).map(([k,j])=>({name:j.tonconnect.walletInfo.name,appName:j.tonconnect.walletInfo.app_name,aboutUrl:j.tonconnect.walletInfo.about_url,imageUrl:j.tonconnect.walletInfo.image,tondns:j.tonconnect.walletInfo.tondns,jsBridgeKey:k,injected:!0,embedded:j.tonconnect.isWalletBrowser,platforms:j.tonconnect.walletInfo.platforms})):[]}static isWindowContainsWallet(_,d){return!!_&&d in _&&typeof _[d]=="object"&&"tonconnect"in _[d]}connect(_){this._connect(PROTOCOL_VERSION,_)}restoreConnection(){return __awaiter(this,void 0,void 0,function*(){try{logDebug("Injected Provider restoring connection...");const _=yield this.injectedWallet.restoreConnection();logDebug("Injected Provider restoring connection response",_),_.event==="connect"?(this.makeSubscriptions(),this.listeners.forEach(d=>d(_))):yield this.connectionStorage.removeConnection()}catch(_){yield this.connectionStorage.removeConnection(),console.error(_)}})}closeConnection(){this.listenSubscriptions&&this.injectedWallet.disconnect(),this.closeAllListeners()}disconnect(){return __awaiter(this,void 0,void 0,function*(){return new Promise(_=>{const d=()=>{this.closeAllListeners(),this.connectionStorage.removeConnection().then(_)};try{this.injectedWallet.disconnect(),d()}catch(k){logDebug(k),this.sendRequest({method:"disconnect",params:[]},d)}})})}closeAllListeners(){var _;this.listenSubscriptions=!1,this.listeners=[],(_=this.unsubscribeCallback)===null||_===void 0||_.call(this)}listen(_){return this.listeners.push(_),()=>this.listeners=this.listeners.filter(d=>d!==_)}sendRequest(_,d){return __awaiter(this,void 0,void 0,function*(){const k=(yield this.connectionStorage.getNextRpcRequestId()).toString();yield this.connectionStorage.increaseNextRpcRequestId(),logDebug("Send injected-bridge request:",Object.assign(Object.assign({},_),{id:k}));const j=this.injectedWallet.send(Object.assign(Object.assign({},_),{id:k}));return j.then($=>logDebug("Wallet message received:",$)),d==null||d(),j})}_connect(_,d){return __awaiter(this,void 0,void 0,function*(){try{logDebug(`Injected Provider connect request: protocolVersion: ${_}, message:`,d);const k=yield this.injectedWallet.connect(_,d);logDebug("Injected Provider connect response:",k),k.event==="connect"&&(yield this.updateSession(),this.makeSubscriptions()),this.listeners.forEach(j=>j(k))}catch(k){logDebug(k);const j={event:"connect_error",payload:{code:0,message:k==null?void 0:k.toString()}};this.listeners.forEach($=>$(j))}})}makeSubscriptions(){this.listenSubscriptions=!0,this.unsubscribeCallback=this.injectedWallet.listen(_=>{logDebug("Wallet message received:",_),this.listenSubscriptions&&this.listeners.forEach(d=>d(_)),_.event==="disconnect"&&this.disconnect()})}updateSession(){return this.connectionStorage.storeConnection({type:"injected",jsBridgeKey:this.injectedWalletKey,nextRpcRequestId:0})}}InjectedProvider.window=getWindow$2();class DefaultStorage{constructor(){this.localStorage=tryGetLocalStorage$1()}getItem(_){return __awaiter(this,void 0,void 0,function*(){return this.localStorage.getItem(_)})}removeItem(_){return __awaiter(this,void 0,void 0,function*(){this.localStorage.removeItem(_)})}setItem(_,d){return __awaiter(this,void 0,void 0,function*(){this.localStorage.setItem(_,d)})}}function isWalletInfoCurrentlyInjected(b){return isWalletInfoInjectable(b)&&b.injected}function isWalletInfoCurrentlyEmbedded(b){return isWalletInfoCurrentlyInjected(b)&&b.embedded}function isWalletInfoInjectable(b){return"jsBridgeKey"in b}function isWalletInfoRemote(b){return"bridgeUrl"in b}const FALLBACK_WALLETS_LIST=[{app_name:"telegram-wallet",name:"Wallet",image:"https://wallet.tg/images/logo-288.png",about_url:"https://wallet.tg/",universal_url:"https://t.me/wallet?attach=wallet",bridge:[{type:"sse",url:"https://bridge.tonapi.io/bridge"}],platforms:["ios","android","macos","windows","linux"]},{app_name:"tonkeeper",name:"Tonkeeper",image:"https://tonkeeper.com/assets/tonconnect-icon.png",tondns:"tonkeeper.ton",about_url:"https://tonkeeper.com",universal_url:"https://app.tonkeeper.com/ton-connect",bridge:[{type:"sse",url:"https://bridge.tonapi.io/bridge"},{type:"js",key:"tonkeeper"}],platforms:["ios","android","chrome","firefox"]},{app_name:"openmask",name:"OpenMask",image:"https://raw.githubusercontent.com/OpenProduct/openmask-extension/main/public/openmask-logo-288.png",about_url:"https://www.openmask.app/",bridge:[{type:"js",key:"openmask"}],platforms:["chrome"]},{app_name:"mytonwallet",name:"MyTonWallet",image:"https://mytonwallet.io/icon-256.png",about_url:"https://mytonwallet.io",universal_url:"https://connect.mytonwallet.org",bridge:[{type:"js",key:"mytonwallet"},{type:"sse",url:"https://tonconnectbridge.mytonwallet.org/bridge/"}],platforms:["chrome","windows","macos","linux"]},{app_name:"tonhub",name:"Tonhub",image:"https://tonhub.com/tonconnect_logo.png",about_url:"https://tonhub.com",universal_url:"https://tonhub.com/ton-connect",bridge:[{type:"js",key:"tonhub"},{type:"sse",url:"https://connect.tonhubapi.com/tonconnect"}],platforms:["ios","android"]},{app_name:"tonflow",name:"TonFlow",image:"https://tonflow.net/assets/images/tonflow_ico_192.png",about_url:"https://tonflow.net",bridge:[{type:"js",key:"tonflow"}],platforms:["chrome"]},{app_name:"dewallet",name:"DeWallet",image:"https://app.delabwallet.com/logo_black.png",about_url:"https://delabwallet.com",bridge:[{type:"js",key:"dewallet"}],platforms:["chrome"]},{app_name:"xtonwallet",name:"XTONWallet",image:"https://xtonwallet.com/assets/img/icon-256-back.png",about_url:"https://xtonwallet.com",bridge:[{type:"js",key:"xtonwallet"}],platforms:["chrome","firefox"]},{app_name:"tonwallet",name:"TON Wallet",image:"https://wallet.ton.org/assets/ui/qr-logo.png",about_url:"https://chrome.google.com/webstore/detail/ton-wallet/nphplpgoakhhjchkkhmiggakijnkhfnd",bridge:[{type:"js",key:"tonwallet"}],platforms:["chrome"]}];class WalletsListManager{constructor(_){this.walletsListCache=null,this.walletsListCacheCreationTimestamp=null,this.walletsListSource="https://raw.githubusercontent.com/ton-blockchain/wallets-list/main/wallets-v2.json",_!=null&&_.walletsListSource&&(this.walletsListSource=_.walletsListSource),_!=null&&_.cacheTTLMs&&(this.cacheTTLMs=_.cacheTTLMs)}getWallets(){return __awaiter(this,void 0,void 0,function*(){return this.cacheTTLMs&&this.walletsListCacheCreationTimestamp&&Date.now()>this.walletsListCacheCreationTimestamp+this.cacheTTLMs&&(this.walletsListCache=null),this.walletsListCache||(this.walletsListCache=this.fetchWalletsList(),this.walletsListCache.then(()=>{this.walletsListCacheCreationTimestamp=Date.now()}).catch(()=>{this.walletsListCache=null,this.walletsListCacheCreationTimestamp=null})),this.walletsListCache})}getEmbeddedWallet(){return __awaiter(this,void 0,void 0,function*(){const d=(yield this.getWallets()).filter(isWalletInfoCurrentlyEmbedded);return d.length!==1?null:d[0]})}fetchWalletsList(){return __awaiter(this,void 0,void 0,function*(){let _=[];try{if(_=yield(yield fetch(this.walletsListSource)).json(),!Array.isArray(_))throw new FetchWalletsError("Wrong wallets list format, wallets list must be an array.");const j=_.filter($=>!this.isCorrectWalletConfigDTO($));j.length&&(logError$1(`Wallet(s) ${j.map($=>$.name).join(", ")} config format is wrong. They were removed from the wallets list.`),_=_.filter($=>this.isCorrectWalletConfigDTO($)))}catch(k){logError$1(k),_=FALLBACK_WALLETS_LIST}let d=[];try{d=InjectedProvider.getCurrentlyInjectedWallets()}catch(k){logError$1(k)}return this.mergeWalletsLists(this.walletConfigDTOListToWalletConfigList(_),d)})}walletConfigDTOListToWalletConfigList(_){return _.map(d=>{const j={name:d.name,appName:d.app_name,imageUrl:d.image,aboutUrl:d.about_url,tondns:d.tondns,platforms:d.platforms};return d.bridge.forEach($=>{if($.type==="sse"&&(j.bridgeUrl=$.url,j.universalLink=d.universal_url,j.deepLink=d.deepLink),$.type==="js"){const et=$.key;j.jsBridgeKey=et,j.injected=InjectedProvider.isWalletInjected(et),j.embedded=InjectedProvider.isInsideWalletBrowser(et)}}),j})}mergeWalletsLists(_,d){return[...new Set(_.concat(d).map(j=>j.name)).values()].map(j=>{const $=_.find(tt=>tt.name===j),et=d.find(tt=>tt.name===j);return Object.assign(Object.assign({},$&&Object.assign({},$)),et&&Object.assign({},et))})}isCorrectWalletConfigDTO(_){if(!_||typeof _!="object")return!1;const d="name"in _,k="app_name"in _,j="image"in _,$="about_url"in _,et="platforms"in _;if(!d||!j||!$||!et||!k||!_.platforms||!Array.isArray(_.platforms)||!_.platforms.length||!("bridge"in _)||!Array.isArray(_.bridge)||!_.bridge.length)return!1;const tt=_.bridge;if(tt.some(ot=>!ot||typeof ot!="object"||!("type"in ot)))return!1;const rt=tt.find(ot=>ot.type==="sse");if(rt&&(!("url"in rt)||!rt.url||!_.universal_url))return!1;const nt=tt.find(ot=>ot.type==="js");return!(nt&&(!("key"in nt)||!nt.key))}}class WalletNotSupportFeatureError extends TonConnectError{get info(){return"Wallet doesn't support requested feature method."}constructor(..._){super(..._),Object.setPrototypeOf(this,WalletNotSupportFeatureError.prototype)}}function checkSendTransactionSupport(b,_){const d=b.includes("SendTransaction"),k=b.find(j=>j&&typeof j=="object"&&j.name==="SendTransaction");if(!d&&!k)throw new WalletNotSupportFeatureError("Wallet doesn't support SendTransaction feature.");if(k&&k.maxMessages!==void 0){if(k.maxMessages<_.requiredMessagesNumber)throw new WalletNotSupportFeatureError(`Wallet is not able to handle such SendTransaction request. Max support messages number is ${k.maxMessages}, but ${_.requiredMessagesNumber} is required.`);return}logWarning$1("Connected wallet didn't provide information about max allowed messages in the SendTransaction request. Request may be rejected by the wallet.")}class TonConnect{constructor(_){if(this.walletsList=new WalletsListManager,this._wallet=null,this.provider=null,this.statusChangeSubscriptions=[],this.statusChangeErrorSubscriptions=[],this.dappSettings={manifestUrl:(_==null?void 0:_.manifestUrl)||getWebPageManifest(),storage:(_==null?void 0:_.storage)||new DefaultStorage},this.walletsList=new WalletsListManager({walletsListSource:_==null?void 0:_.walletsListSource,cacheTTLMs:_==null?void 0:_.walletsListCacheTTLMs}),!this.dappSettings.manifestUrl)throw new DappMetadataError("Dapp tonconnect-manifest.json must be specified if window.location.origin is undefined. See more https://github.com/ton-connect/docs/blob/main/requests-responses.md#app-manifest");this.bridgeConnectionStorage=new BridgeConnectionStorage(this.dappSettings.storage),_!=null&&_.disableAutoPauseConnection||this.addWindowFocusAndBlurSubscriptions()}static getWallets(){return this.walletsList.getWallets()}get connected(){return this._wallet!==null}get account(){var _;return((_=this._wallet)===null||_===void 0?void 0:_.account)||null}get wallet(){return this._wallet}set wallet(_){this._wallet=_,this.statusChangeSubscriptions.forEach(d=>d(this._wallet))}getWallets(){return this.walletsList.getWallets()}onStatusChange(_,d){return this.statusChangeSubscriptions.push(_),d&&this.statusChangeErrorSubscriptions.push(d),()=>{this.statusChangeSubscriptions=this.statusChangeSubscriptions.filter(k=>k!==_),d&&(this.statusChangeErrorSubscriptions=this.statusChangeErrorSubscriptions.filter(k=>k!==d))}}connect(_,d){var k;if(this.connected)throw new WalletAlreadyConnectedError;return(k=this.provider)===null||k===void 0||k.closeConnection(),this.provider=this.createProvider(_),this.provider.connect(this.createConnectRequest(d))}restoreConnection(){return __awaiter(this,void 0,void 0,function*(){const[_,d]=yield Promise.all([this.bridgeConnectionStorage.storedConnectionType(),this.walletsList.getEmbeddedWallet()]);try{switch(_){case"http":this.provider=yield BridgeProvider.fromStorage(this.dappSettings.storage);break;case"injected":this.provider=yield InjectedProvider.fromStorage(this.dappSettings.storage);break;default:if(d)this.provider=yield this.createProvider(d);else return}}catch{yield this.bridgeConnectionStorage.removeConnection(),this.provider=null;return}return this.provider.listen(this.walletEventsListener.bind(this)),this.provider.restoreConnection()})}sendTransaction(_,d){return __awaiter(this,void 0,void 0,function*(){this.checkConnection(),checkSendTransactionSupport(this.wallet.device.features,{requiredMessagesNumber:_.messages.length});const{validUntil:k}=_,j=__rest(_,["validUntil"]),$=_.from||this.account.address,et=_.network||this.account.chain,tt=yield this.provider.sendRequest(sendTransactionParser.convertToRpcRequest(Object.assign(Object.assign({},j),{valid_until:k,from:$,network:et})),d);return sendTransactionParser.isError(tt)?sendTransactionParser.parseAndThrowError(tt):sendTransactionParser.convertFromRpcResponse(tt)})}disconnect(){return __awaiter(this,void 0,void 0,function*(){if(!this.connected)throw new WalletNotConnectedError;yield this.provider.disconnect(),this.onWalletDisconnected()})}pauseConnection(){var _;((_=this.provider)===null||_===void 0?void 0:_.type)==="http"&&this.provider.pause()}unPauseConnection(){var _;return((_=this.provider)===null||_===void 0?void 0:_.type)!=="http"?Promise.resolve():this.provider.unPause()}addWindowFocusAndBlurSubscriptions(){const _=getDocument();if(_)try{_.addEventListener("visibilitychange",()=>{_.hidden?this.pauseConnection():this.unPauseConnection()})}catch(d){console.error("Cannot subscribe to the document.visibilitychange: ",d)}}createProvider(_){let d;return!Array.isArray(_)&&isWalletConnectionSourceJS(_)?d=new InjectedProvider(this.dappSettings.storage,_.jsBridgeKey):d=new BridgeProvider(this.dappSettings.storage,_),d.listen(this.walletEventsListener.bind(this)),d}walletEventsListener(_){switch(_.event){case"connect":this.onWalletConnected(_.payload);break;case"connect_error":this.onWalletConnectError(_.payload);break;case"disconnect":this.onWalletDisconnected()}}onWalletConnected(_){const d=_.items.find($=>$.name==="ton_addr"),k=_.items.find($=>$.name==="ton_proof");if(!d)throw new TonConnectError("ton_addr connection item was not found");const j={device:_.device,provider:this.provider.type,account:{address:d.address,chain:d.network,walletStateInit:d.walletStateInit,publicKey:d.publicKey}};k&&(j.connectItems={tonProof:k}),this.wallet=j}onWalletConnectError(_){const d=connectErrorsParser.parseError(_);if(this.statusChangeErrorSubscriptions.forEach(k=>k(d)),console.debug(d),d instanceof ManifestNotFoundError||d instanceof ManifestContentErrorError)throw console.error(d),d}onWalletDisconnected(){this.wallet=null}checkConnection(){if(!this.connected)throw new WalletNotConnectedError}createConnectRequest(_){const d=[{name:"ton_addr"}];return _!=null&&_.tonProof&&d.push({name:"ton_proof",payload:_.tonProof}),{manifestUrl:this.dappSettings.manifestUrl,items:d}}}TonConnect.walletsList=new WalletsListManager;TonConnect.isWalletInjected=b=>InjectedProvider.isWalletInjected(b);TonConnect.isInsideWalletBrowser=b=>InjectedProvider.isInsideWalletBrowser(b);const noBounceableTag=81,testOnlyTag=128;function toUserFriendlyAddress(b,_=!1){const{wc:d,hex:k}=parseHexAddress(b);let j=noBounceableTag;_&&(j|=testOnlyTag);const $=new Int8Array(34);$[0]=j,$[1]=d,$.set(k,2);const et=new Uint8Array(36);return et.set($),et.set(crc16($),34),Base64.encode(et).replace(/\+/g,"-").replace(/\//g,"_")}function parseHexAddress(b){if(!b.includes(":"))throw new WrongAddressError(`Wrong address ${b}. Address must include ":".`);const _=b.split(":");if(_.length!==2)throw new WrongAddressError(`Wrong address ${b}. Address must include ":" only once.`);const d=parseInt(_[0]);if(d!==0&&d!==-1)throw new WrongAddressError(`Wrong address ${b}. WC must be eq 0 or -1, but ${d} received.`);const k=_[1];if((k==null?void 0:k.length)!==64)throw new WrongAddressError(`Wrong address ${b}. Hex part must be 64bytes length, but ${k==null?void 0:k.length} received.`);return{wc:d,hex:hexToBytes(k)}}function crc16(b){let d=0;const k=new Uint8Array(b.length+2);k.set(b);for(let j of k){let $=128;for(;$>0;)d<<=1,j&$&&(d+=1),$>>=1,d>65535&&(d&=65535,d^=4129)}return new Uint8Array([Math.floor(d/256),d%256])}const toByteMap={};for(let b=0;b<=255;b++){let _=b.toString(16);_.length<2&&(_="0"+_),toByteMap[_]=b}function hexToBytes(b){b=b.toLowerCase();const _=b.length;if(_%2!==0)throw new ParseHexError("Hex string must have length a multiple of 2: "+b);const d=_/2,k=new Uint8Array(d);for(let j=0;j0?fr.length===2?typeof fr[1]==tt?this[fr[0]]=fr[1].call(this,vr):this[fr[0]]=fr[1]:fr.length===3?typeof fr[1]===tt&&!(fr[1].exec&&fr[1].test)?this[fr[0]]=vr?fr[1].call(this,vr,fr[2]):k:this[fr[0]]=vr?vr.replace(fr[1],fr[2]):k:fr.length===4&&(this[fr[0]]=vr?fr[3].call(this,vr.replace(fr[1],fr[2])):k):this[fr]=vr||k;qt+=2}},Pn=function(pn,Vt){for(var qt in Vt)if(typeof Vt[qt]===nt&&Vt[qt].length>0){for(var wn=0;wn2&&(Zn[it]="iPad",Zn[ut]=lt),Zn},this.getEngine=function(){var Zn={};return Zn[dt]=k,Zn[ft]=k,Rn.call(Zn,wn,lr.engine),Zn},this.getOS=function(){var Zn={};return Zn[dt]=k,Zn[ft]=k,Rn.call(Zn,wn,lr.os),fr&&!Zn[dt]&&Ln&&Ln.platform!="Unknown"&&(Zn[dt]=Ln.platform.replace(/chrome os/i,xn).replace(/macos/i,fn)),Zn},this.getResult=function(){return{ua:this.getUA(),browser:this.getBrowser(),engine:this.getEngine(),os:this.getOS(),device:this.getDevice(),cpu:this.getCPU()}},this.getUA=function(){return wn},this.setUA=function(Zn){return wn=typeof Zn===ot&&Zn.length>Et?Tn(Zn,Et):Zn,this},this.setUA(wn),this};Bn.VERSION=j,Bn.BROWSER=bn([dt,ft,at]),Bn.CPU=bn([st]),Bn.DEVICE=bn([it,ht,ut,ct,pt,wt,lt,vt,yt]),Bn.ENGINE=Bn.OS=bn([dt,ft]),b.exports&&(_=b.exports=Bn),_.UAParser=Bn;var Nn=typeof d!==rt&&(d.jQuery||d.Zepto);if(Nn&&!Nn.ua){var Wn=new Bn;Nn.ua=Wn.getResult(),Nn.ua.get=function(){return Wn.getUA()},Nn.ua.set=function(pn){Wn.setUA(pn);var Vt=Wn.getResult();for(var qt in Vt)Nn.ua[qt]=Vt[qt]}}})(typeof window=="object"?window:commonjsGlobal)})(uaParser,uaParser.exports);var uaParserExports=uaParser.exports;const UAParser=getDefaultExportFromCjs(uaParserExports);var isMergeableObject=function(_){return isNonNullObject(_)&&!isSpecial(_)};function isNonNullObject(b){return!!b&&typeof b=="object"}function isSpecial(b){var _=Object.prototype.toString.call(b);return _==="[object RegExp]"||_==="[object Date]"||isReactElement(b)}var canUseSymbol=typeof Symbol=="function"&&Symbol.for,REACT_ELEMENT_TYPE=canUseSymbol?Symbol.for("react.element"):60103;function isReactElement(b){return b.$$typeof===REACT_ELEMENT_TYPE}function emptyTarget(b){return Array.isArray(b)?[]:{}}function cloneUnlessOtherwiseSpecified(b,_){return _.clone!==!1&&_.isMergeableObject(b)?deepmerge(emptyTarget(b),b,_):b}function defaultArrayMerge(b,_,d){return b.concat(_).map(function(k){return cloneUnlessOtherwiseSpecified(k,d)})}function getMergeFunction(b,_){if(!_.customMerge)return deepmerge;var d=_.customMerge(b);return typeof d=="function"?d:deepmerge}function getEnumerableOwnPropertySymbols(b){return Object.getOwnPropertySymbols?Object.getOwnPropertySymbols(b).filter(function(_){return b.propertyIsEnumerable(_)}):[]}function getKeys(b){return Object.keys(b).concat(getEnumerableOwnPropertySymbols(b))}function propertyIsOnObject(b,_){try{return _ in b}catch{return!1}}function propertyIsUnsafe(b,_){return propertyIsOnObject(b,_)&&!(Object.hasOwnProperty.call(b,_)&&Object.propertyIsEnumerable.call(b,_))}function mergeObject(b,_,d){var k={};return d.isMergeableObject(b)&&getKeys(b).forEach(function(j){k[j]=cloneUnlessOtherwiseSpecified(b[j],d)}),getKeys(_).forEach(function(j){propertyIsUnsafe(b,j)||(propertyIsOnObject(b,j)&&d.isMergeableObject(_[j])?k[j]=getMergeFunction(j,d)(b[j],_[j],d):k[j]=cloneUnlessOtherwiseSpecified(_[j],d))}),k}function deepmerge(b,_,d){d=d||{},d.arrayMerge=d.arrayMerge||defaultArrayMerge,d.isMergeableObject=d.isMergeableObject||isMergeableObject,d.cloneUnlessOtherwiseSpecified=cloneUnlessOtherwiseSpecified;var k=Array.isArray(_),j=Array.isArray(b),$=k===j;return $?k?d.arrayMerge(b,_,d):mergeObject(b,_,d):cloneUnlessOtherwiseSpecified(_,d)}deepmerge.all=function(_,d){if(!Array.isArray(_))throw new Error("first argument should be an array");return _.reduce(function(k,j){return deepmerge(k,j,d)},{})};var deepmerge_1=deepmerge,cjs=deepmerge_1;const deepmerge$1=getDefaultExportFromCjs(cjs);var classnames={exports:{}};/*! +`+_:""}`,Object.setPrototypeOf(this,TonConnectError.prototype)}get info(){return""}}TonConnectError.prefix="[TON_CONNECT_SDK_ERROR]";class DappMetadataError extends TonConnectError{get info(){return"Passed DappMetadata is in incorrect format."}constructor(..._){super(..._),Object.setPrototypeOf(this,DappMetadataError.prototype)}}class ManifestContentErrorError extends TonConnectError{get info(){return"Passed `tonconnect-manifest.json` contains errors. Check format of your manifest. See more https://github.com/ton-connect/docs/blob/main/requests-responses.md#app-manifest"}constructor(..._){super(..._),Object.setPrototypeOf(this,ManifestContentErrorError.prototype)}}class ManifestNotFoundError extends TonConnectError{get info(){return"Manifest not found. Make sure you added `tonconnect-manifest.json` to the root of your app or passed correct manifestUrl. See more https://github.com/ton-connect/docs/blob/main/requests-responses.md#app-manifest"}constructor(..._){super(..._),Object.setPrototypeOf(this,ManifestNotFoundError.prototype)}}class WalletAlreadyConnectedError extends TonConnectError{get info(){return"Wallet connection called but wallet already connected. To avoid the error, disconnect the wallet before doing a new connection."}constructor(..._){super(..._),Object.setPrototypeOf(this,WalletAlreadyConnectedError.prototype)}}class WalletNotConnectedError extends TonConnectError{get info(){return"Send transaction or other protocol methods called while wallet is not connected."}constructor(..._){super(..._),Object.setPrototypeOf(this,WalletNotConnectedError.prototype)}}function isWalletConnectionSourceJS(b){return"jsBridgeKey"in b}class UserRejectsError extends TonConnectError{get info(){return"User rejects the action in the wallet."}constructor(..._){super(..._),Object.setPrototypeOf(this,UserRejectsError.prototype)}}class BadRequestError extends TonConnectError{get info(){return"Request to the wallet contains errors."}constructor(..._){super(..._),Object.setPrototypeOf(this,BadRequestError.prototype)}}class UnknownAppError extends TonConnectError{get info(){return"App tries to send rpc request to the injected wallet while not connected."}constructor(..._){super(..._),Object.setPrototypeOf(this,UnknownAppError.prototype)}}class WalletNotInjectedError extends TonConnectError{get info(){return"There is an attempt to connect to the injected wallet while it is not exists in the webpage."}constructor(..._){super(..._),Object.setPrototypeOf(this,WalletNotInjectedError.prototype)}}class FetchWalletsError extends TonConnectError{get info(){return"An error occurred while fetching the wallets list."}constructor(..._){super(..._),Object.setPrototypeOf(this,FetchWalletsError.prototype)}}class WrongAddressError extends TonConnectError{get info(){return"Passed address is in incorrect format."}constructor(..._){super(..._),Object.setPrototypeOf(this,WrongAddressError.prototype)}}class ParseHexError extends TonConnectError{get info(){return"Passed hex is in incorrect format."}constructor(..._){super(..._),Object.setPrototypeOf(this,ParseHexError.prototype)}}class UnknownError extends TonConnectError{constructor(..._){super(..._),Object.setPrototypeOf(this,UnknownError.prototype)}}const connectEventErrorsCodes={[CONNECT_EVENT_ERROR_CODES.UNKNOWN_ERROR]:UnknownError,[CONNECT_EVENT_ERROR_CODES.USER_REJECTS_ERROR]:UserRejectsError,[CONNECT_EVENT_ERROR_CODES.BAD_REQUEST_ERROR]:BadRequestError,[CONNECT_EVENT_ERROR_CODES.UNKNOWN_APP_ERROR]:UnknownAppError,[CONNECT_EVENT_ERROR_CODES.MANIFEST_NOT_FOUND_ERROR]:ManifestNotFoundError,[CONNECT_EVENT_ERROR_CODES.MANIFEST_CONTENT_ERROR]:ManifestContentErrorError};class ConnectErrorsParser{parseError(_){let d=UnknownError;return _.code in connectEventErrorsCodes&&(d=connectEventErrorsCodes[_.code]||UnknownError),new d(_.message)}}const connectErrorsParser=new ConnectErrorsParser;class RpcParser{isError(_){return"error"in _}}const sendTransactionErrors={[SEND_TRANSACTION_ERROR_CODES.UNKNOWN_ERROR]:UnknownError,[SEND_TRANSACTION_ERROR_CODES.USER_REJECTS_ERROR]:UserRejectsError,[SEND_TRANSACTION_ERROR_CODES.BAD_REQUEST_ERROR]:BadRequestError,[SEND_TRANSACTION_ERROR_CODES.UNKNOWN_APP_ERROR]:UnknownAppError};class SendTransactionParser extends RpcParser{convertToRpcRequest(_){return{method:"sendTransaction",params:[JSON.stringify(_)]}}parseAndThrowError(_){let d=UnknownError;throw _.error.code in sendTransactionErrors&&(d=sendTransactionErrors[_.error.code]||UnknownError),new d(_.error.message)}convertFromRpcResponse(_){return{boc:_.result}}}const sendTransactionParser=new SendTransactionParser;class HttpBridgeGatewayStorage{constructor(_,d){this.storage=_,this.storeKey="ton-connect-storage_http-bridge-gateway::"+d}storeLastEventId(_){return __awaiter(this,void 0,void 0,function*(){return this.storage.setItem(this.storeKey,_)})}removeLastEventId(){return __awaiter(this,void 0,void 0,function*(){return this.storage.removeItem(this.storeKey)})}getLastEventId(){return __awaiter(this,void 0,void 0,function*(){const _=yield this.storage.getItem(this.storeKey);return _||null})}}function removeUrlLastSlash(b){return b.slice(-1)==="/"?b.slice(0,-1):b}function addPathToUrl(b,_){return removeUrlLastSlash(b)+"/"+_}function isTelegramUrl(b){if(!b)return!1;const _=new URL(b);return _.protocol==="tg:"||_.hostname==="t.me"}function encodeTelegramUrlParameters(b){return b.replaceAll(".","%2E").replaceAll("-","%2D").replaceAll("_","%5F").replaceAll("&","-").replaceAll("=","__").replaceAll("%","--")}class BridgeGateway{constructor(_,d,k,j,$){this.bridgeUrl=d,this.sessionId=k,this.listener=j,this.errorsListener=$,this.ssePath="events",this.postPath="message",this.heartbeatMessage="heartbeat",this.defaultTtl=300,this.isClosed=!1,this.bridgeGatewayStorage=new HttpBridgeGatewayStorage(_,d)}registerSession(_){return __awaiter(this,void 0,void 0,function*(){const d=new URL(addPathToUrl(this.bridgeUrl,this.ssePath));d.searchParams.append("client_id",this.sessionId);const k=yield this.bridgeGatewayStorage.getLastEventId();if(!this.isClosed)return k&&d.searchParams.append("last_event_id",k),this.eventSource=new EventSource(d.toString()),new Promise((j,$)=>{const et=_!=null&&_.openingDeadlineMS?setTimeout(()=>{var tt;((tt=this.eventSource)===null||tt===void 0?void 0:tt.readyState)!==EventSource.OPEN&&($(new TonConnectError("Bridge connection timeout")),this.close())},_.openingDeadlineMS):void 0;this.eventSource.onerror=()=>$,this.eventSource.onopen=()=>{clearTimeout(et),this.isClosed=!1,this.eventSource.onerror=this.errorsHandler.bind(this),this.eventSource.onmessage=this.messagesHandler.bind(this),j()}})})}send(_,d,k,j){return __awaiter(this,void 0,void 0,function*(){const $=new URL(addPathToUrl(this.bridgeUrl,this.postPath));$.searchParams.append("client_id",this.sessionId),$.searchParams.append("to",d),$.searchParams.append("ttl",(j||this.defaultTtl).toString()),$.searchParams.append("topic",k);const et=yield fetch($,{method:"post",body:Base64.encode(_)});if(!et.ok)throw new TonConnectError(`Bridge send failed, status ${et.status}`)})}pause(){var _;(_=this.eventSource)===null||_===void 0||_.close()}unPause(){return this.registerSession()}close(){var _;this.isClosed=!0,(_=this.eventSource)===null||_===void 0||_.close()}setListener(_){this.listener=_}setErrorsListener(_){this.errorsListener=_}errorsHandler(_){var d,k;if(!this.isClosed){if(((d=this.eventSource)===null||d===void 0?void 0:d.readyState)===EventSource.CLOSED){this.eventSource.close(),this.registerSession();return}if(((k=this.eventSource)===null||k===void 0?void 0:k.readyState)===EventSource.CONNECTING){console.debug("[TON_CONNET_SDK_ERROR]: Bridge error",JSON.stringify(_));return}this.errorsListener(_)}}messagesHandler(_){return __awaiter(this,void 0,void 0,function*(){if(_.data!==this.heartbeatMessage&&(yield this.bridgeGatewayStorage.storeLastEventId(_.lastEventId),!this.isClosed)){let d;try{d=JSON.parse(_.data)}catch(k){throw new TonConnectError(`Bridge message parse failed, message ${k.data}`)}this.listener(d)}})}}function isPendingConnectionHttp(b){return!("connectEvent"in b)}class BridgeConnectionStorage{constructor(_){this.storage=_,this.storeKey="ton-connect-storage_bridge-connection"}storeConnection(_){return __awaiter(this,void 0,void 0,function*(){if(_.type==="injected")return this.storage.setItem(this.storeKey,JSON.stringify(_));if(!isPendingConnectionHttp(_)){const k={sessionKeyPair:_.session.sessionCrypto.stringifyKeypair(),walletPublicKey:_.session.walletPublicKey,bridgeUrl:_.session.bridgeUrl},j={type:"http",connectEvent:_.connectEvent,session:k,lastWalletEventId:_.lastWalletEventId,nextRpcRequestId:_.nextRpcRequestId};return this.storage.setItem(this.storeKey,JSON.stringify(j))}const d={type:"http",connectionSource:_.connectionSource,sessionCrypto:_.sessionCrypto.stringifyKeypair()};return this.storage.setItem(this.storeKey,JSON.stringify(d))})}removeConnection(){return __awaiter(this,void 0,void 0,function*(){return this.storage.removeItem(this.storeKey)})}getConnection(){return __awaiter(this,void 0,void 0,function*(){const _=yield this.storage.getItem(this.storeKey);if(!_)return null;const d=JSON.parse(_);if(d.type==="injected")return d;if("connectEvent"in d){const k=new SessionCrypto(d.session.sessionKeyPair);return{type:"http",connectEvent:d.connectEvent,lastWalletEventId:d.lastWalletEventId,nextRpcRequestId:d.nextRpcRequestId,session:{sessionCrypto:k,bridgeUrl:d.session.bridgeUrl,walletPublicKey:d.session.walletPublicKey}}}return{type:"http",sessionCrypto:new SessionCrypto(d.sessionCrypto),connectionSource:d.connectionSource}})}getHttpConnection(){return __awaiter(this,void 0,void 0,function*(){const _=yield this.getConnection();if(!_)throw new TonConnectError("Trying to read HTTP connection source while nothing is stored");if(_.type==="injected")throw new TonConnectError("Trying to read HTTP connection source while injected connection is stored");return _})}getHttpPendingConnection(){return __awaiter(this,void 0,void 0,function*(){const _=yield this.getConnection();if(!_)throw new TonConnectError("Trying to read HTTP connection source while nothing is stored");if(_.type==="injected")throw new TonConnectError("Trying to read HTTP connection source while injected connection is stored");if(!isPendingConnectionHttp(_))throw new TonConnectError("Trying to read HTTP-pending connection while http connection is stored");return _})}getInjectedConnection(){return __awaiter(this,void 0,void 0,function*(){const _=yield this.getConnection();if(!_)throw new TonConnectError("Trying to read Injected bridge connection source while nothing is stored");if((_==null?void 0:_.type)==="http")throw new TonConnectError("Trying to read Injected bridge connection source while HTTP connection is stored");return _})}storedConnectionType(){return __awaiter(this,void 0,void 0,function*(){const _=yield this.storage.getItem(this.storeKey);return _?JSON.parse(_).type:null})}storeLastWalletEventId(_){return __awaiter(this,void 0,void 0,function*(){const d=yield this.getConnection();if(d&&d.type==="http"&&!isPendingConnectionHttp(d))return d.lastWalletEventId=_,this.storeConnection(d)})}getLastWalletEventId(){return __awaiter(this,void 0,void 0,function*(){const _=yield this.getConnection();if(_&&"lastWalletEventId"in _)return _.lastWalletEventId})}increaseNextRpcRequestId(){return __awaiter(this,void 0,void 0,function*(){const _=yield this.getConnection();if(_&&"nextRpcRequestId"in _){const d=_.nextRpcRequestId||0;return _.nextRpcRequestId=d+1,this.storeConnection(_)}})}getNextRpcRequestId(){return __awaiter(this,void 0,void 0,function*(){const _=yield this.getConnection();return _&&"nextRpcRequestId"in _&&_.nextRpcRequestId||0})}}const PROTOCOL_VERSION=2;function logDebug(...b){try{console.debug("[TON_CONNECT_SDK]",...b)}catch{}}function logError$1(...b){try{console.error("[TON_CONNECT_SDK]",...b)}catch{}}function logWarning$1(...b){try{console.warn("[TON_CONNECT_SDK]",...b)}catch{}}class BridgeProvider{constructor(_,d){this.storage=_,this.walletConnectionSource=d,this.type="http",this.standardUniversalLink="tc://",this.pendingRequests=new Map,this.session=null,this.gateway=null,this.pendingGateways=[],this.listeners=[],this.connectionStorage=new BridgeConnectionStorage(_)}static fromStorage(_){return __awaiter(this,void 0,void 0,function*(){const k=yield new BridgeConnectionStorage(_).getHttpConnection();return isPendingConnectionHttp(k)?new BridgeProvider(_,k.connectionSource):new BridgeProvider(_,{bridgeUrl:k.session.bridgeUrl})})}connect(_){this.closeGateways();const d=new SessionCrypto;this.session={sessionCrypto:d,bridgeUrl:"bridgeUrl"in this.walletConnectionSource?this.walletConnectionSource.bridgeUrl:""},this.connectionStorage.storeConnection({type:"http",connectionSource:this.walletConnectionSource,sessionCrypto:d}).then(()=>this.openGateways(d));const k="universalLink"in this.walletConnectionSource&&this.walletConnectionSource.universalLink?this.walletConnectionSource.universalLink:this.standardUniversalLink;return this.generateUniversalLink(k,_)}restoreConnection(){return __awaiter(this,void 0,void 0,function*(){this.closeGateways();const _=yield this.connectionStorage.getHttpConnection();if(_){if(isPendingConnectionHttp(_))return this.session={sessionCrypto:_.sessionCrypto,bridgeUrl:"bridgeUrl"in this.walletConnectionSource?this.walletConnectionSource.bridgeUrl:""},this.openGateways(_.sessionCrypto,{openingDeadlineMS:5e3});if(Array.isArray(this.walletConnectionSource))throw new TonConnectError("Internal error. Connection source is array while WalletConnectionSourceHTTP was expected.");this.session=_.session,this.gateway=new BridgeGateway(this.storage,this.walletConnectionSource.bridgeUrl,_.session.sessionCrypto.sessionId,this.gatewayListener.bind(this),this.gatewayErrorsListener.bind(this));try{yield this.gateway.registerSession({openingDeadlineMS:5e3})}catch{yield this.disconnect();return}this.listeners.forEach(d=>d(_.connectEvent))}})}sendRequest(_,d){return new Promise((k,j)=>__awaiter(this,void 0,void 0,function*(){if(!this.gateway||!this.session||!("walletPublicKey"in this.session))throw new TonConnectError("Trying to send bridge request without session");const $=(yield this.connectionStorage.getNextRpcRequestId()).toString();yield this.connectionStorage.increaseNextRpcRequestId(),logDebug("Send http-bridge request:",Object.assign(Object.assign({},_),{id:$}));const et=this.session.sessionCrypto.encrypt(JSON.stringify(Object.assign(Object.assign({},_),{id:$})),hexToByteArray(this.session.walletPublicKey));try{yield this.gateway.send(et,this.session.walletPublicKey,_.method),d==null||d(),this.pendingRequests.set($.toString(),k)}catch(tt){j(tt)}}))}closeConnection(){this.closeGateways(),this.listeners=[],this.session=null,this.gateway=null}disconnect(){return __awaiter(this,void 0,void 0,function*(){return new Promise(_=>__awaiter(this,void 0,void 0,function*(){let d=!1;const k=()=>{d=!0,this.removeBridgeAndSession().then(_)};try{yield this.sendRequest({method:"disconnect",params:[]},k)}catch(j){console.debug(j),d||this.removeBridgeAndSession().then(_)}}))})}listen(_){return this.listeners.push(_),()=>this.listeners=this.listeners.filter(d=>d!==_)}pause(){var _;(_=this.gateway)===null||_===void 0||_.pause(),this.pendingGateways.forEach(d=>d.pause())}unPause(){return __awaiter(this,void 0,void 0,function*(){const _=this.pendingGateways.map(d=>d.unPause());this.gateway&&_.push(this.gateway.unPause()),yield Promise.all(_)})}pendingGatewaysListener(_,d,k){return __awaiter(this,void 0,void 0,function*(){if(!this.pendingGateways.includes(_)){_.close();return}return this.closeGateways({except:_}),this.session.bridgeUrl=d,this.gateway=_,this.gateway.setErrorsListener(this.gatewayErrorsListener.bind(this)),this.gateway.setListener(this.gatewayListener.bind(this)),this.gatewayListener(k)})}gatewayListener(_){return __awaiter(this,void 0,void 0,function*(){const d=JSON.parse(this.session.sessionCrypto.decrypt(Base64.decode(_.message).toUint8Array(),hexToByteArray(_.from)));if(logDebug("Wallet message received:",d),!("event"in d)){const j=d.id.toString(),$=this.pendingRequests.get(j);if(!$){logDebug(`Response id ${j} doesn't match any request's id`);return}$(d),this.pendingRequests.delete(j);return}if(d.id!==void 0){const j=yield this.connectionStorage.getLastWalletEventId();if(j!==void 0&&d.id<=j){logError$1(`Received event id (=${d.id}) must be greater than stored last wallet event id (=${j}) `);return}d.event!=="connect"&&(yield this.connectionStorage.storeLastWalletEventId(d.id))}const k=this.listeners;d.event==="connect"&&(yield this.updateSession(d,_.from)),d.event==="disconnect"&&(yield this.removeBridgeAndSession()),k.forEach(j=>j(d))})}gatewayErrorsListener(_){return __awaiter(this,void 0,void 0,function*(){throw new TonConnectError(`Bridge error ${JSON.stringify(_)}`)})}updateSession(_,d){return __awaiter(this,void 0,void 0,function*(){this.session=Object.assign(Object.assign({},this.session),{walletPublicKey:d});const k=_.payload.items.find($=>$.name==="ton_addr"),j=Object.assign(Object.assign({},_),{payload:Object.assign(Object.assign({},_.payload),{items:[k]})});yield this.connectionStorage.storeConnection({type:"http",session:this.session,lastWalletEventId:_.id,connectEvent:j,nextRpcRequestId:0})})}removeBridgeAndSession(){return __awaiter(this,void 0,void 0,function*(){this.closeConnection(),yield this.connectionStorage.removeConnection()})}generateUniversalLink(_,d){return isTelegramUrl(_)?this.generateTGUniversalLink(_,d):this.generateRegularUniversalLink(_,d)}generateRegularUniversalLink(_,d){const k=new URL(_);return k.searchParams.append("v",PROTOCOL_VERSION.toString()),k.searchParams.append("id",this.session.sessionCrypto.sessionId),k.searchParams.append("r",JSON.stringify(d)),k.toString()}generateTGUniversalLink(_,d){const j=this.generateRegularUniversalLink("about:blank",d).split("?")[1],$="tonconnect-"+encodeTelegramUrlParameters(j),et=this.convertToDirectLink(_),tt=new URL(et);return tt.searchParams.append("startapp",$),tt.toString()}convertToDirectLink(_){const d=new URL(_);return d.searchParams.has("attach")&&(d.searchParams.delete("attach"),d.pathname+="/start"),d.toString()}openGateways(_,d){return __awaiter(this,void 0,void 0,function*(){if(Array.isArray(this.walletConnectionSource)){this.pendingGateways=this.walletConnectionSource.map(k=>{const j=new BridgeGateway(this.storage,k.bridgeUrl,_.sessionId,()=>{},$=>{console.error($)});return j.setListener($=>this.pendingGatewaysListener(j,k.bridgeUrl,$)),j}),yield Promise.allSettled(this.pendingGateways.map(k=>k.registerSession(d)));return}else return this.gateway=new BridgeGateway(this.storage,this.walletConnectionSource.bridgeUrl,_.sessionId,this.gatewayListener.bind(this),this.gatewayErrorsListener.bind(this)),this.gateway.registerSession(d)})}closeGateways(_){var d;(d=this.gateway)===null||d===void 0||d.close(),this.pendingGateways.filter(k=>k!==(_==null?void 0:_.except)).forEach(k=>k.close()),this.pendingGateways=[]}}function hasProperty(b,_){return hasProperties(b,[_])}function hasProperties(b,_){return!b||typeof b!="object"?!1:_.every(d=>d in b)}function isJSBridgeWithMetadata(b){try{return!hasProperty(b,"tonconnect")||!hasProperty(b.tonconnect,"walletInfo")?!1:hasProperties(b.tonconnect.walletInfo,["name","app_name","image","about_url","platforms"])}catch{return!1}}let InMemoryStorage$1=class Jo{constructor(){this.storage={}}static getInstance(){return Jo.instance||(Jo.instance=new Jo),Jo.instance}get length(){return Object.keys(this.storage).length}clear(){this.storage={}}getItem(_){var d;return(d=this.storage[_])!==null&&d!==void 0?d:null}key(_){var d;const k=Object.keys(this.storage);return _<0||_>=k.length?null:(d=k[_])!==null&&d!==void 0?d:null}removeItem(_){delete this.storage[_]}setItem(_,d){this.storage[_]=d}};function getWindow$2(){if(!(typeof window>"u"))return window}function tryGetWindowKeys(){const b=getWindow$2();if(!b)return[];try{return Object.keys(b)}catch{return[]}}function getDocument(){if(!(typeof document>"u"))return document}function getWebPageManifest(){var b;const _=(b=getWindow$2())===null||b===void 0?void 0:b.location.origin;return _?_+"/tonconnect-manifest.json":""}function tryGetLocalStorage$1(){if(isLocalStorageAvailable$1())return localStorage;if(isNodeJs$1())throw new TonConnectError("`localStorage` is unavailable, but it is required for TonConnect. For more details, see https://github.com/ton-connect/sdk/tree/main/packages/sdk#init-connector");return InMemoryStorage$1.getInstance()}function isLocalStorageAvailable$1(){try{return typeof localStorage<"u"}catch{return!1}}function isNodeJs$1(){return typeof process<"u"&&process.versions!=null&&process.versions.node!=null}class InjectedProvider{constructor(_,d){this.injectedWalletKey=d,this.type="injected",this.unsubscribeCallback=null,this.listenSubscriptions=!1,this.listeners=[];const k=InjectedProvider.window;if(!InjectedProvider.isWindowContainsWallet(k,d))throw new WalletNotInjectedError;this.connectionStorage=new BridgeConnectionStorage(_),this.injectedWallet=k[d].tonconnect}static fromStorage(_){return __awaiter(this,void 0,void 0,function*(){const k=yield new BridgeConnectionStorage(_).getInjectedConnection();return new InjectedProvider(_,k.jsBridgeKey)})}static isWalletInjected(_){return InjectedProvider.isWindowContainsWallet(this.window,_)}static isInsideWalletBrowser(_){return InjectedProvider.isWindowContainsWallet(this.window,_)?this.window[_].tonconnect.isWalletBrowser:!1}static getCurrentlyInjectedWallets(){return this.window?tryGetWindowKeys().filter(([k,j])=>isJSBridgeWithMetadata(j)).map(([k,j])=>({name:j.tonconnect.walletInfo.name,appName:j.tonconnect.walletInfo.app_name,aboutUrl:j.tonconnect.walletInfo.about_url,imageUrl:j.tonconnect.walletInfo.image,tondns:j.tonconnect.walletInfo.tondns,jsBridgeKey:k,injected:!0,embedded:j.tonconnect.isWalletBrowser,platforms:j.tonconnect.walletInfo.platforms})):[]}static isWindowContainsWallet(_,d){return!!_&&d in _&&typeof _[d]=="object"&&"tonconnect"in _[d]}connect(_){this._connect(PROTOCOL_VERSION,_)}restoreConnection(){return __awaiter(this,void 0,void 0,function*(){try{logDebug("Injected Provider restoring connection...");const _=yield this.injectedWallet.restoreConnection();logDebug("Injected Provider restoring connection response",_),_.event==="connect"?(this.makeSubscriptions(),this.listeners.forEach(d=>d(_))):yield this.connectionStorage.removeConnection()}catch(_){yield this.connectionStorage.removeConnection(),console.error(_)}})}closeConnection(){this.listenSubscriptions&&this.injectedWallet.disconnect(),this.closeAllListeners()}disconnect(){return __awaiter(this,void 0,void 0,function*(){return new Promise(_=>{const d=()=>{this.closeAllListeners(),this.connectionStorage.removeConnection().then(_)};try{this.injectedWallet.disconnect(),d()}catch(k){logDebug(k),this.sendRequest({method:"disconnect",params:[]},d)}})})}closeAllListeners(){var _;this.listenSubscriptions=!1,this.listeners=[],(_=this.unsubscribeCallback)===null||_===void 0||_.call(this)}listen(_){return this.listeners.push(_),()=>this.listeners=this.listeners.filter(d=>d!==_)}sendRequest(_,d){return __awaiter(this,void 0,void 0,function*(){const k=(yield this.connectionStorage.getNextRpcRequestId()).toString();yield this.connectionStorage.increaseNextRpcRequestId(),logDebug("Send injected-bridge request:",Object.assign(Object.assign({},_),{id:k}));const j=this.injectedWallet.send(Object.assign(Object.assign({},_),{id:k}));return j.then($=>logDebug("Wallet message received:",$)),d==null||d(),j})}_connect(_,d){return __awaiter(this,void 0,void 0,function*(){try{logDebug(`Injected Provider connect request: protocolVersion: ${_}, message:`,d);const k=yield this.injectedWallet.connect(_,d);logDebug("Injected Provider connect response:",k),k.event==="connect"&&(yield this.updateSession(),this.makeSubscriptions()),this.listeners.forEach(j=>j(k))}catch(k){logDebug(k);const j={event:"connect_error",payload:{code:0,message:k==null?void 0:k.toString()}};this.listeners.forEach($=>$(j))}})}makeSubscriptions(){this.listenSubscriptions=!0,this.unsubscribeCallback=this.injectedWallet.listen(_=>{logDebug("Wallet message received:",_),this.listenSubscriptions&&this.listeners.forEach(d=>d(_)),_.event==="disconnect"&&this.disconnect()})}updateSession(){return this.connectionStorage.storeConnection({type:"injected",jsBridgeKey:this.injectedWalletKey,nextRpcRequestId:0})}}InjectedProvider.window=getWindow$2();class DefaultStorage{constructor(){this.localStorage=tryGetLocalStorage$1()}getItem(_){return __awaiter(this,void 0,void 0,function*(){return this.localStorage.getItem(_)})}removeItem(_){return __awaiter(this,void 0,void 0,function*(){this.localStorage.removeItem(_)})}setItem(_,d){return __awaiter(this,void 0,void 0,function*(){this.localStorage.setItem(_,d)})}}function isWalletInfoCurrentlyInjected(b){return isWalletInfoInjectable(b)&&b.injected}function isWalletInfoCurrentlyEmbedded(b){return isWalletInfoCurrentlyInjected(b)&&b.embedded}function isWalletInfoInjectable(b){return"jsBridgeKey"in b}function isWalletInfoRemote(b){return"bridgeUrl"in b}const FALLBACK_WALLETS_LIST=[{app_name:"telegram-wallet",name:"Wallet",image:"https://wallet.tg/images/logo-288.png",about_url:"https://wallet.tg/",universal_url:"https://t.me/wallet?attach=wallet",bridge:[{type:"sse",url:"https://bridge.tonapi.io/bridge"}],platforms:["ios","android","macos","windows","linux"]},{app_name:"tonkeeper",name:"Tonkeeper",image:"https://tonkeeper.com/assets/tonconnect-icon.png",tondns:"tonkeeper.ton",about_url:"https://tonkeeper.com",universal_url:"https://app.tonkeeper.com/ton-connect",deepLink:"tonkeeper-tc://",bridge:[{type:"sse",url:"https://bridge.tonapi.io/bridge"},{type:"js",key:"tonkeeper"}],platforms:["ios","android","chrome","firefox","macos"]},{app_name:"openmask",name:"OpenMask",image:"https://raw.githubusercontent.com/OpenProduct/openmask-extension/main/public/openmask-logo-288.png",about_url:"https://www.openmask.app/",bridge:[{type:"js",key:"openmask"}],platforms:["chrome"]},{app_name:"mytonwallet",name:"MyTonWallet",image:"https://mytonwallet.io/icon-256.png",about_url:"https://mytonwallet.io",universal_url:"https://connect.mytonwallet.org",bridge:[{type:"js",key:"mytonwallet"},{type:"sse",url:"https://tonconnectbridge.mytonwallet.org/bridge/"}],platforms:["chrome","windows","macos","linux"]},{app_name:"tonhub",name:"Tonhub",image:"https://tonhub.com/tonconnect_logo.png",about_url:"https://tonhub.com",universal_url:"https://tonhub.com/ton-connect",bridge:[{type:"js",key:"tonhub"},{type:"sse",url:"https://connect.tonhubapi.com/tonconnect"}],platforms:["ios","android"]},{app_name:"tonflow",name:"TonFlow",image:"https://tonflow.net/assets/images/tonflow_ico_192.png",about_url:"https://tonflow.net",bridge:[{type:"js",key:"tonflow"}],platforms:["chrome"]},{app_name:"dewallet",name:"DeWallet",image:"https://app.delabwallet.com/logo_black.png",about_url:"https://delabwallet.com",bridge:[{type:"js",key:"dewallet"}],platforms:["chrome"]},{app_name:"xtonwallet",name:"XTONWallet",image:"https://xtonwallet.com/assets/img/icon-256-back.png",about_url:"https://xtonwallet.com",bridge:[{type:"js",key:"xtonwallet"}],platforms:["chrome","firefox"]},{app_name:"tonwallet",name:"TON Wallet",image:"https://wallet.ton.org/assets/ui/qr-logo.png",about_url:"https://chrome.google.com/webstore/detail/ton-wallet/nphplpgoakhhjchkkhmiggakijnkhfnd",bridge:[{type:"js",key:"tonwallet"}],platforms:["chrome"]}];class WalletsListManager{constructor(_){this.walletsListCache=null,this.walletsListCacheCreationTimestamp=null,this.walletsListSource="https://raw.githubusercontent.com/ton-blockchain/wallets-list/main/wallets-v2.json",_!=null&&_.walletsListSource&&(this.walletsListSource=_.walletsListSource),_!=null&&_.cacheTTLMs&&(this.cacheTTLMs=_.cacheTTLMs)}getWallets(){return __awaiter(this,void 0,void 0,function*(){return this.cacheTTLMs&&this.walletsListCacheCreationTimestamp&&Date.now()>this.walletsListCacheCreationTimestamp+this.cacheTTLMs&&(this.walletsListCache=null),this.walletsListCache||(this.walletsListCache=this.fetchWalletsList(),this.walletsListCache.then(()=>{this.walletsListCacheCreationTimestamp=Date.now()}).catch(()=>{this.walletsListCache=null,this.walletsListCacheCreationTimestamp=null})),this.walletsListCache})}getEmbeddedWallet(){return __awaiter(this,void 0,void 0,function*(){const d=(yield this.getWallets()).filter(isWalletInfoCurrentlyEmbedded);return d.length!==1?null:d[0]})}fetchWalletsList(){return __awaiter(this,void 0,void 0,function*(){let _=[];try{if(_=yield(yield fetch(this.walletsListSource)).json(),!Array.isArray(_))throw new FetchWalletsError("Wrong wallets list format, wallets list must be an array.");const j=_.filter($=>!this.isCorrectWalletConfigDTO($));j.length&&(logError$1(`Wallet(s) ${j.map($=>$.name).join(", ")} config format is wrong. They were removed from the wallets list.`),_=_.filter($=>this.isCorrectWalletConfigDTO($)))}catch(k){logError$1(k),_=FALLBACK_WALLETS_LIST}let d=[];try{d=InjectedProvider.getCurrentlyInjectedWallets()}catch(k){logError$1(k)}return this.mergeWalletsLists(this.walletConfigDTOListToWalletConfigList(_),d)})}walletConfigDTOListToWalletConfigList(_){return _.map(d=>{const j={name:d.name,appName:d.app_name,imageUrl:d.image,aboutUrl:d.about_url,tondns:d.tondns,platforms:d.platforms};return d.bridge.forEach($=>{if($.type==="sse"&&(j.bridgeUrl=$.url,j.universalLink=d.universal_url,j.deepLink=d.deepLink),$.type==="js"){const et=$.key;j.jsBridgeKey=et,j.injected=InjectedProvider.isWalletInjected(et),j.embedded=InjectedProvider.isInsideWalletBrowser(et)}}),j})}mergeWalletsLists(_,d){return[...new Set(_.concat(d).map(j=>j.name)).values()].map(j=>{const $=_.find(tt=>tt.name===j),et=d.find(tt=>tt.name===j);return Object.assign(Object.assign({},$&&Object.assign({},$)),et&&Object.assign({},et))})}isCorrectWalletConfigDTO(_){if(!_||typeof _!="object")return!1;const d="name"in _,k="app_name"in _,j="image"in _,$="about_url"in _,et="platforms"in _;if(!d||!j||!$||!et||!k||!_.platforms||!Array.isArray(_.platforms)||!_.platforms.length||!("bridge"in _)||!Array.isArray(_.bridge)||!_.bridge.length)return!1;const tt=_.bridge;if(tt.some(ot=>!ot||typeof ot!="object"||!("type"in ot)))return!1;const rt=tt.find(ot=>ot.type==="sse");if(rt&&(!("url"in rt)||!rt.url||!_.universal_url))return!1;const nt=tt.find(ot=>ot.type==="js");return!(nt&&(!("key"in nt)||!nt.key))}}class WalletNotSupportFeatureError extends TonConnectError{get info(){return"Wallet doesn't support requested feature method."}constructor(..._){super(..._),Object.setPrototypeOf(this,WalletNotSupportFeatureError.prototype)}}function checkSendTransactionSupport(b,_){const d=b.includes("SendTransaction"),k=b.find(j=>j&&typeof j=="object"&&j.name==="SendTransaction");if(!d&&!k)throw new WalletNotSupportFeatureError("Wallet doesn't support SendTransaction feature.");if(k&&k.maxMessages!==void 0){if(k.maxMessages<_.requiredMessagesNumber)throw new WalletNotSupportFeatureError(`Wallet is not able to handle such SendTransaction request. Max support messages number is ${k.maxMessages}, but ${_.requiredMessagesNumber} is required.`);return}logWarning$1("Connected wallet didn't provide information about max allowed messages in the SendTransaction request. Request may be rejected by the wallet.")}class TonConnect{constructor(_){if(this.walletsList=new WalletsListManager,this._wallet=null,this.provider=null,this.statusChangeSubscriptions=[],this.statusChangeErrorSubscriptions=[],this.dappSettings={manifestUrl:(_==null?void 0:_.manifestUrl)||getWebPageManifest(),storage:(_==null?void 0:_.storage)||new DefaultStorage},this.walletsList=new WalletsListManager({walletsListSource:_==null?void 0:_.walletsListSource,cacheTTLMs:_==null?void 0:_.walletsListCacheTTLMs}),!this.dappSettings.manifestUrl)throw new DappMetadataError("Dapp tonconnect-manifest.json must be specified if window.location.origin is undefined. See more https://github.com/ton-connect/docs/blob/main/requests-responses.md#app-manifest");this.bridgeConnectionStorage=new BridgeConnectionStorage(this.dappSettings.storage),_!=null&&_.disableAutoPauseConnection||this.addWindowFocusAndBlurSubscriptions()}static getWallets(){return this.walletsList.getWallets()}get connected(){return this._wallet!==null}get account(){var _;return((_=this._wallet)===null||_===void 0?void 0:_.account)||null}get wallet(){return this._wallet}set wallet(_){this._wallet=_,this.statusChangeSubscriptions.forEach(d=>d(this._wallet))}getWallets(){return this.walletsList.getWallets()}onStatusChange(_,d){return this.statusChangeSubscriptions.push(_),d&&this.statusChangeErrorSubscriptions.push(d),()=>{this.statusChangeSubscriptions=this.statusChangeSubscriptions.filter(k=>k!==_),d&&(this.statusChangeErrorSubscriptions=this.statusChangeErrorSubscriptions.filter(k=>k!==d))}}connect(_,d){var k;if(this.connected)throw new WalletAlreadyConnectedError;return(k=this.provider)===null||k===void 0||k.closeConnection(),this.provider=this.createProvider(_),this.provider.connect(this.createConnectRequest(d))}restoreConnection(){return __awaiter(this,void 0,void 0,function*(){const[_,d]=yield Promise.all([this.bridgeConnectionStorage.storedConnectionType(),this.walletsList.getEmbeddedWallet()]);try{switch(_){case"http":this.provider=yield BridgeProvider.fromStorage(this.dappSettings.storage);break;case"injected":this.provider=yield InjectedProvider.fromStorage(this.dappSettings.storage);break;default:if(d)this.provider=yield this.createProvider(d);else return}}catch{yield this.bridgeConnectionStorage.removeConnection(),this.provider=null;return}return this.provider.listen(this.walletEventsListener.bind(this)),this.provider.restoreConnection()})}sendTransaction(_,d){return __awaiter(this,void 0,void 0,function*(){this.checkConnection(),checkSendTransactionSupport(this.wallet.device.features,{requiredMessagesNumber:_.messages.length});const{validUntil:k}=_,j=__rest(_,["validUntil"]),$=_.from||this.account.address,et=_.network||this.account.chain,tt=yield this.provider.sendRequest(sendTransactionParser.convertToRpcRequest(Object.assign(Object.assign({},j),{valid_until:k,from:$,network:et})),d);return sendTransactionParser.isError(tt)?sendTransactionParser.parseAndThrowError(tt):sendTransactionParser.convertFromRpcResponse(tt)})}disconnect(){return __awaiter(this,void 0,void 0,function*(){if(!this.connected)throw new WalletNotConnectedError;yield this.provider.disconnect(),this.onWalletDisconnected()})}pauseConnection(){var _;((_=this.provider)===null||_===void 0?void 0:_.type)==="http"&&this.provider.pause()}unPauseConnection(){var _;return((_=this.provider)===null||_===void 0?void 0:_.type)!=="http"?Promise.resolve():this.provider.unPause()}addWindowFocusAndBlurSubscriptions(){const _=getDocument();if(_)try{_.addEventListener("visibilitychange",()=>{_.hidden?this.pauseConnection():this.unPauseConnection()})}catch(d){console.error("Cannot subscribe to the document.visibilitychange: ",d)}}createProvider(_){let d;return!Array.isArray(_)&&isWalletConnectionSourceJS(_)?d=new InjectedProvider(this.dappSettings.storage,_.jsBridgeKey):d=new BridgeProvider(this.dappSettings.storage,_),d.listen(this.walletEventsListener.bind(this)),d}walletEventsListener(_){switch(_.event){case"connect":this.onWalletConnected(_.payload);break;case"connect_error":this.onWalletConnectError(_.payload);break;case"disconnect":this.onWalletDisconnected()}}onWalletConnected(_){const d=_.items.find($=>$.name==="ton_addr"),k=_.items.find($=>$.name==="ton_proof");if(!d)throw new TonConnectError("ton_addr connection item was not found");const j={device:_.device,provider:this.provider.type,account:{address:d.address,chain:d.network,walletStateInit:d.walletStateInit,publicKey:d.publicKey}};k&&(j.connectItems={tonProof:k}),this.wallet=j}onWalletConnectError(_){const d=connectErrorsParser.parseError(_);if(this.statusChangeErrorSubscriptions.forEach(k=>k(d)),console.debug(d),d instanceof ManifestNotFoundError||d instanceof ManifestContentErrorError)throw console.error(d),d}onWalletDisconnected(){this.wallet=null}checkConnection(){if(!this.connected)throw new WalletNotConnectedError}createConnectRequest(_){const d=[{name:"ton_addr"}];return _!=null&&_.tonProof&&d.push({name:"ton_proof",payload:_.tonProof}),{manifestUrl:this.dappSettings.manifestUrl,items:d}}}TonConnect.walletsList=new WalletsListManager;TonConnect.isWalletInjected=b=>InjectedProvider.isWalletInjected(b);TonConnect.isInsideWalletBrowser=b=>InjectedProvider.isInsideWalletBrowser(b);const noBounceableTag=81,testOnlyTag=128;function toUserFriendlyAddress(b,_=!1){const{wc:d,hex:k}=parseHexAddress(b);let j=noBounceableTag;_&&(j|=testOnlyTag);const $=new Int8Array(34);$[0]=j,$[1]=d,$.set(k,2);const et=new Uint8Array(36);return et.set($),et.set(crc16($),34),Base64.encode(et).replace(/\+/g,"-").replace(/\//g,"_")}function parseHexAddress(b){if(!b.includes(":"))throw new WrongAddressError(`Wrong address ${b}. Address must include ":".`);const _=b.split(":");if(_.length!==2)throw new WrongAddressError(`Wrong address ${b}. Address must include ":" only once.`);const d=parseInt(_[0]);if(d!==0&&d!==-1)throw new WrongAddressError(`Wrong address ${b}. WC must be eq 0 or -1, but ${d} received.`);const k=_[1];if((k==null?void 0:k.length)!==64)throw new WrongAddressError(`Wrong address ${b}. Hex part must be 64bytes length, but ${k==null?void 0:k.length} received.`);return{wc:d,hex:hexToBytes(k)}}function crc16(b){let d=0;const k=new Uint8Array(b.length+2);k.set(b);for(let j of k){let $=128;for(;$>0;)d<<=1,j&$&&(d+=1),$>>=1,d>65535&&(d&=65535,d^=4129)}return new Uint8Array([Math.floor(d/256),d%256])}const toByteMap={};for(let b=0;b<=255;b++){let _=b.toString(16);_.length<2&&(_="0"+_),toByteMap[_]=b}function hexToBytes(b){b=b.toLowerCase();const _=b.length;if(_%2!==0)throw new ParseHexError("Hex string must have length a multiple of 2: "+b);const d=_/2,k=new Uint8Array(d);for(let j=0;j0?fr.length===2?typeof fr[1]==tt?this[fr[0]]=fr[1].call(this,vr):this[fr[0]]=fr[1]:fr.length===3?typeof fr[1]===tt&&!(fr[1].exec&&fr[1].test)?this[fr[0]]=vr?fr[1].call(this,vr,fr[2]):k:this[fr[0]]=vr?vr.replace(fr[1],fr[2]):k:fr.length===4&&(this[fr[0]]=vr?fr[3].call(this,vr.replace(fr[1],fr[2])):k):this[fr]=vr||k;qt+=2}},Pn=function(pn,Vt){for(var qt in Vt)if(typeof Vt[qt]===nt&&Vt[qt].length>0){for(var wn=0;wn2&&(Zn[it]="iPad",Zn[ut]=lt),Zn},this.getEngine=function(){var Zn={};return Zn[dt]=k,Zn[ft]=k,Rn.call(Zn,wn,lr.engine),Zn},this.getOS=function(){var Zn={};return Zn[dt]=k,Zn[ft]=k,Rn.call(Zn,wn,lr.os),fr&&!Zn[dt]&&Ln&&Ln.platform!="Unknown"&&(Zn[dt]=Ln.platform.replace(/chrome os/i,xn).replace(/macos/i,fn)),Zn},this.getResult=function(){return{ua:this.getUA(),browser:this.getBrowser(),engine:this.getEngine(),os:this.getOS(),device:this.getDevice(),cpu:this.getCPU()}},this.getUA=function(){return wn},this.setUA=function(Zn){return wn=typeof Zn===ot&&Zn.length>Et?Tn(Zn,Et):Zn,this},this.setUA(wn),this};Bn.VERSION=j,Bn.BROWSER=bn([dt,ft,at]),Bn.CPU=bn([st]),Bn.DEVICE=bn([it,ht,ut,ct,pt,wt,lt,vt,yt]),Bn.ENGINE=Bn.OS=bn([dt,ft]),b.exports&&(_=b.exports=Bn),_.UAParser=Bn;var Nn=typeof d!==rt&&(d.jQuery||d.Zepto);if(Nn&&!Nn.ua){var Wn=new Bn;Nn.ua=Wn.getResult(),Nn.ua.get=function(){return Wn.getUA()},Nn.ua.set=function(pn){Wn.setUA(pn);var Vt=Wn.getResult();for(var qt in Vt)Nn.ua[qt]=Vt[qt]}}})(typeof window=="object"?window:commonjsGlobal)})(uaParser,uaParser.exports);var uaParserExports=uaParser.exports;const UAParser=getDefaultExportFromCjs(uaParserExports);var isMergeableObject=function(_){return isNonNullObject(_)&&!isSpecial(_)};function isNonNullObject(b){return!!b&&typeof b=="object"}function isSpecial(b){var _=Object.prototype.toString.call(b);return _==="[object RegExp]"||_==="[object Date]"||isReactElement(b)}var canUseSymbol=typeof Symbol=="function"&&Symbol.for,REACT_ELEMENT_TYPE=canUseSymbol?Symbol.for("react.element"):60103;function isReactElement(b){return b.$$typeof===REACT_ELEMENT_TYPE}function emptyTarget(b){return Array.isArray(b)?[]:{}}function cloneUnlessOtherwiseSpecified(b,_){return _.clone!==!1&&_.isMergeableObject(b)?deepmerge(emptyTarget(b),b,_):b}function defaultArrayMerge(b,_,d){return b.concat(_).map(function(k){return cloneUnlessOtherwiseSpecified(k,d)})}function getMergeFunction(b,_){if(!_.customMerge)return deepmerge;var d=_.customMerge(b);return typeof d=="function"?d:deepmerge}function getEnumerableOwnPropertySymbols(b){return Object.getOwnPropertySymbols?Object.getOwnPropertySymbols(b).filter(function(_){return Object.propertyIsEnumerable.call(b,_)}):[]}function getKeys(b){return Object.keys(b).concat(getEnumerableOwnPropertySymbols(b))}function propertyIsOnObject(b,_){try{return _ in b}catch{return!1}}function propertyIsUnsafe(b,_){return propertyIsOnObject(b,_)&&!(Object.hasOwnProperty.call(b,_)&&Object.propertyIsEnumerable.call(b,_))}function mergeObject(b,_,d){var k={};return d.isMergeableObject(b)&&getKeys(b).forEach(function(j){k[j]=cloneUnlessOtherwiseSpecified(b[j],d)}),getKeys(_).forEach(function(j){propertyIsUnsafe(b,j)||(propertyIsOnObject(b,j)&&d.isMergeableObject(_[j])?k[j]=getMergeFunction(j,d)(b[j],_[j],d):k[j]=cloneUnlessOtherwiseSpecified(_[j],d))}),k}function deepmerge(b,_,d){d=d||{},d.arrayMerge=d.arrayMerge||defaultArrayMerge,d.isMergeableObject=d.isMergeableObject||isMergeableObject,d.cloneUnlessOtherwiseSpecified=cloneUnlessOtherwiseSpecified;var k=Array.isArray(_),j=Array.isArray(b),$=k===j;return $?k?d.arrayMerge(b,_,d):mergeObject(b,_,d):cloneUnlessOtherwiseSpecified(_,d)}deepmerge.all=function(_,d){if(!Array.isArray(_))throw new Error("first argument should be an array");return _.reduce(function(k,j){return deepmerge(k,j,d)},{})};var deepmerge_1=deepmerge,cjs=deepmerge_1;const deepmerge$1=getDefaultExportFromCjs(cjs);var classnames={exports:{}};/*! Copyright (c) 2018 Jed Watson. Licensed under the MIT License (MIT), see http://jedwatson.github.io/classnames @@ -99,7 +99,7 @@ PERFORMANCE OF THIS SOFTWARE. body.${usingMouseClass} ${globalStylesTag} *:focus { outline: none; } -`;return createComponent(b,{})};function hexToRgb(b){b[0]==="#"&&(b=b.slice(1));const _=parseInt(b,16),d=_>>16&255,k=_>>8&255,j=_&255;return[d,k,j].join(",")}function rgba(b,_){return b[0]==="#"&&(b=hexToRgb(b)),`rgba(${b}, ${_})`}function toPx(b){return b.toString()+"px"}const _InMemoryStorage=class{constructor(){__publicField(this,"storage",{})}static getInstance(){return _InMemoryStorage.instance||(_InMemoryStorage.instance=new _InMemoryStorage),_InMemoryStorage.instance}get length(){return Object.keys(this.storage).length}clear(){this.storage={}}getItem(b){var _;return(_=this.storage[b])!=null?_:null}key(b){var _;const d=Object.keys(this.storage);return b<0||b>=d.length?null:(_=d[b])!=null?_:null}removeItem(b){delete this.storage[b]}setItem(b,_){this.storage[b]=_}};let InMemoryStorage=_InMemoryStorage;__publicField(InMemoryStorage,"instance");class TonConnectUIError extends TonConnectError{constructor(..._){super(..._),Object.setPrototypeOf(this,TonConnectUIError.prototype)}}function openLink(b,_="_self"){window.open(b,_,"noopener noreferrer")}function openLinkBlank(b){openLink(b,"_blank")}function openDeeplinkWithFallback(b,_){const d=()=>{isBrowser("safari")||_()},k=setTimeout(()=>d(),1e3);window.addEventListener("blur",()=>clearTimeout(k),{once:!0}),openLink(b,"_self")}function getSystemTheme(){return window.matchMedia&&window.matchMedia("(prefers-color-scheme: light)").matches?THEME.LIGHT:THEME.DARK}function subscribeToThemeChange(b){const _=d=>b(d.matches?THEME.DARK:THEME.LIGHT);return window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change",_),()=>window.matchMedia("(prefers-color-scheme: dark)").removeEventListener("change",_)}function disableScroll(){document.documentElement.scrollHeight!==document.documentElement.clientHeight&&(document.body.style.top=toPx(-document.documentElement.scrollTop),document.body.classList.add(disableScrollClass))}function enableScroll(){document.body.classList.remove(disableScrollClass),document.documentElement.scrollTo({top:-parseFloat(getComputedStyle(document.body).top)}),document.body.style.top="auto"}function fixMobileSafariActiveTransition(){document.body.hasAttribute("ontouchstart")||document.body.setAttribute("ontouchstart","")}function defineStylesRoot(){customElements.define(globalStylesTag,class extends HTMLElement{})}function createMacrotask(b){return __async(this,null,function*(){yield new Promise(_=>requestAnimationFrame(_)),b()})}function preloadImages(b){document.readyState!=="complete"?window.addEventListener("load",()=>createMacrotask(()=>preloadImages(b)),{once:!0}):b.forEach(_=>{const d=new window.Image;d.src=_})}function getWindow$1(){if(typeof window<"u")return window}function tryGetLocalStorage(){if(isLocalStorageAvailable())return localStorage;if(isNodeJs())throw new TonConnectUIError("`localStorage` is unavailable, but it is required for TonConnect. For more details, see https://github.com/ton-connect/sdk/tree/main/packages/sdk#init-connector");return InMemoryStorage.getInstance()}function isLocalStorageAvailable(){try{return typeof localStorage<"u"}catch{return!1}}function isNodeJs(){return typeof process<"u"&&process.versions!=null&&process.versions.node!=null}function getUserAgent(){var b,_;const d=new UAParser().getResult(),k=(b=d.os.name)==null?void 0:b.toLowerCase();let j;switch(!0){case k==="ios":j="ios";break;case k==="android":j="android";break;case k==="mac os":j="macos";break;case k==="linux":j="linux";break;case(k==null?void 0:k.includes("windows")):j="windows";break}const $=(_=d.browser.name)==null?void 0:_.toLowerCase();let et;switch(!0){case $==="chrome":et="chrome";break;case $==="firefox":et="firefox";break;case($==null?void 0:$.includes("safari")):et="safari";break}return{os:j,browser:et}}function isOS(...b){return b.includes(getUserAgent().os)}function isBrowser(...b){return b.includes(getUserAgent().browser)}class WalletInfoStorage{constructor(){__publicField(this,"localStorage"),__publicField(this,"storageKey","ton-connect-ui_wallet-info"),this.localStorage=tryGetLocalStorage()}setWalletInfo(_){this.localStorage.setItem(this.storageKey,JSON.stringify(_))}getWalletInfo(){const _=this.localStorage.getItem(this.storageKey);return _?JSON.parse(_):null}removeWalletInfo(){this.localStorage.removeItem(this.storageKey)}}class PreferredWalletStorage{constructor(){__publicField(this,"localStorage"),__publicField(this,"storageKey","ton-connect-ui_preferred-wallet"),this.localStorage=tryGetLocalStorage()}setPreferredWalletAppName(_){this.localStorage.setItem(this.storageKey,_)}getPreferredWalletAppName(){return this.localStorage.getItem(this.storageKey)||void 0}}class LastSelectedWalletInfoStorage{constructor(){__publicField(this,"localStorage"),__publicField(this,"storageKey","ton-connect-ui_last-selected-wallet-info"),this.localStorage=tryGetLocalStorage()}setLastSelectedWalletInfo(_){this.localStorage.setItem(this.storageKey,JSON.stringify(_))}getLastSelectedWalletInfo(){const _=this.localStorage.getItem(this.storageKey);return _?JSON.parse(_):null}removeLastSelectedWalletInfo(){this.localStorage.removeItem(this.storageKey)}}const[walletsModalState,setWalletsModalState]=createSignal({status:"closed",closeReason:null}),getWalletsModalIsOpened=createMemo(()=>walletsModalState().status==="opened");let lastSelectedWalletInfoStorage=typeof window<"u"?new LastSelectedWalletInfoStorage:void 0;const[lastSelectedWalletInfo,_setLastSelectedWalletInfo]=createSignal((lastSelectedWalletInfoStorage==null?void 0:lastSelectedWalletInfoStorage.getLastSelectedWalletInfo())||null),setLastSelectedWalletInfo=b=>{lastSelectedWalletInfoStorage||(lastSelectedWalletInfoStorage=new LastSelectedWalletInfoStorage),b?lastSelectedWalletInfoStorage.setLastSelectedWalletInfo(b):lastSelectedWalletInfoStorage.removeLastSelectedWalletInfo(),_setLastSelectedWalletInfo(b)},[action,setAction]=createSignal(null),common$1={close:"Close",openWallet:"Open wallet",copyLink:"Copy Link",linkCopied:"Link Copied",copied:"Copied",yourWallet:"Your Wallet",retry:"Retry",get:"GET",mobile:"Mobile",browserExtension:"Browser Extension",desktop:"Desktop"},button$1={connectWallet:"Connect Wallet",dropdown:{copy:"Copy address",copied:"Address copied!",disconnect:"Disconnect"}},notifications$1={confirm:{header:"Open {{ name }} to confirm the transaction."},transactionSent:{header:"Transaction sent",text:"Your transaction will be processed in a few seconds."},transactionCanceled:{header:"Transaction canceled",text:"There will be no changes to your account."}},walletItem$1={walletOn:"Wallet On",recent:"Recent",installed:"Installed",popular:"Popular"},walletModal$1={loading:"Loading wallets",wallets:"Wallets",mobileUniversalModal:{connectYourWallet:"Connect your wallet",openWalletOnTelegramOrSelect:"Open Wallet in Telegram or select your wallet to connect",openWalletOnTelegram:"Open Wallet in Telegram",openLink:"Open Link",scan:"Scan with your mobile wallet"},desktopUniversalModal:{connectYourWallet:"Connect your wallet",scan:"Scan with your mobile wallet",availableWallets:"Available wallets"},mobileConnectionModal:{showQR:"Show QR Code",scanQR:"Scan the QR code below with your phone’s or {{ name }}’s camera",continueIn:"Continue in {{ name }}…",connectionDeclined:"Connection declined"},desktopConnectionModal:{scanQR:"Scan the QR code below with your phone’s or {{ name }}’s camera",continueInExtension:"Continue in {{ name }} browser extension…",dontHaveExtension:"Seems you don't have installed {{ name }} browser extension",getWallet:"Get {{ name }}",continueOnDesktop:"Continue in {{ name }} on desktop…",openWalletOnTelegram:"Open Wallet in Telegram on desktop",connectionDeclined:"Connection declined"},infoModal:{whatIsAWallet:"What is a wallet",secureDigitalAssets:"Secure digital assets storage",walletProtects:"A wallet protects and manages your digital assets including TON, tokens and collectables.",controlIdentity:"Control your Web3 identity",manageIdentity:"Manage your digital identity and access decentralized applications with ease. Maintain control over your data and engage securely in the blockchain ecosystem.",effortlessCryptoTransactions:"Effortless crypto transactions",easilySend:"Easily send, receive, monitor your cryptocurrencies. Streamline your operations with decentralized applications.",getAWallet:"Get a Wallet"}},actionModal$1={confirmTransaction:{header:"Confirm the transaction in {{ name }}",text:"It will only take a moment."},transactionSent:"$notifications.transactionSent",transactionCanceled:"$notifications.transactionCanceled"},en={common:common$1,button:button$1,notifications:notifications$1,walletItem:walletItem$1,walletModal:walletModal$1,actionModal:actionModal$1},common={close:"Закрыть",openWallet:"Открыть кошелёк",copyLink:"Копировать ссылку",linkCopied:"Ссылка скопирована",copied:"Ссылка скопирована",yourWallet:"Ваш кошелёк",retry:"Повторить",get:"Скачать",mobile:"Мобильный",browserExtension:"Расширение",desktop:"Десктоп"},button={connectWallet:"Подключить кошелёк",dropdown:{copy:"Скопировать адрес",copied:"Адрес скопирован!",disconnect:"Отключить кошелёк"}},notifications={confirm:{header:"Откройте {{ name }}, чтобы подтвердить транзакцию."},transactionSent:{header:"Транзакция отправлена",text:"Ваша транзакция будет обработана через несколько секунд."},transactionCanceled:{header:"Транзакция отменена",text:"Состояние вашего счёта не изменится."}},walletItem={walletOn:"Wallet в",recent:"Недавний",installed:"Установлен",popular:"Популярен"},walletModal={loading:"Кошельки загружаются",wallets:"Кошельки",mobileUniversalModal:{connectYourWallet:"Подключите кошелёк",openWalletOnTelegramOrSelect:"Подключите Wallet в Telegram или выберете кошелёк для подключения",openWalletOnTelegram:"Открыть Wallet в Telegram",openLink:"Открыть ссылку",scan:"Отсканируйте камерой вашего телефона"},desktopUniversalModal:{connectYourWallet:"Подключите кошелёк",scan:"Отсканируйте QR-код камерой вашего телефона",availableWallets:"Доступные кошельки"},mobileConnectionModal:{showQR:"Показать QR-код",scanQR:"Отсканируйте QR-код ниже камерой в приложении {{ name }}, или камерой телефона",continueIn:"Продолжите в {{ name }}…",connectionDeclined:"Подключение отклонено"},desktopConnectionModal:{scanQR:"Отсканируйте QR-код ниже камерой в приложении {{ name }}, или камерой телефона",continueInExtension:"Откройте браузерное расширение {{ name }}",dontHaveExtension:"Похоже, у вас не установлено браузерное расширение {{ name }}",getWallet:"Скачать {{ name }}",continueOnDesktop:"Откройте {{ name }} на компьютере…",openWalletOnTelegram:"Открыть Wallet в Telegram",connectionDeclined:"Подключение отклонено"},infoModal:{whatIsAWallet:"Что такое кошелёк?",secureDigitalAssets:"Надежное хранилище цифровых активов",walletProtects:"Кошелёк защищает ваши цифровые активы, включая TON, токены и предметы коллекционирования, и управляет ими.",controlIdentity:"Контроль своей личности Web3",manageIdentity:"Управляйте своей цифровой идентификацией и с легкостью получайте доступ к децентрализованным приложениям. Сохраняйте контроль над своими данными и безопасно участвуйте в экосистеме блокчейна.",effortlessCryptoTransactions:"Простые криптотранзакции",easilySend:"Легко отправляйте, получайте и отслеживайте свои криптовалюты. Оптимизируйте свои операции с помощью децентрализованных приложений.",getAWallet:"Скачать кошелёк"}},actionModal={confirmTransaction:{header:"Подтвердите действие в {{ name }}",text:"Это займет пару секунд."},transactionSent:"$notifications.transactionSent",transactionCanceled:"$notifications.transactionCanceled"},ru={common,button,notifications,walletItem,walletModal,actionModal},i18nDictionary={en:parseDictionary(en),ru:parseDictionary(ru)};function parseDictionary(b){const _="$",d=k=>{Object.entries(k).forEach(([j,$])=>{if(typeof $=="object"&&$)return d($);if(typeof $=="string"){if($[0]===_){const et=$.slice(1).split(".");let tt=b;et.forEach(rt=>{if(rt in tt)tt=tt[rt];else throw new Error(`Cannot parse translations: there is no property ${rt} in translation`)}),k[j]=tt}$.slice(0,2)===`\\${_}`&&(k[j]=$.slice(1))}})};return d(b),b}const ConnectorContext=createContext(),$RAW=Symbol("store-raw"),$NODE=Symbol("store-node"),$NAME=Symbol("store-name");function wrap$1(b,_){let d=b[$PROXY];if(!d&&(Object.defineProperty(b,$PROXY,{value:d=new Proxy(b,proxyTraps$1)}),!Array.isArray(b))){const k=Object.keys(b),j=Object.getOwnPropertyDescriptors(b);for(let $=0,et=k.length;$b[$PROXY][_]),d}function trackSelf(b){if(getListener()){const _=getDataNodes(b);(_._||(_._=createDataNode()))()}}function ownKeys(b){return trackSelf(b),Reflect.ownKeys(b)}function createDataNode(b){const[_,d]=createSignal(b,{equals:!1,internal:!0});return _.$=d,_}const proxyTraps$1={get(b,_,d){if(_===$RAW)return b;if(_===$PROXY)return d;if(_===$TRACK)return trackSelf(b),d;const k=getDataNodes(b),j=k.hasOwnProperty(_);let $=j?k[_]():b[_];if(_===$NODE||_==="__proto__")return $;if(!j){const et=Object.getOwnPropertyDescriptor(b,_);getListener()&&(typeof $!="function"||b.hasOwnProperty(_))&&!(et&&et.get)&&($=getDataNode(k,_,$)())}return isWrappable($)?wrap$1($):$},has(b,_){return _===$RAW||_===$PROXY||_===$TRACK||_===$NODE||_==="__proto__"?!0:(this.get(b,_,b),_ in b)},set(){return!0},deleteProperty(){return!0},ownKeys,getOwnPropertyDescriptor:proxyDescriptor$1};function setProperty(b,_,d,k=!1){if(!k&&b[_]===d)return;const j=b[_],$=b.length;d===void 0?delete b[_]:b[_]=d;let et=getDataNodes(b),tt;(tt=getDataNode(et,_,j))&&tt.$(()=>d),Array.isArray(b)&&b.length!==$&&(tt=getDataNode(et,"length",$))&&tt.$(b.length),(tt=et._)&&tt.$()}function mergeStoreNode(b,_){const d=Object.keys(_);for(let k=0;k1){k=_.shift();const et=typeof k,tt=Array.isArray(b);if(Array.isArray(k)){for(let rt=0;rt1){updatePath(b[k],_,[k].concat(d));return}j=b[k],d=[k].concat(d)}let $=_[0];typeof $=="function"&&($=$(j,d),$===j)||k===void 0&&$==null||($=unwrap($),k===void 0||isWrappable(j)&&isWrappable($)&&!Array.isArray($)?mergeStoreNode(j,$):setProperty(b,k,$))}function createStore(...[b,_]){const d=unwrap(b||{}),k=Array.isArray(d),j=wrap$1(d);function $(...et){batch(()=>{k&&et.length===1?updateArray(d,et[0]):updatePath(d,et)})}return[j,$]}const defaultLightColorsSet={constant:{black:"#000000",white:"#FFFFFF"},connectButton:{background:"#0098EA",foreground:"#FFFFFF"},accent:"#0098EA",telegramButton:"#0098EA",icon:{primary:"#0F0F0F",secondary:"#7A8999",tertiary:"#C1CAD2",success:"#29CC6A",error:"#F5A73B"},background:{primary:"#FFFFFF",secondary:"#F1F3F5",segment:"#FFFFFF",tint:"#F1F3F5",qr:"#F1F3F5"},text:{primary:"#0F0F0F",secondary:"#6A7785"}},defaultDarkColorsSet={constant:{black:"#000000",white:"#FFFFFF"},connectButton:{background:"#0098EA",foreground:"#FFFFFF"},accent:"#E5E5EA",telegramButton:"#31A6F5",icon:{primary:"#E5E5EA",secondary:"#909099",tertiary:"#434347",success:"#29CC6A",error:"#F5A73B"},background:{primary:"#121214",secondary:"#18181A",segment:"#262629",tint:"#222224",qr:"#FFFFFF"},text:{primary:"#E5E5EA",secondary:"#7D7D85"}};/*! +`;return createComponent(b,{})};function hexToRgb(b){b[0]==="#"&&(b=b.slice(1));const _=parseInt(b,16),d=_>>16&255,k=_>>8&255,j=_&255;return[d,k,j].join(",")}function rgba(b,_){return b[0]==="#"&&(b=hexToRgb(b)),`rgba(${b}, ${_})`}function toPx(b){return b.toString()+"px"}const _InMemoryStorage=class{constructor(){__publicField(this,"storage",{})}static getInstance(){return _InMemoryStorage.instance||(_InMemoryStorage.instance=new _InMemoryStorage),_InMemoryStorage.instance}get length(){return Object.keys(this.storage).length}clear(){this.storage={}}getItem(b){var _;return(_=this.storage[b])!=null?_:null}key(b){var _;const d=Object.keys(this.storage);return b<0||b>=d.length?null:(_=d[b])!=null?_:null}removeItem(b){delete this.storage[b]}setItem(b,_){this.storage[b]=_}};let InMemoryStorage=_InMemoryStorage;__publicField(InMemoryStorage,"instance");class TonConnectUIError extends TonConnectError{constructor(..._){super(..._),Object.setPrototypeOf(this,TonConnectUIError.prototype)}}function openLink(b,_="_self"){window.open(b,_,"noopener noreferrer")}function openLinkBlank(b){openLink(b,"_blank")}function openDeeplinkWithFallback(b,_){const d=()=>{isBrowser("safari")||_()},k=setTimeout(()=>d(),200);window.addEventListener("blur",()=>clearTimeout(k),{once:!0}),openLink(b,"_self")}function getSystemTheme(){return window.matchMedia&&window.matchMedia("(prefers-color-scheme: light)").matches?THEME.LIGHT:THEME.DARK}function subscribeToThemeChange(b){const _=d=>b(d.matches?THEME.DARK:THEME.LIGHT);return window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change",_),()=>window.matchMedia("(prefers-color-scheme: dark)").removeEventListener("change",_)}function disableScroll(){document.documentElement.scrollHeight!==document.documentElement.clientHeight&&(document.body.style.top=toPx(-document.documentElement.scrollTop),document.body.classList.add(disableScrollClass))}function enableScroll(){document.body.classList.remove(disableScrollClass),document.documentElement.scrollTo({top:-parseFloat(getComputedStyle(document.body).top)}),document.body.style.top="auto"}function fixMobileSafariActiveTransition(){document.body.hasAttribute("ontouchstart")||document.body.setAttribute("ontouchstart","")}function defineStylesRoot(){customElements.define(globalStylesTag,class extends HTMLElement{})}function createMacrotask(b){return __async(this,null,function*(){yield new Promise(_=>requestAnimationFrame(_)),b()})}function preloadImages(b){document.readyState!=="complete"?window.addEventListener("load",()=>createMacrotask(()=>preloadImages(b)),{once:!0}):b.forEach(_=>{const d=new window.Image;d.src=_})}function getWindow$1(){if(typeof window<"u")return window}function tryGetLocalStorage(){if(isLocalStorageAvailable())return localStorage;if(isNodeJs())throw new TonConnectUIError("`localStorage` is unavailable, but it is required for TonConnect. For more details, see https://github.com/ton-connect/sdk/tree/main/packages/sdk#init-connector");return InMemoryStorage.getInstance()}function isLocalStorageAvailable(){try{return typeof localStorage<"u"}catch{return!1}}function isNodeJs(){return typeof process<"u"&&process.versions!=null&&process.versions.node!=null}function getUserAgent(){var b,_;const d=new UAParser().getResult(),k=(b=d.os.name)==null?void 0:b.toLowerCase();let j;switch(!0){case k==="ios":j="ios";break;case k==="android":j="android";break;case k==="mac os":j="macos";break;case k==="linux":j="linux";break;case(k==null?void 0:k.includes("windows")):j="windows";break}const $=(_=d.browser.name)==null?void 0:_.toLowerCase();let et;switch(!0){case $==="chrome":et="chrome";break;case $==="firefox":et="firefox";break;case($==null?void 0:$.includes("safari")):et="safari";break}return{os:j,browser:et}}function isOS(...b){return b.includes(getUserAgent().os)}function isBrowser(...b){return b.includes(getUserAgent().browser)}function toDeeplink(b,_){const d=new URL(b);return _+d.search}class WalletInfoStorage{constructor(){__publicField(this,"localStorage"),__publicField(this,"storageKey","ton-connect-ui_wallet-info"),this.localStorage=tryGetLocalStorage()}setWalletInfo(_){this.localStorage.setItem(this.storageKey,JSON.stringify(_))}getWalletInfo(){const _=this.localStorage.getItem(this.storageKey);return _?JSON.parse(_):null}removeWalletInfo(){this.localStorage.removeItem(this.storageKey)}}class PreferredWalletStorage{constructor(){__publicField(this,"localStorage"),__publicField(this,"storageKey","ton-connect-ui_preferred-wallet"),this.localStorage=tryGetLocalStorage()}setPreferredWalletAppName(_){this.localStorage.setItem(this.storageKey,_)}getPreferredWalletAppName(){return this.localStorage.getItem(this.storageKey)||void 0}}class LastSelectedWalletInfoStorage{constructor(){__publicField(this,"localStorage"),__publicField(this,"storageKey","ton-connect-ui_last-selected-wallet-info"),this.localStorage=tryGetLocalStorage()}setLastSelectedWalletInfo(_){this.localStorage.setItem(this.storageKey,JSON.stringify(_))}getLastSelectedWalletInfo(){const _=this.localStorage.getItem(this.storageKey);return _?JSON.parse(_):null}removeLastSelectedWalletInfo(){this.localStorage.removeItem(this.storageKey)}}const[walletsModalState,setWalletsModalState]=createSignal({status:"closed",closeReason:null}),getWalletsModalIsOpened=createMemo(()=>walletsModalState().status==="opened");let lastSelectedWalletInfoStorage=typeof window<"u"?new LastSelectedWalletInfoStorage:void 0;const[lastSelectedWalletInfo,_setLastSelectedWalletInfo]=createSignal((lastSelectedWalletInfoStorage==null?void 0:lastSelectedWalletInfoStorage.getLastSelectedWalletInfo())||null),setLastSelectedWalletInfo=b=>{lastSelectedWalletInfoStorage||(lastSelectedWalletInfoStorage=new LastSelectedWalletInfoStorage),b?lastSelectedWalletInfoStorage.setLastSelectedWalletInfo(b):lastSelectedWalletInfoStorage.removeLastSelectedWalletInfo(),_setLastSelectedWalletInfo(b)},[action,setAction]=createSignal(null),common$1={close:"Close",openWallet:"Open wallet",copyLink:"Copy Link",linkCopied:"Link Copied",copied:"Copied",yourWallet:"Your Wallet",retry:"Retry",get:"GET",mobile:"Mobile",browserExtension:"Browser Extension",desktop:"Desktop"},button$1={connectWallet:"Connect Wallet",dropdown:{copy:"Copy address",copied:"Address copied!",disconnect:"Disconnect"}},notifications$1={confirm:{header:"Open {{ name }} to confirm the transaction."},transactionSent:{header:"Transaction sent",text:"Your transaction will be processed in a few seconds."},transactionCanceled:{header:"Transaction canceled",text:"There will be no changes to your account."}},walletItem$1={walletOn:"Wallet On",recent:"Recent",installed:"Installed",popular:"Popular"},walletModal$1={loading:"Loading wallets",wallets:"Wallets",mobileUniversalModal:{connectYourWallet:"Connect your wallet",openWalletOnTelegramOrSelect:"Open Wallet in Telegram or select your wallet to connect",openWalletOnTelegram:"Open Wallet in Telegram",openLink:"Open Link",scan:"Scan with your mobile wallet"},desktopUniversalModal:{connectYourWallet:"Connect your wallet",scan:"Scan with your mobile wallet",availableWallets:"Available wallets"},mobileConnectionModal:{showQR:"Show QR Code",scanQR:"Scan the QR code below with your phone’s or {{ name }}’s camera",continueIn:"Continue in {{ name }}…",connectionDeclined:"Connection declined"},desktopConnectionModal:{scanQR:"Scan the QR code below with your phone’s or {{ name }}’s camera",continueInExtension:"Continue in {{ name }} browser extension…",dontHaveExtension:"Seems you don't have installed {{ name }} browser extension",getWallet:"Get {{ name }}",continueOnDesktop:"Continue in {{ name }} on desktop…",openWalletOnTelegram:"Open Wallet in Telegram on desktop",connectionDeclined:"Connection declined"},infoModal:{whatIsAWallet:"What is a wallet",secureDigitalAssets:"Secure digital assets storage",walletProtects:"A wallet protects and manages your digital assets including TON, tokens and collectables.",controlIdentity:"Control your Web3 identity",manageIdentity:"Manage your digital identity and access decentralized applications with ease. Maintain control over your data and engage securely in the blockchain ecosystem.",effortlessCryptoTransactions:"Effortless crypto transactions",easilySend:"Easily send, receive, monitor your cryptocurrencies. Streamline your operations with decentralized applications.",getAWallet:"Get a Wallet"}},actionModal$1={confirmTransaction:{header:"Confirm the transaction in {{ name }}",text:"It will only take a moment."},transactionSent:"$notifications.transactionSent",transactionCanceled:"$notifications.transactionCanceled"},en={common:common$1,button:button$1,notifications:notifications$1,walletItem:walletItem$1,walletModal:walletModal$1,actionModal:actionModal$1},common={close:"Закрыть",openWallet:"Открыть кошелёк",copyLink:"Копировать ссылку",linkCopied:"Ссылка скопирована",copied:"Ссылка скопирована",yourWallet:"Ваш кошелёк",retry:"Повторить",get:"Скачать",mobile:"Мобильный",browserExtension:"Расширение",desktop:"Десктоп"},button={connectWallet:"Подключить кошелёк",dropdown:{copy:"Скопировать адрес",copied:"Адрес скопирован!",disconnect:"Отключить кошелёк"}},notifications={confirm:{header:"Откройте {{ name }}, чтобы подтвердить транзакцию."},transactionSent:{header:"Транзакция отправлена",text:"Ваша транзакция будет обработана через несколько секунд."},transactionCanceled:{header:"Транзакция отменена",text:"Состояние вашего счёта не изменится."}},walletItem={walletOn:"Wallet в",recent:"Недавний",installed:"Установлен",popular:"Популярен"},walletModal={loading:"Кошельки загружаются",wallets:"Кошельки",mobileUniversalModal:{connectYourWallet:"Подключите кошелёк",openWalletOnTelegramOrSelect:"Подключите Wallet в Telegram или выберете кошелёк для подключения",openWalletOnTelegram:"Открыть Wallet в Telegram",openLink:"Открыть ссылку",scan:"Отсканируйте камерой вашего телефона"},desktopUniversalModal:{connectYourWallet:"Подключите кошелёк",scan:"Отсканируйте QR-код камерой вашего телефона",availableWallets:"Доступные кошельки"},mobileConnectionModal:{showQR:"Показать QR-код",scanQR:"Отсканируйте QR-код ниже камерой в приложении {{ name }}, или камерой телефона",continueIn:"Продолжите в {{ name }}…",connectionDeclined:"Подключение отклонено"},desktopConnectionModal:{scanQR:"Отсканируйте QR-код ниже камерой в приложении {{ name }}, или камерой телефона",continueInExtension:"Откройте браузерное расширение {{ name }}",dontHaveExtension:"Похоже, у вас не установлено браузерное расширение {{ name }}",getWallet:"Скачать {{ name }}",continueOnDesktop:"Откройте {{ name }} на компьютере…",openWalletOnTelegram:"Открыть Wallet в Telegram",connectionDeclined:"Подключение отклонено"},infoModal:{whatIsAWallet:"Что такое кошелёк?",secureDigitalAssets:"Надежное хранилище цифровых активов",walletProtects:"Кошелёк защищает ваши цифровые активы, включая TON, токены и предметы коллекционирования, и управляет ими.",controlIdentity:"Контроль своей личности Web3",manageIdentity:"Управляйте своей цифровой идентификацией и с легкостью получайте доступ к децентрализованным приложениям. Сохраняйте контроль над своими данными и безопасно участвуйте в экосистеме блокчейна.",effortlessCryptoTransactions:"Простые криптотранзакции",easilySend:"Легко отправляйте, получайте и отслеживайте свои криптовалюты. Оптимизируйте свои операции с помощью децентрализованных приложений.",getAWallet:"Скачать кошелёк"}},actionModal={confirmTransaction:{header:"Подтвердите действие в {{ name }}",text:"Это займет пару секунд."},transactionSent:"$notifications.transactionSent",transactionCanceled:"$notifications.transactionCanceled"},ru={common,button,notifications,walletItem,walletModal,actionModal},i18nDictionary={en:parseDictionary(en),ru:parseDictionary(ru)};function parseDictionary(b){const _="$",d=k=>{Object.entries(k).forEach(([j,$])=>{if(typeof $=="object"&&$)return d($);if(typeof $=="string"){if($[0]===_){const et=$.slice(1).split(".");let tt=b;et.forEach(rt=>{if(rt in tt)tt=tt[rt];else throw new Error(`Cannot parse translations: there is no property ${rt} in translation`)}),k[j]=tt}$.slice(0,2)===`\\${_}`&&(k[j]=$.slice(1))}})};return d(b),b}const ConnectorContext=createContext(),$RAW=Symbol("store-raw"),$NODE=Symbol("store-node"),$NAME=Symbol("store-name");function wrap$1(b,_){let d=b[$PROXY];if(!d&&(Object.defineProperty(b,$PROXY,{value:d=new Proxy(b,proxyTraps$1)}),!Array.isArray(b))){const k=Object.keys(b),j=Object.getOwnPropertyDescriptors(b);for(let $=0,et=k.length;$b[$PROXY][_]),d}function trackSelf(b){if(getListener()){const _=getDataNodes(b);(_._||(_._=createDataNode()))()}}function ownKeys(b){return trackSelf(b),Reflect.ownKeys(b)}function createDataNode(b){const[_,d]=createSignal(b,{equals:!1,internal:!0});return _.$=d,_}const proxyTraps$1={get(b,_,d){if(_===$RAW)return b;if(_===$PROXY)return d;if(_===$TRACK)return trackSelf(b),d;const k=getDataNodes(b),j=k.hasOwnProperty(_);let $=j?k[_]():b[_];if(_===$NODE||_==="__proto__")return $;if(!j){const et=Object.getOwnPropertyDescriptor(b,_);getListener()&&(typeof $!="function"||b.hasOwnProperty(_))&&!(et&&et.get)&&($=getDataNode(k,_,$)())}return isWrappable($)?wrap$1($):$},has(b,_){return _===$RAW||_===$PROXY||_===$TRACK||_===$NODE||_==="__proto__"?!0:(this.get(b,_,b),_ in b)},set(){return!0},deleteProperty(){return!0},ownKeys,getOwnPropertyDescriptor:proxyDescriptor$1};function setProperty(b,_,d,k=!1){if(!k&&b[_]===d)return;const j=b[_],$=b.length;d===void 0?delete b[_]:b[_]=d;let et=getDataNodes(b),tt;(tt=getDataNode(et,_,j))&&tt.$(()=>d),Array.isArray(b)&&b.length!==$&&(tt=getDataNode(et,"length",$))&&tt.$(b.length),(tt=et._)&&tt.$()}function mergeStoreNode(b,_){const d=Object.keys(_);for(let k=0;k1){k=_.shift();const et=typeof k,tt=Array.isArray(b);if(Array.isArray(k)){for(let rt=0;rt1){updatePath(b[k],_,[k].concat(d));return}j=b[k],d=[k].concat(d)}let $=_[0];typeof $=="function"&&($=$(j,d),$===j)||k===void 0&&$==null||($=unwrap($),k===void 0||isWrappable(j)&&isWrappable($)&&!Array.isArray($)?mergeStoreNode(j,$):setProperty(b,k,$))}function createStore(...[b,_]){const d=unwrap(b||{}),k=Array.isArray(d),j=wrap$1(d);function $(...et){batch(()=>{k&&et.length===1?updateArray(d,et[0]):updatePath(d,et)})}return[j,$]}const defaultLightColorsSet={constant:{black:"#000000",white:"#FFFFFF"},connectButton:{background:"#0098EA",foreground:"#FFFFFF"},accent:"#0098EA",telegramButton:"#0098EA",icon:{primary:"#0F0F0F",secondary:"#7A8999",tertiary:"#C1CAD2",success:"#29CC6A",error:"#F5A73B"},background:{primary:"#FFFFFF",secondary:"#F1F3F5",segment:"#FFFFFF",tint:"#F1F3F5",qr:"#F1F3F5"},text:{primary:"#0F0F0F",secondary:"#6A7785"}},defaultDarkColorsSet={constant:{black:"#000000",white:"#FFFFFF"},connectButton:{background:"#0098EA",foreground:"#FFFFFF"},accent:"#E5E5EA",telegramButton:"#31A6F5",icon:{primary:"#E5E5EA",secondary:"#909099",tertiary:"#434347",success:"#29CC6A",error:"#F5A73B"},background:{primary:"#121214",secondary:"#18181A",segment:"#262629",tint:"#222224",qr:"#FFFFFF"},text:{primary:"#E5E5EA",secondary:"#7D7D85"}};/*! * is-plain-object * * Copyright (c) 2014-2017, Jon Schlinkert. @@ -801,7 +801,7 @@ PERFORMANCE OF THIS SOFTWARE. width: 32px; height: 32px; border-radius: ${b=>tgIconBorders[b.theme.borderRadius]}; -`,Translation=b=>{const[_]=useI18n();return createMemo(()=>{var d;return _(b.translationKey,b.translationValues,(d=b.children)==null?void 0:d.toString())})};function addReturnStrategy(b,_){let d;typeof _=="string"?d=_:d=isInTMA()?_.twaReturnUrl||_.returnStrategy:"none";const k=addQueryParameter(b,"ret",d);if(!isTelegramUrl(b))return k;const j=k.slice(k.lastIndexOf("&")+1);return k.slice(0,k.lastIndexOf("&"))+"-"+encodeTelegramUrlParameters(j)}function redirectToTelegram(b,_){_=__spreadValues$1({},_);const d=convertToDirectLink(b),k=new URL(d);if(k.searchParams.has("startapp")||k.searchParams.append("startapp","tonconnect"),isInTMA())isTmaPlatform("ios","android")?(_.returnStrategy="back",_.twaReturnUrl=void 0,sendOpenTelegramLink(addReturnStrategy(k.toString(),_))):isTmaPlatform("macos","tdesktop")||isTmaPlatform("weba")?sendOpenTelegramLink(addReturnStrategy(k.toString(),_)):isTmaPlatform("web")?(_.returnStrategy="back",_.twaReturnUrl=void 0,sendOpenTelegramLink(addReturnStrategy(k.toString(),_))):openLinkBlank(addReturnStrategy(k.toString(),_));else if(isOS("ios","android"))_.returnStrategy="none",openLinkBlank(addReturnStrategy(k.toString(),_.returnStrategy));else if(isOS("macos","windows","linux"))if(_.returnStrategy="none",_.twaReturnUrl=void 0,_.forceRedirect)openLinkBlank(addReturnStrategy(k.toString(),_));else{const j=addReturnStrategy(k.toString(),_),$=convertToDeepLink(j);openDeeplinkWithFallback($,()=>openLinkBlank(j))}else openLinkBlank(addReturnStrategy(k.toString(),_))}function addQueryParameter(b,_,d){const k=new URL(b);return k.searchParams.append(_,d),k.toString()}function convertToDirectLink(b){const _=new URL(b);return _.searchParams.has("attach")&&(_.searchParams.delete("attach"),_.pathname+="/start"),_.toString()}function convertToDeepLink(b){const _=new URL(b),[,d,k]=_.pathname.split("/"),j=_.searchParams.get("startapp");return`tg://resolve?domain=${d}&appname=${k}&startapp=${j}`}const DesktopConnectionModal=b=>{const[_,d]=createSignal("mobile"),[k,j]=createSignal(!1),[$,et]=createSignal(),[tt,rt]=createSignal(!0),nt=useContext(ConnectorContext),ot=nt.onStatusChange(()=>{},()=>{b.wallet.appName!==AT_WALLET_APP_NAME&&j(!0)});onCleanup(ot);const at=()=>{et(nt.connect({universalLink:b.wallet.universalLink,bridgeUrl:b.wallet.bridgeUrl},b.additionalRequest))};createEffect(()=>{untrack(_)!=="extension"&&(supportsMobile(b.wallet)||supportsDesktop(b.wallet))&&at()});const it=()=>{j(!1),_()==="extension"&&at(),d("mobile"),setLastSelectedWalletInfo(__spreadProps(__spreadValues$1({},b.wallet),{openMethod:"qrcode"}))},dt=()=>{j(!1),_()==="extension"&&at(),d("desktop"),setLastSelectedWalletInfo(__spreadProps(__spreadValues$1({},b.wallet),{openMethod:"universal-link"})),openLinkBlank(addReturnStrategy($(),appState.returnStrategy))},ut=()=>{const ft=!tt();rt(!1),setLastSelectedWalletInfo(__spreadProps(__spreadValues$1({},b.wallet),{openMethod:"universal-link"})),redirectToTelegram($(),{returnStrategy:appState.returnStrategy,twaReturnUrl:appState.twaReturnUrl,forceRedirect:ft})},ht=()=>{j(!1),d("extension"),isWalletInfoCurrentlyInjected(b.wallet)&&(setLastSelectedWalletInfo(b.wallet),nt.connect({jsBridgeKey:b.wallet.jsBridgeKey},b.additionalRequest))};return supportsMobile(b.wallet)?it():supportsExtension(b.wallet)?ht():dt(),createComponent(DesktopConnectionModalStyled,{"data-tc-wallets-modal-connection-desktop":"true",get children(){return[createComponent(StyledIconButton$2,{icon:"arrow",onClick:()=>b.onBackClick()}),createComponent(H1Styled$6,{get children(){return b.wallet.name}}),createComponent(Show,{get when(){return _()==="mobile"},get children(){return createComponent(H2Styled$4,{translationKey:"walletModal.desktopConnectionModal.scanQR",get translationValues(){return{name:b.wallet.name}},get children(){return["Scan the QR code below with your phone’s or ",createMemo(()=>b.wallet.name),"’s camera"]}})}}),createComponent(BodyStyled$1,{get qr(){return _()==="mobile"},get children(){return createComponent(Switch,{get children(){return[createComponent(Match,{get when(){return _()==="mobile"},get children(){return createComponent(QRCodeStyled$1,{disableCopy:!1,get sourceUrl(){return addReturnStrategy($(),"none")},get imageUrl(){return b.wallet.imageUrl}})}}),createComponent(Match,{get when(){return k()},get children(){return[createComponent(ErrorIconStyled$1,{size:"s"}),createComponent(BodyTextStyled$1,{translationKey:"walletModal.desktopConnectionModal.connectionDeclined",children:"Connection declined"}),createComponent(ButtonsContainerStyled$1,{get children(){return createComponent(Button,{get leftIcon(){return createComponent(RetryIcon,{})},get onClick(){return _()==="extension"?ht:dt},get children(){return createComponent(Translation,{translationKey:"common.retry",children:"Retry"})}})}})]}}),createComponent(Match,{get when(){return _()==="extension"},get children(){return[createComponent(Show,{get when(){return isWalletInfoCurrentlyInjected(b.wallet)},get children(){return[createComponent(LoaderStyled$1,{size:"s"}),createComponent(BodyTextStyled$1,{translationKey:"walletModal.desktopConnectionModal.continueInExtension",get translationValues(){return{name:b.wallet.name}},get children(){return["Continue in ",createMemo(()=>b.wallet.name)," browser extension…"]}}),createComponent(ButtonsContainerStyled$1,{get children(){return createComponent(Button,{get leftIcon(){return createComponent(RetryIcon,{})},onClick:ht,get children(){return createComponent(Translation,{translationKey:"common.retry",children:"Retry"})}})}})]}}),createComponent(Show,{get when(){return!isWalletInfoCurrentlyInjected(b.wallet)},get children(){return[createComponent(BodyTextStyled$1,{translationKey:"walletModal.desktopConnectionModal.dontHaveExtension",get translationValues(){return{name:b.wallet.name}},get children(){return["Seems you don't have installed ",createMemo(()=>b.wallet.name)," browser extension"]}}),createComponent(ButtonsContainerStyled$1,{get children(){return createComponent(Link,{get href(){return b.wallet.aboutUrl},blank:!0,get children(){return createComponent(Button,{get rightIcon(){return createComponent(LinkIcon,{})},onClick:ht,get children(){return createComponent(Translation,{translationKey:"walletModal.desktopConnectionModal.getWallet",get translationValues(){return{name:b.wallet.name}},get children(){return["Get ",createMemo(()=>b.wallet.name)]}})}})}})}})]}})]}}),createComponent(Match,{get when(){return _()==="desktop"},get children(){return[createComponent(LoaderIcon,{size:"m"}),createComponent(BodyTextStyled$1,{translationKey:"walletModal.desktopConnectionModal.continueOnDesktop",get translationValues(){return{name:b.wallet.name}},get children(){return["Continue in ",createMemo(()=>b.wallet.name)," on desktop…"]}}),createComponent(ButtonsContainerStyled$1,{get children(){return[createComponent(Button,{get leftIcon(){return createComponent(RetryIcon,{})},onClick:dt,get children(){return createComponent(Translation,{translationKey:"common.retry",children:"Retry"})}}),createComponent(Link,{get href(){return b.wallet.aboutUrl},blank:!0,get children(){return createComponent(Button,{get rightIcon(){return createComponent(LinkIcon,{})},get children(){return createComponent(Translation,{translationKey:"walletModal.desktopConnectionModal.getWallet",get translationValues(){return{name:b.wallet.name}},get children(){return["Get ",createMemo(()=>b.wallet.name)]}})}})}})]}})]}})]}})}}),createComponent(Show,{get when(){return b.wallet.appName===AT_WALLET_APP_NAME},get children(){return createComponent(TgButtonStyled,{get rightIcon(){return createComponent(TgImageStyled,{get src(){return IMG.TG}})},scale:"s",onClick:ut,get children(){return createComponent(Translation,{translationKey:"walletModal.desktopConnectionModal.openWalletOnTelegram",children:"Open Wallet in Telegram on desktop"})}})}}),createComponent(Show,{get when(){return b.wallet.appName!==AT_WALLET_APP_NAME},get children(){return createComponent(BottomButtonsContainerStyled,{get children(){return[createComponent(Show,{get when(){return createMemo(()=>_()!=="mobile")()&&supportsMobile(b.wallet)},get children(){return createComponent(FooterButton$1,{appearance:"secondary",get leftIcon(){return createComponent(MobileIcon,{})},onClick:it,get children(){return createComponent(Translation,{translationKey:"common.mobile",children:"Mobile"})}})}}),createComponent(Show,{get when(){return createMemo(()=>_()!=="extension")()&&supportsExtension(b.wallet)},get children(){return createComponent(FooterButton$1,{appearance:"secondary",get leftIcon(){return createComponent(BrowserIcon,{})},onClick:ht,get children(){return createComponent(Translation,{translationKey:"common.browserExtension",children:"Browser Extension"})}})}}),createComponent(Show,{get when(){return createMemo(()=>_()!=="desktop")()&&supportsDesktop(b.wallet)},get children(){return createComponent(FooterButton$1,{appearance:"secondary",get leftIcon(){return createComponent(DesktopIcon,{})},onClick:dt,get children(){return createComponent(Translation,{translationKey:"common.desktop",children:"Desktop"})}})}})]}})}})]}})},InfoModalStyled=styled.div``,StyledIconButton$1=styled(IconButton)` +`,Translation=b=>{const[_]=useI18n();return createMemo(()=>{var d;return _(b.translationKey,b.translationValues,(d=b.children)==null?void 0:d.toString())})};function addReturnStrategy(b,_){let d;typeof _=="string"?d=_:d=isInTMA()?_.twaReturnUrl||_.returnStrategy:"none";const k=addQueryParameter(b,"ret",d);if(!isTelegramUrl(b))return k;const j=k.slice(k.lastIndexOf("&")+1);return k.slice(0,k.lastIndexOf("&"))+"-"+encodeTelegramUrlParameters(j)}function redirectToTelegram(b,_){_=__spreadValues$1({},_);const d=convertToTGDirectLink(b),k=new URL(d);if(k.searchParams.has("startapp")||k.searchParams.append("startapp","tonconnect"),isInTMA())isTmaPlatform("ios","android")?(_.returnStrategy="back",_.twaReturnUrl=void 0,sendOpenTelegramLink(addReturnStrategy(k.toString(),_))):isTmaPlatform("macos","tdesktop")||isTmaPlatform("weba")?sendOpenTelegramLink(addReturnStrategy(k.toString(),_)):isTmaPlatform("web")?(_.returnStrategy="back",_.twaReturnUrl=void 0,sendOpenTelegramLink(addReturnStrategy(k.toString(),_))):openLinkBlank(addReturnStrategy(k.toString(),_));else if(isOS("ios","android"))_.returnStrategy="none",openLinkBlank(addReturnStrategy(k.toString(),_.returnStrategy));else if(isOS("macos","windows","linux"))if(_.returnStrategy="none",_.twaReturnUrl=void 0,_.forceRedirect)openLinkBlank(addReturnStrategy(k.toString(),_));else{const j=addReturnStrategy(k.toString(),_),$=convertToTGDeepLink(j);openDeeplinkWithFallback($,()=>openLinkBlank(j))}else openLinkBlank(addReturnStrategy(k.toString(),_))}function addQueryParameter(b,_,d){const k=new URL(b);return k.searchParams.append(_,d),k.toString()}function convertToTGDirectLink(b){const _=new URL(b);return _.searchParams.has("attach")&&(_.searchParams.delete("attach"),_.pathname+="/start"),_.toString()}function convertToTGDeepLink(b){const _=new URL(b),[,d,k]=_.pathname.split("/"),j=_.searchParams.get("startapp");return`tg://resolve?domain=${d}&appname=${k}&startapp=${j}`}let openDesktopDeeplinkAttempts=0;const DesktopConnectionModal=b=>{const[_,d]=createSignal("mobile"),[k,j]=createSignal(!1),[$,et]=createSignal(),[tt,rt]=createSignal(!0),nt=useContext(ConnectorContext),ot=nt.onStatusChange(()=>{},()=>{b.wallet.appName!==AT_WALLET_APP_NAME&&j(!0)});onCleanup(ot);const at=()=>{et(nt.connect({universalLink:b.wallet.universalLink,bridgeUrl:b.wallet.bridgeUrl},b.additionalRequest))};createEffect(()=>{untrack(_)!=="extension"&&(supportsMobile(b.wallet)||supportsDesktop(b.wallet))&&at()});const it=()=>{j(!1),_()==="extension"&&at(),d("mobile"),setLastSelectedWalletInfo(__spreadProps(__spreadValues$1({},b.wallet),{openMethod:"qrcode"}))},dt=()=>{j(!1),_()==="extension"&&at(),d("desktop");const ft=addReturnStrategy($(),appState.returnStrategy),st=isBrowser("safari")&&openDesktopDeeplinkAttempts>=1;b.wallet.deepLink&&!st?(openDesktopDeeplinkAttempts++,setLastSelectedWalletInfo(__spreadProps(__spreadValues$1({},b.wallet),{openMethod:"custom-deeplink"})),openDeeplinkWithFallback(toDeeplink(ft,b.wallet.deepLink),()=>{setLastSelectedWalletInfo(__spreadProps(__spreadValues$1({},b.wallet),{openMethod:"universal-link"})),openLinkBlank(ft)})):(setLastSelectedWalletInfo(__spreadProps(__spreadValues$1({},b.wallet),{openMethod:"universal-link"})),openLinkBlank(ft))},ut=()=>{const ft=!tt();rt(!1),setLastSelectedWalletInfo(__spreadProps(__spreadValues$1({},b.wallet),{openMethod:"universal-link"})),redirectToTelegram($(),{returnStrategy:appState.returnStrategy,twaReturnUrl:appState.twaReturnUrl,forceRedirect:ft})},ht=()=>{j(!1),d("extension"),isWalletInfoCurrentlyInjected(b.wallet)&&(setLastSelectedWalletInfo(b.wallet),nt.connect({jsBridgeKey:b.wallet.jsBridgeKey},b.additionalRequest))};return supportsMobile(b.wallet)?it():supportsExtension(b.wallet)?ht():dt(),createComponent(DesktopConnectionModalStyled,{"data-tc-wallets-modal-connection-desktop":"true",get children(){return[createComponent(StyledIconButton$2,{icon:"arrow",onClick:()=>b.onBackClick()}),createComponent(H1Styled$6,{get children(){return b.wallet.name}}),createComponent(Show,{get when(){return _()==="mobile"},get children(){return createComponent(H2Styled$4,{translationKey:"walletModal.desktopConnectionModal.scanQR",get translationValues(){return{name:b.wallet.name}},get children(){return["Scan the QR code below with your phone’s or ",createMemo(()=>b.wallet.name),"’s camera"]}})}}),createComponent(BodyStyled$1,{get qr(){return _()==="mobile"},get children(){return createComponent(Switch,{get children(){return[createComponent(Match,{get when(){return _()==="mobile"},get children(){return createComponent(QRCodeStyled$1,{disableCopy:!1,get sourceUrl(){return addReturnStrategy($(),"none")},get imageUrl(){return b.wallet.imageUrl}})}}),createComponent(Match,{get when(){return k()},get children(){return[createComponent(ErrorIconStyled$1,{size:"s"}),createComponent(BodyTextStyled$1,{translationKey:"walletModal.desktopConnectionModal.connectionDeclined",children:"Connection declined"}),createComponent(ButtonsContainerStyled$1,{get children(){return createComponent(Button,{get leftIcon(){return createComponent(RetryIcon,{})},get onClick(){return _()==="extension"?ht:dt},get children(){return createComponent(Translation,{translationKey:"common.retry",children:"Retry"})}})}})]}}),createComponent(Match,{get when(){return _()==="extension"},get children(){return[createComponent(Show,{get when(){return isWalletInfoCurrentlyInjected(b.wallet)},get children(){return[createComponent(LoaderStyled$1,{size:"s"}),createComponent(BodyTextStyled$1,{translationKey:"walletModal.desktopConnectionModal.continueInExtension",get translationValues(){return{name:b.wallet.name}},get children(){return["Continue in ",createMemo(()=>b.wallet.name)," browser extension…"]}}),createComponent(ButtonsContainerStyled$1,{get children(){return createComponent(Button,{get leftIcon(){return createComponent(RetryIcon,{})},onClick:ht,get children(){return createComponent(Translation,{translationKey:"common.retry",children:"Retry"})}})}})]}}),createComponent(Show,{get when(){return!isWalletInfoCurrentlyInjected(b.wallet)},get children(){return[createComponent(BodyTextStyled$1,{translationKey:"walletModal.desktopConnectionModal.dontHaveExtension",get translationValues(){return{name:b.wallet.name}},get children(){return["Seems you don't have installed ",createMemo(()=>b.wallet.name)," browser extension"]}}),createComponent(ButtonsContainerStyled$1,{get children(){return createComponent(Link,{get href(){return b.wallet.aboutUrl},blank:!0,get children(){return createComponent(Button,{get rightIcon(){return createComponent(LinkIcon,{})},onClick:ht,get children(){return createComponent(Translation,{translationKey:"walletModal.desktopConnectionModal.getWallet",get translationValues(){return{name:b.wallet.name}},get children(){return["Get ",createMemo(()=>b.wallet.name)]}})}})}})}})]}})]}}),createComponent(Match,{get when(){return _()==="desktop"},get children(){return[createComponent(LoaderIcon,{size:"m"}),createComponent(BodyTextStyled$1,{translationKey:"walletModal.desktopConnectionModal.continueOnDesktop",get translationValues(){return{name:b.wallet.name}},get children(){return["Continue in ",createMemo(()=>b.wallet.name)," on desktop…"]}}),createComponent(ButtonsContainerStyled$1,{get children(){return[createComponent(Button,{get leftIcon(){return createComponent(RetryIcon,{})},onClick:dt,get children(){return createComponent(Translation,{translationKey:"common.retry",children:"Retry"})}}),createComponent(Link,{get href(){return b.wallet.aboutUrl},blank:!0,get children(){return createComponent(Button,{get rightIcon(){return createComponent(LinkIcon,{})},get children(){return createComponent(Translation,{translationKey:"walletModal.desktopConnectionModal.getWallet",get translationValues(){return{name:b.wallet.name}},get children(){return["Get ",createMemo(()=>b.wallet.name)]}})}})}})]}})]}})]}})}}),createComponent(Show,{get when(){return b.wallet.appName===AT_WALLET_APP_NAME},get children(){return createComponent(TgButtonStyled,{get rightIcon(){return createComponent(TgImageStyled,{get src(){return IMG.TG}})},scale:"s",onClick:ut,get children(){return createComponent(Translation,{translationKey:"walletModal.desktopConnectionModal.openWalletOnTelegram",children:"Open Wallet in Telegram on desktop"})}})}}),createComponent(Show,{get when(){return b.wallet.appName!==AT_WALLET_APP_NAME},get children(){return createComponent(BottomButtonsContainerStyled,{get children(){return[createComponent(Show,{get when(){return createMemo(()=>_()!=="mobile")()&&supportsMobile(b.wallet)},get children(){return createComponent(FooterButton$1,{appearance:"secondary",get leftIcon(){return createComponent(MobileIcon,{})},onClick:it,get children(){return createComponent(Translation,{translationKey:"common.mobile",children:"Mobile"})}})}}),createComponent(Show,{get when(){return createMemo(()=>_()!=="extension")()&&supportsExtension(b.wallet)},get children(){return createComponent(FooterButton$1,{appearance:"secondary",get leftIcon(){return createComponent(BrowserIcon,{})},onClick:ht,get children(){return createComponent(Translation,{translationKey:"common.browserExtension",children:"Browser Extension"})}})}}),createComponent(Show,{get when(){return createMemo(()=>_()!=="desktop")()&&supportsDesktop(b.wallet)},get children(){return createComponent(FooterButton$1,{appearance:"secondary",get leftIcon(){return createComponent(DesktopIcon,{})},onClick:dt,get children(){return createComponent(Translation,{translationKey:"common.desktop",children:"Desktop"})}})}})]}})}})]}})},InfoModalStyled=styled.div``,StyledIconButton$1=styled(IconButton)` position: absolute; top: 16px; left: 16px; diff --git a/docs/index.html b/docs/index.html index 7ef79a2..18bc8f1 100644 --- a/docs/index.html +++ b/docs/index.html @@ -7,7 +7,7 @@ Demo Dapp React UI - +