diff --git a/.env.example b/.env.example index 502b882..a36aeeb 100644 --- a/.env.example +++ b/.env.example @@ -30,11 +30,24 @@ REMINDER_HOURS_BEFORE=24 # --- Contrato escrow --------------------------------------------------------- # Dirección del contrato desplegado (contracts/escrow.fc), formato EQ... / 0:... ESCROW_ADDRESS= -# Dirección del admin del contrato (la que firmará resolve/cancel). Informativo. +# Dirección del admin del contrato (firma resolve/cancel/pausa/comisión/retiro). +# El backend la usa para avisar si tu wallet vinculada no es la administradora; +# opcional, pero sin ella no puede comprobarlo. ESCROW_ADMIN_ADDRESS= # Apuesta mínima aceptada por el contrato, en nanoTON (0.1 TON) MIN_STAKE_NANO=100000000 +# Apuesta máxima que el backend acepta preparar, en nanoTON (5000 TON) +MAX_STAKE_NANO=5000000000000 MAX_OPTIONS=8 +# Gas adjunto por operación, en nanoTON (0.03 / 0.05 / 0.05 / 0.02 TON) +BET_GAS_NANO=30000000 +CREATE_GAS_NANO=50000000 +ADMIN_GAS_NANO=50000000 +CLAIM_GAS_NANO=20000000 +# Ventana de creación de mercados y caducidad de la firma +MIN_MARKET_DURATION_MIN=15 +MAX_MARKET_DURATION_DAYS=365 +TX_TTL_SECONDS=300 # --- TON Connect / ton_proof ------------------------------------------------- PUBLIC_BASE_URL=https://betpoly.example.com @@ -68,3 +81,11 @@ APP_TITLE=BetPoly SUPPORT_URL= # Orígenes que pueden embeber la Mini App (CSP frame-ancestors) FRAME_ANCESTORS='self' https://*.telegram.org https://web.telegram.org https://*.e2b.app + +# --- Proxy inverso (IP real para los límites de tasa) ------------------------- +# Solo se honra X-Forwarded-For si TRUST_PROXY=true Y la conexión viene de una +# de estas redes. Con TRUST_PROXY=false la cabecera se ignora (recomendado si +# el proceso escucha directo en Internet). +TRUST_PROXY=false +# Lista de CIDR separada por comas, p. ej. 127.0.0.1/32,10.0.0.0/8 +TRUSTED_PROXIES= diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..d9a303f --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,99 @@ +name: CI + +on: + push: + branches: ["**"] + pull_request: + branches: [main] + +concurrency: + group: ci-${{ github.ref }} + cancel-in-progress: true + +jobs: + lint: + name: Lint (ruff + vulture) + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: "3.11" + cache: pip + - run: pip install -r requirements-dev.txt + - run: ruff check . + - name: Código muerto (vulture) + run: vulture bot config.py main.py scripts --min-confidence 80 + + test: + name: Tests (pytest + cobertura) + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: "3.11" + cache: pip + - run: pip install -r requirements-dev.txt + - name: Suite offline + env: + BOT_TOKEN: "123456:CI-TOKEN-NOT-REAL" + BET_MODE: points + DATABASE_PATH: /tmp/ci.db + run: | + pytest \ + --cov=bot --cov=config --cov=main --cov=scripts \ + --cov-report=term-missing:skip-covered \ + --cov-fail-under=83 + - name: Cobertura de la capa Telegram (Fase 5) + run: | + pytest tests/test_handlers_navigation.py tests/test_handlers_flows.py \ + --cov=bot.handlers --cov=bot.keyboards --cov-fail-under=70 + + contract: + name: Contrato (build + sandbox + audit) + runs-on: ubuntu-latest + defaults: + run: + working-directory: contracts + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: "20" + cache: npm + cache-dependency-path: contracts/package-lock.json + - run: npm ci + - name: Compilar y verificar hash + run: | + node scripts/build.js + node -e " + const fs = require('fs'); + const boc = fs.readFileSync('build/escrow.code.boc'); + const { Cell } = require('@ton/core'); + const hash = Cell.fromBoc(boc)[0].hash().toString('hex'); + const pinned = require('fs').readFileSync('../tests/test_contract_sync.py', 'utf8') + .match(/CODE_HASH = \"([0-9a-f]+)\"/)[1]; + if (hash !== pinned) { + console.error('❌ hash compilado', hash, '≠ pinneado', pinned); + process.exit(1); + } + console.log('✅ hash reproducible', hash); + " + - name: Sandbox TVM + run: node tests/escrow.test.js + - name: Excepciones de auditoría (test) + run: node tests/audit.test.js + - name: npm audit + run: node scripts/audit.js + + security: + name: Dependencias (pip-audit) + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: "3.11" + - run: pip install pip-audit + - run: pip-audit -r requirements.txt --strict diff --git a/.gitignore b/.gitignore index 5d70b05..cda6e33 100644 --- a/.gitignore +++ b/.gitignore @@ -27,6 +27,14 @@ contracts/build/deploy.json *.db-shm *.db-wal +# Tests / coverage +.coverage +.coverage.* +htmlcov/ +coverage.xml +.mypy_cache/ +.pytest_cache/ + # Logs *.log diff --git a/AUDITORIA.md b/AUDITORIA.md new file mode 100644 index 0000000..d2551eb --- /dev/null +++ b/AUDITORIA.md @@ -0,0 +1,463 @@ +# Auditoría técnica — BetPoly_Bot + +**Fecha:** 2026-10-23 +**Alcance:** repositorio completo (`bot/`, `config.py`, `main.py`, `web/`, `contracts/`, `scripts/`, `tests/`). +**Commit auditado:** `6b50853` (rama `arena/de3be963-betpoly-bot`, igual a `origin/main`). +**Naturaleza de este documento:** **solo hallazgos documentados**. No se ha modificado ni una línea del proyecto. + +> Este informe está ordenado por severidad. Cada hallazgo indica evidencia reproducible (`archivo:línea`), impacto y, cuando aplica, la prueba ejecutada que lo confirma. +> La numeración (`S-*`, `F-*`, `D-*`, `H-*`, `R-*`, `T-*`) es estable para poder referenciarla en instrucciones posteriores. + +--- + +## 0. Resumen ejecutivo + +| Área | Veredicto | +| :--- | :--- | +| Contrato escrow (FunC) | ✅ Compila de forma determinista y pasa 22/22 comprobaciones en sandbox TVM | +| Backend no-custodial | ✅ Se mantiene el invariante: nunca hay claves privadas ni firma del lado servidor | +| Persistencia | ⚠️ Transacciones correctas, pero hay pérdida silenciosa de eventos on-chain (S-01) | +| Índice on-chain | ❌ Un error de persistencia descarta el evento para siempre (S-01) | +| API HTTP | ⚠️ Autenticación sólida; limitador de tasa eludible (S-04) | +| Capa Telegram (handlers) | ⚠️ 0 % de cobertura y varios defectos de navegación/entrada (F-01, F-04) | +| Mini App (`web/`) | ⚠️ Cableada correctamente, salvo un botón roto por CSP (S-05) | +| Código muerto / duplicado | ⚠️ 19 símbolos sin uso, 3 clones reales, 1 fachada de paquete sin consumidores | +| Hardcodeo | ⚠️ Sin secretos ni direcciones; sí constantes de dinero/tiempos dispersas | +| Dependencias | ✅ Fijadas y al día salvo `python-telegram-bot` (una major por detrás) | +| Automatización | ❌ No existe CI: los 263 tests nunca se ejecutan automáticamente | + +**Conteo:** 7 hallazgos críticos/altos · 15 medios · 25 menores, más 19 símbolos de código muerto. + +**Estado tras la Fase 7 (2026-10-23):** los 47 hallazgos están cerrados. La tabla +de arriba es la foto del commit auditado y se conserva como registro; cada +hallazgo lleva al final su línea *Resuelto*. Medido hoy: `pytest` **670 tests en +verde**, cobertura **85,8 %**; `ruff check .` y `vulture --min-confidence 80` +limpios; contrato con el mismo hash reproducible y 25/25 comprobaciones. + +--- + +## 1. Metodología y evidencia + +Herramientas ejecutadas sobre el commit auditado: + +- `ruff` (0.17.2), `vulture` (2.16), `bandit` (1.9.4), `radon`, `jscpd` (4.x), `pip-audit` (2.10.1), `npm audit`. +- `pytest` con `pytest-cov` → **263 tests en verde, cobertura total 55 %**. +- `contracts/`: `node scripts/build.js`, `node tests/escrow.test.js` (22 comprobaciones), `npm audit`, `node scripts/deploy.js` (dry-run real). +- Arranque real de `scripts/dev_server.py` en el puerto 8080 y sondeo con `curl`. +- Pruebas de API con `aiohttp.test_utils.TestClient` sobre bases de datos desechables (`/tmp/audit*.db`), incluidos casos de abuso (rotación de `X-Forwarded-For`, montos límite, `limit`/`offset` extremos). +- Pruebas directas contra `bot.database` y `bot.chain.indexer` con clientes falsos para forzar fallos de persistencia. +- Lectura manual íntegra de `bot/api.py`, `bot/security.py`, `bot/database.py`, `bot/markets.py`, `bot/chain/*`, `bot/handlers/*`, `bot/keyboards.py`, `config.py`, `web/index.html`, `web/static/app.js`, `main.py`, `contracts/scripts/*.js` y secciones de `contracts/escrow.fc`. +- Verificación de versiones publicadas hoy en PyPI y npm contra los *pins* del repositorio. + +--- + +## 2. Lo que sí está verificado y funciona + +Para que el listado de problemas no dé una impresión falsa del estado del proyecto: + +1. **Contrato:** `node scripts/build.js` reproduce exactamente el hash fijado en `tests/test_contract_sync.py::CODE_HASH` → `a29c5c51fe93597967c6d37c976a27e989d13662117165dec1d899fe3292db9b`. Compilación determinista y verificable. +2. **Suite del contrato:** 22/22 comprobaciones en `@ton/sandbox` (crear, apostar, resolver, reclamar, cancelar, reembolsos, pausa, fees). +3. **Suite Python:** 263 tests, 0 fallos, sin red. +4. **Arranque de la Mini App:** `scripts/dev_server.py` responde `200` en `/`, `/api/health` y devuelve mercados sembrados en `/api/markets`. +5. **`main.py --check`:** valida de verdad y sale con código `2` ante configuración inválida (probado con `BET_MODE=hybrid` sin `ESCROW_ADDRESS` y con `PUBLIC_BASE_URL` en `http://`). +6. **`deploy.js`:** dry-run correcto, exit `1` con dirección inválida, exit `0` con datos válidos; no envía transacciones en dry-run. +7. **Validación de importes (crítica para dinero):** matriz probada contra `/api/markets/{id}/bets/prepare` → `-5e9` → `stake_too_low`, `1e18` → `stake_too_high`, `true` → `bad_amount`, `"1e9"` → `bad_amount`, `"0.000000001"` → `stake_too_low`, sin wallet → `wallet_required`. **Correcto.** +8. **Cadena de autenticación:** `initData` (HMAC) → nonce de un solo uso (`ton_proof`) → `verify_ton_proof` (valida `state_init.hash == address_hash` y luego la firma) → `link_wallet`. Sin fugas: `/api/me` no expone el nonce. +9. **SQLite:** `journal_mode=WAL`, `synchronous=NORMAL`, `busy_timeout=5000`; liquidaciones idempotentes; `chain_txs(tx_hash, lt)` como PK garantiza procesamiento *exactly-once*. +10. **Dependencias:** `npm audit` sin vulnerabilidades; `pip-audit` limpio sobre `requirements.txt`; los *pins* de npm coinciden con las últimas versiones publicadas. +11. **Sin secretos en el código:** ni tokens, ni mnemónicos, ni direcciones de administrador embebidas. Las fixtures de test usan valores evidentemente falsos (`123456789:TEST-TOKEN-…`). +12. **Variables de entorno:** todas las declaradas en `.env.example` se leen en `config.py`; una de ellas (`ESCROW_ADMIN_ADDRESS`) se lee y luego no se usa (ver D-03). *(Una sospecha inicial sobre `FRAME_ANCESTORS` resultó **falsa**: sí se lee en `config.py:254`.)* + +--- + +## 3. Hallazgos críticos y altos + +### S-01 — 🔴 El indexador pierde eventos on-chain de forma permanente si falla una escritura +**Evidencia:** `bot/chain/indexer.py:140-157` +En el `except` se marca la tx como no procesada (`unmark_tx_processed`) con el comentario *«retry this tx next poll»*, pero **acto seguido el cursor se actualiza igual** (`if tx.lt >= newest_lt: newest_lt, newest_hash = tx.lt, tx.tx_hash`) y se persiste con `set_cursor(...)`. El siguiente ciclo solo pide transacciones *más nuevas* que el cursor, por lo que la tx fallida queda fuera de la ventana para siempre. + +**Prueba ejecutada** (3 txs, fallo forzado en la del medio): +``` +run 1 -> fetched 3 processed 2 errores 1 +cursor tras run 1: (30, ...) +run 2 -> fetched 0 processed 0 +¿tx 20 quedó procesada? True ← el cursor ya la dejó atrás +``` +**Impacto:** una apuesta o una resolución on-chain puede quedar invisible para el backend mientras el dinero sí se movió. No hay reconciliación posterior ni alerta. Es el hallazgo de mayor riesgo del proyecto. + +--- + +### S-02 — 🔴 `upsert_market` ignora silenciosamente cualquier corrección posterior de los datos del mercado +**Evidencia:** `bot/database.py:943` (`INSERT OR IGNORE INTO markets ...`), usado desde `bot/chain/indexer.py:286` y `:321`. +La fila se crea la primera vez y **nunca se actualiza**. El caso real está documentado en el propio código (`indexer.py:319-330`): si una apuesta llega antes que el evento de creación, se crea un marcador con `title="Mercado #N"`, `closes_at=0` y sin `fee_bps`; cuando luego se indexa el evento de creación, los datos buenos se descartan. + +**Prueba ejecutada:** +``` +upsert_market existente -> created: False | título final: 'Mercado #1' | closes_at: 0 +``` +**Impacto:** mercado con fecha de cierre de 1970 (aparece siempre como cerrado), título genérico permanente, `option_count` incorrecto y `estimate_payout` calculando con `fee_bps = 0`. + +--- + +### S-03 — 🔴 Funciones de administración del contrato inalcanzables desde cualquier interfaz +**Evidencia:** `bot/chain/bodies.py` define `build_set_paused`, `build_set_fee`, `build_change_admin`, `build_withdraw_fees`; `contracts/escrow.fc` las implementa; **ningún** router, handler, teclado o botón de la Mini App las invoca (búsqueda exhaustiva sobre `bot/`, `main.py`, `web/`). +El indexador sí sabe *leer* esos eventos, lo que confirma que el contrato los emite. + +**Impacto:** el administrador **no puede retirar las comisiones acumuladas, pausar el contrato en una emergencia, cambiar la comisión ni transferir la administración** sin construir el mensaje a mano en una wallet. Las fees quedan atrapadas en el contrato. Es una funcionalidad completa (código + contrato) sin puerta de entrada. + +--- + +### S-04 — 🔴 El limitador de tasa es eludible falsificando `X-Forwarded-For` +**Evidencia:** `bot/api.py:82-84` +```python +def _client_ip(request): + forwarded = request.headers.get("X-Forwarded-For", "") + return (forwarded.split(",")[0].strip() if forwarded else request.remote) or "?" +``` +Se confía en la cabecera sin lista blanca de proxies. Se aplica a `/api/session` (`api.py:243`) y, por clave de usuario, a `/api/wallet/verify`. + +**Prueba ejecutada:** 40 peticiones `POST /api/session` rotando `X-Forwarded-For: 10.0.0.N` → **40 × 200, cero 429**. +**Impacto:** un atacante abre sesiones ilimitadas y evita el freno de verificación de wallet; además el diccionario interno del limitador recibe claves arbitrarias (el recorte de memoria solo elimina cubetas vacías, `bot/security.py`). + +--- + +### S-05 — 🔴 La CSP del propio servidor anula el botón «Reintentar» de la Mini App +**Evidencia:** `web/static/app.js:186` inyecta ` + +
Cargando estado…
+ + + + +

+ Solo se pueden retirar las comisiones acumuladas. El contrato nunca + permite sacar los fondos de los usuarios. +

+ + +
+ + +

Aplica solo a los mercados creados a partir de ahora.

+
+ +
+ + +

+ ⚠️ Irreversible: si pierdes esa wallet, pierdes el control del contrato. +

+
+ + +

+ Pausado: nadie puede crear mercados ni apostar. Resolver, cancelar y + reclamar pagos siguen funcionando. Cada acción se firma en tu wallet: + el backend nunca tiene llaves. +

+ +

Estado del indexador

—
diff --git a/web/static/app.js b/web/static/app.js index b368961..9057e8b 100644 --- a/web/static/app.js +++ b/web/static/app.js @@ -22,6 +22,11 @@ sheetMode: 'bet', verifying: false, pollTimer: null, + pollStep: 0, + marketsFingerprint: '', + quote: null, + quoteSeq: 0, + quoteTimer: null, }; let tonConnectUI = null; @@ -175,15 +180,43 @@ bindEvents(); await Promise.all([loadMarkets(), loadMine()]); - state.pollTimer = setInterval(() => { - if (document.visibilityState === 'visible' && state.view === 'markets') loadMarkets(true); - }, 25000); + schedulePoll(); + } + + /* R-08: sondeo adaptativo. Empieza en 15 s y, si nada cambia, se relaja a + 30 s y luego a 60 s. Cualquier actividad del usuario (o un cambio real en + los mercados) vuelve a 15 s: se refresca rápido cuando importa y se deja + de gastar batería y datos cuando no pasa nada. */ + const POLL_DELAYS = [15000, 30000, 60000]; + + function schedulePoll() { + const delay = POLL_DELAYS[Math.min(state.pollStep, POLL_DELAYS.length - 1)]; + clearTimeout(state.pollTimer); + state.pollTimer = setTimeout(pollOnce, delay); + } + + async function pollOnce() { + if (document.visibilityState === 'visible' && state.view === 'markets') { + const before = state.marketsFingerprint; + try { + await loadMarkets(true); + } catch (error) { /* se reintenta en el siguiente ciclo */ } + const changed = state.marketsFingerprint !== before; + state.pollStep = changed ? 0 : Math.min(state.pollStep + 1, POLL_DELAYS.length - 1); + } + schedulePoll(); + } + + function pollNow() { + // Interacción del usuario: el siguiente refresco vuelve a ser el más rápido. + state.pollStep = 0; + schedulePoll(); } function showFatal(message) { const boot = $('#boot'); boot.innerHTML = `

${esc(message)}

- `; + `; } function applyConfig() { @@ -192,7 +225,7 @@ ? 'Mercados no-custodiales en TON' : 'Modo puntos (sin dinero real)'; const gas = $('#create-gas'); - if (gas) gas.textContent = cfg.create_gas_ton || '0.05'; + if (gas) gas.textContent = cfg.create_gas_ton || '—'; $('#escrow-label').textContent = cfg.escrow_address ? `Escrow: ${short(cfg.escrow_address, 6)}` : 'Escrow: no configurado'; @@ -377,7 +410,10 @@ ${esc(points)} puntos ${state.myBets.length} apuestas on-chain ${wins} ganadas -
`; + + ${state.wallet + ? `` + : ''}`; } function marketCard(market) { @@ -483,7 +519,10 @@ 🪙 ${fmtTon(market.pool_ton)} TON ⏰ ${fmtDate(market.closes_at)} - +
+ + +
`).join(''); } @@ -500,6 +539,8 @@ try { const data = await api('/api/markets?status=open&limit=50', { auth: !!state.session }); state.markets = data.markets || []; + // Huella para el sondeo adaptativo (R-08): si no cambió, se relaja. + state.marketsFingerprint = JSON.stringify(state.markets); renderMarkets(); if (state.view === 'admin') renderAdmin(); } catch (error) { @@ -591,11 +632,16 @@
${options}
`; + if (market.resolving) { + body += `

🔒 Resolución en curso: no se aceptan apuestas nuevas.

`; + } + if (isOpen && !myBet) { body += ` @@ -654,25 +700,55 @@ } const option = state.selection.option; const amount = Number(state.selection.amount || 0); - const optionData = market.options.find((o) => o.index === option); - const total = Number(market.pool_ton || 0); - const pool = optionData ? Number(optionData.pool_ton || 0) : 0; - const potential = option != null && amount > 0 && total + amount > 0 - ? (amount * (total + amount)) / (pool + amount) - : 0; if (option == null) { summary.textContent = 'Elige una opción.'; confirm.disabled = true; } else if (!(amount >= Number(state.config.min_stake_ton))) { summary.textContent = `Escribe al menos ${state.config.min_stake_ton} TON.`; confirm.disabled = true; + } else if (!state.quote) { + // La economía la calcula el backend (/quote): aquí solo se formatea. + summary.textContent = 'Calculando el pago potencial…'; + confirm.disabled = false; } else { - summary.innerHTML = `Pago potencial ≈ ${fmtTon(potential)} TON · ` + summary.innerHTML = `Pago potencial ≈ ${fmtTon(state.quote.payout_ton)} TON · ` + `se enviarán ${fmtTon(amount + Number(state.config.bet_gas_ton))} TON (incluye gas).`; confirm.disabled = false; } } + function scheduleQuote() { + clearTimeout(state.quoteTimer); + state.quote = null; + state.quoteTimer = setTimeout(requestQuote, 250); + } + + async function requestQuote() { + const market = state.market; + const option = state.selection.option; + const amount = Number(state.selection.amount || 0); + if (!market || option == null || !(amount > 0)) { + state.quote = null; + updateSheetSummary(); + return; + } + const seq = state.quoteSeq + 1; + state.quoteSeq = seq; + const stake = encodeURIComponent(state.selection.amount); + try { + const quote = await api( + `/api/markets/${market.market_id}/quote?option=${option}&stake_ton=${stake}`, + { auth: false }, + ); + if (seq !== state.quoteSeq) return; + state.quote = quote; + } catch (error) { + if (seq !== state.quoteSeq) return; + state.quote = null; + } + updateSheetSummary(); + } + /* -------------------------------------------------------------- flows */ async function confirmSheet() { @@ -765,8 +841,9 @@ return; } const closesAt = Math.floor(new Date(closeValue).getTime() / 1000); - if (!isFinite(closesAt) || closesAt < Math.floor(Date.now() / 1000) + 900) { - toast('El cierre debe ser al menos 15 minutos en el futuro.', 'error'); + const minMinutes = Number(state.config.min_market_duration_min || 15); + if (!isFinite(closesAt) || closesAt < Math.floor(Date.now() / 1000) + minMinutes * 60) { + toast(`El cierre debe ser al menos ${minMinutes} minutos en el futuro.`, 'error'); return; } busy(true); @@ -844,6 +921,162 @@ } } + /* --------------------------------------------------- contrato escrow */ + + const contract = { data: null }; + + function renderContract() { + const box = $('#contract-state'); + if (!box || !contract.data) return; + const data = contract.data; + const paused = !!data.is_paused; + const tons = (nano) => `${fmtTon(Number(nano || 0) / 1e9)} TON`; + const rows = [ + ['Estado', paused ? '⏸ pausado' : '▶️ activo'], + ['Comisión actual', `${data.fee_percent || '0.00'} %`], + ['Apuesta mínima', tons(data.min_stake_nano)], + ['Comisiones acumuladas', tons(data.fees_nano)], + ['Fondos de usuarios bloqueados', tons(data.total_locked_nano)], + ['Mercados creados', String(data.market_count == null ? '—' : data.market_count)], + ]; + if (data.balance_nano != null) rows.push(['Balance del contrato', tons(data.balance_nano)]); + if (data.admin) rows.push(['Admin configurado', short(data.admin, 6)]); + const warnings = []; + if (data.stale) warnings.push('⚠️ Estado sin actualizar: la cadena no respondió.'); + if (data.admin_matches_wallet === false) { + warnings.push('⚠️ Tu wallet vinculada no es la administradora: el contrato rechazaría la firma.'); + } + if (data.admin_matches_wallet === null && data.admin) { + warnings.push('ℹ️ Vincula tu wallet en el bot para comprobar quién es el administrador.'); + } + box.innerHTML = ` +
+ ${rows.map(([label, value]) => `
${esc(label)}
${esc(value)}
`).join('')} +
+ ${warnings.map((text) => `

${esc(text)}

`).join('')}`; + + const pause = $('#contract-pause'); + if (pause) pause.textContent = paused ? 'Reanudar contrato' : 'Pausar contrato'; + const amount = $('#contract-withdraw-amount'); + if (amount) { + const availableTon = Number(data.max_withdrawable_nano || data.fees_nano || 0) / 1e9; + amount.max = String(availableTon); + } + } + + async function loadContract(force = false) { + const box = $('#contract-state'); + if (!box) return; + if (!state.config || !state.config.escrow_enabled) { + box.textContent = 'Esta instancia no tiene contrato escrow configurado.'; + return; + } + try { + const data = force + ? await api('/api/admin/contract?refresh=1') + : await api('/api/admin/contract'); + contract.data = data; + renderContract(); + } catch (error) { + contract.data = null; + box.textContent = friendlyError(error); + } + } + + async function signContract(prepare, message) { + busy(true); + try { + const tx = await prepare(); + busy(false); + await signTransaction(tx); + toast(message, 'ok'); + loadContract(true); + } catch (error) { + busy(false); + toast(friendlyError(error), 'error'); + } + } + + async function contractWithdraw(event) { + event.preventDefault(); + const amount = $('#contract-withdraw-amount').value.trim(); + if (!amount) return; + if (!window.confirm(`¿Retirar ${amount} TON de comisiones? La firma la hace tu wallet.`)) return; + await signContract( + () => api('/api/admin/contract/withdraw/prepare', { method: 'POST', body: { amount } }), + 'Retiro enviado. El indexador lo confirmará en unos segundos.'); + } + + async function contractSetFee(event) { + event.preventDefault(); + const percent = $('#contract-fee-percent').value.trim(); + if (!percent) return; + if (!window.confirm(`¿Cambiar la comisión al ${percent} %? Solo afecta a mercados nuevos.`)) return; + await signContract( + () => api('/api/admin/contract/set-fee/prepare', { method: 'POST', body: { percent } }), + 'Comisión enviada. Se aplicará a los mercados creados desde ahora.'); + } + + async function contractSetPaused() { + if (!contract.data) return; + const paused = !contract.data.is_paused; + const question = paused + ? '¿Pausar el contrato? Nadie podrá crear mercados ni apostar.' + : '¿Reanudar el contrato? Se volverán a aceptar mercados y apuestas.'; + if (!window.confirm(question)) return; + await signContract( + () => api('/api/admin/contract/set-paused/prepare', { method: 'POST', body: { paused } }), + paused ? 'Contrato pausado.' : 'Contrato reanudado.'); + } + + async function contractChangeAdmin(event) { + event.preventDefault(); + const address = $('#contract-admin-address').value.trim(); + if (!address) return; + const sure = window.confirm( + `Vas a transferir la administración a:\n${address}\n\nEs irreversible. ¿Continuar?`); + if (!sure) return; + await signContract( + () => api('/api/admin/contract/change-admin/prepare', { method: 'POST', body: { address } }), + 'Cambio de administrador enviado. Verifícalo on-chain antes de cerrar.'); + } + + async function unlinkWallet() { + if (!state.wallet) return; + const sure = window.confirm( + '¿Desvincular esta wallet de tu cuenta?\n\nPodrás volver a conectarla cuando quieras.'); + if (!sure) return; + busy(true); + try { + await api('/api/wallet', { method: 'DELETE' }); + busy(false); + state.wallet = null; + renderWallet(); + renderProfile(); + toast('Wallet desvinculada.', 'ok'); + } catch (error) { + busy(false); + toast(friendlyError(error), 'error'); + } + } + + async function adminCancelMarket(marketId) { + const sure = window.confirm( + `¿Cancelar el mercado #${marketId}?\n\nTodos podrán reclamar su reembolso completo.`); + if (!sure) return; + busy(true); + try { + const tx = await api(`/api/admin/markets/${marketId}/cancel/prepare`, { method: 'POST' }); + busy(false); + await signTransaction(tx); + toast('Cancelación enviada. El indexador la confirmará.', 'ok'); + switchView('admin'); + } catch (error) { + busy(false); + toast(friendlyError(error), 'error'); + } + } + async function loadAdminStatus() { try { const status = await api('/api/indexer'); @@ -864,9 +1097,15 @@ const section = document.getElementById(`view-${name}`); if (section) section.classList.toggle('hidden', name !== view); }); - if (view === 'admin') loadAdminStatus(); + if (view === 'admin') { + loadAdminStatus(); + loadContract(); + } if (view === 'mine') loadMine(); - if (view === 'markets') loadMarkets(true); + if (view === 'markets') { + pollNow(); + loadMarkets(true); + } } /* ------------------------------------------------------------- events */ @@ -879,6 +1118,17 @@ $('#wallet-chip').addEventListener('click', connectWallet); $('#reconnect').addEventListener('click', reconnectWallet); $('#refresh-markets').addEventListener('click', () => loadMarkets()); + const contractBindings = [ + ['#contract-refresh', 'click', () => loadContract(true)], + ['#contract-withdraw-form', 'submit', contractWithdraw], + ['#contract-fee-form', 'submit', contractSetFee], + ['#contract-admin-form', 'submit', contractChangeAdmin], + ['#contract-pause', 'click', contractSetPaused], + ]; + contractBindings.forEach(([selector, event, handler]) => { + const el = $(selector); + if (el) el.addEventListener(event, handler); + }); $('#create-form').addEventListener('submit', createMarket); $('#sheet-confirm').addEventListener('click', () => { if (state.sheetMode === 'resolve') confirmResolve(); @@ -889,6 +1139,23 @@ }); document.addEventListener('click', (event) => { + const reloadEl = event.target.closest('[data-reload]'); + if (reloadEl) { + window.location.reload(); + return; + } + const unlinkEl = event.target.closest('[data-unlink-wallet]'); + if (unlinkEl) { + unlinkWallet(); + return; + } + const cancelEl = event.target.closest('[data-admin-cancel]'); + if (cancelEl) { + adminCancelMarket(Number(cancelEl.dataset.adminCancel)).catch((error) => { + toast(friendlyError(error), 'error'); + }); + return; + } const openEl = event.target.closest('[data-open-market]'); if (openEl) { openMarket(Number(openEl.dataset.openMarket)); @@ -911,6 +1178,7 @@ document.querySelectorAll('[data-pick-option]').forEach((el) => { el.classList.toggle('selected', el === pick); }); + scheduleQuote(); updateSheetSummary(); return; } @@ -928,6 +1196,7 @@ const input = $('#bet-amount'); if (input) input.value = quick.dataset.quick; state.selection.amount = quick.dataset.quick; + scheduleQuote(); updateSheetSummary(); return; } @@ -942,12 +1211,14 @@ document.addEventListener('input', (event) => { if (event.target && event.target.id === 'bet-amount') { state.selection.amount = event.target.value; + scheduleQuote(); updateSheetSummary(); } }); document.addEventListener('visibilitychange', () => { if (document.visibilityState === 'visible') { + pollNow(); loadMarkets(true); loadMine(); } diff --git a/web/static/icon.png b/web/static/icon.png index 4aad9f3..ca23bc8 100644 Binary files a/web/static/icon.png and b/web/static/icon.png differ diff --git a/web/static/styles.css b/web/static/styles.css index 6d8e30f..de8a5fb 100644 --- a/web/static/styles.css +++ b/web/static/styles.css @@ -52,8 +52,10 @@ body { overscroll-behavior-y: contain; } color: var(--muted); } .boot-logo { - font-size: 54px; - color: var(--accent); + width: 96px; + height: 96px; + margin: 0 auto; + border-radius: 22px; animation: pulse 1.6s ease-in-out infinite; } @keyframes pulse { 0%,100% { transform: scale(1); opacity: .8 } 50% { transform: scale(1.08); opacity: 1 } } @@ -71,12 +73,9 @@ body { overscroll-behavior-y: contain; } .brand p { margin: 0; } .brand-mark { width: 38px; height: 38px; - display: grid; place-content: center; border-radius: 12px; - background: linear-gradient(140deg, var(--accent), #7b5cff); - color: #fff; - font-size: 20px; - font-weight: 700; + object-fit: cover; + box-shadow: 0 0 0 1px var(--border); } .chip { @@ -351,3 +350,12 @@ textarea { resize: vertical; min-height: 84px; } .sheet { align-items: center; justify-items: center; } .sheet-panel { width: min(94vw, 480px); border-radius: 22px; } } + +/* ------------------------------------------------- contrato escrow (admin) */ +.contract-rows { display: grid; gap: 6px; margin: 10px 0; } +.contract-rows > div { display: flex; justify-content: space-between; gap: 10px; } +.contract-rows dt { color: var(--muted); font-size: 12.5px; margin: 0; } +.contract-rows dd { margin: 0; font-size: 12.5px; font-weight: 650; text-align: right; } + +/* Arranque fallido: el botón «Reintentar» se engancha por delegación (sin inline). */ +.boot-retry { max-width: 240px; margin: 0 auto; } diff --git a/web/static/tonconnect-ui.min.js b/web/static/tonconnect-ui.min.js new file mode 100644 index 0000000..554e8a9 --- /dev/null +++ b/web/static/tonconnect-ui.min.js @@ -0,0 +1,1295 @@ +!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).TON_CONNECT_UI={})}(this,function(e){"use strict";var t,n=Object.defineProperty,r=Object.defineProperties,o=Object.getOwnPropertyDescriptors,i=Object.getOwnPropertySymbols,a=Object.prototype.hasOwnProperty,s=Object.prototype.propertyIsEnumerable,l=Math.pow,c=(e,t,r)=>t in e?n(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,d=(e,t)=>{for(var n in t||(t={}))a.call(t,n)&&c(e,n,t[n]);if(i)for(var n of i(t))s.call(t,n)&&c(e,n,t[n]);return e},u=(e,t)=>r(e,o(t)),h=(e,t)=>{var n={};for(var r in e)a.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&i)for(var r of i(e))t.indexOf(r)<0&&s.call(e,r)&&(n[r]=e[r]);return n},p=(e,t,n)=>new Promise((r,o)=>{var i=e=>{try{s(n.next(e))}catch(Yo){o(Yo)}},a=e=>{try{s(n.throw(e))}catch(Yo){o(Yo)}},s=e=>e.done?r(e.value):Promise.resolve(e.value).then(i,a);s((n=n.apply(e,t)).next())});function f(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function g(e){if(Object.prototype.hasOwnProperty.call(e,"__esModule"))return e;var t=e.default;if("function"==typeof t){var n=function e(){var n=!1;try{n=this instanceof e}catch(r){}return n?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};n.prototype=t.prototype}else n={};return Object.defineProperty(n,"__esModule",{value:!0}),Object.keys(e).forEach(function(t){var r=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(n,t,r.get?r:{enumerable:!0,get:function(){return e[t]}})}),n}var m,v,w,y,b={exports:{}};const C=f((m||(m=1,w=b.exports,y=function(){var e={};function t(e){if(!/^(?:[A-Za-z0-9+\/]{2}[A-Za-z0-9+\/]{2})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$/.test(e))throw new TypeError("invalid encoding")}return e.decodeUTF8=function(e){if("string"!=typeof e)throw new TypeError("expected string");var t,n=unescape(encodeURIComponent(e)),r=new Uint8Array(n.length);for(t=0;t>24&255,e[t+1]=n>>16&255,e[t+2]=n>>8&255,e[t+3]=255&n,e[t+4]=r>>24&255,e[t+5]=r>>16&255,e[t+6]=r>>8&255,e[t+7]=255&r}function f(e,t,n,r,o){var i,a=0;for(i=0;i>>8)-1}function g(e,t,n,r){return f(e,t,n,r,16)}function m(e,t,n,r){return f(e,t,n,r,32)}function v(e,t,n,r){!function(e,t,n,r){for(var o,i=255&r[0]|(255&r[1])<<8|(255&r[2])<<16|(255&r[3])<<24,a=255&n[0]|(255&n[1])<<8|(255&n[2])<<16|(255&n[3])<<24,s=255&n[4]|(255&n[5])<<8|(255&n[6])<<16|(255&n[7])<<24,l=255&n[8]|(255&n[9])<<8|(255&n[10])<<16|(255&n[11])<<24,c=255&n[12]|(255&n[13])<<8|(255&n[14])<<16|(255&n[15])<<24,d=255&r[4]|(255&r[5])<<8|(255&r[6])<<16|(255&r[7])<<24,u=255&t[0]|(255&t[1])<<8|(255&t[2])<<16|(255&t[3])<<24,h=255&t[4]|(255&t[5])<<8|(255&t[6])<<16|(255&t[7])<<24,p=255&t[8]|(255&t[9])<<8|(255&t[10])<<16|(255&t[11])<<24,f=255&t[12]|(255&t[13])<<8|(255&t[14])<<16|(255&t[15])<<24,g=255&r[8]|(255&r[9])<<8|(255&r[10])<<16|(255&r[11])<<24,m=255&n[16]|(255&n[17])<<8|(255&n[18])<<16|(255&n[19])<<24,v=255&n[20]|(255&n[21])<<8|(255&n[22])<<16|(255&n[23])<<24,w=255&n[24]|(255&n[25])<<8|(255&n[26])<<16|(255&n[27])<<24,y=255&n[28]|(255&n[29])<<8|(255&n[30])<<16|(255&n[31])<<24,b=255&r[12]|(255&r[13])<<8|(255&r[14])<<16|(255&r[15])<<24,C=i,x=a,S=s,k=l,E=c,R=d,_=u,T=h,I=p,A=f,O=g,M=m,N=v,P=w,L=y,W=b,D=0;D<20;D+=2)C^=(o=(N^=(o=(I^=(o=(E^=(o=C+N|0)<<7|o>>>25)+C|0)<<9|o>>>23)+E|0)<<13|o>>>19)+I|0)<<18|o>>>14,R^=(o=(x^=(o=(P^=(o=(A^=(o=R+x|0)<<7|o>>>25)+R|0)<<9|o>>>23)+A|0)<<13|o>>>19)+P|0)<<18|o>>>14,O^=(o=(_^=(o=(S^=(o=(L^=(o=O+_|0)<<7|o>>>25)+O|0)<<9|o>>>23)+L|0)<<13|o>>>19)+S|0)<<18|o>>>14,W^=(o=(M^=(o=(T^=(o=(k^=(o=W+M|0)<<7|o>>>25)+W|0)<<9|o>>>23)+k|0)<<13|o>>>19)+T|0)<<18|o>>>14,C^=(o=(k^=(o=(S^=(o=(x^=(o=C+k|0)<<7|o>>>25)+C|0)<<9|o>>>23)+x|0)<<13|o>>>19)+S|0)<<18|o>>>14,R^=(o=(E^=(o=(T^=(o=(_^=(o=R+E|0)<<7|o>>>25)+R|0)<<9|o>>>23)+_|0)<<13|o>>>19)+T|0)<<18|o>>>14,O^=(o=(A^=(o=(I^=(o=(M^=(o=O+A|0)<<7|o>>>25)+O|0)<<9|o>>>23)+M|0)<<13|o>>>19)+I|0)<<18|o>>>14,W^=(o=(L^=(o=(P^=(o=(N^=(o=W+L|0)<<7|o>>>25)+W|0)<<9|o>>>23)+N|0)<<13|o>>>19)+P|0)<<18|o>>>14;C=C+i|0,x=x+a|0,S=S+s|0,k=k+l|0,E=E+c|0,R=R+d|0,_=_+u|0,T=T+h|0,I=I+p|0,A=A+f|0,O=O+g|0,M=M+m|0,N=N+v|0,P=P+w|0,L=L+y|0,W=W+b|0,e[0]=C>>>0&255,e[1]=C>>>8&255,e[2]=C>>>16&255,e[3]=C>>>24&255,e[4]=x>>>0&255,e[5]=x>>>8&255,e[6]=x>>>16&255,e[7]=x>>>24&255,e[8]=S>>>0&255,e[9]=S>>>8&255,e[10]=S>>>16&255,e[11]=S>>>24&255,e[12]=k>>>0&255,e[13]=k>>>8&255,e[14]=k>>>16&255,e[15]=k>>>24&255,e[16]=E>>>0&255,e[17]=E>>>8&255,e[18]=E>>>16&255,e[19]=E>>>24&255,e[20]=R>>>0&255,e[21]=R>>>8&255,e[22]=R>>>16&255,e[23]=R>>>24&255,e[24]=_>>>0&255,e[25]=_>>>8&255,e[26]=_>>>16&255,e[27]=_>>>24&255,e[28]=T>>>0&255,e[29]=T>>>8&255,e[30]=T>>>16&255,e[31]=T>>>24&255,e[32]=I>>>0&255,e[33]=I>>>8&255,e[34]=I>>>16&255,e[35]=I>>>24&255,e[36]=A>>>0&255,e[37]=A>>>8&255,e[38]=A>>>16&255,e[39]=A>>>24&255,e[40]=O>>>0&255,e[41]=O>>>8&255,e[42]=O>>>16&255,e[43]=O>>>24&255,e[44]=M>>>0&255,e[45]=M>>>8&255,e[46]=M>>>16&255,e[47]=M>>>24&255,e[48]=N>>>0&255,e[49]=N>>>8&255,e[50]=N>>>16&255,e[51]=N>>>24&255,e[52]=P>>>0&255,e[53]=P>>>8&255,e[54]=P>>>16&255,e[55]=P>>>24&255,e[56]=L>>>0&255,e[57]=L>>>8&255,e[58]=L>>>16&255,e[59]=L>>>24&255,e[60]=W>>>0&255,e[61]=W>>>8&255,e[62]=W>>>16&255,e[63]=W>>>24&255}(e,t,n,r)}function w(e,t,n,r){!function(e,t,n,r){for(var o,i=255&r[0]|(255&r[1])<<8|(255&r[2])<<16|(255&r[3])<<24,a=255&n[0]|(255&n[1])<<8|(255&n[2])<<16|(255&n[3])<<24,s=255&n[4]|(255&n[5])<<8|(255&n[6])<<16|(255&n[7])<<24,l=255&n[8]|(255&n[9])<<8|(255&n[10])<<16|(255&n[11])<<24,c=255&n[12]|(255&n[13])<<8|(255&n[14])<<16|(255&n[15])<<24,d=255&r[4]|(255&r[5])<<8|(255&r[6])<<16|(255&r[7])<<24,u=255&t[0]|(255&t[1])<<8|(255&t[2])<<16|(255&t[3])<<24,h=255&t[4]|(255&t[5])<<8|(255&t[6])<<16|(255&t[7])<<24,p=255&t[8]|(255&t[9])<<8|(255&t[10])<<16|(255&t[11])<<24,f=255&t[12]|(255&t[13])<<8|(255&t[14])<<16|(255&t[15])<<24,g=255&r[8]|(255&r[9])<<8|(255&r[10])<<16|(255&r[11])<<24,m=255&n[16]|(255&n[17])<<8|(255&n[18])<<16|(255&n[19])<<24,v=255&n[20]|(255&n[21])<<8|(255&n[22])<<16|(255&n[23])<<24,w=255&n[24]|(255&n[25])<<8|(255&n[26])<<16|(255&n[27])<<24,y=255&n[28]|(255&n[29])<<8|(255&n[30])<<16|(255&n[31])<<24,b=255&r[12]|(255&r[13])<<8|(255&r[14])<<16|(255&r[15])<<24,C=0;C<20;C+=2)i^=(o=(v^=(o=(p^=(o=(c^=(o=i+v|0)<<7|o>>>25)+i|0)<<9|o>>>23)+c|0)<<13|o>>>19)+p|0)<<18|o>>>14,d^=(o=(a^=(o=(w^=(o=(f^=(o=d+a|0)<<7|o>>>25)+d|0)<<9|o>>>23)+f|0)<<13|o>>>19)+w|0)<<18|o>>>14,g^=(o=(u^=(o=(s^=(o=(y^=(o=g+u|0)<<7|o>>>25)+g|0)<<9|o>>>23)+y|0)<<13|o>>>19)+s|0)<<18|o>>>14,b^=(o=(m^=(o=(h^=(o=(l^=(o=b+m|0)<<7|o>>>25)+b|0)<<9|o>>>23)+l|0)<<13|o>>>19)+h|0)<<18|o>>>14,i^=(o=(l^=(o=(s^=(o=(a^=(o=i+l|0)<<7|o>>>25)+i|0)<<9|o>>>23)+a|0)<<13|o>>>19)+s|0)<<18|o>>>14,d^=(o=(c^=(o=(h^=(o=(u^=(o=d+c|0)<<7|o>>>25)+d|0)<<9|o>>>23)+u|0)<<13|o>>>19)+h|0)<<18|o>>>14,g^=(o=(f^=(o=(p^=(o=(m^=(o=g+f|0)<<7|o>>>25)+g|0)<<9|o>>>23)+m|0)<<13|o>>>19)+p|0)<<18|o>>>14,b^=(o=(y^=(o=(w^=(o=(v^=(o=b+y|0)<<7|o>>>25)+b|0)<<9|o>>>23)+v|0)<<13|o>>>19)+w|0)<<18|o>>>14;e[0]=i>>>0&255,e[1]=i>>>8&255,e[2]=i>>>16&255,e[3]=i>>>24&255,e[4]=d>>>0&255,e[5]=d>>>8&255,e[6]=d>>>16&255,e[7]=d>>>24&255,e[8]=g>>>0&255,e[9]=g>>>8&255,e[10]=g>>>16&255,e[11]=g>>>24&255,e[12]=b>>>0&255,e[13]=b>>>8&255,e[14]=b>>>16&255,e[15]=b>>>24&255,e[16]=u>>>0&255,e[17]=u>>>8&255,e[18]=u>>>16&255,e[19]=u>>>24&255,e[20]=h>>>0&255,e[21]=h>>>8&255,e[22]=h>>>16&255,e[23]=h>>>24&255,e[24]=p>>>0&255,e[25]=p>>>8&255,e[26]=p>>>16&255,e[27]=p>>>24&255,e[28]=f>>>0&255,e[29]=f>>>8&255,e[30]=f>>>16&255,e[31]=f>>>24&255}(e,t,n,r)}var y=new Uint8Array([101,120,112,97,110,100,32,51,50,45,98,121,116,101,32,107]);function b(e,t,n,r,o,i,a){var s,l,c=new Uint8Array(16),d=new Uint8Array(64);for(l=0;l<16;l++)c[l]=0;for(l=0;l<8;l++)c[l]=i[l];for(;o>=64;){for(v(d,c,a,y),l=0;l<64;l++)e[t+l]=n[r+l]^d[l];for(s=1,l=8;l<16;l++)s=s+(255&c[l])|0,c[l]=255&s,s>>>=8;o-=64,t+=64,r+=64}if(o>0)for(v(d,c,a,y),l=0;l=64;){for(v(l,s,o,y),a=0;a<64;a++)e[t+a]=l[a];for(i=1,a=8;a<16;a++)i=i+(255&s[a])|0,s[a]=255&i,i>>>=8;n-=64,t+=64}if(n>0)for(v(l,s,o,y),a=0;a>>13|n<<3),r=255&e[4]|(255&e[5])<<8,this.r[2]=7939&(n>>>10|r<<6),o=255&e[6]|(255&e[7])<<8,this.r[3]=8191&(r>>>7|o<<9),i=255&e[8]|(255&e[9])<<8,this.r[4]=255&(o>>>4|i<<12),this.r[5]=i>>>1&8190,a=255&e[10]|(255&e[11])<<8,this.r[6]=8191&(i>>>14|a<<2),s=255&e[12]|(255&e[13])<<8,this.r[7]=8065&(a>>>11|s<<5),l=255&e[14]|(255&e[15])<<8,this.r[8]=8191&(s>>>8|l<<8),this.r[9]=l>>>5&127,this.pad[0]=255&e[16]|(255&e[17])<<8,this.pad[1]=255&e[18]|(255&e[19])<<8,this.pad[2]=255&e[20]|(255&e[21])<<8,this.pad[3]=255&e[22]|(255&e[23])<<8,this.pad[4]=255&e[24]|(255&e[25])<<8,this.pad[5]=255&e[26]|(255&e[27])<<8,this.pad[6]=255&e[28]|(255&e[29])<<8,this.pad[7]=255&e[30]|(255&e[31])<<8};function _(e,t,n,r,o,i){var a=new R(i);return a.update(n,r,o),a.finish(e,t),0}function T(e,t,n,r,o,i){var a=new Uint8Array(16);return _(a,0,n,r,o,i),g(e,t,a,0)}function I(e,t,n,r,o){var i;if(n<32)return-1;for(E(e,0,t,0,n,r,o),_(e,16,e,32,n-32,e),i=0;i<16;i++)e[i]=0;return 0}function A(e,t,n,r,o){var i,a=new Uint8Array(32);if(n<32)return-1;if(S(a,0,32,r,o),0!==T(t,16,t,32,n-32,a))return-1;for(E(e,0,t,0,n,r,o),i=0;i<32;i++)e[i]=0;return 0}function O(e,t){var n;for(n=0;n<16;n++)e[n]=0|t[n]}function M(e){var t,n,r=1;for(t=0;t<16;t++)n=e[t]+r+65535,r=Math.floor(n/65536),e[t]=n-65536*r;e[0]+=r-1+37*(r-1)}function N(e,t,n){for(var r,o=~(n-1),i=0;i<16;i++)r=o&(e[i]^t[i]),e[i]^=r,t[i]^=r}function P(e,n){var r,o,i,a=t(),s=t();for(r=0;r<16;r++)s[r]=n[r];for(M(s),M(s),M(s),o=0;o<2;o++){for(a[0]=s[0]-65517,r=1;r<15;r++)a[r]=s[r]-65535-(a[r-1]>>16&1),a[r-1]&=65535;a[15]=s[15]-32767-(a[14]>>16&1),i=a[15]>>16&1,a[14]&=65535,N(s,a,1-i)}for(r=0;r<16;r++)e[2*r]=255&s[r],e[2*r+1]=s[r]>>8}function L(e,t){var n=new Uint8Array(32),r=new Uint8Array(32);return P(n,e),P(r,t),m(n,0,r,0)}function W(e){var t=new Uint8Array(32);return P(t,e),1&t[0]}function D(e,t){var n;for(n=0;n<16;n++)e[n]=t[2*n]+(t[2*n+1]<<8);e[15]&=32767}function j(e,t,n){for(var r=0;r<16;r++)e[r]=t[r]+n[r]}function U(e,t,n){for(var r=0;r<16;r++)e[r]=t[r]-n[r]}function q(e,t,n){var r,o,i=0,a=0,s=0,l=0,c=0,d=0,u=0,h=0,p=0,f=0,g=0,m=0,v=0,w=0,y=0,b=0,C=0,x=0,S=0,k=0,E=0,R=0,_=0,T=0,I=0,A=0,O=0,M=0,N=0,P=0,L=0,W=n[0],D=n[1],j=n[2],U=n[3],q=n[4],B=n[5],z=n[6],F=n[7],K=n[8],H=n[9],V=n[10],$=n[11],G=n[12],X=n[13],Z=n[14],Y=n[15];i+=(r=t[0])*W,a+=r*D,s+=r*j,l+=r*U,c+=r*q,d+=r*B,u+=r*z,h+=r*F,p+=r*K,f+=r*H,g+=r*V,m+=r*$,v+=r*G,w+=r*X,y+=r*Z,b+=r*Y,a+=(r=t[1])*W,s+=r*D,l+=r*j,c+=r*U,d+=r*q,u+=r*B,h+=r*z,p+=r*F,f+=r*K,g+=r*H,m+=r*V,v+=r*$,w+=r*G,y+=r*X,b+=r*Z,C+=r*Y,s+=(r=t[2])*W,l+=r*D,c+=r*j,d+=r*U,u+=r*q,h+=r*B,p+=r*z,f+=r*F,g+=r*K,m+=r*H,v+=r*V,w+=r*$,y+=r*G,b+=r*X,C+=r*Z,x+=r*Y,l+=(r=t[3])*W,c+=r*D,d+=r*j,u+=r*U,h+=r*q,p+=r*B,f+=r*z,g+=r*F,m+=r*K,v+=r*H,w+=r*V,y+=r*$,b+=r*G,C+=r*X,x+=r*Z,S+=r*Y,c+=(r=t[4])*W,d+=r*D,u+=r*j,h+=r*U,p+=r*q,f+=r*B,g+=r*z,m+=r*F,v+=r*K,w+=r*H,y+=r*V,b+=r*$,C+=r*G,x+=r*X,S+=r*Z,k+=r*Y,d+=(r=t[5])*W,u+=r*D,h+=r*j,p+=r*U,f+=r*q,g+=r*B,m+=r*z,v+=r*F,w+=r*K,y+=r*H,b+=r*V,C+=r*$,x+=r*G,S+=r*X,k+=r*Z,E+=r*Y,u+=(r=t[6])*W,h+=r*D,p+=r*j,f+=r*U,g+=r*q,m+=r*B,v+=r*z,w+=r*F,y+=r*K,b+=r*H,C+=r*V,x+=r*$,S+=r*G,k+=r*X,E+=r*Z,R+=r*Y,h+=(r=t[7])*W,p+=r*D,f+=r*j,g+=r*U,m+=r*q,v+=r*B,w+=r*z,y+=r*F,b+=r*K,C+=r*H,x+=r*V,S+=r*$,k+=r*G,E+=r*X,R+=r*Z,_+=r*Y,p+=(r=t[8])*W,f+=r*D,g+=r*j,m+=r*U,v+=r*q,w+=r*B,y+=r*z,b+=r*F,C+=r*K,x+=r*H,S+=r*V,k+=r*$,E+=r*G,R+=r*X,_+=r*Z,T+=r*Y,f+=(r=t[9])*W,g+=r*D,m+=r*j,v+=r*U,w+=r*q,y+=r*B,b+=r*z,C+=r*F,x+=r*K,S+=r*H,k+=r*V,E+=r*$,R+=r*G,_+=r*X,T+=r*Z,I+=r*Y,g+=(r=t[10])*W,m+=r*D,v+=r*j,w+=r*U,y+=r*q,b+=r*B,C+=r*z,x+=r*F,S+=r*K,k+=r*H,E+=r*V,R+=r*$,_+=r*G,T+=r*X,I+=r*Z,A+=r*Y,m+=(r=t[11])*W,v+=r*D,w+=r*j,y+=r*U,b+=r*q,C+=r*B,x+=r*z,S+=r*F,k+=r*K,E+=r*H,R+=r*V,_+=r*$,T+=r*G,I+=r*X,A+=r*Z,O+=r*Y,v+=(r=t[12])*W,w+=r*D,y+=r*j,b+=r*U,C+=r*q,x+=r*B,S+=r*z,k+=r*F,E+=r*K,R+=r*H,_+=r*V,T+=r*$,I+=r*G,A+=r*X,O+=r*Z,M+=r*Y,w+=(r=t[13])*W,y+=r*D,b+=r*j,C+=r*U,x+=r*q,S+=r*B,k+=r*z,E+=r*F,R+=r*K,_+=r*H,T+=r*V,I+=r*$,A+=r*G,O+=r*X,M+=r*Z,N+=r*Y,y+=(r=t[14])*W,b+=r*D,C+=r*j,x+=r*U,S+=r*q,k+=r*B,E+=r*z,R+=r*F,_+=r*K,T+=r*H,I+=r*V,A+=r*$,O+=r*G,M+=r*X,N+=r*Z,P+=r*Y,b+=(r=t[15])*W,a+=38*(x+=r*j),s+=38*(S+=r*U),l+=38*(k+=r*q),c+=38*(E+=r*B),d+=38*(R+=r*z),u+=38*(_+=r*F),h+=38*(T+=r*K),p+=38*(I+=r*H),f+=38*(A+=r*V),g+=38*(O+=r*$),m+=38*(M+=r*G),v+=38*(N+=r*X),w+=38*(P+=r*Z),y+=38*(L+=r*Y),i=(r=(i+=38*(C+=r*D))+(o=1)+65535)-65536*(o=Math.floor(r/65536)),a=(r=a+o+65535)-65536*(o=Math.floor(r/65536)),s=(r=s+o+65535)-65536*(o=Math.floor(r/65536)),l=(r=l+o+65535)-65536*(o=Math.floor(r/65536)),c=(r=c+o+65535)-65536*(o=Math.floor(r/65536)),d=(r=d+o+65535)-65536*(o=Math.floor(r/65536)),u=(r=u+o+65535)-65536*(o=Math.floor(r/65536)),h=(r=h+o+65535)-65536*(o=Math.floor(r/65536)),p=(r=p+o+65535)-65536*(o=Math.floor(r/65536)),f=(r=f+o+65535)-65536*(o=Math.floor(r/65536)),g=(r=g+o+65535)-65536*(o=Math.floor(r/65536)),m=(r=m+o+65535)-65536*(o=Math.floor(r/65536)),v=(r=v+o+65535)-65536*(o=Math.floor(r/65536)),w=(r=w+o+65535)-65536*(o=Math.floor(r/65536)),y=(r=y+o+65535)-65536*(o=Math.floor(r/65536)),b=(r=b+o+65535)-65536*(o=Math.floor(r/65536)),i=(r=(i+=o-1+37*(o-1))+(o=1)+65535)-65536*(o=Math.floor(r/65536)),a=(r=a+o+65535)-65536*(o=Math.floor(r/65536)),s=(r=s+o+65535)-65536*(o=Math.floor(r/65536)),l=(r=l+o+65535)-65536*(o=Math.floor(r/65536)),c=(r=c+o+65535)-65536*(o=Math.floor(r/65536)),d=(r=d+o+65535)-65536*(o=Math.floor(r/65536)),u=(r=u+o+65535)-65536*(o=Math.floor(r/65536)),h=(r=h+o+65535)-65536*(o=Math.floor(r/65536)),p=(r=p+o+65535)-65536*(o=Math.floor(r/65536)),f=(r=f+o+65535)-65536*(o=Math.floor(r/65536)),g=(r=g+o+65535)-65536*(o=Math.floor(r/65536)),m=(r=m+o+65535)-65536*(o=Math.floor(r/65536)),v=(r=v+o+65535)-65536*(o=Math.floor(r/65536)),w=(r=w+o+65535)-65536*(o=Math.floor(r/65536)),y=(r=y+o+65535)-65536*(o=Math.floor(r/65536)),b=(r=b+o+65535)-65536*(o=Math.floor(r/65536)),i+=o-1+37*(o-1),e[0]=i,e[1]=a,e[2]=s,e[3]=l,e[4]=c,e[5]=d,e[6]=u,e[7]=h,e[8]=p,e[9]=f,e[10]=g,e[11]=m,e[12]=v,e[13]=w,e[14]=y,e[15]=b}function B(e,t){q(e,t,t)}function z(e,n){var r,o=t();for(r=0;r<16;r++)o[r]=n[r];for(r=253;r>=0;r--)B(o,o),2!==r&&4!==r&&q(o,o,n);for(r=0;r<16;r++)e[r]=o[r]}function F(e,n){var r,o=t();for(r=0;r<16;r++)o[r]=n[r];for(r=250;r>=0;r--)B(o,o),1!==r&&q(o,o,n);for(r=0;r<16;r++)e[r]=o[r]}function K(e,n,r){var o,i,a=new Uint8Array(32),l=new Float64Array(80),c=t(),d=t(),u=t(),h=t(),p=t(),f=t();for(i=0;i<31;i++)a[i]=n[i];for(a[31]=127&n[31]|64,a[0]&=248,D(l,r),i=0;i<16;i++)d[i]=l[i],h[i]=c[i]=u[i]=0;for(c[0]=h[0]=1,i=254;i>=0;--i)N(c,d,o=a[i>>>3]>>>(7&i)&1),N(u,h,o),j(p,c,u),U(c,c,u),j(u,d,h),U(d,d,h),B(h,p),B(f,c),q(c,u,c),q(u,d,p),j(p,c,u),U(c,c,u),B(d,c),U(u,h,f),q(c,u,s),j(c,c,h),q(u,u,c),q(c,h,f),q(h,d,l),B(d,p),N(c,d,o),N(u,h,o);for(i=0;i<16;i++)l[i+16]=c[i],l[i+32]=u[i],l[i+48]=d[i],l[i+64]=h[i];var g=l.subarray(32),m=l.subarray(16);return z(g,g),q(m,m,g),P(e,m),0}function H(e,t){return K(e,t,o)}function V(e,t){return n(t,32),H(e,t)}function $(e,t,n){var o=new Uint8Array(32);return K(o,n,t),w(e,r,o,y)}R.prototype.blocks=function(e,t,n){for(var r,o,i,a,s,l,c,d,u,h,p,f,g,m,v,w,y,b,C,x=this.fin?0:2048,S=this.h[0],k=this.h[1],E=this.h[2],R=this.h[3],_=this.h[4],T=this.h[5],I=this.h[6],A=this.h[7],O=this.h[8],M=this.h[9],N=this.r[0],P=this.r[1],L=this.r[2],W=this.r[3],D=this.r[4],j=this.r[5],U=this.r[6],q=this.r[7],B=this.r[8],z=this.r[9];n>=16;)h=u=0,h+=(S+=8191&(r=255&e[t+0]|(255&e[t+1])<<8))*N,h+=(k+=8191&(r>>>13|(o=255&e[t+2]|(255&e[t+3])<<8)<<3))*(5*z),h+=(E+=8191&(o>>>10|(i=255&e[t+4]|(255&e[t+5])<<8)<<6))*(5*B),h+=(R+=8191&(i>>>7|(a=255&e[t+6]|(255&e[t+7])<<8)<<9))*(5*q),u=(h+=(_+=8191&(a>>>4|(s=255&e[t+8]|(255&e[t+9])<<8)<<12))*(5*U))>>>13,h&=8191,h+=(T+=s>>>1&8191)*(5*j),h+=(I+=8191&(s>>>14|(l=255&e[t+10]|(255&e[t+11])<<8)<<2))*(5*D),h+=(A+=8191&(l>>>11|(c=255&e[t+12]|(255&e[t+13])<<8)<<5))*(5*W),h+=(O+=8191&(c>>>8|(d=255&e[t+14]|(255&e[t+15])<<8)<<8))*(5*L),p=u+=(h+=(M+=d>>>5|x)*(5*P))>>>13,p+=S*P,p+=k*N,p+=E*(5*z),p+=R*(5*B),u=(p+=_*(5*q))>>>13,p&=8191,p+=T*(5*U),p+=I*(5*j),p+=A*(5*D),p+=O*(5*W),u+=(p+=M*(5*L))>>>13,p&=8191,f=u,f+=S*L,f+=k*P,f+=E*N,f+=R*(5*z),u=(f+=_*(5*B))>>>13,f&=8191,f+=T*(5*q),f+=I*(5*U),f+=A*(5*j),f+=O*(5*D),g=u+=(f+=M*(5*W))>>>13,g+=S*W,g+=k*L,g+=E*P,g+=R*N,u=(g+=_*(5*z))>>>13,g&=8191,g+=T*(5*B),g+=I*(5*q),g+=A*(5*U),g+=O*(5*j),m=u+=(g+=M*(5*D))>>>13,m+=S*D,m+=k*W,m+=E*L,m+=R*P,u=(m+=_*N)>>>13,m&=8191,m+=T*(5*z),m+=I*(5*B),m+=A*(5*q),m+=O*(5*U),v=u+=(m+=M*(5*j))>>>13,v+=S*j,v+=k*D,v+=E*W,v+=R*L,u=(v+=_*P)>>>13,v&=8191,v+=T*N,v+=I*(5*z),v+=A*(5*B),v+=O*(5*q),w=u+=(v+=M*(5*U))>>>13,w+=S*U,w+=k*j,w+=E*D,w+=R*W,u=(w+=_*L)>>>13,w&=8191,w+=T*P,w+=I*N,w+=A*(5*z),w+=O*(5*B),y=u+=(w+=M*(5*q))>>>13,y+=S*q,y+=k*U,y+=E*j,y+=R*D,u=(y+=_*W)>>>13,y&=8191,y+=T*L,y+=I*P,y+=A*N,y+=O*(5*z),b=u+=(y+=M*(5*B))>>>13,b+=S*B,b+=k*q,b+=E*U,b+=R*j,u=(b+=_*D)>>>13,b&=8191,b+=T*W,b+=I*L,b+=A*P,b+=O*N,C=u+=(b+=M*(5*z))>>>13,C+=S*z,C+=k*B,C+=E*q,C+=R*U,u=(C+=_*j)>>>13,C&=8191,C+=T*D,C+=I*W,C+=A*L,C+=O*P,S=h=8191&(u=(u=((u+=(C+=M*N)>>>13)<<2)+u|0)+(h&=8191)|0),k=p+=u>>>=13,E=f&=8191,R=g&=8191,_=m&=8191,T=v&=8191,I=w&=8191,A=y&=8191,O=b&=8191,M=C&=8191,t+=16,n-=16;this.h[0]=S,this.h[1]=k,this.h[2]=E,this.h[3]=R,this.h[4]=_,this.h[5]=T,this.h[6]=I,this.h[7]=A,this.h[8]=O,this.h[9]=M},R.prototype.finish=function(e,t){var n,r,o,i,a=new Uint16Array(10);if(this.leftover){for(i=this.leftover,this.buffer[i++]=1;i<16;i++)this.buffer[i]=0;this.fin=1,this.blocks(this.buffer,0,16)}for(n=this.h[1]>>>13,this.h[1]&=8191,i=2;i<10;i++)this.h[i]+=n,n=this.h[i]>>>13,this.h[i]&=8191;for(this.h[0]+=5*n,n=this.h[0]>>>13,this.h[0]&=8191,this.h[1]+=n,n=this.h[1]>>>13,this.h[1]&=8191,this.h[2]+=n,a[0]=this.h[0]+5,n=a[0]>>>13,a[0]&=8191,i=1;i<10;i++)a[i]=this.h[i]+n,n=a[i]>>>13,a[i]&=8191;for(a[9]-=8192,r=(1^n)-1,i=0;i<10;i++)a[i]&=r;for(r=~r,i=0;i<10;i++)this.h[i]=this.h[i]&r|a[i];for(this.h[0]=65535&(this.h[0]|this.h[1]<<13),this.h[1]=65535&(this.h[1]>>>3|this.h[2]<<10),this.h[2]=65535&(this.h[2]>>>6|this.h[3]<<7),this.h[3]=65535&(this.h[3]>>>9|this.h[4]<<4),this.h[4]=65535&(this.h[4]>>>12|this.h[5]<<1|this.h[6]<<14),this.h[5]=65535&(this.h[6]>>>2|this.h[7]<<11),this.h[6]=65535&(this.h[7]>>>5|this.h[8]<<8),this.h[7]=65535&(this.h[8]>>>8|this.h[9]<<5),o=this.h[0]+this.pad[0],this.h[0]=65535&o,i=1;i<8;i++)o=(this.h[i]+this.pad[i]|0)+(o>>>16)|0,this.h[i]=65535&o;e[t+0]=this.h[0]>>>0&255,e[t+1]=this.h[0]>>>8&255,e[t+2]=this.h[1]>>>0&255,e[t+3]=this.h[1]>>>8&255,e[t+4]=this.h[2]>>>0&255,e[t+5]=this.h[2]>>>8&255,e[t+6]=this.h[3]>>>0&255,e[t+7]=this.h[3]>>>8&255,e[t+8]=this.h[4]>>>0&255,e[t+9]=this.h[4]>>>8&255,e[t+10]=this.h[5]>>>0&255,e[t+11]=this.h[5]>>>8&255,e[t+12]=this.h[6]>>>0&255,e[t+13]=this.h[6]>>>8&255,e[t+14]=this.h[7]>>>0&255,e[t+15]=this.h[7]>>>8&255},R.prototype.update=function(e,t,n){var r,o;if(this.leftover){for((o=16-this.leftover)>n&&(o=n),r=0;r=16&&(o=n-n%16,this.blocks(e,t,o),t+=o,n-=o),n){for(r=0;r=128;){for(x=0;x<16;x++)S=8*x+G,A[x]=n[S+0]<<24|n[S+1]<<16|n[S+2]<<8|n[S+3],O[x]=n[S+4]<<24|n[S+5]<<16|n[S+6]<<8|n[S+7];for(x=0;x<80;x++)if(o=M,i=N,a=P,s=L,l=W,c=D,d=j,h=q,p=B,f=z,g=F,m=K,v=H,w=V,R=65535&(E=$),_=E>>>16,T=65535&(k=U),I=k>>>16,R+=65535&(E=(K>>>14|W<<18)^(K>>>18|W<<14)^(W>>>9|K<<23)),_+=E>>>16,T+=65535&(k=(W>>>14|K<<18)^(W>>>18|K<<14)^(K>>>9|W<<23)),I+=k>>>16,R+=65535&(E=K&H^~K&V),_+=E>>>16,T+=65535&(k=W&D^~W&j),I+=k>>>16,R+=65535&(E=Z[2*x+1]),_+=E>>>16,T+=65535&(k=Z[2*x]),I+=k>>>16,k=A[x%16],_+=(E=O[x%16])>>>16,T+=65535&k,I+=k>>>16,T+=(_+=(R+=65535&E)>>>16)>>>16,R=65535&(E=C=65535&R|_<<16),_=E>>>16,T=65535&(k=b=65535&T|(I+=T>>>16)<<16),I=k>>>16,R+=65535&(E=(q>>>28|M<<4)^(M>>>2|q<<30)^(M>>>7|q<<25)),_+=E>>>16,T+=65535&(k=(M>>>28|q<<4)^(q>>>2|M<<30)^(q>>>7|M<<25)),I+=k>>>16,_+=(E=q&B^q&z^B&z)>>>16,T+=65535&(k=M&N^M&P^N&P),I+=k>>>16,u=65535&(T+=(_+=(R+=65535&E)>>>16)>>>16)|(I+=T>>>16)<<16,y=65535&R|_<<16,R=65535&(E=g),_=E>>>16,T=65535&(k=s),I=k>>>16,_+=(E=C)>>>16,T+=65535&(k=b),I+=k>>>16,N=o,P=i,L=a,W=s=65535&(T+=(_+=(R+=65535&E)>>>16)>>>16)|(I+=T>>>16)<<16,D=l,j=c,U=d,M=u,B=h,z=p,F=f,K=g=65535&R|_<<16,H=m,V=v,$=w,q=y,x%16==15)for(S=0;S<16;S++)k=A[S],R=65535&(E=O[S]),_=E>>>16,T=65535&k,I=k>>>16,k=A[(S+9)%16],R+=65535&(E=O[(S+9)%16]),_+=E>>>16,T+=65535&k,I+=k>>>16,b=A[(S+1)%16],R+=65535&(E=((C=O[(S+1)%16])>>>1|b<<31)^(C>>>8|b<<24)^(C>>>7|b<<25)),_+=E>>>16,T+=65535&(k=(b>>>1|C<<31)^(b>>>8|C<<24)^b>>>7),I+=k>>>16,b=A[(S+14)%16],_+=(E=((C=O[(S+14)%16])>>>19|b<<13)^(b>>>29|C<<3)^(C>>>6|b<<26))>>>16,T+=65535&(k=(b>>>19|C<<13)^(C>>>29|b<<3)^b>>>6),I+=k>>>16,I+=(T+=(_+=(R+=65535&E)>>>16)>>>16)>>>16,A[S]=65535&T|I<<16,O[S]=65535&R|_<<16;R=65535&(E=q),_=E>>>16,T=65535&(k=M),I=k>>>16,k=e[0],_+=(E=t[0])>>>16,T+=65535&k,I+=k>>>16,I+=(T+=(_+=(R+=65535&E)>>>16)>>>16)>>>16,e[0]=M=65535&T|I<<16,t[0]=q=65535&R|_<<16,R=65535&(E=B),_=E>>>16,T=65535&(k=N),I=k>>>16,k=e[1],_+=(E=t[1])>>>16,T+=65535&k,I+=k>>>16,I+=(T+=(_+=(R+=65535&E)>>>16)>>>16)>>>16,e[1]=N=65535&T|I<<16,t[1]=B=65535&R|_<<16,R=65535&(E=z),_=E>>>16,T=65535&(k=P),I=k>>>16,k=e[2],_+=(E=t[2])>>>16,T+=65535&k,I+=k>>>16,I+=(T+=(_+=(R+=65535&E)>>>16)>>>16)>>>16,e[2]=P=65535&T|I<<16,t[2]=z=65535&R|_<<16,R=65535&(E=F),_=E>>>16,T=65535&(k=L),I=k>>>16,k=e[3],_+=(E=t[3])>>>16,T+=65535&k,I+=k>>>16,I+=(T+=(_+=(R+=65535&E)>>>16)>>>16)>>>16,e[3]=L=65535&T|I<<16,t[3]=F=65535&R|_<<16,R=65535&(E=K),_=E>>>16,T=65535&(k=W),I=k>>>16,k=e[4],_+=(E=t[4])>>>16,T+=65535&k,I+=k>>>16,I+=(T+=(_+=(R+=65535&E)>>>16)>>>16)>>>16,e[4]=W=65535&T|I<<16,t[4]=K=65535&R|_<<16,R=65535&(E=H),_=E>>>16,T=65535&(k=D),I=k>>>16,k=e[5],_+=(E=t[5])>>>16,T+=65535&k,I+=k>>>16,I+=(T+=(_+=(R+=65535&E)>>>16)>>>16)>>>16,e[5]=D=65535&T|I<<16,t[5]=H=65535&R|_<<16,R=65535&(E=V),_=E>>>16,T=65535&(k=j),I=k>>>16,k=e[6],_+=(E=t[6])>>>16,T+=65535&k,I+=k>>>16,I+=(T+=(_+=(R+=65535&E)>>>16)>>>16)>>>16,e[6]=j=65535&T|I<<16,t[6]=V=65535&R|_<<16,R=65535&(E=$),_=E>>>16,T=65535&(k=U),I=k>>>16,k=e[7],_+=(E=t[7])>>>16,T+=65535&k,I+=k>>>16,I+=(T+=(_+=(R+=65535&E)>>>16)>>>16)>>>16,e[7]=U=65535&T|I<<16,t[7]=$=65535&R|_<<16,G+=128,r-=128}return r}function Q(e,t,n){var r,o=new Int32Array(8),i=new Int32Array(8),a=new Uint8Array(256),s=n;for(o[0]=1779033703,o[1]=3144134277,o[2]=1013904242,o[3]=2773480762,o[4]=1359893119,o[5]=2600822924,o[6]=528734635,o[7]=1541459225,i[0]=4089235720,i[1]=2227873595,i[2]=4271175723,i[3]=1595750129,i[4]=2917565137,i[5]=725511199,i[6]=4215389547,i[7]=327033209,Y(o,i,t,n),n%=128,r=0;r=0;--o)ee(e,t,r=n[o/8|0]>>(7&o)&1),J(t,e),J(e,e),ee(e,t,r)}function re(e,n){var r=[t(),t(),t(),t()];O(r[0],d),O(r[1],u),O(r[2],a),q(r[3],d,u),ne(e,r,n)}function oe(e,r,o){var i,a=new Uint8Array(64),s=[t(),t(),t(),t()];for(o||n(r,32),Q(a,r,32),a[0]&=248,a[31]&=127,a[31]|=64,re(s,a),te(e,s),i=0;i<32;i++)r[i+32]=e[i];return 0}var ie=new Float64Array([237,211,245,92,26,99,18,88,214,156,247,162,222,249,222,20,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16]);function ae(e,t){var n,r,o,i;for(r=63;r>=32;--r){for(n=0,o=r-32,i=r-12;o>4)*ie[o],n=t[o]>>8,t[o]&=255;for(o=0;o<32;o++)t[o]-=n*ie[o];for(r=0;r<32;r++)t[r+1]+=t[r]>>8,e[r]=255&t[r]}function se(e){var t,n=new Float64Array(64);for(t=0;t<64;t++)n[t]=e[t];for(t=0;t<64;t++)e[t]=0;ae(e,n)}function le(e,n,r,o){var i,a,s=new Uint8Array(64),l=new Uint8Array(64),c=new Uint8Array(64),d=new Float64Array(64),u=[t(),t(),t(),t()];Q(s,o,32),s[0]&=248,s[31]&=127,s[31]|=64;var h=r+64;for(i=0;i>7&&U(e[0],i,e[0]),q(e[3],e[0],e[1]),0)}(p,o))return-1;for(s=0;s=0},e.sign.keyPair=function(){var e=new Uint8Array(pe),t=new Uint8Array(fe);return oe(e,t),{publicKey:e,secretKey:t}},e.sign.keyPair.fromSecretKey=function(e){if(me(e),e.length!==fe)throw new Error("bad secret key size");for(var t=new Uint8Array(pe),n=0;nC.encodeUTF8(n),toObject(){try{return JSON.parse(C.encodeUTF8(n))}catch(e){return null}},toUint8Array:()=>n}}};function W(e){const t={address:e.a,amount:e.am};return void 0!==e.p&&(t.payload=e.p),void 0!==e.si&&(t.stateInit=e.si),void 0!==e.ec&&(t.extra_currency=e.ec),t}function D(e){switch(e.t){case"ton":{const t={type:"ton",address:e.a,amount:e.am};return void 0!==e.p&&(t.payload=e.p),void 0!==e.si&&(t.stateInit=e.si),void 0!==e.ec&&(t.extra_currency=e.ec),t}case"jetton":{const t={type:"jetton",master:e.ma,destination:e.d,amount:e.am};return void 0!==e.aa&&(t.attachAmount=e.aa),void 0!==e.rd&&(t.responseDestination=e.rd),void 0!==e.cp&&(t.customPayload=e.cp),void 0!==e.fa&&(t.forwardAmount=e.fa),void 0!==e.fp&&(t.forwardPayload=e.fp),void 0!==e.qi&&(t.queryId=e.qi),t}case"nft":{const t={type:"nft",nftAddress:e.na,newOwner:e.no};return void 0!==e.aa&&(t.attachAmount=e.aa),void 0!==e.rd&&(t.responseDestination=e.rd),void 0!==e.cp&&(t.customPayload=e.cp),void 0!==e.fa&&(t.forwardAmount=e.fa),void 0!==e.fp&&(t.forwardPayload=e.fp),void 0!==e.qi&&(t.queryId=e.qi),t}}}function j(e){const t={};return void 0!==e.vu&&(t.valid_until=e.vu),void 0!==e.n&&(t.network=e.n),void 0!==e.f&&(t.from=e.f),e.ms&&(t.messages=e.ms.map(W)),e.i&&(t.items=e.i.map(D)),t}function U(e){const t={};switch(void 0!==e.n&&(t.network=e.n),void 0!==e.f&&(t.from=e.f),e.t){case"text":t.type="text",t.text=e.tx;break;case"binary":t.type="binary",t.bytes=e.b;break;case"cell":t.type="cell",t.schema=e.s,t.cell=e.c}return t}function q(e){switch(e.m){case"st":return{method:"sendTransaction",params:[JSON.stringify(j(e))]};case"sm":return{method:"signMessage",params:[JSON.stringify(j(e))]};case"sd":return{method:"signData",params:[JSON.stringify(U(e))]}}}function B(e,t){const n=new Uint8Array(e.length+t.length);return n.set(e),n.set(t,e.length),n}function z(e,t){if(t>=e.length)throw new Error("Index is out of buffer");return[e.slice(0,t),e.slice(t)]}function F(e){let t="";return e.forEach(e=>{t+=("0"+(255&e).toString(16)).slice(-2)}),t}function K(e){if(e.length%2!=0)throw new Error(`Cannot convert ${e} to bytesArray`);const t=new Uint8Array(e.length/2);for(let n=0;n{setTimeout(()=>t(),e)})})}function He(e){const t=new AbortController;return(null==e?void 0:e.aborted)?t.abort():null==e||e.addEventListener("abort",()=>t.abort(),{once:!0}),t}function Ve(e,t){return $(this,0,void 0,function*(){var n,r;const o=null!==(n=null==t?void 0:t.attempts)&&void 0!==n?n:10,i=null!==(r=null==t?void 0:t.delayMs)&&void 0!==r?r:200,a=He(null==t?void 0:t.signal);if("function"!=typeof e)throw new G("Expected a function, got "+typeof e);let s,l=0;for(;l$(this,0,void 0,function*(){if(i=null!=s?s:null,null==a||a.abort(),a=He(s),a.signal.aborted)throw new G("Resource creation was aborted");r=null!=l?l:null;const c=e(a.signal,...l);o=c;const d=yield c;if(o!==c&&d!==n)throw yield t(d),new G("Resource creation was aborted by a new resource creation");return n=d,n});return{create:s,current:()=>null!=n?n:null,dispose:()=>$(this,0,void 0,function*(){try{const r=n;n=null;const i=o;o=null;try{null==a||a.abort()}catch(e){}yield Promise.allSettled([r?t(r):Promise.resolve(),i?t(yield i):Promise.resolve()])}catch(e){}}),recreate:e=>$(this,0,void 0,function*(){const t=n,a=o,l=r,c=i;if(yield Ke(e),t===n&&a===o&&l===r&&c===i)return yield s(i,...null!=l?l:[]);throw new G("Resource recreation was aborted by a new resource creation")})}}((e,t,n)=>$(this,0,void 0,function*(){const r={bridgeUrl:this.bridgeUrl,ssePath:this.ssePath,sessionId:this.sessionId,bridgeGatewayStorage:this.bridgeGatewayStorage,errorHandler:this.errorsHandler.bind(this),messageHandler:this.messagesHandler.bind(this),signal:e,openingDeadlineMS:t,traceId:n};return yield function(e){return $(this,0,void 0,function*(){return yield function(e,t){const n=null==t?void 0:t.timeout,r=He(null==t?void 0:t.signal);return new Promise((t,o)=>$(this,0,void 0,function*(){if(r.signal.aborted)return void o(new G("Operation aborted"));let i;void 0!==n&&(i=setTimeout(()=>{r.abort(),o(new G(`Timeout after ${n}ms`))},n)),r.signal.addEventListener("abort",()=>{clearTimeout(i),o(new G("Operation aborted"))},{once:!0});const a={timeout:n,abort:r.signal};yield e((...e)=>{clearTimeout(i),t(...e)},()=>{clearTimeout(i),o()},a)}))}((t,n,r)=>$(this,0,void 0,function*(){var o;const i=He(r.signal).signal;if(i.aborted)return void n(new G("Bridge connection aborted"));const a=new URL(Le(e.bridgeUrl,e.ssePath));a.searchParams.append("client_id",e.sessionId);const s=yield e.bridgeGatewayStorage.getLastEventId();if(s&&a.searchParams.append("last_event_id",s),e.traceId&&a.searchParams.append("trace_id",e.traceId),i.aborted)return void n(new G("Bridge connection aborted"));const l=new EventSource(a.toString());l.onerror=r=>$(this,0,void 0,function*(){if(i.aborted)return l.close(),void n(new G("Bridge connection aborted"));try{const n=yield e.errorHandler(l,r);n!==l&&l.close(),n&&n!==l&&t(n)}catch(o){l.close(),n(o)}}),l.onopen=()=>{if(i.aborted)return l.close(),void n(new G("Bridge connection aborted"));t(l)},l.onmessage=t=>{if(i.aborted)return l.close(),void n(new G("Bridge connection aborted"));e.messageHandler(t)},null===(o=e.signal)||void 0===o||o.addEventListener("abort",()=>{l.close(),n(new G("Bridge connection aborted"))})}),{timeout:e.openingDeadlineMS,signal:e.signal})})}(r)}),e=>$(this,0,void 0,function*(){e.close()})),this.bridgeGatewayStorage=new Pe(e,t),this.analytics=null==i?void 0:i.scoped({bridge_url:t,client_id:n})}registerSession(e){return $(this,0,void 0,function*(){var t,n,r;try{null===(t=this.analytics)||void 0===t||t.emitBridgeClientConnectStarted({trace_id:null==e?void 0:e.traceId});const r=Date.now();yield this.eventSource.create(null==e?void 0:e.signal,null==e?void 0:e.openingDeadlineMS,null==e?void 0:e.traceId);const o=Date.now()-r;null===(n=this.analytics)||void 0===n||n.emitBridgeClientConnectEstablished({bridge_connect_duration:o,trace_id:null==e?void 0:e.traceId})}catch(o){throw null===(r=this.analytics)||void 0===r||r.emitBridgeClientConnectError({trace_id:null==e?void 0:e.traceId,error_message:String(o)}),o}})}send(e,t,n,r){return $(this,0,void 0,function*(){var o;const i={};"number"==typeof r?i.ttl=r:(i.ttl=null==r?void 0:r.ttl,i.signal=null==r?void 0:r.signal,i.attempts=null==r?void 0:r.attempts,i.traceId=null==r?void 0:r.traceId);const a=new URL(Le(this.bridgeUrl,this.postPath));a.searchParams.append("client_id",this.sessionId),a.searchParams.append("to",t),a.searchParams.append("ttl",((null==i?void 0:i.ttl)||this.defaultTtl).toString()),a.searchParams.append("topic",n),(null==i?void 0:i.traceId)&&a.searchParams.append("trace_id",i.traceId);const s=L.encode(e);yield Ve(e=>$(this,0,void 0,function*(){const t=yield this.post(a,s,e.signal);if(!t.ok)throw new G(`Bridge send failed, status ${t.status}`)}),{attempts:null!==(o=null==i?void 0:i.attempts)&&void 0!==o?o:Number.MAX_SAFE_INTEGER,delayMs:this.defaultResendDelay,signal:null==i?void 0:i.signal})})}pause(){this.eventSource.dispose().catch(e=>Ge(`Bridge pause failed, ${e}`))}unPause(){return $(this,0,void 0,function*(){yield this.eventSource.recreate(0)})}close(){return $(this,0,void 0,function*(){yield this.eventSource.dispose().catch(e=>Ge(`Bridge close failed, ${e}`))})}setListener(e){this.listener=e}setErrorsListener(e){this.errorsListener=e}post(e,t,n){return $(this,0,void 0,function*(){const r=yield fetch(e,{method:"post",body:t,signal:n});if(!r.ok)throw new G(`Bridge send failed, status ${r.status}`);return r})}errorsHandler(e,t){return $(this,0,void 0,function*(){if(this.isConnecting)throw e.close(),new G("Bridge error, failed to connect");if(!this.isReady){if(this.isClosed)return e.close(),$e(`Bridge reconnecting, ${this.defaultReconnectDelay}ms delay`),yield this.eventSource.recreate(this.defaultReconnectDelay);throw new G("Bridge error, unknown state")}try{this.errorsListener(t)}catch(n){}})}messagesHandler(e){return $(this,0,void 0,function*(){if(e.data===this.heartbeatMessage)return;if(yield this.bridgeGatewayStorage.storeLastEventId(e.lastEventId),this.isClosed)return;let t;try{const n=JSON.parse(e.data);t={message:n.message,from:n.from,traceId:n.trace_id}}catch(n){throw new G(`Bridge message parse failed, message ${e.data}`)}this.listener(t)})}}function Ye(e){return!("connectEvent"in e)}let Qe;const Je=new Uint8Array(16);function et(){if(!Qe){if("undefined"==typeof crypto||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");Qe=crypto.getRandomValues.bind(crypto)}return Qe(Je)}const tt=[];for(let pm=0;pm<256;++pm)tt.push((pm+256).toString(16).slice(1));const nt={};function rt(e,t,n){var r,o,i;let a;if(e)a=ot(null!==(i=null!==(r=e.random)&&void 0!==r?r:null===(o=e.rng)||void 0===o?void 0:o.call(e))&&void 0!==i?i:et(),e.msecs,e.seq,t,n);else{const e=Date.now(),r=et();!function(e,t,n){var r,o;null!==(r=e.msecs)&&void 0!==r||(e.msecs=-1/0),null!==(o=e.seq)&&void 0!==o||(e.seq=0),t>e.msecs?(e.seq=n[6]<<23|n[7]<<16|n[8]<<8|n[9],e.msecs=t):(e.seq=e.seq+1|0,0===e.seq&&e.msecs++)}(nt,e,r),a=ot(r,nt.msecs,nt.seq,t,n)}return null!=t?t:function(e,t=0){return(tt[e[t+0]]+tt[e[t+1]]+tt[e[t+2]]+tt[e[t+3]]+"-"+tt[e[t+4]]+tt[e[t+5]]+"-"+tt[e[t+6]]+tt[e[t+7]]+"-"+tt[e[t+8]]+tt[e[t+9]]+"-"+tt[e[t+10]]+tt[e[t+11]]+tt[e[t+12]]+tt[e[t+13]]+tt[e[t+14]]+tt[e[t+15]]).toLowerCase()}(a)}function ot(e,t,n,r,o=0){if(e.length<16)throw new Error("Random bytes length must be >= 16");if(r){if(o<0||o+16>r.length)throw new RangeError(`UUID byte range ${o}:${o+15} is out of buffer bounds`)}else r=new Uint8Array(16),o=0;return null!=t||(t=Date.now()),null!=n||(n=127*e[6]<<24|e[7]<<16|e[8]<<8|e[9]),r[o++]=t/1099511627776&255,r[o++]=t/4294967296&255,r[o++]=t/16777216&255,r[o++]=t/65536&255,r[o++]=t/256&255,r[o++]=255&t,r[o++]=112|n>>>28&15,r[o++]=n>>>20&255,r[o++]=128|n>>>14&63,r[o++]=n>>>6&255,r[o++]=n<<2&255|3&e[10],r[o++]=e[11],r[o++]=e[12],r[o++]=e[13],r[o++]=e[14],r[o++]=e[15],r}function it(e){if("string"!=typeof e)return;const t=e.length+(4-e.length%4)%4;return e.replace(/-/g,"+").replace(/_/g,"/").padEnd(t,"=")}function at(e,t,n){return We(e)?function(e,t,n){const r=st("about:blank",t,n),o="tonconnect-"+je(r.split("?")[1]),i=function(e){const t=new URL(e);t.searchParams.has("attach")&&(t.searchParams.delete("attach"),t.pathname+="/start");return t.toString()}(e),a=new URL(i);return a.searchParams.append("startapp",o),a.toString()}(e,t,n):st(e,t,n)}function st(e,t,n){const r=new URL(e);return r.searchParams.append("v",2..toString()),r.searchParams.append("id",n.sessionId),r.searchParams.append("trace_id",n.traceId),r.searchParams.append("r",JSON.stringify(t)),n.embeddedRequest&&r.searchParams.append("e",L.encode(JSON.stringify(n.embeddedRequest),!1).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")),r.toString()}class lt{static fromStorage(e,t){return $(this,0,void 0,function*(){const n=yield e.getHttpConnection();return Ye(n)?new lt(e,n.connectionSource,t):new lt(e,{bridgeUrl:n.session.bridgeUrl},t)})}constructor(e,t,n){var r;this.connectionStorage=e,this.walletConnectionSource=t,this.analyticsManager=n,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.maxUrlLength=1024,this.optionalOpenGateways=3,this.analytics=null===(r=this.analyticsManager)||void 0===r?void 0:r.scoped()}connect(e,t){var n,r,o,i;const a=null!==(n=null==t?void 0:t.traceId)&&void 0!==n?n:rt(),s=He(null==t?void 0:t.signal);null===(r=this.abortController)||void 0===r||r.abort(),this.abortController=s,this.closeGateways();const l=new H;this.session={sessionCrypto:l,bridgeUrl:"bridgeUrl"in this.walletConnectionSource?this.walletConnectionSource.bridgeUrl:""},this.connectionStorage.storeConnection({type:"http",connectionSource:this.walletConnectionSource,sessionCrypto:l}).then(()=>$(this,0,void 0,function*(){s.signal.aborted||(yield Ve(e=>{var n;return this.openGateways(l,{openingDeadlineMS:null!==(n=null==t?void 0:t.openingDeadlineMS)&&void 0!==n?n:this.defaultOpeningDeadlineMS,signal:null==e?void 0:e.signal,traceId:a})},{attempts:Number.MAX_SAFE_INTEGER,delayMs:this.defaultRetryTimeoutMS,signal:s.signal}))}));const c="universalLink"in this.walletConnectionSource&&this.walletConnectionSource.universalLink?this.walletConnectionSource.universalLink:this.standardUniversalLink,d=null===(o=null==t?void 0:t.embeddedRequest)||void 0===o?void 0:o.peek(),u=at(c,e,{traceId:a,sessionId:this.session.sessionCrypto.sessionId,embeddedRequest:d});return u.length<=this.maxUrlLength?(null===(i=null==t?void 0:t.embeddedRequest)||void 0===i||i.consume(),u):at(c,e,{traceId:a,sessionId:this.session.sessionCrypto.sessionId})}restoreConnection(e){return $(this,0,void 0,function*(){var t,n,r;const o=null!==(t=null==e?void 0:e.traceId)&&void 0!==t?t:rt(),i=He(null==e?void 0:e.signal);if(null===(n=this.abortController)||void 0===n||n.abort(),this.abortController=i,i.signal.aborted)return;this.closeGateways();const a=yield this.connectionStorage.getHttpConnection();if(!a)return;if(i.signal.aborted)return;const s=null!==(r=null==e?void 0:e.openingDeadlineMS)&&void 0!==r?r:this.defaultOpeningDeadlineMS;if(Ye(a))return this.session={sessionCrypto:a.sessionCrypto,bridgeUrl:"bridgeUrl"in this.walletConnectionSource?this.walletConnectionSource.bridgeUrl:""},yield this.openGateways(a.sessionCrypto,{openingDeadlineMS:s,signal:null==i?void 0:i.signal,traceId:null==e?void 0:e.traceId});if(Array.isArray(this.walletConnectionSource))throw new G("Internal error. Connection source is array while WalletConnectionSourceHTTP was expected.");if(this.session=a.session,this.gateway&&($e("Gateway is already opened, closing previous gateway"),yield this.gateway.close()),this.gateway=new Ze(this.connectionStorage.storage,this.walletConnectionSource.bridgeUrl,a.session.sessionCrypto.sessionId,this.gatewayListener.bind(this),this.gatewayErrorsListener.bind(this),this.analyticsManager),!i.signal.aborted){this.listeners.forEach(e=>e(Object.assign(Object.assign({},a.connectEvent),{traceId:o,restored:!0})));try{yield Ve(e=>this.gateway.registerSession({openingDeadlineMS:s,signal:e.signal,traceId:o}),{attempts:Number.MAX_SAFE_INTEGER,delayMs:this.defaultRetryTimeoutMS,signal:i.signal})}catch(l){return void(yield this.disconnect({signal:i.signal,traceId:o}))}}})}sendRequest(e,t){var n;const r={};return"function"==typeof t?r.onRequestSent=t:(r.onRequestSent=null==t?void 0:t.onRequestSent,r.signal=null==t?void 0:t.signal,r.attempts=null==t?void 0:t.attempts,r.traceId=null==t?void 0:t.traceId),null!==(n=r.traceId)&&void 0!==n||(r.traceId=rt()),new Promise((t,n)=>$(this,0,void 0,function*(){var o,i;if(!this.gateway||!this.session||!("walletPublicKey"in this.session))throw new G("Trying to send bridge request without session");const a=(yield this.connectionStorage.getNextRpcRequestId()).toString();yield this.connectionStorage.increaseNextRpcRequestId(),$e("Send http-bridge request:",Object.assign(Object.assign({},e),{id:a}));const s=this.session.sessionCrypto.encrypt(JSON.stringify(Object.assign(Object.assign({},e),{id:a})),K(this.session.walletPublicKey));try{null===(o=this.analytics)||void 0===o||o.emitBridgeClientMessageSent({bridge_url:this.gateway.bridgeUrl,client_id:this.session.sessionCrypto.sessionId,wallet_id:this.session.walletPublicKey,message_id:a,request_type:e.method,trace_id:r.traceId}),yield this.gateway.send(s,this.session.walletPublicKey,e.method,{attempts:null==r?void 0:r.attempts,signal:null==r?void 0:r.signal,traceId:r.traceId}),null===(i=null==r?void 0:r.onRequestSent)||void 0===i||i.call(r),this.pendingRequests.set(a.toString(),t)}catch(l){n(l)}}))}closeConnection(){this.closeGateways(),this.listeners=[],this.session=null,this.gateway=null}disconnect(e){return $(this,0,void 0,function*(){var t;const n=null!==(t=null==e?void 0:e.traceId)&&void 0!==t?t:rt();return new Promise(t=>$(this,0,void 0,function*(){let r=!1,o=null;const i=()=>{r||(r=!0,this.removeBridgeAndSession().then(t))};try{this.closeGateways();const t=He(null==e?void 0:e.signal);o=setTimeout(()=>{t.abort()},this.defaultOpeningDeadlineMS),yield this.sendRequest({method:"disconnect",params:[]},{onRequestSent:i,signal:t.signal,attempts:1,traceId:n})}catch(a){$e("Disconnect error:",a),r||this.removeBridgeAndSession().then(t)}finally{o&&clearTimeout(o),i()}}))})}listen(e){return this.listeners.push(e),()=>this.listeners=this.listeners.filter(t=>t!==e)}pause(){var e;null===(e=this.gateway)||void 0===e||e.pause(),this.pendingGateways.forEach(e=>e.pause())}unPause(){return $(this,0,void 0,function*(){const e=this.pendingGateways.map(e=>e.unPause());this.gateway&&e.push(this.gateway.unPause()),yield Promise.all(e)})}pendingGatewaysListener(e,t,n){return $(this,0,void 0,function*(){if(this.pendingGateways.includes(e))return this.closeGateways({except:e}),this.gateway&&($e("Gateway is already opened, closing previous gateway"),yield this.gateway.close()),this.session.bridgeUrl=t,this.gateway=e,this.gateway.setErrorsListener(this.gatewayErrorsListener.bind(this)),this.gateway.setListener(this.gatewayListener.bind(this)),this.gatewayListener(n);yield e.close()})}gatewayListener(e){return $(this,0,void 0,function*(){var t,n,r;const o=null!==(t=e.traceId)&&void 0!==t?t:rt();let i;try{i=JSON.parse(this.session.sessionCrypto.decrypt(L.decode(e.message).toUint8Array(),K(e.from)))}catch(l){throw null===(n=this.analytics)||void 0===n||n.emitBridgeClientMessageDecodeError({bridge_url:this.session.bridgeUrl,client_id:this.session.sessionCrypto.sessionId,wallet_id:e.from,error_message:String(l),trace_id:null==e?void 0:e.traceId}),l}$e("Wallet message received:",i);const a="event"in i?i.event:"";if(null===(r=this.analytics)||void 0===r||r.emitBridgeClientMessageReceived({bridge_url:this.session.bridgeUrl,client_id:this.session.sessionCrypto.sessionId,wallet_id:e.from,message_id:String(i.id),request_type:a,trace_id:null==e?void 0:e.traceId}),!("event"in i)){const e=i.id.toString(),t=this.pendingRequests.get(e);return t?(t(Object.assign(Object.assign({},i),{traceId:o})),void this.pendingRequests.delete(e)):void $e(`Response id ${e} doesn't match any request's id`)}if(void 0!==i.id){const e=yield this.connectionStorage.getLastWalletEventId();if(void 0!==e&&i.id<=e)return void Ge(`Received event id (=${i.id}) must be greater than stored last wallet event id (=${e}) `);"connect"!==i.event&&(yield this.connectionStorage.storeLastWalletEventId(i.id))}const s=this.listeners;"connect"===i.event&&(yield this.updateSession(i,e.from)),"disconnect"===i.event&&($e("Removing bridge and session: received disconnect event"),yield this.removeBridgeAndSession()),s.forEach(e=>e(Object.assign(Object.assign({},i),{traceId:o})))})}gatewayErrorsListener(e){return $(this,0,void 0,function*(){throw new G(`Bridge error ${JSON.stringify(e)}`)})}updateSession(e,t){return $(this,0,void 0,function*(){this.session=Object.assign(Object.assign({},this.session),{walletPublicKey:t});const n=e.payload.items.find(e=>"ton_addr"===e.name),r=Object.assign(Object.assign({},e),{payload:Object.assign(Object.assign({},e.payload),{items:[n]})});yield this.connectionStorage.storeConnection({type:"http",session:this.session,lastWalletEventId:e.id,connectEvent:r,nextRpcRequestId:0})})}removeBridgeAndSession(){return $(this,0,void 0,function*(){this.closeConnection(),yield this.connectionStorage.removeConnection()})}openGateways(e,t){return $(this,0,void 0,function*(){var n;const r=null!==(n=null==t?void 0:t.traceId)&&void 0!==n?n:rt();if(Array.isArray(this.walletConnectionSource)){this.pendingGateways.map(e=>e.close().catch()),this.pendingGateways=this.walletConnectionSource.map(t=>{const n=new Ze(this.connectionStorage.storage,t.bridgeUrl,e.sessionId,()=>{},()=>{},this.analyticsManager);return n.setListener(e=>this.pendingGatewaysListener(n,t.bridgeUrl,e)),n});const n=Math.max(this.pendingGateways.length-this.optionalOpenGateways,1);return void(yield function(e,t){return $(this,0,void 0,function*(){if(t<=0)return[];if(t>e.length)throw new RangeError("count cannot be greater than the number of promises");const n=new Array(e.length);let r=0;return new Promise(o=>{e.forEach((e,i)=>{Promise.resolve(e).then(e=>({status:"fulfilled",value:e})).catch(e=>({status:"rejected",reason:e})).then(e=>{n[i]=e,r++,r===t&&o(n)})})})})}(this.pendingGateways.map(e=>Ve(n=>{var o;return this.pendingGateways.some(t=>t===e)?e.registerSession({openingDeadlineMS:null!==(o=null==t?void 0:t.openingDeadlineMS)&&void 0!==o?o:this.defaultOpeningDeadlineMS,signal:n.signal,traceId:r}):e.close()},{attempts:Number.MAX_SAFE_INTEGER,delayMs:this.defaultRetryTimeoutMS,signal:null==t?void 0:t.signal})),n))}return this.gateway&&($e("Gateway is already opened, closing previous gateway"),yield this.gateway.close()),this.gateway=new Ze(this.connectionStorage.storage,this.walletConnectionSource.bridgeUrl,e.sessionId,this.gatewayListener.bind(this),this.gatewayErrorsListener.bind(this),this.analyticsManager),yield this.gateway.registerSession({openingDeadlineMS:null==t?void 0:t.openingDeadlineMS,signal:null==t?void 0:t.signal,traceId:r})})}closeGateways(e){var t;null===(t=this.gateway)||void 0===t||t.close(),this.pendingGateways.filter(t=>t!==(null==e?void 0:e.except)).forEach(e=>e.close()),this.pendingGateways=[]}}function ct(e){if("object"!=typeof e||null===e||Array.isArray(e))return;const t=e,n=t.code;if("number"!=typeof n||!Number.isSafeInteger(n))return;const r={code:n,message:"string"==typeof t.message?t.message:""};return"data"in t&&(r.data=t.data),r}const dt=/^(0|[1-9][0-9]{0,2})$/;function ut(e){return Object.prototype.toString.call(e)}function ht(e,t){return e&&t.has(e.code)?e:void 0}function pt(e,t){try{const n=ut(e);if("[object DOMException]"===n)return;if("number"==typeof e)return Number.isSafeInteger(e)?ht({code:e,message:""},t):void 0;if("[object Object]"===n){const n=e;return ht(ct("[object Object]"===ut(n.error)?n.error:n),t)}if("object"==typeof e&&null!==e){const n=e.message;return"string"==typeof n&&dt.test(n)?ht({code:Number(n),message:n},t):void 0}return}catch(n){return}}function ft(e,t){return gt(e,[t])}function gt(e,t){return!(!e||"object"!=typeof e)&&t.every(t=>t in e)}let mt=class e{static getInstance(){return e.instance||(e.instance=new e),e.instance}constructor(){this.storage={}}get length(){return Object.keys(this.storage).length}clear(){this.storage={}}getItem(e){var t;return null!==(t=this.storage[e])&&void 0!==t?t:null}key(e){var t;const n=Object.keys(this.storage);return e<0||e>=n.length?null:null!==(t=n[e])&&void 0!==t?t:null}removeItem(e){delete this.storage[e]}setItem(e,t){this.storage[e]=t}};function vt(){if("undefined"!=typeof window)return window}function wt(){if("undefined"!=typeof document)return document}function yt(){var e,t,n,r;const o=null===(t=null===(e=vt())||void 0===e?void 0:e.location)||void 0===t?void 0:t.origin,i=null===(r=null===(n=vt())||void 0===n?void 0:n.location)||void 0===r?void 0:r.pathname;return o&&i?o+i:""}function bt(){if(function(){try{return"undefined"!=typeof localStorage}catch(e){return!1}}())return localStorage;if("undefined"!=typeof process&&null!=process.versions&&null!=process.versions.node)throw new G("`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 mt.getInstance()}function Ct(e,t=!1){const{wc:n,hex:r}=kt(e);let o=81;t&&(o|=128);const i=new Int8Array(34);i[0]=o,i[1]=n,i.set(r,2);const a=new Uint8Array(36);return a.set(i),a.set(Et(i),34),L.encode(a).replace(/\+/g,"-").replace(/\//g,"_")}function xt(e){try{return St(e),!0}catch(t){return!1}}function St(e){const t=e.replace(/-/g,"+").replace(/_/g,"/");let n;try{n=L.decode(t).toUint8Array()}catch(u){throw new ze(`Invalid base64 encoding in address: ${e}`)}if(36!==n.length)throw new ze(`Invalid address length: ${e}`);const r=n.slice(0,34),o=n.slice(34,36),i=Et(r);if(!o.every((e,t)=>e===i[t]))throw new ze(`Invalid checksum in address: ${e}`);let a=r[0],s=!1,l=!1;if(128&a&&(s=!0,a^=128),17!==a&&81!==a)throw new ze(`Unknown address tag: ${a}`);l=17===a;let c=null;c=255===r[1]?-1:r[1];const d=r.slice(2);if(0!==c&&-1!==c)throw new ze(`Invalid workchain: ${c}`);return{wc:c,hex:Array.from(d).map(e=>e.toString(16).padStart(2,"0")).join(""),testOnly:s,isBounceable:l}}function kt(e){if(!e.includes(":"))throw new ze(`Wrong address ${e}. Address must include ":".`);const t=e.split(":");if(2!==t.length)throw new ze(`Wrong address ${e}. Address must include ":" only once.`);const n=parseInt(t[0]);if(0!==n&&-1!==n)throw new ze(`Wrong address ${e}. WC must be eq 0 or -1, but ${n} received.`);const r=t[1];if(64!==(null==r?void 0:r.length))throw new ze(`Wrong address ${e}. Hex part must be 64bytes length, but ${null==r?void 0:r.length} received.`);return{wc:n,hex:_t(r)}}function Et(e){let t=0;const n=new Uint8Array(e.length+2);n.set(e);for(let r of n){let e=128;for(;e>0;)t<<=1,r&e&&(t+=1),e>>=1,t>65535&&(t&=65535,t^=4129)}return new Uint8Array([Math.floor(t/256),t%256])}const Rt={};for(let pm=0;pm<=255;pm++){let e=pm.toString(16);e.length<2&&(e="0"+e),Rt[e]=pm}function _t(e){const t=(e=e.toLowerCase()).length;if(t%2!=0)throw new Fe("Hex string must have length a multiple of 2: "+e);const n=t/2,r=new Uint8Array(n);for(let o=0;o0}function Pt(e){return Nt(e)&&(function(e){try{return kt(e),!0}catch(t){return!1}}(e)||xt(e))}function Lt(e){return Nt(e)&&/^-?\d+$/.test(e)}function Wt(e){return"string"==typeof e&&(Tt.test(e)||It.test(e))&&e.startsWith("te6cc")}function Dt(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function jt(e){return Array.isArray(e)}function Ut(e,t){return Object.keys(e).some(e=>!t.includes(e))}function qt(e){return Bt(e)}function Bt(e){if(!Dt(e))return"Request must be an object";if(Ut(e,["validUntil","network","from","messages","items"]))return"Request contains extra properties";if(e.validUntil){if(!Mt(e.validUntil))return"Incorrect 'validUntil'";const t=Math.floor(Date.now()/1e3),n=t+300;e.validUntil>n&&console.warn(`validUntil (${e.validUntil}) is more than 5 minutes from now (${t})`)}if(void 0!==e.network&&!Lt(e.network))return"Invalid 'network' format";if(void 0!==e.from&&!Pt(e.from))return"Invalid 'from' address format";const t=jt(e.messages),n=jt(e.items);if(t&&n)return"Request must contain either 'messages' or 'items', not both";if(!t&&!n)return"Request must contain 'messages' or 'items'";if(t){if(0===e.messages.length)return"'messages' must not be empty";for(let t=0;t128)return"Current domain exceeds 128 bytes limit";const o=(new TextEncoder).encode(t).length;if(o>128)return"'tonProof' payload exceeds 128 bytes limit";if(r+o>222)return"'tonProof' domain + payload exceeds 222 bytes limit"}return null}function Ht(e){if(!Dt(e))return"Payload must be an object";if(!Nt(e.type))return"'type' is required";switch(e.type){case"text":return function(e){if(Ut(e,["type","text","network","from"]))return"Text payload contains extra properties";if(!Nt(e.text))return"'text' is required";if(void 0!==e.network&&!Lt(e.network))return"Invalid 'network' format";if(void 0!==e.from&&!Pt(e.from))return"Invalid 'from'";return null}(e);case"binary":return function(e){if(Ut(e,["type","bytes","network","from"]))return"Binary payload contains extra properties";if(!Nt(e.bytes))return"'bytes' is required";if(void 0!==e.network&&!Lt(e.network))return"Invalid 'network' format";if(void 0!==e.from&&!Pt(e.from))return"Invalid 'from'";return null}(e);case"cell":return function(e){if(Ut(e,["type","schema","cell","network","from"]))return"Cell payload contains extra properties";if(!Nt(e.schema))return"'schema' is required";if(!Nt(e.cell))return"'cell' is required";if(!Wt(e.cell))return"Invalid 'cell' format (must be valid base64)";if(void 0!==e.network&&!Lt(e.network))return"Invalid 'network' format";if(void 0!==e.from&&!Pt(e.from))return"Invalid 'from'";return null}(e);default:return"Invalid 'type' value"}}function Vt(e){return Pt(e.address)?Lt(e.network)?null:"Invalid 'ton_addr.network'":"Invalid 'ton_addr.address'"}function $t(e){if(!Dt(e))return"connect payload must be an object";if(!jt(e.items))return"Invalid 'items'";for(const n of e.items){if(!Dt(n)||!Nt(n.name))return"Every connect item must be an object with a name";if("ton_addr"===n.name){const e=Vt(n);if(e)return e}}return Dt(t=e.device)?jt(t.features)?null:"Invalid 'device.features'":"Invalid 'device'";var t}function Gt(e){return"object"==typeof e&&null!==e}function Xt(e){try{if(!Gt(e))return;if("connect"===e.event){const t=e.payload;return null===$t(t)?Object.assign(Object.assign({},e),{payload:t}):void 0}if("connect_error"===e.event){const t=ct(e.payload);return t?Object.assign(Object.assign({},e),{payload:t}):void 0}return}catch(t){return}}class Zt{static fromStorage(e,t){return $(this,0,void 0,function*(){const n=yield e.getInjectedConnection();return new Zt(e,n.jsBridgeKey,t)})}static isWalletInjected(e){return Zt.isWindowContainsWallet(this.window,e)}static isInsideWalletBrowser(e){return!!Zt.isWindowContainsWallet(this.window,e)&&this.window[e].tonconnect.isWalletBrowser}static getCurrentlyInjectedWallets(){if(!this.window)return[];return function(){const e=vt();if(!e)return[];try{return Object.entries(e)}catch(t){return[]}}().filter(([e,t])=>function(e){try{return!(!ft(e,"tonconnect")||!ft(e.tonconnect,"walletInfo"))&>(e.tonconnect.walletInfo,["name","app_name","image","about_url","platforms"])}catch(t){return!1}}(t)).map(([e,t])=>({name:t.tonconnect.walletInfo.name,appName:t.tonconnect.walletInfo.app_name,aboutUrl:t.tonconnect.walletInfo.about_url,imageUrl:t.tonconnect.walletInfo.image,tondns:t.tonconnect.walletInfo.tondns,jsBridgeKey:e,injected:!0,embedded:t.tonconnect.isWalletBrowser,platforms:t.tonconnect.walletInfo.platforms,features:t.tonconnect.walletInfo.features}))}static isWindowContainsWallet(e,t){return!!e&&t in e&&"object"==typeof e[t]&&"tonconnect"in e[t]}constructor(e,t,n){this.connectionStorage=e,this.injectedWalletKey=t,this.type="injected",this.unsubscribeCallback=null,this.listenSubscriptions=!1,this.listeners=[];const r=Zt.window;if(!Zt.isWindowContainsWallet(r,t))throw new ee;this.injectedWallet=r[t].tonconnect,n&&(this.analytics=n.scoped({bridge_key:t,wallet_app_name:this.injectedWallet.deviceInfo.appName,wallet_app_version:this.injectedWallet.deviceInfo.appVersion}))}connect(e,t){this._connect(2,e,t).catch(e=>$e(e))}restoreConnection(e){return $(this,0,void 0,function*(){var t,n,r,o;const i=null!==(t=null==e?void 0:e.traceId)&&void 0!==t?t:rt();try{$e("Injected Provider restoring connection..."),null===(n=this.analytics)||void 0===n||n.emitJsBridgeCall({js_bridge_method:"restoreConnection",trace_id:i});const e=yield this.injectedWallet.restoreConnection();null===(r=this.analytics)||void 0===r||r.emitJsBridgeResponse({js_bridge_method:"restoreConnection",trace_id:i}),$e("Injected Provider restoring connection response",e);const t=Xt(e);"connect"===(null==t?void 0:t.event)?(this.makeSubscriptions({traceId:i}),this.listeners.forEach(e=>e(Object.assign(Object.assign({},t),{traceId:i,restored:!0})))):yield this.connectionStorage.removeConnection()}catch(a){null===(o=this.analytics)||void 0===o||o.emitJsBridgeError({js_bridge_method:"restoreConnection",error_message:Yt(a),trace_id:i}),yield this.connectionStorage.removeConnection(),console.error(a)}})}closeConnection(){if(this.listenSubscriptions)try{this.disconnectWallet()}catch(e){$e(e)}this.closeAllListeners()}disconnectWallet(){Promise.resolve(this.injectedWallet.disconnect()).catch($e)}disconnect(e){return $(this,0,void 0,function*(){var t;const n=null!==(t=null==e?void 0:e.traceId)&&void 0!==t?t:rt();return new Promise((e,t)=>{let r=!1;const o=()=>{if(!r){r=!0;try{this.closeAllListeners()}catch(n){$e(n)}this.connectionStorage.removeConnection().then(e,t)}};try{this.disconnectWallet(),o()}catch(i){$e(i),this.sendRequest({method:"disconnect",params:[]},{onRequestSent:o,traceId:n}).catch($e).then(o)}})})}closeAllListeners(){var e;this.listenSubscriptions=!1,this.listeners=[],null===(e=this.unsubscribeCallback)||void 0===e||e.call(this)}listen(e){return this.listeners.push(e),()=>this.listeners=this.listeners.filter(t=>t!==e)}sendRequest(e,t){return $(this,0,void 0,function*(){var n,r,o;const i={};let a,s;"function"==typeof t?(i.onRequestSent=t,i.traceId=rt()):(i.onRequestSent=null==t?void 0:t.onRequestSent,i.signal=null==t?void 0:t.signal,i.attempts=null==t?void 0:t.attempts,i.traceId=null!==(n=null==t?void 0:t.traceId)&&void 0!==n?n:rt());try{a=(yield this.connectionStorage.getNextRpcRequestId()).toString(),yield this.connectionStorage.increaseNextRpcRequestId(),$e("Send injected-bridge request:",Object.assign(Object.assign({},e),{id:a})),null===(r=this.analytics)||void 0===r||r.emitJsBridgeCall({js_bridge_method:"send"}),s=Promise.resolve(this.injectedWallet.send(Object.assign(Object.assign({},e),{id:a})))}catch(c){throw new oe("Could not send the request to the injected wallet",{cause:c})}const l=s.then(e=>{var t,r;const o=function(e){try{if(!Gt(e))return;if("error"in e){const t=ct(e.error);return t?Object.assign(Object.assign({},e),{error:t}):void 0}if(!("result"in e))return;const t=e.result;return null==t?void 0:Object.assign(Object.assign({},e),{result:t})}catch(n){return}}(e);if(!o)throw null===(t=this.analytics)||void 0===t||t.emitJsBridgeError({js_bridge_method:"send",error_message:Yt(e)}),new oe("Injected wallet answered without a TON Connect response",{cause:e});return null===(r=this.analytics)||void 0===r||r.emitJsBridgeResponse({js_bridge_method:"send"}),$e("Wallet message received:",e),o},e=>{var t;null===(t=this.analytics)||void 0===t||t.emitJsBridgeError({js_bridge_method:"send",error_message:Yt(e)});const n=pt(e,Ee);if(!n)throw new oe("Injected wallet rejected the request without a TON Connect error response",{cause:e});Ce(n);const r={id:a,error:n};return $e("Wallet request rejected, normalized:",r),r});try{null===(o=i.onRequestSent)||void 0===o||o.call(i)}catch(c){throw l.catch(e=>$e(e)),c}return l})}_connect(e,t,n){return $(this,0,void 0,function*(){var r,o,i,a,s;const l=null!==(r=null==n?void 0:n.traceId)&&void 0!==r?r:rt();let c;try{$e(`Injected Provider connect request: protocolVersion: ${e}, message:`,t),null===(o=this.analytics)||void 0===o||o.emitJsBridgeCall({js_bridge_method:"connect",trace_id:l}),c=yield this.injectedWallet.connect(e,t)}catch(u){null===(i=this.analytics)||void 0===i||i.emitJsBridgeError({js_bridge_method:"connect",error_message:Yt(u),trace_id:l}),$e("Injected Provider connect error:",u);const e=pt(u,Re);return void(e?(Ce(e),this.emitConnectError(e,l)):this.emitConnectFailure(u,new oe("Injected wallet rejected the connection without a TON Connect event",{cause:u}),l))}const d=Xt(c);if(!d)return null===(a=this.analytics)||void 0===a||a.emitJsBridgeError({js_bridge_method:"connect",error_message:Yt(c),trace_id:l}),void this.emitConnectFailure(c,new oe("Injected wallet answered the connection without a TON Connect event",{cause:c}),l);try{null===(s=this.analytics)||void 0===s||s.emitJsBridgeResponse({js_bridge_method:"connect"}),$e("Injected Provider connect response:",d),"connect"===d.event&&(yield this.updateSession(),this.makeSubscriptions({traceId:l})),this.listeners.forEach(e=>e(Object.assign(Object.assign({},d),{traceId:l})))}catch(u){$e("Injected Provider connect error:",u),this.emitConnectFailure(u,new G("Injected connection could not be completed",{cause:u}),l)}})}emitWalletEvent(e,t){if("connect"!==e.event&&"connect_error"!==e.event)return void this.listeners.forEach(n=>n(Object.assign(Object.assign({},e),{traceId:t})));const n=Xt(e);if(n)try{this.listeners.forEach(e=>e(Object.assign(Object.assign({},n),{traceId:t})))}catch(r){this.emitConnectFailure(r,new G("Injected connection could not be completed",{cause:r}),t)}else this.emitConnectFailure(e,new oe("Injected wallet sent a malformed TON Connect event",{cause:e}),t)}emitConnectFailure(e,t,n){const r={code:0,message:Yt(e)};!function(e,t){be.set(e,t)}(r,t),this.emitConnectError(r,n)}emitConnectError(e,t){const n={event:"connect_error",payload:e};this.listeners.forEach(e=>e(Object.assign(Object.assign({},n),{traceId:t})))}makeSubscriptions(e){var t,n,r;this.listenSubscriptions=!0,null===(t=this.analytics)||void 0===t||t.emitJsBridgeCall({js_bridge_method:"listen",trace_id:e.traceId});try{this.unsubscribeCallback=this.injectedWallet.listen(e=>{try{this.onWalletEvent(e)}catch(t){$e("Injected Provider could not handle a wallet event:",t)}}),null===(n=this.analytics)||void 0===n||n.emitJsBridgeResponse({js_bridge_method:"listen",trace_id:e.traceId})}catch(o){throw null===(r=this.analytics)||void 0===r||r.emitJsBridgeError({js_bridge_method:"listen",error_message:Yt(o),trace_id:e.traceId}),o}}onWalletEvent(e){var t;if($e("Wallet message received:",e),"object"!=typeof e||null===e)return;const n=null!==(t=e.traceId)&&void 0!==t?t:rt();if(this.listenSubscriptions)try{this.emitWalletEvent(e,n)}catch(r){$e("Injected Provider could not deliver a wallet event:",r)}"disconnect"===e.event&&this.disconnect({traceId:n}).catch(e=>$e(e))}updateSession(){return this.connectionStorage.storeConnection({type:"injected",jsBridgeKey:this.injectedWalletKey,nextRpcRequestId:0})}}function Yt(e){try{return String(e)}catch(t){try{return Object.prototype.toString.call(e)}catch(n){return"[unreadable value]"}}}Zt.window=vt();class Qt{constructor(e,t){this.storage=e,this.walletsListManager=t,this.storeKey="ton-connect-storage_bridge-connection"}storeConnection(e){return $(this,0,void 0,function*(){if("injected"===e.type||"wallet-connect"===e.type)return this.storage.setItem(this.storeKey,JSON.stringify(e));if(!Ye(e)){const t={sessionKeyPair:e.session.sessionCrypto.stringifyKeypair(),walletPublicKey:e.session.walletPublicKey,bridgeUrl:e.session.bridgeUrl},n={type:"http",connectEvent:e.connectEvent,session:t,lastWalletEventId:e.lastWalletEventId,nextRpcRequestId:e.nextRpcRequestId};return this.storage.setItem(this.storeKey,JSON.stringify(n))}const t={type:"http",connectionSource:e.connectionSource,sessionCrypto:e.sessionCrypto.stringifyKeypair(),createdAt:Date.now()};return this.storage.setItem(this.storeKey,JSON.stringify(t))})}removeConnection(){return $(this,0,void 0,function*(){return this.storage.removeItem(this.storeKey)})}getConnection(){return $(this,0,void 0,function*(){try{const e=yield this.storage.getItem(this.storeKey);if(!e)return null;const t=JSON.parse(e);if("injected"===t.type||"wallet-connect"===t.type)return t;if(!function(e){return!("connectEvent"in e)}(t)){const e=new H(t.session.sessionKeyPair);return yield this.actualizeBridgeConnection({type:"http",connectEvent:t.connectEvent,lastWalletEventId:t.lastWalletEventId,nextRpcRequestId:t.nextRpcRequestId,session:{sessionCrypto:e,bridgeUrl:t.session.bridgeUrl,walletPublicKey:t.session.walletPublicKey}})}return function(e){var t;return Date.now()-(null!==(t=e.createdAt)&&void 0!==t?t:0)>3e5}(t)?(yield this.removeConnection(),null):{type:"http",sessionCrypto:new H(t.sessionCrypto),connectionSource:t.connectionSource}}catch(e){return $e("Error retrieving connection",e),null}})}getHttpConnection(){return $(this,0,void 0,function*(){const e=yield this.getConnection();if(!e)throw new G("Trying to read HTTP connection source while nothing is stored");if("http"!==e.type)throw new G(`Trying to read HTTP connection source while ${e.type} connection is stored`);return e})}getHttpPendingConnection(){return $(this,0,void 0,function*(){const e=yield this.getConnection();if(!e)throw new G("Trying to read HTTP connection source while nothing is stored");if("http"!==e.type)throw new G(`Trying to read HTTP connection source while ${e.type} connection is stored`);if(!Ye(e))throw new G("Trying to read HTTP-pending connection while http connection is stored");return e})}getInjectedConnection(){return $(this,0,void 0,function*(){const e=yield this.getConnection();if(!e)throw new G("Trying to read Injected bridge connection source while nothing is stored");if("injected"!==(null==e?void 0:e.type))throw new G(`Trying to read Injected bridge connection source while ${e.type} connection is stored`);return e})}getWalletConnectConnection(){return $(this,0,void 0,function*(){const e=yield this.getConnection();if(!e)throw new G("Trying to read wallet connect bridge connection source while nothing is stored");if("wallet-connect"!==(null==e?void 0:e.type))throw new G(`Trying to read wallet connect bridge connection source while ${e.type} connection is stored`);return e})}storedConnectionType(){return $(this,0,void 0,function*(){const e=yield this.storage.getItem(this.storeKey);if(!e)return null;return JSON.parse(e).type})}storeLastWalletEventId(e){return $(this,0,void 0,function*(){const t=yield this.getConnection();if(t&&"http"===t.type&&!Ye(t))return t.lastWalletEventId=e,this.storeConnection(t)})}getLastWalletEventId(){return $(this,0,void 0,function*(){const e=yield this.getConnection();if(e&&"lastWalletEventId"in e)return e.lastWalletEventId})}increaseNextRpcRequestId(){return $(this,0,void 0,function*(){const e=yield this.getConnection();if(e&&"nextRpcRequestId"in e){const t=e.nextRpcRequestId||0;return e.nextRpcRequestId=t+1,this.storeConnection(e)}})}getNextRpcRequestId(){return $(this,0,void 0,function*(){const e=yield this.getConnection();return e&&"nextRpcRequestId"in e&&e.nextRpcRequestId||0})}actualizeBridgeConnection(e){return $(this,0,void 0,function*(){try{const t=e.connectEvent.payload.device.appName,n=yield this.walletsListManager.getRemoteWallet(t);if(n.bridgeUrl===e.session.bridgeUrl)return e;const r=Object.assign(Object.assign({},e),{session:Object.assign(Object.assign({},e.session),{bridgeUrl:n.bridgeUrl})});return yield this.storeConnection(r),r}catch(t){return $e("Failed to actualize bridge connection",t),e}})}}class Jt{constructor(){this.localStorage=bt()}getItem(e){return $(this,0,void 0,function*(){return this.localStorage.getItem(e)})}removeItem(e){return $(this,0,void 0,function*(){this.localStorage.removeItem(e)})}setItem(e,t){return $(this,0,void 0,function*(){this.localStorage.setItem(e,t)})}}const en=[{app_name:"telegram",name:"Telegram",image:"https://telegram.org/img/t_logo_2x.png",about_url:"https://telegram.org",universal_url:"https://t.me/sendgrams",deepLink:"tg://sendgrams",bridge:[{type:"js",key:"telegram"},{type:"sse",url:"https://tonbridge.telegram.org"}],platforms:["ios","android","chrome","firefox","macos","windows","linux"],features:[{name:"SendTransaction",maxMessages:255,extraCurrencySupported:!1},{name:"SignData",types:["text","binary","cell"]}]},{app_name:"gramwallet",name:"Gram Wallet",image:"https://config.ton.org/assets/gramwallet.png",about_url:"https://gramwallet.io",universal_url:"https://connect.gramwallet.io",deepLink:"gramwallet-tc://",bridge:[{type:"js",key:"gramwallet"},{type:"sse",url:"https://tonconnectbridge.mytonwallet.org/bridge/"}],platforms:["ios","android"],ui:{isButtonTransparent:!0},features:[{name:"SendTransaction",maxMessages:255,extraCurrencySupported:!1},{name:"SignData",types:["text","binary","cell"]}]},{app_name:"telegram-wallet",name:"Walt (ex. Wallet)",image:"https://config.ton.org/assets/telegram_wallet.png",about_url:"https://walt.io/",universal_url:"https://t.me/walt?attach=wallet",bridge:[{type:"sse",url:"https://walletbot.me/tonconnect-bridge/bridge"}],platforms:["ios","android","macos","windows","linux"],features:[{name:"SendTransaction",maxMessages:255,extraCurrencySupported:!0},{name:"SignData",types:["text","binary","cell"]}]},{app_name:"tonkeeper",name:"Keeper",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","windows","linux"],features:[{name:"SendTransaction",maxMessages:255,extraCurrencySupported:!0},{name:"SignData",types:["text","binary","cell"]}]},{app_name:"mytonwallet",name:"My Wallet",image:"https://config.ton.org/assets/mytonwallet.png",about_url:"https://mywallet.io/?utm_source=tc",universal_url:"https://connect.mytonwallet.org",deepLink:"mytonwallet-tc://",bridge:[{type:"js",key:"mytonwallet"},{type:"sse",url:"https://tonconnectbridge.mytonwallet.org/bridge/"}],platforms:["chrome","windows","macos","linux","ios","android","firefox"],features:[{name:"SendTransaction",maxMessages:255,extraCurrencySupported:!1},{name:"SignData",types:["text","binary","cell"]}]},{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"],features:[{name:"SendTransaction",maxMessages:255,extraCurrencySupported:!0},{name:"SignData",types:["text","binary","cell"]}]},{app_name:"bitgetTonWallet",name:"Bitget Wallet",image:"https://raw.githubusercontent.com/bitgetwallet/download/refs/heads/main/logo/png/bitget_wallet_logo_288_mini.png",about_url:"https://web3.bitget.com",deepLink:"bitkeep://",bridge:[{type:"js",key:"bitgetTonWallet"},{type:"sse",url:"https://ton-connect-bridge.bgwapi.io/bridge"}],platforms:["ios","android","chrome"],universal_url:"https://bkcode.vip/ton-connect",features:[{name:"SendTransaction",maxMessages:4,extraCurrencySupported:!1}]},{app_name:"okxMiniWallet",name:"OKX Mini Wallet",image:"https://static.okx.com/cdn/assets/imgs/2411/8BE1A4A434D8F58A.png",about_url:"https://www.okx.com/web3",universal_url:"https://t.me/OKX_WALLET_BOT?attach=wallet",bridge:[{type:"sse",url:"https://www.okx.com/tonbridge/discover/rpc/bridge"}],platforms:["ios","android","macos","windows","linux"],features:[{name:"SendTransaction",maxMessages:4,extraCurrencySupported:!1}]},{app_name:"binanceWeb3TonWallet",name:"Binance Wallet",image:"https://public.bnbstatic.com/static/binance-w3w/ton-provider/binancew3w.png",about_url:"https://www.binance.com/en/web3wallet",deepLink:"bnc://app.binance.com/cedefi/ton-connect",bridge:[{type:"js",key:"binancew3w"},{type:"sse",url:"https://wallet.binance.com/tonbridge/bridge"}],platforms:["ios","android","macos","windows","linux"],universal_url:"https://app.binance.com/cedefi/ton-connect",features:[{name:"SendTransaction",maxMessages:4,extraCurrencySupported:!1}]},{app_name:"fintopio-tg",name:"Fintopio",image:"https://raw.githubusercontent.com/fintopio/ton-pub/refs/heads/main/logos/tonconnect-icon.png",about_url:"https://fintopio.com",universal_url:"https://t.me/fintopio?attach=wallet",bridge:[{type:"sse",url:"https://wallet-bridge.fintopio.com/bridge"}],platforms:["ios","android","macos","windows","linux"],features:[{name:"SendTransaction",maxMessages:4,extraCurrencySupported:!1}]},{app_name:"okxTonWallet",name:"OKX Wallet",image:"https://static.okx.com/cdn/assets/imgs/247/58E63FEA47A2B7D7.png",about_url:"https://www.okx.com/web3",universal_url:"https://www.okx.com/download?appendQuery=true&deeplink=okx://web3/wallet/tonconnect",bridge:[{type:"js",key:"okxTonWallet"},{type:"sse",url:"https://www.okx.com/tonbridge/discover/rpc/bridge"}],platforms:["chrome","safari","firefox","ios","android"],features:[{name:"SendTransaction",maxMessages:4,extraCurrencySupported:!1}]},{app_name:"hot",name:"HOT",image:"https://raw.githubusercontent.com/hot-dao/media/main/logo.png",about_url:"https://hot-labs.org/",universal_url:"https://t.me/herewalletbot?attach=wallet",bridge:[{type:"sse",url:"https://sse-bridge.hot-labs.org"},{type:"js",key:"hotWallet"}],platforms:["ios","android","macos","windows","linux"],features:[{name:"SendTransaction",maxMessages:4,extraCurrencySupported:!1}]},{app_name:"bybitTonWallet",name:"Bybit Wallet",image:"https://raw.githubusercontent.com/bybit-web3/bybit-web3.github.io/main/docs/images/bybit-logo.png",about_url:"https://www.bybit.com/web3",universal_url:"https://app.bybit.com/ton-connect",deepLink:"bybitapp://",bridge:[{type:"js",key:"bybitTonWallet"},{type:"sse",url:"https://api-node.bybit.com/spot/api/web3/bridge/ton/bridge"}],platforms:["ios","android","chrome"],features:[{name:"SendTransaction",maxMessages:4,extraCurrencySupported:!1}]},{app_name:"dewallet",name:"DeWallet",image:"https://raw.githubusercontent.com/delab-team/manifests-images/main/WalletAvatar.png",about_url:"https://delabwallet.com",universal_url:"https://t.me/dewallet?attach=wallet",bridge:[{type:"sse",url:"https://bridge.dewallet.pro/bridge"}],platforms:["ios","android","macos","windows","linux"],features:[{name:"SendTransaction",maxMessages:4,extraCurrencySupported:!1}]},{app_name:"safepalwallet",name:"SafePal",image:"https://s.pvcliping.com/web/public_image/SafePal_x288.png",tondns:"",about_url:"https://www.safepal.com",universal_url:"https://link.safepal.io/ton-connect",deepLink:"safepal-tc://",bridge:[{type:"sse",url:"https://ton-bridge.safepal.com/tonbridge/v1/bridge"},{type:"js",key:"safepalwallet"}],platforms:["ios","android","chrome","firefox"],features:[{name:"SendTransaction",maxMessages:1,extraCurrencySupported:!1}]},{app_name:"GateWallet",name:"GateWallet",image:"https://img.gatedataimg.com/prd-ordinal-imgs/036f07bb8730716e/gateio-0925.png",about_url:"https://www.gate.io/",bridge:[{type:"js",key:"gatetonwallet"},{type:"sse",url:"https://dapp.gateio.services/tonbridge_api/bridge/v1"}],platforms:["ios","android"],universal_url:"https://gate.onelink.me/Hls0/web3?gate_web3_wallet_universal_type=ton_connect",features:[{name:"SendTransaction",maxMessages:4,extraCurrencySupported:!1}]},{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"],features:[{name:"SendTransaction",maxMessages:4,extraCurrencySupported:!1}]},{app_name:"BitgetWeb3",name:"BitgetWeb3",image:"https://img.bitgetimg.com/image/third/1731638059795.png",about_url:"​https://www.bitget.com",universal_url:"https://t.me/BitgetOfficialBot?attach=wallet",bridge:[{type:"sse",url:"https://ton-connect-bridge.bgwapi.io/bridge"}],platforms:["ios","android","windows","macos","linux"],features:[{name:"SendTransaction",maxMessages:4,extraCurrencySupported:!1}]},{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"],features:[{name:"SendTransaction",maxMessages:1,extraCurrencySupported:!1}]},{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"],features:[{name:"SendTransaction",maxMessages:4,extraCurrencySupported:!1}]},{app_name:"bitgetWalletLite",name:"Bitget Wallet Lite",image:"https://raw.githubusercontent.com/bitgetwallet/download/refs/heads/main/logo/png/bitget_wallet_lite_logo_288.png",about_url:"https://web3.bitget.com",universal_url:"https://t.me/BitgetWallet_TGBot?attach=wallet",bridge:[{type:"sse",url:"https://ton-connect-bridge.bgwapi.io/bridge"}],platforms:["ios","android","macos","windows","linux"],features:[{name:"SendTransaction",maxMessages:255,extraCurrencySupported:!1}]},{app_name:"tomoWallet",name:"Tomo Wallet",image:"https://pub.tomo.inc/logo.png",about_url:"https://www.tomo.inc/",universal_url:"https://t.me/tomowalletbot?attach=wallet",bridge:[{type:"sse",url:"https://go-bridge.tomo.inc/bridge"}],platforms:["ios","android","macos","windows","linux"],features:[{name:"SendTransaction",maxMessages:4,extraCurrencySupported:!1}]},{app_name:"miraiapp-tg",name:"Mirai Mini App",image:"https://cdn.mirailabs.co/miraihub/miraiapp-tg-icon-288.png",about_url:"https://mirai.app",universal_url:"https://t.me/MiraiAppBot?attach=wallet",bridge:[{type:"sse",url:"https://bridge.mirai.app"}],platforms:["ios","android","macos","windows","linux"],features:[{name:"SendTransaction",maxMessages:255,extraCurrencySupported:!1},{name:"SignData",types:["text","binary","cell"]}]},{app_name:"Architec.ton",name:"Architec.ton",image:"https://raw.githubusercontent.com/Architec-Ton/wallet-tma/refs/heads/dev/public/images/arcwallet_logo.png",about_url:"https://architecton.tech",universal_url:"https://t.me/architec_ton_bot?attach=wallet",bridge:[{type:"sse",url:"https://tc.architecton.su/bridge"}],platforms:["ios","android","macos","windows","linux"],features:[{name:"SendTransaction",maxMessages:255,extraCurrencySupported:!1}]},{app_name:"tokenpocket",name:"TokenPocket",image:"https://hk.tpstatic.net/logo/tokenpocket.png",about_url:"https://www.tokenpocket.pro",universal_url:"https://tp-lab.tptool.pro/ton-connect/",bridge:[{type:"js",key:"tokenpocket"},{type:"sse",url:"https://ton-connect.mytokenpocket.vip/bridge"}],platforms:["ios","android"],features:[{name:"SendTransaction",maxMessages:4,extraCurrencySupported:!1}]},{app_name:"uxuyWallet",name:"UXUY Wallet",image:"https://chain-cdn.uxuy.com/logo/square_288.png",about_url:"https://docs.uxuy.com",universal_url:"https://t.me/UXUYbot?attach=wallet",bridge:[{type:"sse",url:"https://bridge.uxuy.me/bridge"}],platforms:["ios","android","macos","windows","linux"],features:[{name:"SendTransaction",maxMessages:4,extraCurrencySupported:!1}]},{app_name:"tonkeeper-pro",name:"Tonkeeper Pro",image:"https://tonkeeper.com/assets/tonconnect-icon-pro.png",tondns:"tonkeeper.ton",about_url:"https://tonkeeper.com/pro",universal_url:"https://app.tonkeeper.com/pro/ton-connect",deepLink:"tonkeeper-pro-tc://",bridge:[{type:"sse",url:"https://bridge.tonapi.io/bridge"}],platforms:["ios","macos","windows","linux"],features:[{name:"SendTransaction",maxMessages:255,extraCurrencySupported:!0},{name:"SignData",types:["text","binary","cell"]}]},{app_name:"nicegramWallet",name:"Nicegram Wallet",image:"https://static.nicegram.app/icon.png",about_url:"https://nicegram.app",universal_url:"https://nicegram.app/tc",deepLink:"nicegram-tc://",bridge:[{type:"sse",url:"https://tc.nicegram.app/bridge"},{type:"js",key:"nicegramWallet"}],platforms:["ios","android"],features:[{name:"SendTransaction",maxMessages:255,extraCurrencySupported:!1}]},{app_name:"echoooTonWallet",name:"EchoooWallet",image:"https://cdn.echooo.xyz/front-end/source/images/logo/echooo-ton.png",about_url:"https://www.echooo.xyz",universal_url:"https://www.echooo.xyz/ton-connect",deepLink:"echooo://",bridge:[{type:"js",key:"echoooTonWallet"},{type:"sse",url:"https://ton-connect-bridge.echooo.link/bridge"}],platforms:["ios","android"],features:[{name:"SendTransaction",maxMessages:255,extraCurrencySupported:!1}]},{app_name:"blitzwallet",name:"BLITZ wallet",image:"https://blitzwallet.cfd/wallet/public/logo.png",about_url:"https://blitzwallet.cfd",universal_url:"https://t.me/blitz_wallet_bot?attach=wallet",bridge:[{type:"sse",url:"https://blitzwallet.cfd/bridge/"}],platforms:["ios","android","macos","windows","linux"],features:[{name:"SendTransaction",maxMessages:4,extraCurrencySupported:!1}]},{app_name:"koloWeb3Wallet",name:"Kolo",image:"https://raw.githubusercontent.com/onidev1/tc-assets/refs/heads/main/kolo_logo_288.png",about_url:"https://kolo.xyz",universal_url:"https://t.me/kolo?attach=wallet",bridge:[{type:"sse",url:"https://web3-bridge.kolo.in/bridge"}],platforms:["ios","android","macos","windows","linux"],features:[{name:"SendTransaction",maxMessages:255,extraCurrencySupported:!1}]},{app_name:"imToken",name:"imToken",image:"https://aws-v2-cdn.token.im/orbit/token-v2/icons/logo-ton-connect.png",about_url:"https://token.im",universal_url:"https://connect.token.im/link/ton-connect",deepLink:"imtokenv2://link/ton-connect",bridge:[{type:"sse",url:"https://connect.token.im/tonbridge"},{type:"js",key:"imToken"}],platforms:["ios","android"],features:[{name:"SendTransaction",maxMessages:255,extraCurrencySupported:!1}]},{app_name:"cactuslink",name:"Cactus Link",image:"https://downloads.mycactus.com/288_cactus_link.png",about_url:"https://www.mycactus.com/defi-connector",bridge:[{type:"js",key:"cactuslink_ton"}],platforms:["chrome"],features:[{name:"SendTransaction",maxMessages:4,extraCurrencySupported:!1},{name:"SignData",types:["text","binary"]}]},{app_name:"onekey",name:"OneKey",image:"https://uni.onekey-asset.com/static/logo/onekey-x288.png",about_url:"https://onekey.so",bridge:[{type:"js",key:"onekeyTonWallet"}],platforms:["chrome"],features:[{name:"SendTransaction",maxMessages:4,extraCurrencySupported:!1}]}];let tn=!1,nn=null;function rn(){return tn}function on(){if("undefined"==typeof window)return;if(document.getElementById("ton-connect-qa-banner"))return;const e=document.createElement("div");e.id="ton-connect-qa-banner",e.style.cssText="\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n background: linear-gradient(90deg, #ff6b6b, #ff8e8e);\n color: white;\n padding: 12px 20px;\n text-align: center;\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;\n font-weight: 600;\n font-size: 14px;\n z-index: 999999;\n box-shadow: 0 2px 8px rgba(0,0,0,0.2);\n animation: slideDown 0.3s ease-out;\n user-select: none;\n pointer-events: none;\n ",e.innerHTML="\n 🚨 QA Mode Active - Validation Disabled (Unsafe for Production)\n ";const t=document.createElement("style");t.textContent="\n @keyframes slideDown {\n from { transform: translateY(-100%); }\n to { transform: translateY(0); }\n }\n ",document.head.appendChild(t),document.body.appendChild(e),an()}function an(){if("undefined"==typeof window)return;if(document.getElementById("ton-connect-qa-mode-styles"))return;const e=document.createElement("style");e.id="ton-connect-qa-mode-styles",e.textContent="\n body.qa-mode-active {\n padding-top: 48px !important;\n }\n \n body.qa-mode-active header {\n margin-top: 48px !important;\n }\n \n body.qa-mode-active .qa-mode-control {\n top: 128px !important;\n }\n ",document.head.appendChild(e),document.body.classList.add("qa-mode-active")}class sn{constructor(e){var t;this.walletsListDTOCache=null,this.walletsListDTOCacheCreationTimestamp=null,rn()?this.walletsListSource="https://raw.githubusercontent.com/ton-connect/wallets-list-staging/refs/heads/main/wallets-v2.json":this.walletsListSource=null!==(t=null==e?void 0:e.walletsListSource)&&void 0!==t?t:"https://config.ton.org/wallets-v2.json",this.cacheTTLMs=null==e?void 0:e.cacheTTLMs,this.onDownloadDurationMeasured=null==e?void 0:e.onDownloadDurationMeasured}getWallets(){return $(this,0,void 0,function*(){const[e,t]=yield Promise.all([this.fetchWalletsListDTO(),this.getCurrentlyInjectedWallets()]);return this.mergeWalletsLists(this.walletConfigDTOListToWalletConfigList(e),t)})}getEmbeddedWallet(){return $(this,0,void 0,function*(){const e=(yield this.getWallets()).filter(ce);return 1===e.length?e[0]:null})}fetchWalletsListDTO(){return $(this,0,void 0,function*(){return this.cacheTTLMs&&this.walletsListDTOCacheCreationTimestamp&&Date.now()>this.walletsListDTOCacheCreationTimestamp+this.cacheTTLMs&&(this.walletsListDTOCache=null),this.walletsListDTOCache||(this.walletsListDTOCache=this.fetchWalletsListFromSource(),this.walletsListDTOCache.then(()=>{this.walletsListDTOCacheCreationTimestamp=Date.now()}).catch(()=>{this.walletsListDTOCache=null,this.walletsListDTOCacheCreationTimestamp=null})),this.walletsListDTOCache})}getRemoteWallet(e){return $(this,0,void 0,function*(){const t=(yield this.getWallets()).find(t=>t.appName===e);if(!t)throw new G(`Wallet info not found for appName: "${e}"`);if(!ue(t))throw new G(`Wallet "${e}" is not remote`);return t})}fetchWalletsListFromSource(){return $(this,0,void 0,function*(){var e,t;let n=[];const r=performance.now();try{const t=yield fetch(this.walletsListSource);if(n=yield t.json(),!Array.isArray(n))throw new Be("Wrong wallets list format, wallets list must be an array.");const o=n.filter(e=>!this.isCorrectWalletConfigDTO(e));o.length&&(Ge(`Wallet(s) ${o.map(e=>(null==e?void 0:e.name)||"unknown").join(", ")} config format is wrong. They were removed from the wallets list.`),n=n.filter(e=>this.isCorrectWalletConfigDTO(e)));const i=performance.now(),a=Math.round(i-r);null===(e=this.onDownloadDurationMeasured)||void 0===e||e.call(this,a)}catch(o){Ge(o),n=en,null===(t=this.onDownloadDurationMeasured)||void 0===t||t.call(this,void 0)}return n})}getCurrentlyInjectedWallets(){if(!rn())return[];try{return Zt.getCurrentlyInjectedWallets()}catch(e){return Ge(e),[]}}walletConfigDTOListToWalletConfigList(e){return e.map(e=>{const t={name:e.name,appName:e.app_name,imageUrl:e.image,aboutUrl:e.about_url,tondns:e.tondns,platforms:e.platforms,features:e.features,ui:e.ui&&"object"==typeof e.ui?{isButtonTransparent:!0===e.ui.isButtonTransparent}:void 0};return e.bridge.forEach(n=>{if("sse"===n.type&&(t.bridgeUrl=n.url,t.universalLink=e.universal_url,t.deepLink=e.deepLink),"js"===n.type){const e=n.key;t.jsBridgeKey=e,t.injected=Zt.isWalletInjected(e),t.embedded=Zt.isInsideWalletBrowser(e)}}),t})}mergeWalletsLists(e,t){return[...new Set(e.concat(t).map(e=>e.name)).values()].map(n=>{const r=e.find(e=>e.name===n),o=t.find(e=>e.name===n);return Object.assign(Object.assign({},r&&Object.assign({},r)),o&&Object.assign({},o))})}isCorrectWalletConfigDTO(e){if(!e||"object"!=typeof e)return!1;if(!("name"in e&&"image"in e&&"about_url"in e&&"platforms"in e&&"app_name"in e))return!1;if(!e.platforms||!Array.isArray(e.platforms)||!e.platforms.length)return!1;if(!("bridge"in e)||!Array.isArray(e.bridge)||!e.bridge.length)return!1;const t=e.bridge;if(t.some(e=>!e||"object"!=typeof e||!("type"in e)))return!1;const n=t.find(e=>"sse"===e.type);if(n&&("object"!=typeof n||!("url"in n)||!n.url||!e.universal_url))return!1;const r=t.find(e=>"js"===e.type);return!!(!r||"object"==typeof r&&"key"in r&&r.key)}}function ln(e,t){if("object"!=typeof t)return!0;const{sendTransaction:n,signData:r,signMessage:o,embeddedRequest:i}=t;if(n){const t=cn(e,"SendTransaction");if(!t)return!1;if(!function(e,t){var n;const r=void 0===t.minMessages||t.minMessages<=e.maxMessages,o=!t.extraCurrencyRequired||e.extraCurrencySupported,i=!(null===(n=t.itemTypes)||void 0===n?void 0:n.length)||e.itemTypes&&t.itemTypes.every(t=>e.itemTypes.includes(t));return!!(r&&o&&i)}(t,n))return!1}if(r){const t=cn(e,"SignData");if(!t)return!1;if(!function(e,t){return t.types.every(t=>e.types.includes(t))}(t,r))return!1}if(o){const t=cn(e,"SignMessage");if(!t)return!1;if(!function(e,t){var n;const r=void 0===t.minMessages||t.minMessages<=e.maxMessages,o=!t.extraCurrencyRequired||e.extraCurrencySupported,i=!(null===(n=t.itemTypes)||void 0===n?void 0:n.length)||e.itemTypes&&t.itemTypes.every(t=>e.itemTypes.includes(t));return!!(r&&o&&i)}(t,o))return!1}if(i){if(!cn(e,"EmbeddedRequest"))return!1}return!0}function cn(e,t){return e.find(e=>e&&"object"==typeof e&&e.name===t)}function dn(){return{type:"request-version"}}function un(e){return{type:"response-version",version:e}}function hn(e){return{ton_connect_sdk_lib:e.ton_connect_sdk_lib,ton_connect_ui_lib:e.ton_connect_ui_lib}}function pn(e,t,n){var r,o,i,a,s,l,c,d,u,h,p;const f=(null===(r=null==t?void 0:t.connectItems)||void 0===r?void 0:r.tonProof)&&"proof"in t.connectItems.tonProof?"ton_proof":"ton_addr";return{wallet_address:null!==(i=null===(o=null==t?void 0:t.account)||void 0===o?void 0:o.address)&&void 0!==i?i:null,wallet_state_init:null!==(a=null==t?void 0:t.account.walletStateInit)&&void 0!==a?a:null,wallet_type:null!==(s=null==t?void 0:t.device.appName)&&void 0!==s?s:null,wallet_version:null!==(l=null==t?void 0:t.device.appVersion)&&void 0!==l?l:null,auth_type:f,custom_data:Object.assign({client_id:null!==(c=null==n?void 0:n.clientId)&&void 0!==c?c:null,wallet_id:null!==(d=null==n?void 0:n.walletId)&&void 0!==d?d:null,chain_id:null!==(h=null===(u=null==t?void 0:t.account)||void 0===u?void 0:u.chain)&&void 0!==h?h:null,provider:null!==(p=null==t?void 0:t.provider)&&void 0!==p?p:null},hn(e))}}function fn(e,t){return{type:"connection-started",custom_data:hn(e),trace_id:null!=t?t:null}}function gn(e,t,n){return{type:"connection-initiated",connection_source_kind:t.kind,bridge_key:t.jsBridgeKey,bridge_url:t.bridgeUrl,custom_data:hn(e),trace_id:null!=n?n:null}}function mn(e,t,n){return{type:"connection-link-generated",connection_source_kind:t.kind,bridge_key:t.jsBridgeKey,bridge_url:t.bridgeUrl,custom_data:hn(e),trace_id:null!=n?n:null}}function vn(e,t,n,r,o){return Object.assign({type:"connection-completed",is_success:!0,is_restore:!!o,trace_id:null!=r?r:null},pn(e,t,n))}function wn(e,t,n,r,o){var i,a;return{type:"connection-error",is_success:!1,error_message:t,error_code:null!=n?n:null,trace_id:null!=o?o:null,custom_data:Object.assign({client_id:null!==(i=null==r?void 0:r.clientId)&&void 0!==i?i:null,wallet_id:null!==(a=null==r?void 0:r.walletId)&&void 0!==a?a:null},hn(e))}}function yn(e,t){return{type:"connection-restoring-started",custom_data:hn(e),trace_id:null!=t?t:null}}function bn(e,t,n,r){return Object.assign({type:"connection-restoring-completed",is_success:!0,trace_id:null!=r?r:null},pn(e,t,n))}function Cn(e,t,n){return{type:"connection-restoring-error",is_success:!1,error_message:t,trace_id:null!=n?n:null,custom_data:hn(e)}}function xn(e,t){var n,r,o,i;return{valid_until:null!==(n=String(t.validUntil))&&void 0!==n?n:null,from:null!==(i=null!==(r=t.from)&&void 0!==r?r:null===(o=null==e?void 0:e.account)||void 0===o?void 0:o.address)&&void 0!==i?i:null,messages:pe(t)?t.messages.map(e=>{var t,n;return{address:null!==(t=e.address)&&void 0!==t?t:null,amount:null!==(n=e.amount)&&void 0!==n?n:null}}):[]}}function Sn(e,t,n,r,o){return Object.assign(Object.assign({type:"transaction-sent-for-signature",trace_id:null!=o?o:null},pn(e,t,r)),xn(t,n))}function kn(e,t,n,r,o,i){return Object.assign(Object.assign({type:"transaction-signed",is_success:!0,signed_transaction:r.boc,trace_id:null!=i?i:null},pn(e,t,o)),xn(t,n))}function En(e,t,n,r,o,i,a){return Object.assign(Object.assign({type:"transaction-signing-failed",is_success:!1,error_message:r,error_code:null!=o?o:null,trace_id:null!=a?a:null},pn(e,t,i)),function(e,t){var n,r,o,i;return{valid_until:null!==(n=String(t.validUntil))&&void 0!==n?n:null,from:null!==(i=null!==(r=t.from)&&void 0!==r?r:null===(o=null==e?void 0:e.account)||void 0===o?void 0:o.address)&&void 0!==i?i:null,messages:pe(t)?t.messages.map(e=>{var t,n,r,o;return{address:null!==(t=e.address)&&void 0!==t?t:null,amount:null!==(n=e.amount)&&void 0!==n?n:null,payload:null!==(r=e.payload)&&void 0!==r?r:null,state_init:null!==(o=e.stateInit)&&void 0!==o?o:null}}):[]}}(t,n))}function Rn(e,t,n,r,o){return Object.assign({type:"sign-data-request-initiated",data:n,trace_id:null!=o?o:null},pn(e,t,r))}function _n(e,t,n,r,o,i){return Object.assign({type:"sign-data-request-completed",is_success:!0,data:n,signed_data:r,trace_id:null!=i?i:null},pn(e,t,o))}function Tn(e,t,n,r,o,i,a){return Object.assign({type:"sign-data-request-failed",is_success:!1,data:n,error_message:r,error_code:null!=o?o:null,trace_id:null!=a?a:null},pn(e,t,i))}function In(e,t,n,r,o){return Object.assign({type:"disconnection",scope:n,trace_id:null!=o?o:null},pn(e,t,r))}function An(e,t,n,r){return{type:"wallet-modal-opened",visible_wallets:t,client_id:null!=n?n:null,custom_data:e,trace_id:null!=r?r:null}}function On(e,t,n,r,o,i,a,s){var l;let c=i;return!c&&o&&(c=We(o)?"tg_link":"external_link"),{type:"selected-wallet",wallets_menu:r,visible_wallets:t,client_id:null!=a?a:null,custom_data:e,trace_id:null!=s?s:null,wallet_redirect_method:c,wallet_redirect_link:o||void 0,wallet_type:null!==(l=null==n?void 0:n.appName)&&void 0!==l?l:null}}function Mn(e,t,n,r,o){return{type:"wallet-preselected",wallet_app_name:t,surface:n,selection_source:r,custom_data:hn(e),trace_id:o}}function Nn(e,t,n,r,o,i){return{type:"wallet-selected",wallet_app_name:t,surface:n,selection_source:r,connection_mode:i,custom_data:hn(e),trace_id:o}}class Pn{get version(){return hn({ton_connect_sdk_lib:this.tonConnectSdkVersion,ton_connect_ui_lib:this.tonConnectUiVersion})}constructor(e){this.eventPrefix="ton-connect-",this.tonConnectUiVersion=null,this.eventDispatcher=null==e?void 0:e.eventDispatcher,this.tonConnectSdkVersion=e.tonConnectSdkVersion,this.init().catch()}init(){return $(this,0,void 0,function*(){try{yield this.setRequestVersionHandler(),this.tonConnectUiVersion=yield this.requestTonConnectUiVersion()}catch(e){}})}setRequestVersionHandler(){return $(this,0,void 0,function*(){yield this.eventDispatcher.addEventListener("ton-connect-request-version",()=>$(this,0,void 0,function*(){yield this.eventDispatcher.dispatchEvent("ton-connect-response-version",un(this.tonConnectSdkVersion))}))})}requestTonConnectUiVersion(){return $(this,0,void 0,function*(){return new Promise((e,t)=>$(this,0,void 0,function*(){try{yield this.eventDispatcher.addEventListener("ton-connect-ui-response-version",t=>{e(t.detail.version)},{once:!0}),yield this.eventDispatcher.dispatchEvent("ton-connect-ui-request-version",{type:"request-version"})}catch(n){t(n)}}))})}dispatchUserActionEvent(e){try{this.eventDispatcher.dispatchEvent(`${this.eventPrefix}${e.type}`,e).catch()}catch(t){}}trackConnectionStarted(...e){try{const t=fn(this.version,...e);this.dispatchUserActionEvent(t)}catch(t){}}trackConnectionInitiated(...e){try{const t=gn(this.version,...e);this.dispatchUserActionEvent(t)}catch(t){}}trackConnectionLinkGenerated(...e){try{const t=mn(this.version,...e);this.dispatchUserActionEvent(t)}catch(t){}}trackConnectionCompleted(...e){try{const t=vn(this.version,...e);this.dispatchUserActionEvent(t)}catch(t){}}trackConnectionError(...e){try{const t=wn(this.version,...e);this.dispatchUserActionEvent(t)}catch(t){}}trackConnectionRestoringStarted(...e){try{const t=yn(this.version,...e);this.dispatchUserActionEvent(t)}catch(t){}}trackConnectionRestoringCompleted(...e){try{const t=bn(this.version,...e);this.dispatchUserActionEvent(t)}catch(t){}}trackConnectionRestoringError(...e){try{const t=Cn(this.version,...e);this.dispatchUserActionEvent(t)}catch(t){}}trackDisconnection(...e){try{const t=In(this.version,...e);this.dispatchUserActionEvent(t)}catch(t){}}trackTransactionSentForSignature(...e){try{const t=Sn(this.version,...e);this.dispatchUserActionEvent(t)}catch(t){}}trackTransactionSigned(...e){try{const t=kn(this.version,...e);this.dispatchUserActionEvent(t)}catch(t){}}trackTransactionSigningFailed(...e){try{const t=En(this.version,...e);this.dispatchUserActionEvent(t)}catch(t){}}trackDataSentForSignature(...e){try{const t=Rn(this.version,...e);this.dispatchUserActionEvent(t)}catch(t){}}trackDataSigned(...e){try{const t=_n(this.version,...e);this.dispatchUserActionEvent(t)}catch(t){}}trackDataSigningFailed(...e){try{const t=Tn(this.version,...e);this.dispatchUserActionEvent(t)}catch(t){}}}const Ln="5.0.0";class Wn{constructor(e={}){var t,n,r,o,i,a;this.events=[],this.timeoutId=null,this.isProcessing=!1,this.backoff=1,this.shouldSend=!0,this.batchTimeoutMs=null!==(t=e.batchTimeoutMs)&&void 0!==t?t:2e3,this.currentBatchTimeoutMs=this.batchTimeoutMs,this.maxBatchSize=null!==(n=e.maxBatchSize)&&void 0!==n?n:100,this.analyticsUrl=null!==(r=e.analyticsUrl)&&void 0!==r?r:"https://analytics.ton.org/events",this.mode=null!==(o=e.mode)&&void 0!==o?o:"telemetry",this.baseEvent=Object.assign({subsystem:"dapp-sdk",version:Ln,client_environment:null===(a=null===(i=e.environment)||void 0===i?void 0:i.getClientEnvironment)||void 0===a?void 0:a.call(i)},function(){const e={};try{const t=performance.getEntriesByType("navigation");if(t.length>0){const n=t[0];n.responseStart&&n.requestStart&&(e.conn_ttfb=Math.round(n.responseStart-n.requestStart))}}catch(t){}return e}()),this.addWindowFocusAndBlurSubscriptions()}scoped(e){return new Proxy(this,{get(t,n){const r=n.toString();if(r.startsWith("emit")){const n=r.replace("emit",""),o=n.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase();return function(n){const r=Object.fromEntries(Object.entries(null!=e?e:{}).map(([e,t])=>[e,"function"==typeof t?t():t]));return t.emit(Object.assign(Object.assign({event_name:o},r),n))}}return t[n]}})}emit(e){var t;if("off"===this.mode)return;const n=null!==(t=e.trace_id)&&void 0!==t?t:rt(),r=function(){const e={};try{const t=navigator,n=t.connection||t.mozConnection||t.webkitConnection;n&&(void 0!==n.rtt&&(e.conn_rtt=n.rtt),n.effectiveType?e.conn_network_type=n.effectiveType:n.type&&(e.conn_network_type=n.type))}catch(t){}return e}(),o=Object.assign(Object.assign(Object.assign(Object.assign({},this.baseEvent),r),e),{event_id:rt(),client_timestamp:Math.floor(Date.now()/1e3),trace_id:n}),i="telemetry"===this.mode?this.filterFullModeFields(o):o;rn()&&$e(i),this.events.push(i),this.events.length>=this.maxBatchSize?this.flush():this.startTimeout()}startTimeout(){this.timeoutId||this.isProcessing||(this.timeoutId=setTimeout(()=>{this.flush()},this.currentBatchTimeoutMs))}flush(){return $(this,0,void 0,function*(){if(this.isProcessing||0===this.events.length||!this.shouldSend)return;this.clearTimeout(),this.isProcessing=!0;const e=this.extractEventsToSend();try{yield this.processEventsBatch(e),$e("Analytics events sent successfully")}catch(t){this.restoreEvents(e),Ge("Failed to send analytics events:",t)}finally{this.isProcessing=!1,this.scheduleNextFlushIfNeeded()}})}clearTimeout(){this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null)}extractEventsToSend(){const e=this.events.slice(0,this.maxBatchSize);return this.events=this.events.slice(this.maxBatchSize),e}processEventsBatch(e){return $(this,0,void 0,function*(){$e("Sending analytics events...",e.length);try{const t=yield this.sendEvents(e);this.handleResponse(t)}catch(t){this.handleUnknownError(t)}})}handleResponse(e){const{status:t,statusText:n}=e;this.isTooManyRequests(t)?this.handleTooManyRequests(t,n):this.isClientError(t)?this.handleClientError(t,n):this.isServerError(t)&&this.handleUnknownError({status:t,statusText:n})}restoreEvents(e){this.events.unshift(...e)}scheduleNextFlushIfNeeded(){this.events.length>0&&this.startTimeout()}sendEvents(e){return $(this,0,void 0,function*(){return yield fetch(this.analyticsUrl,{method:"POST",headers:{"Content-Type":"application/json","X-Client-Timestamp":Math.floor(Date.now()/1e3).toString()},body:JSON.stringify(e)})})}isClientError(e){return e>=Wn.HTTP_STATUS.CLIENT_ERROR_START&&e=Wn.HTTP_STATUS.SERVER_ERROR_START}isTooManyRequests(e){return e===Wn.HTTP_STATUS.TOO_MANY_REQUESTS}handleClientError(e,t){Ge("Failed to send analytics events:",new G(`Analytics API error: ${e} ${t}`))}handleUnknownError(e){if(this.backoff{e.hidden?(this.clearTimeout(),this.shouldSend=!1):(this.shouldSend=!0,this.scheduleNextFlushIfNeeded())})}catch(t){Ge("Cannot subscribe to the document.visibilitychange: ",t)}}getMode(){return this.mode}getPendingEventsCount(){return this.events.length}filterFullModeFields(e){const t=Object.assign({},e);for(const r of Wn.FULL_MODE_FIELDS)delete t[r];const n="event_name"in e?String(e.event_name):"";return!("error_code"in e||"error_message"in e||n.includes("error")||"connection-error"===n||"transaction-signing-failed"===n||"sign-data-request-failed"===n)&&"wallet_address"in t&&delete t.wallet_address,t}setWalletListDownloadDuration(e){this.baseEvent=Object.assign(Object.assign({},this.baseEvent),{wallet_list_download_duration:e})}}Wn.HTTP_STATUS={TOO_MANY_REQUESTS:429,CLIENT_ERROR_START:400,SERVER_ERROR_START:500},Wn.MAX_BACKOFF_ATTEMPTS=5,Wn.BACKOFF_MULTIPLIER=2,Wn.FULL_MODE_FIELDS=["user_id","tg_id","locale","tma_is_premium"];class Dn{constructor(){this.window=vt()}dispatchEvent(e,t){return $(this,0,void 0,function*(){var n;const r=new CustomEvent(e,{detail:t});null===(n=this.window)||void 0===n||n.dispatchEvent(r)})}addEventListener(e,t,n){return $(this,0,void 0,function*(){var r;return null===(r=this.window)||void 0===r||r.addEventListener(e,t,n),()=>{var n;return null===(n=this.window)||void 0===n?void 0:n.removeEventListener(e,t)}})}}function jn(e){return{"@tonconnect/sdk":e.ton_connect_sdk_lib||"","@tonconnect/ui":e.ton_connect_ui_lib||""}}function Un(e){var t,n,r,o,i,a,s,l;return{versions:jn(e.custom_data),network_id:null!==(t=e.custom_data.chain_id)&&void 0!==t?t:"",client_id:null!==(n=e.custom_data.client_id)&&void 0!==n?n:"",wallet_id:null!==(r=e.custom_data.wallet_id)&&void 0!==r?r:"",wallet_address:null!==(o=e.wallet_address)&&void 0!==o?o:"",wallet_app_name:null!==(i=e.wallet_type)&&void 0!==i?i:"",wallet_app_version:null!==(a=e.wallet_version)&&void 0!==a?a:"",wallet_state_init:null!==(s=e.wallet_state_init)&&void 0!==s?s:"",trace_id:null!==(l=e.trace_id)&&void 0!==l?l:void 0}}const qn="ton-connect-session_storage_launchParams";function Bn(e){try{return e=e.replace(/\+/g,"%20"),decodeURIComponent(e)}catch(t){return e}}function zn(e){const t={};if(!e.length)return t;const n=e.split("&");for(const r of n){const e=r.split("=");t[Bn(e[0])]=null==e[1]?null:Bn(e[1])}return t}function Fn(e){var t,n,r;try{return JSON.parse(null===(r=null===(n=null===(t=vt())||void 0===t?void 0:t.sessionStorage)||void 0===n?void 0:n.getItem)||void 0===r?void 0:r.call(n,e))}catch(o){}return null}function Kn(e,t){for(const[n,r]of Object.entries(t))null!=r&&void 0===e[n]&&(e[n]=r)}function Hn(){var e,t,n,r;try{return function(e){const t={};if(!(e=e.replace(/^#/,"")).length)return t;if(e.indexOf("=")<0&&e.indexOf("?")<0)return t._path=Bn(e),t;const n=e.indexOf("?");n>=0&&(t._path=Bn(e.substring(0,n)),e=e.substring(n+1));for(const[r,o]of Object.entries(zn(e)))null!=o&&(t[r]=o);return t}(null!==(r=null===(n=null===(t=null===(e=vt())||void 0===e?void 0:e.location)||void 0===t?void 0:t.hash)||void 0===n?void 0:n.toString())&&void 0!==r?r:"")}catch(o){return{}}}function Vn(){var e,t,n,r;const o=Hn();Kn(o,function(){var e,t,n;let r;try{r=null===(n=null===(t=null===(e=vt())||void 0===e?void 0:e.sessionStorage)||void 0===t?void 0:t.getItem)||void 0===n?void 0:n.call(t,"tapps/launchParams")}catch(o){}if(!r)return{};try{const e=JSON.parse(r);if("string"!=typeof e)return{};r=e}catch(o){}return zn(r)}()),Kn(o,null!==(e=Fn("__telegram__initParams"))&&void 0!==e?e:{}),Kn(o,null!==(t=Fn(qn))&&void 0!==t?t:{});try{Object.keys(o).length>0&&(null===(r=null===(n=vt())||void 0===n?void 0:n.sessionStorage)||void 0===r||r.setItem(qn,JSON.stringify(o)))}catch(i){}return o}function $n(e){try{const t=e.tgWebAppData;if(!t)return;const n=zn(t).user;if(!n)return;const r=JSON.parse(n);return"number"==typeof r.id?{id:r.id,isPremium:!0===r.is_premium}:void 0}catch(t){return}}let Gn;function Xn(){var e,t,n;if(Gn)return Gn;const r=Vn(),o=vt();let i="unknown";r.tgWebAppPlatform&&(i=r.tgWebAppPlatform),"unknown"===i&&(i=null!==(n=null===(t=null===(e=null==o?void 0:o.Telegram)||void 0===e?void 0:e.WebApp)||void 0===t?void 0:t.platform)&&void 0!==n?n:"unknown");let a="6.0";return r.tgWebAppVersion&&(a=r.tgWebAppVersion),Gn={platform:i,webAppVersion:a,telegramUser:$n(r)},Gn}function Zn(){return Xn().platform}function Yn(...e){return e.includes(Xn().platform)}function Qn(){var e;return"unknown"!==Xn().platform||!!(null===(e=vt())||void 0===e?void 0:e.TelegramWebviewProxy)}function Jn(){var e;return(Qn()||!!(null===(e=vt())||void 0===e?void 0:e.TelegramWebview))&&"unknown"===Xn().platform}function er(){return Xn().webAppVersion}function tr(){return Xn().telegramUser}class nr{getClientEnvironment(){return Qn()?"miniapp":"web"}getBrowser(){return""}getLocale(){return""}getPlatform(){return""}getTelegramUser(){return tr()}}const rr={};function or(){return void 0!==rr.UniversalConnectorCls&&void 0!==rr.walletConnectOptions}const ir="0";class ar{constructor(e){this.connectionStorage=e,this.type="injected",this.listeners=[],this.connector=void 0;const{projectId:t,metadata:n}=function(){if(void 0===rr.walletConnectOptions)throw new G("Wallet Connect is not initialized.");return rr.walletConnectOptions}();this.config={networks:[{namespace:"ton",chains:[{id:-239,chainNamespace:"ton",caipNetworkId:"ton:-239",name:"TON",nativeCurrency:{name:"TON",symbol:"TON",decimals:9},rpcUrls:{default:{http:[]}}},{id:-3,chainNamespace:"ton",caipNetworkId:"ton:-3",name:"TON",nativeCurrency:{name:"TON",symbol:"TON",decimals:9},rpcUrls:{default:{http:[]}}}],methods:["ton_sendMessage","ton_signData"],events:[]}],projectId:t,metadata:n}}static fromStorage(e){return $(this,0,void 0,function*(){return new ar(e)})}initialize(){return $(this,0,void 0,function*(){return this.connector||(this.connector=yield function(){if(void 0===rr.UniversalConnectorCls)throw new G("Wallet Connect is not initialized.");return rr.UniversalConnectorCls}().init(this.config)),this.connector})}connect(e,t){var n,r;const o=null!==(n=null==t?void 0:t.traceId)&&void 0!==n?n:rt(),i=He(null==t?void 0:t.signal);null===(r=this.abortController)||void 0===r||r.abort(),this.abortController=i,this._connect(e,{traceId:o,signal:i.signal,abortController:i}).catch(e=>$e("WalletConnect connect unexpected error",e))}_connect(t,n){return $(this,0,void 0,function*(){var r,o;const i=yield this.initialize();if(null===(r=n.signal)||void 0===r?void 0:r.aborted)return $e("WalletConnect connect aborted before start"),void this.clearAbortController(n.abortController);const a=t.items.find(e=>"ton_proof"===e.name),s=a?[{domain:new URL(this.config.metadata.url).hostname,chains:["ton:-239"],nonce:"",uri:"ton_proof",ttl:0,statement:a.payload}]:void 0;$e("Connecting through this.connector.connect");try{yield i.connect({authentication:s})}catch(l){if(null===(o=n.signal)||void 0===o?void 0:o.aborted)return $e("WalletConnect connect aborted via signal"),void this.clearAbortController(n.abortController);$e("WalletConnect connect error",l);const t={id:0,event:"connect_error",traceId:n.traceId,payload:{code:e.CONNECT_EVENT_ERROR_CODES.USER_REJECTS_ERROR,message:"User declined the connection"}};return $e("WalletConnect connect response:",t),this.emit(t),void this.clearAbortController(n.abortController)}$e("Connected through this.connector.connect");try{yield this.onConnect(i,Object.assign(Object.assign({},n),{includeTonProof:!0}))}catch(l){$e("WalletConnect onConnect error",l),yield this.disconnect({traceId:n.traceId,signal:n.signal})}finally{this.clearAbortController(n.abortController)}})}restoreConnection(e){return $(this,0,void 0,function*(){var t,n;const r=null!==(t=null==e?void 0:e.traceId)&&void 0!==t?t:rt(),o=He(null==e?void 0:e.signal);if(null===(n=this.abortController)||void 0===n||n.abort(),this.abortController=o,!o.signal.aborted)try{$e("Restoring WalletConnect connection...");if(!(yield this.connectionStorage.getWalletConnectConnection())||o.signal.aborted)return;const e=yield this.initialize();if(o.signal.aborted)return;yield this.onConnect(e,{includeTonProof:!1,restored:!0,traceId:r,signal:o.signal}),$e("WalletConnect successfully restored.")}catch(i){$e("WalletConnect restore error",i),yield this.disconnect({traceId:r,signal:o.signal})}finally{this.clearAbortController(o)}})}closeConnection(){var e;null===(e=this.abortController)||void 0===e||e.abort(),this.abortController=void 0,this.disconnect()}disconnect(e){return $(this,0,void 0,function*(){var t,n;const r=He(null==e?void 0:e.signal);if(null===(t=this.abortController)||void 0===t||t.abort(),this.abortController=r,!r.signal.aborted)try{if(yield this.connectionStorage.removeConnection(),r.signal.aborted)return;yield null===(n=this.connector)||void 0===n?void 0:n.disconnect()}catch(o){$e("WalletConnect disconnect error",o)}finally{this.clearAbortController(r)}})}sendRequest(t,n){return $(this,0,void 0,function*(){var r,o,i,a;if(!this.connector)throw new G("Wallet Connect not initialized");const s={};"function"==typeof n?s.onRequestSent=n:(s.onRequestSent=null==n?void 0:n.onRequestSent,s.signal=null==n?void 0:n.signal,s.attempts=null==n?void 0:n.attempts,s.traceId=null==n?void 0:n.traceId),null!==(r=s.traceId)&&void 0!==r||(s.traceId=rt());try{if(null===(o=s.signal)||void 0===o?void 0:o.aborted)throw new G("WalletConnect request aborted");if($e("Send wallet-connect request:",Object.assign(Object.assign({},t),{id:ir})),"sendTransaction"===t.method){const e=JSON.parse(t.params[0]),{network:n}=e,r=V(e,["network"]),o=this.connector.request({method:"ton_sendMessage",params:r},`ton:${n}`);null===(i=null==s?void 0:s.onRequestSent)||void 0===i||i.call(s);const a=yield o;return $e("Wallet message received:",{result:a,id:ir}),{result:a,id:ir,traceId:s.traceId}}if("signData"===t.method){const e=JSON.parse(t.params[0]),{network:n}=e,r=V(e,["network"]),o=this.connector.request({method:"ton_signData",params:r},`ton:${n}`);null===(a=null==s?void 0:s.onRequestSent)||void 0===a||a.call(s);const i=yield o;return $e("Wallet message received:",{result:i,id:ir}),{result:i,traceId:s.traceId,id:ir}}if("disconnect"===t.method)return{id:ir,traceId:s.traceId}}catch(l){$e("WalletConnect request error",l,l.stack);const e=yield this.handleWalletConnectError(l,{traceId:s.traceId});return $e("Wallet message received:",e),e}return{id:ir,error:{code:e.DISCONNECT_ERROR_CODES.UNKNOWN_ERROR,message:"Not implemented."},traceId:s.traceId}})}handleWalletConnectError(t,n){return $(this,0,void 0,function*(){if("object"==typeof t&&null!==t){const r=String("message"in t?t.message:"msg"in t?t.msg:t);return r.toLowerCase().includes("reject")?{id:ir,traceId:n.traceId,error:{code:e.SEND_TRANSACTION_ERROR_CODES.USER_REJECTS_ERROR,message:r}}:r.toLowerCase().includes("tonvalidationerror")?{id:ir,traceId:n.traceId,error:{code:e.SEND_TRANSACTION_ERROR_CODES.BAD_REQUEST_ERROR,message:r}}:{id:ir,traceId:n.traceId,error:{code:e.SEND_TRANSACTION_ERROR_CODES.UNKNOWN_ERROR,message:r}}}return{id:ir,traceId:n.traceId,error:{code:e.SEND_TRANSACTION_ERROR_CODES.UNKNOWN_ERROR,message:String(t)}}})}listen(e){return this.listeners.push(e),()=>this.listeners=this.listeners.filter(t=>t!==e)}buildTonProof(e){var t,n,r;const o=null===(t=e.provider.session.authentication)||void 0===t?void 0:t[0],i=null===(n=null==o?void 0:o.p)||void 0===n?void 0:n.iat,a=null===(r=null==o?void 0:o.p)||void 0===r?void 0:r.statement;if(!i||!a)return;const s=o.p.domain;return{name:"ton_proof",proof:{timestamp:Math.floor(new Date(i).getTime()/1e3),domain:{lengthBytes:s.length,value:s},payload:a,signature:o.s.s}}}onConnect(t,n){return $(this,0,void 0,function*(){var r,o,i,a;if(null===(r=n.signal)||void 0===r?void 0:r.aborted)return void $e("WalletConnect onConnect aborted");const s=t.provider.session,l=s.namespaces.ton;if(!(null===(o=null==l?void 0:l.accounts)||void 0===o?void 0:o[0]))return void(yield this.disconnectWithError({traceId:n.traceId,code:e.CONNECT_EVENT_ERROR_CODES.BAD_REQUEST_ERROR,message:"Connection error. No TON accounts connected."}));const c=l.accounts[0],[,d,u]=c.split(":",3),h=null===(i=s.sessionProperties)||void 0===i?void 0:i.ton_getPublicKey;if(!h)return void(yield this.disconnectWithError({traceId:n.traceId,code:e.CONNECT_EVENT_ERROR_CODES.BAD_REQUEST_ERROR,message:"Connection error. No sessionProperties.ton_getPublicKey provided."}));const p=null===(a=s.sessionProperties)||void 0===a?void 0:a.ton_getStateInit;if(!p)return void(yield this.disconnectWithError({traceId:n.traceId,code:e.CONNECT_EVENT_ERROR_CODES.BAD_REQUEST_ERROR,message:"Connection error. No sessionProperties.ton_getStateInit provided."}));t.provider.once("session_delete",()=>$(this,0,void 0,function*(){try{yield this.connectionStorage.removeConnection();const e={event:"disconnect",traceId:rt(),payload:{}};$e("Wallet message received:",e),this.emit(e)}catch(e){$e("Error while deleting session",e)}}));const f=(null==n?void 0:n.includeTonProof)?this.buildTonProof(t):void 0,g={items:[{name:"ton_addr",address:xt(u)?function({wc:e,hex:t}){return`${e}:${t}`}(St(u)):u,network:d,publicKey:h,walletStateInit:p},...f?[f]:[]],device:{appName:"wallet_connect",appVersion:"",maxProtocolVersion:2,features:this.buildFeatureList(l.methods),platform:"browser"}};$e("WalletConnect connect response:",{event:"connect",payload:g,id:0}),this.emit({event:"connect",payload:g,traceId:n.traceId,restored:n.restored}),yield this.storeConnection()})}buildFeatureList(e){const t=[];return e.includes("ton_sendMessage")&&t.push("SendTransaction",{name:"SendTransaction",maxMessages:4,extraCurrencySupported:!1}),e.includes("ton_signData")&&t.push({name:"SignData",types:["text","binary","cell"]}),t}disconnectWithError(e){return $(this,0,void 0,function*(){yield this.disconnect();const t={code:e.code,message:e.message};$e("WalletConnect connect response:",{event:"connect_error",id:0,payload:t}),this.emit({event:"connect_error",traceId:e.traceId,payload:t})})}clearAbortController(e){this.abortController===e&&(this.abortController=void 0)}emit(e,t){(null!=t?t:this.listeners).forEach(t=>t(e))}storeConnection(){return this.connectionStorage.storeConnection({type:"wallet-connect"})}}function sr(e){switch(e.method){case"sendTransaction":{const t=e.request;return Object.assign(Object.assign(Object.assign(Object.assign({m:"st"},t.from?{f:t.from}:{}),t.network?{n:t.network}:{}),{vu:t.validUntil}),lr(t))}case"signMessage":{const t=e.request;return Object.assign(Object.assign(Object.assign(Object.assign({m:"sm"},t.from?{f:t.from}:{}),t.network?{n:t.network}:{}),{vu:t.validUntil}),lr(t))}case"signData":{const t=e.request,n=Object.assign(Object.assign({m:"sd"},t.from?{f:t.from}:{}),t.network?{n:t.network}:{});switch(t.type){case"text":return Object.assign(Object.assign({},n),{t:"text",tx:t.text});case"binary":return Object.assign(Object.assign({},n),{t:"binary",b:t.bytes});case"cell":return Object.assign(Object.assign({},n),{t:"cell",s:t.schema,c:t.cell})}}}}function lr(e){return he(e)?{i:e.items.map(e=>function(e){switch(e.type){case"ton":return Object.assign(Object.assign(Object.assign({t:"ton",a:e.address,am:e.amount},e.payload?{p:it(e.payload)}:{}),e.stateInit?{si:it(e.stateInit)}:{}),e.extraCurrency?{ec:e.extraCurrency}:{});case"jetton":return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({t:"jetton",ma:e.master,d:e.destination,am:e.amount},e.attachAmount?{aa:e.attachAmount}:{}),e.responseDestination?{rd:e.responseDestination}:{}),e.customPayload?{cp:it(e.customPayload)}:{}),e.forwardAmount?{fa:e.forwardAmount}:{}),e.forwardPayload?{fp:it(e.forwardPayload)}:{}),e.queryId?{qi:e.queryId}:{});case"nft":return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({t:"nft",na:e.nftAddress,no:e.newOwner},e.attachAmount?{aa:e.attachAmount}:{}),e.responseDestination?{rd:e.responseDestination}:{}),e.customPayload?{cp:it(e.customPayload)}:{}),e.forwardAmount?{fa:e.forwardAmount}:{}),e.forwardPayload?{fp:it(e.forwardPayload)}:{}),e.queryId?{qi:e.queryId}:{})}}(e))}:{ms:e.messages.map(e=>{const t={a:e.address,am:e.amount};return e.payload&&(t.p=it(e.payload)),e.stateInit&&(t.si=it(e.stateInit)),e.extraCurrency&&(t.ec=e.extraCurrency),t})}}const cr=new class{constructor(){this.convertToWireEmbeddedRequest=sr}isError(e){return"error"in e}convertFromRpcResponse(e,t){if(this.isError(t))return{ok:!1,error:t.error};switch(e){case"sendTransaction":return{ok:!0,result:{boc:t.result}};case"signMessage":return{ok:!0,result:{internalBoc:t.result.internalBoc}};case"signData":return{ok:!0,result:t.result};default:throw new Error(`Unexpected embedded request method: ${e}`)}}};class dr{constructor(e){if(this.__isConsumable=!0,e&&"object"==typeof e&&e.__isConsumable)return e;this.value=e}peek(){return this.value}consume(){$e("Consuming object",this.value);const e=this.value;return this.value=void 0,e}get consumed(){return void 0===this.value}}class ur{static getWallets(){return this.walletsList.getWallets()}get connected(){return null!==this._wallet}get account(){var e;return(null===(e=this._wallet)||void 0===e?void 0:e.account)||null}get wallet(){return this._wallet}set wallet(e){this._wallet=e,this.statusChangeSubscriptions.forEach(e=>e(this._wallet))}constructor(e){var t,n,r;this._wallet=null,this.provider=null,this.statusChangeSubscriptions=[],this.statusChangeErrorSubscriptions=[];const o=(null==e?void 0:e.manifestUrl)||function(){var e;const t=null===(e=vt())||void 0===e?void 0:e.location.origin;return t?t+"/tonconnect-manifest.json":""}();this.dappSettings={manifestUrl:o,storage:(null==e?void 0:e.storage)||new Jt},this.walletsRequiredFeatures=null==e?void 0:e.walletsRequiredFeatures,this.environment=null!==(t=null==e?void 0:e.environment)&&void 0!==t?t:new nr,this.walletsList=new sn({walletsListSource:null==e?void 0:e.walletsListSource,cacheTTLMs:null==e?void 0:e.walletsListCacheTTLMs,onDownloadDurationMeasured:e=>{var t;null===(t=this.analytics)||void 0===t||t.setWalletListDownloadDuration(e)}});const i=null!==(n=null==e?void 0:e.eventDispatcher)&&void 0!==n?n:new Dn;if(this.tracker=new Pn({eventDispatcher:i,tonConnectSdkVersion:Ln}),this.environment=null!==(r=null==e?void 0:e.environment)&&void 0!==r?r:new nr,this.initAnalytics(o,i,e),!this.dappSettings.manifestUrl)throw new X("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 Qt(this.dappSettings.storage,this.walletsList),(null==e?void 0:e.disableAutoPauseConnection)||this.addWindowFocusAndBlurSubscriptions()}getWallets(){return this.walletsList.getWallets()}onStatusChange(e,t){return this.statusChangeSubscriptions.push(e),t&&this.statusChangeErrorSubscriptions.push(t),()=>{this.statusChangeSubscriptions=this.statusChangeSubscriptions.filter(t=>t!==e),t&&(this.statusChangeErrorSubscriptions=this.statusChangeErrorSubscriptions.filter(e=>e!==t))}}connect(e,t,n){var r,o,i,a;const s=Object.assign({},n);"object"==typeof t&&null!==t&&("tonProof"in t?s.request=t:Object.assign(s,t));const l=new dr(s.embeddedRequest);if(s.request){const e=Kt(s.request);if(e){if(!rn())throw new G("ConnectAdditionalRequest validation failed: "+e);console.error("ConnectAdditionalRequest validation failed: "+e)}}if(l.peek()){const e=function(e){if(!Dt(e))return"Embedded request must be an object";if(Ut(e,["method","request"]))return"Embedded request contains extra properties";if(!Nt(e.method))return"Embedded request: 'method' is required";if(!("request"in e))return"Embedded request: 'request' is required";const t=t=>null===t?null:`Embedded ${e.method}: ${t}`;switch(e.method){case"sendTransaction":return t(Bt(e.request));case"signData":return t(Ht(e.request));case"signMessage":return t(qt(e.request))}return`Invalid 'method' value: ${e.method}`}(l.peek());if(e){if(!rn())throw new G("EmbeddedRequest validation failed: "+e);console.error("EmbeddedRequest validation failed: "+e)}}if(this.connected)throw new Q;const c=He(null==s?void 0:s.signal);if(null===(r=this.abortController)||void 0===r||r.abort(),this.abortController=c,c.signal.aborted)throw new G("Connection was aborted");null===(o=this.provider)||void 0===o||o.closeConnection(),this.provider=this.createProvider(e),c.signal.addEventListener("abort",()=>{var e;null===(e=this.provider)||void 0===e||e.closeConnection(),this.provider=null});const d=null!==(i=null==s?void 0:s.traceId)&&void 0!==i?i:rt();this.tracker.trackConnectionStarted(d);const u=se(e,e=>Zt.isInsideWalletBrowser(e));(null==s?void 0:s.linkDisplayOnly)?this.tracker.trackConnectionLinkGenerated(u,d):this.tracker.trackConnectionInitiated(u,d);const h=l.peek(),p=h?new dr(cr.convertToWireEmbeddedRequest(h)):void 0,f=this.provider.connect(this.createConnectRequest(null==s?void 0:s.request),{openingDeadlineMS:null==s?void 0:s.openingDeadlineMS,signal:c.signal,traceId:d,embeddedRequest:p});return(null==p?void 0:p.consumed)&&(this.pendingEmbeddedRequestMethod=null===(a=l.consume())||void 0===a?void 0:a.method),f}restoreConnection(e){return $(this,0,void 0,function*(){var t,n,r;const o=null!==(t=null==e?void 0:e.traceId)&&void 0!==t?t:rt();this.tracker.trackConnectionRestoringStarted(o);const i=He(null==e?void 0:e.signal);if(null===(n=this.abortController)||void 0===n||n.abort(),this.abortController=i,i.signal.aborted)return void this.tracker.trackConnectionRestoringError("Connection restoring was aborted",o);const[a,s]=yield Promise.all([this.bridgeConnectionStorage.storedConnectionType(),this.walletsList.getEmbeddedWallet()]);if(i.signal.aborted)return void this.tracker.trackConnectionRestoringError("Connection restoring was aborted",o);let l=null;try{switch(a){case"http":l=yield lt.fromStorage(this.bridgeConnectionStorage,this.analytics);break;case"injected":l=yield Zt.fromStorage(this.bridgeConnectionStorage,this.analytics);break;case"wallet-connect":l=yield ar.fromStorage(this.bridgeConnectionStorage);break;default:if(!s)return;l=this.createProvider(s)}}catch(h){return $e("Provider is not restored",h),this.tracker.trackConnectionRestoringError("Provider is not restored",o),yield this.bridgeConnectionStorage.removeConnection(),null==l||l.closeConnection(),void(l=null)}if(i.signal.aborted)return null==l||l.closeConnection(),void this.tracker.trackConnectionRestoringError("Connection restoring was aborted",o);if(!l)return Ge("Provider is not restored"),void this.tracker.trackConnectionRestoringError("Provider is not restored",o);null===(r=this.provider)||void 0===r||r.closeConnection(),this.provider=l,l.listen(this.walletEventsListener.bind(this));const c=()=>{this.tracker.trackConnectionRestoringError("Connection restoring was aborted",o),null==l||l.closeConnection(),l=null};i.signal.addEventListener("abort",c);const d=Ve(t=>$(this,0,void 0,function*(){if(yield null==l?void 0:l.restoreConnection({openingDeadlineMS:null==e?void 0:e.openingDeadlineMS,signal:t.signal,traceId:o}),i.signal.removeEventListener("abort",c),this.connected){const e=this.getSessionInfo();this.tracker.trackConnectionRestoringCompleted(this.wallet,e,o)}else this.tracker.trackConnectionRestoringError("Connection restoring failed",o)}),{attempts:Number.MAX_SAFE_INTEGER,delayMs:2e3,signal:null==e?void 0:e.signal}),u=new Promise(e=>setTimeout(()=>e(),12e3));return Promise.race([d,u])})}sendTransaction(t,n){return $(this,0,void 0,function*(){var r,o,i,a;const s={};"function"==typeof n?s.onRequestSent=n:(s.onRequestSent=null==n?void 0:n.onRequestSent,s.signal=null==n?void 0:n.signal,s.traceId=null==n?void 0:n.traceId);const l=Bt(t);if(l){if(!rn())throw new G("SendTransactionRequest validation failed: "+l);console.error("SendTransactionRequest validation failed: "+l)}const c=He(null==s?void 0:s.signal);if(c.signal.aborted)throw new G("Transaction sending was aborted");this.checkConnection();const{requiredMessagesNumber:d,requireExtraCurrencies:u,requiredItemTypes:h}=this.extractRequiredFeatures(t);!function(e,t){var n;const r=e.includes("SendTransaction"),o=cn(e,"SendTransaction"),i={minMessages:t.requiredMessagesNumber,extraCurrencyRequired:t.requireExtraCurrencies,itemTypes:t.requiredItemTypes};if(!r&&!o)throw new te("Wallet doesn't support SendTransaction feature.",{cause:{requiredFeature:{featureName:"SendTransaction",value:i}}});if(t.requireExtraCurrencies&&(!o||!o.extraCurrencySupported))throw new te("Wallet is not able to handle such SendTransaction request. Extra currencies support is required.",{cause:{requiredFeature:{featureName:"SendTransaction",value:i}}});if(null===(n=t.requiredItemTypes)||void 0===n?void 0:n.length){if(!(null==o?void 0:o.itemTypes))throw new te("Wallet doesn't support structured items in SendTransaction.",{cause:{requiredFeature:{featureName:"SendTransaction",value:i}}});const e=t.requiredItemTypes.filter(e=>!o.itemTypes.includes(e));if(e.length)throw new te(`Wallet doesn't support item types: ${e.join(", ")} in SendTransaction.`,{cause:{requiredFeature:{featureName:"SendTransaction",value:i}}})}if(o&&void 0!==o.maxMessages){if(o.maxMessagesthis.tracker.trackTransactionSigningFailed(this.wallet,t,n,e.SEND_TRANSACTION_ERROR_CODES.UNKNOWN_ERROR,p,f));if(Oe.isError(w))return this.tracker.trackTransactionSigningFailed(this.wallet,t,w.error.message,w.error.code,p,f),Oe.parseAndThrowError(w);const y=Oe.convertFromRpcResponse(w);return this.tracker.trackTransactionSigned(this.wallet,t,y,p,f),Object.assign(Object.assign({},y),{traceId:w.traceId})})}sendRequestTrackingTransport(e,t,n){return $(this,0,void 0,function*(){let r=!1;const o=t.onRequestSent&&(()=>{try{t.onRequestSent()}catch(e){throw r=!0,e}});try{return yield this.provider.sendRequest(e,Object.assign(Object.assign({},t),{onRequestSent:o}))}catch(i){throw i instanceof oe&&!r&&n(i.message),i}})}extractRequiredFeatures(e){var t;const n=he(e);return{requiredMessagesNumber:n?e.items.length:e.messages.length,requireExtraCurrencies:n?null===(t=e.items)||void 0===t?void 0:t.filter(e=>"ton"===e.type).some(e=>e.extraCurrency&&Object.keys(e.extraCurrency).length>0):e.messages.some(e=>e.extraCurrency&&Object.keys(e.extraCurrency).length>0),requiredItemTypes:n?[...new Set(e.items.map(e=>e.type))]:void 0}}signData(t,n){return $(this,0,void 0,function*(){var r,o,i,a;const s=He(null==n?void 0:n.signal);if(s.signal.aborted)throw new G("data sending was aborted");const l=Ht(t);if(l){if(!rn())throw new G("SignDataPayload validation failed: "+l);console.error("SignDataPayload validation failed: "+l)}this.checkConnection(),function(e,t){const n=e.find(e=>e&&"object"==typeof e&&"SignData"===e.name);if(!n)throw new te("Wallet doesn't support SignData feature.",{cause:{requiredFeature:{featureName:"SignData",value:{types:t.requiredTypes}}}});const r=t.requiredTypes.filter(e=>!n.types.includes(e));if(r.length)throw new te(`Wallet doesn't support required SignData types: ${r.join(", ")}.`,{cause:{requiredFeature:{featureName:"SignData",value:{types:r}}}})}(this.wallet.device.features,{requiredTypes:[t.type]});const c=this.getSessionInfo(),d=null!==(r=null==n?void 0:n.traceId)&&void 0!==r?r:rt();this.tracker.trackDataSentForSignature(this.wallet,t,c,d);const u=t.from||this.account.address,h=t.network||this.account.chain;if((null===(o=this.wallet)||void 0===o?void 0:o.account.chain)&&h!==this.wallet.account.chain){if(!rn())throw new re("Wallet connected to a wrong network",{cause:{expectedChainId:null===(i=this.wallet)||void 0===i?void 0:i.account.chain,actualChainId:h}});console.error("Wallet connected to a wrong network",{expectedChainId:null===(a=this.wallet)||void 0===a?void 0:a.account.chain,actualChainId:h})}const p=yield this.sendRequestTrackingTransport(Me.convertToRpcRequest(Object.assign(Object.assign(Object.assign({},t),"cell"===t.type?{cell:it(t.cell)}:{}),{from:u,network:h})),{onRequestSent:null==n?void 0:n.onRequestSent,signal:s.signal,traceId:d},n=>this.tracker.trackDataSigningFailed(this.wallet,t,n,e.SIGN_DATA_ERROR_CODES.UNKNOWN_ERROR,c,d));if(Me.isError(p))return this.tracker.trackDataSigningFailed(this.wallet,t,p.error.message,p.error.code,c,d),Me.parseAndThrowError(p);const f=Me.convertFromRpcResponse(p);return this.tracker.trackDataSigned(this.wallet,t,f,c,d),Object.assign(Object.assign({},f),{traceId:d})})}signMessage(e,t){return $(this,0,void 0,function*(){var n,r,o,i;const a=He(null==t?void 0:t.signal);if(a.signal.aborted)throw new G("Message signing was aborted");const s=qt(e);if(s){if(!rn())throw new G("SignMessageRequest validation failed: "+s);console.error("SignMessageRequest validation failed: "+s)}this.checkConnection();const{requiredMessagesNumber:l,requireExtraCurrencies:c,requiredItemTypes:d}=this.extractRequiredFeatures(e);!function(e,t){var n;const r=cn(e,"SignMessage"),o={minMessages:t.requiredMessagesNumber,extraCurrencyRequired:t.requireExtraCurrencies,itemTypes:t.requiredItemTypes};if(!r)throw new te("Wallet doesn't support SignMessage feature.",{cause:{requiredFeature:{featureName:"SignMessage",value:o}}});if(t.requireExtraCurrencies&&!r.extraCurrencySupported)throw new te("Wallet is not able to handle such SignMessage request. Extra currencies support is required.",{cause:{requiredFeature:{featureName:"SignMessage",value:o}}});if(null===(n=t.requiredItemTypes)||void 0===n?void 0:n.length){if(!r.itemTypes)throw new te("Wallet doesn't support structured items in SignMessage.",{cause:{requiredFeature:{featureName:"SignMessage",value:o}}});const e=t.requiredItemTypes.filter(e=>!r.itemTypes.includes(e));if(e.length)throw new te(`Wallet doesn't support item types: ${e.join(", ")} in SignMessage.`,{cause:{requiredFeature:{featureName:"SignMessage",value:o}}})}if(void 0===r.maxMessages)Xe("Connected wallet didn't provide information about max allowed messages in the SignMessage request. Request may be rejected by the wallet.");else if(r.maxMessages{var{extraCurrency:t,payload:n,stateInit:r}=e,o=V(e,["extraCurrency","payload","stateInit"]);return Object.assign(Object.assign({},o),{payload:it(n),stateInit:it(r),extra_currency:t})})}}buildItemsRpcPayload(e,t,n){return{from:t,network:n,valid_until:e.validUntil,items:e.items.map(e=>function(e){switch(e.type){case"ton":{const{extraCurrency:t}=e,n=V(e,["extraCurrency"]);return Object.assign(Object.assign({},n),{payload:it(e.payload),stateInit:it(e.stateInit),extra_currency:t})}case"jetton":case"nft":return Object.assign(Object.assign({},e),{customPayload:it(e.customPayload),forwardPayload:it(e.forwardPayload)})}}(e))}}pauseConnection(){var e;"http"===(null===(e=this.provider)||void 0===e?void 0:e.type)&&this.provider.pause()}unPauseConnection(){var e;return"http"!==(null===(e=this.provider)||void 0===e?void 0:e.type)?Promise.resolve():this.provider.unPause()}addWindowFocusAndBlurSubscriptions(){const e=wt();if(e)try{e.addEventListener("visibilitychange",()=>{e.hidden?this.pauseConnection():this.unPauseConnection().catch(()=>{})})}catch(t){Ge("Cannot subscribe to the document.visibilitychange: ",t)}}initAnalytics(e,t,n){var r;const o=null==n?void 0:n.analytics,i=null!==(r=null==o?void 0:o.mode)&&void 0!==r?r:"telemetry";if("off"===i)return;const a=new Wn({environment:this.environment,analyticsUrl:null==o?void 0:o.url,mode:i});this.analytics=a;const s=this.environment.getTelegramUser(),l={browser:this.environment.getBrowser(),platform:this.environment.getPlatform(),manifest_json_url:e,origin_url:yt,locale:this.environment.getLocale()};s&&(l.tg_id=s.id,l.tma_is_premium=s.isPremium),function(e,t){e.addEventListener("ton-connect-ui-wallet-modal-opened",e=>{var n;const{detail:r}=e;t.emitConnectionStarted({client_id:r.client_id||"",versions:jn(r.custom_data),main_screen:r.visible_wallets,trace_id:null!==(n=r.trace_id)&&void 0!==n?n:void 0})}),e.addEventListener("ton-connect-ui-selected-wallet",e=>{var n,r;const{detail:o}=e;t.emitConnectionSelectedWallet({client_id:o.client_id||"",versions:jn(o.custom_data),main_screen:o.visible_wallets,wallets_menu:o.wallets_menu,trace_id:null!==(n=o.trace_id)&&void 0!==n?n:void 0,wallet_app_name:null!==(r=o.wallet_type)&&void 0!==r?r:"",wallet_redirect_method:o.wallet_redirect_method,wallet_redirect_link:o.wallet_redirect_link})}),e.addEventListener("ton-connect-ui-wallet-preselected",e=>{const{detail:n}=e;t.emitWalletPreselected({versions:jn(n.custom_data),wallet_app_name:n.wallet_app_name,surface:n.surface,selection_source:n.selection_source,trace_id:n.trace_id})}),e.addEventListener("ton-connect-ui-wallet-selected",e=>{const{detail:n}=e;t.emitWalletSelected({versions:jn(n.custom_data),wallet_app_name:n.wallet_app_name,surface:n.surface,selection_source:n.selection_source,connection_mode:n.connection_mode,trace_id:n.trace_id})});const n=e=>{var n;const{detail:r}=e;t.emitConnectionInitiated({versions:jn(r.custom_data),connection_source_kind:r.connection_source_kind,bridge_key:r.bridge_key,bridge_url:r.bridge_url,trace_id:null!==(n=r.trace_id)&&void 0!==n?n:void 0})};e.addEventListener("ton-connect-connection-initiated",n),e.addEventListener("ton-connect-ui-connection-initiated",n),e.addEventListener("ton-connect-connection-link-generated",e=>{var n;const{detail:r}=e;t.emitConnectionLinkGenerated({versions:jn(r.custom_data),connection_source_kind:r.connection_source_kind,bridge_key:r.bridge_key,bridge_url:r.bridge_url,trace_id:null!==(n=r.trace_id)&&void 0!==n?n:void 0})}),e.addEventListener("ton-connect-connection-completed",e=>{const{detail:n}=e;t.emitConnectionCompleted(Object.assign(Object.assign({},Un(n)),{is_restore:n.is_restore}))}),e.addEventListener("ton-connect-connection-error",e=>{var n,r;const{detail:o}=e;t.emitConnectionError({client_id:o.custom_data.client_id||"",wallet_id:o.custom_data.wallet_id||"",error_code:null!==(n=o.error_code)&&void 0!==n?n:0,error_message:o.error_message,trace_id:null!==(r=o.trace_id)&&void 0!==r?r:void 0})}),e.addEventListener("ton-connect-disconnection",e=>{const{detail:n}=e;t.emitDisconnection(Un(n))}),e.addEventListener("ton-connect-transaction-sent-for-signature",e=>{const{detail:n}=e;t.emitTransactionSent(Un(n))}),e.addEventListener("ton-connect-transaction-signed",e=>{const{detail:n}=e;t.emitTransactionSigned(Object.assign(Object.assign({},Un(n)),{signed_boc:e.detail.signed_transaction}))}),e.addEventListener("ton-connect-transaction-signing-failed",e=>{var n;const{detail:r}=e;t.emitTransactionSigningFailed(Object.assign(Object.assign({},Un(r)),{valid_until:Number(r.valid_until),messages:r.messages.map(e=>{var t,n,r,o;return{address:null!==(t=e.address)&&void 0!==t?t:"",amount:null!==(n=e.amount)&&void 0!==n?n:"",payload:null!==(r=e.payload)&&void 0!==r?r:"",state_init:null!==(o=e.state_init)&&void 0!==o?o:""}}),error_message:r.error_message,error_code:null!==(n=r.error_code)&&void 0!==n?n:0}))}),e.addEventListener("ton-connect-sign-data-request-initiated",e=>{const{detail:n}=e;null==t||t.emitSignDataRequestInitiated(Un(n))}),e.addEventListener("ton-connect-sign-data-request-completed",e=>{const{detail:n}=e;null==t||t.emitSignDataRequestCompleted(Un(n))}),e.addEventListener("ton-connect-sign-data-request-failed",e=>{var n;const{detail:r}=e;let o,i="";"text"===r.data.type&&(i=r.data.text),"cell"===r.data.type&&(i=r.data.cell,o=r.data.schema),"binary"===r.data.type&&(i=r.data.bytes),null==t||t.emitSignDataRequestFailed(Object.assign(Object.assign({},Un(r)),{sign_data_type:r.data.type,sign_data_value:i,sign_data_schema:o,error_code:null!==(n=r.error_code)&&void 0!==n?n:0,error_message:r.error_message}))})}(t,a.scoped(l))}createProvider(e){let t;return t=!Array.isArray(e)&&ie(e)?new Zt(this.bridgeConnectionStorage,e.jsBridgeKey,this.analytics):!Array.isArray(e)&&ae(e)?new ar(this.bridgeConnectionStorage):new lt(this.bridgeConnectionStorage,e,this.analytics),t.listen(this.walletEventsListener.bind(this)),t}walletEventsListener(e){switch(e.event){case"connect":this.onWalletConnected(e.payload,{traceId:e.traceId,response:e.response,restored:e.restored});break;case"connect_error":this.tracker.trackConnectionError(e.payload.message,e.payload.code,this.getSessionInfo(),e.traceId);const t=Te.parseError(e.payload);this.onWalletConnectError(t);break;case"disconnect":this.onWalletDisconnected("wallet",{traceId:e.traceId})}}onWalletConnected(t,n){var r,o;const i=this.pendingEmbeddedRequestMethod;this.pendingEmbeddedRequestMethod=void 0;const a=t.items.find(e=>"ton_addr"===e.name),s=t.items.find(e=>"ton_proof"===e.name);if(!a)throw new G("ton_addr connection item was not found");if(!ln(t.device.features,this.walletsRequiredFeatures))return null===(r=this.provider)||void 0===r||r.disconnect().catch(e=>$e(e)),void this.onWalletConnectError(new ne("Wallet does not support required features",{cause:{connectEvent:t}}));const l={device:t.device,provider:this.provider.type,account:{address:a.address,chain:a.network,walletStateInit:a.walletStateInit,publicKey:a.publicKey}};if(this.desiredChainId&&l.account.chain!==this.desiredChainId){const e=this.desiredChainId,t=l.account.chain;return null===(o=this.provider)||void 0===o||o.disconnect().catch(e=>$e(e)),void this.onWalletConnectError(new re("Wallet connected to a wrong network",{cause:{expectedChainId:e,actualChainId:t}}))}if(s){const t=function(e){if(!Dt(e))return"ton_proof item must be an object";if(Ut(e,["error","proof","name"]))return"ton_proof item contains extra properties";const t=Object.prototype.hasOwnProperty.call(e,"proof"),n=Object.prototype.hasOwnProperty.call(e,"error");if(!t&&!n)return"'ton_proof' item must contain either 'proof' or 'error'";if(t&&n)return"'ton_proof' item must contain either 'proof' or 'error', not both";if(t){const t=e.proof;if(!Dt(t))return"Invalid 'proof' object";if(Ut(t,["timestamp","domain","payload","signature"]))return"ton_proof item contains extra properties";if(!Mt(t.timestamp))return"Invalid 'proof.timestamp'";const n=t.domain;if(!Dt(n))return"Invalid 'proof.domain'";if(!Mt(n.lengthBytes))return"Invalid 'proof.domain.lengthBytes'";if(!Nt(n.value))return"Invalid 'proof.domain.value'";try{if(("undefined"!=typeof TextEncoder?(new TextEncoder).encode(n.value).length:n.value.length)!==n.lengthBytes)return"'proof.domain.lengthBytes' does not match 'proof.domain.value'"}catch(r){}if(!Nt(t.payload))return"Invalid 'proof.payload'";if(!Nt(t.signature)||!Tt.test(t.signature))return"Invalid 'proof.signature' format"}if(n){const t=e.error;if(!Dt(t))return"Invalid 'error' object";if(Ut(t,["code","message"]))return"ton_proof error contains extra properties";if(!Mt(t.code))return"Invalid 'error.code'";if(!Nt(t.message))return"Invalid 'error.message'"}return null}(s);let n;if(t)rn()&&console.error("TonProofItem validation failed: "+t),n={name:"ton_proof",error:{code:e.CONNECT_ITEM_ERROR_CODES.UNKNOWN_ERROR,message:t}};else try{if("proof"in s)n={name:"ton_proof",proof:{timestamp:s.proof.timestamp,domain:{lengthBytes:s.proof.domain.lengthBytes,value:s.proof.domain.value},payload:s.proof.payload,signature:s.proof.signature}};else{if(!("error"in s))throw new G("Invalid data format");n={name:"ton_proof",error:{code:s.error.code,message:s.error.message}}}}catch(d){n={name:"ton_proof",error:{code:e.CONNECT_ITEM_ERROR_CODES.UNKNOWN_ERROR,message:"Invalid data format"}}}l.connectItems={tonProof:n}}n.response&&i&&(l.embeddedResponse=cr.convertFromRpcResponse(i,n.response)),this.wallet=l;const c=this.getSessionInfo();this.tracker.trackConnectionCompleted(l,c,null==n?void 0:n.traceId,null==n?void 0:n.restored)}onWalletConnectError(e){if(this.statusChangeErrorSubscriptions.forEach(t=>t(e)),$e(e),e instanceof Y||e instanceof Z)throw Ge(e),e}onWalletDisconnected(e,t){const n=this.getSessionInfo();this.tracker.trackDisconnection(this.wallet,e,n,null==t?void 0:t.traceId),this.wallet=null}checkConnection(){if(!this.connected)throw new J}createConnectRequest(e){const t=[Object.assign({name:"ton_addr"},this.desiredChainId?{network:this.desiredChainId}:{})];return(null==e?void 0:e.tonProof)&&t.push({name:"ton_proof",payload:e.tonProof}),{manifestUrl:this.dappSettings.manifestUrl,items:t}}}ur.walletsList=new sn,ur.isWalletInjected=e=>Zt.isWalletInjected(e),ur.isInsideWalletBrowser=e=>Zt.isInsideWalletBrowser(e);const hr=Symbol("solid-proxy"),pr="function"==typeof Proxy,fr=Symbol("solid-track"),gr={equals:(e,t)=>e===t};let mr=to;const vr=1,wr=2,yr={owned:null,cleanups:null,context:null,owner:null},br={};var Cr=null;let xr=null,Sr=null,kr=null,Er=null,Rr=0;function _r(e,t){const n=Sr,r=Cr,o=0===e.length,i=void 0===t?r:t,a=o?yr:{owned:null,cleanups:null,context:i?i.context:null,owner:i},s=o?e:()=>e(()=>Lr(()=>io(a)));Cr=a,Sr=null;try{return eo(s,!0)}finally{Sr=n,Cr=r}}function Tr(e,t){const n={value:e,observers:null,observerSlots:null,comparator:(t=t?Object.assign({},gr,t):gr).equals||void 0};return[Xr.bind(n),e=>("function"==typeof e&&(e=e(n.value)),Zr(n,e))]}function Ir(e,t,n){Yr(Qr(e,t,!0,vr))}function Ar(e,t,n){Yr(Qr(e,t,!1,vr))}function Or(e,t,n){mr=no;const r=Qr(e,t,!1,vr);n&&n.render||(r.user=!0),Er?Er.push(r):Yr(r)}function Mr(e,t,n){n=n?Object.assign({},gr,n):gr;const r=Qr(e,t,!0,0);return r.observers=null,r.observerSlots=null,r.comparator=n.equals||void 0,Yr(r),Xr.bind(r)}function Nr(e,t,n){let r,o,i;r=!0,o=e,i={};let a=null,s=br,l=!1,c="initialValue"in i,d=!1;const u=new Set,[h,p]=(i.storage||Tr)(i.initialValue),[f,g]=Tr(void 0),[m,v]=Tr(void 0,{equals:!1}),[w,y]=Tr(c?"ready":"unresolved");function b(e,t,n,r){return a===e&&(a=null,void 0!==r&&(c=!0),e!==s&&t!==s||!i.onHydrated||queueMicrotask(()=>i.onHydrated(r,{value:t})),s=br,function(e,t){eo(()=>{void 0===t&&p(()=>e),y(void 0!==t?"errored":c?"ready":"unresolved"),g(t);for(const e of u.keys())e.decrement();u.clear()},!1)}(t,n)),t}function C(){const e=h(),t=f();if(void 0!==t&&!a)throw t;return Sr&&Sr.user,e}function x(e=!0){if(!1!==e&&l)return;l=!1;const t=d?d():r;if(null==t||!1===t)return void b(a,Lr(h));let n;const i=s!==br?s:Lr(()=>{try{return o(t,{value:h(),refetching:e})}catch(r){n=r}});var u;if(void 0===n)return(u=i)&&"object"==typeof u&&"then"in u?(a=i,"v"in i?(1===i.s?b(a,i.v,void 0,t):b(a,void 0,ao(i.v),t),i):(l=!0,queueMicrotask(()=>l=!1),eo(()=>{y(c?"refreshing":"pending"),v()},!1),i.then(e=>b(i,e,void 0,t),e=>b(i,void 0,ao(e),t)))):(b(a,i,void 0,t),i);b(a,void 0,ao(n),t)}Object.defineProperties(C,{state:{get:()=>w()},error:{get:()=>f()},loading:{get(){const e=w();return"pending"===e||"refreshing"===e}},latest:{get(){if(!c)return C();const e=f();if(e&&!a)throw e;return h()}}});let S=Cr;return d?Ir(()=>(S=Cr,x(!1))):x(!1),[C,{refetch:e=>Br(S,()=>x(e)),mutate:p}]}function Pr(e){return eo(e,!1)}function Lr(e){if(null===Sr)return e();const t=Sr;Sr=null;try{return e()}finally{Sr=t}}function Wr(e,t,n){const r=Array.isArray(e);let o;return n=>{let i;if(r){i=Array(e.length);for(let t=0;tt(i,o,n));return o=i,a}}function Dr(e){Or(()=>Lr(e))}function jr(e){return null===Cr||(null===Cr.cleanups?Cr.cleanups=[e]:Cr.cleanups.push(e)),e}function Ur(){return Sr}function qr(){return Cr}function Br(e,t){const n=Cr,r=Sr;Cr=e,Sr=null;try{return eo(t,!0)}catch(o){so(o)}finally{Cr=n,Sr=r}}function zr(e){const t=Sr,n=Cr;return Promise.resolve().then(()=>{Sr=t,Cr=n,eo(e,!1),Sr=Cr=null})}const[Fr,Kr]=Tr(!1);function Hr(){return[Fr,zr]}function Vr(e,t){const n=Symbol("context");return{id:n,Provider:co(n),defaultValue:e}}function $r(e){let t;return Cr&&Cr.context&&void 0!==(t=Cr.context[e.id])?t:e.defaultValue}function Gr(e){const t=Mr(e),n=Mr(()=>lo(t()));return n.toArray=()=>{const e=n();return Array.isArray(e)?e:null!=e?[e]:[]},n}function Xr(){if(this.sources&&this.state)if(this.state===vr)Yr(this);else{const e=kr;kr=null,eo(()=>ro(this),!1),kr=e}if(Sr){const e=this.observers?this.observers.length:0;Sr.sources?(Sr.sources.push(this),Sr.sourceSlots.push(e)):(Sr.sources=[this],Sr.sourceSlots=[e]),this.observers?(this.observers.push(Sr),this.observerSlots.push(Sr.sources.length-1)):(this.observers=[Sr],this.observerSlots=[Sr.sources.length-1])}return this.value}function Zr(e,t,n){let r=e.value;return e.comparator&&e.comparator(r,t)||(e.value=t,e.observers&&e.observers.length&&eo(()=>{for(let t=0;t1e6)throw kr=[],new Error},!1)),t}function Yr(e){if(!e.fn)return;io(e);const t=Rr;!function(e,t,n){let r;const o=Cr,i=Sr;Sr=Cr=e;try{r=e.fn(t)}catch(a){return e.pure&&(e.state=vr,e.owned&&e.owned.forEach(io),e.owned=null),e.updatedAt=n+1,so(a)}finally{Sr=i,Cr=o}(!e.updatedAt||e.updatedAt<=n)&&(null!=e.updatedAt&&"observers"in e?Zr(e,r):e.value=r,e.updatedAt=n)}(e,e.value,t)}function Qr(e,t,n,r=vr,o){const i={fn:e,state:r,updatedAt:null,owned:null,sources:null,sourceSlots:null,cleanups:null,value:t,owner:Cr,context:Cr?Cr.context:null,pure:n};return null===Cr||Cr!==yr&&(Cr.owned?Cr.owned.push(i):Cr.owned=[i]),i}function Jr(e){if(0===e.state)return;if(e.state===wr)return ro(e);if(e.suspense&&Lr(e.suspense.inFallback))return e.suspense.effects.push(e);const t=[e];for(;(e=e.owner)&&(!e.updatedAt||e.updatedAt=0;n--)if((e=t[n]).state===vr)Yr(e);else if(e.state===wr){const n=kr;kr=null,eo(()=>ro(e,t[0]),!1),kr=n}}function eo(e,t){if(kr)return e();let n=!1;t||(kr=[]),Er?n=!0:Er=[],Rr++;try{const t=e();return function(e){kr&&(to(kr),kr=null);if(e)return;const t=Er;Er=null,t.length&&eo(()=>mr(t),!1)}(n),t}catch(r){n||(Er=null),kr=null,so(r)}}function to(e){for(let t=0;t=0;t--)io(e.tOwned[t]);delete e.tOwned}if(e.owned){for(t=e.owned.length-1;t>=0;t--)io(e.owned[t]);e.owned=null}if(e.cleanups){for(t=e.cleanups.length-1;t>=0;t--)e.cleanups[t]();e.cleanups=null}e.state=0}function ao(e){return e instanceof Error?e:new Error("string"==typeof e?e:"Unknown error",{cause:e})}function so(e,t=Cr){throw ao(e)}function lo(e){if("function"==typeof e&&!e.length)return lo(e());if(Array.isArray(e)){const t=[];for(let n=0;nn=Lr(()=>(Cr.context=u(d({},Cr.context),{[e]:t.value}),Gr(()=>t.children))),void 0),n}}const uo=Symbol("fallback");function ho(e){for(let t=0;te(t||{}))}function fo(){return!0}const go={get:(e,t,n)=>t===hr?n:e.get(t),has:(e,t)=>t===hr||e.has(t),set:fo,deleteProperty:fo,getOwnPropertyDescriptor:(e,t)=>({configurable:!0,enumerable:!0,get:()=>e.get(t),set:fo,deleteProperty:fo}),ownKeys:e=>e.keys()};function mo(e){return(e="function"==typeof e?e():e)?e:{}}function vo(){for(let e=0,t=this.length;e=0;n--){const r=mo(e[n])[t];if(void 0!==r)return r}},has(t){for(let n=e.length-1;n>=0;n--)if(t in mo(e[n]))return!0;return!1},keys(){const t=[];for(let n=0;n=0;a--){const t=e[a];if(!t)continue;const o=Object.getOwnPropertyNames(t);for(let e=o.length-1;e>=0;e--){const i=o[e];if("__proto__"===i||"constructor"===i)continue;const a=Object.getOwnPropertyDescriptor(t,i);if(r[i]){const e=n[i];e&&(a.get?e.push(a.get.bind(t)):void 0!==a.value&&e.push(()=>a.value))}else r[i]=a.get?{enumerable:!0,configurable:!0,get:vo.bind(n[i]=[a.get.bind(t)])}:void 0!==a.value?a:void 0}}const o={},i=Object.keys(r);for(let a=i.length-1;a>=0;a--){const e=i[a],t=r[e];t&&t.get?Object.defineProperty(o,e,t):o[e]=t?t.value:void 0}return o}function yo(e,...t){if(pr&&hr in e){const n=new Set(t.length>1?t.flat():t[0]),r=t.map(t=>new Proxy({get:n=>t.includes(n)?e[n]:void 0,has:n=>t.includes(n)&&n in e,keys:()=>t.filter(t=>t in e)},go));return r.push(new Proxy({get:t=>n.has(t)?void 0:e[t],has:t=>!n.has(t)&&t in e,keys:()=>Object.keys(e).filter(e=>!n.has(e))},go)),r}const n={},r=t.map(()=>({}));for(const o of Object.getOwnPropertyNames(e)){const i=Object.getOwnPropertyDescriptor(e,o),a=!i.get&&!i.set&&i.enumerable&&i.writable&&i.configurable;let s=!1,l=0;for(const e of t)e.includes(o)&&(s=!0,a?r[l][o]=i.value:Object.defineProperty(r[l],o,i)),++l;s||(a?n[o]=i.value:Object.defineProperty(n,o,i))}return[...r,n]}const bo=e=>`Stale read from <${e}>.`;function Co(e){const t="fallback"in e&&{fallback:()=>e.fallback};return Mr(function(e,t,n={}){let r=[],o=[],i=[],a=0,s=t.length>1?[]:null;return jr(()=>ho(i)),()=>{let l,c,d=e()||[],u=d.length;return d[fr],Lr(()=>{let e,t,p,f,g,m,v,w,y;if(0===u)0!==a&&(ho(i),i=[],r=[],o=[],a=0,s&&(s=[])),n.fallback&&(r=[uo],o[0]=_r(e=>(i[0]=e,n.fallback())),a=1);else if(0===a){for(o=new Array(u),c=0;c=m&&w>=m&&r[v]===d[w];v--,w--)p[w]=o[v],f[w]=i[v],s&&(g[w]=s[v]);for(e=new Map,t=new Array(w+1),c=w;c>=m;c--)y=d[c],l=e.get(y),t[c]=void 0===l?-1:l,e.set(y,c);for(l=m;l<=v;l++)y=r[l],c=e.get(y),void 0!==c&&-1!==c?(p[c]=o[l],f[c]=i[l],s&&(g[c]=s[l]),c=t[c],e.set(y,c)):i[l]();for(c=m;ce.each,e.children,t||void 0))}function xo(e){const t=e.keyed,n=Mr(()=>e.when,void 0,void 0),r=t?n:Mr(n,void 0,{equals:(e,t)=>!e==!t});return Mr(()=>{const o=r();if(o){const i=e.children;return"function"==typeof i&&i.length>0?Lr(()=>i(t?o:()=>{if(!Lr(r))throw bo("Show");return n()})):i}return e.fallback},void 0,void 0)}function So(e){const t=Gr(()=>e.children),n=Mr(()=>{const e=t(),n=Array.isArray(e)?e:[e];let r=()=>{};for(let t=0;ti()?void 0:o.when,void 0,void 0),s=o.keyed?a:Mr(a,void 0,{equals:(e,t)=>!e==!t});r=()=>i()||(s()?[e,a,o]:void 0)}return r});return Mr(()=>{const t=n()();if(!t)return e.fallback;const[r,o,i]=t,a=i.children;return"function"==typeof a&&a.length>0?Lr(()=>a(i.keyed?o():()=>{var e;if((null==(e=Lr(n)())?void 0:e[0])!==r)throw bo("Match");return o()})):a},void 0,void 0)}function ko(e){return e}const Eo=new Set(["className","value","readOnly","noValidate","formNoValidate","isMap","noModule","playsInline","allowfullscreen","async","autofocus","autoplay","checked","controls","default","disabled","formnovalidate","hidden","indeterminate","inert","ismap","loop","multiple","muted","nomodule","novalidate","open","playsinline","readonly","required","reversed","seamless","selected"]),Ro=new Set(["innerHTML","textContent","innerText","children"]),_o=Object.assign(Object.create(null),{className:"class",htmlFor:"for"}),To=Object.assign(Object.create(null),{class:"className",novalidate:{$:"noValidate",FORM:1},formnovalidate:{$:"formNoValidate",BUTTON:1,INPUT:1},ismap:{$:"isMap",IMG:1},nomodule:{$:"noModule",SCRIPT:1},playsinline:{$:"playsInline",VIDEO:1},readonly:{$:"readOnly",INPUT:1,TEXTAREA:1}});const Io=new Set(["beforeinput","click","dblclick","contextmenu","focusin","focusout","input","keydown","keyup","mousedown","mousemove","mouseout","mouseover","mouseup","pointerdown","pointermove","pointerout","pointerover","pointerup","touchend","touchmove","touchstart"]),Ao=new Set(["altGlyph","altGlyphDef","altGlyphItem","animate","animateColor","animateMotion","animateTransform","circle","clipPath","color-profile","cursor","defs","desc","ellipse","feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence","filter","font","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","foreignObject","g","glyph","glyphRef","hkern","image","line","linearGradient","marker","mask","metadata","missing-glyph","mpath","path","pattern","polygon","polyline","radialGradient","rect","set","stop","svg","switch","symbol","text","textPath","tref","tspan","use","view","vkern"]),Oo={xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace"},Mo=e=>Mr(()=>e());const No="_$DX_DELEGATE";function Po(e,t,n,r){let o;const i=()=>{const t=r?document.createElementNS("http://www.w3.org/1998/Math/MathML","template"):document.createElement("template");return t.innerHTML=e,n?t.content.firstChild.firstChild:r?t.firstChild:t.content.firstChild},a=t?()=>Lr(()=>document.importNode(o||(o=i()),!0)):()=>(o||(o=i())).cloneNode(!0);return a.cloneNode=a,a}function Lo(e,t,n){null==n?e.removeAttribute(t):e.setAttribute(t,n)}function Wo(e,t){null==t?e.removeAttribute("class"):e.className=t}function Do(e,t={},n,r){const o={};return Ar(()=>o.children=Fo(e,t.children,o.children)),Ar(()=>"function"==typeof t.ref&&jo(t.ref,e)),Ar(()=>function(e,t,n,r,o={},i=!1){t||(t={});for(const a in o)if(!(a in t)){if("children"===a)continue;o[a]=Bo(e,a,null,o[a],n,i,t)}for(const a in t){if("children"===a)continue;const r=t[a];o[a]=Bo(e,a,r,o[a],n,i,t)}}(e,t,n,0,o,!0)),o}function jo(e,t,n){return Lr(()=>e(t,n))}function Uo(e,t,n,r){if(void 0===n||r||(r=[]),"function"!=typeof t)return Fo(e,t,r,n);Ar(r=>Fo(e,t(),r,n),r)}function qo(e,t,n){const r=t.trim().split(/\s+/);for(let o=0,i=r.length;or.call(e,n[1],t))}else e.addEventListener(t,n,"function"!=typeof n&&n)}(e,o,n,i),i&&function(e,t=window.document){const n=t[No]||(t[No]=new Set);for(let r=0,o=e.length;rt.toUpperCase()))]=n;else{const r=o&&t.indexOf(":")>-1&&Oo[t.split(":")[0]];r?function(e,t,n,r){null==r?e.removeAttributeNS(t,n):e.setAttributeNS(t,n,r)}(e,r,t,n):Lo(e,_o[t]||t,n)}var h;return n}function zo(e){let t=e.target;const n=`$$${e.type}`,r=e.target,o=e.currentTarget,i=t=>Object.defineProperty(e,"target",{configurable:!0,value:t}),a=()=>{const r=t[n];if(r&&!t.disabled){const o=t[`${n}Data`];if(void 0!==o?r.call(t,o,e):r.call(t,e),e.cancelBubble)return}return t.host&&"string"!=typeof t.host&&!t.host._$host&&t.contains(e.target)&&i(t.host),!0},s=()=>{for(;a()&&(t=t._$host||t.parentNode||t.host););};if(Object.defineProperty(e,"currentTarget",{configurable:!0,get:()=>t||document}),e.composedPath){const n=e.composedPath();i(n[0]);for(let e=0;e{let o=t();for(;"function"==typeof o;)o=o();n=Fo(e,o,n,r)}),()=>n;if(Array.isArray(t)){const i=[],s=n&&Array.isArray(n);if(Ko(i,t,n,o))return Ar(()=>n=Fo(e,i,n,r,!0)),()=>n;if(0===i.length){if(n=Vo(e,n,r),a)return n}else s?0===n.length?Ho(e,i,r):function(e,t,n){let r=n.length,o=t.length,i=r,a=0,s=0,l=t[o-1].nextSibling,c=null;for(;ar-s){const o=t[a];for(;s=0;i--){const a=t[i];if(o!==a){const t=a.parentNode===e;r||i?t&&a.remove():t?e.replaceChild(o,a):e.insertBefore(o,n)}else r=!0}}else e.insertBefore(o,n);return[o]}function $o(e,t=!1){return t?document.createElementNS("http://www.w3.org/2000/svg",e):document.createElement(e)}function Go(e){const{useShadow:t}=e,n=document.createTextNode(""),r=qr();let o;return Or(()=>{o||(o=Br(r,()=>Mr(()=>e.children)));const i=e.mount||document.body;if(i instanceof HTMLHeadElement){const[e,t]=Tr(!1),n=()=>t(!0);_r(t=>Uo(i,()=>e()?t():o(),null)),jr(n)}else{const r=$o(e.isSVG?"g":"div",e.isSVG),a=t&&r.attachShadow?r.attachShadow({mode:"open"}):r;Object.defineProperty(r,"_$host",{get:()=>n.parentNode,configurable:!0}),Uo(a,o),i.appendChild(r),e.ref&&e.ref(r),jr(()=>i.removeChild(r))}},void 0,{render:!0}),n}function Xo(e){const[,t]=yo(e,["component"]);return function(e,t){const n=Mr(e);return Mr(()=>{const e=n();switch(typeof e){case"function":return Lr(()=>e(t));case"string":const n=Ao.has(e),r=$o(e,n);return Do(r,t,n),r}})}(()=>e.component,t)}var Zo=(e=>(e.DARK="DARK",e.LIGHT="LIGHT",e))(Zo||{});let Yo={data:""},Qo=/(?:([\u0080-\uFFFF\w-%@]+) *:? *([^{;]+?);|([^;}{]*?) *{)|(}\s*)/g,Jo=/\/\*[^]*?\*\/| +/g,ei=/\n+/g,ti=(e,t)=>{let n="",r="",o="";for(let i in e){let a=e[i];"@"==i[0]?"i"==i[1]?n=i+" "+a+";":r+="f"==i[1]?ti(a,i):i+"{"+ti(a,"k"==i[1]?"":t)+"}":"object"==typeof a?r+=ti(a,t?t.replace(/([^,])+/g,e=>i.replace(/(^:.*)|([^,])+/g,t=>/&/.test(t)?t.replace(/&/g,e):e?e+" "+t:t)):i):null!=a&&(i=/^--/.test(i)?i:i.replace(/[A-Z]/g,"-$&").toLowerCase(),o+=ti.p?ti.p(i,a):i+":"+a+";")}return n+(t&&o?t+"{"+o+"}":o)+r},ni={},ri=e=>{if("object"==typeof e){let t="";for(let n in e)t+=n+ri(e[n]);return t}return e};function oi(e){let t=this||{},n=e.call?e(t.p):e;return((e,t,n,r,o)=>{let i=ri(e),a=ni[i]||(ni[i]=(e=>{let t=0,n=11;for(;t>>0;return"go"+n})(i));if(!ni[a]){let t=i!==e?e:(e=>{let t,n,r=[{}];for(;t=Qo.exec(e.replace(Jo,""));)t[4]?r.shift():t[3]?(n=t[3].replace(ei," ").trim(),r.unshift(r[0][n]=r[0][n]||{})):r[0][t[1]]=t[2].replace(ei," ").trim();return r[0]})(e);ni[a]=ti(o?{["@keyframes "+a]:t}:t,n?"":"."+a)}let s=n&&ni.g?ni.g:null;return n&&(ni.g=ni[a]),l=ni[a],c=t,d=r,(u=s)?c.data=c.data.replace(u,l):-1===c.data.indexOf(l)&&(c.data=d?l+c.data:c.data+l),a;var l,c,d,u})(n.unshift?n.raw?((e,t,n)=>e.reduce((e,r,o)=>{let i=t[o];if(i&&i.call){let e=i(n),t=e&&e.props&&e.props.className||/^go/.test(e)&&e;i=t?"."+t:e&&"object"==typeof e?e.props?"":ti(e,""):!1===e?"":e}return e+r+(null==i?"":i)},""))(n,[].slice.call(arguments,1),t.p):n.reduce((e,n)=>Object.assign(e,n&&n.call?n(t.p):n),{}):n,(r=t.target,"object"==typeof window?((r?r.querySelector("#_goober"):window._goober)||Object.assign((r||document.head).appendChild(document.createElement("style")),{innerHTML:" ",id:"_goober"})).firstChild:r||Yo),t.g,t.o,t.k);var r}oi.bind({g:1});let ii=oi.bind({k:1});const ai=Vr();function si(e){return po(ai.Provider,{value:e.theme,get children(){return e.children}})}function li(){return $r(ai)}function ci(e){let t=this||{};return(...n)=>{const r=r=>{const o=wo(r,{theme:$r(ai)}),i=wo(o,{get class(){const e=o.class,r="class"in o&&/^go[0-9]+/.test(e);return[e,oi.apply({target:t.target,o:r,p:o,g:t.g},n)].filter(Boolean).join(" ")}}),[a,s]=yo(i,["as","theme"]),l=s,c=a.as||e;let d;return"function"==typeof c?d=c(l):1==t.g?(d=document.createElement(c),Do(d,l)):d=Xo(wo({component:c},l)),d};return r.class=e=>Lr(()=>oi.apply({target:t.target,p:e,g:t.g},n)),r}}const di=new Proxy(ci,{get:(e,t)=>e(t)});function ui(){const e=ci.call({g:1},"div").apply(null,arguments);return function(t){return e(t),null}}const hi="tc-root",pi="tc-disable-scroll",fi="tc-using-mouse",gi=()=>{document.body.addEventListener("mousedown",()=>document.body.classList.add(fi)),document.body.addEventListener("keydown",e=>{"Tab"===e.key&&document.body.classList.remove(fi)});return po(ui` + ${hi} * { + margin: 0; + padding: 0; + box-sizing: border-box; + + font-family: -apple-system, BlinkMacSystemFont, 'Roboto', 'Helvetica Neue', Arial, Tahoma, Verdana, sans-serif; + -webkit-font-smoothing: antialiased; + -moz-osx-font-smoothing: grayscale; + -webkit-tap-highlight-color: transparent; + } + + ${hi} img { + -webkit-user-select: none; + -webkit-touch-callout: none; + } + + ${hi} *:focus { + outline: #08f auto 2px; + } + + ${hi} li { + list-style: none; + } + + ${hi} button { + outline: none; + } + + body.${pi} { + position: fixed; + overflow-y: scroll; + right: 0; + left: 0; + } + + body.${fi} ${hi} *:focus { + outline: none; + } +`,{})};function mi(e,t){return"#"===e[0]&&(e=function(e){"#"===e[0]&&(e=e.slice(1));const t=parseInt(e,16);return[t>>16&255,t>>8&255,255&t].join(",")}(e)),`rgba(${e}, ${t})`}function vi(e){return e.toString()+"px"}var wi,yi={exports:{}},bi=yi.exports;var Ci=(wi||(wi=1,function(e,t){!function(n,r){var o="function",i="undefined",a="object",s="string",l="major",c="model",d="name",u="type",h="vendor",p="version",f="architecture",g="console",m="mobile",v="tablet",w="smarttv",y="wearable",b="embedded",C="Amazon",x="Apple",S="ASUS",k="BlackBerry",E="Browser",R="Chrome",_="Firefox",T="Google",I="Huawei",A="LG",O="Microsoft",M="Motorola",N="Opera",P="Samsung",L="Sharp",W="Sony",D="Xiaomi",j="Zebra",U="Facebook",q="Chromium OS",B="Mac OS",z=" Browser",F=function(e){for(var t={},n=0;n0?2===l.length?typeof l[1]==o?this[l[0]]=l[1].call(this,d):this[l[0]]=l[1]:3===l.length?typeof l[1]!==o||l[1].exec&&l[1].test?this[l[0]]=d?d.replace(l[1],l[2]):r:this[l[0]]=d?l[1].call(this,d,l[2]):r:4===l.length&&(this[l[0]]=d?l[3].call(this,d.replace(l[1],l[2])):r):this[l]=d||r;u+=2}},G=function(e,t){for(var n in t)if(typeof t[n]===a&&t[n].length>0){for(var o=0;o2&&(e[c]="iPad",e[u]=v),e},this.getEngine=function(){var e={};return e[d]=r,e[p]=r,$.call(e,w,b.engine),e},this.getOS=function(){var e={};return e[d]=r,e[p]=r,$.call(e,w,b.os),C&&!e[d]&&y&&y.platform&&"Unknown"!=y.platform&&(e[d]=y.platform.replace(/chrome os/i,q).replace(/macos/i,B)),e},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 w},this.setUA=function(e){return w=typeof e===s&&e.length>500?V(e,500):e,this},this.setUA(w),this};Y.VERSION="1.0.40",Y.BROWSER=F([d,p,l]),Y.CPU=F([f]),Y.DEVICE=F([c,h,u,g,m,w,v,y,b]),Y.ENGINE=Y.OS=F([d,p]),e.exports&&(t=e.exports=Y),t.UAParser=Y;var Q=typeof n!==i&&(n.jQuery||n.Zepto);if(Q&&!Q.ua){var J=new Y;Q.ua=J.getResult(),Q.ua.get=function(){return J.getUA()},Q.ua.set=function(e){J.setUA(e);var t=J.getResult();for(var n in t)Q.ua[n]=t[n]}}}("object"==typeof window?window:bi)}(yi,yi.exports)),yi.exports);const xi=f(Ci);class Si{constructor(){this.storage={}}static getInstance(){return Si.instance||(Si.instance=new Si),Si.instance}get length(){return Object.keys(this.storage).length}clear(){this.storage={}}getItem(e){var t;return null!=(t=this.storage[e])?t:null}key(e){var t;const n=Object.keys(this.storage);return e<0||e>=n.length?null:null!=(t=n[e])?t:null}removeItem(e){delete this.storage[e]}setItem(e,t){this.storage[e]=t}}const ki=class extends G{constructor(...e){super(...e)}};ki.errorName="TonConnectUIError";let Ei=ki;function Ri(...e){try{console.debug("[TON_CONNECT_UI]",...e)}catch(t){}}function _i(...e){try{console.error("[TON_CONNECT_UI]",...e)}catch(t){}}function Ti(){Oi("web_app_expand",{})}function Ii(e,t){e.length>qi&&(e=Wi(e));const n=new URL(e);if("http:"!==n.protocol&&"https:"!==n.protocol){if(t)return t();throw new Ei(`Url protocol is not supported: ${n}`)}if("t.me"!==n.hostname){if(t)return t();throw new Ei(`Url host is not supported: ${n}`)}const r=n.pathname+n.search;var o;Ai()||(o="6.1",function(e,t){"string"!=typeof e&&(e="");let n,r,o,i,a=e.replace(/^\s+|\s+$/g,"").split("."),s=t.replace(/^\s+|\s+$/g,"").split(".");for(n=Math.max(a.length,s.length),r=0;ri?1:-1;return 0}(er(),o)>=0)?(Ta({link:r,type:"tg_link"}),Oi("web_app_open_tg_link",{path_full:r})):zi("https://t.me"+r)}function Ai(){try{const e=Vi();return!!e&&(null!=e.parent&&e!==e.parent)}catch(e){return!1}}function Oi(e,t){try{const n=Vi();if(!n)throw new Ei("Can't post event to parent window: window is not defined");if(void 0!==n.TelegramWebviewProxy)Ri("postEvent",e,t),n.TelegramWebviewProxy.postEvent(e,JSON.stringify(t));else if(n.external&&"notify"in n.external)Ri("postEvent",e,t),n.external.notify(JSON.stringify({eventType:e,eventData:t}));else{if(!Ai())throw new Ei("Can't post event to TMA");{const r="*",o=JSON.stringify({eventType:e,eventData:t});Ri("postEvent",e,t),n.parent.postMessage(o,r)}}}catch(n){_i(`Can't post event to parent window: ${n}`)}}function Mi(e,t){let n;n="string"==typeof t?t:Qn()?t.twaReturnUrl||t.returnStrategy:"none";const r=function(e,t,n){const r=new URL(e);return r.searchParams.append(t,n),r.toString()}(e,"ret",n);if(!We(e))return r;const o=r.slice(r.lastIndexOf("&")+1);return r.slice(0,r.lastIndexOf("&"))+"-"+je(o)}function Ni(e,t){t=d({},t);const n=Di(e),r=new URL(n);if(r.searchParams.has("startapp")||r.searchParams.append("startapp","tonconnect"),Jn()){t.returnStrategy="back";zi(Mi(r.toString(),t.returnStrategy))}else if(Qn())if(Yn("ios","android","macos","tdesktop","web")){t.returnStrategy="back";Ii(Mi(r.toString(),t.returnStrategy))}else Yn("weba")?Ii(Mi(r.toString(),t)):zi(Mi(r.toString(),t));else if(Zi("ios")){"back"===t.returnStrategy&&(Yi("safari")?t.returnStrategy="back":Yi("chrome")?t.returnStrategy="googlechrome://":Yi("firefox")?t.returnStrategy="firefox://":Yi("opera")?t.returnStrategy="opera-http://":t.returnStrategy=location.href);const e=Yi("chrome"),n=Yi("firefox");if((e||n)&&!t.forceRedirect){const e=Mi(r.toString(),t.returnStrategy);Fi(Ui(e),()=>zi(e))}else{zi(Mi(r.toString(),t.returnStrategy))}}else if(Zi("android")){t.returnStrategy="back";const e=Yi("chrome"),n=Yi("firefox");if((e||n)&&!t.forceRedirect){const e=Mi(r.toString(),t.returnStrategy);Fi(Ui(e),()=>zi(e))}else{zi(Mi(r.toString(),t.returnStrategy))}}else if(Zi("ipad")){"back"===t.returnStrategy&&(Yi("safari")?t.returnStrategy="back":Yi("chrome")?t.returnStrategy="googlechrome://":Yi("firefox")?t.returnStrategy="firefox://":Yi("opera")?t.returnStrategy="opera-http://":t.returnStrategy=location.href);const e=Yi("chrome"),n=Yi("firefox"),o=(e||n)&&!t.forceRedirect,i=Mi(r.toString(),t.returnStrategy);if(o){Fi(Ui(i),()=>zi(i))}else zi(i)}else if(Zi("macos","windows","linux")){t.returnStrategy="back",t.twaReturnUrl=void 0;const e=Mi(r.toString(),t.returnStrategy);if(t.forceRedirect)zi(e);else{Fi(Ui(e),()=>zi(e))}}else zi(Mi(r.toString(),t))}function Pi(e,t,n,r){if(n=d({},n),Jn())if(Zi("ios","android"))"back"===n.returnStrategy&&(n.returnStrategy="tg://resolve"),r("universal-link"),Bi(Mi(e,n.returnStrategy),"_self");else{r("universal-link");zi(Mi(e,n.returnStrategy))}else if(Qn())if(Yn("ios","android")){"back"===n.returnStrategy&&(n.returnStrategy="tg://resolve"),r("universal-link");const t=Mi(e,n.returnStrategy);Ii(t,()=>{r("universal-link"),zi(t)})}else if(Yn("macos","tdesktop")){"back"===n.returnStrategy&&(n.returnStrategy="tg://resolve");const o=Mi(e,n.returnStrategy);!!t&&!n.forceRedirect?(r("custom-deeplink"),Fi(Qi(o,t),()=>{r("universal-link"),zi(o)})):(r("universal-link"),zi(o))}else if(Yn("weba")){"back"===n.returnStrategy&&(Yi("safari")?n.returnStrategy=location.href:Yi("chrome")?n.returnStrategy="googlechrome://":Yi("firefox")?n.returnStrategy="firefox://":Yi("opera")?n.returnStrategy="opera-http://":n.returnStrategy=location.href);const o=Mi(e,n.returnStrategy);!!t&&!n.forceRedirect?(r("custom-deeplink"),Fi(Qi(o,t),()=>{r("universal-link"),zi(o)})):(r("universal-link"),zi(o))}else if(Yn("web")){"back"===n.returnStrategy&&(Yi("safari")?n.returnStrategy=location.href:Yi("chrome")?n.returnStrategy="googlechrome://":Yi("firefox")?n.returnStrategy="firefox://":Yi("opera")?n.returnStrategy="opera-http://":n.returnStrategy=location.href);const o=Mi(e,n.returnStrategy);!!t&&!n.forceRedirect?(r("custom-deeplink"),Fi(Qi(o,t),()=>{r("universal-link"),zi(o)})):(r("universal-link"),zi(o))}else{r("universal-link");zi(Mi(e,n.returnStrategy))}else if(Zi("ios"))"back"===n.returnStrategy&&(Yi("safari")?n.returnStrategy="none":Yi("chrome")?n.returnStrategy="googlechrome://":Yi("firefox")?n.returnStrategy="firefox://":Yi("opera")?n.returnStrategy="opera-http://":n.returnStrategy=location.href),Yi("chrome")?(r("universal-link"),Bi(Mi(e,n.returnStrategy),"_self")):(r("universal-link"),zi(Mi(e,n.returnStrategy)));else if(Zi("android"))"back"===n.returnStrategy&&(Yi("chrome")?n.returnStrategy="googlechrome://":Yi("firefox")?n.returnStrategy="firefox://":Yi("opera")?n.returnStrategy="opera-http://":n.returnStrategy=location.href),r("universal-link"),zi(Mi(e,n.returnStrategy));else if(Zi("ipad"))"back"===n.returnStrategy&&(Yi("safari")?n.returnStrategy="none":Yi("chrome")?n.returnStrategy="googlechrome://":Yi("firefox")?n.returnStrategy="firefox://":Yi("opera")?n.returnStrategy="opera-http://":n.returnStrategy=location.href),Yi("chrome")?(r("universal-link"),Bi(Mi(e,n.returnStrategy),"_self")):(r("universal-link"),zi(Mi(e,n.returnStrategy)));else if(Zi("macos","windows","linux")){"back"===n.returnStrategy&&(Yi("safari")?n.returnStrategy="none":Yi("chrome")?n.returnStrategy="googlechrome://":Yi("firefox")?n.returnStrategy="firefox://":Yi("opera")?n.returnStrategy="opera-http://":n.returnStrategy="none");const o=Mi(e,n.returnStrategy);!!t&&!n.forceRedirect?(r("custom-deeplink"),Fi(Qi(o,t),()=>{r("universal-link"),zi(o)})):(r("universal-link"),zi(o))}else r("universal-link"),zi(Mi(e,n.returnStrategy))}function Li(e,t){var n,r;if(!We(e))return function(e,t){const n=new URL(e);for(const[r,o]of Object.entries(t))null!=o&&n.searchParams.set(r,o);return n.toString()}(e,{id:t.sessionId,trace_id:t.traceId});const o=Di(e),i=new URL(o);let a=ji(Ue(null!=(n=i.searchParams.get("startapp"))?n:""));const s=null!=(r=t.sessionId)?r:a.get("id"),l=t.traceId,c=["tonconnect","v","id","trace_id"],h=Array.from(a.entries()).filter(([e])=>!c.includes(e)),p=function(e){const t=ji();for(const[n,r]of Object.entries(e))null!=r&&t.append(n,r);return t.toString()}(u(d({tonconnect:"",v:"2",id:s},Object.fromEntries(h)),{trace_id:l})).replace("=&","&");return i.searchParams.set("startapp",je(p)),i.toString()}function Wi(e){return function(e,t){var n;if(!We(e))return function(e,t){const n=new URL(e);for(const r of t)n.searchParams.delete(r);return n.toString()}(e,t);const r=Di(e),o=new URL(r);let i=ji(Ue(null!=(n=o.searchParams.get("startapp"))?n:""));for(const s of t)i.delete(s);const a=i.toString().replace("=&","&");return o.searchParams.set("startapp",je(a)),o.toString()}(e,["e"])}function Di(e){const t=new URL(e);return t.searchParams.has("attach")&&(t.searchParams.delete("attach"),t.pathname+="/start"),t.toString()}function ji(e=""){const t=new URL("https://example.com");return t.search=e,t.searchParams}function Ui(e){const t=new URL(e),[,n,r]=t.pathname.split("/");return`tg://resolve?domain=${n}${r?`&appname=${r}`:""}&startapp=${t.searchParams.get("startapp")}`}const qi=1024;function Bi(e,t="_self"){e.length>qi&&(e=Wi(e)),Ta({link:e}),Ri("openLink",e,t),window.open(e,t,"noopener noreferrer")}function zi(e){Bi(e,"_blank")}function Fi(e,t){const n=setTimeout(()=>{Yi("safari")||Zi("android")&&Yi("firefox")||Zi("windows")||t()},200);window.addEventListener("blur",()=>clearTimeout(n),{once:!0}),Bi(e,"_self")}function Ki(e){return p(this,null,function*(){yield new Promise(e=>requestAnimationFrame(e)),e()})}function Hi(e){"complete"!==document.readyState?window.addEventListener("load",()=>Ki(()=>Hi(e)),{once:!0}):e.forEach(e=>{(new window.Image).src=e})}function Vi(){if("undefined"!=typeof window)return window}function $i(){if(function(){try{return"undefined"!=typeof localStorage}catch(e){return!1}}())return localStorage;if("undefined"!=typeof process&&null!=process.versions&&null!=process.versions.node)throw new Ei("`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 Si.getInstance()}function Gi(){let e=!1;var t;return t=navigator.userAgent||navigator.vendor||window.opera,(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(t)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(t.slice(0,4)))&&(e=!0),e}function Xi(){var e,t,n;const r=(new xi).getResult(),o=null==(e=r.os.name)?void 0:e.toLowerCase();let i;switch(!0){case"ipad"===(null==(t=r.device.model)?void 0:t.toLowerCase()):i="ipad";break;case"ios"===o:i="ios";break;case"android"===o:i="android";break;case"mac os"===o:i="macos";break;case"linux"===o:i="linux";break;case null==o?void 0:o.includes("windows"):i="windows"}const a=null==(n=r.browser.name)?void 0:n.toLowerCase();let s;switch(!0){case"chrome"===a:s="chrome";break;case"firefox"===a:s="firefox";break;case null==a?void 0:a.includes("safari"):s="safari";break;case null==a?void 0:a.includes("opera"):s="opera"}return{os:i,browser:s}}function Zi(...e){return e.includes(Xi().os)}function Yi(...e){return e.includes(Xi().browser)}function Qi(e,t){return t+new URL(e).search}class Ji{constructor(){this.storageKey="ton-connect-ui_wallet-info",this.localStorage=$i()}setWalletInfo(e){this.localStorage.setItem(this.storageKey,JSON.stringify(e))}getWalletInfo(){const e=this.localStorage.getItem(this.storageKey);return e?JSON.parse(e):null}removeWalletInfo(){this.localStorage.removeItem(this.storageKey)}}class ea{constructor(){this.storageKey="ton-connect-ui_preferred-wallet",this.localStorage=$i()}setPreferredWalletAppName(e){this.localStorage.setItem(this.storageKey,e)}getPreferredWalletAppName(){return this.localStorage.getItem(this.storageKey)||void 0}}class ta{constructor(){this.storageKey="ton-connect-ui_last-selected-wallet-info",this.localStorage=$i()}setLastSelectedWalletInfo(e){this.localStorage.setItem(this.storageKey,JSON.stringify(e))}getLastSelectedWalletInfo(){const e=this.localStorage.getItem(this.storageKey);return e?JSON.parse(e):null}removeLastSelectedWalletInfo(){this.localStorage.removeItem(this.storageKey)}}const na="sendTransaction",ra="signData",oa="signMessage",ia={[na]:"confirm-transaction",[ra]:"confirm-sign-data",[oa]:"confirm-sign-message"},aa={[na]:"transaction-sent",[ra]:"data-signed",[oa]:"message-signed"},sa={[na]:"transaction-canceled",[ra]:"sign-data-canceled",[oa]:"sign-message-canceled"},la=new Set(Object.values(ia)),ca=new Set(Object.values(aa)),da=new Set(Object.values(sa));function ua(e){return la.has(e.name)}const[ha,pa]=Tr({status:"closed",closeReason:null}),fa=Mr(()=>"opened"===ha().status),[ga,ma]=Tr({status:"closed",closeReason:null}),va=Mr(()=>"opened"===ga().status),wa=Mr(()=>{const e=ga();return"opened"===e.status?e.walletInfo:null});let ya="undefined"!=typeof window?new ta:void 0;const[ba,Ca]=Tr((null==ya?void 0:ya.getLastSelectedWalletInfo())||null),xa=e=>{ya||(ya=new ta),e?ya.setLastSelectedWalletInfo(e):ya.removeLastSelectedWalletInfo(),Ca(e)},[Sa,ka]=Tr(null),[Ea,Ra]=Tr({walletsMenu:"explicit_wallet",wallets:[]}),[_a,Ta]=Tr({link:""}),Ia={common:{close:"Закрыть",openWallet:"Открыть кошелёк",copyLink:"Скопировать",linkCopied:"Ссылка скопирована",copied:"Скопировано",yourWallet:"Ваш кошелёк",retry:"Повторить",get:"Скачать",mobile:"Мобильный",browserExtension:"Расширение",desktop:"Десктоп",connectTelegram:"Подключить Telegram"},button:{connectWallet:"Подключить кошелёк",dropdown:{copy:"Скопировать адрес",copied:"Адрес скопирован!",disconnect:"Отключить кошелёк"}},notifications:{confirmTransaction:{header:"Откройте {{ name }}, чтобы подтвердить транзакцию."},confirmSignData:{header:"Откройте {{ name }}, чтобы подтвердить подпись данных."},confirmSignMessage:{header:"Откройте {{ name }}, чтобы подтвердить подпись сообщения."},transactionSent:{header:"Транзакция отправлена",text:"Ваша транзакция будет обработана через несколько секунд."},transactionCanceled:{header:"Транзакция отменена",text:"Состояние вашего счёта не изменится."},dataSigned:{header:"Данные подписаны"},signDataCanceled:{header:"Подпись данных отменена"},messageSigned:{header:"Сообщение подписано"},signMessageCanceled:{header:"Подпись сообщения отменена"}},walletItem:{recent:"Недавний",installed:"Установлен",new:"Новый"},walletModal:{loading:"Кошельки загружаются",wallets:"Кошельки",mobileUniversalModal:{connectYourWallet:"Подключите TON-кошелёк",useTelegramWallet:"Используйте свой Telegram-кошелёк",chooseOtherApplication:"Или выберите другое приложение:",chooseApplication:"Выберите приложение:",openLink:"Открыть",scan:"Отсканируйте камерой вашего телефона"},desktopUniversalModal:{connectYourWallet:"Подключите TON-кошелёк",scan:"Отсканируйте QR-код камерой вашего телефона",availableWallets:"Доступные кошельки"},mobileConnectionModal:{showQR:"Показать QR-код",scanQR:"Отсканируйте QR-код ниже камерой в приложении {{ name }}, или камерой телефона",missingFeatures:"Обновите {{ name }}, ваша версия не поддерживает необходимые функции для этого dApp",wrongNetwork:"Подключённый кошелёк находится в другой сети. Пожалуйста, переключите сеть в {{ name }} и попробуйте снова",notSupportedWallet:"{{ name }} не поддерживает запрошенное действие. Пожалуйста, подключите другой кошелёк, который поддерживает это",continueIn:"Продолжите в {{ name }}…",updateWallet:"Обновить {{ name }}",chooseAnotherWallet:"Выбрать другой кошелёк",connectionDeclined:"Подключение отклонено"},desktopConnectionModal:{scanQR:"Отсканируйте QR-код ниже камерой в приложении {{ name }}, или камерой телефона",continueInExtension:"Откройте браузерное расширение {{ name }}",dontHaveExtension:"Похоже, у вас не установлено браузерное расширение {{ name }}",missingFeatures:"Обновите {{ name }}, ваша версия не поддерживает необходимые функции для этого dApp",wrongNetwork:"Подключённый кошелёк находится в другой сети. Пожалуйста, переключите сеть в {{ name }} и попробуйте снова",notSupportedWallet:"{{ name }} не поддерживает запрошенное действие. Пожалуйста, подключите другой кошелёк, который поддерживает это",getWallet:"Скачать {{ name }}",updateWallet:"Обновить {{ name }}",chooseAnotherWallet:"Выбрать другой кошелёк",continueOnDesktop:"Откройте {{ name }} на компьютере…",connectionDeclined:"Подключение отклонено"},infoModal:{whatIsAWallet:"Что такое кошелёк?",secureDigitalAssets:"Надежное хранилище цифровых активов",walletProtects:"Кошелёк защищает ваши цифровые активы, включая TON, токены и предметы коллекционирования, и управляет ими.",controlIdentity:"Контроль своей личности Web3",manageIdentity:"Управляйте своей цифровой идентификацией и с легкостью получайте доступ к децентрализованным приложениям. Сохраняйте контроль над своими данными и безопасно участвуйте в экосистеме блокчейна.",effortlessCryptoTransactions:"Простые криптотранзакции",easilySend:"Легко отправляйте, получайте и отслеживайте свои криптовалюты. Оптимизируйте свои операции с помощью децентрализованных приложений.",getAWallet:"Скачать кошелёк"},restoreModal:{title:"Восстановление",step1:{title:"Найдите вашу текущую фразу восстановления",text:"Откройте настройки кошелька и найдите фразу восстановления"},step2:{title:"Скопируйте вашу фразу восстановления",text:"Запишите её или сохраните в безопасном месте"},step3:{title:"Восстановите в поддерживаемом кошельке",text:"Введите фразу восстановления для доступа к вашему кошельку"}},allWallets:{walletsBelowNotSupported:"Кошельки ниже не поддерживают все функции подключённого сервиса. Вы можете использовать свою фразу восстановления в одном из поддерживаемых выше кошельков.",walletNotSupportService:"{{ name }} не поддерживает подключённый сервис"},featureNotSupported:{wallet:{title:"{{ name }} не поддерживает запрошенное действие",description:"Установите поддерживаемый кошелёк из списка ниже, восстановите его с помощью фразы восстановления, затем подключитесь и попробуйте снова.",info:"Узнать, как восстановить кошелёк"},version:{description:"Текущая версия {{ name }} или тип контракта кошелька не поддерживает необходимые функции. Обновите кошелёк, чтобы продолжить.",updateButton:"Обновить {{ name }}",aboutW5:"Про W5"},disconnect:{title:"Подтвердите отключение",description:"Вы будете отключены от текущего кошелька и перенаправлены на подключение {{ name }}.",button:"Отключиться"}}},actionModal:{confirmTransaction:{header:"Подтвердите действие в {{ name }}",text:"Это займет пару секунд."},signData:{header:"Подпишите данные в {{ name }}",text:"Это займет пару секунд."},transactionSent:"$notifications.transactionSent",transactionCanceled:"$notifications.transactionCanceled",signMessage:{header:"Подпишите сообщение в {{ name }}",text:"Это займет пару секунд."},dataSigned:"$notifications.dataSigned",signDataCanceled:"$notifications.signDataCanceled",messageSigned:"$notifications.messageSigned",signMessageCanceled:"$notifications.signMessageCanceled"}},Aa={en:Oa({common:{close:"Close",openWallet:"Open wallet",copyLink:"Copy Link",linkCopied:"Link Copied",copied:"Copied",yourWallet:"Your Wallet",retry:"Retry",get:"GET",mobile:"Mobile",browserExtension:"Browser Extension",desktop:"Desktop",connectTelegram:"Connect Telegram"},button:{connectWallet:"Connect Wallet",dropdown:{copy:"Copy address",copied:"Address copied!",disconnect:"Disconnect"}},notifications:{confirmTransaction:{header:"Open {{ name }} to confirm the transaction."},confirmSignData:{header:"Open {{ name }} to confirm the data signing."},confirmSignMessage:{header:"Open {{ name }} to confirm the message signing."},transactionSent:{header:"Transaction sent",text:"Your transaction will be processed in a few seconds."},transactionCanceled:{header:"Transaction canceled",text:"There will be no changes to your account."},dataSigned:{header:"Data signed"},signDataCanceled:{header:"Sign data canceled"},messageSigned:{header:"Message signed"},signMessageCanceled:{header:"Sign message canceled"}},walletItem:{recent:"Recent",installed:"Installed",new:"New"},walletModal:{loading:"Loading wallets",wallets:"Wallets",mobileUniversalModal:{connectYourWallet:"Connect your TON wallet",useTelegramWallet:"Use your Telegram wallet",chooseOtherApplication:"Or choose another app:",chooseApplication:"Choose an app:",openLink:"Open Link",scan:"Scan with your mobile wallet"},desktopUniversalModal:{connectYourWallet:"Connect your TON wallet",scan:"Scan with your mobile wallet",availableWallets:"Available wallets"},mobileConnectionModal:{showQR:"Show QR Code",scanQR:"Scan the QR code below with your phone’s or {{ name }}’s camera",missingFeatures:"Please update {{ name }}, your version does not support required features for this dApp",wrongNetwork:"Connected wallet is on a different network. Please switch network in {{ name }} and try again",notSupportedWallet:"{{ name }} doesn’t support the requested action. Please connect another wallet that supports it",continueIn:"Continue in {{ name }}…",updateWallet:"Update {{ name }}",chooseAnotherWallet:"Choose Another Wallet",connectionDeclined:"Connection declined"},desktopConnectionModal:{scanQR:"Scan the QR code below with your phone’s or {{ name }}’s camera",continueInExtension:"Continue in {{ name }} browser extension…",dontHaveExtension:"Seems you don't have installed {{ name }} browser extension",missingFeatures:"Please update {{ name }}, your version does not support required features for this dApp",wrongNetwork:"Connected wallet is on a different network. Please switch network in {{ name }} and try again",notSupportedWallet:"{{ name }} doesn’t support the requested action. Please connect another wallet that supports it",getWallet:"Get {{ name }}",updateWallet:"Update {{ name }}",chooseAnotherWallet:"Choose Another Wallet",continueOnDesktop:"Continue in {{ name }} on desktop…",connectionDeclined:"Connection declined"},infoModal:{whatIsAWallet:"What is a wallet",secureDigitalAssets:"Secure digital assets storage",walletProtects:"A wallet protects and manages your digital assets including TON, tokens and collectables.",controlIdentity:"Control your Web3 identity",manageIdentity:"Manage your digital identity and access decentralized applications with ease. Maintain control over your data and engage securely in the blockchain ecosystem.",effortlessCryptoTransactions:"Effortless crypto transactions",easilySend:"Easily send, receive, monitor your cryptocurrencies. Streamline your operations with decentralized applications.",getAWallet:"Get a Wallet"},restoreModal:{title:"Restore",step1:{title:"Find your current recovery phrase",text:"Open your wallet settings and locate the recovery phrase"},step2:{title:"Copy your recovery phrase",text:"Write it down or copy it to a safe place"},step3:{title:"Restore in a supported wallet",text:"Enter the recovery phrase to access your wallet"}},allWallets:{walletsBelowNotSupported:"The wallets below don’t support all features of the connected service. You can use your recovery phrase in one of the supported wallets above.",walletNotSupportService:"{{ name }} doesn’t support connected service"},featureNotSupported:{wallet:{title:"{{ name }} doesn’t support the requested action",description:"Install a supported wallet from the list below, restore it with your recovery phrase, then connect it and try again.",info:"Learn how to restore your wallet"},version:{description:"Your current version of {{ name }} or wallet contract type doesn't support the required features. Please update it to continue.",updateButton:"Update {{ name }}",aboutW5:"About W5"},disconnect:{title:"Confirm Disconnect",description:"You will be disconnected from your current wallet and redirected to connect {{ name }}.",button:"Disconnect"}}},actionModal:{confirmTransaction:{header:"Confirm the transaction in {{ name }}",text:"It will only take a moment."},signData:{header:"Sign the data in {{ name }}",text:"It will only take a moment."},transactionSent:"$notifications.transactionSent",transactionCanceled:"$notifications.transactionCanceled",signMessage:{header:"Sign the message in {{ name }}",text:"It will only take a moment."},dataSigned:"$notifications.dataSigned",signDataCanceled:"$notifications.signDataCanceled",messageSigned:"$notifications.messageSigned",signMessageCanceled:"$notifications.signMessageCanceled"}}),ru:Oa(Ia)};function Oa(e){const t=n=>{Object.entries(n).forEach(([r,o])=>{if("object"==typeof o&&o)return t(o);if("string"==typeof o){if("$"===o[0]){const t=o.slice(1).split(".");let i=e;t.forEach(e=>{if(!(e in i))throw new Error(`Cannot parse translations: there is no property ${e} in translation`);i=i[e]}),n[r]=i}"\\$"===o.slice(0,2)&&(n[r]=o.slice(1))}})};return t(e),e}const Ma=Vr(),Na=Symbol("store-raw"),Pa=Symbol("store-node"),La=Symbol("store-has"),Wa=Symbol("store-self");function Da(e){let t=e[hr];if(!t&&(Object.defineProperty(e,hr,{value:t=new Proxy(e,Fa)}),!Array.isArray(e))){const n=Object.keys(e),r=Object.getOwnPropertyDescriptors(e);for(let o=0,i=n.length;ot===Na||t===hr||t===fr||t===Pa||t===La||"__proto__"===t||(Ur()&&Ba(qa(e,La),t)(),t in e),set:()=>!0,deleteProperty:()=>!0,ownKeys:function(e){return za(e),Reflect.ownKeys(e)},getOwnPropertyDescriptor:function(e,t){const n=Reflect.getOwnPropertyDescriptor(e,t);return n&&!n.get&&n.configurable&&t!==hr&&t!==Pa?(delete n.value,delete n.writable,n.get=()=>e[hr][t],n):n}};function Ka(e,t,n,r=!1){if(!r&&e[t]===n)return;const o=e[t],i=e.length;void 0===n?(delete e[t],e[La]&&e[La][t]&&void 0!==o&&e[La][t].$()):(e[t]=n,e[La]&&e[La][t]&&void 0===o&&e[La][t].$());let a,s=qa(e,Pa);if((a=Ba(s,t,o))&&a.$(()=>n),Array.isArray(e)&&e.length!==i){for(let t=e.length;t1){r=t.shift();const i=typeof r,a=Array.isArray(e);if(Array.isArray(r)){for(let o=0;o1)return void Va(e[r],t,[r].concat(n));o=e[r],n=[r].concat(n)}let i=t[0];"function"==typeof i&&(i=i(o,n),i===o)||void 0===r&&null==i||(i=Ua(i),void 0===r||ja(o)&&ja(i)&&!Array.isArray(i)?Ha(o,i):Ka(e,r,i))}function $a(...[e,t]){const n=Ua(e||{}),r=Array.isArray(n);return[Da(n),function(...e){Pr(()=>{r&&1===e.length?function(e,t){if("function"==typeof t&&(t=t(e)),t=Ua(t),Array.isArray(t)){if(e===t)return;let n=0,r=t.length;for(;nt,isMergeableObject:Ja})}const[ts,ns]=$a({theme:Zo.LIGHT,colors:Ga,borderRadius:"m"}),rs={[Zo.LIGHT]:Ga,[Zo.DARK]:{constant:{black:"#000000",white:"#FFFFFF"},connectButton:{background:"#0098EA",foreground:"#FFFFFF"},accent:"#E5E5EA",telegramButton:"#0E9AF5",icon:{primary:"#E5E5EA",secondary:"#909099",tertiary:"#434347",success:"#29CC6A",error:"#F5A73B"},background:{primary:"#121214",secondary:"#18181A",segment:"#262629",tint:"#222224",qr:"#FFFFFF"},text:{primary:"#E5E5EA",secondary:"#7D7D85"}}},os={[Zo.LIGHT]:void 0,[Zo.DARK]:void 0};function is(e,t){t&&(os[Zo.DARK]=es(t[Zo.DARK],os[Zo.DARK]),os[Zo.LIGHT]=es(t[Zo.LIGHT],os[Zo.LIGHT])),ns({theme:e,colors:es(os[e],rs[e])})}const as=di.div` + background-color: ${e=>e.theme.colors.background.secondary}; +`,ss=e=>{let t;const[n,r]=Tr(null);return Or(()=>{const t=new window.Image;return t.src=e.src,t.alt=e.alt||"",t.setAttribute("draggable","false"),e.class&&t.classList.add(e.class),t.complete?r(t):(t.addEventListener("load",()=>r(t)),()=>t.removeEventListener("load",()=>r(t)))}),[po(xo,{get when(){return n()},get children(){return n()}}),po(xo,{get when(){return!n()},get children(){return po(as,{get class(){return e.class},ref(e){"function"==typeof t?t(e):t=e}})}})]},ls=440,cs=1020;function ds(e){const t=Vi();if(!t)return"desktop"===e;if(Yn("weba"))return!0;const n=t.innerWidth;switch(e){case"desktop":return n>cs;case"tablet":return n>ls;default:return n<=ls||Zi("ios","android","ipad")}}function us(e){switch(e){case"mobile":return`@media (max-width: ${ls}px)`;case"tablet":return`@media (max-width: ${cs}px) (min-width: ${ls}px)`;default:return`@media (min-width: ${cs}px)`}}const hs="@media (hover: none)",ps="@media not all and (hover: none)",fs={m:"100vh",s:"8px",none:"0"},gs={s:.02,m:.04},ms=di.button` + display: ${e=>e.leftIcon||e.rightIcon?"flex":"inline-block"}; + gap: ${e=>e.leftIcon||e.rightIcon?"6px":"unset"}; + align-items: ${e=>e.leftIcon||e.rightIcon?"center":"unset"}; + justify-content: ${e=>e.leftIcon||e.rightIcon?"space-between":"unset"}; + background-color: ${e=>"flat"===e.appearance?"transparent":"secondary"===e.appearance?e.theme.colors.background.tint:mi(e.theme.colors.accent,.12)}; + color: ${e=>"secondary"===e.appearance?e.theme.colors.text.primary:e.theme.colors.accent}; + + padding: ${e=>"flat"===e.appearance?"0":"9px 16px"}; + padding-left: ${e=>e.leftIcon&&"flat"!==e.appearance?"12px":"16px"}; + padding-right: ${e=>e.rightIcon&&"flat"!==e.appearance?"12px":"16px"}; + border: none; + border-radius: ${e=>fs[e.theme.borderRadius]}; + cursor: ${e=>e.disabled?"not-allowed":"pointer"}; + + font-size: 14px; + font-weight: 510; + line-height: 18px; + + transition: transform 0.125s ease-in-out; + + ${ps} { + &:hover { + transform: ${e=>e.disabled?"unset":`scale(${1+gs[e.scale]})`}; + } + } + + &:active { + transform: ${e=>e.disabled?"unset":`scale(${1-gs[e.scale]})`}; + } + + ${hs} { + &:active { + transform: ${e=>e.disabled?"unset":`scale(${1-2*gs[e.scale]})`}; + } + } +`;function vs(e){const t=Lr(()=>Object.keys(e).filter(e=>e.startsWith("data-"))),[n]=yo(e,t);return n}const ws=e=>{const t=vs(e);return po(ms,wo({type:"button",get appearance(){return e.appearance||"primary"},get class(){return e.class},onClick:t=>{var n;return null==(n=e.onClick)?void 0:n.call(e,t)},onMouseEnter:t=>{var n;return null==(n=e.onMouseEnter)?void 0:n.call(e,t)},onMouseLeave:t=>{var n;return null==(n=e.onMouseLeave)?void 0:n.call(e,t)},ref(t){var n=e.ref;"function"==typeof n?n(t):e.ref=t},get disabled(){return e.disabled},get scale(){return e.scale||"m"},get leftIcon(){return!!e.leftIcon},get rightIcon(){return!!e.rightIcon},"data-tc-button":"true"},t,{get children(){return[Mo(()=>e.leftIcon),Mo(()=>e.children),Mo(()=>e.rightIcon)]}}))};var ys,bs={exports:{}};var Cs=(ys||(ys=1,function(e){!function(){var t={}.hasOwnProperty;function n(){for(var e="",t=0;tSs[e.theme.borderRadius]}; + padding: 0 16px; + border: none; + cursor: pointer; + + transition: transform 0.125s ease-in-out; + + ${ps} { + &:hover { + transform: scale(1.02); + } + } + + &:active { + transform: scale(0.98); + } + + ${hs} { + &:active { + transform: scale(0.96); + } + } +`,Es=di.span` + display: inline-flex; + align-items: center; + justify-content: center; + gap: 8px; + + font-weight: 500; + font-size: 16px; + line-height: 20px; +`,Rs=oi` + position: relative; + overflow: hidden; + + &::before { + content: ''; + + position: absolute; + top: 0; + left: 0; + + width: 100%; + height: 100%; + + pointer-events: none; + + opacity: var(--tc-shine-opacity, 1); + background: linear-gradient( + to right, + transparent 0%, + rgba(232, 232, 232, 0.3) 50%, + transparent 100% + ); + + animation: ${ii` + 0% { + transform: translateX(-100%); + } + 37.5%, + 100% { + transform: translateX(100%); + } +`} 2s ease-out infinite; + } + + @media (prefers-reduced-motion: reduce) { + &::before { + display: none; + } + } +`,_s=e=>po(ks,{type:"button",get class(){return xs(e.class,e.shiny&&Rs)},get style(){var t;return{"--tc-shine-opacity":null==(t=e.shineOpacity)?void 0:t.toString()}},onClick:()=>e.onClick(),"data-tc-button":"true",get children(){return po(Es,{get children(){return[Mo(()=>e.icon),Mo(()=>e.children)]}})}}),Ts=di(_s)` + background-color: ${e=>e.theme.colors.telegramButton}; + color: ${e=>e.theme.colors.constant.white}; +`,Is="data:image/webp;base64,UklGRrwhAABXRUJQVlA4WAoAAAAQAAAA/wEA/wEAQUxQSDMEAAABJyAQSOFmFxERg8TItt22+YBQAAMKYCoApFFAev13pQS8e67zj+i/JLeNBEly9IDwZG/2NbN3ax9Q7E/1P9X/VP9T/U/1P9X/VP9Txc7h+OnctpnT8fNB/rPX14/bKxLNjzNsXpFyzg1mLksknZHydYvEw7jNEqnn3pj/iXi4/4m4w+UZAnNm+6CQmBb0x++HLqHyonuT7/dcQmgaqN8p5cGmyIZQSsGkGEiKQaR55gjzhODAZFBMi/Nu7/UQkkPTJStMl6woXXQalC5aUbr5GrJD0s3XOcJ8XcN8vUSYr7NyOozufeEQYb5OEebrop0HQzdfB/W8IXTxCtDlh6CbX5gjzNdVP6F/5zJfZ4J08h1gQX1XhCq+q/m6MOQh3SFGu0MsSO9qvq4UCeVDp/k6c6QX7hgLuruarxNJOtlDJ0gV7SjTiB46URZEu/kaMKPZzdc5wnxdaTIq3rnM14knnWD3vnAIoNHbFWhBblfzdSVKqO2KVOV2tb7pwpSH1K5Qo7Ur1ILUrubrSpVRacV8nbjSCe2KtSDTwUZnV7AFmV3N1xUtKivm68CWTmRXtCrR4Uajwy1I7Gq+rnhRWDFfB750AruarwE4+bv5hZkwffpdARey72q+Dozpku9qvgbk5F4xvzBQ5i31qQPyjalj/o2r/QTm/LnKQpnRfvrE5w77uXCeu92/sfmJ/d5hcN/LAbNnrpA9dYXs5mvzk/v3rhe+tKVkx/6/uzlwavry1ZciAN4uCsApwYqo6cPn28/Ac3cqgKkDlD8B/++A0ixYzxwJLWOtKy0jrYuBpBpAysGj3sA9ce33+tkr5kBz4ZQERklg1ARKy7evVjVlAblxyQKiLhgKg6EyEEoDoTYIioOgOgDKA6A+8gIgLwHiIiAuA9JCIC0FwmIgLAeygiArCaKiICoLksIgKQ2C4iAoD3ICIScRYiIhJhNSQiElFUJiISQXMoIhIxkioiEiGxLCISEdAuIhIB/pBSS9hKBo53mEhjFlTv18ASSppSSxmOSVc55AOngqeSyoGZI+WcxKSmFJqXceBTeXfBcu3lnSCUw6iUkmMslkJpXQpJKaRGKTWK9fwPQFPIc0X7eQk0R0csg+z4S6vX+PBT9Dgq9b+NldA+yudx7FQi6JTtzc169dNcGuumBHbbCjPthNI+ymE3bSCkn0+gVMX8zksMvXLW7YWb/Xr7EYyrD5fdsRu2j7E1pPKcumRy5TbKorNtQWG+qLzTTGDjo+fffFWg4bXbi8sbGOT99jsZdhgwuXPzbS9ie0DlOWbx65LPJNPfItTfItXfINbbKJjk/ffTGaw5cvXE75to5P32Mxm+FLFy63fFnbn9D6TVk+PXIZ5lMd84mWcW8p8xe1fPpuXKc835+4fc/6we+s/6ot1l+ve1vsT/U/1f9U/1P9T/U/1f/8FZwCAFZQOCBiHQAA8MYAnQEqAAIAAj5RKJFGo6akIyEUKTDQCgllbvGAPiNiu/AKAjwB+GekV/hnBwf7l+AF6xND9663MFXp/yT/LD5rrT/lv77+q/7X70O9/tHzy/Lf4D/a/3/94f8x24fME/g38+/039p7BXmI/qn+b9Yb0s/1j1AP5L/iv/f/0e1B9Aj92vVs/5n/l/5HwU/tn+0P/V+Qf+Y/1f/wfn/8gHoAf8/1AP3/9rfkz+EvVCd1W7OtsTJnlZrLp4jvT6gvlo+sP9mf//7gH6vB6aVcdY1XHWNVx1jVcdY1XHWNVx1jVcdY1XHWNVx1jVcdY1XHWNVx1jVcdY1XHWNVx1jVcdY1XHWNVx1jVcdY1XHWNVx1jVcdY1XHWNVx1jVcdY1XHWNVx1jVcdY1XHWNVx1jVcdY1XHWNVx1jVcdY1XHWNVx1jVcdY1VitiATdoKY6BNU9knx8jRt6QZ4p2sPz0FE3yy+XQsGNGL4boiYzyrW+Ez2sV713lF/Id59iHeaIvZOkTFEU2ZzLa/kuOcajrnH6+ayLS/AQvfgeX36bElxp3eC+MvqIjl1qsz063zacJ14OE7LOu/QrWXwKA7bxElNKuOnBbv5zEw2smzphkPnzGkRgZbnf0IMf0kgBKX8ofFDmjnCMQFYoGjKDwd8kIU6mHQUQhkpAwqFM3bqD76hh8coiWrKLJTSrjrGoUYzjiwll/aZNiMugJCY9r8ZLxduFuMRNpcn3UHqZqKAx2KEkp2d/JyG4nJigKewmlMt3tVYCp0bn3RcWQ9R9qoqEqaHrQEQ7z7EOjzrbgxI4XhJTq833fh4pzCC89xBqADP9g4wmhdbtSa8ZBB9fsh7hv0saWK4Ttn7H0aBxpU3fs58RCWdYO23HRwzsWzBQR5EgodGBK+yzkLkXd0W4Q48WT+LQK6T2FX1gI51YX88i7Hu//eU+tT5HEs2h8Qs/YSR54QtzlnjmStfWlDwhEbRXvhY1czoXzyAiHefYZS8FXiaht2rpcueiLjH8EEc7ulqk5gm7qIS4d6K7Pvq+5PawVmHAOaGEfGQ+fZC7OJkz368rZ+VEvVBf4MRlKjbOLZ7tLeiv04aBBU52t4e7GM/j4CNxf0XjWh3Vn8Ei997c5FvxJYQbFxozUSTqCJoJQmSEYFfkVxRnjfaolDOUr27kBfq/9M7ANqqsVdFaj8njQOKn2rjrGLpKvxTupJF8qQyWoVsdqy9RFHg2sJHO8YXWIUPU5O/pQyEU8jwBQ8rmfPfckAgPb2oFp3fOkFKAyvUO0DhENJll9T+p2mq/AAG/Id59bQsLWGbNdoGWOaX5+8joWcP2RICZAlXxpC/RsdNEjgm8OtcvdHPE3heV2w1D413u2q+dth8Gy+GXap6t46SPAYkWy0vvuFzQLat2NVx1jGwYWPEzmlLBGe+X9tMYF+MGRz5lNEYnVZ9i5Zf1rk7JiOn8YhWMFtyA0257h3CPLzO+JQGvewA6W5WzqCj1TCqqMIDSPSfXAB8zmiROt2NVx1jUVEYPo94bD2f8vFYzLxeSnSu9q9wD59d3i4G3zgkU2OP87V/GRDBsbdcGqru6eW9f+iD0P2OHUjg2KpQE+cs4Cj+fmpBt5xElNKuOsaq4O5PeqjH9i5k4c692pV8Ku9SBM1kOgW5dW/uZYX5By7KKbYKFB+0kADLkQ/wmQ6p4N6EeP4C1ChUDsj/XsQ7z7EO8+xCfZMwF7HF2XarLe3JULaEJElgWmSa8rUpl//5ra4Omj+/iEkCl5fIitx5pc2zjB9Q1WWQPLUfS+c06MXpQoI8iSmlXHWNRNn8Xi2IJCPffe0E+OPAqcRhvwqsa3QkuNdLKWl87neVdXrZwyGANXLXTRf9gWuzuRJTSrjrGq46xqKh4x2fud0tm4xvc3g9mMTxL09Cdkh4YfYM7/mPNexDvPsQ7z7EO8+w0sePJhMiiGhYE2olPH3RIe8fUKzWGVjnD3Y1XHWNVx1jVcdYI+iKui+iGnVmaZ7Qsy+xquOsarjrGq46xquNyAIh3n2Id59iHefYh3n2Id59iHefYh3n2Id59iHefYh3n2Id59iHefYh3n2Id59iHefYh3n2Id59iHefYh3n2Id59iHefYh3n2Id59iHefYh3nvgAD+/eUwAAAAAAAAAAAAAAAKr8MkvYAYuDvieBd/T8pZ9Ial4+3AYQ4qG4EMlmDAA9qy6r+3ujvX/v3Rum4DtvkJ9jQb053XBs4+k1KOHUmbPdGPv9retVLMnvRjGPgAMGYbC7mBeij0JItR84fyjOikf3zMMUNibZxt2SPpxVTEB5sn5TIzkx2RUz0qIXJXVXt0PEZ/n8QCbf632ByItsZczG1mHuiTaIvqetTY0HsGDQOnCzcsbObB+VIf5IPqE/Nd/3XsLou3PsvMytDXsUSgubfu/QW8SGfreCdyMlKkOT19M8rTAxYDHbEsH63mJVbIjf4/nLrepRbt/HqFwFaPQTyT81gKjPQC3cjGWt8iJ8bzNW8QHbjnNveYRZbdNQLbG9BUJiy3VYaKZ6rMRDg2HxBr+4cP4GqlpSfz1Y/TsVL1e6v368S/AKAs6y0Hy/jTXRtq29xYz0FFZtpBwVwDXwXYjj++1Ga7X2yN/JRTcFijbompxW7hYuijIa3EpNWuL0tIl2QTbKMmKxYD5CTVDuCV0MKo5TejeT7yJg8+zQmS78Ufn8oybUA3wqxT0lPGxRJLtahhfM5te9mxHUTSzC3xZWKtSTm9vzcFUUGQUFsiOOd1WSJqNYePvjlACi5apw9/kFoVV7P3gav0kORLpC87BTID7TucaJEuWC6daVZPDXzryLoX7ruqHQ9IwmDe+vP6S+k105UD+JlP/VBdsL+gCBd/Pt+VwF0AJyMde3UWucwGwSjC64S8dTN1rXl3urgHPB3f2iwhlpP1iUlTgHyLFhsx5nU2saAMvgkWALfnqz+v1USrKO5quguO7wK8LTKBXM+mjzy/ZAuaV1afi2WX2PUFxAOj60oUEZLA4vEOjb5qRJ1/hPXqWJklxi97oLrdpcH1v4uwD5AB+Gdv1hIP8D3lh8lzwbiTnpzd9ntIed3KyT9Qr8DvoQBziFVpy9T+hMNCJ3Z+Uj0UACPKTzGH7L3pkVHfWFVBu++WBUv7feeMcJ0ecOjMu7D8BFmH9HHw1apBdvFq4I/esmtDSDAbIkiztOHKKCsQ8xob8E79Vz1WCDshpzL3FKCLNzIcjYzkSx+GruV5kCDMCrw2a4w854hCHBZ+jThQPZUqm2EOuZc91GmO5VHicfLFUjLi28nA0z/qFqVLI9Q3VBnSQvUuuFFIFrR/NHRjxA52FZ+mroe/uipk4yOqdNp1y6mv5pEHu9m7HlV4Bmuqrd8wHSlVy/Tw2OjxF3+34qF3ittnNvBfFKpM8tqHX2o8BWnXOjpYYn7BRZg5nBxvlJe+NkWvqOC3ZelgLLJrJMFMRflSQvl7qSj1sneMszAcrBjGNodB5ZYqDVJquXC9YiBfiVQmhO477GGN3NHAehXZ0XFANi/o1XLs4JGLuO8Rj7PTzJXjlE5pen9fZXquJqdW82J0mOpEzpfa4XnOnNMXtjdAnFvJkyRf8LSgiwRYFJyt9ZLoDGspVoHUF0j/toz3PdQpwzm+KBosQm9w1Q37HdLNddy4zZhWvMPjgWWcKMezMCX8WcQsk7qaurErXg6dVImwcewjej+DOTSqLICTrnkOmvgIHt2Wk2YPInxtapBDNXg+B+LTXs35XtauRtnnUoM+IvII/VrMXHGvHqm1b+KHLzBhfqS085wYTNv/WNuN0MFEyN3Pn0yv+XRqayEqe5cB2ok6/agYOYoyCi31cPj8X07LQRcXzlWdR0gGNwcY/NT6OesClWOALzgMqjemmodysQnYmE/upoxo1+92gJpEcHMbKIKuQgW7uo54vZlFn+U48CTjttTjO76dV0SUurxW23GzHMxwxAozSBziHwfHiD+BW0E9yaNvcQHeOdR2UfX3Nyv4hOwiBXqLGEfL8ld+LLsxE4udRoJWozjMbnKlJouCpYkGZZO8kB88hSXmRbt4oDJ5dFzfXXviGe0PZ2Ru3R4Py6yIjv4p01ibpiwvJlYvjhv1awHSb7qgPlMNOVbARTmtCuLmkR5J/QY2uockX6D8FQ8VH/rn61Avbzo5tzI8UrfooU7cT2ZEuOEn88xg9a36y0JssF/EhgxyPjwnFfpwT7vx5NqgxeU9ZjcqemQAO1Xxf2mhGuZzLo4emQcN1B7HFxP/2krLUNlwn1A0WV6X8lXYL9w9xWMjUWRnBtVptwIFURaiIiPoljGgIzGwVlORo/htWRdqL5EUsBJg/OEgojjcQOT9iXWZNPspdSEyuLnZkIapMJaRC+plVJuKLcxld8CO1u79wpLZTHUuSloygwaAs5KhxkQFocSAfWZrC3GpE9GguNx4xCp8d3MpmbuZMiI0B5Ce4PHqFYpOL2CgugS986z45MiEKaorQgWA87ru4WIunZ9WmIlzdbie79OX4pMq+cMt0J0gsSLeomWsj/eE/9aCt1+3cILLaBAuL43qGXdlr4LLLYlrOUCxLwjU45G58c4A60CQG0gtgBWCXk2prWkzxlmadJEygvXpr5U/uOcVkXNUmpLkO2XcACxWfTupL3nwXaeNLmyxKCLaO8YBKt54httnvQazbbvIDmi5ev/XKnsAPq0pyqa4YA9sQH4bclE5r2ia8hWxgCVHWvaF64LqQf/fkSpdxbHG+Qr3lH8v0HBldIeqd//BVL9YeNmolyimwGdfUG576KD80aFJb+LICfxBKdJq1neHSEj41KUE/tT43yFfKclpjhGZj4NNm8Rttyk8EmKpxzhpRRNF1Pigius1NvaOD5SlwIpHB0vrxYAqKoGCxn2OCrcF6cCGi4eEq4Sr5NSQSINdp6WUqKzzUUquEPR5enZUjQR9Qc+IJec5JzCILTBH6g5jql22ZxsioU6on+Pb7d9VfFDTzm2y+8twZ67UNHG+TrlnhOC2wT0n+Jq+cSlR4uSCsTeJxa6yzEQ7+Wt5ibU8cAGfNR6CxOEbzSQUQ+YuGEtRZ8XUtJxLDzw4+8HIev2eYHn2GGPOKdlVZNYBRUKO2vtquhrNJBOr4AL/PXD2vgvi9ocvridNS+yi+7kVTYoW+tnyE9L8TtrFR+FSPLey90NygpGv+r+RCDQtA64f7eV1LN8ih6XSqxywaRcTIidtAz5VhBxRca3tl/etZr/Pk4knbr1lXbyOFlIuWlnx1WiC53xo0vy22ZdPpduIBexcUIZLKVTetT8ZVw7v7fIsVXR3S9XqB+ZmBDjr/g1e2sh85pDKo+5PyFo9aAt/HOv5Tycc1V/HXPwv9GRi25jHlW5dxbyT/Lo46xz6m3b0JtENsuqU7H67umh26dv+aaDf5ByURMniOWPAdGDfbt+iDAwCLFcLUXcDoYn8SuNpriFGVqQrqcUcXOaZ0sJNCA00xcffWhIhNU9wXmO8d6rog1X6CQvqrXC1eWU0ti4p7rlPGnIguZ3pSAtn5o3LSV3oyd5ELsT2pOsE5F9rbrdtSlaqz+coUBWOiJfLKx+44pzgguPPwlqi8Ei3dDYL9JOccCNra6aYxfUQKIIAag6RmjUR0m5uZhVMoW7Badd/zm3/Tw1RZF2U6QSeSb6ZmsC1Jq1qKKJM5KR7qBnAB/BOhqf3UWxzGNl083dvTEWei3ttFN7Uiy8ywGj544+is0p+MSHRbR5JK1BrDOKDNnONHO/MLC2kM7UmGbPIW1IJ4oHgawNPbR/6be2inRAoPgKgQ2F6E6z4RahoK1iLqtXJuEI8/pVw6GXTG9TBZ8Yimry+3/IiWyOBe4mBIGUxI5F976KaV8KVvZKqnfLZN2x3GHgBrxWSW7o/u1pqJFcDUIysaA68XTZ44/yP7rXj9TZylWJfxTzai4bj4dUL74KZ/23EaXpZoaRaC6FEMA3pOkhLDr8/G5M7F3hXOJaO/YMDBal2zXZDbUD9zMKKmbck54nG4MkScQIGk0Ss0PO6WRijDbAqXMmt8M0xF5XfwRWsqz1A/OgGbgwCA90dsq0SBd/hJcfaqmut0Emwe+lOkrieShk3i9eQbNfvUuIF/uI9DIY+or14oMXYpImBvehusBuX3m1fKGfBbRghhDHsCsgaKS01TD3eWaaLhf4lMOeT8hjHzDfUUk+J+tmHs6HZHiOmDp7Pb+Vt5ocgl7icMvlJMjenxIuXvkfwNIsmR/9lAXSMA3VHj4oD3UkI82Wb9iSGqjC13e8qMwsfT/Zy5Tby04aH7njvb/8S3N8m4fR74kH/sIdXidblQxUdzRaPS7z8jba6OZB7eypryyqK/0sy4syCYpLA8YF150AIOOP60TmaPn8+UnrwmYhXxGb1rslJ1TwvSYGtHG5AVP39IFUIu3kzuiHJhSdXhkfh/03pfKGxaws4IgOzZjivc2zV3mUexFfmG5cuHCqUzfOs6m5dbqHgxicQ1GLSaVQMfduIL4JjIrzHe8Es1UMSIoMyAjYbN24RRgTdWcOSy96C77Ijsj4he8+I2X5J17I4Pm/aYoOA3Now7Wm4z6uovMj6izn8sek2EVrMDEchBMiaDmt3SU8+IIf7e1bNH9xOm7P0Oj+F3TIfFbUW9H2MD1WTlWsZ5NP1HPcyFmXbIJJUPdOxS8rg4P7zTGGNHFofKsOMNDtaXbERqVIRqNoEfhuys1VA8kSxTm1JnMB0nxBloCy2hSb9qfGSpMv5F0eYO0tJHA5/Ik0LuFrtsKebPzdBBdiKNS9/XRVuaor/SnLLVeXOw3Kn3l2m5/Rlq0UP+/Obcqy6qaGImQ7pwtjNA2HCfjkKz3lsAO08KrGPQZbot4cj3R8pmc9qlMyhkKZYFrkQnHz70fewYYVJxBVHOt9a8t9efHBmfjvuUjcqPkx6QdrcRpCPHx1Sfn8+jC++PR5pitO7tg8259vz2WARhfcUha/+AM0sxhVR0CMfaWJ7eWx9XP/ItSG4GRO8qqh115PLcpzmle2r20dRr9NzQwHMDyHhy8kjc9Ve45Sd+ue94FDwpFJEPlJmQl7IR48G8TNbS6mYSW0LGCA8QphAe0Kxbdfh9PgkLsU6dMyqxSNhnbyF7YbW//6Tr0nusXqCWk3PjguVUTHsHCkv7IPdhgxDoQKkzrHFmcuUsObtiQ9G+9SPv2J9MUDWTQj+DkxhuIL3NofAXDicBRCJ3+7rxmu1IFVYZIZDeThvNldUODZui4O+3zKeOIug9Dl78sG0qyijTNa5fRNB/Lawpoa+J+NY6GWPj/U7mfKjtZsJBhMeM8OOQ/4d9TPlr+dVDJALqbxYSqe0YIdaiYNWJ9KUP8QfJhcnbvZcUqx0KQD5s1eXQISWKDMp81XwVlVh6fFD2/VYgbYPhvY6uyb49nORi/Lo58YHJFO02IjusvvIS79U7G4tO6yXONbXIMu2U3OczZ3JkoDl433p56uXb0a8DGibMKEurAicB7oTtZY0ESJ46p60f61tyd5pGm0byA/IPspEfQAdcnhpJ405ncHv9fSmsO95U9rRWq9Z1YA7dtcuOAxQp6j9CPWkWmKM1bDyCcYEADKkvlUX0mdu6ml/XJh+9/AZiCUDACU1FTN+C75lrMQVZhnpc/JNfd4UwvL4WcemqJMatNtBKYwR2nSRS+bvE+FcAmfwKvbECnv46UWplOvM8n28pP9+jfYa/mcUbKsHXRCgz5NZWY9RX4wGpHWadyt55o2OR0x7GK9wH18/MVUNNXuDcvjyaMNxS0la9t+y2MmsciPowoMlBzaCNKEwolTcUz3oCfcLJQAB4WpPLQpSKgoeOng2R5kdI/8p8J3i702XP7WUclp9ikj2ZyOb3y1zdOZDlaj2tbXltKR5OSjlxNFMZWPf2QOmmCoeVZrf+L54r43/A/2NjCHtoS77AJYaQif9syXuANuOAABP1RTunfe+Icnlnl4iLoqhdMaftUytAGZoK9d6Y/wAakRtFCqGquYfi4EsQt0Oyy6LRynv8RVqoNXoZVaH3S6WTm+j7Lcmyhd64txGgq7xLQyGHGeowP/REQmInXPlj2XGKViNAPp8NKp3nOEh59SgICE4jXe2dLaiA5z7qGHU5M7ECKqxay2KWOKndzd+YxtUBOjpdv8wDCVULBgQDv/p5mKaBsYow5HbDOnG9eLE6cpOFtL7f5isFcmH0cFZ0o6eRAHuZsgi5wHxNAKW8S6NK/ZksOueExhDu3MQHgMBWHGLWgBYoSPW0yjAcOxnR2ozsJQ3gs9j8/M79U5JwqO0MsJ2bUItGhI9ZvMXPQbmx3ShAPt2W1Qj1RLK/q4Q7mulN8/zRxNeo0J4olOAtYUzTJkRbnhYl/7JCVpVlmk8a2SqywNNuWuvKrAgP7I3PCpVMsO8mIatdNFerDqa8Qk1/i1o1b6FJE/1NnggHDLafULpR8ZTykT5fe4ZTBcpx8qzW8uv8k+B+QBRpKEBhBHJ5j4nBGwQSNP8odcpf5snroipAAAET/hAiNtbvHVut3D9w9WBV5zA8awX1EXpeVwBsyCh1+P+CeOh5MmeAW9WelJ/uNWX4IXvdLRBCDk2Z+nYuAt8ILrE2B/KrRTdK9XTdYlmDCFttXDrNF+9We/t3cC6UW8202Cx//uaMu+VCXb5aZWfQET8ObzFi8b9y6BjZrLmT+qvyt7E/h6usS325WLFNrKriWqYE/xBjL70a/kb7zwi3fe7PGMqOBr3U6E7IncJnyISxXwFNKV+oKF7efhPMZW2OIN9zRSlDpHZpIXOTk7ZlEDQp7EDoMQtJmjIdBIxnIXDx4hZ15oSe1T55CBBTi/eioT9+VbZIu+4gIafqcsZ6fYWoWoLSiVzCx77vf7KYxDEx1NSvAYGJ0r+TTBqfaB9olXQQFl3KdwHE0HP5v7ZXa9lqBK4/HWW8bKWF55ZemU5/yw5RcDmRoLxqg/8horcha36srYPebxmvuS/FDIpT6AABD/JyD4nTHbtb13/ZFd5jAkIObHRdBgOh6oYJoIgndWObLmn+AIa2eqrvj5jPIWsc2XJXn4ZsGnHZX87Q9dBo5/8PzVJSepLyehmqASdDx8BT7iLIbkSsDLQTtJ+IQcLzKUCs3+rsecAATAZEQRbSFwu/dZWc0yR6WSUHkFK7wLv8SPjxchUTgIBJ8tIfnKeW5DTqTJDHxRk5MfjTyNa6+NSGnOoTM2X03ZHtkoKX99MfoJuVh4deIx/qcpFvYP2gKXdbqvJGLYGWD/YP7h17qTAw3YhaKFWowyeeYdcAjSxNN3hiekdBUFYUPi4GvSqnzfr33Xx+5iqkgHdo0x8zvZdtrAk4UOkxcMiaHSZA37f1Em3Fny60Me5yhekjhkOIubzU//wId76xyyZugAAKhOBTshfPjZfILTbwyuw+nF5cx9EKaY7vFcz2WVzUIVuxD1AMAAS9TORpgbGicjOWs3M50uFoPTLcr/5bwLwh9i51FuwkS0NZpbrFFV1WVXU+iwHlCey/+r06eZ/8zvfD4c4rSbWge75IQMyPeL6yo8dOJjQVgDMy8y6DeHF3SqSqpgitfdpRnlF4rSc7cnwaydcfo8Fb2WVpVGPXMp2LDMK4SJsVbfML8DxCOM/4YW5nZhonQ60IQtoy200465LTPmNDf98rIi3sDAvo6CsQpr3Dkhezulf+NW/jJ9mNXJ3DQfz4V16x7N6FwD6tBAiCDrwABuuBT9gMkRjEwYSfS/nnsEOqXRXEMI/nOMoPmzvHdwnM/5iUB7FCptv7QW+z+bgXNil+wuTnjaDLEt7cUzWB9tR6oayfPifkEzouK05zCrH83etOnnTHXJaVKnk9ngrwCw8WU584OErXDrViMo7apZsXIO6DqKZuvwhSFWzPU+MAAAACz74MBiyi63fCz/uyXXDSBTRWD5asA0LH7w3Tb6f5eM5u+hNjhU8uxwHfmD+Wx5OyLjx3V8Xp2INh2zj/dln8hqyUEZXcPASulxbYwEqIV0Q06QRHtn780HTpyTf+rdrBFAAAAAAAAAAAAAAAAAAAA==";let As=!1;const Os=new Set;function Ms(){return As}function Ns(e){As||(Ri(`Diamond falls back to its still image: ${e}`),As=!0,Os.forEach(e=>e()))}function Ps(){let e,t=0,n=[];return{track:function(r){if(void 0===e||r-e>1e3)return e=r,t=r+1e3,void(n=[]);const o=r-e;if(e=r,re-t);return t[Math.floor(t.length/2)]}(n);n=[],t=r,i>50&&Ns(`median frame interval ${Math.round(i)} ms`)},reset:function(){e=void 0,n=[]}}}function Ls(e,t,n){return Math.min(n,Math.max(t,e))}function Ws(e,t,n){return e+(t-e)*n}const Ds=42,js=1440,Us=["crownGradient","pavilionGradient","lightSweep","crownSweep","rightCrownSweep","leftCrownSweep","pavilionSweep","rightPavilionSweep","leftPavilionSweep"],qs=["model","inverseModel","projection"],Bs=["parameters","viewport","sparkleShape","sparkleHalo","facetProjection","appearance",...Us],zs=.9975,Fs=360/Math.PI,Ks=Math.sin(.25),Hs=Math.sin(.96),Vs=Math.PI/2,$s=Math.PI/15,Gs=Math.PI*(2/15),Xs=1/60;let Zs;function Ys(e){return p(this,null,function*(){const t=el(e,"#version 300 es\nprecision highp float;\nprecision highp int;\n#define saturate(x) clamp(x,0.0,1.0)\nstruct Vertex { vec4 position; vec4 normal; vec4 surface; };\nstruct Uniforms {\n mat4 model;\n mat4 projection;\n mat4 inverseModel;\n vec4 parameters; // time, refraction, brightness, sparkles\n vec4 viewport; // width, height, optical plane count, unused\n vec4 sparkleShape; // main layer scale, contour morph, core scale, star glow scale\n vec4 sparkleHalo; // circular glow scale, main face rotation, horizontal correction, visibility\n vec4 crownGradient;\n vec4 pavilionGradient;\n vec4 lightSweep; // diagonal position, environment phase, transmission, reserved\n vec4 facetProjection; // reference pitch cosine/sine, source units, projected top\n vec4 crownSweep;\n vec4 rightCrownSweep;\n vec4 leftCrownSweep;\n vec4 pavilionSweep;\n vec4 rightPavilionSweep;\n vec4 leftPavilionSweep;\n vec4 appearance; // palette identifier, reserved\n vec4 referenceCrownFlash;\n vec4 referencePavilionFlash;\n};\nstruct Raster {\n vec4 position ;\n vec3 localPosition;\n vec3 normal;\n vec3 worldPosition;\n vec3 facetWeights; // table, crown, pavilion; interpolated across rounded edges\n};\nstruct SparkleVertex { vec4 contours; vec4 material; };\nstruct SparkleRaster {\n vec4 position ;\n vec2 sourcePoint;\n float strength ;\n uint layer ;\n};\nstruct SparkleAnchor { vec4 position; vec4 normal; };\nuniform Uniforms u;\nuniform vec4 planes[17];\nuniform SparkleAnchor anchors[8];\nout vec3 v_localPosition;\nout vec3 v_normal;\nout vec3 v_worldPosition;\nout vec3 v_facetWeights;\nlayout(location=0) in vec4 a_position; layout(location=1) in vec4 a_normal; layout(location=2) in vec4 a_surface;\n\nvoid main(){\n\n Vertex v = Vertex(a_position,a_normal,a_surface);\n vec4 world = u.model * v.position;\n Raster result;\n result.position = u.projection * world;\n result.localPosition = v.position.xyz;\n result.normal = normalize((u.model * v.normal).xyz);\n result.worldPosition = world.xyz;\n result.facetWeights = v.surface.z == 3.0 ? vec3(v.surface.xy, 1.0-v.surface.x-v.surface.y)\n : vec3(v.surface.z == 0.0, v.surface.z == 1.0, v.surface.z == 2.0);\n gl_Position=result.position; gl_Position.z=gl_Position.z*2.0-gl_Position.w;\nv_localPosition=result.localPosition;\nv_normal=result.normal;\nv_worldPosition=result.worldPosition;\nv_facetWeights=result.facetWeights;\n\n}\n","#version 300 es\nprecision highp float;\nprecision highp int;\n#define saturate(x) clamp(x,0.0,1.0)\nstruct Vertex { vec4 position; vec4 normal; vec4 surface; };\nstruct Uniforms {\n mat4 model;\n mat4 projection;\n mat4 inverseModel;\n vec4 parameters; // time, refraction, brightness, sparkles\n vec4 viewport; // width, height, optical plane count, unused\n vec4 sparkleShape; // main layer scale, contour morph, core scale, star glow scale\n vec4 sparkleHalo; // circular glow scale, main face rotation, horizontal correction, visibility\n vec4 crownGradient;\n vec4 pavilionGradient;\n vec4 lightSweep; // diagonal position, environment phase, transmission, reserved\n vec4 facetProjection; // reference pitch cosine/sine, source units, projected top\n vec4 crownSweep;\n vec4 rightCrownSweep;\n vec4 leftCrownSweep;\n vec4 pavilionSweep;\n vec4 rightPavilionSweep;\n vec4 leftPavilionSweep;\n vec4 appearance; // palette identifier, reserved\n vec4 referenceCrownFlash;\n vec4 referencePavilionFlash;\n};\nstruct Raster {\n vec4 position ;\n vec3 localPosition;\n vec3 normal;\n vec3 worldPosition;\n vec3 facetWeights; // table, crown, pavilion; interpolated across rounded edges\n};\nstruct SparkleVertex { vec4 contours; vec4 material; };\nstruct SparkleRaster {\n vec4 position ;\n vec2 sourcePoint;\n float strength ;\n uint layer ;\n};\nstruct SparkleAnchor { vec4 position; vec4 normal; };\nuniform Uniforms u;\n// Read the optical hull directly from uniforms. Passing this array by value\n// makes mobile drivers materialize private copies for each ray query.\nuniform vec4 planes[17];\nuniform SparkleAnchor anchors[8];\nin vec3 v_localPosition;\nin vec3 v_normal;\nin vec3 v_worldPosition;\nin vec3 v_facetWeights;\nvec3 referenceCrown(vec2 p, vec4 gradient) {\n const float stops[7] =float[7](0.0, 0.162, 0.324, 0.501, 0.667, 0.833, 1.0);\n const vec3 colors[7] =vec3[7](vec3(0.145,0.792,1.0), vec3(0.373,0.875,1.0),\n vec3(0.6,0.957,1.0), vec3(0.3,0.798,1.0), vec3(0.0,0.639,1.0),\n vec3(0.0,0.545,1.0), vec3(0.0,0.451,1.0));\n vec2 start = gradient.xy, direction = gradient.zw - start;\n float t = saturate(dot(p-start, direction) / dot(direction,direction));\n for (uint i = 1u; i < 7u; ++i) {\n if (t <= stops[i]) { return mix(colors[i-1u], colors[i], (t-stops[i-1u])/(stops[i]-stops[i-1u])); }\n }\n return colors[6];\n}\n\nvec3 lateralDepth(vec3 color, vec3 normal, float y, vec3 facetWeights,\n float opticalLuminance) {\n float horizontalNormal = length(normal.xz);\n float side = smoothstep(0.22, 0.80, abs(normal.x) / max(horizontalNormal, 0.001));\n float shoulder = smoothstep(0.06, 0.57, y);\n float lower = smoothstep(0.12, 0.90, -y);\n float reflectedLight = smoothstep(0.28, 0.78, color.g);\n // A restrained blue-violet shadow keeps the sides distinct without\n // swallowing their cyan gradients and moving reflections.\n vec3 deepBlue = mix(vec3(0.017, 0.035, 0.90),\n vec3(0.006, 0.11, 1.0), reflectedLight);\n vec3 sideColor = mix(deepBlue, vec3(0.22, 0.86, 1.0), shoulder * 0.69);\n sideColor = mix(sideColor, vec3(0.018, 0.39, 1.0), lower * 0.52);\n float reflectionDetail = 0.105 + opticalLuminance * 0.14\n + smoothstep(0.70, 0.95, color.g) * 0.26;\n sideColor = mix(sideColor, color, reflectionDetail);\n float weight = side * 0.96 * (1.0 - facetWeights.x);\n return mix(color, sideColor, weight);\n}\n\nvec3 facetBarycentric(vec2 p, vec2 a, vec2 b, vec2 c) {\n vec2 v = b-a, w = c-a, q = p-a;\n float determinant = v.x*w.y - v.y*w.x;\n float y = (q.x*w.y - q.y*w.x) / determinant;\n float z = (v.x*q.y - v.y*q.x) / determinant;\n return vec3(1.0-y-z, y, z);\n}\n\nfloat facetCoverage(vec3 barycentric) {\n float edge = min(barycentric.x, min(barycentric.y, barycentric.z));\n float aa = max(fwidth(edge), 0.004);\n return smoothstep(-aa, aa, edge);\n}\n\nvec2 sourceFacetPoint(vec3 localPosition, vec2 outward, Uniforms u) {\n float across = dot(localPosition.xz, vec2(outward.y,-outward.x));\n float depth = dot(localPosition.xz,outward);\n float c = u.facetProjection.x, s = u.facetProjection.y;\n float y = c*localPosition.y-s*depth;\n float z = s*localPosition.y+c*depth;\n float w = u.projection[2].w*z+u.projection[3].w;\n return vec2(257.6+across/w*u.facetProjection.z,\n 103.8+(u.facetProjection.w-y/w)*u.facetProjection.z);\n}\n\nvec3 illustratedFacets(vec3 color, Raster inputData, Uniforms u) {\n vec3 localNormal = normalize((u.inverseModel * vec4(normalize(inputData.normal), 0.0)).xyz);\n // Fixed material coordinates on each broad face. The same reference camera\n // maps the authored facets and the sparkle anchors onto the current cut.\n vec2 outward = abs(localNormal.x) > abs(localNormal.z)\n ? vec2(sign(localNormal.x),0.0) : vec2(0.0,sign(localNormal.z));\n vec3 tangent = vec3(outward.y,0.0,-outward.x);\n vec2 p = sourceFacetPoint(inputData.localPosition,outward,u);\n // Fade the drawing before the diagonal facets, where the next face's\n // coordinate system takes over. No duplicated motifs along rounded edges.\n vec2 normalXZ = abs(localNormal.xz);\n float broad = 1.0-smoothstep(0.20,0.65,min(normalXZ.x,normalXZ.y)/max(max(normalXZ.x,normalXZ.y),0.0001));\n vec3 worldTangent = (u.model * vec4(tangent, 0.0)).xyz;\n vec3 n = normalize(inputData.normal);\n vec3 light = normalize(vec3(0.6*sin(u.lightSweep.y), 0.5, 1.0));\n float leftLight = pow(saturate(dot(normalize(n - worldTangent*0.38), light)), 5.0);\n float rightLight = pow(saturate(dot(normalize(n + worldTangent*0.38), light)), 5.0);\n if (inputData.facetWeights.y > 0.0) {\n // Both crown triangles meet at the same upper junction.\n const vec2 crownJunction = vec2(258.8,128.9);\n // Authored lower corners now share the same projection as the mesh.\n const vec2 crownBaseLeft = vec2(108.8,240.8);\n const vec2 crownBaseRight = vec2(406.8,240.8);\n vec3 left = facetBarycentric(p, vec2(142.1,106.3), crownJunction, crownBaseLeft);\n float leftStrength = facetCoverage(left) * (0.18 + 0.40*leftLight) * saturate(1.0-left.y);\n color = mix(color, vec3(0.79,0.988,1.0), leftStrength * inputData.facetWeights.y * broad);\n vec3 right = facetBarycentric(p, crownBaseRight, crownJunction, vec2(378.5,108.2));\n // The source is light at the left junction and dark at the right edge.\n // Use horizontal facet coordinates so the gradient turns with the gem.\n float gradient = smoothstep(crownJunction.x,crownBaseRight.x,p.x);\n vec3 tint = mix(vec3(0.28,0.83,1.0),vec3(0.025,0.43,1.0),gradient);\n tint = mix(tint,vec3(0.57,0.95,1.0),rightLight*0.24);\n color = mix(color, tint, facetCoverage(right) * 0.90 * inputData.facetWeights.y * broad);\n }\n if (inputData.facetWeights.z > 0.0) {\n // A translucent kite belongs to each broad pavilion face. Material-space\n // edges stay attached to the surface throughout a complete rotation.\n vec2 kite = vec2(dot(inputData.localPosition,tangent),inputData.localPosition.y);\n const float halfWidth = 0.245, top = -0.61, shoulder = -0.70, bottom = -1.075;\n const float upperHeight = top-shoulder, lowerHeight = shoulder-bottom;\n float upperEdge = ((top-kite.y)*halfWidth-abs(kite.x)*upperHeight)\n / length(vec2(halfWidth,upperHeight));\n float lowerEdge = ((kite.y-bottom)*halfWidth-abs(kite.x)*lowerHeight)\n / length(vec2(halfWidth,lowerHeight));\n float edge = min(upperEdge,lowerEdge);\n float aa = max(fwidth(edge),0.0015);\n float coverage = smoothstep(-aa,aa,edge);\n float illumination = saturate(dot(n,normalize(vec3(-0.65,0.5,1.0))));\n vec3 tint = mix(vec3(0.48,0.96,1.0),vec3(0.70,1.0,1.0),illumination);\n float across = saturate(0.5+kite.x/(2.0*halfWidth));\n tint *= mix(vec3(1.0),vec3(0.88,0.97,1.0),across);\n color = mix(color,tint,coverage*0.28*inputData.facetWeights.z*broad);\n }\n\n return color;\n}\n\nvec3 studio(vec3 d, float phase) {\n float angle = 0.85 * sin(phase);\n d.xz = vec2(cos(angle)*d.x - sin(angle)*d.z, sin(angle)*d.x + cos(angle)*d.z);\n float up = smoothstep(-0.65, 0.85, d.y);\n vec3 c = mix(vec3(0.002, 0.075, 0.88), vec3(0.19, 0.78, 1.0), up);\n float key = pow(saturate(dot(d, normalize(vec3(-0.6, 0.8, 0.7)))), 10.0);\n float stripPosition = 0.12 + 0.48 * sin(phase);\n float strip = exp(-pow((d.x + d.y * 0.42 - stripPosition) * 9.0, 2.0));\n float side = pow(saturate(dot(d, normalize(vec3(0.8, 0.2, -0.5)))), 18.0);\n c = mix(c, vec3(0.68, 0.98, 1.0), key * 0.94);\n c = mix(c, vec3(0.80, 0.99, 1.0), strip * 0.64);\n c += side * vec3(0.1, 0.3, 0.38);\n return c;\n}\n\nvec2 facetEdgeRoll(vec2 p, vec2 a, vec2 b) {\n vec2 segment = b-a;\n float edgeLength = length(segment);\n vec2 along = segment/edgeLength;\n vec2 across = vec2(-along.y,along.x);\n float distance = dot(p-a,across);\n float progress = dot(p-a,along);\n float width = max(1.6,fwidth(distance));\n float q = distance/width;\n float ends = smoothstep(0.0,5.0,progress)*(1.0-smoothstep(edgeLength-5.0,edgeLength,progress));\n return across*(q*exp(-q*q)*0.22*ends);\n}\n\nvec3 polishedNormal(Raster inputData, vec3 localNormal, Uniforms u) {\n // Only the two surface crown diagonals get this tiny optical fillet.\n // The actual outline and the internal optical hull stay unchanged.\n if (inputData.facetWeights.y <= 0.0) { return normalize(inputData.normal); }\n vec2 outward = abs(localNormal.x) > abs(localNormal.z)\n ? vec2(sign(localNormal.x),0.0) : vec2(0.0,sign(localNormal.z));\n vec2 normalXZ = abs(localNormal.xz);\n float broad = 1.0-smoothstep(0.20,0.65,min(normalXZ.x,normalXZ.y)/max(max(normalXZ.x,normalXZ.y),0.0001));\n vec2 p = sourceFacetPoint(inputData.localPosition,outward,u);\n vec2 roll = facetEdgeRoll(p,vec2(258.8,128.9),vec2(108.8,240.8))\n + facetEdgeRoll(p,vec2(258.8,128.9),vec2(406.8,240.8));\n vec3 across = vec3(outward.y,0.0,-outward.x);\n vec3 up = normalize(cross(localNormal,across));\n vec3 normal = normalize(localNormal-(across*roll.x-up*roll.y)*broad*inputData.facetWeights.y);\n return normalize((u.model*vec4(normal,0.0)).xyz);\n}\n\nfloat studioPanel(vec3 reflected, vec3 direction, vec2 size) {\n float alignment = dot(reflected,direction);\n vec3 horizontal = normalize(cross(vec3(0.0,1.0,0.0),direction));\n vec3 vertical = cross(direction,horizontal);\n vec2 point = vec2(dot(reflected,horizontal),dot(reflected,vertical))/max(alignment,0.15);\n // Filter the narrow reflection at small sizes and grazing angles.\n vec2 dx = dFdx(point), dy = dFdy(point);\n vec2 variance = size*size+dx*dx+dy*dy;\n float energy = size.x*size.y/sqrt(variance.x*variance.y);\n return exp(-dot(point*point,1.0/variance))*energy*smoothstep(0.15,0.40,alignment);\n}\n\nvec3 surfaceFinish(vec3 color, vec3 normal, vec3 view, Uniforms u) {\n vec3 reflected = reflect(-view,normal);\n float phase = u.lightSweep.y;\n float key = studioPanel(reflected,normalize(vec3(-0.36+0.14*sin(phase),0.90,0.72)),vec2(0.16,0.48));\n float rim = studioPanel(reflected,normalize(vec3(0.72,-0.52+0.10*cos(phase),0.18)),vec2(0.10,0.60));\n float fresnel = pow(1.0-saturate(dot(normal,view)),4.0);\n float strength = key*(0.35+0.35*fresnel)+rim*(0.16+0.30*fresnel);\n return mix(color,vec3(0.87,0.99,1.0),strength);\n}\n\n// The optical hull always has 17 planes. Constant indices avoid the expensive\n// dynamically indexed uniform loop on mobile GPUs, without changing ray math.\n\nvoid exitPlane(vec4 plane, vec3 origin, vec3 ray, inout float nearest,\n inout float second, inout vec3 normal, inout vec3 secondNormal) {\n float denominator = dot(plane.xyz, ray);\n if (denominator > 0.0001) {\n float t = -(dot(plane.xyz, origin) + plane.w) / denominator;\n if (t > 0.001 && t < nearest) {\n second = nearest; secondNormal = normal;\n nearest = t; normal = plane.xyz;\n } else if (t > 0.001 && t < second) {\n second = t; secondNormal = plane.xyz;\n }\n }\n}\n\nfloat nearestExit(vec3 origin, vec3 ray, inout vec3 normal) {\n float nearest = 1e5;\n float second = 1e5;\n vec3 secondNormal = normal;\n#define TEST_EXIT(I) exitPlane(planes[I], origin, ray, nearest, second, normal, secondNormal);\n TEST_EXIT(0u) TEST_EXIT(1u) TEST_EXIT(2u) TEST_EXIT(3u) TEST_EXIT(4u) TEST_EXIT(5u)\n TEST_EXIT(6u) TEST_EXIT(7u) TEST_EXIT(8u) TEST_EXIT(9u) TEST_EXIT(10u) TEST_EXIT(11u)\n TEST_EXIT(12u) TEST_EXIT(13u) TEST_EXIT(14u) TEST_EXIT(15u) TEST_EXIT(16u)\n#undef TEST_EXIT\n if (second < 1e5) {\n // The optical hull inherits a tiny edge fillet. This also filters its\n // reflected boundaries when they become thinner than a screen pixel.\n float width = max(0.008,min(0.035,fwidth(second-nearest)));\n float blend = 0.5*(1.0-smoothstep(0.0,width,second-nearest));\n normal = normalize(mix(normal,secondNormal,blend));\n }\n return nearest;\n}\n\nvec4 oppositeFacets(vec3 p, vec3 ray, Uniforms u) {\n vec3 origin = p + ray*0.004;\n vec3 normal = vec3(0.0,1.0,0.0);\n float distance = nearestExit(origin,ray,normal);\n if (distance > 100.0 || normal.y > 0.95) { return vec4(0.0); }\n vec3 hit = origin + ray*distance;\n vec3 worldNormal = (u.model*vec4(normal,0.0)).xyz;\n vec3 tangent = normalize(vec3(normal.z+0.00001,0.0,-normal.x));\n float across = dot(hit,tangent);\n vec2 authored = vec2(across*225.8, (normal.y > 0.0 ? 0.3065-hit.y : -0.54-hit.y)*239.0);\n vec3 color;\n if (normal.y > 0.0) {\n color = referenceCrown(authored,u.crownGradient);\n float response = pow(saturate(dot(worldNormal, normalize(vec3(0.7*sin(u.lightSweep.y),0.55,-1.0)))),4.0);\n color = mix(color*vec3(0.45,0.70,0.98), vec3(0.60,0.94,1.0), response*0.55);\n } else {\n // The pavilion is one connected eight-facet hull. Looking through its\n // front reveals the actual opposite facet, without view-switched motifs.\n vec3 reflected = normalize((u.model*vec4(reflect(ray,normal),0.0)).xyz);\n vec3 environment = studio(reflected,u.lightSweep.y);\n float response = pow(saturate(dot(worldNormal,normalize(vec3(-0.4,-0.55,-1.0)))),2.0);\n color = mix(vec3(0.012,0.38,1.0),vec3(0.27,0.94,1.0),response*0.65+environment.g*0.35);\n color = mix(color,environment,0.28);\n float panel = studioPanel(reflected,normalize(vec3(-0.36,0.90,0.72)),vec2(0.20,0.52));\n color = mix(color,vec3(0.72,0.98,1.0),panel*0.48);\n }\n float coverage = smoothstep(0.03,0.35,distance) * exp(-distance*0.16);\n return vec4(color,coverage);\n}\n\nfloat sourceBand(vec2 p, vec4 gradient) {\n vec2 direction = gradient.zw-gradient.xy;\n float t = dot(p-gradient.xy,direction)/dot(direction,direction);\n return saturate(1.0-abs(t-0.49)/0.49);\n}\n\nfloat facetSweep(Raster inputData, vec3 localNormal, Uniforms u) {\n vec3 tangent = normalize(vec3(localNormal.z+0.00001,0.0,-localNormal.x));\n float across = dot(inputData.localPosition,tangent)*225.8;\n float side = smoothstep(0.20,0.50,abs(normalize(inputData.normal).x));\n bool right = inputData.normal.x > 0.0;\n vec4 crown = mix(u.crownSweep, right ? u.rightCrownSweep : u.leftCrownSweep, side);\n vec4 pavilion = mix(u.pavilionSweep, right ? u.rightPavilionSweep : u.leftPavilionSweep, side);\n return sourceBand(vec2(across,(0.3065-inputData.localPosition.y)*239.0),crown)*inputData.facetWeights.y\n + sourceBand(vec2(across,(-0.54-inputData.localPosition.y)*235.0),pavilion)*inputData.facetWeights.z;\n}\n\nvec3 internalEnvironment(vec3 position, vec3 direction, float pavilion, Uniforms u) {\n vec3 worldPosition = (u.model*vec4(position,1.0)).xyz;\n vec3 worldDirection = normalize((u.model*vec4(direction,0.0)).xyz);\n // A finite studio gives each reflected facet a spatial gradient, rather\n // than a flat swatch. The lights and the optical hull share one 3D space.\n float along = dot(worldPosition,worldDirection);\n float distance = -along+sqrt(max(0.0,along*along+3.2*3.2-dot(worldPosition,worldPosition)));\n vec3 sampleValue = normalize(worldPosition+worldDirection*distance);\n if (pavilion <= 0.0) { return studio(sampleValue,u.lightSweep.y); }\n // Keep a uniform blue surround below the crown. A bright upper hemisphere\n // reflected inputData the pavilion reads as a filled tip with a horizontal meniscus.\n // Narrow studio panels retain moving reflections without filling whole facets.\n float phase = u.lightSweep.y;\n float key = studioPanel(sampleValue,normalize(vec3(-0.12+0.035*sin(phase),-0.60,0.79)),vec2(0.055,0.52));\n float rim = studioPanel(sampleValue,normalize(vec3(0.12,0.75+0.035*cos(phase),-0.65)),vec2(0.055,0.50));\n vec3 lower = mix(vec3(0.015,0.41,1.0),vec3(0.58,0.94,1.0),key*0.95);\n lower = mix(lower,vec3(0.24,0.78,1.0),rim*0.82);\n return pavilion < 1.0 ? mix(studio(sampleValue,u.lightSweep.y),lower,pavilion) : lower;\n}\n\nfloat reflectionTriangle(vec3 origin, vec3 ray, vec3 a, vec3 b, vec3 c,\n out vec3 coordinates) {\n vec3 ab = b-a, ac = c-a, crossRay = cross(ray,ac);\n float determinant = dot(ab,crossRay);\n if (abs(determinant) < 0.00001) { return 1e5; }\n vec3 offset = origin-a;\n float u = dot(offset,crossRay)/determinant;\n vec3 q = cross(offset,ab);\n float v = dot(ray,q)/determinant;\n float t = dot(ac,q)/determinant;\n coordinates = vec3(1.0-u-v,u,v);\n return min(min(coordinates.x,coordinates.y),coordinates.z) >= 0.0 && t > 0.001 ? t : 1e5;\n}\n\nvec3 pavilionReflections(vec3 color, vec3 origin, vec3 ray, Uniforms u) {\n if (u.parameters.y <= 0.0) { return color; }\n const vec2 ring[8] =vec2[8](vec2(0.0,1.0),vec2(0.70710678,0.70710678),\n vec2(1.0,0.0),vec2(0.70710678,-0.70710678),vec2(0.0,-1.0),\n vec2(-0.70710678,-0.70710678),vec2(-1.0,0.0),vec2(-0.70710678,0.70710678));\n // One convex fan of reflected facets, shared by every camera orientation.\n // Clip the whole volume so adjoining facets never acquire dark seams.\n const vec3 top = vec3(0.0,-0.28,0.0), tip = vec3(0.0,-1.06,0.0);\n float entry = 0.0, exit = 1e5;\n vec3 entryNormal = vec3(0.0,1.0,0.0);\n vec3 worldRay = normalize((u.model*vec4(ray,0.0)).xyz);\n vec3 illumination = normalize(vec3(-0.55,0.65,1.0));\n vec3 sideColor = vec3(0.0);\n float sideWeight = 0.0;\n vec3 veilColor = vec3(0.0);\n float veilWeight = 0.0;\n for (uint i = 0u; i < 8u; ++i) {\n vec2 current = ring[i], next = ring[(i+1u)%8u];\n vec3 a = vec3(current.x*0.28,-0.68,current.y*0.28);\n vec3 b = vec3(next.x*0.28,-0.68,next.y*0.28);\n for (uint part = 0u; part < 2u; ++part) {\n vec3 peak = part == 0u ? top : tip;\n vec3 n = normalize(cross(a-peak,b-peak));\n if (dot(n,(a+b+peak)/3.0-vec3(0.0,-0.68,0.0)) < 0.0) { n = -n; }\n float denominator = dot(n,ray);\n float side = dot(n,origin-peak);\n if (abs(denominator) < 0.00001) {\n if (side > 0.0) { exit = -1.0; }\n } else {\n float t = -side/denominator;\n if (denominator < 0.0 && t > entry) { entry = t; entryNormal = n; }\n if (denominator > 0.0) { exit = min(exit,t); }\n }\n }\n vec3 radial = vec3(current.x,0.0,current.y);\n vec3 tangent = vec3(current.y,0.0,-current.x);\n // Broad, low-contrast echoes of the crown stretch through the volume\n // towards the same lower junction. Adjacent planes meet without dark gaps.\n // Continue the same planes above the girdle so their top fade stays\n // hidden behind the crown, including the deeper, opposite reflections.\n const float upperY = 0.20;\n const float extension = (upperY+0.12)/0.65;\n const float upperRadius = 0.64+(0.64-0.19)*extension;\n const float upperWidth = 0.265097+(0.265097-0.078701)*extension;\n vec3 upperLeft = radial*upperRadius - tangent*upperWidth + vec3(0.0,upperY,0.0);\n vec3 upperRight = radial*upperRadius + tangent*upperWidth + vec3(0.0,upperY,0.0);\n vec3 lowerLeft = radial*0.19 - tangent*0.078701 + vec3(0.0,-0.77,0.0);\n vec3 lowerRight = radial*0.19 + tangent*0.078701 + vec3(0.0,-0.77,0.0);\n vec3 ribbonCoordinates;\n float ribbon = reflectionTriangle(origin,ray,upperLeft,upperRight,lowerLeft,ribbonCoordinates);\n if (ribbon > 100.0) {\n ribbon = reflectionTriangle(origin,ray,upperRight,lowerRight,lowerLeft,ribbonCoordinates);\n }\n if (ribbon < 100.0) {\n vec3 hit = origin+ray*ribbon;\n float depth = (-0.12-hit.y)/0.65;\n float across = dot(hit,tangent);\n float right = mix(0.265097,0.078701,depth), left = -right;\n vec3 worldRadial = normalize((u.model*vec4(radial,0.0)).xyz);\n float facing = saturate(-dot(worldRadial,worldRay));\n float fade = smoothstep(0.0,0.065,upperY-hit.y)*(1.0-smoothstep(0.70,1.0,depth));\n float opacity = fade*(0.16+0.84*facing);\n float light = saturate(0.5+0.5*dot(worldRadial,illumination));\n // Broad reflected facets fill the middle with restrained diagonal\n // changes inputData tone, expressed inputData the fixed plane's own coordinates.\n float acrossPlane = saturate((across-left)/(right-left));\n float diagonal = smoothstep(-0.045,0.045,acrossPlane-0.35-depth*0.55);\n float middle = smoothstep(0.12,0.24,depth)*(1.0-smoothstep(0.50,0.64,depth));\n vec3 tint = mix(vec3(0.015,0.56,1.0),vec3(0.33,0.97,1.0),light);\n tint = mix(tint,vec3(0.42,0.97,1.0),middle*(0.32-0.20*diagonal));\n tint = mix(tint,vec3(0.015,0.46,1.0),diagonal*0.24);\n veilColor += tint*opacity;\n veilWeight += opacity;\n }\n vec3 aSide = radial*0.72 + tangent*0.055 + vec3(0.0,-0.30,0.0);\n vec3 bSide = radial*0.49 - tangent*0.105 + vec3(0.0,-0.60,0.0);\n vec3 cSide = radial*0.15 + tangent*0.020 + vec3(0.0,-0.93,0.0);\n vec3 coordinates;\n float t = reflectionTriangle(origin,ray,aSide,bSide,cSide,coordinates);\n if (t < 100.0) {\n vec3 worldRadial = normalize((u.model*vec4(radial,0.0)).xyz);\n // Long glints read at the sides; a front-facing sector must not\n // become an opaque needle inputData the middle of the stone.\n float sideFacing = 1.0-abs(dot(worldRadial,worldRay));\n float edge = min(coordinates.y,coordinates.z);\n float opacity = smoothstep(0.20,0.75,sideFacing)\n * smoothstep(0.0,0.085,edge) * smoothstep(0.0,0.035,coordinates.x);\n float light = 0.5+0.5*dot(worldRadial,illumination);\n vec3 tint = mix(vec3(0.16,0.80,1.0),vec3(0.85,1.0,1.0),light);\n sideColor += tint*opacity;\n sideWeight += opacity;\n }\n }\n float strength = saturate(u.parameters.y/0.72);\n if (veilWeight > 0.0) {\n color = mix(color,veilColor/veilWeight,(1.0-exp(-veilWeight*0.46))*strength);\n }\n if (sideWeight > 0.0) {\n color = mix(color,sideColor/sideWeight,(1.0-exp(-sideWeight*1.4))*strength);\n }\n {\n // studioPanel uses screen derivatives. Evaluate it on both sides of the\n // hull boundary; divergent execution produces dotted edges on Adreno.\n vec3 hit = origin+ray*entry;\n vec3 worldNormal = normalize((u.model*vec4(entryNormal,0.0)).xyz);\n float light = saturate(dot(worldNormal,normalize(vec3(-0.65,0.15,1.0))));\n float gleam = studioPanel(reflect(worldRay,worldNormal),\n normalize(vec3(-0.35+0.15*sin(u.lightSweep.y),0.60,0.75)),vec2(0.25,0.65));\n vec3 tint = mix(vec3(0.025,0.54,1.0),vec3(0.40,0.92,1.0),light);\n tint = mix(tint,vec3(0.72,0.99,1.0),gleam*0.16);\n float thickness = smoothstep(0.0,0.18,exit-entry);\n float fade = smoothstep(-1.07,-0.93,hit.y);\n color = mix(color,tint,0.28*thickness*fade*strength*(entry < exit ? 1.0 : 0.0));\n }\n return color;\n}\n\nvec3 interior(vec3 p, vec3 direction, float pavilion, Uniforms u) {\n vec3 accumulated = vec3(0.0);\n float weight = 0.60;\n vec3 origin = p + direction * 0.004;\n for (uint bounce = 0u; bounce < 2u; ++bounce) {\n vec3 n = vec3(0.0, 1.0, 0.0);\n float distance = nearestExit(origin, direction, n);\n if (distance > 100.0) { break; }\n vec3 hit = origin + direction * distance;\n vec3 outgoing = refract(direction, -n, 1.62);\n vec3 reflection = reflect(direction, n);\n vec3 color = internalEnvironment(hit,reflection,pavilion,u);\n if (dot(outgoing,outgoing) > 0.01) {\n // Fresnel approaches total internal reflection continuously; a hard\n // switch between the two rays made whole patches change abruptly.\n float incident = saturate(dot(direction,n));\n float transmitted = saturate(dot(outgoing,n));\n float rs = (1.62*incident-transmitted)/(1.62*incident+transmitted);\n float rp = (incident-1.62*transmitted)/(incident+1.62*transmitted);\n float reflectance = 0.5*(rs*rs+rp*rp);\n color = mix(internalEnvironment(hit,outgoing,pavilion,u),color,reflectance);\n }\n color *= exp(-vec3(0.30, 0.07, 0.006) * distance);\n accumulated += weight * color;\n weight *= 0.52;\n direction = reflection;\n origin = hit + direction * 0.004;\n }\n return accumulated;\n}\n\nvec3 materialPalette(vec3 color, vec3 facetWeights, uint appearance) {\n switch (appearance) {\n case 1u: {\n // Keep the authored icy blue inputData the middle values: interpolating\n // directly to white desaturates the crown into a cold grey.\n float tone = smoothstep(0.0,0.92,saturate(dot(color.rg,vec2(0.22,0.78))));\n vec3 shadow = mix(vec3(0.63,0.77,0.95),vec3(0.733,0.859,1.0),facetWeights.y*0.25);\n const vec3 ice = vec3(207.0,241.0,253.0) / 255.0; // #cff1fd\n vec3 upper = mix(shadow,ice,smoothstep(0.0,0.62,tone));\n upper = mix(upper,vec3(1.0),smoothstep(0.58,1.0,tone)*0.92);\n // Lift the pavilion while retaining a distinct shadow range below\n // the white crown, with a little more blue inputData its lighter facets.\n vec3 lower = mix(vec3(0.59,0.71,0.865),vec3(0.96,0.985,1.0),pow(tone,1.10));\n return mix(upper,lower,facetWeights.z);\n }\n case 2u: {\n float tone = smoothstep(0.035,0.90,saturate(dot(color.rg,vec2(0.20,0.80))));\n vec3 cool = mix(vec3(0.025,0.29,0.83),vec3(0.38,0.78,1.0),smoothstep(0.0,0.65,tone));\n vec3 upper = mix(cool,vec3(0.94,0.99,1.0),smoothstep(0.45,1.0,tone));\n vec3 lower = mix(vec3(0.025,0.34,0.92),vec3(0.90,0.99,1.0),pow(tone,2.35));\n return mix(upper,lower,facetWeights.z);\n }\n default: return color;\n }\n}\n\nvoid glowPlane(vec4 plane, vec3 position, vec3 ray, vec3 localNormal,\n inout float planeAlignment, inout float thickness) {\n planeAlignment = max(planeAlignment,dot(plane.xyz,localNormal));\n float denominator = dot(plane.xyz,ray);\n if (denominator > 0.0001) {\n float exit = -(dot(plane.xyz,position)+plane.w) / denominator;\n thickness = min(thickness,max(0.0,exit));\n }\n}\n\nvec3 coolInnerGlow(vec3 color, vec3 position, vec3 ray, vec3 normal, vec3 localNormal, vec3 view,\n Uniforms u) {\n // Thin parts transmit a white light band into the stone. The optical chord\n // follows the 3D cut under every rotation, without expanding the silhouette.\n float thickness = 1e5;\n float planeAlignment = 0.0;\n#define TEST_GLOW(I) glowPlane(planes[I], position, ray, localNormal, planeAlignment, thickness);\n TEST_GLOW(0u) TEST_GLOW(1u) TEST_GLOW(2u) TEST_GLOW(3u) TEST_GLOW(4u) TEST_GLOW(5u)\n TEST_GLOW(6u) TEST_GLOW(7u) TEST_GLOW(8u) TEST_GLOW(9u) TEST_GLOW(10u) TEST_GLOW(11u)\n TEST_GLOW(12u) TEST_GLOW(13u) TEST_GLOW(14u) TEST_GLOW(15u) TEST_GLOW(16u)\n#undef TEST_GLOW\n // Scale the penetration with the taper: the tip gets a narrow rim,\n // rather than filling with a solid white pool as its whole depth shrinks.\n float crossSection = clamp((position.y+1.09)/0.98,0.07,1.0);\n float inner = 1.0-smoothstep(0.01,0.80*crossSection,thickness);\n float grazing = 1.0-saturate(dot(normal,view));\n float roundedEdge = smoothstep(0.0015,0.028,1.0-planeAlignment);\n float bevel = pow(grazing,3.0);\n float glow = saturate(inner*0.85 + bevel*0.85 + roundedEdge*smoothstep(0.18,0.80,grazing));\n return mix(color,vec3(0.96,1.0,1.0),glow);\n}\n\nvec4 diamondSurface(Raster inputData, Uniforms u) {\n vec3 n = normalize(inputData.normal);\n float cameraDistance = -u.projection[3].w / u.projection[2].w;\n vec3 view = normalize(vec3(0.0, 0.0, cameraDistance) - inputData.worldPosition);\n vec3 localView = (u.inverseModel * vec4(-view, 0.0)).xyz;\n vec3 localNormal = normalize((u.inverseModel * vec4(n, 0.0)).xyz);\n vec3 transmitted = refract(localView, localNormal, 1.0 / 1.62);\n // Zero internal bounces on every device; retain the existing material mapping.\n vec3 optical = vec3(0.0);\n vec3 reflection = studio(reflect(-view, n), u.lightSweep.y);\n float fresnel = 0.08 + 0.46 * pow(1.0 - saturate(dot(n, view)), 4.0);\n\n float height = saturate((inputData.localPosition.y + 1.05) / 1.65);\n float key = saturate(dot(n, normalize(vec3(-0.65, 0.85, 1.0))));\n float left = saturate(0.52 - inputData.worldPosition.x * 0.43);\n vec3 blue = vec3(0.008, 0.22, 1.0);\n vec3 cyan = vec3(0.29, 0.87, 1.0);\n vec3 body = mix(blue, cyan, saturate(key * 0.60 + left * 0.38));\n float verticalBand = mix(0.5 + 0.5 * sin(height * 18.0 + n.x * 3.0),1.0,inputData.facetWeights.z);\n body *= mix(vec3(0.24, 0.48, 0.96), vec3(1.0), verticalBand * 0.5 + 0.5);\n float opticalLuminance = smoothstep(0.25, 0.85, optical.g);\n // Give the pavilion a cyan body tone without changing reflection contrast\n // or the subdued lower motif. Crown and table keep their existing palette.\n vec3 opticalShadow = mix(vec3(0.005,0.13,1.0),vec3(0.015,0.36,1.0),inputData.facetWeights.z);\n vec3 opticalLight = mix(vec3(0.58,0.97,1.0),vec3(0.45,0.99,1.0),inputData.facetWeights.z);\n optical = mix(opticalShadow,opticalLight,opticalLuminance);\n float opticalWeight = u.parameters.y * mix(0.90, 0.08, inputData.facetWeights.y);\n vec3 color = mix(body, optical, opticalWeight);\n color = mix(color, reflection, fresnel);\n\n float crownGlow = smoothstep(0.10, 0.60, inputData.localPosition.y) * left;\n color = mix(color, vec3(0.70, 0.99, 1.0), crownGlow * 0.58);\n float crownLight = pow(saturate(dot(n, normalize(vec3(-0.38, 0.55, 1.0)))), 9.0);\n crownLight *= smoothstep(-0.03, 0.28, inputData.localPosition.y);\n color = mix(color, vec3(0.65, 0.98, 1.0), crownLight * 0.35);\n vec3 facetBase = color;\n if (inputData.facetWeights.y > 0.0) {\n float softbox = exp(-pow((inputData.worldPosition.x + 0.42) * 1.6, 2.0)\n -pow((inputData.worldPosition.y - 0.32) * 2.2, 2.0));\n color = mix(color, vec3(0.71, 0.99, 1.0), softbox * crownLight * 0.36);\n float shadow = pow(saturate(1.0 - key), 1.4);\n color = mix(color, vec3(0.015, 0.08, 1.0), shadow * 0.7);\n vec3 tangent = normalize(vec3(localNormal.z, 0.0, -localNormal.x));\n vec2 authoredPosition = vec2(dot(inputData.localPosition, tangent) * 225.8 + n.x * 65.0,\n (0.3065 - inputData.localPosition.y) * 244.0);\n color = mix(referenceCrown(authoredPosition, u.crownGradient), color, 0.28);\n color = mix(facetBase, color, inputData.facetWeights.y);\n }\n if (inputData.facetWeights.z > 0.0) {\n color = mix(color,mix(vec3(0.008,0.32,1.0),optical,0.86),inputData.facetWeights.z*u.parameters.y);\n }\n float facetFlash = smoothstep(0.20, 0.78, opticalLuminance);\n float flashWeight = mix(0.24,0.08,inputData.facetWeights.y);\n color *= mix(vec3(1.0),mix(vec3(0.76, 0.82, 0.99), vec3(1.0), facetFlash),flashWeight);\n color = mix(color, vec3(0.66, 0.98, 1.0), pow(facetFlash, 2.0) * 0.24 * flashWeight);\n color = lateralDepth(color, n, inputData.localPosition.y, inputData.facetWeights, opticalLuminance);\n color = mix(color,optical,inputData.facetWeights.z*u.parameters.y*0.48);\n color = mix(color,body,inputData.facetWeights.z*pow(saturate(n.z),2.0)*0.32);\n vec3 rearRay = normalize(mix(localView,transmitted,mix(0.68,0.18,inputData.facetWeights.y)));\n // Disable the opposite-face ray independently of the lower-facet reflections.\n vec4 rear = vec4(0.0);\n float transmission = mix(0.34,0.12+u.lightSweep.z*0.65,inputData.facetWeights.y) * u.parameters.y;\n float facing = smoothstep(0.12,0.65,n.z);\n color = mix(color,rear.rgb,rear.a*transmission*facing*mix(1.0,0.12,inputData.facetWeights.y));\n if (inputData.facetWeights.z > 0.0) {\n vec3 detailRay = normalize(mix(localView,transmitted,0.16));\n color = mix(color,pavilionReflections(color,inputData.localPosition,detailRay,u),inputData.facetWeights.z);\n }\n float tipGlow = pow(saturate((-inputData.localPosition.y - 0.55) / 0.50), 2.0);\n color = mix(color, vec3(0.57, 0.96, 1.0), tipGlow * 0.20);\n // A shallow, translucent image of the table, like Layer 36.0 inputData Lottie.\n // Its optical footprint is smaller than the rounded outer shoulder.\n vec3 tableRay = localView;\n tableRay.y *= 0.72;\n if (tableRay.y > 0.001) {\n float tableHeight = -planes[0].w / planes[0].y;\n float distance = (tableHeight-inputData.localPosition.y)/tableRay.y;\n vec2 hit = (inputData.localPosition + tableRay*distance).xz;\n const float extent = 0.632;\n const float corner = 0.285;\n vec2 q = abs(hit);\n float edge = max(max(q.x,q.y)-extent, (q.x+q.y-extent-corner)*0.70710678);\n float aa = max(fwidth(edge),0.001);\n float coverage = 1.0-smoothstep(-aa,aa,edge);\n vec2 direction = tableRay.xz / max(length(tableRay.xz),0.0001);\n float depth = saturate(0.5+dot(hit,direction)/(2.0*extent));\n // Source opacity: 80.0% group opacity times a 49...65% fill gradient.\n float opacity = mix(0.39,0.52,depth);\n color = mix(color,vec3(0.765,0.988,1.0),coverage*opacity\n *saturate(u.parameters.y/0.72)*inputData.facetWeights.y);\n }\n color = illustratedFacets(color, inputData, u);\n color = mix(color, vec3(0.63, 0.96, 1.0), 0.58 * inputData.facetWeights.x);\n float sweep = facetSweep(inputData,localNormal,u);\n float sweepCore = smoothstep(0.35,1.0,sweep);\n color = mix(color,vec3(0.592,0.953,1.0),sweep*0.20+sweepCore*sweepCore*0.62);\n color = surfaceFinish(color,polishedNormal(inputData,localNormal,u),view,u);\n color = materialPalette(color,inputData.facetWeights,uint(u.appearance.x));\n if (uint(u.appearance.x) == 2u) {\n color = coolInnerGlow(color,inputData.localPosition,localView,n,localNormal,view,u);\n }\n if (uint(u.appearance.x) == 1u) {\n // Source facet flashes stay on the physical front/side planes, including\n // their rounded transitions. They never become screen-space overlays.\n vec2 direction = normalize(localNormal.xz + vec2(0.0,0.00001));\n float side = smoothstep(0.18,0.65,abs(direction.x));\n float front = smoothstep(0.02,0.32,direction.y);\n vec3 regions = vec3(1.0-side, side*step(0.0,direction.x), side*(1.0-step(0.0,direction.x))) * front;\n float alpha = dot(regions,u.referenceCrownFlash.xyz)*inputData.facetWeights.y\n + dot(regions,u.referencePavilionFlash.xyz)*inputData.facetWeights.z;\n float referenceFacing = smoothstep(0.0,0.2,(u.model * vec4(0.0,0.0,1.0,0.0)).z);\n color = mix(color,vec3(1.0),alpha*referenceFacing);\n }\n float whiten = u.appearance.y;\n if (whiten > 0.0) {\n float w = pow(whiten, 0.7);\n float luma = dot(color, vec3(0.2126, 0.7152, 0.0722));\n float lift = smoothstep(0.32, 0.62, luma);\n vec3 glass = mix(vec3(0.07, 0.33, 0.95), vec3(1.0), lift);\n float rim = pow(1.0 - saturate(abs(n.z)), 2.2);\n glass = mix(glass, vec3(1.0), rim * 0.8);\n float seam = saturate(length(fwidth(n)) * 5.5);\n glass = mix(glass, vec3(1.0), seam * 0.85);\n glass = max(glass, vec3(smoothstep(0.62, 0.95, luma)));\n color = mix(color, glass, w);\n float alpha = mix(1.0, mix(0.34, 0.94, max(lift, max(rim, seam))), w);\n return vec4(saturate(color * u.parameters.z) * alpha, alpha);\n }\n return vec4(saturate(color * u.parameters.z), 1.0);\n}\n\nout vec4 fragColor;\n\nvoid main(){\nRaster inputData;\ninputData.localPosition=v_localPosition;\ninputData.normal=v_normal;\ninputData.worldPosition=v_worldPosition;\ninputData.facetWeights=v_facetWeights;\n\n fragColor = diamondSurface(inputData, u);\n\n}\n"),n=el(e,"#version 300 es\nprecision highp float;\nprecision highp int;\n#define saturate(x) clamp(x,0.0,1.0)\nstruct Vertex { vec4 position; vec4 normal; vec4 surface; };\nstruct Uniforms {\n mat4 model;\n mat4 projection;\n mat4 inverseModel;\n vec4 parameters; // time, refraction, brightness, sparkles\n vec4 viewport; // width, height, optical plane count, unused\n vec4 sparkleShape; // main layer scale, contour morph, core scale, star glow scale\n vec4 sparkleHalo; // circular glow scale, main face rotation, horizontal correction, visibility\n vec4 crownGradient;\n vec4 pavilionGradient;\n vec4 lightSweep; // diagonal position, environment phase, transmission, reserved\n vec4 facetProjection; // reference pitch cosine/sine, source units, projected top\n vec4 crownSweep;\n vec4 rightCrownSweep;\n vec4 leftCrownSweep;\n vec4 pavilionSweep;\n vec4 rightPavilionSweep;\n vec4 leftPavilionSweep;\n vec4 appearance; // palette identifier, reserved\n vec4 referenceCrownFlash;\n vec4 referencePavilionFlash;\n};\nstruct Raster {\n vec4 position ;\n vec3 localPosition;\n vec3 normal;\n vec3 worldPosition;\n vec3 facetWeights; // table, crown, pavilion; interpolated across rounded edges\n};\nstruct SparkleVertex { vec4 contours; vec4 material; };\nstruct SparkleRaster {\n vec4 position ;\n vec2 sourcePoint;\n float strength ;\n uint layer ;\n};\nstruct SparkleAnchor { vec4 position; vec4 normal; };\nuniform Uniforms u;\nuniform vec4 planes[17];\nuniform SparkleAnchor anchors[8];\nout vec2 v_sourcePoint;\nflat out float v_strength;\nflat out uint v_layer;\nlayout(location=0) in vec4 a_contours; layout(location=1) in vec4 a_material; uniform uint baseInstance;\n\nvoid main(){\n\n SparkleVertex v = SparkleVertex(a_contours,a_material);\n uint instance=uint(gl_InstanceID)+baseInstance;\n uint layer = uint(v.material.x);\n const float authoringToWorld = 2.0 / 447.9;\n vec3 local = anchors[instance].position.xyz;\n vec3 normal = anchors[instance].normal.xyz;\n if (instance == 0u) {\n float c = cos(u.sparkleHalo.y), s = sin(u.sparkleHalo.y);\n local.xz = vec2(c*local.x + s*local.z, -s*local.x + c*local.z);\n normal.xz = vec2(c*normal.x + s*normal.z, -s*normal.x + c*normal.z);\n }\n if (instance != 0u) { local += normal * 0.008; }\n vec3 worldNormal = (u.model * vec4(normal, 0.0)).xyz;\n float pulse = pow(max(0.0, sin(u.parameters.x * 2.1 + float(instance) * 2.37 + 1.5)), 16.0);\n float front = instance == 0u ? u.sparkleHalo.w : smoothstep(0.15, 0.55, worldNormal.z);\n float strength = front * u.parameters.w;\n vec4 center = u.projection * u.model * vec4(local, 1.0);\n if (u.viewport.w > 0.0) {\n center = vec4(0.0, 0.0, 0.5, 1.0);\n strength = instance == 0u ? u.parameters.w : 0.0;\n }\n float morph = instance == 0u ? u.sparkleShape.y : 0.0;\n vec2 sourcePoint = mix(v.contours.xy, v.contours.zw, morph);\n float groupScale = 1.0;\n vec2 offset = vec2(0.0);\n if (layer == 0u) { groupScale = u.sparkleHalo.x; offset.y = 5.9; }\n if (layer == 1u) { groupScale = u.sparkleShape.w; offset.y = -0.8; }\n if (layer == 2u) { groupScale = u.sparkleShape.z; offset.y = -0.9; }\n if (layer == 3u) { groupScale = 0.309; offset = vec2(0.6, -0.4); }\n float mainEnvelope = u.viewport.w > 0.0 ? 1.0 : u.sparkleHalo.w;\n float scale = instance == 0u ? u.sparkleShape.x * mainEnvelope : (0.632 / 0.75) * pulse;\n vec2 point = (sourcePoint * groupScale + offset) * authoringToWorld * scale;\n SparkleRaster result;\n // Correct the anchor with the gem, but keep the authored flare proportions.\n result.position = center + center.w * vec4(point.x * u.projection[0][0] / u.sparkleHalo.z,\n -point.y * u.projection[1][1], 0.0, 0.0);\n result.sourcePoint = sourcePoint;\n result.strength = strength;\n result.layer = layer;\n gl_Position=result.position; gl_Position.z=gl_Position.z*2.0-gl_Position.w;\nv_sourcePoint=result.sourcePoint;\nv_strength=result.strength;\nv_layer=result.layer;\n\n}\n","#version 300 es\nprecision highp float;\nprecision highp int;\n#define saturate(x) clamp(x,0.0,1.0)\nstruct Vertex { vec4 position; vec4 normal; vec4 surface; };\nstruct Uniforms {\n mat4 model;\n mat4 projection;\n mat4 inverseModel;\n vec4 parameters; // time, refraction, brightness, sparkles\n vec4 viewport; // width, height, optical plane count, unused\n vec4 sparkleShape; // main layer scale, contour morph, core scale, star glow scale\n vec4 sparkleHalo; // circular glow scale, main face rotation, horizontal correction, visibility\n vec4 crownGradient;\n vec4 pavilionGradient;\n vec4 lightSweep; // diagonal position, environment phase, transmission, reserved\n vec4 facetProjection; // reference pitch cosine/sine, source units, projected top\n vec4 crownSweep;\n vec4 rightCrownSweep;\n vec4 leftCrownSweep;\n vec4 pavilionSweep;\n vec4 rightPavilionSweep;\n vec4 leftPavilionSweep;\n vec4 appearance; // palette identifier, reserved\n vec4 referenceCrownFlash;\n vec4 referencePavilionFlash;\n};\nstruct Raster {\n vec4 position ;\n vec3 localPosition;\n vec3 normal;\n vec3 worldPosition;\n vec3 facetWeights; // table, crown, pavilion; interpolated across rounded edges\n};\nstruct SparkleVertex { vec4 contours; vec4 material; };\nstruct SparkleRaster {\n vec4 position ;\n vec2 sourcePoint;\n float strength ;\n uint layer ;\n};\nstruct SparkleAnchor { vec4 position; vec4 normal; };\nuniform Uniforms u;\nuniform vec4 planes[17];\nuniform SparkleAnchor anchors[8];\nin vec2 v_sourcePoint;\nflat in float v_strength;\nflat in uint v_layer;\nfloat radialOpacity(float radius, float first, float middle) {\n if (radius <= first) { return 1.0; }\n if (radius <= middle) { return mix(1.0, 0.5, (radius-first)/(middle-first)); }\n return 0.5 * saturate((1.0-radius)/(1.0-middle));\n}\n\nout vec4 fragColor;\n\nvoid main(){\nSparkleRaster inputData;\ninputData.sourcePoint=v_sourcePoint;\ninputData.strength=v_strength;\ninputData.layer=v_layer;\n\n float alpha = 1.0;\n vec3 color = vec3(1.0);\n if (inputData.layer == 0u) {\n float r = length(inputData.sourcePoint - vec2(-0.5, 0.2)) / 108.5;\n alpha = radialOpacity(r, 0.312, 0.624) * 0.60;\n } else if (inputData.layer == 1u) {\n float r = length(inputData.sourcePoint - vec2(-0.5, 0.9)) / 113.1;\n alpha = radialOpacity(r, 0.297, 0.503) * 0.60;\n color = vec3(0.82, 1.0, 0.902);\n } else if (inputData.layer == 2u) {\n alpha = 0.96;\n } else if (inputData.layer == 3u) {\n float r = saturate(length(inputData.sourcePoint) / length(vec2(176.0, -170.0)));\n alpha = 1.0 - r;\n color = mix(vec3(0.694, 0.969, 1.0), vec3(0.663, 0.957, 1.0), r);\n } else if (inputData.layer == 5u) {\n alpha = radialOpacity(length(inputData.sourcePoint) / length(vec2(228.9, 3.9)), 0.237, 0.623);\n }\n if (uint(u.appearance.x) == 1u) {\n color = inputData.layer == 0u ? vec3(0.635,0.749,1.0) : vec3(1.0);\n // The white source retains only the circular halo, without the extra\n // star-shaped glow used by the blue material.\n if (inputData.layer == 1u) { alpha = 0.0; }\n } else if (uint(u.appearance.x) == 2u) {\n color = inputData.layer == 1u ? vec3(0.82,0.96,1.0) : vec3(1.0);\n }\n alpha *= inputData.strength;\n fragColor = vec4(color * alpha, alpha);\n\n}\n"),[r]=yield Promise.all([Qs(),nl(e,[t,n])]);return function(e,t,n){const{frames:r,planes:o,anchors:i,widths:a,facetProjection:s,camera:c}=t,{diamondProgram:d,sparkleProgram:u,diamond:h,mainSparkle:p,smallSparkles:f}=n,g=c[0],m=new Float32Array(Ds),v=new Float32Array(16),w=new Float32Array(16),y=function(e,t,n){const r=t[1],o=t[2],i=1.52*Math.max(1,1/e)*(n/zs),a=1/o,s=-a/r,l=.12/i;return new Float32Array([1/(e*i),0,0,0,0,1/i,0,0,0,l*s,-a/6,s,0,l*a,.5*a,a])}(1,c,a[0]),b=y[0];function C(t,n,r,o,i,s){x(r);const c=Math.cos(s),m=s+g;S(m,i);const v=function(e,t,n){const r=Math.abs(e-Math.round(e/Vs)*Vs),o=Math.min(90,r*Fs),i=Math.min(89,Math.floor(o)),a=function(e,t,n){const r=e[t],o=e[t+1],i=0===t?0:(o-e[t-1])/2,a=t+2>=e.length?0:(e[t+2]-r)/2;return(((2*(r-o)+i+a)*n+(3*(o-r)-2*i-a))*n+i)*n+r}(n,i,o-i),s=(1-.035*l(Math.sin(2*r),2))*n[0],c=il(Ls((Math.abs(Math.sin(t))-Ks)/(Hs-Ks),0,1));return 1+(1-c)*(s/a-1)}(i,m,a);y[0]=b*v;let w=0,C=-1;for(let e=0;e<4;e++){const t=2*e*Math.PI/4,n=c*Math.cos(i+t);n>C&&(C=n,w=t)}const{lastYaw:k,lastTilt:R}=t,_=void 0===k||void 0===R||o<=0?.596:Math.hypot(Math.atan2(Math.sin(i-k),Math.cos(i-k)),m-R)/o;t.lastYaw=i,t.lastTilt=m;const T=Ls(1-Math.acos(Ls(C,-1,1))/$s,0,1),I=il(Ls((Gs/Math.max(_,.001)-.06)/.34,0,1))*il(T),{x:A,y:O,size:M}=n;e.viewport(A,O,M,M),e.scissor(A,O,M,M),e.clear(e.COLOR_BUFFER_BIT|e.DEPTH_BUFFER_BIT),E(d,M,r,w,v,I),e.disable(e.BLEND),e.enable(e.DEPTH_TEST),e.enable(e.CULL_FACE),e.bindVertexArray(h.vao),e.drawArrays(e.TRIANGLES,0,h.vertexCount),E(u,M,r,w,v,I),e.enable(e.BLEND),e.disable(e.CULL_FACE),e.disable(e.DEPTH_TEST),e.bindVertexArray(p.vao),e.uniform1ui(u.uniforms.baseInstance,0),e.drawArraysInstanced(e.TRIANGLES,0,p.vertexCount,1),e.bindVertexArray(f.vao),e.uniform1ui(u.uniforms.baseInstance,1),e.drawArraysInstanced(e.TRIANGLES,0,f.vertexCount,7)}function x(e){const t=240*e%js,n=Math.floor(t),o=t-n,i=n*Ds;for(let a=0;a{e.uniform4fv(n[t],m,4*r,4)})}return e.depthFunc(e.LEQUAL),e.blendFunc(e.ONE,e.ONE_MINUS_SRC_ALPHA),e.enable(e.SCISSOR_TEST),[d,u].forEach(k),{draw:C}}(e,r,{diamondProgram:rl(e,t),sparkleProgram:rl(e,n),diamond:ol(e,r.vertices,3),mainSparkle:ol(e,r.mainSparkle,2),smallSparkles:ol(e,r.smallSparkles,2)})})}function Qs(){return Zs||(Zs=function(){return p(this,null,function*(){const[e,t,n,r,o,i,a,s,l]=yield Promise.all([Js("vertices"),Js("main"),Js("small"),Js("frames"),Js("planes"),Js("anchors"),Js("widths"),Js("facetProjection"),Js("camera")]);if(60522!==r.length||68!==o.length||64!==i.length||91!==a.length||4!==s.length||3!==l.length)throw new Error("Unexpected diamond model data");return{vertices:e,mainSparkle:t,smallSparkles:n,frames:r,planes:o,anchors:i,widths:a,facetProjection:s,camera:l}})}(),Zs.catch(()=>{Zs=void 0})),Zs}function Js(e){return p(this,null,function*(){const t=`https://s.ton-connect.io/diamond/v1/${e}.bin`,n=yield fetch(t);if(!n.ok)throw new Error(`Cannot load ${t}`);return new Float32Array(yield n.arrayBuffer())})}function el(e,t,n){const r=e.createProgram();return e.attachShader(r,tl(e,e.VERTEX_SHADER,t)),e.attachShader(r,tl(e,e.FRAGMENT_SHADER,n)),e.linkProgram(r),r}function tl(e,t,n){const r=e.createShader(t);return e.shaderSource(r,n),e.compileShader(r),r}function nl(e,t){return p(this,null,function*(){const n=e.getExtension("KHR_parallel_shader_compile");if(n)for(;!t.every(t=>e.getProgramParameter(t,n.COMPLETION_STATUS_KHR));)yield new Promise(e=>requestAnimationFrame(e))})}function rl(e,t){if(!e.getProgramParameter(t,e.LINK_STATUS))throw new Error(e.getProgramInfoLog(t)||"Cannot link diamond shaders");const n={planes:e.getUniformLocation(t,"planes[0]"),baseInstance:e.getUniformLocation(t,"baseInstance")};[...qs,...Bs].forEach(r=>{n[r]=e.getUniformLocation(t,`u.${r}`)});for(let r=0;r<8;r++)["position","normal"].forEach(o=>{const i=`anchors[${r}].${o}`;n[i]=e.getUniformLocation(t,i)});return{program:t,uniforms:n}}function ol(e,t,n){const r=e.createVertexArray();e.bindVertexArray(r),e.bindBuffer(e.ARRAY_BUFFER,e.createBuffer()),e.bufferData(e.ARRAY_BUFFER,t,e.STATIC_DRAW);const o=4*n*4;for(let i=0;i=1&&(d=void 0,null==(t=n.onEnd)||t.call(n))}function T(){return void 0===u||f{const r=1-function(e){const t=e-1;return t*t*(3*t+2)+1}(n);m=e*r,v=t*r}}}function A(t,n){if(Math.abs(m)>10)return;const r=Math.max(1,e.clientWidth/2),o=m,i=v,a=(r-t)*bl()/r,s=(r-n)*bl()/r;d={startTime:f,duration:.22,onUpdate:e=>{const t=1+l(e-1,5);m=Ws(o,a,t),v=Ws(i,s,t)},onEnd:I}}function O(t){0===t.button&&(w=!0,y=!1,d=void 0,b=x=t.clientX,C=S=t.clientY,e.setPointerCapture(t.pointerId))}function M(e){if(w)if(e.buttons){if(!y){if(Math.hypot(e.clientX-b,e.clientY-C)<=8)return;y=!0}m+=.75*(e.clientX-x),v+=(e.clientY-S)*("touch"===e.pointerType?.1:.25),x=e.clientX,S=e.clientY}else N(e)}function N(e){w&&(w=!1,I(),y||"pointerup"!==e.type||A(e.offsetX,e.offsetY))}function P(){clearTimeout(h),E=p,e.style.transform=`scale(${p})`}function L(){e.style.transform="",h=setTimeout(()=>{E=1},200)}function W(){i&&e.isConnected&&!document.hidden?D():j()}function D(){void 0===s&&(c=void 0,r.reset(),s=requestAnimationFrame(R))}function j(){void 0!==s&&(cancelAnimationFrame(s),s=void 0)}function U(){var n;ml=void 0,j(),q(),document.removeEventListener("visibilitychange",W),e.removeEventListener("webglcontextlost",U),e.remove(),null==(n=t.getExtension("WEBGL_lose_context"))||n.loseContext(),null==a||a.onError()}const q=(B=U,Os.add(B),()=>{Os.delete(B)});var B;return document.addEventListener("visibilitychange",W),e.addEventListener("webglcontextlost",U),e.addEventListener("pointerdown",O),e.addEventListener("pointermove",M),e.addEventListener("pointerup",N),e.addEventListener("pointercancel",N),e.addEventListener("touchstart",yl,{passive:!1}),e.addEventListener("pointerenter",P),e.addEventListener("pointerleave",L),Ys(t).then(e=>{i=e,W()}).catch(U),{hasDrawn:()=>g,attach(t,{size:n,hoverScale:r},o){a=o,p=r,u=g?f:void 0,clearTimeout(h),e.style.transform="",E=1,k=n,e.style.width=`${n}px`,e.style.height=`${n}px`,t.appendChild(e),W()}}}()),ml?ml.attach(e,t,n):n.onError())}function wl(e){return Math.exp(-e/fl)-Math.exp(-e/pl)}function yl(e){e.preventDefault()}function bl(){return 30*Math.random()+40}function Cl(e){return e*Math.PI/180}const xl=e=>{const[t,n]=Tr(function(){var e;const t=Vi(),n=!!(null==(e=null==t?void 0:t.matchMedia)?void 0:e.call(t,"(prefers-reduced-motion: reduce)").matches);return!Ms()&&!n}()),[r,o]=Tr((null==ml?void 0:ml.hasDrawn())?"gone":"shown");let i;return Dr(()=>{var r;if(!t()||!i)return;let a;const s={size:e.size,hoverScale:null!=(r=e.hoverScale)?r:1.7};vl(i,s,{onFirstFrame:()=>{o("fading"),a=setTimeout(()=>o("gone"),200)},onError:()=>n(!1)}),jr(()=>clearTimeout(a))}),po(al,{get class(){return e.class},get style(){return{width:`${e.size}px`,height:`${e.size}px`}},get children(){return po(xo,{get when(){return t()},get fallback(){return po(sl,{src:Is,alt:"",draggable:!1})},get children(){return[po(cl,{ref(e){"function"==typeof i?i(e):i=e}}),po(xo,{get when(){return"gone"!==r()},get children(){return po(ll,{src:Is,alt:"",draggable:!1,get style(){return{opacity:"fading"===r()?0:1,transition:"opacity 0.2s linear"}}})}})]}})}})};const Sl=()=>{},kl=(e,t)=>t();const El=e=>e instanceof Element;function Rl(e,t){if(t(e))return e;if("function"==typeof e&&!e.length)return Rl(e(),t);if(Array.isArray(e)){const n=[];for(const r of e){const e=Rl(r,t);e&&(Array.isArray(e)?n.push.apply(n,e):n.push(e))}return n.length?n:null}return null}function _l(e,t=El,n=El){const r=Mr(e),o=Mr(()=>Rl(r(),t));return o.toArray=()=>{const e=o();return Array.isArray(e)?e:e?[e]:[]},o}function Tl(e,t){if(t(e))return e;if("function"==typeof e&&!e.length)return Tl(e(),t);if(Array.isArray(e))for(const n of e){const e=Tl(n,t);if(e)return e}return null}function Il(e,t=El,n=El){const r=Mr(e);return Mr(()=>Tl(r(),t))}function Al(e){return Mr(()=>{const t=e.name||"s";return{enterActive:(e.enterActiveClass||t+"-enter-active").split(" "),enter:(e.enterClass||t+"-enter").split(" "),enterTo:(e.enterToClass||t+"-enter-to").split(" "),exitActive:(e.exitActiveClass||t+"-exit-active").split(" "),exit:(e.exitClass||t+"-exit").split(" "),exitTo:(e.exitToClass||t+"-exit-to").split(" "),move:(e.moveClass||t+"-move").split(" ")}})}function Ol(e){requestAnimationFrame(()=>requestAnimationFrame(e))}function Ml(e,t,n,r){const{onBeforeEnter:o,onEnter:i,onAfterEnter:a}=t;function s(t){t&&t.target!==n||(null==r||r(),n.removeEventListener("transitionend",s),n.removeEventListener("animationend",s),n.classList.remove(...e.enterActive),n.classList.remove(...e.enterTo),null==a||a(n))}null==o||o(n),n.classList.add(...e.enter),n.classList.add(...e.enterActive),queueMicrotask(()=>{if(!n.parentNode)return null==r?void 0:r();null==i||i(n,()=>s())}),Ol(()=>{n.classList.remove(...e.enter),n.classList.add(...e.enterTo),(!i||i.length<2)&&(n.addEventListener("transitionend",s),n.addEventListener("animationend",s))})}function Nl(e,t,n,r){const{onBeforeExit:o,onExit:i,onAfterExit:a}=t;if(!n.parentNode)return null==r?void 0:r();function s(t){t&&t.target!==n||(null==r||r(),n.removeEventListener("transitionend",s),n.removeEventListener("animationend",s),n.classList.remove(...e.exitActive),n.classList.remove(...e.exitTo),null==a||a(n))}null==o||o(n),n.classList.add(...e.exit),n.classList.add(...e.exitActive),null==i||i(n,()=>s()),Ol(()=>{n.classList.remove(...e.exit),n.classList.add(...e.exitTo),(!i||i.length<2)&&(n.addEventListener("transitionend",s),n.addEventListener("animationend",s))})}const Pl={inout:"in-out",outin:"out-in"},Ll=e=>{const t=Al(e);return function(e,t){const n=Lr(e),r=n?[n]:[],{onEnter:o=kl,onExit:i=kl}=t,[a,s]=Tr(t.appear?[]:r),[l]=Hr();let c,d=!1;function u(e,t){if(!e)return t&&t();d=!0,i(e,()=>{Pr(()=>{d=!1,s(t=>t.filter(t=>t!==e)),t&&t()})})}function h(e){const t=c;if(!t)return e&&e();c=void 0,s(e=>[t,...e]),o(t,null!=e?e:Sl)}const p="out-in"===t.mode?e=>d||u(e,h):"in-out"===t.mode?e=>h(()=>u(e)):e=>{u(e),h()};return Ir(t=>{const n=e();return Lr(l)?(l(),t):(n!==t&&(c=n,Pr(()=>Lr(()=>p(t)))),n)},t.appear?void 0:n),a}(Il(()=>e.children),{mode:Pl[e.mode],appear:e.appear,onEnter(n,r){Ml(t(),e,n,r)},onExit(n,r){Nl(t(),e,n,r)}})},Wl=e=>{const t=Al(e);return function(e,t){const n=Lr(e),{onChange:r}=t;let o=new Set(t.appear?void 0:n);const i=new WeakSet,[a,s]=Tr([],{equals:!1}),[l]=Hr(),c=e=>{s(t=>(t.push.apply(t,e),t));for(const t of e)i.delete(t)},d=(e,t,n)=>e.splice(n,0,t);return Mr(t=>{const n=a(),s=e();if(s[fr],Lr(l))return l(),t;if(n.length){const e=t.filter(e=>!n.includes(e));return n.length=0,r({list:e,added:[],removed:[],unchanged:e,finishRemoved:c}),e}return Lr(()=>{const e=new Set(s),n=s.slice(),a=[],l=[],u=[];for(const t of s)(o.has(t)?u:a).push(t);let h=!a.length;for(let r=0;re.children).toArray,{appear:e.appear,onChange({added:n,removed:r,finishRemoved:o,list:i}){const a=t();for(const t of n)Ml(a,e,t);const s=[];for(const e of i)e.isConnected&&(e instanceof HTMLElement||e instanceof SVGElement)&&s.push({el:e,rect:e.getBoundingClientRect()});queueMicrotask(()=>{const e=[];for(const{el:t,rect:n}of s)if(t.isConnected){const r=t.getBoundingClientRect(),o=n.left-r.left,i=n.top-r.top;(o||i)&&(t.style.transform=`translate(${o}px, ${i}px)`,t.style.transitionDuration="0s",e.push(t))}document.body.offsetHeight;for(const t of e){let e=function(n){(n.target===t||/transform$/.test(n.propertyName))&&(t.removeEventListener("transitionend",e),t.classList.remove(...a.move))};t.classList.add(...a.move),t.style.transform=t.style.transitionDuration="",t.addEventListener("transitionend",e)}});for(const t of r)Nl(a,e,t,()=>o([t]))}})};const Dl="androidBackHandler",jl={[Dl]:!0};var Ul=Po('',!1,!0,!1);const ql={left:0,top:90,right:180,bottom:270},Bl=e=>{const t=li();return po(di("svg")` + transform: rotate(${e=>ql[e.svgDirection]}deg); + transition: transform 0.1s ease-in-out; + `,{xmlns:"http://www.w3.org/2000/svg",width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",get svgDirection(){return e.direction||"left"},get children(){var n=Ul();return Ar(()=>Lo(n,"fill",e.fill||t.colors.icon.secondary)),n}})};var zl=Po('');const Fl=e=>{const t=li();return n=zl(),r=n.firstChild,Ar(()=>Lo(r,"fill",e.fill||t.colors.icon.secondary)),n;var n,r},Kl=di.button` + padding: 0; + display: flex; + justify-content: center; + align-items: center; + width: 32px; + height: 32px; + border-radius: 50%; + background-color: ${e=>e.theme.colors.background.tint}; + border: none; + cursor: pointer; + + transition: transform 0.125s ease-in-out; + + ${ps} { + &:hover { + transform: scale(1.04); + } + } + + &:active { + transform: scale(0.96); + } + + ${hs} { + &:active { + transform: scale(0.92); + } + } +`,Hl=e=>{const t=vs(e),n=()=>e.icon||"close";return po(Kl,wo({get class(){return e.class},onClick:()=>e.onClick(),"data-tc-icon-button":"true"},t,{get children(){return[po(xo,{get when(){return!!e.children},get children(){return e.children}}),po(xo,{get when(){return!e.children},get children(){return po(So,{get children(){return[po(ko,{get when(){return"close"===n()},get children(){return po(Fl,{get fill(){return e.fill}})}}),po(ko,{get when(){return"arrow"===n()},get children(){return po(Bl,{get fill(){return e.fill}})}}),po(ko,{get when(){return"question"===n()},get children(){return po(Id,{get fill(){return e.fill}})}}),po(ko,{get when(){return"string"!=typeof n()},get children(){return n()}})]}})}})]}}))},Vl={m:"24px",s:"16px",none:"0"},$l=di.div` + display: flex; + position: fixed; + z-index: 1000; + left: 0; + top: 0; + width: 100%; + height: 100%; + background-color: rgba(0, 0, 0, 0.4); + padding: 20px 0; + overflow-y: auto; + + ${us("mobile")} { + padding-bottom: 0; + } +`,Gl=oi` + box-shadow: + 0 4px 16px rgba(0, 0, 0, 0.08), + 0 16px 64px rgba(0, 0, 0, 0.16); + width: fit-content; + margin: auto; + + ${us("mobile")} { + width: 100%; + height: fit-content; + margin: auto 0 0 0; + } +`,Xl=di.div` + position: relative; + min-height: 100px; + width: 416px; + padding: 44px 56px 24px; + + box-shadow: 0 2px 8px 0 rgba(0, 0, 0, 0.04); + + background-color: ${e=>e.theme.colors.background.primary}; + border-radius: ${e=>Vl[e.theme.borderRadius]}; + + ${us("mobile")} { + width: 100%; + border-radius: ${e=>Vl[e.theme.borderRadius]} + ${e=>Vl[e.theme.borderRadius]} 0 0; + } +`,Zl=di(Hl)` + position: absolute; + right: 16px; + top: 16px; +`,Yl=di.div` + display: flex; + justify-content: space-between; + align-items: center; + padding: 16px 16px 16px 18px; + border-radius: 0 0 ${e=>Vl[e.theme.borderRadius]} + ${e=>Vl[e.theme.borderRadius]}; +`,Ql=di(Hl)` + background-color: ${e=>mi(e.theme.colors.icon.secondary,.12)}; +`;class Jl{constructor(){this.currentTime=0}}const ec=class e{constructor(){this.currentTime=0,this.playbackRate=1,this.startTime=null,this.timeline=new Jl,this.finished=Promise.resolve(this),this.effect=null,this.id="",this.pending=!1,this.playState="finished",this.replaceState="active",this.ready=Promise.resolve(this),this.oncancel=null,this.onfinish=null,this.onremove=null}static create(){return e._instance||(!function(...e){try{console.warn("[TON_CONNECT_UI]",...e)}catch(t){}}("Animation is not supported in this environment: please consider using the `web-animations-js` polyfill to provide a fallback implementation of the Web Animations API."),e._instance=new e),e._instance}cancel(){}finish(){}pause(){}play(){}reverse(){}addEventListener(e,t,n){}dispatchEvent(e){return!1}removeEventListener(e,t,n){}updatePlaybackRate(e){}commitStyles(){}persist(){}};ec._instance=null;let tc=ec;function nc(e,t,n){return"animate"in e?e.animate(t,n):tc.create()}var rc=Po("
");const oc=function(e,t){const n=n=>{var r;return!e.contains(n.target)&&(null==(r=t())?void 0:r())};document.body.addEventListener("click",n),jr(()=>document.body.removeEventListener("click",n))},ic=function(e,t){const n=e=>{var n,r;"Escape"===e.key&&(null==(n=document.activeElement)||n.blur(),null==(r=t())||r())};document.body.addEventListener("keydown",n),jr(()=>document.body.removeEventListener("keydown",n))},ac=function(e,t){const{isEnabled:n,onClose:r}=t();if(!n)return;if(!("android"===Xi().os))return;window.history.pushState(jl,"");const o=e=>{e.preventDefault(),r()};window.addEventListener("popstate",o,{once:!0}),jr(()=>{window.removeEventListener("popstate",o),Ki(()=>{var e;!0===(null==(e=window.history.state)?void 0:e[Dl])&&window.history.back()})})},sc=e=>{const t=li(),n=vs(e);return Or(()=>{e.opened?document.documentElement.scrollHeight!==document.documentElement.clientHeight&&(document.body.style.top=vi(-document.documentElement.scrollTop),document.body.classList.add(pi)):document.body.classList.contains(pi)&&(document.body.classList.remove(pi),document.documentElement.scrollTo({top:-parseFloat(getComputedStyle(document.body).top)}),document.body.style.top="auto")}),po(Ll,{onBeforeEnter:e=>{const t=ds("mobile")?200:100;nc(e,[{opacity:0},{opacity:1}],{duration:t,easing:"ease-out"}),ds("mobile")&&nc(e.firstElementChild,[{transform:"translateY(390px)"},{transform:"translateY(0)"}],{duration:t,easing:"ease-out"})},onExit:(e,t)=>{const n=ds("mobile")?200:100,r=nc(e,[{opacity:1},{opacity:0}],{duration:n});if(ds("mobile")){const o=nc(e.firstElementChild,[{transform:"translateY(0)"},{transform:"translateY(390px)"}],{duration:n});Promise.all([r.finished,o.finished]).then(t)}else r.finished.then(t)},get children(){return po(xo,{get when(){return e.opened},get children(){return po($l,wo({"data-tc-modal":"true"},n,{get children(){var n=rc();return jo(ac,n,()=>({isEnabled:e.enableAndroidBackHandler,onClose:()=>e.onClose()})),jo(ic,n,()=>()=>e.onClose()),jo(oc,n,()=>()=>e.onClose()),Uo(n,po(Xl,{get class(){return e.class},get children(){return[po(Zl,{icon:"close",onClick:()=>e.onClose()}),Mo(()=>e.children)]}}),null),Uo(n,po(xo,{get when(){return e.onClickQuestion&&e.showFooter},get children(){return po(Yl,{get children(){return[po(_d,{}),po(Ql,{get onClick(){return e.onClickQuestion},icon:"question"})]}})}}),null),Ar(()=>Wo(n,xs(Gl,oi` + border-radius: ${Vl[t.borderRadius]}; + background-color: ${t.colors.background.tint}; + + ${us("mobile")} { + border-radius: ${Vl[t.borderRadius]} + ${Vl[t.borderRadius]} 0 0; + } + `))),n}}))}})}})},lc={m:"22px",s:"12px",none:"0"},cc={m:"18px",s:"8px",none:"0"},dc=di.div` + display: grid; + grid-template: 1fr / 1fr 1fr; + width: fit-content; + justify-items: center; + gap: 4px; + + position: relative; + padding: 4px; + border-radius: ${e=>lc[e.theme.borderRadius]}; + + background-color: ${e=>e.theme.colors.background.secondary}; +`,uc=di.div` + position: absolute; + top: 4px; + left: 4px; + + height: calc(100% - 8px); + width: calc(50% - 4px); + + border-radius: ${e=>cc[e.theme.borderRadius]}; + background-color: ${e=>e.theme.colors.background.segment}; + + transform: ${e=>e.right?"translateX(100%)":"translateX(0)"}; + + transition: transform 0.13s ease-in-out; +`,hc=di.input` + display: none; +`,pc=di.label` + padding: 9px 12px; + z-index: 1; + + cursor: ${e=>e.isActive?"default":"pointer"}; + + transition: transform 0.13s ease-in-out; + + &:hover { + transform: ${e=>e.isActive?"none":"scale(1.025)"}; + } + + > * { + ${e=>e.isActive?"":`color: ${e.theme.colors.text.secondary};`} + } +`,fc={m:"16px",s:"12px",none:"0"},gc={m:"12px",s:"8px",none:"0"},mc=di.div` + width: 52px; + height: 52px; + background: transparent; + position: absolute; + right: 0; + bottom: 0; + + display: flex; + align-items: center; + justify-content: center; + transition: transform 0.125s ease-in-out; +`,vc=di.button` + display: flex; + align-items: center; + justify-content: center; + position: relative; + background-color: ${e=>e.theme.colors.background.qr}; + border-radius: ${e=>fc[e.theme.borderRadius]}; + padding: ${vi(24)} 0; + height: ${vi(304)}; + width: 100%; + + overflow: hidden; + cursor: pointer; + border: none; + + ${ps} { + &:hover { + ${mc.class} { + transform: scale(1.04); + } + } + } + + &:active { + ${mc.class} { + transform: scale(0.96); + } + } + + ${hs} { + &:active { + ${mc.class} { + transform: scale(0.92); + } + } + } +`,wc=di.div` + position: relative; + display: flex; + justify-content: center; + align-items: center; + margin: 0 auto; + + > div:first-child { + display: flex; + align-items: center; + justify-content: center; + } + + rect { + fill: transparent; + } + + path { + fill: ${e=>e.theme.colors.constant.black}; + } +`,yc=di.div` + position: absolute; + width: ${vi(60)}; + height: ${vi(60)}; + + display: flex; + align-items: center; + justify-content: center; +`,bc=di.div` + display: flex; +`,Cc=di(ss)` + width: ${e=>vi(e.size)}; + height: ${e=>vi(e.size)}; + border-radius: ${e=>gc[e.theme.borderRadius]}; + background-color: ${e=>e.theme.colors.background.qr}; +`,xc=di.div` + position: absolute; + bottom: 14px; + left: 50%; + transform: translate(-50%, 0); + + display: flex; + gap: 6px; + align-items: center; + border-radius: 18px; + min-width: 126px; + padding: 9px 16px 9px 10px; + + filter: drop-shadow(0px 2px 8px rgba(0, 0, 0, 0.08)); + background-color: ${e=>e.theme.colors.background.segment}; +`;var Sc,kc={exports:{}};var Ec=(Sc||(Sc=1,function(e){var t=function(){var e=function(e,t){var n=e,r=d[t],o=null,i=0,a=null,s=[],l={},c=function(e,t){o=function(e){for(var t=new Array(e),n=0;n=7&&f(e),null==a&&(a=v(n,r,s)),m(a,t)},u=function(e,t){for(var n=-1;n<=7;n+=1)if(!(e+n<=-1||i<=e+n))for(var r=-1;r<=7;r+=1)t+r<=-1||i<=t+r||(o[e+n][t+r]=0<=n&&n<=6&&(0==r||6==r)||0<=r&&r<=6&&(0==n||6==n)||2<=n&&n<=4&&2<=r&&r<=4)},h=function(){for(var e=8;e>r&1);o[Math.floor(r/3)][r%3+i-8-3]=a}for(r=0;r<18;r+=1)a=!e&&1==(t>>r&1),o[r%3+i-8-3][Math.floor(r/3)]=a},g=function(e,t){for(var n=r<<3|t,a=y.getBCHTypeInfo(n),s=0;s<15;s+=1){var l=!e&&1==(a>>s&1);s<6?o[s][8]=l:s<8?o[s+1][8]=l:o[i-15+s][8]=l}for(s=0;s<15;s+=1)l=!e&&1==(a>>s&1),s<8?o[8][i-s-1]=l:s<9?o[8][15-s-1+1]=l:o[8][15-s-1]=l;o[i-8][8]=!e},m=function(e,t){for(var n=-1,r=i-1,a=7,s=0,l=y.getMaskFunction(t),c=i-1;c>0;c-=2)for(6==c&&(c-=1);;){for(var d=0;d<2;d+=1)if(null==o[r][c-d]){var u=!1;s>>a&1)),l(r,c-d)&&(u=!u),o[r][c-d]=u,-1==(a-=1)&&(s+=1,a=7)}if((r+=n)<0||i<=r){r-=n,n=-n;break}}},v=function(e,t,n){for(var r=x.getRSBlocks(e,t),o=S(),i=0;i8*s)throw"code length overflow. ("+o.getLengthInBits()+">"+8*s+")";for(o.getLengthInBits()+4<=8*s&&o.put(0,4);o.getLengthInBits()%8!=0;)o.putBit(!1);for(;!(o.getLengthInBits()>=8*s||(o.put(236,8),o.getLengthInBits()>=8*s));)o.put(17,8);return function(e,t){for(var n=0,r=0,o=0,i=new Array(t.length),a=new Array(t.length),s=0;s=0?h.getAt(p):0}}var f=0;for(d=0;dr)&&(e=r,t=n)}return t}())},l.createTableTag=function(e,t){e=e||2;var n="";n+='',n+="";for(var r=0;r";for(var o=0;o';n+=""}return n+="",n+="
"},l.createSvgTag=function(e,t,n,r){var o={};"object"==typeof arguments[0]&&(e=(o=arguments[0]).cellSize,t=o.margin,n=o.alt,r=o.title),e=e||2,t=void 0===t?4*e:t,(n="string"==typeof n?{text:n}:n||{}).text=n.text||null,n.id=n.text?n.id||"qrcode-description":null,(r="string"==typeof r?{text:r}:r||{}).text=r.text||null,r.id=r.text?r.id||"qrcode-title":null;var i,a,s,c,d=l.getModuleCount()*e+2*t,u="";for(c="l"+e+",0 0,"+e+" -"+e+",0 0,-"+e+"z ",u+=''+w(r.text)+"":"",u+=n.text?''+w(n.text)+"":"",u+='',u+='":t+=">";break;case"&":t+="&";break;case'"':t+=""";break;default:t+=r}}return t};return l.createASCII=function(e,t){if((e=e||1)<2)return function(e){e=void 0===e?2:e;var t,n,r,o,i,a=1*l.getModuleCount()+2*e,s=e,c=a-e,d={"██":"█","█ ":"▀"," █":"▄"," ":" "},u={"██":"▀","█ ":"▀"," █":" "," ":" "},h="";for(t=0;t=c?u[i]:d[i];h+="\n"}return a%2&&e>0?h.substring(0,h.length-a-1)+Array(a+1).join("▀"):h.substring(0,h.length-1)}(t);e-=1,t=void 0===t?2*e:t;var n,r,o,i,a=l.getModuleCount()*e+2*t,s=t,c=a-t,d=Array(e+1).join("██"),u=Array(e+1).join(" "),h="",p="";for(n=0;n>>8),t.push(255&a)):t.push(r)}}return t}};var t,n,r,o,i,a=1,s=2,l=4,c=8,d={L:1,M:0,Q:3,H:2},u=0,h=1,p=2,f=3,g=4,m=5,v=6,w=7,y=(t=[[],[6,18],[6,22],[6,26],[6,30],[6,34],[6,22,38],[6,24,42],[6,26,46],[6,28,50],[6,30,54],[6,32,58],[6,34,62],[6,26,46,66],[6,26,48,70],[6,26,50,74],[6,30,54,78],[6,30,56,82],[6,30,58,86],[6,34,62,90],[6,28,50,72,94],[6,26,50,74,98],[6,30,54,78,102],[6,28,54,80,106],[6,32,58,84,110],[6,30,58,86,114],[6,34,62,90,118],[6,26,50,74,98,122],[6,30,54,78,102,126],[6,26,52,78,104,130],[6,30,56,82,108,134],[6,34,60,86,112,138],[6,30,58,86,114,142],[6,34,62,90,118,146],[6,30,54,78,102,126,150],[6,24,50,76,102,128,154],[6,28,54,80,106,132,158],[6,32,58,84,110,136,162],[6,26,54,82,110,138,166],[6,30,58,86,114,142,170]],n=1335,r=7973,i=function(e){for(var t=0;0!=e;)t+=1,e>>>=1;return t},(o={}).getBCHTypeInfo=function(e){for(var t=e<<10;i(t)-i(n)>=0;)t^=n<=0;)t^=r<5&&(n+=3+i-5)}for(r=0;r=256;)t-=255;return e[t]}};return r}();function C(e,t){if(void 0===e.length)throw e.length+"/"+t;var n=function(){for(var n=0;n>>7-t%8&1)},put:function(e,t){for(var r=0;r>>t-r-1&1))},getLengthInBits:function(){return t},putBit:function(n){var r=Math.floor(t/8);e.length<=r&&e.push(0),n&&(e[r]|=128>>>t%8),t+=1}};return n},k=function(e){var t=a,n=e,r={getMode:function(){return t},getLength:function(e){return n.length},write:function(e){for(var t=n,r=0;r+2>>8&255)+(255&r),e.put(r,13),n+=2}if(n>>8)},writeBytes:function(e,n,r){n=n||0,r=r||e.length;for(var o=0;o0&&(t+=","),t+=e[n];return t+="]"}};return t},I=function(e){var t=e,n=0,r=0,o=0,i={read:function(){for(;o<8;){if(n>=t.length){if(0==o)return-1;throw"unexpected end of file./"+o}var e=t.charAt(n);if(n+=1,"="==e)return o=0,-1;e.match(/^\s$/)||(r=r<<6|a(e.charCodeAt(0)),o+=6)}var i=r>>>o-8&255;return o-=8,i}},a=function(e){if(65<=e&&e<=90)return e-65;if(97<=e&&e<=122)return e-97+26;if(48<=e&&e<=57)return e-48+52;if(43==e)return 62;if(47==e)return 63;throw"c:"+e};return i},A=function(e,t,n){for(var r=function(e,t){var n=e,r=t,o=new Array(e*t),i={setPixel:function(e,t,r){o[t*n+e]=r},write:function(e){e.writeString("GIF87a"),e.writeShort(n),e.writeShort(r),e.writeByte(128),e.writeByte(0),e.writeByte(0),e.writeByte(0),e.writeByte(0),e.writeByte(0),e.writeByte(255),e.writeByte(255),e.writeByte(255),e.writeString(","),e.writeShort(0),e.writeShort(0),e.writeShort(n),e.writeShort(r),e.writeByte(0);var t=a(2);e.writeByte(2);for(var o=0;t.length-o>255;)e.writeByte(255),e.writeBytes(t,o,255),o+=255;e.writeByte(t.length-o),e.writeBytes(t,o,t.length-o),e.writeByte(0),e.writeString(";")}},a=function(e){for(var t=1<>>t!=0)throw"length over";for(;c+t>=8;)l.writeByte(255&(e<>>=8-c,d=0,c=0;d|=e<0&&l.writeByte(d)}});h.write(t,r);var p=0,f=String.fromCharCode(o[p]);for(p+=1;p=6;)i(e>>>t-6),t-=6},o.flush=function(){if(t>0&&(i(e<<6-t),e=0,t=0),n%3!=0)for(var o=3-n%3,a=0;a>6,128|63&r):r<55296||r>=57344?t.push(224|r>>12,128|r>>6&63,128|63&r):(n++,r=65536+((1023&r)<<10|1023&e.charCodeAt(n)),t.push(240|r>>18,128|r>>12&63,128|r>>6&63,128|63&r))}return t}(e)},e.exports=t}(kc)),kc.exports);const Rc=f(Ec);function _c(e){return p(this,null,function*(){try{if(!(null==navigator?void 0:navigator.clipboard))throw new Ei("Clipboard API not available");return yield navigator.clipboard.writeText(e)}catch(t){}!function(e){const t=document.createElement("textarea");t.value=e,t.style.top="0",t.style.left="0",t.style.position="fixed",document.body.appendChild(t),t.focus(),t.select();try{document.execCommand("copy")}finally{document.body.removeChild(t)}}(e)})}function Tc(e,t,n){const r=e.getModuleCount(),o=r*t,i=(e,t)=>e<7&&(t<7||t>=r-7)||e>=r-7&&t<7,a=(t,o)=>t>=0&&o>=0&&t{if(!n)return!1;const r=n.size/2,o=n.start+r;return l(Math.abs((t+.5-o)/r),4)+l(Math.abs((e+.5-o)/r),4)<=1})(t,o)&&e.isDark(t,o),s=(e,t,n,r)=>a(e+n,t)||a(e,t+r)?0:.5,c=[];for(let l=0;lc.push(function(e,t){return Ac(e,t,7,2.4)+Ac(e+1,t+1,5,1.4,!0)+Ac(e+2,t+2,3,1.1)}(e,t))),``}function Ic(e,t,n,r){const o=.5;return`M${Mc(e)} ${Mc(t)}L${Mc(e+n*o)} ${Mc(t)}C${Mc(e+.14*n)} ${Mc(t)} ${Mc(e)} ${Mc(t+.14*r)} ${Mc(e)} ${Mc(t+r*o)}Z`}function Ac(e,t,n,r,o=!1){return Oc(e,t,n,n,{topLeft:r,topRight:r,bottomRight:r,bottomLeft:r},o)}function Oc(e,t,n,r,o,i=!1){const a=e+n,s=t+r,l=[[a,t,1,0,o.topRight],[a,s,0,1,o.bottomRight],[e,s,-1,0,o.bottomLeft],[e,t,0,-1,o.topLeft]],c=i?function(e){return[...e].reverse().map(([e,t,n,r,o])=>[e,t,- -r,-n,o])}(l):l;let d="";return c.forEach(([e,t,n,r,o],a)=>{const s=i?r:-r,l=i?-n:n,c=e-n*o,u=t-r*o,h=e+s*o,p=t+l*o;if(d+=`${0===a?"M":"L"}${Mc(c)} ${Mc(u)}`,o>0){const e=.72*o;d+=`C${Mc(c+n*e)} ${Mc(u+r*e)} ${Mc(h-s*e)} ${Mc(p-l*e)} ${Mc(h)} ${Mc(p)}`}}),`${d}Z`}function Mc(e){return String(Math.round(1e3*e)/1e3)}var Nc=Po("
");const Pc=e=>{let t,n,r;const[o,i]=Tr(!1),a=Gr(()=>e.logo),[s,l]=Tr(48);Or(()=>{const o=Rc(0,"L");o.addData(e.sourceUrl),o.make();const i=4*o.getModuleCount(),a=Math.round(256/i*1e5)/1e5;let s;if(r){const e=4*Math.ceil(60/(4*a)),t=4*Math.ceil((i-e)/8);r.style.top=vi(t),r.style.left=vi(t),r.style.height=vi(e),r.style.width=vi(e),s={start:t/4,size:e/4},l(Math.round(48/a))}t.innerHTML=Tc(o,4,s),n.style.transform=`scale(${a})`});let c=null;return po(vc,{get class(){return e.class},onClick:()=>{i(!0),_c(e.sourceUrl),null!=c&&clearTimeout(c),c=setTimeout(()=>i(!1),1500)},get children(){return[po(wc,{ref(e){"function"==typeof n?n(e):n=e},get children(){return[(n=Nc(),"function"==typeof t?jo(t,n):t=n,n),po(xo,{get when(){return e.imageUrl||a()},get children(){return po(yc,{ref(e){"function"==typeof r?r(e):r=e},get children(){return po(xo,{get when(){return a()},get fallback(){return po(Cc,{get src(){return e.imageUrl},alt:"",get size(){return s()}})},get children(){return po(bc,{onClick:e=>e.stopPropagation(),get children(){return a()}})}})}})}})];var n}}),po(Ll,{onBeforeEnter:e=>{nc(e,[{opacity:0,transform:"translate(-50%, 44px)"},{opacity:1,transform:"translate(-50%, 0)"}],{duration:150,easing:"ease-out"})},onExit:(e,t)=>{nc(e,[{opacity:1,transform:"translate(-50%, 0)"},{opacity:0,transform:"translate(-50%, 44px)"}],{duration:150,easing:"ease-out"}).finished.then(()=>{t()})},get children(){return po(xo,{get when(){return o()&&!e.disableCopy},get children(){return po(xc,{get children(){return[po(vd,{size:"xs"}),po(qc,{translationKey:"common.linkCopied",children:"Link Copied"})]}})}})}}),po(xo,{get when(){return!e.disableCopy},get children(){return po(mc,{get children(){return po(Yd,{})}})}})]}})};var Lc=(e,t,n)=>{const r=t.trim().split(".").reduce((e,t)=>e?e[t]:void 0,e);return void 0!==r?r:n},Wc=(e={},t=(navigator.language in e?navigator.language:Object.keys(e)[0]))=>{const[n,r]=Tr(t),[o,i]=$a(e);return[(e,t,r)=>{const i=Lc(o[n()],e,r||"");return"function"==typeof i?i(t):"string"==typeof i?((e,t,n=/{{(.*?)}}/g)=>e.replace(n,(e,n)=>Lc(t,n,"")))(i,t||{}):i},{add(e,t){i(e,e=>Object.assign(e||{},t))},locale:e=>e?r(e):n(),dict:e=>Lc(o,e)}]},Dc=Vr({}),jc=()=>$r(Dc);const Uc=di.div` + font-style: normal; + font-weight: ${e=>e.fontWeight}; + font-size: ${e=>e.fontSize}; + line-height: ${e=>e.lineHeight}; + + color: ${e=>e.color}; +`,qc=e=>{const t=li(),[n]=jc();let r;const o=wo({fontSize:"14px",fontWeight:"510",lineHeight:"130%"},e);return Or(()=>{r&&"unset"!==o.cursor&&"pointer"!==getComputedStyle(r).cursor&&(r.style.cursor="default")}),po(Uc,{get fontSize(){return o.fontSize},get fontWeight(){return o.fontWeight},get lineHeight(){return o.lineHeight},get color(){return e.color||t.colors.text.primary},get class(){return o.class},ref(e){"function"==typeof r?r(e):r=e},"data-tc-text":"true",get children(){var e;return Mo(()=>!!o.translationKey)()?n(o.translationKey,o.translationValues,null==(e=o.children)?void 0:e.toString()):o.children}})},Bc=di.div` + position: relative; + + &::after { + content: ''; + display: block; + position: absolute; + top: 0; + bottom: 0; + left: 0; + right: 0; + border: 0.5px solid rgba(0, 0, 0, 0.08); + border-radius: inherit; + } +`,zc=di(ss)` + width: 100%; + height: 100%; + border-radius: inherit; +`,Fc=e=>po(Bc,{get class(){return e.class},get children(){return[po(zc,{get src(){return e.src}}),Mo(()=>e.badge)]}}),Kc={m:"16px",s:"12px",none:"0"},Hc={m:"6px",s:"6px",none:"0"},Vc=di.ul` + display: flex; + gap: 0; + width: 100%; + overflow-x: auto; + padding: 8px 12px 16px 12px; + margin: 0; + list-style: none; + flex-wrap: nowrap; + + &&::-webkit-scrollbar { + display: none; + } + -ms-overflow-style: none; + scrollbar-width: none; + + > li { + display: flex; + flex: 1; + min-width: 78px; + height: fit-content; + } + + > li > button { + width: 100%; + } +`,$c=di.button` + position: relative; + cursor: pointer; + border: none; + background-color: unset; + padding: 8px 4px; + min-width: 78px; + display: flex; + flex-direction: column; + align-items: center; + + transition: transform 0.125s ease-in-out; + + ${ps} { + &:hover { + transform: scale(1.04); + } + } + + &:active { + transform: scale(0.96); + } + + ${hs} { + &:active { + transform: scale(0.92); + } + } +`,Gc=di(Fc)` + width: 60px; + height: 60px; + border-radius: ${e=>Kc[e.theme.borderRadius]}; + margin-bottom: 8px; + position: relative; +`,Xc=di(ss)` + position: absolute; + right: -6px; + bottom: -6px; + width: 24px; + height: 24px; + border-radius: ${e=>Hc[e.theme.borderRadius]}; + box-shadow: 0 2px 8px 0 rgba(0, 0, 0, 0.08); +`,Zc=di(qc)` + max-width: 90px; + font-weight: 510; + white-space: nowrap; + text-overflow: ellipsis; + overflow: hidden; + + ${us("mobile")} { + max-width: 80px; + } +`,Yc=di(qc)` + font-weight: ${e=>e.colorPrimary?"510":"400"}; + max-width: 90px; + white-space: nowrap; + text-overflow: ellipsis; + overflow: hidden; + color: ${e=>e.colorPrimary?e.theme.colors.text.primary:e.theme.colors.text.secondary}; + + ${us("mobile")} { + max-width: 80px; + } +`;function Qc(e){return"jsBridgeKey"in e?u(d({},e),{injected:ur.isWalletInjected(e.jsBridgeKey),embedded:ur.isInsideWalletBrowser(e.jsBridgeKey)}):e}function Jc(e,t){var n,r,o,i;return t?((null==(n=t.includeWallets)?void 0:n.length)&&(r="name",o=e,i=t.includeWallets.map(Qc),e=o.map(e=>{const t=i.find(t=>t[r]===e[r]);return i=i.filter(t=>t[r]!==e[r]),void 0===t?e:t}).concat(i)),e):e}function ed(e){return e.platforms.some(e=>["macos","linux","windows"].includes(e))}function td(e){return e.platforms.some(e=>["ios","android"].includes(e))}function nd(e){return e.platforms.some(e=>["chrome","firefox","safari"].includes(e))}function rd(e,t){return!!t&&(e.name.toLowerCase()===t.toLowerCase()||e.appName.toLowerCase()===t.toLowerCase())}var od=Po("
");const id=e=>{let t=null;const n=()=>{const e=null==t?void 0:t.querySelector("div");if(e&&e.scrollWidth>e.clientWidth){let t=0;const n=-.4,r=.05;for(;e.scrollWidth>e.clientWidth&&t>=n;)t-=r,e.style.letterSpacing=`${t}px`;0!==t&&(t-=r,e.style.letterSpacing=`${t}px`)}},r=()=>function(e){const t=/^(.+?)\s*\(([^()]+)\)$/.exec(e);return(null==t?void 0:t[1])&&t[2]?{name:t[1],note:t[2]}:{name:e}}(e.name),o=()=>{var t;return null!=(t=e.secondLine)?t:r().note};return Dr(()=>n()),Or(()=>{n()}),po($c,{get class(){return e.class},onClick:()=>e.onClick(),"data-tc-wallet-item":"true",get children(){return[Mo(()=>Mo(()=>"string"==typeof e.icon)()?po(Gc,{get src(){return e.icon},get badge(){return Mo(()=>!!e.badgeUrl)()&&po(Xc,{get src(){return e.badgeUrl}})}}):e.icon),(n=od(),jo(e=>t=e,n),Uo(n,po(Zc,{get children(){return r().name}})),n),Mo(()=>Mo(()=>!!o())()&&po(Yc,{get colorPrimary(){return void 0!==e.secondLine&&(null==(t=e.secondLineColorPrimary)||t);var t},get children(){return o()}}))];var n}})},ad=di.h1` + font-style: normal; + font-weight: 590; + font-size: 20px; + line-height: 28px; + + text-align: center; + + color: ${e=>e.theme.colors.text.primary}; + + margin-top: 0; + margin-bottom: 0; + + cursor: default; +`,sd=e=>{const[t]=jc();return po(ad,{get class(){return e.class},"data-tc-h1":"true",get children(){var n;return Mo(()=>!!e.translationKey)()?t(e.translationKey,e.translationValues,null==(n=e.children)?void 0:n.toString()):e.children}})},ld=di.h2` + font-style: normal; + font-weight: 400; + font-size: 16px; + line-height: 22px; + + text-align: center; + + color: ${e=>e.theme.colors.text.secondary}; + + margin-top: 0; + margin-bottom: 32px; + + cursor: default; +`,cd=e=>{const[t]=jc();return po(ld,{get class(){return e.class},"data-tc-h2":"true",get children(){var n;return Mo(()=>!!e.translationKey)()?t(e.translationKey,e.translationValues,null==(n=e.children)?void 0:n.toString()):e.children}})},dd=di.h3` + font-style: normal; + font-weight: 510; + font-size: 16px; + line-height: 20px; + + color: ${e=>e.theme.colors.text.primary}; + + margin-top: 0; + margin-bottom: 0; + + cursor: default; +`,ud=e=>{const[t]=jc();return po(dd,{"data-tc-h3":"true",get class(){return e.class},get children(){var n;return Mo(()=>!!e.translationKey)()?t(e.translationKey,e.translationValues,null==(n=e.children)?void 0:n.toString()):e.children}})};var hd=Po('');const pd=e=>{const t=li();return n=hd(),r=n.firstChild,Ar(()=>Lo(r,"fill",e.fill||t.colors.icon.primary)),n;var n,r};var fd=Po(''),gd=Po(''),md=Po('');const vd=e=>{const t=li(),n=()=>e.size||"s",r=()=>e.fill||t.colors.icon.success;return Mo(()=>{return Mo(()=>"xs"===n())()?(d=fd(),u=d.firstChild.firstChild,h=u.nextSibling,Ar(n=>{var o=e.class,i=r(),a=t.colors.constant.white;return o!==n.e&&Lo(d,"class",n.e=o),i!==n.t&&Lo(u,"fill",n.t=i),a!==n.a&&Lo(h,"stroke",n.a=a),n},{e:void 0,t:void 0,a:void 0}),d):Mo(()=>"s"===n())()?(s=gd(),l=s.firstChild,c=l.nextSibling,Ar(n=>{var o=e.class,i=r(),a=t.colors.constant.white;return o!==n.e&&Lo(s,"class",n.e=o),i!==n.t&&Lo(l,"fill",n.t=i),a!==n.a&&Lo(c,"fill",n.a=a),n},{e:void 0,t:void 0,a:void 0}),s):(o=md(),i=o.firstChild,a=i.nextSibling,Ar(n=>{var s=e.class,l=r(),c=t.colors.constant.white;return s!==n.e&&Lo(o,"class",n.e=s),l!==n.t&&Lo(i,"fill",n.t=l),c!==n.a&&Lo(a,"fill",n.a=c),n},{e:void 0,t:void 0,a:void 0}),o);var o,i,a,s,l,c,d,u,h})};var wd=Po(''),yd=Po(''),bd=Po('');const Cd=e=>{const t=li(),n=()=>e.size||"m",r=()=>e.fill||t.colors.icon.error;return Mo(()=>{return Mo(()=>"m"===n())()?(d=wd(),u=d.firstChild,h=u.nextSibling,Ar(n=>{var o=e.class,i=r(),a=t.colors.constant.white;return o!==n.e&&Lo(d,"class",n.e=o),i!==n.t&&Lo(u,"fill",n.t=i),a!==n.a&&Lo(h,"fill",n.a=a),n},{e:void 0,t:void 0,a:void 0}),d):Mo(()=>"s"===n())()?(s=yd(),l=s.firstChild,c=l.nextSibling,Ar(n=>{var o=e.class,i=r(),a=t.colors.constant.white;return o!==n.e&&Lo(s,"class",n.e=o),i!==n.t&&Lo(l,"fill",n.t=i),a!==n.a&&Lo(c,"stroke",n.a=a),n},{e:void 0,t:void 0,a:void 0}),s):(o=bd(),i=o.firstChild,a=i.nextSibling,Ar(n=>{var s=e.class,l=r(),c=t.colors.constant.white;return s!==n.e&&Lo(o,"class",n.e=s),l!==n.t&&Lo(i,"fill",n.t=l),c!==n.a&&Lo(a,"fill",n.a=c),n},{e:void 0,t:void 0,a:void 0}),o);var o,i,a,s,l,c,d,u,h})};var xd=Po(''),Sd=Po(''),kd=Po('');const Ed=e=>{const t=li(),n=()=>e.size||"xs",r=()=>e.fill||t.colors.icon.tertiary,o=oi` + animation: ${ii` + 0% { + transform: rotate(0deg); + } + 100% { + transform: rotate(360deg); + } + `} 1s linear infinite; + `;return Mo(()=>{return Mo(()=>"xs"===n())()?(l=xd(),c=l.firstChild,Ar(t=>{var n=xs(o,e.class),i=r();return n!==t.e&&Lo(l,"class",t.e=n),i!==t.t&&Lo(c,"fill",t.t=i),t},{e:void 0,t:void 0}),l):Mo(()=>"s"===n())()?(a=Sd(),s=a.firstChild,Ar(t=>{var n=xs(o,e.class),i=r();return n!==t.e&&Lo(a,"class",t.e=n),i!==t.t&&Lo(s,"fill",t.t=i),t},{e:void 0,t:void 0}),a):(t=kd(),i=t.firstChild,Ar(n=>{var a=xs(o,e.class),s=r();return a!==n.e&&Lo(t,"class",n.e=a),s!==n.t&&Lo(i,"stroke",n.t=s),n},{e:void 0,t:void 0}),t);var t,i,a,s,l,c})};var Rd=Po('');const _d=()=>{const e=li();return t=Rd(),n=t.firstChild.nextSibling.nextSibling,Ar(()=>Lo(n,"fill",e.theme===Zo.DARK?e.colors.constant.white:e.colors.constant.black)),t;var t,n};var Td=Po('');const Id=e=>{const t=li();return n=Td(),r=n.firstChild,Ar(()=>Lo(r,"fill",e.fill||t.colors.icon.secondary)),n;var n,r};var Ad=Po('');const Od=e=>{const t=li();return n=Ad(),r=n.firstChild,Ar(()=>Lo(r,"fill",e.fill||t.colors.icon.primary)),n;var n,r};var Md=Po('');const Nd=e=>{const t=li();return n=Md(),r=n.firstChild,Ar(()=>Lo(r,"fill",e.fill||t.colors.icon.primary)),n;var n,r};var Pd=Po('');const Ld=e=>{const t=li();return n=Pd(),r=n.firstChild,Ar(()=>Lo(r,"fill",e.fill||t.colors.icon.primary)),n;var n,r};var Wd=Po('');const Dd=e=>{const t=li();return n=Wd(),r=n.firstChild.firstChild,Ar(()=>Lo(r,"fill",e.fill||t.colors.accent)),n;var n,r};var jd=Po('');const Ud=e=>{const t=li();return n=jd(),r=n.firstChild,Ar(()=>Lo(r,"fill",e.fill||t.colors.accent)),n;var n,r};var qd=Po('');const Bd=e=>{const t=li();return n=qd(),r=n.firstChild.firstChild,Ar(()=>Lo(r,"fill",e.fill||t.colors.accent)),n;var n,r};var zd=Po('');const Fd=e=>{const t=li();return n=zd(),r=n.firstChild,Ar(o=>{var i=e.class,a=e.fill||t.colors.icon.secondary;return i!==o.e&&Lo(n,"class",o.e=i),a!==o.t&&Lo(r,"fill",o.t=a),o},{e:void 0,t:void 0}),n;var n,r};var Kd=Po('');const Hd=e=>{const t=li();return n=Kd(),r=n.firstChild,Ar(o=>{var i=e.class,a=e.fill||t.colors.icon.secondary;return i!==o.e&&Lo(n,"class",o.e=i),a!==o.t&&Lo(r,"fill",o.t=a),o},{e:void 0,t:void 0}),n;var n,r};var Vd=Po('');const $d=e=>{const t=li();return n=Vd(),r=n.firstChild,Ar(o=>{var i=e.class,a=e.fill||t.colors.icon.secondary;return i!==o.e&&Lo(n,"class",o.e=i),a!==o.t&&Lo(r,"fill",o.t=a),o},{e:void 0,t:void 0}),n;var n,r};var Gd=Po('');const Xd=e=>{const t=li();return n=Gd(),r=n.firstChild,Ar(o=>{var i=e.class,a=e.fill||t.colors.constant.white;return i!==o.e&&Lo(n,"class",o.e=i),a!==o.t&&Lo(r,"fill",o.t=a),o},{e:void 0,t:void 0}),n;var n,r};var Zd=Po('');const Yd=e=>{const t=li(),n=()=>e.fill||t.colors.icon.secondary;return r=Zd(),o=r.firstChild,Ar(e=>{var t=n(),i=n();return t!==e.e&&Lo(r,"fill",e.e=t),i!==e.t&&Lo(o,"fill",e.t=i),e},{e:void 0,t:void 0}),r;var r,o};var Qd=Po('');const Jd=e=>{const t=li();return n=Qd(),r=n.firstChild,Ar(()=>Lo(r,"fill",e.fill||t.colors.icon.secondary)),n;var n,r},eu={m:"16px",s:"12px",none:"0"},tu={m:"6px",s:"6px",none:"0"},nu=di.div` + width: 60px; + height: 60px; + padding: 8px; + margin-bottom: 8px; + border-radius: ${e=>eu[e.theme.borderRadius]}; + background-color: ${e=>e.theme.colors.background.tint}; + display: grid; + grid-template: 1fr 1fr / 1fr 1fr; + gap: 4px; +`,ru=di(Fc)` + width: 20px; + height: 20px; + border-radius: ${e=>tu[e.theme.borderRadius]}; +`,ou=e=>po(id,{get name(){return e.labelLine1},get secondLine(){return e.labelLine2},get icon(){return po(nu,{get children(){return po(Co,{each:[0,1,2,3],children:t=>po(ru,{get src(){return e.images[t]}})})}})},onClick:()=>e.onClick()}),iu="telegram",au="gramwallet";const su=e=>{const[t]=jc();return po(id,{get icon(){return e.wallet.imageUrl},get name(){return e.wallet.name},get secondLine(){return"isPreferred"in e.wallet&&e.wallet.isPreferred?t("walletItem.recent",{},"Recent"):e.wallet.appName===au?t("walletItem.new",{},"New"):"type"in(n=e.wallet)&&"wallet-connect"===n.type||!le(e.wallet)?void 0:t("walletItem.installed",{},"Installed");var n},secondLineColorPrimary:!1,onClick:()=>e.onClick(),get class(){return e.class}})},lu=di.div` + width: 100%; + overflow-y: auto; + max-height: ${e=>e.maxHeight}; + + scrollbar-width: none; + &&::-webkit-scrollbar { + display: none; + } + + &&::-webkit-scrollbar-track { + background: transparent; + } + + &&::-webkit-scrollbar-thumb { + display: none; + } +`,cu=di.div` + height: 1px; + margin: 0 -24px; + width: calc(100% + 48px); + opacity: 0.08; + background: ${e=>e.isShown?e.theme.colors.icon.secondary:"transparent"}; + transition: background 0.15s ease-in-out; + + ${us("mobile")} { + width: 100%; + margin: 0; + } +`,[du,uu]=Tr((null==(t=Vi())?void 0:t.innerHeight)||0);Vi()&&window.addEventListener("resize",()=>uu(window.innerHeight));const[hu,pu]=Tr(ds("mobile")),fu=()=>pu(ds("mobile"));Vi()&&(window.addEventListener("resize",()=>fu()),window.addEventListener("load",()=>fu(),{once:!0}));const gu=e=>{const[t,n]=Tr(!1),r=()=>void 0!==e.maxHeight?`${e.maxHeight}px`:du()-(hu()?150:200)+"px";return[po(cu,{get isShown(){return t()}}),po(lu,{get maxHeight(){return r()},onScroll:e=>{n(e.target.scrollTop>0)},get class(){return e.class},get children(){return e.children}})]},mu=di.a` + display: block; + text-decoration: unset; +`,vu=e=>po(mu,wo({get href(){return e.href},get target(){return e.blank?"_blank":"_self"},get class(){return e.class}},()=>e.blank?{rel:"noreferrer noopener"}:{},{get children(){return e.children}})),wu=Vr();var yu=Po('');const bu=e=>{const t=li();return n=yu(),r=n.firstChild,Ar(o=>{var i=e.class,a=e.fill||t.colors.icon.primary;return i!==o.e&&Lo(n,"class",o.e=i),a!==o.t&&Lo(r,"fill",o.t=a),o},{e:void 0,t:void 0}),n;var n,r};var Cu=Po('');const xu=e=>{const t=li(),n=()=>e.fill||t.colors.icon.primary;return r=Cu(),o=r.firstChild,i=o.nextSibling,Ar(e=>{var t=n(),r=n();return t!==e.e&&Lo(o,"fill",e.e=t),r!==e.t&&Lo(i,"fill",e.t=r),e},{e:void 0,t:void 0}),r;var r,o,i},Su={m:"8px",s:"4px",none:"0"},ku={m:"16px",s:"8px",none:"0"},Eu=di.div` + width: 256px; + box-shadow: 0 4px 24px rgba(0, 0, 0, 0.16); + border-radius: ${e=>ku[e.theme.borderRadius]}; + + background-color: ${e=>e.theme.colors.background.primary} + + color: ${e=>e.theme.colors.text.primary} +`,Ru=di.ul` + background-color: ${e=>e.theme.colors.background.primary}; + padding: 8px; +`,_u=di.button` + display: flex; + align-items: center; + gap: 8px; + height: 40px; + padding-left: 8px; + width: 100%; + + background-color: ${e=>e.theme.colors.background.primary}; + border: none; + border-radius: ${e=>Su[e.theme.borderRadius]}; + cursor: pointer; + + transition: + background-color, + transform 0.1s ease-in-out; + + &:hover { + background-color: ${e=>e.theme.colors.background.secondary}; + } + + &:active { + transform: scale(0.96); + } +`;var Tu=Po("
  • ");const Iu=e=>po(qc,{get translationKey(){return e.translationKey},fontSize:"15px",fontWeight:"590",get children(){return e.children}}),Au={m:"16px",s:"8px",none:"0"},Ou=di.div` + width: 256px; + padding: 12px 16px; + display: flex; + gap: 9px; + + background-color: ${e=>e.theme.colors.background.primary}; + box-shadow: 0 4px 24px rgba(0, 0, 0, 0.16); + border-radius: ${e=>Au[e.theme.borderRadius]}; +`,Mu=di.div` + width: 192px; + + > h3 { + font-size: 15px; + } +`,Nu=di(qc)` + margin-top: 4px; + color: ${e=>e.theme.colors.text.secondary}; +`,Pu=e=>{const t=vs(e);return po(Ou,wo({get class(){return e.class},"data-tc-notification":"true"},t,{get children(){return[po(Mu,{get children(){return[po(ud,{get translationKey(){return e.header.translationKey},get translationValues(){return e.header.translationValues},get children(){return e.children}}),po(xo,{get when(){return e.text},get children(){return po(Nu,{get translationKey(){return e.text.translationKey},get translationValues(){return e.text.translationValues}})}})]}}),Mo(()=>e.icon)]}}))},Lu=di(Ed)` + align-self: center; +`,Wu=e=>{const t=$r(wu),[n]=jc();return po(Pu,{get header(){return{translationKey:"notifications.confirmTransaction.header",translationValues:{name:t.wallet&&"name"in t.wallet?t.wallet.name:n("common.yourWallet",{},"Your wallet")}}},get class(){return e.class},get icon(){return po(Lu,{})},"data-tc-notification-confirm-transaction":"true",children:"Confirm transaction in your wallet"})},Du=e=>{const t=$r(wu),[n]=jc();return po(Pu,{get header(){return{translationKey:"notifications.confirmSignData.header",translationValues:{name:t.wallet&&"name"in t.wallet?t.wallet.name:n("common.yourWallet",{},"Your wallet")}}},get class(){return e.class},get icon(){return po(Lu,{})},"data-tc-notification-confirm-sign-data":"true",children:"Confirm data signing in your wallet"})},ju=e=>{const t=$r(wu),[n]=jc();return po(Pu,{get header(){return{translationKey:"notifications.confirmSignMessage.header",translationValues:{name:t.wallet&&"name"in t.wallet?t.wallet.name:n("common.yourWallet",{},"Your wallet")}}},get class(){return e.class},get icon(){return po(Lu,{})},"data-tc-notification-confirm-sign-message":"true",children:"Confirm message signing in your wallet"})},Uu=di(Cd)` + margin-top: 2px; +`,qu=e=>po(Pu,{header:{translationKey:"notifications.transactionCanceled.header"},text:{translationKey:"notifications.transactionCanceled.text"},get icon(){return po(Uu,{size:"xs"})},get class(){return e.class},"data-tc-notification-tx-cancelled":"true",children:"Transaction cancelled"}),Bu=di(vd)` + margin-top: 2px; +`,zu=e=>po(Pu,{header:{translationKey:"notifications.transactionSent.header"},text:{translationKey:"notifications.transactionSent.text"},get icon(){return po(Bu,{})},get class(){return e.class},"data-tc-notification-tx-sent":"true",children:"Transaction sent"}),Fu=oi` + transform: translateY(-8px); + margin-bottom: 12px; +`,Ku={timeout:4500},[Hu,Vu]=Tr(null);const $u=di(Cd)` + margin-top: 2px; +`,Gu=e=>po(Pu,{header:{translationKey:"notifications.signDataCanceled.header"},get icon(){return po($u,{size:"xs"})},get class(){return e.class},"data-tc-notification-sign-data-cancelled":"true",children:"Sign data canceled"}),Xu=e=>po(Pu,{header:{translationKey:"notifications.dataSigned.header"},get icon(){return po(Bu,{})},get class(){return e.class},"data-tc-notification-data-signed":"true",children:"Data signed"}),Zu=e=>po(Pu,{header:{translationKey:"notifications.messageSigned.header"},get icon(){return po(Bu,{})},get class(){return e.class},"data-tc-notification-message-signed":"true",children:"Message signed"}),Yu=di(Cd)` + margin-top: 2px; +`,Qu=e=>po(Pu,{header:{translationKey:"notifications.signMessageCanceled.header"},get icon(){return po(Yu,{size:"xs"})},get class(){return e.class},"data-tc-notification-sign-message-cancelled":"true",children:"Sign message canceled"});var Ju=Po("
    ");const eh=di(ws)` + background-color: ${e=>e.theme.colors.connectButton.background}; + color: ${e=>e.theme.colors.connectButton.foreground}; + box-shadow: ${e=>`0 4px 24px ${mi(e.theme.colors.constant.black,.16)}`}; + padding: 8px 16px 8px 12px; + + display: flex; + align-items: center; + gap: 4px; + height: 40px; +`,th=di(eh)` + padding: 12px 16px; + min-width: 148px; + justify-content: center; + background-color: ${e=>e.theme.colors.background.primary}; +`,nh=di(ws)` + min-width: 148px; + height: 40px; + + background-color: ${e=>e.theme.colors.background.primary}; + color: ${e=>e.theme.colors.connectButton.foreground}; + box-shadow: ${e=>`0 4px 24px ${mi(e.theme.colors.constant.black,.16)}`}; + + display: flex; + align-items: center; + justify-content: center; +`,rh=di(Ed)` + height: 18px; + width: 18px; +`,oh=di.div` + width: fit-content; + display: flex; + flex-direction: column; + align-items: flex-end; +`,ih=di(t=>{const n=$r(wu),[r,o]=Tr(!1);return po(Eu,{ref(e){var n=t.ref;"function"==typeof n?n(e):t.ref=e},get class(){return t.class},"data-tc-dropdown":"true",get children(){return po(Ru,{get children(){return[(a=Tu(),Uo(a,po(_u,{onClick:()=>p(null,null,function*(){const t=Ct(n.account.address,n.account.chain===e.CHAIN.TESTNET);yield _c(t),o(!0),setTimeout(()=>o(!1),1e3)}),get children(){return[po(bu,{}),po(xo,{get when(){return!r()},get children(){return po(Iu,{translationKey:"button.dropdown.copy",children:"Copy address"})}}),po(xo,{get when(){return r()},get children(){return po(Iu,{translationKey:"button.dropdown.copied",children:"Address copied!"})}})]}})),a),(i=Tu(),Uo(i,po(_u,{onClick:()=>(n.disconnect().catch(e=>Ri(e)),void t.onClose()),get children(){return[po(xu,{}),po(Iu,{translationKey:"button.dropdown.disconnect",children:"Disconnect"})]}})),i)];var i,a}})}})})` + box-sizing: border-box; + overflow: hidden; + margin-top: 12px; +`,ah=di(e=>{const t=function(e){const{timeout:t}=d(d({},Ku),e),[n,r]=Tr([]),[o,i]=Tr([]);return Or(Wr(Sa,e=>{var n;if(!e||!e.showNotification)return void r(e=>e.filter(e=>!ua(e.action)));if(Hu()===e)return;if((null==(n=Hu())?void 0:n.name)===e.name&&ua(e))return;Vu(e),r(e=>e.filter(e=>!ua(e.action)));const o={action:e};r(e=>[...e,o]);const a=setTimeout(()=>{r(e=>e.filter(e=>e!==o)),i(e=>e.filter(e=>e!==a))},t);i(e=>[...e,a])})),jr(()=>{o().forEach(e=>clearTimeout(e))}),n}();return Uo(n=Ju(),po(Wl,{onBeforeEnter:e=>{nc(e,[{opacity:0,transform:"translateY(0)"},{opacity:1,transform:"translateY(-8px)"}],{duration:200})},onExit:(e,t)=>{nc(e,[{opacity:1,transform:"translateY(-8px)"},{opacity:0,transform:"translateY(-30px)"}],{duration:200}).finished.then(t)},get children(){return po(Co,{get each(){return t()},children:({action:e})=>po(So,{get children(){return[po(ko,{get when(){return e.name===aa.sendTransaction},get children(){return po(zu,{class:Fu})}}),po(ko,{get when(){return e.name===sa.sendTransaction},get children(){return po(qu,{class:Fu})}}),po(ko,{get when(){return e.name===aa.signData},get children(){return po(Xu,{class:Fu})}}),po(ko,{get when(){return e.name===aa.signMessage},get children(){return po(Zu,{class:Fu})}}),po(ko,{get when(){return e.name===sa.signData},get children(){return po(Gu,{class:Fu})}}),po(ko,{get when(){return e.name===sa.signMessage},get children(){return po(Qu,{class:Fu})}}),po(ko,{get when(){return e.name===ia.sendTransaction},get children(){return po(Wu,{class:Fu})}}),po(ko,{get when(){return e.name===ia.signData},get children(){return po(Du,{class:Fu})}}),po(ko,{get when(){return e.name===ia.signMessage},get children(){return po(ju,{class:Fu})}})]}})})}})),Ar(()=>Wo(n,e.class)),n;var n})` + > div:first-child { + margin-top: 20px; + } +`,sh=Math.min,lh=Math.max,ch=Math.round,dh=Math.floor,uh=e=>({x:e,y:e}),hh={left:"right",right:"left",bottom:"top",top:"bottom"},ph={start:"end",end:"start"};function fh(e,t,n){return lh(e,sh(t,n))}function gh(e,t){return"function"==typeof e?e(t):e}function mh(e){return e.split("-")[0]}function vh(e){return e.split("-")[1]}function wh(e){return"x"===e?"y":"x"}function yh(e){return"y"===e?"height":"width"}const bh=new Set(["top","bottom"]);function Ch(e){return bh.has(mh(e))?"y":"x"}function xh(e){return wh(Ch(e))}function Sh(e){return e.replace(/start|end/g,e=>ph[e])}const kh=["left","right"],Eh=["right","left"],Rh=["top","bottom"],_h=["bottom","top"];function Th(e,t,n,r){const o=vh(e);let i=function(e,t,n){switch(e){case"top":case"bottom":return n?t?Eh:kh:t?kh:Eh;case"left":case"right":return t?Rh:_h;default:return[]}}(mh(e),"start"===n,r);return o&&(i=i.map(e=>e+"-"+o),t&&(i=i.concat(i.map(Sh)))),i}function Ih(e){return e.replace(/left|right|bottom|top/g,e=>hh[e])}function Ah(e){return"number"!=typeof e?function(e){return d({top:0,right:0,bottom:0,left:0},e)}(e):{top:e,right:e,bottom:e,left:e}}function Oh(e){const{x:t,y:n,width:r,height:o}=e;return{width:r,height:o,top:n,left:t,right:t+r,bottom:n+o,x:t,y:n}}function Mh(e,t,n){let{reference:r,floating:o}=e;const i=Ch(t),a=xh(t),s=yh(a),l=mh(t),c="y"===i,d=r.x+r.width/2-o.width/2,u=r.y+r.height/2-o.height/2,h=r[s]/2-o[s]/2;let p;switch(l){case"top":p={x:d,y:r.y-o.height};break;case"bottom":p={x:d,y:r.y+r.height};break;case"right":p={x:r.x+r.width,y:u};break;case"left":p={x:r.x-o.width,y:u};break;default:p={x:r.x,y:r.y}}switch(vh(t)){case"start":p[a]-=h*(n&&c?-1:1);break;case"end":p[a]+=h*(n&&c?-1:1)}return p}function Nh(e,t){return p(this,null,function*(){var n;void 0===t&&(t={});const{x:r,y:o,platform:i,rects:a,elements:s,strategy:l}=e,{boundary:c="clippingAncestors",rootBoundary:d="viewport",elementContext:u="floating",altBoundary:h=!1,padding:p=0}=gh(t,e),f=Ah(p),g=s[h?"floating"===u?"reference":"floating":u],m=Oh(yield i.getClippingRect({element:null==(n=yield null==i.isElement?void 0:i.isElement(g))||n?g:g.contextElement||(yield null==i.getDocumentElement?void 0:i.getDocumentElement(s.floating)),boundary:c,rootBoundary:d,strategy:l})),v="floating"===u?{x:r,y:o,width:a.floating.width,height:a.floating.height}:a.reference,w=yield null==i.getOffsetParent?void 0:i.getOffsetParent(s.floating),y=(yield null==i.isElement?void 0:i.isElement(w))&&(yield null==i.getScale?void 0:i.getScale(w))||{x:1,y:1},b=Oh(i.convertOffsetParentRelativeRectToViewportRelativeRect?yield i.convertOffsetParentRelativeRectToViewportRelativeRect({elements:s,rect:v,offsetParent:w,strategy:l}):v);return{top:(m.top-b.top+f.top)/y.y,bottom:(b.bottom-m.bottom+f.bottom)/y.y,left:(m.left-b.left+f.left)/y.x,right:(b.right-m.right+f.right)/y.x}})}function Ph(){return"undefined"!=typeof window}function Lh(e){return jh(e)?(e.nodeName||"").toLowerCase():"#document"}function Wh(e){var t;return(null==e||null==(t=e.ownerDocument)?void 0:t.defaultView)||window}function Dh(e){var t;return null==(t=(jh(e)?e.ownerDocument:e.document)||window.document)?void 0:t.documentElement}function jh(e){return!!Ph()&&(e instanceof Node||e instanceof Wh(e).Node)}function Uh(e){return!!Ph()&&(e instanceof Element||e instanceof Wh(e).Element)}function qh(e){return!!Ph()&&(e instanceof HTMLElement||e instanceof Wh(e).HTMLElement)}function Bh(e){return!(!Ph()||"undefined"==typeof ShadowRoot)&&(e instanceof ShadowRoot||e instanceof Wh(e).ShadowRoot)}const zh=new Set(["inline","contents"]);function Fh(e){const{overflow:t,overflowX:n,overflowY:r,display:o}=tp(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&!zh.has(o)}const Kh=new Set(["table","td","th"]);function Hh(e){return Kh.has(Lh(e))}const Vh=[":popover-open",":modal"];function $h(e){return Vh.some(t=>{try{return e.matches(t)}catch(n){return!1}})}const Gh=["transform","translate","scale","rotate","perspective"],Xh=["transform","translate","scale","rotate","perspective","filter"],Zh=["paint","layout","strict","content"];function Yh(e){const t=Qh(),n=Uh(e)?tp(e):e;return Gh.some(e=>!!n[e]&&"none"!==n[e])||!!n.containerType&&"normal"!==n.containerType||!t&&!!n.backdropFilter&&"none"!==n.backdropFilter||!t&&!!n.filter&&"none"!==n.filter||Xh.some(e=>(n.willChange||"").includes(e))||Zh.some(e=>(n.contain||"").includes(e))}function Qh(){return!("undefined"==typeof CSS||!CSS.supports)&&CSS.supports("-webkit-backdrop-filter","none")}const Jh=new Set(["html","body","#document"]);function ep(e){return Jh.has(Lh(e))}function tp(e){return Wh(e).getComputedStyle(e)}function np(e){return Uh(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function rp(e){if("html"===Lh(e))return e;const t=e.assignedSlot||e.parentNode||Bh(e)&&e.host||Dh(e);return Bh(t)?t.host:t}function op(e){const t=rp(e);return ep(t)?e.ownerDocument?e.ownerDocument.body:e.body:qh(t)&&Fh(t)?t:op(t)}function ip(e,t,n){var r;void 0===t&&(t=[]),void 0===n&&(n=!0);const o=op(e),i=o===(null==(r=e.ownerDocument)?void 0:r.body),a=Wh(o);if(i){const e=ap(a);return t.concat(a,a.visualViewport||[],Fh(o)?o:[],e&&n?ip(e):[])}return t.concat(o,ip(o,[],n))}function ap(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function sp(e){const t=tp(e);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const o=qh(e),i=o?e.offsetWidth:n,a=o?e.offsetHeight:r,s=ch(n)!==i||ch(r)!==a;return s&&(n=i,r=a),{width:n,height:r,$:s}}function lp(e){return Uh(e)?e:e.contextElement}function cp(e){const t=lp(e);if(!qh(t))return uh(1);const n=t.getBoundingClientRect(),{width:r,height:o,$:i}=sp(t);let a=(i?ch(n.width):n.width)/r,s=(i?ch(n.height):n.height)/o;return a&&Number.isFinite(a)||(a=1),s&&Number.isFinite(s)||(s=1),{x:a,y:s}}const dp=uh(0);function up(e){const t=Wh(e);return Qh()&&t.visualViewport?{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}:dp}function hp(e,t,n,r){void 0===t&&(t=!1),void 0===n&&(n=!1);const o=e.getBoundingClientRect(),i=lp(e);let a=uh(1);t&&(r?Uh(r)&&(a=cp(r)):a=cp(e));const s=function(e,t,n){return void 0===t&&(t=!1),!(!n||t&&n!==Wh(e))&&t}(i,n,r)?up(i):uh(0);let l=(o.left+s.x)/a.x,c=(o.top+s.y)/a.y,d=o.width/a.x,u=o.height/a.y;if(i){const e=Wh(i),t=r&&Uh(r)?Wh(r):r;let n=e,o=ap(n);for(;o&&r&&t!==n;){const e=cp(o),t=o.getBoundingClientRect(),r=tp(o),i=t.left+(o.clientLeft+parseFloat(r.paddingLeft))*e.x,a=t.top+(o.clientTop+parseFloat(r.paddingTop))*e.y;l*=e.x,c*=e.y,d*=e.x,u*=e.y,l+=i,c+=a,n=Wh(o),o=ap(n)}}return Oh({width:d,height:u,x:l,y:c})}function pp(e,t){const n=np(e).scrollLeft;return t?t.left+n:hp(Dh(e)).left+n}function fp(e,t,n){void 0===n&&(n=!1);const r=e.getBoundingClientRect();return{x:r.left+t.scrollLeft-(n?0:pp(e,r)),y:r.top+t.scrollTop}}const gp=new Set(["absolute","fixed"]);function mp(e,t,n){let r;if("viewport"===t)r=function(e,t){const n=Wh(e),r=Dh(e),o=n.visualViewport;let i=r.clientWidth,a=r.clientHeight,s=0,l=0;if(o){i=o.width,a=o.height;const e=Qh();(!e||e&&"fixed"===t)&&(s=o.offsetLeft,l=o.offsetTop)}return{width:i,height:a,x:s,y:l}}(e,n);else if("document"===t)r=function(e){const t=Dh(e),n=np(e),r=e.ownerDocument.body,o=lh(t.scrollWidth,t.clientWidth,r.scrollWidth,r.clientWidth),i=lh(t.scrollHeight,t.clientHeight,r.scrollHeight,r.clientHeight);let a=-n.scrollLeft+pp(e);const s=-n.scrollTop;return"rtl"===tp(r).direction&&(a+=lh(t.clientWidth,r.clientWidth)-o),{width:o,height:i,x:a,y:s}}(Dh(e));else if(Uh(t))r=function(e,t){const n=hp(e,!0,"fixed"===t),r=n.top+e.clientTop,o=n.left+e.clientLeft,i=qh(e)?cp(e):uh(1);return{width:e.clientWidth*i.x,height:e.clientHeight*i.y,x:o*i.x,y:r*i.y}}(t,n);else{const n=up(e);r={x:t.x-n.x,y:t.y-n.y,width:t.width,height:t.height}}return Oh(r)}function vp(e,t){const n=rp(e);return!(n===t||!Uh(n)||ep(n))&&("fixed"===tp(n).position||vp(n,t))}function wp(e,t,n){const r=qh(t),o=Dh(t),i="fixed"===n,a=hp(e,!0,i,t);let s={scrollLeft:0,scrollTop:0};const l=uh(0);function c(){l.x=pp(o)}if(r||!r&&!i)if(("body"!==Lh(t)||Fh(o))&&(s=np(t)),r){const e=hp(t,!0,i,t);l.x=e.x+t.clientLeft,l.y=e.y+t.clientTop}else o&&c();i&&!r&&o&&c();const d=!o||r||i?uh(0):fp(o,s);return{x:a.left+s.scrollLeft-l.x-d.x,y:a.top+s.scrollTop-l.y-d.y,width:a.width,height:a.height}}function yp(e){return"static"===tp(e).position}function bp(e,t){if(!qh(e)||"fixed"===tp(e).position)return null;if(t)return t(e);let n=e.offsetParent;return Dh(e)===n&&(n=n.ownerDocument.body),n}function Cp(e,t){const n=Wh(e);if($h(e))return n;if(!qh(e)){let t=rp(e);for(;t&&!ep(t);){if(Uh(t)&&!yp(t))return t;t=rp(t)}return n}let r=bp(e,t);for(;r&&Hh(r)&&yp(r);)r=bp(r,t);return r&&ep(r)&&yp(r)&&!Yh(r)?n:r||function(e){let t=rp(e);for(;qh(t)&&!ep(t);){if(Yh(t))return t;if($h(t))return null;t=rp(t)}return null}(e)||n}const xp={convertOffsetParentRelativeRectToViewportRelativeRect:function(e){let{elements:t,rect:n,offsetParent:r,strategy:o}=e;const i="fixed"===o,a=Dh(r),s=!!t&&$h(t.floating);if(r===a||s&&i)return n;let l={scrollLeft:0,scrollTop:0},c=uh(1);const d=uh(0),u=qh(r);if((u||!u&&!i)&&(("body"!==Lh(r)||Fh(a))&&(l=np(r)),qh(r))){const e=hp(r);c=cp(r),d.x=e.x+r.clientLeft,d.y=e.y+r.clientTop}const h=!a||u||i?uh(0):fp(a,l,!0);return{width:n.width*c.x,height:n.height*c.y,x:n.x*c.x-l.scrollLeft*c.x+d.x+h.x,y:n.y*c.y-l.scrollTop*c.y+d.y+h.y}},getDocumentElement:Dh,getClippingRect:function(e){let{element:t,boundary:n,rootBoundary:r,strategy:o}=e;const i=[..."clippingAncestors"===n?$h(t)?[]:function(e,t){const n=t.get(e);if(n)return n;let r=ip(e,[],!1).filter(e=>Uh(e)&&"body"!==Lh(e)),o=null;const i="fixed"===tp(e).position;let a=i?rp(e):e;for(;Uh(a)&&!ep(a);){const t=tp(a),n=Yh(a);n||"fixed"!==t.position||(o=null),(i?!n&&!o:!n&&"static"===t.position&&o&&gp.has(o.position)||Fh(a)&&!n&&vp(e,a))?r=r.filter(e=>e!==a):o=t,a=rp(a)}return t.set(e,r),r}(t,this._c):[].concat(n),r],a=i[0],s=i.reduce((e,n)=>{const r=mp(t,n,o);return e.top=lh(r.top,e.top),e.right=sh(r.right,e.right),e.bottom=sh(r.bottom,e.bottom),e.left=lh(r.left,e.left),e},mp(t,a,o));return{width:s.right-s.left,height:s.bottom-s.top,x:s.left,y:s.top}},getOffsetParent:Cp,getElementRects:function(e){return p(this,null,function*(){const t=this.getOffsetParent||Cp,n=this.getDimensions,r=yield n(e.floating);return{reference:wp(e.reference,yield t(e.floating),e.strategy),floating:{x:0,y:0,width:r.width,height:r.height}}})},getClientRects:function(e){return Array.from(e.getClientRects())},getDimensions:function(e){const{width:t,height:n}=sp(e);return{width:t,height:n}},getScale:cp,isElement:Uh,isRTL:function(e){return"rtl"===tp(e).direction}};function Sp(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}function kp(e,t,n,r){void 0===r&&(r={});const{ancestorScroll:o=!0,ancestorResize:i=!0,elementResize:a="function"==typeof ResizeObserver,layoutShift:s="function"==typeof IntersectionObserver,animationFrame:l=!1}=r,c=lp(e),h=o||i?[...c?ip(c):[],...ip(t)]:[];h.forEach(e=>{o&&e.addEventListener("scroll",n,{passive:!0}),i&&e.addEventListener("resize",n)});const p=c&&s?function(e,t){let n,r=null;const o=Dh(e);function i(){var e;clearTimeout(n),null==(e=r)||e.disconnect(),r=null}return function a(s,l){void 0===s&&(s=!1),void 0===l&&(l=1),i();const c=e.getBoundingClientRect(),{left:h,top:p,width:f,height:g}=c;if(s||t(),!f||!g)return;const m={rootMargin:-dh(p)+"px "+-dh(o.clientWidth-(h+f))+"px "+-dh(o.clientHeight-(p+g))+"px "+-dh(h)+"px",threshold:lh(0,sh(1,l))||1};let v=!0;function w(t){const r=t[0].intersectionRatio;if(r!==l){if(!v)return a();r?a(!1,r):n=setTimeout(()=>{a(!1,1e-7)},1e3)}1!==r||Sp(c,e.getBoundingClientRect())||a(),v=!1}try{r=new IntersectionObserver(w,u(d({},m),{root:o.ownerDocument}))}catch(y){r=new IntersectionObserver(w,m)}r.observe(e)}(!0),i}(c,n):null;let f,g=-1,m=null;a&&(m=new ResizeObserver(e=>{let[r]=e;r&&r.target===c&&m&&(m.unobserve(t),cancelAnimationFrame(g),g=requestAnimationFrame(()=>{var e;null==(e=m)||e.observe(t)})),n()}),c&&!l&&m.observe(c),m.observe(t));let v=l?hp(e):null;return l&&function t(){const r=hp(e);v&&!Sp(v,r)&&n();v=r,f=requestAnimationFrame(t)}(),n(),()=>{var e;h.forEach(e=>{o&&e.removeEventListener("scroll",n),i&&e.removeEventListener("resize",n)}),null==p||p(),null==(e=m)||e.disconnect(),m=null,l&&cancelAnimationFrame(f)}}const Ep=function(e){return void 0===e&&(e={}),{name:"shift",options:e,fn(t){return p(this,null,function*(){const{x:n,y:r,placement:o}=t,i=gh(e,t),{mainAxis:a=!0,crossAxis:s=!1,limiter:l={fn:e=>{let{x:t,y:n}=e;return{x:t,y:n}}}}=i,c=h(i,["mainAxis","crossAxis","limiter"]),p={x:n,y:r},f=yield Nh(t,c),g=Ch(mh(o)),m=wh(g);let v=p[m],w=p[g];if(a){const e="y"===m?"bottom":"right";v=fh(v+f["y"===m?"top":"left"],v,v-f[e])}if(s){const e="y"===g?"bottom":"right";w=fh(w+f["y"===g?"top":"left"],w,w-f[e])}const y=l.fn(u(d({},t),{[m]:v,[g]:w}));return u(d({},y),{data:{x:y.x-n,y:y.y-r,enabled:{[m]:a,[g]:s}}})})}}},Rp=function(e){return void 0===e&&(e={}),{name:"flip",options:e,fn(t){return p(this,null,function*(){var n,r;const{placement:o,middlewareData:i,rects:a,initialPlacement:s,platform:l,elements:c}=t,d=gh(e,t),{mainAxis:u=!0,crossAxis:p=!0,fallbackPlacements:f,fallbackStrategy:g="bestFit",fallbackAxisSideDirection:m="none",flipAlignment:v=!0}=d,w=h(d,["mainAxis","crossAxis","fallbackPlacements","fallbackStrategy","fallbackAxisSideDirection","flipAlignment"]);if(null!=(n=i.arrow)&&n.alignmentOffset)return{};const y=mh(o),b=Ch(s),C=mh(s)===s,x=yield null==l.isRTL?void 0:l.isRTL(c.floating),S=f||(C||!v?[Ih(s)]:function(e){const t=Ih(e);return[Sh(e),t,Sh(t)]}(s)),k="none"!==m;!f&&k&&S.push(...Th(s,v,m,x));const E=[s,...S],R=yield Nh(t,w),_=[];let T=(null==(r=i.flip)?void 0:r.overflows)||[];if(u&&_.push(R[y]),p){const e=function(e,t,n){void 0===n&&(n=!1);const r=vh(e),o=xh(e),i=yh(o);let a="x"===o?r===(n?"end":"start")?"right":"left":"start"===r?"bottom":"top";return t.reference[i]>t.floating[i]&&(a=Ih(a)),[a,Ih(a)]}(o,a,x);_.push(R[e[0]],R[e[1]])}if(T=[...T,{placement:o,overflows:_}],!_.every(e=>e<=0)){var I,A;const e=((null==(I=i.flip)?void 0:I.index)||0)+1,t=E[e];if(t){if(!("alignment"===p&&b!==Ch(t))||T.every(e=>Ch(e.placement)!==b||e.overflows[0]>0))return{data:{index:e,overflows:T},reset:{placement:t}}}let n=null==(A=T.filter(e=>e.overflows[0]<=0).sort((e,t)=>e.overflows[1]-t.overflows[1])[0])?void 0:A.placement;if(!n)switch(g){case"bestFit":{var O;const e=null==(O=T.filter(e=>{if(k){const t=Ch(e.placement);return t===b||"y"===t}return!0}).map(e=>[e.placement,e.overflows.filter(e=>e>0).reduce((e,t)=>e+t,0)]).sort((e,t)=>e[1]-t[1])[0])?void 0:O[0];e&&(n=e);break}case"initialPlacement":n=s}if(o!==n)return{reset:{placement:n}}}return{}})}}},_p=(e,t,n)=>{const r=new Map,o=d({platform:xp},n),i=u(d({},o.platform),{_c:r});return((e,t,n)=>p(null,null,function*(){const{placement:r="bottom",strategy:o="absolute",middleware:i=[],platform:a}=n,s=i.filter(Boolean),l=yield null==a.isRTL?void 0:a.isRTL(t);let c=yield a.getElementRects({reference:e,floating:t,strategy:o}),{x:h,y:p}=Mh(c,r,l),f=r,g={},m=0;for(let n=0;n",!0,!1,!1);const Ip=()=>{const t=li(),n=$r(Ma),r=$r(wu),[o,i]=Tr(!1),[a,s]=Tr(n.account),[l,c]=Tr(!n.account);let d;const[u,h]=Tr(),[p,f]=Tr(),g=function(e,t,n){let r=()=>{var e;return null!=(e=null==n?void 0:n.placement)?e:"bottom"},o=()=>{var e;return null!=(e=null==n?void 0:n.strategy)?e:"absolute"},[i,a]=Tr({x:null,y:null,placement:r(),strategy:o(),middlewareData:{}}),[s,l]=Tr();Or(()=>{let e=s();if(e)throw e.value});let c=Mr(()=>(e(),t(),{}));function d(){let i=e(),s=t();if(i&&s){let e=c();_p(i,s,{middleware:null==n?void 0:n.middleware,placement:r(),strategy:o()}).then(t=>{e===c()&&a(t)},e=>{l(e)})}}return Or(()=>{let i=e(),a=t();if(r(),o(),i&&a)if(null!=n&&n.whileElementsMounted){let e=n.whileElementsMounted(i,a,d);e&&jr(e)}else d()}),{get x(){return i().x},get y(){return i().y},get placement(){return i().placement},get strategy(){return i().strategy},get middlewareData(){return i().middlewareData},update:d}}(p,u,{whileElementsMounted:kp,placement:"bottom-end",middleware:[Rp(),Ep()]});r.connectionRestored.then(()=>c(!1));const m=n.onStatusChange(e=>{if(!e)return i(!1),s(null),void c(!1);s(e.account),c(!1)}),v=e=>{if(!a()||!o())return;const t=p().contains(e.target),n=d.contains(e.target);t||n||i(!1)};return Dr(()=>{document.body.addEventListener("click",v)}),jr(()=>{document.body.removeEventListener("click",v),m()}),po(Xo,{component:hi,get children(){return[po(xo,{get when(){return l()},get children(){return po(nh,{disabled:!0,"data-tc-connect-button-loading":"true",get children(){return po(rh,{})}})}}),po(xo,{get when(){return!l()},get children(){return[po(xo,{get when(){return!a()},get children(){return po(eh,{onClick:()=>r.openModal(),"data-tc-connect-button":"true",scale:"s",get children(){return[po(pd,{get fill(){return t.colors.connectButton.foreground}}),po(qc,{translationKey:"button.connectWallet",fontSize:"15px",lineHeight:"18px",fontWeight:"590",get color(){return t.colors.connectButton.foreground},children:"Connect wallet"})]}})}}),po(xo,{get when(){return a()},get children(){return po(oh,{get children(){return[po(th,{onClick:()=>i(e=>!e),ref:f,"data-tc-dropdown-button":"true",scale:"s",get children(){return[po(qc,{fontSize:"15px",fontWeight:"590",lineHeight:"18px",get children(){return(()=>{const t=a();if(t){const n=Ct(t.address,t.chain===e.CHAIN.TESTNET);return n.slice(0,4)+"…"+n.slice(-4)}return""})()}}),po(Bl,{direction:"bottom"})]}}),po(Go,{get children(){var e=Tp();return jo(h,e),e.style.setProperty("z-index","999"),e._$owner=qr(),Uo(e,po(Ll,{onBeforeEnter:e=>{nc(e,[{opacity:0,transform:"translateY(-8px)"},{opacity:1,transform:"translateY(0)"}],{duration:150})},onExit:(e,t)=>{nc(e,[{opacity:1,transform:"translateY(0)"},{opacity:0,transform:"translateY(-8px)"}],{duration:150}).finished.then(t)},get children(){return po(xo,{get when(){return o()},get children(){return po(ih,{get hidden(){return!o()},onClose:()=>i(!1),ref(e){"function"==typeof d?d(e):d=e}})}})}}),null),Uo(e,po(ah,{}),null),Ar(t=>{var n,r,o=g.strategy,i=`${null!=(n=g.y)?n:0}px`,a=`${null!=(r=g.x)?r:0}px`;return o!==t.e&&(null!=(t.e=o)?e.style.setProperty("position",o):e.style.removeProperty("position")),i!==t.t&&(null!=(t.t=i)?e.style.setProperty("top",i):e.style.removeProperty("top")),a!==t.a&&(null!=(t.a=a)?e.style.setProperty("left",a):e.style.removeProperty("left")),t},{e:void 0,t:void 0,a:void 0}),e}})]}})}})]}})]}})},Ap=di(sc)` + padding-left: 24px; + padding-right: 24px; + padding-top: 18px; + padding-bottom: 0; + + ${us("mobile")} { + padding-left: 0; + padding-right: 0; + } +`,Op=di(sd)` + margin-top: 12px; + + ${us("mobile")} { + padding: 0 10px; + } +`,Mp=di.div` + margin: 30px 0; + width: 100%; + display: flex; + justify-content: center; + + ${us("mobile")} { + height: 160px; + align-items: center; + } +`;di(qc)` + min-width: 84px; + text-align: center; + font-weight: 590; +`,di(e=>{const t="tabBar"+Math.floor(1e4*Math.random());return po(dc,{get class(){return e.class},"data-tc-tab-bar":"true",get children(){return[po(uc,{get right(){return 1===e.selectedTabIndex}}),po(pc,{get isActive(){return 0===e.selectedTabIndex},get children(){return[po(hc,{type:"radio",name:t,get checked(){return 0===e.selectedTabIndex},onInput:()=>{var t;return null==(t=e.onSelectedTabIndexChange)?void 0:t.call(e,0)}}),Mo(()=>e.tab1)]}}),po(pc,{get isActive(){return 1===e.selectedTabIndex},get children(){return[po(hc,{type:"radio",get checked(){return 1===e.selectedTabIndex},name:t,onInput:()=>{var t;return null==(t=e.onSelectedTabIndexChange)?void 0:t.call(e,1)}}),Mo(()=>e.tab2)]}})]}})})` + margin: 0 auto 22px; +`;const[Np,Pp]=$a({buttonRootId:null,language:"en",returnStrategy:"back",twaReturnUrl:void 0,walletsListConfiguration:{},enableAndroidBackHandler:!0});function Lp(e,t){const{isMobile:n,walletAppName:r,surface:o,selectionSource:i,traceId:a}=t;n?e.trackWalletSelected(r,o,i,a):e.trackWalletPreselected(r,o,i,a)}const Wp=di.div` + display: flex; + flex-direction: column; + align-items: center; +`,Dp=di(sd)` + margin-bottom: 18px; +`;di.div` + height: 1px; + margin: 0 -24px; + width: calc(100% + 48px); + opacity: 0.12; + background: ${e=>e.isShown?e.theme.colors.icon.secondary:"transparent"}; + transition: background 0.15s ease-in-out; + + ${us("mobile")} { + width: 100%; + } +`;const jp=di.ul` + display: grid; + grid-template-columns: repeat(auto-fit, 92px); + grid-template-rows: auto; + align-content: flex-start; + row-gap: 8px; + justify-content: center; + width: 100%; + padding: 0 0 16px; + align-self: flex-start; + max-width: 400px; + margin: 0 auto; + list-style: none; + + > li { + display: block; + height: fit-content; + } + + > li > button { + width: 100%; + } + + ${us("mobile")} { + display: grid; + grid-template-columns: repeat(4, 1fr); + gap: 0; + padding: 8px 12px 16px; + max-width: none; + + > li { + min-width: 78px; + display: flex; + } + + > li > * { + width: 100%; + } + } +`;di(ws)` + display: block; + margin: 0 auto 1px; + font-size: 15px; +`;const Up=di(Hl)` + position: absolute; + top: 16px; + left: 16px; +`,qp=di(su)` + opacity: ${e=>e.withOpacity?"0.4":"1"}; +`,Bp=di.div` + display: grid; + grid-template-columns: auto 28px; + gap: 16px; + padding: 16px; + margin-bottom: 16px; + border-radius: 16px; + color: ${e=>e.theme.colors.text.secondary}; + background: ${e=>e.theme.colors.background.tint}; + + ${us("mobile")} { + margin-left: 16px; + margin-right: 16px; + } +`,zp=di(cd)` + color: ${e=>e.theme.colors.text.secondary}; + text-align: left; + margin: 0; +`,Fp=di.div` + position: absolute; + bottom: 14px; + left: 50%; + transform: translate(-50%, 0); + + text-wrap: nowrap; + display: flex; + gap: 6px; + align-items: center; + border-radius: 18px; + min-width: 126px; + padding: 9px 16px 9px 10px; + + filter: drop-shadow(0px 2px 8px rgba(0, 0, 0, 0.08)); + background-color: ${e=>e.theme.colors.background.segment}; +`;var Kp=Po(''),Hp=Po('');const Vp=e=>{const t=li(),n=()=>e.size,r=()=>e.fill||t.colors.icon.error;return Mo(()=>{return Mo(()=>"16"===n())()?(l=Kp(),c=l.firstChild,d=c.firstChild,u=d.nextSibling,h=u.nextSibling,p=c.nextSibling.firstChild.firstChild,Ar(e=>{var n=r(),o=t.colors.constant.white,i=t.colors.constant.white,a=t.colors.constant.white;return n!==e.e&&Lo(d,"fill",e.e=n),o!==e.t&&Lo(u,"fill",e.t=o),i!==e.a&&Lo(h,"fill",e.a=i),a!==e.o&&Lo(p,"fill",e.o=a),e},{e:void 0,t:void 0,a:void 0,o:void 0}),l):Mo(()=>"28"===n())()?(o=Hp(),i=o.firstChild,a=i.nextSibling,s=a.nextSibling,Ar(n=>{var l=e.class,c=r(),d=t.colors.constant.white,u=t.colors.constant.white;return l!==n.e&&Lo(o,"class",n.e=l),c!==n.t&&Lo(i,"fill",n.t=c),d!==n.a&&Lo(a,"fill",n.a=d),u!==n.o&&Lo(s,"fill",n.o=u),n},{e:void 0,t:void 0,a:void 0,o:void 0}),o):null;var o,i,a,s,l,c,d,u,h,p})},$p="wallet_connect",Gp="WalletConnect",Xp="https://raw.githubusercontent.com/ton-connect/sdk/main/assets/walletconnect-icon-288.png";var Zp=Po("
  • ");const Yp=e=>{const t=Np.connector,n=Np.connectRequestParameters,r=()=>{e.traceId&&Np.tracker.trackWalletSelected($p,"all-wallets-list","manual",e.traceId),t.connect({type:"wallet-connect"},"ready"===(null==n?void 0:n.state)?n.value:void 0,{traceId:e.traceId})},[o,i]=Tr(null);let a=null;const s=t=>{t.isSupportRequiredFeatures||"strict"!==e.featureCheckMode?e.onSelect(t):(e=>{i(e),null!=a&&clearTimeout(a),a=setTimeout(()=>i(null),1500)})(t)},l=()=>hu()?e.walletsList.filter(td):e.walletsList,c=()=>l().filter(e=>e.isSupportRequiredFeatures);Ra({walletsMenu:"other_wallets",wallets:c()});const d=()=>l().filter(e=>!e.isSupportRequiredFeatures);return po(Wp,{"data-tc-wallets-modal-list":"true",get children(){return[po(Up,{icon:"arrow",onClick:()=>e.onBack()}),po(Dp,{translationKey:"walletModal.wallets",children:"Wallets"}),po(gu,{get maxHeight(){return hu()?void 0:510},get children(){return[po(jp,{get children(){return[po(Co,{get each(){return c()},children:t=>{return Uo(n=Zp(),po(qp,{wallet:t,onClick:()=>e.onSelect(t)})),n;var n}}),po(xo,{get when(){return Mo(()=>!Qn())()&&or()},get children(){return po(qp,{get wallet(){return{type:"wallet-connect",name:Gp,appName:$p,imageUrl:Xp}},onClick:r})}})]}}),po(xo,{get when(){return d().length>0&&"hide"!==e.featureCheckMode},get children(){return[po(Bp,{get children(){return[po(zp,{translationKey:"walletModal.allWallets.walletsBelowNotSupported",children:"The wallets below don’t support all features of the connected service. You can use your recovery phrase in one of the supported wallets above."}),po(Vp,{size:"28"})]}}),po(jp,{get children(){return po(Co,{get each(){return d()},children:t=>{return Uo(n=Zp(),po(qp,{wallet:t,onClick:()=>s(t),get withOpacity(){return"strict"===e.featureCheckMode}})),n;var n}})}}),po(Ll,{onBeforeEnter:e=>{nc(e,[{opacity:0,transform:"translate(-50%, 44px)"},{opacity:1,transform:"translate(-50%, 0)"}],{duration:150,easing:"ease-out"})},onExit:(e,t)=>{nc(e,[{opacity:1,transform:"translate(-50%, 0)"},{opacity:0,transform:"translate(-50%, 44px)"}],{duration:150,easing:"ease-out"}).finished.then(()=>{t()})},get children(){return po(xo,{get when(){return o()},get children(){return po(Fp,{get children(){return[po(Cd,{size:"xs"}),po(qc,{translationKey:"walletModal.allWallets.walletNotSupportService",get translationValues(){return{name:o().name}},get children(){return[Mo(()=>o().name)," doesn’t support connected service"]}})]}})}})}})]}})]}})]}})},Qp=di.div` + display: flex; + flex-direction: column; +`,Jp=di.div` + flex: 1; + margin-top: ${e=>e.qr?"0":"18px"}; + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + min-height: 232px; +`,ef=di(Pc)` + margin-bottom: 24px; +`,tf=di(sd)` + max-width: 288px; + margin: 0 auto 2px; +`,nf=di(cd)` + max-width: 288px; + text-align: center; + margin: 0 auto 20px; +`,rf=di(Hl)` + position: absolute; + top: 16px; + left: 16px; +`,of=di.div` + display: flex; + justify-content: center; + gap: 8px; + padding-bottom: 16px; +`,af=di(of)` + padding-bottom: 0; +`,sf=di(ws)` + margin-bottom: 24px; +`,lf=di(Ed)` + margin-bottom: 18px; + margin-top: 2px; +`,cf=di(Cd)` + margin-bottom: 16px; +`,df=di(cd)` + color: ${e=>e.theme.colors.text.secondary}; + text-align: center; + margin-bottom: 20px; +`,uf=e=>{const[t]=jc();return Mo(()=>{var n;return t(e.translationKey,e.translationValues,null==(n=e.children)?void 0:n.toString())})},hf=e=>{const[t,n]=Tr("mobile"),[r,o]=Tr(null);Or(()=>{var t;o(null!=(t=e.defaultError)?t:null)});const[i,a]=Tr(),[s,l]=Tr(!0),c=$r(Ma);jr(c.onStatusChange(()=>{},t=>{t instanceof ne?o("missing-features"):t instanceof re?o("wrong-network"):"telegram-wallet"!==e.wallet.appName&&o("connection-declined")}));const h=()=>{var t;try{const n=c.connect({universalLink:e.wallet.universalLink,bridgeUrl:e.wallet.bridgeUrl},e.additionalRequest,{traceId:null==(t=e.walletsModalState)?void 0:t.traceId,linkDisplayOnly:!0});a(n)}catch(n){}},p=()=>{var t;Np.tracker.trackConnectionInitiated({kind:"http-specific-wallet",bridgeUrl:e.wallet.bridgeUrl},null==(t=e.walletsModalState)?void 0:t.traceId)};Or(()=>{"extension"!==Lr(t)&&(td(e.wallet)||ed(e.wallet))&&h()});const f=()=>{o(null),"extension"===t()&&h(),n("mobile"),xa(u(d({},e.wallet),{openMethod:"qrcode"}))},g=()=>{if(o(null),"extension"===t()&&h(),n("desktop"),We(i()))m();else{const t=!s();l(!1),p(),Pi(i(),e.wallet.deepLink,{returnStrategy:Np.returnStrategy,forceRedirect:t},t=>{xa(u(d({},e.wallet),{openMethod:t}))})}},m=()=>{const t=!s();l(!1),xa(u(d({},e.wallet),{openMethod:"universal-link"})),p(),Ni(i(),{returnStrategy:Np.returnStrategy,twaReturnUrl:Np.twaReturnUrl,forceRedirect:t})},v=(t,n)=>{var r;const o=null==(r=e.walletsModalState)?void 0:r.traceId;o&&Np.tracker.trackWalletSelected(e.wallet.appName,"connection-modal",n,o,t)},w=()=>{var t;o(null),n("extension"),le(e.wallet)&&(xa(e.wallet),c.connect({jsBridgeKey:e.wallet.jsBridgeKey},e.additionalRequest,{traceId:null==(t=e.walletsModalState)?void 0:t.traceId}))};return td(e.wallet)?f():nd(e.wallet)?(le(e.wallet)&&v("extension",e.selectionSource),w()):(v("desktop",e.selectionSource),g()),po(Qp,{"data-tc-wallets-modal-connection-desktop":"true",get children(){return[po(xo,{get when(){return!e.backDisabled},get children(){return po(rf,{icon:"arrow",onClick:()=>e.onBackClick()})}}),po(tf,{get children(){return e.wallet.name}}),po(xo,{get when(){return Mo(()=>"mobile"===t())()&&!r()},get children(){return po(nf,{translationKey:"walletModal.desktopConnectionModal.scanQR",get translationValues(){return{name:e.wallet.name}},get children(){return["Scan the QR code below with your phone’s or ",Mo(()=>e.wallet.name),"’s camera"]}})}}),po(Jp,{get qr(){return"mobile"===t()},get children(){return po(So,{get children(){return[po(ko,{get when(){return r()},get children(){return[po(cf,{size:"s"}),po(So,{get children(){return[po(ko,{get when(){return"missing-features"===r()},get children(){return po(df,{translationKey:"walletModal.desktopConnectionModal.missingFeatures",get translationValues(){return{name:e.wallet.name}},children:"Please update Wallet, your version does not support required features for this dApp"})}}),po(ko,{get when(){return"connection-declined"===r()},get children(){return po(df,{translationKey:"walletModal.desktopConnectionModal.connectionDeclined",children:"Connection declined"})}}),po(ko,{get when(){return"not-supported"===r()},get children(){return po(df,{translationKey:"walletModal.desktopConnectionModal.notSupportedWallet",get translationValues(){return{name:e.wallet.name}},get children(){return[Mo(()=>e.wallet.name)," doesn’t support the requested action. Please connect another wallet that supports it."]}})}}),po(ko,{get when(){return"wrong-network"===r()},get children(){return po(df,{translationKey:"walletModal.desktopConnectionModal.wrongNetwork",get translationValues(){return{name:e.wallet.name}},get children(){return["Connected wallet is on a different network. Please switch network in ",Mo(()=>e.wallet.name)," and try again."]}})}})]}}),po(of,{get children(){return[po(xo,{get when(){return"not-supported"!==r()},get children(){return po(ws,{get leftIcon(){return po(Dd,{})},get onClick(){return"extension"===t()?w:g},get children(){return po(uf,{translationKey:"common.retry",children:"Retry"})}})}}),po(xo,{get when(){return"missing-features"===r()},get children(){return po(vu,{get href(){return e.wallet.aboutUrl},blank:!0,get children(){return po(ws,{get leftIcon(){return po(Ud,{})},get children(){return po(uf,{translationKey:"walletModal.desktopConnectionModal.updateWallet",get translationValues(){return{name:e.wallet.name}},get children(){return["Update ",Mo(()=>e.wallet.name)]}})}})}})}}),po(xo,{get when(){return"not-supported"===r()},get children(){return po(ws,{onClick:()=>e.onBackClick(),get children(){return po(uf,{translationKey:"walletModal.desktopConnectionModal.chooseAnotherWallet",children:"Choose Another Wallet"})}})}})]}})]}}),po(ko,{get when(){return"mobile"===t()},get children(){return po(ef,{disableCopy:!1,get sourceUrl(){return Mi(i(),"none")},get imageUrl(){return e.wallet.imageUrl}})}}),po(ko,{get when(){return"extension"===t()},get children(){return[po(xo,{get when(){return le(e.wallet)},get children(){return[po(lf,{size:"s"}),po(df,{translationKey:"walletModal.desktopConnectionModal.continueInExtension",get translationValues(){return{name:e.wallet.name}},get children(){return["Continue in ",Mo(()=>e.wallet.name)," browser extension…"]}}),po(of,{get children(){return po(ws,{get leftIcon(){return po(Dd,{})},onClick:w,get children(){return po(uf,{translationKey:"common.retry",children:"Retry"})}})}})]}}),po(xo,{get when(){return!le(e.wallet)},get children(){return[po(df,{translationKey:"walletModal.desktopConnectionModal.dontHaveExtension",get translationValues(){return{name:e.wallet.name}},get children(){return["Seems you don't have installed ",Mo(()=>e.wallet.name)," browser extension"]}}),po(of,{get children(){return po(vu,{get href(){return e.wallet.aboutUrl},blank:!0,get children(){return po(ws,{get rightIcon(){return po(Ud,{})},onClick:w,get children(){return po(uf,{translationKey:"walletModal.desktopConnectionModal.getWallet",get translationValues(){return{name:e.wallet.name}},get children(){return["Get ",Mo(()=>e.wallet.name)]}})}})}})}})]}})]}}),po(ko,{get when(){return"desktop"===t()},get children(){return[po(Ed,{size:"m"}),po(df,{translationKey:"walletModal.desktopConnectionModal.continueOnDesktop",get translationValues(){return{name:e.wallet.name}},get children(){return["Continue in ",Mo(()=>e.wallet.name)," on desktop…"]}}),po(of,{get children(){return[po(ws,{get leftIcon(){return po(Dd,{})},onClick:g,get children(){return po(uf,{translationKey:"common.retry",children:"Retry"})}}),po(vu,{get href(){return e.wallet.aboutUrl},blank:!0,get children(){return po(ws,{get rightIcon(){return po(Ud,{})},get children(){return po(uf,{translationKey:"walletModal.desktopConnectionModal.getWallet",get translationValues(){return{name:e.wallet.name}},get children(){return["Get ",Mo(()=>e.wallet.name)]}})}})}})]}})]}})]}})}}),po(af,{get children(){return[po(xo,{get when(){return Mo(()=>"mobile"!==t())()&&td(e.wallet)},get children(){return po(sf,{appearance:"secondary",get leftIcon(){return po(Nd,{})},onClick:()=>{v("mobile","manual"),f()},get children(){return po(uf,{translationKey:"common.mobile",children:"Mobile"})}})}}),po(xo,{get when(){return Mo(()=>"extension"!==t())()&&nd(e.wallet)},get children(){return po(sf,{appearance:"secondary",get leftIcon(){return po(Od,{})},onClick:()=>{v("extension","manual"),w()},get children(){return po(uf,{translationKey:"common.browserExtension",children:"Browser Extension"})}})}}),po(xo,{get when(){return Mo(()=>"desktop"!==t())()&&ed(e.wallet)},get children(){return po(sf,{appearance:"secondary",get leftIcon(){return po(Ld,{})},onClick:()=>{v("desktop","manual"),g()},get children(){return po(uf,{translationKey:"common.desktop",children:"Desktop"})}})}})]}})]}})},pf=di.div``,ff=di(Hl)` + position: absolute; + top: 16px; + left: 16px; +`,gf=di(sd)` + margin-bottom: 18px; +`,mf=di.div` + padding: 16px 0; + display: flex; + flex-direction: column; + align-items: center; +`,vf=oi` + margin-bottom: 12px; +`,wf=di(ud)` + text-align: center; + margin-bottom: 4px; +`,yf=di(qc)` + text-align: center; + max-width: 352px; + color: ${e=>e.theme.colors.text.secondary}; +`,bf=di.div` + padding: 16px 24px 24px; + display: flex; + align-items: center; + justify-content: center; + gap: 8px; +`,Cf="https://ton.org/wallets?filters[wallet_features][slug][$in]=dapp-auth&pagination[limit]=-1",xf=e=>po(pf,{"data-tc-wallets-modal-info":"true",get children(){return[po(ff,{icon:"arrow",onClick:()=>e.onBackClick()}),po(gf,{translationKey:"walletModal.infoModal.whatIsAWallet",children:"What is a wallet"}),po(gu,{get children(){return[po(mf,{get children(){return[po(Fd,{class:vf}),po(wf,{translationKey:"walletModal.infoModal.secureDigitalAssets",children:"Secure digital assets storage"}),po(yf,{translationKey:"walletModal.infoModal.walletProtects",children:"A wallet protects and manages your digital assets including TON, tokens and collectables."})]}}),po(mf,{get children(){return[po(Hd,{class:vf}),po(wf,{translationKey:"walletModal.infoModal.controlIdentity",children:"Control your Web3 identity"}),po(yf,{translationKey:"walletModal.infoModal.manageIdentity",children:"Manage your digital identity and access decentralized applications with ease. Maintain control over your data and engage securely in the blockchain ecosystem."})]}}),po(mf,{get children(){return[po($d,{class:vf}),po(wf,{translationKey:"walletModal.infoModal.effortlessCryptoTransactions",children:"Effortless crypto transactions"}),po(yf,{translationKey:"walletModal.infoModal.easilySend",children:"Easily send, receive, monitor your cryptocurrencies. Streamline your operations with decentralized applications."})]}}),po(bf,{get children(){return po(vu,{get href(){return Cf},blank:!0,get children(){return po(ws,{get rightIcon(){return po(Bd,{})},get children(){return po(uf,{translationKey:"walletModal.infoModal.getAWallet",children:"Get a Wallet"})}})}})}})]}})]}}),Sf=di.div``,kf=di.div` + flex: 1; + margin-top: 18px; + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + min-height: 232px; +`,Ef=di(sd)` + max-width: 262px; + margin: 0 auto 8px; +`,Rf=di(Hl)` + position: absolute; + top: 16px; + left: 16px; +`,_f=di.div` + padding: 16px; + display: flex; + align-items: center; + gap: 12px; + border-top: 0.5px solid ${e=>mi(e.theme.colors.icon.secondary,.2)}; +`,Tf=di(ss)` + width: 36px; + height: 36px; + border-radius: 10px; +`,If=di(vu)` + margin-left: auto; +`,Af=di(Ed)` + margin-bottom: 18px; + margin-top: 2px; +`,Of=di(Cd)` + margin-bottom: 16px; +`,Mf=di(cd)` + color: ${e=>e.theme.colors.text.secondary}; + text-align: center; + margin-bottom: 20px; +`,Nf=di.div` + display: flex; + justify-content: center; + gap: 8px; + padding-bottom: 16px; +`,Pf={m:"16px",s:"8px",none:"0"},Lf=di(sd)` + margin-bottom: 2px; + padding: 0 52px; +`,Wf=di(cd)` + margin-bottom: 20px; + padding: 0 64px; +`,Df=di.div` + padding: 0 24px 16px; +`,jf=di.div` + display: flex; + flex-direction: row; + gap: 16px; + padding: 0 24px 24px; + margin-top: 0; +`,Uf=di(ws)` + width: 100%; + height: 56px; + border-radius: ${e=>Pf[e.theme.borderRadius]}; + background-color: ${e=>mi(e.theme.colors.accent,.12)}; + color: ${e=>e.theme.colors.accent}; + font-size: 16px; + line-height: 20px; + font-weight: 500; + padding: 17px 20px 19px 20px; +`,qf=e=>[po(Lf,{get children(){return e.walletInfo.name}}),po(Wf,{translationKey:"walletModal.mobileConnectionModal.scanQR",get translationValues(){return{name:e.walletInfo.name}},get children(){return["Scan the QR code below with your phone’s or ",Mo(()=>e.walletInfo.name),"’s camera"]}}),po(Df,{get children(){return po(Pc,{get imageUrl(){return e.walletInfo.imageUrl},get sourceUrl(){return Mi(e.universalLink,"none")},disableCopy:!0})}}),po(jf,{get children(){return[po(Uf,{appearance:"secondary",onClick:()=>{var t;return null==(t=e.onOpenLink)?void 0:t.call(e)},get children(){return po(uf,{translationKey:"walletModal.mobileUniversalModal.openLink",children:"Open Link"})}}),po(Uf,{appearance:"secondary",onClick:()=>{var t;return null==(t=e.onCopy)?void 0:t.call(e)},get children(){return po(uf,{get translationKey(){return void 0!==e.isCopiedShown?"common.copied":"common.copyLink"},get children(){return void 0!==e.isCopiedShown?"Copied":"Copy Link"}})}})]}})],Bf=e=>{const t=li(),[n,r]=Tr(!0),[o,i]=Tr(!1),[a,s]=Tr(null);Or(()=>{var t;s(null!=(t=e.defaultError)?t:null)});const l=$r(Ma),c=l.onStatusChange(()=>{},e=>{s(e instanceof ne?"missing-features":e instanceof re?"wrong-network":null)}),[h,f]=Tr(null),g=t=>{var n,r;let o=h(),i=!o;if(!o){const t=ln(null!=(n=e.wallet.features)?n:[],{embeddedRequest:{}})&&e.walletsModalState&&"embeddedRequest"in e.walletsModalState?e.walletsModalState.embeddedRequest:void 0;o=l.connect({universalLink:e.wallet.universalLink,bridgeUrl:e.wallet.bridgeUrl},e.additionalRequest,{traceId:null==(r=e.walletsModalState)?void 0:r.traceId,embeddedRequest:null!=t?t:void 0})}const a=Wi(o),s=t?a:o,c=t?o:a;return(c!==s||i)&&f(s),Ri("getUniversalLink",c),c},m=()=>{const t=g(!0);if(We(t))return o=t,xa(u(d({},e.wallet),{openMethod:"universal-link"})),void Ni(o,{returnStrategy:Np.returnStrategy,twaReturnUrl:Np.twaReturnUrl,forceRedirect:!0});var o;s(null);const i=!n();r(!1),Pi(t,e.wallet.deepLink,{returnStrategy:Np.returnStrategy,forceRedirect:i},t=>{xa(u(d({},e.wallet),{openMethod:t}))})},[v,w]=Tr(void 0),y=()=>p(null,null,function*(){void 0!==v()&&clearTimeout(v()),yield _c(g(!1));const e=setTimeout(()=>w(void 0),1500);w(e)}),b=()=>{s(null),i(!0),xa(u(d({},e.wallet),{openMethod:"qrcode"}))},C=()=>{o()?(i(!1),xa(u(d({},e.wallet),{openMethod:"universal-link"}))):e.onBackClick()};return jr(c),m(),po(Sf,{"data-tc-wallets-modal-connection-mobile":"true",get children(){return[po(xo,{get when(){return!e.backDisabled||o()},get children(){return po(Rf,{icon:"arrow",onClick:C})}}),po(xo,{get when(){return o()},get children(){return po(qf,{get universalLink(){return g(!1)},get walletInfo(){return e.wallet},onOpenLink:m,onCopy:y,get isCopiedShown(){return v()}})}}),po(xo,{get when(){return!o()},get children(){return[po(Ef,{get children(){return e.wallet.name}}),po(kf,{get children(){return[po(xo,{get when(){return a()},get children(){return[po(Of,{size:"s"}),po(So,{get children(){return[po(ko,{get when(){return"missing-features"===a()},get children(){return po(Mf,{translationKey:"walletModal.mobileConnectionModal.missingFeatures",get translationValues(){return{name:e.wallet.name}},children:"Please update Wallet, your version does not support required features for this dApp"})}}),po(ko,{get when(){return"connection-declined"===a()},get children(){return po(Mf,{translationKey:"walletModal.mobileConnectionModal.connectionDeclined",children:"Connection declined"})}}),po(ko,{get when(){return"wrong-network"===a()},get children(){return po(Mf,{translationKey:"walletModal.mobileConnectionModal.wrongNetwork",get translationValues(){return{name:e.wallet.name}},get children(){return["Connected wallet is on a different network. Please switch network in ",Mo(()=>e.wallet.name)," and try again."]}})}}),po(ko,{get when(){return"not-supported"===a()},get children(){return po(Mf,{translationKey:"walletModal.mobileConnectionModal.notSupportedWallet",get translationValues(){return{name:e.wallet.name}},get children(){return[Mo(()=>e.wallet.name)," doesn't support the requested action. Please connect another wallet that supports it."]}})}})]}}),po(Nf,{get children(){return po(So,{get children(){return[po(ko,{get when(){return"missing-features"===a()},get children(){return[po(ws,{get leftIcon(){return po(Dd,{})},onClick:m,get children(){return po(uf,{translationKey:"common.retry",children:"Retry"})}}),po(vu,{get href(){return e.wallet.aboutUrl},blank:!0,get children(){return po(ws,{get leftIcon(){return po(Ud,{})},get children(){return po(uf,{translationKey:"walletModal.mobileConnectionModal.updateWallet",get translationValues(){return{name:e.wallet.name}},get children(){return["Update ",Mo(()=>e.wallet.name)]}})}})}})]}}),po(ko,{get when(){return"not-supported"===a()},get children(){return po(ws,{onClick:()=>e.onBackClick(),get children(){return po(uf,{translationKey:"walletModal.mobileConnectionModal.chooseAnotherWallet",children:"Choose Another Wallet"})}})}}),po(ko,{get when(){return"wrong-network"===a()},get children(){return po(ws,{get leftIcon(){return po(Dd,{})},onClick:m,get children(){return po(uf,{translationKey:"common.retry",children:"Retry"})}})}}),po(ko,{get when(){return"connection-declined"===a()},get children(){return[po(ws,{get leftIcon(){return po(Dd,{})},onClick:m,get children(){return po(uf,{translationKey:"common.retry",children:"Retry"})}}),po(ws,{get leftIcon(){return po(Jd,{get fill(){return t.colors.accent}})},onClick:b,get children(){return po(uf,{translationKey:"walletModal.mobileConnectionModal.showQR",children:"Show QR Code"})}})]}})]}})}})]}}),po(xo,{get when(){return!a()},get children(){return[po(Af,{size:"s"}),po(Mf,{translationKey:"walletModal.mobileConnectionModal.continueIn",get translationValues(){return{name:e.wallet.name}},get children(){return["Continue in ",Mo(()=>e.wallet.name),"…"]}}),po(Nf,{get children(){return[po(ws,{get leftIcon(){return po(Dd,{})},onClick:m,get children(){return po(uf,{translationKey:"common.retry",children:"Retry"})}}),po(ws,{get leftIcon(){return po(Jd,{get fill(){return t.colors.accent}})},onClick:b,get children(){return po(uf,{translationKey:"walletModal.mobileConnectionModal.showQR",children:"Show QR Code"})}})]}})]}})]}}),po(_f,{get children(){return[po(Tf,{get src(){return e.wallet.imageUrl}}),po(ud,{get children(){return e.wallet.name}}),po(If,{get href(){return e.wallet.aboutUrl},blank:!0,get children(){return po(ws,{get children(){return po(uf,{translationKey:"common.get",children:"GET"})}})}})]}})]}})]}})},zf="\n margin-left: 28px;\n margin-right: 28px;\n width: calc(100% - 56px);\n\n @media (max-width: 375px) {\n margin-left: 16px;\n margin-right: 16px;\n width: calc(100% - 32px);\n }\n",Ff={m:"6px",s:"6px",none:"0"};di.li` + width: 82px; + min-width: 82px; + height: 124px; + display: flex; + flex-direction: column; + align-items: center; + padding: 8px 4px; + + text-align: center; + cursor: pointer; + + transition: transform 0.1s ease-in-out; + + ${ps} { + &:hover { + transform: scale(1.04); + } + } + + &:active { + transform: scale(0.96); + } + + ${hs} { + &:active { + transform: scale(0.92); + } + } +`;const Kf=di(sd)` + margin-top: 38px; + margin-bottom: 4px; + padding: 0 24px; +`,Hf=di(xl)` + margin: 0 auto 4px; +`,Vf=di(sd)` + margin-top: 0; + margin-bottom: 20px; + padding: 0 24px; +`,$f=di(cd)` + margin: ${e=>{var t;return null!=(t=e.margin)?t:"0 0 28px 0"}}; + padding: ${e=>{var t;return null!=(t=e.padding)?t:"0 24px"}}; + min-height: ${e=>{var t;return null!=(t=e.padding)?t:"44px"}}; + max-width: ${e=>e.maxWidth}px; + margin-left: ${e=>e.maxWidth?"auto":"0px"}; + margin-right: ${e=>e.maxWidth?"auto":"0px"}; +`;di(ws)` + display: block; + margin: 0 auto; +`;const Gf=di(Ts)` + ${zf} + margin-bottom: 12px; +`,Xf=di(_s)` + ${zf} + margin-bottom: 24px; + background-color: ${e=>e.transparent?"transparent":e.theme.colors.background.tint}; + color: ${e=>e.theme.colors.text.primary}; +`,Zf=di(ss)` + width: 24px; + height: 24px; + border-radius: ${e=>Ff[e.theme.borderRadius]}; +`,Yf=di(Hl)` + position: absolute; + top: 16px; + left: 16px; +`,Qf={m:"16px",s:"8px",none:"0"},Jf=di(sd)` + margin-bottom: 2px; + padding: 0 52px; +`,eg=di(cd)` + margin-bottom: 20px; + padding: 0 64px; +`,tg=di.div` + padding: 0 24px 16px; +`,ng=di.div` + display: flex; + flex-direction: row; + gap: 16px; + padding: 0 24px 24px; + margin-top: 0; +`,rg=di(ws)` + width: 100%; + height: 56px; + border-radius: ${e=>Qf[e.theme.borderRadius]}; + background-color: ${e=>mi(e.theme.colors.accent,.12)}; + color: ${e=>e.theme.colors.accent}; + font-size: 16px; + line-height: 20px; + font-weight: 500; + padding: 17px 20px 19px 20px; +`,og=()=>po(xl,{size:75,hoverScale:2.75}),ig=e=>[po(Jf,{translationKey:"walletModal.mobileUniversalModal.connectYourWallet",children:"Connect your TON wallet"}),po(eg,{translationKey:"walletModal.mobileUniversalModal.scan",children:"Scan with your mobile wallet"}),po(tg,{get children(){return po(Pc,{get logo(){return po(og,{})},get sourceUrl(){return Mi(e.universalLink,"none")},disableCopy:!0})}}),po(ng,{get children(){return[po(rg,{appearance:"secondary",onClick:()=>e.onOpenLink(),get children(){return po(uf,{translationKey:"walletModal.mobileUniversalModal.openLink",children:"Open Link"})}}),po(rg,{appearance:"secondary",onClick:()=>e.onCopy(),get children(){return po(uf,{get translationKey(){return void 0!==e.isCopiedShown?"common.copied":"common.copyLink"},get children(){return void 0!==e.isCopiedShown?"Copied":"Copy Link"}})}})]}})];function ag(e){const t=new Set(e.filter(ue).map(e=>e.bridgeUrl));return Array.from(t).map(e=>({bridgeUrl:e}))}function sg(e,t){const n=new Set(null==e?void 0:e.map(e=>e.bridgeUrl)),r=new Set(null==t?void 0:t.map(e=>e.bridgeUrl));return n.size===r.size&&[...n].every(e=>r.has(e))}var lg=Po("
  • "),cg=Po("
    ");const dg=e=>{const[t,n]=Tr(!1),[r,o]=Tr(!0),[i,a]=Tr(null),s=Np.connector,l=[iu,au],c=()=>e.walletsList.filter(e=>td(e)&&!l.includes(e.appName)),d=()=>c().length>7,u=t=>{var n;return null!=(n=e.walletsList.find(e=>e.appName===t&&td(e)&&e.isSupportRequiredFeatures))?n:null},h=Mr(()=>u(iu),null),f=Mr(()=>u(au),null),g=()=>!!h()||!!f(),m=Mr(()=>ag(e.walletsList),null,{equals:sg}),v=t=>{let n=i(),r=!n;if(!n){const t="embeddedRequest"in e.walletModalState?e.walletModalState.embeddedRequest:void 0;n=s.connect(m(),e.additionalRequest,{traceId:e.walletModalState.traceId,embeddedRequest:null!=t?t:void 0,linkDisplayOnly:!0})}const o=Wi(n),l=t.useEmbeddedRequest?o:n,c=t.useEmbeddedRequest?n:o;return(c!==l||r)&&a(l),Ri("getUniversalLink",c),c};xa({openMethod:"universal-link"});const[w,y]=Tr(void 0),b=()=>p(null,null,function*(){void 0!==w()&&clearTimeout(w()),yield _c(v({useEmbeddedRequest:!1}));const e=setTimeout(()=>y(void 0),1500);y(e)}),C=()=>{Np.tracker.trackConnectionInitiated({kind:"http-any-wallet"},e.walletModalState.traceId);const t=!r();o(!1),Pi(v({useEmbeddedRequest:!0}),void 0,{returnStrategy:Np.returnStrategy,forceRedirect:t},e=>{xa({openMethod:e})})},x=()=>{n(!0),xa({openMethod:"qrcode"})},S=()=>{n(!1),xa({openMethod:"universal-link"})},k=Mr(()=>c().filter(e=>e.isSupportRequiredFeatures),null),E=Mr(()=>k().slice(0,3),null);Ra({walletsMenu:"main_screen",wallets:[h(),f(),...E()].filter(e=>!!e)});const R=Mr(()=>c().filter(e=>!E().find(t=>t.appName===e.appName)).slice(0,4),null);return Uo(_=cg(),po(xo,{get when(){return t()},get children(){return[po(Yf,{icon:"arrow",onClick:S}),po(ig,{get universalLink(){return v({useEmbeddedRequest:!1})},get isCopiedShown(){return w()},onOpenLink:C,onCopy:b})]}}),null),Uo(_,po(xo,{get when(){return!t()},get children(){return[po(Yf,{get icon(){return po(Jd,{})},onClick:x}),po(xo,{get when(){return h()},get fallback(){return po(Kf,{translationKey:"walletModal.mobileUniversalModal.connectYourWallet",children:"Connect your TON wallet"})},get children(){return[po(Hf,{size:120}),po(Vf,{translationKey:"walletModal.mobileUniversalModal.useTelegramWallet",children:"Use your Telegram wallet"}),po(Gf,{shiny:!0,get icon(){return po(Xd,{})},onClick:()=>e.onSelect(h()),get children(){return po(uf,{translationKey:"common.connectTelegram",children:"Connect Telegram"})}})]}}),po(xo,{get when(){return f()},get children(){return po(Xf,{get transparent(){var e;return null==(e=f().ui)?void 0:e.isButtonTransparent},get shiny(){var e;return!(null==(e=f().ui)?void 0:e.isButtonTransparent)},shineOpacity:.085,get icon(){return po(Zf,{get src(){return f().imageUrl}})},onClick:()=>e.onSelect(f()),get children(){return f().name}})}}),po($f,{get translationKey(){return g()?"walletModal.mobileUniversalModal.chooseOtherApplication":"walletModal.mobileUniversalModal.chooseApplication"},maxWidth:342,padding:"0 24px 8px 24px",margin:"0",get children(){return g()?"Or choose another app:":"Choose an app:"}}),po(Vc,{get children(){return[po(Co,{get each(){return Mo(()=>!!d())()?E():k()},children:t=>{return Uo(n=lg(),po(id,{get icon(){return t.imageUrl},get name(){return t.name},onClick:()=>e.onSelect(t)})),n;var n}}),po(xo,{get when(){return d()},get children(){var t=lg();return Uo(t,po(ou,{labelLine1:"View all",labelLine2:"wallets",get images(){return R().map(e=>e.imageUrl)},onClick:()=>e.onSelectAllWallets()})),t}})]}})]}}),null),_;var _},ug={m:"16px",s:"8px",none:"0"},hg={m:"8px",s:"4px",none:"0"},pg=di.div` + display: flex; + flex-direction: column; + align-items: center; + padding-bottom: 16px; +`,fg=di(cd)` + max-width: 320px; + margin-top: 2px; + margin-bottom: 20px; +`,gg=di(cd)` + margin-bottom: 16px; +`,mg=di(Pc)` + margin-bottom: 24px; +`,vg=di.ul` + display: flex; +`;di.div` + display: flex; + gap: 16px; + width: 100%; +`,di(ws)` + position: relative; + font-size: 16px; + line-height: 20px; + width: 100%; + padding: 0 16px; + height: 56px; + border-radius: ${e=>ug[e.theme.borderRadius]}; + + &:hover { + ${e=>e.disableEventsAnimation?"transform: unset;":""} + } + + &:active { + ${e=>e.disableEventsAnimation?"transform: unset;":""} + } +`,di.ul` + position: absolute; + bottom: 100%; + left: 0; + margin: 0; + padding: 8px; + width: 188px; + transform: translateY(-16px); + + background-color: ${e=>e.theme.colors.background.primary}; + border-radius: ${e=>ug[e.theme.borderRadius]}; + box-shadow: 0 4px 24px rgba(0, 0, 0, 0.16); +`,di.li` + padding: 8px; + + display: flex; + align-items: center; + gap: 8px; + + cursor: pointer; + border-radius: ${e=>hg[e.theme.borderRadius]}; + + transition: + background-color, + transform 0.1s ease-in-out; + + &:hover { + background-color: ${e=>e.theme.colors.background.secondary}; + } + + &:active { + transform: scale(0.96); + } +`,di(ss)` + width: 24px; + height: 24px; + + border-radius: 6px; +`,di.div` + margin-top: 23px; + margin-bottom: 1px; + width: 100%; + display: flex; + justify-content: center; + align-items: center; +`,di(qc)` + color: ${e=>e.theme.colors.text.secondary}; + font-size: 16px; +`;var wg=Po("
  • ");const yg=e=>{const[t,n]=Tr(!1),r=Np.connector,o=Mr(()=>ag(e.walletsList),null,{equals:sg});xa({openMethod:"qrcode"});const i=Mr(()=>r.connect(o(),e.additionalRequest,{traceId:e.walletModalState.traceId,linkDisplayOnly:!0})),a=Mr(()=>e.walletsList.filter(e=>e.isSupportRequiredFeatures),null),s=Mr(()=>a().slice(0,3),null);Ra({walletsMenu:"main_screen",wallets:s()});const l=Mr(()=>e.walletsList.filter(e=>!s().find(t=>t.appName===e.appName)).slice(0,4),null);return po(pg,{onClick:()=>n(!1),"data-tc-wallets-modal-universal-desktop":"true",get children(){return[po(sd,{translationKey:"walletModal.desktopUniversalModal.connectYourWallet",children:"Connect your wallet"}),po(fg,{translationKey:"walletModal.desktopUniversalModal.scan",children:"Scan with your mobile wallet"}),po(mg,{get sourceUrl(){return Mi(i(),"none")},get disableCopy(){return t()},get logo(){return po(og,{})}}),po(gg,{translationKey:"walletModal.desktopUniversalModal.availableWallets",children:"Available wallets"}),po(vg,{get children(){return[po(Co,{get each(){return s()},children:t=>{return Uo(n=wg(),po(su,{wallet:t,onClick:()=>e.onSelect(t)})),n;var n}}),po(ou,{labelLine1:"View all",labelLine2:"wallets",get images(){return l().map(e=>e.imageUrl)},onClick:()=>e.onSelectAllWallets()})]}})]}})},bg={m:"16px",s:"8px",none:"0"},Cg=di(sd)` + max-width: 288px; + margin: 0 auto 38px; +`,xg=di.div` + display: flex; + flex-direction: column; + align-items: center; +`,Sg=di(Hl)` + position: absolute; + top: 16px; + left: 16px; +`,kg=di(sd)` + text-align: center; + font-size: 20px; + line-height: 28px; +`,Eg=di(qc)` + margin-top: 12px; + margin-bottom: 24px; + text-align: center; + max-width: 360px; + font-weight: 400; + color: ${e=>e.theme.colors.text.secondary}; +`;di.button` + background: transparent; + border: none; + padding: 0; + margin: 0; + color: ${e=>e.theme.colors.accent}; + text-decoration: underline; + cursor: pointer; + font: inherit; +`;const Rg=di.div` + margin-bottom: 46px; +`,_g=di(Cd)` + margin-bottom: 16px; +`;di.ul` + display: flex; + gap: 8px; + margin-bottom: 24px; + list-style: none; + padding: 0; +`;const Tg=di(ws)` + max-width: 320px; + width: 100%; + height: 48px; + font-size: 16px; + line-height: 20px; + border-radius: ${e=>bg[e.theme.borderRadius]}; + margin-bottom: 28px; +`,Ig=di(cd)` + color: ${e=>e.theme.colors.text.secondary}; + text-align: center; + margin-bottom: 20px; +`,Ag=di.div` + display: flex; + justify-content: center; + gap: 8px; + padding-bottom: 31px; +`,Og=di.div` + margin: 0 8px 16px 8px; +`,Mg=di(Hl)` + position: absolute; + top: 16px; + left: 16px; +`,Ng=di(sd)` + margin-bottom: 18px; + text-align: center; +`,Pg=di.div` + padding: 16px 0; + display: flex; + flex-direction: column; + align-items: center; +`;di.div` + margin-bottom: 12px; +`;const Lg=di(ud)` + text-align: center; + margin-bottom: 4px; +`,Wg=di(qc)` + text-align: center; + max-width: 352px; + color: ${e=>e.theme.colors.text.secondary}; +`,Dg=di.div` + width: 44px; + height: 44px; + border-radius: 20px; + background-color: ${e=>{var t;return null==(t=e.theme)?void 0:t.colors.icon.secondary}}; + display: flex; + align-items: center; + justify-content: center; + margin-bottom: 12px; + font-weight: 700; + font-size: 22px; + color: ${e=>{var t;return null==(t=e.theme)?void 0:t.colors.text.primary}}; +`,jg=e=>po(Og,{"data-tc-wallets-modal-restore":"true",get children(){return[po(Mg,{icon:"arrow",get onClick(){return e.onBackClick}}),po(Ng,{translationKey:"walletModal.restoreInfoModal.title",children:"Restore"}),po(gu,{get children(){return[po(Pg,{get children(){return[po(Dg,{children:"1"}),po(Lg,{translationKey:"walletModal.restoreModal.step1.title",children:"Find your current recovery phrase"}),po(Wg,{translationKey:"walletModal.restoreModal.step1.text",children:"Open your wallet settings and locate the recovery phrase"})]}}),po(Pg,{get children(){return[po(Dg,{children:"2"}),po(Lg,{translationKey:"walletModal.restoreModal.step2.title",children:"Copy your recovery phrase"}),po(Wg,{translationKey:"walletModal.restoreModal.step2.text",children:"Write it down or copy it to a safe place"})]}}),po(Pg,{get children(){return[po(Dg,{children:"3"}),po(Lg,{translationKey:"walletModal.restoreModal.step3.title",children:"Restore in a supported wallet from the list below"}),po(Wg,{translationKey:"walletModal.restoreModal.step3.text",children:"Enter the recovery phrase to access your wallet"})]}})]}})]}}),Ug=e=>{const[t,n]=Tr(null),[r,o]=Tr(!1),i=Mr(()=>e.walletsList.find(t=>rd(t,e.currentWallet.device.appName))),a=Mr(()=>{var t,n;return null!=(n=null==(t=i())?void 0:t.name)?n:e.currentWallet.device.appName}),s=Mr(()=>{const t=i();if(!(null==t?void 0:t.features))return!1;const n=e.walletsModalState.requiredFeature,r=n?{[n.featureName]:n.value}:{},o=ln(t.features,r),a=ln(e.currentWallet.device.features,r);return o&&!a});return po(xg,{get children(){return po(So,{get children(){return[po(ko,{get when(){return r()},get children(){return po(jg,{onBackClick:()=>o(!1)})}}),po(ko,{get when(){return t()},get children(){return[po(Rg,{}),po(xg,{get children(){return[po(Sg,{icon:"arrow",onClick:()=>n(null)}),po(kg,{translationKey:"walletModal.featureNotSupported.disconnect.title",children:"Confirm Disconnect"}),po(Eg,{translationKey:"walletModal.featureNotSupported.disconnect.description",get translationValues(){return{name:t().name}},get children(){return["You will be disconnected from your current wallet and redirected to connect ",Mo(()=>{var e;return null==(e=t())?void 0:e.name}),"."]}}),po(Tg,{onClick:()=>p(null,null,function*(){yield e.onDisconnect(),e.onSelect(t())}),get children(){return po(uf,{translationKey:"walletModal.featureNotSupported.disconnect.button",children:"Disconnect"})}})]}})]}}),po(ko,{get when(){return s()},get children(){return[po(Cg,{get children(){return a()}}),po(_g,{size:"s"}),po(Ig,{translationKey:"walletModal.featureNotSupported.version.description",get translationValues(){return{name:a()}},get children(){return["Your current version of ",Mo(()=>a())," or wallet contract type doesn't support the required features. Please update it to continue."]}}),po(Ag,{get children(){return[po(vu,{get href(){return i().aboutUrl},blank:!0,get children(){return po(ws,{get leftIcon(){return po(Ud,{})},get children(){return po(uf,{translationKey:"walletModal.featureNotSupported.version.updateButton",get translationValues(){return{name:a()}},get children(){return["Update ",Mo(()=>a())]}})}})}}),po(vu,{href:"https://tonkeeper.helpscoutdocs.com/article/102-w5",blank:!0,get children(){return po(ws,{get leftIcon(){return po(Ud,{})},get children(){return po(uf,{translationKey:"walletModal.featureNotSupported.version.aboutW5",children:"About W5"})}})}})]}})]}}),po(ko,{when:!0,get children(){return[po(Rg,{}),po(_g,{size:"s"}),po(kg,{translationKey:"walletModal.featureNotSupported.wallet.title",get translationValues(){return{name:a()}},get children(){return[Mo(()=>a())," doesn’t support the requested action"]}}),po(Rg,{})]}})]}})}})},qg=()=>{const{locale:e}=jc()[1];Or(()=>e(Np.language)),Or(()=>{fa()?(fu(),o()):(a(null),h("universal"),f(!1))});const t=$r(Ma),n=$r(wu),[r,{refetch:o}]=Nr(()=>n.getWallets()),[i,a]=Tr(null),[s,l]=Tr(null),[c,h]=Tr("universal"),[p,f]=Tr(!1),g=Mr(()=>{const e=ha();return"type"in e&&"wallet-not-support-feature"===e.type}),m=Mr(()=>{var e;if("ready"!==r.state)return null;let t=Jc(r(),Np.walletsListConfiguration);const o=t.filter(le),i=t.filter(e=>!le(e));t=(o||[]).concat(i);const a=Np.preferredWalletAppName,s=t.find(e=>rd(e,a)),l=t.filter(e=>rd(e,a)).length>=2;a&&s&&!l&&(t=[u(d({},s),{isPreferred:!0})].concat(t.filter(e=>!rd(e,a))));const c=null!=(e=null==n?void 0:n.walletsRequiredFeatures)?e:null==n?void 0:n.walletsPreferredFeatures;return t.map(e=>{var t;return u(d({},e),{isSupportRequiredFeatures:!c||ln(null!=(t=e.features)?t:[],c)})})}),v=()=>{var e;return"loading"===(null==(e=Np.connectRequestParameters)?void 0:e.state)},w=Mr(()=>{var e;if(!v())return null==(e=Np.connectRequestParameters)?void 0:e.value}),y=e=>{n.closeModal(e)},b=t.onStatusChange(e=>{e&&y("wallet-selected")},e=>{var t;if(e instanceof ne){const n=e.cause.connectEvent.device.appName,r=null==(t=m())?void 0:t.find(e=>rd(e,n));if(!r)throw new G("Wallet not found");const o=r.isSupportRequiredFeatures?"missing-features":"not-supported";l(o),a(r)}}),C=()=>{h("all-wallets")},x=()=>{h("universal")},S=(e,t)=>{const n=ha().traceId;n&&Lp(Np.tracker,{isMobile:hu(),walletAppName:e.appName,surface:t,selectionSource:"manual",traceId:n}),a(e)},k=e=>{a(e),am.openWalletsModal()},E=()=>{a(null),l(null)};return jr(()=>{a(null),l(null),f(!1)}),jr(b),po(Ap,{get opened(){return fa()},get enableAndroidBackHandler(){return Np.enableAndroidBackHandler},onClose:()=>y("action-cancelled"),onClickQuestion:()=>f(e=>!e),get showFooter(){return!g()},"data-tc-wallets-modal-container":"true",get children(){return[po(xo,{get when(){return p()},get children(){return po(xf,{onBackClick:()=>f(!1)})}}),po(xo,{get when(){return!p()},get children(){return[po(xo,{get when(){return v()||!m()},get children(){return[po(Op,{translationKey:"walletModal.loading",children:"Wallets list is loading"}),po(Mp,{get children(){return po(Ed,{size:"m"})}})]}}),po(xo,{get when(){return Mo(()=>!v())()&&m()},get children(){return po(So,{get children(){return[po(ko,{get when(){return g()},get children(){return po(Ug,{get walletsList(){return m()},get currentWallet(){return null==n?void 0:n.wallet},onSelect:k,onSelectAllWallets:C,onDisconnect:()=>t.disconnect().catch(e=>Ri(e)),get walletsModalState(){return ha()},onClose:()=>y("action-cancelled")})}}),po(ko,{get when(){return i()},get children(){return po(Xo,{get component(){return hu()?Bf:hf},get walletsModalState(){return ha()},get wallet(){return i()},get additionalRequest(){return w()},selectionSource:"manual",onBackClick:E,get defaultError(){return s()}})}}),po(ko,{get when(){return"universal"===c()},get children(){return po(Xo,{get component(){return hu()?dg:yg},onSelect:e=>S(e,"universal-modal"),get walletModalState(){return ha()},get walletsList(){return m()},get additionalRequest(){return w()},onSelectAllWallets:C})}}),po(ko,{get when(){return"all-wallets"===c()},get children(){return po(Yp,{get walletsList(){return m()},get featureCheckMode(){return(null==n?void 0:n.walletsRequiredFeatures)?"strict":"soft"},onBack:x,get traceId(){return ha().traceId},onSelect:e=>S(e,"all-wallets-list")})}})]}})}})]}})]}})},Bg=di.div` + display: flex; + flex-direction: column; + align-items: center; + padding-bottom: 8px; +`,zg=di(sd)` + margin-top: 16px; +`,Fg=di(qc)` + font-weight: 510; + font-size: 16px; + line-height: 20px; + text-align: center; + max-width: 250px; + + color: ${e=>e.theme.colors.text.secondary}; +`,Kg=di(ws)` + min-width: 112px; + margin-top: 32px; +`,Hg=di(Ed)` + height: 16px; + width: 16px; +`,Vg=di(ws)` + margin-top: 32px; +`,$g=e=>{const t=vs(e),n=$r(wu),[r,o]=Tr(!0),[i,a]=Tr(!1),[s,l]=Tr(!1);let c,d;Or(()=>{const e=Sa();var t;a(!!e&&("executed"in e&&!!e.executed||(t=e,ca.has(t.name)))),l(!!e&&function(e){return da.has(e.name)}(e))}),(null==n?void 0:n.wallet)&&"universalLink"in n.wallet&&("universal-link"===n.wallet.openMethod||We(n.wallet.universalLink)&&Qn())&&(c=n.wallet.universalLink),(null==n?void 0:n.wallet)&&"deepLink"in n.wallet&&("custom-deeplink"===n.wallet.openMethod||We(n.wallet.deepLink)&&Qn())&&(d=n.wallet.deepLink);const u=()=>{const e=Sa(),t="returnStrategy"in e&&e.returnStrategy||Np.returnStrategy,n=!r();o(!1);const i=Li(c,{sessionId:e.sessionId,traceId:e.traceId});We(c)?Ni(i,{returnStrategy:t,twaReturnUrl:"twaReturnUrl"in e&&e.twaReturnUrl||Np.twaReturnUrl,forceRedirect:n}):Pi(i,d,{returnStrategy:t,forceRedirect:n},()=>{})};return po(Bg,wo(t,{get children(){return[Mo(()=>e.icon),po(zg,{get translationKey(){return e.headerTranslationKey},get translationValues(){return e.headerTranslationValues}}),po(Fg,{get translationKey(){return e.textTranslationKey},get translationValues(){return e.textTranslationValues}}),po(xo,{get when(){return!i()&&!s()&&("open-wallet"===e.showButton&&c||"open-wallet"!==e.showButton)},get children(){return po(Kg,{disabled:!0,"data-tc-connect-button-loading":"true",get children(){return po(Hg,{})}})}}),po(xo,{get when(){return i()},get children(){return[po(xo,{get when(){return"open-wallet"!==e.showButton},get children(){return po(Vg,{onClick:()=>e.onClose(),get children(){return po(uf,{translationKey:"common.close",children:"Close"})}})}}),po(xo,{get when(){return"open-wallet"===e.showButton&&c},get children(){return po(Vg,{onClick:u,get children(){return po(uf,{translationKey:"common.openWallet",children:"Open wallet"})}})}})]}})]}}))},Gg=e=>{const t=$r(wu),[n]=jc();return po($g,{headerTranslationKey:"actionModal.confirmTransaction.header",get headerTranslationValues(){return{name:t.wallet&&"name"in t.wallet?t.wallet.name:n("common.yourWallet",{},"Your wallet")}},textTranslationKey:"actionModal.confirmTransaction.text",get icon(){return po(Ed,{size:"m"})},onClose:()=>e.onClose(),showButton:"open-wallet","data-tc-confirm-modal":"true"})},Xg=e=>po($g,{headerTranslationKey:"actionModal.transactionCanceled.header",textTranslationKey:"actionModal.transactionCanceled.text",get icon(){return po(Cd,{size:"m"})},onClose:()=>e.onClose(),"data-tc-transaction-canceled-modal":"true"}),Zg=e=>po($g,{headerTranslationKey:"actionModal.transactionSent.header",textTranslationKey:"actionModal.transactionSent.text",get icon(){return po(vd,{size:"m"})},showButton:"open-wallet",onClose:()=>e.onClose(),"data-tc-transaction-sent-modal":"true"}),Yg=e=>{const t=$r(wu),[n]=jc();return po($g,{headerTranslationKey:"actionModal.signData.header",get headerTranslationValues(){return{name:t.wallet&&"name"in t.wallet?t.wallet.name:n("common.yourWallet",{},"Your wallet")}},textTranslationKey:"actionModal.signData.text",get icon(){return po(Ed,{size:"m"})},onClose:()=>e.onClose(),showButton:"open-wallet","data-tc-sign-data-confirm-modal":"true"})},Qg=e=>po($g,{headerTranslationKey:"actionModal.signDataCanceled.header",get icon(){return po(Cd,{size:"m"})},onClose:()=>e.onClose(),"data-tc-sign-data-canceled-modal":"true"}),Jg=e=>po($g,{headerTranslationKey:"actionModal.dataSigned.header",get icon(){return po(vd,{size:"m"})},onClose:()=>e.onClose(),"data-tc-data-signed-modal":"true"}),em=e=>{const t=$r(wu),[n]=jc();return po($g,{headerTranslationKey:"actionModal.signMessage.header",get headerTranslationValues(){return{name:t.wallet&&"name"in t.wallet?t.wallet.name:n("common.yourWallet",{},"Your wallet")}},textTranslationKey:"actionModal.signMessage.text",get icon(){return po(Ed,{size:"m"})},onClose:()=>e.onClose(),showButton:"open-wallet","data-tc-sign-message-confirm-modal":"true"})},tm=e=>po($g,{headerTranslationKey:"actionModal.messageSigned.header",get icon(){return po(vd,{size:"m"})},onClose:()=>e.onClose(),"data-tc-message-signed-modal":"true"}),nm=e=>po($g,{headerTranslationKey:"actionModal.signMessageCanceled.header",get icon(){return po(Cd,{size:"m"})},onClose:()=>e.onClose(),"data-tc-sign-message-canceled-modal":"true"}),rm=()=>po(sc,{get opened(){var e;return Mo(()=>null!==Sa())()&&!0===(null==(e=Sa())?void 0:e.openModal)},get enableAndroidBackHandler(){return Np.enableAndroidBackHandler},onClose:()=>ka(null),showFooter:!1,"data-tc-actions-modal-container":"true",get children(){return po(So,{get children(){return[po(ko,{get when(){return Sa().name===aa.sendTransaction},get children(){return po(Zg,{onClose:()=>ka(null)})}}),po(ko,{get when(){return Sa().name===sa.sendTransaction},get children(){return po(Xg,{onClose:()=>ka(null)})}}),po(ko,{get when(){return Sa().name===ia.sendTransaction},get children(){return po(Gg,{onClose:()=>ka(null)})}}),po(ko,{get when(){return Sa().name===aa.signData},get children(){return po(Jg,{onClose:()=>ka(null)})}}),po(ko,{get when(){return Sa().name===sa.signData},get children(){return po(Qg,{onClose:()=>ka(null)})}}),po(ko,{get when(){return Sa().name===ia.signData},get children(){return po(Yg,{onClose:()=>ka(null)})}}),po(ko,{get when(){return Sa().name===aa.signMessage},get children(){return po(tm,{onClose:()=>ka(null)})}}),po(ko,{get when(){return Sa().name===sa.signMessage},get children(){return po(nm,{onClose:()=>ka(null)})}}),po(ko,{get when(){return Sa().name===ia.signMessage},get children(){return po(em,{onClose:()=>ka(null)})}})]}})}}),om=()=>{const{locale:e}=jc()[1];Or(()=>e(Np.language)),Or(()=>{va()&&fu()});const t=$r(Ma),n=$r(wu),[r,o]=Tr(!1),i=()=>{var e;return"loading"===(null==(e=Np.connectRequestParameters)?void 0:e.state)},a=Mr(()=>{var e;if(!i())return null==(e=Np.connectRequestParameters)?void 0:e.value}),s=Mr(()=>({status:"opened",closeReason:null,traceId:ga().traceId})),l=e=>{n.closeSingleWalletModal(e)};return jr(t.onStatusChange(e=>{e&&l("wallet-selected")})),jr(()=>{o(!1)}),po(Ap,{get opened(){return va()},get enableAndroidBackHandler(){return Np.enableAndroidBackHandler},onClose:()=>l("action-cancelled"),onClickQuestion:()=>o(e=>!e),showFooter:!0,"data-tc-wallets-modal-container":"true",get children(){return[po(xo,{get when(){return r()},get children(){return po(xf,{onBackClick:()=>o(!1)})}}),po(xo,{get when(){return!r()},get children(){return[po(xo,{get when(){return i()},get children(){return[po(Op,{translationKey:"walletModal.loading",children:"Wallets list is loading"}),po(Mp,{get children(){return po(Ed,{size:"m"})}})]}}),po(xo,{get when(){return!i()},get children(){return po(Xo,{get component(){return hu()?Bf:hf},get wallet(){return wa()},get walletsModalState(){return s()},get additionalRequest(){return a()},selectionSource:"auto-dapp-directed",onBackClick:()=>{},backDisabled:!0})}})]}})]}})},im=e=>{const t=Wc(Aa,Np.language);return customElements.get("tc-root")||customElements.define(hi,class extends HTMLElement{}),document.body.hasAttribute("ontouchstart")||document.body.setAttribute("ontouchstart",""),po(Dc.Provider,{value:t,get children(){return po(wu.Provider,{get value(){return e.tonConnectUI},get children(){return po(Ma.Provider,{get value(){return Np.connector},get children(){return[po(gi,{}),po(si,{theme:ts,get children(){return[po(xo,{get when(){return Np.buttonRootId},get children(){return po(Go,{get mount(){return document.getElementById(Np.buttonRootId)},get children(){return po(Ip,{})}})}}),po(Xo,{component:hi,get children(){return[po(qg,{}),po(om,{}),po(rm,{})]}})]}})]}})}})}})},am={openWalletsModal:e=>{setTimeout(()=>pa(t=>{var n;return{status:"opened",traceId:null!=(n=null==e?void 0:e.traceId)?n:null==t?void 0:t.traceId,closeReason:null,embeddedRequest:null==e?void 0:e.embeddedRequest}}))},closeWalletsModal:e=>{setTimeout(()=>pa({status:"closed",closeReason:e}))},openSingleWalletModal:(e,t)=>{setTimeout(()=>ma({status:"opened",traceId:null==t?void 0:t.traceId,closeReason:null,walletInfo:e}))},closeSingleWalletModal:e=>{setTimeout(()=>ma({status:"closed",closeReason:e}))},openWalletNotSupportFeatureModal:(e,t)=>{setTimeout(()=>pa({status:"opened",traceId:t.traceId,closeReason:null,type:"wallet-not-support-feature",requiredFeature:e.requiredFeature}))},setAction:e=>{setTimeout(()=>ka(e))},clearAction:()=>{setTimeout(()=>ka(null))},getSelectedWalletInfo:()=>ba(),getLastVisibleWallets:()=>Ea(),removeSelectedWalletInfo:()=>xa(null),renderApp:(e,t)=>function(e,t,n,r={}){let o;return _r(r=>{o=r,t===document?e():Uo(t,e(),t.firstChild?null:void 0,n)},r.owner),()=>{o(),t.textContent=""}}(()=>po(im,{tonConnectUI:t}),document.getElementById(e))};class sm{constructor(e){this.consumers=[],this.state=ha(),this.connector=e.connector,this.tracker=e.tracker,this.setConnectRequestParametersCallback=e.setConnectRequestParametersCallback,Or(()=>{const e=ha();this.state=e,this.consumers.forEach(t=>t(e))}),Or(Wr(ba,(e,t)=>p(this,null,function*(){try{const{wallets:n,walletsMenu:r}=am.getLastVisibleWallets();if(e&&"appName"in e){if(t&&"appName"in t&&t.appName===e.appName)return;const o=yield this.connector.getSessionId();this.tracker.trackSelectedWallet(n.map(e=>e.name),e,r,"",void 0,o,this.state.traceId)}}catch(n){_i(n)}}))),Or(Wr(_a,e=>p(this,null,function*(){try{const{wallets:t,walletsMenu:n}=am.getLastVisibleWallets();if(De(e.link)){const r=ba(),o=yield this.connector.getSessionId();this.tracker.trackSelectedWallet(t.map(e=>e.name),r&&"appName"in r?r:null,n,e.link,e.type,o,this.state.traceId)}}catch(t){_i(t)}})))}open(e){return p(this,null,function*(){var t;const n=null!=(t=null==e?void 0:e.traceId)?t:rt();this.tracker.trackConnectionStarted(n);const r=(yield this.connector.getWallets()).find(ce);return r?this.connectEmbeddedWallet(r,{traceId:n}):this.openWalletsModal({traceId:n,embeddedRequest:null==e?void 0:e.embeddedRequest})})}close(e="action-cancelled"){"action-cancelled"===e&&this.tracker.trackConnectionError("Connection was cancelled"),am.closeWalletsModal(e)}onStateChange(e){return this.consumers.push(e),()=>{this.consumers=this.consumers.filter(t=>t!==e)}}connectEmbeddedWallet(e,t){const n=n=>{this.tracker.trackWalletSelected(e.appName,"embedded","auto-embedded",t.traceId),xa(e),this.connector.connect({jsBridgeKey:e.jsBridgeKey},n,{traceId:t.traceId})},r=Np.connectRequestParameters;"loading"===(null==r?void 0:r.state)?this.setConnectRequestParametersCallback(n):n(null==r?void 0:r.value)}openWalletsModal(e){return p(this,null,function*(){return Qn()&&Ti(),am.openWalletsModal({traceId:e.traceId,embeddedRequest:e.embeddedRequest}),new Promise(e=>{const t=this.onStateChange(n=>{const{status:r}=n;"opened"===r&&(t(),e())})})})}}class lm{constructor(e){this.consumers=[],this.connector=e.connector,Or(()=>{const e=Sa();this.consumers.forEach(t=>t(e))})}onStateChange(e){return this.consumers.push(e),()=>{this.consumers=this.consumers.filter(t=>t!==e)}}}class cm{constructor(e){this.consumers=[],this.state=ga(),this.connector=e.connector,this.tracker=e.tracker,this.setConnectRequestParametersCallback=e.setConnectRequestParametersCallback,Or(()=>{const e=ga();this.state=e,this.consumers.forEach(t=>t(e))})}open(e){return p(this,null,function*(){const t=rt();this.tracker.trackConnectionStarted(t);const n=Jc(yield this.connector.getWallets(),Np.walletsListConfiguration),r=n.find(ce);if(!!r)return this.connectEmbeddedWallet(r,{traceId:t});const o=n.filter(ue).find(t=>rd(t,e));if(!!o)return fu(),Lp(this.tracker,{isMobile:hu(),walletAppName:o.appName,surface:"single-wallet-modal",selectionSource:"auto-dapp-directed",traceId:t}),this.openSingleWalletModal(o,{traceId:t});const i=`Trying to open modal window with unknown wallet "${e}".`;throw this.tracker.trackConnectionError(i),new Ei(i)})}close(e="action-cancelled"){"action-cancelled"===e&&this.tracker.trackConnectionError("Connection was cancelled"),am.closeSingleWalletModal("action-cancelled")}onStateChange(e){return this.consumers.push(e),()=>{this.consumers=this.consumers.filter(t=>t!==e)}}connectEmbeddedWallet(e,t){const n=n=>{this.tracker.trackWalletSelected(e.appName,"embedded","auto-embedded",t.traceId),xa(e),this.connector.connect({jsBridgeKey:e.jsBridgeKey},n,{traceId:t.traceId})},r=Np.connectRequestParameters;"loading"===(null==r?void 0:r.state)?this.setConnectRequestParametersCallback(n):n(null==r?void 0:r.value)}openSingleWalletModal(e,t){return p(this,null,function*(){return Qn()&&Ti(),am.openSingleWalletModal(e,{traceId:null==t?void 0:t.traceId}),new Promise(e=>{const t=this.onStateChange(n=>{const{status:r}=n;"opened"===r&&(t(),e())})})})}}class dm{constructor(e){this.eventPrefix="ton-connect-ui-",this.tonConnectSdkVersion=null,this.eventDispatcher=null==e?void 0:e.eventDispatcher,this.tonConnectUiVersion=e.tonConnectUiVersion,this.init().catch()}get version(){return hn({ton_connect_sdk_lib:this.tonConnectSdkVersion,ton_connect_ui_lib:this.tonConnectUiVersion})}init(){return p(this,null,function*(){try{yield this.setRequestVersionHandler(),this.tonConnectSdkVersion=yield this.requestTonConnectSdkVersion()}catch(e){}})}setRequestVersionHandler(){return p(this,null,function*(){yield this.eventDispatcher.addEventListener("ton-connect-ui-request-version",()=>p(this,null,function*(){var e;let t=un(this.tonConnectUiVersion);try{const n=Xi();t=u(d({},t),{tma:Qn(),tmaPlatform:Zn(),tmaVersion:Qn()?er():null,telegramBrowser:Jn(),os:n.os,browser:n.browser,rawBrowser:null!=(e=(new xi).getBrowser().name)?e:null,mobile:Gi()})}catch(n){}yield this.eventDispatcher.dispatchEvent("ton-connect-ui-response-version",t)}))})}requestTonConnectSdkVersion(){return p(this,null,function*(){return new Promise((e,t)=>p(this,null,function*(){try{yield this.eventDispatcher.addEventListener("ton-connect-response-version",t=>{e(t.detail.version)},{once:!0}),yield this.eventDispatcher.dispatchEvent("ton-connect-request-version",{type:"request-version"})}catch(n){t(n)}}))})}dispatchUserActionEvent(e){var t;try{null==(t=this.eventDispatcher)||t.dispatchEvent(`${this.eventPrefix}${e.type}`,e).catch()}catch(n){}}trackWalletModalOpened(...e){try{const t=An(this.version,...e);this.dispatchUserActionEvent(t)}catch(t){}}trackSelectedWallet(...e){try{const t=On(this.version,...e);this.dispatchUserActionEvent(t)}catch(t){_i(t)}}trackWalletPreselected(...e){try{const t=Mn(this.version,...e);this.dispatchUserActionEvent(t)}catch(t){_i(t)}}trackWalletSelected(...e){try{const t=Nn(this.version,...e);this.dispatchUserActionEvent(t)}catch(t){_i(t)}}trackConnectionInitiated(...e){try{const t=gn(this.version,...e);this.dispatchUserActionEvent(t)}catch(t){_i(t)}}trackConnectionStarted(...e){try{const t=fn(this.version,...e);this.dispatchUserActionEvent(t)}catch(t){}}trackConnectionCompleted(...e){try{const t=vn(this.version,...e);this.dispatchUserActionEvent(t)}catch(t){}}trackConnectionError(...e){try{const t=wn(this.version,...e);this.dispatchUserActionEvent(t)}catch(t){}}trackConnectionRestoringStarted(...e){try{const t=yn(this.version,...e);this.dispatchUserActionEvent(t)}catch(t){}}trackConnectionRestoringCompleted(...e){try{const t=bn(this.version,...e);this.dispatchUserActionEvent(t)}catch(t){}}trackConnectionRestoringError(...e){try{const t=Cn(this.version,...e);this.dispatchUserActionEvent(t)}catch(t){}}trackDisconnection(...e){try{const t=In(this.version,...e);this.dispatchUserActionEvent(t)}catch(t){}}trackTransactionSentForSignature(...e){try{const t=Sn(this.version,...e);this.dispatchUserActionEvent(t)}catch(t){}}trackTransactionSigned(...e){try{const t=kn(this.version,...e);this.dispatchUserActionEvent(t)}catch(t){}}trackTransactionSigningFailed(...e){try{const t=En(this.version,...e);this.dispatchUserActionEvent(t)}catch(t){}}trackDataSentForSignature(...e){try{const t=Rn(this.version,...e);this.dispatchUserActionEvent(t)}catch(t){}}trackDataSigned(...e){try{const t=_n(this.version,...e);this.dispatchUserActionEvent(t)}catch(t){}}trackDataSigningFailed(...e){try{const t=Tn(this.version,...e);this.dispatchUserActionEvent(t)}catch(t){}}}class um{constructor(){this.userAgent=Xi()}getLocale(){var e;return(null==(e=navigator.languages)?void 0:e[0])||navigator.language||""}getBrowser(){var e;return null!=(e=this.userAgent.browser)?e:""}getPlatform(){var e;return null!=(e=this.userAgent.os)?e:""}getTelegramUser(){return tr()}getClientEnvironment(){return Qn()?"miniapp":"web"}}function hm(e){return"object"==typeof e&&null!==e&&"enableEmbeddedRequest"in e&&!0===e.enableEmbeddedRequest}e.BadRequestError=ge,e.Base64=L,e.BrowserEventDispatcher=Dn,e.Consumable=dr,e.FetchWalletsError=Be,e.LocalstorageNotFoundError=qe,e.MethodNotSupportedError=me,e.ParseHexError=Fe,e.SessionCrypto=H,e.THEME=Zo,e.TonConnect=ur,e.TonConnectError=G,e.TonConnectUI=class{constructor(e){var t;this.walletInfoStorage=new Ji,this.preferredWalletStorage=new ea,this.walletInfo=null,this.systemThemeChangeUnsubscribe=null,this.connectionRestored=Promise.resolve(!1);let n=null!=(t=null==e?void 0:e.eventDispatcher)?t:new Dn;if(e&&"connector"in e&&e.connector)this.connector=e.connector;else{if(!(e&&"manifestUrl"in e&&e.manifestUrl))throw new Ei("You have to specify a `manifestUrl` or a `connector` in the options.");this.connector=new ur({manifestUrl:e.manifestUrl,eventDispatcher:n,walletsRequiredFeatures:e.walletsRequiredFeatures,environment:new um,analytics:e.analytics})}this.tracker=new dm({eventDispatcher:n,tonConnectUiVersion:"5.0.1"}),this.modalManager=new sm({connector:this.connector,tracker:this.tracker,setConnectRequestParametersCallback:e=>{this.connectRequestParametersCallback=e}}),this.modal=this.modalManager,this.singleWalletModal=new cm({connector:this.connector,tracker:this.tracker,setConnectRequestParametersCallback:e=>{this.connectRequestParametersCallback=e}}),this.transactionModal=new lm({connector:this.connector}),this._walletsRequiredFeatures=e.walletsRequiredFeatures,this._walletsPreferredFeatures=e.walletsPreferredFeatures,this.walletsList=this.getWallets(),this.walletsList.then(e=>{return Hi((t=e.map(e=>e.imageUrl),[...new Set(t)]));var t});const r=this.normalizeWidgetRoot(null==e?void 0:e.widgetRootId);this.subscribeToWalletChange(),!1!==(null==e?void 0:e.restoreConnection)&&(this.connectionRestored=function(e){return p(this,null,function*(){return yield new Promise(e=>requestAnimationFrame(e)),e()})}(()=>p(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=es(e,{uiPreferences:{theme:"SYSTEM"}});const o=this.preferredWalletStorage.getPreferredWalletAppName();Pp({connector:this.connector,tracker:this.tracker,preferredWalletAppName:o}),am.renderApp(r,this)}static getWallets(){return ur.getWallets()}get walletsRequiredFeatures(){return this._walletsRequiredFeatures}get walletsPreferredFeatures(){return this._walletsPreferredFeatures}get connected(){return this.connector.connected}get account(){return this.connector.account}get wallet(){return this.connector.wallet?d(d({},this.connector.wallet),this.walletInfo):null}set uiOptions(e){var t,n,r,o,i,a,s;this.checkButtonRootExist(e.buttonRootId),this.actionsConfiguration=e.actionsConfiguration,"walletsRequiredFeatures"in e&&(this._walletsRequiredFeatures=e.walletsRequiredFeatures),"walletsPreferredFeatures"in e&&(this._walletsPreferredFeatures=e.walletsPreferredFeatures),(null==(t=e.uiPreferences)?void 0:t.theme)?"SYSTEM"!==(null==(n=e.uiPreferences)?void 0:n.theme)?(null==(r=this.systemThemeChangeUnsubscribe)||r.call(this),is(e.uiPreferences.theme,e.uiPreferences.colorsSet)):(is(window.matchMedia&&window.matchMedia("(prefers-color-scheme: light)").matches?Zo.LIGHT:Zo.DARK,e.uiPreferences.colorsSet),this.systemThemeChangeUnsubscribe||(this.systemThemeChangeUnsubscribe=function(e){const t=t=>e(t.matches?Zo.DARK:Zo.LIGHT);return window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change",t),()=>window.matchMedia("(prefers-color-scheme: dark)").removeEventListener("change",t)}(is))):(null==(o=e.uiPreferences)?void 0:o.colorsSet)&&(a=e.uiPreferences.colorsSet,os[Zo.DARK]=es(a[Zo.DARK],os[Zo.DARK]),os[Zo.LIGHT]=es(a[Zo.LIGHT],os[Zo.LIGHT]),ns(e=>({colors:es(os[e.theme],rs[e.theme])}))),(null==(i=e.uiPreferences)?void 0:i.borderRadius)&&(s=e.uiPreferences.borderRadius,ns({borderRadius:s})),Pp(t=>{var n,r;const o=es(d(d(d(d({},e.language&&{language:e.language}),!!(null==(n=e.actionsConfiguration)?void 0:n.returnStrategy)&&{returnStrategy:e.actionsConfiguration.returnStrategy}),!!(null==(r=e.actionsConfiguration)?void 0:r.twaReturnUrl)&&{twaReturnUrl:e.actionsConfiguration.twaReturnUrl}),!!e.walletsListConfiguration&&{walletsListConfiguration:e.walletsListConfiguration}),Ua(t));return void 0!==e.buttonRootId&&(o.buttonRootId=e.buttonRootId),void 0!==e.enableAndroidBackHandler&&(o.enableAndroidBackHandler=e.enableAndroidBackHandler),o})}setConnectRequestParameters(e){var t;Pp({connectRequestParameters:e}),"ready"!==(null==e?void 0:e.state)&&e||null==(t=this.connectRequestParametersCallback)||t.call(this,null==e?void 0:e.value)}setConnectionNetwork(e){this.connector.setConnectionNetwork(e)}getWallets(){return p(this,null,function*(){return this.connector.getWallets()})}onStatusChange(e,t){return this.connector.onStatusChange(t=>p(this,null,function*(){if(t){const n=yield this.getSelectedWalletInfo(t);e(d(d({},t),n||this.walletInfoStorage.getWalletInfo()))}else e(t)}),t)}openModal(e){return p(this,null,function*(){var t;const n=null!=(t=null==e?void 0:e.traceId)?t:rt();yield this.modal.open({traceId:n});const r=yield this.getSessionId(),o=am.getLastVisibleWallets();this.tracker.trackWalletModalOpened(o.wallets.map(e=>e.name),r,n)})}closeModal(e){this.modal.close(e)}onModalStateChange(e){return this.modal.onStateChange(e)}get modalState(){return this.modal.state}openSingleWalletModal(e){return p(this,null,function*(){return this.singleWalletModal.open(e)})}closeSingleWalletModal(e){this.singleWalletModal.close(e)}onSingleWalletModalStateChange(e){return this.singleWalletModal.onStateChange(e)}get singleWalletModalState(){return this.singleWalletModal.state}connectWallet(e){return p(this,null,function*(){var t;const n=null!=(t=null==e?void 0:e.traceId)?t:rt(),r=(yield this.getWallets()).find(ce);return r?yield this.connectEmbeddedWallet(r,{traceId:n}):yield this.connectExternalWallet({traceId:n})})}disconnect(e){var t;const n=null!=(t=null==e?void 0:e.traceId)?t:rt();return this.tracker.trackDisconnection(this.wallet,"dapp"),am.clearAction(),am.removeSelectedWalletInfo(),this.walletInfoStorage.removeWalletInfo(),this.connector.disconnect({traceId:n})}sendTransaction(e,t){return p(this,null,function*(){var n;const r=null!=(n=null==t?void 0:t.traceId)?n:rt();this.tracker.trackTransactionSentForSignature(this.wallet,e);const o={onAbort:()=>(this.tracker.trackTransactionSigningFailed(this.wallet,e,"Transaction was cancelled"),new Ei("Transaction was not sent")),sendRequestBuilder:t=>()=>p(this,null,function*(){const n=yield this.connector.sendTransaction(e,t);return this.tracker.trackTransactionSigned(this.wallet,e,n),n})},i="sendTransaction",a=hm(t);if(!this.connected&&a)return this.initiateEmbeddedRequestFlow({method:"sendTransaction",request:e},i,u(d({},t),{traceId:r}));if(!this.connected)throw this.tracker.trackTransactionSigningFailed(this.wallet,e,"Wallet was not connected"),new Ei("Connect wallet to send a transaction.");const s=yield this.initiateBridgeFlow(o,i,u(d({},t),{traceId:r}));return a?{hasResponse:!0,response:s,traceId:r}:s})}signData(e,t){return p(this,null,function*(){var n;const r=null!=(n=null==t?void 0:t.traceId)?n:rt();this.tracker.trackDataSentForSignature(this.wallet,e);const o={onAbort:()=>(this.tracker.trackDataSigningFailed(this.wallet,e,"SignData was cancelled"),new Ei("SignData was not sent")),sendRequestBuilder:t=>()=>p(this,null,function*(){const n=yield this.connector.signData(e,t);return this.tracker.trackDataSigned(this.wallet,e,n),n})},i="signData",a=hm(t);if(!this.connected&&a)return this.initiateEmbeddedRequestFlow({method:"signData",request:e},i,u(d({},t),{traceId:r}));if(!this.connected)throw this.tracker.trackDataSigningFailed(this.wallet,e,"Wallet was not connected"),new Ei("Connect wallet to sign data.");const s=yield this.initiateBridgeFlow(o,i,u(d({},t),{traceId:r}));return a?{hasResponse:!0,response:s,traceId:r}:s})}signMessage(e,t){return p(this,null,function*(){var n;const r=null!=(n=null==t?void 0:t.traceId)?n:rt(),o={onAbort:()=>new Ei("SignMessage was not sent"),sendRequestBuilder:t=>()=>p(this,null,function*(){return yield this.connector.signMessage(e,t)})},i="signMessage",a=hm(t);if(!this.connected&&a)return this.initiateEmbeddedRequestFlow({method:"signMessage",request:e},i,u(d({},t),{traceId:r}));if(!this.connected)throw new Ei("Connect wallet to sign a message.");const s=yield this.initiateBridgeFlow(o,i,u(d({},t),{traceId:r}));return a?{hasResponse:!0,response:s,traceId:r}:s})}getSessionId(){return p(this,null,function*(){var e,t;try{const n=null==(e=this.connector.dappSettings)?void 0:e.storage;if(n){const e=yield n.getItem("ton-connect-storage_bridge-connection");if(e){const n=JSON.parse(e);if("http"===n.type&&n.sessionCrypto){const e=new H(n.sessionCrypto);return e.sessionId}if("http"===n.type&&(null==(t=n.session)?void 0:t.sessionKeyPair)){const e=new H(n.session.sessionKeyPair);return e.sessionId}}}}catch(n){}return null})}redirectAfterRequestSent({returnStrategy:e,twaReturnUrl:t,forceRedirect:n,sessionId:r,traceId:o}){if(this.walletInfo&&"universalLink"in this.walletInfo&&("universal-link"===this.walletInfo.openMethod||"custom-deeplink"===this.walletInfo.openMethod)){const i=Li(this.walletInfo.universalLink,{sessionId:r,traceId:o});We(this.walletInfo.universalLink)?Ni(i,{returnStrategy:e,twaReturnUrl:t||Np.twaReturnUrl,forceRedirect:n||!1}):Pi(i,this.walletInfo.deepLink,{returnStrategy:e,forceRedirect:n||!1},()=>{})}}connectEmbeddedWallet(e,t){return p(this,null,function*(){const n=n=>{this.tracker.trackWalletSelected(e.appName,"embedded","auto-embedded",t.traceId),xa(e),this.connector.connect({jsBridgeKey:e.jsBridgeKey},n,{traceId:t.traceId})},r=Np.connectRequestParameters;return"loading"===(null==r?void 0:r.state)?this.connectRequestParametersCallback=n:n(null==r?void 0:r.value),yield this.waitForWalletConnection({ignoreErrors:!1,traceId:t.traceId})})}connectExternalWallet(e){return p(this,null,function*(){const t=new AbortController;am.openWalletsModal({traceId:e.traceId});const n=this.onModalStateChange(e=>{const{status:r,closeReason:o}=e;"opened"!==r&&(n(),"action-cancelled"===o&&t.abort())});return yield this.waitForWalletConnection({ignoreErrors:!0,signal:t.signal,traceId:e.traceId})})}waitForWalletConnection(e){return p(this,null,function*(){return new Promise((t,n)=>{this.tracker.trackConnectionStarted(e.traceId);const{ignoreErrors:r=!1,signal:o=null}=e;if(o&&o.aborted)return this.tracker.trackConnectionError("Connection was cancelled"),n(new Ei("Wallet was not connected"));const i=o=>p(this,null,function*(){if(o)this.tracker.trackConnectionCompleted(o,null,e.traceId),s(),t(o);else{if(this.tracker.trackConnectionError("Connection was cancelled"),r)return;s(),n(new Ei("Wallet was not connected"))}}),a=e=>{this.tracker.trackConnectionError(e.message),r||(s(),n(e))},s=this.onStatusChange(e=>i(e),e=>a(e));o&&o.addEventListener("abort",()=>{s(),n(new Ei("Wallet was not connected"))},{once:!0})})})}initiateEmbeddedRequestFlow(e,t,n){return p(this,null,function*(){const r=new dr(e),o=new AbortController;yield this.modalManager.open({traceId:n.traceId,embeddedRequest:r});const i=this.onModalStateChange(e=>{"opened"!==e.status&&(i(),"action-cancelled"===e.closeReason&&o.abort())}),a=(yield this.waitForWalletConnection({ignoreErrors:!0,signal:o.signal,traceId:n.traceId})).embeddedResponse;if(a){const{notifications:e,modals:r}=this.getModalsAndNotificationsConfiguration(n);if(!a.ok)throw am.setAction({name:sa[t],showNotification:e.includes("error"),openModal:r.includes("error"),traceId:n.traceId}),new Ei(a.error.message||"Wallet rejected the embedded request");return am.setAction({name:aa[t],showNotification:e.includes("success"),openModal:r.includes("success"),traceId:n.traceId}),{hasResponse:!0,response:a.result,traceId:n.traceId}}return{hasResponse:!1,connectResult:{dispatched:r.consumed},traceId:n.traceId}})}initiateBridgeFlow(e,t,n){return p(this,null,function*(){Qn()&&Ti();const{notifications:r,modals:o,returnStrategy:i,twaReturnUrl:a}=this.getModalsAndNotificationsConfiguration(n),s=yield this.getSessionId();am.setAction({name:ia[t],showNotification:r.includes("before"),openModal:o.includes("before"),executed:!1,sessionId:s||void 0,traceId:n.traceId,returnStrategy:i,twaReturnUrl:a});const l=new AbortController,c=()=>{var e;if(l.signal.aborted)return;am.setAction({name:ia[t],showNotification:r.includes("before"),openModal:o.includes("before"),executed:!0,sessionId:s||void 0,traceId:n.traceId,returnStrategy:i,twaReturnUrl:a}),this.redirectAfterRequestSent({returnStrategy:i,twaReturnUrl:a,sessionId:s||void 0,traceId:n.traceId});let c=!0;null==(e=null==n?void 0:n.onRequestSent)||e.call(n,()=>p(this,null,function*(){if(l.signal.aborted)return;const e=!c;c=!1,yield this.redirectAfterRequestSent({returnStrategy:i,twaReturnUrl:a,forceRedirect:e,sessionId:s||void 0,traceId:n.traceId})}))},d=this.onTransactionModalStateChange(e=>{(null==e?void 0:e.openModal)||(d(),e||l.abort())});try{const i=yield this.runConnectorRequestWithAbortHandling(l.signal,e.onAbort,e.sendRequestBuilder({onRequestSent:c,signal:l.signal,traceId:n.traceId}));return am.setAction({name:aa[t],showNotification:r.includes("success"),openModal:o.includes("success"),traceId:n.traceId}),i}catch(u){if(u instanceof te)throw am.clearAction(),am.openWalletNotSupportFeatureModal(u.cause,{traceId:n.traceId}),u;throw am.setAction({name:sa[t],showNotification:r.includes("error"),openModal:o.includes("error"),traceId:n.traceId}),u instanceof G?u:(console.error(u),new Ei("Unhandled error:"+u))}finally{d()}})}runConnectorRequestWithAbortHandling(e,t,n){return p(this,null,function*(){return new Promise((r,o)=>{if(e.aborted)return o(t());const i=()=>{o(t())};e.addEventListener("abort",i,{once:!0}),n().then(t=>{e.removeEventListener("abort",i),r(t)}).catch(t=>{e.removeEventListener("abort",i),o(t)})})})}onTransactionModalStateChange(e){return this.transactionModal.onStateChange(e)}subscribeToWalletChange(){this.connector.onStatusChange(e=>p(this,null,function*(){var t;e?(yield this.updateWalletInfo(e),this.setPreferredWalletAppName((null==(t=this.walletInfo)?void 0:t.appName)||e.device.appName)):this.walletInfoStorage.removeWalletInfo()}))}setPreferredWalletAppName(e){this.preferredWalletStorage.setPreferredWalletAppName(e),Pp({preferredWalletAppName:e})}getSelectedWalletInfo(e){return p(this,null,function*(){let t=am.getSelectedWalletInfo();if(!t)return null;if(!("name"in t)){if(e.device.appName===$p)return{type:"wallet-connect",name:Gp,appName:$p,imageUrl:Xp,aboutUrl:"https://reown.com/",features:e.device.features,platforms:[]};const n=Jc(yield this.walletsList,Np.walletsListConfiguration).find(t=>rd(t,e.device.appName));if(!n)throw new Ei(`Cannot find WalletInfo for the '${e.device.appName}' wallet`);return d(d({},n),t)}return t})}updateWalletInfo(e){return p(this,null,function*(){const t=yield this.getSelectedWalletInfo(e);if(t)return this.walletInfo=t,void this.walletInfoStorage.setWalletInfo(t);const n=this.walletInfoStorage.getWalletInfo();this.walletInfo=n||((yield this.walletsList).find(t=>rd(t,e.device.appName))||null)})}normalizeWidgetRoot(e){if(!e||!document.getElementById(e)){e="tc-widget-root";const t=document.createElement("div");t.id=e,document.body.appendChild(t)}return e}checkButtonRootExist(e){if(null!=e&&!document.getElementById(e))throw new Ei(`${e} element not found in the document.`)}getModalsAndNotificationsConfiguration(e){var t,n,r,o,i,a;const s=["before","success","error"];let l=s;(null==(t=this.actionsConfiguration)?void 0:t.notifications)&&"all"!==(null==(n=this.actionsConfiguration)?void 0:n.notifications)&&(l=this.actionsConfiguration.notifications),(null==e?void 0:e.notifications)&&(l="all"===e.notifications?s:e.notifications);let c=["before"];(null==(r=this.actionsConfiguration)?void 0:r.modals)&&(c="all"===this.actionsConfiguration.modals?s:this.actionsConfiguration.modals),(null==e?void 0:e.modals)&&(c="all"===e.modals?s:e.modals);const d=(null==e?void 0:e.returnStrategy)||(null==(o=this.actionsConfiguration)?void 0:o.returnStrategy)||"back",u=(null==e?void 0:e.twaReturnUrl)||(null==(i=this.actionsConfiguration)?void 0:i.twaReturnUrl);let h=(null==e?void 0:e.skipRedirectToWallet)||(null==(a=this.actionsConfiguration)?void 0:a.skipRedirectToWallet)||"ios";return Qn()&&(h="never"),{notifications:l,modals:c,returnStrategy:d,twaReturnUrl:u,skipRedirectToWallet:h}}},e.TonConnectUIError=Ei,e.UUIDv7=rt,e.UnknownAppError=ve,e.UnknownError=we,e.UserRejectsError=fe,e.WalletAlreadyConnectedError=Q,e.WalletMissingRequiredFeaturesError=ne,e.WalletNotConnectedError=J,e.WalletNotInjectedError=ee,e.WalletNotSupportFeatureError=te,e.WalletTransportError=oe,e.WalletWrongNetworkError=re,e.WalletsListManager=sn,e.WrongAddressError=ze,e.checkRequiredWalletFeatures=ln,e.concatUint8Arrays=B,e.createConnectionCompletedEvent=vn,e.createConnectionErrorEvent=wn,e.createConnectionInitiatedEvent=gn,e.createConnectionLinkGeneratedEvent=mn,e.createConnectionRestoringCompletedEvent=bn,e.createConnectionRestoringErrorEvent=Cn,e.createConnectionRestoringStartedEvent=yn,e.createConnectionStartedEvent=fn,e.createDataSentForSignatureEvent=Rn,e.createDataSignedEvent=_n,e.createDataSigningFailedEvent=Tn,e.createDisconnectionEvent=In,e.createRequestVersionEvent=dn,e.createResponseVersionEvent=un,e.createSelectedWalletEvent=On,e.createTransactionSentForSignatureEvent=Sn,e.createTransactionSignedEvent=kn,e.createTransactionSigningFailedEvent=En,e.createVersionInfo=hn,e.createWalletModalOpenedEvent=An,e.createWalletPreselectedEvent=Mn,e.createWalletSelectedEvent=Nn,e.decodeEmbeddedRequestParam=function(e){const t=function(e){const t=e.length+(4-e.length%4)%4,n=e.replace(/-/g,"+").replace(/_/g,"/").padEnd(t,"=");return L.decode(n).toString()}(e);return q(JSON.parse(t))},e.decodeTelegramUrlParameters=Ue,e.decodeWireEmbeddedRequest=q,e.describeWalletConnectionSource=se,e.enableQaMode=function(){tn=!0,console.warn("🚨 QA Mode enabled - validation is disabled. This is unsafe for production!"),on(),function(){if("undefined"==typeof window||nn)return;nn=new MutationObserver(e=>{e.forEach(e=>{"childList"===e.type&&e.removedNodes.forEach(e=>{if(e.nodeType===Node.ELEMENT_NODE){const t=e;"ton-connect-qa-banner"===t.id&&tn?(console.warn("QA Mode banner was removed, restoring..."),setTimeout(()=>on(),100)):"ton-connect-qa-mode-styles"===t.id&&tn&&(console.warn("QA Mode styles were removed, restoring..."),setTimeout(()=>an(),100))}})})}),nn.observe(document.body,{childList:!0,subtree:!1}),nn.observe(document.head,{childList:!0,subtree:!1})}(),an()},e.encodeTelegramUrlParameters=je,e.getTgUser=tr,e.getTmaPlatform=Zn,e.getTmaWebAppVersion=er,e.hasItems=he,e.hasMessages=pe,e.hexToByteArray=K,e.initializeWalletConnect=function(e,t){if(void 0!==(null==rr?void 0:rr.walletConnectOptions)||void 0!==(null==rr?void 0:rr.UniversalConnectorCls))throw new G("Wallet Connect already initialized.");if("function"!=typeof e||!("init"in e))throw new G("Initialize UniversalConnectorCls must be set");rr.UniversalConnectorCls=e,rr.walletConnectOptions=t},e.isConnectUrl=De,e.isInTMA=Qn,e.isInTelegramBrowser=Jn,e.isNode=function(){return"undefined"!=typeof process&&null!=process.versions&&null!=process.versions.node},e.isQaModeEnabled=rn,e.isTelegramUrl=We,e.isTmaPlatform=Yn,e.isWalletConnectInitialized=or,e.isWalletInfoCurrentlyEmbedded=ce,e.isWalletInfoCurrentlyInjected=le,e.isWalletInfoInjectable=de,e.isWalletInfoInjected=function(e){return"jsBridgeKey"in e},e.isWalletInfoRemote=ue,e.splitToUint8Arrays=z,e.toHexString=F,e.toUserFriendlyAddress=Ct,Object.defineProperty(e,Symbol.toStringTag,{value:"Module"})}); +//# sourceMappingURL=tonconnect-ui.min.js.map