Skip to content

Commit

Permalink
Add MPC Core Kit Quick Starts
Browse files Browse the repository at this point in the history
  • Loading branch information
yashovardhan committed Oct 24, 2023
1 parent fed8050 commit ef2e22c
Show file tree
Hide file tree
Showing 276 changed files with 41,400 additions and 9,126 deletions.

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
{
"name": "sfa-angular-quick-start",
"version": "0.0.0",
"scripts": {
"ng": "ng",
"start": "ng serve",
"build": "ng build",
"watch": "ng build --watch --configuration development",
"test": "ng test",
"lint": "ng line"
},
"private": true,
"dependencies": {
"@angular/animations": "~14.2.7",
"@angular/common": "~14.2.7",
"@angular/compiler": "~14.2.7",
"@angular/core": "~14.2.7",
"@angular/forms": "~14.2.7",
"@angular/platform-browser": "~14.2.7",
"@angular/platform-browser-dynamic": "~14.2.7",
"@angular/router": "~14.2.7",
"@web3auth/mpc-core-kit": "^1.1.0",
"empty-module": "^0.0.2",
"firebase": "^10.4.0",
"web3": "^1.8.1"
},
"devDependencies": {
"@angular-devkit/build-angular": "~14.2.6",
"@angular/cli": "~14.2.6",
"@angular/compiler-cli": "~14.2.7",
"@types/jasmine": "~4.3.0",
"@types/keccak": "^3.0.1",
"@types/node": "^18.11.2",
"@types/readable-stream": "^2.3.14",
"jasmine-core": "~4.4.0",
"karma": "~6.4.1",
"karma-chrome-launcher": "~3.1.1",
"karma-coverage": "~2.2.0",
"karma-jasmine": "~5.1.0",
"karma-jasmine-html-reporter": "~2.0.0",
"typescript": "~4.8.0",
"buffer": "^6.0.3",
"assert": "^2.0.0",
"crypto-browserify": "^3.12.0",
"https-browserify": "^1.0.0",
"os-browserify": "^0.3.0",
"eslint-config-react-app": "^7.0.1",
"process": "^0.11.10",
"stream-browserify": "^3.0.0",
"stream-http": "^3.2.0",
"browserify-zlib": "^0.2.0",
"url": "^0.11.1"
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
<div class="content">
<h1 class="title">
<a target="_blank" href="http://web3auth.io/">Web3Auth MPC Core Kit</a> Angular
Quick Start
</h1>
<div class="setting">
<div
*ngIf="coreKitStatus === 'LOGGED_IN'; else elseBlock"
class="card-container"
>
<button class="card card-small" (click)="getUserInfo()">
Get User Info
</button>
<button (click)="keyDetails()" class='card card-small'>
Key Details
</button>
<button (click)="enableMFA()" class='card card-small'>
Enable MFA
</button>
<button class="card card-small" (click)="getAccounts()">
Get Accounts
</button>
<button class="card card-small" (click)="getBalance()">
Get Balance
</button>
<button class="card card-small" (click)="signMessage()">
Sign Message
</button>
<button class="card card-small" (click)="logout()">Log Out</button>
<button (click)="criticalResetAccount()" class="card card-small">
[CRITICAL] Reset Account
</button>
<button (click)="exportMnemonicFactor()" class='card card-small'>
Generate Backup (Mnemonic)
</button>
</div>
<ng-template #elseBlock>
<div class="card-container">
<button class="card card-small" (click)="login()">Login</button>
<div class="card-container" *ngIf="coreKitStatus === 'REQUIRED_SHARE'" >
<button (click)="getDeviceFactor()" class="card card-small">
Get Device Factor
</button>
<label>Backup/ Device Factor:</label>
<input name="backupFactorKeyInputField" [(ngModel)]="backupFactorKey" (ngModelChange)="getBackupFactorKeyInputEvent($event)" />
<button (click)="inputBackupFactorKey()" class="card card-small">
Input Backup Factor Key
</button>
<button (click)="criticalResetAccount()" class="card card-small">
[CRITICAL] Reset Account
</button>
<label>Recover Using Mnemonic Factor Key:</label>
<input name="MnemonicFactorInputField" [(ngModel)]="mnemonicFactor" (ngModelChange)="getMnemonicFactorInputEvent($event)" />
<button (click)="MnemonicToFactorKeyHex(mnemonicFactor)" class="card card-small">
Get Recovery Factor Key using Mnemonic
</button>
</div>
</div>
</ng-template>
<div class="console" id="console-ui">
<p class="code">Logged In</p>
</div>
</div>
<footer class="footer">
<a
href="https://github.com/Web3Auth/web3auth-pnp-examples/tree/main/web-no-modal-sdk/quick-starts/angular-no-modal-quick-start"
target="_blank"
rel="noopener noreferrer"
>
Source code
</a>
</footer>
</div>
Original file line number Diff line number Diff line change
@@ -0,0 +1,263 @@
import { Component } from "@angular/core";
import { Web3AuthMPCCoreKit, WEB3AUTH_NETWORK, IdTokenLoginParams, TssShareType, parseToken, getWebBrowserFactor, generateFactorKey, COREKIT_STATUS, keyToMnemonic, mnemonicToKey } from "@web3auth/mpc-core-kit";
import Web3 from "web3";
import { BN } from "bn.js";

// Firebase libraries for custom authentication
import { initializeApp } from "firebase/app";
import { GoogleAuthProvider, getAuth, signInWithPopup, UserCredential } from "firebase/auth";

const verifier = "w3a-firebase-demo";

// Your web app's Firebase configuration
const firebaseConfig = {
apiKey: "AIzaSyB0nd9YsPLu-tpdCrsXn8wgsWVAiYEpQ_E",
authDomain: "web3auth-oauth-logins.firebaseapp.com",
projectId: "web3auth-oauth-logins",
storageBucket: "web3auth-oauth-logins.appspot.com",
messagingSenderId: "461819774167",
appId: "1:461819774167:web:e74addfb6cc88f3b5b9c92",
};

const coreKitInstance = new Web3AuthMPCCoreKit(
{
web3AuthClientId: 'BPi5PB_UiIZ-cPz1GtV5i1I2iOSOHuimiXBI0e-Oe_u6X3oVAbCiAZOTEBtTXw4tsluTITPqA8zMsfxIKMjiqNQ',
web3AuthNetwork: WEB3AUTH_NETWORK.MAINNET,
}
);

@Component({
selector: "app-root",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"],
})
export class AppComponent {
title = "Web3Auth tKey Angular Quick Start";
coreKitStatus: COREKIT_STATUS = COREKIT_STATUS.NOT_INITIALIZED;
backupFactorKey: string = "";
mnemonicFactor: string = "";

getBackupFactorKeyInputEvent(event: any) {
this.backupFactorKey = event.target.value;
}
getMnemonicFactorInputEvent(event: any) {
this.mnemonicFactor = event.target.value;
}

app = initializeApp(firebaseConfig);

async ngOnInit() {
const init = async () => {
try {
await coreKitInstance.init();

this.coreKitStatus = coreKitInstance.status;
} catch (error) {
console.error(error);
}
};

init();
}

signInWithGoogle = async (): Promise<UserCredential> => {
try {
const auth = getAuth(this.app);
const googleProvider = new GoogleAuthProvider();
const res = await signInWithPopup(auth, googleProvider);
console.log(res);
return res;
} catch (err) {
console.error(err);
throw err;
}
};

login = async () => {
try {
if (!coreKitInstance) {
throw new Error('initiated to login');
}
const loginRes = await this.signInWithGoogle();
const idToken = await loginRes.user.getIdToken(true);
const parsedToken = parseToken(idToken);

const idTokenLoginParams = {
verifier,
verifierId: parsedToken.sub,
idToken,
} as IdTokenLoginParams;

await coreKitInstance.loginWithJWT(idTokenLoginParams);

if (coreKitInstance.status === COREKIT_STATUS.REQUIRED_SHARE) {
this.uiConsole("required more shares, please enter your backup/ device factor key, or reset account [unrecoverable once reset, please use it with caution]");
}

this.coreKitStatus = coreKitInstance.status;
}
catch (err) {
this.uiConsole(err);
}
};

inputBackupFactorKey = async () => {
if (!coreKitInstance) {
throw new Error("coreKitInstance not found");
}
if (!this.backupFactorKey) {
throw new Error("backupFactorKey not found");
}
const factorKey = new BN(this.backupFactorKey, "hex")
await coreKitInstance.inputFactorKey(factorKey);

this.coreKitStatus = coreKitInstance.status;

if (coreKitInstance.status === COREKIT_STATUS.REQUIRED_SHARE) {
this.uiConsole("required more shares even after inputing backup factor key, please enter your backup/ device factor key, or reset account [unrecoverable once reset, please use it with caution]");
}
};

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

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

keyDetails = async () => {
if (!coreKitInstance) {
throw new Error('coreKitInstance not found');
}
this.uiConsole(coreKitInstance.getKeyDetails());
};

getDeviceFactor = async () => {
try {
const factorKey = await getWebBrowserFactor(coreKitInstance!);
this.backupFactorKey = factorKey!;
this.uiConsole("Device share: ", factorKey);
} catch (e) {
this.uiConsole(e);
}
};

exportMnemonicFactor = async (): Promise<void> => {
if (!coreKitInstance) {
throw new Error("coreKitInstance is not set");
}
this.uiConsole("export share type: ", TssShareType.RECOVERY);
const factorKey = generateFactorKey();
await coreKitInstance.createFactor({
shareType: TssShareType.RECOVERY,
factorKey: factorKey.private
});
const factorKeyMnemonic = await keyToMnemonic(factorKey.private.toString("hex"));
this.uiConsole("Export factor key mnemonic: ", factorKeyMnemonic);
};

MnemonicToFactorKeyHex = async (mnemonic: string) => {
if (!coreKitInstance) {
throw new Error("coreKitInstance is not set");
}
try {
const factorKey = await mnemonicToKey(mnemonic);
this.backupFactorKey = factorKey;
return factorKey;
} catch (error) {
this.uiConsole(error);
return null
}
};

getUserInfo = async () => {
this.uiConsole(coreKitInstance.getUserInfo());
};

logout = async () => {
await coreKitInstance.logout();
this.coreKitStatus = coreKitInstance.status;
this.uiConsole("logged out");
};

getAccounts = async () => {
if (!coreKitInstance) {
this.uiConsole("provider not initialized yet");
return;
}
const web3 = new Web3(coreKitInstance.provider as any);

// Get user's Ethereum public address
const address = await web3.eth.getAccounts();
this.uiConsole(address);
};

getBalance = async () => {
if (!coreKitInstance) {
this.uiConsole("provider not initialized yet");
return;
}
const web3 = new Web3(coreKitInstance.provider as any);

// Get user's Ethereum public address
const address = (await web3.eth.getAccounts())[0];

// Get user's balance in ether
const balance = web3.utils.fromWei(
await web3.eth.getBalance(address), // Balance is in wei
"ether"
);
this.uiConsole(balance);
};

signMessage = async () => {
if (!coreKitInstance) {
this.uiConsole("provider not initialized yet");
return;
}
const web3 = new Web3(coreKitInstance.provider as any);

// Get user's Ethereum public address
const fromAddress = (await web3.eth.getAccounts())[0];

const originalMessage = "YOUR_MESSAGE";

// Sign the message
const signedMessage = await web3.eth.personal.sign(
originalMessage,
fromAddress,
"test password!" // configure your own password here.
);
this.uiConsole(signedMessage);
};

criticalResetAccount = async (): Promise<void> => {
// 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 (!coreKitInstance) {
throw new Error("coreKitInstance is not set");
}
//@ts-ignore
// if (selectedNetwork === WEB3AUTH_NETWORK.MAINNET) {
// throw new Error("reset account is not recommended on mainnet");
// }
await coreKitInstance.tKey.storageLayer.setMetadata({
privKey: new BN(coreKitInstance.metadataKey!, "hex"),
input: { message: "KEY_NOT_FOUND" },
});
this.uiConsole('reset');
this.logout();
}


uiConsole(...args: any[]) {
const el = document.querySelector("#console-ui>p");
if (el) {
el.innerHTML = JSON.stringify(args || {}, null, 2);
}
}
}
Loading

0 comments on commit ef2e22c

Please sign in to comment.