> ## Documentation Index
> Fetch the complete documentation index at: https://docs.dynamic.xyz/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# useEmbeddedWallet

<Card title="Recommended: JavaScript SDK with React Hooks" icon="react" color="#4779FE">
  For new React apps, we recommend the JavaScript SDK with React Hooks (`@dynamic-labs-sdk/react-hooks`) instead of the legacy React SDK documented here. The JS SDK comes with many benefits such as a much smaller bundle size and other optimizations. Use the [React quickstart (JavaScript SDK)](/javascript/reference/react-quickstart) to get started.
</Card>

This hook gives you control over when you create an embedded wallet for any given user, the ability to check if a user currently has an embedded wallet, the ability to create and validate user sessions, and other helpful methods.

You can also utilize the methods in combination with each other to create a fully custom UI implementation of embedded wallet onboarding flows.

## Usage

```javascript theme={"system"}
import { useEmbeddedWallet } from “@dynamic-labs/sdk-react-core”

 // component declaration and all other logic you might need
const {
    createEmbeddedWallet,
    createEmbeddedWalletAccount,
    createOrRestoreSession,
    createPasskey,
    getPasskeys,
    isLoadingEmbeddedWallet,
    isSessionActive,
    sendOneTimeCode,
    userHasEmbeddedWallet
} = useEmbeddedWallet();

const oneTimeCodeSent = useRef(false);
```

### Create embedded wallet

Create an embedded wallet at any point.

#### Method Signature

```typescript theme={"system"}
createEmbeddedWallet( chains?: ChainEnum[], options?: { webAuthnAttestation: WebAuthnAttestation }): Promise<Wallet | undefined>
```

#### Example

```javascript theme={"system"}
const onClick = async () => {
    if(!userHasEmbeddedWallet()) {
      try {
        const walletId = await createEmbeddedWallet();
        // do whatever you want with that Id
      } catch(e) {
        // handle error
      }
    }
}

return (
    <button onClick={() => onClick()}>Create Wallet</button>
)
```

### Create embedded wallet account

Used to create an embedded wallet on an additional chain if a user already has an embedded wallet on another chain.

```typescript theme={"system"}
import { EmbeddedWalletChainEnum } from '@dynamic-labs/sdk-api-core';

createEmbeddedWalletAccount({ chain: EmbeddedWalletChainEnum.Evm }): Promise<UserProfile | undefined>
```

### Create session

Create an embedded wallet session whenever you need to validate the user authenticity to perform transactions without the need to prompt user confirmation every single time.

#### Steps

1. First you need to trigger the sending of a one-time code for authenticity validation, the `sendOneTimeCode` method handles this.
2. Once the user enters the one-time code, the `createOrRestoreSession` method will initiate a session as long as the code is valid.

```javascript theme={"system"}
const onSendOneTimeCodeHandler = async () => {
    if(!isSessionActive) {
      try {
        await sendOneTimeCode();
        oneTimeCodeSent.current = true;
        // do whatever you want with that Id
      } catch(e) {
        // handle error
      }
    }
}

const onCreateSessionHandler: FormEventHandler<HTMLFormElement> = async (event) => {
    try {
      event.stopPropagation();
      event.preventDefault();

      if (!primaryWallet || !userHasEmbeddedWallet()) return;

      const otc = event.currentTarget.otc.value;

      await createOrRestoreSession({ oneTimeCode: otc })
        .then((result) => setResult(result))
        .catch((error) => setResult(JSON.stringify(error, null, 2)));
    } catch (err) {
      logger.error(err);
    }
  };

return (
  <>
    {!oneTimeCodeSent.current && <button onClick={onSendOneTimeCodeHandler}>Start session</button>}
    {oneTimeCodeSent.current && (
      <form onSubmit={onCreateSessionHandler} className='create-session-method'>
      <Typography>
        Enter one-time code sent to email to create a session
      </Typography>

      <input required name='otc' type='text' placeholder='One-time code' />
      <br />
      <Button type='submit'>Create session</Button>

    </form>
    )}
  </>
)
```

### Create passkey

Create a passkey whenever you need to validate the user authenticity to perform a transaction or to access a specific feature as well as to handle cases where the user lost access to their device.

#### Steps

1. If the user is not in an active session, we first need to send them a one-time code for authenticity validation.
2. Once the user enters the one-time code, the `createPasskey` method will validate it and create a passkey.

```javascript theme={"system"}
const onSendOneTimeCodeHandler = async () => {
    if(!isSessionActive) {
      try {
        await sendOneTimeCode();
        oneTimeCodeSent.current = true;
        // do whatever you want with that Id
      } catch(e) {
        // handle error
      }
    }
}

const onCreatePasskeyHandler: FormEventHandler<HTMLFormElement> = async (event) => {
    try {
      event.stopPropagation();
      event.preventDefault();

      if (!primaryWallet || !userHasEmbeddedWallet() || !isSessionActive) return;

      const otc = event.currentTarget.otc.value;

      await createPasskey({ oneTimeCode: otc })
        .then((result) => setResult(result))
        .catch((error) => setResult(JSON.stringify(error, null, 2)));
    } catch (err) {
      logger.error(err);
    }
  };

return (
  <>
    {!oneTimeCodeSent.current && <button onClick={onSendOneTimeCodeHandler}>Start passkey creation</button>}
    {oneTimeCodeSent.current && (
      <form onSubmit={onCreatePasskeyHandler} className='create-session-method'>
      <Typography>
        Enter one-time code sent to email to create a new passkey
      </Typography>

      <input required name='otc' type='text' placeholder='One-time code' />
      <br />
      <Button type='submit'>Create passkey</Button>

    </form>
    )}
  </>
)
```

## Return Values

* **createEmbeddedWallet** returns a promise which will resolve to a wallet ID once the creation flow has been successful.
* **createEmbeddedWalletAccount** returns a promise which will resolve to a user once the creation flow has been successful.
* **createOrRestoreSession** returns a promise which will resolve to a string `session_created` or `session_restored` if the session has been created or restored successfully.
* **createPasskey** returns a promise which will resolve to a passkey data `(attestation, challenge, displayName)` once the creation flow has been successful.
* **getPasskeys** returns a promise which will resolve to an array of passkeys info.
* **isLoadingEmbeddedWallet** returns a boolean which will be true if the embedded wallet is being created.
* **isSessionActive** returns a boolean which will be true if the user has an active session.
* **sendOneTimeCode** returns a promise which will resolve to a string `code_sent` if the code has been sent successfully.
* **userHasEmbeddedWallet** returns a boolean which will be true if the user has an embedded wallet at that time.
