Skip to content

Commit

Permalink
Merge branch 'master' into stake-splitting
Browse files Browse the repository at this point in the history
  • Loading branch information
panleone authored Nov 18, 2024
2 parents ae7e05a + 60f3415 commit e0dec6a
Show file tree
Hide file tree
Showing 19 changed files with 361 additions and 179 deletions.
3 changes: 3 additions & 0 deletions cypress/e2e/wallet_balance.cy.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@ describe('Wallet balance tests', () => {
matching: { ignores: ['hostname', 'port'] },
}).as('sync');
cy.visit('/');
cy.waitForLoading().should('be.visible');
cy.setExplorer(0);
cy.goToTab('dashboard');
cy.importWallet('DLabsktzGMnsK5K9uRTMCF6NoYNY6ET4Bb');
});
it('calculates balance correctly', () => {
Expand Down
16 changes: 8 additions & 8 deletions cypress/snapshots/html/snapshot.html

Large diffs are not rendered by default.

11 changes: 8 additions & 3 deletions cypress/support/commands.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,23 +24,24 @@ Cypress.Commands.add(
}
);

Cypress.Commands.add('waitForLoading', () => {
cy.get('[data-testid="generateWallet"]');
});

Cypress.Commands.add('createWallet', (password) => {
cy.visit('');
cy.get('[data-testid="generateWallet"]').click();
const seedPhrase = cy.get('.seed-phrase').invoke('text');
cy.get('[data-testid="seedphraseModal"]').click();
cy.encryptWallet(password);
return seedPhrase;
});
Cypress.Commands.add('createVanityWallet', (prefix, password) => {
cy.visit('');
cy.get('[data-testid="vanityWalletButton"]').click();
cy.get('[data-testid="prefixInput"]').should('be.visible').type(prefix);
cy.get('[data-testid="generateBtn"]').click();
cy.encryptWallet(password);
});
Cypress.Commands.add('importWallet', (key, password) => {
cy.visit('');
cy.get('[data-testid="accWalletButton"]').click();
cy.get('[data-testid="secretInp"]').should('be.visible').type(key);
if (password)
Expand Down Expand Up @@ -77,3 +78,7 @@ Cypress.Commands.add('deleteWallet', () => {
cy.get('[data-testid="deleteWalletButton"]').click();
cy.get('[data-i18n="popupConfirm"]').click();
});
Cypress.Commands.add('setExplorer', (explorerNameOrIndex) => {
cy.goToTab('settings');
cy.get('#explorer').select(explorerNameOrIndex);
});
2 changes: 1 addition & 1 deletion cypress/support/snapshot.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ Cypress.Commands.add(
const snapshotPath = `cypress/snapshots/html/${snapshotName}.html`;

cy.task('fileExists', snapshotPath).then((exists) => {
if (exists && !process.env.CYPRESS_PLAYBACK_MODE === 'record') {
if (exists && process.env.CYPRESS_PLAYBACK_MODE !== 'record') {
cy.readFile(snapshotPath).then((expectedHtml) => {
expect(htmlContent === expectedHtml).to.equal(true);
});
Expand Down
28 changes: 14 additions & 14 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 3 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -96,9 +96,9 @@
"jquery": "^3.6.3",
"pinia": "^2.1.7",
"pivx-promos": "^0.2.0",
"pivx-shield": "^1.1.6",
"pivx-shield-rust": "^1.1.6",
"pivx-shield-rust-multicore": "^1.1.10",
"pivx-shield": "^1.2.0-7",
"pivx-shield-rust": "^1.2.0-7",
"pivx-shield-rust-multicore": "^1.2.0-7",
"qr-scanner": "^1.4.2",
"qrcode-generator": "^1.4.4",
"vue": "^3.3.4",
Expand Down
8 changes: 4 additions & 4 deletions scripts/alerts/alert.js
Original file line number Diff line number Diff line change
Expand Up @@ -54,9 +54,9 @@ export class AlertController {
* - The use of `.innerHTML` allows for input styling at this cost.
* @param {'success'|'info'|'warning'} type - The alert level
* @param {string} message - The message to relay to the user
* @param {number?} timeout - The time in `ms` until the alert expires (Defaults to never expiring)
* @param {number?} timeout - The time in `ms` until the alert expires
*/
createAlert(level, message, timeout = 2000) {
createAlert(level, message, timeout = 10000) {
this.addAlert(new Alert({ level, message, timeout }));
}

Expand Down Expand Up @@ -93,9 +93,9 @@ export class AlertController {
* - The use of `.innerHTML` allows for input styling at this cost.
* @param {'success'|'info'|'warning'} type - The alert level
* @param {string} message - The message to relay to the user
* @param {number?} [timeout] - The time in `ms` until the alert expires (Defaults to never expiring)
* @param {number?} [timeout] - The time in `ms` until the alert expires
*/
export function createAlert(type, message, timeout = 0) {
export function createAlert(type, message, timeout) {
const alertController = AlertController.getInstance();
return alertController.createAlert(type, message, timeout);
}
71 changes: 19 additions & 52 deletions scripts/dashboard/Activity.vue
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@ let txCount = 0;
const updating = ref(false);
const isHistorySynced = ref(false);
const rewardAmount = ref(0);
let nRewardUpdateHeight = 0;
const ticker = computed(() => cChainParams.current.TICKER);
const network = useNetwork();
function getActivityUrl(tx) {
Expand Down Expand Up @@ -70,6 +69,15 @@ const txMap = computed(() => {
};
});
function updateReward() {
if (!props.rewards) return;
let res = 0;
for (const tx of wallet.getHistoricalTxs()) {
if (tx.type !== HistoricalTxType.STAKE) continue;
res += tx.amount;
}
rewardAmount.value = res;
}
async function update(txToAdd = 0) {
// Return if wallet is not synced yet
if (!wallet.isSynced) {
Expand All @@ -88,22 +96,6 @@ async function update(txToAdd = 0) {
const historicalTxs = wallet.getHistoricalTxs();
// For Rewards: aggregate the total amount
if (props.rewards) {
for (const tx of historicalTxs) {
// If this Tx Height is under our last scanned height, we stop
if (tx.blockHeight <= nRewardUpdateHeight) break;
// Only compute rewards
if (tx.type != HistoricalTxType.STAKE) continue;
// Aggregate the total rewards
rewardAmount.value += tx.amount;
}
// Keep track of the scan block height
if (historicalTxs.length) {
nRewardUpdateHeight = historicalTxs[0].blockHeight;
}
}
let i = 0;
let found = 0;
while (found < txCount + txToAdd) {
Expand Down Expand Up @@ -143,9 +135,6 @@ async function parseTXs(arrTXs) {
minute: '2-digit',
hour12: true,
};
// And also keep track of our last Tx's timestamp, to re-use a cache, which is much faster than the slow `.toLocaleDateString`
let prevDateString = '';
let prevTimestamp = 0;
const cDB = await Database.getInstance();
const cAccount = await cDB.getAccount();
Expand All @@ -154,33 +143,19 @@ async function parseTXs(arrTXs) {
// If this Tx is older than 24h, then hit the `Date` cache logic, otherwise, use a `Time` and skip it
let strDate =
Date.now() / 1000 - cTx.time > 86400
? ''
? dateTime.toLocaleDateString(undefined, dateOptions)
: dateTime.toLocaleTimeString(undefined, timeOptions);
if (!strDate) {
if (
prevDateString &&
prevTimestamp - cTx.time * 1000 < 12 * 60 * 60 * 1000
) {
// Use our date cache
strDate = prevDateString;
} else {
// Create a new date, this Tx is too old to use the cache
prevDateString = dateTime.toLocaleDateString(
undefined,
dateOptions
);
strDate = prevDateString;
}
if (cTx.blockHeight === -1) {
strDate = 'Pending';
}
// Update the time cache
prevTimestamp = cTx.time * 1000;
// Coinbase Transactions (rewards) require coinbaseMaturity confs
const fConfirmed =
let fConfirmed =
cTx.blockHeight > 0 &&
blockCount - cTx.blockHeight >=
(cTx.type === HistoricalTxType.STAKE
? cChainParams.current.coinbaseMaturity
: 6);
(cTx.type === HistoricalTxType.STAKE
? cChainParams.current.coinbaseMaturity
: 6);
// Choose the content type, for the Dashboard; use a generative description, otherwise, a TX-ID
// let txContent = props.rewards ? cTx.id : 'Block Reward';
Expand Down Expand Up @@ -267,25 +242,17 @@ const rewardsText = computed(() => {
function reset() {
txs.value = [];
txCount = 0;
nRewardUpdateHeight = 0;
rewardAmount.value = 0;
update(0);
}
function getTxCount() {
return txCount;
}
getEventEmitter().on(
'transparent-sync-status-update',
(i, totalPages, done) => done && update()
);
getEventEmitter().on(
'shield-sync-status-update',
(blocks, totalBlocks, done) => done && update()
);
onMounted(() => update());
defineExpose({ update, reset, getTxCount });
defineExpose({ update, reset, getTxCount, updateReward });
</script>
<template>
Expand Down
1 change: 1 addition & 0 deletions scripts/dashboard/Dashboard.vue
Original file line number Diff line number Diff line change
Expand Up @@ -393,6 +393,7 @@ async function importFromDatabase() {
const account = await database.getAccount();
await wallet.setMasterKey({ mk: null });
activity.value?.reset();
getEventEmitter().emit('reset-activity');
if (account?.isHardware) {
await importWallet({ type: 'hardware', secret: account.publicKey });
} else if (wallet.isEncrypted) {
Expand Down
33 changes: 12 additions & 21 deletions scripts/dashboard/WalletBalance.vue
Original file line number Diff line number Diff line change
Expand Up @@ -60,13 +60,12 @@ const {
// Transparent sync status
const transparentSyncing = ref(false);
const transparentProgressSyncing = ref(0.0);
const percentage = ref(0.0);
const syncTStr = ref('');
// Shield sync status
const shieldSyncing = ref(false);
const shieldPercentageSyncing = ref(0.0);
const shieldBlockRemainingSyncing = ref(0);
const shieldSyncingStr = ref('');
// Shield transaction creation
const isCreatingTx = ref(false);
Expand Down Expand Up @@ -137,20 +136,20 @@ getEventEmitter().on(
]);
const progress = ((totalPages - i) / totalPages) * 100;
syncTStr.value = str;
transparentProgressSyncing.value = progress;
percentage.value = progress;
transparentSyncing.value = !finished;
}
);
getEventEmitter().on(
'shield-sync-status-update',
(blocks, totalBlocks, finished) => {
shieldPercentageSyncing.value = Math.round(
(blocks / totalBlocks) * 100
);
shieldBlockRemainingSyncing.value = (
totalBlocks - blocks
).toLocaleString('en-GB');
(bytes, totalBytes, finished) => {
percentage.value = Math.round((100 * bytes) / totalBytes);
const mb = bytes / 1_000_000;
const totalMb = totalBytes / 1_000_000;
shieldSyncingStr.value = `Syncing Shield (${mb.toFixed(
1
)}MB/${totalMb.toFixed(1)}MB)`;
shieldSyncing.value = !finished;
}
);
Expand Down Expand Up @@ -510,18 +509,10 @@ function restoreWallet() {
<i class="fas fa-spinner spinningLoading"></i>
</div>
<div style="width: 100%">
{{
transparentSyncing
? syncTStr
: `Syncing ${shieldBlockRemainingSyncing} Blocks...`
}}
{{ transparentSyncing ? syncTStr : shieldSyncingStr }}
<LoadingBar
:show="true"
:percentage="
transparentSyncing
? transparentProgressSyncing
: shieldPercentageSyncing
"
:percentage="percentage"
style="
border: 1px solid #932ecd;
border-radius: 4px;
Expand Down
15 changes: 14 additions & 1 deletion scripts/network/network.js
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,10 @@ export class Network {
throw new Error('getProposals must be implemented');
}

async getShieldData(_initialBlock = 0) {
throw new Error('getShieldData must be implemented');
}

async getProposalVote(_proposalName, _collateralTxId, _outidx) {
throw new Error('getProposalVote must be implemented');
}
Expand Down Expand Up @@ -153,6 +157,7 @@ export class RPCNodeNetwork extends Network {

async #callRPC(api, isText = false) {
const cRes = await this.#fetchNode(api);
if (!cRes.ok) throw new Error('Failed to call rpc');
const cResTxt = await cRes.text();
if (isText) return cResTxt;
// RPC calls with filters might return empty string instead of empty JSON,
Expand Down Expand Up @@ -199,7 +204,7 @@ export class RPCNodeNetwork extends Network {
// Use Nodes as a fallback
let strTXID = await this.#callRPC(
'/sendrawtransaction?params=' + hex,
true
'text'
);
strTXID = strTXID.replace(/"/g, '');
return { result: strTXID };
Expand Down Expand Up @@ -315,6 +320,14 @@ export class RPCNodeNetwork extends Network {
true
);
}

async getShieldData(startBlock) {
const res = await this.#fetchNode(
`/getshielddata?startBlock=${startBlock}`
);
if (!res.ok) throw new Error('Invalid response');
return res;
}
}

/**
Expand Down
Loading

0 comments on commit e0dec6a

Please sign in to comment.