Skip to content

Commit

Permalink
fix: session, network and wc (#905)
Browse files Browse the repository at this point in the history
  • Loading branch information
kenshyx committed Mar 2, 2021
1 parent ac56158 commit e651a4f
Show file tree
Hide file tree
Showing 9 changed files with 86 additions and 47 deletions.
14 changes: 12 additions & 2 deletions api/hub/src/resolvers/query.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,12 @@ const query = {
query.getPost(_source, { pubKey, id: postID }, { dataSources }),
),
);
const quotedByAuthors = qPosts?.map(el => el.author);
let uniqueAuthors = {};
qPosts.forEach(el => {
uniqueAuthors[el.author.pubKey] = el.author;
});
const quotedByAuthors: any = Object.values(uniqueAuthors);
uniqueAuthors = null;
if (pubKey) {
const pProfile = await dataSources.profileAPI.resolveProfile(pubKey);
quotedByAuthors?.sort((a, b) => {
Expand Down Expand Up @@ -79,7 +84,12 @@ const query = {
query.getPost(_source, { pubKey, id: postID }, { dataSources }),
),
);
const quotedByAuthors = qPosts?.map(el => el.author);
let uniqueAuthors = {};
qPosts.forEach(el => {
uniqueAuthors[el.author.pubKey] = el.author;
});
const quotedByAuthors: any = Object.values(uniqueAuthors);
uniqueAuthors = null;
if (pubKey) {
const pProfile = await dataSources.profileAPI.resolveProfile(pubKey);
quotedByAuthors?.sort((a, b) => {
Expand Down
44 changes: 27 additions & 17 deletions sdk-packages/auth/src/auth.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import services, {
AUTH_ENDPOINT,
AUTH_MESSAGE,
AUTH_SERVICE,
authStatus,
ethAddressCache,
moduleName,
} from './constants';
Expand All @@ -37,7 +38,7 @@ const service: AkashaService = (invoke, log, globalChannel) => {
let db: Database;
let channel;
let sessKey;
let currentUser: { pubKey: string; ethAddress: string };
let currentUser: { pubKey: string; ethAddress: string; isNewUser?: boolean };
let tokenGenerator: () => Promise<UserAuth>;
const waitForAuth = 'waitForAuth';
const providerKey = '@providerType';
Expand All @@ -54,12 +55,14 @@ const service: AkashaService = (invoke, log, globalChannel) => {
channel.onmessage = function (event) {
const { type } = event.data;
if (type === SYNC_REQUEST) {
const response = {
[providerKey]: sessionStorage.getItem(providerKey),
[currentUserKey]: sessionStorage.getItem(currentUserKey),
identity: { key: sessKey, value: identity?.toString() },
};
channel.postMessage({ response, type: SYNC_RESPONSE });
if (currentUser) {
const response = {
[providerKey]: sessionStorage.getItem(providerKey),
[currentUserKey]: sessionStorage.getItem(currentUserKey),
identity: { key: sessKey, value: identity?.toString() },
};
channel.postMessage({ response, type: SYNC_RESPONSE });
}
} else if (type === SYNC_RESPONSE) {
const { response } = event.data;
if (response && response.identity.key !== sessKey) {
Expand Down Expand Up @@ -87,7 +90,7 @@ const service: AkashaService = (invoke, log, globalChannel) => {
};
}
const signIn = async (provider: EthProviders = EthProviders.Web3Injected) => {
let currentProvider;
let currentProvider: number;
// const { setServiceSettings } = invoke(coreServices.SETTINGS_SERVICE);
const cache = await invoke(commonServices[CACHE_SERVICE]).getStash();

Expand All @@ -98,6 +101,11 @@ const service: AkashaService = (invoke, log, globalChannel) => {
currentProvider = +sessionStorage.getItem(providerKey); // cast to int
} else {
currentProvider = provider;
if (currentProvider === EthProviders.WalletConnect) {
// @Todo: track https://github.com/WalletConnect/walletconnect-monorepo/issues/444
// until there is a consistent way of detecting previous sessions and initiate disconnect
localStorage.clear();
}
}
try {
const web3 = await invoke(commonServices[WEB3_SERVICE]).regen(currentProvider);
Expand Down Expand Up @@ -140,16 +148,18 @@ const service: AkashaService = (invoke, log, globalChannel) => {

// @Todo: on error try to setupMail
await hubUser.setupMailbox();
sessionStorage.setItem(providerKey, currentProvider.toString());
sessionStorage.setItem(sessKey, identity.toString());
sessionStorage.setItem(currentUserKey, JSON.stringify(currentUser));
if (channel) {
const response = {
[providerKey]: sessionStorage.getItem(providerKey),
identity: { key: sessKey, value: identity?.toString() },
identity: { key: sessKey, value: sessionStorage.getItem(sessKey) },
[currentUserKey]: sessionStorage.getItem(currentUserKey),
};
channel.postMessage({ response, type: SYNC_RESPONSE });
}
sessionStorage.setItem(providerKey, currentProvider);
sessionStorage.setItem(sessKey, identity.toString());
sessionStorage.setItem(currentUserKey, JSON.stringify(currentUser));

if (currentUser?.pubKey) {
db = new Database(
`awf-alpha-user-${currentUser.pubKey.slice(-8)}`,
Expand All @@ -174,7 +184,7 @@ const service: AkashaService = (invoke, log, globalChannel) => {
args: null,
},
});
return currentUser;
return Object.assign(currentUser, authStatus);
};

const getSession = async () => {
Expand Down Expand Up @@ -261,9 +271,6 @@ const service: AkashaService = (invoke, log, globalChannel) => {

const signOut = async () => {
sessionStorage.clear();
const cache = await invoke(commonServices[CACHE_SERVICE]).getStash();
await invoke(commonServices[WEB3_SERVICE]).destroy({});
cache.clear();
identity = null;
hubClient = null;
hubUser = null;
Expand All @@ -274,7 +281,10 @@ const service: AkashaService = (invoke, log, globalChannel) => {
if (channel) {
channel.postMessage({ type: SIGN_OUT_EVENT });
}
return;
const cache = await invoke(commonServices[CACHE_SERVICE]).getStash();
await invoke(commonServices[WEB3_SERVICE]).destroy({});
cache.clear();
return true;
};

const signData = async (data: object | string, base64Format: boolean = false) => {
Expand Down
4 changes: 4 additions & 0 deletions sdk-packages/auth/src/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,10 @@ export const tokenCache = 'token';
export const moduleName = 'auth';
const servicePath = buildServicePath(moduleName);

export const authStatus = {
isNewUser: false,
};

const services: IAkashaModuleServices = {
[AUTH_SERVICE]: servicePath(AUTH_SERVICE),
};
Expand Down
8 changes: 5 additions & 3 deletions sdk-packages/auth/src/hub.auth.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { PrivateKey, Identity, UserAuth } from '@textile/hub';
import { authStatus } from './constants';

const metamaskGen = (ethAddress: string, secret: string, appName = 'ethereum.world') =>
`
Expand Down Expand Up @@ -75,17 +76,18 @@ export const loginWithChallenge = (
/** Convert the challenge json to a Buffer */
const buf = Buffer.from(data.value);
let addressChallenge;
let currentAddress;
let ethAddress;
if (data.addressChallenge) {
addressChallenge = await signer.signMessage(data.addressChallenge);
currentAddress = await signer.getAddress();
ethAddress = await signer.getAddress();
authStatus.isNewUser = true;
}
/** User our identity to sign the challenge */
const signed = await identity.sign(buf);
socket.send(
JSON.stringify({
addressChallenge,
ethAddress: currentAddress,
ethAddress,
type: 'challenge',
sig: Buffer.from(signed).toJSON(),
}),
Expand Down
32 changes: 16 additions & 16 deletions sdk-packages/common/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 sdk-packages/common/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@
"@akashaproject/sdk-runtime": "*",
"@walletconnect/web3-provider": "1.3.6",
"@akashaproject/ui-awf-typings": "*",
"ethers": "5.0.30",
"ethers": "5.0.31",
"browser-image-resizer": "2.1.3",
"@metamask/detect-provider": "1.2.0"
},
Expand Down
8 changes: 5 additions & 3 deletions sdk-packages/common/src/web3.methods/provider-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,13 @@ export const ConnectToInjected = async () => {
if (!acc?.length) {
throw new Error('Must connect at least one address from the wallet.');
}
provider.on('accountsChanged', _ => {
const refreshPage = _ => {
sessionStorage.clear();
// refresh on metamask logout or changed acc
window.location.reload();
});
};
provider.on('accountsChanged', refreshPage);
provider.on('chainChanged', refreshPage);
return provider;
};

Expand All @@ -48,7 +50,7 @@ export const ConnectToWalletConnect = (
return new Promise(async (resolve, reject) => {
const qrcode = true;
let infuraId = '';
let chainId = 1;
let chainId;

if (opts) {
infuraId = opts.infuraId || '';
Expand Down
7 changes: 2 additions & 5 deletions sdk-packages/common/src/web3.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import { EthProviders } from '@akashaproject/ui-awf-typings';
import { ethers } from 'ethers';
import commonServices, { CACHE_SERVICE, ETH_NETWORK, moduleName, WEB3_SERVICE } from './constants';
import getProvider from './web3.methods/provider';
import * as net from 'net';

const service: AkashaService = (invoke, log) => {
const regen = async provider => {
Expand Down Expand Up @@ -71,13 +70,11 @@ const service: AkashaService = (invoke, log) => {
const checkCurrentNetwork = async () => {
const web3Instance = await getWeb3Instance();
const { getSettings } = invoke(coreServices.SETTINGS_SERVICE);
const network = await web3Instance.getNetwork();
const network = await web3Instance.detectNetwork();
const moduleSettings = await getSettings(moduleName);
const networkName = moduleSettings[ETH_NETWORK];
if (network?.name !== networkName) {
throw new Error(
`Change the ethereum network to: ${networkName}! Currently on: ${network?.name}`,
);
throw new Error(`Please change the ethereum network to ${networkName}!`);
}
log.info(`currently on network: ${network.name}`);
};
Expand Down
14 changes: 14 additions & 0 deletions sdk-packages/registry/src/ens.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ const service: AkashaService = (invoke, log) => {
let AkashaRegistrarInstance;
let ReverseRegistrarInstance;
let ENSinstance;
let chainChecked = false;

// register an akasha.eth subdomain
const registerName = async (args: { name: string }) => {
Expand Down Expand Up @@ -46,7 +47,15 @@ const service: AkashaService = (invoke, log) => {
};

const resolveAddress = async (args: { ethAddress: string }) => {
if (!chainChecked) {
const { checkCurrentNetwork } = await invoke(commonServices[WEB3_SERVICE]);
await checkCurrentNetwork();
chainChecked = true;
}
const web3Provider = await invoke(commonServices[WEB3_SERVICE]).getWeb3Instance();
if (!AkashaRegistrarInstance) {
await setupContracts();
}
return web3Provider.lookupAddress(args.ethAddress);
};

Expand Down Expand Up @@ -75,6 +84,11 @@ const service: AkashaService = (invoke, log) => {

// boilerplate for smart contracts
const setupContracts = async () => {
if (!chainChecked) {
const { checkCurrentNetwork } = await invoke(commonServices[WEB3_SERVICE]);
await checkCurrentNetwork();
chainChecked = true;
}
const web3Provider = await invoke(commonServices[WEB3_SERVICE]).getWeb3Instance();
const contractFactory = await invoke(commonServices[WEB3_SERVICE]).getContractFactory();
const AkashaRegistrar = await contractFactory.fromSolidity(AkashaRegistrarABI);
Expand Down

0 comments on commit e651a4f

Please sign in to comment.