Skip to content

Commit

Permalink
refactor: move vuex hdwallet methods to sdk wallet lib
Browse files Browse the repository at this point in the history
  • Loading branch information
peronczyk committed Oct 24, 2023
1 parent 217334a commit d2f6c8b
Show file tree
Hide file tree
Showing 97 changed files with 486 additions and 755 deletions.
8 changes: 4 additions & 4 deletions 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 package.json
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,7 @@
"svgo": "^3.0.2",
"svgo-loader": "^4.0.0",
"ts-jest": "^27.1.5",
"typescript": "~4.5.5",
"typescript": "~4.9.4",
"vue-cli-plugin-browser-extension": "npm:@rhilip/vue-cli-plugin-browser-extension@^0.27.0",
"web-ext-types": "^3.2.1",
"xml-js": "^1.6.11"
Expand Down
45 changes: 29 additions & 16 deletions src/background/popupHandler.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,34 @@
import { v4 as uuid } from 'uuid';
import type { Dictionary, PopupType } from '@/types';
import type {
Dictionary,
IPopupProps,
PopupType,
} from '@/types';
import {
POPUP_TYPE_SIGN,
POPUP_TYPE_CONNECT,
POPUP_TYPE_RAW_SIGN,
IS_EXTENSION,
} from '@/constants';
import { isTxOfASupportedType } from '@/protocols/aeternity/helpers';

const popups: Dictionary = {};
interface IPopupConfig {
actions: Pick<IPopupProps, 'resolve' | 'reject'>;
props: Omit<IPopupProps, 'resolve' | 'reject'>;
}

const popups: Dictionary<IPopupConfig> = {};

export const getAeppUrl = (v: any) => new URL(v.connection.port.sender.url);

export const openPopup = async (type: PopupType, aepp: any, params?: any) => {
export const openPopup = async (
popupType: PopupType,
aepp: string | object,
params: Partial<IPopupProps> = {},
) => {
const id = uuid();
const { href, protocol, host } = typeof aepp === 'object' ? getAeppUrl(aepp) : new URL(aepp);
const { href, protocol, host } = (typeof aepp === 'object') ? getAeppUrl(aepp) : new URL(aepp);
const { name = host } = (typeof aepp === 'object') ? aepp : {} as any;

const tabs = await browser.tabs.query({ active: true });

// @ts-ignore
tabs.forEach(({ url: tabURL, id: tabId }) => {
const tabUrl = new URL(tabURL as string);
Expand All @@ -28,8 +41,6 @@ export const openPopup = async (type: PopupType, aepp: any, params?: any) => {
});

const extUrl = browser.runtime.getURL('./index.html');
const isRawSign = type === POPUP_TYPE_SIGN && !isTxOfASupportedType(params.tx);
const popupType = isRawSign ? POPUP_TYPE_RAW_SIGN : type;
const popupUrl = `${extUrl}?id=${id}&type=${popupType}&url=${encodeURIComponent(href)}`;
const isMacOsExtension = IS_EXTENSION && window.browser.runtime.getPlatformInfo().then(({ os }) => os === 'mac');

Expand All @@ -41,25 +52,27 @@ export const openPopup = async (type: PopupType, aepp: any, params?: any) => {
});

return new Promise((resolve, reject) => {
if (!popupWindow) reject();
if (!popupWindow) {
reject();
}

popups[id] = {
actions: { resolve, reject },
props: {
app: {
url: href,
icons: aepp?.icons || [],
name: aepp?.name || host,
name,
protocol,
host,
},
...(params?.message && { message: params.message }),
...(params?.txObject && !isRawSign && { tx: params.txObject, txBase64: params.tx }),
...(isRawSign && { data: params.tx }),
message: params.message,
tx: params.tx,
txBase64: params.txBase64,
},
};
});
};

export const removePopup = (id: string) => delete popups[id];

export const getPopup = (id: string) => popups[id];
export const getPopup = (id: string): IPopupConfig => popups[id];
10 changes: 0 additions & 10 deletions src/background/store.js

This file was deleted.

11 changes: 5 additions & 6 deletions src/background/wallet.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
import { watch } from 'vue';
import { isEqual } from 'lodash-es';
import { BrowserRuntimeConnection } from '@aeternity/aepp-sdk';
import { CONNECTION_TYPES } from '@/constants';
import { CONNECTION_TYPES, POPUP_ACTIONS } from '@/constants';
import { removePopup, getPopup } from './popupHandler';
import { detectConnectionType } from './utils';
import store from './store';
import { useAccounts, useAeSdk, useNetworks } from '../composables';

window.browser = require('webextension-polyfill');
Expand All @@ -13,7 +12,7 @@ let isAeSdkBlocked = false;
let connectionsQueue = [];

const addAeppConnection = async (port) => {
const { getAeSdk } = useAeSdk({ store });
const { getAeSdk } = useAeSdk();
const aeSdk = await getAeSdk();
const connection = new BrowserRuntimeConnection({ port });
const clientId = aeSdk.addRpcClient(connection);
Expand All @@ -28,7 +27,7 @@ const addAeppConnection = async (port) => {
export async function init() {
const { activeNetwork } = useNetworks();
const { activeAccount } = useAccounts();
const { isAeSdkReady, getAeSdk, resetNode } = useAeSdk({ store });
const { isAeSdkReady, getAeSdk, resetNode } = useAeSdk();

browser.runtime.onConnect.addListener(async (port) => {
if (port.sender.id !== browser.runtime.id) return;
Expand All @@ -39,7 +38,7 @@ export async function init() {
const popup = getPopup(id);

port.onMessage.addListener((msg) => {
if (msg.type === 'getProps') {
if (msg.type === POPUP_ACTIONS.getProps) {
port.postMessage({ uuid: msg.uuid, res: popup?.props });
return;
}
Expand Down Expand Up @@ -100,7 +99,7 @@ export async function init() {
}

export async function disconnect() {
const { getAeSdk } = useAeSdk({ store });
const { getAeSdk } = useAeSdk();
const aeSdk = await getAeSdk();

aeSdk._clients.forEach((aepp, aeppId) => {
Expand Down
71 changes: 35 additions & 36 deletions src/composables/aeSdk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ import {
METHODS,
} from '@aeternity/aepp-sdk';
import type {
IDefaultComposableOptions,
INetwork,
IResponseChallenge,
IRespondChallenge,
Expand Down Expand Up @@ -51,7 +50,7 @@ const aeppInfo: Record<string, any> = {};
let dryAeSdk: AeSdk;
let dryAeSdkCurrentNodeNetworkId: string;

export function useAeSdk({ store }: IDefaultComposableOptions) {
export function useAeSdk() {
const { aeActiveNetworkSettings, activeNetworkName } = useAeNetworkSettings();
const {
accountsAddressList,
Expand Down Expand Up @@ -95,45 +94,45 @@ export function useAeSdk({ store }: IDefaultComposableOptions) {
aeSdkBlocked = true;
isAeSdkReady.value = false;

await Promise.all([
watchUntilTruthy(() => store.state.isRestored),
watchUntilTruthy(isLoggedIn),
]);
await watchUntilTruthy(isLoggedIn);

storedNetworkName = activeNetworkName.value;
const nodeInstance = await createNodeInstance(aeActiveNetworkSettings.value.nodeUrl);

aeSdk = new AeSdkSuperhero(store, {
name: 'Superhero',
nodes: [{
name: activeNetworkName.value,
instance: nodeInstance!,
}],
id: 'Superhero Wallet',
type: IS_EXTENSION ? WALLET_TYPE.extension : WALLET_TYPE.window,
onConnection(aeppId: string, params: any, origin: string) {
aeppInfo[aeppId] = { ...params, origin };
},
onDisconnect(aeppId: string) {
delete aeppInfo[aeppId];
},
async onSubscription(aeppId: string, params: any, origin: string) {
const aepp = aeppInfo[aeppId];
const host = IS_EXTENSION_BACKGROUND ? aepp.origin : origin;
if (await checkOrAskPermission(host, METHODS.subscribeAddress)) {
return getLastActiveProtocolAccount(PROTOCOL_AETERNITY)!.address;
}
return Promise.reject(new RpcRejectedByUserError('Rejected by user'));
},
async onAskAccounts(aeppId: string, params: any, origin: string) {
const aepp = aeppInfo[aeppId];
const host = IS_EXTENSION_BACKGROUND ? aepp.origin : origin;
if (await checkOrAskPermission(host, METHODS.address)) {
return accountsAddressList.value;
}
return Promise.reject(new RpcRejectedByUserError('Rejected by user'));
aeSdk = new AeSdkSuperhero(
{
name: 'Superhero',
nodes: [{
name: activeNetworkName.value,
instance: nodeInstance!,
}],
id: 'Superhero Wallet',
type: IS_EXTENSION ? WALLET_TYPE.extension : WALLET_TYPE.window,
onConnection(aeppId: string, params: any, origin: string) {
aeppInfo[aeppId] = { ...params, origin };
},
onDisconnect(aeppId: string) {
delete aeppInfo[aeppId];
},
async onSubscription(aeppId: string, params: any, origin: string) {
const aepp = aeppInfo[aeppId];
const host = IS_EXTENSION_BACKGROUND ? aepp.origin : origin;
if (await checkOrAskPermission(host, METHODS.subscribeAddress)) {
return getLastActiveProtocolAccount(PROTOCOL_AETERNITY)!.address;
}
return Promise.reject(new RpcRejectedByUserError('Rejected by user'));
},
async onAskAccounts(aeppId: string, params: any, origin: string) {
const aepp = aeppInfo[aeppId];
const host = IS_EXTENSION_BACKGROUND ? aepp.origin : origin;
if (await checkOrAskPermission(host, METHODS.address)) {
return accountsAddressList.value;
}
return Promise.reject(new RpcRejectedByUserError('Rejected by user'));
},
},
});
nodeNetworkId,
);

if (IN_FRAME && !FramesConnection.initialized) {
FramesConnection.init(aeSdk);
Expand Down
4 changes: 2 additions & 2 deletions src/composables/latestTransactionList.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,12 +33,12 @@ const { onNetworkChange } = createNetworkWatcher();
export function useLatestTransactionList({ store }: IDefaultComposableOptions) {
const { accounts } = useAccounts();
const { accountsTotalBalance } = useBalances();
const { nodeNetworkId } = useAeSdk({ store });
const { nodeNetworkId } = useAeSdk();

const {
transactions,
fetchTransactions,
} = useTransactionList({ store });
} = useTransactionList();

const btcTransactions = ref<ITransaction[]>([]);

Expand Down
11 changes: 4 additions & 7 deletions src/composables/maxAmount.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,7 @@ import {
} from '@aeternity/aepp-sdk';

import FungibleTokenFullInterfaceACI from '@/lib/contracts/FungibleTokenFullInterfaceACI.json';
import type {
IDefaultComposableOptions,
IFormModel,
} from '@/types';
import type { IFormModel } from '@/types';
import {
executeAndSetInterval,
handleUnknownError,
Expand All @@ -43,16 +40,16 @@ import { useAeSdk } from './aeSdk';
import { useBalances } from './balances';
import { useAccounts } from './accounts';

export interface MaxAmountOptions extends IDefaultComposableOptions {
export interface MaxAmountOptions {
formModel: Ref<IFormModel>
}

/**
* Composable that allows to use real max amount of selected token
* considering the fee that needs to be paid.
*/
export function useMaxAmount({ store, formModel }: MaxAmountOptions) {
const { getAeSdk } = useAeSdk({ store });
export function useMaxAmount({ formModel }: MaxAmountOptions) {
const { getAeSdk } = useAeSdk();
const { balance } = useBalances();
const { getLastActiveProtocolAccount } = useAccounts();

Expand Down
12 changes: 2 additions & 10 deletions src/composables/modals.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,8 @@ import {
ref,
} from 'vue';
import type {
IModalProps,
ProtocolView,
RejectCallback,
ResolveCallback,
StatusIconType,
} from '@/types';
import {
Expand All @@ -33,13 +32,6 @@ interface IModalSettings {
viewComponentName?: ProtocolView;
}

export interface IModalProps {
[key: string]: any; // Props defined on the component's level
resolve?: ResolveCallback;
reject?: RejectCallback;
show?: boolean;
}

/**
* Params passed to the modal when trying to open it.
*/
Expand Down Expand Up @@ -117,7 +109,7 @@ export function useModals() {
/**
* These modals use the `usePopupProps` composable instead of props
* even if they are not opened in a popup
*/
*/
if (modalSettings.showInPopupIfWebFrame && !inPopup) {
const { setPopupProps } = usePopupProps();
setPopupProps({
Expand Down
8 changes: 3 additions & 5 deletions src/composables/multisigAccountCreate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ import {
import dayjs from 'dayjs';

import type {
IDefaultComposableOptions,
IMultisigAccount,
IMultisigCreationPhase,
IRawMultisigAccount,
Expand All @@ -34,12 +33,12 @@ const pendingMultisigCreationTxs = ref<Record<string, IRawMultisigAccount>>({});
const multisigAccountCreationPhase = ref<IMultisigCreationPhase>(null);
const notEnoughBalanceToCreateMultisig = ref<boolean>(false);

export function useMultisigAccountCreate({ store }: IDefaultComposableOptions) {
const { getDryAeSdk, getAeSdk } = useAeSdk({ store });
export function useMultisigAccountCreate() {
const { getDryAeSdk, getAeSdk } = useAeSdk();
const {
getMultisigAccountByContractId,
addPendingMultisigAccount,
} = useMultisigAccounts({ store, pollOnce: true });
} = useMultisigAccounts({ pollOnce: true });
const { balances } = useBalances();

const multisigAccount = ref<IMultisigAccount | null>(null);
Expand Down Expand Up @@ -146,7 +145,6 @@ export function useMultisigAccountCreate({ store }: IDefaultComposableOptions) {
tx: signedAttachTx,
}),
{
modal: false,
fromAccount: payerId,
} as any,
);
Expand Down
Loading

0 comments on commit d2f6c8b

Please sign in to comment.