Skip to content

Support connection from smart wallets #416

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Mar 16, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion packages/backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
"bluebird": "3.7.2",
"body-parser": "1.19.0",
"discord.js": "^12.5.1",
"ethers": "4.0.48",
"ethers": "5.0.32",
"express": "4.17.1",
"express-graphql": "0.11.0",
"graphql": "15.4.0",
Expand Down
3 changes: 2 additions & 1 deletion packages/backend/src/handlers/auth-webhook/handler.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { did } from '@metafam/utils';
import { Request, Response } from 'express';

import { defaultProvider } from '../../lib/ethereum';
import { getOrCreatePlayer } from './users';

const unauthorizedVariables = {
Expand Down Expand Up @@ -33,7 +34,7 @@ export const authHandler = async (
if (!token) {
res.json(unauthorizedVariables);
} else {
const claim = did.verifyToken(token);
const claim = await did.verifyToken(token, defaultProvider);
if (!claim) {
res.status(401).send();
return;
Expand Down
2 changes: 1 addition & 1 deletion packages/utils/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
},
"dependencies": {
"bignumber.js": "^9.0.1",
"ethers": "5.0.17",
"ethers": "5.0.32",
"js-base64": "3.5.2",
"uuid": "8.3.2"
},
Expand Down
28 changes: 11 additions & 17 deletions packages/utils/src/did/index.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { providers, utils } from 'ethers';
import { providers } from 'ethers';
import { Base64 } from 'js-base64';
import { v4 as uuidv4 } from 'uuid';

import { signerHelper } from '../ethereumHelper';
import { signerHelper, verifySignature } from '../ethereumHelper';

const tokenDuration = 1000 * 60 * 60 * 24 * 7; // 7 days

Expand Down Expand Up @@ -36,26 +36,20 @@ export async function createToken(
return Base64.encode(JSON.stringify([proof, serializedClaim]));
}

export function getSignerAddress(token: string): string | null {
try {
const rawToken = Base64.decode(token);
const [proof, rawClaim] = JSON.parse(rawToken);
return utils.verifyMessage(rawClaim, proof);
} catch (e) {
console.error('Token verification failed', e);
return null;
}
}

export function verifyToken(token: string): Claim | null {
export async function verifyToken(
token: string,
provider: providers.JsonRpcProvider,
): Promise<Claim | null> {
try {
const rawToken = Base64.decode(token, 'base64');
const [proof, rawClaim] = JSON.parse(rawToken);
const claim: Claim = JSON.parse(rawClaim);
const address = claim.iss;

const valid = await verifySignature(address, rawClaim, proof, provider);

const signerAddress = utils.verifyMessage(rawClaim, proof);
if (signerAddress !== claim.iss) {
return null;
if (!valid) {
throw new Error('invalid signature');
}
return claim;
} catch (e) {
Expand Down
49 changes: 47 additions & 2 deletions packages/utils/src/ethereumHelper.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { providers } from 'ethers';
import { Contract, providers, utils } from 'ethers';

export async function signerHelper(
provider: providers.Web3Provider,
rawMessage: string,
) {
): Promise<string> {
const ethereum = provider.provider;
const signer = provider.getSigner();
const address = await signer.getAddress();
Expand All @@ -19,3 +19,48 @@ export async function signerHelper(
});
return signature;
}

const smartWalletABI = [
'function isValidSignature(bytes32 _message, bytes _signature) public view returns (bool)',
];

enum WalletType {
EOA,
SMART,
}

async function getWalletType(
address: string,
provider: providers.BaseProvider,
): Promise<WalletType> {
const code = await provider.getCode(address);
return code === '0x' ? WalletType.EOA : WalletType.SMART;
}

export async function verifySignature(
address: string,
message: string,
signature: string,
provider: providers.BaseProvider,
): Promise<boolean> {
const walletType = await getWalletType(address, provider);

if (walletType === WalletType.EOA) {
const recoveredAddress = utils.verifyMessage(message, signature);
return address === recoveredAddress;
}

// Smart wallet
const arrayishMessage = utils.toUtf8Bytes(message);
const hexMessage = utils.hexlify(arrayishMessage);
const hexArray = utils.arrayify(hexMessage);
const hashMessage = utils.hashMessage(hexArray);

const contract = new Contract(address, smartWalletABI, provider);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This also throws sometimes if the contract doesn't support the ABI, and should be inside the try-catch

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Are you sure about this ? It is a constructor, so it's sync, so I don't think it can go check the contract code and throw here

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

True. I've had some issues with ethersJS sometimes though. But never mind. Lets go ahead with this

try {
const returnValue = await contract.isValidSignature(hashMessage, signature);
return returnValue;
} catch(error) {
throw new Error('unsupported smart wallet');
}
}
50 changes: 30 additions & 20 deletions packages/web/contexts/Web3Context.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,17 @@ import WalletConnectProvider from '@walletconnect/web3-provider';
import { providers } from 'ethers';
import {
clearToken,
clearWCMobile,
clearWalletConnect,
getTokenFromStore,
setTokenInStore,
} from 'lib/auth';
import React, { createContext, useCallback, useEffect, useRef,useState } from 'react';
import React, {
createContext,
useCallback,
useEffect,
useRef,
useState,
} from 'react';
import Web3Modal from 'web3modal';

import { CONFIG } from '../config';
Expand Down Expand Up @@ -49,19 +55,19 @@ const web3Modal =
providerOptions,
});

function getExistingAuth(ethAddress: string): string | null {
async function getExistingAuth(
ethersProvider: providers.Web3Provider,
): Promise<string | null> {
const token = getTokenFromStore();
if (!token) return null;

const signerAddress = did.getSignerAddress(token);
if (
!signerAddress ||
signerAddress.toLowerCase() !== ethAddress.toLowerCase()
) {
try {
await did.verifyToken(token, ethersProvider);
return token;
} catch (e) {
clearToken();
return null;
}
return token;
}

async function authenticateWallet(
Expand All @@ -73,11 +79,14 @@ async function authenticateWallet(
}

interface Web3ContextProviderOptions {
children: React.ReactElement,
resetUrqlClient?: () => void,
children: React.ReactElement;
resetUrqlClient?: () => void;
}

export const Web3ContextProvider: React.FC<Web3ContextProviderOptions> = ({ children, resetUrqlClient }) => {
export const Web3ContextProvider: React.FC<Web3ContextProviderOptions> = ({
children,
resetUrqlClient,
}) => {
const [provider, setProvider] = useState<providers.Web3Provider | null>(null);
const [isConnected, setIsConnected] = useState<boolean>(false);
const [isConnecting, setIsConnecting] = useState<boolean>(false);
Expand All @@ -89,27 +98,27 @@ export const Web3ContextProvider: React.FC<Web3ContextProviderOptions> = ({ chil
if (web3Modal === false) return;

web3Modal.clearCachedProvider();
clearWCMobile();
clearWalletConnect();
clearToken();
setAuthToken(null);
setAddress(null);
setProvider(null);
setIsConnecting(false);
setIsConnected(false);
if(resetUrqlClient) resetUrqlClient();
if (resetUrqlClient) resetUrqlClient();
}, [resetUrqlClient]);

const connectWeb3 = useCallback(async () => {
if (web3Modal === false) return;
setIsConnecting(true);

try {
const modalProvider = await web3Modal.connect();
const ethersProvider = new providers.Web3Provider(modalProvider);
const web3Provider = await web3Modal.connect();
const ethersProvider = new providers.Web3Provider(web3Provider);

const ethAddress = await ethersProvider.getSigner().getAddress();

let token: string | null = getExistingAuth(ethAddress);
let token: string | null = await getExistingAuth(ethersProvider);
if (!token) {
token = await authenticateWallet(ethersProvider);
}
Expand All @@ -119,15 +128,16 @@ export const Web3ContextProvider: React.FC<Web3ContextProviderOptions> = ({ chil
setAuthToken(token);
setIsConnecting(false);
setIsConnected(true);
if(resetUrqlClient) resetUrqlClient();
} catch (_) {
if (resetUrqlClient) resetUrqlClient();
} catch (error) {
console.log(error);
setIsConnecting(false);
disconnect();
}
}, [resetUrqlClient, disconnect]);

useEffect(() => {
if(calledOnce.current) return;
if (calledOnce.current) return;
calledOnce.current = true;

if (web3Modal === false) return;
Expand Down
6 changes: 5 additions & 1 deletion packages/web/lib/auth.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { get, remove, set } from './store';

const STORAGE_KEY = 'metagame-auth-token';
const walletconnectKey = 'walletconnect';
const mobileLinkChoiceKey = 'WALLETCONNECT_DEEPLINK_CHOICE';

export const getTokenFromStore = (): string | null => get(STORAGE_KEY);
Expand All @@ -11,4 +12,7 @@ export const clearToken = (): void => remove(STORAGE_KEY);

// Temporary workaround to clear cached walletconnect mobile wallet
// https://github.com/WalletConnect/walletconnect-monorepo/issues/394
export const clearWCMobile = (): void => remove(mobileLinkChoiceKey);
export const clearWalletConnect = (): void => {
remove(walletconnectKey);
remove(mobileLinkChoiceKey);
};
2 changes: 1 addition & 1 deletion packages/web/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
"@metafam/utils": "1.0.0",
"@walletconnect/web3-provider": "1.3.1",
"copy-to-clipboard": "^3.3.1",
"ethers": "5.0.17",
"ethers": "5.0.32",
"fake-tag": "2.0.0",
"framer-motion": "3.1.1",
"graphql": "15.4.0",
Expand Down
Loading