Skip to content

Commit

Permalink
cleaned up
Browse files Browse the repository at this point in the history
  • Loading branch information
andrewkmin committed Aug 21, 2024
1 parent b168960 commit d0e4c70
Show file tree
Hide file tree
Showing 9 changed files with 62 additions and 162 deletions.
8 changes: 0 additions & 8 deletions examples/with-wallet-stamper/src/app/dashboard/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,8 @@ import User from "@/components/user";

import Image from "next/image";

import { TurnkeyIframeContainerId } from "@/lib/turnkey";

import { useTurnkey as useReactTurnkey } from "@turnkey/sdk-react";


export default function Dashboard() {
const { turnkey, authIframeClient } = useReactTurnkey();

Expand Down Expand Up @@ -43,11 +40,6 @@ export default function Dashboard() {
<div className="flex flex-col items-center justify-center mb-auto mt-52 w-full">
<User />
</div>
{/* <div
className="iframe"
id={TurnkeyIframeContainerId}
style={{ display: "none" }}
/> */}
</main>
);
}
25 changes: 6 additions & 19 deletions examples/with-wallet-stamper/src/app/layout.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,11 @@
"use client"
"use client";

import type { Metadata } from "next";
import { Inter } from "next/font/google";
import "./globals.css";
import { Providers } from "@/components/providers";

import { TurnkeyIframeContainerId } from "@/lib/turnkey";

import { TurnkeyProvider, useTurnkey } from "@turnkey/sdk-react";
import { TurnkeyProvider as TurnkeyReactProvider } from "@turnkey/sdk-react";

const inter = Inter({ subsets: ["latin"] });

Expand All @@ -27,23 +25,12 @@ const turnkeyConfig = {

export default function RootLayout({ children }: RootLayoutProps) {
return (
<html
lang="en"
suppressHydrationWarning
className="dark"
>
<TurnkeyProvider config={turnkeyConfig}>
<html lang="en" suppressHydrationWarning className="dark">
<TurnkeyReactProvider config={turnkeyConfig}>
<body className={inter.className}>
<Providers>
{children}
{/* <div
className="iframe"
id={TurnkeyIframeContainerId}
style={{ display: "none" }}
/> */}
</Providers>
<Providers>{children}</Providers>
</body>
</TurnkeyProvider>
</TurnkeyReactProvider>
</html>
);
}
8 changes: 2 additions & 6 deletions examples/with-wallet-stamper/src/components/auth/auth.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import { AuthOptions } from "./auth.options";
import { Tabs, TabsContent } from "../ui/tabs";
import { ConnectWallet } from "../connect-wallet";
import { useTurnkey } from "../turnkey-provider";
import { Email, TurnkeyIframeContainerId } from "@/lib/turnkey";
import { Email } from "@/lib/turnkey";

import { useTurnkey as useReactTurnkey } from "@turnkey/sdk-react";

Expand Down Expand Up @@ -89,10 +89,7 @@ export function AuthForm({ isSignUp = false }) {
<CardContent className="flex flex-col gap-4">
<ConnectWallet />
{walletClient && (
<Button
variant="secondary"
onClick={handleSignUp}
>
<Button variant="secondary" onClick={handleSignUp}>
{authenticating && (
<Loader className="w-4 h-4 mr-2 animate-spin" />
)}
Expand Down Expand Up @@ -132,7 +129,6 @@ export function AuthForm({ isSignUp = false }) {
</TabsContent>
</Tabs>
</CardContent>
<div id={TurnkeyIframeContainerId}></div>
</Card>
);
}
9 changes: 2 additions & 7 deletions examples/with-wallet-stamper/src/components/providers.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,14 +22,9 @@ export function Providers({ children }: { children: React.ReactNode }) {

return (
<ConnectionProvider endpoint={endpoint}>
<WalletProvider
autoConnect
wallets={wallets}
>
<WalletProvider autoConnect wallets={wallets}>
<WalletModalProvider>
<TurnkeyProvider>
{children}
</TurnkeyProvider>
<TurnkeyProvider>{children}</TurnkeyProvider>
</WalletModalProvider>
</WalletProvider>
</ConnectionProvider>
Expand Down
118 changes: 23 additions & 95 deletions examples/with-wallet-stamper/src/components/turnkey-provider.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,4 @@
import React, {
createContext,
useContext,
useState,
useEffect,
useRef,
} from "react";
import React, { createContext, useContext, useState, useEffect } from "react";
// import { TurnkeyProvider, useTurnkey } from "@turnkey/sdk-react";

import { createActivityPoller, type TurnkeyClient } from "@turnkey/http";
Expand Down Expand Up @@ -33,13 +27,7 @@ import {
WalletStamper,
EvmWalletInterface,
} from "@turnkey/wallet-stamper";
import {
createWebauthnStamper,
createIframeStamper,
Email,
TurnkeyIframeContainerId,
TurnkeyIframeElementId,
} from "@/lib/turnkey";
import { createWebauthnStamper, Email } from "@/lib/turnkey";
import { createUserSubOrg, getSubOrgByPublicKey } from "@/lib/server";
import { ChainType } from "@/lib/types";
import { useWallet } from "@solana/wallet-adapter-react";
Expand All @@ -61,7 +49,7 @@ const TurnkeyContext = createContext<{
getWallets: () => Promise<Wallet[]>;
authenticating: boolean;
user: User | null;
createWallet: (walletName: string) => Promise<void>;
createWallet: (walletName: string, callback: any) => Promise<void>;
}>({
turnkey: null,
client: null,
Expand Down Expand Up @@ -132,24 +120,18 @@ export const TurnkeyProvider: React.FC<TurnkeyProviderProps> = ({

const getActiveIframeClient =
async (): Promise<TurnkeyIframeClient | null> => {
console.log("getting active");
let currentClient = null;

if (!iframeClient) {
console.log("returning null");
return null;
}

console.log("yoyo");

const localCredential = localStorage.getItem("CREDENTIAL_BUNDLE");
console.log("local credential", localCredential);

const injected = await iframeClient?.injectCredentialBundle(
localCredential!
);

console.log("injected", injected);
if (injected) {
await iframeClient?.getWhoami({
organizationId: user?.organizationId ?? NEXT_PUBLIC_ORGANIZATION_ID!,
Expand All @@ -160,28 +142,19 @@ export const TurnkeyProvider: React.FC<TurnkeyProviderProps> = ({
const whoami = await iframeClient!.getWhoami({
organizationId: user?.organizationId ?? NEXT_PUBLIC_ORGANIZATION_ID!,
});
console.log("whoami", whoami);

try {
console.log(
"trying",
iframeClient,
user?.organizationId,
NEXT_PUBLIC_ORGANIZATION_ID
);
// check if the iframeClient is active
const whoami = await iframeClient!.getWhoami({
organizationId: user?.organizationId ?? NEXT_PUBLIC_ORGANIZATION_ID!,
});
console.log("whoami", whoami);
currentClient = iframeClient;
} catch (error: any) {
console.error("unable to getwhoami", error);

try {
// if not, check if there's a valid credential in localStorage, and try to initialize an iframeClient with it
const localCredential = localStorage.getItem("CREDENTIAL_BUNDLE");
console.log("local credential", localCredential);

if (localCredential) {
const injected = await iframeClient?.injectCredentialBundle(
Expand All @@ -207,11 +180,6 @@ export const TurnkeyProvider: React.FC<TurnkeyProviderProps> = ({
email?: Email,
chainType: ChainType = ChainType.SOLANA
) {
console.log({
email,
chainType,
});

setAuthenticating(true);
let publicKey = null;
if (chainType === ChainType.SOLANA) {
Expand Down Expand Up @@ -241,22 +209,13 @@ export const TurnkeyProvider: React.FC<TurnkeyProviderProps> = ({
}

async function getWallets(): Promise<Wallet[]> {
console.log("trying to get wallets");

console.log({
walletClient,
userorgid: user?.organizationId,
});

if (!walletClient || !user?.organizationId) {
return [];
}

let wallets = [];

console.log("before active");
const iframeClient = await getActiveIframeClient();
console.log("iframe client", iframeClient);

if (iframeClient) {
const { wallets: walletsResponse } = await iframeClient.getWallets({
Expand All @@ -270,35 +229,26 @@ export const TurnkeyProvider: React.FC<TurnkeyProviderProps> = ({
wallets = walletsResponse;
}

console.log("wallets response", wallets);

return wallets as unknown as Wallet[];
}

// Sign in with wallet and create an active session
async function signInWithWallet(email?: Email): Promise<User | null> {
let whoami: User | null = null;

console.log("yo we inside");
console.log({
walletClient,
email,
});

if (!walletClient) {
return null;
}

// If no email is provided, log in with wallet. Will require multiple approvals.
if (!email) {
console.log("inside no email case");

const publicKey = (wallet as SolanaWalletInterface)?.recoverPublicKey();
const { organizationIds } = await getSubOrgByPublicKey(publicKey); // this requires one tap?
const { organizationIds } = await getSubOrgByPublicKey(publicKey); // One wallet request
const organizationId = organizationIds[0];

if (walletClient) {
try {
// another tap
// Another wallet request
whoami = await walletClient.getWhoami({
organizationId,
});
Expand All @@ -312,29 +262,17 @@ export const TurnkeyProvider: React.FC<TurnkeyProviderProps> = ({
return whoami;
}

// Create session
// Email is required for the next bit.
// If you do not have their email, you will have to create a session with another tap
// Create an iframe session. Email is required for the next bit.
try {
const activityPoller = createActivityPoller({
client: walletClient,
requestFn: walletClient.createReadWriteSession,
});

console.log("email... again", email);
// console.log("iframe related clients", {
// iframeClient,
// iframeStamper,
// publicKey: iframeClient!.iframePublicKey,
// publicKey2: iframeStamper!.publicKey(),
// publicKey3: iframeStamper!.iframePublicKey,
// });

const completedActivity = await activityPoller({
type: "ACTIVITY_TYPE_CREATE_READ_WRITE_SESSION",
timestampMs: new Date().getTime().toString(),
// organizationId: organizationId, // this can also accept parent org if we don't know the suborg in advance
organizationId: NEXT_PUBLIC_ORGANIZATION_ID, // this can also accept parent org if we don't know the suborg in advance
organizationId: NEXT_PUBLIC_ORGANIZATION_ID, // This can accept the parent org if we don't know the suborg in advance
parameters: {
email: email!,
targetPublicKey: iframeClient?.iframePublicKey!,
Expand All @@ -343,7 +281,8 @@ export const TurnkeyProvider: React.FC<TurnkeyProviderProps> = ({

const result = completedActivity.result.createReadWriteSessionResult;

// need to save resulting bundle and information
// Need to save resulting bundle and information.
// This is required by the authIframeClient abstraction.
localStorage.setItem("CREDENTIAL_BUNDLE", result?.credentialBundle!);
localStorage.setItem(
"@turnkey/current_user",
Expand All @@ -357,11 +296,6 @@ export const TurnkeyProvider: React.FC<TurnkeyProviderProps> = ({
})
);

console.log(
"stored credential bundle",
localStorage.getItem("CREDENTIAL_BUNDLE")
);

setUser({
userId: result?.userId!,
username: result?.username!,
Expand All @@ -376,34 +310,27 @@ export const TurnkeyProvider: React.FC<TurnkeyProviderProps> = ({
return whoami;
}

async function createWallet(walletName: string) {
async function createWallet(walletName: string, callback: any) {
if (!walletClient || !user?.organizationId) {
return;
}

let activeClient = walletClient; // default

// get active client here
console.log({
walletClient,
iframeClient,
activeClient,
});

const activeIframeClient = await getActiveIframeClient();
console.log("active iframe client", activeIframeClient);

// If an iframe client exists, let's try to use it
if (activeIframeClient) {
console.log("inside here");
try {
const result = await activeIframeClient.createWallet({
walletName,
accounts: [ACCOUNT_CONFIG_SOLANA],
});

const result = await activeIframeClient.createWallet({
walletName,
accounts: [ACCOUNT_CONFIG_SOLANA],
});
callback();

console.log("iframe client result", result);
return;
return;
} catch (error) {
console.error("unable to create wallet using iframe client", error);
}
}

// We have a wallet client
Expand All @@ -422,7 +349,8 @@ export const TurnkeyProvider: React.FC<TurnkeyProviderProps> = ({
},
});

console.log("wallet completed activity", completedActivity);
callback();

return;
}

Expand Down
Loading

0 comments on commit d0e4c70

Please sign in to comment.