@flapsdk/vault-runtime 0.1.37 → 0.1.38

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.
Files changed (43) hide show
  1. package/README.md +13 -2
  2. package/{chunk-HYBZWS6U.js → chunk-DY34U27M.js} +90 -252
  3. package/chunk-DY34U27M.js.map +1 -0
  4. package/{chunk-22KTLOYH.js → chunk-FWYBGHBX.js} +17 -4
  5. package/chunk-FWYBGHBX.js.map +1 -0
  6. package/chunk-GY7YY67I.js +78 -0
  7. package/chunk-GY7YY67I.js.map +1 -0
  8. package/{chunk-SDCB3RJS.js → chunk-JJJSK6HF.js} +3 -3
  9. package/{chunk-SDCB3RJS.js.map → chunk-JJJSK6HF.js.map} +1 -1
  10. package/{chunk-3X2K7YYU.js → chunk-NWBIKFHH.js} +218 -76
  11. package/chunk-NWBIKFHH.js.map +1 -0
  12. package/chunk-QS475ZC7.js +583 -0
  13. package/chunk-QS475ZC7.js.map +1 -0
  14. package/{chunk-SRZFHGSO.js → chunk-WN4MIMCY.js} +3 -3
  15. package/{chunk-SRZFHGSO.js.map → chunk-WN4MIMCY.js.map} +1 -1
  16. package/host-client.d.mts +9 -2
  17. package/host-client.js +5 -6
  18. package/host.d.mts +5 -5
  19. package/host.js +7 -7
  20. package/{hostRuntimeConfig-DM6JjbeO.d.mts → hostRuntimeConfig-CKjug1-9.d.mts} +1 -1
  21. package/{mpegts-536UQHCG.js → mpegts-J2J6JTD7.js} +6 -6
  22. package/{mpegts-536UQHCG.js.map → mpegts-J2J6JTD7.js.map} +1 -1
  23. package/package.json +4 -3
  24. package/runtime-contract.json +5 -1
  25. package/sdk.d.mts +42 -4
  26. package/sdk.js +41 -9
  27. package/sdk.js.map +1 -1
  28. package/server.d.mts +3 -3
  29. package/server.js +4 -5
  30. package/server.js.map +1 -1
  31. package/{txError-vvvBIsa-.d.mts → txError-BTuW38It.d.mts} +15 -2
  32. package/{types-cyAEoeXa.d.mts → types-BolUPLIE.d.mts} +101 -2
  33. package/ui.d.mts +13 -2
  34. package/ui.js +2 -3
  35. package/chunk-22KTLOYH.js.map +0 -1
  36. package/chunk-27VBKY3J.js +0 -36
  37. package/chunk-27VBKY3J.js.map +0 -1
  38. package/chunk-3X2K7YYU.js.map +0 -1
  39. package/chunk-AGLB72HK.js +0 -61
  40. package/chunk-AGLB72HK.js.map +0 -1
  41. package/chunk-FUOBTZMQ.js +0 -47
  42. package/chunk-FUOBTZMQ.js.map +0 -1
  43. package/chunk-HYBZWS6U.js.map +0 -1
package/README.md CHANGED
@@ -6,7 +6,7 @@ Generated from `flap-vault-ui-template`.
6
6
 
7
7
  This package is the shared runtime surface that local preview, Artifact Workbench, and `flap.sh` should agree on.
8
8
 
9
- Package version: `0.1.37`. Source commit: `ad40bab7dfc976d20dd82050aeec17fef18a39b3`.
9
+ Package version: `0.1.38`. Source commit: `1220ee9813f73eafd434decb365a08ae6a681445`.
10
10
 
11
11
  ## Exports
12
12
 
@@ -17,6 +17,15 @@ Package version: `0.1.37`. Source commit: `ad40bab7dfc976d20dd82050aeec17fef18a3
17
17
 
18
18
  See `runtime-contract.json` for the machine-readable subpath contract.
19
19
 
20
+ ## Shared Vault UI and Mini App v2
21
+
22
+ This shared runtime supports standalone App wallet operations through
23
+ `useFlapSdk({ chainId })` and the host-owned `CopyButton` from `./ui`.
24
+ Vault UI keeps `useFlapSdk()` and its token-bound context. Both use this one
25
+ package; existing token-bound Mini Apps remain compatible.
26
+ Stable development uses the official main template and npm latest.
27
+ The shared CopyButton copies up to 1,048,576 UTF-16 code units without truncation.
28
+
20
29
  ## Dynamic IPFS content
21
30
 
22
31
  Stable runtime `0.1.37` introduces `sdk.readIpfsText(cid, path?)`, which returns
@@ -27,7 +36,9 @@ The SDK exports `IPFS_CONTENT_VERSION = 1`; the runtime contract advertises
27
36
 
28
37
  Vault source keeps the `@/src/sdk` and `@/src/ui` authoring aliases. Obtain
29
38
  `sdk` with `useFlapSdk()`, then call the reader from an async effect or event
30
- handler. Import `IpfsText` and `IpfsImage` from the UI alias for rendering:
39
+ handler. Independent Mini App v2 uses `useFlapSdk({ chainId: 56 })`;
40
+ its chain SDK exposes the same reader and reviewed `readFsi` API.
41
+ Import `IpfsText` and `IpfsImage` from the UI alias for rendering:
31
42
 
32
43
  ```tsx
33
44
  const body = await sdk.readIpfsText(textCid);
@@ -1,254 +1,75 @@
1
- import { createVaultRuntimeContext, chainLabelForChain } from './chunk-AGLB72HK.js';
2
- import { createLocalNftMetadataReader, createLocalMediaUploader, vaultV2NftAbi, nftTokenUriAbi } from './chunk-SRZFHGSO.js';
1
+ import { createVaultRuntimeContext, chainLabelForChain, readContractEventsInBlockRanges, resolveSafeContractWriteFeeOverrides, createIpfsTextReader, readFsiJson, createFlapChainSdk } from './chunk-QS475ZC7.js';
2
+ import { createLocalMediaUploader, createLocalNftMetadataReader, vaultV2NftAbi, nftTokenUriAbi } from './chunk-WN4MIMCY.js';
3
3
  import { fetchOracleJson } from './chunk-JLI25XFB.js';
4
- import { RuntimeContext, Alert } from './chunk-3X2K7YYU.js';
4
+ import { RuntimeContext, Alert } from './chunk-NWBIKFHH.js';
5
5
  import { isValidAddress, ZERO_ADDRESS } from './chunk-B4WKI3EW.js';
6
- import { resolveIpfsImageUrls } from './chunk-27VBKY3J.js';
7
- import { useState, useRef, useCallback, useEffect, useMemo } from 'react';
8
- import { useAccount, useChainId, useConnect, useDisconnect, useSwitchChain, usePublicClient, useWalletClient, useBalance } from 'wagmi';
9
- import { toFunctionSelector, parseAbi, encodeFunctionData, formatUnits, decodeFunctionResult, decodeAbiParameters, decodeEventLog, getContractAddress, concatHex, encodeAbiParameters, keccak256 } from 'viem';
6
+ import { useRef, useMemo, useState, useCallback, useEffect } from 'react';
7
+ import { useConfig, useAccount, useChainId, useConnect, useDisconnect, useSwitchChain, usePublicClient, useWalletClient, useBalance } from 'wagmi';
8
+ import { switchChain, disconnect, getAccount, getPublicClient, getWalletClient } from 'wagmi/actions';
9
+ import { toFunctionSelector, parseAbi, encodeFunctionData, decodeFunctionResult, formatUnits, decodeAbiParameters, decodeEventLog, getContractAddress, concatHex, encodeAbiParameters, keccak256 } from 'viem';
10
10
  import { jsxs, jsx } from 'react/jsx-runtime';
11
11
 
12
- // src/sdk/fsiPolicy.mjs
13
- var FSI_QUERY_PREFIX = "https://bsc-debug.butterfly.army/fsi/v1";
14
- var FSI_ORIGIN = "https://bsc-debug.butterfly.army";
15
- var FSI_PATH = "/fsi/v1";
16
- var encodedPathSyntax = /%(?:2e|2f|5c|25)/i;
17
- var hasDotSegment = (path) => path.split("/").some((part) => part === "." || part === "..");
18
- function isFsiQueryUrl(value) {
19
- try {
20
- if (typeof value !== "string" || /[\\#\u0000-\u0020\u007f]/.test(value)) return false;
21
- const rawPath = value.match(/^[a-z][a-z\d+.-]*:\/\/[^/?#]*([^?#]*)/i)?.[1];
22
- if (rawPath === void 0 || encodedPathSyntax.test(rawPath) || hasDotSegment(rawPath)) return false;
23
- const url = new URL(value);
24
- return url.origin === FSI_ORIGIN && !url.username && !url.password && !url.hash && (url.pathname === FSI_PATH || url.pathname.startsWith(`${FSI_PATH}/`)) && !encodedPathSyntax.test(url.pathname);
25
- } catch {
26
- return false;
27
- }
28
- }
29
- function hasFsiQueryDeclaration(endpoints) {
30
- const urls = typeof endpoints === "string" ? [endpoints] : endpoints;
31
- return Array.isArray(urls) && urls.some((value) => {
32
- if (!isFsiQueryUrl(value)) return false;
33
- const url = new URL(value);
34
- return !url.search && (url.pathname === FSI_PATH || url.pathname === `${FSI_PATH}/`);
35
- });
36
- }
37
- function buildFsiQueryUrl(path, params = {}) {
38
- if (typeof path !== "string" || path.startsWith("/") || /[\\?#\s\u0000-\u001f\u007f]/.test(path)) {
39
- throw new Error("FSI path must be relative to /fsi/v1 without query or fragment; pass query parameters separately.");
40
- }
41
- if (encodedPathSyntax.test(path) || hasDotSegment(path)) {
42
- throw new Error("FSI path traversal and encoded path separators/dots are not allowed.");
43
- }
44
- const url = new URL(`${FSI_QUERY_PREFIX}/${path}`);
45
- if (!isFsiQueryUrl(url.href)) throw new Error("FSI URL is outside the platform query allowlist.");
46
- for (const [key, value] of Object.entries(params)) {
47
- if (typeof value !== "string") throw new Error("FSI query parameter values must be strings.");
48
- url.searchParams.set(key, value);
49
- }
50
- return url.href;
51
- }
52
-
53
- // src/sdk/fsi.ts
54
- async function readFsiJson(endpoints, path, params, fetchImpl = fetch) {
55
- if (!hasFsiQueryDeclaration(endpoints)) {
56
- throw new Error("FSI requires https://bsc-debug.butterfly.army/fsi/v1 in manifest.endpoints for review.");
57
- }
58
- const url = buildFsiQueryUrl(path, params);
59
- const response = await fetchImpl(url, {
60
- method: "GET",
61
- credentials: "omit",
62
- redirect: "error",
63
- referrerPolicy: "no-referrer",
64
- cache: "no-store"
65
- });
66
- if (!response.ok) throw new Error(`FSI request returned ${response.status}.`);
67
- return await response.json();
68
- }
69
-
70
- // src/sdk/ipfsText.ts
71
- var MAX_TEXT_BYTES = 256 * 1024;
72
- var MAX_CONCURRENT_READS = 6;
73
- var MAX_PENDING_READS = 128;
74
- var MAX_CACHED_READS = 64;
75
- var TEXT_MEDIA_TYPES = /* @__PURE__ */ new Set(["text/plain", "application/json", "application/octet-stream"]);
76
- async function readTextBody(response, signal) {
77
- const contentType = response.headers.get("content-type") ?? "";
78
- if (!TEXT_MEDIA_TYPES.has(contentType.split(";")[0].trim().toLowerCase())) {
79
- throw new Error("IPFS text must use text/plain, application/json or application/octet-stream.");
80
- }
81
- const charset = /charset\s*=\s*["']?([^;"'\s]+)/i.exec(contentType)?.[1];
82
- if (charset && !/^utf-?8$/i.test(charset)) throw new Error("IPFS text must use UTF-8.");
83
- if (Number(response.headers.get("content-length")) > MAX_TEXT_BYTES) {
84
- await response.body?.cancel();
85
- throw new Error("IPFS text exceeds 256 KiB.");
86
- }
87
- const reader = response.body?.getReader();
88
- if (!reader) return "";
89
- const abort = () => {
90
- void reader.cancel().catch(() => {
91
- });
92
- };
93
- signal.addEventListener("abort", abort, { once: true });
94
- const decoder = new TextDecoder("utf-8", { fatal: true });
95
- let bytes = 0;
96
- let text = "";
97
- try {
98
- while (true) {
99
- const chunk = await reader.read();
100
- if (signal.aborted) throw new Error("IPFS text request timed out.");
101
- if (chunk.done) break;
102
- bytes += chunk.value.byteLength;
103
- if (bytes > MAX_TEXT_BYTES) throw new Error("IPFS text exceeds 256 KiB.");
104
- text += decoder.decode(chunk.value, { stream: true });
105
- }
106
- text += decoder.decode();
107
- if (/[\u0000-\u0008\u000b\u000c\u000e-\u001f]/.test(text)) throw new Error("IPFS content is not plain UTF-8 text.");
108
- return text;
109
- } catch (error) {
110
- void reader.cancel().catch(() => {
111
- });
112
- throw error;
113
- } finally {
114
- signal.removeEventListener("abort", abort);
115
- reader.releaseLock();
116
- }
117
- }
118
- function createIpfsTextReader({ fetchImpl = fetch, timeoutMs = 8e3 } = {}) {
119
- const cache = /* @__PURE__ */ new Map();
120
- const pending = /* @__PURE__ */ new Map();
121
- const waiting = [];
122
- let active = 0;
123
- async function load(urls) {
124
- if (active >= MAX_CONCURRENT_READS) await new Promise((resolve) => waiting.push(resolve));
125
- active++;
126
- const controller = new AbortController();
127
- const timer = setTimeout(() => controller.abort(), timeoutMs);
128
- try {
129
- let lastError;
130
- for (const url of urls) {
131
- let response;
132
- try {
133
- response = await fetchImpl(url, {
134
- method: "GET",
135
- credentials: "omit",
136
- redirect: "error",
137
- referrerPolicy: "no-referrer",
138
- cache: "force-cache",
139
- signal: controller.signal
140
- });
141
- } catch (error) {
142
- if (controller.signal.aborted) throw new Error("IPFS text request timed out.");
143
- lastError = error;
144
- continue;
145
- }
146
- if (!response.ok) {
147
- await response.body?.cancel();
148
- lastError = new Error(`IPFS text request returned ${response.status}.`);
149
- continue;
12
+ var defaultUploader = createLocalMediaUploader();
13
+ function useFlapWalletRuntime({ connect, readOnly = false, mediaUploader = defaultUploader }) {
14
+ const config = useConfig();
15
+ const account = useAccount();
16
+ const connectRef = useRef(connect);
17
+ connectRef.current = connect;
18
+ return useMemo(() => {
19
+ const publicClient = (chainId) => {
20
+ const client = getPublicClient(config, { chainId });
21
+ if (!client) throw new Error(`No host public client for ${chainId}.`);
22
+ return client;
23
+ };
24
+ const walletClient = async (chainId, expected) => {
25
+ if (readOnly) throw new Error("Preview fixtures cannot authorize transactions.");
26
+ const client = await getWalletClient(config, { chainId });
27
+ const current = getAccount(config);
28
+ if (!current.isConnected || current.chainId !== chainId || current.address?.toLowerCase() !== expected.toLowerCase() || client.account.address.toLowerCase() !== expected.toLowerCase() || client.chain.id !== chainId) throw new Error("The host wallet changed. Review the account and network again.");
29
+ return client;
30
+ };
31
+ return {
32
+ chains: config.chains.map((chain) => ({ id: chain.id, name: chain.name, explorerBaseUrl: chain.blockExplorers?.default.url })),
33
+ readOnly,
34
+ getAccount: () => {
35
+ const current = getAccount(config);
36
+ return { address: current.address, chainId: current.chainId, isConnected: current.isConnected };
37
+ },
38
+ generation: `${account.address ?? ""}:${account.chainId ?? ""}:${account.isConnected}`,
39
+ connect: () => connectRef.current(),
40
+ disconnect: () => {
41
+ void disconnect(config);
42
+ },
43
+ switchChain: async (chainId) => {
44
+ if (readOnly) throw new Error("Preview fixtures cannot switch a wallet.");
45
+ await switchChain(config, { chainId });
46
+ },
47
+ readContract: async (chainId, request) => {
48
+ const client = publicClient(chainId);
49
+ if (request.gasPrice !== void 0) {
50
+ const { data } = await client.call({ to: request.address, data: encodeFunctionData(request), account: request.account, gasPrice: request.gasPrice });
51
+ return decodeFunctionResult({ abi: request.abi, functionName: request.functionName, data: data ?? "0x" });
150
52
  }
151
- return await readTextBody(response, controller.signal);
53
+ return client.readContract(request);
54
+ },
55
+ simulateContract: async (chainId, request) => (await publicClient(chainId).simulateContract(request)).result,
56
+ writeContract: async (chainId, request) => (await walletClient(chainId, request.account)).writeContract(request),
57
+ sendTransaction: async (chainId, request) => (await walletClient(chainId, request.account)).sendTransaction(request),
58
+ waitForTx: async (chainId, hash2) => {
59
+ const receipt = await publicClient(chainId).waitForTransactionReceipt({ hash: hash2 });
60
+ return { hash: receipt.transactionHash, status: receipt.status, blockNumber: receipt.blockNumber, logs: receipt.logs };
61
+ },
62
+ getCode: (chainId, address2) => publicClient(chainId).getCode({ address: address2 }),
63
+ getGasPrice: (chainId) => publicClient(chainId).getGasPrice(),
64
+ getBlockNumber: (chainId) => publicClient(chainId).getBlockNumber(),
65
+ getBalance: (chainId, address2) => publicClient(chainId).getBalance({ address: address2 }),
66
+ getContractEvents: async (chainId, request) => publicClient(chainId).getContractEvents(request),
67
+ upload: mediaUploader,
68
+ openUrl: (url) => {
69
+ window.open(url, "_blank", "noopener,noreferrer");
152
70
  }
153
- throw lastError ?? new Error("IPFS text could not be loaded.");
154
- } finally {
155
- clearTimeout(timer);
156
- controller.abort();
157
- active--;
158
- waiting.shift()?.();
159
- }
160
- }
161
- return (cid, path) => {
162
- const urls = resolveIpfsImageUrls(cid, 56, path);
163
- if (!urls.length) return Promise.reject(new Error("IPFS text requires a bare CID and an optional safe relative path."));
164
- const key = urls[0];
165
- const cached = cache.get(key);
166
- if (cached !== void 0) {
167
- cache.delete(key);
168
- cache.set(key, cached);
169
- return Promise.resolve(cached);
170
- }
171
- const existing = pending.get(key);
172
- if (existing) return existing;
173
- if (pending.size >= MAX_PENDING_READS) return Promise.reject(new Error("Too many IPFS text reads; paginate the content."));
174
- const request = load(urls).then((text) => {
175
- cache.set(key, text);
176
- if (cache.size > MAX_CACHED_READS) cache.delete(cache.keys().next().value);
177
- return text;
178
- }).finally(() => pending.delete(key));
179
- pending.set(key, request);
180
- return request;
181
- };
182
- }
183
-
184
- // src/sdk/contractWriteFees.ts
185
- var MAX_CONTRACT_WRITE_GAS = 5000000n;
186
- var MAX_GAS_PRICE_MULTIPLIER = 2n;
187
- async function resolveSafeContractWriteFeeOverrides(request, getNetworkGasPrice) {
188
- if (request.gas !== void 0) {
189
- if (request.gas <= 0n) throw new Error("Contract write gas must be greater than zero.");
190
- if (request.gas > MAX_CONTRACT_WRITE_GAS) {
191
- throw new Error(`Contract write gas must not exceed ${MAX_CONTRACT_WRITE_GAS.toString()}.`);
192
- }
193
- }
194
- if (request.gasPrice !== void 0) {
195
- if (request.gasPrice <= 0n) throw new Error("Contract write gasPrice must be greater than zero.");
196
- const networkGasPrice = await getNetworkGasPrice();
197
- if (networkGasPrice <= 0n) throw new Error("The runtime returned an invalid network gas price.");
198
- const maximumGasPrice = networkGasPrice * MAX_GAS_PRICE_MULTIPLIER;
199
- if (request.gasPrice > maximumGasPrice) {
200
- throw new Error(
201
- `Contract write gasPrice ${request.gasPrice.toString()} exceeds the runtime safety limit ${maximumGasPrice.toString()}.`
202
- );
203
- }
204
- }
205
- return {
206
- ...request.gas === void 0 ? {} : { gas: request.gas },
207
- ...request.gasPrice === void 0 ? {} : { gasPrice: request.gasPrice }
208
- };
209
- }
210
-
211
- // src/sdk/contractEvents.ts
212
- var MAX_CONTRACT_EVENT_BLOCK_SPAN = 1000n;
213
- var MAX_CONTRACT_EVENT_BLOCK_LOOKBACK = 20000n;
214
- var CONTRACT_EVENT_QUERY_CONCURRENCY = 4;
215
- function splitContractEventBlockRanges(fromBlock, toBlock, maxBlockSpan = MAX_CONTRACT_EVENT_BLOCK_SPAN, maxLookback = MAX_CONTRACT_EVENT_BLOCK_LOOKBACK) {
216
- if (fromBlock < 0n || toBlock < 0n) {
217
- throw new RangeError("Contract event block numbers must not be negative.");
218
- }
219
- if (maxBlockSpan <= 0n) {
220
- throw new RangeError("Contract event block span must be greater than zero.");
221
- }
222
- if (maxLookback < 0n) {
223
- throw new RangeError("Contract event block lookback must not be negative.");
224
- }
225
- if (toBlock < fromBlock) return [];
226
- if (toBlock - fromBlock > maxLookback) {
227
- throw new RangeError(`Contract event block range must not exceed ${maxLookback.toString()} blocks.`);
228
- }
229
- const ranges = [];
230
- let cursor = fromBlock;
231
- while (cursor <= toBlock) {
232
- const candidateEnd = cursor + maxBlockSpan;
233
- const chunkEnd = candidateEnd < toBlock ? candidateEnd : toBlock;
234
- ranges.push({ fromBlock: cursor, toBlock: chunkEnd });
235
- cursor = chunkEnd + 1n;
236
- }
237
- return ranges;
238
- }
239
- async function readContractEventsInBlockRanges(input) {
240
- const concurrency = input.concurrency ?? CONTRACT_EVENT_QUERY_CONCURRENCY;
241
- if (!Number.isInteger(concurrency) || concurrency < 1 || concurrency > CONTRACT_EVENT_QUERY_CONCURRENCY) {
242
- throw new RangeError(`Contract event query concurrency must be between 1 and ${CONTRACT_EVENT_QUERY_CONCURRENCY}.`);
243
- }
244
- const ranges = splitContractEventBlockRanges(input.fromBlock, input.toBlock);
245
- const events = [];
246
- for (let index2 = 0; index2 < ranges.length; index2 += concurrency) {
247
- const batch = ranges.slice(index2, index2 + concurrency);
248
- const batchEvents = await Promise.all(batch.map((range) => input.readRange(range)));
249
- for (const items of batchEvents) events.push(...items);
250
- }
251
- return events;
71
+ };
72
+ }, [config, readOnly, mediaUploader, account.address, account.chainId, account.isConnected]);
252
73
  }
253
74
  var forbiddenName = /^(?:execute(?:Call|Batch)?|multicall|delegatecall|approve|increaseAllowance|decreaseAllowance|setApprovalForAll|transferOwnership|acceptOwnership|upgradeTo.*|setConfig|setSwapPath|setSplit)$/i;
254
75
  var forbiddenSignatures = ["executeCall(address,uint256,bytes)", "approve(address,uint256)", "setApprovalForAll(address,bool)", "transferOwnership(address)", "upgradeTo(address)", "upgradeToAndCall(address,bytes)"];
@@ -672,7 +493,7 @@ function VaultRuntimeProvider({ children, manifest, i18n, runtimeContext: runtim
672
493
  const { address: accountAddress, isConnected } = useAccount();
673
494
  const connectedChainId = useChainId();
674
495
  const { connect, connectors } = useConnect();
675
- const { disconnect } = useDisconnect();
496
+ const { disconnect: disconnect2 } = useDisconnect();
676
497
  const { switchChainAsync, isPending: isSwitchingChain } = useSwitchChain();
677
498
  const effectiveChainId = runtimeOverrides?.chainId ?? hostRuntimeResult?.addresses.chainId ?? connectedChainId ?? manifest.match.bindings[0]?.chainId ?? 56;
678
499
  const publicClient = usePublicClient({ chainId: effectiveChainId });
@@ -761,7 +582,7 @@ function VaultRuntimeProvider({ children, manifest, i18n, runtimeContext: runtim
761
582
  const connector = connectors[0];
762
583
  if (connector) connect({ connector });
763
584
  },
764
- disconnect: () => disconnect(),
585
+ disconnect: () => disconnect2(),
765
586
  switchChain: async () => {
766
587
  if (previewWallet) {
767
588
  throw new Error(`Switch wallet to ${chainLabelForChain(runtimeContext.chainId)} before continuing.`);
@@ -773,7 +594,7 @@ function VaultRuntimeProvider({ children, manifest, i18n, runtimeContext: runtim
773
594
  }
774
595
  };
775
596
  },
776
- [accountAddress, connect, connectedChainId, connectors, disconnect, isConnected, isSwitchingChain, nativeBalance, runtimeContext.chainId, runtimeOverrides?.previewWallet, switchChainAsync]
597
+ [accountAddress, connect, connectedChainId, connectors, disconnect2, isConnected, isSwitchingChain, nativeBalance, runtimeContext.chainId, runtimeOverrides?.previewWallet, switchChainAsync]
777
598
  );
778
599
  const assertWalletWriteReady = useCallback(
779
600
  (actionLabel) => {
@@ -1089,8 +910,25 @@ function VaultRuntimeProvider({ children, manifest, i18n, runtimeContext: runtim
1089
910
  }
1090
911
  }, [assertWalletWriteReady, nftWithdrawalEnvironment, publicClient, refetch, runtimeContext, walletClient]);
1091
912
  const componentContext = useMemo(() => structuredClone(runtimeContext), [runtimeContext]);
913
+ const chainRuntime = useFlapWalletRuntime({ connect: wallet.connect, mediaUploader: mediaUploader ?? defaultMediaUploader });
914
+ const forChain = useCallback((chainId) => createFlapChainSdk({
915
+ ...chainRuntime,
916
+ // Reuse the Vault's strict target and resolver policies for scoped access too.
917
+ simulateContract: async (_chainId, request) => {
918
+ if (_chainId !== runtimeContext.chainId) throw new Error("Vault writes require the bound network.");
919
+ return (await simulateContract(request)).result;
920
+ },
921
+ writeContract: async (_chainId, request) => {
922
+ if (_chainId !== runtimeContext.chainId) throw new Error("Vault writes require the bound network.");
923
+ return writeContract(request);
924
+ },
925
+ sendTransaction: async () => {
926
+ throw new Error("Raw transactions require a reviewed standalone App.");
927
+ }
928
+ }, { chainId, manifest, writableChains: [runtimeContext.chainId], i18n: i18nApi, notify, readIpfsText }), [chainRuntime, manifest, runtimeContext.chainId, i18nApi, notify, readIpfsText, simulateContract, writeContract]);
1092
929
  const sdk = useMemo(
1093
930
  () => ({
931
+ forChain,
1094
932
  context: componentContext,
1095
933
  i18n: i18nApi,
1096
934
  notify,
@@ -1114,7 +952,7 @@ function VaultRuntimeProvider({ children, manifest, i18n, runtimeContext: runtim
1114
952
  refetchNonce: version,
1115
953
  openExplorerTx
1116
954
  }),
1117
- [getBlockNumber, getContractEvents, getGasPrice, i18nApi, notify, openExplorerTx, resolveContract, readContract, readNftMetadata, readOracle, readFsi, readIpfsText, refetch, componentContext, simulateContract, uploadImage, uploadText, version, waitForTx, wallet, withdrawNftAccount2, writeContract]
955
+ [forChain, getBlockNumber, getContractEvents, getGasPrice, i18nApi, notify, openExplorerTx, resolveContract, readContract, readNftMetadata, readOracle, readFsi, readIpfsText, refetch, componentContext, simulateContract, uploadImage, uploadText, version, waitForTx, wallet, withdrawNftAccount2, writeContract]
1118
956
  );
1119
957
  return /* @__PURE__ */ jsxs(RuntimeContext.Provider, { value: sdk, children: [
1120
958
  children,
@@ -1129,6 +967,6 @@ function VaultRuntimeProvider({ children, manifest, i18n, runtimeContext: runtim
1129
967
  ] });
1130
968
  }
1131
969
 
1132
- export { VaultRuntimeProvider };
1133
- //# sourceMappingURL=chunk-HYBZWS6U.js.map
1134
- //# sourceMappingURL=chunk-HYBZWS6U.js.map
970
+ export { VaultRuntimeProvider, useFlapWalletRuntime };
971
+ //# sourceMappingURL=chunk-DY34U27M.js.map
972
+ //# sourceMappingURL=chunk-DY34U27M.js.map