Skip to content

Commit

Permalink
Update sfa rn apps
Browse files Browse the repository at this point in the history
  • Loading branch information
yashovardhan committed Oct 25, 2023
1 parent 5041fb8 commit b12478a
Show file tree
Hide file tree
Showing 11 changed files with 614 additions and 1,208 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ import {
} from 'react-native';
import auth from '@react-native-firebase/auth';
import EncryptedStorage from 'react-native-encrypted-storage';
// @ts-ignore
import {decode as atob} from 'base-64';
import {IProvider} from '@web3auth/base';

Expand Down Expand Up @@ -48,7 +47,6 @@ const chainConfig = {
const web3auth = new Web3Auth(EncryptedStorage, {
clientId, // Get your Client ID from Web3Auth Dashboard
web3AuthNetwork: 'sapphire_mainnet',
usePnPKey: false, // By default, this sdk returns CoreKitKey
});

const privateKeyProvider = new EthereumPrivateKeyProvider({
Expand Down

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

Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
"@react-native/eslint-config": "^0.72.2",
"@react-native/metro-config": "^0.72.7",
"@tsconfig/react-native": "^3.0.0",
"@types/base-64": "^1.0.1",
"@types/metro-config": "^0.76.3",
"@types/react": "^18.0.24",
"@types/react-test-renderer": "^18.0.0",
Expand Down
177 changes: 93 additions & 84 deletions single-factor-auth-react-native/sfa-rn-expo-auth0-example/App.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
/* eslint-disable @typescript-eslint/no-use-before-define */
/* eslint-disable @typescript-eslint/ban-ts-comment */
import '@ethersproject/shims';
import { decode as atob } from "base-64";
// @ts-ignore
import React, {useEffect, useState} from 'react';
import {
Button,
Expand All @@ -12,56 +10,54 @@ import {
Dimensions,
ActivityIndicator,
} from 'react-native';
import RPC from './ethersRPC'; // for using ethers.js
import {IProvider} from '@web3auth/base';

import Web3Auth from '@web3auth/single-factor-auth-react-native';
import {EthereumPrivateKeyProvider} from '@web3auth/ethereum-provider';
import * as SecureStore from "expo-secure-store";
import { Auth0Provider, useAuth0 } from "react-native-auth0";
import {ethers} from 'ethers';

const clientId =
'BPi5PB_UiIZ-cPz1GtV5i1I2iOSOHuimiXBI0e-Oe_u6X3oVAbCiAZOTEBtTXw4tsluTITPqA8zMsfxIKMjiqNQ'; // get from https://dashboard.web3auth.io

const verifier = 'w3a-auth0-demo';

const chainConfig = {
chainId: '0x1', // Please use 0x1 for Mainnet
rpcTarget: 'https://rpc.ankr.com/eth',
displayName: 'Ethereum Mainnet',
blockExplorer: 'https://etherscan.io/',
ticker: 'ETH',
tickerName: 'Ethereum',
};

const web3auth = new Web3Auth(SecureStore, {
clientId,
web3AuthNetwork: 'sapphire_mainnet',
usePnPKey: false, // By default, this sdk returns CoreKitKey
});

const privateKeyProvider = new EthereumPrivateKeyProvider({
config: {chainConfig},
});

const Home = () => {
const [privateKey, setPrivateKey] = useState<string | null>();
const [provider, setProvider] = useState<IProvider | null>(null);
const [loggedIn, setLoggedIn] = useState<boolean>(false);
const [loading, setLoading] = useState<boolean>(false);
const [userInfo, setUserInfo] = useState<string>('');
const [consoleUI, setConsoleUI] = useState<string>('');
const [web3auth, setWeb3Auth] = useState<Web3Auth | null>(null);

useEffect(() => {
async function init() {
try {
const authProvider = new Web3Auth(SecureStore, {
clientId:
'BEglQSgt4cUWcj6SKRdu5QkOXTsePmMcusG5EAoyjyOYKlVRjIF1iCNnMOTfpzCiunHRrMui8TIwQPXdkQ8Yxuk', // Get your Client ID from Web3Auth Dashboard
web3AuthNetwork: 'cyan',
usePnPKey: false, // By default, this sdk returns CoreKitKey
});

const privateKeyProvider = new EthereumPrivateKeyProvider({
config: {
/*
pass the chain config that you want to connect with
all chainConfig fields are required.
*/
chainConfig: {
chainId: '0x1',
rpcTarget: 'https://rpc.ankr.com/eth',
displayName: 'mainnet',
blockExplorer: 'https://etherscan.io/',
ticker: 'ETH',
tickerName: 'Ethereum',
},
},
});
setWeb3Auth(authProvider);
await authProvider.init(privateKeyProvider);

if (authProvider.connected) {
const finalPrivateKey = await authProvider.provider!.request({
method: 'eth_private_key',
});

setPrivateKey(finalPrivateKey as string);
uiConsole('Private Key: ' + finalPrivateKey);
await web3auth.init(privateKeyProvider);

if (web3auth.sessionId) {
setProvider(web3auth.provider);
setLoggedIn(true);
uiConsole('Logged In', web3auth.sessionId);
}
} catch (error) {
uiConsole(error, 'mounted caught');
Expand All @@ -74,6 +70,7 @@ const Home = () => {

const signInWithAuth0 = async () => {
try {
//@ts-ignore
await authorize({ scope: "openid profile email" }, { customScheme: "auth0.com.web3authsfaauth0" }, { responseType: "token id_token" });
const credentials = await getCredentials();

Expand Down Expand Up @@ -103,67 +100,83 @@ const Home = () => {

const parsedToken = parseToken(idToken);
setUserInfo(parsedToken);
console.log("parsedToken", parsedToken);

const verifier = "web3auth-auth0-demo";
const verifierId = parsedToken.sub;

const provider = await web3auth!.connect({
verifier, // e.g. `web3auth-sfa-verifier` replace with your verifier name, and it has to be on the same network passed in init().
verifierId, // e.g. `Yux1873xnibdui` or `[email protected]` replace with your verifier id(sub or email)'s value.
idToken,
});
const finalPrivateKey = await provider!.request({
method: 'eth_private_key',
});

setPrivateKey(finalPrivateKey as string);
uiConsole('Private Key: ' + finalPrivateKey);

setLoading(false);
uiConsole('Logged In');
if (web3auth.connected) {
setLoggedIn(true);
uiConsole('Logged In');
}
} catch (e) {
uiConsole(e);
setLoading(false);
}
};

const getChainId = async () => {
setConsoleUI('Getting chain id');
const networkDetails = await RPC.getChainId();
uiConsole(networkDetails);
};

const getAccounts = async () => {
setConsoleUI('Getting account');
const address = await RPC.getAccounts(privateKey as string);
// 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);
// 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);
};
const authenticateUser = async () => {
setConsoleUI('Authenticating user');
const data = await web3auth!
.authenticateUser()
.catch(error => console.log('error', error));
uiConsole(data);
// 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.web3authsfaauth0" });
setPrivateKey(null);
web3auth.logout();
setProvider(null);
setLoggedIn(false);
setUserInfo('');
};

Expand All @@ -174,15 +187,11 @@ const Home = () => {

const loggedInView = (
<View style={styles.buttonArea}>
<Button title="Get User Info" onPress={() => uiConsole(userInfo)} />
<Button title="Get Chain ID" onPress={() => getChainId()} />
<Button title="Get Accounts" onPress={() => getAccounts()} />
<Button title="Get Balance" onPress={() => getBalance()} />
<Button title="Send Transaction" onPress={() => sendTransaction()} />
<Button title="Sign Message" onPress={() => signMessage()} />
<Button title="Get Private Key" onPress={() => uiConsole(privateKey)} />
<Button title="Authenticate user" onPress={authenticateUser} />
<Button title="Log Out" onPress={logout} />
<Button title="Get User Info" onPress={() => uiConsole(userInfo)} />
<Button title="Get Accounts" onPress={() => getAccounts()} />
<Button title="Get Balance" onPress={() => getBalance()} />
<Button title="Sign Message" onPress={() => signMessage()} />
<Button title="Log Out" onPress={logout} />
</View>
);

Expand All @@ -195,7 +204,7 @@ const Home = () => {

return (
<View style={styles.container}>
{privateKey ? loggedInView : unloggedInView}
{loggedIn ? loggedInView : unloggedInView}
<View style={styles.consoleArea}>
<Text style={styles.consoleText}>Console:</Text>
<ScrollView style={styles.consoleUI}>
Expand All @@ -208,7 +217,7 @@ const Home = () => {

const App = () => {
return (
<Auth0Provider domain={"shahbaz-torus.us.auth0.com"} clientId={"294QRkchfq2YaXUbPri7D6PH7xzHgQMT"}>
<Auth0Provider domain={"https://web3auth.au.auth0.com"} clientId={"hUVVf4SEsZT7syOiL0gLU9hFEtm2gQ6O"}>
<Home />
</Auth0Provider>
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
[
"react-native-auth0",
{
"domain": "shahbaz-torus.us.auth0.com",
"domain": "https://web3auth.au.auth0.com",
"customScheme": "auth0.com.web3authsfaauth0"
}
]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,13 @@ module.exports = function(api) {
api.cache(true);
return {
presets: ['babel-preset-expo'],
overrides: [
{
test: './node_modules/ethers',
plugins: [
["@babel/plugin-transform-private-methods", { "loose": true }]
]
}
]
};
};
Loading

0 comments on commit b12478a

Please sign in to comment.