Ethereum Boilerplate Questions

Try downgrading your Nodejs version to 16.0 and try again

Hey folks, I still couldnā€™t figure out why my swap ainā€™t working, the latest version from 1inch is installed. It says Failed to load resource: the server responded with a status of 400 ()
promiseUtils.js:44
Moralis: You are not using the latest version of the SDK. Please update it as soon as possible to enjoy the newest features. Most recent version: 1.9.1
console.warn @ promiseUtils.js:44

My Dapp:
Naga Swap - Dex

This isnā€™t an issue, itā€™s warning you can ignore

You can debug this easier in development mode and give more info rather than checking in production as only eth isnā€™t working properly as checked

thanks for your helpā€¦
so looks like im getting closerā€¦

Compiled successfully!

You can now view whalealerts in the browser.     

  Local:            http://localhost:3000     

it opens a tab in Waterfox but i cant put anything in the fieldsā€¦ nothing works

here goes my console result, please have a check , seems like the server ainā€™t responding

You can check the console for possible errors

i didnt get any errorsā€¦ says also no problems
ran a debug on node.js

C:\Program Files (x86)\nodejs\node.exe .\Downloads\moralis-whale-alerts-main\src\Cloud\CloudFile.js
Process exited with code 1
Uncaught ReferenceError ReferenceError: Moralis is not defined
    at <anonymous> (c:\Users\laliruto\Downloads\moralis-whale-alerts-main\src\Cloud\CloudFile.js:56:1)
    at Module._compile (internal/modules/cjs/loader:1105:14)
    at Module._extensions..js (internal/modules/cjs/loader:1159:10)
    at Module.load (internal/modules/cjs/loader:981:32)
    at Module._load (internal/modules/cjs/loader:822:12)
    at executeUserEntryPoint (internal/modules/run_main:77:12)
    at <anonymous> (internal/main/run_main_module:17:47)

just now ran npm start againā€¦ a windows firewall window opened upā€¦ i gave node.js accessā€¦ could the firewall settings be a problem?

so i get the tab to open up, but cant enter anythingā€¦

i changed firewall settings and tried on different browsersā€¦ still cant enter anythingā€¦
:roll_eyes:

Can you screenshot your browser console (F12) for any errors.

You can click into the 400 links to see what the errors are. If the error is required param address not provided as soon as you load the swap components, this is a problem with the original Ethereum Boilerplate. Have you tried doing a swap?

Do you have the Onramper / Fiat plugin installed?

you are rightā€¦ there are 2 errors

import { useState, useCallback, useEffect } from "react";
import { setMultipleDataToUser, SetUserData } from "./utils/setUserData";
import { Web3Provider } from "./_useMoralisWeb3";
import { AuthError } from "src";
import MoralisType from "moralis";
import { Environment } from "./_useMoralisInit";

export enum AuthenticationState {
  UNDEFINED = "undefined",
  UNAUTHENTICATED = "unauthenticated",
  AUTHENTICATED = "authenticated",
  AUTHENTICATING = "authenticating",
  LOGGING_OUT = "logging_out",
  ERROR = "error",
}

export type Authentication =
  | {
      state: AuthenticationState.UNDEFINED;
      error: null;
    }
  | {
      state: AuthenticationState.UNAUTHENTICATED;
      error: null;
    }
  | {
      state: AuthenticationState.AUTHENTICATED;
      error: null;
    }
  | {
      state: AuthenticationState.AUTHENTICATING;
      error: null;
    }
  | {
      state: AuthenticationState.ERROR;
      error: Error;
    }
  | {
      state: AuthenticationState.LOGGING_OUT;
      error: null;
    };

const initialAuth: Authentication = {
  state: AuthenticationState.UNDEFINED,
  error: null,
};

export type AuthType = "dot" | "polkadot" | "kusama" | "erd" | "elrond";

export interface AuthenticateOptions {
  onError?: (error: Error) => void;
  onSuccess?: (user: MoralisType.User) => void;
  onComplete?: () => void;
  throwOnError?: boolean;
  type?: AuthType;
  provider?: Web3Provider;
  chainId?: number;
  signingMessage?: string;
}

export interface SignupOptions {
  onError?: (error: Error) => void;
  onSuccess?: (user: MoralisType.User) => void;
  onComplete?: () => void;
  throwOnError?: boolean;
}
export interface LoginOptions {
  onError?: (error: Error) => void;
  onSuccess?: (user: MoralisType.User) => void;
  onComplete?: () => void;
  throwOnError?: boolean;
  usePost?: boolean;
}

export interface LogoutOptions {
  onError?: (error: Error) => void;
  onSuccess?: () => void;
  onComplete?: () => void;
  throwOnError?: boolean;
}

export type Login = (
  username: string,
  password: string,
  options?: LoginOptions,
) => Promise<void>;

export type Signup = (
  username: string,
  password: string,
  email?: string,
  otherFields?: SetUserData,
  options?: SignupOptions,
) => Promise<void>;

export type OnAccountChanged = (account: string) => void;

export interface UseMoralisAuthOptions {
  onAccountChanged?: OnAccountChanged;
  setUser?: (user: MoralisType.User | null) => void;
  Moralis: MoralisType;
  environment: Environment;
}

const defaultUseMoralisAuthOptions = (
  moralis: MoralisType,
): UseMoralisAuthOptions => ({
  // We will override this right away, we just want to
  setUser: () => {},
  Moralis: moralis,
  environment: "browser",
});

/**
 * Hook that handles all authentication logic and returns the correct auth state
 * and its functions
 */
export const _useMoralisAuth = (options: UseMoralisAuthOptions) => {
  const { onAccountChanged, Moralis, environment } = {
    ...defaultUseMoralisAuthOptions(options.Moralis),
    ...options,
  };

  const setUser = options.setUser!;
  const [auth, setAuth] = useState<Authentication>(initialAuth);
  const [hasOnAccountChangeListener, setHasOnAccountChangeListener] =
    useState(false);

  /**
   * Authenticates the user by calling the Moralis.Web3.authenticate function
   * The auth state will update upon successful/error
   * For direct feedback, a callback can be provided
   */
  const authenticate = useCallback(
    async ({
      onComplete,
      onError,
      onSuccess,
      throwOnError,
      ...rest
    }: AuthenticateOptions = {}) => {
      setAuth({
        state: AuthenticationState.AUTHENTICATING,
        error: null,
      });

      try {
        // @ts-ignore
        const user = await Moralis.authenticate(rest);

        setUser(user);

        setAuth({
          state: AuthenticationState.AUTHENTICATED,
          error: null,
        });

        if (onSuccess) {
          onSuccess(user);
        }
      } catch (error) {
        setAuth({ state: AuthenticationState.ERROR, error });
        if (onError) {
          onError(error);
        }
        if (throwOnError) {
          throw error;
        }
      } finally {
        if (onComplete) {
          onComplete();
        }
      }
    },
    [],
  );

  /**
   * signup the user in with provided credentials
   */
  const signup = useCallback<Signup>(
    async (
      username: string,
      password: string,
      email?: string,
      otherFields = {},
      { throwOnError, onSuccess, onError, onComplete } = {},
    ) => {
      setAuth({
        state: AuthenticationState.AUTHENTICATING,
        error: null,
      });

      const newUser = new Moralis.User();

      setMultipleDataToUser(
        {
          username,
          password,
          email,
          ...otherFields,
        },
        newUser,
      );

      try {
        const user = await newUser.signUp();
        setAuth({
          state: AuthenticationState.AUTHENTICATED,
          error: null,
        });
        setUser(user);
        if (onSuccess) {
          onSuccess(user);
        }
      } catch (error) {
        setAuth({ state: AuthenticationState.ERROR, error });
        if (throwOnError) {
          throw error;
        }
        if (onError) {
          onError(error);
        }
      } finally {
        if (onComplete) {
          onComplete();
        }
      }
    },
    [],
  );
  /**
   * Logs the user in with provided credentials
   */
  const login = useCallback<Login>(
    async (
      username,
      password,
      { usePost, throwOnError, onError, onSuccess, onComplete } = {},
    ) => {
      setAuth({
        state: AuthenticationState.AUTHENTICATING,
        error: null,
      });

      try {
        const user = await Moralis.User.logIn(username, password, {
          // @ts-ignore: missing types
          usePost,
        });
        setAuth({
          state: AuthenticationState.AUTHENTICATED,
          error: null,
        });
        setUser(user);
        if (onSuccess) {
          onSuccess(user);
        }
      } catch (error) {
        setAuth({ state: AuthenticationState.ERROR, error });
        if (throwOnError) {
          throw error;
        }
        if (onError) {
          onError(error);
        }
      } finally {
        if (onComplete) {
          onComplete();
        }
      }
    },
    [],
  );

  /**
   * Logs the user out via Moralis.User.logOut and handles the internal state
   */
  const logout = useCallback(
    async ({
      throwOnError,
      onError,
      onSuccess,
      onComplete,
    }: LogoutOptions = {}) => {
      setAuth({
        state: AuthenticationState.AUTHENTICATING,
        error: null,
      });

      try {
        await Moralis.User.logOut();
        setAuth({ state: AuthenticationState.UNAUTHENTICATED, error: null });
        setUser(null);
        if (onSuccess) {
          onSuccess();
        }
      } catch (error) {
        setAuth({ state: AuthenticationState.ERROR, error });
        // Set user to the currentUser (we don't know if the logout was successfull)
        setUser(Moralis.User.current() ?? null);
        if (throwOnError) {
          throw error;
        }
        if (onError) {
          onError(error);
        }
      } finally {
        if (onComplete) {
          onComplete();
        }
      }
    },
    [],
  );

  /**
   * Update the auth state if the user already ahs authenticated before
   */
  useEffect(() => {
    try {
      const currentUser = Moralis.User.current();
      if (currentUser) {
        setAuth({
          state: AuthenticationState.AUTHENTICATED,
          error: null,
        });
        setUser(currentUser);
      } else {
        throw new Error("Let it catch");
      }
    } catch (error) {
      setAuth({
        state: AuthenticationState.UNAUTHENTICATED,
        error: null,
      });
      setUser(null);
    }
  }, []);

  /**
   * Assign web3 Listener to handle change of accounts
   *
   * Important!: these eventListeners cannot be cleaned up, so don't reassign it
   * See https://github.com/MetaMask/metamask-extension/issues/10873
   *
   * The drawback of this is that we cannot update these function via a React state
   * // TODO: find a way to work around this
   */
  useEffect(() => {
    if (hasOnAccountChangeListener) {
      return;
    }

    if (environment !== "browser") {
      // Currently only support browser environment
      return;
    }

    if (!window) {
      // eslint-disable-next-line no-console
      console.warn("No window object found");
      return;
    }

    try {
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      const ethereum = (window as any).ethereum;

      if (!ethereum) {
        // eslint-disable-next-line no-console
        console.warn("No window.ethereum found");
        return;
      }
      ethereum.on("accountsChanged", async (accounts: string[]) => {
        const account = accounts[0];

        if (onAccountChanged) {
          onAccountChanged(account);
        }
      });
    } catch (error) {
      // eslint-disable-next-line no-console
      console.warn(error.message);
    }

    setHasOnAccountChangeListener(true);
  }, [hasOnAccountChangeListener]);

  const isAuthenticated = auth.state === AuthenticationState.AUTHENTICATED;
  const isUnauthenticated = auth.state === AuthenticationState.UNAUTHENTICATED;
  const isAuthenticating = auth.state === AuthenticationState.AUTHENTICATING;
  const hasAuthError = auth.state === AuthenticationState.ERROR;
  const isLoggingOut = auth.state === AuthenticationState.LOGGING_OUT;
  const isAuthUndefined = auth.state === AuthenticationState.UNDEFINED;

  return {
    auth,
    authenticate,
    signup,
    login,
    logout,
    authError: auth.error as AuthError,
    isAuthenticated,
    isUnauthenticated,
    isAuthenticating,
    hasAuthError,
    isLoggingOut,
    isAuthUndefined,
  };
};

It should be Moralis.start Connect with Vanilla JS - Moralis. Which project or tutorial are you following, this thread is for the Ethereum Boilerplate. Where is this last file from?

For the last process is not defined error, you can reload the page. Or to fix, install [email protected] and add the following to your package.json (use ā€œoverridesā€ instead of ā€œresolutionsā€ for npm):

"resolutions": {
  "react-error-overlay": "6.0.9"
}

hey,
i am trying to make a whale alerts dappā€¦ from ashbeech/moralis-whale-alerts


he talks about the boilerplate he used for this dappā€¦
am i mistaken?
thanks in advance

That project is quite outdated and is using very old versions of Moralis / react-moralis. You can try updating these packages, but there will likely be other things breaking. You can check the docs if you need to update any code for any outdated function syntax.

ok, i will try and update some filesā€¦
should i start a new thread? its a great dapp and i would love to get it working
thanks

1 Like

Yes you can do that.

{ā€œcodeā€:141,ā€œerrorā€:ā€œInvalid hex numberā€} - gtczd8o8ohzz.usemoralis.com:2053/server/functions/getTokenPrice:1

Failed to load resource: the server responded with a status of 400 ()

I do have onramper installed

I have seen that error occasionally, itā€™s an issue with the boilerplate. Does your app / swap page still work?