@tangle-network/blueprint-ui 0.5.2 → 0.5.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/styles.css CHANGED
@@ -293,6 +293,7 @@
293
293
  .outline-none{--un-outline-style:none;outline-style:none;}
294
294
  .focus\:outline-none:focus{--un-outline-style:none;outline-style:none;}
295
295
  .\[\&_tr\:last-child\]\:border-0 tr:last-child{border-width:0px;}
296
+ .b,
296
297
  .border{border-width:1px;}
297
298
  .border-2{border-width:2px;}
298
299
  .border-b{border-bottom-width:1px;}
@@ -1,8 +1,48 @@
1
1
  export { T as TANGLE_CLOUD_ORIGINS_DEFAULT, d as detectTangleCloudParentOrigin } from '../detectParentOrigin-BYruoIdc.js';
2
2
  import * as wagmi from 'wagmi';
3
+ import { CreateConnectorFn } from 'wagmi';
3
4
  import { Address } from 'viem';
4
5
  export { A as AccountChanged, C as CallJobRequest, a as ChainChanged, b as ChainContext, H as HandshakeAck, c as HandshakeRequest, I as IframeRequest, J as JobInputs, d as JobResultEvent, e as JobResultStatus, N as NO_WALLET_ADDRESS, P as ParentMessage, R as ReadAccountRequest, f as ReadAccountResult, S as ServiceContextBroadcast, g as ServiceContextJob, h as ServiceContextOperator, i as SignMessageRequest, j as SignMessageResult, k as SignTransactionRequest, l as SignTransactionResult, m as SignTypedDataRequest, n as SignTypedDataResult, o as SwitchChainRequest, p as SwitchChainResult, T as TANGLE_IFRAME_PROTOCOL_PREFIX, q as TANGLE_IFRAME_PROTOCOL_VERSION, r as makeCorrelationId } from '../parentBridgeProtocol-BSgLXg9g.js';
5
6
 
7
+ interface TangleBlueprintConnectorsOptions {
8
+ /** App id reported to the parent dapp on handshake (when embedded). */
9
+ appId: string;
10
+ /**
11
+ * Connectors used when running STANDALONE (the app's own domain) — e.g.
12
+ * `[injected(), walletConnect({ projectId })]`. Ignored when embedded.
13
+ */
14
+ standalone: CreateConnectorFn[];
15
+ /** Extra trusted parent origins (staging / preview deploys). */
16
+ extraOrigins?: readonly string[];
17
+ /** Override the bridged-request timeout (ms). */
18
+ requestTimeoutMs?: number;
19
+ }
20
+ /**
21
+ * One connector list, two deployment modes — so a blueprint app can ship a
22
+ * single build that runs both standalone and embedded in Tangle Cloud:
23
+ *
24
+ * - **Embedded** (a trusted Tangle Cloud parent is detected): the
25
+ * parent-bridge connector is the *only* connector. The sandboxed iframe
26
+ * can't inject a wallet extension, so it inherits / drives the parent's
27
+ * wallet over the postMessage bridge — surfacing injected/WalletConnect
28
+ * here would just dead-end.
29
+ * - **Standalone** (no trusted parent): the app's own `standalone`
30
+ * connectors, exactly as a normal dapp.
31
+ *
32
+ * The choice is made at runtime from the embedding context, so the same
33
+ * artifact works in both places with no build flags.
34
+ *
35
+ * createConfig({
36
+ * chains,
37
+ * transports,
38
+ * connectors: tangleBlueprintConnectors({
39
+ * appId: 'trading-arena',
40
+ * standalone: [injected(), walletConnect({ projectId })],
41
+ * }),
42
+ * })
43
+ */
44
+ declare function tangleBlueprintConnectors(options: TangleBlueprintConnectorsOptions): CreateConnectorFn[];
45
+
6
46
  type EventName = 'accountsChanged' | 'chainChanged' | 'connect' | 'disconnect' | 'message';
7
47
  type Listener = (...args: unknown[]) => void;
8
48
  type ParentBridgeOptions = {
@@ -91,4 +131,4 @@ declare class ParentBridgeProvider {
91
131
  type ParentBridgeConnectorOptions = ParentBridgeOptions;
92
132
  declare function parentBridgeConnector(options: ParentBridgeConnectorOptions): wagmi.CreateConnectorFn<ParentBridgeProvider, Record<string, unknown>, Record<string, unknown>>;
93
133
 
94
- export { type ParentBridgeConnectorOptions, type ParentBridgeOptions, ParentBridgeProvider, isRunningInIframe, parentBridgeConnector };
134
+ export { type ParentBridgeConnectorOptions, type ParentBridgeOptions, ParentBridgeProvider, type TangleBlueprintConnectorsOptions, isRunningInIframe, parentBridgeConnector, tangleBlueprintConnectors };
@@ -440,6 +440,23 @@ function parentBridgeConnector(options) {
440
440
  };
441
441
  });
442
442
  }
443
+
444
+ // src/wallet/tangleConnectors.ts
445
+ function tangleBlueprintConnectors(options) {
446
+ const parentOrigin = detectTangleCloudParentOrigin({
447
+ extraOrigins: options.extraOrigins
448
+ });
449
+ if (parentOrigin === null) {
450
+ return options.standalone;
451
+ }
452
+ return [
453
+ parentBridgeConnector({
454
+ parentOrigin,
455
+ appId: options.appId,
456
+ ...options.requestTimeoutMs !== void 0 ? { requestTimeoutMs: options.requestTimeoutMs } : {}
457
+ })
458
+ ];
459
+ }
443
460
  export {
444
461
  NO_WALLET_ADDRESS,
445
462
  ParentBridgeProvider,
@@ -449,6 +466,7 @@ export {
449
466
  detectTangleCloudParentOrigin,
450
467
  isRunningInIframe,
451
468
  makeCorrelationId,
452
- parentBridgeConnector
469
+ parentBridgeConnector,
470
+ tangleBlueprintConnectors
453
471
  };
454
472
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/wallet/parentBridgeConnector.ts","../../src/wallet/parentBridgeProvider.ts"],"sourcesContent":["// Wagmi connector that proxies wallet operations to the Tangle Cloud parent\n// dapp via the iframe postMessage bridge. Becomes the autoConnect target\n// when this app is loaded inside an iframe sandbox without a window.ethereum\n// — i.e. always, when embedded by cloud.tangle.tools.\n//\n// Architecture: the connector owns one `ParentBridgeProvider` (singleton),\n// forwards every wagmi method to it, and reflects the provider's EIP-1193\n// events back to wagmi's emitter so the rest of the dapp (ConnectKit's\n// account chip, hooks like useAccount/useChainId) reacts to parent-state\n// changes without polling.\n\nimport type { Address, Chain } from 'viem';\nimport { createConnector } from 'wagmi';\n\nimport { ParentBridgeProvider, type ParentBridgeOptions } from './parentBridgeProvider';\n\nexport type ParentBridgeConnectorOptions = ParentBridgeOptions;\n\nexport function parentBridgeConnector(options: ParentBridgeConnectorOptions) {\n let provider: ParentBridgeProvider | undefined;\n let installed = false;\n\n return createConnector<ParentBridgeProvider>((config) => {\n const ensureProvider = (): ParentBridgeProvider => {\n if (!provider) provider = new ParentBridgeProvider(options);\n if (!installed) {\n provider.install();\n installed = true;\n // Wire the provider's EIP-1193 events to wagmi's emitter so\n // ConnectKit and useAccount/useChainId reflect parent-state changes\n // without polling.\n provider.on('accountsChanged', (accounts) => {\n config.emitter.emit('change', {\n accounts: Array.isArray(accounts)\n ? (accounts as readonly Address[])\n : ([] as readonly Address[]),\n });\n });\n provider.on('chainChanged', (chainIdHex) => {\n const chainId =\n typeof chainIdHex === 'string'\n ? Number.parseInt(chainIdHex, 16)\n : Number(chainIdHex);\n if (Number.isFinite(chainId)) {\n config.emitter.emit('change', { chainId });\n }\n });\n provider.on('disconnect', () => {\n config.emitter.emit('disconnect');\n });\n }\n return provider;\n };\n\n return {\n id: 'tangleParentBridge',\n name: 'Tangle Cloud',\n type: 'parentBridge',\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n async connect(): Promise<any> {\n // wagmi v3's connect() return type is a conditional based on\n // `withCapabilities`. We always return plain addresses; cast through\n // `any` rather than re-implementing the type predicate.\n const p = ensureProvider();\n const accountsResult = (await p.request({\n method: 'eth_requestAccounts',\n })) as readonly Address[];\n const chainIdHex = (await p.request({ method: 'eth_chainId' })) as string;\n const chainId = Number.parseInt(chainIdHex, 16);\n return {\n accounts: accountsResult,\n chainId: Number.isFinite(chainId) ? chainId : 0,\n };\n },\n\n async disconnect() {\n // Disconnect from the iframe's perspective is a local-only state\n // reset — we can't ask the parent dapp to disconnect its wallet on\n // our behalf, and a real disconnect should be initiated from the\n // parent's UI. Tear down listeners + the message bridge so a future\n // reconnect re-handshakes cleanly.\n if (provider) provider.uninstall();\n installed = false;\n provider = undefined;\n },\n\n async getAccounts() {\n const p = ensureProvider();\n const cached = p.getCachedAccount();\n if (cached) return [cached];\n const accounts = (await p.request({\n method: 'eth_accounts',\n })) as readonly Address[];\n return accounts;\n },\n\n async getChainId() {\n const p = ensureProvider();\n const cached = p.getCachedChainId();\n if (cached !== null) return cached;\n const chainIdHex = (await p.request({ method: 'eth_chainId' })) as string;\n const chainId = Number.parseInt(chainIdHex, 16);\n return Number.isFinite(chainId) ? chainId : 0;\n },\n\n async getProvider() {\n return ensureProvider();\n },\n\n async isAuthorized() {\n // Always authorized when in iframe mode — the parent dapp has\n // already gated access by being the embedder. Returning `true`\n // makes wagmi auto-reconnect on every page load, which is the\n // right UX (iframe → parent wallet is always-on).\n try {\n const p = ensureProvider();\n const accounts = (await p.request({\n method: 'eth_accounts',\n })) as readonly Address[];\n return accounts.length > 0;\n } catch {\n return false;\n }\n },\n\n async switchChain({ chainId }): Promise<Chain> {\n const p = ensureProvider();\n await p.request({\n method: 'wallet_switchEthereumChain',\n params: [{ chainId: `0x${chainId.toString(16)}` }],\n });\n const chain = config.chains.find((c) => c.id === chainId);\n if (!chain) {\n throw new Error(`Chain ${chainId} not configured for this app`);\n }\n return chain;\n },\n\n onAccountsChanged(accounts) {\n config.emitter.emit('change', {\n accounts: accounts as readonly Address[],\n });\n },\n onChainChanged(chainIdHex) {\n const chainId = Number.parseInt(chainIdHex, 16);\n if (Number.isFinite(chainId)) {\n config.emitter.emit('change', { chainId });\n }\n },\n onDisconnect() {\n config.emitter.emit('disconnect');\n },\n };\n });\n}\n","// EIP-1193 provider implementation that proxies wallet calls to the parent\n// dapp via window.postMessage. The iframe doesn't talk to a wallet directly\n// — it inherits the parent's connected account + chain, and forwards signing\n// requests through the existing tangle.app.* protocol.\n//\n// This is the lowest layer of the parent-bridge stack. Wagmi sees this as a\n// regular Ethereum provider and routes `eth_accounts`, `eth_chainId`,\n// `personal_sign`, `eth_sendTransaction`, `wallet_switchEthereumChain`, etc.\n// through it.\n\nimport type { Address, Hex } from 'viem';\n\nimport {\n makeCorrelationId,\n NO_WALLET_ADDRESS,\n TANGLE_IFRAME_PROTOCOL_VERSION,\n type ConnectResult,\n type ParentMessage,\n type ReadAccountResult,\n type SignMessageResult,\n type SignTransactionResult,\n type SwitchChainResult,\n} from './parentBridgeProtocol';\n\ntype EventName = 'accountsChanged' | 'chainChanged' | 'connect' | 'disconnect' | 'message';\ntype Listener = (...args: unknown[]) => void;\n\ntype PendingRequest<T> = {\n resolve: (value: T) => void;\n reject: (reason: Error) => void;\n expectedKind: ParentMessage['kind'];\n};\n\nexport type ParentBridgeOptions = {\n /**\n * Origin of the parent dapp that hosts this iframe. The provider posts to\n * `window.parent` with this exact origin and rejects inbound messages from\n * any other origin. Pass `'*'` only in development; production must pin to\n * the real parent (`https://cloud.tangle.tools` or its develop equivalent).\n */\n parentOrigin: string;\n /**\n * Stable identifier for this iframe app. The parent includes this in the\n * handshake ack so dev tooling can correlate logs across the two windows.\n */\n appId: string;\n /**\n * Optional ms timeout for each bridged request. Defaults to 60 seconds —\n * long enough for a user to read + approve a signing prompt in the parent.\n */\n requestTimeoutMs?: number;\n};\n\nconst DEFAULT_REQUEST_TIMEOUT_MS = 60_000;\n// Connecting is gated on the user interacting with the parent's modal — allow\n// a generous window rather than the standard per-request timeout.\nconst CONNECT_REQUEST_TIMEOUT_MS = 300_000;\n\n/**\n * Detect iframe execution context. When this returns `false` the bridge\n * connector should not be installed and the host app should fall back to its\n * normal wallet config (ConnectKit + injected/walletConnect).\n *\n * `window.parent !== window` is the most reliable signal that works across\n * sandbox-iframe contexts where direct property access to parent throws.\n */\nexport function isRunningInIframe(): boolean {\n if (typeof window === 'undefined') return false;\n try {\n return window.parent !== undefined && window.parent !== window;\n } catch {\n // Cross-origin read of `window.parent` shouldn't throw, but be defensive.\n return true;\n }\n}\n\n/**\n * EIP-1193 provider backed by the Tangle Cloud iframe protocol. One instance\n * lives per iframe app; the wagmi connector owns the singleton.\n */\nexport class ParentBridgeProvider {\n private listeners = new Map<EventName, Set<Listener>>();\n private pending = new Map<string, PendingRequest<unknown>>();\n private cachedAccount: Address | null = null;\n private cachedChainId: number | null = null;\n private handshakeAcked = false;\n private handshakeWaiters: Array<() => void> = [];\n private installed = false;\n\n constructor(private readonly options: ParentBridgeOptions) {}\n\n /**\n * Wire up the global message listener and send the initial handshake.\n * Idempotent — safe to call repeatedly during reconnect attempts.\n */\n install(): void {\n if (this.installed || typeof window === 'undefined') return;\n this.installed = true;\n window.addEventListener('message', this.handleParentMessage);\n this.postToParent({\n kind: 'tangle.app.handshake',\n appId: this.options.appId,\n version: TANGLE_IFRAME_PROTOCOL_VERSION,\n });\n }\n\n uninstall(): void {\n if (!this.installed || typeof window === 'undefined') return;\n this.installed = false;\n window.removeEventListener('message', this.handleParentMessage);\n // Reject every pending request so callers don't hang forever.\n for (const [, pending] of this.pending) {\n pending.reject(new Error('Parent bridge uninstalled'));\n }\n this.pending.clear();\n }\n\n // ── EIP-1193 surface ────────────────────────────────────────────────────\n\n async request(req: { method: string; params?: unknown[] }): Promise<unknown> {\n const method = req.method;\n const params = (req.params ?? []) as unknown[];\n switch (method) {\n case 'eth_chainId': {\n await this.ensureBootstrapped();\n return this.cachedChainId !== null ? `0x${this.cachedChainId.toString(16)}` : '0x0';\n }\n case 'eth_accounts': {\n // Passive read — never opens a modal.\n await this.ensureBootstrapped();\n return this.cachedAccount !== null ? [this.cachedAccount] : [];\n }\n case 'eth_requestAccounts': {\n // Active connect (the wallet \"Connect\" button). If the parent has no\n // wallet yet, delegate to it to open its connect modal and wait.\n await this.ensureBootstrapped();\n if (this.cachedAccount !== null) return [this.cachedAccount];\n const account = await this.requestConnect();\n return account !== null ? [account] : [];\n }\n case 'personal_sign': {\n const [message, _signer] = params as [string, Address];\n return this.requestSignMessage(message);\n }\n case 'eth_signTypedData_v4': {\n // The current protocol doesn't carry typed-data — surface a clear\n // error rather than silently producing a personal_sign. Publishers\n // that need typed-data signing should upgrade the protocol.\n throw bridgeError(\n 4200,\n 'eth_signTypedData_v4 is not supported by the parent-bridge protocol yet.',\n );\n }\n case 'eth_sendTransaction': {\n const [tx] = params as [\n { to?: Address; data?: Hex; value?: Hex | string; chainId?: Hex | number },\n ];\n if (!tx?.to || !tx.data) {\n throw bridgeError(-32602, 'eth_sendTransaction requires `to` and `data`.');\n }\n return this.requestSignTransaction(tx);\n }\n case 'wallet_switchEthereumChain': {\n const [{ chainId }] = params as [{ chainId: Hex }];\n const numeric = Number.parseInt(chainId, 16);\n if (!Number.isFinite(numeric) || numeric <= 0) {\n throw bridgeError(-32602, `Invalid chainId: ${chainId}`);\n }\n await this.requestSwitchChain(numeric);\n return null;\n }\n case 'wallet_addEthereumChain': {\n // The parent owns the chain registry; iframes can't add chains the\n // dapp doesn't already know about.\n throw bridgeError(\n 4200,\n 'wallet_addEthereumChain is not supported through the parent bridge.',\n );\n }\n default:\n throw bridgeError(4200, `Method ${method} not supported by parent bridge.`);\n }\n }\n\n on(event: EventName, listener: Listener): void {\n const set = this.listeners.get(event) ?? new Set();\n set.add(listener);\n this.listeners.set(event, set);\n }\n\n removeListener(event: EventName, listener: Listener): void {\n this.listeners.get(event)?.delete(listener);\n }\n\n // ── Internal: dispatch + book-keeping ───────────────────────────────────\n\n private postToParent(message: object): void {\n if (typeof window === 'undefined') return;\n try {\n window.parent.postMessage(message, this.options.parentOrigin);\n } catch {\n // Cross-origin / sandboxed; parent.postMessage shouldn't actually throw\n // but be defensive against future browser changes.\n }\n }\n\n private handleParentMessage = (event: MessageEvent): void => {\n // Origin gate first; never parse untrusted payloads.\n if (event.origin !== this.options.parentOrigin) return;\n const data = event.data;\n if (typeof data !== 'object' || data === null) return;\n const message = data as ParentMessage;\n switch (message.kind) {\n case 'tangle.app.handshakeAck':\n this.handshakeAcked = true;\n for (const resolve of this.handshakeWaiters) resolve();\n this.handshakeWaiters = [];\n // After ack, ask for the current account so cached state reflects\n // reality before any consumer queries. Fire-and-forget — explicit\n // calls (`eth_accounts`, etc.) await their own request.\n this.sendReadAccount().catch(() => {\n // The first read commonly races with bridge teardown in tests\n // and isn't user-facing; swallow rather than producing unhandled\n // rejections. Subsequent `eth_accounts` calls retry on demand.\n });\n return;\n case 'tangle.app.readAccountResult':\n case 'tangle.app.connectResult':\n this.resolvePending(message);\n if (message.ok) {\n this.updateAccount(\n message.data.account === NO_WALLET_ADDRESS\n ? null\n : message.data.account,\n );\n this.updateChainId(message.data.chainId);\n }\n return;\n case 'tangle.app.switchChainResult':\n this.resolvePending(message);\n if (message.ok) this.updateChainId(message.data.chainId);\n return;\n case 'tangle.app.signMessageResult':\n case 'tangle.app.signTransactionResult':\n this.resolvePending(message);\n return;\n case 'tangle.app.accountChanged':\n this.updateAccount(message.account);\n return;\n case 'tangle.app.chainChanged':\n this.updateChainId(message.chainId);\n return;\n }\n };\n\n private sendReadAccount(): Promise<{ account: Address; chainId: number }> {\n return this.dispatch({\n kind: 'tangle.app.readAccount',\n expectedKind: 'tangle.app.readAccountResult',\n }) as Promise<{ account: Address; chainId: number }>;\n }\n\n /**\n * Ask the parent to connect a wallet (opening its modal if needed) and wait\n * for the result. Long timeout — the user is interacting with the modal.\n */\n private requestConnect(): Promise<Address | null> {\n return this.dispatch({\n kind: 'tangle.app.requestConnect',\n expectedKind: 'tangle.app.connectResult',\n timeoutMs: CONNECT_REQUEST_TIMEOUT_MS,\n }).then((data) => {\n const { account } = data as { account: Address; chainId: number };\n return account === NO_WALLET_ADDRESS ? null : account;\n });\n }\n\n private requestSignMessage(message: string): Promise<Hex> {\n const chainId = this.cachedChainId ?? 1;\n return this.dispatch({\n kind: 'tangle.app.signMessage',\n expectedKind: 'tangle.app.signMessageResult',\n payload: { chainId, message },\n }).then((data) => (data as { signature: Hex }).signature);\n }\n\n private requestSignTransaction(tx: {\n to?: Address;\n data?: Hex;\n value?: Hex | string;\n }): Promise<Hex> {\n const chainId = this.cachedChainId ?? 1;\n const value =\n typeof tx.value === 'string' && tx.value.startsWith('0x')\n ? BigInt(tx.value).toString(10)\n : typeof tx.value === 'string'\n ? tx.value\n : undefined;\n return this.dispatch({\n kind: 'tangle.app.signTransaction',\n expectedKind: 'tangle.app.signTransactionResult',\n payload: {\n chainId,\n to: tx.to as Address,\n data: tx.data as Hex,\n ...(value !== undefined ? { value } : {}),\n },\n }).then((data) => (data as { txHash: Hex }).txHash);\n }\n\n private requestSwitchChain(chainId: number): Promise<number> {\n return this.dispatch({\n kind: 'tangle.app.switchChain',\n expectedKind: 'tangle.app.switchChainResult',\n payload: { chainId },\n }).then((data) => (data as { chainId: number }).chainId);\n }\n\n private async dispatch(req: {\n kind:\n | 'tangle.app.readAccount'\n | 'tangle.app.switchChain'\n | 'tangle.app.signMessage'\n | 'tangle.app.signTransaction'\n | 'tangle.app.requestConnect';\n expectedKind: ParentMessage['kind'];\n payload?: Record<string, unknown>;\n timeoutMs?: number;\n }): Promise<unknown> {\n await this.ensureBootstrapped();\n const correlationId = makeCorrelationId(req.kind);\n const timeout = req.timeoutMs ?? this.options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;\n return new Promise<unknown>((resolve, reject) => {\n const timer = window.setTimeout(() => {\n this.pending.delete(correlationId);\n reject(bridgeError(4900, `Parent did not respond to ${req.kind} within ${timeout}ms`));\n }, timeout);\n this.pending.set(correlationId, {\n resolve: (v) => {\n window.clearTimeout(timer);\n resolve(v);\n },\n reject: (e) => {\n window.clearTimeout(timer);\n reject(e);\n },\n expectedKind: req.expectedKind,\n });\n this.postToParent({\n kind: req.kind,\n correlationId,\n ...(req.payload ?? {}),\n });\n });\n }\n\n /**\n * Resolves wallet-shape responses (`{ ok, data | error }`). Job results\n * use a different envelope (`{ status, data?, chunk?, error? }`) and are\n * routed through a separate listener registered by `useCallJob` / the SDK\n * — the provider doesn't double-handle them.\n */\n private resolvePending(\n message:\n | ReadAccountResult\n | ConnectResult\n | SwitchChainResult\n | SignMessageResult\n | SignTransactionResult,\n ): void {\n const entry = this.pending.get(message.correlationId);\n if (!entry) return;\n this.pending.delete(message.correlationId);\n if (entry.expectedKind !== message.kind) {\n entry.reject(\n bridgeError(\n -32000,\n `Parent replied with ${message.kind} but ${entry.expectedKind} was expected`,\n ),\n );\n return;\n }\n if (message.ok) {\n entry.resolve(message.data);\n } else {\n entry.reject(bridgeError(4001, message.error));\n }\n }\n\n private async ensureBootstrapped(): Promise<void> {\n if (this.handshakeAcked) return;\n this.install();\n await new Promise<void>((resolve) => {\n this.handshakeWaiters.push(resolve);\n // Re-send handshake every 500ms while we wait — covers a parent that\n // mounted after the iframe and missed the initial post.\n const retry = window.setInterval(() => {\n if (this.handshakeAcked) {\n window.clearInterval(retry);\n return;\n }\n this.postToParent({\n kind: 'tangle.app.handshake',\n appId: this.options.appId,\n version: TANGLE_IFRAME_PROTOCOL_VERSION,\n });\n }, 500);\n // Safety stop — handshake won't be re-attempted indefinitely.\n window.setTimeout(() => window.clearInterval(retry), 10_000);\n });\n }\n\n private updateAccount(next: Address | null): void {\n if (this.cachedAccount === next) return;\n const prev = this.cachedAccount;\n this.cachedAccount = next;\n if (next === null && prev !== null) {\n this.emit('disconnect');\n this.emit('accountsChanged', []);\n } else if (next !== null) {\n this.emit('accountsChanged', [next]);\n if (prev === null) {\n this.emit('connect', { chainId: this.cachedChainId ?? 0 });\n }\n }\n }\n\n private updateChainId(next: number): void {\n if (this.cachedChainId === next) return;\n this.cachedChainId = next;\n this.emit('chainChanged', `0x${next.toString(16)}`);\n }\n\n private emit(event: EventName, ...args: unknown[]): void {\n const set = this.listeners.get(event);\n if (!set) return;\n for (const listener of [...set]) {\n try {\n listener(...args);\n } catch {\n // Listener bugs shouldn't break the bridge.\n }\n }\n }\n\n // ── Test seams ──────────────────────────────────────────────────────────\n\n /** Visible for tests + the connector's `getAccounts()` shortcut. */\n getCachedAccount(): Address | null {\n return this.cachedAccount;\n }\n /** Visible for tests + the connector's `getChainId()` shortcut. */\n getCachedChainId(): number | null {\n return this.cachedChainId;\n }\n}\n\nfunction bridgeError(code: number, message: string): Error {\n const err = new Error(message) as Error & { code?: number };\n err.code = code;\n return err;\n}\n"],"mappings":";;;;;;;;;;AAYA,SAAS,uBAAuB;;;ACyChC,IAAM,6BAA6B;AAGnC,IAAM,6BAA6B;AAU5B,SAAS,oBAA6B;AAC3C,MAAI,OAAO,WAAW,YAAa,QAAO;AAC1C,MAAI;AACF,WAAO,OAAO,WAAW,UAAa,OAAO,WAAW;AAAA,EAC1D,QAAQ;AAEN,WAAO;AA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U;AAC1B,eAAO,QAAQ,KAAK,UAAU;AAAA,UAC5B;AAAA,QACF,CAAC;AAAA,MACH;AAAA,MACA,eAAe,YAAY;AACzB,cAAM,UAAU,OAAO,SAAS,YAAY,EAAE;AAC9C,YAAI,OAAO,SAAS,OAAO,GAAG;AAC5B,iBAAO,QAAQ,KAAK,UAAU,EAAE,QAAQ,CAAC;AAAA,QAC3C;AAAA,MACF;AAAA,MACA,eAAe;AACb,eAAO,QAAQ,KAAK,YAAY;AAAA,MAClC;AAAA,IACF;AAAA,EACF,CAAC;AACH;","names":[]}
1
+ {"version":3,"sources":["../../src/wallet/parentBridgeConnector.ts","../../src/wallet/parentBridgeProvider.ts","../../src/wallet/tangleConnectors.ts"],"sourcesContent":["// Wagmi connector that proxies wallet operations to the Tangle Cloud parent\n// dapp via the iframe postMessage bridge. Becomes the autoConnect target\n// when this app is loaded inside an iframe sandbox without a window.ethereum\n// — i.e. always, when embedded by cloud.tangle.tools.\n//\n// Architecture: the connector owns one `ParentBridgeProvider` (singleton),\n// forwards every wagmi method to it, and reflects the provider's EIP-1193\n// events back to wagmi's emitter so the rest of the dapp (ConnectKit's\n// account chip, hooks like useAccount/useChainId) reacts to parent-state\n// changes without polling.\n\nimport type { Address, Chain } from 'viem';\nimport { createConnector } from 'wagmi';\n\nimport { ParentBridgeProvider, type ParentBridgeOptions } from './parentBridgeProvider';\n\nexport type ParentBridgeConnectorOptions = ParentBridgeOptions;\n\nexport function parentBridgeConnector(options: ParentBridgeConnectorOptions) {\n let provider: ParentBridgeProvider | undefined;\n let installed = false;\n\n return createConnector<ParentBridgeProvider>((config) => {\n const ensureProvider = (): ParentBridgeProvider => {\n if (!provider) provider = new ParentBridgeProvider(options);\n if (!installed) {\n provider.install();\n installed = true;\n // Wire the provider's EIP-1193 events to wagmi's emitter so\n // ConnectKit and useAccount/useChainId reflect parent-state changes\n // without polling.\n provider.on('accountsChanged', (accounts) => {\n config.emitter.emit('change', {\n accounts: Array.isArray(accounts)\n ? (accounts as readonly Address[])\n : ([] as readonly Address[]),\n });\n });\n provider.on('chainChanged', (chainIdHex) => {\n const chainId =\n typeof chainIdHex === 'string'\n ? Number.parseInt(chainIdHex, 16)\n : Number(chainIdHex);\n if (Number.isFinite(chainId)) {\n config.emitter.emit('change', { chainId });\n }\n });\n provider.on('disconnect', () => {\n config.emitter.emit('disconnect');\n });\n }\n return provider;\n };\n\n return {\n id: 'tangleParentBridge',\n name: 'Tangle Cloud',\n type: 'parentBridge',\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n async connect(): Promise<any> {\n // wagmi v3's connect() return type is a conditional based on\n // `withCapabilities`. We always return plain addresses; cast through\n // `any` rather than re-implementing the type predicate.\n const p = ensureProvider();\n const accountsResult = (await p.request({\n method: 'eth_requestAccounts',\n })) as readonly Address[];\n const chainIdHex = (await p.request({ method: 'eth_chainId' })) as string;\n const chainId = Number.parseInt(chainIdHex, 16);\n return {\n accounts: accountsResult,\n chainId: Number.isFinite(chainId) ? chainId : 0,\n };\n },\n\n async disconnect() {\n // Disconnect from the iframe's perspective is a local-only state\n // reset — we can't ask the parent dapp to disconnect its wallet on\n // our behalf, and a real disconnect should be initiated from the\n // parent's UI. Tear down listeners + the message bridge so a future\n // reconnect re-handshakes cleanly.\n if (provider) provider.uninstall();\n installed = false;\n provider = undefined;\n },\n\n async getAccounts() {\n const p = ensureProvider();\n const cached = p.getCachedAccount();\n if (cached) return [cached];\n const accounts = (await p.request({\n method: 'eth_accounts',\n })) as readonly Address[];\n return accounts;\n },\n\n async getChainId() {\n const p = ensureProvider();\n const cached = p.getCachedChainId();\n if (cached !== null) return cached;\n const chainIdHex = (await p.request({ method: 'eth_chainId' })) as string;\n const chainId = Number.parseInt(chainIdHex, 16);\n return Number.isFinite(chainId) ? chainId : 0;\n },\n\n async getProvider() {\n return ensureProvider();\n },\n\n async isAuthorized() {\n // Always authorized when in iframe mode — the parent dapp has\n // already gated access by being the embedder. Returning `true`\n // makes wagmi auto-reconnect on every page load, which is the\n // right UX (iframe → parent wallet is always-on).\n try {\n const p = ensureProvider();\n const accounts = (await p.request({\n method: 'eth_accounts',\n })) as readonly Address[];\n return accounts.length > 0;\n } catch {\n return false;\n }\n },\n\n async switchChain({ chainId }): Promise<Chain> {\n const p = ensureProvider();\n await p.request({\n method: 'wallet_switchEthereumChain',\n params: [{ chainId: `0x${chainId.toString(16)}` }],\n });\n const chain = config.chains.find((c) => c.id === chainId);\n if (!chain) {\n throw new Error(`Chain ${chainId} not configured for this app`);\n }\n return chain;\n },\n\n onAccountsChanged(accounts) {\n config.emitter.emit('change', {\n accounts: accounts as readonly Address[],\n });\n },\n onChainChanged(chainIdHex) {\n const chainId = Number.parseInt(chainIdHex, 16);\n if (Number.isFinite(chainId)) {\n config.emitter.emit('change', { chainId });\n }\n },\n onDisconnect() {\n config.emitter.emit('disconnect');\n },\n };\n });\n}\n","// EIP-1193 provider implementation that proxies wallet calls to the parent\n// dapp via window.postMessage. The iframe doesn't talk to a wallet directly\n// — it inherits the parent's connected account + chain, and forwards signing\n// requests through the existing tangle.app.* protocol.\n//\n// This is the lowest layer of the parent-bridge stack. Wagmi sees this as a\n// regular Ethereum provider and routes `eth_accounts`, `eth_chainId`,\n// `personal_sign`, `eth_sendTransaction`, `wallet_switchEthereumChain`, etc.\n// through it.\n\nimport type { Address, Hex } from 'viem';\n\nimport {\n makeCorrelationId,\n NO_WALLET_ADDRESS,\n TANGLE_IFRAME_PROTOCOL_VERSION,\n type ConnectResult,\n type ParentMessage,\n type ReadAccountResult,\n type SignMessageResult,\n type SignTransactionResult,\n type SwitchChainResult,\n} from './parentBridgeProtocol';\n\ntype EventName = 'accountsChanged' | 'chainChanged' | 'connect' | 'disconnect' | 'message';\ntype Listener = (...args: unknown[]) => void;\n\ntype PendingRequest<T> = {\n resolve: (value: T) => void;\n reject: (reason: Error) => void;\n expectedKind: ParentMessage['kind'];\n};\n\nexport type ParentBridgeOptions = {\n /**\n * Origin of the parent dapp that hosts this iframe. The provider posts to\n * `window.parent` with this exact origin and rejects inbound messages from\n * any other origin. Pass `'*'` only in development; production must pin to\n * the real parent (`https://cloud.tangle.tools` or its develop equivalent).\n */\n parentOrigin: string;\n /**\n * Stable identifier for this iframe app. The parent includes this in the\n * handshake ack so dev tooling can correlate logs across the two windows.\n */\n appId: string;\n /**\n * Optional ms timeout for each bridged request. Defaults to 60 seconds —\n * long enough for a user to read + approve a signing prompt in the parent.\n */\n requestTimeoutMs?: number;\n};\n\nconst DEFAULT_REQUEST_TIMEOUT_MS = 60_000;\n// Connecting is gated on the user interacting with the parent's modal — allow\n// a generous window rather than the standard per-request timeout.\nconst CONNECT_REQUEST_TIMEOUT_MS = 300_000;\n\n/**\n * Detect iframe execution context. When this returns `false` the bridge\n * connector should not be installed and the host app should fall back to its\n * normal wallet config (ConnectKit + injected/walletConnect).\n *\n * `window.parent !== window` is the most reliable signal that works across\n * sandbox-iframe contexts where direct property access to parent throws.\n */\nexport function isRunningInIframe(): boolean {\n if (typeof window === 'undefined') return false;\n try {\n return window.parent !== undefined && window.parent !== window;\n } catch {\n // Cross-origin read of `window.parent` shouldn't throw, but be defensive.\n return true;\n }\n}\n\n/**\n * EIP-1193 provider backed by the Tangle Cloud iframe protocol. One instance\n * lives per iframe app; the wagmi connector owns the singleton.\n */\nexport class ParentBridgeProvider {\n private listeners = new Map<EventName, Set<Listener>>();\n private pending = new Map<string, PendingRequest<unknown>>();\n private cachedAccount: Address | null = null;\n private cachedChainId: number | null = null;\n private handshakeAcked = false;\n private handshakeWaiters: Array<() => void> = [];\n private installed = false;\n\n constructor(private readonly options: ParentBridgeOptions) {}\n\n /**\n * Wire up the global message listener and send the initial handshake.\n * Idempotent — safe to call repeatedly during reconnect attempts.\n */\n install(): void {\n if (this.installed || typeof window === 'undefined') return;\n this.installed = true;\n window.addEventListener('message', this.handleParentMessage);\n this.postToParent({\n kind: 'tangle.app.handshake',\n appId: this.options.appId,\n version: TANGLE_IFRAME_PROTOCOL_VERSION,\n });\n }\n\n uninstall(): void {\n if (!this.installed || typeof window === 'undefined') return;\n this.installed = false;\n window.removeEventListener('message', this.handleParentMessage);\n // Reject every pending request so callers don't hang forever.\n for (const [, pending] of this.pending) {\n pending.reject(new Error('Parent bridge uninstalled'));\n }\n this.pending.clear();\n }\n\n // ── EIP-1193 surface ────────────────────────────────────────────────────\n\n async request(req: { method: string; params?: unknown[] }): Promise<unknown> {\n const method = req.method;\n const params = (req.params ?? []) as unknown[];\n switch (method) {\n case 'eth_chainId': {\n await this.ensureBootstrapped();\n return this.cachedChainId !== null ? `0x${this.cachedChainId.toString(16)}` : '0x0';\n }\n case 'eth_accounts': {\n // Passive read — never opens a modal.\n await this.ensureBootstrapped();\n return this.cachedAccount !== null ? [this.cachedAccount] : [];\n }\n case 'eth_requestAccounts': {\n // Active connect (the wallet \"Connect\" button). If the parent has no\n // wallet yet, delegate to it to open its connect modal and wait.\n await this.ensureBootstrapped();\n if (this.cachedAccount !== null) return [this.cachedAccount];\n const account = await this.requestConnect();\n return account !== null ? [account] : [];\n }\n case 'personal_sign': {\n const [message, _signer] = params as [string, Address];\n return this.requestSignMessage(message);\n }\n case 'eth_signTypedData_v4': {\n // The current protocol doesn't carry typed-data — surface a clear\n // error rather than silently producing a personal_sign. Publishers\n // that need typed-data signing should upgrade the protocol.\n throw bridgeError(\n 4200,\n 'eth_signTypedData_v4 is not supported by the parent-bridge protocol yet.',\n );\n }\n case 'eth_sendTransaction': {\n const [tx] = params as [\n { to?: Address; data?: Hex; value?: Hex | string; chainId?: Hex | number },\n ];\n if (!tx?.to || !tx.data) {\n throw bridgeError(-32602, 'eth_sendTransaction requires `to` and `data`.');\n }\n return this.requestSignTransaction(tx);\n }\n case 'wallet_switchEthereumChain': {\n const [{ chainId }] = params as [{ chainId: Hex }];\n const numeric = Number.parseInt(chainId, 16);\n if (!Number.isFinite(numeric) || numeric <= 0) {\n throw bridgeError(-32602, `Invalid chainId: ${chainId}`);\n }\n await this.requestSwitchChain(numeric);\n return null;\n }\n case 'wallet_addEthereumChain': {\n // The parent owns the chain registry; iframes can't add chains the\n // dapp doesn't already know about.\n throw bridgeError(\n 4200,\n 'wallet_addEthereumChain is not supported through the parent bridge.',\n );\n }\n default:\n throw bridgeError(4200, `Method ${method} not supported by parent bridge.`);\n }\n }\n\n on(event: EventName, listener: Listener): void {\n const set = this.listeners.get(event) ?? new Set();\n set.add(listener);\n this.listeners.set(event, set);\n }\n\n removeListener(event: EventName, listener: Listener): void {\n this.listeners.get(event)?.delete(listener);\n }\n\n // ── Internal: dispatch + book-keeping ───────────────────────────────────\n\n private postToParent(message: object): void {\n if (typeof window === 'undefined') return;\n try {\n window.parent.postMessage(message, this.options.parentOrigin);\n } catch {\n // Cross-origin / sandboxed; parent.postMessage shouldn't actually throw\n // but be defensive against future browser changes.\n }\n }\n\n private handleParentMessage = (event: MessageEvent): void => {\n // Origin gate first; never parse untrusted payloads.\n if (event.origin !== this.options.parentOrigin) return;\n const data = event.data;\n if (typeof data !== 'object' || data === null) return;\n const message = data as ParentMessage;\n switch (message.kind) {\n case 'tangle.app.handshakeAck':\n this.handshakeAcked = true;\n for (const resolve of this.handshakeWaiters) resolve();\n this.handshakeWaiters = [];\n // After ack, ask for the current account so cached state reflects\n // reality before any consumer queries. Fire-and-forget — explicit\n // calls (`eth_accounts`, etc.) await their own request.\n this.sendReadAccount().catch(() => {\n // The first read commonly races with bridge teardown in tests\n // and isn't user-facing; swallow rather than producing unhandled\n // rejections. Subsequent `eth_accounts` calls retry on demand.\n });\n return;\n case 'tangle.app.readAccountResult':\n case 'tangle.app.connectResult':\n this.resolvePending(message);\n if (message.ok) {\n this.updateAccount(\n message.data.account === NO_WALLET_ADDRESS\n ? null\n : message.data.account,\n );\n this.updateChainId(message.data.chainId);\n }\n return;\n case 'tangle.app.switchChainResult':\n this.resolvePending(message);\n if (message.ok) this.updateChainId(message.data.chainId);\n return;\n case 'tangle.app.signMessageResult':\n case 'tangle.app.signTransactionResult':\n this.resolvePending(message);\n return;\n case 'tangle.app.accountChanged':\n this.updateAccount(message.account);\n return;\n case 'tangle.app.chainChanged':\n this.updateChainId(message.chainId);\n return;\n }\n };\n\n private sendReadAccount(): Promise<{ account: Address; chainId: number }> {\n return this.dispatch({\n kind: 'tangle.app.readAccount',\n expectedKind: 'tangle.app.readAccountResult',\n }) as Promise<{ account: Address; chainId: number }>;\n }\n\n /**\n * Ask the parent to connect a wallet (opening its modal if needed) and wait\n * for the result. Long timeout — the user is interacting with the modal.\n */\n private requestConnect(): Promise<Address | null> {\n return this.dispatch({\n kind: 'tangle.app.requestConnect',\n expectedKind: 'tangle.app.connectResult',\n timeoutMs: CONNECT_REQUEST_TIMEOUT_MS,\n }).then((data) => {\n const { account } = data as { account: Address; chainId: number };\n return account === NO_WALLET_ADDRESS ? null : account;\n });\n }\n\n private requestSignMessage(message: string): Promise<Hex> {\n const chainId = this.cachedChainId ?? 1;\n return this.dispatch({\n kind: 'tangle.app.signMessage',\n expectedKind: 'tangle.app.signMessageResult',\n payload: { chainId, message },\n }).then((data) => (data as { signature: Hex }).signature);\n }\n\n private requestSignTransaction(tx: {\n to?: Address;\n data?: Hex;\n value?: Hex | string;\n }): Promise<Hex> {\n const chainId = this.cachedChainId ?? 1;\n const value =\n typeof tx.value === 'string' && tx.value.startsWith('0x')\n ? BigInt(tx.value).toString(10)\n : typeof tx.value === 'string'\n ? tx.value\n : undefined;\n return this.dispatch({\n kind: 'tangle.app.signTransaction',\n expectedKind: 'tangle.app.signTransactionResult',\n payload: {\n chainId,\n to: tx.to as Address,\n data: tx.data as Hex,\n ...(value !== undefined ? { value } : {}),\n },\n }).then((data) => (data as { txHash: Hex }).txHash);\n }\n\n private requestSwitchChain(chainId: number): Promise<number> {\n return this.dispatch({\n kind: 'tangle.app.switchChain',\n expectedKind: 'tangle.app.switchChainResult',\n payload: { chainId },\n }).then((data) => (data as { chainId: number }).chainId);\n }\n\n private async dispatch(req: {\n kind:\n | 'tangle.app.readAccount'\n | 'tangle.app.switchChain'\n | 'tangle.app.signMessage'\n | 'tangle.app.signTransaction'\n | 'tangle.app.requestConnect';\n expectedKind: ParentMessage['kind'];\n payload?: Record<string, unknown>;\n timeoutMs?: number;\n }): Promise<unknown> {\n await this.ensureBootstrapped();\n const correlationId = makeCorrelationId(req.kind);\n const timeout = req.timeoutMs ?? this.options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;\n return new Promise<unknown>((resolve, reject) => {\n const timer = window.setTimeout(() => {\n this.pending.delete(correlationId);\n reject(bridgeError(4900, `Parent did not respond to ${req.kind} within ${timeout}ms`));\n }, timeout);\n this.pending.set(correlationId, {\n resolve: (v) => {\n window.clearTimeout(timer);\n resolve(v);\n },\n reject: (e) => {\n window.clearTimeout(timer);\n reject(e);\n },\n expectedKind: req.expectedKind,\n });\n this.postToParent({\n kind: req.kind,\n correlationId,\n ...(req.payload ?? {}),\n });\n });\n }\n\n /**\n * Resolves wallet-shape responses (`{ ok, data | error }`). Job results\n * use a different envelope (`{ status, data?, chunk?, error? }`) and are\n * routed through a separate listener registered by `useCallJob` / the SDK\n * — the provider doesn't double-handle them.\n */\n private resolvePending(\n message:\n | ReadAccountResult\n | ConnectResult\n | SwitchChainResult\n | SignMessageResult\n | SignTransactionResult,\n ): void {\n const entry = this.pending.get(message.correlationId);\n if (!entry) return;\n this.pending.delete(message.correlationId);\n if (entry.expectedKind !== message.kind) {\n entry.reject(\n bridgeError(\n -32000,\n `Parent replied with ${message.kind} but ${entry.expectedKind} was expected`,\n ),\n );\n return;\n }\n if (message.ok) {\n entry.resolve(message.data);\n } else {\n entry.reject(bridgeError(4001, message.error));\n }\n }\n\n private async ensureBootstrapped(): Promise<void> {\n if (this.handshakeAcked) return;\n this.install();\n await new Promise<void>((resolve) => {\n this.handshakeWaiters.push(resolve);\n // Re-send handshake every 500ms while we wait — covers a parent that\n // mounted after the iframe and missed the initial post.\n const retry = window.setInterval(() => {\n if (this.handshakeAcked) {\n window.clearInterval(retry);\n return;\n }\n this.postToParent({\n kind: 'tangle.app.handshake',\n appId: this.options.appId,\n version: TANGLE_IFRAME_PROTOCOL_VERSION,\n });\n }, 500);\n // Safety stop — handshake won't be re-attempted indefinitely.\n window.setTimeout(() => window.clearInterval(retry), 10_000);\n });\n }\n\n private updateAccount(next: Address | null): void {\n if (this.cachedAccount === next) return;\n const prev = this.cachedAccount;\n this.cachedAccount = next;\n if (next === null && prev !== null) {\n this.emit('disconnect');\n this.emit('accountsChanged', []);\n } else if (next !== null) {\n this.emit('accountsChanged', [next]);\n if (prev === null) {\n this.emit('connect', { chainId: this.cachedChainId ?? 0 });\n }\n }\n }\n\n private updateChainId(next: number): void {\n if (this.cachedChainId === next) return;\n this.cachedChainId = next;\n this.emit('chainChanged', `0x${next.toString(16)}`);\n }\n\n private emit(event: EventName, ...args: unknown[]): void {\n const set = this.listeners.get(event);\n if (!set) return;\n for (const listener of [...set]) {\n try {\n listener(...args);\n } catch {\n // Listener bugs shouldn't break the bridge.\n }\n }\n }\n\n // ── Test seams ──────────────────────────────────────────────────────────\n\n /** Visible for tests + the connector's `getAccounts()` shortcut. */\n getCachedAccount(): Address | null {\n return this.cachedAccount;\n }\n /** Visible for tests + the connector's `getChainId()` shortcut. */\n getCachedChainId(): number | null {\n return this.cachedChainId;\n }\n}\n\nfunction bridgeError(code: number, message: string): Error {\n const err = new Error(message) as Error & { code?: number };\n err.code = code;\n return err;\n}\n","import type { CreateConnectorFn } from 'wagmi';\n\nimport { detectTangleCloudParentOrigin } from './detectParentOrigin';\nimport { parentBridgeConnector } from './parentBridgeConnector';\n\nexport interface TangleBlueprintConnectorsOptions {\n /** App id reported to the parent dapp on handshake (when embedded). */\n appId: string;\n /**\n * Connectors used when running STANDALONE (the app's own domain) — e.g.\n * `[injected(), walletConnect({ projectId })]`. Ignored when embedded.\n */\n standalone: CreateConnectorFn[];\n /** Extra trusted parent origins (staging / preview deploys). */\n extraOrigins?: readonly string[];\n /** Override the bridged-request timeout (ms). */\n requestTimeoutMs?: number;\n}\n\n/**\n * One connector list, two deployment modes — so a blueprint app can ship a\n * single build that runs both standalone and embedded in Tangle Cloud:\n *\n * - **Embedded** (a trusted Tangle Cloud parent is detected): the\n * parent-bridge connector is the *only* connector. The sandboxed iframe\n * can't inject a wallet extension, so it inherits / drives the parent's\n * wallet over the postMessage bridge — surfacing injected/WalletConnect\n * here would just dead-end.\n * - **Standalone** (no trusted parent): the app's own `standalone`\n * connectors, exactly as a normal dapp.\n *\n * The choice is made at runtime from the embedding context, so the same\n * artifact works in both places with no build flags.\n *\n * createConfig({\n * chains,\n * transports,\n * connectors: tangleBlueprintConnectors({\n * appId: 'trading-arena',\n * standalone: [injected(), walletConnect({ projectId })],\n * }),\n * })\n */\nexport function tangleBlueprintConnectors(\n options: TangleBlueprintConnectorsOptions,\n): CreateConnectorFn[] {\n const parentOrigin = detectTangleCloudParentOrigin({\n extraOrigins: options.extraOrigins,\n });\n if (parentOrigin === null) {\n return options.standalone;\n }\n return [\n parentBridgeConnector({\n parentOrigin,\n appId: options.appId,\n ...(options.requestTimeoutMs !== undefined\n ? { requestTimeoutMs: options.requestTimeoutMs }\n : {}),\n }),\n ];\n}\n"],"mappings":";;;;;;;;;;AAYA,SAAS,uBAAuB;;;ACyChC,IAAM,6BAA6B;AAGnC,IAAM,6BAA6B;AAU5B,SAAS,oBAA6B;AAC3C,MAAI,OAAO,WAAW,YAAa,QAAO;AAC1C,MAAI;AACF,WAAO,OAAO,WAAW,UAAa,OAAO,WAAW;AAAA,EAC1D,QAAQ;AAEN,WAAO;AAAA,EACT;AACF;AAMO,IAAM,uBAAN,MAA2B;AAAA,EAShC,YAA6B,SAA8B;AAA9B;AAAA,EAA+B;AAAA,EAA/B;AAAA,EARrB,YAAY,oBAAI,IAA8B;AAAA,EAC9C,UAAU,oBAAI,IAAqC;AAAA,EACnD,gBAAgC;AAAA,EAChC,gBAA+B;AAAA,EAC/B,iBAAiB;AAAA,EACjB,mBAAsC,CAAC;AAAA,EACvC,YAAY;AAAA;AAAA;AAAA;AAAA;AAAA,EAQpB,UA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;AAAA,IACF;AAAA,EACF,CAAC;AACH;;;AEhHO,SAAS,0BACd,SACqB;AACrB,QAAM,eAAe,8BAA8B;AAAA,IACjD,cAAc,QAAQ;AAAA,EACxB,CAAC;AACD,MAAI,iBAAiB,MAAM;AACzB,WAAO,QAAQ;AAAA,EACjB;AACA,SAAO;AAAA,IACL,sBAAsB;AAAA,MACpB;AAAA,MACA,OAAO,QAAQ;AAAA,MACf,GAAI,QAAQ,qBAAqB,SAC7B,EAAE,kBAAkB,QAAQ,iBAAiB,IAC7C,CAAC;AAAA,IACP,CAAC;AAAA,EACH;AACF;","names":[]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tangle-network/blueprint-ui",
3
- "version": "0.5.2",
3
+ "version": "0.5.3",
4
4
  "description": "Shared blueprint UI components, hooks, and contract utilities for Tangle Network apps",
5
5
  "license": "MIT OR Apache-2.0",
6
6
  "repository": {
@@ -8,26 +8,27 @@
8
8
  * postMessage protocol, so the iframe inherits the parent's wallet without
9
9
  * its own picker.
10
10
  *
11
- * Usage in an iframe app's wagmi config:
11
+ * Build a blueprint app ONCE and ship it both standalone and embedded — the
12
+ * recommended entry point is `tangleBlueprintConnectors`, which picks the
13
+ * right connectors at runtime:
12
14
  *
13
- * import {
14
- * detectTangleCloudParentOrigin,
15
- * parentBridgeConnector,
16
- * } from '@tangle-network/blueprint-ui/wallet';
15
+ * import { tangleBlueprintConnectors } from '@tangle-network/blueprint-ui/wallet';
17
16
  *
18
- * const parent = detectTangleCloudParentOrigin();
19
- * const config = createConfig(
20
- * parent !== null
21
- * ? { ...getDefaultConfig({...}), connectors: [
22
- * parentBridgeConnector({ parentOrigin: parent, appId: 'my-app' }),
23
- * ] }
24
- * : getDefaultConfig({...}),
25
- * );
17
+ * createConfig({
18
+ * chains, transports,
19
+ * connectors: tangleBlueprintConnectors({
20
+ * appId: 'my-app',
21
+ * standalone: [injected(), walletConnect({ projectId })],
22
+ * }),
23
+ * });
26
24
  *
27
- * The bridge is intentionally the ONLY connector when running inside the
28
- * dapp surfacing injected / WalletConnect / Coinbase inside a sandboxed
29
- * iframe doesn't work (no popup, no extension injection) and would just
30
- * confuse operators.
25
+ * Embedded in Tangle Cloud the bridge connector inherits/drives the parent
26
+ * wallet. Standalone the app's own connectors. The bridge is intentionally
27
+ * the ONLY connector when embedded surfacing injected / WalletConnect inside
28
+ * a sandboxed iframe doesn't work (no popup, no extension injection).
29
+ *
30
+ * `detectTangleCloudParentOrigin` + `parentBridgeConnector` stay exported for
31
+ * apps that hand-roll the selection.
31
32
  */
32
33
 
33
34
  export {
@@ -35,6 +36,11 @@ export {
35
36
  TANGLE_CLOUD_ORIGINS_DEFAULT,
36
37
  } from './detectParentOrigin';
37
38
 
39
+ export {
40
+ tangleBlueprintConnectors,
41
+ type TangleBlueprintConnectorsOptions,
42
+ } from './tangleConnectors';
43
+
38
44
  export {
39
45
  parentBridgeConnector,
40
46
  type ParentBridgeConnectorOptions,
@@ -0,0 +1,18 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import type { CreateConnectorFn } from 'wagmi';
3
+
4
+ import { tangleBlueprintConnectors } from './tangleConnectors';
5
+
6
+ // jsdom: window.parent === window (not iframed) → no trusted parent → the
7
+ // helper must hand back the app's own standalone connectors unchanged. The
8
+ // embedded branch needs a real cross-origin referrer and is covered by the
9
+ // connector's own integration tests.
10
+ describe('tangleBlueprintConnectors', () => {
11
+ it('returns the standalone connectors when not embedded', () => {
12
+ const a = (() => ({})) as unknown as CreateConnectorFn;
13
+ const b = (() => ({})) as unknown as CreateConnectorFn;
14
+ expect(
15
+ tangleBlueprintConnectors({ appId: 'my-app', standalone: [a, b] }),
16
+ ).toEqual([a, b]);
17
+ });
18
+ });
@@ -0,0 +1,62 @@
1
+ import type { CreateConnectorFn } from 'wagmi';
2
+
3
+ import { detectTangleCloudParentOrigin } from './detectParentOrigin';
4
+ import { parentBridgeConnector } from './parentBridgeConnector';
5
+
6
+ export interface TangleBlueprintConnectorsOptions {
7
+ /** App id reported to the parent dapp on handshake (when embedded). */
8
+ appId: string;
9
+ /**
10
+ * Connectors used when running STANDALONE (the app's own domain) — e.g.
11
+ * `[injected(), walletConnect({ projectId })]`. Ignored when embedded.
12
+ */
13
+ standalone: CreateConnectorFn[];
14
+ /** Extra trusted parent origins (staging / preview deploys). */
15
+ extraOrigins?: readonly string[];
16
+ /** Override the bridged-request timeout (ms). */
17
+ requestTimeoutMs?: number;
18
+ }
19
+
20
+ /**
21
+ * One connector list, two deployment modes — so a blueprint app can ship a
22
+ * single build that runs both standalone and embedded in Tangle Cloud:
23
+ *
24
+ * - **Embedded** (a trusted Tangle Cloud parent is detected): the
25
+ * parent-bridge connector is the *only* connector. The sandboxed iframe
26
+ * can't inject a wallet extension, so it inherits / drives the parent's
27
+ * wallet over the postMessage bridge — surfacing injected/WalletConnect
28
+ * here would just dead-end.
29
+ * - **Standalone** (no trusted parent): the app's own `standalone`
30
+ * connectors, exactly as a normal dapp.
31
+ *
32
+ * The choice is made at runtime from the embedding context, so the same
33
+ * artifact works in both places with no build flags.
34
+ *
35
+ * createConfig({
36
+ * chains,
37
+ * transports,
38
+ * connectors: tangleBlueprintConnectors({
39
+ * appId: 'trading-arena',
40
+ * standalone: [injected(), walletConnect({ projectId })],
41
+ * }),
42
+ * })
43
+ */
44
+ export function tangleBlueprintConnectors(
45
+ options: TangleBlueprintConnectorsOptions,
46
+ ): CreateConnectorFn[] {
47
+ const parentOrigin = detectTangleCloudParentOrigin({
48
+ extraOrigins: options.extraOrigins,
49
+ });
50
+ if (parentOrigin === null) {
51
+ return options.standalone;
52
+ }
53
+ return [
54
+ parentBridgeConnector({
55
+ parentOrigin,
56
+ appId: options.appId,
57
+ ...(options.requestTimeoutMs !== undefined
58
+ ? { requestTimeoutMs: options.requestTimeoutMs }
59
+ : {}),
60
+ }),
61
+ ];
62
+ }