@flapsdk/vault-runtime 0.1.37 → 0.1.39-next.0

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 (41) hide show
  1. package/README.md +11 -2
  2. package/{chunk-3X2K7YYU.js → chunk-3MVBV65H.js} +215 -74
  3. package/chunk-3MVBV65H.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-HYBZWS6U.js → chunk-JW4MM24W.js} +90 -252
  11. package/chunk-JW4MM24W.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/package.json +4 -3
  22. package/runtime-contract.json +5 -1
  23. package/sdk.d.mts +42 -4
  24. package/sdk.js +41 -9
  25. package/sdk.js.map +1 -1
  26. package/server.d.mts +3 -3
  27. package/server.js +4 -5
  28. package/server.js.map +1 -1
  29. package/{txError-vvvBIsa-.d.mts → txError-BTuW38It.d.mts} +15 -2
  30. package/{types-cyAEoeXa.d.mts → types-BolUPLIE.d.mts} +101 -2
  31. package/ui.d.mts +13 -2
  32. package/ui.js +2 -3
  33. package/chunk-22KTLOYH.js.map +0 -1
  34. package/chunk-27VBKY3J.js +0 -36
  35. package/chunk-27VBKY3J.js.map +0 -1
  36. package/chunk-3X2K7YYU.js.map +0 -1
  37. package/chunk-AGLB72HK.js +0 -61
  38. package/chunk-AGLB72HK.js.map +0 -1
  39. package/chunk-FUOBTZMQ.js +0 -47
  40. package/chunk-FUOBTZMQ.js.map +0 -1
  41. package/chunk-HYBZWS6U.js.map +0 -1
@@ -0,0 +1,583 @@
1
+ import { resolveManifestBinding } from './chunk-B4WKI3EW.js';
2
+ import { resolveIpfsImageUrls } from './chunk-GY7YY67I.js';
3
+ import { toFunctionSelector, parseAbi, isHex, decodeFunctionData, encodeFunctionData, isAddress, keccak256 } from 'viem';
4
+
5
+ var bad = (ok, reason) => {
6
+ if (!ok) throw new Error(`app-wallet/${reason}`);
7
+ };
8
+ var address = (a) => typeof a === "string" && isAddress(a, { strict: false }) && !/^0x0{40}$/i.test(a);
9
+ var admin = /^(?:execute(?:Call|Batch)?|multicall|delegatecall|setApprovalForAll|transferOwnership|acceptOwnership|upgradeTo.*|setConfig|setSwapPath|setSplit|increaseAllowance|decreaseAllowance)$/i;
10
+ var forbiddenSelectors = new Set(["execute(address,uint256,bytes,uint8)", "execute(address,uint256,bytes)", "executeCall(address,uint256,bytes)", "setApprovalForAll(address,bool)", "transferOwnership(address)", "upgradeTo(address)", "upgradeToAndCall(address,bytes)"].map(toFunctionSelector));
11
+ function signatures(items, read = false) {
12
+ bad(Array.isArray(items) && items.length <= 32, "invalid-signatures");
13
+ const abi = items.map((text) => {
14
+ bad(typeof text === "string" && text.length <= 2048, "invalid-signature");
15
+ const entries = parseAbi([text]);
16
+ bad(entries.length === 1 && entries[0].type === "function", "invalid-signature");
17
+ const f = entries[0];
18
+ bad(read ? ["view", "pure"].includes(f.stateMutability) : !["view", "pure"].includes(f.stateMutability) && !admin.test(f.name) && !forbiddenSelectors.has(toFunctionSelector(f)), "forbidden-function");
19
+ return f;
20
+ });
21
+ bad(new Set(abi.map(toFunctionSelector)).size === abi.length, "duplicate-selector");
22
+ return abi;
23
+ }
24
+ function permissions(input) {
25
+ const writes = signatures(input.allow ?? []);
26
+ const reads = signatures(input.read ?? [], true);
27
+ bad(writes.length + reads.length > 0, "empty-permissions");
28
+ bad(input.maxValueWei === void 0 || typeof input.maxValueWei === "string" && /^[1-9][0-9]{0,77}$/.test(input.maxValueWei) && BigInt(input.maxValueWei) < 2n ** 256n, "invalid-value-cap");
29
+ if (writes.some((f) => f.stateMutability === "payable")) bad(input.maxValueWei !== void 0, "missing-value-cap");
30
+ if (writes.some((f) => f.name === "approve")) {
31
+ bad(writes.filter((f) => f.name === "approve").every((f) => toFunctionSelector(f) === "0x095ea7b3"), "invalid-approve");
32
+ bad(Array.isArray(input.approvalSpenders) && input.approvalSpenders.length > 0 && input.approvalSpenders.length <= 8 && input.approvalSpenders.every(address), "missing-approval-spenders");
33
+ bad(typeof input.maxApprovalWei === "string" && /^[1-9][0-9]{0,77}$/.test(input.maxApprovalWei) && BigInt(input.maxApprovalWei) < 2n ** 256n, "missing-approval-cap");
34
+ } else bad(input.approvalSpenders === void 0 && input.maxApprovalWei === void 0, "unexpected-approval-policy");
35
+ return { definition: structuredClone(input), writes, reads };
36
+ }
37
+ var hasDynamicBytes = (parameter) => /^bytes(?:\[|$)/.test(parameter.type) || parameter.components?.some(hasDynamicBytes);
38
+ var common = ["id", "allow", "read", "maxValueWei", "approvalSpenders", "maxApprovalWei", "codeHash"];
39
+ function identity(input, keys) {
40
+ bad(input && typeof input === "object" && !Array.isArray(input) && Object.keys(input).every((k) => keys.includes(k)), "unknown-field");
41
+ bad(typeof input.id === "string" && /^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(input.id) && input.id.length <= 64, "invalid-id");
42
+ bad(input.codeHash === void 0 || /^0x[0-9a-fA-F]{64}$/.test(input.codeHash), "invalid-code-hash");
43
+ }
44
+ function parseAppWalletContracts(value) {
45
+ bad(Array.isArray(value) && value.length > 0 && value.length <= 16, "invalid-contracts");
46
+ const ids = /* @__PURE__ */ new Set();
47
+ const targets = /* @__PURE__ */ new Set();
48
+ return value.map((input) => {
49
+ identity(input, [...common, "chainId", "address", "resolvedContracts"]);
50
+ bad(Number.isSafeInteger(input.chainId) && input.chainId > 0 && address(input.address), "invalid-target");
51
+ const key = `${input.chainId}:${input.address.toLowerCase()}`;
52
+ bad(!targets.has(key) && !ids.has(input.id), "duplicate-contract");
53
+ targets.add(key);
54
+ ids.add(input.id);
55
+ const policy = permissions(input);
56
+ bad(input.resolvedContracts === void 0 || Array.isArray(input.resolvedContracts) && input.resolvedContracts.length <= 8, "invalid-resolvers");
57
+ const resolved = (input.resolvedContracts ?? []).map((item) => {
58
+ identity(item, [...common, "resolver"]);
59
+ bad(!ids.has(item.id), "duplicate-resolver");
60
+ ids.add(item.id);
61
+ bad(typeof item.resolver === "string" && item.resolver.length <= 2048, "invalid-resolver");
62
+ const entries = parseAbi([item.resolver]);
63
+ const resolver = entries[0];
64
+ bad(entries.length === 1 && resolver.type === "function" && ["view", "pure"].includes(resolver.stateMutability) && resolver.outputs.length === 1 && resolver.outputs[0].type === "address" && resolver.inputs.length <= 32, "invalid-resolver");
65
+ const parsed = permissions(item);
66
+ bad(parsed.writes.every((f) => !f.inputs.some(hasDynamicBytes)), "nested-calldata-not-allowed");
67
+ return { ...parsed, resolver };
68
+ });
69
+ return { ...policy, resolved };
70
+ });
71
+ }
72
+ var requireRule = (ok, reason) => {
73
+ if (!ok) throw new Error(`app-wallet/${reason}`);
74
+ };
75
+ var same = (a, b) => typeof a === "string" && typeof b === "string" && a.toLowerCase() === b.toLowerCase();
76
+ function createAppWalletContracts(runtime, chainId, manifest) {
77
+ const roots = manifest.walletContracts === void 0 ? [] : parseAppWalletContracts(manifest.walletContracts).filter((p) => p.definition.chainId === chainId);
78
+ const records = /* @__PURE__ */ new WeakMap();
79
+ async function checkCode(address2, policy) {
80
+ const code = await runtime.getCode(chainId, address2);
81
+ requireRule(code && code !== "0x", "missing-code");
82
+ if (policy.definition.codeHash) requireRule(same(keccak256(code), policy.definition.codeHash), "code-hash-changed");
83
+ }
84
+ async function resolve(root, policy, args) {
85
+ await checkCode(root.definition.address, root);
86
+ const address2 = await runtime.readContract(chainId, { address: root.definition.address, abi: [policy.resolver], functionName: policy.resolver.name, args });
87
+ requireRule(typeof address2 === "string" && /^0x[0-9a-f]{40}$/i.test(address2) && !/^0x0{40}$/i.test(address2), "invalid-resolved-target");
88
+ await checkCode(address2, policy);
89
+ return address2;
90
+ }
91
+ async function resolveContract(id, input) {
92
+ const root = roots.find((p) => p.resolved.some((r) => r.definition.id === id));
93
+ const policy = root?.resolved.find((p) => p.definition.id === id);
94
+ if (!root || !policy) throw new Error("app-wallet/undeclared-resolver");
95
+ const args = structuredClone([...input]);
96
+ encodeFunctionData({ abi: [policy.resolver], functionName: policy.resolver.name, args });
97
+ const address2 = await resolve(root, policy, args);
98
+ const handle = Object.freeze({ id, chainId, address: address2, args: Object.freeze(structuredClone(args)) });
99
+ records.set(handle, { root, policy, address: address2, args });
100
+ return handle;
101
+ }
102
+ function snapshot(input) {
103
+ const { contract, ...data } = input;
104
+ const request = structuredClone(data);
105
+ const record = typeof contract === "object" && contract !== null ? records.get(contract) : void 0;
106
+ requireRule(typeof contract !== "object" || record, "forged-or-expired-handle");
107
+ requireRule(!record || input.address === void 0, "handle-with-address");
108
+ const root = roots.find((p) => same(p.definition.address, request.address));
109
+ const policy = record?.policy ?? root;
110
+ requireRule(policy, "undeclared-target");
111
+ return { request, record, root, policy };
112
+ }
113
+ function checkFunction(request, policy, write) {
114
+ requireRule(request.abi && request.functionName, "invalid-call");
115
+ const data = encodeFunctionData({ abi: request.abi, functionName: request.functionName, args: request.args });
116
+ const entry = (write ? policy.writes : policy.reads).find((f) => toFunctionSelector(f) === data.slice(0, 10));
117
+ requireRule(entry, "selector-not-allowed");
118
+ requireRule(encodeFunctionData({ abi: [entry], functionName: entry.name, args: request.args }) === data, "abi-mismatch");
119
+ const value = request.value ?? 0n;
120
+ requireRule(value >= 0n && (value === 0n || entry.stateMutability === "payable" && policy.definition.maxValueWei && value <= BigInt(policy.definition.maxValueWei)), "value-not-allowed");
121
+ if (write && entry.name === "approve") {
122
+ requireRule(policy.definition.approvalSpenders?.some((a) => same(a, request.args?.[0])), "spender-not-allowed");
123
+ const amount = request.args?.[1];
124
+ requireRule(typeof amount === "bigint" && amount >= 0n && amount <= BigInt(policy.definition.maxApprovalWei), "approval-cap-exceeded");
125
+ }
126
+ return { ...request, abi: [entry], functionName: entry.name };
127
+ }
128
+ async function validate(prepared, write) {
129
+ const { record, root, policy } = prepared;
130
+ let address2 = root?.definition.address;
131
+ if (record) {
132
+ address2 = await resolve(record.root, record.policy, record.args);
133
+ requireRule(same(address2, record.address), "resolved-target-changed");
134
+ } else if (write) await checkCode(address2, policy);
135
+ return checkFunction({ ...prepared.request, address: address2 }, policy, write);
136
+ }
137
+ return { roots, snapshot, validate, resolveContract };
138
+ }
139
+
140
+ // src/sdk/ipfsText.ts
141
+ var MAX_TEXT_BYTES = 256 * 1024;
142
+ var MAX_CONCURRENT_READS = 6;
143
+ var MAX_PENDING_READS = 128;
144
+ var MAX_CACHED_READS = 64;
145
+ var TEXT_MEDIA_TYPES = /* @__PURE__ */ new Set(["text/plain", "application/json", "application/octet-stream"]);
146
+ async function readTextBody(response, signal) {
147
+ const contentType = response.headers.get("content-type") ?? "";
148
+ if (!TEXT_MEDIA_TYPES.has(contentType.split(";")[0].trim().toLowerCase())) {
149
+ throw new Error("IPFS text must use text/plain, application/json or application/octet-stream.");
150
+ }
151
+ const charset = /charset\s*=\s*["']?([^;"'\s]+)/i.exec(contentType)?.[1];
152
+ if (charset && !/^utf-?8$/i.test(charset)) throw new Error("IPFS text must use UTF-8.");
153
+ if (Number(response.headers.get("content-length")) > MAX_TEXT_BYTES) {
154
+ await response.body?.cancel();
155
+ throw new Error("IPFS text exceeds 256 KiB.");
156
+ }
157
+ const reader = response.body?.getReader();
158
+ if (!reader) return "";
159
+ const abort = () => {
160
+ void reader.cancel().catch(() => {
161
+ });
162
+ };
163
+ signal.addEventListener("abort", abort, { once: true });
164
+ const decoder = new TextDecoder("utf-8", { fatal: true });
165
+ let bytes = 0;
166
+ let text = "";
167
+ try {
168
+ while (true) {
169
+ const chunk = await reader.read();
170
+ if (signal.aborted) throw new Error("IPFS text request timed out.");
171
+ if (chunk.done) break;
172
+ bytes += chunk.value.byteLength;
173
+ if (bytes > MAX_TEXT_BYTES) throw new Error("IPFS text exceeds 256 KiB.");
174
+ text += decoder.decode(chunk.value, { stream: true });
175
+ }
176
+ text += decoder.decode();
177
+ if (/[\u0000-\u0008\u000b\u000c\u000e-\u001f]/.test(text)) throw new Error("IPFS content is not plain UTF-8 text.");
178
+ return text;
179
+ } catch (error) {
180
+ void reader.cancel().catch(() => {
181
+ });
182
+ throw error;
183
+ } finally {
184
+ signal.removeEventListener("abort", abort);
185
+ reader.releaseLock();
186
+ }
187
+ }
188
+ function createIpfsTextReader({ fetchImpl = fetch, timeoutMs = 8e3 } = {}) {
189
+ const cache = /* @__PURE__ */ new Map();
190
+ const pending = /* @__PURE__ */ new Map();
191
+ const waiting = [];
192
+ let active = 0;
193
+ async function load(urls) {
194
+ if (active >= MAX_CONCURRENT_READS) await new Promise((resolve) => waiting.push(resolve));
195
+ active++;
196
+ const controller = new AbortController();
197
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
198
+ try {
199
+ let lastError;
200
+ for (const url of urls) {
201
+ let response;
202
+ try {
203
+ response = await fetchImpl(url, {
204
+ method: "GET",
205
+ credentials: "omit",
206
+ redirect: "error",
207
+ referrerPolicy: "no-referrer",
208
+ cache: "force-cache",
209
+ signal: controller.signal
210
+ });
211
+ } catch (error) {
212
+ if (controller.signal.aborted) throw new Error("IPFS text request timed out.");
213
+ lastError = error;
214
+ continue;
215
+ }
216
+ if (!response.ok) {
217
+ await response.body?.cancel();
218
+ lastError = new Error(`IPFS text request returned ${response.status}.`);
219
+ continue;
220
+ }
221
+ return await readTextBody(response, controller.signal);
222
+ }
223
+ throw lastError ?? new Error("IPFS text could not be loaded.");
224
+ } finally {
225
+ clearTimeout(timer);
226
+ controller.abort();
227
+ active--;
228
+ waiting.shift()?.();
229
+ }
230
+ }
231
+ return (cid, path) => {
232
+ const urls = resolveIpfsImageUrls(cid, 56, path);
233
+ if (!urls.length) return Promise.reject(new Error("IPFS text requires a bare CID and an optional safe relative path."));
234
+ const key = urls[0];
235
+ const cached = cache.get(key);
236
+ if (cached !== void 0) {
237
+ cache.delete(key);
238
+ cache.set(key, cached);
239
+ return Promise.resolve(cached);
240
+ }
241
+ const existing = pending.get(key);
242
+ if (existing) return existing;
243
+ if (pending.size >= MAX_PENDING_READS) return Promise.reject(new Error("Too many IPFS text reads; paginate the content."));
244
+ const request = load(urls).then((text) => {
245
+ cache.set(key, text);
246
+ if (cache.size > MAX_CACHED_READS) cache.delete(cache.keys().next().value);
247
+ return text;
248
+ }).finally(() => pending.delete(key));
249
+ pending.set(key, request);
250
+ return request;
251
+ };
252
+ }
253
+
254
+ // src/sdk/fsiPolicy.mjs
255
+ var FSI_QUERY_PREFIX = "https://bsc-debug.butterfly.army/fsi/v1";
256
+ var FSI_ORIGIN = "https://bsc-debug.butterfly.army";
257
+ var FSI_PATH = "/fsi/v1";
258
+ var encodedPathSyntax = /%(?:2e|2f|5c|25)/i;
259
+ var hasDotSegment = (path) => path.split("/").some((part) => part === "." || part === "..");
260
+ function isFsiQueryUrl(value) {
261
+ try {
262
+ if (typeof value !== "string" || /[\\#\u0000-\u0020\u007f]/.test(value)) return false;
263
+ const rawPath = value.match(/^[a-z][a-z\d+.-]*:\/\/[^/?#]*([^?#]*)/i)?.[1];
264
+ if (rawPath === void 0 || encodedPathSyntax.test(rawPath) || hasDotSegment(rawPath)) return false;
265
+ const url = new URL(value);
266
+ return url.origin === FSI_ORIGIN && !url.username && !url.password && !url.hash && (url.pathname === FSI_PATH || url.pathname.startsWith(`${FSI_PATH}/`)) && !encodedPathSyntax.test(url.pathname);
267
+ } catch {
268
+ return false;
269
+ }
270
+ }
271
+ function hasFsiQueryDeclaration(endpoints) {
272
+ const urls = typeof endpoints === "string" ? [endpoints] : endpoints;
273
+ return Array.isArray(urls) && urls.some((value) => {
274
+ if (!isFsiQueryUrl(value)) return false;
275
+ const url = new URL(value);
276
+ return !url.search && (url.pathname === FSI_PATH || url.pathname === `${FSI_PATH}/`);
277
+ });
278
+ }
279
+ function buildFsiQueryUrl(path, params = {}) {
280
+ if (typeof path !== "string" || path.startsWith("/") || /[\\?#\s\u0000-\u001f\u007f]/.test(path)) {
281
+ throw new Error("FSI path must be relative to /fsi/v1 without query or fragment; pass query parameters separately.");
282
+ }
283
+ if (encodedPathSyntax.test(path) || hasDotSegment(path)) {
284
+ throw new Error("FSI path traversal and encoded path separators/dots are not allowed.");
285
+ }
286
+ const url = new URL(`${FSI_QUERY_PREFIX}/${path}`);
287
+ if (!isFsiQueryUrl(url.href)) throw new Error("FSI URL is outside the platform query allowlist.");
288
+ for (const [key, value] of Object.entries(params)) {
289
+ if (typeof value !== "string") throw new Error("FSI query parameter values must be strings.");
290
+ url.searchParams.set(key, value);
291
+ }
292
+ return url.href;
293
+ }
294
+
295
+ // src/sdk/fsi.ts
296
+ async function readFsiJson(endpoints, path, params, fetchImpl = fetch) {
297
+ if (!hasFsiQueryDeclaration(endpoints)) {
298
+ throw new Error("FSI requires https://bsc-debug.butterfly.army/fsi/v1 in manifest.endpoints for review.");
299
+ }
300
+ const url = buildFsiQueryUrl(path, params);
301
+ const response = await fetchImpl(url, {
302
+ method: "GET",
303
+ credentials: "omit",
304
+ redirect: "error",
305
+ referrerPolicy: "no-referrer",
306
+ cache: "no-store"
307
+ });
308
+ if (!response.ok) throw new Error(`FSI request returned ${response.status}.`);
309
+ return await response.json();
310
+ }
311
+
312
+ // src/sdk/contractWriteFees.ts
313
+ var MAX_CONTRACT_WRITE_GAS = 5000000n;
314
+ var MAX_GAS_PRICE_MULTIPLIER = 2n;
315
+ async function resolveSafeContractWriteFeeOverrides(request, getNetworkGasPrice) {
316
+ if (request.gas !== void 0) {
317
+ if (request.gas <= 0n) throw new Error("Contract write gas must be greater than zero.");
318
+ if (request.gas > MAX_CONTRACT_WRITE_GAS) {
319
+ throw new Error(`Contract write gas must not exceed ${MAX_CONTRACT_WRITE_GAS.toString()}.`);
320
+ }
321
+ }
322
+ if (request.gasPrice !== void 0) {
323
+ if (request.gasPrice <= 0n) throw new Error("Contract write gasPrice must be greater than zero.");
324
+ const networkGasPrice = await getNetworkGasPrice();
325
+ if (networkGasPrice <= 0n) throw new Error("The runtime returned an invalid network gas price.");
326
+ const maximumGasPrice = networkGasPrice * MAX_GAS_PRICE_MULTIPLIER;
327
+ if (request.gasPrice > maximumGasPrice) {
328
+ throw new Error(
329
+ `Contract write gasPrice ${request.gasPrice.toString()} exceeds the runtime safety limit ${maximumGasPrice.toString()}.`
330
+ );
331
+ }
332
+ }
333
+ return {
334
+ ...request.gas === void 0 ? {} : { gas: request.gas },
335
+ ...request.gasPrice === void 0 ? {} : { gasPrice: request.gasPrice }
336
+ };
337
+ }
338
+
339
+ // src/sdk/contractEvents.ts
340
+ var MAX_CONTRACT_EVENT_BLOCK_SPAN = 1000n;
341
+ var MAX_CONTRACT_EVENT_BLOCK_LOOKBACK = 20000n;
342
+ var CONTRACT_EVENT_QUERY_CONCURRENCY = 4;
343
+ function splitContractEventBlockRanges(fromBlock, toBlock, maxBlockSpan = MAX_CONTRACT_EVENT_BLOCK_SPAN, maxLookback = MAX_CONTRACT_EVENT_BLOCK_LOOKBACK) {
344
+ if (fromBlock < 0n || toBlock < 0n) {
345
+ throw new RangeError("Contract event block numbers must not be negative.");
346
+ }
347
+ if (maxBlockSpan <= 0n) {
348
+ throw new RangeError("Contract event block span must be greater than zero.");
349
+ }
350
+ if (maxLookback < 0n) {
351
+ throw new RangeError("Contract event block lookback must not be negative.");
352
+ }
353
+ if (toBlock < fromBlock) return [];
354
+ if (toBlock - fromBlock > maxLookback) {
355
+ throw new RangeError(`Contract event block range must not exceed ${maxLookback.toString()} blocks.`);
356
+ }
357
+ const ranges = [];
358
+ let cursor = fromBlock;
359
+ while (cursor <= toBlock) {
360
+ const candidateEnd = cursor + maxBlockSpan;
361
+ const chunkEnd = candidateEnd < toBlock ? candidateEnd : toBlock;
362
+ ranges.push({ fromBlock: cursor, toBlock: chunkEnd });
363
+ cursor = chunkEnd + 1n;
364
+ }
365
+ return ranges;
366
+ }
367
+ async function readContractEventsInBlockRanges(input) {
368
+ const concurrency = input.concurrency ?? CONTRACT_EVENT_QUERY_CONCURRENCY;
369
+ if (!Number.isInteger(concurrency) || concurrency < 1 || concurrency > CONTRACT_EVENT_QUERY_CONCURRENCY) {
370
+ throw new RangeError(`Contract event query concurrency must be between 1 and ${CONTRACT_EVENT_QUERY_CONCURRENCY}.`);
371
+ }
372
+ const ranges = splitContractEventBlockRanges(input.fromBlock, input.toBlock);
373
+ const events = [];
374
+ for (let index = 0; index < ranges.length; index += concurrency) {
375
+ const batch = ranges.slice(index, index + concurrency);
376
+ const batchEvents = await Promise.all(batch.map((range) => input.readRange(range)));
377
+ for (const items of batchEvents) events.push(...items);
378
+ }
379
+ return events;
380
+ }
381
+
382
+ // src/sdk/flapChainRuntime.ts
383
+ var FLAP_WALLET_RUNTIME_VERSION = 1;
384
+ function assertAddress(address2) {
385
+ if (typeof address2 !== "string" || !isAddress(address2, { strict: false }) || /^0x0{40}$/i.test(address2)) throw new Error("A valid nonzero target address is required.");
386
+ }
387
+ function contractRequest(request) {
388
+ assertAddress(request.address);
389
+ if (!Array.isArray(request.abi) || !request.abi.length || !request.functionName?.trim()) throw new Error("Contract calls require an explicit ABI and function name.");
390
+ return { address: request.address, abi: request.abi, functionName: request.functionName, args: request.args, account: request.account, gasPrice: request.gasPrice };
391
+ }
392
+ function assertValue(value) {
393
+ if (value !== void 0 && (typeof value !== "bigint" || value < 0n)) throw new Error("Transaction value must be a nonnegative bigint.");
394
+ }
395
+ function createFlapChainSdk(runtime, input) {
396
+ const { chainId, i18n, notify } = input;
397
+ const manifest = structuredClone(input.manifest);
398
+ const writableChains = [...input.writableChains];
399
+ const chain = runtime.chains.find((item) => item.id === chainId);
400
+ if (!Number.isSafeInteger(chainId) || !chain) throw new Error(`Unsupported host chain ${chainId}.`);
401
+ const chainName = chain.name;
402
+ const appPolicy = manifest.appModel === "standalone" ? createAppWalletContracts(runtime, chainId, manifest) : void 0;
403
+ function writeAccount(expected) {
404
+ runtime.assertActive?.();
405
+ if (runtime.readOnly) throw new Error("Preview fixtures cannot authorize transactions.");
406
+ if (!writableChains.includes(chainId)) throw new Error(`Declare walletChains containing ${chainId} before using wallet actions.`);
407
+ const account = runtime.getAccount();
408
+ if (!account.isConnected || !account.address) throw new Error("Connect the host wallet before using wallet actions.");
409
+ if (account.chainId !== chainId) throw new Error(`Switch the host wallet to ${chainName} before using wallet actions.`);
410
+ if (expected && expected.toLowerCase() !== account.address.toLowerCase()) throw new Error("The host wallet account changed. Review the transaction again.");
411
+ return account.address;
412
+ }
413
+ async function prepareWrite(request) {
414
+ const account = writeAccount(request.account);
415
+ const prepared = appPolicy?.snapshot(request);
416
+ const snapshot = prepared?.request ?? structuredClone(request);
417
+ assertValue(snapshot.value);
418
+ const fees = await resolveSafeContractWriteFeeOverrides(snapshot, () => runtime.getGasPrice(chainId));
419
+ const call = appPolicy && prepared ? await appPolicy.validate(prepared, true) : contractRequest(snapshot);
420
+ writeAccount(account);
421
+ return { call: { ...call, ...fees, account, value: snapshot.value }, prepared };
422
+ }
423
+ let switchingChain = false;
424
+ const wallet = {
425
+ get address() {
426
+ return runtime.getAccount().isConnected ? runtime.getAccount().address : void 0;
427
+ },
428
+ get chainId() {
429
+ return runtime.getAccount().chainId;
430
+ },
431
+ get chainLabel() {
432
+ return runtime.chains.find((item) => item.id === runtime.getAccount().chainId)?.name;
433
+ },
434
+ requiredChainId: chainId,
435
+ requiredChainLabel: chain.name,
436
+ get isConnected() {
437
+ return runtime.getAccount().isConnected;
438
+ },
439
+ get isWrongNetwork() {
440
+ const account = runtime.getAccount();
441
+ return account.isConnected && account.chainId !== chainId;
442
+ },
443
+ canSwitchChain: !runtime.readOnly,
444
+ get isSwitchingChain() {
445
+ return switchingChain;
446
+ },
447
+ connect: () => runtime.connect(),
448
+ disconnect: () => runtime.disconnect(),
449
+ switchChain: async () => {
450
+ if (runtime.readOnly) throw new Error("Preview fixtures cannot switch a wallet.");
451
+ switchingChain = true;
452
+ try {
453
+ await runtime.switchChain(chainId);
454
+ } finally {
455
+ switchingChain = false;
456
+ }
457
+ }
458
+ };
459
+ return {
460
+ context: { chainId, manifest },
461
+ i18n,
462
+ notify,
463
+ wallet,
464
+ resolveContract: async (id, args) => {
465
+ if (!appPolicy) throw new Error("Use the Vault SDK's resolveContract for bound targets.");
466
+ return appPolicy.resolveContract(id, args);
467
+ },
468
+ readContract: async (request) => {
469
+ const call = appPolicy ? await appPolicy.validate(appPolicy.snapshot(request), false) : contractRequest(request);
470
+ return runtime.readContract(chainId, call);
471
+ },
472
+ simulateContract: async (request) => {
473
+ const { call } = await prepareWrite(request);
474
+ const result = await runtime.simulateContract(chainId, call);
475
+ writeAccount(call.account);
476
+ return { request: { ...call, ...typeof request.contract === "object" ? { contract: request.contract, address: void 0 } : {} }, result };
477
+ },
478
+ writeContract: async (request) => {
479
+ let { call, prepared } = await prepareWrite(request);
480
+ if (appPolicy && prepared?.record) {
481
+ await runtime.simulateContract(chainId, call);
482
+ call = { ...call, ...await appPolicy.validate(prepared, true), account: call.account };
483
+ }
484
+ writeAccount(call.account);
485
+ return runtime.writeContract(chainId, call);
486
+ },
487
+ sendTransaction: async (request) => {
488
+ request = structuredClone(request);
489
+ const account = writeAccount();
490
+ assertAddress(request.to);
491
+ assertValue(request.value);
492
+ if (!appPolicy || !request.data || !isHex(request.data, { strict: true }) || request.data.length % 2 !== 0) throw new Error("Raw transactions require declared App contract calldata.");
493
+ const root = appPolicy.roots.find((p) => p.definition.address.toLowerCase() === request.to.toLowerCase());
494
+ if (!root) throw new Error("app-wallet/undeclared-target");
495
+ const decoded = decodeFunctionData({ abi: root.writes, data: request.data });
496
+ const { call } = await prepareWrite({ address: request.to, abi: root.writes, functionName: decoded.functionName, args: decoded.args ? [...decoded.args] : [], value: request.value, gas: request.gas, gasPrice: request.gasPrice });
497
+ writeAccount(account);
498
+ return runtime.sendTransaction(chainId, { to: call.address, data: encodeFunctionData(call), value: call.value, gas: call.gas, gasPrice: call.gasPrice, account });
499
+ },
500
+ waitForTx: (hash) => {
501
+ if (!/^0x[0-9a-f]{64}$/i.test(hash)) throw new Error("Invalid transaction hash.");
502
+ return runtime.waitForTx(chainId, hash);
503
+ },
504
+ getGasPrice: () => runtime.getGasPrice(chainId),
505
+ getBlockNumber: () => runtime.getBlockNumber(chainId),
506
+ getBalance: async (address2 = runtime.getAccount().address) => {
507
+ assertAddress(address2);
508
+ return runtime.getBalance(chainId, address2);
509
+ },
510
+ getContractEvents: async (request) => {
511
+ assertAddress(request.address);
512
+ if (!request.abi?.length || !request.eventName?.trim()) throw new Error("Event lookup requires an ABI and event name.");
513
+ return readContractEventsInBlockRanges({ fromBlock: request.fromBlock, toBlock: typeof request.toBlock === "bigint" ? request.toBlock : await runtime.getBlockNumber(chainId), readRange: async (range) => runtime.getContractEvents(chainId, { ...request, ...range }) });
514
+ },
515
+ readIpfsText: input.readIpfsText ?? createIpfsTextReader(),
516
+ readFsi: (path, params) => readFsiJson(manifest.endpoints ?? [], path, params),
517
+ uploadImage: (file, options) => runtime.upload({ kind: "image", file, chainId, ...options }),
518
+ uploadText: (text, options) => runtime.upload({ kind: "text", file: new Blob([text], { type: "text/plain;charset=utf-8" }), chainId, ...options }),
519
+ openExplorerTx: (hash) => {
520
+ if (chain.explorerBaseUrl && /^0x[0-9a-f]{64}$/i.test(hash)) runtime.openUrl(`${chain.explorerBaseUrl.replace(/\/$/, "")}/tx/${hash}`);
521
+ }
522
+ };
523
+ }
524
+
525
+ // src/sdk/runtimeContext.ts
526
+ var zeroAddress = "0x0000000000000000000000000000000000000000";
527
+ function explorerForChain(chainId) {
528
+ if (chainId === 56) return "https://bscscan.com";
529
+ if (chainId === 97) return "https://testnet.bscscan.com";
530
+ if (chainId === 4663) return "https://robinhoodchain.blockscout.com";
531
+ if (chainId === 46630) return "https://explorer.testnet.chain.robinhood.com";
532
+ return void 0;
533
+ }
534
+ function chainLabelForChain(chainId) {
535
+ if (chainId === 56) return "BNB Chain";
536
+ if (chainId === 97) return "BNB Testnet";
537
+ if (chainId === 4663) return "Robinhood Chain";
538
+ if (chainId === 46630) return "Robinhood Chain Testnet";
539
+ return `Chain ${chainId}`;
540
+ }
541
+ function buildRuntimeExtraConfig(input) {
542
+ const hostRuntimeResult = input.hostRuntimeResult;
543
+ const runtimeOverrides = input.runtimeOverrides;
544
+ return {
545
+ ...hostRuntimeResult ? {
546
+ hostRuntimeStatus: hostRuntimeResult.status,
547
+ hostRuntimePolicy: hostRuntimeResult.policy,
548
+ hostRuntimeDegradeReason: hostRuntimeResult.degradeReason,
549
+ hostRuntimeWarnings: hostRuntimeResult.warnings
550
+ } : {},
551
+ ...hostRuntimeResult?.presentation?.extraConfig ?? {},
552
+ ...runtimeOverrides?.extraConfig ?? {}
553
+ };
554
+ }
555
+ function createVaultRuntimeContext(input) {
556
+ const runtimeOverrides = input.runtimeOverrides;
557
+ const resolvedBinding = resolveManifestBinding(input.manifest, {
558
+ chainId: runtimeOverrides?.chainId ?? input.connectedChainId ?? input.hostRuntimeResult?.addresses.chainId,
559
+ factoryAddress: runtimeOverrides?.factoryAddress ?? input.hostRuntimeResult?.addresses.factoryAddress,
560
+ vaultAddress: runtimeOverrides?.vaultAddress ?? input.hostRuntimeResult?.addresses.vaultAddress,
561
+ tokenAddress: runtimeOverrides?.tokenAddress ?? input.hostRuntimeResult?.addresses.tokenAddress
562
+ });
563
+ const effectiveChainId = runtimeOverrides?.chainId ?? input.hostRuntimeResult?.addresses.chainId ?? input.connectedChainId ?? resolvedBinding?.chainId ?? input.manifest.match.bindings[0]?.chainId ?? 56;
564
+ return {
565
+ chainId: effectiveChainId,
566
+ factoryAddress: runtimeOverrides?.factoryAddress ?? input.hostRuntimeResult?.addresses.factoryAddress ?? resolvedBinding?.factoryAddress ?? zeroAddress,
567
+ tokenAddress: runtimeOverrides?.tokenAddress ?? input.hostRuntimeResult?.addresses.tokenAddress ?? zeroAddress,
568
+ vaultAddress: runtimeOverrides?.vaultAddress ?? input.hostRuntimeResult?.addresses.vaultAddress ?? zeroAddress,
569
+ userAddress: runtimeOverrides?.userAddress,
570
+ tokenSymbol: runtimeOverrides?.tokenSymbol ?? input.hostRuntimeResult?.tokenSymbol,
571
+ tokenName: runtimeOverrides?.tokenName ?? input.hostRuntimeResult?.tokenName,
572
+ tokenImageUrl: runtimeOverrides?.tokenImageUrl ?? input.hostRuntimeResult?.tokenImageUrl,
573
+ explorerBaseUrl: runtimeOverrides?.explorerBaseUrl ?? explorerForChain(effectiveChainId),
574
+ paymentToken: runtimeOverrides?.paymentToken ?? input.hostRuntimeResult?.paymentToken,
575
+ host: runtimeOverrides?.host ?? input.hostRuntimeResult?.host,
576
+ extraConfig: buildRuntimeExtraConfig(input),
577
+ manifest: input.manifest
578
+ };
579
+ }
580
+
581
+ export { FLAP_WALLET_RUNTIME_VERSION, chainLabelForChain, createFlapChainSdk, createIpfsTextReader, createVaultRuntimeContext, explorerForChain, parseAppWalletContracts, readContractEventsInBlockRanges, readFsiJson, resolveSafeContractWriteFeeOverrides };
582
+ //# sourceMappingURL=chunk-QS475ZC7.js.map
583
+ //# sourceMappingURL=chunk-QS475ZC7.js.map