@flapsdk/vault-runtime 0.1.33 → 0.1.34

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.
@@ -0,0 +1,945 @@
1
+ import { createVaultRuntimeContext, chainLabelForChain } from './chunk-AGLB72HK.js';
2
+ import { createLocalNftMetadataReader, createLocalMediaUploader, vaultV2NftAbi, nftTokenUriAbi } from './chunk-PU7VEZWA.js';
3
+ import { fetchOracleJson } from './chunk-JLI25XFB.js';
4
+ import { RuntimeContext, Alert } from './chunk-CXCG5MGE.js';
5
+ import { isValidAddress, ZERO_ADDRESS } from './chunk-B4WKI3EW.js';
6
+ import { useState, useRef, useCallback, useEffect, useMemo } from 'react';
7
+ import { useAccount, useChainId, useConnect, useDisconnect, useSwitchChain, usePublicClient, useWalletClient, useBalance } from 'wagmi';
8
+ import { toFunctionSelector, parseAbi, encodeFunctionData, formatUnits, decodeFunctionResult, decodeAbiParameters, decodeEventLog, getContractAddress, concatHex, encodeAbiParameters, keccak256 } from 'viem';
9
+
10
+ // src/sdk/contractWriteFees.ts
11
+ var MAX_CONTRACT_WRITE_GAS = 5000000n;
12
+ var MAX_GAS_PRICE_MULTIPLIER = 2n;
13
+ async function resolveSafeContractWriteFeeOverrides(request, getNetworkGasPrice) {
14
+ if (request.gas !== void 0) {
15
+ if (request.gas <= 0n) throw new Error("Contract write gas must be greater than zero.");
16
+ if (request.gas > MAX_CONTRACT_WRITE_GAS) {
17
+ throw new Error(`Contract write gas must not exceed ${MAX_CONTRACT_WRITE_GAS.toString()}.`);
18
+ }
19
+ }
20
+ if (request.gasPrice !== void 0) {
21
+ if (request.gasPrice <= 0n) throw new Error("Contract write gasPrice must be greater than zero.");
22
+ const networkGasPrice = await getNetworkGasPrice();
23
+ if (networkGasPrice <= 0n) throw new Error("The runtime returned an invalid network gas price.");
24
+ const maximumGasPrice = networkGasPrice * MAX_GAS_PRICE_MULTIPLIER;
25
+ if (request.gasPrice > maximumGasPrice) {
26
+ throw new Error(
27
+ `Contract write gasPrice ${request.gasPrice.toString()} exceeds the runtime safety limit ${maximumGasPrice.toString()}.`
28
+ );
29
+ }
30
+ }
31
+ return {
32
+ ...request.gas === void 0 ? {} : { gas: request.gas },
33
+ ...request.gasPrice === void 0 ? {} : { gasPrice: request.gasPrice }
34
+ };
35
+ }
36
+
37
+ // src/sdk/contractEvents.ts
38
+ var MAX_CONTRACT_EVENT_BLOCK_SPAN = 1000n;
39
+ var MAX_CONTRACT_EVENT_BLOCK_LOOKBACK = 20000n;
40
+ var CONTRACT_EVENT_QUERY_CONCURRENCY = 4;
41
+ function splitContractEventBlockRanges(fromBlock, toBlock, maxBlockSpan = MAX_CONTRACT_EVENT_BLOCK_SPAN, maxLookback = MAX_CONTRACT_EVENT_BLOCK_LOOKBACK) {
42
+ if (fromBlock < 0n || toBlock < 0n) {
43
+ throw new RangeError("Contract event block numbers must not be negative.");
44
+ }
45
+ if (maxBlockSpan <= 0n) {
46
+ throw new RangeError("Contract event block span must be greater than zero.");
47
+ }
48
+ if (maxLookback < 0n) {
49
+ throw new RangeError("Contract event block lookback must not be negative.");
50
+ }
51
+ if (toBlock < fromBlock) return [];
52
+ if (toBlock - fromBlock > maxLookback) {
53
+ throw new RangeError(`Contract event block range must not exceed ${maxLookback.toString()} blocks.`);
54
+ }
55
+ const ranges = [];
56
+ let cursor = fromBlock;
57
+ while (cursor <= toBlock) {
58
+ const candidateEnd = cursor + maxBlockSpan;
59
+ const chunkEnd = candidateEnd < toBlock ? candidateEnd : toBlock;
60
+ ranges.push({ fromBlock: cursor, toBlock: chunkEnd });
61
+ cursor = chunkEnd + 1n;
62
+ }
63
+ return ranges;
64
+ }
65
+ async function readContractEventsInBlockRanges(input) {
66
+ const concurrency = input.concurrency ?? CONTRACT_EVENT_QUERY_CONCURRENCY;
67
+ if (!Number.isInteger(concurrency) || concurrency < 1 || concurrency > CONTRACT_EVENT_QUERY_CONCURRENCY) {
68
+ throw new RangeError(`Contract event query concurrency must be between 1 and ${CONTRACT_EVENT_QUERY_CONCURRENCY}.`);
69
+ }
70
+ const ranges = splitContractEventBlockRanges(input.fromBlock, input.toBlock);
71
+ const events = [];
72
+ for (let index2 = 0; index2 < ranges.length; index2 += concurrency) {
73
+ const batch = ranges.slice(index2, index2 + concurrency);
74
+ const batchEvents = await Promise.all(batch.map((range) => input.readRange(range)));
75
+ for (const items of batchEvents) events.push(...items);
76
+ }
77
+ return events;
78
+ }
79
+ var forbiddenName = /^(?:execute(?:Call|Batch)?|multicall|delegatecall|approve|increaseAllowance|decreaseAllowance|setApprovalForAll|transferOwnership|acceptOwnership|upgradeTo.*|setConfig|setSwapPath|setSplit)$/i;
80
+ var forbiddenSignatures = ["execute(address,uint256,bytes,uint8)", "execute(address,uint256,bytes)", "executeCall(address,uint256,bytes)", "approve(address,uint256)", "setApprovalForAll(address,bool)", "transferOwnership(address)", "upgradeTo(address)", "upgradeToAndCall(address,bytes)"];
81
+ var forbiddenSelectors = new Set(forbiddenSignatures.map(toFunctionSelector));
82
+ var hash = /^0x[0-9a-fA-F]{64}$/;
83
+ var index = (x) => Number.isInteger(x) && x >= 0 && x < 32;
84
+ function requireRule(ok, reason) {
85
+ if (!ok) throw new Error(`resolved-contract/${reason}`);
86
+ }
87
+ function func(text) {
88
+ requireRule(typeof text === "string" && text.length <= 512, "invalid-signature");
89
+ const entries = parseAbi([text]);
90
+ requireRule(entries.length === 1 && entries[0].type === "function", "invalid-signature");
91
+ return entries[0];
92
+ }
93
+ var hasDynamicBytes = (p) => /^bytes(?:\[|$)/.test(p.type) || p.components?.some(hasDynamicBytes);
94
+ function parseResolvedContract(input) {
95
+ requireRule(input && typeof input === "object" && !Array.isArray(input), "invalid-declaration");
96
+ const allowed = /* @__PURE__ */ new Set(["id", "label", "resolver", "allow", "read", "payable", "maxValueWei", "codePattern", "codeHash", "implementationCodeHash", "checks"]);
97
+ requireRule(Object.keys(input).every((k) => allowed.has(k)), "unknown-field");
98
+ const definition = structuredClone(input);
99
+ requireRule(typeof definition.id === "string" && definition.id.length <= 64 && /^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(definition.id), "invalid-id");
100
+ requireRule(["vault", "token", "nft"].includes(definition.label), "invalid-label");
101
+ const resolver = func(definition.resolver);
102
+ requireRule(["view", "pure"].includes(resolver.stateMutability) && resolver.outputs.length === 1 && resolver.outputs[0].type === "address" && resolver.inputs.length > 0 && resolver.inputs.length <= 32, "invalid-resolver");
103
+ requireRule(Array.isArray(definition.allow) && definition.allow.length > 0 && definition.allow.length <= 16, "invalid-allow");
104
+ const writes = definition.allow.map(func);
105
+ const seen = /* @__PURE__ */ new Set();
106
+ for (const f of writes) {
107
+ const selector = toFunctionSelector(f);
108
+ requireRule(!["view", "pure"].includes(f.stateMutability) && !forbiddenName.test(f.name) && !forbiddenSelectors.has(selector) && !f.inputs.some(hasDynamicBytes), "forbidden-write");
109
+ requireRule(!seen.has(selector), "duplicate-selector");
110
+ seen.add(selector);
111
+ }
112
+ const reads = definition.read === void 0 || definition.read === "any" ? "any" : definition.read;
113
+ requireRule(reads === "any" || Array.isArray(reads) && reads.length <= 16, "invalid-read");
114
+ const readFunctions = reads === "any" ? reads : reads.map(func);
115
+ requireRule(readFunctions === "any" || readFunctions.every((f) => ["view", "pure"].includes(f.stateMutability)), "invalid-read");
116
+ requireRule(definition.payable === void 0 || typeof definition.payable === "boolean", "invalid-payable");
117
+ if (definition.payable) requireRule(typeof definition.maxValueWei === "string" && /^[1-9][0-9]{0,77}$/.test(definition.maxValueWei) && BigInt(definition.maxValueWei) < 2n ** 256n, "missing-value-cap");
118
+ else requireRule(definition.maxValueWei === void 0, "unexpected-value-cap");
119
+ requireRule(definition.codePattern === void 0 || ["none", "eip6551-proxy"].includes(definition.codePattern), "invalid-code-pattern");
120
+ requireRule(definition.codeHash === void 0 || hash.test(definition.codeHash), "invalid-code-hash");
121
+ requireRule(definition.implementationCodeHash === void 0 || definition.codePattern === "eip6551-proxy" && hash.test(definition.implementationCodeHash), "invalid-implementation-hash");
122
+ requireRule(definition.checks === void 0 || Array.isArray(definition.checks) && definition.checks.length <= 8, "invalid-checks");
123
+ for (const check of definition.checks ?? []) {
124
+ requireRule(check && typeof check === "object" && !Array.isArray(check), "invalid-check");
125
+ const keys = {
126
+ owner: ["kind", "target"],
127
+ ownerOf: ["kind", "target", "resolverArg"],
128
+ recipient: ["kind", "function", "arg"],
129
+ balance: ["kind", "function", "amountArg", "token", "owner"]
130
+ }[check.kind];
131
+ requireRule(Array.isArray(keys) && Object.keys(check).every((k) => keys.includes(k)) && keys.every((k) => k in check), "invalid-check");
132
+ if (check.kind === "owner" || check.kind === "ownerOf") {
133
+ requireRule(["vault", "resolved"].includes(check.target), "invalid-check-target");
134
+ if (check.kind === "ownerOf") requireRule(index(check.resolverArg) && resolver.inputs[check.resolverArg]?.type === "uint256", "invalid-check-argument");
135
+ } else {
136
+ const f = func(check.function);
137
+ const selected = writes.find((w) => toFunctionSelector(w) === toFunctionSelector(f));
138
+ requireRule(selected, "unknown-check-function");
139
+ if (check.kind === "recipient") requireRule(index(check.arg) && selected.inputs[check.arg]?.type === "address", "invalid-check-argument");
140
+ else requireRule(index(check.amountArg) && /^uint(?:[0-9]+)?$/.test(selected.inputs[check.amountArg]?.type ?? "") && ["token", "resolved"].includes(check.token) && ["user", "resolved"].includes(check.owner), "invalid-check-argument");
141
+ }
142
+ }
143
+ return { definition, resolver, writes, reads: readFunctions };
144
+ }
145
+
146
+ // src/sdk/resolvedContracts.ts
147
+ var zero = /^0x0+$/i;
148
+ var same = (a, b) => typeof a === "string" && typeof b === "string" && a.toLowerCase() === b.toLowerCase();
149
+ function requireRule2(ok, code) {
150
+ if (!ok) throw new Error(`resolved-contract/${code}`);
151
+ }
152
+ function validAddress(a) {
153
+ return typeof a === "string" && /^0x[0-9a-f]{40}$/i.test(a) && !zero.test(a);
154
+ }
155
+ function isEip6551Proxy(code) {
156
+ return /^0x363d3d373d3d3d363d73[0-9a-f]{40}5af43d82803e903d91602b57fd5bf3[0-9a-f]{256}$/i.test(code);
157
+ }
158
+ function freezeData(value) {
159
+ if (value && typeof value === "object") {
160
+ Object.values(value).forEach(freezeData);
161
+ Object.freeze(value);
162
+ }
163
+ return value;
164
+ }
165
+ var checksAbi = parseAbi(["function owner() view returns (address)", "function ownerOf(uint256) view returns (address)", "function balanceOf(address) view returns (uint256)"]);
166
+ function createResolvedContractRuntime(environment) {
167
+ const manifest = structuredClone(environment.manifest);
168
+ const context = structuredClone(environment.context);
169
+ const client = environment.client;
170
+ const records = /* @__PURE__ */ new WeakMap();
171
+ const bindings = manifest.match.bindings.filter((b) => b.chainId === context.chainId && (b.factoryAddress ? same(b.factoryAddress, context.factoryAddress) : b.vaultAddresses?.length ? b.vaultAddresses.some((v) => same(v, context.vaultAddress)) && (!b.tokenAddresses?.length || b.tokenAddresses.some((t) => same(t, context.tokenAddress))) : b.tokenAddresses?.some((t) => same(t, context.tokenAddress))));
172
+ requireRule2(bindings.length <= 1, "ambiguous-binding");
173
+ const binding = bindings[0];
174
+ const definitions = /* @__PURE__ */ new Map();
175
+ if (binding?.resolvedContracts !== void 0) {
176
+ requireRule2(validAddress(binding.factoryAddress) && binding.resolvedContracts.length > 0 && binding.resolvedContracts.length <= 8, "invalid-declarations");
177
+ for (const input of binding.resolvedContracts) {
178
+ const parsed = parseResolvedContract(input);
179
+ requireRule2(!definitions.has(parsed.definition.id), "duplicate-id");
180
+ definitions.set(parsed.definition.id, parsed);
181
+ }
182
+ }
183
+ const genericAddresses = /* @__PURE__ */ new Set();
184
+ const add = (a) => {
185
+ if (validAddress(a)) genericAddresses.add(a.toLowerCase());
186
+ };
187
+ [context.vaultAddress, context.tokenAddress, context.factoryAddress, context.paymentToken?.address, context.host?.taxInfo?.quoteToken, context.host?.taxInfo?.dividendToken].forEach(add);
188
+ if (binding) [binding.factoryAddress, ...binding.vaultAddresses ?? [], ...binding.tokenAddresses ?? [], ...(binding.externalContracts ?? []).map((c) => c.address)].forEach(add);
189
+ async function chain() {
190
+ requireRule2(await client.getChainId() === context.chainId, "chain-changed");
191
+ }
192
+ async function wallet(expected) {
193
+ const live = await environment.getWallet();
194
+ requireRule2(validAddress(live.address) && live.chainId === context.chainId && (!expected || same(live.address, expected)), "wallet-or-chain-changed");
195
+ return live.address;
196
+ }
197
+ async function validateCode(address2, parsed, blockNumber) {
198
+ const code = await client.getCode({ address: address2, blockNumber });
199
+ requireRule2(code && code !== "0x", "missing-code");
200
+ const d = parsed.definition;
201
+ if (d.codePattern === "eip6551-proxy") requireRule2(isEip6551Proxy(code), "code-pattern-mismatch");
202
+ if (d.codeHash) requireRule2(same(keccak256(code), d.codeHash), "code-hash-mismatch");
203
+ if (d.implementationCodeHash) {
204
+ const implementation = `0x${code.slice(22, 62)}`;
205
+ const implCode = await client.getCode({ address: implementation, blockNumber });
206
+ requireRule2(implCode && implCode !== "0x" && same(keccak256(implCode), d.implementationCodeHash), "implementation-hash-mismatch");
207
+ }
208
+ }
209
+ async function resolve(parsed, args, blockNumber) {
210
+ requireRule2(validAddress(context.vaultAddress), "missing-vault");
211
+ const address2 = await client.readContract({ address: context.vaultAddress, abi: [parsed.resolver], functionName: parsed.resolver.name, args, blockNumber });
212
+ requireRule2(validAddress(address2), "invalid-resolved-address");
213
+ await validateCode(address2, parsed, blockNumber);
214
+ return address2;
215
+ }
216
+ async function resolveContract(id, input) {
217
+ const parsed = definitions.get(id);
218
+ requireRule2(parsed, "undeclared-resolver");
219
+ const args = structuredClone([...input]);
220
+ encodeFunctionData({ abi: [parsed.resolver], functionName: parsed.resolver.name, args });
221
+ await chain();
222
+ const address2 = await resolve(parsed, args, await client.getBlockNumber());
223
+ const handle = freezeData({ id, address: address2, args: structuredClone(args), chainId: context.chainId });
224
+ records.set(handle, { parsed, args, address: address2 });
225
+ return handle;
226
+ }
227
+ function snapshot(input) {
228
+ const contract = input.contract;
229
+ const record = typeof contract === "object" && contract !== null ? records.get(contract) : void 0;
230
+ requireRule2(typeof contract !== "object" || record, "forged-or-expired-handle");
231
+ requireRule2(!record || input.address === void 0, "handle-with-address");
232
+ const { contract: _contract, ...data } = input;
233
+ const request = structuredClone(data);
234
+ if (record) request.address = record.address;
235
+ requireRule2(validAddress(request.address) && request.abi, "invalid-request");
236
+ return { record, request };
237
+ }
238
+ function allowedFunction(request, functions) {
239
+ const data = encodeFunctionData({ abi: request.abi, functionName: request.functionName, args: request.args });
240
+ const selected = functions.find((f) => toFunctionSelector(f) === data.slice(0, 10));
241
+ requireRule2(selected, "selector-not-allowed");
242
+ requireRule2(encodeFunctionData({ abi: [selected], functionName: selected.name, args: request.args }) === data, "abi-mismatch");
243
+ request.abi = [selected];
244
+ request.functionName = selected.name;
245
+ return selected;
246
+ }
247
+ async function validate(input, write, expectedSender) {
248
+ const { record, request } = input;
249
+ await chain();
250
+ const sender = write ? await wallet(expectedSender) : void 0;
251
+ const blockNumber = await client.getBlockNumber();
252
+ if (!record) {
253
+ if (write) {
254
+ if (!genericAddresses.has(request.address.toLowerCase())) {
255
+ requireRule2(environment.targetPolicy === "warn", "unapproved-raw-target");
256
+ environment.warn?.("resolved-contract/legacy-derived-target: migrate to resolveContract before production");
257
+ }
258
+ const code = await client.getCode({ address: request.address, blockNumber });
259
+ requireRule2(!code || !isEip6551Proxy(code), "account-requires-profile");
260
+ }
261
+ return { request, sender, blockNumber };
262
+ }
263
+ requireRule2(same(await resolve(record.parsed, record.args, blockNumber), record.address), "resolved-address-changed");
264
+ const d = record.parsed.definition;
265
+ if (!write) {
266
+ const reads = record.parsed.reads;
267
+ const f2 = reads === "any" ? allowedFunction(request, request.abi.filter((f3) => f3.type === "function")) : allowedFunction(request, reads);
268
+ requireRule2(f2 && ["view", "pure"].includes(f2.stateMutability), "read-not-view");
269
+ return { request, blockNumber };
270
+ }
271
+ const f = allowedFunction(request, record.parsed.writes);
272
+ const value = request.value ?? 0n;
273
+ requireRule2(typeof value === "bigint" && value >= 0n && (value === 0n || d.payable && f.stateMutability === "payable" && value <= BigInt(d.maxValueWei)), "value-not-allowed");
274
+ request.account = sender;
275
+ for (const check of d.checks ?? []) {
276
+ if (check.kind === "owner" || check.kind === "ownerOf") {
277
+ const owner = await client.readContract({ address: check.target === "vault" ? context.vaultAddress : record.address, abi: checksAbi, functionName: check.kind, args: check.kind === "ownerOf" ? [record.args[check.resolverArg]] : [], blockNumber });
278
+ requireRule2(same(owner, sender), "ownership-check-failed");
279
+ } else if (toFunctionSelector(check.function) === toFunctionSelector(f)) {
280
+ if (check.kind === "recipient") requireRule2(same(request.args?.[check.arg], sender), "recipient-check-failed");
281
+ else {
282
+ const amount = request.args?.[check.amountArg];
283
+ const balance = await client.readContract({ address: check.token === "token" ? context.tokenAddress : record.address, abi: checksAbi, functionName: "balanceOf", args: [check.owner === "user" ? sender : record.address], blockNumber });
284
+ requireRule2(typeof amount === "bigint" && amount >= 0n && amount <= balance, "balance-check-failed");
285
+ }
286
+ }
287
+ }
288
+ return { request, sender, blockNumber };
289
+ }
290
+ return { resolveContract, snapshot, validate, assertWallet: wallet };
291
+ }
292
+ var abi = parseAbi([
293
+ "function nft() view returns (address)",
294
+ "function vault() view returns (address)",
295
+ "function bag() view returns (address)",
296
+ "function registry() view returns (address)",
297
+ "function salt() view returns (bytes32)",
298
+ "function accountImpl() view returns (address)",
299
+ "function walletOf(uint256) view returns (address)",
300
+ "function tokenIdOfWallet(address) view returns (uint256)",
301
+ "function ownerOf(uint256) view returns (address)",
302
+ "function controllerOf(uint256) view returns (address)",
303
+ "function owner() view returns (address)",
304
+ "function token() view returns (uint256,address,uint256)",
305
+ "function implementation() view returns (address)",
306
+ "function nftBeacon() view returns (address)",
307
+ "function vaultBeacon() view returns (address)",
308
+ "function balanceOf(address) view returns (uint256)",
309
+ "function account(address,bytes32,uint256,address,uint256) view returns (address)",
310
+ "function transfer(address,uint256) returns (bool)",
311
+ "function execute(address,uint256,bytes,uint8) payable returns (bytes)",
312
+ "event SyncFailed(uint256 indexed tokenId,uint256 bagBefore,uint256 bagAfter)",
313
+ "event Transfer(address indexed from,address indexed to,uint256 value)"
314
+ ]);
315
+ var beaconSlot = "0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50";
316
+ var executeSelector = encodeFunctionData({ abi, functionName: "execute", args: ["0x0000000000000000000000000000000000000001", 0n, "0x", 0] }).slice(0, 10);
317
+ var zero2 = /^0x0+$/i;
318
+ function requireRule3(ok, code) {
319
+ if (!ok) throw new Error(`nft-account/${code}`);
320
+ }
321
+ function same2(a, b) {
322
+ return typeof a === "string" && typeof b === "string" && a.toLowerCase() === b.toLowerCase();
323
+ }
324
+ function address(value) {
325
+ requireRule3(typeof value === "string" && /^0x[0-9a-f]{40}$/i.test(value) && !zero2.test(value), "invalid-address");
326
+ }
327
+ function assertNoGenericNftAccountExecute(request) {
328
+ if (!request.abi) return;
329
+ const data = encodeFunctionData({ abi: request.abi, functionName: request.functionName, args: request.args });
330
+ requireRule3(data.slice(0, 10) !== executeSelector, "use-restricted-entry");
331
+ }
332
+ function snapshotGenericContractWrite(request) {
333
+ const snapshot = structuredClone(request);
334
+ assertNoGenericNftAccountExecute(snapshot);
335
+ return snapshot;
336
+ }
337
+ function nftAccountCode(implementation, salt, chainId, nft, tokenId) {
338
+ return concatHex([
339
+ "0x363d3d373d3d3d363d73",
340
+ implementation,
341
+ "0x5af43d82803e903d91602b57fd5bf3",
342
+ salt,
343
+ encodeAbiParameters([{ type: "uint256" }, { type: "address" }, { type: "uint256" }], [BigInt(chainId), nft, tokenId])
344
+ ]);
345
+ }
346
+ function deriveNftAccount(policy, tokenId) {
347
+ const code = nftAccountCode(policy.accountImplementation.address, policy.salt, policy.chainId, policy.nft.address, tokenId);
348
+ return getContractAddress({ opcode: "CREATE2", from: policy.registry.address, salt: policy.salt, bytecode: concatHex(["0x3d60ad80600a3d3981f3", code]) });
349
+ }
350
+ async function withdrawNftAccount(env, request) {
351
+ const input = { ...request };
352
+ requireRule3(Object.keys(input).every((key) => ["policyId", "tokenId", "amount"].includes(key)), "unexpected-input");
353
+ requireRule3(typeof input.tokenId === "bigint" && input.tokenId > 0n && input.tokenId < 2n ** 256n, "invalid-token-id");
354
+ requireRule3(typeof input.amount === "bigint" && input.amount > 0n && input.amount < 2n ** 256n, "invalid-amount");
355
+ const policies = env.policies.filter((p2) => p2.policyId === input.policyId && p2.artifactId === env.manifest.artifactId && p2.chainId === env.context.chainId);
356
+ requireRule3(policies.length === 1, "policy-not-approved");
357
+ const p = structuredClone(policies[0]);
358
+ requireRule3(p.profile === "null-bag-withdraw-v1", "unsupported-profile");
359
+ requireRule3(same2(env.context.vaultAddress, p.vault.address) && same2(env.context.tokenAddress, p.token.address) && same2(env.context.factoryAddress, p.factory.address), "host-binding-mismatch");
360
+ requireRule3(/^0x[0-9a-f]{64}$/i.test(p.salt), "invalid-salt");
361
+ const bindings = env.manifest.match.bindings.filter((b) => b.chainId === p.chainId && same2(b.factoryAddress, p.factory.address));
362
+ requireRule3(bindings.length === 1 && bindings[0].nftAccountWithdrawals?.some((d) => d.policyId === p.policyId && d.profile === p.profile), "policy-not-declared");
363
+ const recipient = (await env.getWallet()).address;
364
+ address(recipient);
365
+ const accountAddress = deriveNftAccount(p, input.tokenId);
366
+ async function validate() {
367
+ const wallet = await env.getWallet();
368
+ requireRule3(same2(wallet.address, recipient) && wallet.chainId === p.chainId && await env.client.getChainId() === p.chainId, "wallet-or-chain-changed");
369
+ const blockNumber = await env.client.getBlockNumber();
370
+ async function read(at, functionName, args2) {
371
+ return await env.client.readContract({ address: at, abi, functionName, args: args2, blockNumber });
372
+ }
373
+ async function pin(contract) {
374
+ address(contract.address);
375
+ requireRule3(/^0x[0-9a-f]{64}$/i.test(contract.codeHash), "invalid-code-hash");
376
+ const code2 = await env.client.getCode({ address: contract.address, blockNumber });
377
+ requireRule3(code2 && code2 !== "0x" && same2(keccak256(code2), contract.codeHash), "code-changed");
378
+ }
379
+ async function beacon(contract) {
380
+ await pin(contract);
381
+ await pin(contract.beacon);
382
+ await pin(contract.implementation);
383
+ const slot = await env.client.getStorageAt({ address: contract.address, slot: beaconSlot, blockNumber });
384
+ requireRule3(slot && same2(`0x${slot.slice(-40)}`, contract.beacon.address), "beacon-changed");
385
+ requireRule3(same2(await read(contract.beacon.address, "implementation"), contract.implementation.address), "implementation-changed");
386
+ }
387
+ await Promise.all([pin(p.factory), pin(p.token), pin(p.registry), pin(p.accountImplementation), beacon(p.vault), beacon(p.nft)]);
388
+ const checks = await Promise.all([
389
+ read(p.factory.address, "nftBeacon"),
390
+ read(p.factory.address, "vaultBeacon"),
391
+ read(p.vault.address, "nft"),
392
+ read(p.nft.address, "vault"),
393
+ read(p.nft.address, "bag"),
394
+ read(p.nft.address, "registry"),
395
+ read(p.nft.address, "salt"),
396
+ read(p.nft.address, "accountImpl"),
397
+ read(p.accountImplementation.address, "nft"),
398
+ read(p.accountImplementation.address, "vault"),
399
+ read(p.nft.address, "walletOf", [input.tokenId]),
400
+ read(p.registry.address, "account", [p.accountImplementation.address, p.salt, BigInt(p.chainId), p.nft.address, input.tokenId]),
401
+ read(p.nft.address, "ownerOf", [input.tokenId]),
402
+ read(p.nft.address, "controllerOf", [input.tokenId]),
403
+ read(accountAddress, "owner"),
404
+ read(accountAddress, "nft"),
405
+ read(accountAddress, "vault")
406
+ ]);
407
+ const expected = [p.nft.beacon.address, p.vault.beacon.address, p.nft.address, p.vault.address, p.token.address, p.registry.address, p.salt, p.accountImplementation.address, p.nft.address, p.vault.address, accountAddress, accountAddress, recipient, recipient, recipient, p.nft.address, p.vault.address];
408
+ requireRule3(checks.every((value, i) => same2(value, expected[i])), "relationship-mismatch");
409
+ requireRule3(await read(p.nft.address, "tokenIdOfWallet", [accountAddress]) === input.tokenId, "wallet-id-mismatch");
410
+ const token = await read(accountAddress, "token");
411
+ requireRule3(token[0] === BigInt(p.chainId) && same2(token[1], p.nft.address) && token[2] === input.tokenId, "footer-mismatch");
412
+ const code = await env.client.getCode({ address: accountAddress, blockNumber });
413
+ requireRule3(same2(code, nftAccountCode(p.accountImplementation.address, p.salt, p.chainId, p.nft.address, input.tokenId)), "account-code-mismatch");
414
+ const balance = await read(p.token.address, "balanceOf", [accountAddress]);
415
+ requireRule3(typeof balance === "bigint" && input.amount <= balance, "insufficient-balance");
416
+ }
417
+ await validate();
418
+ const data = encodeFunctionData({ abi, functionName: "transfer", args: [recipient, input.amount] });
419
+ const args = [p.token.address, 0n, data, 0];
420
+ const base = { account: recipient, address: accountAddress, abi, functionName: "execute", args, value: 0n };
421
+ const estimated = await env.client.estimateContractGas(base);
422
+ const padded = estimated * 120n / 100n + 50000n;
423
+ const gas = padded < 600000n ? 600000n : padded;
424
+ requireRule3(gas >= 600000n && gas <= 5000000n, "gas-out-of-range");
425
+ const simulation = await env.client.simulateContract({ ...base, gas });
426
+ const returned = simulation.result;
427
+ requireRule3(returned === "0x" || typeof returned === "string" && returned.length === 66 && decodeAbiParameters([{ type: "bool" }], returned)[0], "token-transfer-rejected");
428
+ await validate();
429
+ const hash2 = await env.send({ address: accountAddress, abi, functionName: "execute", args: [...args], value: 0n, gas }, recipient);
430
+ let receipt;
431
+ try {
432
+ receipt = await env.client.waitForTransactionReceipt({ hash: hash2 });
433
+ } catch {
434
+ try {
435
+ await env.refetch();
436
+ } catch {
437
+ }
438
+ return { hash: hash2, status: "effect-unconfirmed", accountAddress, recipient, amount: input.amount };
439
+ }
440
+ let balanceAfter;
441
+ try {
442
+ balanceAfter = await env.client.readContract({ address: p.token.address, abi, functionName: "balanceOf", args: [accountAddress], blockNumber: receipt.blockNumber });
443
+ } catch {
444
+ }
445
+ let transferred = 0n;
446
+ let syncFailed = false;
447
+ for (const log of receipt.logs) {
448
+ try {
449
+ const event = decodeEventLog({ abi, data: log.data, topics: log.topics });
450
+ if (same2(log.address, accountAddress) && event.eventName === "SyncFailed" && event.args.tokenId === input.tokenId) syncFailed = true;
451
+ if (same2(log.address, p.token.address) && event.eventName === "Transfer" && same2(event.args.from, accountAddress) && same2(event.args.to, recipient)) transferred += event.args.value;
452
+ } catch {
453
+ }
454
+ }
455
+ const status = receipt.status !== "success" ? "reverted" : transferred > 0n && transferred <= input.amount ? syncFailed ? "withdrawn-sync-required" : "withdrawn" : "effect-unconfirmed";
456
+ try {
457
+ await env.refetch();
458
+ } catch {
459
+ }
460
+ return { hash: hash2, status, accountAddress, recipient, amount: input.amount, balanceAfter };
461
+ }
462
+
463
+ // src/sdk/runtime.tsx
464
+ var EMPTY_NFT_ACCOUNT_POLICIES = Object.freeze([]);
465
+ var defaultNftMetadataReader = createLocalNftMetadataReader();
466
+ var defaultMediaUploader = createLocalMediaUploader();
467
+ var NFT_METADATA_MAX_CONCURRENCY = 6;
468
+ var activeNftMetadataReads = 0;
469
+ var pendingNftMetadataReads = [];
470
+ async function limitNftMetadataRead(task) {
471
+ if (activeNftMetadataReads >= NFT_METADATA_MAX_CONCURRENCY) {
472
+ await new Promise((resolve) => pendingNftMetadataReads.push(resolve));
473
+ }
474
+ activeNftMetadataReads += 1;
475
+ try {
476
+ return await task();
477
+ } finally {
478
+ activeNftMetadataReads -= 1;
479
+ pendingNftMetadataReads.shift()?.();
480
+ }
481
+ }
482
+ function applyParams(value, params) {
483
+ if (!params) return value;
484
+ return Object.entries(params).reduce((acc, [key, item]) => acc.replaceAll(`{${key}}`, String(item)), value);
485
+ }
486
+ function getPreviewOracleEndpoint(extraConfig, oracleId) {
487
+ const oracleEndpoints = extraConfig?.oracleEndpoints;
488
+ if (!oracleEndpoints || typeof oracleEndpoints !== "object" || Array.isArray(oracleEndpoints)) return void 0;
489
+ const endpoint = oracleEndpoints[oracleId];
490
+ return typeof endpoint === "string" ? endpoint : void 0;
491
+ }
492
+ function VaultRuntimeProvider({ children, manifest, i18n, runtimeContext: runtimeOverrides, hostRuntimeResult, locale = "en", oracleReader, nftMetadataReader, mediaUploader, nftAccountWithdrawalPolicies = EMPTY_NFT_ACCOUNT_POLICIES, contractTargetPolicy = "strict" }) {
493
+ const [version, setVersion] = useState(0);
494
+ const [messages, setMessages] = useState([]);
495
+ const toastTimersRef = useRef(/* @__PURE__ */ new Map());
496
+ const nftMetadataCacheRef = useRef(/* @__PURE__ */ new Map());
497
+ const vaultNftAddressCacheRef = useRef(/* @__PURE__ */ new Map());
498
+ const { address: accountAddress, isConnected } = useAccount();
499
+ const connectedChainId = useChainId();
500
+ const { connect, connectors } = useConnect();
501
+ const { disconnect } = useDisconnect();
502
+ const { switchChainAsync, isPending: isSwitchingChain } = useSwitchChain();
503
+ const effectiveChainId = runtimeOverrides?.chainId ?? hostRuntimeResult?.addresses.chainId ?? connectedChainId ?? manifest.match.bindings[0]?.chainId ?? 56;
504
+ const publicClient = usePublicClient({ chainId: effectiveChainId });
505
+ const { data: walletClient } = useWalletClient();
506
+ const { data: nativeBalance } = useBalance({ address: accountAddress, chainId: isConnected ? connectedChainId : void 0 });
507
+ const dismissMessage = useCallback((id) => {
508
+ const timerId = toastTimersRef.current.get(id);
509
+ if (timerId) {
510
+ window.clearTimeout(timerId);
511
+ toastTimersRef.current.delete(id);
512
+ }
513
+ setMessages((items) => items.filter((item) => item.id !== id));
514
+ }, []);
515
+ useEffect(() => {
516
+ const timers = toastTimersRef.current;
517
+ return () => {
518
+ for (const timerId of timers.values()) {
519
+ window.clearTimeout(timerId);
520
+ }
521
+ timers.clear();
522
+ };
523
+ }, []);
524
+ const runtimeContext = useMemo(() => {
525
+ return createVaultRuntimeContext({
526
+ manifest,
527
+ connectedChainId,
528
+ hostRuntimeResult,
529
+ runtimeOverrides: {
530
+ ...runtimeOverrides,
531
+ userAddress: runtimeOverrides?.userAddress ?? accountAddress
532
+ }
533
+ });
534
+ }, [accountAddress, connectedChainId, hostRuntimeResult, manifest, runtimeOverrides]);
535
+ const i18nApi = useMemo(
536
+ () => ({
537
+ locale,
538
+ t(key, fallback, params) {
539
+ const defaultLocale = manifest.i18n[0];
540
+ const resolved = i18n[locale]?.[key] ?? i18n[defaultLocale]?.[key] ?? i18n.en?.[key] ?? fallback ?? key;
541
+ return applyParams(resolved, params);
542
+ }
543
+ }),
544
+ [i18n, locale, manifest.i18n]
545
+ );
546
+ const push = useCallback(
547
+ (level, message) => {
548
+ const id = Date.now() + Math.floor(Math.random() * 1e3);
549
+ setMessages((items) => [{ id, level, message }, ...items].slice(0, 4));
550
+ const timerId = window.setTimeout(() => {
551
+ dismissMessage(id);
552
+ }, 4200);
553
+ toastTimersRef.current.set(id, timerId);
554
+ },
555
+ [dismissMessage]
556
+ );
557
+ const notify = useMemo(
558
+ () => ({
559
+ info: (message) => push("info", message),
560
+ success: (message) => push("success", message),
561
+ warning: (message) => push("warning", message),
562
+ error: (message) => push("error", message)
563
+ }),
564
+ [push]
565
+ );
566
+ const wallet = useMemo(
567
+ () => {
568
+ const previewWallet = runtimeOverrides?.previewWallet;
569
+ const walletAddress = previewWallet?.address ?? accountAddress;
570
+ const walletConnected = previewWallet?.isConnected ?? isConnected;
571
+ const walletChainId = previewWallet?.chainId ?? connectedChainId;
572
+ return {
573
+ address: walletAddress,
574
+ chainId: walletConnected ? walletChainId : void 0,
575
+ chainLabel: walletConnected && walletChainId ? chainLabelForChain(walletChainId) : void 0,
576
+ requiredChainId: runtimeContext.chainId,
577
+ requiredChainLabel: chainLabelForChain(runtimeContext.chainId),
578
+ isConnected: walletConnected,
579
+ isWrongNetwork: Boolean(walletConnected && walletChainId && walletChainId !== runtimeContext.chainId),
580
+ canSwitchChain: previewWallet?.canSwitchChain ?? Boolean(switchChainAsync),
581
+ isSwitchingChain,
582
+ // Real native-token balance from the connected wallet. "0" until a wallet is connected.
583
+ balance: previewWallet ? "0" : nativeBalance ? formatUnits(nativeBalance.value, nativeBalance.decimals) : "0",
584
+ // Wallet connection is host/shell-owned. In this preview the SDK forwards to the
585
+ // injected wagmi connector so the surface is functional rather than a no-op stub.
586
+ connect: () => {
587
+ const connector = connectors[0];
588
+ if (connector) connect({ connector });
589
+ },
590
+ disconnect: () => disconnect(),
591
+ switchChain: async () => {
592
+ if (previewWallet) {
593
+ throw new Error(`Switch wallet to ${chainLabelForChain(runtimeContext.chainId)} before continuing.`);
594
+ }
595
+ if (!switchChainAsync) {
596
+ throw new Error(`Switch wallet to ${chainLabelForChain(runtimeContext.chainId)} before continuing.`);
597
+ }
598
+ await switchChainAsync({ chainId: runtimeContext.chainId });
599
+ }
600
+ };
601
+ },
602
+ [accountAddress, connect, connectedChainId, connectors, disconnect, isConnected, isSwitchingChain, nativeBalance, runtimeContext.chainId, runtimeOverrides?.previewWallet, switchChainAsync]
603
+ );
604
+ const assertWalletWriteReady = useCallback(
605
+ (actionLabel) => {
606
+ if (!accountAddress) throw new Error("Wallet is not connected.");
607
+ if (isConnected && connectedChainId !== runtimeContext.chainId) {
608
+ throw new Error(`Wrong network. Switch wallet to ${chainLabelForChain(runtimeContext.chainId)} before ${actionLabel}.`);
609
+ }
610
+ },
611
+ [accountAddress, connectedChainId, isConnected, runtimeContext.chainId]
612
+ );
613
+ const contractRuntime = useMemo(() => publicClient ? createResolvedContractRuntime({
614
+ client: publicClient,
615
+ manifest,
616
+ context: runtimeContext,
617
+ targetPolicy: contractTargetPolicy,
618
+ getWallet: async () => {
619
+ if (!walletClient) throw new Error("resolved-contract/wallet-unavailable");
620
+ const [address2] = await walletClient.getAddresses();
621
+ if (!address2) throw new Error("resolved-contract/wallet-unavailable");
622
+ return { address: address2, chainId: await walletClient.getChainId() };
623
+ },
624
+ warn: (message) => console.warn(message)
625
+ }) : void 0, [publicClient, walletClient, manifest, runtimeContext, contractTargetPolicy]);
626
+ const currentContractRuntime = useRef(contractRuntime);
627
+ currentContractRuntime.current = contractRuntime;
628
+ const resolveContract = useCallback((id, args) => {
629
+ if (!contractRuntime) throw new Error("resolved-contract/client-unavailable");
630
+ return contractRuntime.resolveContract(id, args);
631
+ }, [contractRuntime]);
632
+ const readContract = useCallback(
633
+ async (request) => {
634
+ if (!publicClient || !contractRuntime) throw new Error("resolved-contract/client-unavailable");
635
+ const checked = await contractRuntime.validate(contractRuntime.snapshot(request), false);
636
+ request = checked.request;
637
+ if (!request.abi || !request.address) {
638
+ throw new Error(`Contract read ${request.functionName} requires a public client, ABI, and address.`);
639
+ }
640
+ if (request.gasPrice !== void 0) {
641
+ if (request.gasPrice <= 0n) throw new Error("Contract read gasPrice must be greater than zero.");
642
+ const data = encodeFunctionData({
643
+ abi: request.abi,
644
+ functionName: request.functionName,
645
+ args: request.args
646
+ });
647
+ const response = await publicClient.call({
648
+ account: request.account,
649
+ to: request.address,
650
+ data,
651
+ gasPrice: request.gasPrice,
652
+ blockNumber: checked.blockNumber
653
+ });
654
+ if (!response.data) throw new Error(`Contract read ${request.functionName} returned no data.`);
655
+ return decodeFunctionResult({
656
+ abi: request.abi,
657
+ functionName: request.functionName,
658
+ args: request.args,
659
+ data: response.data
660
+ });
661
+ }
662
+ return await publicClient.readContract({
663
+ address: request.address,
664
+ abi: request.abi,
665
+ functionName: request.functionName,
666
+ args: request.args,
667
+ account: request.account,
668
+ blockNumber: checked.blockNumber
669
+ });
670
+ },
671
+ [publicClient, contractRuntime]
672
+ );
673
+ const getGasPrice = useCallback(async () => {
674
+ if (!publicClient) throw new Error("Gas-price lookup requires a public client.");
675
+ const gasPrice = await publicClient.getGasPrice();
676
+ if (gasPrice <= 0n) throw new Error("The runtime returned an invalid network gas price.");
677
+ return gasPrice;
678
+ }, [publicClient]);
679
+ const getBlockNumber = useCallback(async () => {
680
+ if (!publicClient) throw new Error("Block-number lookup requires a public client.");
681
+ const blockNumber = await publicClient.getBlockNumber();
682
+ if (blockNumber < 0n) throw new Error("The runtime returned an invalid block number.");
683
+ return blockNumber;
684
+ }, [publicClient]);
685
+ const getContractEvents = useCallback(
686
+ async (request) => {
687
+ if (!publicClient || !request.abi || !request.address || !request.eventName.trim()) {
688
+ throw new Error("Contract event lookup requires a public client, ABI, address, and event name.");
689
+ }
690
+ const toBlock = typeof request.toBlock === "bigint" ? request.toBlock : await getBlockNumber();
691
+ return readContractEventsInBlockRanges({
692
+ fromBlock: request.fromBlock,
693
+ toBlock,
694
+ readRange: async ({ fromBlock, toBlock: chunkToBlock }) => {
695
+ const events = await publicClient.getContractEvents({
696
+ address: request.address,
697
+ abi: request.abi,
698
+ eventName: request.eventName,
699
+ args: request.args,
700
+ fromBlock,
701
+ toBlock: chunkToBlock,
702
+ strict: request.strict
703
+ });
704
+ return events;
705
+ }
706
+ });
707
+ },
708
+ [getBlockNumber, publicClient]
709
+ );
710
+ const simulateContract = useCallback(
711
+ async (input) => {
712
+ assertWalletWriteReady(`simulating ${input.functionName}`);
713
+ if (!publicClient || !contractRuntime) throw new Error("resolved-contract/client-unavailable");
714
+ const contract = input.contract;
715
+ const prepared = contractRuntime.snapshot(input);
716
+ prepared.request = snapshotGenericContractWrite(prepared.request);
717
+ const feeOverrides = await resolveSafeContractWriteFeeOverrides(prepared.request, getGasPrice);
718
+ const checked = await contractRuntime.validate(prepared, true);
719
+ const request = checked.request;
720
+ const simulation = await publicClient.simulateContract({
721
+ account: checked.sender,
722
+ address: request.address,
723
+ abi: request.abi,
724
+ functionName: request.functionName,
725
+ args: request.args,
726
+ value: request.value,
727
+ blockNumber: checked.blockNumber,
728
+ ...feeOverrides
729
+ });
730
+ const resultRequest = prepared.record ? { ...request, address: void 0, contract } : request;
731
+ return { request: resultRequest, result: simulation.result };
732
+ },
733
+ [assertWalletWriteReady, getGasPrice, publicClient, contractRuntime]
734
+ );
735
+ const writeContract = useCallback(
736
+ async (input) => {
737
+ assertWalletWriteReady(`writing ${input.functionName}`);
738
+ if (!walletClient || !publicClient || !contractRuntime) throw new Error("resolved-contract/client-unavailable");
739
+ const prepared = contractRuntime.snapshot(input);
740
+ prepared.request = snapshotGenericContractWrite(prepared.request);
741
+ const feeOverrides = await resolveSafeContractWriteFeeOverrides(prepared.request, getGasPrice);
742
+ let checked = await contractRuntime.validate(prepared, true);
743
+ if (prepared.record) {
744
+ await publicClient.simulateContract({
745
+ account: checked.sender,
746
+ address: checked.request.address,
747
+ abi: checked.request.abi,
748
+ functionName: checked.request.functionName,
749
+ args: checked.request.args,
750
+ value: checked.request.value,
751
+ blockNumber: checked.blockNumber,
752
+ ...feeOverrides
753
+ });
754
+ checked = await contractRuntime.validate(prepared, true, checked.sender);
755
+ }
756
+ await contractRuntime.assertWallet(checked.sender);
757
+ if (currentContractRuntime.current !== contractRuntime) throw new Error("resolved-contract/context-changed");
758
+ const request = checked.request;
759
+ const hash2 = await walletClient.writeContract({
760
+ account: checked.sender,
761
+ address: request.address,
762
+ abi: request.abi,
763
+ functionName: request.functionName,
764
+ args: request.args,
765
+ value: request.value,
766
+ ...feeOverrides
767
+ });
768
+ return hash2;
769
+ },
770
+ [assertWalletWriteReady, getGasPrice, walletClient, publicClient, contractRuntime]
771
+ );
772
+ const waitForTx = useCallback(
773
+ async (hash2) => {
774
+ if (!publicClient) throw new Error("Transaction receipt requires a public client.");
775
+ const receipt = await publicClient.waitForTransactionReceipt({ hash: hash2 });
776
+ return { hash: hash2, status: receipt.status === "success" ? "success" : "reverted" };
777
+ },
778
+ [publicClient]
779
+ );
780
+ const readOracle = useCallback(
781
+ async (oracleId, params) => {
782
+ if (oracleReader) {
783
+ return oracleReader({
784
+ oracleId,
785
+ params,
786
+ context: runtimeContext
787
+ });
788
+ }
789
+ const endpoint = getPreviewOracleEndpoint(runtimeContext.extraConfig, oracleId);
790
+ if (!endpoint) throw new Error(`Oracle ${oracleId} is not provisioned by the runtime.`);
791
+ return fetchOracleJson({
792
+ endpoint,
793
+ params
794
+ });
795
+ },
796
+ [oracleReader, runtimeContext]
797
+ );
798
+ const readNftMetadata = useCallback(
799
+ async (request) => {
800
+ if (request.tokenId < 0n) throw new Error("NFT tokenId must not be negative.");
801
+ const vaultAddress = runtimeContext.vaultAddress;
802
+ if (!isValidAddress(vaultAddress) || vaultAddress.toLowerCase() === ZERO_ADDRESS) {
803
+ throw new Error("Vault V2 NFT metadata requires a valid runtime Vault address.");
804
+ }
805
+ const cacheKey = `${runtimeContext.chainId}:${vaultAddress.toLowerCase()}:${request.tokenId.toString()}:${version}`;
806
+ const cached = nftMetadataCacheRef.current.get(cacheKey);
807
+ if (cached) return cached;
808
+ const pending = limitNftMetadataRead(async () => {
809
+ const nftAddressCacheKey = `${runtimeContext.chainId}:${vaultAddress.toLowerCase()}:${version}`;
810
+ let nftAddressPending = vaultNftAddressCacheRef.current.get(nftAddressCacheKey);
811
+ if (!nftAddressPending) {
812
+ nftAddressPending = readContract({
813
+ contract: "vault",
814
+ address: vaultAddress,
815
+ abi: vaultV2NftAbi,
816
+ functionName: "nft"
817
+ }).then((nftAddress2) => {
818
+ if (!isValidAddress(nftAddress2) || nftAddress2.toLowerCase() === ZERO_ADDRESS) {
819
+ throw new Error("Vault V2 nft() returned an invalid NFT address.");
820
+ }
821
+ return nftAddress2;
822
+ });
823
+ vaultNftAddressCacheRef.current.set(nftAddressCacheKey, nftAddressPending);
824
+ if (vaultNftAddressCacheRef.current.size > 32) {
825
+ const oldestNftAddressKey = vaultNftAddressCacheRef.current.keys().next().value;
826
+ if (oldestNftAddressKey) vaultNftAddressCacheRef.current.delete(oldestNftAddressKey);
827
+ }
828
+ nftAddressPending.catch(() => vaultNftAddressCacheRef.current.delete(nftAddressCacheKey));
829
+ }
830
+ const nftAddress = await nftAddressPending;
831
+ const tokenUri = await readContract({
832
+ contract: "nft",
833
+ address: nftAddress,
834
+ abi: nftTokenUriAbi,
835
+ functionName: "tokenURI",
836
+ args: [request.tokenId]
837
+ });
838
+ if (typeof tokenUri !== "string" || !tokenUri.trim()) throw new Error("NFT tokenURI returned an empty value.");
839
+ return (nftMetadataReader ?? defaultNftMetadataReader)({
840
+ ...request,
841
+ chainId: runtimeContext.chainId,
842
+ nftAddress,
843
+ tokenUri: tokenUri.trim(),
844
+ context: runtimeContext
845
+ });
846
+ });
847
+ nftMetadataCacheRef.current.set(cacheKey, pending);
848
+ if (nftMetadataCacheRef.current.size > 128) {
849
+ const oldestKey = nftMetadataCacheRef.current.keys().next().value;
850
+ if (oldestKey) nftMetadataCacheRef.current.delete(oldestKey);
851
+ }
852
+ pending.catch(() => nftMetadataCacheRef.current.delete(cacheKey));
853
+ return pending;
854
+ },
855
+ [nftMetadataReader, readContract, runtimeContext, version]
856
+ );
857
+ const uploadImage = useCallback(
858
+ (file, options) => (mediaUploader ?? defaultMediaUploader)({ kind: "image", file, chainId: effectiveChainId, signal: options?.signal }),
859
+ [effectiveChainId, mediaUploader]
860
+ );
861
+ const uploadText = useCallback(
862
+ (text, options) => (mediaUploader ?? defaultMediaUploader)({ kind: "text", file: new Blob([text], { type: "text/plain;charset=utf-8" }), chainId: effectiveChainId, signal: options?.signal }),
863
+ [effectiveChainId, mediaUploader]
864
+ );
865
+ const refetch = useCallback(async () => {
866
+ setVersion((item) => item + 1);
867
+ }, []);
868
+ const openExplorerTx = useCallback(
869
+ (hash2) => {
870
+ if (!runtimeContext.explorerBaseUrl) return;
871
+ window.open(`${runtimeContext.explorerBaseUrl.replace(/\/$/, "")}/tx/${hash2}`, "_blank", "noreferrer");
872
+ },
873
+ [runtimeContext.explorerBaseUrl]
874
+ );
875
+ const nftAccountWithdrawalPendingRef = useRef(false);
876
+ const nftWithdrawalEnvironment = useMemo(() => ({
877
+ manifest: structuredClone(manifest),
878
+ context: { ...runtimeContext },
879
+ policies: structuredClone(nftAccountWithdrawalPolicies)
880
+ }), [manifest, nftAccountWithdrawalPolicies, runtimeContext]);
881
+ const withdrawNftAccount2 = useCallback(async (request) => {
882
+ assertWalletWriteReady("withdrawing from an NFT account");
883
+ if (!publicClient || !walletClient) throw new Error("nft-account/wallet-unavailable");
884
+ if (nftAccountWithdrawalPendingRef.current) throw new Error("nft-account/withdrawal-pending");
885
+ nftAccountWithdrawalPendingRef.current = true;
886
+ try {
887
+ return await withdrawNftAccount({
888
+ client: publicClient,
889
+ ...nftWithdrawalEnvironment,
890
+ getWallet: async () => {
891
+ const [address2] = await walletClient.getAddresses();
892
+ const chainId = await walletClient.getChainId();
893
+ if (!address2) throw new Error("nft-account/wallet-unavailable");
894
+ return { address: address2, chainId };
895
+ },
896
+ send: async (tx, expectedSender) => {
897
+ const [address2] = await walletClient.getAddresses();
898
+ if (address2?.toLowerCase() !== expectedSender.toLowerCase() || await walletClient.getChainId() !== runtimeContext.chainId) throw new Error("nft-account/wallet-or-chain-changed");
899
+ return walletClient.writeContract({ account: address2, address: tx.address, abi: tx.abi, functionName: tx.functionName, args: tx.args, value: tx.value, gas: tx.gas });
900
+ },
901
+ refetch
902
+ }, request);
903
+ } finally {
904
+ nftAccountWithdrawalPendingRef.current = false;
905
+ }
906
+ }, [assertWalletWriteReady, nftWithdrawalEnvironment, publicClient, refetch, runtimeContext, walletClient]);
907
+ const componentContext = useMemo(() => structuredClone(runtimeContext), [runtimeContext]);
908
+ const sdk = useMemo(
909
+ () => ({
910
+ context: componentContext,
911
+ i18n: i18nApi,
912
+ notify,
913
+ wallet,
914
+ getGasPrice,
915
+ getBlockNumber,
916
+ getContractEvents,
917
+ resolveContract,
918
+ readContract,
919
+ simulateContract,
920
+ writeContract,
921
+ waitForTx,
922
+ withdrawNftAccount: withdrawNftAccount2,
923
+ readOracle,
924
+ readNftMetadata,
925
+ uploadImage,
926
+ uploadText,
927
+ refetch,
928
+ refetchNonce: version,
929
+ openExplorerTx
930
+ }),
931
+ [getBlockNumber, getContractEvents, getGasPrice, i18nApi, notify, openExplorerTx, resolveContract, readContract, readNftMetadata, readOracle, refetch, componentContext, simulateContract, uploadImage, uploadText, version, waitForTx, wallet, withdrawNftAccount2, writeContract]
932
+ );
933
+ return /* @__PURE__ */ React.createElement(RuntimeContext.Provider, { value: sdk }, children, /* @__PURE__ */ React.createElement("div", { className: "pointer-events-none fixed bottom-4 right-4 z-50 flex w-[min(360px,calc(100vw-2rem))] flex-col gap-2" }, messages.map((message) => /* @__PURE__ */ React.createElement("div", { key: message.id, className: "pointer-events-auto" }, /* @__PURE__ */ React.createElement(
934
+ Alert,
935
+ {
936
+ tone: message.level === "error" ? "danger" : message.level,
937
+ className: "cursor-pointer shadow-panel backdrop-blur-sm transition hover:translate-y-[-1px]"
938
+ },
939
+ /* @__PURE__ */ React.createElement("button", { type: "button", className: "w-full text-left", onClick: () => dismissMessage(message.id) }, message.message)
940
+ )))));
941
+ }
942
+
943
+ export { VaultRuntimeProvider };
944
+ //# sourceMappingURL=chunk-JVZ4TFPY.js.map
945
+ //# sourceMappingURL=chunk-JVZ4TFPY.js.map