Skip to content
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

Move vuex hdWallet methods to SDK wallet lib #2409

Merged
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
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.5",
"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,
Comment on lines +68 to +70
Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Previously the Raw Sign modal was receiving the props in a different format than the regular sign modal. I aligned both modals as they both are using the PopupProps composable. Now the structure is enforced by the TypeScript - less possible to make a mistake.

},
};
});
};

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
25 changes: 10 additions & 15 deletions src/composables/fungibleTokens.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
import { watch } from 'vue';
import camelCaseKeysDeep from 'camelcase-keys-deep';
import BigNumber from 'bignumber.js';
import { Encoded, Encoding } from '@aeternity/aepp-sdk';
import { Contract, Encoded, Encoding } from '@aeternity/aepp-sdk';
import { fetchAllPages, handleUnknownError, toShiftedBigNumber } from '@/utils';
import type {
BigNumberPublic,
IDefaultComposableOptions,
IToken,
ITokenBalanceResponse,
ITokenList,
Expand All @@ -28,6 +27,8 @@ import { createNetworkWatcher } from './networks';
import { createPollingBasedOnMountedComponents } from './composablesHelpers';
import { useStorageRef } from './storageRef';

type ContractInitializeOptions = Omit<Parameters<typeof Contract.initialize>[0], 'onNode'>;

/**
* List of all custom tokens available (currently only AE network).
* As this list is quite big (hundreds of items) it requires processing optimizations.
Expand All @@ -49,10 +50,10 @@ const { onNetworkChange } = createNetworkWatcher();
const availableTokensPooling = createPollingBasedOnMountedComponents(60000);
const tokenBalancesPooling = createPollingBasedOnMountedComponents(10000);

export function useFungibleTokens({ store }: IDefaultComposableOptions) {
const { getAeSdk } = useAeSdk({ store });
export function useFungibleTokens() {
const { getAeSdk } = useAeSdk();
const { fetchFromMiddleware } = useMiddleware();
const { tippingContractAddresses } = useTippingContracts({ store });
const { tippingContractAddresses } = useTippingContracts();
const {
isLoggedIn,
aeAccounts,
Expand Down Expand Up @@ -210,28 +211,22 @@ export function useFungibleTokens({ store }: IDefaultComposableOptions) {
tokenContractId: Encoded.ContractAddress,
toAccount: Encoded.AccountAddress,
amount: number,
option: {
waitMined: boolean,
modal: boolean,
},
options: ContractInitializeOptions,
) {
const aeSdk = await getAeSdk();
const tokenContract = await aeSdk.initializeContract({
aci: FungibleTokenFullInterfaceACI,
address: tokenContractId,
});
return tokenContract.transfer(toAccount, amount.toFixed(), option);
return tokenContract.transfer(toAccount, amount.toFixed(), options);
}

async function burnTriggerPoS(
address: Encoded.ContractAddress,
posAddress: string,
invoiceId: string,
amount: number,
option: {
waitMined: boolean,
modal: boolean,
},
options: ContractInitializeOptions,
) {
const aeSdk = await getAeSdk();
const tokenContract = await aeSdk.initializeContract({
Expand All @@ -242,7 +237,7 @@ export function useFungibleTokens({ store }: IDefaultComposableOptions) {
amount.toFixed(),
posAddress,
invoiceId,
option,
options,
);
}

Expand Down
9 changes: 3 additions & 6 deletions src/composables/latestTransactionList.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import {
ref,
} from 'vue';
import { Encoded } from '@aeternity/aepp-sdk';
import type { IDefaultComposableOptions, ITransaction } from '@/types';
import type { ITransaction } from '@/types';
import { DASHBOARD_TRANSACTION_LIMIT } from '@/constants';
import {
pipe,
Expand All @@ -19,10 +19,8 @@ const isTransactionListLoading = ref(false);
* Store the state of the latest transactions to avoid multiple fetching when opening pages
* that wants to use this data.
*/
export function useLatestTransactionList({ store }: IDefaultComposableOptions) {
const {
transactions,
} = useTransactionList({ store });
export function useLatestTransactionList() {
const { transactions } = useTransactionList();

const latestTransactions = computed(() => {
const allTransactions = Object.entries(transactions.value)
Expand All @@ -39,7 +37,6 @@ export function useLatestTransactionList({ store }: IDefaultComposableOptions) {
const {
direction,
} = useTransactionTx({
store,
tx: tr.tx,
externalAddress: accountAddress as Encoded.AccountAddress,
});
Expand Down
Loading