Skip to content

Commit

Permalink
[BRG-464] add getter to extension to get active account (#30)
Browse files Browse the repository at this point in the history
* [BRG-464] add method getAccountsSync

* [BRG-464] return active account

* [BRH--464] fix

* [BRG-464] fix label active account in example.html

* [BRG-464] fix loadAccounts

* [BRG-464] refactoring

* [BRG-464] refactoring

* [BRG-464] fix

* [BRG-464] fix getAccess

* [BRG-464] fix readme

* Up version 1.11.0-rc.1

* Up version 1.11.0-rc.1
  • Loading branch information
AlinaLoz authored and vital-33 committed Sep 18, 2019
1 parent dfaf675 commit ec4fa54
Show file tree
Hide file tree
Showing 8 changed files with 157 additions and 13 deletions.
12 changes: 12 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,18 @@ Subscribe to change active account. Callback will be triggered when active accou
echojslib.extension.subscribeSwitchAccount((account) => console.log(account))
```

### Get active account synchronously
If you don't get access or there isn't active account, then you get null, else account id.
```javascript
/**
* @example
* echojslib.extension.activeAccount // null
* @example
* echojslib.extension.activeAccount // "1.2.1"
* @return {null|string}
*/
echojslib.extension.activeAccount
```
### Sign transaction with Bridge

#### Transfer
Expand Down
2 changes: 1 addition & 1 deletion config/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
"96": "images/96.png",
"128": "images/128.png"
},
"version": "1.10.2",
"version": "1.11.0",
"background": {
"scripts": [
"background.js"
Expand Down
20 changes: 17 additions & 3 deletions examples/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,14 @@ <h4>Accounts</h4>
</div>
<!---->

<!-- Active account(current network) -->
<div style="padding-bottom: 10px; border-top: 1px solid #000;">
<h4>Active account</h4>
<button id="activeAccount-click">submit</button>
<div id="activeAccount-info"></div>
</div>
<!---->

<!-- Transfer -->
<div style="padding-bottom: 10px; border-top: 1px solid #000;">
<h4>Transfer</h4>
Expand Down Expand Up @@ -323,9 +331,7 @@ <h4>Sign message</h4>
});
}

window.onload = () => {
resetData();
};
window.addEventListener("load", resetData);

$(document).ready(function() {
$("#getAccess-click").click(function(e) {
Expand Down Expand Up @@ -367,6 +373,14 @@ <h4>Sign message</h4>
});
});

$("#activeAccount-click").click(function(e) {
if (!isAccess) return;
const result = window.echojslib.extension.activeAccount;
jQuery("#activeAccount-info").html(
`<p>RESULT: ${JSON.stringify(result)}</p>`
);
});

$("#transfer-click").click(function(e) {
if (!isAccess) return;
const transaction = {
Expand Down
92 changes: 85 additions & 7 deletions extension/background.js
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ const crypto = new Crypto();

let lastRequestType = '';
const accountsRequests = [];
let activeAccountRequests = [];

let requestQueue = [];
const networkSubscribers = [];
Expand All @@ -65,8 +66,6 @@ let signMessageRequests = [];
const providerNotification = new NotificationManager();
const signNotification = new NotificationManager();

const tabUrls = {};

const connectSubscribe = (status) => {
try {
switch (status) {
Expand Down Expand Up @@ -239,7 +238,9 @@ const resolveAccounts = async () => {
const network = await getNetwork();

try {
const accounts = await crypto.getInByNetwork(network.name, 'accounts') || [];
let accounts = await crypto.getInByNetwork(network.name, 'accounts') || [];
accounts = accounts.filter((account) => account.active);

accountsRequests.forEach((request) => {
try {
request.cb({ id: request.id, res: accounts });
Expand All @@ -256,6 +257,64 @@ const resolveAccounts = async () => {

};

/**
* Get active account by network
* @param {String} switchNetwork
* @returns {Promise<[activeAccount]>}
*/
const getActiveAccount = async (switchNetwork) => {
const network = switchNetwork || await getNetwork();

let activeAccount = null;

if (!crypto.isLocked()) {
let accounts = await crypto.getInByNetwork(network.name, 'accounts') || [];
accounts = accounts.filter((account) => account.active);
if (accounts.length > 0) {
activeAccount = accounts[0].id;
}
}

return activeAccount;
};

/**
* Resolve request to get active account from inpage
* @param request
* @returns {Promise<void>}
*/
const resolveActiveAccount = async (request) => {
try {
const account = await getActiveAccount();
request.cb({ id: request.id, res: account });
} catch (e) {
console.log(e.message);
}
};


/**
* Update active account on all requested inpage
* @returns {Promise<null|{error: *}>}
*/
const updateActiveAccountInpage = async (network) => {
try {
const account = await getActiveAccount(network);

activeAccountRequests.forEach((request) => {
try {
request.cb({ id: request.id, res: account });
} catch (e) {
console.log(e.message);
}
});

return null;

} catch (e) {
return { error: e.message };
}
};

/**
* On content script request
Expand All @@ -273,6 +332,8 @@ const onMessage = (request, sender, sendResponse) => {
if (!request.method || !request.appId || request.appId !== APP_ID) return false;

if (request.method === 'closeTab') {
activeAccountRequests = activeAccountRequests
.filter((accountRequest) => accountRequest.tabId !== tabId);
const indexFindRequest = providerRequests.findIndex((rq) => rq.origin === hostname);
if (indexFindRequest === -1) return true;
const indexTabId = providerRequests[indexFindRequest].tabs
Expand Down Expand Up @@ -405,6 +466,18 @@ const onMessage = (request, sender, sendResponse) => {
triggerPopup();
}

} else if (request.method === 'getActiveAccount') {
const tabIndex = activeAccountRequests.findIndex(({ tabId: reqTabId }) => tabId === reqTabId);
const req = {
id: request.id, cb: sendResponse, tabId,
};
if (tabIndex === -1) {
resolveActiveAccount(req);
activeAccountRequests.push(req);
return true;
}
activeAccountRequests[tabIndex] = req;
return true;
}

return true;
Expand All @@ -415,8 +488,13 @@ const onPinUnlock = () => {
resolveAccounts();
closePopup();
}
updateActiveAccountInpage();
return null;
};

const onLock = () => {
updateActiveAccountInpage();
return null;
};

/**
Expand Down Expand Up @@ -611,6 +689,7 @@ export const onSend = async (options, networkName) => {
export const onSwitchNetwork = async (network) => {
try {
await createSocket(network.url);
updateActiveAccountInpage(network);
} catch (e) {
console.warn('Switch network error', e);
} finally {
Expand All @@ -621,13 +700,14 @@ export const onSwitchNetwork = async (network) => {
console.warn('Switch network callback error', error);
}
});

}

};


const onSwitchActiveAccount = (res) => {
updateActiveAccountInpage();
if (!res) return;
activeAccountSubscribers.forEach(({ id, cb }) => {
try {
cb({ id, res });
Expand Down Expand Up @@ -759,11 +839,9 @@ window.getSignMessageMap = () => signMessageRequests.reduce((map, {
extensionizer.runtime.onMessage.addListener(onMessage);

crypto.on('unlocked', onPinUnlock);

crypto.on('locked', onLock);

extensionizer.runtime.onInstalled.addListener(onFirstInstall);

extensionizer.browserAction.setBadgeText({ text: 'BETA' });



39 changes: 39 additions & 0 deletions extension/inpage.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ const requestQueue = [];
const networkSubscribers = [];
const accountSubscribers = [];

let activeAccount = null;

/**
* network subscription
*
Expand Down Expand Up @@ -123,6 +125,11 @@ const subscribeSwitchNetwork = (subscriberCb) => {
return result;
};

/**
* Notify about switch account
* @param {Function} subscriberCb
* @returns {Promise}
*/
const subscribeSwitchAccount = (subscriberCb) => {
const id = IdHelper.getId();

Expand Down Expand Up @@ -276,6 +283,34 @@ const getAccounts = () => {
return result;
};

/**
* Load active bridge account
* @returns {undefined}
*/
const loadActiveAccount = () => {
const id = IdHelper.getId();

const cb = ({ data }) => {
window.postMessage({
method: 'getActiveAccount', id, target: 'content', appId: APP_ID,
}, '*');

const error = data.error || (data.res && data.res.error);

if (error) {
activeAccount = null;
} else {
activeAccount = data.res;
requestQueue.push({ id, cb });
}
};

requestQueue.push({ id, cb });
window.postMessage({
method: 'getActiveAccount', id, target: 'content', appId: APP_ID,
}, '*');
};

const proofOfAuthority = (message, accountId) => {
const id = IdHelper.getId();
const result = new Promise((resolve, reject) => {
Expand Down Expand Up @@ -315,6 +350,7 @@ const getAccess = () => {
if (data.error) {
reject(data.error);
} else {
loadActiveAccount();
resolve(data.status);
}
};
Expand Down Expand Up @@ -401,6 +437,7 @@ echojslib.Transaction.prototype.signWithBridge = async function signWithBridge()
};

const extension = {
get activeAccount() { return activeAccount; },
getAccounts: () => getAccounts(),
sendTransaction: (data) => sendTransaction(data),
getCurrentNetwork: () => getCurrentNetwork(),
Expand All @@ -417,3 +454,5 @@ window.echojslib.extension = extension;
window.echojslib.Buffer = Buffer;

window.addEventListener('message', onMessage, false);

loadActiveAccount();
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "echo-bridge",
"description": "The bridge between your web site and the Echo",
"version": "1.10.2",
"version": "1.11.0-rc.1",
"scripts": {
"start": "cross-env NODE_ENV=local webpack-dev-server --mode development --progress --colors --history-api-fallback --hot --inline --port 8081",
"build": "cross-env NODE_ENV=production webpack --progress --display-error-details --colors --mode production",
Expand Down
2 changes: 1 addition & 1 deletion src/actions/ChainStoreAction.js
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ export const subscribe = () => (dispatch) => {
*/
export const checkActiveLoading = () => async (dispatch) => {
const draftStorage = await storageGetDraft();
const signUp = draftStorage[FORM_SIGN_UP];
const signUp = draftStorage && draftStorage[FORM_SIGN_UP];
const loading = signUp && signUp.loading;
dispatch(setValue(FORM_SIGN_UP, 'loading', loading));
dispatch(GlobalReducer.actions.set({ field: 'loading', value: loading }));
Expand Down
1 change: 1 addition & 0 deletions src/actions/GlobalActions.js
Original file line number Diff line number Diff line change
Expand Up @@ -361,6 +361,7 @@ export const onLogout = (name) => async (dispatch, getState) => {
}

if (!accounts.get(networkName).size) {
emitter.emit('activeAccountResponse', null);
dispatch(GlobalReducer.actions.logout());
history.push(CREATE_ACCOUNT_PATH);
return false;
Expand Down

0 comments on commit ec4fa54

Please sign in to comment.