@flapsdk/vault-runtime 0.1.43 → 0.1.44-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.
@@ -1,11 +1,14 @@
1
1
  import { resolveManifestBinding } from './chunk-B4WKI3EW.js';
2
2
  import { resolveIpfsImageUrls } from './chunk-GY7YY67I.js';
3
- import { toFunctionSelector, parseAbi, isHex, decodeFunctionData, encodeFunctionData, isAddress, keccak256, prepareEncodeFunctionData } from 'viem';
3
+ import { toFunctionSelector, parseAbi, isHex, decodeFunctionData, encodeFunctionData, isAddress, keccak256 } from 'viem';
4
4
 
5
5
  var bad = (ok, reason) => {
6
6
  if (!ok) throw new Error(`app-wallet/${reason}`);
7
7
  };
8
8
  var address = (a) => typeof a === "string" && isAddress(a, { strict: false }) && !/^0x0{40}$/i.test(a);
9
+ var identifier = (id) => typeof id === "string" && id.length <= 64 && /^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(id);
10
+ var ERC20_APPROVE_SELECTOR = "0x095ea7b3";
11
+ var PRESALE_CONTRIBUTE_QUOTE_SELECTOR = toFunctionSelector("contributeQuote(uint256)");
9
12
  var admin = /^(?:execute(?:Call|Batch)?|multicall|delegatecall|setApprovalForAll|transferOwnership|acceptOwnership|upgradeTo.*|setConfig|setSwapPath|setSplit|increaseAllowance|decreaseAllowance)$/i;
10
13
  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
14
  function signatures(items, read = false) {
@@ -27,67 +30,38 @@ function permissions(input) {
27
30
  bad(writes.length + reads.length > 0, "empty-permissions");
28
31
  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
32
  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");
33
+ const approves = writes.filter((f) => f.name === "approve" || toFunctionSelector(f) === ERC20_APPROVE_SELECTOR);
34
+ if (approves.length) {
35
+ bad(approves.every((f) => f.name === "approve" && f.inputs.length === 2 && f.inputs[0].type === "address" && f.inputs[1].type === "uint256"), "invalid-approve");
32
36
  bad(Array.isArray(input.approvalSpenders) && input.approvalSpenders.length > 0 && input.approvalSpenders.length <= 8 && input.approvalSpenders.every(address), "missing-approval-spenders");
33
37
  bad(typeof input.maxApprovalWei === "string" && /^[1-9][0-9]{0,77}$/.test(input.maxApprovalWei) && BigInt(input.maxApprovalWei) < 2n ** 256n, "missing-approval-cap");
34
38
  } else bad(input.approvalSpenders === void 0 && input.maxApprovalWei === void 0, "unexpected-approval-policy");
35
39
  return { definition: structuredClone(input), writes, reads };
36
40
  }
37
41
  var hasDynamicBytes = (parameter) => /^bytes(?:\[|$)/.test(parameter.type) || parameter.components?.some(hasDynamicBytes);
38
- var MAX_FIXED_BYTES_PER_CALL = 4096;
42
+ var common = ["id", "allow", "read", "maxValueWei", "approvalSpenders", "maxApprovalWei", "codeHash"];
39
43
  function hasOnlyFields(value, keys) {
40
44
  return value && typeof value === "object" && !Array.isArray(value) && Object.keys(value).every((key) => keys.includes(key));
41
45
  }
42
- function parseResolvedWriteConstraints(root, resolved, writes) {
43
- const constraints = /* @__PURE__ */ new Map();
44
- if (resolved.writeConstraints !== void 0) {
45
- const rules = resolved.writeConstraints;
46
- bad(Array.isArray(rules) && rules.length > 0 && rules.length <= writes.length, "invalid-write-constraints");
47
- bad(root.codeHash && resolved.codeHash, "missing-code-hash");
48
- for (const rule of rules) {
49
- bad(hasOnlyFields(rule, ["selector", "fixedBytes", "valueWei"]), "invalid-write-constraints");
50
- bad(typeof rule.selector === "string" && rule.selector.length === 10 && /^0x[0-9a-f]{8}$/i.test(rule.selector), "invalid-constrained-selector");
51
- const selector = rule.selector.toLowerCase();
52
- const entry = writes.find((method) => toFunctionSelector(method) === selector);
53
- bad(entry && !constraints.has(selector), "invalid-constrained-selector");
54
- bad(Array.isArray(rule.fixedBytes) && rule.fixedBytes.length > 0 && rule.fixedBytes.length <= entry.inputs.length, "invalid-fixed-bytes");
55
- const fixedBytes = /* @__PURE__ */ new Map();
56
- let totalBytes = 0;
57
- for (const bound of rule.fixedBytes) {
58
- bad(hasOnlyFields(bound, ["index", "length"]) && Number.isSafeInteger(bound.index) && bound.index >= 0 && entry.inputs[bound.index]?.type === "bytes" && !fixedBytes.has(bound.index), "invalid-fixed-bytes");
59
- bad(Number.isSafeInteger(bound.length) && bound.length > 0 && bound.length <= MAX_FIXED_BYTES_PER_CALL, "invalid-fixed-bytes");
60
- fixedBytes.set(bound.index, bound.length);
61
- totalBytes += bound.length;
62
- }
63
- bad(totalBytes <= MAX_FIXED_BYTES_PER_CALL, "invalid-fixed-bytes");
64
- let valueWei;
65
- if (rule.valueWei !== void 0) {
66
- bad(entry.stateMutability === "payable" && typeof rule.valueWei === "string" && /^(?:0|[1-9][0-9]{0,77})$/.test(rule.valueWei), "invalid-exact-value");
67
- valueWei = BigInt(rule.valueWei);
68
- bad(String(valueWei) === rule.valueWei && valueWei <= BigInt(resolved.maxValueWei), "invalid-exact-value");
69
- }
70
- constraints.set(selector, { fixedBytes, valueWei });
71
- }
72
- }
73
- for (const method of writes) {
74
- const fixedBytes = constraints.get(toFunctionSelector(method))?.fixedBytes;
75
- bad(method.inputs.every((input, index) => !hasDynamicBytes(input) || input.type === "bytes" && fixedBytes?.has(index)), "nested-calldata-not-allowed");
76
- }
77
- return constraints;
78
- }
79
- var common = ["id", "allow", "read", "maxValueWei", "approvalSpenders", "maxApprovalWei", "codeHash"];
80
46
  function identity(input, keys) {
81
47
  bad(hasOnlyFields(input, keys), "unknown-field");
82
- bad(typeof input.id === "string" && /^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(input.id) && input.id.length <= 64, "invalid-id");
83
- bad(input.codeHash === void 0 || typeof input.codeHash === "string" && input.codeHash.length === 66 && /^0x[0-9a-fA-F]{64}$/.test(input.codeHash), "invalid-code-hash");
48
+ bad(identifier(input.id), "invalid-id");
49
+ bad(input.codeHash === void 0 || /^0x[0-9a-fA-F]{64}$/.test(input.codeHash), "invalid-code-hash");
50
+ }
51
+ function checkPresaleApproval(declaration, resolved) {
52
+ if (declaration === void 0) return;
53
+ bad(hasOnlyFields(declaration, ["policyId", "launcherResolver", "maxApprovalWei"]) && identifier(declaration.policyId) && identifier(declaration.launcherResolver), "invalid-presale-approval");
54
+ const cap = declaration.maxApprovalWei;
55
+ bad(typeof cap === "string" && /^[1-9][0-9]{0,77}$/.test(cap) && BigInt(cap) < 2n ** 256n - 1n, "invalid-presale-approval-cap");
56
+ const launcher = resolved.find((entry) => entry.definition.id === declaration.launcherResolver);
57
+ bad(launcher?.writes.some((entry) => entry.name === "contributeQuote" && entry.stateMutability === "nonpayable" && entry.inputs.length === 1 && entry.inputs[0].type === "uint256" && entry.outputs.length === 0), "invalid-presale-launcher-resolver");
84
58
  }
85
59
  function parseAppWalletContracts(value) {
86
60
  bad(Array.isArray(value) && value.length > 0 && value.length <= 16, "invalid-contracts");
87
61
  const ids = /* @__PURE__ */ new Set();
88
62
  const targets = /* @__PURE__ */ new Set();
89
63
  return value.map((input) => {
90
- identity(input, [...common, "chainId", "address", "resolvedContracts"]);
64
+ identity(input, [...common, "chainId", "address", "resolvedContracts", "presaleApproval"]);
91
65
  bad(Number.isSafeInteger(input.chainId) && input.chainId > 0 && address(input.address), "invalid-target");
92
66
  const key = `${input.chainId}:${input.address.toLowerCase()}`;
93
67
  bad(!targets.has(key) && !ids.has(input.id), "duplicate-contract");
@@ -96,7 +70,7 @@ function parseAppWalletContracts(value) {
96
70
  const policy = permissions(input);
97
71
  bad(input.resolvedContracts === void 0 || Array.isArray(input.resolvedContracts) && input.resolvedContracts.length <= 8, "invalid-resolvers");
98
72
  const resolved = (input.resolvedContracts ?? []).map((item) => {
99
- identity(item, [...common, "resolver", "writeConstraints"]);
73
+ identity(item, [...common, "resolver"]);
100
74
  bad(!ids.has(item.id), "duplicate-resolver");
101
75
  ids.add(item.id);
102
76
  bad(typeof item.resolver === "string" && item.resolver.length <= 2048, "invalid-resolver");
@@ -104,19 +78,28 @@ function parseAppWalletContracts(value) {
104
78
  const resolver = entries[0];
105
79
  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");
106
80
  const parsed = permissions(item);
107
- const writeConstraints = parseResolvedWriteConstraints(input, item, parsed.writes);
108
- return { ...parsed, resolver, ...writeConstraints.size ? { writeConstraints } : {} };
81
+ bad(parsed.writes.every((f) => !f.inputs.some(hasDynamicBytes)), "nested-calldata-not-allowed");
82
+ return { ...parsed, resolver };
109
83
  });
84
+ checkPresaleApproval(input.presaleApproval, resolved);
110
85
  return { ...policy, resolved };
111
86
  });
112
87
  }
113
- var requireRule = (ok, reason) => {
88
+ function requireRule(ok, reason) {
114
89
  if (!ok) throw new Error(`app-wallet/${reason}`);
115
- };
90
+ }
116
91
  var same = (a, b) => typeof a === "string" && typeof b === "string" && a.toLowerCase() === b.toLowerCase();
92
+ function isContractAddress(address2) {
93
+ return typeof address2 === "string" && /^0x[0-9a-f]{40}$/i.test(address2) && !/^0x0{40}$/i.test(address2);
94
+ }
95
+ var quoteAbi = parseAbi([
96
+ "function approve(address spender,uint256 amount) returns (bool)",
97
+ "function allowance(address owner,address spender) view returns (uint256)"
98
+ ]);
117
99
  function createAppWalletContracts(runtime, chainId, manifest) {
118
100
  const roots = manifest.walletContracts === void 0 ? [] : parseAppWalletContracts(manifest.walletContracts).filter((p) => p.definition.chainId === chainId);
119
101
  const records = /* @__PURE__ */ new WeakMap();
102
+ const hasPresaleApproval = roots.some(({ definition }) => definition.presaleApproval !== void 0);
120
103
  async function checkCode(address2, policy) {
121
104
  const code = await runtime.getCode(chainId, address2);
122
105
  requireRule(code && code !== "0x", "missing-code");
@@ -125,7 +108,7 @@ function createAppWalletContracts(runtime, chainId, manifest) {
125
108
  async function resolve(root, policy, args) {
126
109
  await checkCode(root.definition.address, root);
127
110
  const address2 = await runtime.readContract(chainId, { address: root.definition.address, abi: [policy.resolver], functionName: policy.resolver.name, args });
128
- requireRule(typeof address2 === "string" && /^0x[0-9a-f]{40}$/i.test(address2) && !/^0x0{40}$/i.test(address2), "invalid-resolved-target");
111
+ requireRule(isContractAddress(address2), "invalid-resolved-target");
129
112
  await checkCode(address2, policy);
130
113
  return address2;
131
114
  }
@@ -153,39 +136,62 @@ function createAppWalletContracts(runtime, chainId, manifest) {
153
136
  }
154
137
  function checkFunction(request, policy, write) {
155
138
  requireRule(request.abi && request.functionName, "invalid-call");
156
- const parameters = { abi: request.abi, functionName: request.functionName, args: request.args };
157
- const value = request.value ?? 0n;
158
- const prepared = write && policy.writeConstraints?.size ? prepareEncodeFunctionData(parameters) : void 0;
159
- const constraint = prepared && policy.writeConstraints?.get(prepared.functionName);
160
- if (constraint) {
161
- for (const [index, length] of constraint.fixedBytes) {
162
- const bytes = request.args?.[index];
163
- requireRule(typeof bytes === "string" && bytes.length === 2 + 2 * length && bytes.startsWith("0x") && !/[^a-f0-9]/i.test(bytes.slice(2)), "fixed-bytes-length-mismatch");
164
- }
165
- requireRule(constraint.valueWei === void 0 || value === constraint.valueWei, "exact-value-mismatch");
166
- }
167
- const data = encodeFunctionData({ ...parameters, ...prepared });
168
- const entry = (write ? policy.writes : policy.reads).find((f) => toFunctionSelector(f) === data.slice(0, 10));
139
+ const data = encodeFunctionData({ abi: request.abi, functionName: request.functionName, args: request.args });
140
+ const selector = data.slice(0, 10);
141
+ const entry = (write ? policy.writes : policy.reads).find((f) => toFunctionSelector(f) === selector);
169
142
  requireRule(entry, "selector-not-allowed");
170
143
  requireRule(encodeFunctionData({ abi: [entry], functionName: entry.name, args: request.args }) === data, "abi-mismatch");
144
+ const value = request.value ?? 0n;
171
145
  requireRule(value >= 0n && (value === 0n || entry.stateMutability === "payable" && policy.definition.maxValueWei && value <= BigInt(policy.definition.maxValueWei)), "value-not-allowed");
172
- if (write && entry.name === "approve") {
146
+ if (write && selector === ERC20_APPROVE_SELECTOR) {
173
147
  requireRule(policy.definition.approvalSpenders?.some((a) => same(a, request.args?.[0])), "spender-not-allowed");
174
148
  const amount = request.args?.[1];
175
149
  requireRule(typeof amount === "bigint" && amount >= 0n && amount <= BigInt(policy.definition.maxApprovalWei), "approval-cap-exceeded");
176
150
  }
177
- return { ...request, abi: [entry], functionName: entry.name };
151
+ return { selector, call: { ...request, abi: [entry], functionName: entry.name } };
152
+ }
153
+ async function resolvePresaleQuote(record, launcher, amount) {
154
+ const declaration = record?.root.definition.presaleApproval;
155
+ requireRule(record && launcher && declaration && record.policy.definition.id === declaration.launcherResolver, "undeclared-presale-launcher");
156
+ requireRule(typeof amount === "bigint" && amount > 0n && amount <= BigInt(declaration.maxApprovalWei), "presale-approval-cap-exceeded");
157
+ requireRule(runtime.resolvePresaleApproval, "presale-approval-unavailable");
158
+ const approval = await runtime.resolvePresaleApproval({ chainId, policyId: declaration.policyId, factory: record.root.definition.address, launcher });
159
+ requireRule(approval && isContractAddress(approval.quoteToken), "invalid-presale-quote-token");
160
+ requireRule(typeof approval.maxApprovalWei === "bigint" && amount <= approval.maxApprovalWei, "presale-approval-cap-exceeded");
161
+ return { token: approval.quoteToken, amount };
162
+ }
163
+ function snapshotQuoteApproval(input) {
164
+ requireRule(input && typeof input === "object" && Object.keys(input).every((key) => key === "pool" || key === "amount"), "invalid-presale-approval-request");
165
+ const { pool, amount } = input;
166
+ const record = records.get(pool);
167
+ requireRule(record, "forged-or-expired-handle");
168
+ return { record, amount };
169
+ }
170
+ async function validateQuoteApproval(prepared) {
171
+ const { record, amount } = prepared;
172
+ const launcher = await resolve(record.root, record.policy, record.args);
173
+ requireRule(same(launcher, record.address), "resolved-target-changed");
174
+ const { token } = await resolvePresaleQuote(record, launcher, amount);
175
+ return { address: token, abi: quoteAbi, functionName: "approve", args: [launcher, amount], value: 0n };
178
176
  }
179
- async function validate(prepared, write) {
177
+ async function validate(prepared, write, account) {
180
178
  const { record, root, policy } = prepared;
181
179
  let address2 = root?.definition.address;
182
180
  if (record) {
183
181
  address2 = await resolve(record.root, record.policy, record.args);
184
182
  requireRule(same(address2, record.address), "resolved-target-changed");
185
183
  } else if (write) await checkCode(address2, policy);
186
- return checkFunction({ ...prepared.request, address: address2 }, policy, write);
184
+ const { selector, call } = checkFunction({ ...prepared.request, address: address2 }, policy, write);
185
+ if (write && hasPresaleApproval && selector === PRESALE_CONTRIBUTE_QUOTE_SELECTOR) {
186
+ requireRule(account, "presale-account-unavailable");
187
+ const { token, amount } = await resolvePresaleQuote(record, address2, call.args?.[0]);
188
+ const allowance = await runtime.readContract(chainId, { address: token, abi: quoteAbi, functionName: "allowance", args: [account, address2] });
189
+ requireRule(typeof allowance === "bigint" && allowance >= amount, "presale-allowance-insufficient");
190
+ return { call, presaleQuoteToken: token };
191
+ }
192
+ return { call, presaleQuoteToken: void 0 };
187
193
  }
188
- return { roots, snapshot, validate, resolveContract };
194
+ return { roots, snapshot, validate, resolveContract, snapshotQuoteApproval, validateQuoteApproval };
189
195
  }
190
196
 
191
197
  // src/sdk/ipfsText.ts
@@ -306,8 +312,7 @@ function createIpfsTextReader({ fetchImpl = fetch, timeoutMs = 8e3 } = {}) {
306
312
  var FSI_QUERY_PREFIX = "https://bsc-debug.butterfly.army/fsi/v1";
307
313
  var FSI_QUERY_PREFIXES = Object.freeze([
308
314
  "https://fsi.taxed.fun/fsi/v1",
309
- FSI_QUERY_PREFIX,
310
- "https://bsc-testnet-debug.butterfly.army/fsi/v1"
315
+ FSI_QUERY_PREFIX
311
316
  ]);
312
317
  var FSI_ORIGINS = new Set(FSI_QUERY_PREFIXES.map((prefix) => new URL(prefix).origin));
313
318
  var FSI_PATH = "/fsi/v1";
@@ -377,13 +382,11 @@ async function readFsiJson(endpoints, path, params, fetchImpl = fetch) {
377
382
  // src/sdk/contractWriteFees.ts
378
383
  var MAX_CONTRACT_WRITE_GAS = 5000000n;
379
384
  var MAX_GAS_PRICE_MULTIPLIER = 2n;
380
- var BSC_MAX_CONTRACT_WRITE_GAS = 15000000n;
381
- async function resolveSafeContractWriteFeeOverrides(request, getNetworkGasPrice, chainId) {
385
+ async function resolveSafeContractWriteFeeOverrides(request, getNetworkGasPrice) {
382
386
  if (request.gas !== void 0) {
383
387
  if (request.gas <= 0n) throw new Error("Contract write gas must be greater than zero.");
384
- const maximumGas = chainId === 56 || chainId === 97 ? BSC_MAX_CONTRACT_WRITE_GAS : MAX_CONTRACT_WRITE_GAS;
385
- if (request.gas > maximumGas) {
386
- throw new Error(`Contract write gas must not exceed ${maximumGas.toString()}.`);
388
+ if (request.gas > MAX_CONTRACT_WRITE_GAS) {
389
+ throw new Error(`Contract write gas must not exceed ${MAX_CONTRACT_WRITE_GAS.toString()}.`);
387
390
  }
388
391
  }
389
392
  if (request.gasPrice !== void 0) {
@@ -448,6 +451,7 @@ async function readContractEventsInBlockRanges(input) {
448
451
 
449
452
  // src/sdk/flapChainRuntime.ts
450
453
  var FLAP_WALLET_RUNTIME_VERSION = 1;
454
+ var PRESALE_APPROVAL_VERSION = 1;
451
455
  function assertAddress(address2) {
452
456
  if (typeof address2 !== "string" || !isAddress(address2, { strict: false }) || /^0x0{40}$/i.test(address2)) throw new Error("A valid nonzero target address is required.");
453
457
  }
@@ -482,10 +486,10 @@ function createFlapChainSdk(runtime, input) {
482
486
  const prepared = appPolicy?.snapshot(request);
483
487
  const snapshot = prepared?.request ?? structuredClone(request);
484
488
  assertValue(snapshot.value);
485
- const fees = await resolveSafeContractWriteFeeOverrides(snapshot, () => runtime.getGasPrice(chainId), chainId);
486
- const call = appPolicy && prepared ? await appPolicy.validate(prepared, true) : contractRequest(snapshot);
489
+ const fees = await resolveSafeContractWriteFeeOverrides(snapshot, () => runtime.getGasPrice(chainId));
490
+ const { call, presaleQuoteToken } = appPolicy && prepared ? await appPolicy.validate(prepared, true, account) : { call: contractRequest(snapshot), presaleQuoteToken: void 0 };
487
491
  writeAccount(account);
488
- return { call: { ...call, ...fees, account, value: snapshot.value }, prepared };
492
+ return { call: { ...call, ...fees, account, value: snapshot.value }, prepared, presaleQuoteToken };
489
493
  }
490
494
  let switchingChain = false;
491
495
  const wallet = {
@@ -533,7 +537,7 @@ function createFlapChainSdk(runtime, input) {
533
537
  return appPolicy.resolveContract(id, args);
534
538
  },
535
539
  readContract: async (request) => {
536
- const call = appPolicy ? await appPolicy.validate(appPolicy.snapshot(request), false) : contractRequest(request);
540
+ const call = appPolicy ? (await appPolicy.validate(appPolicy.snapshot(request), false)).call : contractRequest(request);
537
541
  return runtime.readContract(chainId, call);
538
542
  },
539
543
  simulateContract: async (request) => {
@@ -543,14 +547,28 @@ function createFlapChainSdk(runtime, input) {
543
547
  return { request: { ...call, ...typeof request.contract === "object" ? { contract: request.contract, address: void 0 } : {} }, result };
544
548
  },
545
549
  writeContract: async (request) => {
546
- let { call, prepared } = await prepareWrite(request);
550
+ const { call, prepared, presaleQuoteToken } = await prepareWrite(request);
547
551
  if (appPolicy && prepared?.record) {
548
552
  await runtime.simulateContract(chainId, call);
549
- call = { ...call, ...await appPolicy.validate(prepared, true), account: call.account };
553
+ const rechecked = await appPolicy.validate(prepared, true, call.account);
554
+ if (rechecked.presaleQuoteToken?.toLowerCase() !== presaleQuoteToken?.toLowerCase()) throw new Error("app-wallet/presale-quote-changed");
550
555
  }
551
556
  writeAccount(call.account);
552
557
  return runtime.writeContract(chainId, call);
553
558
  },
559
+ approveQuote: async (request) => {
560
+ const account = writeAccount();
561
+ if (!appPolicy) throw new Error("app-wallet/presale-approval-unavailable");
562
+ const prepared = appPolicy.snapshotQuoteApproval(request);
563
+ const call = await appPolicy.validateQuoteApproval(prepared);
564
+ writeAccount(account);
565
+ const accepted = await runtime.simulateContract(chainId, { ...call, account });
566
+ if (accepted !== true) throw new Error("app-wallet/presale-approval-simulation-failed");
567
+ const rechecked = await appPolicy.validateQuoteApproval(prepared);
568
+ if (rechecked.address.toLowerCase() !== call.address.toLowerCase()) throw new Error("app-wallet/presale-quote-changed");
569
+ writeAccount(account);
570
+ return runtime.writeContract(chainId, { ...call, account });
571
+ },
554
572
  sendTransaction: async (request) => {
555
573
  request = structuredClone(request);
556
574
  const account = writeAccount();
@@ -589,6 +607,339 @@ function createFlapChainSdk(runtime, input) {
589
607
  };
590
608
  }
591
609
 
610
+ // src/sdk/deviceSensors.ts
611
+ var DEVICE_SENSORS_VERSION = 1;
612
+ var ALL = ["location", "motion", "orientation"];
613
+ var DEFAULT_TIMEOUT_MS = 1e4;
614
+ var finite = (value) => typeof value === "number" && Number.isFinite(value) ? value : null;
615
+ var nonnegative = (value) => {
616
+ const number = finite(value);
617
+ return number !== null && number >= 0 ? number : null;
618
+ };
619
+ var boundedTimeout = (value) => Math.min(12e4, Math.max(1, nonnegative(value) ?? DEFAULT_TIMEOUT_MS));
620
+ function browserEnvironment() {
621
+ if (typeof window === "undefined" || typeof document === "undefined" || typeof navigator === "undefined") return void 0;
622
+ return {
623
+ secure: window.isSecureContext === true,
624
+ window,
625
+ document,
626
+ geolocation: navigator.geolocation,
627
+ setTimeout: (callback, milliseconds) => window.setTimeout(callback, milliseconds),
628
+ clearTimeout: (id) => window.clearTimeout(id),
629
+ now: Date.now
630
+ };
631
+ }
632
+ function locationData(value, now) {
633
+ const coords = value?.coords;
634
+ const latitude = finite(coords?.latitude), longitude = finite(coords?.longitude), accuracy = nonnegative(coords?.accuracy);
635
+ if (latitude === null || Math.abs(latitude) > 90 || longitude === null || Math.abs(longitude) > 180 || accuracy === null) return null;
636
+ return { latitude, longitude, accuracy, altitude: finite(coords.altitude), altitudeAccuracy: nonnegative(coords.altitudeAccuracy), heading: finite(coords.heading), speed: nonnegative(coords.speed), timestamp: finite(value.timestamp) ?? now };
637
+ }
638
+ function vector(value) {
639
+ const result = { x: finite(value?.x), y: finite(value?.y), z: finite(value?.z) };
640
+ return Object.values(result).some((item) => item !== null) ? result : null;
641
+ }
642
+ function motionData(value, now) {
643
+ const acceleration = vector(value?.acceleration), accelerationIncludingGravity = vector(value?.accelerationIncludingGravity);
644
+ const rotation = { alpha: finite(value?.rotationRate?.alpha), beta: finite(value?.rotationRate?.beta), gamma: finite(value?.rotationRate?.gamma) };
645
+ const rotationRate = Object.values(rotation).some((item) => item !== null) ? rotation : null;
646
+ if (!acceleration && !accelerationIncludingGravity && !rotationRate) return null;
647
+ return { acceleration, accelerationIncludingGravity, rotationRate, interval: nonnegative(value?.interval), timestamp: now };
648
+ }
649
+ function orientationData(value, now) {
650
+ const alpha = finite(value?.alpha), beta = finite(value?.beta), gamma = finite(value?.gamma);
651
+ return alpha === null && beta === null && gamma === null ? null : { alpha, beta, gamma, absolute: value?.absolute === true, timestamp: now };
652
+ }
653
+ function inactiveSensor(status, mode) {
654
+ const snapshot = Object.freeze({ status, permission: "unknown", data: null, mode });
655
+ return { getSnapshot: () => snapshot, subscribe: () => () => {
656
+ }, request: () => Promise.resolve(snapshot), stop() {
657
+ } };
658
+ }
659
+ function createBrowserChannel(kind, declared, resolveEnvironment) {
660
+ if (!declared) return inactiveSensor("not-declared", "real");
661
+ let state = { status: "idle", permission: "unknown", data: null, mode: "real" };
662
+ const listeners = /* @__PURE__ */ new Set();
663
+ let generation = 0;
664
+ let pending;
665
+ let environment;
666
+ let options = {};
667
+ let watchId;
668
+ let timer;
669
+ let eventListener;
670
+ let visibilityListener;
671
+ let abortListener;
672
+ let shouldResume = false;
673
+ let sawInvalidData = false;
674
+ let sessionActive = false;
675
+ const eventName = kind === "motion" ? "devicemotion" : "deviceorientation";
676
+ function update(next) {
677
+ state = { ...state, ...next };
678
+ for (const listener of listeners) listener();
679
+ }
680
+ function settle() {
681
+ const task = pending;
682
+ pending = void 0;
683
+ task?.resolve(state);
684
+ }
685
+ function clearTimer() {
686
+ if (timer !== void 0) environment?.clearTimeout(timer);
687
+ timer = void 0;
688
+ }
689
+ function detachHardware() {
690
+ clearTimer();
691
+ if (watchId !== void 0) environment?.geolocation?.clearWatch(watchId);
692
+ watchId = void 0;
693
+ if (eventListener) environment?.window.removeEventListener(eventName, eventListener);
694
+ eventListener = void 0;
695
+ }
696
+ function cleanup() {
697
+ generation += 1;
698
+ detachHardware();
699
+ if (visibilityListener) environment?.document.removeEventListener("visibilitychange", visibilityListener);
700
+ visibilityListener = void 0;
701
+ if (abortListener) options.signal?.removeEventListener("abort", abortListener);
702
+ abortListener = void 0;
703
+ sessionActive = false;
704
+ shouldResume = false;
705
+ }
706
+ function finish(status, permission = state.permission) {
707
+ cleanup();
708
+ update({ status, permission, data: null });
709
+ settle();
710
+ }
711
+ function stop() {
712
+ const hadWork = sessionActive || Boolean(pending);
713
+ cleanup();
714
+ update({ status: hadWork ? "cancelled" : "idle", data: null });
715
+ settle();
716
+ }
717
+ function guard(env) {
718
+ if (!env) return "unsupported";
719
+ if (!env.secure) return "insecure";
720
+ const features = kind === "location" ? ["geolocation"] : ["accelerometer", "gyroscope"];
721
+ const policy = env.document.permissionsPolicy ?? env.document.featurePolicy;
722
+ try {
723
+ if (policy && features.some((feature) => !policy.allowsFeature(feature))) return "policy-blocked";
724
+ } catch (error) {
725
+ if (error?.name === "SecurityError") return "policy-blocked";
726
+ }
727
+ if (kind === "location" ? !env.geolocation : !(kind === "motion" ? env.window.DeviceMotionEvent : env.window.DeviceOrientationEvent)) return "unsupported";
728
+ return null;
729
+ }
730
+ function accept(raw, token) {
731
+ if (token !== generation || !sessionActive) return;
732
+ const data = kind === "location" ? locationData(raw, environment.now()) : kind === "motion" ? motionData(raw, environment.now()) : orientationData(raw, environment.now());
733
+ if (!data) {
734
+ sawInvalidData = true;
735
+ return;
736
+ }
737
+ clearTimer();
738
+ update({ status: "active", permission: "granted", data });
739
+ settle();
740
+ if (kind === "location" && !options.watch) {
741
+ cleanup();
742
+ }
743
+ }
744
+ function startHardware() {
745
+ const env = environment;
746
+ if (env.document.visibilityState === "hidden") {
747
+ shouldResume = true;
748
+ update({ status: "paused", data: null });
749
+ settle();
750
+ return;
751
+ }
752
+ const token = generation;
753
+ sawInvalidData = false;
754
+ update({ status: "requesting", data: null });
755
+ timer = env.setTimeout(() => {
756
+ if (token === generation) finish(sawInvalidData ? "unavailable" : "timeout");
757
+ }, boundedTimeout(options.timeoutMs));
758
+ try {
759
+ if (kind === "location") {
760
+ const failed = (error) => {
761
+ if (token !== generation || !sessionActive) return;
762
+ const status = error?.code === 1 ? "denied" : error?.code === 3 ? "timeout" : "unavailable";
763
+ finish(status, status === "denied" ? "denied" : state.permission);
764
+ };
765
+ const geoOptions = { enableHighAccuracy: options.enableHighAccuracy === true, maximumAge: nonnegative(options.maximumAge) ?? 0, timeout: boundedTimeout(options.timeoutMs) };
766
+ if (options.watch) {
767
+ const id = env.geolocation.watchPosition((value) => accept(value, token), failed, geoOptions);
768
+ if (token === generation && sessionActive) watchId = id;
769
+ else env.geolocation.clearWatch(id);
770
+ } else env.geolocation.getCurrentPosition((value) => accept(value, token), failed, geoOptions);
771
+ } else {
772
+ eventListener = (value) => accept(value, token);
773
+ env.window.addEventListener(eventName, eventListener);
774
+ }
775
+ } catch (error) {
776
+ if (token === generation) finish(error?.name === "SecurityError" ? "policy-blocked" : "unavailable");
777
+ }
778
+ }
779
+ function observeSession() {
780
+ const env = environment;
781
+ visibilityListener = () => {
782
+ if (!sessionActive) return;
783
+ if (env.document.visibilityState === "hidden") {
784
+ generation += 1;
785
+ detachHardware();
786
+ shouldResume = true;
787
+ update({ status: "paused", data: null });
788
+ settle();
789
+ } else if (shouldResume) {
790
+ shouldResume = false;
791
+ if (state.permission === "granted") startHardware();
792
+ else finish("paused");
793
+ }
794
+ };
795
+ env.document.addEventListener("visibilitychange", visibilityListener);
796
+ if (options.signal) {
797
+ abortListener = () => finish("cancelled");
798
+ options.signal.addEventListener("abort", abortListener, { once: true });
799
+ }
800
+ }
801
+ function request(requestOptions = {}) {
802
+ if (pending) return pending.promise;
803
+ if (state.status === "active" && (kind !== "location" || options.watch && requestOptions.watch)) return Promise.resolve(state);
804
+ cleanup();
805
+ options = { ...requestOptions };
806
+ let blocked;
807
+ try {
808
+ environment = resolveEnvironment();
809
+ blocked = guard(environment);
810
+ } catch (error) {
811
+ blocked = error?.name === "SecurityError" ? "policy-blocked" : "unavailable";
812
+ }
813
+ if (blocked) {
814
+ update({ status: blocked, data: null });
815
+ return Promise.resolve(state);
816
+ }
817
+ if (options.signal?.aborted) {
818
+ update({ status: "cancelled", data: null });
819
+ return Promise.resolve(state);
820
+ }
821
+ if (environment.document.visibilityState === "hidden") {
822
+ update({ status: "paused", data: null });
823
+ return Promise.resolve(state);
824
+ }
825
+ sessionActive = true;
826
+ let resolve;
827
+ const promise = new Promise((done) => {
828
+ resolve = done;
829
+ });
830
+ pending = { promise, resolve };
831
+ update({ status: "requesting", data: null });
832
+ observeSession();
833
+ const token = generation;
834
+ if (kind === "location") startHardware();
835
+ else {
836
+ const constructor = kind === "motion" ? environment.window.DeviceMotionEvent : environment.window.DeviceOrientationEvent;
837
+ try {
838
+ const permission = constructor?.requestPermission?.();
839
+ if (permission) {
840
+ Promise.resolve(permission).then((result) => {
841
+ if (token !== generation || !sessionActive) return;
842
+ if (result !== "granted") {
843
+ finish("denied", "denied");
844
+ return;
845
+ }
846
+ update({ permission: "granted" });
847
+ startHardware();
848
+ }, (error) => {
849
+ if (token === generation && sessionActive) finish(error?.name === "NotAllowedError" ? "denied" : "unavailable");
850
+ });
851
+ } else startHardware();
852
+ } catch (error) {
853
+ if (token === generation) finish(error?.name === "NotAllowedError" ? "denied" : "unavailable");
854
+ }
855
+ }
856
+ return promise;
857
+ }
858
+ return {
859
+ getSnapshot: () => state,
860
+ subscribe(listener) {
861
+ listeners.add(listener);
862
+ let subscribed = true;
863
+ return () => {
864
+ if (!subscribed) return;
865
+ subscribed = false;
866
+ listeners.delete(listener);
867
+ if (listeners.size === 0 && sessionActive) stop();
868
+ };
869
+ },
870
+ request,
871
+ stop
872
+ };
873
+ }
874
+ function createBrowserDeviceSensors(options = {}) {
875
+ const allowed = new Set(options.capabilities ?? ALL);
876
+ const environment = () => typeof options.environment === "function" ? options.environment() : options.environment ?? browserEnvironment();
877
+ const location = createBrowserChannel("location", allowed.has("location"), environment);
878
+ const motion = createBrowserChannel("motion", allowed.has("motion"), environment);
879
+ const orientation = createBrowserChannel("orientation", allowed.has("orientation"), environment);
880
+ return { version: DEVICE_SENSORS_VERSION, mode: "real", location, motion, orientation, dispose() {
881
+ location.stop();
882
+ motion.stop();
883
+ orientation.stop();
884
+ } };
885
+ }
886
+ function createMockDeviceSensors(options = {}) {
887
+ const allowed = new Set(options.capabilities ?? ALL);
888
+ function channel(capability, data) {
889
+ if (!allowed.has(capability)) return inactiveSensor("not-declared", "mock");
890
+ let state = { status: "idle", permission: "unknown", data: null, mode: "mock" };
891
+ const listeners = /* @__PURE__ */ new Set();
892
+ const update = (next) => {
893
+ state = next;
894
+ for (const listener of listeners) listener();
895
+ };
896
+ return {
897
+ getSnapshot: () => state,
898
+ subscribe(listener) {
899
+ listeners.add(listener);
900
+ return () => {
901
+ listeners.delete(listener);
902
+ };
903
+ },
904
+ request(requestOptions) {
905
+ const outcome = options.outcome ?? "granted";
906
+ const status = requestOptions?.signal?.aborted ? "cancelled" : outcome === "granted" ? "active" : outcome;
907
+ update({ status, permission: status === "active" ? "granted" : status === "denied" ? "denied" : "unknown", data: status === "active" ? data : null, mode: "mock" });
908
+ return Promise.resolve(state);
909
+ },
910
+ stop() {
911
+ update({ ...state, status: "idle", data: null });
912
+ }
913
+ };
914
+ }
915
+ const location = channel("location", { latitude: 0, longitude: 0, accuracy: 100, altitude: null, altitudeAccuracy: null, heading: null, speed: null, timestamp: 0, ...options.location });
916
+ const motion = channel("motion", { acceleration: { x: 0, y: 0, z: 0 }, accelerationIncludingGravity: { x: 0, y: 0, z: 9.8 }, rotationRate: { alpha: 0, beta: 0, gamma: 0 }, interval: 16, timestamp: 0, ...options.motion });
917
+ const orientation = channel("orientation", { alpha: 0, beta: 0, gamma: 0, absolute: false, timestamp: 0, ...options.orientation });
918
+ return { version: DEVICE_SENSORS_VERSION, mode: "mock", location, motion, orientation, dispose() {
919
+ location.stop();
920
+ motion.stop();
921
+ orientation.stop();
922
+ } };
923
+ }
924
+ function scopeDeviceSensors(sensors, capabilities = []) {
925
+ const declared = new Set(capabilities);
926
+ const location = declared.has("location") ? sensors.location : inactiveSensor("not-declared", sensors.mode);
927
+ const motion = declared.has("motion") ? sensors.motion : inactiveSensor("not-declared", sensors.mode);
928
+ const orientation = declared.has("orientation") ? sensors.orientation : inactiveSensor("not-declared", sensors.mode);
929
+ return { version: DEVICE_SENSORS_VERSION, mode: sensors.mode, location, motion, orientation, dispose() {
930
+ location.stop();
931
+ motion.stop();
932
+ orientation.stop();
933
+ } };
934
+ }
935
+ function unavailableDeviceSensors() {
936
+ const location = inactiveSensor("unsupported", "real");
937
+ const motion = inactiveSensor("unsupported", "real");
938
+ const orientation = inactiveSensor("unsupported", "real");
939
+ return { version: DEVICE_SENSORS_VERSION, mode: "real", location, motion, orientation, dispose() {
940
+ } };
941
+ }
942
+
592
943
  // src/sdk/runtimeContext.ts
593
944
  var zeroAddress = "0x0000000000000000000000000000000000000000";
594
945
  function explorerForChain(chainId) {
@@ -645,6 +996,6 @@ function createVaultRuntimeContext(input) {
645
996
  };
646
997
  }
647
998
 
648
- export { FLAP_WALLET_RUNTIME_VERSION, chainLabelForChain, createFlapChainSdk, createIpfsTextReader, createVaultRuntimeContext, explorerForChain, parseAppWalletContracts, readContractEventsInBlockRanges, readFsiJson, resolveSafeContractWriteFeeOverrides };
649
- //# sourceMappingURL=chunk-56WOVXXG.js.map
650
- //# sourceMappingURL=chunk-56WOVXXG.js.map
999
+ export { DEVICE_SENSORS_VERSION, FLAP_WALLET_RUNTIME_VERSION, PRESALE_APPROVAL_VERSION, chainLabelForChain, createBrowserDeviceSensors, createFlapChainSdk, createIpfsTextReader, createMockDeviceSensors, createVaultRuntimeContext, explorerForChain, parseAppWalletContracts, readContractEventsInBlockRanges, readFsiJson, resolveSafeContractWriteFeeOverrides, scopeDeviceSensors, unavailableDeviceSensors };
1000
+ //# sourceMappingURL=chunk-BIRAO6LU.js.map
1001
+ //# sourceMappingURL=chunk-BIRAO6LU.js.map