@oasisprotocol/privana-sdk 0.5.9 → 0.5.11

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.
@@ -1366,7 +1366,7 @@ async function ctrlHydrateViaRefresh(ctrl, record, address) {
1366
1366
  }
1367
1367
  }
1368
1368
 
1369
- // src/sdk/hooks/private-read-token-store.ts
1369
+ // src/sdk/utils/private-read-token-store.ts
1370
1370
  var cache = /* @__PURE__ */ new Map();
1371
1371
  function createScopeKey(apiUrl, chainId, address) {
1372
1372
  return `${apiUrl.replace(/\/$/, "")}:${chainId}:${address.toLowerCase()}`;
@@ -1991,395 +1991,129 @@ function useSafePrivanaContext() {
1991
1991
  return useContext(PrivanaContext);
1992
1992
  }
1993
1993
 
1994
- // src/sdk/hooks/browser-storage.ts
1995
- function storageCandidate(name) {
1996
- try {
1997
- if (typeof window === "undefined") return void 0;
1998
- return window[name] ?? void 0;
1999
- } catch {
2000
- return void 0;
2001
- }
2002
- }
2003
- function storageCandidates() {
2004
- return [storageCandidate("localStorage"), storageCandidate("sessionStorage")].filter(
2005
- (storage) => storage !== void 0
2006
- );
2007
- }
2008
- function canUseBrowserStorage() {
2009
- const probeKey = "privana:storage-probe";
2010
- for (const storage of storageCandidates()) {
1994
+ // src/sdk/utils/deposit-finality.ts
1995
+ async function checkDepositWithFinalityRetry({
1996
+ checkDeposit,
1997
+ isStale,
1998
+ onRetry,
1999
+ timeoutMs,
2000
+ retryIntervalMs,
2001
+ startedAt = Date.now(),
2002
+ now = Date.now,
2003
+ sleep = defaultSleep
2004
+ }) {
2005
+ while (true) {
2006
+ if (isStale()) return { kind: "stale" };
2011
2007
  try {
2012
- storage.setItem(probeKey, "1");
2013
- storage.removeItem(probeKey);
2014
- return true;
2015
- } catch {
2008
+ const response = await checkDeposit();
2009
+ if (!isInsufficientFinalityMessage(response.detail) || response.status !== "error") {
2010
+ return { kind: "response", response };
2011
+ }
2012
+ if (response.detail) onRetry(response.detail);
2013
+ } catch (error) {
2014
+ if (isStale()) return { kind: "stale" };
2015
+ if (!isInsufficientFinalityError(error)) throw error;
2016
+ onRetry(
2017
+ error instanceof AccountingApiError && error.detail ? error.detail : error instanceof Error ? error.message : String(error)
2018
+ );
2016
2019
  }
2020
+ if (now() - startedAt > timeoutMs) return { kind: "timeout" };
2021
+ await sleep(retryIntervalMs);
2017
2022
  }
2018
- return false;
2019
2023
  }
2020
- function setBrowserStorageItem(key, value) {
2021
- let stored = false;
2022
- for (const storage of storageCandidates()) {
2023
- try {
2024
- storage.setItem(key, value);
2025
- stored = true;
2026
- } catch {
2027
- }
2024
+ function isInsufficientFinalityError(error) {
2025
+ if (error instanceof AccountingApiError) {
2026
+ return isInsufficientFinalityMessage(error.detail) || isInsufficientFinalityMessage(error.message);
2028
2027
  }
2029
- return stored;
2028
+ return error instanceof Error && isInsufficientFinalityMessage(error.message);
2030
2029
  }
2031
- function getBrowserStorageItem(key) {
2032
- for (const storage of storageCandidates()) {
2033
- try {
2034
- const value = storage.getItem(key);
2035
- if (value !== null) return value;
2036
- } catch {
2037
- }
2038
- }
2039
- return null;
2030
+ function isInsufficientFinalityMessage(message) {
2031
+ return message?.includes("Insufficient finality") ?? false;
2040
2032
  }
2041
- function removeBrowserStorageItem(key) {
2042
- for (const storage of storageCandidates()) {
2043
- try {
2044
- storage.removeItem(key);
2045
- } catch {
2046
- }
2047
- }
2033
+ function defaultSleep(milliseconds) {
2034
+ return new Promise((resolve) => setTimeout(resolve, milliseconds));
2048
2035
  }
2049
- function canUseSharedBrowserStorage() {
2050
- const storage = storageCandidate("localStorage");
2051
- if (!storage) return false;
2052
- const probeKey = "privana:shared-storage-probe";
2036
+ var INITIAL_AUTH_BACKOFF_MS = 5e3;
2037
+ var MAX_AUTH_BACKOFF_MS = 6e4;
2038
+ var privateReadFailureCache = /* @__PURE__ */ new Map();
2039
+ var privateReadInflight = /* @__PURE__ */ new Map();
2040
+ async function executeHostedAuthPrivateReadRequest({
2041
+ client,
2042
+ hostedAuthSession,
2043
+ refreshHostedAuthSession,
2044
+ request
2045
+ }) {
2046
+ const ensureHostedAuth = async (forceRefresh) => {
2047
+ if (!hostedAuthSession) {
2048
+ throw new HostedAuthRequiredError();
2049
+ }
2050
+ if (!forceRefresh && isHostedAuthSessionActive(hostedAuthSession)) {
2051
+ client.clearPrivateReadToken();
2052
+ client.setBearerToken(hostedAuthSession.accessToken);
2053
+ return hostedAuthSession.accessToken;
2054
+ }
2055
+ const refreshed = await refreshHostedAuthSession();
2056
+ client.clearPrivateReadToken();
2057
+ client.setBearerToken(refreshed.accessToken);
2058
+ return refreshed.accessToken;
2059
+ };
2060
+ await ensureHostedAuth(false);
2053
2061
  try {
2054
- storage.setItem(probeKey, "1");
2055
- storage.removeItem(probeKey);
2056
- return true;
2057
- } catch {
2058
- return false;
2062
+ return await request(client);
2063
+ } catch (error) {
2064
+ if (!(error instanceof AccountingApiError) || error.statusCode !== 401) {
2065
+ throw error;
2066
+ }
2067
+ await ensureHostedAuth(true);
2068
+ return request(client);
2059
2069
  }
2060
2070
  }
2061
- function setSharedBrowserStorageItem(key, value) {
2062
- const storage = storageCandidate("localStorage");
2063
- if (!storage) return false;
2064
- try {
2065
- storage.setItem(key, value);
2066
- } catch {
2067
- return false;
2068
- }
2069
- try {
2070
- storageCandidate("sessionStorage")?.removeItem(key);
2071
- } catch {
2072
- }
2073
- return true;
2071
+ function clearPrivateReadScope(scopeKey, client) {
2072
+ deleteCachedPrivateReadToken(scopeKey);
2073
+ privateReadFailureCache.delete(scopeKey);
2074
+ client.clearPrivateReadToken();
2074
2075
  }
2075
- function getSharedBrowserStorageItem(key) {
2076
+ async function executeSiwePrivateReadRequest({
2077
+ client,
2078
+ scopeKey,
2079
+ getToken,
2080
+ request
2081
+ }) {
2082
+ const run = (token2) => request(client.withPrivateReadToken(token2));
2083
+ const token = await getToken(false);
2076
2084
  try {
2077
- return storageCandidate("localStorage")?.getItem(key) ?? null;
2078
- } catch {
2079
- return null;
2080
- }
2081
- }
2082
- function removeSharedBrowserStorageItem(key) {
2083
- for (const storage of storageCandidates()) {
2084
- try {
2085
- storage.removeItem(key);
2086
- } catch {
2085
+ return await run(token);
2086
+ } catch (error) {
2087
+ if (!(error instanceof AccountingApiError) || error.statusCode !== 401) {
2088
+ throw error;
2087
2089
  }
2090
+ clearPrivateReadScope(scopeKey, client);
2091
+ return run(await getToken(true));
2088
2092
  }
2089
2093
  }
2090
-
2091
- // src/sdk/hooks/pending-lock.ts
2092
- var DEFAULT_LOCK_DURATION_SECONDS = 259200;
2093
- var DEFAULT_ONRAMP_LOCK_BUFFER = 0.02;
2094
- var BUFFER_SCALE = 1000000n;
2095
- function applyLockBuffer(amount, buffer = DEFAULT_ONRAMP_LOCK_BUFFER) {
2096
- if (!Number.isFinite(buffer) || buffer < 0 || buffer >= 1) {
2097
- throw new Error(`Lock buffer must be in [0, 1), got ${buffer}`);
2098
- }
2099
- const shave = BigInt(Math.max(0, Math.ceil(buffer * Number(BUFFER_SCALE) - 1e-6)));
2100
- return amount * (BUFFER_SCALE - shave) / BUFFER_SCALE;
2101
- }
2102
- function clampLockAmount(amount, maxAmount) {
2103
- return maxAmount !== void 0 && maxAmount < amount ? maxAmount : amount;
2104
- }
2105
- function requireServiceAddress(serviceAddress) {
2106
- if (!serviceAddress) {
2107
- throw new Error("Service address not configured");
2108
- }
2109
- return serviceAddress;
2110
- }
2111
- function requireDepositLockOwner(walletAddress, beneficiary) {
2112
- if (!walletAddress) throw new Error("No wallet connected");
2113
- if (!beneficiary) throw new Error("No authenticated deposit account");
2114
- if (walletAddress.toLowerCase() !== beneficiary.toLowerCase()) {
2115
- throw new Error("Connected wallet does not match the authenticated deposit account");
2116
- }
2117
- return beneficiary;
2118
- }
2119
- function walletClientAccountAddress(walletClient) {
2120
- const account = walletClient.account;
2121
- if (!account) return void 0;
2122
- return typeof account === "string" ? account : account.address;
2094
+ function recordPrivateReadFailure(scopeKey) {
2095
+ const previous = privateReadFailureCache.get(scopeKey);
2096
+ const backoffMs = Math.min(
2097
+ previous ? previous.backoffMs * 2 : INITIAL_AUTH_BACKOFF_MS,
2098
+ MAX_AUTH_BACKOFF_MS
2099
+ );
2100
+ privateReadFailureCache.set(scopeKey, {
2101
+ backoffMs,
2102
+ retryAt: Date.now() + backoffMs
2103
+ });
2123
2104
  }
2124
- async function createSignedLockRequest({
2125
- client,
2126
- walletClient,
2127
- userAddress,
2128
- networkConfig,
2129
- serviceAddress,
2130
- tokenId,
2131
- amount,
2132
- lockDuration = DEFAULT_LOCK_DURATION_SECONDS
2133
- }) {
2134
- if (amount <= 0n) {
2135
- throw new Error("Lock amount must be positive");
2136
- }
2137
- const signerAddress = walletClientAccountAddress(walletClient);
2138
- if (!signerAddress || signerAddress.toLowerCase() !== userAddress.toLowerCase()) {
2139
- throw new Error("Connected wallet does not match the authenticated deposit account");
2105
+ function ensureFailureBackoff(scopeKey) {
2106
+ const failure = privateReadFailureCache.get(scopeKey);
2107
+ if (!failure) return;
2108
+ if (failure.retryAt <= Date.now()) {
2109
+ privateReadFailureCache.delete(scopeKey);
2110
+ return;
2140
2111
  }
2141
- const expiry = BigInt(Math.floor(Date.now() / 1e3) + lockDuration);
2142
- const { nonce } = await client.getLockNonce(userAddress);
2143
- const signature = await signLockMessage({
2144
- walletClient,
2145
- chainId: networkConfig.chainId,
2146
- verifyingContract: networkConfig.accountingContract,
2147
- message: {
2148
- serviceAddress,
2149
- tokenId,
2150
- amount,
2151
- expiry,
2152
- nonce: BigInt(nonce)
2153
- }
2154
- });
2155
- return {
2156
- service_address: serviceAddress,
2157
- token_id: tokenId,
2158
- amount: amount.toString(),
2159
- expiry: expiry.toString(),
2160
- nonce: String(nonce),
2161
- signature
2162
- };
2163
- }
2164
- var EXPIRY_SLACK_SECONDS = 60;
2165
- function isSignedLockUsable(payload) {
2166
- const expiry = Number(payload.expiry);
2167
- if (!Number.isFinite(expiry)) return false;
2168
- return expiry > Math.floor(Date.now() / 1e3) + EXPIRY_SLACK_SECONDS;
2169
- }
2170
- var PostDepositLockError = class _PostDepositLockError extends Error {
2171
- constructor(message, reason, signedAmount, creditedAmount, options) {
2172
- super(message, options);
2173
- this.reason = reason;
2174
- this.signedAmount = signedAmount;
2175
- this.creditedAmount = creditedAmount;
2176
- this.name = "PostDepositLockError";
2177
- this.submissionMayHaveSucceeded = options?.submissionMayHaveSucceeded ?? false;
2178
- Object.setPrototypeOf(this, _PostDepositLockError.prototype);
2179
- }
2180
- };
2181
- async function submitPendingLock({
2182
- client,
2183
- payload,
2184
- creditedAmount,
2185
- beforeSubmit
2186
- }) {
2187
- let signedAmount;
2188
- try {
2189
- signedAmount = BigInt(payload.amount);
2190
- } catch (err) {
2191
- throw new PostDepositLockError(
2192
- "Stored signed lock payload is malformed",
2193
- "submission-failed",
2194
- void 0,
2195
- creditedAmount,
2196
- { cause: err }
2197
- );
2198
- }
2199
- if (!isSignedLockUsable(payload)) {
2200
- throw new PostDepositLockError(
2201
- "Signed lock expired before the deposit was credited",
2202
- "expired",
2203
- signedAmount,
2204
- creditedAmount
2205
- );
2206
- }
2207
- if (creditedAmount !== void 0 && creditedAmount < signedAmount) {
2208
- throw new PostDepositLockError(
2209
- "Credited amount is below the signed lock amount",
2210
- "credited-below-signed",
2211
- signedAmount,
2212
- creditedAmount
2213
- );
2214
- }
2215
- try {
2216
- beforeSubmit?.();
2217
- return await client.lockFunds(payload);
2218
- } catch (err) {
2219
- throw new PostDepositLockError(
2220
- err instanceof Error ? err.message : "Lock submission failed",
2221
- "submission-failed",
2222
- signedAmount,
2223
- creditedAmount,
2224
- { cause: err }
2225
- );
2226
- }
2227
- }
2228
- function pendingLockKey(userAddress, correlationId) {
2229
- return `privana:pending-lock:${userAddress.toLowerCase()}:${correlationId}`;
2230
- }
2231
- function savePendingLock(userAddress, correlationId, payload) {
2232
- const record = { payload, savedAt: Date.now() };
2233
- const stored = setBrowserStorageItem(
2234
- pendingLockKey(userAddress, correlationId),
2235
- JSON.stringify(record)
2236
- );
2237
- if (!stored) {
2238
- throw new Error("Unable to persist signed lock for recovery");
2239
- }
2240
- }
2241
- function loadPendingLock(userAddress, correlationId) {
2242
- const key = pendingLockKey(userAddress, correlationId);
2243
- try {
2244
- const raw = getBrowserStorageItem(key);
2245
- if (!raw) return void 0;
2246
- const record = JSON.parse(raw);
2247
- if (!record?.payload?.signature) {
2248
- removeBrowserStorageItem(key);
2249
- return void 0;
2250
- }
2251
- return record.payload;
2252
- } catch {
2253
- return void 0;
2254
- }
2255
- }
2256
- function clearPendingLock(userAddress, correlationId) {
2257
- removeBrowserStorageItem(pendingLockKey(userAddress, correlationId));
2258
- }
2259
-
2260
- // src/sdk/hooks/deposit-finality.ts
2261
- async function checkDepositWithFinalityRetry({
2262
- checkDeposit,
2263
- isStale,
2264
- onRetry,
2265
- timeoutMs,
2266
- retryIntervalMs,
2267
- startedAt = Date.now(),
2268
- now = Date.now,
2269
- sleep = defaultSleep
2270
- }) {
2271
- while (true) {
2272
- if (isStale()) return { kind: "stale" };
2273
- try {
2274
- const response = await checkDeposit();
2275
- if (!isInsufficientFinalityMessage(response.detail) || response.status !== "error") {
2276
- return { kind: "response", response };
2277
- }
2278
- if (response.detail) onRetry(response.detail);
2279
- } catch (error) {
2280
- if (isStale()) return { kind: "stale" };
2281
- if (!isInsufficientFinalityError(error)) throw error;
2282
- onRetry(
2283
- error instanceof AccountingApiError && error.detail ? error.detail : error instanceof Error ? error.message : String(error)
2284
- );
2285
- }
2286
- if (now() - startedAt > timeoutMs) return { kind: "timeout" };
2287
- await sleep(retryIntervalMs);
2288
- }
2289
- }
2290
- function isInsufficientFinalityError(error) {
2291
- if (error instanceof AccountingApiError) {
2292
- return isInsufficientFinalityMessage(error.detail) || isInsufficientFinalityMessage(error.message);
2293
- }
2294
- return error instanceof Error && isInsufficientFinalityMessage(error.message);
2295
- }
2296
- function isInsufficientFinalityMessage(message) {
2297
- return message?.includes("Insufficient finality") ?? false;
2298
- }
2299
- function defaultSleep(milliseconds) {
2300
- return new Promise((resolve) => setTimeout(resolve, milliseconds));
2301
- }
2302
- var INITIAL_AUTH_BACKOFF_MS = 5e3;
2303
- var MAX_AUTH_BACKOFF_MS = 6e4;
2304
- var privateReadFailureCache = /* @__PURE__ */ new Map();
2305
- var privateReadInflight = /* @__PURE__ */ new Map();
2306
- async function executeHostedAuthPrivateReadRequest({
2307
- client,
2308
- hostedAuthSession,
2309
- refreshHostedAuthSession,
2310
- request
2311
- }) {
2312
- const ensureHostedAuth = async (forceRefresh) => {
2313
- if (!hostedAuthSession) {
2314
- throw new HostedAuthRequiredError();
2315
- }
2316
- if (!forceRefresh && isHostedAuthSessionActive(hostedAuthSession)) {
2317
- client.clearPrivateReadToken();
2318
- client.setBearerToken(hostedAuthSession.accessToken);
2319
- return hostedAuthSession.accessToken;
2320
- }
2321
- const refreshed = await refreshHostedAuthSession();
2322
- client.clearPrivateReadToken();
2323
- client.setBearerToken(refreshed.accessToken);
2324
- return refreshed.accessToken;
2325
- };
2326
- await ensureHostedAuth(false);
2327
- try {
2328
- return await request(client);
2329
- } catch (error) {
2330
- if (!(error instanceof AccountingApiError) || error.statusCode !== 401) {
2331
- throw error;
2332
- }
2333
- await ensureHostedAuth(true);
2334
- return request(client);
2335
- }
2336
- }
2337
- function clearPrivateReadScope(scopeKey, client) {
2338
- deleteCachedPrivateReadToken(scopeKey);
2339
- privateReadFailureCache.delete(scopeKey);
2340
- client.clearPrivateReadToken();
2341
- }
2342
- async function executeSiwePrivateReadRequest({
2343
- client,
2344
- scopeKey,
2345
- getToken,
2346
- request
2347
- }) {
2348
- const run = (token2) => request(client.withPrivateReadToken(token2));
2349
- const token = await getToken(false);
2350
- try {
2351
- return await run(token);
2352
- } catch (error) {
2353
- if (!(error instanceof AccountingApiError) || error.statusCode !== 401) {
2354
- throw error;
2355
- }
2356
- clearPrivateReadScope(scopeKey, client);
2357
- return run(await getToken(true));
2358
- }
2359
- }
2360
- function recordPrivateReadFailure(scopeKey) {
2361
- const previous = privateReadFailureCache.get(scopeKey);
2362
- const backoffMs = Math.min(
2363
- previous ? previous.backoffMs * 2 : INITIAL_AUTH_BACKOFF_MS,
2364
- MAX_AUTH_BACKOFF_MS
2365
- );
2366
- privateReadFailureCache.set(scopeKey, {
2367
- backoffMs,
2368
- retryAt: Date.now() + backoffMs
2369
- });
2370
- }
2371
- function ensureFailureBackoff(scopeKey) {
2372
- const failure = privateReadFailureCache.get(scopeKey);
2373
- if (!failure) return;
2374
- if (failure.retryAt <= Date.now()) {
2375
- privateReadFailureCache.delete(scopeKey);
2376
- return;
2377
- }
2378
- throw new Error(
2379
- `Private-read authentication is temporarily paused after a recent failure. Retry in ${Math.ceil(
2380
- (failure.retryAt - Date.now()) / 1e3
2381
- )}s.`
2382
- );
2112
+ throw new Error(
2113
+ `Private-read authentication is temporarily paused after a recent failure. Retry in ${Math.ceil(
2114
+ (failure.retryAt - Date.now()) / 1e3
2115
+ )}s.`
2116
+ );
2383
2117
  }
2384
2118
  function usePrivateReadRequest() {
2385
2119
  const wagmiContext = useContext(WagmiContext);
@@ -2703,6 +2437,272 @@ function creditedAmountFromResponse(response, requestedAmount) {
2703
2437
  function isDefinitiveCandidateFailure(error) {
2704
2438
  return error instanceof AccountingApiError && error.statusCode === 400;
2705
2439
  }
2440
+
2441
+ // src/sdk/utils/browser-storage.ts
2442
+ function storageCandidate(name) {
2443
+ try {
2444
+ if (typeof window === "undefined") return void 0;
2445
+ return window[name] ?? void 0;
2446
+ } catch {
2447
+ return void 0;
2448
+ }
2449
+ }
2450
+ function storageCandidates() {
2451
+ return [storageCandidate("localStorage"), storageCandidate("sessionStorage")].filter(
2452
+ (storage) => storage !== void 0
2453
+ );
2454
+ }
2455
+ function canUseBrowserStorage() {
2456
+ const probeKey = "privana:storage-probe";
2457
+ for (const storage of storageCandidates()) {
2458
+ try {
2459
+ storage.setItem(probeKey, "1");
2460
+ storage.removeItem(probeKey);
2461
+ return true;
2462
+ } catch {
2463
+ }
2464
+ }
2465
+ return false;
2466
+ }
2467
+ function setBrowserStorageItem(key, value) {
2468
+ let stored = false;
2469
+ for (const storage of storageCandidates()) {
2470
+ try {
2471
+ storage.setItem(key, value);
2472
+ stored = true;
2473
+ } catch {
2474
+ }
2475
+ }
2476
+ return stored;
2477
+ }
2478
+ function getBrowserStorageItem(key) {
2479
+ for (const storage of storageCandidates()) {
2480
+ try {
2481
+ const value = storage.getItem(key);
2482
+ if (value !== null) return value;
2483
+ } catch {
2484
+ }
2485
+ }
2486
+ return null;
2487
+ }
2488
+ function removeBrowserStorageItem(key) {
2489
+ for (const storage of storageCandidates()) {
2490
+ try {
2491
+ storage.removeItem(key);
2492
+ } catch {
2493
+ }
2494
+ }
2495
+ }
2496
+ function canUseSharedBrowserStorage() {
2497
+ const storage = storageCandidate("localStorage");
2498
+ if (!storage) return false;
2499
+ const probeKey = "privana:shared-storage-probe";
2500
+ try {
2501
+ storage.setItem(probeKey, "1");
2502
+ storage.removeItem(probeKey);
2503
+ return true;
2504
+ } catch {
2505
+ return false;
2506
+ }
2507
+ }
2508
+ function setSharedBrowserStorageItem(key, value) {
2509
+ const storage = storageCandidate("localStorage");
2510
+ if (!storage) return false;
2511
+ try {
2512
+ storage.setItem(key, value);
2513
+ } catch {
2514
+ return false;
2515
+ }
2516
+ try {
2517
+ storageCandidate("sessionStorage")?.removeItem(key);
2518
+ } catch {
2519
+ }
2520
+ return true;
2521
+ }
2522
+ function getSharedBrowserStorageItem(key) {
2523
+ try {
2524
+ return storageCandidate("localStorage")?.getItem(key) ?? null;
2525
+ } catch {
2526
+ return null;
2527
+ }
2528
+ }
2529
+ function removeSharedBrowserStorageItem(key) {
2530
+ for (const storage of storageCandidates()) {
2531
+ try {
2532
+ storage.removeItem(key);
2533
+ } catch {
2534
+ }
2535
+ }
2536
+ }
2537
+
2538
+ // src/sdk/utils/pending-lock.ts
2539
+ var DEFAULT_LOCK_DURATION_SECONDS = 259200;
2540
+ var DEFAULT_ONRAMP_LOCK_BUFFER = 0.02;
2541
+ var BUFFER_SCALE = 1000000n;
2542
+ function applyLockBuffer(amount, buffer = DEFAULT_ONRAMP_LOCK_BUFFER) {
2543
+ if (!Number.isFinite(buffer) || buffer < 0 || buffer >= 1) {
2544
+ throw new Error(`Lock buffer must be in [0, 1), got ${buffer}`);
2545
+ }
2546
+ const shave = BigInt(Math.max(0, Math.ceil(buffer * Number(BUFFER_SCALE) - 1e-6)));
2547
+ return amount * (BUFFER_SCALE - shave) / BUFFER_SCALE;
2548
+ }
2549
+ function clampLockAmount(amount, maxAmount) {
2550
+ return maxAmount !== void 0 && maxAmount < amount ? maxAmount : amount;
2551
+ }
2552
+ function requireServiceAddress(serviceAddress) {
2553
+ if (!serviceAddress) {
2554
+ throw new Error("Service address not configured");
2555
+ }
2556
+ return serviceAddress;
2557
+ }
2558
+ function requireDepositLockOwner(walletAddress, beneficiary) {
2559
+ if (!walletAddress) throw new Error("No wallet connected");
2560
+ if (!beneficiary) throw new Error("No authenticated deposit account");
2561
+ if (walletAddress.toLowerCase() !== beneficiary.toLowerCase()) {
2562
+ throw new Error("Connected wallet does not match the authenticated deposit account");
2563
+ }
2564
+ return beneficiary;
2565
+ }
2566
+ function walletClientAccountAddress(walletClient) {
2567
+ const account = walletClient.account;
2568
+ if (!account) return void 0;
2569
+ return typeof account === "string" ? account : account.address;
2570
+ }
2571
+ async function createSignedLockRequest({
2572
+ client,
2573
+ walletClient,
2574
+ userAddress,
2575
+ networkConfig,
2576
+ serviceAddress,
2577
+ tokenId,
2578
+ amount,
2579
+ lockDuration = DEFAULT_LOCK_DURATION_SECONDS
2580
+ }) {
2581
+ if (amount <= 0n) {
2582
+ throw new Error("Lock amount must be positive");
2583
+ }
2584
+ const signerAddress = walletClientAccountAddress(walletClient);
2585
+ if (!signerAddress || signerAddress.toLowerCase() !== userAddress.toLowerCase()) {
2586
+ throw new Error("Connected wallet does not match the authenticated deposit account");
2587
+ }
2588
+ const expiry = BigInt(Math.floor(Date.now() / 1e3) + lockDuration);
2589
+ const { nonce } = await client.getLockNonce(userAddress);
2590
+ const signature = await signLockMessage({
2591
+ walletClient,
2592
+ chainId: networkConfig.chainId,
2593
+ verifyingContract: networkConfig.accountingContract,
2594
+ message: {
2595
+ serviceAddress,
2596
+ tokenId,
2597
+ amount,
2598
+ expiry,
2599
+ nonce: BigInt(nonce)
2600
+ }
2601
+ });
2602
+ return {
2603
+ service_address: serviceAddress,
2604
+ token_id: tokenId,
2605
+ amount: amount.toString(),
2606
+ expiry: expiry.toString(),
2607
+ nonce: String(nonce),
2608
+ signature
2609
+ };
2610
+ }
2611
+ var EXPIRY_SLACK_SECONDS = 60;
2612
+ function isSignedLockUsable(payload) {
2613
+ const expiry = Number(payload.expiry);
2614
+ if (!Number.isFinite(expiry)) return false;
2615
+ return expiry > Math.floor(Date.now() / 1e3) + EXPIRY_SLACK_SECONDS;
2616
+ }
2617
+ var PostDepositLockError = class _PostDepositLockError extends Error {
2618
+ constructor(message, reason, signedAmount, creditedAmount, options) {
2619
+ super(message, options);
2620
+ this.reason = reason;
2621
+ this.signedAmount = signedAmount;
2622
+ this.creditedAmount = creditedAmount;
2623
+ this.name = "PostDepositLockError";
2624
+ this.submissionMayHaveSucceeded = options?.submissionMayHaveSucceeded ?? false;
2625
+ Object.setPrototypeOf(this, _PostDepositLockError.prototype);
2626
+ }
2627
+ };
2628
+ async function submitPendingLock({
2629
+ client,
2630
+ payload,
2631
+ creditedAmount,
2632
+ beforeSubmit
2633
+ }) {
2634
+ let signedAmount;
2635
+ try {
2636
+ signedAmount = BigInt(payload.amount);
2637
+ } catch (err) {
2638
+ throw new PostDepositLockError(
2639
+ "Stored signed lock payload is malformed",
2640
+ "submission-failed",
2641
+ void 0,
2642
+ creditedAmount,
2643
+ { cause: err }
2644
+ );
2645
+ }
2646
+ if (!isSignedLockUsable(payload)) {
2647
+ throw new PostDepositLockError(
2648
+ "Signed lock expired before the deposit was credited",
2649
+ "expired",
2650
+ signedAmount,
2651
+ creditedAmount
2652
+ );
2653
+ }
2654
+ if (creditedAmount !== void 0 && creditedAmount < signedAmount) {
2655
+ throw new PostDepositLockError(
2656
+ "Credited amount is below the signed lock amount",
2657
+ "credited-below-signed",
2658
+ signedAmount,
2659
+ creditedAmount
2660
+ );
2661
+ }
2662
+ try {
2663
+ beforeSubmit?.();
2664
+ return await client.lockFunds(payload);
2665
+ } catch (err) {
2666
+ throw new PostDepositLockError(
2667
+ err instanceof Error ? err.message : "Lock submission failed",
2668
+ "submission-failed",
2669
+ signedAmount,
2670
+ creditedAmount,
2671
+ { cause: err }
2672
+ );
2673
+ }
2674
+ }
2675
+ function pendingLockKey(userAddress, correlationId) {
2676
+ return `privana:pending-lock:${userAddress.toLowerCase()}:${correlationId}`;
2677
+ }
2678
+ function savePendingLock(userAddress, correlationId, payload) {
2679
+ const record = { payload, savedAt: Date.now() };
2680
+ const stored = setBrowserStorageItem(
2681
+ pendingLockKey(userAddress, correlationId),
2682
+ JSON.stringify(record)
2683
+ );
2684
+ if (!stored) {
2685
+ throw new Error("Unable to persist signed lock for recovery");
2686
+ }
2687
+ }
2688
+ function loadPendingLock(userAddress, correlationId) {
2689
+ const key = pendingLockKey(userAddress, correlationId);
2690
+ try {
2691
+ const raw = getBrowserStorageItem(key);
2692
+ if (!raw) return void 0;
2693
+ const record = JSON.parse(raw);
2694
+ if (!record?.payload?.signature) {
2695
+ removeBrowserStorageItem(key);
2696
+ return void 0;
2697
+ }
2698
+ return record.payload;
2699
+ } catch {
2700
+ return void 0;
2701
+ }
2702
+ }
2703
+ function clearPendingLock(userAddress, correlationId) {
2704
+ removeBrowserStorageItem(pendingLockKey(userAddress, correlationId));
2705
+ }
2706
2706
  var BYTES32_PATTERN = /^0x[0-9a-fA-F]{64}$/;
2707
2707
  var PROVIDER_ASSET_CODE_PATTERN = /^[a-zA-Z0-9_-]{1,64}$/;
2708
2708
  var TRANSAK_MINIMUM_TARGET_PERCENT = 105n;
@@ -6057,5 +6057,5 @@ function useTransakOnRamp(options) {
6057
6057
  }
6058
6058
 
6059
6059
  export { AccountingApiError, Button, DEFAULT_LOCK_DURATION_SECONDS, DEFAULT_ONRAMP_LOCK_BUFFER, FiatOnRampForm, HOSTED_AUTH_CLOCK_SKEW_MS, HostedAuthError, HostedAuthRequiredError, HostedAuthStateMismatchError, HttpClient, LOCK_TYPES, MODIFY_LOCK_TYPES, NETWORK_CONFIG, NetworkError, PostDepositLockError, PrivanaClient, PrivanaProvider, SUPPORTED_CHAINS, SiweAuthProvider, Skeleton, TRANSFER_LOCKED_TYPES, TRANSFER_TYPES, ValidationError, WITHDRAW_FROM_LOCK_TYPES, WITHDRAW_TYPES, applyLockBuffer, applyRefreshResponse, buildHostedAuthSession, buildSiweStatement, buttonVariants, canRetryOnRampVerification, canUseBrowserStorage, canUseSharedBrowserStorage, clampLockAmount, clearHostedAuthPendingTransaction, clearPendingLock, cn, createDomain, createHostedAuthPendingStorageKey, createHostedAuthState, createHostedAuthStorageKey, createLockExpiry, createPkceChallenge, createPkceVerifier, createProductOnRampFlowSnapshot, createProductOnRampOutcomeCallbacks, createSignedLockRequest, formatCountdown, formatTimeRemaining, formatTokenAmount, getAccountingContract, getApiUrl, getBlockNumber, getBrowserStorageItem, getChainById, getChainId, getExplorerAddressUrl, getExplorerLabel, getSharedBrowserStorageItem, getTransactionReceipt, getTransakMinimumTargetBaseUnits, getWalletClient3 as getWalletClient, isHostedAuthRefreshActive, isHostedAuthSessionActive, isMoonPayProductOnRamp, isSignedLockUsable, loadPendingLock, matchesFrozenOnRampToken, matchesOnRampTransaction, matchesProductOnRampScope, normalizeAddress, normalizeHex, parseHostedAuthCallback, parseTokenAmount, persistHostedAuthPendingTransaction, readHostedAuthPendingTransaction, readStoredHostedAuthSession, removeBrowserStorageItem, removeSharedBrowserStorageItem, requireDepositLockOwner, requireServiceAddress, resolveProductOnRamp, savePendingLock, setBrowserStorageItem, setSharedBrowserStorageItem, shortenAddress, signLockMessage, signModifyLockMessage, signTransferLockedMessage, signTransferMessage, signWithdrawFromLockMessage, signWithdrawMessage, stripHostedAuthCallbackParams, submitPendingLock, syncHostedAuthSessionToClient, useDepositVerification, useEnsureCorrectChain, useFiatOnRamp, usePrivanaContext, usePrivateReadRequest, useSafeAccount, useSafePrivanaContext, useSiweAuth, useTransakOnRamp, waitForTransactionReceipt };
6060
- //# sourceMappingURL=chunk-RDYNQUMV.js.map
6061
- //# sourceMappingURL=chunk-RDYNQUMV.js.map
6060
+ //# sourceMappingURL=chunk-KUHXTCVW.js.map
6061
+ //# sourceMappingURL=chunk-KUHXTCVW.js.map