Skip to content

Commit

Permalink
Fixing incorrectly typed token decimal attribute
Browse files Browse the repository at this point in the history
  • Loading branch information
ryanml committed Mar 18, 2021
1 parent 88ad383 commit d2af4f2
Show file tree
Hide file tree
Showing 4 changed files with 763 additions and 1 deletion.
2 changes: 1 addition & 1 deletion app/scripts/controllers/preferences.js
Original file line number Diff line number Diff line change
Expand Up @@ -378,7 +378,7 @@ export default class PreferencesController {
*/
async addToken(rawAddress, symbol, decimals, image) {
const address = normalizeAddress(rawAddress);
const newEntry = { address, symbol, decimals };
const newEntry = { address, symbol, decimals: Number(decimals) };
const { tokens, hiddenTokens } = this.store.getState();
const assetImages = this.getAssetImages();
const updatedHiddenTokens = hiddenTokens.filter(
Expand Down
69 changes: 69 additions & 0 deletions app/scripts/migrations/054.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import { cloneDeep } from 'lodash';

const version = 54;

function isValidDecimals(decimals) {
return !isNaN(Number(decimals));
}

/**
* Migrates preference tokens with 0 decimals typed as 'string' to 'number'
*/
export default {
version,
async migrate(originalVersionedData) {
const versionedData = cloneDeep(originalVersionedData);
versionedData.meta.version = version;
const state = versionedData.data;
const newState = transformState(state);
versionedData.data = newState;
return versionedData;
},
};

function transformState(state) {
const newState = state;

if (!newState.PreferencesController) {
return newState;
}

const tokens = newState.PreferencesController.tokens || [];
// Filter out any tokens with corrupted decimal values
const validTokens = tokens.filter(({ decimals }) =>
isValidDecimals(decimals),
);
for (const token of validTokens) {
// In the case of a decimal value type string, set to 0.
if (typeof token.decimals === 'string') {
token.decimals = 0;
}
}
newState.PreferencesController.tokens = validTokens;

const { accountTokens } = newState.PreferencesController;
if (accountTokens && typeof accountTokens === 'object') {
for (const address of Object.keys(accountTokens)) {
const networkTokens = accountTokens[address];
if (networkTokens && typeof networkTokens === 'object') {
for (const network of Object.keys(networkTokens)) {
const tokensOnNetwork = networkTokens[network] || [];
// Filter out any tokens with corrupted decimal values
const validTokensOnNetwork = tokensOnNetwork.filter(({ decimals }) =>
isValidDecimals(decimals),
);
// In the case of a decimal value type string, set to 0.
for (const token of validTokensOnNetwork) {
if (typeof token.decimals === 'string') {
token.decimals = 0;
}
}
networkTokens[network] = validTokensOnNetwork;
}
}
}
}
newState.PreferencesController.accountTokens = accountTokens;

return newState;
}
Loading

0 comments on commit d2af4f2

Please sign in to comment.