Skip to content

Commit

Permalink
update README and add loading spinner
Browse files Browse the repository at this point in the history
  • Loading branch information
lwin-kyaw committed Apr 18, 2024
1 parent 290bd94 commit 4232114
Show file tree
Hide file tree
Showing 6 changed files with 78 additions and 58 deletions.
8 changes: 4 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,10 +36,10 @@ import { Web3AuthMPCCoreKit } from "@web3auth/mpc-core-kit";

const DEFAULT_CHAIN_CONFIG: CustomChainConfig = {
chainNamespace: CHAIN_NAMESPACES.EIP155,
chainId: "0x5",
rpcTarget: "https://rpc.ankr.com/eth_goerli",
displayName: "Goerli Testnet",
blockExplorer: "https://goerli.etherscan.io",
chainId: "0xaa36a7",
rpcTarget: "https://rpc.ankr.com/eth_sepolia",
displayName: "Ethereum Sepolia Testnet",
blockExplorer: "https://sepolia.etherscan.io",
ticker: "ETH",
tickerName: "Ethereum",
decimals: 18,
Expand Down
69 changes: 33 additions & 36 deletions demo/redirect-flow-example/README.md
Original file line number Diff line number Diff line change
@@ -1,46 +1,43 @@
# Getting Started with Create React App
## Example App
To run the demo, under this directory
- `npm install`
- `npm start`

This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
## Glossaries
<u>**Export TSS Key**</u>
- Exporting `TSS Key` reconstructs the original key.

## Available Scripts
<u>**Import TSS Key**</u>
- Import the exported TSS Key from one account to another.

In the project directory, you can run:
<u>**Recover TSS Key**</u>
- Recover your TSS Key with the `device` & `recovery` factors which you got from enabling MFA.

### `npm start`
>_Note: **recover** and **export** TSS Key reset the account. (i.e: the new account has different factors and shares but will have the same public address)_
Runs the app in the development mode.\
Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
----
### To test on `export/import` and `recover/import` functions, you can do the followings in the demo -

The page will reload if you make edits.\
You will also see any lint errors in the console.
#### Export/Import
- when you're logged in, click on the `Export/Import Key` button, this will first reconstructs and exports your `TSS Key`
- After successful export, you will be logged out and asked to enter the account name/email which you will import the **exported TSS Key**
- then you will be logged in with the new account/email and **exported Key**

### `npm test`
#### Recover/Import
- as a prerequisite, your account need to be **MFA enabled** and have access to **Factor Keys**(Device and Recovery), in order to do the TSS Key recovery
- at the login screen, enter your factor keys (`Device` and `Recovery`) which you got from enabling MFA and click on `Recover with Factor Keys` button
- the above step will reconstruct the **TSS Key** using your factor keys (device & recovery) and export **TSS Key**
- then, you will be asked to enter the new email address which will be used to associate to your **exported Key**
- after successful import, you will be logged in with different user/email

Launches the test runner in the interactive watch mode.\
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
#### Verification
- to verify the above features, you can click on `Get User Info` button or `Get Accounts` button (under the Blockchain Calls section)
- The expected result is`your email address changees` but `the account is remaining the same`

### `npm run build`
#### How to enable MFA
1. log in
2. click `Enable MFA`
3. then you can export your `device` and `recovery` shares which you can use to login or recover your account

Builds the app for production to the `build` folder.\
It correctly bundles React in production mode and optimizes the build for the best performance.

The build is minified and the filenames include the hashes.\
Your app is ready to be deployed!

See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.

### `npm run eject`

**Note: this is a one-way operation. Once you `eject`, you can’t go back!**

If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.

Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own.

You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it.

## Learn More

You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).

To learn React, check out the [React documentation](https://reactjs.org/).
> Note: when `manualSync` is true, (which you can specify during Corekit instantiation ) you will need to commit your changes before/after enabling MFA (Step-2).
----
2 changes: 1 addition & 1 deletion demo/redirect-flow-example/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion demo/redirect-flow-example/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
"@types/node": "^16.18.48",
"@types/react": "^18.2.21",
"@types/react-dom": "^18.2.7",
"@web3auth/mpc-core-kit": "file:../..",
"@web3auth/mpc-core-kit": "2.3.0",
"browserify-zlib": "^0.2.0",
"copy-webpack-plugin": "^11.0.0",
"html-webpack-plugin": "^5.5.3",
Expand Down
49 changes: 33 additions & 16 deletions demo/redirect-flow-example/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,14 @@ import Web3 from "web3";
import type { provider } from "web3-core";

import "./App.css";
import { SafeEventEmitterProvider, isHexStrict } from "@web3auth/base";
import { SafeEventEmitterProvider } from "@web3auth/base";
import { BN } from "bn.js";

import jwt, { Algorithm } from "jsonwebtoken";
import { flow } from "./flow";
import LoggedinView from "./LoggedinView";
import { CHAIN_CONFIGS, CHAIN_NAMESPACE, isHex } from "./utils";
import LoadingSpinner from "./components/LoadingIndicator";

const uiConsole = (...args: any[]): void => {
const el = document.querySelector("#console>p");
Expand Down Expand Up @@ -75,7 +76,7 @@ export const mockLogin = async (email: string) => {

function App() {
const [mockEmail, setMockEmail] = useState<string>("[email protected]");

const [loading, setLoading] = useState<boolean>(false);
const [backupFactorKey, setBackupFactorKey] = useState<string>("");
const [deviceFactorKey, setDeviceFactorKey] = useState<string>("");
const [recoveryFactor, setRecoveryFactor] = useState<string>("");
Expand Down Expand Up @@ -130,6 +131,7 @@ function App() {
useEffect(() => {
if (provider) {
const web3 = new Web3(provider as provider);
console.log('setting web3');
setWeb3(web3);
}
}, [provider]);
Expand Down Expand Up @@ -222,7 +224,7 @@ function App() {
if (!backupFactorKey) {
throw new Error("backupFactorKey not found");
}

setLoading(true);
const factorStr = isHex(backupFactorKey) ? backupFactorKey : mnemonicToKey(backupFactorKey)
console.log("factorStr", factorStr);
const factorKey = new BN(factorStr, "hex");
Expand All @@ -242,6 +244,7 @@ function App() {
if (coreKitInstance.provider) {
setProvider(coreKitInstance.provider);
}
setLoading(false);
};

const recoverSecurityQuestionFactor = async () => {
Expand Down Expand Up @@ -314,9 +317,17 @@ function App() {
return key;
};

const importTssKey = async (newOauthLogin: string, importedTssKey: string) => {
const importTssKey = async (importedTssKey: string) => {
let email = window.prompt("Enter new email to import your key");
while (email == null) {
window.alert("Please enter valid/non-empty email");
email = window.prompt("Enter new email to import your key");
}

setMockEmail(email);
setLoading(true);
// import key to new instance
let { idToken, parsedToken } = await mockLogin(newOauthLogin);
let { idToken, parsedToken } = await mockLogin(email);

const newCoreKitInstance = new Web3AuthMPCCoreKit({
web3AuthClientId: "BPi5PB_UiIZ-cPz1GtV5i1I2iOSOHuimiXBI0e-Oe_u6X3oVAbCiAZOTEBtTXw4tsluTITPqA8zMsfxIKMjiqNQ",
Expand All @@ -339,10 +350,13 @@ function App() {
coreKitStatus: newCoreKitInstance.status,
}));
coreKitInstance = newCoreKitInstance;

setUpProvider();
setCoreKitStatus(newCoreKitInstance.status);
setLoading(false);
};

const recoverTssKey = async (factorKeys: string[], newOauthLogin: string) => {
const recoverTssKey = async (factorKeys: string[]) => {
const recoverMpcInstance = new Web3AuthMPCCoreKit({
web3AuthClientId: "BPi5PB_UiIZ-cPz1GtV5i1I2iOSOHuimiXBI0e-Oe_u6X3oVAbCiAZOTEBtTXw4tsluTITPqA8zMsfxIKMjiqNQ",
web3AuthNetwork: selectedNetwork,
Expand All @@ -355,10 +369,10 @@ function App() {

let recoveredTssKey = await recoverMpcInstance._UNSAFE_recoverTssKey(factorKeys);
uiConsole("Recovered TSS Private Key: ", recoveredTssKey);
let web3Local = new Web3("https://eth.llamarpc.com");
let account = web3Local.eth.accounts.privateKeyToAccount(recoveredTssKey);
let signedTx = await account.signTransaction({ to: "0x2E464670992574A613f10F7682D5057fB507Cc21", value: "1000000000000000000" });
console.log(signedTx);
// let web3Local = new Web3("https://eth.llamarpc.com");
// let account = web3Local.eth.accounts.privateKeyToAccount(recoveredTssKey);
// let signedTx = await account.signTransaction({ to: "0x2E464670992574A613f10F7682D5057fB507Cc21", value: "1000000000000000000" });
// console.log(signedTx);
return recoveredTssKey;
};

Expand All @@ -369,13 +383,15 @@ function App() {
await logout();
// wait for 2 sec before import and login
await new Promise(r => setTimeout(r, 2000));
await importTssKey(newOauthLogin || mockEmail, key);
await importTssKey(key);
};

const recoverTssKeyImportTssKey = async () => {
const factorKeys = [mnemonicToKey(deviceFactorKey), mnemonicToKey(recoveryFactor)];
let key = await recoverTssKey(factorKeys, mockEmail);
await importTssKey(mockEmail, key);
const deviceShare = isHex(deviceFactorKey) ? deviceFactorKey : mnemonicToKey(deviceFactorKey);
const recoveryShare = isHex(recoveryFactor) ? recoveryFactor : mnemonicToKey(recoveryFactor);
const factorKeys = [deviceShare, recoveryShare];
let key = await recoverTssKey(factorKeys);
await importTssKey(key);
};

const unloggedInView = (
Expand Down Expand Up @@ -418,17 +434,18 @@ function App() {
<h4>Recover account with factors</h4>
<div className="recovery-form">
<div className="left">
<label>Device Factor (Mnemonic): </label>
<label>Device Factor: </label>
<input value={deviceFactorKey} onChange={(e) => setDeviceFactorKey(e.target.value)} />
</div>
<div className="right">
<label>Recovery Factor (Mnemonic): </label>
<label>Recovery Factor: </label>
<input value={recoveryFactor} onChange={(e) => setRecoveryFactor(e.target.value)} />
</div>
</div>
<button onClick={() => recoverTssKeyImportTssKey()} className="card">
Recover Account with Factor Keys
</button>
{loading && <LoadingSpinner />}
</div>
</>
);
Expand Down
6 changes: 6 additions & 0 deletions demo/redirect-flow-example/src/LoggedinView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import SecurityQuestion from "./components/SecurityQuestion";
import BlockchainCalls from "./components/BlockchainCalls";
import { CHAIN_NAMESPACE } from "./utils";
import Web3 from "web3";
import LoadingSpinner from "./components/LoadingIndicator";

interface ILoggedinViewProps {
web3: Web3;
Expand All @@ -27,6 +28,7 @@ function LoggedinView({ web3, coreKitInstance, criticalResetAccount, logout, inp
const [exportTssShareType, setExportTssShareType] = useState<TssShareType>(TssShareType.DEVICE);
const [factorPubToDelete, setFactorPubToDelete] = useState<string>("");
const [backupFactorKey, setBackupFactorKey] = useState<string | undefined>(undefined);
const [loading, setLoading] = useState<boolean>(false);

const getUserInfo = async () => {
const userInfo = coreKitInstance.getUserInfo();
Expand Down Expand Up @@ -62,13 +64,15 @@ function LoggedinView({ web3, coreKitInstance, criticalResetAccount, logout, inp
};

const enableMFA = async () => {
setLoading(true);
if (!coreKitInstance) {
throw new Error("coreKitInstance is not set");
}
const factorKey = await coreKitInstance.enableMFA({});
const factorKeyMnemonic = keyToMnemonic(factorKey);

uiConsole("MFA enabled, device factor stored in local store, deleted hashed cloud key, your backup factor key: ", factorKeyMnemonic);
setLoading(false);
};

const exportFactor = async (): Promise<void> => {
Expand Down Expand Up @@ -194,6 +198,8 @@ function LoggedinView({ web3, coreKitInstance, criticalResetAccount, logout, inp
</div>

<BlockchainCalls coreKitInstance={coreKitInstance} web3={web3} switchChain={switchChain} />

{loading && <LoadingSpinner />}
</div>
);
}
Expand Down

0 comments on commit 4232114

Please sign in to comment.