diff --git a/docs/assets/index-b0c518ca.js b/docs/assets/index-303a9795.js similarity index 96% rename from docs/assets/index-b0c518ca.js rename to docs/assets/index-303a9795.js index 0591f84..f3f4009 100644 --- a/docs/assets/index-b0c518ca.js +++ b/docs/assets/index-303a9795.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{var j,$;if(!((j=_==null?void 0:_.signal)===null||j===void 0)&&j.aborted){k(new TonConnectError("Delay aborted"));return}const et=setTimeout(()=>d(),b);($=_==null?void 0:_.signal)===null||$===void 0||$.addEventListener("abort",()=>{clearTimeout(et),k(new TonConnectError("Delay aborted"))})})})}function createAbortController(b){const _=new AbortController;return b!=null&&b.aborted?_.abort():b==null||b.addEventListener("abort",()=>_.abort(),{once:!0}),_}function callForSuccess(b,_){var d,k;return __awaiter(this,void 0,void 0,function*(){const j=(d=_==null?void 0:_.attempts)!==null&&d!==void 0?d:10,$=(k=_==null?void 0:_.delayMs)!==null&&k!==void 0?k:200,et=createAbortController(_==null?void 0:_.signal);if(typeof b!="function")throw new TonConnectError(`Expected a function, got ${typeof b}`);let tt=0,rt;for(;tt__awaiter(this,void 0,void 0,function*(){if($=at??null,et==null||et.abort(),et=createAbortController(at),et.signal.aborted)throw new TonConnectError("Resource creation was aborted");k=it??null;const dt=b(et.signal,...it);j=dt;const ut=yield dt;if(j!==dt&&ut!==d)throw yield _(ut),new TonConnectError("Resource creation was aborted by a new resource creation");return d=ut,d});return{create:tt,current:()=>d??null,dispose:()=>__awaiter(this,void 0,void 0,function*(){try{const at=d;d=null;const it=j;j=null;try{et==null||et.abort()}catch{}yield Promise.allSettled([at?_(at):Promise.resolve(),it?_(yield it):Promise.resolve()])}catch{}}),recreate:at=>__awaiter(this,void 0,void 0,function*(){const it=d,dt=j,ut=k,ht=$;if(yield delay(at),it===d&&dt===j&&ut===k&&ht===$)return yield tt($,...ut??[]);throw new TonConnectError("Resource recreation was aborted by a new resource creation")})}}function timeout(b,_){const d=_==null?void 0:_.timeout,k=_==null?void 0:_.signal,j=createAbortController(k);return new Promise(($,et)=>__awaiter(this,void 0,void 0,function*(){if(j.signal.aborted){et(new TonConnectError("Operation aborted"));return}let tt;typeof d<"u"&&(tt=setTimeout(()=>{j.abort(),et(new TonConnectError(`Timeout after ${d}ms`))},d)),j.signal.addEventListener("abort",()=>{clearTimeout(tt),et(new TonConnectError("Operation aborted"))},{once:!0});const rt={timeout:d,abort:j.signal};yield b((...nt)=>{clearTimeout(tt),$(...nt)},()=>{clearTimeout(tt),et()},rt)}))}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.defaultReconnectDelay=2e3,this.defaultResendDelay=5e3,this.eventSource=createResource$1((et,tt)=>__awaiter(this,void 0,void 0,function*(){const rt={bridgeUrl:this.bridgeUrl,ssePath:this.ssePath,sessionId:this.sessionId,bridgeGatewayStorage:this.bridgeGatewayStorage,errorHandler:this.errorsHandler.bind(this),messageHandler:this.messagesHandler.bind(this),signal:et,openingDeadlineMS:tt};return yield createEventSource(rt)}),et=>__awaiter(this,void 0,void 0,function*(){et.close()})),this.bridgeGatewayStorage=new HttpBridgeGatewayStorage(_,d)}get isReady(){const _=this.eventSource.current();return(_==null?void 0:_.readyState)===EventSource.OPEN}get isClosed(){const _=this.eventSource.current();return(_==null?void 0:_.readyState)!==EventSource.OPEN}get isConnecting(){const _=this.eventSource.current();return(_==null?void 0:_.readyState)===EventSource.CONNECTING}registerSession(_){return __awaiter(this,void 0,void 0,function*(){yield this.eventSource.create(_==null?void 0:_.signal,_==null?void 0:_.openingDeadlineMS)})}send(_,d,k,j){var $;return __awaiter(this,void 0,void 0,function*(){const et={};typeof j=="number"?et.ttl=j:(et.ttl=j==null?void 0:j.ttl,et.signal=j==null?void 0:j.signal,et.attempts=j==null?void 0:j.attempts);const tt=new URL(addPathToUrl(this.bridgeUrl,this.postPath));tt.searchParams.append("client_id",this.sessionId),tt.searchParams.append("to",d),tt.searchParams.append("ttl",((et==null?void 0:et.ttl)||this.defaultTtl).toString()),tt.searchParams.append("topic",k);const rt=Base64.encode(_);yield callForSuccess(nt=>__awaiter(this,void 0,void 0,function*(){const ot=yield this.post(tt,rt,nt.signal);if(!ot.ok)throw new TonConnectError(`Bridge send failed, status ${ot.status}`)}),{attempts:($=et==null?void 0:et.attempts)!==null&&$!==void 0?$:Number.MAX_SAFE_INTEGER,delayMs:this.defaultResendDelay,signal:et==null?void 0:et.signal})})}pause(){this.eventSource.dispose().catch(_=>logError$1(`Bridge pause failed, ${_}`))}unPause(){return __awaiter(this,void 0,void 0,function*(){yield this.eventSource.recreate(0)})}close(){return __awaiter(this,void 0,void 0,function*(){yield this.eventSource.dispose().catch(_=>logError$1(`Bridge close failed, ${_}`))})}setListener(_){this.listener=_}setErrorsListener(_){this.errorsListener=_}post(_,d,k){return __awaiter(this,void 0,void 0,function*(){const j=yield fetch(_,{method:"post",body:d,signal:k});if(!j.ok)throw new TonConnectError(`Bridge send failed, status ${j.status}`);return j})}errorsHandler(_,d){return __awaiter(this,void 0,void 0,function*(){if(this.isConnecting)throw _.close(),new TonConnectError("Bridge error, failed to connect");if(this.isReady){try{this.errorsListener(d)}catch{}return}if(this.isClosed)return _.close(),logDebug$1(`Bridge reconnecting, ${this.defaultReconnectDelay}ms delay`),yield this.eventSource.recreate(this.defaultReconnectDelay);throw new TonConnectError("Bridge error, unknown state")})}messagesHandler(_){return __awaiter(this,void 0,void 0,function*(){if(_.data===this.heartbeatMessage||(yield this.bridgeGatewayStorage.storeLastEventId(_.lastEventId),this.isClosed))return;let d;try{d=JSON.parse(_.data)}catch(k){throw new TonConnectError(`Bridge message parse failed, message ${k.data}`)}this.listener(d)})}}function createEventSource(b){return __awaiter(this,void 0,void 0,function*(){return yield timeout((_,d,k)=>__awaiter(this,void 0,void 0,function*(){var j;const et=createAbortController(k.signal).signal;if(et.aborted){d(new TonConnectError("Bridge connection aborted"));return}const tt=new URL(addPathToUrl(b.bridgeUrl,b.ssePath));tt.searchParams.append("client_id",b.sessionId);const rt=yield b.bridgeGatewayStorage.getLastEventId();if(rt&&tt.searchParams.append("last_event_id",rt),et.aborted){d(new TonConnectError("Bridge connection aborted"));return}const nt=new EventSource(tt.toString());nt.onerror=ot=>__awaiter(this,void 0,void 0,function*(){if(et.aborted){nt.close(),d(new TonConnectError("Bridge connection aborted"));return}try{const at=yield b.errorHandler(nt,ot);at!==nt&&nt.close(),at&&at!==nt&&_(at)}catch(at){nt.close(),d(at)}}),nt.onopen=()=>{if(et.aborted){nt.close(),d(new TonConnectError("Bridge connection aborted"));return}_(nt)},nt.onmessage=ot=>{if(et.aborted){nt.close(),d(new TonConnectError("Bridge connection aborted"));return}b.messageHandler(ot)},(j=b.signal)===null||j===void 0||j.addEventListener("abort",()=>{nt.close(),d(new TonConnectError("Bridge connection aborted"))})}),{timeout:b.openingDeadlineMS,signal:b.signal})})}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;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.defaultOpeningDeadlineMS=12e3,this.defaultRetryTimeoutMS=2e3,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(_,d){var k;const j=createAbortController(d==null?void 0:d.signal);(k=this.abortController)===null||k===void 0||k.abort(),this.abortController=j,this.closeGateways();const $=new SessionCrypto;this.session={sessionCrypto:$,bridgeUrl:"bridgeUrl"in this.walletConnectionSource?this.walletConnectionSource.bridgeUrl:""},this.connectionStorage.storeConnection({type:"http",connectionSource:this.walletConnectionSource,sessionCrypto:$}).then(()=>__awaiter(this,void 0,void 0,function*(){j.signal.aborted||(yield callForSuccess(tt=>{var rt;return this.openGateways($,{openingDeadlineMS:(rt=d==null?void 0:d.openingDeadlineMS)!==null&&rt!==void 0?rt:this.defaultOpeningDeadlineMS,signal:tt==null?void 0:tt.signal})},{attempts:Number.MAX_SAFE_INTEGER,delayMs:this.defaultRetryTimeoutMS,signal:j.signal}))}));const et="universalLink"in this.walletConnectionSource&&this.walletConnectionSource.universalLink?this.walletConnectionSource.universalLink:this.standardUniversalLink;return this.generateUniversalLink(et,_)}restoreConnection(_){var d,k;return __awaiter(this,void 0,void 0,function*(){const j=createAbortController(_==null?void 0:_.signal);if((d=this.abortController)===null||d===void 0||d.abort(),this.abortController=j,j.signal.aborted)return;this.closeGateways();const $=yield this.connectionStorage.getHttpConnection();if(!$||j.signal.aborted)return;const et=(k=_==null?void 0:_.openingDeadlineMS)!==null&&k!==void 0?k:this.defaultOpeningDeadlineMS;if(isPendingConnectionHttp($))return this.session={sessionCrypto:$.sessionCrypto,bridgeUrl:"bridgeUrl"in this.walletConnectionSource?this.walletConnectionSource.bridgeUrl:""},yield this.openGateways($.sessionCrypto,{openingDeadlineMS:et,signal:j==null?void 0:j.signal});if(Array.isArray(this.walletConnectionSource))throw new TonConnectError("Internal error. Connection source is array while WalletConnectionSourceHTTP was expected.");if(this.session=$.session,this.gateway&&(logDebug$1("Gateway is already opened, closing previous gateway"),yield this.gateway.close()),this.gateway=new BridgeGateway(this.storage,this.walletConnectionSource.bridgeUrl,$.session.sessionCrypto.sessionId,this.gatewayListener.bind(this),this.gatewayErrorsListener.bind(this)),!j.signal.aborted){this.listeners.forEach(tt=>tt($.connectEvent));try{yield callForSuccess(tt=>this.gateway.registerSession({openingDeadlineMS:et,signal:tt.signal}),{attempts:Number.MAX_SAFE_INTEGER,delayMs:this.defaultRetryTimeoutMS,signal:j.signal})}catch{yield this.disconnect({signal:j.signal});return}}})}sendRequest(_,d){const k={};return typeof d=="function"?k.onRequestSent=d:(k.onRequestSent=d==null?void 0:d.onRequestSent,k.signal=d==null?void 0:d.signal,k.attempts=d==null?void 0:d.attempts),new Promise((j,$)=>__awaiter(this,void 0,void 0,function*(){var et;if(!this.gateway||!this.session||!("walletPublicKey"in this.session))throw new TonConnectError("Trying to send bridge request without session");const tt=(yield this.connectionStorage.getNextRpcRequestId()).toString();yield this.connectionStorage.increaseNextRpcRequestId(),logDebug$1("Send http-bridge request:",Object.assign(Object.assign({},_),{id:tt}));const rt=this.session.sessionCrypto.encrypt(JSON.stringify(Object.assign(Object.assign({},_),{id:tt})),hexToByteArray(this.session.walletPublicKey));try{yield this.gateway.send(rt,this.session.walletPublicKey,_.method,{attempts:k==null?void 0:k.attempts,signal:k==null?void 0:k.signal}),(et=k==null?void 0:k.onRequestSent)===null||et===void 0||et.call(k),this.pendingRequests.set(tt.toString(),j)}catch(nt){$(nt)}}))}closeConnection(){this.closeGateways(),this.listeners=[],this.session=null,this.gateway=null}disconnect(_){return __awaiter(this,void 0,void 0,function*(){return new Promise(d=>__awaiter(this,void 0,void 0,function*(){let k=!1,j=null;const $=()=>{k||(k=!0,this.removeBridgeAndSession().then(d))};try{this.closeGateways();const et=createAbortController(_==null?void 0:_.signal);j=setTimeout(()=>{et.abort()},this.defaultOpeningDeadlineMS),yield this.sendRequest({method:"disconnect",params:[]},{onRequestSent:$,signal:et.signal,attempts:1})}catch(et){logDebug$1("Disconnect error:",et),k||this.removeBridgeAndSession().then(d)}finally{j&&clearTimeout(j),$()}}))})}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(_)){yield _.close();return}return this.closeGateways({except:_}),this.gateway&&(logDebug$1("Gateway is already opened, closing previous gateway"),yield this.gateway.close()),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$1("Wallet message received:",d),!("event"in d)){const j=d.id.toString(),$=this.pendingRequests.get(j);if(!$){logDebug$1(`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"&&(logDebug$1("Removing bridge and session: received disconnect event"),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.map(k=>k.close().catch()),this.pendingGateways=this.walletConnectionSource.map(k=>{const j=new BridgeGateway(this.storage,k.bridgeUrl,_.sessionId,()=>{},()=>{});return j.setListener($=>this.pendingGatewaysListener(j,k.bridgeUrl,$)),j}),yield Promise.allSettled(this.pendingGateways.map(k=>callForSuccess(j=>{var $;return this.pendingGateways.some(et=>et===k)?k.registerSession({openingDeadlineMS:($=d==null?void 0:d.openingDeadlineMS)!==null&&$!==void 0?$:this.defaultOpeningDeadlineMS,signal:j.signal}):k.close()},{attempts:Number.MAX_SAFE_INTEGER,delayMs:this.defaultRetryTimeoutMS,signal:d==null?void 0:d.signal})));return}else return this.gateway&&(logDebug$1("Gateway is already opened, closing previous gateway"),yield this.gateway.close()),this.gateway=new BridgeGateway(this.storage,this.walletConnectionSource.bridgeUrl,_.sessionId,this.gatewayListener.bind(this),this.gatewayErrorsListener.bind(this)),yield this.gateway.registerSession({openingDeadlineMS:d==null?void 0:d.openingDeadlineMS,signal:d==null?void 0:d.signal})})}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$1("Injected Provider restoring connection...");const _=yield this.injectedWallet.restoreConnection();logDebug$1("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$1(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){var k;return __awaiter(this,void 0,void 0,function*(){const j={};typeof d=="function"?j.onRequestSent=d:(j.onRequestSent=d==null?void 0:d.onRequestSent,j.signal=d==null?void 0:d.signal);const $=(yield this.connectionStorage.getNextRpcRequestId()).toString();yield this.connectionStorage.increaseNextRpcRequestId(),logDebug$1("Send injected-bridge request:",Object.assign(Object.assign({},_),{id:$}));const et=this.injectedWallet.send(Object.assign(Object.assign({},_),{id:$}));return et.then(tt=>logDebug$1("Wallet message received:",tt)),(k=j==null?void 0:j.onRequestSent)===null||k===void 0||k.call(j),et})}_connect(_,d){return __awaiter(this,void 0,void 0,function*(){try{logDebug$1(`Injected Provider connect request: protocolVersion: ${_}, message:`,d);const k=yield this.injectedWallet.connect(_,d);logDebug$1("Injected Provider connect response:",k),k.event==="connect"&&(yield this.updateSession(),this.makeSubscriptions()),this.listeners.forEach(j=>j(k))}catch(k){logDebug$1("Injected Provider connect error:",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$1("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:"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","ios","android","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:"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:"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.")}function createRequestVersionEvent(){return{type:"request-version"}}function createResponseVersionEvent(b){return{type:"response-version",version:b}}function createVersionInfo(b){return{ton_connect_sdk_lib:b.ton_connect_sdk_lib,ton_connect_ui_lib:b.ton_connect_ui_lib}}function createConnectionInfo(b,_){var d,k,j,$,et,tt,rt,nt;const at=((d=_==null?void 0:_.connectItems)===null||d===void 0?void 0:d.tonProof)&&"proof"in _.connectItems.tonProof?"ton_proof":"ton_addr";return{wallet_address:(j=(k=_==null?void 0:_.account)===null||k===void 0?void 0:k.address)!==null&&j!==void 0?j:null,wallet_type:($=_==null?void 0:_.device.appName)!==null&&$!==void 0?$:null,wallet_version:(et=_==null?void 0:_.device.appVersion)!==null&&et!==void 0?et:null,auth_type:at,custom_data:Object.assign({chain_id:(rt=(tt=_==null?void 0:_.account)===null||tt===void 0?void 0:tt.chain)!==null&&rt!==void 0?rt:null,provider:(nt=_==null?void 0:_.provider)!==null&&nt!==void 0?nt:null},createVersionInfo(b))}}function createConnectionStartedEvent(b){return{type:"connection-started",custom_data:createVersionInfo(b)}}function createConnectionCompletedEvent(b,_){return Object.assign({type:"connection-completed",is_success:!0},createConnectionInfo(b,_))}function createConnectionErrorEvent(b,_,d){return{type:"connection-error",is_success:!1,error_message:_,error_code:d??null,custom_data:createVersionInfo(b)}}function createConnectionRestoringStartedEvent(b){return{type:"connection-restoring-started",custom_data:createVersionInfo(b)}}function createConnectionRestoringCompletedEvent(b,_){return Object.assign({type:"connection-restoring-completed",is_success:!0},createConnectionInfo(b,_))}function createConnectionRestoringErrorEvent(b,_){return{type:"connection-restoring-error",is_success:!1,error_message:_,custom_data:createVersionInfo(b)}}function createTransactionInfo(b,_){var d,k,j,$;return{valid_until:(d=String(_.validUntil))!==null&&d!==void 0?d:null,from:($=(k=_.from)!==null&&k!==void 0?k:(j=b==null?void 0:b.account)===null||j===void 0?void 0:j.address)!==null&&$!==void 0?$:null,messages:_.messages.map(et=>{var tt,rt;return{address:(tt=et.address)!==null&&tt!==void 0?tt:null,amount:(rt=et.amount)!==null&&rt!==void 0?rt:null}})}}function createTransactionSentForSignatureEvent(b,_,d){return Object.assign(Object.assign({type:"transaction-sent-for-signature"},createConnectionInfo(b,_)),createTransactionInfo(_,d))}function createTransactionSignedEvent(b,_,d,k){return Object.assign(Object.assign({type:"transaction-signed",is_success:!0,signed_transaction:k.boc},createConnectionInfo(b,_)),createTransactionInfo(_,d))}function createTransactionSigningFailedEvent(b,_,d,k,j){return Object.assign(Object.assign({type:"transaction-signing-failed",is_success:!1,error_message:k,error_code:j??null},createConnectionInfo(b,_)),createTransactionInfo(_,d))}function createDisconnectionEvent(b,_,d){return Object.assign({type:"disconnection",scope:d},createConnectionInfo(b,_))}class BrowserEventDispatcher{constructor(){this.window=getWindow$2()}dispatchEvent(_,d){var k;return __awaiter(this,void 0,void 0,function*(){const j=new CustomEvent(_,{detail:d});(k=this.window)===null||k===void 0||k.dispatchEvent(j)})}addEventListener(_,d,k){var j;return __awaiter(this,void 0,void 0,function*(){return(j=this.window)===null||j===void 0||j.addEventListener(_,d,k),()=>{var $;return($=this.window)===null||$===void 0?void 0:$.removeEventListener(_,d)}})}}class TonConnectTracker{constructor(_){var d;this.eventPrefix="ton-connect-",this.tonConnectUiVersion=null,this.eventDispatcher=(d=_==null?void 0:_.eventDispatcher)!==null&&d!==void 0?d:new BrowserEventDispatcher,this.tonConnectSdkVersion=_.tonConnectSdkVersion,this.init().catch()}get version(){return createVersionInfo({ton_connect_sdk_lib:this.tonConnectSdkVersion,ton_connect_ui_lib:this.tonConnectUiVersion})}init(){return __awaiter(this,void 0,void 0,function*(){try{yield this.setRequestVersionHandler(),this.tonConnectUiVersion=yield this.requestTonConnectUiVersion()}catch{}})}setRequestVersionHandler(){return __awaiter(this,void 0,void 0,function*(){yield this.eventDispatcher.addEventListener("ton-connect-request-version",()=>__awaiter(this,void 0,void 0,function*(){yield this.eventDispatcher.dispatchEvent("ton-connect-response-version",createResponseVersionEvent(this.tonConnectSdkVersion))}))})}requestTonConnectUiVersion(){return __awaiter(this,void 0,void 0,function*(){return new Promise((_,d)=>__awaiter(this,void 0,void 0,function*(){try{yield this.eventDispatcher.addEventListener("ton-connect-ui-response-version",k=>{_(k.detail.version)},{once:!0}),yield this.eventDispatcher.dispatchEvent("ton-connect-ui-request-version",createRequestVersionEvent())}catch(k){d(k)}}))})}dispatchUserActionEvent(_){try{this.eventDispatcher.dispatchEvent(`${this.eventPrefix}${_.type}`,_).catch()}catch{}}trackConnectionStarted(..._){try{const d=createConnectionStartedEvent(this.version,..._);this.dispatchUserActionEvent(d)}catch{}}trackConnectionCompleted(..._){try{const d=createConnectionCompletedEvent(this.version,..._);this.dispatchUserActionEvent(d)}catch{}}trackConnectionError(..._){try{const d=createConnectionErrorEvent(this.version,..._);this.dispatchUserActionEvent(d)}catch{}}trackConnectionRestoringStarted(..._){try{const d=createConnectionRestoringStartedEvent(this.version,..._);this.dispatchUserActionEvent(d)}catch{}}trackConnectionRestoringCompleted(..._){try{const d=createConnectionRestoringCompletedEvent(this.version,..._);this.dispatchUserActionEvent(d)}catch{}}trackConnectionRestoringError(..._){try{const d=createConnectionRestoringErrorEvent(this.version,..._);this.dispatchUserActionEvent(d)}catch{}}trackDisconnection(..._){try{const d=createDisconnectionEvent(this.version,..._);this.dispatchUserActionEvent(d)}catch{}}trackTransactionSentForSignature(..._){try{const d=createTransactionSentForSignatureEvent(this.version,..._);this.dispatchUserActionEvent(d)}catch{}}trackTransactionSigned(..._){try{const d=createTransactionSignedEvent(this.version,..._);this.dispatchUserActionEvent(d)}catch{}}trackTransactionSigningFailed(..._){try{const d=createTransactionSigningFailedEvent(this.version,..._);this.dispatchUserActionEvent(d)}catch{}}}const tonConnectSdkVersion="3.0.4-beta.2";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.tracker=new TonConnectTracker({eventDispatcher:_==null?void 0:_.eventDispatcher,tonConnectSdkVersion}),!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,j;const $={};if(typeof d=="object"&&"tonProof"in d&&($.request=d),typeof d=="object"&&("openingDeadlineMS"in d||"signal"in d||"request"in d)&&($.request=d==null?void 0:d.request,$.openingDeadlineMS=d==null?void 0:d.openingDeadlineMS,$.signal=d==null?void 0:d.signal),this.connected)throw new WalletAlreadyConnectedError;const et=createAbortController($==null?void 0:$.signal);if((k=this.abortController)===null||k===void 0||k.abort(),this.abortController=et,et.signal.aborted)throw new TonConnectError("Connection was aborted");return(j=this.provider)===null||j===void 0||j.closeConnection(),this.provider=this.createProvider(_),et.signal.addEventListener("abort",()=>{var tt;(tt=this.provider)===null||tt===void 0||tt.closeConnection(),this.provider=null}),this.tracker.trackConnectionStarted(),this.provider.connect(this.createConnectRequest($==null?void 0:$.request),{openingDeadlineMS:$==null?void 0:$.openingDeadlineMS,signal:et.signal})}restoreConnection(_){var d,k;return __awaiter(this,void 0,void 0,function*(){this.tracker.trackConnectionRestoringStarted();const j=createAbortController(_==null?void 0:_.signal);if((d=this.abortController)===null||d===void 0||d.abort(),this.abortController=j,j.signal.aborted){this.tracker.trackConnectionRestoringError("Connection restoring was aborted");return}const[$,et]=yield Promise.all([this.bridgeConnectionStorage.storedConnectionType(),this.walletsList.getEmbeddedWallet()]);if(j.signal.aborted){this.tracker.trackConnectionRestoringError("Connection restoring was aborted");return}let tt=null;try{switch($){case"http":tt=yield BridgeProvider.fromStorage(this.dappSettings.storage);break;case"injected":tt=yield InjectedProvider.fromStorage(this.dappSettings.storage);break;default:if(et)tt=this.createProvider(et);else return}}catch{this.tracker.trackConnectionRestoringError("Provider is not restored"),yield this.bridgeConnectionStorage.removeConnection(),tt==null||tt.closeConnection(),tt=null;return}if(j.signal.aborted){tt==null||tt.closeConnection(),this.tracker.trackConnectionRestoringError("Connection restoring was aborted");return}if(!tt){logError$1("Provider is not restored"),this.tracker.trackConnectionRestoringError("Provider is not restored");return}(k=this.provider)===null||k===void 0||k.closeConnection(),this.provider=tt,tt.listen(this.walletEventsListener.bind(this));const rt=()=>{this.tracker.trackConnectionRestoringError("Connection restoring was aborted"),tt==null||tt.closeConnection(),tt=null};j.signal.addEventListener("abort",rt);const nt=callForSuccess(at=>__awaiter(this,void 0,void 0,function*(){yield tt==null?void 0:tt.restoreConnection({openingDeadlineMS:_==null?void 0:_.openingDeadlineMS,signal:at.signal}),j.signal.removeEventListener("abort",rt),this.connected?this.tracker.trackConnectionRestoringCompleted(this.wallet):this.tracker.trackConnectionRestoringError("Connection restoring failed")}),{attempts:Number.MAX_SAFE_INTEGER,delayMs:2e3,signal:_==null?void 0:_.signal}),ot=new Promise(at=>setTimeout(()=>at(),12e3));return Promise.race([nt,ot])})}sendTransaction(_,d){return __awaiter(this,void 0,void 0,function*(){const k={};typeof d=="function"?k.onRequestSent=d:(k.onRequestSent=d==null?void 0:d.onRequestSent,k.signal=d==null?void 0:d.signal);const j=createAbortController(k==null?void 0:k.signal);if(j.signal.aborted)throw new TonConnectError("Transaction sending was aborted");this.checkConnection(),checkSendTransactionSupport(this.wallet.device.features,{requiredMessagesNumber:_.messages.length}),this.tracker.trackTransactionSentForSignature(this.wallet,_);const{validUntil:$}=_,et=__rest(_,["validUntil"]),tt=_.from||this.account.address,rt=_.network||this.account.chain,nt=yield this.provider.sendRequest(sendTransactionParser.convertToRpcRequest(Object.assign(Object.assign({},et),{valid_until:$,from:tt,network:rt})),{onRequestSent:k.onRequestSent,signal:j.signal});if(sendTransactionParser.isError(nt))return this.tracker.trackTransactionSigningFailed(this.wallet,_,nt.error.message,nt.error.code),sendTransactionParser.parseAndThrowError(nt);const ot=sendTransactionParser.convertFromRpcResponse(nt);return this.tracker.trackTransactionSigned(this.wallet,_,ot),ot})}disconnect(_){var d;return __awaiter(this,void 0,void 0,function*(){if(!this.connected)throw new WalletNotConnectedError;const k=createAbortController(_==null?void 0:_.signal),j=this.abortController;if(this.abortController=k,k.signal.aborted)throw new TonConnectError("Disconnect was aborted");this.onWalletDisconnected("dapp"),yield(d=this.provider)===null||d===void 0?void 0:d.disconnect({signal:k.signal}),j==null||j.abort()})}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()})}catch(d){logError$1("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("wallet")}}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,this.tracker.trackConnectionCompleted(j)}onWalletConnectError(_){const d=connectErrorsParser.parseError(_);if(this.statusChangeErrorSubscriptions.forEach(k=>k(d)),logDebug$1(d),this.tracker.trackConnectionError(_.message,_.code),d instanceof ManifestNotFoundError||d instanceof ManifestContentErrorError)throw logError$1(d),d}onWalletDisconnected(_){this.tracker.trackDisconnection(this.wallet,_),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;Gt+=2}},Ln=function(pn,Vt){for(var Gt in Vt)if(typeof Vt[Gt]===nt&&Vt[Gt].length>0){for(var wn=0;wn2&&(Zn[it]="iPad",Zn[ut]=st),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]&&Pn&&Pn.platform&&Pn.platform!="Unknown"&&(Zn[dt]=Pn.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>St?Tn(Zn,St):Zn,this},this.setUA(wn),this};Bn.VERSION=j,Bn.BROWSER=bn([dt,ft,at]),Bn.CPU=bn([lt]),Bn.DEVICE=bn([it,ht,ut,ct,pt,wt,st,yt,vt]),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 Hn=new Bn;Nn.ua=Hn.getResult(),Nn.ua.get=function(){return Hn.getUA()},Nn.ua.set=function(pn){Hn.setUA(pn);var Vt=Hn.getResult();for(var Gt in Vt)Nn.ua[Gt]=Vt[Gt]}}})(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:{}};/*! +`+_:""}`,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("%","--")}function delay(b,_){return __awaiter(this,void 0,void 0,function*(){return new Promise((d,k)=>{var j,$;if(!((j=_==null?void 0:_.signal)===null||j===void 0)&&j.aborted){k(new TonConnectError("Delay aborted"));return}const et=setTimeout(()=>d(),b);($=_==null?void 0:_.signal)===null||$===void 0||$.addEventListener("abort",()=>{clearTimeout(et),k(new TonConnectError("Delay aborted"))})})})}function createAbortController(b){const _=new AbortController;return b!=null&&b.aborted?_.abort():b==null||b.addEventListener("abort",()=>_.abort(),{once:!0}),_}function callForSuccess(b,_){var d,k;return __awaiter(this,void 0,void 0,function*(){const j=(d=_==null?void 0:_.attempts)!==null&&d!==void 0?d:10,$=(k=_==null?void 0:_.delayMs)!==null&&k!==void 0?k:200,et=createAbortController(_==null?void 0:_.signal);if(typeof b!="function")throw new TonConnectError(`Expected a function, got ${typeof b}`);let tt=0,rt;for(;tt__awaiter(this,void 0,void 0,function*(){if($=at??null,et==null||et.abort(),et=createAbortController(at),et.signal.aborted)throw new TonConnectError("Resource creation was aborted");k=it??null;const dt=b(et.signal,...it);j=dt;const ut=yield dt;if(j!==dt&&ut!==d)throw yield _(ut),new TonConnectError("Resource creation was aborted by a new resource creation");return d=ut,d});return{create:tt,current:()=>d??null,dispose:()=>__awaiter(this,void 0,void 0,function*(){try{const at=d;d=null;const it=j;j=null;try{et==null||et.abort()}catch{}yield Promise.allSettled([at?_(at):Promise.resolve(),it?_(yield it):Promise.resolve()])}catch{}}),recreate:at=>__awaiter(this,void 0,void 0,function*(){const it=d,dt=j,ut=k,ht=$;if(yield delay(at),it===d&&dt===j&&ut===k&&ht===$)return yield tt($,...ut??[]);throw new TonConnectError("Resource recreation was aborted by a new resource creation")})}}function timeout(b,_){const d=_==null?void 0:_.timeout,k=_==null?void 0:_.signal,j=createAbortController(k);return new Promise(($,et)=>__awaiter(this,void 0,void 0,function*(){if(j.signal.aborted){et(new TonConnectError("Operation aborted"));return}let tt;typeof d<"u"&&(tt=setTimeout(()=>{j.abort(),et(new TonConnectError(`Timeout after ${d}ms`))},d)),j.signal.addEventListener("abort",()=>{clearTimeout(tt),et(new TonConnectError("Operation aborted"))},{once:!0});const rt={timeout:d,abort:j.signal};yield b((...nt)=>{clearTimeout(tt),$(...nt)},()=>{clearTimeout(tt),et()},rt)}))}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.defaultReconnectDelay=2e3,this.defaultResendDelay=5e3,this.eventSource=createResource$1((et,tt)=>__awaiter(this,void 0,void 0,function*(){const rt={bridgeUrl:this.bridgeUrl,ssePath:this.ssePath,sessionId:this.sessionId,bridgeGatewayStorage:this.bridgeGatewayStorage,errorHandler:this.errorsHandler.bind(this),messageHandler:this.messagesHandler.bind(this),signal:et,openingDeadlineMS:tt};return yield createEventSource(rt)}),et=>__awaiter(this,void 0,void 0,function*(){et.close()})),this.bridgeGatewayStorage=new HttpBridgeGatewayStorage(_,d)}get isReady(){const _=this.eventSource.current();return(_==null?void 0:_.readyState)===EventSource.OPEN}get isClosed(){const _=this.eventSource.current();return(_==null?void 0:_.readyState)!==EventSource.OPEN}get isConnecting(){const _=this.eventSource.current();return(_==null?void 0:_.readyState)===EventSource.CONNECTING}registerSession(_){return __awaiter(this,void 0,void 0,function*(){yield this.eventSource.create(_==null?void 0:_.signal,_==null?void 0:_.openingDeadlineMS)})}send(_,d,k,j){var $;return __awaiter(this,void 0,void 0,function*(){const et={};typeof j=="number"?et.ttl=j:(et.ttl=j==null?void 0:j.ttl,et.signal=j==null?void 0:j.signal,et.attempts=j==null?void 0:j.attempts);const tt=new URL(addPathToUrl(this.bridgeUrl,this.postPath));tt.searchParams.append("client_id",this.sessionId),tt.searchParams.append("to",d),tt.searchParams.append("ttl",((et==null?void 0:et.ttl)||this.defaultTtl).toString()),tt.searchParams.append("topic",k);const rt=Base64.encode(_);yield callForSuccess(nt=>__awaiter(this,void 0,void 0,function*(){const ot=yield this.post(tt,rt,nt.signal);if(!ot.ok)throw new TonConnectError(`Bridge send failed, status ${ot.status}`)}),{attempts:($=et==null?void 0:et.attempts)!==null&&$!==void 0?$:Number.MAX_SAFE_INTEGER,delayMs:this.defaultResendDelay,signal:et==null?void 0:et.signal})})}pause(){this.eventSource.dispose().catch(_=>logError$1(`Bridge pause failed, ${_}`))}unPause(){return __awaiter(this,void 0,void 0,function*(){yield this.eventSource.recreate(0)})}close(){return __awaiter(this,void 0,void 0,function*(){yield this.eventSource.dispose().catch(_=>logError$1(`Bridge close failed, ${_}`))})}setListener(_){this.listener=_}setErrorsListener(_){this.errorsListener=_}post(_,d,k){return __awaiter(this,void 0,void 0,function*(){const j=yield fetch(_,{method:"post",body:d,signal:k});if(!j.ok)throw new TonConnectError(`Bridge send failed, status ${j.status}`);return j})}errorsHandler(_,d){return __awaiter(this,void 0,void 0,function*(){if(this.isConnecting)throw _.close(),new TonConnectError("Bridge error, failed to connect");if(this.isReady){try{this.errorsListener(d)}catch{}return}if(this.isClosed)return _.close(),logDebug$1(`Bridge reconnecting, ${this.defaultReconnectDelay}ms delay`),yield this.eventSource.recreate(this.defaultReconnectDelay);throw new TonConnectError("Bridge error, unknown state")})}messagesHandler(_){return __awaiter(this,void 0,void 0,function*(){if(_.data===this.heartbeatMessage||(yield this.bridgeGatewayStorage.storeLastEventId(_.lastEventId),this.isClosed))return;let d;try{d=JSON.parse(_.data)}catch(k){throw new TonConnectError(`Bridge message parse failed, message ${k.data}`)}this.listener(d)})}}function createEventSource(b){return __awaiter(this,void 0,void 0,function*(){return yield timeout((_,d,k)=>__awaiter(this,void 0,void 0,function*(){var j;const et=createAbortController(k.signal).signal;if(et.aborted){d(new TonConnectError("Bridge connection aborted"));return}const tt=new URL(addPathToUrl(b.bridgeUrl,b.ssePath));tt.searchParams.append("client_id",b.sessionId);const rt=yield b.bridgeGatewayStorage.getLastEventId();if(rt&&tt.searchParams.append("last_event_id",rt),et.aborted){d(new TonConnectError("Bridge connection aborted"));return}const nt=new EventSource(tt.toString());nt.onerror=ot=>__awaiter(this,void 0,void 0,function*(){if(et.aborted){nt.close(),d(new TonConnectError("Bridge connection aborted"));return}try{const at=yield b.errorHandler(nt,ot);at!==nt&&nt.close(),at&&at!==nt&&_(at)}catch(at){nt.close(),d(at)}}),nt.onopen=()=>{if(et.aborted){nt.close(),d(new TonConnectError("Bridge connection aborted"));return}_(nt)},nt.onmessage=ot=>{if(et.aborted){nt.close(),d(new TonConnectError("Bridge connection aborted"));return}b.messageHandler(ot)},(j=b.signal)===null||j===void 0||j.addEventListener("abort",()=>{nt.close(),d(new TonConnectError("Bridge connection aborted"))})}),{timeout:b.openingDeadlineMS,signal:b.signal})})}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;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.defaultOpeningDeadlineMS=12e3,this.defaultRetryTimeoutMS=2e3,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(_,d){var k;const j=createAbortController(d==null?void 0:d.signal);(k=this.abortController)===null||k===void 0||k.abort(),this.abortController=j,this.closeGateways();const $=new SessionCrypto;this.session={sessionCrypto:$,bridgeUrl:"bridgeUrl"in this.walletConnectionSource?this.walletConnectionSource.bridgeUrl:""},this.connectionStorage.storeConnection({type:"http",connectionSource:this.walletConnectionSource,sessionCrypto:$}).then(()=>__awaiter(this,void 0,void 0,function*(){j.signal.aborted||(yield callForSuccess(tt=>{var rt;return this.openGateways($,{openingDeadlineMS:(rt=d==null?void 0:d.openingDeadlineMS)!==null&&rt!==void 0?rt:this.defaultOpeningDeadlineMS,signal:tt==null?void 0:tt.signal})},{attempts:Number.MAX_SAFE_INTEGER,delayMs:this.defaultRetryTimeoutMS,signal:j.signal}))}));const et="universalLink"in this.walletConnectionSource&&this.walletConnectionSource.universalLink?this.walletConnectionSource.universalLink:this.standardUniversalLink;return this.generateUniversalLink(et,_)}restoreConnection(_){var d,k;return __awaiter(this,void 0,void 0,function*(){const j=createAbortController(_==null?void 0:_.signal);if((d=this.abortController)===null||d===void 0||d.abort(),this.abortController=j,j.signal.aborted)return;this.closeGateways();const $=yield this.connectionStorage.getHttpConnection();if(!$||j.signal.aborted)return;const et=(k=_==null?void 0:_.openingDeadlineMS)!==null&&k!==void 0?k:this.defaultOpeningDeadlineMS;if(isPendingConnectionHttp($))return this.session={sessionCrypto:$.sessionCrypto,bridgeUrl:"bridgeUrl"in this.walletConnectionSource?this.walletConnectionSource.bridgeUrl:""},yield this.openGateways($.sessionCrypto,{openingDeadlineMS:et,signal:j==null?void 0:j.signal});if(Array.isArray(this.walletConnectionSource))throw new TonConnectError("Internal error. Connection source is array while WalletConnectionSourceHTTP was expected.");if(this.session=$.session,this.gateway&&(logDebug$1("Gateway is already opened, closing previous gateway"),yield this.gateway.close()),this.gateway=new BridgeGateway(this.storage,this.walletConnectionSource.bridgeUrl,$.session.sessionCrypto.sessionId,this.gatewayListener.bind(this),this.gatewayErrorsListener.bind(this)),!j.signal.aborted){this.listeners.forEach(tt=>tt($.connectEvent));try{yield callForSuccess(tt=>this.gateway.registerSession({openingDeadlineMS:et,signal:tt.signal}),{attempts:Number.MAX_SAFE_INTEGER,delayMs:this.defaultRetryTimeoutMS,signal:j.signal})}catch{yield this.disconnect({signal:j.signal});return}}})}sendRequest(_,d){const k={};return typeof d=="function"?k.onRequestSent=d:(k.onRequestSent=d==null?void 0:d.onRequestSent,k.signal=d==null?void 0:d.signal,k.attempts=d==null?void 0:d.attempts),new Promise((j,$)=>__awaiter(this,void 0,void 0,function*(){var et;if(!this.gateway||!this.session||!("walletPublicKey"in this.session))throw new TonConnectError("Trying to send bridge request without session");const tt=(yield this.connectionStorage.getNextRpcRequestId()).toString();yield this.connectionStorage.increaseNextRpcRequestId(),logDebug$1("Send http-bridge request:",Object.assign(Object.assign({},_),{id:tt}));const rt=this.session.sessionCrypto.encrypt(JSON.stringify(Object.assign(Object.assign({},_),{id:tt})),hexToByteArray(this.session.walletPublicKey));try{yield this.gateway.send(rt,this.session.walletPublicKey,_.method,{attempts:k==null?void 0:k.attempts,signal:k==null?void 0:k.signal}),(et=k==null?void 0:k.onRequestSent)===null||et===void 0||et.call(k),this.pendingRequests.set(tt.toString(),j)}catch(nt){$(nt)}}))}closeConnection(){this.closeGateways(),this.listeners=[],this.session=null,this.gateway=null}disconnect(_){return __awaiter(this,void 0,void 0,function*(){return new Promise(d=>__awaiter(this,void 0,void 0,function*(){let k=!1,j=null;const $=()=>{k||(k=!0,this.removeBridgeAndSession().then(d))};try{this.closeGateways();const et=createAbortController(_==null?void 0:_.signal);j=setTimeout(()=>{et.abort()},this.defaultOpeningDeadlineMS),yield this.sendRequest({method:"disconnect",params:[]},{onRequestSent:$,signal:et.signal,attempts:1})}catch(et){logDebug$1("Disconnect error:",et),k||this.removeBridgeAndSession().then(d)}finally{j&&clearTimeout(j),$()}}))})}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(_)){yield _.close();return}return this.closeGateways({except:_}),this.gateway&&(logDebug$1("Gateway is already opened, closing previous gateway"),yield this.gateway.close()),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$1("Wallet message received:",d),!("event"in d)){const j=d.id.toString(),$=this.pendingRequests.get(j);if(!$){logDebug$1(`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"&&(logDebug$1("Removing bridge and session: received disconnect event"),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.map(k=>k.close().catch()),this.pendingGateways=this.walletConnectionSource.map(k=>{const j=new BridgeGateway(this.storage,k.bridgeUrl,_.sessionId,()=>{},()=>{});return j.setListener($=>this.pendingGatewaysListener(j,k.bridgeUrl,$)),j}),yield Promise.allSettled(this.pendingGateways.map(k=>callForSuccess(j=>{var $;return this.pendingGateways.some(et=>et===k)?k.registerSession({openingDeadlineMS:($=d==null?void 0:d.openingDeadlineMS)!==null&&$!==void 0?$:this.defaultOpeningDeadlineMS,signal:j.signal}):k.close()},{attempts:Number.MAX_SAFE_INTEGER,delayMs:this.defaultRetryTimeoutMS,signal:d==null?void 0:d.signal})));return}else return this.gateway&&(logDebug$1("Gateway is already opened, closing previous gateway"),yield this.gateway.close()),this.gateway=new BridgeGateway(this.storage,this.walletConnectionSource.bridgeUrl,_.sessionId,this.gatewayListener.bind(this),this.gatewayErrorsListener.bind(this)),yield this.gateway.registerSession({openingDeadlineMS:d==null?void 0:d.openingDeadlineMS,signal:d==null?void 0:d.signal})})}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$1("Injected Provider restoring connection...");const _=yield this.injectedWallet.restoreConnection();logDebug$1("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$1(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){var k;return __awaiter(this,void 0,void 0,function*(){const j={};typeof d=="function"?j.onRequestSent=d:(j.onRequestSent=d==null?void 0:d.onRequestSent,j.signal=d==null?void 0:d.signal);const $=(yield this.connectionStorage.getNextRpcRequestId()).toString();yield this.connectionStorage.increaseNextRpcRequestId(),logDebug$1("Send injected-bridge request:",Object.assign(Object.assign({},_),{id:$}));const et=this.injectedWallet.send(Object.assign(Object.assign({},_),{id:$}));return et.then(tt=>logDebug$1("Wallet message received:",tt)),(k=j==null?void 0:j.onRequestSent)===null||k===void 0||k.call(j),et})}_connect(_,d){return __awaiter(this,void 0,void 0,function*(){try{logDebug$1(`Injected Provider connect request: protocolVersion: ${_}, message:`,d);const k=yield this.injectedWallet.connect(_,d);logDebug$1("Injected Provider connect response:",k),k.event==="connect"&&(yield this.updateSession(),this.makeSubscriptions()),this.listeners.forEach(j=>j(k))}catch(k){logDebug$1("Injected Provider connect error:",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$1("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:"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","ios","android","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:"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:"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.")}function createRequestVersionEvent(){return{type:"request-version"}}function createResponseVersionEvent(b){return{type:"response-version",version:b}}function createVersionInfo(b){return{ton_connect_sdk_lib:b.ton_connect_sdk_lib,ton_connect_ui_lib:b.ton_connect_ui_lib}}function createConnectionInfo(b,_){var d,k,j,$,et,tt,rt,nt;const at=((d=_==null?void 0:_.connectItems)===null||d===void 0?void 0:d.tonProof)&&"proof"in _.connectItems.tonProof?"ton_proof":"ton_addr";return{wallet_address:(j=(k=_==null?void 0:_.account)===null||k===void 0?void 0:k.address)!==null&&j!==void 0?j:null,wallet_type:($=_==null?void 0:_.device.appName)!==null&&$!==void 0?$:null,wallet_version:(et=_==null?void 0:_.device.appVersion)!==null&&et!==void 0?et:null,auth_type:at,custom_data:Object.assign({chain_id:(rt=(tt=_==null?void 0:_.account)===null||tt===void 0?void 0:tt.chain)!==null&&rt!==void 0?rt:null,provider:(nt=_==null?void 0:_.provider)!==null&&nt!==void 0?nt:null},createVersionInfo(b))}}function createConnectionStartedEvent(b){return{type:"connection-started",custom_data:createVersionInfo(b)}}function createConnectionCompletedEvent(b,_){return Object.assign({type:"connection-completed",is_success:!0},createConnectionInfo(b,_))}function createConnectionErrorEvent(b,_,d){return{type:"connection-error",is_success:!1,error_message:_,error_code:d??null,custom_data:createVersionInfo(b)}}function createConnectionRestoringStartedEvent(b){return{type:"connection-restoring-started",custom_data:createVersionInfo(b)}}function createConnectionRestoringCompletedEvent(b,_){return Object.assign({type:"connection-restoring-completed",is_success:!0},createConnectionInfo(b,_))}function createConnectionRestoringErrorEvent(b,_){return{type:"connection-restoring-error",is_success:!1,error_message:_,custom_data:createVersionInfo(b)}}function createTransactionInfo(b,_){var d,k,j,$;return{valid_until:(d=String(_.validUntil))!==null&&d!==void 0?d:null,from:($=(k=_.from)!==null&&k!==void 0?k:(j=b==null?void 0:b.account)===null||j===void 0?void 0:j.address)!==null&&$!==void 0?$:null,messages:_.messages.map(et=>{var tt,rt;return{address:(tt=et.address)!==null&&tt!==void 0?tt:null,amount:(rt=et.amount)!==null&&rt!==void 0?rt:null}})}}function createTransactionSentForSignatureEvent(b,_,d){return Object.assign(Object.assign({type:"transaction-sent-for-signature"},createConnectionInfo(b,_)),createTransactionInfo(_,d))}function createTransactionSignedEvent(b,_,d,k){return Object.assign(Object.assign({type:"transaction-signed",is_success:!0,signed_transaction:k.boc},createConnectionInfo(b,_)),createTransactionInfo(_,d))}function createTransactionSigningFailedEvent(b,_,d,k,j){return Object.assign(Object.assign({type:"transaction-signing-failed",is_success:!1,error_message:k,error_code:j??null},createConnectionInfo(b,_)),createTransactionInfo(_,d))}function createDisconnectionEvent(b,_,d){return Object.assign({type:"disconnection",scope:d},createConnectionInfo(b,_))}class BrowserEventDispatcher{constructor(){this.window=getWindow$2()}dispatchEvent(_,d){var k;return __awaiter(this,void 0,void 0,function*(){const j=new CustomEvent(_,{detail:d});(k=this.window)===null||k===void 0||k.dispatchEvent(j)})}addEventListener(_,d,k){var j;return __awaiter(this,void 0,void 0,function*(){return(j=this.window)===null||j===void 0||j.addEventListener(_,d,k),()=>{var $;return($=this.window)===null||$===void 0?void 0:$.removeEventListener(_,d)}})}}class TonConnectTracker{constructor(_){var d;this.eventPrefix="ton-connect-",this.tonConnectUiVersion=null,this.eventDispatcher=(d=_==null?void 0:_.eventDispatcher)!==null&&d!==void 0?d:new BrowserEventDispatcher,this.tonConnectSdkVersion=_.tonConnectSdkVersion,this.init().catch()}get version(){return createVersionInfo({ton_connect_sdk_lib:this.tonConnectSdkVersion,ton_connect_ui_lib:this.tonConnectUiVersion})}init(){return __awaiter(this,void 0,void 0,function*(){try{yield this.setRequestVersionHandler(),this.tonConnectUiVersion=yield this.requestTonConnectUiVersion()}catch{}})}setRequestVersionHandler(){return __awaiter(this,void 0,void 0,function*(){yield this.eventDispatcher.addEventListener("ton-connect-request-version",()=>__awaiter(this,void 0,void 0,function*(){yield this.eventDispatcher.dispatchEvent("ton-connect-response-version",createResponseVersionEvent(this.tonConnectSdkVersion))}))})}requestTonConnectUiVersion(){return __awaiter(this,void 0,void 0,function*(){return new Promise((_,d)=>__awaiter(this,void 0,void 0,function*(){try{yield this.eventDispatcher.addEventListener("ton-connect-ui-response-version",k=>{_(k.detail.version)},{once:!0}),yield this.eventDispatcher.dispatchEvent("ton-connect-ui-request-version",createRequestVersionEvent())}catch(k){d(k)}}))})}dispatchUserActionEvent(_){try{this.eventDispatcher.dispatchEvent(`${this.eventPrefix}${_.type}`,_).catch()}catch{}}trackConnectionStarted(..._){try{const d=createConnectionStartedEvent(this.version,..._);this.dispatchUserActionEvent(d)}catch{}}trackConnectionCompleted(..._){try{const d=createConnectionCompletedEvent(this.version,..._);this.dispatchUserActionEvent(d)}catch{}}trackConnectionError(..._){try{const d=createConnectionErrorEvent(this.version,..._);this.dispatchUserActionEvent(d)}catch{}}trackConnectionRestoringStarted(..._){try{const d=createConnectionRestoringStartedEvent(this.version,..._);this.dispatchUserActionEvent(d)}catch{}}trackConnectionRestoringCompleted(..._){try{const d=createConnectionRestoringCompletedEvent(this.version,..._);this.dispatchUserActionEvent(d)}catch{}}trackConnectionRestoringError(..._){try{const d=createConnectionRestoringErrorEvent(this.version,..._);this.dispatchUserActionEvent(d)}catch{}}trackDisconnection(..._){try{const d=createDisconnectionEvent(this.version,..._);this.dispatchUserActionEvent(d)}catch{}}trackTransactionSentForSignature(..._){try{const d=createTransactionSentForSignatureEvent(this.version,..._);this.dispatchUserActionEvent(d)}catch{}}trackTransactionSigned(..._){try{const d=createTransactionSignedEvent(this.version,..._);this.dispatchUserActionEvent(d)}catch{}}trackTransactionSigningFailed(..._){try{const d=createTransactionSigningFailedEvent(this.version,..._);this.dispatchUserActionEvent(d)}catch{}}}const tonConnectSdkVersion="3.0.4";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.tracker=new TonConnectTracker({eventDispatcher:_==null?void 0:_.eventDispatcher,tonConnectSdkVersion}),!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,j;const $={};if(typeof d=="object"&&"tonProof"in d&&($.request=d),typeof d=="object"&&("openingDeadlineMS"in d||"signal"in d||"request"in d)&&($.request=d==null?void 0:d.request,$.openingDeadlineMS=d==null?void 0:d.openingDeadlineMS,$.signal=d==null?void 0:d.signal),this.connected)throw new WalletAlreadyConnectedError;const et=createAbortController($==null?void 0:$.signal);if((k=this.abortController)===null||k===void 0||k.abort(),this.abortController=et,et.signal.aborted)throw new TonConnectError("Connection was aborted");return(j=this.provider)===null||j===void 0||j.closeConnection(),this.provider=this.createProvider(_),et.signal.addEventListener("abort",()=>{var tt;(tt=this.provider)===null||tt===void 0||tt.closeConnection(),this.provider=null}),this.tracker.trackConnectionStarted(),this.provider.connect(this.createConnectRequest($==null?void 0:$.request),{openingDeadlineMS:$==null?void 0:$.openingDeadlineMS,signal:et.signal})}restoreConnection(_){var d,k;return __awaiter(this,void 0,void 0,function*(){this.tracker.trackConnectionRestoringStarted();const j=createAbortController(_==null?void 0:_.signal);if((d=this.abortController)===null||d===void 0||d.abort(),this.abortController=j,j.signal.aborted){this.tracker.trackConnectionRestoringError("Connection restoring was aborted");return}const[$,et]=yield Promise.all([this.bridgeConnectionStorage.storedConnectionType(),this.walletsList.getEmbeddedWallet()]);if(j.signal.aborted){this.tracker.trackConnectionRestoringError("Connection restoring was aborted");return}let tt=null;try{switch($){case"http":tt=yield BridgeProvider.fromStorage(this.dappSettings.storage);break;case"injected":tt=yield InjectedProvider.fromStorage(this.dappSettings.storage);break;default:if(et)tt=this.createProvider(et);else return}}catch{this.tracker.trackConnectionRestoringError("Provider is not restored"),yield this.bridgeConnectionStorage.removeConnection(),tt==null||tt.closeConnection(),tt=null;return}if(j.signal.aborted){tt==null||tt.closeConnection(),this.tracker.trackConnectionRestoringError("Connection restoring was aborted");return}if(!tt){logError$1("Provider is not restored"),this.tracker.trackConnectionRestoringError("Provider is not restored");return}(k=this.provider)===null||k===void 0||k.closeConnection(),this.provider=tt,tt.listen(this.walletEventsListener.bind(this));const rt=()=>{this.tracker.trackConnectionRestoringError("Connection restoring was aborted"),tt==null||tt.closeConnection(),tt=null};j.signal.addEventListener("abort",rt);const nt=callForSuccess(at=>__awaiter(this,void 0,void 0,function*(){yield tt==null?void 0:tt.restoreConnection({openingDeadlineMS:_==null?void 0:_.openingDeadlineMS,signal:at.signal}),j.signal.removeEventListener("abort",rt),this.connected?this.tracker.trackConnectionRestoringCompleted(this.wallet):this.tracker.trackConnectionRestoringError("Connection restoring failed")}),{attempts:Number.MAX_SAFE_INTEGER,delayMs:2e3,signal:_==null?void 0:_.signal}),ot=new Promise(at=>setTimeout(()=>at(),12e3));return Promise.race([nt,ot])})}sendTransaction(_,d){return __awaiter(this,void 0,void 0,function*(){const k={};typeof d=="function"?k.onRequestSent=d:(k.onRequestSent=d==null?void 0:d.onRequestSent,k.signal=d==null?void 0:d.signal);const j=createAbortController(k==null?void 0:k.signal);if(j.signal.aborted)throw new TonConnectError("Transaction sending was aborted");this.checkConnection(),checkSendTransactionSupport(this.wallet.device.features,{requiredMessagesNumber:_.messages.length}),this.tracker.trackTransactionSentForSignature(this.wallet,_);const{validUntil:$}=_,et=__rest(_,["validUntil"]),tt=_.from||this.account.address,rt=_.network||this.account.chain,nt=yield this.provider.sendRequest(sendTransactionParser.convertToRpcRequest(Object.assign(Object.assign({},et),{valid_until:$,from:tt,network:rt})),{onRequestSent:k.onRequestSent,signal:j.signal});if(sendTransactionParser.isError(nt))return this.tracker.trackTransactionSigningFailed(this.wallet,_,nt.error.message,nt.error.code),sendTransactionParser.parseAndThrowError(nt);const ot=sendTransactionParser.convertFromRpcResponse(nt);return this.tracker.trackTransactionSigned(this.wallet,_,ot),ot})}disconnect(_){var d;return __awaiter(this,void 0,void 0,function*(){if(!this.connected)throw new WalletNotConnectedError;const k=createAbortController(_==null?void 0:_.signal),j=this.abortController;if(this.abortController=k,k.signal.aborted)throw new TonConnectError("Disconnect was aborted");this.onWalletDisconnected("dapp"),yield(d=this.provider)===null||d===void 0?void 0:d.disconnect({signal:k.signal}),j==null||j.abort()})}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()})}catch(d){logError$1("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("wallet")}}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,this.tracker.trackConnectionCompleted(j)}onWalletConnectError(_){const d=connectErrorsParser.parseError(_);if(this.statusChangeErrorSubscriptions.forEach(k=>k(d)),logDebug$1(d),this.tracker.trackConnectionError(_.message,_.code),d instanceof ManifestNotFoundError||d instanceof ManifestContentErrorError)throw logError$1(d),d}onWalletDisconnected(_){this.tracker.trackDisconnection(this.wallet,_),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;Gt+=2}},Ln=function(pn,Vt){for(var Gt in Vt)if(typeof Vt[Gt]===nt&&Vt[Gt].length>0){for(var wn=0;wn2&&(Zn[it]="iPad",Zn[ut]=st),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]&&Pn&&Pn.platform&&Pn.platform!="Unknown"&&(Zn[dt]=Pn.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>St?Tn(Zn,St):Zn,this},this.setUA(wn),this};Bn.VERSION=j,Bn.BROWSER=bn([dt,ft,at]),Bn.CPU=bn([lt]),Bn.DEVICE=bn([it,ht,ut,ct,pt,wt,st,yt,vt]),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 Hn=new Bn;Nn.ua=Hn.getResult(),Nn.ua.get=function(){return Hn.getUA()},Nn.ua.set=function(pn){Hn.setUA(pn);var Vt=Hn.getResult();for(var Gt in Vt)Nn.ua[Gt]=Vt[Gt]}}})(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 @@ -1093,7 +1093,7 @@ PERFORMANCE OF THIS SOFTWARE. width: 16px; `,ButtonStyled=styled(Button)` margin-top: 32px; -`,ActionModal=b=>{const _=useDataAttributes(b),d=useContext(TonConnectUiContext),[k,j]=createSignal(!0),[$,et]=createSignal(!1);createEffect(()=>{const ot=action();et(!!ot&&"sent"in ot&&ot.sent)});let tt;d!=null&&d.wallet&&"universalLink"in d.wallet&&(d.wallet.openMethod==="universal-link"||isTelegramUrl(d.wallet.universalLink)&&isInTMA())&&(tt=d.wallet.universalLink);let rt;d!=null&&d.wallet&&"deepLink"in d.wallet&&(d.wallet.openMethod==="custom-deeplink"||isTelegramUrl(d.wallet.deepLink)&&isInTMA())&&(rt=d.wallet.deepLink);const nt=()=>{const ot=action(),at="returnStrategy"in ot?ot.returnStrategy:appState.returnStrategy,it=!k();j(!1),isTelegramUrl(tt)?redirectToTelegram(tt,{returnStrategy:at,twaReturnUrl:"twaReturnUrl"in ot?ot.twaReturnUrl:appState.twaReturnUrl,forceRedirect:it}):redirectToWallet(tt,rt,{returnStrategy:at,forceRedirect:it},()=>{})};return createComponent(ActionModalStyled,mergeProps(_,{get children(){return[createMemo(()=>b.icon),createComponent(H1Styled,{get translationKey(){return b.headerTranslationKey},get translationValues(){return b.headerTranslationValues}}),createComponent(TextStyled,{get translationKey(){return b.textTranslationKey},get translationValues(){return b.textTranslationValues}}),createComponent(Show,{get when(){return!$()&&(b.showButton==="open-wallet"&&tt||b.showButton!=="open-wallet")},get children(){return createComponent(LoaderButtonStyled,{disabled:!0,"data-tc-connect-button-loading":"true",get children(){return createComponent(LoaderIconStyled,{})}})}}),createComponent(Show,{get when(){return $()},get children(){return[createComponent(Show,{get when(){return b.showButton!=="open-wallet"},get children(){return createComponent(ButtonStyled,{onClick:()=>b.onClose(),get children(){return createComponent(Translation,{translationKey:"common.close",children:"Close"})}})}}),createComponent(Show,{get when(){return b.showButton==="open-wallet"&&tt},get children(){return createComponent(ButtonStyled,{onClick:nt,get children(){return createComponent(Translation,{translationKey:"common.openWallet",children:"Open wallet"})}})}})]}})]}}))},ConfirmTransactionModal=b=>{const _=useContext(TonConnectUiContext),[d]=useI18n(),k=()=>_.wallet&&"name"in _.wallet?_.wallet.name:d("common.yourWallet",{},"Your wallet");return createComponent(ActionModal,{headerTranslationKey:"actionModal.confirmTransaction.header",get headerTranslationValues(){return{name:k()}},textTranslationKey:"actionModal.confirmTransaction.text",get icon(){return createComponent(LoaderIcon,{size:"m"})},onClose:()=>b.onClose(),showButton:"open-wallet","data-tc-confirm-modal":"true"})},TransactionCanceledModal=b=>createComponent(ActionModal,{headerTranslationKey:"actionModal.transactionCanceled.header",textTranslationKey:"actionModal.transactionCanceled.text",get icon(){return createComponent(ErrorIcon,{size:"m"})},onClose:()=>b.onClose(),"data-tc-transaction-canceled-modal":"true"}),TransactionSentModal=b=>createComponent(ActionModal,{headerTranslationKey:"actionModal.transactionSent.header",textTranslationKey:"actionModal.transactionSent.text",get icon(){return createComponent(SuccessIcon,{size:"m"})},onClose:()=>b.onClose(),"data-tc-transaction-sent-modal":"true"}),ActionsModal=()=>createComponent(Modal,{get opened(){var b;return createMemo(()=>action()!==null)()&&((b=action())==null?void 0:b.openModal)===!0},get enableAndroidBackHandler(){return appState.enableAndroidBackHandler},onClose:()=>setAction(null),"data-tc-actions-modal-container":"true",get children(){return createComponent(Switch,{get children(){return[createComponent(Match,{get when(){return action().name==="transaction-sent"},get children(){return createComponent(TransactionSentModal,{onClose:()=>setAction(null)})}}),createComponent(Match,{get when(){return action().name==="transaction-canceled"},get children(){return createComponent(TransactionCanceledModal,{onClose:()=>setAction(null)})}}),createComponent(Match,{get when(){return action().name==="confirm-transaction"},get children(){return createComponent(ConfirmTransactionModal,{onClose:()=>setAction(null)})}})]}})}}),SingleWalletModal=()=>{const{locale:b}=useI18n()[1];createEffect(()=>b(appState.language)),createEffect(()=>{getSingleWalletModalIsOpened()&&updateIsMobile()});const _=useContext(ConnectorContext),d=useContext(TonConnectUiContext),[k,j]=createSignal(!1),$=()=>{var nt;return((nt=appState.connectRequestParameters)==null?void 0:nt.state)==="loading"},et=createMemo(()=>{var nt;if(!$())return(nt=appState.connectRequestParameters)==null?void 0:nt.value}),tt=nt=>{d.closeSingleWalletModal(nt)},rt=_.onStatusChange(nt=>{nt&&tt("wallet-selected")});return onCleanup(rt),onCleanup(()=>{j(!1)}),createComponent(StyledModal,{get opened(){return getSingleWalletModalIsOpened()},get enableAndroidBackHandler(){return appState.enableAndroidBackHandler},onClose:()=>tt("action-cancelled"),onClickQuestion:()=>j(nt=>!nt),"data-tc-wallets-modal-container":"true",get children(){return[createComponent(Show,{get when(){return k()},get children(){return createComponent(InfoModal,{onBackClick:()=>j(!1)})}}),createComponent(Show,{get when(){return!k()},get children(){return[createComponent(Show,{get when(){return $()},get children(){return[createComponent(H1Styled$8,{translationKey:"walletModal.loading",children:"Wallets list is loading"}),createComponent(LoaderContainerStyled,{get children(){return createComponent(LoaderIcon,{size:"m"})}})]}}),createComponent(Show,{get when(){return!$()},get children(){return createComponent(Dynamic,{get component(){return isMobile()?MobileConnectionModal:DesktopConnectionModal},get wallet(){return getSingleWalletModalWalletInfo()},get additionalRequest(){return et()},onBackClick:()=>{},backDisabled:!0})}})]}})]}})},App$1=b=>{const _=createI18nContext(i18nDictionary,appState.language);return defineStylesRoot(),fixMobileSafariActiveTransition(),createComponent(I18nContext.Provider,{value:_,get children(){return createComponent(TonConnectUiContext.Provider,{get value(){return b.tonConnectUI},get children(){return createComponent(ConnectorContext.Provider,{get value(){return appState.connector},get children(){return[createComponent(GlobalStyles,{}),createComponent(ThemeProvider,{theme:themeState,get children(){return[createComponent(Show,{get when(){return appState.buttonRootId},get children(){return createComponent(Portal,{get mount(){return document.getElementById(appState.buttonRootId)},get children(){return createComponent(AccountButton,{})}})}}),createComponent(Dynamic,{component:globalStylesTag,get children(){return[createComponent(WalletsModal,{}),createComponent(SingleWalletModal,{}),createComponent(ActionsModal,{})]}})]}})]}})}})}})},widgetController={openWalletsModal:()=>void setTimeout(()=>setWalletsModalState({status:"opened",closeReason:null})),closeWalletsModal:b=>void setTimeout(()=>setWalletsModalState({status:"closed",closeReason:b})),openSingleWalletModal:b=>{setTimeout(()=>setSingleWalletModalState({status:"opened",closeReason:null,walletInfo:b}))},closeSingleWalletModal:b=>void setTimeout(()=>setSingleWalletModalState({status:"closed",closeReason:b})),setAction:b=>void setTimeout(()=>setAction(b)),clearAction:()=>void setTimeout(()=>setAction(null)),getSelectedWalletInfo:()=>lastSelectedWalletInfo(),removeSelectedWalletInfo:()=>setLastSelectedWalletInfo(null),renderApp:(b,_)=>render(()=>createComponent(App$1,{tonConnectUI:_}),document.getElementById(b))};class WalletsModalManager{constructor(_){__publicField(this,"connector"),__publicField(this,"setConnectRequestParametersCallback"),__publicField(this,"consumers",[]),__publicField(this,"tracker"),__publicField(this,"state",walletsModalState()),this.connector=_.connector,this.tracker=_.tracker,this.setConnectRequestParametersCallback=_.setConnectRequestParametersCallback,createEffect(()=>{const d=walletsModalState();this.state=d,this.consumers.forEach(k=>k(d))})}open(){return __async(this,null,function*(){this.tracker.trackConnectionStarted();const d=(yield this.connector.getWallets()).find(isWalletInfoCurrentlyEmbedded);return d?this.connectEmbeddedWallet(d):this.openWalletsModal()})}close(_="action-cancelled"){_==="action-cancelled"&&this.tracker.trackConnectionError("Connection was cancelled"),widgetController.closeWalletsModal(_)}onStateChange(_){return this.consumers.push(_),()=>{this.consumers=this.consumers.filter(d=>d!==_)}}connectEmbeddedWallet(_){const d=j=>{setLastSelectedWalletInfo(_),this.connector.connect({jsBridgeKey:_.jsBridgeKey},j)},k=appState.connectRequestParameters;(k==null?void 0:k.state)==="loading"?this.setConnectRequestParametersCallback(d):d(k==null?void 0:k.value)}openWalletsModal(){return __async(this,null,function*(){return isInTMA()&&sendExpand(),widgetController.openWalletsModal(),new Promise(_=>{const d=this.onStateChange(k=>{const{status:j}=k;j==="opened"&&(d(),_())})})})}}class TransactionModalManager{constructor(_){__publicField(this,"connector"),__publicField(this,"consumers",[]),this.connector=_.connector,createEffect(()=>{const d=action();this.consumers.forEach(k=>k(d))})}onStateChange(_){return this.consumers.push(_),()=>{this.consumers=this.consumers.filter(d=>d!==_)}}}class SingleWalletModalManager{constructor(_){__publicField(this,"connector"),__publicField(this,"setConnectRequestParametersCallback"),__publicField(this,"consumers",[]),__publicField(this,"tracker"),__publicField(this,"state",singleWalletModalState()),this.connector=_.connector,this.tracker=_.tracker,this.setConnectRequestParametersCallback=_.setConnectRequestParametersCallback,createEffect(()=>{const d=singleWalletModalState();this.state=d,this.consumers.forEach(k=>k(d))})}open(_){return __async(this,null,function*(){this.tracker.trackConnectionStarted();const d=yield this.connector.getWallets(),k=applyWalletsListConfiguration(d,appState.walletsListConfiguration),j=k.find(isWalletInfoCurrentlyEmbedded);if(!!j)return this.connectEmbeddedWallet(j);const tt=k.filter(isWalletInfoRemote).find(ot=>eqWalletName(ot,_));if(!!tt)return this.openSingleWalletModal(tt);const nt=`Trying to open modal window with unknown wallet "${_}".`;throw this.tracker.trackConnectionError(nt),new TonConnectUIError(nt)})}close(_="action-cancelled"){_==="action-cancelled"&&this.tracker.trackConnectionError("Connection was cancelled"),widgetController.closeSingleWalletModal("action-cancelled")}onStateChange(_){return this.consumers.push(_),()=>{this.consumers=this.consumers.filter(d=>d!==_)}}connectEmbeddedWallet(_){const d=j=>{setLastSelectedWalletInfo(_),this.connector.connect({jsBridgeKey:_.jsBridgeKey},j)},k=appState.connectRequestParameters;(k==null?void 0:k.state)==="loading"?this.setConnectRequestParametersCallback(d):d(k==null?void 0:k.value)}openSingleWalletModal(_){return __async(this,null,function*(){return isInTMA()&&sendExpand(),widgetController.openSingleWalletModal(_),new Promise(d=>{const k=this.onStateChange(j=>{const{status:$}=j;$==="opened"&&(k(),d())})})})}}class TonConnectUITracker{constructor(_){__publicField(this,"eventPrefix","ton-connect-ui-"),__publicField(this,"tonConnectUiVersion"),__publicField(this,"tonConnectSdkVersion",null),__publicField(this,"eventDispatcher");var d;this.eventDispatcher=(d=_==null?void 0:_.eventDispatcher)!=null?d:new BrowserEventDispatcher,this.tonConnectUiVersion=_.tonConnectUiVersion,this.init().catch()}get version(){return createVersionInfo({ton_connect_sdk_lib:this.tonConnectSdkVersion,ton_connect_ui_lib:this.tonConnectUiVersion})}init(){return __async(this,null,function*(){try{yield this.setRequestVersionHandler(),this.tonConnectSdkVersion=yield this.requestTonConnectSdkVersion()}catch{}})}setRequestVersionHandler(){return __async(this,null,function*(){yield this.eventDispatcher.addEventListener("ton-connect-ui-request-version",()=>__async(this,null,function*(){yield this.eventDispatcher.dispatchEvent("ton-connect-ui-response-version",createResponseVersionEvent(this.tonConnectUiVersion))}))})}requestTonConnectSdkVersion(){return __async(this,null,function*(){return new Promise((_,d)=>__async(this,null,function*(){try{yield this.eventDispatcher.addEventListener("ton-connect-response-version",k=>{_(k.detail.version)},{once:!0}),yield this.eventDispatcher.dispatchEvent("ton-connect-request-version",createRequestVersionEvent())}catch(k){d(k)}}))})}dispatchUserActionEvent(_){var d;try{(d=this.eventDispatcher)==null||d.dispatchEvent(`${this.eventPrefix}${_.type}`,_).catch()}catch{}}trackConnectionStarted(..._){try{const d=createConnectionStartedEvent(this.version,..._);this.dispatchUserActionEvent(d)}catch{}}trackConnectionCompleted(..._){try{const d=createConnectionCompletedEvent(this.version,..._);this.dispatchUserActionEvent(d)}catch{}}trackConnectionError(..._){try{const d=createConnectionErrorEvent(this.version,..._);this.dispatchUserActionEvent(d)}catch{}}trackConnectionRestoringStarted(..._){try{const d=createConnectionRestoringStartedEvent(this.version,..._);this.dispatchUserActionEvent(d)}catch{}}trackConnectionRestoringCompleted(..._){try{const d=createConnectionRestoringCompletedEvent(this.version,..._);this.dispatchUserActionEvent(d)}catch{}}trackConnectionRestoringError(..._){try{const d=createConnectionRestoringErrorEvent(this.version,..._);this.dispatchUserActionEvent(d)}catch{}}trackDisconnection(..._){try{const d=createDisconnectionEvent(this.version,..._);this.dispatchUserActionEvent(d)}catch{}}trackTransactionSentForSignature(..._){try{const d=createTransactionSentForSignatureEvent(this.version,..._);this.dispatchUserActionEvent(d)}catch{}}trackTransactionSigned(..._){try{const d=createTransactionSignedEvent(this.version,..._);this.dispatchUserActionEvent(d)}catch{}}trackTransactionSigningFailed(..._){try{const d=createTransactionSigningFailedEvent(this.version,..._);this.dispatchUserActionEvent(d)}catch{}}}const tonConnectUiVersion="2.0.7-beta.2";class TonConnectUI{constructor(_){if(__publicField(this,"walletInfoStorage",new WalletInfoStorage),__publicField(this,"preferredWalletStorage",new PreferredWalletStorage),__publicField(this,"tracker"),__publicField(this,"walletInfo",null),__publicField(this,"systemThemeChangeUnsubscribe",null),__publicField(this,"actionsConfiguration"),__publicField(this,"walletsList"),__publicField(this,"connectRequestParametersCallback"),__publicField(this,"connector"),__publicField(this,"modal"),__publicField(this,"singleWalletModal"),__publicField(this,"transactionModal"),__publicField(this,"connectionRestored",Promise.resolve(!1)),_&&"connector"in _&&_.connector)this.connector=_.connector;else if(_&&"manifestUrl"in _&&_.manifestUrl)this.connector=new TonConnect({manifestUrl:_.manifestUrl,eventDispatcher:_==null?void 0:_.eventDispatcher});else throw new TonConnectUIError("You have to specify a `manifestUrl` or a `connector` in the options.");this.tracker=new TonConnectUITracker({eventDispatcher:_==null?void 0:_.eventDispatcher,tonConnectUiVersion}),this.modal=new WalletsModalManager({connector:this.connector,tracker:this.tracker,setConnectRequestParametersCallback:j=>{this.connectRequestParametersCallback=j}}),this.singleWalletModal=new SingleWalletModalManager({connector:this.connector,tracker:this.tracker,setConnectRequestParametersCallback:j=>{this.connectRequestParametersCallback=j}}),this.transactionModal=new TransactionModalManager({connector:this.connector}),this.walletsList=this.getWallets(),this.walletsList.then(j=>preloadImages(uniq(j.map($=>$.imageUrl))));const d=this.normalizeWidgetRoot(_==null?void 0:_.widgetRootId);this.subscribeToWalletChange(),(_==null?void 0:_.restoreConnection)!==!1&&(this.connectionRestored=createMacrotaskAsync(()=>__async(this,null,function*(){return this.tracker.trackConnectionRestoringStarted(),yield this.connector.restoreConnection(),this.connector.connected?this.tracker.trackConnectionRestoringCompleted(this.wallet):(this.tracker.trackConnectionRestoringError("Connection was not restored"),this.walletInfoStorage.removeWalletInfo()),this.connector.connected}))),this.uiOptions=mergeOptions(_,{uiPreferences:{theme:"SYSTEM"}});const k=this.preferredWalletStorage.getPreferredWalletAppName();setAppState({connector:this.connector,preferredWalletAppName:k}),widgetController.renderApp(d,this)}static getWallets(){return TonConnect.getWallets()}get connected(){return this.connector.connected}get account(){return this.connector.account}get wallet(){return this.connector.wallet?__spreadValues$1(__spreadValues$1({},this.connector.wallet),this.walletInfo):null}set uiOptions(_){var d,k,j,$,et;this.checkButtonRootExist(_.buttonRootId),this.actionsConfiguration=_.actionsConfiguration,(d=_.uiPreferences)!=null&&d.theme?((k=_.uiPreferences)==null?void 0:k.theme)!=="SYSTEM"?((j=this.systemThemeChangeUnsubscribe)==null||j.call(this),setTheme(_.uiPreferences.theme,_.uiPreferences.colorsSet)):(setTheme(getSystemTheme(),_.uiPreferences.colorsSet),this.systemThemeChangeUnsubscribe||(this.systemThemeChangeUnsubscribe=subscribeToThemeChange(setTheme))):($=_.uiPreferences)!=null&&$.colorsSet&&setColors(_.uiPreferences.colorsSet),(et=_.uiPreferences)!=null&&et.borderRadius&&setBorderRadius(_.uiPreferences.borderRadius),setAppState(tt=>{var rt,nt;const ot=mergeOptions(__spreadValues$1(__spreadValues$1(__spreadValues$1(__spreadValues$1({},_.language&&{language:_.language}),!!((rt=_.actionsConfiguration)!=null&&rt.returnStrategy)&&{returnStrategy:_.actionsConfiguration.returnStrategy}),!!((nt=_.actionsConfiguration)!=null&&nt.twaReturnUrl)&&{twaReturnUrl:_.actionsConfiguration.twaReturnUrl}),!!_.walletsListConfiguration&&{walletsListConfiguration:_.walletsListConfiguration}),unwrap(tt));return _.buttonRootId!==void 0&&(ot.buttonRootId=_.buttonRootId),_.enableAndroidBackHandler!==void 0&&(ot.enableAndroidBackHandler=_.enableAndroidBackHandler),ot})}setConnectRequestParameters(_){var d;setAppState({connectRequestParameters:_}),((_==null?void 0:_.state)==="ready"||!_)&&((d=this.connectRequestParametersCallback)==null||d.call(this,_==null?void 0:_.value))}getWallets(){return __async(this,null,function*(){return this.connector.getWallets()})}onStatusChange(_,d){return this.connector.onStatusChange(k=>__async(this,null,function*(){if(k){const j=yield this.getSelectedWalletInfo(k);_(__spreadValues$1(__spreadValues$1({},k),j||this.walletInfoStorage.getWalletInfo()))}else _(k)}),d)}openModal(){return __async(this,null,function*(){return this.modal.open()})}closeModal(_){this.modal.close(_)}onModalStateChange(_){return this.modal.onStateChange(_)}get modalState(){return this.modal.state}openSingleWalletModal(_){return __async(this,null,function*(){return this.singleWalletModal.open(_)})}closeSingleWalletModal(_){this.singleWalletModal.close(_)}onSingleWalletModalStateChange(_){return this.singleWalletModal.onStateChange(_)}get singleWalletModalState(){return this.singleWalletModal.state}connectWallet(){return __async(this,null,function*(){const d=(yield this.getWallets()).find(isWalletInfoCurrentlyEmbedded);return d?yield this.connectEmbeddedWallet(d):yield this.connectExternalWallet()})}disconnect(){return this.tracker.trackDisconnection(this.wallet,"dapp"),widgetController.clearAction(),widgetController.removeSelectedWalletInfo(),this.walletInfoStorage.removeWalletInfo(),this.connector.disconnect()}sendTransaction(_,d){return __async(this,null,function*(){if(this.tracker.trackTransactionSentForSignature(this.wallet,_),!this.connected)throw this.tracker.trackTransactionSigningFailed(this.wallet,_,"Wallet was not connected"),new TonConnectUIError("Connect wallet to send a transaction.");isInTMA()&&sendExpand();const{notifications:k,modals:j,returnStrategy:$,twaReturnUrl:et,skipRedirectToWallet:tt}=this.getModalsAndNotificationsConfiguration(d);widgetController.setAction({name:"confirm-transaction",showNotification:k.includes("before"),openModal:j.includes("before"),sent:!1});const rt=()=>{nt.signal.aborted||(widgetController.setAction({name:"confirm-transaction",showNotification:k.includes("before"),openModal:j.includes("before"),sent:!0}),this.walletInfo&&"universalLink"in this.walletInfo&&(this.walletInfo.openMethod==="universal-link"||this.walletInfo.openMethod==="custom-deeplink")&&(isTelegramUrl(this.walletInfo.universalLink)?redirectToTelegram(this.walletInfo.universalLink,{returnStrategy:$,twaReturnUrl:et||appState.twaReturnUrl,forceRedirect:!1}):redirectToWallet(this.walletInfo.universalLink,this.walletInfo.deepLink,{returnStrategy:$,forceRedirect:!1},()=>{})))},nt=new AbortController,ot=this.onTransactionModalStateChange(at=>{at!=null&&at.openModal||(ot(),at||nt.abort())});try{const at=yield this.waitForSendTransaction({transaction:_,signal:nt.signal},rt);return this.tracker.trackTransactionSigned(this.wallet,_,at),widgetController.setAction({name:"transaction-sent",showNotification:k.includes("success"),openModal:j.includes("success")}),at}catch(at){throw widgetController.setAction({name:"transaction-canceled",showNotification:k.includes("error"),openModal:j.includes("error")}),at instanceof TonConnectError?at:(console.error(at),new TonConnectUIError("Unhandled error:"+at))}finally{ot()}})}connectEmbeddedWallet(_){return __async(this,null,function*(){const d=j=>{setLastSelectedWalletInfo(_),this.connector.connect({jsBridgeKey:_.jsBridgeKey},j)},k=appState.connectRequestParameters;return(k==null?void 0:k.state)==="loading"?this.connectRequestParametersCallback=d:d(k==null?void 0:k.value),yield this.waitForWalletConnection({ignoreErrors:!1})})}connectExternalWallet(){return __async(this,null,function*(){const _=new AbortController;widgetController.openWalletsModal();const d=this.onModalStateChange(k=>{const{status:j,closeReason:$}=k;j!=="opened"&&(d(),$==="action-cancelled"&&_.abort())});return yield this.waitForWalletConnection({ignoreErrors:!0,signal:_.signal})})}waitForWalletConnection(_){return __async(this,null,function*(){return new Promise((d,k)=>{this.tracker.trackConnectionStarted();const{ignoreErrors:j=!1,signal:$=null}=_;if($&&$.aborted)return this.tracker.trackConnectionError("Connection was cancelled"),k(new TonConnectUIError("Wallet was not connected"));const et=nt=>__async(this,null,function*(){if(nt)this.tracker.trackConnectionCompleted(nt),rt(),d(nt);else{if(this.tracker.trackConnectionError("Connection was cancelled"),j)return;rt(),k(new TonConnectUIError("Wallet was not connected"))}}),tt=nt=>{this.tracker.trackConnectionError(nt.message),!j&&(rt(),k(nt))},rt=this.onStatusChange(nt=>et(nt),nt=>tt(nt));$&&$.addEventListener("abort",()=>{rt(),k(new TonConnectUIError("Wallet was not connected"))},{once:!0})})})}waitForSendTransaction(_,d){return __async(this,null,function*(){return new Promise((k,j)=>{const{transaction:$,signal:et}=_;if(et.aborted)return this.tracker.trackTransactionSigningFailed(this.wallet,$,"Transaction was cancelled"),j(new TonConnectUIError("Transaction was not sent"));const tt=ot=>__async(this,null,function*(){k(ot)}),rt=ot=>{j(ot)},nt=()=>{this.tracker.trackTransactionSigningFailed(this.wallet,$,"Transaction was cancelled"),j(new TonConnectUIError("Transaction was not sent"))};et.addEventListener("abort",nt,{once:!0}),this.connector.sendTransaction($,{onRequestSent:d,signal:et}).then(ot=>(et.removeEventListener("abort",nt),tt(ot))).catch(ot=>(et.removeEventListener("abort",nt),rt(ot)))})})}onTransactionModalStateChange(_){return this.transactionModal.onStateChange(_)}subscribeToWalletChange(){this.connector.onStatusChange(_=>__async(this,null,function*(){var d;_?(yield this.updateWalletInfo(_),this.setPreferredWalletAppName(((d=this.walletInfo)==null?void 0:d.appName)||_.device.appName)):this.walletInfoStorage.removeWalletInfo()}))}setPreferredWalletAppName(_){this.preferredWalletStorage.setPreferredWalletAppName(_),setAppState({preferredWalletAppName:_})}getSelectedWalletInfo(_){return __async(this,null,function*(){let d=widgetController.getSelectedWalletInfo();if(!d)return null;let k;if("name"in d)k=d;else{const $=applyWalletsListConfiguration(yield this.walletsList,appState.walletsListConfiguration).find(et=>eqWalletName(et,_.device.appName));if(!$)throw new TonConnectUIError(`Cannot find WalletInfo for the '${_.device.appName}' wallet`);k=__spreadValues$1(__spreadValues$1({},$),d)}return k})}updateWalletInfo(_){return __async(this,null,function*(){const d=yield this.getSelectedWalletInfo(_);if(d){this.walletInfo=d,this.walletInfoStorage.setWalletInfo(d);return}const k=this.walletInfoStorage.getWalletInfo();if(k){this.walletInfo=k;return}this.walletInfo=(yield this.walletsList).find(j=>eqWalletName(j,_.device.appName))||null})}normalizeWidgetRoot(_){if(!_||!document.getElementById(_)){_="tc-widget-root";const d=document.createElement("div");d.id=_,document.body.appendChild(d)}return _}checkButtonRootExist(_){if(_!=null&&!document.getElementById(_))throw new TonConnectUIError(`${_} element not found in the document.`)}getModalsAndNotificationsConfiguration(_){var d,k,j,$,et,tt;const rt=["before","success","error"];let nt=rt;(d=this.actionsConfiguration)!=null&&d.notifications&&((k=this.actionsConfiguration)==null?void 0:k.notifications)!=="all"&&(nt=this.actionsConfiguration.notifications),_!=null&&_.notifications&&(_.notifications==="all"?nt=rt:nt=_.notifications);let ot=["before"];(j=this.actionsConfiguration)!=null&&j.modals&&(this.actionsConfiguration.modals==="all"?ot=rt:ot=this.actionsConfiguration.modals),_!=null&&_.modals&&(_.modals==="all"?ot=rt:ot=_.modals);const at=(_==null?void 0:_.returnStrategy)||(($=this.actionsConfiguration)==null?void 0:$.returnStrategy)||"back",it=(_==null?void 0:_.twaReturnUrl)||((et=this.actionsConfiguration)==null?void 0:et.twaReturnUrl);let dt=(_==null?void 0:_.skipRedirectToWallet)||((tt=this.actionsConfiguration)==null?void 0:tt.skipRedirectToWallet)||"ios";return isInTMA()&&(dt="never"),{notifications:nt,modals:ot,returnStrategy:at,twaReturnUrl:it,skipRedirectToWallet:dt}}}var __defProp=Object.defineProperty,__getOwnPropSymbols=Object.getOwnPropertySymbols,__hasOwnProp=Object.prototype.hasOwnProperty,__propIsEnum=Object.prototype.propertyIsEnumerable,__defNormalProp=(b,_,d)=>_ in b?__defProp(b,_,{enumerable:!0,configurable:!0,writable:!0,value:d}):b[_]=d,__spreadValues=(b,_)=>{for(var d in _||(_={}))__hasOwnProp.call(_,d)&&__defNormalProp(b,d,_[d]);if(__getOwnPropSymbols)for(var d of __getOwnPropSymbols(_))__propIsEnum.call(_,d)&&__defNormalProp(b,d,_[d]);return b},__objRest=(b,_)=>{var d={};for(var k in b)__hasOwnProp.call(b,k)&&_.indexOf(k)<0&&(d[k]=b[k]);if(b!=null&&__getOwnPropSymbols)for(var k of __getOwnPropSymbols(b))_.indexOf(k)<0&&__propIsEnum.call(b,k)&&(d[k]=b[k]);return d},jsxRuntime={exports:{}},reactJsxRuntime_production_min={};/** +`,ActionModal=b=>{const _=useDataAttributes(b),d=useContext(TonConnectUiContext),[k,j]=createSignal(!0),[$,et]=createSignal(!1);createEffect(()=>{const ot=action();et(!!ot&&"sent"in ot&&ot.sent)});let tt;d!=null&&d.wallet&&"universalLink"in d.wallet&&(d.wallet.openMethod==="universal-link"||isTelegramUrl(d.wallet.universalLink)&&isInTMA())&&(tt=d.wallet.universalLink);let rt;d!=null&&d.wallet&&"deepLink"in d.wallet&&(d.wallet.openMethod==="custom-deeplink"||isTelegramUrl(d.wallet.deepLink)&&isInTMA())&&(rt=d.wallet.deepLink);const nt=()=>{const ot=action(),at="returnStrategy"in ot?ot.returnStrategy:appState.returnStrategy,it=!k();j(!1),isTelegramUrl(tt)?redirectToTelegram(tt,{returnStrategy:at,twaReturnUrl:"twaReturnUrl"in ot?ot.twaReturnUrl:appState.twaReturnUrl,forceRedirect:it}):redirectToWallet(tt,rt,{returnStrategy:at,forceRedirect:it},()=>{})};return createComponent(ActionModalStyled,mergeProps(_,{get children(){return[createMemo(()=>b.icon),createComponent(H1Styled,{get translationKey(){return b.headerTranslationKey},get translationValues(){return b.headerTranslationValues}}),createComponent(TextStyled,{get translationKey(){return b.textTranslationKey},get translationValues(){return b.textTranslationValues}}),createComponent(Show,{get when(){return!$()&&(b.showButton==="open-wallet"&&tt||b.showButton!=="open-wallet")},get children(){return createComponent(LoaderButtonStyled,{disabled:!0,"data-tc-connect-button-loading":"true",get children(){return createComponent(LoaderIconStyled,{})}})}}),createComponent(Show,{get when(){return $()},get children(){return[createComponent(Show,{get when(){return b.showButton!=="open-wallet"},get children(){return createComponent(ButtonStyled,{onClick:()=>b.onClose(),get children(){return createComponent(Translation,{translationKey:"common.close",children:"Close"})}})}}),createComponent(Show,{get when(){return b.showButton==="open-wallet"&&tt},get children(){return createComponent(ButtonStyled,{onClick:nt,get children(){return createComponent(Translation,{translationKey:"common.openWallet",children:"Open wallet"})}})}})]}})]}}))},ConfirmTransactionModal=b=>{const _=useContext(TonConnectUiContext),[d]=useI18n(),k=()=>_.wallet&&"name"in _.wallet?_.wallet.name:d("common.yourWallet",{},"Your wallet");return createComponent(ActionModal,{headerTranslationKey:"actionModal.confirmTransaction.header",get headerTranslationValues(){return{name:k()}},textTranslationKey:"actionModal.confirmTransaction.text",get icon(){return createComponent(LoaderIcon,{size:"m"})},onClose:()=>b.onClose(),showButton:"open-wallet","data-tc-confirm-modal":"true"})},TransactionCanceledModal=b=>createComponent(ActionModal,{headerTranslationKey:"actionModal.transactionCanceled.header",textTranslationKey:"actionModal.transactionCanceled.text",get icon(){return createComponent(ErrorIcon,{size:"m"})},onClose:()=>b.onClose(),"data-tc-transaction-canceled-modal":"true"}),TransactionSentModal=b=>createComponent(ActionModal,{headerTranslationKey:"actionModal.transactionSent.header",textTranslationKey:"actionModal.transactionSent.text",get icon(){return createComponent(SuccessIcon,{size:"m"})},onClose:()=>b.onClose(),"data-tc-transaction-sent-modal":"true"}),ActionsModal=()=>createComponent(Modal,{get opened(){var b;return createMemo(()=>action()!==null)()&&((b=action())==null?void 0:b.openModal)===!0},get enableAndroidBackHandler(){return appState.enableAndroidBackHandler},onClose:()=>setAction(null),"data-tc-actions-modal-container":"true",get children(){return createComponent(Switch,{get children(){return[createComponent(Match,{get when(){return action().name==="transaction-sent"},get children(){return createComponent(TransactionSentModal,{onClose:()=>setAction(null)})}}),createComponent(Match,{get when(){return action().name==="transaction-canceled"},get children(){return createComponent(TransactionCanceledModal,{onClose:()=>setAction(null)})}}),createComponent(Match,{get when(){return action().name==="confirm-transaction"},get children(){return createComponent(ConfirmTransactionModal,{onClose:()=>setAction(null)})}})]}})}}),SingleWalletModal=()=>{const{locale:b}=useI18n()[1];createEffect(()=>b(appState.language)),createEffect(()=>{getSingleWalletModalIsOpened()&&updateIsMobile()});const _=useContext(ConnectorContext),d=useContext(TonConnectUiContext),[k,j]=createSignal(!1),$=()=>{var nt;return((nt=appState.connectRequestParameters)==null?void 0:nt.state)==="loading"},et=createMemo(()=>{var nt;if(!$())return(nt=appState.connectRequestParameters)==null?void 0:nt.value}),tt=nt=>{d.closeSingleWalletModal(nt)},rt=_.onStatusChange(nt=>{nt&&tt("wallet-selected")});return onCleanup(rt),onCleanup(()=>{j(!1)}),createComponent(StyledModal,{get opened(){return getSingleWalletModalIsOpened()},get enableAndroidBackHandler(){return appState.enableAndroidBackHandler},onClose:()=>tt("action-cancelled"),onClickQuestion:()=>j(nt=>!nt),"data-tc-wallets-modal-container":"true",get children(){return[createComponent(Show,{get when(){return k()},get children(){return createComponent(InfoModal,{onBackClick:()=>j(!1)})}}),createComponent(Show,{get when(){return!k()},get children(){return[createComponent(Show,{get when(){return $()},get children(){return[createComponent(H1Styled$8,{translationKey:"walletModal.loading",children:"Wallets list is loading"}),createComponent(LoaderContainerStyled,{get children(){return createComponent(LoaderIcon,{size:"m"})}})]}}),createComponent(Show,{get when(){return!$()},get children(){return createComponent(Dynamic,{get component(){return isMobile()?MobileConnectionModal:DesktopConnectionModal},get wallet(){return getSingleWalletModalWalletInfo()},get additionalRequest(){return et()},onBackClick:()=>{},backDisabled:!0})}})]}})]}})},App$1=b=>{const _=createI18nContext(i18nDictionary,appState.language);return defineStylesRoot(),fixMobileSafariActiveTransition(),createComponent(I18nContext.Provider,{value:_,get children(){return createComponent(TonConnectUiContext.Provider,{get value(){return b.tonConnectUI},get children(){return createComponent(ConnectorContext.Provider,{get value(){return appState.connector},get children(){return[createComponent(GlobalStyles,{}),createComponent(ThemeProvider,{theme:themeState,get children(){return[createComponent(Show,{get when(){return appState.buttonRootId},get children(){return createComponent(Portal,{get mount(){return document.getElementById(appState.buttonRootId)},get children(){return createComponent(AccountButton,{})}})}}),createComponent(Dynamic,{component:globalStylesTag,get children(){return[createComponent(WalletsModal,{}),createComponent(SingleWalletModal,{}),createComponent(ActionsModal,{})]}})]}})]}})}})}})},widgetController={openWalletsModal:()=>void setTimeout(()=>setWalletsModalState({status:"opened",closeReason:null})),closeWalletsModal:b=>void setTimeout(()=>setWalletsModalState({status:"closed",closeReason:b})),openSingleWalletModal:b=>{setTimeout(()=>setSingleWalletModalState({status:"opened",closeReason:null,walletInfo:b}))},closeSingleWalletModal:b=>void setTimeout(()=>setSingleWalletModalState({status:"closed",closeReason:b})),setAction:b=>void setTimeout(()=>setAction(b)),clearAction:()=>void setTimeout(()=>setAction(null)),getSelectedWalletInfo:()=>lastSelectedWalletInfo(),removeSelectedWalletInfo:()=>setLastSelectedWalletInfo(null),renderApp:(b,_)=>render(()=>createComponent(App$1,{tonConnectUI:_}),document.getElementById(b))};class WalletsModalManager{constructor(_){__publicField(this,"connector"),__publicField(this,"setConnectRequestParametersCallback"),__publicField(this,"consumers",[]),__publicField(this,"tracker"),__publicField(this,"state",walletsModalState()),this.connector=_.connector,this.tracker=_.tracker,this.setConnectRequestParametersCallback=_.setConnectRequestParametersCallback,createEffect(()=>{const d=walletsModalState();this.state=d,this.consumers.forEach(k=>k(d))})}open(){return __async(this,null,function*(){this.tracker.trackConnectionStarted();const d=(yield this.connector.getWallets()).find(isWalletInfoCurrentlyEmbedded);return d?this.connectEmbeddedWallet(d):this.openWalletsModal()})}close(_="action-cancelled"){_==="action-cancelled"&&this.tracker.trackConnectionError("Connection was cancelled"),widgetController.closeWalletsModal(_)}onStateChange(_){return this.consumers.push(_),()=>{this.consumers=this.consumers.filter(d=>d!==_)}}connectEmbeddedWallet(_){const d=j=>{setLastSelectedWalletInfo(_),this.connector.connect({jsBridgeKey:_.jsBridgeKey},j)},k=appState.connectRequestParameters;(k==null?void 0:k.state)==="loading"?this.setConnectRequestParametersCallback(d):d(k==null?void 0:k.value)}openWalletsModal(){return __async(this,null,function*(){return isInTMA()&&sendExpand(),widgetController.openWalletsModal(),new Promise(_=>{const d=this.onStateChange(k=>{const{status:j}=k;j==="opened"&&(d(),_())})})})}}class TransactionModalManager{constructor(_){__publicField(this,"connector"),__publicField(this,"consumers",[]),this.connector=_.connector,createEffect(()=>{const d=action();this.consumers.forEach(k=>k(d))})}onStateChange(_){return this.consumers.push(_),()=>{this.consumers=this.consumers.filter(d=>d!==_)}}}class SingleWalletModalManager{constructor(_){__publicField(this,"connector"),__publicField(this,"setConnectRequestParametersCallback"),__publicField(this,"consumers",[]),__publicField(this,"tracker"),__publicField(this,"state",singleWalletModalState()),this.connector=_.connector,this.tracker=_.tracker,this.setConnectRequestParametersCallback=_.setConnectRequestParametersCallback,createEffect(()=>{const d=singleWalletModalState();this.state=d,this.consumers.forEach(k=>k(d))})}open(_){return __async(this,null,function*(){this.tracker.trackConnectionStarted();const d=yield this.connector.getWallets(),k=applyWalletsListConfiguration(d,appState.walletsListConfiguration),j=k.find(isWalletInfoCurrentlyEmbedded);if(!!j)return this.connectEmbeddedWallet(j);const tt=k.filter(isWalletInfoRemote).find(ot=>eqWalletName(ot,_));if(!!tt)return this.openSingleWalletModal(tt);const nt=`Trying to open modal window with unknown wallet "${_}".`;throw this.tracker.trackConnectionError(nt),new TonConnectUIError(nt)})}close(_="action-cancelled"){_==="action-cancelled"&&this.tracker.trackConnectionError("Connection was cancelled"),widgetController.closeSingleWalletModal("action-cancelled")}onStateChange(_){return this.consumers.push(_),()=>{this.consumers=this.consumers.filter(d=>d!==_)}}connectEmbeddedWallet(_){const d=j=>{setLastSelectedWalletInfo(_),this.connector.connect({jsBridgeKey:_.jsBridgeKey},j)},k=appState.connectRequestParameters;(k==null?void 0:k.state)==="loading"?this.setConnectRequestParametersCallback(d):d(k==null?void 0:k.value)}openSingleWalletModal(_){return __async(this,null,function*(){return isInTMA()&&sendExpand(),widgetController.openSingleWalletModal(_),new Promise(d=>{const k=this.onStateChange(j=>{const{status:$}=j;$==="opened"&&(k(),d())})})})}}class TonConnectUITracker{constructor(_){__publicField(this,"eventPrefix","ton-connect-ui-"),__publicField(this,"tonConnectUiVersion"),__publicField(this,"tonConnectSdkVersion",null),__publicField(this,"eventDispatcher");var d;this.eventDispatcher=(d=_==null?void 0:_.eventDispatcher)!=null?d:new BrowserEventDispatcher,this.tonConnectUiVersion=_.tonConnectUiVersion,this.init().catch()}get version(){return createVersionInfo({ton_connect_sdk_lib:this.tonConnectSdkVersion,ton_connect_ui_lib:this.tonConnectUiVersion})}init(){return __async(this,null,function*(){try{yield this.setRequestVersionHandler(),this.tonConnectSdkVersion=yield this.requestTonConnectSdkVersion()}catch{}})}setRequestVersionHandler(){return __async(this,null,function*(){yield this.eventDispatcher.addEventListener("ton-connect-ui-request-version",()=>__async(this,null,function*(){yield this.eventDispatcher.dispatchEvent("ton-connect-ui-response-version",createResponseVersionEvent(this.tonConnectUiVersion))}))})}requestTonConnectSdkVersion(){return __async(this,null,function*(){return new Promise((_,d)=>__async(this,null,function*(){try{yield this.eventDispatcher.addEventListener("ton-connect-response-version",k=>{_(k.detail.version)},{once:!0}),yield this.eventDispatcher.dispatchEvent("ton-connect-request-version",createRequestVersionEvent())}catch(k){d(k)}}))})}dispatchUserActionEvent(_){var d;try{(d=this.eventDispatcher)==null||d.dispatchEvent(`${this.eventPrefix}${_.type}`,_).catch()}catch{}}trackConnectionStarted(..._){try{const d=createConnectionStartedEvent(this.version,..._);this.dispatchUserActionEvent(d)}catch{}}trackConnectionCompleted(..._){try{const d=createConnectionCompletedEvent(this.version,..._);this.dispatchUserActionEvent(d)}catch{}}trackConnectionError(..._){try{const d=createConnectionErrorEvent(this.version,..._);this.dispatchUserActionEvent(d)}catch{}}trackConnectionRestoringStarted(..._){try{const d=createConnectionRestoringStartedEvent(this.version,..._);this.dispatchUserActionEvent(d)}catch{}}trackConnectionRestoringCompleted(..._){try{const d=createConnectionRestoringCompletedEvent(this.version,..._);this.dispatchUserActionEvent(d)}catch{}}trackConnectionRestoringError(..._){try{const d=createConnectionRestoringErrorEvent(this.version,..._);this.dispatchUserActionEvent(d)}catch{}}trackDisconnection(..._){try{const d=createDisconnectionEvent(this.version,..._);this.dispatchUserActionEvent(d)}catch{}}trackTransactionSentForSignature(..._){try{const d=createTransactionSentForSignatureEvent(this.version,..._);this.dispatchUserActionEvent(d)}catch{}}trackTransactionSigned(..._){try{const d=createTransactionSignedEvent(this.version,..._);this.dispatchUserActionEvent(d)}catch{}}trackTransactionSigningFailed(..._){try{const d=createTransactionSigningFailedEvent(this.version,..._);this.dispatchUserActionEvent(d)}catch{}}}const tonConnectUiVersion="2.0.7";class TonConnectUI{constructor(_){if(__publicField(this,"walletInfoStorage",new WalletInfoStorage),__publicField(this,"preferredWalletStorage",new PreferredWalletStorage),__publicField(this,"tracker"),__publicField(this,"walletInfo",null),__publicField(this,"systemThemeChangeUnsubscribe",null),__publicField(this,"actionsConfiguration"),__publicField(this,"walletsList"),__publicField(this,"connectRequestParametersCallback"),__publicField(this,"connector"),__publicField(this,"modal"),__publicField(this,"singleWalletModal"),__publicField(this,"transactionModal"),__publicField(this,"connectionRestored",Promise.resolve(!1)),_&&"connector"in _&&_.connector)this.connector=_.connector;else if(_&&"manifestUrl"in _&&_.manifestUrl)this.connector=new TonConnect({manifestUrl:_.manifestUrl,eventDispatcher:_==null?void 0:_.eventDispatcher});else throw new TonConnectUIError("You have to specify a `manifestUrl` or a `connector` in the options.");this.tracker=new TonConnectUITracker({eventDispatcher:_==null?void 0:_.eventDispatcher,tonConnectUiVersion}),this.modal=new WalletsModalManager({connector:this.connector,tracker:this.tracker,setConnectRequestParametersCallback:j=>{this.connectRequestParametersCallback=j}}),this.singleWalletModal=new SingleWalletModalManager({connector:this.connector,tracker:this.tracker,setConnectRequestParametersCallback:j=>{this.connectRequestParametersCallback=j}}),this.transactionModal=new TransactionModalManager({connector:this.connector}),this.walletsList=this.getWallets(),this.walletsList.then(j=>preloadImages(uniq(j.map($=>$.imageUrl))));const d=this.normalizeWidgetRoot(_==null?void 0:_.widgetRootId);this.subscribeToWalletChange(),(_==null?void 0:_.restoreConnection)!==!1&&(this.connectionRestored=createMacrotaskAsync(()=>__async(this,null,function*(){return this.tracker.trackConnectionRestoringStarted(),yield this.connector.restoreConnection(),this.connector.connected?this.tracker.trackConnectionRestoringCompleted(this.wallet):(this.tracker.trackConnectionRestoringError("Connection was not restored"),this.walletInfoStorage.removeWalletInfo()),this.connector.connected}))),this.uiOptions=mergeOptions(_,{uiPreferences:{theme:"SYSTEM"}});const k=this.preferredWalletStorage.getPreferredWalletAppName();setAppState({connector:this.connector,preferredWalletAppName:k}),widgetController.renderApp(d,this)}static getWallets(){return TonConnect.getWallets()}get connected(){return this.connector.connected}get account(){return this.connector.account}get wallet(){return this.connector.wallet?__spreadValues$1(__spreadValues$1({},this.connector.wallet),this.walletInfo):null}set uiOptions(_){var d,k,j,$,et;this.checkButtonRootExist(_.buttonRootId),this.actionsConfiguration=_.actionsConfiguration,(d=_.uiPreferences)!=null&&d.theme?((k=_.uiPreferences)==null?void 0:k.theme)!=="SYSTEM"?((j=this.systemThemeChangeUnsubscribe)==null||j.call(this),setTheme(_.uiPreferences.theme,_.uiPreferences.colorsSet)):(setTheme(getSystemTheme(),_.uiPreferences.colorsSet),this.systemThemeChangeUnsubscribe||(this.systemThemeChangeUnsubscribe=subscribeToThemeChange(setTheme))):($=_.uiPreferences)!=null&&$.colorsSet&&setColors(_.uiPreferences.colorsSet),(et=_.uiPreferences)!=null&&et.borderRadius&&setBorderRadius(_.uiPreferences.borderRadius),setAppState(tt=>{var rt,nt;const ot=mergeOptions(__spreadValues$1(__spreadValues$1(__spreadValues$1(__spreadValues$1({},_.language&&{language:_.language}),!!((rt=_.actionsConfiguration)!=null&&rt.returnStrategy)&&{returnStrategy:_.actionsConfiguration.returnStrategy}),!!((nt=_.actionsConfiguration)!=null&&nt.twaReturnUrl)&&{twaReturnUrl:_.actionsConfiguration.twaReturnUrl}),!!_.walletsListConfiguration&&{walletsListConfiguration:_.walletsListConfiguration}),unwrap(tt));return _.buttonRootId!==void 0&&(ot.buttonRootId=_.buttonRootId),_.enableAndroidBackHandler!==void 0&&(ot.enableAndroidBackHandler=_.enableAndroidBackHandler),ot})}setConnectRequestParameters(_){var d;setAppState({connectRequestParameters:_}),((_==null?void 0:_.state)==="ready"||!_)&&((d=this.connectRequestParametersCallback)==null||d.call(this,_==null?void 0:_.value))}getWallets(){return __async(this,null,function*(){return this.connector.getWallets()})}onStatusChange(_,d){return this.connector.onStatusChange(k=>__async(this,null,function*(){if(k){const j=yield this.getSelectedWalletInfo(k);_(__spreadValues$1(__spreadValues$1({},k),j||this.walletInfoStorage.getWalletInfo()))}else _(k)}),d)}openModal(){return __async(this,null,function*(){return this.modal.open()})}closeModal(_){this.modal.close(_)}onModalStateChange(_){return this.modal.onStateChange(_)}get modalState(){return this.modal.state}openSingleWalletModal(_){return __async(this,null,function*(){return this.singleWalletModal.open(_)})}closeSingleWalletModal(_){this.singleWalletModal.close(_)}onSingleWalletModalStateChange(_){return this.singleWalletModal.onStateChange(_)}get singleWalletModalState(){return this.singleWalletModal.state}connectWallet(){return __async(this,null,function*(){const d=(yield this.getWallets()).find(isWalletInfoCurrentlyEmbedded);return d?yield this.connectEmbeddedWallet(d):yield this.connectExternalWallet()})}disconnect(){return this.tracker.trackDisconnection(this.wallet,"dapp"),widgetController.clearAction(),widgetController.removeSelectedWalletInfo(),this.walletInfoStorage.removeWalletInfo(),this.connector.disconnect()}sendTransaction(_,d){return __async(this,null,function*(){if(this.tracker.trackTransactionSentForSignature(this.wallet,_),!this.connected)throw this.tracker.trackTransactionSigningFailed(this.wallet,_,"Wallet was not connected"),new TonConnectUIError("Connect wallet to send a transaction.");isInTMA()&&sendExpand();const{notifications:k,modals:j,returnStrategy:$,twaReturnUrl:et,skipRedirectToWallet:tt}=this.getModalsAndNotificationsConfiguration(d);widgetController.setAction({name:"confirm-transaction",showNotification:k.includes("before"),openModal:j.includes("before"),sent:!1});const rt=()=>{nt.signal.aborted||(widgetController.setAction({name:"confirm-transaction",showNotification:k.includes("before"),openModal:j.includes("before"),sent:!0}),this.walletInfo&&"universalLink"in this.walletInfo&&(this.walletInfo.openMethod==="universal-link"||this.walletInfo.openMethod==="custom-deeplink")&&(isTelegramUrl(this.walletInfo.universalLink)?redirectToTelegram(this.walletInfo.universalLink,{returnStrategy:$,twaReturnUrl:et||appState.twaReturnUrl,forceRedirect:!1}):redirectToWallet(this.walletInfo.universalLink,this.walletInfo.deepLink,{returnStrategy:$,forceRedirect:!1},()=>{})))},nt=new AbortController,ot=this.onTransactionModalStateChange(at=>{at!=null&&at.openModal||(ot(),at||nt.abort())});try{const at=yield this.waitForSendTransaction({transaction:_,signal:nt.signal},rt);return this.tracker.trackTransactionSigned(this.wallet,_,at),widgetController.setAction({name:"transaction-sent",showNotification:k.includes("success"),openModal:j.includes("success")}),at}catch(at){throw widgetController.setAction({name:"transaction-canceled",showNotification:k.includes("error"),openModal:j.includes("error")}),at instanceof TonConnectError?at:(console.error(at),new TonConnectUIError("Unhandled error:"+at))}finally{ot()}})}connectEmbeddedWallet(_){return __async(this,null,function*(){const d=j=>{setLastSelectedWalletInfo(_),this.connector.connect({jsBridgeKey:_.jsBridgeKey},j)},k=appState.connectRequestParameters;return(k==null?void 0:k.state)==="loading"?this.connectRequestParametersCallback=d:d(k==null?void 0:k.value),yield this.waitForWalletConnection({ignoreErrors:!1})})}connectExternalWallet(){return __async(this,null,function*(){const _=new AbortController;widgetController.openWalletsModal();const d=this.onModalStateChange(k=>{const{status:j,closeReason:$}=k;j!=="opened"&&(d(),$==="action-cancelled"&&_.abort())});return yield this.waitForWalletConnection({ignoreErrors:!0,signal:_.signal})})}waitForWalletConnection(_){return __async(this,null,function*(){return new Promise((d,k)=>{this.tracker.trackConnectionStarted();const{ignoreErrors:j=!1,signal:$=null}=_;if($&&$.aborted)return this.tracker.trackConnectionError("Connection was cancelled"),k(new TonConnectUIError("Wallet was not connected"));const et=nt=>__async(this,null,function*(){if(nt)this.tracker.trackConnectionCompleted(nt),rt(),d(nt);else{if(this.tracker.trackConnectionError("Connection was cancelled"),j)return;rt(),k(new TonConnectUIError("Wallet was not connected"))}}),tt=nt=>{this.tracker.trackConnectionError(nt.message),!j&&(rt(),k(nt))},rt=this.onStatusChange(nt=>et(nt),nt=>tt(nt));$&&$.addEventListener("abort",()=>{rt(),k(new TonConnectUIError("Wallet was not connected"))},{once:!0})})})}waitForSendTransaction(_,d){return __async(this,null,function*(){return new Promise((k,j)=>{const{transaction:$,signal:et}=_;if(et.aborted)return this.tracker.trackTransactionSigningFailed(this.wallet,$,"Transaction was cancelled"),j(new TonConnectUIError("Transaction was not sent"));const tt=ot=>__async(this,null,function*(){k(ot)}),rt=ot=>{j(ot)},nt=()=>{this.tracker.trackTransactionSigningFailed(this.wallet,$,"Transaction was cancelled"),j(new TonConnectUIError("Transaction was not sent"))};et.addEventListener("abort",nt,{once:!0}),this.connector.sendTransaction($,{onRequestSent:d,signal:et}).then(ot=>(et.removeEventListener("abort",nt),tt(ot))).catch(ot=>(et.removeEventListener("abort",nt),rt(ot)))})})}onTransactionModalStateChange(_){return this.transactionModal.onStateChange(_)}subscribeToWalletChange(){this.connector.onStatusChange(_=>__async(this,null,function*(){var d;_?(yield this.updateWalletInfo(_),this.setPreferredWalletAppName(((d=this.walletInfo)==null?void 0:d.appName)||_.device.appName)):this.walletInfoStorage.removeWalletInfo()}))}setPreferredWalletAppName(_){this.preferredWalletStorage.setPreferredWalletAppName(_),setAppState({preferredWalletAppName:_})}getSelectedWalletInfo(_){return __async(this,null,function*(){let d=widgetController.getSelectedWalletInfo();if(!d)return null;let k;if("name"in d)k=d;else{const $=applyWalletsListConfiguration(yield this.walletsList,appState.walletsListConfiguration).find(et=>eqWalletName(et,_.device.appName));if(!$)throw new TonConnectUIError(`Cannot find WalletInfo for the '${_.device.appName}' wallet`);k=__spreadValues$1(__spreadValues$1({},$),d)}return k})}updateWalletInfo(_){return __async(this,null,function*(){const d=yield this.getSelectedWalletInfo(_);if(d){this.walletInfo=d,this.walletInfoStorage.setWalletInfo(d);return}const k=this.walletInfoStorage.getWalletInfo();if(k){this.walletInfo=k;return}this.walletInfo=(yield this.walletsList).find(j=>eqWalletName(j,_.device.appName))||null})}normalizeWidgetRoot(_){if(!_||!document.getElementById(_)){_="tc-widget-root";const d=document.createElement("div");d.id=_,document.body.appendChild(d)}return _}checkButtonRootExist(_){if(_!=null&&!document.getElementById(_))throw new TonConnectUIError(`${_} element not found in the document.`)}getModalsAndNotificationsConfiguration(_){var d,k,j,$,et,tt;const rt=["before","success","error"];let nt=rt;(d=this.actionsConfiguration)!=null&&d.notifications&&((k=this.actionsConfiguration)==null?void 0:k.notifications)!=="all"&&(nt=this.actionsConfiguration.notifications),_!=null&&_.notifications&&(_.notifications==="all"?nt=rt:nt=_.notifications);let ot=["before"];(j=this.actionsConfiguration)!=null&&j.modals&&(this.actionsConfiguration.modals==="all"?ot=rt:ot=this.actionsConfiguration.modals),_!=null&&_.modals&&(_.modals==="all"?ot=rt:ot=_.modals);const at=(_==null?void 0:_.returnStrategy)||(($=this.actionsConfiguration)==null?void 0:$.returnStrategy)||"back",it=(_==null?void 0:_.twaReturnUrl)||((et=this.actionsConfiguration)==null?void 0:et.twaReturnUrl);let dt=(_==null?void 0:_.skipRedirectToWallet)||((tt=this.actionsConfiguration)==null?void 0:tt.skipRedirectToWallet)||"ios";return isInTMA()&&(dt="never"),{notifications:nt,modals:ot,returnStrategy:at,twaReturnUrl:it,skipRedirectToWallet:dt}}}var __defProp=Object.defineProperty,__getOwnPropSymbols=Object.getOwnPropertySymbols,__hasOwnProp=Object.prototype.hasOwnProperty,__propIsEnum=Object.prototype.propertyIsEnumerable,__defNormalProp=(b,_,d)=>_ in b?__defProp(b,_,{enumerable:!0,configurable:!0,writable:!0,value:d}):b[_]=d,__spreadValues=(b,_)=>{for(var d in _||(_={}))__hasOwnProp.call(_,d)&&__defNormalProp(b,d,_[d]);if(__getOwnPropSymbols)for(var d of __getOwnPropSymbols(_))__propIsEnum.call(_,d)&&__defNormalProp(b,d,_[d]);return b},__objRest=(b,_)=>{var d={};for(var k in b)__hasOwnProp.call(b,k)&&_.indexOf(k)<0&&(d[k]=b[k]);if(b!=null&&__getOwnPropSymbols)for(var k of __getOwnPropSymbols(b))_.indexOf(k)<0&&__propIsEnum.call(b,k)&&(d[k]=b[k]);return d},jsxRuntime={exports:{}},reactJsxRuntime_production_min={};/** * @license React * react-jsx-runtime.production.min.js * diff --git a/docs/index.html b/docs/index.html index 06dcbe7..03b3ce2 100644 --- a/docs/index.html +++ b/docs/index.html @@ -7,7 +7,7 @@ Demo Dapp React UI - +