Skip to content
Open
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 8 additions & 4 deletions packages/ethers-sdk/src/ethers-adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,12 +32,16 @@
private _provider: Provider;
uuid: string;

constructor(provider: Provider, signer?: Signer) {
constructor(provider: Provider, signer?: Signer, connectedSigner?: Signer) {
this._provider = provider;
this.uuid = crypto.randomUUID();
this._signer = signer
? signer.connect(this._provider)
: this._provider.getSigner();
if (connectedSigner) {
this._signer = connectedSigner;

Check warning on line 39 in packages/ethers-sdk/src/ethers-adapter.ts

View check run for this annotation

Codecov / codecov/patch

packages/ethers-sdk/src/ethers-adapter.ts#L39

Added line #L39 was not covered by tests
} else {
this._signer = signer
? signer.connect(this._provider)
: this._provider.getSigner();
}
Comment on lines +35 to +44
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I have to check again if this can be reverted

}

public async getSignerAddress() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,14 @@ import React, {
import { css, CSSProperties, styled } from "styled-components";
import { Grid } from "../../../ui/Grid";
import { Typography } from "../../../ui/Typography";
import { useAccount, useBreakpoints } from "../../../../hooks";
import { useAccount, useBreakpoints, usePrevious } from "../../../../hooks";
import { CaretDown, CaretUp, CheckCircle, Power } from "phosphor-react";
import { useIsRobloxLoggedIn } from "../../../../hooks/roblox/useIsRobloxLoggedIn";
import { useRobloxLogout } from "../../../../hooks/roblox/useRobloxLogout";
import { useRobloxConfigContext } from "../../../../hooks/roblox/context/useRobloxConfigContext";
import { ConnectWalletWithLogic } from "./ConnectWalletWithLogic";
import { useGetRobloxWalletAuth } from "../../../../hooks/roblox/useGetRobloxWalletAuth";
import { useRobloxBackendLogin } from "../../../../hooks/roblox/useRobloxBackendLogin";
import { useQuery } from "react-query";
import { useDisconnect } from "../../../../hooks/connection/useDisconnect";
import { useCookies } from "react-cookie";
import {
Expand All @@ -32,6 +31,8 @@ import ThemedButton from "../../../ui/ThemedButton";
import { maxWidthStepper } from "./styles";
import { productsPageSize, purchasedProductsPageSize, statuses } from "./const";
import { breakpoint } from "../../../../lib/ui/breakpoint";
import { useQuery } from "react-query";
import { mutationKeys } from "../../../../hooks/roblox/mutationKeys";

const stepToIcon = {
0: (
Expand Down Expand Up @@ -319,6 +320,7 @@ type ActiveStep = 0 | 1 | 2;
export const ConnectRoblox = forwardRef<HTMLDivElement, ConnectRobloxProps>(
({ step3, sellerId }, ref) => {
const { address = "" } = useAccount();
const prevAddress = usePrevious(address);
const [isSignUpDone, setSignUpDone] = useState<boolean>(false);
const [activeStep, setActiveStep] = useState<ActiveStep>(0);
const disconnect = useDisconnect();
Expand All @@ -345,28 +347,35 @@ export const ConnectRoblox = forwardRef<HTMLDivElement, ConnectRobloxProps>(
pageSize: purchasedProductsPageSize,
options: { enabled: false }
});
const disconnectWallet = useCallback(() => {
console.log("disconnectWallet()");
// setIsSigning(false);
// setIsWalletAuthenticated(false);
const removeWalletAuthCookie = useCallback(() => {
// const domain = backendOrigin
// .replace("https://", "")
// .replace("http://", "");
const isHttps = ((backendOrigin || "") as string).startsWith("https");
const sameSite = isHttps ? "none" : undefined;
removeCookie?.(WEB3AUTH_COOKIE_NAME, { path: "/", sameSite }); // TODO: no domain?
}, [backendOrigin, removeCookie]);
const disconnectWallet = useCallback(() => {
console.log("disconnectWallet()");
removeWalletAuthCookie();
disconnect({ isUserDisconnecting: false });
loadAvailableBosonProducts(); // Refresh products
loadUnavailableBosonProducts(); // Refresh products
loadBosonExchanges(); // Refresh exchanges
}, [
removeCookie,
removeWalletAuthCookie,
disconnect,
backendOrigin,
loadAvailableBosonProducts,
loadUnavailableBosonProducts,
loadBosonExchanges
]);
useEffect(() => {
// change of connected wallet address
// or disconnection of wallet
if (prevAddress !== address) {
removeWalletAuthCookie();
}
}, [address, removeWalletAuthCookie, prevAddress]);
const { data: robloxLoggedInData } = useIsRobloxLoggedIn({
sellerId,
options: {
Expand All @@ -385,30 +394,20 @@ export const ConnectRoblox = forwardRef<HTMLDivElement, ConnectRobloxProps>(
const { data: isAuthChecked } = useGetRobloxWalletAuth({
sellerId,
options: {
enabled: !!robloxLoggedInData?.isLoggedIn
enabled: !!robloxLoggedInData?.isLoggedIn && !!address
}
});
const {
mutateAsync: robloxBackendLoginAsync,
data: isWalletAuthenticatedSigned
} = useRobloxBackendLogin({
const robloxBackendLoginKey = mutationKeys.postWalletAuth({
address,
isAuthChecked,
robloxLoggedInData
});
const { mutateAsync: robloxBackendLoginAsync } = useRobloxBackendLogin({
loggedInData: robloxLoggedInData,
address,
sellerId,
mutationKey: [
address,
isAuthChecked?.walletAuth,
isAuthChecked,
robloxLoggedInData
],
options: {
onError: (...args) => {
console.error("robloxBackendLoginAsync error", { ...args });
disconnectWallet();
}
}
mutationKey: robloxBackendLoginKey
});
const isWalletAuthenticated =
isWalletAuthenticatedSigned || isAuthChecked?.walletAuth;
useEffect(() => {
if (!robloxLoggedInData?.isLoggedIn) {
setActiveStep(0);
Expand All @@ -418,24 +417,34 @@ export const ConnectRoblox = forwardRef<HTMLDivElement, ConnectRobloxProps>(
}, [robloxLoggedInData?.isLoggedIn, address]);

useQuery(
[robloxLoggedInData, address, isAuthChecked],
() => {
if (robloxLoggedInData?.claims && robloxLoggedInData?.nonce) {
robloxBackendLoginAsync();
} else {
console.error("robloxLoggedInData is not valid");
}
robloxBackendLoginKey,
async () => {
return await robloxBackendLoginAsync();
},
{
staleTime: Infinity,
retry: function (failureCount, error) {
const didUserReject: boolean =
typeof error === "object" &&
!!error &&
"message" in error &&
error.message === "User rejected the request.";
const shouldRetry = failureCount < 3 && !didUserReject;
return shouldRetry;
},
retryDelay: 1000,
onError: () => {
console.log("robloxBackendLoginAsync errored after all attemps");
// When all attempt have failed, force the wallet disconnection to avoid a dead end state of the app
disconnect({ isUserDisconnecting: false });
},
enabled:
!!robloxLoggedInData?.isLoggedIn &&
!!address &&
!!isAuthChecked &&
!isWalletAuthenticated
!isAuthChecked?.walletAuth &&
!!robloxLoggedInData?.claims &&
!!robloxLoggedInData?.nonce
}
);

const { mutateAsync: robloxLogoutAsync } = useRobloxLogout();
const nextLatestActiveStep = (step: ActiveStep) => {
setActiveStep((activeStep) => Math.max(step, activeStep) as ActiveStep);
Expand Down
18 changes: 14 additions & 4 deletions packages/react-kit/src/hooks/core-sdk/useCoreSdkWithContext.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { Token } from "../../components/widgets/finance/convertion-rate/Converti
import { useSigner } from "../connection/connection";
import { useMemo } from "react";
import { useExternalSigner } from "../../components/signer/useExternalSigner";
import { hooks } from "../..";
import { EthersAdapter, hooks } from "../..";

export function useCoreSDKWithContext(): CoreSDK {
const { envName, configId, metaTx } = useEnvContext();
Expand All @@ -15,9 +15,19 @@ export function useCoreSDKWithContext(): CoreSDK {
const defaultConfig = getEnvConfigById(envName, configId);
const overrides = useMemo(() => {
return externalSigner
? { web3Lib: externalSigner.externalWeb3LibAdapter }
: undefined;
}, [externalSigner]);
? {
web3Lib: externalSigner.externalWeb3LibAdapter
}
: signer && signer.provider
? {
web3Lib: new EthersAdapter(
signer.provider as providers.Web3Provider,
undefined,
signer
)
}
: undefined;
}, [externalSigner, signer]);
return hooks.useCoreSdk(
{
envName,
Expand Down
29 changes: 27 additions & 2 deletions packages/react-kit/src/hooks/roblox/mutationKeys.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
import {
GetLoggedInResponse,
GetWalletAuthResponse
} from "@bosonprotocol/roblox-sdk";

// eslint-disable-next-line @typescript-eslint/no-empty-interface, @typescript-eslint/no-unused-vars
interface GetMutationKey
// This any will be infered, it is more like generic, will be never seen as any in use
Expand Down Expand Up @@ -35,8 +40,28 @@ export const mutationKeys = {
userWallet,
pageSize
] as const,
getWalletAuth: ({ backendOrigin }: { backendOrigin: string }) =>
["get-wallet-auth", backendOrigin] as const
getWalletAuth: ({
backendOrigin,
address
}: {
backendOrigin: string;
address: string;
}) => ["get-wallet-auth", backendOrigin, address] as const,
postWalletAuth: ({
address,
isAuthChecked,
robloxLoggedInData
}: {
address: string;
isAuthChecked: GetWalletAuthResponse | undefined;
robloxLoggedInData: GetLoggedInResponse | null | undefined;
}) =>
[
"post-wallet-auth",
address,
!!isAuthChecked?.walletAuth,
robloxLoggedInData
] as const
} as const satisfies GetMutationKey;

export type MutationKey = (typeof mutationKeys)[keyof typeof mutationKeys];
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { useRobloxConfigContext } from "./context/useRobloxConfigContext";
import { mutationKeys } from "./mutationKeys";
import { GetWalletAuthResponse } from "@bosonprotocol/roblox-sdk";
import { productsPageSize } from "../../components/widgets/roblox/components/const";
import { useAccount } from "../connection/connection";
type UseGetRobloxWalletAuthProps = {
sellerId: string;
options: { enabled: boolean };
Expand All @@ -11,10 +12,11 @@ export const useGetRobloxWalletAuth = ({
sellerId,
options
}: UseGetRobloxWalletAuthProps) => {
const { address = "" } = useAccount();
const { backendOrigin } = useRobloxConfigContext();
const queryClient = useQueryClient();
return useQuery(
mutationKeys.getWalletAuth({ backendOrigin }),
mutationKeys.getWalletAuth({ backendOrigin, address }),
async () => {
const response = await fetch(`${backendOrigin}/wallet-auth`, {
credentials: "include"
Expand Down
21 changes: 8 additions & 13 deletions packages/react-kit/src/hooks/roblox/useRobloxBackendLogin.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { formatBytes32String } from "ethers/lib/utils";
import { useAccount, useWeb3SignTypedData } from "../connection/connection";
import { useWeb3SignTypedData } from "../connection/connection";
import { GetLoggedInResponse } from "@bosonprotocol/roblox-sdk";
import { useMutation } from "react-query";
import { useDisconnect } from "../connection/useDisconnect";
import { usePostRobloxWalletAuth } from "./usePostRobloxWalletAuth";
import { mutationKeys } from "./mutationKeys";

const domainValues = {
name: "Boson-Roblox-Bridge",
Expand Down Expand Up @@ -49,8 +49,8 @@ export function prepareAuthSignature(
type UseRobloxBackendLoginProps = {
loggedInData: GetLoggedInResponse | undefined | null;
sellerId: string;
mutationKey: unknown[];

mutationKey: ReturnType<(typeof mutationKeys)["postWalletAuth"]>;
address: string;
options?: {
onError?:
| ((
Expand All @@ -66,12 +66,11 @@ export const useRobloxBackendLogin = ({
loggedInData,
sellerId,
mutationKey,
options
options,
address
}: UseRobloxBackendLoginProps) => {
const { mutateAsync: signTypedDataAsync } = useWeb3SignTypedData();
const { mutateAsync: verifySignature } = usePostRobloxWalletAuth();
const { address = "" } = useAccount();
const disconnect = useDisconnect();
return useMutation(
mutationKey,
async () => {
Expand All @@ -98,16 +97,12 @@ export const useRobloxBackendLogin = ({
},
{
...options,
onSettled: (data, error) => {
retry: 0,
onSettled: (data) => {
if (data) {
console.log("useSignTypedData success", data);
verifySignature({ signature: data, sellerId, address });
}
if (error) {
console.error("useSignTypedData error: " + error);
// When all attempt have failed, force the wallet disconnection to avoid a dead end state of the app
disconnect({ isUserDisconnecting: false });
}
}
}
);
Expand Down
Loading