From a54cafa2a816226b35254285645f87590e41c638 Mon Sep 17 00:00:00 2001 From: Yashovardhan Agrawal Date: Thu, 26 Oct 2023 01:24:16 +0530 Subject: [PATCH] update tkey rn examples --- .../package.json | 2 +- .../tkey-rn-expo-auth0-example/App.tsx | 513 +- .../tkey-rn-expo-auth0-example/app.json | 2 +- .../babel.config.js | 8 + .../tkey-rn-expo-auth0-example/ethersRPC.ts | 84 - .../tkey-rn-expo-auth0-example/ios/Podfile | 5 + .../ios/Podfile.lock | 2 +- .../package-lock.json | 6895 +++++++++-------- .../tkey-rn-expo-auth0-example/package.json | 21 +- .../tkey-rn-expo-auth0-example/tkey.ts | 29 +- 10 files changed, 3935 insertions(+), 3626 deletions(-) delete mode 100644 tkey-react-native/tkey-rn-expo-auth0-example/ethersRPC.ts diff --git a/tkey-react-native/tkey-react-native-quick-start/package.json b/tkey-react-native/tkey-react-native-quick-start/package.json index a2eb088f..8f7b3a55 100644 --- a/tkey-react-native/tkey-react-native-quick-start/package.json +++ b/tkey-react-native/tkey-react-native-quick-start/package.json @@ -1,5 +1,5 @@ { - "name": "tkeyfirebaseexample", + "name": "tkey-react-native-quick-start", "version": "0.0.1", "private": true, "scripts": { diff --git a/tkey-react-native/tkey-rn-expo-auth0-example/App.tsx b/tkey-react-native/tkey-rn-expo-auth0-example/App.tsx index 0fe8d1b9..07f589a8 100644 --- a/tkey-react-native/tkey-rn-expo-auth0-example/App.tsx +++ b/tkey-react-native/tkey-rn-expo-auth0-example/App.tsx @@ -7,31 +7,38 @@ import React, { useEffect, useState } from "react"; import { ActivityIndicator, Button, TouchableOpacity, Dimensions, ScrollView, StyleSheet, Text, View } from "react-native"; import { Auth0Provider, useAuth0 } from "react-native-auth0"; import * as SecureStore from "expo-secure-store"; -import BN from 'bn.js'; - -import RPC from "./ethersRPC"; // for using ethers.js -import { ethereumPrivateKeyProvider, tKeyInstance } from "./tkey"; +import { tKey, chainConfig } from "./tkey"; import { ShareSerializationModule } from "@tkey/share-serialization"; import SfaServiceProvider from "@tkey/service-provider-sfa"; import ReactNativeStorageModule from "@tkey/react-native-storage"; +import '@ethersproject/shims'; +import {ethers} from 'ethers'; +import {EthereumPrivateKeyProvider} from '@web3auth/ethereum-provider'; +import {IProvider} from '@web3auth/base'; + +const verifier = 'w3a-auth0-demo'; + +const ethereumPrivateKeyProvider = new EthereumPrivateKeyProvider({ + config: { + chainConfig, + }, +}); const Home = () => { - const [privateKey, setPrivateKey] = useState(); + const [tKeyInitialised, setTKeyInitialised] = useState(false); + const [provider, setProvider] = useState(null); + const [loggedIn, setLoggedIn] = useState(false); + const [userInfo, setUserInfo] = useState({}); + const [recoveryShare, setRecoveryShare] = useState(''); + const [mnemonicShare, setMnemonicShare] = useState(''); + const [consoleUI, setConsoleUI] = useState(''); const [loading, setLoading] = useState(false); - const [oAuthShare, setOAuthShare] = useState(null); - const [userInfo, setUserInfo] = useState(""); - const [consoleUI, setConsoleUI] = useState(""); - const [recoveryPassword, setRecoveryPassword] = useState(""); - const [recoveryMnemonic, setRecoveryMnemonic] = useState(""); - const [recoveryModalVisibility, setRecoveryModalVisibility] = useState(false); - const [passwordShareModalVisibility, setPasswordShareModalVisibility] = useState(false); - const [changePasswordShareModalVisibility, setChangePasswordShareModalVisibility] = useState(false); useEffect(() => { const init = async () => { // Initialization of Service Provider try { - await (tKeyInstance.serviceProvider as any).init( + await (tKey.serviceProvider as any).init( ethereumPrivateKeyProvider, ); } catch (error) { @@ -75,45 +82,33 @@ const Home = () => { const parsedToken = parseToken(idToken); setUserInfo(parsedToken); - const verifier = "web3auth-auth0-demo"; const verifierId = parsedToken.sub; const OAuthShareKey = await ( - tKeyInstance.serviceProvider as SfaServiceProvider + tKey.serviceProvider as SfaServiceProvider ).connect({ verifier, verifierId, idToken, }); - uiConsole('OAuthShareKey', OAuthShareKey); - setOAuthShare(OAuthShareKey); + await tKey.initialize(); + + setTKeyInitialised(true); - await tKeyInstance.initialize(); + var {requiredShares} = tKey.getKeyDetails(); - var { requiredShares } = tKeyInstance.getKeyDetails(); - uiConsole("requiredShares", requiredShares); - const deviceShare = await getDeviceShare(); + uiConsole('requiredShares', requiredShares); if (requiredShares > 0) { - if (deviceShare) { - try { - await tKeyInstance.inputShare(deviceShare); - } catch (error) { - uiConsole(error); - } - } - var { requiredShares } = tKeyInstance.getKeyDetails(); - if (requiredShares > 0) { - await toggleRecoveryModalVisibility(); - setLoading(false); - return; - } + uiConsole( + 'Please enter your backup shares, requiredShares:', + requiredShares, + ); + } else { + await reconstructKey(); } - await reconstructKey(); - setLoading(false); - uiConsole("Logged In"); } catch (e) { uiConsole(e); setLoading(false); @@ -122,66 +117,46 @@ const Home = () => { const reconstructKey = async () => { try { - const reconstructedKey = await tKeyInstance.reconstructKey(); - const finalPrivateKey = reconstructedKey?.privKey.toString("hex"); - const deviceShare = await getDeviceShare(); - await setPrivateKey(finalPrivateKey); - uiConsole(`Private Key: ${finalPrivateKey}`); - if (!deviceShare) { - setDeviceShare(); - } - } catch (error) { - uiConsole(error); - } - } + const reconstructedKey = await tKey.reconstructKey(); + const privateKey = reconstructedKey?.privKey.toString('hex'); - const recoverPasswordShare = async (password: string) => { - if (!tKeyInstance) { - uiConsole("tKeyInstance not initialized yet"); - return; - } - - if (password.length > 10) { - try { - setLoading(true); - await (tKeyInstance.modules.securityQuestions as any).inputShareFromSecurityQuestions(password); // 2/2 flow - await reconstructKey(); - uiConsole("Successfully logged you in with the recovery password."); - } catch (error) { - uiConsole(error); - setLoading(false); - } - } else { - uiConsole("Error", "Password must be >= 11 characters", "error"); - setLoading(false); + await ethereumPrivateKeyProvider.setupProvider(privateKey); + setProvider(ethereumPrivateKeyProvider); + setLoggedIn(true); + setDeviceShare(); + } catch (e) { + uiConsole(e); } }; - const recoverMnemonicShare = async (mnemonic: string) => { - if (!tKeyInstance) { - uiConsole("tKeyInstance not initialized yet"); - return; - } + const inputRecoveryShare = async (share: string) => { try { - setLoading(true); - const share = await (tKeyInstance.modules.shareSerialization as ShareSerializationModule).deserialize(mnemonic, "mnemonic"); - await tKeyInstance.inputShare(share); + await tKey.inputShare(share); await reconstructKey(); - uiConsole("Input Mnemonic Successful."); + uiConsole('Recovery Share Input Successfully'); + return; } catch (error) { - uiConsole(error); - setLoading(false); + uiConsole('Input Recovery Share Error:', error); + } + }; + + const keyDetails = async () => { + if (!tKey) { + uiConsole('tKey not initialized yet'); + return; } - } + const keyDetail = await tKey.getKeyDetails(); + uiConsole(keyDetail); + }; const setDeviceShare = async () => { try { - const generateShareResult = await tKeyInstance.generateNewShare(); - const share = await tKeyInstance.outputShareStore( + const generateShareResult = await tKey.generateNewShare(); + const share = await tKey.outputShareStore( generateShareResult.newShareIndex, ); await ( - tKeyInstance.modules.reactNativeStorage as ReactNativeStorageModule + tKey.modules.reactNativeStorage as ReactNativeStorageModule ).storeDeviceShare(share); uiConsole('Device Share Set', JSON.stringify(share)); } catch (error) { @@ -192,7 +167,7 @@ const Home = () => { const getDeviceShare = async () => { try { const share = await ( - tKeyInstance.modules.reactNativeStorage as ReactNativeStorageModule + tKey.modules.reactNativeStorage as ReactNativeStorageModule ).getStoreFromReactNativeStorage(); if (share) { @@ -200,6 +175,7 @@ const Home = () => { 'Device Share Captured Successfully across', JSON.stringify(share), ); + setRecoveryShare(share.share.share.toString('hex')); return share; } uiConsole('Device Share Not found'); @@ -211,7 +187,7 @@ const Home = () => { const deleteDeviceShare = async () => { try { - const metadata = await tKeyInstance.getMetadata(); + const metadata = await tKey.getMetadata(); await SecureStore.deleteItemAsync(metadata.pubKey.x.toString('hex')); uiConsole('Device Share Deleted'); } catch (error) { @@ -219,125 +195,130 @@ const Home = () => { } }; - const changeSecurityQuestionAndAnswer = async (password: string) => { - if (!tKeyInstance) { - uiConsole("tKeyInstance not initialized yet"); - return; - } - - if (password.length > 10) { - try { - setLoading(true); - await (tKeyInstance.modules.securityQuestions as any).changeSecurityQuestionAndAnswer(password, "whats your password?"); - uiConsole("Successfully changed new share with password."); - } catch (error) { - uiConsole("Error", (error as any)?.message.toString(), "error"); - setLoading(false); - } - } else { - uiConsole("Error", "Password must be >= 11 characters", "error"); - setLoading(false); - } - - const keyDetails = await tKeyInstance.getKeyDetails(); - uiConsole(keyDetails); - }; - - const generateNewShareWithPassword = async (password: string) => { - if (!tKeyInstance) { - uiConsole("tKeyInstance not initialized yet"); - return; - } - if (password.length > 10) { - try { - setLoading(true); - await (tKeyInstance.modules.securityQuestions as any).generateNewShareWithSecurityQuestions(password, "whats your password?"); - uiConsole("Successfully generated new share with password."); - } catch (error) { - uiConsole("Error", (error as any)?.message.toString(), "error"); - setLoading(false); - } - } else { - uiConsole("Error", "Password must be >= 11 characters", "error"); - setLoading(false); - } - }; - - const exportMnemonic = async () => { - if (!tKeyInstance) { - uiConsole("tKeyInstance not initialized yet"); - return; - } + const exportMnemonicShare = async () => { try { - const generateShareResult = await tKeyInstance.generateNewShare(); - const share = await tKeyInstance.outputShareStore( + const generateShareResult = await tKey.generateNewShare(); + const share = await tKey.outputShareStore( generateShareResult.newShareIndex, ).share.share; - const mnemonic = await (tKeyInstance.modules.shareSerialization as ShareSerializationModule).serialize(share, "mnemonic"); + const mnemonic = await ( + tKey.modules.shareSerialization as ShareSerializationModule + ).serialize(share, 'mnemonic'); uiConsole(mnemonic); + return mnemonic; } catch (error) { uiConsole(error); } - } - - const getKeyDetails = async () => { - if (!tKeyInstance) { - uiConsole("tKeyInstance not initialized yet"); - return; - } - - setConsoleUI("Getting Key Details"); - uiConsole(await tKeyInstance.getKeyDetails()); }; - const resetAccount = async () => { - if (!tKeyInstance) { - uiConsole("tKeyInstance not initialized yet"); + const MnemonicToShareHex = async (mnemonic: string) => { + if (!tKey) { + uiConsole('tKey not initialized yet'); return; } try { - uiConsole(oAuthShare); - await tKeyInstance.storageLayer.setMetadata({ - privKey: oAuthShare as any, - input: { message: "KEY_NOT_FOUND" }, - }); - uiConsole("Reset Account Successful."); - } catch (e) { - uiConsole(e); + const share = await ( + tKey.modules.shareSerialization as ShareSerializationModule + ).deserialize(mnemonic, 'mnemonic'); + setRecoveryShare(share.toString('hex')); + return share; + } catch (error) { + uiConsole(error); } }; - const getChainId = async () => { - setConsoleUI("Getting chain id"); - const networkDetails = await RPC.getChainId(); - uiConsole(networkDetails); + + const getUserInfo = async () => { + uiConsole(userInfo); }; const getAccounts = async () => { - setConsoleUI("Getting account"); - const address = await RPC.getAccounts(privateKey as string); + if (!provider) { + uiConsole('provider not set'); + return; + } + setConsoleUI('Getting account'); + // For ethers v5 + // const ethersProvider = new ethers.providers.Web3Provider(this.provider); + const ethersProvider = new ethers.BrowserProvider(provider!); + + // For ethers v5 + // const signer = ethersProvider.getSigner(); + const signer = await ethersProvider.getSigner(); + + // Get user's Ethereum public address + const address = signer.getAddress(); uiConsole(address); }; + const getBalance = async () => { - setConsoleUI("Fetching balance"); - const balance = await RPC.getBalance(privateKey as string); + if (!provider) { + uiConsole('provider not set'); + return; + } + setConsoleUI('Fetching balance'); + // For ethers v5 + // const ethersProvider = new ethers.providers.Web3Provider(this.provider); + const ethersProvider = new ethers.BrowserProvider(provider!); + + // For ethers v5 + // const signer = ethersProvider.getSigner(); + const signer = await ethersProvider.getSigner(); + + // Get user's Ethereum public address + const address = signer.getAddress(); + + // Get user's balance in ether + // For ethers v5 + // const balance = ethers.utils.formatEther( + // await ethersProvider.getBalance(address) // Balance is in wei + // ); + const balance = ethers.formatEther( + await ethersProvider.getBalance(address), // Balance is in wei + ); uiConsole(balance); }; - const sendTransaction = async () => { - setConsoleUI("Sending transaction"); - const tx = await RPC.sendTransaction(privateKey as string); - uiConsole(tx); - }; + const signMessage = async () => { - setConsoleUI("Signing message"); - const message = await RPC.signMessage(privateKey as string); - uiConsole(message); + if (!provider) { + uiConsole('provider not set'); + return; + } + setConsoleUI('Signing message'); + // For ethers v5 + // const ethersProvider = new ethers.providers.Web3Provider(this.provider); + const ethersProvider = new ethers.BrowserProvider(provider!); + + // For ethers v5 + // const signer = ethersProvider.getSigner(); + const signer = await ethersProvider.getSigner(); + const originalMessage = 'YOUR_MESSAGE'; + + // Sign the message + const signedMessage = await signer.signMessage(originalMessage); + uiConsole(signedMessage); }; + const logout = async () => { - await clearSession({ customScheme: "auth0.com.tkeyrnauth0" }); - setPrivateKey(null); - setOAuthShare(null); - setUserInfo(''); + setProvider(null); + setLoggedIn(false); + setUserInfo({}); + uiConsole('logged out'); + }; + + const criticalResetAccount = async (): Promise => { + // This is a critical function that should only be used for testing purposes + // Resetting your account means clearing all the metadata associated with it from the metadata server + // The key details will be deleted from our server and you will not be able to recover your account + if (!tKeyInitialised) { + throw new Error('tKeyInitialised is initialised yet'); + } + await tKey.storageLayer.setMetadata({ + privKey: tKey.serviceProvider.postboxKey, + input: {message: 'KEY_NOT_FOUND'}, + }); + uiConsole('reset'); + logout(); }; const uiConsole = (...args: any) => { @@ -345,110 +326,99 @@ const Home = () => { console.log(...args); }; - const toggleRecoveryModalVisibility = async () => { - setRecoveryModalVisibility(!recoveryModalVisibility); - }; - const recoveryModal = ( - - - {loading && } - setRecoveryPassword(value)} /> + const loggedInView = ( + + + Get User Info + + + Get Key Details + + + Generate Backup (Mnemonic) + + + Get Accounts + + + Get Balance + + + Sign Message + + + Get Device Share + + + Set Device Share + + + Delete Device Share + + + Log Out + + + [CRITICAL] Reset Account + + + ); + + const unloggedInView = ( + + - ); - - const togglePasswordShareModalVisibility = async () => { - setPasswordShareModalVisibility(!passwordShareModalVisibility); - }; - - const setPasswordShareModal = ( - - - setRecoveryPassword(value)} /> - {loading && } - ); - - const toggleChangePasswordShareModalVisibility = async () => { - setChangePasswordShareModalVisibility(!changePasswordShareModalVisibility); - }; - - const changePasswordShareModal = ( - - - setRecoveryPassword(value)} /> - {loading && } - ); - - const loggedInView = ( - - {setPasswordShareModal} - {changePasswordShareModal} - uiConsole(userInfo)} >Get User Info - Get Key Details - Get Chain ID - Set Password Share - Change Password Share - Get Accounts - Get Balance - Send Transaction - Sign Message - uiConsole(privateKey)} >Get Private Key - Set Device Share - Get Device Share - Delete Device Share - Export Mnemonic Share - Reset Account - Log Out - - ); - - const unloggedInView = ( - - {recoveryModal} -