@oasisprotocol/privana-sdk 0.5.1 → 0.5.2

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.
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use client";
2
- import { usePrivanaContext, createHostedAuthPendingStorageKey, clearHostedAuthPendingTransaction, HostedAuthRequiredError, HostedAuthError, createPkceVerifier, createPkceChallenge, createHostedAuthState, persistHostedAuthPendingTransaction, parseHostedAuthCallback, readHostedAuthPendingTransaction, HostedAuthStateMismatchError, buildHostedAuthSession, useSafePrivanaContext, usePrivateReadRequest, formatTokenAmount, submitPendingLock, PostDepositLockError, useDepositVerification, useEnsureCorrectChain, getTransactionReceipt, waitForTransactionReceipt, canUseBrowserStorage, clampLockAmount, getWalletClient, createSignedLockRequest, signWithdrawMessage, signLockMessage, signTransferMessage, signTransferLockedMessage, signModifyLockMessage, cn, Button, stripHostedAuthCallbackParams, AccountingApiError, getBrowserStorageItem, removeBrowserStorageItem, isSignedLockUsable, setBrowserStorageItem, shortenAddress, formatTimeRemaining, parseTokenAmount, getExplorerAddressUrl, getExplorerLabel, Skeleton, formatCountdown, FiatOnRampForm } from './chunk-SAJ7K5WT.js';
3
- export { AccountingApiError, Button, DEFAULT_LOCK_DURATION_SECONDS, DEFAULT_ONRAMP_LOCK_BUFFER, 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, clampLockAmount, clearHostedAuthPendingTransaction, clearPendingLock, createDomain, createHostedAuthPendingStorageKey, createHostedAuthState, createHostedAuthStorageKey, createLockExpiry, createPkceChallenge, createPkceVerifier, createSignedLockRequest, getAccountingContract, getApiUrl, getChainById, getChainId, getExplorerAddressUrl, getExplorerLabel, isHostedAuthRefreshActive, isHostedAuthSessionActive, isSignedLockUsable, loadPendingLock, normalizeAddress, normalizeHex, parseHostedAuthCallback, persistHostedAuthPendingTransaction, readHostedAuthPendingTransaction, readStoredHostedAuthSession, savePendingLock, signLockMessage, signModifyLockMessage, signTransferLockedMessage, signTransferMessage, signWithdrawFromLockMessage, signWithdrawMessage, stripHostedAuthCallbackParams, submitPendingLock, syncHostedAuthSessionToClient, useDepositVerification, usePrivanaContext, useSafeAccount, useSafePrivanaContext, useSiweAuth } from './chunk-SAJ7K5WT.js';
2
+ import { usePrivanaContext, createHostedAuthPendingStorageKey, clearHostedAuthPendingTransaction, HostedAuthRequiredError, HostedAuthError, createPkceVerifier, createPkceChallenge, createHostedAuthState, persistHostedAuthPendingTransaction, parseHostedAuthCallback, readHostedAuthPendingTransaction, HostedAuthStateMismatchError, buildHostedAuthSession, useSafePrivanaContext, usePrivateReadRequest, formatTokenAmount, submitPendingLock, PostDepositLockError, useDepositVerification, useEnsureCorrectChain, getTransactionReceipt, getBlockNumber, waitForTransactionReceipt, canUseBrowserStorage, clampLockAmount, getWalletClient, createSignedLockRequest, signWithdrawMessage, signLockMessage, signTransferMessage, signTransferLockedMessage, signModifyLockMessage, cn, Button, stripHostedAuthCallbackParams, AccountingApiError, getBrowserStorageItem, removeBrowserStorageItem, isSignedLockUsable, setBrowserStorageItem, shortenAddress, formatTimeRemaining, parseTokenAmount, getExplorerAddressUrl, getExplorerLabel, Skeleton, formatCountdown, FiatOnRampForm } from './chunk-ZVUMV4NR.js';
3
+ export { AccountingApiError, Button, DEFAULT_LOCK_DURATION_SECONDS, DEFAULT_ONRAMP_LOCK_BUFFER, 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, clampLockAmount, clearHostedAuthPendingTransaction, clearPendingLock, createDomain, createHostedAuthPendingStorageKey, createHostedAuthState, createHostedAuthStorageKey, createLockExpiry, createPkceChallenge, createPkceVerifier, createSignedLockRequest, getAccountingContract, getApiUrl, getChainById, getChainId, getExplorerAddressUrl, getExplorerLabel, isHostedAuthRefreshActive, isHostedAuthSessionActive, isSignedLockUsable, loadPendingLock, normalizeAddress, normalizeHex, parseHostedAuthCallback, persistHostedAuthPendingTransaction, readHostedAuthPendingTransaction, readStoredHostedAuthSession, savePendingLock, signLockMessage, signModifyLockMessage, signTransferLockedMessage, signTransferMessage, signWithdrawFromLockMessage, signWithdrawMessage, stripHostedAuthCallbackParams, submitPendingLock, syncHostedAuthSessionToClient, useDepositVerification, usePrivanaContext, useSafeAccount, useSafePrivanaContext, useSiweAuth } from './chunk-ZVUMV4NR.js';
4
4
  import { useState, useRef, useMemo, useCallback, useContext, useEffect, useId } from 'react';
5
5
  import { QueryClientContext, useQuery, useQueryClient, useMutation, keepPreviousData } from '@tanstack/react-query';
6
6
  import { useAccount, useWalletClient, useConfig, useWriteContract, useSendTransaction, useBalance as useBalance$1, useReadContract } from 'wagmi';
@@ -479,8 +479,12 @@ function useDeposit(options = {}) {
479
479
  try {
480
480
  let confirmed = false;
481
481
  try {
482
- await getTransactionReceipt(config, { hash, chainId: persisted.chainId });
483
- confirmed = true;
482
+ const receipt = await getTransactionReceipt(config, {
483
+ hash,
484
+ chainId: persisted.chainId
485
+ });
486
+ const blockNumber = await getBlockNumber(config, { chainId: persisted.chainId });
487
+ confirmed = blockNumber - receipt.blockNumber + 1n >= BigInt(confirmations);
484
488
  } catch {
485
489
  }
486
490
  if (!confirmed) {
@@ -1926,7 +1930,8 @@ function TransactionErrorView({
1926
1930
  explorerLabel,
1927
1931
  onRetry,
1928
1932
  onDismiss,
1929
- isRetrying
1933
+ isRetrying,
1934
+ retryLabel = "Retry Verification"
1930
1935
  }) {
1931
1936
  return /* @__PURE__ */ jsxs("div", { className: "flex w-full flex-col gap-4", children: [
1932
1937
  /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-3", children: [
@@ -1965,7 +1970,7 @@ function TransactionErrorView({
1965
1970
  onClick: onRetry,
1966
1971
  disabled: isRetrying,
1967
1972
  className: "bg-primary text-primary-foreground hover:bg-primary/90 flex h-10 flex-1 cursor-pointer items-center justify-center rounded-[10px] px-3 py-2 text-sm font-medium transition-colors disabled:cursor-not-allowed disabled:opacity-50",
1968
- children: isRetrying ? "Retrying..." : "Retry Verification"
1973
+ children: isRetrying ? "Retrying..." : retryLabel
1969
1974
  }
1970
1975
  )
1971
1976
  ] })
@@ -4550,7 +4555,7 @@ function WalletBalanceView({
4550
4555
  allowance,
4551
4556
  amount,
4552
4557
  onAmountChange,
4553
- onPlay,
4558
+ onFundSession,
4554
4559
  onAddFunds,
4555
4560
  onWithdraw
4556
4561
  }) {
@@ -4575,18 +4580,17 @@ function WalletBalanceView({
4575
4580
  const hasValidAmount = !!amount && parseFloat(amount) > 0;
4576
4581
  const tooManyDecimals = hasValidAmount && !!token && amount.includes(".") && amount.split(".")[1].length > token.decimals;
4577
4582
  const exceedsBalance = hasValidAmount && !tooManyDecimals && !!token && !isBalanceLoading && !isBalanceError && parseTokenAmount(amount, token.decimals) > availableWei;
4578
- const canPlay = hasValidAmount && !!token && !tooManyDecimals && !exceedsBalance && !isBalanceLoading && !isBalanceError;
4583
+ const canFundSession = hasValidAmount && !!token && !tooManyDecimals && !exceedsBalance && !isBalanceLoading && !isBalanceError;
4579
4584
  const handleMax = () => {
4580
4585
  const max = availableFormatted.replace(/\s/g, "");
4581
4586
  if (parseFloat(max) > 0) onAmountChange(max);
4582
4587
  };
4583
- const handlePlay = () => {
4584
- if (!token || !canPlay || !onPlay) return;
4585
- onPlay({ tokenId: token.id, amount });
4586
- onAmountChange("");
4588
+ const handleFundSession = () => {
4589
+ if (!token || !canFundSession || !onFundSession) return;
4590
+ onFundSession({ tokenId: token.id, amount });
4587
4591
  };
4588
4592
  const showInput = variant !== "fully-in-use";
4589
- const showInlinePlay = variant === "session-zero" || variant === "mixed";
4593
+ const showInlineFund = variant === "session-zero" || variant === "mixed";
4590
4594
  return /* @__PURE__ */ jsxs("div", { className: "bg-muted flex flex-col gap-6 rounded-[10px] p-5", children: [
4591
4595
  /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-2", children: [
4592
4596
  /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-1", children: [
@@ -4638,14 +4642,14 @@ function WalletBalanceView({
4638
4642
  }
4639
4643
  )
4640
4644
  ] }),
4641
- showInlinePlay && /* @__PURE__ */ jsx(
4645
+ showInlineFund && /* @__PURE__ */ jsx(
4642
4646
  "button",
4643
4647
  {
4644
4648
  type: "button",
4645
- disabled: !onPlay || !canPlay,
4646
- onClick: handlePlay,
4649
+ disabled: !onFundSession || !canFundSession,
4650
+ onClick: handleFundSession,
4647
4651
  className: "border-border flex h-10 min-w-20 cursor-pointer items-center justify-center rounded-[10px] border px-3 text-sm font-medium text-[#4fc77f] transition-opacity hover:opacity-80 disabled:cursor-not-allowed disabled:opacity-50",
4648
- children: "Play"
4652
+ children: "Fund session"
4649
4653
  }
4650
4654
  )
4651
4655
  ] }),
@@ -4669,10 +4673,10 @@ function WalletBalanceView({
4669
4673
  "button",
4670
4674
  {
4671
4675
  type: "button",
4672
- disabled: !onPlay || !canPlay,
4673
- onClick: handlePlay,
4676
+ disabled: !onFundSession || !canFundSession,
4677
+ onClick: handleFundSession,
4674
4678
  className: "bg-primary text-primary-foreground hover:bg-primary/90 flex h-10 flex-1 cursor-pointer items-center justify-center rounded-[10px] px-3 py-2 text-sm font-medium transition-colors disabled:cursor-not-allowed disabled:opacity-50",
4675
- children: "Play"
4679
+ children: "Fund session"
4676
4680
  }
4677
4681
  ),
4678
4682
  /* @__PURE__ */ jsx(
@@ -4709,10 +4713,34 @@ function WalletBalanceView({
4709
4713
  ] }) })
4710
4714
  ] });
4711
4715
  }
4716
+ function invokeGuarded(runRef, invoke, handlers) {
4717
+ const run = ++runRef.current;
4718
+ const isCurrent = () => runRef.current === run;
4719
+ let result;
4720
+ try {
4721
+ result = invoke();
4722
+ } catch (err) {
4723
+ if (isCurrent()) handlers.onError(err);
4724
+ return;
4725
+ }
4726
+ if (result == null || typeof result.then !== "function") {
4727
+ handlers.onSyncResult();
4728
+ return;
4729
+ }
4730
+ handlers.onAsyncStart();
4731
+ result.then(
4732
+ () => {
4733
+ if (isCurrent()) handlers.onSuccess();
4734
+ },
4735
+ (err) => {
4736
+ if (isCurrent()) handlers.onError(err);
4737
+ }
4738
+ );
4739
+ }
4712
4740
  function WalletModalContent({
4713
4741
  session,
4714
4742
  allowance,
4715
- onPlay,
4743
+ onFundSession,
4716
4744
  onEndSession,
4717
4745
  onDepositSuccess,
4718
4746
  onClose,
@@ -4727,7 +4755,10 @@ function WalletModalContent({
4727
4755
  const [depositBlocked, setDepositBlocked] = useState(false);
4728
4756
  const [withdrawPending, setWithdrawPending] = useState(false);
4729
4757
  const [endSessionError, setEndSessionError] = useState(null);
4758
+ const [fundSessionError, setFundSessionError] = useState(null);
4730
4759
  const endSessionRunRef = useRef(0);
4760
+ const fundSessionRunRef = useRef(0);
4761
+ const [pendingFundSession, setPendingFundSession] = useState(null);
4731
4762
  const prevAddressRef = useRef(address);
4732
4763
  useEffect(() => {
4733
4764
  const prev = prevAddressRef.current;
@@ -4739,10 +4770,13 @@ function WalletModalContent({
4739
4770
  setDepositBlocked(false);
4740
4771
  setWithdrawPending(false);
4741
4772
  setEndSessionError(null);
4773
+ setFundSessionError(null);
4774
+ setPendingFundSession(null);
4742
4775
  endSessionRunRef.current++;
4776
+ fundSessionRunRef.current++;
4743
4777
  }
4744
4778
  }, [address, hostedAuthConfig]);
4745
- const closeBlocked = depositBlocked || withdrawPending || view === "ending-session";
4779
+ const closeBlocked = depositBlocked || withdrawPending || view === "funding-session" || view === "ending-session";
4746
4780
  useEffect(() => {
4747
4781
  onCloseBlockedChange?.(closeBlocked);
4748
4782
  }, [closeBlocked, onCloseBlockedChange]);
@@ -4756,20 +4790,16 @@ function WalletModalContent({
4756
4790
  };
4757
4791
  const startEndSession = () => {
4758
4792
  if (!onEndSession) return;
4759
- const run = ++endSessionRunRef.current;
4760
4793
  setEndSessionError(null);
4761
- setView("ending-session");
4762
- Promise.resolve().then(() => onEndSession()).then(
4763
- () => {
4764
- if (endSessionRunRef.current !== run) return;
4765
- setView("withdraw");
4766
- },
4767
- (err) => {
4768
- if (endSessionRunRef.current !== run) return;
4794
+ invokeGuarded(endSessionRunRef, () => onEndSession(), {
4795
+ onSyncResult: () => setView("withdraw"),
4796
+ onAsyncStart: () => setView("ending-session"),
4797
+ onSuccess: () => setView("withdraw"),
4798
+ onError: (err) => {
4769
4799
  setEndSessionError(err instanceof Error ? err.message : null);
4770
4800
  setView("end-session-error");
4771
4801
  }
4772
- );
4802
+ });
4773
4803
  };
4774
4804
  const handleWithdraw = () => {
4775
4805
  if (session && onEndSession) {
@@ -4783,6 +4813,36 @@ function WalletModalContent({
4783
4813
  setEndSessionError(null);
4784
4814
  setView("balance");
4785
4815
  };
4816
+ const fundSession = (args) => {
4817
+ if (!onFundSession) return;
4818
+ setFundSessionError(null);
4819
+ setPendingFundSession(args);
4820
+ setAmount("");
4821
+ invokeGuarded(fundSessionRunRef, () => onFundSession(args), {
4822
+ onSyncResult: () => {
4823
+ setPendingFundSession(null);
4824
+ setView("balance");
4825
+ },
4826
+ onAsyncStart: () => setView("funding-session"),
4827
+ onSuccess: () => {
4828
+ setPendingFundSession(null);
4829
+ setView("balance");
4830
+ },
4831
+ onError: (err) => {
4832
+ setFundSessionError(err instanceof Error ? err.message : null);
4833
+ setView("fund-session-error");
4834
+ }
4835
+ });
4836
+ };
4837
+ const dismissFundSessionError = () => {
4838
+ fundSessionRunRef.current++;
4839
+ setFundSessionError(null);
4840
+ if (pendingFundSession) {
4841
+ setAmount(pendingFundSession.amount);
4842
+ setPendingFundSession(null);
4843
+ }
4844
+ setView("balance");
4845
+ };
4786
4846
  return /* @__PURE__ */ jsxs(Fragment, { children: [
4787
4847
  onClose && /* @__PURE__ */ jsx(
4788
4848
  "button",
@@ -4798,7 +4858,7 @@ function WalletModalContent({
4798
4858
  children: /* @__PURE__ */ jsx(CloseIcon, {})
4799
4859
  }
4800
4860
  ),
4801
- (view === "balance" || view === "ending-session" || view === "end-session-error") && /* @__PURE__ */ jsx("div", { className: "flex items-center px-5 py-4", children: /* @__PURE__ */ jsx("span", { className: "text-foreground text-xl leading-5 font-medium", children: appName }) }),
4861
+ (view === "balance" || view === "funding-session" || view === "fund-session-error" || view === "ending-session" || view === "end-session-error") && /* @__PURE__ */ jsx("div", { className: "flex items-center px-5 py-4", children: /* @__PURE__ */ jsx("span", { className: "text-foreground text-xl leading-5 font-medium", children: appName }) }),
4802
4862
  view === "balance" && /* @__PURE__ */ jsx(
4803
4863
  WalletBalanceView,
4804
4864
  {
@@ -4806,11 +4866,30 @@ function WalletModalContent({
4806
4866
  allowance,
4807
4867
  amount,
4808
4868
  onAmountChange: setAmount,
4809
- onPlay,
4869
+ onFundSession: onFundSession ? fundSession : void 0,
4810
4870
  onAddFunds: () => setView("deposit"),
4811
4871
  onWithdraw: handleWithdraw
4812
4872
  }
4813
4873
  ),
4874
+ view === "funding-session" && /* @__PURE__ */ jsx("div", { className: "bg-muted flex flex-col gap-6 rounded-[10px] p-5", children: /* @__PURE__ */ jsx(
4875
+ TransactionProgressView,
4876
+ {
4877
+ title: "Funding session...",
4878
+ steps: [{ label: "Waiting for the session to be funded", status: "active" }]
4879
+ }
4880
+ ) }),
4881
+ view === "fund-session-error" && /* @__PURE__ */ jsx("div", { className: "bg-muted flex flex-col gap-6 rounded-[10px] p-5", children: /* @__PURE__ */ jsx(
4882
+ TransactionErrorView,
4883
+ {
4884
+ title: "Could not fund session",
4885
+ message: fundSessionError ? `Your session could not be funded. (${fundSessionError})` : "Your session could not be funded.",
4886
+ onRetry: () => {
4887
+ if (pendingFundSession) fundSession(pendingFundSession);
4888
+ },
4889
+ onDismiss: dismissFundSessionError,
4890
+ retryLabel: "Try again"
4891
+ }
4892
+ ) }),
4814
4893
  view === "ending-session" && /* @__PURE__ */ jsx("div", { className: "bg-muted flex flex-col gap-6 rounded-[10px] p-5", children: /* @__PURE__ */ jsx(
4815
4894
  TransactionProgressView,
4816
4895
  {
@@ -4824,7 +4903,8 @@ function WalletModalContent({
4824
4903
  title: "Could not end session",
4825
4904
  message: endSessionError ? `Your game session could not be ended, so the funds committed to it are not available to withdraw yet. (${endSessionError})` : "Your game session could not be ended, so the funds committed to it are not available to withdraw yet.",
4826
4905
  onRetry: startEndSession,
4827
- onDismiss: dismissEndSessionError
4906
+ onDismiss: dismissEndSessionError,
4907
+ retryLabel: "Try again"
4828
4908
  }
4829
4909
  ) }),
4830
4910
  view === "withdraw" && /* @__PURE__ */ jsx(WithdrawModalContent, { onBack: exitWithdraw, onPendingChange: setWithdrawPending }),