Skip to content
Draft
Show file tree
Hide file tree
Changes from 1 commit
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
Prev Previous commit
temp: adding debug snap test button for testing
  • Loading branch information
Prithpal-Sooriya committed Jan 10, 2025
commit fa23db106757a19cc18d90a8bb0f9ec11e7c06f1
94 changes: 55 additions & 39 deletions src/components/AuthLogin/AuthModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,7 @@ import {
AUTH_WALLET_SESSION_NAME,
AUTH_WALLET_USER_PLAN,
} from "@site/src/lib/siwsrp/auth";
import {
REQUEST_PARAMS,
} from "@site/src/lib/constants";
import { REQUEST_PARAMS } from "@site/src/lib/constants";
import { MetamaskProviderContext } from "@site/src/theme/Root";

Modal.setAppElement("#__docusaurus");
Expand All @@ -39,7 +37,7 @@ export enum AUTH_LOGIN_STEP {
export enum WALLET_LINK_TYPE {
NO = "NO",
ONE = "ONE",
MULTIPLE = "MULTIPLE"
MULTIPLE = "MULTIPLE",
}

const ConnectingModal = () => {
Expand Down Expand Up @@ -161,7 +159,7 @@ const AuthModal = ({
const { pathname } = location;

const login = async () => {
console.log('in login')
console.log("in login");
setStep(AUTH_LOGIN_STEP.CONNECTING);
try {
// This will cause problems on mobile
Expand All @@ -171,49 +169,67 @@ const AuthModal = ({

// Try to connect wallet first
const accounts = await sdk.connect();
console.log({ accounts })
console.log({ accounts });

console.log('before accounts if')
console.log("before accounts if");
if (accounts && accounts.length > 0) {
setMetaMaskAccount(accounts[0]);
fetchLineaEns(accounts[0]);
const provider = sdk.getProvider();
setMetaMaskProvider(provider);
}

console.log('before get customProvider')
const customProvider = sdk.getProvider()
console.log('customProvider', customProvider)
console.log("before get customProvider");
const customProvider = sdk.getProvider();
console.log("customProvider", customProvider);

console.log("CUSTOM TEST -----------");

// console.log("GETTING WALLET ACCOUNTS");
// console.log(
// await customProvider.request({ method: "eth_accounts", params: [] })
// );
// console.log("GETTING WALLET ACCOUNTS DONE");

// console.log("GETTING SNAPS");
// try {
// const res = await customProvider.request({
// method: "wallet_getSnaps",
// });
// } catch (e) {
// console.error("GETTING SNAPS FAILED", e, e.message);
// }
// console.log("GETTING SNAPS DONE");

console.log("CUSTOM TEST END -----------");

// Call Profile SDK API to retrieve Hydra Access Token & Wallet userProfile
// Hydra Access Token will be used to fetch Infura API
console.log('before authenticateAndAuthorize')
console.log("before authenticateAndAuthorize");
const { accessToken, userProfile } = await authenticateAndAuthorize(
VERCEL_ENV as string,
// @ts-ignore
window.ethereum,
window.ethereum
);
console.log('accessToken', accessToken)
console.log('userProfile', userProfile)
console.log("accessToken", accessToken);
console.log("userProfile", userProfile);

console.log("before loginResponse")
console.log("before loginResponse");

const loginResponse = await (
await fetch(
`${DASHBOARD_URL}/api/wallet/login`,
{
...REQUEST_PARAMS("POST", {
hydra_token: accessToken,
token: "true",
}),
body: JSON.stringify({
profileId: userProfile.profileId,
redirect_to: window.location.href,
}),
},
)
await fetch(`${DASHBOARD_URL}/api/wallet/login`, {
...REQUEST_PARAMS("POST", {
hydra_token: accessToken,
token: "true",
}),
body: JSON.stringify({
profileId: userProfile.profileId,
redirect_to: window.location.href,
}),
})
).json();

console.log('loginResponse', loginResponse)
console.log("loginResponse", loginResponse);

if (!loginResponse) throw new Error("Something went wrong");

Expand All @@ -228,7 +244,7 @@ const AuthModal = ({
mmAuthSession: sessionStorage.getItem(AUTH_WALLET_SESSION_NAME),
walletPairing: data.pairing,
token: true,
}),
})
).toString("base64");

const walletAuthUrl = `${DASHBOARD_URL}/login?mm_auth=${mm_auth}&redirect_to=${session.redirect_to}`;
Expand All @@ -251,10 +267,10 @@ const AuthModal = ({
if (data.mfa?.enabled) {
const mm_auth = Buffer.from(
JSON.stringify({
step: 'verify',
step: "verify",
mmAuthSession: sessionStorage.getItem(AUTH_WALLET_SESSION_NAME),
dashboardSessionToken: token
}),
dashboardSessionToken: token,
})
).toString("base64");

const walletAuthUrl = `${DASHBOARD_URL}/login?mm_auth=${mm_auth}&redirect_to=${session.redirect_to}`;
Expand Down Expand Up @@ -289,7 +305,7 @@ const AuthModal = ({
`${DASHBOARD_URL}/api/v1/users/${userId}/projects`,
{
...REQUEST_PARAMS("GET", { Authorization: `Bearer ${token}` }),
},
}
);
const {
result: { projects },
Expand All @@ -301,7 +317,7 @@ const AuthModal = ({
`${DASHBOARD_URL}/api/v1/users/${userId}`,
{
...REQUEST_PARAMS("GET", { Authorization: `Bearer ${token}` }),
},
}
);
const {
result: {
Expand All @@ -324,12 +340,12 @@ const AuthModal = ({
}
};

console.log('just before use effect')
console.log("just before use effect");

useEffect(() => {
console.log('in use effect')
console.log('open', open)
console.log('step', step)
console.log("in use effect");
console.log("open", open);
console.log("step", step);
if (open && step == AUTH_LOGIN_STEP.CONNECTING) {
(async () => {
try {
Expand Down
157 changes: 154 additions & 3 deletions src/components/Faucet/Hero.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,10 @@
import React, { useContext, useEffect, useState } from "react";
import React, {
useCallback,
useContext,
useEffect,
useRef,
useState,
} from "react";
import Text from "@site/src/components/Text";
import Button from "@site/src/components/Button";
import Input from "@site/src/components/Input";
Expand All @@ -19,6 +25,60 @@ interface IHero {
isLimitedUserPlan?: boolean;
}

const useConsoleListener = () => {
const logsRef = useRef([]);
const [, forceUpdate] = useState(0); // State to force re-render

useEffect(() => {
const originalLog = console.log;
const originalError = console.error;

const stringify = (arg) => {
try {
return typeof arg === "object" ? JSON.stringify(arg) : arg;
} catch (e) {
return "[Unserializable Object]";
}
};

const handleLog = (args) => {
const message = args.map(stringify).join(" ");
logsRef.current = [...logsRef.current, `LOG: ${message}`];
};

const handleError = (args) => {
const message = args.map(stringify).join(" ");
logsRef.current = [...logsRef.current, `ERROR: ${message}`];
};

console.log = (...args) => {
handleLog([...args]);
originalLog.apply(console, args);
};

console.error = (...args) => {
handleError([...args]);
originalError.apply(console, args);
};

return () => {
console.log = originalLog;
console.error = originalError;
};
}, []);

const clearLogs = useCallback(() => {
logsRef.current = [];
forceUpdate((prev) => prev + 1); // Force re-render
}, []);

const refreshLogs = useCallback(() => {
forceUpdate((prev) => prev + 1); // Force re-render
}, []);

return [logsRef.current, clearLogs, refreshLogs] as const;
};

export default function Hero({
network,
className,
Expand All @@ -37,10 +97,11 @@ export default function Hero({
walletAuthUrl,
} = useContext(MetamaskProviderContext);

const [logs, clearLogs, refreshLogs] = useConsoleListener();

// const isMobile = sdk.platformManager.isMobile;
const isMobile = true
console.log(sdk.platformManager)
const isMobile = true;
console.log(sdk.platformManager);
const isExtensionActive = sdk.isExtensionActive();

const showInstallButton = !isExtensionActive && !isMobile;
Expand Down Expand Up @@ -123,6 +184,96 @@ export default function Hero({
: "Select your Infura account to get started and request ETH."
: "Enter your MetaMask wallet address and request ETH."}
</Text>
<details>
<summary>DEBUG LOGS ({logs.length})</summary>
<button onClick={clearLogs}>Clear Logs</button>
<button onClick={refreshLogs}>Refresh Logs</button>
<div
style={{
maxHeight: "200px", // Adjust the height as needed
overflowY: "auto",
whiteSpace: "nowrap", // Prevent text wrapping
border: "1px solid #ccc",
padding: "10px",
backgroundColor: "#f9f9f9",
}}
>
{logs.map((log, index) => (
<div
key={index}
style={{
fontFamily: "monospace",
marginBottom: "5px",
}}
>
{log}
</div>
))}
</div>
</details>
<button
onClick={async () => {
console.log("START TEST");

console.log("CONNECT ACCOUNTS");
const accounts = await sdk.connect();
console.log("CONNECT ACCOUNTS DONE", accounts);

console.log("GET PROVIDER");
const provider = sdk.getProvider();
console.log("GET PROVIDER DONE", provider);

console.log("WALLET RPC CALL");
const walletResponse = await provider.request({
method: "eth_accounts",
params: [],
});
console.log("WALLET RPC CALL DONE", walletResponse);

console.log("SNAP wallet_getSnaps CALL");
const wallet_getSnaps_response = await provider.request({
method: "wallet_getSnaps",
});
console.log(
"SNAP wallet_getSnaps CALL DONE",
wallet_getSnaps_response
);

console.log("SNAP wallet_requestSnaps CALL");
const wallet_requestSnaps_response = await provider.request({
method: "wallet_requestSnaps",
params: {
["npm:@metamask/message-signing-snap"]: {},
},
});
console.log(
"SNAP wallet_requestSnaps CALL DONE",
wallet_requestSnaps_response
);

// THIS REQUEST FAILS ON MOBILE!!
// ERROR: MetaMask - RPC Error: Property 'handleSnapRequest' doesn't exist {"code":-32603,"message":"Property 'handleSnapRequest' ...
console.log("SNAP wallet_invokeSnap_getPublicKey CALL");
const wallet_invokeSnap_getPublicKey_response =
await provider.request({
method: "wallet_invokeSnap",
params: {
snapId: "npm:@metamask/message-signing-snap",
request: { method: "getPublicKey" },
},
});
console.log(
"SNAP wallet_invokeSnap_getPublicKey CALL DONE",
wallet_invokeSnap_getPublicKey_response
);

console.log("END TEST");

refreshLogs();
}}
>
DEBUG TEST
</button>
<div className={styles.actions}>
{!!Object.keys(projects).length && (
<div className={styles.inputCont}>
Expand Down
Loading