@flapsdk/vault-runtime 0.1.42 → 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.
@@ -6,6 +6,9 @@ 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,8 +30,9 @@ 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");
@@ -36,17 +40,28 @@ function permissions(input) {
36
40
  }
37
41
  var hasDynamicBytes = (parameter) => /^bytes(?:\[|$)/.test(parameter.type) || parameter.components?.some(hasDynamicBytes);
38
42
  var common = ["id", "allow", "read", "maxValueWei", "approvalSpenders", "maxApprovalWei", "codeHash"];
43
+ function hasOnlyFields(value, keys) {
44
+ return value && typeof value === "object" && !Array.isArray(value) && Object.keys(value).every((key) => keys.includes(key));
45
+ }
39
46
  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");
47
+ bad(hasOnlyFields(input, keys), "unknown-field");
48
+ bad(identifier(input.id), "invalid-id");
42
49
  bad(input.codeHash === void 0 || /^0x[0-9a-fA-F]{64}$/.test(input.codeHash), "invalid-code-hash");
43
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");
58
+ }
44
59
  function parseAppWalletContracts(value) {
45
60
  bad(Array.isArray(value) && value.length > 0 && value.length <= 16, "invalid-contracts");
46
61
  const ids = /* @__PURE__ */ new Set();
47
62
  const targets = /* @__PURE__ */ new Set();
48
63
  return value.map((input) => {
49
- identity(input, [...common, "chainId", "address", "resolvedContracts"]);
64
+ identity(input, [...common, "chainId", "address", "resolvedContracts", "presaleApproval"]);
50
65
  bad(Number.isSafeInteger(input.chainId) && input.chainId > 0 && address(input.address), "invalid-target");
51
66
  const key = `${input.chainId}:${input.address.toLowerCase()}`;
52
67
  bad(!targets.has(key) && !ids.has(input.id), "duplicate-contract");
@@ -66,16 +81,25 @@ function parseAppWalletContracts(value) {
66
81
  bad(parsed.writes.every((f) => !f.inputs.some(hasDynamicBytes)), "nested-calldata-not-allowed");
67
82
  return { ...parsed, resolver };
68
83
  });
84
+ checkPresaleApproval(input.presaleApproval, resolved);
69
85
  return { ...policy, resolved };
70
86
  });
71
87
  }
72
- var requireRule = (ok, reason) => {
88
+ function requireRule(ok, reason) {
73
89
  if (!ok) throw new Error(`app-wallet/${reason}`);
74
- };
90
+ }
75
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
+ ]);
76
99
  function createAppWalletContracts(runtime, chainId, manifest) {
77
100
  const roots = manifest.walletContracts === void 0 ? [] : parseAppWalletContracts(manifest.walletContracts).filter((p) => p.definition.chainId === chainId);
78
101
  const records = /* @__PURE__ */ new WeakMap();
102
+ const hasPresaleApproval = roots.some(({ definition }) => definition.presaleApproval !== void 0);
79
103
  async function checkCode(address2, policy) {
80
104
  const code = await runtime.getCode(chainId, address2);
81
105
  requireRule(code && code !== "0x", "missing-code");
@@ -84,7 +108,7 @@ function createAppWalletContracts(runtime, chainId, manifest) {
84
108
  async function resolve(root, policy, args) {
85
109
  await checkCode(root.definition.address, root);
86
110
  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");
111
+ requireRule(isContractAddress(address2), "invalid-resolved-target");
88
112
  await checkCode(address2, policy);
89
113
  return address2;
90
114
  }
@@ -113,28 +137,61 @@ function createAppWalletContracts(runtime, chainId, manifest) {
113
137
  function checkFunction(request, policy, write) {
114
138
  requireRule(request.abi && request.functionName, "invalid-call");
115
139
  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));
140
+ const selector = data.slice(0, 10);
141
+ const entry = (write ? policy.writes : policy.reads).find((f) => toFunctionSelector(f) === selector);
117
142
  requireRule(entry, "selector-not-allowed");
118
143
  requireRule(encodeFunctionData({ abi: [entry], functionName: entry.name, args: request.args }) === data, "abi-mismatch");
119
144
  const value = request.value ?? 0n;
120
145
  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") {
146
+ if (write && selector === ERC20_APPROVE_SELECTOR) {
122
147
  requireRule(policy.definition.approvalSpenders?.some((a) => same(a, request.args?.[0])), "spender-not-allowed");
123
148
  const amount = request.args?.[1];
124
149
  requireRule(typeof amount === "bigint" && amount >= 0n && amount <= BigInt(policy.definition.maxApprovalWei), "approval-cap-exceeded");
125
150
  }
126
- 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 };
127
176
  }
128
- async function validate(prepared, write) {
177
+ async function validate(prepared, write, account) {
129
178
  const { record, root, policy } = prepared;
130
179
  let address2 = root?.definition.address;
131
180
  if (record) {
132
181
  address2 = await resolve(record.root, record.policy, record.args);
133
182
  requireRule(same(address2, record.address), "resolved-target-changed");
134
183
  } else if (write) await checkCode(address2, policy);
135
- 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 };
136
193
  }
137
- return { roots, snapshot, validate, resolveContract };
194
+ return { roots, snapshot, validate, resolveContract, snapshotQuoteApproval, validateQuoteApproval };
138
195
  }
139
196
 
140
197
  // src/sdk/ipfsText.ts
@@ -255,8 +312,7 @@ function createIpfsTextReader({ fetchImpl = fetch, timeoutMs = 8e3 } = {}) {
255
312
  var FSI_QUERY_PREFIX = "https://bsc-debug.butterfly.army/fsi/v1";
256
313
  var FSI_QUERY_PREFIXES = Object.freeze([
257
314
  "https://fsi.taxed.fun/fsi/v1",
258
- FSI_QUERY_PREFIX,
259
- "https://bsc-testnet-debug.butterfly.army/fsi/v1"
315
+ FSI_QUERY_PREFIX
260
316
  ]);
261
317
  var FSI_ORIGINS = new Set(FSI_QUERY_PREFIXES.map((prefix) => new URL(prefix).origin));
262
318
  var FSI_PATH = "/fsi/v1";
@@ -395,6 +451,7 @@ async function readContractEventsInBlockRanges(input) {
395
451
 
396
452
  // src/sdk/flapChainRuntime.ts
397
453
  var FLAP_WALLET_RUNTIME_VERSION = 1;
454
+ var PRESALE_APPROVAL_VERSION = 1;
398
455
  function assertAddress(address2) {
399
456
  if (typeof address2 !== "string" || !isAddress(address2, { strict: false }) || /^0x0{40}$/i.test(address2)) throw new Error("A valid nonzero target address is required.");
400
457
  }
@@ -430,9 +487,9 @@ function createFlapChainSdk(runtime, input) {
430
487
  const snapshot = prepared?.request ?? structuredClone(request);
431
488
  assertValue(snapshot.value);
432
489
  const fees = await resolveSafeContractWriteFeeOverrides(snapshot, () => runtime.getGasPrice(chainId));
433
- const call = appPolicy && prepared ? await appPolicy.validate(prepared, true) : contractRequest(snapshot);
490
+ const { call, presaleQuoteToken } = appPolicy && prepared ? await appPolicy.validate(prepared, true, account) : { call: contractRequest(snapshot), presaleQuoteToken: void 0 };
434
491
  writeAccount(account);
435
- return { call: { ...call, ...fees, account, value: snapshot.value }, prepared };
492
+ return { call: { ...call, ...fees, account, value: snapshot.value }, prepared, presaleQuoteToken };
436
493
  }
437
494
  let switchingChain = false;
438
495
  const wallet = {
@@ -480,7 +537,7 @@ function createFlapChainSdk(runtime, input) {
480
537
  return appPolicy.resolveContract(id, args);
481
538
  },
482
539
  readContract: async (request) => {
483
- 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);
484
541
  return runtime.readContract(chainId, call);
485
542
  },
486
543
  simulateContract: async (request) => {
@@ -490,14 +547,28 @@ function createFlapChainSdk(runtime, input) {
490
547
  return { request: { ...call, ...typeof request.contract === "object" ? { contract: request.contract, address: void 0 } : {} }, result };
491
548
  },
492
549
  writeContract: async (request) => {
493
- let { call, prepared } = await prepareWrite(request);
550
+ const { call, prepared, presaleQuoteToken } = await prepareWrite(request);
494
551
  if (appPolicy && prepared?.record) {
495
552
  await runtime.simulateContract(chainId, call);
496
- 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");
497
555
  }
498
556
  writeAccount(call.account);
499
557
  return runtime.writeContract(chainId, call);
500
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
+ },
501
572
  sendTransaction: async (request) => {
502
573
  request = structuredClone(request);
503
574
  const account = writeAccount();
@@ -536,6 +607,339 @@ function createFlapChainSdk(runtime, input) {
536
607
  };
537
608
  }
538
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
+
539
943
  // src/sdk/runtimeContext.ts
540
944
  var zeroAddress = "0x0000000000000000000000000000000000000000";
541
945
  function explorerForChain(chainId) {
@@ -592,6 +996,6 @@ function createVaultRuntimeContext(input) {
592
996
  };
593
997
  }
594
998
 
595
- export { FLAP_WALLET_RUNTIME_VERSION, chainLabelForChain, createFlapChainSdk, createIpfsTextReader, createVaultRuntimeContext, explorerForChain, parseAppWalletContracts, readContractEventsInBlockRanges, readFsiJson, resolveSafeContractWriteFeeOverrides };
596
- //# sourceMappingURL=chunk-PLIQ3EPB.js.map
597
- //# sourceMappingURL=chunk-PLIQ3EPB.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