Skip to content

Commit

Permalink
Merge pull request CounterpartyXCP#845 from monaparty/pr-reduce-immed…
Browse files Browse the repository at this point in the history
…iate-strings

Reduce immediate string values.
  • Loading branch information
chiguireitor authored Sep 27, 2018
2 parents cb0a5a8 + fe961b6 commit 9356b56
Show file tree
Hide file tree
Showing 19 changed files with 140 additions and 108 deletions.
12 changes: 6 additions & 6 deletions src/js/components/address.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,8 @@ function AddressViewModel(type, key, address, initialLabel, pubKeys) {
self.withMovement = ko.observable(false);

self.assets = ko.observableArray([
new AssetViewModel({address: address, asset: "BTC"}), //will be updated with data loaded from insight
new AssetViewModel({address: address, asset: "XCP"}) //will be updated with data loaded from counterpartyd
new AssetViewModel({address: address, asset: KEY_ASSET.BTC}), //will be updated with data loaded from insight
new AssetViewModel({address: address, asset: KEY_ASSET.XCP}) //will be updated with data loaded from counterpartyd
]);

self.assetFilter = ko.observable('');
Expand All @@ -39,7 +39,7 @@ function AddressViewModel(type, key, address, initialLabel, pubKeys) {
return self.assets();
} else if (self.assetFilter() == 'base') {
return ko.utils.arrayFilter(self.assets(), function(asset) {
return asset.ASSET == 'BTC' || asset.ASSET == 'XCP';
return asset.ASSET === KEY_ASSET.BTC || asset.ASSET === KEY_ASSET.XCP;
});

} else if (self.assetFilter() == 'mine') {
Expand Down Expand Up @@ -142,7 +142,7 @@ function AddressViewModel(type, key, address, initialLabel, pubKeys) {
return item.ASSET === asset;
});

if (asset == 'BTC' || asset == 'XCP') { //special case update
if (asset === KEY_ASSET.BTC || asset === KEY_ASSET.XCP) { //special case update
assert(match, 'was created when the address viewmodel was initialized...');
match.rawBalance(initialRawBalance);
match.escrowedBalance(escrowedBalance);
Expand Down Expand Up @@ -272,7 +272,7 @@ function AddressViewModel(type, key, address, initialLabel, pubKeys) {
self.createAsset = function() {
if (!WALLET.canDoTransaction(self.ADDRESS)) return false;

var xcpBalance = WALLET.getBalance(self.ADDRESS, 'XCP');
var xcpBalance = WALLET.getBalance(self.ADDRESS, KEY_ASSET.XCP);
CREATE_ASSET_MODAL.show(self.ADDRESS, xcpBalance, true);
}

Expand Down Expand Up @@ -344,7 +344,7 @@ function AddressViewModel(type, key, address, initialLabel, pubKeys) {

self.getXCPBalance = function() {
var xcpAsset = $.grep(self.assets(), function(value) {
return value.ASSET == 'XCP';
return value.ASSET === KEY_ASSET.XCP;
});
return xcpAsset[0].normalizedBalance();
}
Expand Down
12 changes: 10 additions & 2 deletions src/js/components/asset.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ function AssetViewModel(props) {
self.DIVISIBLE = props['divisible'] !== undefined ? props['divisible'] : true;
self.owner = ko.observable(props['owner']);
self.locked = ko.observable(props['locked'] !== undefined ? props['locked'] : false);
self.rawBalance = ko.observable(props['rawBalance'] || (self.ASSET == 'BTC' ? null : 0));
self.rawBalance = ko.observable(props['rawBalance'] || (self.ASSET === KEY_ASSET.BTC ? null : 0));
//^ raw (not normalized) (for BTC/XCP, default to null to show '??' instead of 0, until the balance is populated)
self.rawSupply = ko.observable(props['rawSupply'] || 0); //raw
self.SUPPLY = normalizeQuantity(self.rawSupply(), self.DIVISIBLE);
Expand All @@ -35,8 +35,16 @@ function AssetViewModel(props) {
self.escrowedBalance(self.escrowedBalance() + delta);
}

self.isBTC = ko.computed(function() {
return self.ASSET === KEY_ASSET.BTC;
}, self);

self.isXCP = ko.computed(function() {
return self.ASSET === KEY_ASSET.XCP;
}, self);

self.isMine = ko.computed(function() {
if (self.ASSET == 'BTC' || self.ASSET == 'XCP') return null; //special value for BTC and XCP
if (self.isBTC() || self.isXCP()) return null; //special value for BTC and XCP
return self.owner() == self.ADDRESS;
}, self);

Expand Down
58 changes: 30 additions & 28 deletions src/js/components/balances.js
Original file line number Diff line number Diff line change
Expand Up @@ -569,7 +569,7 @@ function SendModalViewModel() {
if (!isNumber(self.quantity())) return null;
var curBalance = normalizeQuantity(self.rawBalance(), self.divisible());
var balRemaining = Decimal.round(new Decimal(curBalance).sub(parseFloat(self.quantity())), 8, Decimal.MidpointRounding.ToEven).toFloat();
if (self.asset() == 'BTC')
if (self.asset() === KEY_ASSET.BTC)
balRemaining = subFloat(balRemaining, normalizeQuantity(MIN_FEE)) // include the fee
if (balRemaining < 0) return null;
return balRemaining;
Expand Down Expand Up @@ -616,7 +616,7 @@ function SendModalViewModel() {
return 'memo_data_note_hex';
});
shouldShowMemoFields = ko.computed(function() {
return self.asset() && self.asset() != 'BTC';
return self.asset() && self.asset() !== KEY_ASSET.BTC;
})

self.validationModel = ko.validatedObservable({
Expand Down Expand Up @@ -658,7 +658,7 @@ function SendModalViewModel() {

self.maxAmount = function() {
assert(self.normalizedBalance(), "No balance present?");
if (self.asset() == 'BTC')
if (self.asset() === KEY_ASSET.BTC)
self.quantity(subFloat(self.normalizedBalance(), normalizeQuantity(MIN_FEE)));
else
self.quantity(self.normalizedBalance());
Expand Down Expand Up @@ -724,7 +724,7 @@ function SendModalViewModel() {
});

self.show = function(fromAddress, asset, assetDisp, rawBalance, isDivisible, resetForm) {
if (asset == 'BTC' && rawBalance == null) {
if (asset === KEY_ASSET.BTC && rawBalance === null) {
return bootbox.alert(i18n.t("cannot_send_server_unavailable"));
}
assert(rawBalance, "Balance is null or undefined?");
Expand Down Expand Up @@ -892,7 +892,9 @@ function SweepModalViewModel() {

self.addressForPrivateKey.subscribe(function(address) {
//set up handler on changes in private key to generate a list of balances
self.sweepAssetsCost = {'BTC': MIN_FEE + REGULAR_DUST_SIZE};
var hash = {};
hash[KEY_ASSET.BTC] = MIN_FEE + REGULAR_DUST_SIZE;
self.sweepAssetsCost = hash;
if (!address || address == '') return;

//Get the balance of ALL assets at this address
Expand Down Expand Up @@ -930,9 +932,9 @@ function SweepModalViewModel() {
if (unconfirmedRawBal > 0) {
//We don't need to supply asset info to the SweepAssetInDropdownItemModel constructor for BTC
// b/c we won't be transferring any asset ownership with it
var viewModel = new SweepAssetInDropdownItemModel("BTC", unconfirmedRawBal, normalizeQuantity(unconfirmedRawBal));
var viewModel = new SweepAssetInDropdownItemModel(KEY_ASSET.BTC, unconfirmedRawBal, normalizeQuantity(unconfirmedRawBal));
self.availableAssetsToSweep.unshift(viewModel);
assets.push("BTC");
assets.push(KEY_ASSET.BTC);
self.btcBalanceForPrivateKey(data[0]['confirmedRawBal']);
self.txoutsCountForPrivateKey = data[0]['rawUtxoData'].length;

Expand All @@ -954,7 +956,7 @@ function SweepModalViewModel() {
return;
}
WALLET.retrieveBTCAddrsInfo([address], function(data) {
self.addressForFeesBalanceMessage(normalizeQuantity(data[0]['confirmedRawBal']) + ' BTC in ' + address);
self.addressForFeesBalanceMessage([normalizeQuantity(data[0]['confirmedRawBal']), KEY_ASSET.BTC, 'in', address].join(' '));
self.addressForFeesBalance(data[0]['confirmedRawBal']);
});
});
Expand Down Expand Up @@ -988,7 +990,7 @@ function SweepModalViewModel() {
WALLET.BITCOIN_WALLET.getOldAddressesInfos(function(data) {
for (var address in data) {
if (self.excludedOldAddresses.indexOf(address) == -1) {
self.availableOldAddresses.push(new BalancesAddressInDropdownItemModel(address, address, data[address]['BTC']['privkey']));
self.availableOldAddresses.push(new BalancesAddressInDropdownItemModel(address, address, data[address][KEY_ASSET.BTC]['privkey']));
}
}
});
Expand Down Expand Up @@ -1077,7 +1079,7 @@ function SweepModalViewModel() {
var sweepBTC = false;
for (var i = 0; i < self.selectedAssetsToSweep().length; i++) {
var assetName = self.selectedAssetsToSweep()[i];
if (assetName == 'BTC') sweepBTC = true;
if (assetName === KEY_ASSET.BTC) sweepBTC = true;
}
if (sweepBTC) {
self.missingBtcForFees += REGULAR_DUST_SIZE;
Expand All @@ -1088,7 +1090,7 @@ function SweepModalViewModel() {
source: self.addressForPrivateKeyForFees(),
destination: self.addressForPrivateKey(),
quantity: self.missingBtcForFees,
asset: 'BTC',
asset: KEY_ASSET.BTC,
encoding: 'auto',
pubkey: pubkey,
allow_unconfirmed_inputs: true
Expand Down Expand Up @@ -1153,7 +1155,7 @@ function SweepModalViewModel() {
source: self.addressForPrivateKey(),
destination: self.addressForPrivateKey(),
quantity: self.btcBalanceForPrivateKey() - fees,
asset: 'BTC',
asset: KEY_ASSET.BTC,
encoding: 'auto',
pubkey: pubkey,
allow_unconfirmed_inputs: true,
Expand All @@ -1162,7 +1164,7 @@ function SweepModalViewModel() {

var onTransactionError = function() {
if (arguments.length == 4) {
var match = arguments[1].match(/Insufficient BTC at address [^\s]+\. \(Need approximately ([\d]+\.[\d]+) BTC/);
var match = arguments[1].match(/Insufficient [^\s]+ at address [^\s]+\. \(Need approximately ([\d]+\.[\d]+) [^\s]+/);

if (match != null) {
$.jqlog.debug(arguments[1]);
Expand Down Expand Up @@ -1266,7 +1268,7 @@ function SweepModalViewModel() {

// here we adjust the BTC balance whith the change output
var newBtcBalance = CWBitcore.extractChangeTxoutValue(transferData.source, unsignedTxHex);
$.jqlog.debug("New BTC balance: " + newBtcBalance);
$.jqlog.debug(['New', KEY_ASSET.BTC, 'balance:', newBtcBalance].join(' '));
self.btcBalanceForPrivateKey(newBtcBalance);

self.sweepingCurrentStep++;
Expand Down Expand Up @@ -1312,7 +1314,7 @@ function SweepModalViewModel() {
$.jqlog.debug('_doSendAsset: ' + asset);

//TODO: remove this
if (asset == 'BTC') assert(adjustedBTCQuantity !== null);
if (asset === KEY_ASSET.BTC) assert(adjustedBTCQuantity !== null);
else assert(adjustedBTCQuantity === null);

var selectedAsset = ko.utils.arrayFirst(self.availableAssetsToSweep(), function(item) {
Expand All @@ -1321,13 +1323,13 @@ function SweepModalViewModel() {
var sendTx = null, i = null;

$.jqlog.debug("btcBalanceForPrivateKey: " + self.btcBalanceForPrivateKey());
var quantity = (asset == 'BTC') ? (self.btcBalanceForPrivateKey() - MIN_FEE) : selectedAsset.RAW_BALANCE;
var normalizedQuantity = (asset == 'BTC') ? normalizeQuantity(quantity) : selectedAsset.NORMALIZED_BALANCE;
var quantity = (asset === KEY_ASSET.BTC) ? (self.btcBalanceForPrivateKey() - MIN_FEE) : selectedAsset.RAW_BALANCE;
var normalizedQuantity = (asset === KEY_ASSET.BTC) ? normalizeQuantity(quantity) : selectedAsset.NORMALIZED_BALANCE;

assert(selectedAsset);

if (!quantity) { //if there is no quantity to send for the asset, only do the transfer
if (asset == 'XCP' || asset == 'BTC') { //nothing to send, and no transfer to do
if (asset === KEY_ASSET.XCP || asset === KEY_ASSET.BTC) { //nothing to send, and no transfer to do
return callback(); //my valuable work here is done!
} else {
self._doTransferAsset(selectedAsset, key, pubkey, opsComplete, callback); //will trigger callback() once done
Expand Down Expand Up @@ -1377,15 +1379,15 @@ function SweepModalViewModel() {
PENDING_ACTION_FEED.add(sendTxHash, "sends", sendData);

// here we adjust the BTC balance whith the change output
if (selectedAsset.ASSET != 'BTC') {
if (selectedAsset.ASSET !== KEY_ASSET.BTC) {
var newBtcBalance = CWBitcore.extractChangeTxoutValue(sendData.source, unsignedTxHex);
$.jqlog.debug("New BTC balance: " + newBtcBalance);
$.jqlog.debug(['New', KEY_ASSET.BTC, 'balance:', newBtcBalance].join(' '));
self.btcBalanceForPrivateKey(newBtcBalance);
}

//For non BTC/XCP assets, also take ownership (iif the address we are sweeping from is the asset's owner')
if (selectedAsset.ASSET != 'XCP'
&& selectedAsset.ASSET != 'BTC'
if (selectedAsset.ASSET !== KEY_ASSET.XCP
&& selectedAsset.ASSET !== KEY_ASSET.BTC
&& selectedAsset.ASSET_INFO['owner'] == self.addressForPrivateKey()) {
$.jqlog.debug("waiting " + TRANSACTION_DELAY + "ms");
setTimeout(function() {
Expand Down Expand Up @@ -1448,15 +1450,15 @@ function SweepModalViewModel() {
var selectedAsset = null, hasBTC = false;
for (var i = 0; i < self.selectedAssetsToSweep().length; i++) {
selectedAsset = self.selectedAssetsToSweep()[i];
if (selectedAsset == 'BTC') {
if (selectedAsset === KEY_ASSET.BTC) {
hasBTC = i; //send BTC last so the sweep doesn't randomly eat our primed txouts for the other assets
} else {
sendsToMake.push([selectedAsset, cwk, pubkey, opsComplete, null]);
}
}
if (hasBTC !== false) {
//This balance is adjusted after each asset transfert with the change output.
sendsToMake.push(["BTC", cwk, pubkey, opsComplete, self.btcBalanceForPrivateKey()]);
sendsToMake.push([KEY_ASSET.BTC, cwk, pubkey, opsComplete, self.btcBalanceForPrivateKey()]);
}

var total = sendsToMake.length;
Expand Down Expand Up @@ -1520,7 +1522,7 @@ function SweepModalViewModel() {
}

var launchSweep = function() {
if (sendsToMake.length == 1 && sendsToMake[0][0] == 'BTC') {
if (sendsToMake.length === 1 && sendsToMake[0][0] === KEY_ASSET.BTC) {
doSweep();
} else {
// merge output then start sweeping.
Expand Down Expand Up @@ -1626,9 +1628,9 @@ function TestnetBurnModalViewModel() {
params: self
}, {
validator: function(val, self) {
return parseFloat(val) <= WALLET.getBalance(self.address(), 'BTC') - normalizeQuantity(MIN_FEE);
return parseFloat(val) <= WALLET.getBalance(self.address(), KEY_ASSET.BTC) - normalizeQuantity(MIN_FEE);
},
message: i18n.t('quantity_of_exceeds_balance', 'BTC'),
message: i18n.t('quantity_of_exceeds_balance', KEY_ASSET.BTC),
params: self
}, {
validator: function(val, self) {
Expand All @@ -1650,7 +1652,7 @@ function TestnetBurnModalViewModel() {

self.maxPossibleBurn = ko.computed(function() { //normalized
if (self.btcAlreadyBurned() === null) return null;
return Math.min(1 - self.btcAlreadyBurned(), WALLET.getAddressObj(self.address()).getAssetObj('BTC').normalizedBalance())
return Math.min(1 - self.btcAlreadyBurned(), WALLET.getAddressObj(self.address()).getAssetObj(KEY_ASSET.BTC).normalizedBalance())
}, self);

self.validationModel = ko.validatedObservable({
Expand Down
4 changes: 2 additions & 2 deletions src/js/components/balances_assets.js
Original file line number Diff line number Diff line change
Expand Up @@ -672,7 +672,7 @@ function PayDividendModalViewModel() {
}

// fetch shareholders to check transaction dest.
if (self.selectedDividendAsset() == 'BTC') {
if (self.selectedDividendAsset() === KEY_ASSET.BTC) {
var params = {
'filters': [
{'field': 'asset', 'op': '=', 'value': self.assetData().asset},
Expand Down Expand Up @@ -749,7 +749,7 @@ function PayDividendModalViewModel() {
//Also get the BTC balance at this address and put at head of the list
WALLET.retrieveBTCBalance(address.ADDRESS, function(balance) {
if (balance) {
self.availableDividendAssets.unshift(new DividendAssetInDropdownItemModel("BTC", "BTC", balance, normalizeQuantity(balance)));
self.availableDividendAssets.unshift(new DividendAssetInDropdownItemModel(KEY_ASSET.BTC, KEY_ASSET.BTC, balance, normalizeQuantity(balance)));
}
});
});
Expand Down
6 changes: 3 additions & 3 deletions src/js/components/betting.js
Original file line number Diff line number Diff line change
Expand Up @@ -250,7 +250,7 @@ function FeedBrowserViewModel() {
for (var i = 0; i < addresses.length; i++) {
options.push({
address: addresses[i][0],
label: addresses[i][1] + ' (' + addresses[i][2] + ' XCP)'
label: addresses[i][1] + ' (' + addresses[i][2] + ' ' + KEY_ASSET.XCP + ')'
});
self.balances[addresses[i][0]] = addresses[i][2];
}
Expand Down Expand Up @@ -314,8 +314,8 @@ function FeedBrowserViewModel() {
'expired': i18n.t('expired')
};
for (var i in feed.counters.bets) {
feed.counters.bets[i].wager_quantity = normalizeQuantity(feed.counters.bets[i].wager_quantity) + ' XCP';
feed.counters.bets[i].wager_remaining = normalizeQuantity(feed.counters.bets[i].wager_remaining) + ' XCP';
feed.counters.bets[i].wager_quantity = normalizeQuantity(feed.counters.bets[i].wager_quantity) + ' ' + KEY_ASSET.XCP;
feed.counters.bets[i].wager_remaining = normalizeQuantity(feed.counters.bets[i].wager_remaining) + ' ' + KEY_ASSET.XCP;
feed.counters.bets[i].status_html = '<span class="label label-' + classes[feed.counters.bets[i].status] + '">' + feed.counters.bets[i].status + '</span>';

}
Expand Down
8 changes: 4 additions & 4 deletions src/js/components/donate.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ function DonationViewModel() {
validator: function(val, self) {
var address = self.sourceAddress();
var quantity = self.quantity();
if (self.donationCurrency() == 'XCP') {
if (self.donationCurrency() === KEY_ASSET.XCP) {
return parseFloat(quantity) <= self.balancesXCP[address];
} else {
return parseFloat(quantity) <= self.balancesBTC[address];
Expand All @@ -26,7 +26,7 @@ function DonationViewModel() {
self.balancesXCP = {};
self.balancesBTC = {};
self.quantity = ko.observable(null).extend(quantityValidator);
self.donationCurrency = ko.observable('BTC');
self.donationCurrency = ko.observable(KEY_ASSET.BTC);


self.validationModel = ko.validatedObservable({
Expand All @@ -50,10 +50,10 @@ function DonationViewModel() {
var addresses = WALLET.getAddressesList(true);
var options = []
for (var i = 0; i < addresses.length; i++) {
var btcBalance = WALLET.getBalance(addresses[i][0], 'BTC', true);
var btcBalance = WALLET.getBalance(addresses[i][0], KEY_ASSET.BTC, true);
options.push({
address: addresses[i][0],
label: addresses[i][1] + ' (' + round(btcBalance, 2) + ' BTC / ' + round(addresses[i][2], 2) + ' XCP)'
label: addresses[i][1] + ' (' + [round(btcBalance, 2), KEY_ASSET.BTC, '/', round(addresses[i][2], 2), KEY_ASSET.XCP].join(' ') + ')'
});
self.balancesBTC[addresses[i][0]] = btcBalance;
self.balancesXCP[addresses[i][0]] = addresses[i][2];
Expand Down
Loading

0 comments on commit 9356b56

Please sign in to comment.