From 4dbf69af37bb24c98e11ebdbfb74bfee78f38f1e Mon Sep 17 00:00:00 2001 From: Cristian Merlo Date: Wed, 3 Aug 2022 17:24:56 -0300 Subject: [PATCH 001/172] Added tests for change currency pairing --- .../features/pages/generalSettingsPage.js | 22 ++ .../features/pages/walletTransactionsPage.js | 6 +- .../yoroi-extension/features/settings.feature | 27 ++ .../features/step_definitions/common-steps.js | 21 +- .../general-settings-steps.js | 73 +++++- .../step_definitions/settings-ui-steps.js | 95 +++++-- .../step_definitions/sidebar-steps.js | 8 +- .../step_definitions/tx-history-steps.js | 247 ++++++++++-------- .../wallet-delegation-steps.js | 4 - .../support/helpers/common-constants.js | 5 + 10 files changed, 360 insertions(+), 148 deletions(-) create mode 100644 packages/yoroi-extension/features/pages/generalSettingsPage.js create mode 100644 packages/yoroi-extension/features/settings.feature diff --git a/packages/yoroi-extension/features/pages/generalSettingsPage.js b/packages/yoroi-extension/features/pages/generalSettingsPage.js new file mode 100644 index 0000000000..fd8707791a --- /dev/null +++ b/packages/yoroi-extension/features/pages/generalSettingsPage.js @@ -0,0 +1,22 @@ +// @flow + +import type { LocatorObject } from '../support/webdriver'; + +export const generalSettingsComponent: LocatorObject = { + locator: '.GeneralSettings_component', + method: 'css', +}; +export const coinPriceCurrency: LocatorObject = { + locator: '//div[starts-with(@id, "coinPriceCurrencyId--")]', + method: 'xpath', +}; + +export const amountDisplayFiat: LocatorObject = { + locator: '.AmountDisplay_fiat', + method: 'css', +}; + +export const amountDisplayADA: LocatorObject = { + locator: '.AmountDisplay_amount', + method: 'css', + }; \ No newline at end of file diff --git a/packages/yoroi-extension/features/pages/walletTransactionsPage.js b/packages/yoroi-extension/features/pages/walletTransactionsPage.js index 83ac150032..a06ea83a76 100644 --- a/packages/yoroi-extension/features/pages/walletTransactionsPage.js +++ b/packages/yoroi-extension/features/pages/walletTransactionsPage.js @@ -1,3 +1,7 @@ // @flow -export const walletSummaryBox = { locator: 'walletSummary_box', method: 'id' } \ No newline at end of file +export const walletSummaryBox = { locator: 'walletSummary_box', method: 'id' }; +export const walletTransactionAmount = { + locator: '//*[@id="root"]/div/div[2]/div/div/div[2]/div[2]/div[2]/div/div/div/div/div[3]/div[1]/div/div/div[1]/div/div[1]/div[3]/p', + method: 'xpath', +}; diff --git a/packages/yoroi-extension/features/settings.feature b/packages/yoroi-extension/features/settings.feature new file mode 100644 index 0000000000..5fa3788cf9 --- /dev/null +++ b/packages/yoroi-extension/features/settings.feature @@ -0,0 +1,27 @@ +Feature: Wallet UI Settings + + Background: + Given I have opened the extension + And I have completed the basic setup + Then I should see the Create wallet screen + Given There is a Shelley wallet stored named shelley-simple-15 + Then Revamp. I switch to revamp version + Then I should see the "General Settings" page + +@currency-1 + Scenario: Change currency pair to JPY + When I select JPY as fiat pairing currency + Then I see the correct conversion value for JPY on header + +@currency-2 + Scenario: Change currency pair back to ADA + When I select USD as fiat pairing currency + And I select ADA as fiat pairing currency + Then I see only ADA value on header + +@currency-3 + Scenario: Check wallet transactions pairings after changing currency to EUR + When I select EUR as fiat pairing currency + And Revamp. I go to the wallet shelley-simple-15 + Then I validate the transaction amount to EUR currency pairing + diff --git a/packages/yoroi-extension/features/step_definitions/common-steps.js b/packages/yoroi-extension/features/step_definitions/common-steps.js index 5553002f5a..81017753bf 100644 --- a/packages/yoroi-extension/features/step_definitions/common-steps.js +++ b/packages/yoroi-extension/features/step_definitions/common-steps.js @@ -9,6 +9,7 @@ import { AfterAll, setDefinitionFunctionWrapper, setDefaultTimeout, + When, } from 'cucumber'; import * as CardanoServer from '../mock-chain/mockCardanoServer'; import * as ErgoServer from '../mock-chain/mockErgoServer'; @@ -17,10 +18,7 @@ import { enterRecoveryPhrase, getLogDate } from '../support/helpers/helpers'; import { testWallets } from '../mock-chain/TestWallets'; import * as ErgoImporter from '../mock-chain/mockErgoImporter'; import * as CardanoImporter from '../mock-chain/mockCardanoImporter'; -import { - testRunsDataDir, - snapshotsDir, - } from '../support/helpers/common-constants'; +import { testRunsDataDir, snapshotsDir } from '../support/helpers/common-constants'; import { expect } from 'chai'; import { satisfies } from 'semver'; // eslint-disable-next-line import/named @@ -50,7 +48,7 @@ import { trezorConfirmButton, walletNameInput, saveDialog, - saveButton + saveButton, } from '../pages/newWalletPages'; import { allowPubKeysAndSwitchToYoroi, switchToTrezorAndAllow } from './trezor-steps'; import * as helpers from '../support/helpers/helpers'; @@ -661,7 +659,16 @@ Then(/^Revamp. I go to the wallet ([^"]*)$/, async function (walletName) { await walletButtonInRow.click(); }); -Then(/^Debug. Take screenshot$/, async function () { +Then(/^I should see the dashboard screen$/, async function () { + await this.waitForElement({ locator: '.StakingDashboard_page', method: 'css' }); +}); + +When(/^I go to General Settings$/, async function () { + await goToSettings(this); + await selectSubmenuSettings(this, 'general'); +}); + +Then(/^Debug. Take screenshot$/, async function () { const currentTime = getLogDate(); await takeScreenshot(this.driver, `debug_${currentTime}`); await takePageSnapshot(this.driver, `debug_${currentTime}`); @@ -671,4 +678,4 @@ Then(/^Debug. Take screenshot$/, async function () { Then(/^Debug. Make driver sleep for 2 seconds$/, async function () { await this.driver.sleep(2000); -}); \ No newline at end of file +}); diff --git a/packages/yoroi-extension/features/step_definitions/general-settings-steps.js b/packages/yoroi-extension/features/step_definitions/general-settings-steps.js index a3ca6d8be3..3fff603827 100644 --- a/packages/yoroi-extension/features/step_definitions/general-settings-steps.js +++ b/packages/yoroi-extension/features/step_definitions/general-settings-steps.js @@ -5,14 +5,26 @@ import { camelCase } from 'lodash'; import { waitUntilUrlEquals, navigateTo } from '../support/helpers/route-helpers'; import i18n from '../support/helpers/i18n-helpers'; import { By, WebElement } from 'selenium-webdriver'; +import { expect } from 'chai'; +import { + generalSettingsComponent, + coinPriceCurrency, + amountDisplayFiat, + amountDisplayADA, +} from '../pages/generalSettingsPage'; +import type { LocatorObject } from '../support/webdriver'; +import { adaToFiatPrices } from '../support/helpers/common-constants'; + +const axios = require('axios'); export async function selectSubmenuSettings(customWorld: Object, buttonName: string) { const formattedButtonName = camelCase(buttonName); const buttonSelector = `.SubMenuItem_component.${formattedButtonName}`; await customWorld.click({ locator: buttonSelector, method: 'css' }); - await customWorld.waitForElement( - { locator: `.SubMenuItem_component.SubMenuItem_active.${formattedButtonName}`, method: 'css' } - ); + await customWorld.waitForElement({ + locator: `.SubMenuItem_component.SubMenuItem_active.${formattedButtonName}`, + method: 'css', + }); } export async function goToSettings(customWorld: Object) { @@ -46,11 +58,17 @@ When(/^I click on secondary menu "([^"]*)" item$/, async function (buttonName) { const formattedButtonName = camelCase(buttonName); const buttonSelector = `.SubMenuItem_component.${formattedButtonName}`; await this.click({ locator: buttonSelector, method: 'css' }); - await this.waitForElement({ locator: `.SubMenuItem_component.SubMenuItem_active.${formattedButtonName}`, method: 'css' }); + await this.waitForElement({ + locator: `.SubMenuItem_component.SubMenuItem_active.${formattedButtonName}`, + method: 'css', + }); }); When(/^I select second theme$/, async function () { - await this.click({ locator: '.ThemeSettingsBlock_themesWrapper > button:nth-child(2)', method: 'css' }); + await this.click({ + locator: '.ThemeSettingsBlock_themesWrapper > button:nth-child(2)', + method: 'css', + }); }); When(/^I open General Settings language selection dropdown$/, async function () { @@ -76,7 +94,7 @@ Then(/^The Japanese language should be selected$/, async function () { Then(/^I should see second theme as selected$/, async function () { await this.waitForElement({ locator: '.ThemeSettingsBlock_themesWrapper button:nth-child(2).ThemeSettingsBlock_active', - method: 'css' + method: 'css', }); }); @@ -93,3 +111,46 @@ Then(/^I select the simplest level$/, async function () { const cardChoseButton = await getComplexityLevelButton(this, true); await cardChoseButton.click(); // chose the simplest }); + +Then(/^I should see the "General Settings" page$/, async function () { + await this.waitForElement(generalSettingsComponent); +}); + +When( + /^I select (ADA|USD|JPY|EUR|CNY|KRW|BTC|ETH|BRL) as fiat pairing currency$/, + async function (currency) { + await this.waitForElement(coinPriceCurrency); + await this.click(coinPriceCurrency); + + const currencySelector: LocatorObject = { + locator: `//*[starts-with(text(), "${currency}")]`, + method: 'xpath', + }; + await this.waitForElement(currencySelector); + await this.click(currencySelector); + } +); + +Then( + /^I see the correct conversion value for (USD|JPY|EUR|CNY|KRW|BTC|ETH|BRL) on header$/, + async function (currency) { + const amountFiat = await this.driver.findElement(By.css('.AmountDisplay_fiat')); + const amountDisplayFiatValue = await amountFiat.getText(); + + const response = await axios(adaToFiatPrices); + + const value = await response.data.ticker.prices[currency]; + + const amountDisplayAmount = await this.driver.findElement(By.css('.AmountDisplay_amount')); + const adaAmount = await amountDisplayAmount.getText(); + const adaValue = await parseFloat(parseFloat(adaAmount.replace('\n', '').replace(' ADA', '')).toFixed(2)); + const expectedValue = await adaValue * value; + + expect(amountDisplayFiatValue).to.equal(`${expectedValue} ${currency}`); + } +); + +Then(/^I see only ADA value on header$/, async function () { + expect(await this.isDisplayed(amountDisplayADA), 'ADA value is not displayed').to.be.true; + expect(await this.checkIfExists(amountDisplayFiat), 'The fiat value is displayed').to.be.false; +}); diff --git a/packages/yoroi-extension/features/step_definitions/settings-ui-steps.js b/packages/yoroi-extension/features/step_definitions/settings-ui-steps.js index 9567bda029..776a5bc06a 100644 --- a/packages/yoroi-extension/features/step_definitions/settings-ui-steps.js +++ b/packages/yoroi-extension/features/step_definitions/settings-ui-steps.js @@ -3,7 +3,7 @@ import { When, Given, Then } from 'cucumber'; import i18n from '../support/helpers/i18n-helpers'; import { By, Key } from 'selenium-webdriver'; -import { truncateLongName, } from '../../app/utils/formatters'; +import { truncateLongName } from '../../app/utils/formatters'; import { expect } from 'chai'; import { checkErrorByTranslationId } from './common-steps'; @@ -15,7 +15,10 @@ Given(/^I should see the "([^"]*)" wallet password dialog$/, async function (dia }); When(/^I click on "name" input field$/, async function () { - await this.click({ locator: '.SettingsLayout_settingsPane .InlineEditingInput_component', method: 'css' }); + await this.click({ + locator: '.SettingsLayout_settingsPane .InlineEditingInput_component', + method: 'css', + }); }); When(/^I enter new wallet name:$/, async function (table) { @@ -25,7 +28,7 @@ When(/^I enter new wallet name:$/, async function (table) { * This makes our InlineEditingInput become disabled causing the clear and sendKeys to fail * https://github.com/seleniumhq/selenium-google-code-issue-archive/issues/214 * We instead repeatedly delete characters until we've deleted the whole name - */ + */ // can't programmatically get the wallet name due to the issue above // so assume max length @@ -53,17 +56,32 @@ When(/^I click on the "([^"]*)" password label$/, async function (label) { When(/^I change wallet password:$/, async function (table) { const fields = table.hashes()[0]; - await this.input({ locator: '.changePasswordDialog .currentPassword input', method: 'css' }, fields.currentPassword); - await this.input({ locator: '.changePasswordDialog .newPassword input', method: 'css' }, fields.password); - await this.input({ locator: '.changePasswordDialog .repeatedPassword input', method: 'css' }, fields.repeatedPassword); + await this.input( + { locator: '.changePasswordDialog .currentPassword input', method: 'css' }, + fields.currentPassword + ); + await this.input( + { locator: '.changePasswordDialog .newPassword input', method: 'css' }, + fields.password + ); + await this.input( + { locator: '.changePasswordDialog .repeatedPassword input', method: 'css' }, + fields.repeatedPassword + ); }); When(/^I clear the current wallet password ([^"]*)$/, async function (password) { - await this.clearInputUpdatingForm({ locator: '.changePasswordDialog .currentPassword input', method: 'css' }, password.length); + await this.clearInputUpdatingForm( + { locator: '.changePasswordDialog .currentPassword input', method: 'css' }, + password.length + ); }); When(/^I clear the current wallet repeat password ([^"]*)$/, async function (repeatPassword) { - await this.clearInputUpdatingForm({ locator: '.changePasswordDialog .repeatedPassword input', method: 'css' }, repeatPassword.length); + await this.clearInputUpdatingForm( + { locator: '.changePasswordDialog .repeatedPassword input', method: 'css' }, + repeatPassword.length + ); }); When(/^I submit the wallet password dialog$/, async function () { @@ -79,15 +97,22 @@ Then(/^I should not see the change password dialog anymore$/, async function () }); Then(/^I should see new wallet name "([^"]*)"$/, async function (walletName) { - await this.waitUntilText({ locator: '.NavPlate_name', method: 'css' }, truncateLongName(walletName)); + await this.waitUntilText( + { locator: '.NavPlate_name', method: 'css' }, + truncateLongName(walletName) + ); }); Then(/^I should see the following error messages:$/, async function (data) { const error = data.hashes()[0]; await checkErrorByTranslationId( this, - { locator: '//p[starts-with(@id, "walletPassword--") and contains(@id, "-helper-text")]', method: 'xpath' }, - error); + { + locator: '//p[starts-with(@id, "walletPassword--") and contains(@id, "-helper-text")]', + method: 'xpath', + }, + error + ); }); Then(/^I should see "Doesn't match" error message:$/, async function (data) { @@ -95,7 +120,8 @@ Then(/^I should see "Doesn't match" error message:$/, async function (data) { await checkErrorByTranslationId( this, { locator: '.MuiFormHelperText-root', method: 'css' }, - error); + error + ); }); Then(/^I should see the following submit error messages:$/, async function (data) { @@ -103,25 +129,43 @@ Then(/^I should see the following submit error messages:$/, async function (data await checkErrorByTranslationId( this, { locator: '.ChangeWalletPasswordDialog_error', method: 'css' }, - error); + error + ); }); Then(/^I should stay in the change password dialog$/, async function () { - const changePasswordMessage = await i18n.formatMessage(this.driver, - { id: 'wallet.settings.changePassword.dialog.title.changePassword' }); - await this.waitUntilText({ locator: '.dialog__title', method: 'css' }, changePasswordMessage.toUpperCase(), 2000); + const changePasswordMessage = await i18n.formatMessage(this.driver, { + id: 'wallet.settings.changePassword.dialog.title.changePassword', + }); + await this.waitUntilText( + { locator: '.dialog__title', method: 'css' }, + changePasswordMessage.toUpperCase(), + 2000 + ); }); Then(/^I should see support screen$/, async function () { - await this.waitForElement({ locator: "//h1[contains(text(), 'Frequently asked questions')]", method: 'xpath' }); - await this.waitForElement({ locator: "//h1[contains(text(), 'Reporting a problem')]", method: 'xpath' }); + await this.waitForElement({ + locator: "//h1[contains(text(), 'Frequently asked questions')]", + method: 'xpath', + }); + await this.waitForElement({ + locator: "//h1[contains(text(), 'Reporting a problem')]", + method: 'xpath', + }); await this.waitForElement({ locator: "//h1[contains(text(), 'Logs')]", method: 'xpath' }); }); Then(/^I should see blockchain screen$/, async function () { await this.waitForElement({ locator: '.ExplorerSettings_component', method: 'css' }); - await this.waitForElement({ locator: "//h2[contains(text(), 'Cardano Payment URLs')]", method: 'xpath' }); - await this.waitForElement({ locator: "//h2[contains(text(), 'Currency Conversion')]", method: 'xpath' }); + await this.waitForElement({ + locator: "//h2[contains(text(), 'Cardano Payment URLs')]", + method: 'xpath', + }); + await this.waitForElement({ + locator: "//h2[contains(text(), 'Currency Conversion')]", + method: 'xpath', + }); }); When(/^I click on remove wallet$/, async function () { @@ -144,16 +188,15 @@ Then(/^I should see the wallet export for key "([^"]*)"$/, async function (expec }); Then(/^I click on the checkbox$/, async function () { - const warningCheckboxElement = await this.driver.findElement(By.css('.DangerousActionDialog_checkbox')); + const warningCheckboxElement = await this.driver.findElement( + By.css('.DangerousActionDialog_checkbox') + ); const checkbox = await warningCheckboxElement.findElement(By.xpath('//input[@type="checkbox"]')); await checkbox.click(); }); Then(/^I should see a no wallet message$/, async function () { - const noWalletMessage = await i18n.formatMessage( - this.driver, - { id: 'wallet.nowallet.title' } - ); + const noWalletMessage = await i18n.formatMessage(this.driver, { id: 'wallet.nowallet.title' }); await this.waitUntilText({ locator: '.FullscreenMessage_title', method: 'css' }, noWalletMessage); }); @@ -161,7 +204,7 @@ Then(/^I sleep for ([^"]*)$/, async function (ms) { await this.driver.sleep(Number.parseInt(ms, 10)); }); -Then(/^I should see "Incorrect wallet password." error message$/, async function(){ +Then(/^I should see "Incorrect wallet password." error message$/, async function () { const errorSelector = '.ChangeWalletPasswordDialog_error'; await this.waitUntilText( { locator: errorSelector, method: 'css' }, diff --git a/packages/yoroi-extension/features/step_definitions/sidebar-steps.js b/packages/yoroi-extension/features/step_definitions/sidebar-steps.js index 94bbdf291a..0d2e447da5 100644 --- a/packages/yoroi-extension/features/step_definitions/sidebar-steps.js +++ b/packages/yoroi-extension/features/step_definitions/sidebar-steps.js @@ -2,7 +2,7 @@ import { When, Then } from 'cucumber'; import { expect } from 'chai'; -import { faqButton } from '../pages/sidebarPage'; +import { faqButton, walletButton } from '../pages/sidebarPage'; import { faqTabName } from '../support/windowManager'; When(/^I click on FAQ button$/, async function () { @@ -21,3 +21,9 @@ Then(/^I should see a new tab opened with address (.+)$/, async function (addres const actualAddresses = await this.driver.getCurrentUrl(); expect(actualAddresses).to.equal(address); }); + +When(/^I click on Wallet button$/, async function () { + this.webDriverLogger.info(`Step: I click on Wallet button`); + await this.click(walletButton); + await this.waitForElement() +}); diff --git a/packages/yoroi-extension/features/step_definitions/tx-history-steps.js b/packages/yoroi-extension/features/step_definitions/tx-history-steps.js index 02ea1952b2..dc8b9ff7e2 100644 --- a/packages/yoroi-extension/features/step_definitions/tx-history-steps.js +++ b/packages/yoroi-extension/features/step_definitions/tx-history-steps.js @@ -2,13 +2,25 @@ import { Then, When, Given } from 'cucumber'; import { By } from 'selenium-webdriver'; -import chai from 'chai'; +import chai, { expect } from 'chai'; import moment from 'moment'; import i18n from '../support/helpers/i18n-helpers'; +import { walletTransactionAmount } from '../pages/walletTransactionsPage'; +import { adaToFiatPrices } from '../support/helpers/common-constants'; + +const axios = require('axios'); function verifyAllTxsFields( - txType, txAmount, txTime, txStatus, txFee, txFromList, txToList, - txId, expectedTx, txConfirmations + txType, + txAmount, + txTime, + txStatus, + txFee, + txFromList, + txToList, + txId, + expectedTx, + txConfirmations ) { chai.expect(txType).to.equal(expectedTx.txType); chai.expect(txAmount.split(' ')[0]).to.equal(expectedTx.txAmount); @@ -47,8 +59,9 @@ When(/^I see the transactions summary$/, async function () { Then( /^I should see that the number of transactions is ([^"]*)$/, async function (expectedTxsNumber) { - const txsNumberMessage = await i18n.formatMessage(this.driver, - { id: 'wallet.summary.page.transactionsLabel' }); + const txsNumberMessage = await i18n.formatMessage(this.driver, { + id: 'wallet.summary.page.transactionsLabel', + }); await this.waitUntilText( { locator: '.WalletSummary_numberOfTransactions', method: 'css' }, txsNumberMessage + ': ' + expectedTxsNumber @@ -56,56 +69,63 @@ Then( } ); - Then(/^I should see no transactions$/, async function () { await this.waitForElement({ locator: '.WalletNoTransactions_component', method: 'css' }); - const actualTxsList = await this.getElementsBy({ locator: '.Transaction_component', method: 'css' }); + const actualTxsList = await this.getElementsBy({ + locator: '.Transaction_component', + method: 'css', + }); chai.expect(actualTxsList.length).to.equal(0); }); -Then( - /^I should see ([^"]*) ([^"]*) transactions$/, - async function (txsNumber, txExpectedStatus) { - const txsAmount = parseInt(txsNumber, 10); - const showMoreLocator = '.WalletTransactionsList_component .MuiButton-primary'; +Then(/^I should see ([^"]*) ([^"]*) transactions$/, async function (txsNumber, txExpectedStatus) { + const txsAmount = parseInt(txsNumber, 10); + const showMoreLocator = '.WalletTransactionsList_component .MuiButton-primary'; - await this.driver.sleep(500); - // press the show more transaction button until all transactions are visible - for (let i = 1; i < txsAmount; i++) { - const buttonShowMoreExists = await this.checkIfExists({ locator: showMoreLocator, method: 'css' }); - if (!buttonShowMoreExists) { - break; - } - await this.click({ locator: showMoreLocator, method: 'css' }); - await this.driver.sleep(500); + await this.driver.sleep(500); + // press the show more transaction button until all transactions are visible + for (let i = 1; i < txsAmount; i++) { + const buttonShowMoreExists = await this.checkIfExists({ + locator: showMoreLocator, + method: 'css', + }); + if (!buttonShowMoreExists) { + break; } + await this.click({ locator: showMoreLocator, method: 'css' }); + await this.driver.sleep(500); + } - const allTxsList = await this.getElementsBy({ locator: '.Transaction_component', method: 'css' }); - const pendingTxsList = await this.getElementsBy({ locator: '.Transaction_pendingLabel', method: 'css' }); - const failedTxsList = await this.getElementsBy({ locator: '.Transaction_failedLabel', method: 'css' }); - if (txExpectedStatus === 'pending') { - chai.expect(pendingTxsList.length).to.equal(txsAmount); - return; - } - if (txExpectedStatus === 'failed') { - chai.expect(failedTxsList.length).to.equal(txsAmount); - return; - } - chai.expect(allTxsList.length - pendingTxsList.length - failedTxsList.length) - .to.equal(txsAmount); + const allTxsList = await this.getElementsBy({ locator: '.Transaction_component', method: 'css' }); + const pendingTxsList = await this.getElementsBy({ + locator: '.Transaction_pendingLabel', + method: 'css', + }); + const failedTxsList = await this.getElementsBy({ + locator: '.Transaction_failedLabel', + method: 'css', + }); + if (txExpectedStatus === 'pending') { + chai.expect(pendingTxsList.length).to.equal(txsAmount); + return; } -); + if (txExpectedStatus === 'failed') { + chai.expect(failedTxsList.length).to.equal(txsAmount); + return; + } + chai.expect(allTxsList.length - pendingTxsList.length - failedTxsList.length).to.equal(txsAmount); +}); -When( - /^I expand the top transaction$/, - async function () { - await this.waitForElement({ locator: '.Transaction_component', method: 'css' }); - const actualTxsList = await this.getElementsBy({ locator: '.Transaction_component', method: 'css' }); - const topTx = actualTxsList[0]; +When(/^I expand the top transaction$/, async function () { + await this.waitForElement({ locator: '.Transaction_component', method: 'css' }); + const actualTxsList = await this.getElementsBy({ + locator: '.Transaction_component', + method: 'css', + }); + const topTx = actualTxsList[0]; - await topTx.click(); - } -); + await topTx.click(); +}); async function parseTxInfo(addressList) { const addressInfoRow = await addressList.findElements(By.css('.Transaction_addressItem')); @@ -120,65 +140,75 @@ async function parseTxInfo(addressList) { return result; } -Then( - /^I verify top transaction content ([^"]*)$/, - async function (walletName) { - await this.waitForElement({ locator: '.Transaction_component', method: 'css' }); - const actualTxsList = await this.getElementsBy({ locator: '.Transaction_component', method: 'css' }); - const topTx = actualTxsList[0]; - - let status = 'successful'; - { - const pending = await topTx.findElements(By.css('.Transaction_pendingLabel')); - const failed = await topTx.findElements(By.css('.Transaction_failedLabel')); - if (pending.length > 0) { - status = 'pending'; - } else if (failed.length > 0) { - status = 'failed'; - } +Then(/^I verify top transaction content ([^"]*)$/, async function (walletName) { + await this.waitForElement({ locator: '.Transaction_component', method: 'css' }); + const actualTxsList = await this.getElementsBy({ + locator: '.Transaction_component', + method: 'css', + }); + const topTx = actualTxsList[0]; + + let status = 'successful'; + { + const pending = await topTx.findElements(By.css('.Transaction_pendingLabel')); + const failed = await topTx.findElements(By.css('.Transaction_failedLabel')); + if (pending.length > 0) { + status = 'pending'; + } else if (failed.length > 0) { + status = 'failed'; } + } - await topTx.click(); + await topTx.click(); - const txList = await topTx.findElements(By.css('.Transaction_addressList')); - const fromTxInfo = await parseTxInfo(txList[0]); - const toTxInfo = await parseTxInfo(txList[1]); + const txList = await topTx.findElements(By.css('.Transaction_addressList')); + const fromTxInfo = await parseTxInfo(txList[0]); + const toTxInfo = await parseTxInfo(txList[1]); - const txData = await topTx.getText(); - const txDataFields = txData.split('\n'); - const [txTime, txType, txStatus, txFee, txAmount] = txDataFields; + const txData = await topTx.getText(); + const txDataFields = txData.split('\n'); + const [txTime, txType, txStatus, txFee, txAmount] = txDataFields; - const expectedTx = displayInfo[walletName]; + const expectedTx = displayInfo[walletName]; - const txId = await (async () => { - const elem = await topTx.findElement(By.css('.txid')); - return await elem.getText(); - })(); - const txConfirmation = - status === 'successful' - ? await (async () => { + const txId = await (async () => { + const elem = await topTx.findElement(By.css('.txid')); + return await elem.getText(); + })(); + const txConfirmation = + status === 'successful' + ? await (async () => { const txConfirmationsCount = await topTx.findElement(By.css('.confirmationCount')); const txConfirmationParentElem = await txConfirmationsCount.findElement(By.xpath('./..')); return await txConfirmationParentElem.getText(); })() - : undefined; + : undefined; - verifyAllTxsFields(txType, txAmount, txTime, txStatus, txFee, fromTxInfo, - toTxInfo, txId, expectedTx, txConfirmation); - } -); + verifyAllTxsFields( + txType, + txAmount, + txTime, + txStatus, + txFee, + fromTxInfo, + toTxInfo, + txId, + expectedTx, + txConfirmation + ); +}); -Then( - /^The number of confirmations of the top tx is ([^"]*)$/, - async function (count) { - await this.waitForElement({ locator: '.Transaction_component', method: 'css' }); - const actualTxsList = await this.getElementsBy({ locator: '.Transaction_component', method: 'css' }); - const topTx = actualTxsList[0]; - const assuranceElem = await topTx.findElements(By.css('.confirmationCount')); - const confirmationCount = await assuranceElem[0].getText(); - chai.expect(confirmationCount).to.equal(count); - } -); +Then(/^The number of confirmations of the top tx is ([^"]*)$/, async function (count) { + await this.waitForElement({ locator: '.Transaction_component', method: 'css' }); + const actualTxsList = await this.getElementsBy({ + locator: '.Transaction_component', + method: 'css', + }); + const topTx = actualTxsList[0]; + const assuranceElem = await topTx.findElements(By.css('.confirmationCount')); + const confirmationCount = await assuranceElem[0].getText(); + chai.expect(confirmationCount).to.equal(count); +}); const displayInfo = { 'many-tx-wallet': { @@ -186,9 +216,7 @@ const displayInfo = { txAmount: '-0.169999', txTime: '2019-04-21T15:13:33.000Z', txStatus: 'HIGH', - txFrom: [ - ['Ae2tdPwUPE...VWfitHfUM9', 'BYRON - INTERNAL', '-0.82 ADA'], - ], + txFrom: [['Ae2tdPwUPE...VWfitHfUM9', 'BYRON - INTERNAL', '-0.82 ADA']], txTo: [ ['Ae2tdPwUPE...iLjTnt34Aj', 'BYRON - EXTERNAL', '+0.000001 ADA'], ['Ae2tdPwUPE...BA7XbSMhKd', 'BYRON - INTERNAL', '+0.65 ADA'], @@ -202,12 +230,8 @@ const displayInfo = { txAmount: '-0.999999', txTime: '2019-04-20T23:14:52.000Z', txStatus: 'PENDING', - txFrom: [ - ['Ae2tdPwUPE...e1cT2aGdSJ', 'BYRON - EXTERNAL', '-1 ADA'], - ], - txTo: [ - ['Ae2tdPwUPE...sTrQfTxPVX', 'PROCESSING...', '+0.000001 ADA'] - ], + txFrom: [['Ae2tdPwUPE...e1cT2aGdSJ', 'BYRON - EXTERNAL', '-1 ADA']], + txTo: [['Ae2tdPwUPE...sTrQfTxPVX', 'PROCESSING...', '+0.000001 ADA']], txId: 'fa6f2c82fb511d0cc9c12a540b5fac6e5a9b0f288f2d140f909f981279e16fbe', txFee: '0.999999', }, @@ -216,9 +240,7 @@ const displayInfo = { txAmount: '-0.18', txTime: '2019-04-20T23:14:51.000Z', txStatus: 'FAILED', - txFrom: [ - ['Ae2tdPwUPE...gBfkkDNBNv', 'BYRON - EXTERNAL', '-1 ADA'], - ], + txFrom: [['Ae2tdPwUPE...gBfkkDNBNv', 'BYRON - EXTERNAL', '-1 ADA']], txTo: [ ['Ae2tdPwUPE...xJPmFzi6G2', 'ADDRESS BOOK', '+0.000001 ADA'], ['Ae2tdPwUPE...bL4UYPN3eU', 'BYRON - INTERNAL', '+0.82 ADA'], @@ -231,3 +253,22 @@ const displayInfo = { When(/^I go to the tx history screen$/, async function () { await this.click({ locator: '.summary ', method: 'css' }); }); + +Then( + /^I validate the transaction amount to (USD|JPY|EUR|CNY|KRW|BTC|ETH|BRL) currency pairing$/, + async function (currency) { + const txAmount = await this.getText(walletTransactionAmount); + expect(txAmount).to.contain(currency); + + const response = await axios(adaToFiatPrices); + const rate = await response.data.ticker.prices[currency]; + + const amountList = await txAmount.split('\n'); + + const fiatAmount = await amountList[0].replace(currency, ''); + const adaAmount = await parseFloat(amountList[1].replace('ADA', '')); + + const expectedValue = await parseFloat(((await adaAmount) * rate).toFixed(6)); + expect(fiatAmount).to.contain(`${expectedValue}`); + } +); diff --git a/packages/yoroi-extension/features/step_definitions/wallet-delegation-steps.js b/packages/yoroi-extension/features/step_definitions/wallet-delegation-steps.js index b2d43721f7..b2594cf3d2 100644 --- a/packages/yoroi-extension/features/step_definitions/wallet-delegation-steps.js +++ b/packages/yoroi-extension/features/step_definitions/wallet-delegation-steps.js @@ -28,7 +28,3 @@ Given(/^I click on see dashboard$/, async function () { await this.click({ locator: "//button[contains(text(), 'Dashboard page')]", method: 'xpath' }); }); -When(/^I should see the dashboard screen$/, async function () { - await this.waitForElement({ locator: '.StakingDashboard_page', method: 'css' }); -}); - diff --git a/packages/yoroi-extension/features/support/helpers/common-constants.js b/packages/yoroi-extension/features/support/helpers/common-constants.js index 19ed3b4ccc..06fe888d4f 100644 --- a/packages/yoroi-extension/features/support/helpers/common-constants.js +++ b/packages/yoroi-extension/features/support/helpers/common-constants.js @@ -13,3 +13,8 @@ export const emailOptions = { url: `https://mailsac.com/api/addresses/${mailsacEmail}/messages`, headers: { 'Mailsac-Key': mailsacAPIKey }, }; + +export const adaToFiatPrices = { + method: 'get', + url: `https://iohk-mainnet.yoroiwallet.com/api/price/ADA/current`, +} From e0d70a55a9210d579dceee84f46a21861300a7cb Mon Sep 17 00:00:00 2001 From: Denis Date: Thu, 4 Aug 2022 16:45:46 +0300 Subject: [PATCH 002/172] Added ids for testing purposes --- .../app/components/wallet/transactions/TransactionRevamp.js | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/packages/yoroi-extension/app/components/wallet/transactions/TransactionRevamp.js b/packages/yoroi-extension/app/components/wallet/transactions/TransactionRevamp.js index 0cc8fcd40e..4445c2d34e 100644 --- a/packages/yoroi-extension/app/components/wallet/transactions/TransactionRevamp.js +++ b/packages/yoroi-extension/app/components/wallet/transactions/TransactionRevamp.js @@ -548,7 +548,7 @@ export default class TransactionRevamp extends Component { {moment(data.date).format('hh:mm A')} - + {state === TxStatusCodes.IN_BLOCK ? ( { variant="body1" color="var(--yoroi-palette-gray-900)" sx={columnTXStyles.fee} + id='txFee' > {this.renderFeeDisplay({ amount: data.fee, @@ -587,7 +588,7 @@ export default class TransactionRevamp extends Component { })} - + {this.renderAmountWithUnitOfAccount({ entry: data.amount.getDefaultEntry(), timestamp: data.date.valueOf(), From f3577bc8c8b9dfaa5366f283ceeee49e5c2b14e4 Mon Sep 17 00:00:00 2001 From: Cristian Merlo Date: Thu, 4 Aug 2022 17:22:14 -0300 Subject: [PATCH 003/172] Added all the fiat currencies to tests and added endpoint to mockCardanoServer --- .../mock-chain/mockCardanoImporter.js | 25 +++++++++- .../features/mock-chain/mockCardanoServer.js | 8 +++ .../features/pages/walletTransactionsPage.js | 4 -- .../yoroi-extension/features/settings.feature | 49 ++++++++++++++++--- .../general-settings-steps.js | 16 +++--- .../step_definitions/tx-history-steps.js | 26 ++++++---- .../features/support/webdriver.js | 8 +++ 7 files changed, 104 insertions(+), 32 deletions(-) diff --git a/packages/yoroi-extension/features/mock-chain/mockCardanoImporter.js b/packages/yoroi-extension/features/mock-chain/mockCardanoImporter.js index ae2fff71d8..b9e5c30345 100644 --- a/packages/yoroi-extension/features/mock-chain/mockCardanoImporter.js +++ b/packages/yoroi-extension/features/mock-chain/mockCardanoImporter.js @@ -2315,7 +2315,27 @@ const getUtxoData = (txHash: string, txIndex: number): UtxoData | null => { output: output.output, spendingTxHash: output.spendingTxHash }; -} +}; + +const currentADAPrice = { + error: null, + ticker: { + from: 'ADA', + timestamp: 1659640203000, + signature: + '5ead08f0e91be35413d5a9b25da1727779aa3a3298b87a343a449b65ef24285d4b128d58e9806bfb209b4bcb83f620de347b93534553d0410c8092cc66c83d0a', + prices: { + BRL: 2.5935456329171314, + BTC: 0.000022075, + CNY: 3.358264434856802, + ETH: 0.00031116608241096773, + EUR: 0.48543447946200424, + JPY: 66.128348113336, + KRW: 648.4642598773457, + USD: 0.4975722571017442, + }, + }, +}; export default { utxoForAddresses, @@ -2329,4 +2349,5 @@ export default { getRewardHistory, getAccountState, getUtxoData, -}; + currentADAPrice, +}; \ No newline at end of file diff --git a/packages/yoroi-extension/features/mock-chain/mockCardanoServer.js b/packages/yoroi-extension/features/mock-chain/mockCardanoServer.js index 7ae28156e0..e04a1fc3ee 100644 --- a/packages/yoroi-extension/features/mock-chain/mockCardanoServer.js +++ b/packages/yoroi-extension/features/mock-chain/mockCardanoServer.js @@ -276,6 +276,14 @@ export function getMockServer(settings: { res.send(status); }); + server.get('/api/price/ADA/current', (req, res) => { + logger.info(`mockCardanoServer: /api/price/ADA/current -> request`); + const price = mockImporter.currentADAPrice; + logger.info(`mockCardanoServer: GET: /api/price/ADA/current`); + logger.info(JSON.stringify(price)); + res.send(price); + }); + // To test the dApp connector, we need a no-op mock dApp. server.get('/mock-dapp', (req, res: { send(arg: ServerStatusResponse): any, ... }): void => { // $FlowFixMe[prop-missing] diff --git a/packages/yoroi-extension/features/pages/walletTransactionsPage.js b/packages/yoroi-extension/features/pages/walletTransactionsPage.js index a06ea83a76..432894043a 100644 --- a/packages/yoroi-extension/features/pages/walletTransactionsPage.js +++ b/packages/yoroi-extension/features/pages/walletTransactionsPage.js @@ -1,7 +1,3 @@ // @flow export const walletSummaryBox = { locator: 'walletSummary_box', method: 'id' }; -export const walletTransactionAmount = { - locator: '//*[@id="root"]/div/div[2]/div/div/div[2]/div[2]/div[2]/div/div/div/div/div[3]/div[1]/div/div/div[1]/div/div[1]/div[3]/p', - method: 'xpath', -}; diff --git a/packages/yoroi-extension/features/settings.feature b/packages/yoroi-extension/features/settings.feature index 5fa3788cf9..6127a92fa0 100644 --- a/packages/yoroi-extension/features/settings.feature +++ b/packages/yoroi-extension/features/settings.feature @@ -9,19 +9,52 @@ Feature: Wallet UI Settings Then I should see the "General Settings" page @currency-1 - Scenario: Change currency pair to JPY - When I select JPY as fiat pairing currency - Then I see the correct conversion value for JPY on header + Scenario Outline: Change currency pair + When I select as fiat pairing currency + Then I see the correct conversion value for on header + + Examples: + | currency | + | USD | + | JPY | + | EUR | + | CNY | + | KRW | + | BTC | + | ETH | + | BRL | @currency-2 - Scenario: Change currency pair back to ADA - When I select USD as fiat pairing currency + Scenario Outline: Change currency pair back to ADA + When I select as fiat pairing currency And I select ADA as fiat pairing currency Then I see only ADA value on header + Examples: + | currency | + | USD | + | JPY | + | EUR | + | CNY | + | KRW | + | BTC | + | ETH | + | BRL | + @currency-3 - Scenario: Check wallet transactions pairings after changing currency to EUR - When I select EUR as fiat pairing currency + Scenario Outline: Check wallet transactions pairings after changing currency + When I select as fiat pairing currency And Revamp. I go to the wallet shelley-simple-15 - Then I validate the transaction amount to EUR currency pairing + Then I validate the transaction amount to currency pairing + + Examples: + | currency | + | USD | + | JPY | + | EUR | + | CNY | + | KRW | + | BTC | + | ETH | + | BRL | diff --git a/packages/yoroi-extension/features/step_definitions/general-settings-steps.js b/packages/yoroi-extension/features/step_definitions/general-settings-steps.js index 3fff603827..601bb38425 100644 --- a/packages/yoroi-extension/features/step_definitions/general-settings-steps.js +++ b/packages/yoroi-extension/features/step_definitions/general-settings-steps.js @@ -126,7 +126,8 @@ When( locator: `//*[starts-with(text(), "${currency}")]`, method: 'xpath', }; - await this.waitForElement(currencySelector); + + await this.scrollIntoView(currencySelector); await this.click(currencySelector); } ); @@ -134,18 +135,17 @@ When( Then( /^I see the correct conversion value for (USD|JPY|EUR|CNY|KRW|BTC|ETH|BRL) on header$/, async function (currency) { - const amountFiat = await this.driver.findElement(By.css('.AmountDisplay_fiat')); - const amountDisplayFiatValue = await amountFiat.getText(); + const amountDisplayFiatValue = await this.getText(amountDisplayFiat); const response = await axios(adaToFiatPrices); - const value = await response.data.ticker.prices[currency]; - const amountDisplayAmount = await this.driver.findElement(By.css('.AmountDisplay_amount')); - const adaAmount = await amountDisplayAmount.getText(); - const adaValue = await parseFloat(parseFloat(adaAmount.replace('\n', '').replace(' ADA', '')).toFixed(2)); - const expectedValue = await adaValue * value; + const adaAmount = await this.getText(amountDisplayADA); + const adaValue = await parseFloat( + parseFloat(adaAmount.replace('\n', '').replace(' ADA', '')).toFixed(2) + ); + const expectedValue = (await adaValue) * value; expect(amountDisplayFiatValue).to.equal(`${expectedValue} ${currency}`); } ); diff --git a/packages/yoroi-extension/features/step_definitions/tx-history-steps.js b/packages/yoroi-extension/features/step_definitions/tx-history-steps.js index dc8b9ff7e2..912908ff15 100644 --- a/packages/yoroi-extension/features/step_definitions/tx-history-steps.js +++ b/packages/yoroi-extension/features/step_definitions/tx-history-steps.js @@ -5,7 +5,6 @@ import { By } from 'selenium-webdriver'; import chai, { expect } from 'chai'; import moment from 'moment'; import i18n from '../support/helpers/i18n-helpers'; -import { walletTransactionAmount } from '../pages/walletTransactionsPage'; import { adaToFiatPrices } from '../support/helpers/common-constants'; const axios = require('axios'); @@ -257,18 +256,25 @@ When(/^I go to the tx history screen$/, async function () { Then( /^I validate the transaction amount to (USD|JPY|EUR|CNY|KRW|BTC|ETH|BRL) currency pairing$/, async function (currency) { - const txAmount = await this.getText(walletTransactionAmount); - expect(txAmount).to.contain(currency); + const allTxsAmountList = await this.getElementsBy({ + locator: 'transactionAmount', + method: 'id', + }); + + for (const txAmountElem of allTxsAmountList) { + const txAmount = await txAmountElem.getText(); + expect(txAmount).to.contain(currency); - const response = await axios(adaToFiatPrices); - const rate = await response.data.ticker.prices[currency]; + const response = await axios(adaToFiatPrices); + const rate = await response.data.ticker.prices[currency]; - const amountList = await txAmount.split('\n'); + const amountList = await txAmount.split('\n'); - const fiatAmount = await amountList[0].replace(currency, ''); - const adaAmount = await parseFloat(amountList[1].replace('ADA', '')); + const fiatAmount = await amountList[0].replace(currency, ''); + const adaAmount = await parseFloat(amountList[1].replace('ADA', '')); - const expectedValue = await parseFloat(((await adaAmount) * rate).toFixed(6)); - expect(fiatAmount).to.contain(`${expectedValue}`); + const expectedValue = await parseFloat(((await adaAmount) * rate).toFixed(6)); + expect(fiatAmount).to.contain(`${expectedValue}`); + } } ); diff --git a/packages/yoroi-extension/features/support/webdriver.js b/packages/yoroi-extension/features/support/webdriver.js index 94076cf7af..104503cd9b 100644 --- a/packages/yoroi-extension/features/support/webdriver.js +++ b/packages/yoroi-extension/features/support/webdriver.js @@ -278,6 +278,14 @@ function CustomWorld(cmdInput: WorldInput) { }, timeout); }; + this.scrollIntoView = async (locator: LocatorObject) => { + this.webDriverLogger.info(`Webdriver: Scroll into view "${JSON.stringify(locator)}"`); + await this.waitForElement(locator); + const clickable = await this.getElementBy(locator); + await this.driver.executeScript('arguments[0].scrollIntoView()', clickable); + }; + + this.click = async (locator: LocatorObject) => { this.webDriverLogger.info(`Webdriver: Clicking on "${JSON.stringify(locator)}"`); await this.waitForElement(locator); From 039a5f72b095b2ccc54d15c17178bbfbb71748d3 Mon Sep 17 00:00:00 2001 From: Denis Date: Mon, 8 Aug 2022 02:29:46 +0300 Subject: [PATCH 004/172] Improvements --- .../features/mock-chain/mockCardanoServer.js | 23 +++++++++---- .../features/pages/commonComponentsPage.js | 8 +++++ .../features/pages/walletTransactionsPage.js | 32 ++++++++++++++++++- .../features/step_definitions/common-steps.js | 2 ++ .../general-settings-steps.js | 6 ++-- .../step_definitions/tx-history-steps.js | 27 ++++++---------- 6 files changed, 71 insertions(+), 27 deletions(-) create mode 100644 packages/yoroi-extension/features/pages/commonComponentsPage.js diff --git a/packages/yoroi-extension/features/mock-chain/mockCardanoServer.js b/packages/yoroi-extension/features/mock-chain/mockCardanoServer.js index e04a1fc3ee..a53527c68c 100644 --- a/packages/yoroi-extension/features/mock-chain/mockCardanoServer.js +++ b/packages/yoroi-extension/features/mock-chain/mockCardanoServer.js @@ -31,10 +31,11 @@ import { installCoinPriceRequestHandlers } from './coinPriceRequestHandler'; import { Ports } from '../../scripts/connections'; import { getCircularReplacer, getLogDate } from '../support/helpers/helpers'; -import { testRunsDataDir } from '../support/helpers/common-constants'; +import { adaToFiatPrices, testRunsDataDir } from '../support/helpers/common-constants'; const simpleNodeLogger = require('simple-node-logger'); const fs = require('fs'); +const axios = require('axios'); // MockData should always be consistent with the following values const addressesLimit = 50; @@ -276,12 +277,20 @@ export function getMockServer(settings: { res.send(status); }); - server.get('/api/price/ADA/current', (req, res) => { - logger.info(`mockCardanoServer: /api/price/ADA/current -> request`); - const price = mockImporter.currentADAPrice; - logger.info(`mockCardanoServer: GET: /api/price/ADA/current`); - logger.info(JSON.stringify(price)); - res.send(price); + server.get('/api/price/:from/current', async (req, res) => { + logger.info(`mockCardanoServer: /api/price/${req.params.from}/current -> request`); + const cardanoResponsePrice = (await axios(adaToFiatPrices)).data; + logger.info(`mockCardanoServer: GET: /api/price/${req.params.from}/current <- response`); + logger.info(JSON.stringify(cardanoResponsePrice)); + res.send(cardanoResponsePrice); + }); + + server.get('/api/price/:from/:timestamps', async (req, res) => { + logger.info(`mockCardanoServer: /api/price/${req.params.from}/${req.params.timestamps} -> request`); + const cardanoResponsePrice = (await axios(adaToFiatPrices)).data; + logger.info(`mockCardanoServer: GET: /api/price/${req.params.from}/${req.params.timestamps} <- response`); + logger.info(JSON.stringify(cardanoResponsePrice)); + res.send(cardanoResponsePrice); }); // To test the dApp connector, we need a no-op mock dApp. diff --git a/packages/yoroi-extension/features/pages/commonComponentsPage.js b/packages/yoroi-extension/features/pages/commonComponentsPage.js new file mode 100644 index 0000000000..e4d9537524 --- /dev/null +++ b/packages/yoroi-extension/features/pages/commonComponentsPage.js @@ -0,0 +1,8 @@ +// @flow + +import type { LocatorObject } from '../support/webdriver'; + +export const loadingSpinnerWindow: LocatorObject = { + locator: '.MuiModal-root .LoadingSpinner_component', + method: 'css', +}; diff --git a/packages/yoroi-extension/features/pages/walletTransactionsPage.js b/packages/yoroi-extension/features/pages/walletTransactionsPage.js index 432894043a..d6d5c9f9c7 100644 --- a/packages/yoroi-extension/features/pages/walletTransactionsPage.js +++ b/packages/yoroi-extension/features/pages/walletTransactionsPage.js @@ -1,3 +1,33 @@ // @flow -export const walletSummaryBox = { locator: 'walletSummary_box', method: 'id' }; +import type { LocatorObject } from '../support/webdriver'; +import { getMethod } from '../support/helpers/helpers'; + +export const walletSummaryBox: LocatorObject = { locator: 'walletSummary_box', method: 'id' }; +export const txRowComponent: LocatorObject = { locator: '.Transaction_component', method: 'css' }; +export const txStatus: LocatorObject = { locator: 'txStatus', method: 'id' }; +export const txFee: LocatorObject = { locator: 'txFee', method: 'id' }; +export const txAmount: LocatorObject = { locator: 'transactionAmount', method: 'id' }; + +export const getLastTx = async (customWorld: any) => { + const allTxs = await customWorld.findElements(txRowComponent); + return allTxs[0]; +} + +export const getLastTxStatus = async (customWorld: any): Promise => { + const lastTx = await getLastTx(customWorld); + const statusElement = await lastTx.findElement(getMethod(txStatus.method)(txStatus.locator)); + return await statusElement.getText(); +} + +export const getLastTxFee = async (customWorld: any): Promise => { + const lastTx = await getLastTx(customWorld); + const feeElement = await lastTx.findElement(getMethod(txFee.method)(txFee.locator)); + return await feeElement.getText(); +} + +export const getLastTxAmount = async (customWorld: any): Promise => { + const lastTx = await getLastTx(customWorld); + const amountElement = await lastTx.findElement(getMethod(txAmount.method)(txAmount.locator)); + return await amountElement.getText(); +} \ No newline at end of file diff --git a/packages/yoroi-extension/features/step_definitions/common-steps.js b/packages/yoroi-extension/features/step_definitions/common-steps.js index 81017753bf..b9d77b0537 100644 --- a/packages/yoroi-extension/features/step_definitions/common-steps.js +++ b/packages/yoroi-extension/features/step_definitions/common-steps.js @@ -52,6 +52,7 @@ import { } from '../pages/newWalletPages'; import { allowPubKeysAndSwitchToYoroi, switchToTrezorAndAllow } from './trezor-steps'; import * as helpers from '../support/helpers/helpers'; +import { walletSummaryBox } from '../pages/walletTransactionsPage'; const { promisify } = require('util'); const fs = require('fs'); @@ -657,6 +658,7 @@ Then(/^Revamp. I go to the wallet ([^"]*)$/, async function (walletName) { const restoreInfo = testWallets[walletName]; const walletButtonInRow = await getWalletButtonByPlate(this, restoreInfo.plate); await walletButtonInRow.click(); + await this.waitForElement(walletSummaryBox); }); Then(/^I should see the dashboard screen$/, async function () { diff --git a/packages/yoroi-extension/features/step_definitions/general-settings-steps.js b/packages/yoroi-extension/features/step_definitions/general-settings-steps.js index 601bb38425..191f1e4f26 100644 --- a/packages/yoroi-extension/features/step_definitions/general-settings-steps.js +++ b/packages/yoroi-extension/features/step_definitions/general-settings-steps.js @@ -14,6 +14,7 @@ import { } from '../pages/generalSettingsPage'; import type { LocatorObject } from '../support/webdriver'; import { adaToFiatPrices } from '../support/helpers/common-constants'; +import { loadingSpinnerWindow } from '../pages/commonComponentsPage'; const axios = require('axios'); @@ -126,9 +127,10 @@ When( locator: `//*[starts-with(text(), "${currency}")]`, method: 'xpath', }; - + await this.waitForElement(currencySelector); await this.scrollIntoView(currencySelector); await this.click(currencySelector); + await this.waitForElementNotPresent(loadingSpinnerWindow) } ); @@ -141,7 +143,7 @@ Then( const value = await response.data.ticker.prices[currency]; const adaAmount = await this.getText(amountDisplayADA); - const adaValue = await parseFloat( + const adaValue = parseFloat( parseFloat(adaAmount.replace('\n', '').replace(' ADA', '')).toFixed(2) ); diff --git a/packages/yoroi-extension/features/step_definitions/tx-history-steps.js b/packages/yoroi-extension/features/step_definitions/tx-history-steps.js index 912908ff15..836b04162b 100644 --- a/packages/yoroi-extension/features/step_definitions/tx-history-steps.js +++ b/packages/yoroi-extension/features/step_definitions/tx-history-steps.js @@ -6,6 +6,7 @@ import chai, { expect } from 'chai'; import moment from 'moment'; import i18n from '../support/helpers/i18n-helpers'; import { adaToFiatPrices } from '../support/helpers/common-constants'; +import { getLastTxAmount } from '../pages/walletTransactionsPage'; const axios = require('axios'); @@ -256,25 +257,17 @@ When(/^I go to the tx history screen$/, async function () { Then( /^I validate the transaction amount to (USD|JPY|EUR|CNY|KRW|BTC|ETH|BRL) currency pairing$/, async function (currency) { - const allTxsAmountList = await this.getElementsBy({ - locator: 'transactionAmount', - method: 'id', - }); - - for (const txAmountElem of allTxsAmountList) { - const txAmount = await txAmountElem.getText(); - expect(txAmount).to.contain(currency); + const lastTxAmount = await getLastTxAmount(this); + expect(lastTxAmount).to.contain(currency); - const response = await axios(adaToFiatPrices); - const rate = await response.data.ticker.prices[currency]; + const response = await axios(adaToFiatPrices); + const rate = await response.data.ticker.prices[currency]; - const amountList = await txAmount.split('\n'); + const amountList = lastTxAmount.split('\n'); + const fiatAmount = amountList[0].replace(currency, ''); + const adaAmount = parseFloat(amountList[1].replace('ADA', '')); - const fiatAmount = await amountList[0].replace(currency, ''); - const adaAmount = await parseFloat(amountList[1].replace('ADA', '')); - - const expectedValue = await parseFloat(((await adaAmount) * rate).toFixed(6)); - expect(fiatAmount).to.contain(`${expectedValue}`); - } + const expectedValue = parseFloat((adaAmount * rate).toFixed(6)); + expect(fiatAmount).to.contain(`${expectedValue}`); } ); From c0e45229ff944f2e4f9a44689ed82c6b53b07999 Mon Sep 17 00:00:00 2001 From: Denis Date: Mon, 8 Aug 2022 13:19:07 +0300 Subject: [PATCH 005/172] Check all txs in the txs list --- .../features/pages/walletTransactionsPage.js | 5 +++++ .../yoroi-extension/features/settings.feature | 6 +++--- .../step_definitions/tx-history-steps.js | 21 +++++++++++-------- 3 files changed, 20 insertions(+), 12 deletions(-) diff --git a/packages/yoroi-extension/features/pages/walletTransactionsPage.js b/packages/yoroi-extension/features/pages/walletTransactionsPage.js index d6d5c9f9c7..734a006689 100644 --- a/packages/yoroi-extension/features/pages/walletTransactionsPage.js +++ b/packages/yoroi-extension/features/pages/walletTransactionsPage.js @@ -30,4 +30,9 @@ export const getLastTxAmount = async (customWorld: any): Promise => { const lastTx = await getLastTx(customWorld); const amountElement = await lastTx.findElement(getMethod(txAmount.method)(txAmount.locator)); return await amountElement.getText(); +} + +export const getTxAmount = async (txElement: any): Promise => { + const amountElement = await txElement.findElement(getMethod(txAmount.method)(txAmount.locator)); + return await amountElement.getText(); } \ No newline at end of file diff --git a/packages/yoroi-extension/features/settings.feature b/packages/yoroi-extension/features/settings.feature index 6127a92fa0..ccee1ff5bc 100644 --- a/packages/yoroi-extension/features/settings.feature +++ b/packages/yoroi-extension/features/settings.feature @@ -9,7 +9,7 @@ Feature: Wallet UI Settings Then I should see the "General Settings" page @currency-1 - Scenario Outline: Change currency pair + Scenario Outline: Change currency pair. ADA -> . @currency-1 When I select as fiat pairing currency Then I see the correct conversion value for on header @@ -25,7 +25,7 @@ Feature: Wallet UI Settings | BRL | @currency-2 - Scenario Outline: Change currency pair back to ADA + Scenario Outline: Change currency pair back to ADA. -> ADA. @currency-2 When I select as fiat pairing currency And I select ADA as fiat pairing currency Then I see only ADA value on header @@ -42,7 +42,7 @@ Feature: Wallet UI Settings | BRL | @currency-3 - Scenario Outline: Check wallet transactions pairings after changing currency + Scenario Outline: Check wallet transactions pairings after changing currency to . @currency-3 When I select as fiat pairing currency And Revamp. I go to the wallet shelley-simple-15 Then I validate the transaction amount to currency pairing diff --git a/packages/yoroi-extension/features/step_definitions/tx-history-steps.js b/packages/yoroi-extension/features/step_definitions/tx-history-steps.js index 836b04162b..82412b5ad6 100644 --- a/packages/yoroi-extension/features/step_definitions/tx-history-steps.js +++ b/packages/yoroi-extension/features/step_definitions/tx-history-steps.js @@ -6,7 +6,7 @@ import chai, { expect } from 'chai'; import moment from 'moment'; import i18n from '../support/helpers/i18n-helpers'; import { adaToFiatPrices } from '../support/helpers/common-constants'; -import { getLastTxAmount } from '../pages/walletTransactionsPage'; +import { getTxAmount, txRowComponent } from '../pages/walletTransactionsPage'; const axios = require('axios'); @@ -257,17 +257,20 @@ When(/^I go to the tx history screen$/, async function () { Then( /^I validate the transaction amount to (USD|JPY|EUR|CNY|KRW|BTC|ETH|BRL) currency pairing$/, async function (currency) { - const lastTxAmount = await getLastTxAmount(this); - expect(lastTxAmount).to.contain(currency); - const response = await axios(adaToFiatPrices); const rate = await response.data.ticker.prices[currency]; - const amountList = lastTxAmount.split('\n'); - const fiatAmount = amountList[0].replace(currency, ''); - const adaAmount = parseFloat(amountList[1].replace('ADA', '')); + const allTxsList = await this.findElements(txRowComponent); + for (const txListElement of allTxsList) { + const txAmount = await getTxAmount(txListElement); + expect(txAmount).to.contain(currency); + + const amountList = txAmount.split('\n'); + const fiatAmount = amountList[0].replace(currency, ''); + const adaAmount = parseFloat(amountList[1].replace('ADA', '')); - const expectedValue = parseFloat((adaAmount * rate).toFixed(6)); - expect(fiatAmount).to.contain(`${expectedValue}`); + const expectedValue = parseFloat((adaAmount * rate).toFixed(6)); + expect(fiatAmount).to.contain(`${expectedValue}`); + } } ); From 432e1b9f9d8dcd1dc3aa2ee39d49095710b826a7 Mon Sep 17 00:00:00 2001 From: Denis Date: Fri, 14 Oct 2022 16:32:22 +0300 Subject: [PATCH 006/172] added wrappers for the regular logger --- .../features/mock-chain/mockCardanoServer.js | 41 +++++++++++++++++++ 1 file changed, 41 insertions(+) diff --git a/packages/yoroi-extension/features/mock-chain/mockCardanoServer.js b/packages/yoroi-extension/features/mock-chain/mockCardanoServer.js index 662409c47b..bf12321f3c 100644 --- a/packages/yoroi-extension/features/mock-chain/mockCardanoServer.js +++ b/packages/yoroi-extension/features/mock-chain/mockCardanoServer.js @@ -79,6 +79,47 @@ export function setExpectedTx(signedTx: void | string): void { // TODO: no type from json-server let MockServer: null | any = null; +class MethodLogger { + constructor(localLogger: LocalLogger, method: string, url: string) { + this.localLogger = localLogger; + this.method = method; + this.url = url; + } + + logRequest = (message?: string) => { + this.localLogger + .logInfo(`${this.method}: ${this.url} <- request${message? `\n ${message}`: ''}`, false); + }; + + logResponseSuccess = (message?: string) => { + this.localLogger + .logInfo(`${this.method}: ${this.url} -> response${message? `\n ${message}`: ''}`, false); + }; + + logResponseError = (errorMessage: string) => { + this.localLogger.logError(`${this.method}: ${this.url} ->\n Error:\n${errorMessage}`, false); + }; +} + +class LocalLogger { + constructor(fileName: string, logPath) { + this.fileName = fileName; + this.logger = simpleNodeLogger.createSimpleFileLogger(logPath); + } + + getMethodLogger = (method: string, url: string) => { + return new MethodLogger(this, method, url); + } + + logInfo = (message: string, spaceBefore: boolean = true) => { + this.logger.info(`${this.fileName}:${spaceBefore? ' ' : ''}${message}`); + }; + + logError = (message: string, spaceAfter: boolean = true) => { + this.logger.error(`${this.fileName}:${spaceAfter? ' ' : ''}${message}`); + }; +} + export function getMockServer(settings: { signedTransaction?: ( req: { body: SignedRequestInternal, ... }, From d2623305d164fa6efa8b583fa4460e5f0a7c0bc4 Mon Sep 17 00:00:00 2001 From: Denis Date: Fri, 14 Oct 2022 16:32:57 +0300 Subject: [PATCH 007/172] using new loggers --- .../features/mock-chain/mockCardanoServer.js | 191 +++++++++--------- 1 file changed, 101 insertions(+), 90 deletions(-) diff --git a/packages/yoroi-extension/features/mock-chain/mockCardanoServer.js b/packages/yoroi-extension/features/mock-chain/mockCardanoServer.js index bf12321f3c..873dbae669 100644 --- a/packages/yoroi-extension/features/mock-chain/mockCardanoServer.js +++ b/packages/yoroi-extension/features/mock-chain/mockCardanoServer.js @@ -40,12 +40,14 @@ const fs = require('fs'); const addressesLimit = 50; const txsLimit = 20; -let logger; - -function _validateAddressesReq({ addresses }: { addresses: Array, ... } = {}): boolean { - logger.info(`mockCardanoServer: Validate Addresses request`); +function _validateAddressesReq( + { addresses }: { addresses: Array, ... } = {}, + localLogger: LocalLogger) + : boolean { + localLogger.logInfo(`Validate Addresses request`); if (!addresses || addresses.length > addressesLimit || addresses.length === 0) { - throw new Error('Addresses request length should be (0, ' + addressesLimit + ']'); + localLogger.logError(`Addresses request length should be (0, ${addressesLimit})`); + throw new Error(`Addresses request length should be (0, ${addressesLimit})`); } // TODO: Add address validation return true; @@ -53,21 +55,19 @@ function _validateAddressesReq({ addresses }: { addresses: Array, ... } function _defaultSignedTransaction( req: { body: SignedRequestInternal, ... }, - res: { send(arg: SignedResponse): any, ... } + res: { send(arg: SignedResponse): any, ... }, + localLogger: LocalLogger ): void { - logger.info(`mockCardanoServer: Default Signed Transaction`); - logger.info(`mockCardanoServer: mockImporter.sendTx -> request`); - logger.info(JSON.stringify(req.body)); + localLogger.logInfo(`Default Signed Transaction`); + localLogger.logInfo(`mockImporter.sendTx <- request\n ${JSON.stringify(req.body)}`); const response = mockImporter.sendTx(req.body); - logger.info(`mockCardanoServer: mockImporter.sendTx -> response`); - logger.info(JSON.stringify(response)); + localLogger.logInfo(`mockImporter.sendTx -> response\n ${JSON.stringify(response)}`); res.send(response); } const expectedTxBase64 = []; export function setExpectedTx(signedTx: void | string): void { - logger.info(`mockCardanoServer: Set expected transaction`); if (signedTx == null) { // remove all elements from the array expectedTxBase64.splice(0, expectedTxBase64.length); @@ -137,14 +137,14 @@ export function getMockServer(settings: { if (!fs.existsSync(dir)) { fs.mkdirSync(dir, { recursive: true }); } - const loggerPath = `${dir}/cardanoMockServerLog_${getLogDate()}.log`; + const logPath = `${dir}/cardanoMockServerLog_${getLogDate()}.log`; + const localLogger = new LocalLogger('mockCardanoServer', logPath); - logger = simpleNodeLogger.createSimpleFileLogger(loggerPath); if (!MockServer) { const middlewares = [...defaults({ logger: !!settings.outputLog }), bodyParser]; const server = create(); - logger.info(`mockCardanoServer: JSON Server Created`); + localLogger.logInfo(`JSON Server Created`); server.use(middlewares); @@ -154,12 +154,11 @@ export function getMockServer(settings: { req: { body: AddressUtxoRequest, ... }, res: { send(arg: AddressUtxoResponse): any, ... } ): Promise => { - chai.assert.isTrue(_validateAddressesReq(req.body)); - logger.info(`mockCardanoServer: /api/txs/utxoForAddresses -> request`); - logger.info(JSON.stringify(req.body)); + const methodLogger = localLogger.getMethodLogger('POST', '/api/txs/utxoForAddresses'); + chai.assert.isTrue(_validateAddressesReq(req.body, localLogger)); + methodLogger.logRequest(JSON.stringify(req.body)); const utxoForAddresses = await mockImporter.utxoForAddresses(req.body); - logger.info(`mockCardanoServer: /api/txs/utxoForAddresses -> response`); - logger.info(JSON.stringify(utxoForAddresses)); + methodLogger.logResponseSuccess(JSON.stringify(utxoForAddresses)); res.send(utxoForAddresses); } ); @@ -170,12 +169,11 @@ export function getMockServer(settings: { req: { body: UtxoSumRequest, ... }, res: { send(arg: UtxoSumResponse): any, ... } ): Promise => { - chai.assert.isTrue(_validateAddressesReq(req.body)); - logger.info(`mockCardanoServer: /api/txs/utxoSumForAddresses -> request`); - logger.info(JSON.stringify(req.body)); + const methodLogger = localLogger.getMethodLogger('POST', '/api/txs/utxoSumForAddresses'); + chai.assert.isTrue(_validateAddressesReq(req.body, localLogger)); + methodLogger.logRequest(JSON.stringify(req.body)); const utxoSumForAddresses = await mockImporter.utxoSumForAddresses(req.body); - logger.info(`mockCardanoServer: /api/txs/utxoSumForAddresses -> response`); - logger.info(JSON.stringify(utxoSumForAddresses)); + methodLogger.logResponseSuccess(JSON.stringify(utxoSumForAddresses)); res.send(utxoSumForAddresses); } ); @@ -186,13 +184,11 @@ export function getMockServer(settings: { req: { body: HistoryRequest, ... }, res: { send(arg: HistoryResponse): any, ... } ): Promise => { - chai.assert.isTrue(_validateAddressesReq(req.body)); - logger.info(`mockCardanoServer: /api/v2/txs/history -> request`); - logger.info(JSON.stringify(req.body)); - + const methodLogger = localLogger.getMethodLogger('POST', '/api/v2/txs/history'); + chai.assert.isTrue(_validateAddressesReq(req.body, localLogger)); + methodLogger.logRequest(JSON.stringify(req.body)); const history = await mockImporter.history(req.body); - logger.info(`mockCardanoServer: /api/v2/txs/history -> response`); - logger.info(JSON.stringify(history)); + methodLogger.logResponseSuccess(JSON.stringify(history)); // Returns a chunk of txs res.send(history.slice(0, txsLimit)); } @@ -204,11 +200,10 @@ export function getMockServer(settings: { req: { body: BestBlockRequest, ... }, res: { send(arg: BestBlockResponse): any, ... } ): Promise => { - logger.info(`mockCardanoServer: /api/v2/getblock-> request`); - logger.info(JSON.stringify(req.body)); + const methodLogger = localLogger.getMethodLogger('POST', '/api/v2/bestblock'); + methodLogger.logRequest(JSON.stringify(req.body)); const bestBlock = await mockImporter.getBestBlock(req.body); - logger.info(`mockCardanoServer: /api/v2/getblock -> response`); - logger.info(JSON.stringify(bestBlock)); + methodLogger.logResponseSuccess(JSON.stringify(bestBlock)); res.send(bestBlock); } ); @@ -223,26 +218,25 @@ export function getMockServer(settings: { ... } ): void => { - logger.info(`mockCardanoServer: /api/txs/signed-> request`); + const methodLogger = localLogger.getMethodLogger('POST', '/api/txs/signed'); // note: don't use this in practice because ttl makes the tx hash computer-time-sensitive if (expectedTxBase64.length !== 0 && expectedTxBase64[0] !== req.body.signedTx) { - logger.error( - `mockCardanoServer: Wrong transaction payload. Expected ${expectedTxBase64[0]} and found ${req.body.signedTx}` - ); - /*throw new Error( + localLogger.logError( `Wrong transaction payload. Expected ${expectedTxBase64[0]} and found ${req.body.signedTx}` - );*/ + ); + // throw new Error( + // `Wrong transaction payload. Expected ${expectedTxBase64[0]} and found ${req.body.signedTx}` + // ); } - logger.info(JSON.stringify(req.body)); + methodLogger.logRequest(JSON.stringify(req.body)); if (settings.signedTransaction) { settings.signedTransaction(req, res); } else { - _defaultSignedTransaction(req, res); + _defaultSignedTransaction(req, res, localLogger); } - logger.info(`mockCardanoServer: /api/txs/signed-> response`); - logger.info(JSON.stringify(res, getCircularReplacer())); + methodLogger.logResponseSuccess(JSON.stringify(res, getCircularReplacer())); } ); @@ -252,12 +246,11 @@ export function getMockServer(settings: { req: { body: PoolInfoRequest, ... }, res: { send(arg: PoolInfoResponse): any, ... } ): Promise => { - logger.info(`mockCardanoServer: /api/pool/info -> request`); - logger.info(JSON.stringify(req.body)); + const methodLogger = localLogger.getMethodLogger('POST', '/api/pool/info'); + methodLogger.logRequest(JSON.stringify(req.body)); const poolsInfo = await mockImporter.getPoolInfo(req.body); - logger.info(`mockCardanoServer: /api/pool/info -> response`); - logger.info(JSON.stringify(poolsInfo)); + methodLogger.logResponseSuccess(JSON.stringify(poolsInfo)); res.send(poolsInfo); } ); @@ -268,12 +261,11 @@ export function getMockServer(settings: { req: { body: RewardHistoryRequest, ... }, res: { send(arg: RewardHistoryResponse): any, ... } ): Promise => { - logger.info(`mockCardanoServer: /api/account/rewardHistory -> request`); - logger.info(JSON.stringify(req.body)); + const methodLogger = localLogger.getMethodLogger('POST', '/api/account/rewardHistory'); + methodLogger.logRequest(JSON.stringify(req.body)); const poolsInfo = await mockImporter.getRewardHistory(req.body); - logger.info(`mockCardanoServer: /api/account/rewardHistory -> response`); - logger.info(JSON.stringify(poolsInfo)); + methodLogger.logResponseSuccess(JSON.stringify(poolsInfo)); res.send(poolsInfo); } ); @@ -284,13 +276,12 @@ export function getMockServer(settings: { req: { body: AccountStateRequest, ... }, res: { send(arg: AccountStateResponse): any, ... } ): Promise => { - chai.assert.isTrue(_validateAddressesReq(req.body)); - logger.info(`mockCardanoServer: /api/account/state -> request`); - logger.info(JSON.stringify(req.body)); + const methodLogger = localLogger.getMethodLogger('POST', '/api/account/rewardHistory'); + chai.assert.isTrue(_validateAddressesReq(req.body, localLogger)); + methodLogger.logRequest(JSON.stringify(req.body)); const accountState = await mockImporter.getAccountState(req.body); - logger.info(`mockCardanoServer: /api/account/state -> response`); - logger.info(JSON.stringify(accountState)); + methodLogger.logResponseSuccess(JSON.stringify(accountState)); res.send(accountState); } ); @@ -301,27 +292,30 @@ export function getMockServer(settings: { req: { body: FilterUsedRequest, ... }, res: { send(arg: FilterUsedResponse): any, ... } ): Promise => { - logger.info(`mockCardanoServer: /api/v2/addresses/filterUsed -> request`); - logger.info(JSON.stringify(req.body)); + const methodLogger = localLogger.getMethodLogger('POST', '/api/v2/addresses/filterUsed'); + methodLogger.logRequest(JSON.stringify(req.body)); const response = await mockImporter.usedAddresses(req.body); - logger.info(`mockCardanoServer: /api/v2/addresses/filterUsed -> response`); - logger.info(JSON.stringify(response)); + methodLogger.logResponseSuccess(JSON.stringify(response)); res.send(response); } ); server.get('/api/status', (req, res: { send(arg: ServerStatusResponse): any, ... }): void => { + const methodLogger = localLogger.getMethodLogger('GET', '/api/status'); + methodLogger.logRequest(); const status = mockImporter.getApiStatus(); - logger.info(`mockCardanoServer: GET: /api/status`); - logger.info(JSON.stringify(status)); + methodLogger.logResponseSuccess(JSON.stringify(status)); res.send(status); }); // To test the dApp connector, we need a no-op mock dApp. server.get('/mock-dapp', (req, res: { send(arg: ServerStatusResponse): any, ... }): void => { + const methodLogger = localLogger.getMethodLogger('GET', '/mock-dapp'); + methodLogger.logRequest(); // $FlowFixMe[prop-missing] res.header('content-type', 'text/html'); + methodLogger.logResponseSuccess(); // $FlowFixMe[incompatible-call] res.send(` @@ -336,86 +330,103 @@ export function getMockServer(settings: { }); server.get('/api/txs/io/:txHash/o/:txIndex', (req, res) => { - logger.info(`mockCardanoServer: /api/txs/io/:txHash/o/:txIndex -> request`); - logger.info(JSON.stringify(req.body)); + const methodLogger = localLogger.getMethodLogger('GET', '/api/txs/io/:txHash/o/:txIndex'); + methodLogger.logRequest(JSON.stringify(req.body)); const result = mockImporter.getUtxoData(req.params.txHash, Number(req.params.txIndex)); - logger.info(`mockCardanoServer: /api/txs/io/:txHash/o/:txIndex -> response`); - logger.info(JSON.stringify(result)); if (result) { res.send(result); + methodLogger.logResponseSuccess(JSON.stringify(result)); return; } + methodLogger.logResponseError(`404 Transaction not found`) res.status(404); res.send('Transaction not found'); }); server.get('/api/v2/tipStatus', async (req, res) => { + const methodLogger = localLogger.getMethodLogger('GET', '/api/v2/tipStatus'); + methodLogger.logRequest(); const bestBlockHash = await mockImporter.mockUtxoApi.getBestBlock(); const safeBlockHash = await mockImporter.mockUtxoApi.getSafeBlock(); - res.send({ + const response = { safeBlocK: { hash: safeBlockHash }, bestBlock: { hash: bestBlockHash }, - }); + }; + methodLogger.logResponseSuccess(JSON.stringify(response)); + res.send(response); }); server.post('/api/v2/tipStatus', async (req, res) => { + const methodLogger = localLogger.getMethodLogger('POST', '/api/v2/tipStatus'); + methodLogger.logRequest(JSON.stringify(req.body)); const { bestBlocks } = req.body.reference; const tipStatus = await mockImporter.mockUtxoApi.getTipStatusWithReference( bestBlocks ); if (tipStatus.result !== 'SUCCESS') { + methodLogger.logResponseError('500 REFERENCE_POINT_BLOCK_NOT_FOUND'); res.status(500); res.send({ error: { response: 'REFERENCE_POINT_BLOCK_NOT_FOUND' } }); } else { const value = tipStatus.value; if (!value) { - throw new Error('unpected null value'); + methodLogger.logResponseError('unexpected null value'); + throw new Error('unexpected null value'); } const bestBlockHash = await mockImporter.mockUtxoApi.getBestBlock(); const safeBlockHash = await mockImporter.mockUtxoApi.getSafeBlock(); - res.send({ + const response = { safeBlock: safeBlockHash, bestBlock: bestBlockHash, reference: value.reference, - }); + }; + methodLogger.logResponseSuccess(JSON.stringify(response)); + res.send(response); } }); server.post('/api/v2/txs/utxoAtPoint', async (req, res) => { + const methodLogger = localLogger.getMethodLogger('POST', '/api/v2/txs/utxoAtPoint'); + methodLogger.logRequest(JSON.stringify(req.body)); const { addresses, referenceBlockHash } = req.body; const { value } = await mockImporter.mockUtxoApi.getUtxoAtPoint( { addresses, referenceBlockHash } ); if (!value) { - throw new Error('unpected null value'); + methodLogger.logResponseError('unexpected null value'); + throw new Error('unexpected null value'); } - res.send( - value.map(v => ( - { - utxo_id: v.utxoId, - tx_hash: v.txHash, - tx_index: v.txIndex, - block_num: v.blockNum, - receiver: v.receiver, - amount: v.amount, - assets: v.assets, - } - )) - ); + const response = value.map(v => ( + { + utxo_id: v.utxoId, + tx_hash: v.txHash, + tx_index: v.txIndex, + block_num: v.blockNum, + receiver: v.receiver, + amount: v.amount, + assets: v.assets, + } + )); + methodLogger.logResponseSuccess(JSON.stringify(response)); + res.send(response); }); server.post('/api/v2/txs/utxoDiffSincePoint', async (req, res) => { + const methodLogger = localLogger.getMethodLogger('POST', '/api/v2/txs/utxoDiffSincePoint'); + methodLogger.logRequest(req.body); const { addresses, untilBlockHash, afterBestBlock } = req.body; const { result, value } = await mockImporter.mockUtxoApi.getUtxoDiffSincePoint( { addresses, untilBlockHash, afterBestBlock } ); if (result !== 'SUCCESS') { + methodLogger.logResponseError('500 REFERENCE_POINT_BLOCK_NOT_FOUND'); res.status(500); res.send({ error: { response: 'REFERENCE_POINT_BLOCK_NOT_FOUND' } }); } else { if (!value) { - throw new Error('unpected null value'); + methodLogger.logResponseError('unexpected null value'); + throw new Error('unexpected null value'); } // casting `value` to `any` is the only way to pass flow check const diffItems = (value: any).diffItems.map(item => { @@ -433,6 +444,7 @@ export function getMockServer(settings: { tx_index: item.utxo.txIndex, }; }); + methodLogger.logResponseSuccess({ diffItems }); res.send({ diffItems }); } }); @@ -442,7 +454,7 @@ export function getMockServer(settings: { MockServer = server.listen(Ports.DevBackendServe, () => { // eslint-disable-next-line no-console console.log(`JSON Server is running at ${Ports.DevBackendServe}`); - logger.info(`mockCardanoServer: JSON Server is running at ${Ports.DevBackendServe}`); + localLogger.logInfo(`JSON Server is running at ${Ports.DevBackendServe}`); }); } return MockServer; @@ -452,6 +464,5 @@ export function closeMockServer() { if (MockServer) { MockServer.close(); MockServer = null; - logger.info(`mockCardanoServer: JSON Server closed`); } } From 2a5fc14a74315f0450efa7c4e3c731129b63641f Mon Sep 17 00:00:00 2001 From: Denis Date: Fri, 14 Oct 2022 16:37:00 +0300 Subject: [PATCH 008/172] prettified --- .../features/mock-chain/mockCardanoServer.js | 63 ++++++++++--------- 1 file changed, 33 insertions(+), 30 deletions(-) diff --git a/packages/yoroi-extension/features/mock-chain/mockCardanoServer.js b/packages/yoroi-extension/features/mock-chain/mockCardanoServer.js index 873dbae669..f1fb953444 100644 --- a/packages/yoroi-extension/features/mock-chain/mockCardanoServer.js +++ b/packages/yoroi-extension/features/mock-chain/mockCardanoServer.js @@ -42,8 +42,8 @@ const txsLimit = 20; function _validateAddressesReq( { addresses }: { addresses: Array, ... } = {}, - localLogger: LocalLogger) - : boolean { + localLogger: LocalLogger +): boolean { localLogger.logInfo(`Validate Addresses request`); if (!addresses || addresses.length > addressesLimit || addresses.length === 0) { localLogger.logError(`Addresses request length should be (0, ${addressesLimit})`); @@ -87,13 +87,17 @@ class MethodLogger { } logRequest = (message?: string) => { - this.localLogger - .logInfo(`${this.method}: ${this.url} <- request${message? `\n ${message}`: ''}`, false); + this.localLogger.logInfo( + `${this.method}: ${this.url} <- request${message ? `\n ${message}` : ''}`, + false + ); }; logResponseSuccess = (message?: string) => { - this.localLogger - .logInfo(`${this.method}: ${this.url} -> response${message? `\n ${message}`: ''}`, false); + this.localLogger.logInfo( + `${this.method}: ${this.url} -> response${message ? `\n ${message}` : ''}`, + false + ); }; logResponseError = (errorMessage: string) => { @@ -109,14 +113,14 @@ class LocalLogger { getMethodLogger = (method: string, url: string) => { return new MethodLogger(this, method, url); - } + }; logInfo = (message: string, spaceBefore: boolean = true) => { - this.logger.info(`${this.fileName}:${spaceBefore? ' ' : ''}${message}`); + this.logger.info(`${this.fileName}:${spaceBefore ? ' ' : ''}${message}`); }; logError = (message: string, spaceAfter: boolean = true) => { - this.logger.error(`${this.fileName}:${spaceAfter? ' ' : ''}${message}`); + this.logger.error(`${this.fileName}:${spaceAfter ? ' ' : ''}${message}`); }; } @@ -339,7 +343,7 @@ export function getMockServer(settings: { methodLogger.logResponseSuccess(JSON.stringify(result)); return; } - methodLogger.logResponseError(`404 Transaction not found`) + methodLogger.logResponseError(`404 Transaction not found`); res.status(404); res.send('Transaction not found'); }); @@ -361,9 +365,7 @@ export function getMockServer(settings: { const methodLogger = localLogger.getMethodLogger('POST', '/api/v2/tipStatus'); methodLogger.logRequest(JSON.stringify(req.body)); const { bestBlocks } = req.body.reference; - const tipStatus = await mockImporter.mockUtxoApi.getTipStatusWithReference( - bestBlocks - ); + const tipStatus = await mockImporter.mockUtxoApi.getTipStatusWithReference(bestBlocks); if (tipStatus.result !== 'SUCCESS') { methodLogger.logResponseError('500 REFERENCE_POINT_BLOCK_NOT_FOUND'); res.status(500); @@ -390,24 +392,23 @@ export function getMockServer(settings: { const methodLogger = localLogger.getMethodLogger('POST', '/api/v2/txs/utxoAtPoint'); methodLogger.logRequest(JSON.stringify(req.body)); const { addresses, referenceBlockHash } = req.body; - const { value } = await mockImporter.mockUtxoApi.getUtxoAtPoint( - { addresses, referenceBlockHash } - ); + const { value } = await mockImporter.mockUtxoApi.getUtxoAtPoint({ + addresses, + referenceBlockHash, + }); if (!value) { methodLogger.logResponseError('unexpected null value'); throw new Error('unexpected null value'); } - const response = value.map(v => ( - { - utxo_id: v.utxoId, - tx_hash: v.txHash, - tx_index: v.txIndex, - block_num: v.blockNum, - receiver: v.receiver, - amount: v.amount, - assets: v.assets, - } - )); + const response = value.map(v => ({ + utxo_id: v.utxoId, + tx_hash: v.txHash, + tx_index: v.txIndex, + block_num: v.blockNum, + receiver: v.receiver, + amount: v.amount, + assets: v.assets, + })); methodLogger.logResponseSuccess(JSON.stringify(response)); res.send(response); }); @@ -416,9 +417,11 @@ export function getMockServer(settings: { const methodLogger = localLogger.getMethodLogger('POST', '/api/v2/txs/utxoDiffSincePoint'); methodLogger.logRequest(req.body); const { addresses, untilBlockHash, afterBestBlock } = req.body; - const { result, value } = await mockImporter.mockUtxoApi.getUtxoDiffSincePoint( - { addresses, untilBlockHash, afterBestBlock } - ); + const { result, value } = await mockImporter.mockUtxoApi.getUtxoDiffSincePoint({ + addresses, + untilBlockHash, + afterBestBlock, + }); if (result !== 'SUCCESS') { methodLogger.logResponseError('500 REFERENCE_POINT_BLOCK_NOT_FOUND'); res.status(500); From 84b09c3f0d66c52ba71d9458ed5e858e9b6b47a9 Mon Sep 17 00:00:00 2001 From: Ahmed Ibrahim Date: Mon, 17 Oct 2022 13:16:51 +0200 Subject: [PATCH 009/172] Rename the connector package --- .../.gitignore | 0 .../README.md | 0 .../build.js | 0 .../example-cardano/bootstrap.js | 0 .../example-cardano/coreUtils.js | 0 .../example-cardano/favicon.ico | Bin .../example-cardano/index.html | 0 .../example-cardano/index.js | 0 .../example-cardano/package-lock.json | 0 .../example-cardano/package.json | 0 .../example-cardano/subpage.html | 0 .../example-cardano/utils.js | 0 .../example-cardano/webpack.config.js | 0 .../example-ergo/bootstrap.js | 0 .../example-ergo/favicon.ico | Bin .../example-ergo/index.html | 0 .../example-ergo/index.js | 0 .../example-ergo/package-lock.json | 0 .../example-ergo/package.json | 0 .../example-ergo/webpack.config.js | 0 .../img/favicon_erg-nightly.svg | 0 .../img/favicon_erg.svg | 0 .../img/icon-128.png | Bin .../img/icon-16.png | Bin .../img/icon-48.png | Bin .../img/nightly-128.png | Bin .../img/nightly-16.png | Bin .../img/nightly-48.png | Bin .../manifest/manifest.template.js | 0 .../package-lock.json | 0 .../package.json | 0 .../src/background.js | 0 .../src/inject.js | 0 33 files changed, 0 insertions(+), 0 deletions(-) rename packages/{yoroi-ergo-connector => yoroi-connector}/.gitignore (100%) rename packages/{yoroi-ergo-connector => yoroi-connector}/README.md (100%) rename packages/{yoroi-ergo-connector => yoroi-connector}/build.js (100%) rename packages/{yoroi-ergo-connector => yoroi-connector}/example-cardano/bootstrap.js (100%) rename packages/{yoroi-ergo-connector => yoroi-connector}/example-cardano/coreUtils.js (100%) rename packages/{yoroi-ergo-connector => yoroi-connector}/example-cardano/favicon.ico (100%) rename packages/{yoroi-ergo-connector => yoroi-connector}/example-cardano/index.html (100%) rename packages/{yoroi-ergo-connector => yoroi-connector}/example-cardano/index.js (100%) rename packages/{yoroi-ergo-connector => yoroi-connector}/example-cardano/package-lock.json (100%) rename packages/{yoroi-ergo-connector => yoroi-connector}/example-cardano/package.json (100%) rename packages/{yoroi-ergo-connector => yoroi-connector}/example-cardano/subpage.html (100%) rename packages/{yoroi-ergo-connector => yoroi-connector}/example-cardano/utils.js (100%) rename packages/{yoroi-ergo-connector => yoroi-connector}/example-cardano/webpack.config.js (100%) rename packages/{yoroi-ergo-connector => yoroi-connector}/example-ergo/bootstrap.js (100%) rename packages/{yoroi-ergo-connector => yoroi-connector}/example-ergo/favicon.ico (100%) rename packages/{yoroi-ergo-connector => yoroi-connector}/example-ergo/index.html (100%) rename packages/{yoroi-ergo-connector => yoroi-connector}/example-ergo/index.js (100%) rename packages/{yoroi-ergo-connector => yoroi-connector}/example-ergo/package-lock.json (100%) rename packages/{yoroi-ergo-connector => yoroi-connector}/example-ergo/package.json (100%) rename packages/{yoroi-ergo-connector => yoroi-connector}/example-ergo/webpack.config.js (100%) rename packages/{yoroi-ergo-connector => yoroi-connector}/img/favicon_erg-nightly.svg (100%) rename packages/{yoroi-ergo-connector => yoroi-connector}/img/favicon_erg.svg (100%) rename packages/{yoroi-ergo-connector => yoroi-connector}/img/icon-128.png (100%) rename packages/{yoroi-ergo-connector => yoroi-connector}/img/icon-16.png (100%) rename packages/{yoroi-ergo-connector => yoroi-connector}/img/icon-48.png (100%) rename packages/{yoroi-ergo-connector => yoroi-connector}/img/nightly-128.png (100%) rename packages/{yoroi-ergo-connector => yoroi-connector}/img/nightly-16.png (100%) rename packages/{yoroi-ergo-connector => yoroi-connector}/img/nightly-48.png (100%) rename packages/{yoroi-ergo-connector => yoroi-connector}/manifest/manifest.template.js (100%) rename packages/{yoroi-ergo-connector => yoroi-connector}/package-lock.json (100%) rename packages/{yoroi-ergo-connector => yoroi-connector}/package.json (100%) rename packages/{yoroi-ergo-connector => yoroi-connector}/src/background.js (100%) rename packages/{yoroi-ergo-connector => yoroi-connector}/src/inject.js (100%) diff --git a/packages/yoroi-ergo-connector/.gitignore b/packages/yoroi-connector/.gitignore similarity index 100% rename from packages/yoroi-ergo-connector/.gitignore rename to packages/yoroi-connector/.gitignore diff --git a/packages/yoroi-ergo-connector/README.md b/packages/yoroi-connector/README.md similarity index 100% rename from packages/yoroi-ergo-connector/README.md rename to packages/yoroi-connector/README.md diff --git a/packages/yoroi-ergo-connector/build.js b/packages/yoroi-connector/build.js similarity index 100% rename from packages/yoroi-ergo-connector/build.js rename to packages/yoroi-connector/build.js diff --git a/packages/yoroi-ergo-connector/example-cardano/bootstrap.js b/packages/yoroi-connector/example-cardano/bootstrap.js similarity index 100% rename from packages/yoroi-ergo-connector/example-cardano/bootstrap.js rename to packages/yoroi-connector/example-cardano/bootstrap.js diff --git a/packages/yoroi-ergo-connector/example-cardano/coreUtils.js b/packages/yoroi-connector/example-cardano/coreUtils.js similarity index 100% rename from packages/yoroi-ergo-connector/example-cardano/coreUtils.js rename to packages/yoroi-connector/example-cardano/coreUtils.js diff --git a/packages/yoroi-ergo-connector/example-cardano/favicon.ico b/packages/yoroi-connector/example-cardano/favicon.ico similarity index 100% rename from packages/yoroi-ergo-connector/example-cardano/favicon.ico rename to packages/yoroi-connector/example-cardano/favicon.ico diff --git a/packages/yoroi-ergo-connector/example-cardano/index.html b/packages/yoroi-connector/example-cardano/index.html similarity index 100% rename from packages/yoroi-ergo-connector/example-cardano/index.html rename to packages/yoroi-connector/example-cardano/index.html diff --git a/packages/yoroi-ergo-connector/example-cardano/index.js b/packages/yoroi-connector/example-cardano/index.js similarity index 100% rename from packages/yoroi-ergo-connector/example-cardano/index.js rename to packages/yoroi-connector/example-cardano/index.js diff --git a/packages/yoroi-ergo-connector/example-cardano/package-lock.json b/packages/yoroi-connector/example-cardano/package-lock.json similarity index 100% rename from packages/yoroi-ergo-connector/example-cardano/package-lock.json rename to packages/yoroi-connector/example-cardano/package-lock.json diff --git a/packages/yoroi-ergo-connector/example-cardano/package.json b/packages/yoroi-connector/example-cardano/package.json similarity index 100% rename from packages/yoroi-ergo-connector/example-cardano/package.json rename to packages/yoroi-connector/example-cardano/package.json diff --git a/packages/yoroi-ergo-connector/example-cardano/subpage.html b/packages/yoroi-connector/example-cardano/subpage.html similarity index 100% rename from packages/yoroi-ergo-connector/example-cardano/subpage.html rename to packages/yoroi-connector/example-cardano/subpage.html diff --git a/packages/yoroi-ergo-connector/example-cardano/utils.js b/packages/yoroi-connector/example-cardano/utils.js similarity index 100% rename from packages/yoroi-ergo-connector/example-cardano/utils.js rename to packages/yoroi-connector/example-cardano/utils.js diff --git a/packages/yoroi-ergo-connector/example-cardano/webpack.config.js b/packages/yoroi-connector/example-cardano/webpack.config.js similarity index 100% rename from packages/yoroi-ergo-connector/example-cardano/webpack.config.js rename to packages/yoroi-connector/example-cardano/webpack.config.js diff --git a/packages/yoroi-ergo-connector/example-ergo/bootstrap.js b/packages/yoroi-connector/example-ergo/bootstrap.js similarity index 100% rename from packages/yoroi-ergo-connector/example-ergo/bootstrap.js rename to packages/yoroi-connector/example-ergo/bootstrap.js diff --git a/packages/yoroi-ergo-connector/example-ergo/favicon.ico b/packages/yoroi-connector/example-ergo/favicon.ico similarity index 100% rename from packages/yoroi-ergo-connector/example-ergo/favicon.ico rename to packages/yoroi-connector/example-ergo/favicon.ico diff --git a/packages/yoroi-ergo-connector/example-ergo/index.html b/packages/yoroi-connector/example-ergo/index.html similarity index 100% rename from packages/yoroi-ergo-connector/example-ergo/index.html rename to packages/yoroi-connector/example-ergo/index.html diff --git a/packages/yoroi-ergo-connector/example-ergo/index.js b/packages/yoroi-connector/example-ergo/index.js similarity index 100% rename from packages/yoroi-ergo-connector/example-ergo/index.js rename to packages/yoroi-connector/example-ergo/index.js diff --git a/packages/yoroi-ergo-connector/example-ergo/package-lock.json b/packages/yoroi-connector/example-ergo/package-lock.json similarity index 100% rename from packages/yoroi-ergo-connector/example-ergo/package-lock.json rename to packages/yoroi-connector/example-ergo/package-lock.json diff --git a/packages/yoroi-ergo-connector/example-ergo/package.json b/packages/yoroi-connector/example-ergo/package.json similarity index 100% rename from packages/yoroi-ergo-connector/example-ergo/package.json rename to packages/yoroi-connector/example-ergo/package.json diff --git a/packages/yoroi-ergo-connector/example-ergo/webpack.config.js b/packages/yoroi-connector/example-ergo/webpack.config.js similarity index 100% rename from packages/yoroi-ergo-connector/example-ergo/webpack.config.js rename to packages/yoroi-connector/example-ergo/webpack.config.js diff --git a/packages/yoroi-ergo-connector/img/favicon_erg-nightly.svg b/packages/yoroi-connector/img/favicon_erg-nightly.svg similarity index 100% rename from packages/yoroi-ergo-connector/img/favicon_erg-nightly.svg rename to packages/yoroi-connector/img/favicon_erg-nightly.svg diff --git a/packages/yoroi-ergo-connector/img/favicon_erg.svg b/packages/yoroi-connector/img/favicon_erg.svg similarity index 100% rename from packages/yoroi-ergo-connector/img/favicon_erg.svg rename to packages/yoroi-connector/img/favicon_erg.svg diff --git a/packages/yoroi-ergo-connector/img/icon-128.png b/packages/yoroi-connector/img/icon-128.png similarity index 100% rename from packages/yoroi-ergo-connector/img/icon-128.png rename to packages/yoroi-connector/img/icon-128.png diff --git a/packages/yoroi-ergo-connector/img/icon-16.png b/packages/yoroi-connector/img/icon-16.png similarity index 100% rename from packages/yoroi-ergo-connector/img/icon-16.png rename to packages/yoroi-connector/img/icon-16.png diff --git a/packages/yoroi-ergo-connector/img/icon-48.png b/packages/yoroi-connector/img/icon-48.png similarity index 100% rename from packages/yoroi-ergo-connector/img/icon-48.png rename to packages/yoroi-connector/img/icon-48.png diff --git a/packages/yoroi-ergo-connector/img/nightly-128.png b/packages/yoroi-connector/img/nightly-128.png similarity index 100% rename from packages/yoroi-ergo-connector/img/nightly-128.png rename to packages/yoroi-connector/img/nightly-128.png diff --git a/packages/yoroi-ergo-connector/img/nightly-16.png b/packages/yoroi-connector/img/nightly-16.png similarity index 100% rename from packages/yoroi-ergo-connector/img/nightly-16.png rename to packages/yoroi-connector/img/nightly-16.png diff --git a/packages/yoroi-ergo-connector/img/nightly-48.png b/packages/yoroi-connector/img/nightly-48.png similarity index 100% rename from packages/yoroi-ergo-connector/img/nightly-48.png rename to packages/yoroi-connector/img/nightly-48.png diff --git a/packages/yoroi-ergo-connector/manifest/manifest.template.js b/packages/yoroi-connector/manifest/manifest.template.js similarity index 100% rename from packages/yoroi-ergo-connector/manifest/manifest.template.js rename to packages/yoroi-connector/manifest/manifest.template.js diff --git a/packages/yoroi-ergo-connector/package-lock.json b/packages/yoroi-connector/package-lock.json similarity index 100% rename from packages/yoroi-ergo-connector/package-lock.json rename to packages/yoroi-connector/package-lock.json diff --git a/packages/yoroi-ergo-connector/package.json b/packages/yoroi-connector/package.json similarity index 100% rename from packages/yoroi-ergo-connector/package.json rename to packages/yoroi-connector/package.json diff --git a/packages/yoroi-ergo-connector/src/background.js b/packages/yoroi-connector/src/background.js similarity index 100% rename from packages/yoroi-ergo-connector/src/background.js rename to packages/yoroi-connector/src/background.js diff --git a/packages/yoroi-ergo-connector/src/inject.js b/packages/yoroi-connector/src/inject.js similarity index 100% rename from packages/yoroi-ergo-connector/src/inject.js rename to packages/yoroi-connector/src/inject.js From 8e645c7e6f39709bd90bc77444bd250b979e3e97 Mon Sep 17 00:00:00 2001 From: Ahmed Ibrahim Date: Mon, 17 Oct 2022 13:42:09 +0200 Subject: [PATCH 010/172] Rename ergo-connector into connector --- .github/workflows/tests.yml | 12 ++++++------ install-all.sh | 6 +++--- packages/yoroi-connector/package-lock.json | 2 +- packages/yoroi-connector/package.json | 6 +++--- packages/yoroi-extension/.storybook/main.js | 4 ++-- packages/yoroi-extension/app/actions/index.js | 2 +- packages/yoroi-extension/app/api/ada/index.js | 2 +- .../app/api/ergo/lib/state-fetch/mockNetwork.js | 2 +- .../yoroi-extension/app/api/localStorage/index.js | 2 +- .../ConnectedWebsites/ConnectedWebsitesPage.js | 2 +- .../app/{ergo-connector => connector}/App.js | 0 .../app/{ergo-connector => connector}/Routes.js | 0 .../actions/connector-actions.js | 2 +- .../{ergo-connector => connector}/actions/index.js | 0 .../app/{ergo-connector => connector}/api/index.js | 2 +- .../assets/images/arrow-expand.inline.svg | 0 .../assets/images/arrow_back.inline.svg | 0 .../assets/images/no-websites-connected.inline.svg | 0 .../assets/images/yoroi_logo.inline.svg | 0 .../components/ProgressBar.js | 0 .../components/ProgressBar.scss | 0 .../components/connect/ConnectPage.js | 2 +- .../components/connect/ConnectPage.scss | 0 .../components/connect/WalletCard.js | 2 +- .../components/connect/WalletCard.scss | 0 .../components/layout/Layout.js | 0 .../components/layout/Layout.scss | 0 .../components/signin/AddCollateralPage.js | 0 .../components/signin/CardanoSignTxPage.js | 2 +- .../components/signin/CardanoUtxoDetails.js | 0 .../components/signin/SignTxPage.js | 4 ++-- .../components/signin/SignTxTabs.js | 0 .../components/signin/UtxoDetails.js | 4 ++-- .../containers/ConnectContainer.js | 2 +- .../containers/ConnectContainer.stories.js | 0 .../containers/SignTxContainer.js | 2 +- .../containers/SignTxContainer.stories.js | 0 .../{ergo-connector => connector}/routes-config.js | 0 .../stores/ConnectorStore.js | 6 +++--- .../stores/ada/index.js | 0 .../stores/ergo/index.js | 0 .../{ergo-connector => connector}/stores/index.js | 0 .../stores/toplevel/ConnectorCoinPriceStore.js | 0 .../stores/toplevel/ConnectorLoadingStore.js | 0 .../stores/toplevel/ExplorerStore.js | 0 .../stores/toplevel/ProfileStore.js | 0 .../app/{ergo-connector => connector}/types.js | 0 .../dapp-connector/ConnectedWebsitesContainer.js | 2 +- .../yoroi-extension/app/stores/DappConnectorStore.js | 4 ++-- .../yoroi-extension/app/types/injectedPropsType.js | 4 ++-- .../yoroi-extension/chrome/extension/background.js | 12 ++++++------ .../extension/{ergo-connector => connector}/api.js | 4 ++-- .../extension/{ergo-connector => connector}/index.js | 6 +++--- .../extension/{ergo-connector => connector}/types.js | 0 .../extension/{ergo-connector => connector}/utils.js | 0 .../{ergo-connector => connector}/main_window.html | 0 packages/yoroi-extension/scripts/build.js | 4 ++-- packages/yoroi-extension/webpack/commonConfig.js | 2 +- packages/yoroi-extension/webpack/devConfig.js | 2 +- packages/yoroi-extension/webpack/prodConfig.js | 2 +- run-cardano-example-dapp.sh | 4 ++-- 61 files changed, 57 insertions(+), 57 deletions(-) rename packages/yoroi-extension/app/{ergo-connector => connector}/App.js (100%) rename packages/yoroi-extension/app/{ergo-connector => connector}/Routes.js (100%) rename packages/yoroi-extension/app/{ergo-connector => connector}/actions/connector-actions.js (90%) rename packages/yoroi-extension/app/{ergo-connector => connector}/actions/index.js (100%) rename packages/yoroi-extension/app/{ergo-connector => connector}/api/index.js (99%) rename packages/yoroi-extension/app/{ergo-connector => connector}/assets/images/arrow-expand.inline.svg (100%) rename packages/yoroi-extension/app/{ergo-connector => connector}/assets/images/arrow_back.inline.svg (100%) rename packages/yoroi-extension/app/{ergo-connector => connector}/assets/images/no-websites-connected.inline.svg (100%) rename packages/yoroi-extension/app/{ergo-connector => connector}/assets/images/yoroi_logo.inline.svg (100%) rename packages/yoroi-extension/app/{ergo-connector => connector}/components/ProgressBar.js (100%) rename packages/yoroi-extension/app/{ergo-connector => connector}/components/ProgressBar.scss (100%) rename packages/yoroi-extension/app/{ergo-connector => connector}/components/connect/ConnectPage.js (99%) rename packages/yoroi-extension/app/{ergo-connector => connector}/components/connect/ConnectPage.scss (100%) rename packages/yoroi-extension/app/{ergo-connector => connector}/components/connect/WalletCard.js (98%) rename packages/yoroi-extension/app/{ergo-connector => connector}/components/connect/WalletCard.scss (100%) rename packages/yoroi-extension/app/{ergo-connector => connector}/components/layout/Layout.js (100%) rename packages/yoroi-extension/app/{ergo-connector => connector}/components/layout/Layout.scss (100%) rename packages/yoroi-extension/app/{ergo-connector => connector}/components/signin/AddCollateralPage.js (100%) rename packages/yoroi-extension/app/{ergo-connector => connector}/components/signin/CardanoSignTxPage.js (99%) rename packages/yoroi-extension/app/{ergo-connector => connector}/components/signin/CardanoUtxoDetails.js (100%) rename packages/yoroi-extension/app/{ergo-connector => connector}/components/signin/SignTxPage.js (99%) rename packages/yoroi-extension/app/{ergo-connector => connector}/components/signin/SignTxTabs.js (100%) rename packages/yoroi-extension/app/{ergo-connector => connector}/components/signin/UtxoDetails.js (98%) rename packages/yoroi-extension/app/{ergo-connector => connector}/containers/ConnectContainer.js (99%) rename packages/yoroi-extension/app/{ergo-connector => connector}/containers/ConnectContainer.stories.js (100%) rename packages/yoroi-extension/app/{ergo-connector => connector}/containers/SignTxContainer.js (99%) rename packages/yoroi-extension/app/{ergo-connector => connector}/containers/SignTxContainer.stories.js (100%) rename packages/yoroi-extension/app/{ergo-connector => connector}/routes-config.js (100%) rename packages/yoroi-extension/app/{ergo-connector => connector}/stores/ConnectorStore.js (99%) rename packages/yoroi-extension/app/{ergo-connector => connector}/stores/ada/index.js (100%) rename packages/yoroi-extension/app/{ergo-connector => connector}/stores/ergo/index.js (100%) rename packages/yoroi-extension/app/{ergo-connector => connector}/stores/index.js (100%) rename packages/yoroi-extension/app/{ergo-connector => connector}/stores/toplevel/ConnectorCoinPriceStore.js (100%) rename packages/yoroi-extension/app/{ergo-connector => connector}/stores/toplevel/ConnectorLoadingStore.js (100%) rename packages/yoroi-extension/app/{ergo-connector => connector}/stores/toplevel/ExplorerStore.js (100%) rename packages/yoroi-extension/app/{ergo-connector => connector}/stores/toplevel/ProfileStore.js (100%) rename packages/yoroi-extension/app/{ergo-connector => connector}/types.js (100%) rename packages/yoroi-extension/chrome/extension/{ergo-connector => connector}/api.js (99%) rename packages/yoroi-extension/chrome/extension/{ergo-connector => connector}/index.js (88%) rename packages/yoroi-extension/chrome/extension/{ergo-connector => connector}/types.js (100%) rename packages/yoroi-extension/chrome/extension/{ergo-connector => connector}/utils.js (100%) rename packages/yoroi-extension/chrome/views/{ergo-connector => connector}/main_window.html (100%) diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 4f00e0127f..ea85ffe618 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -88,8 +88,8 @@ jobs: # https://github.com/actions/cache/blob/main/examples.md#node---npm # It is recommended to cache the NPM cache (~/.npm) instead of node_modules. # But we put node version into the cache key and cache node_modules. - path: packages/yoroi-ergo-connector/node_modules - key: ${{ runner.os }}-build-${{ env.cache-name }}-node-${{ steps.nvm.outputs.NVMRC }}-${{ hashFiles('packages/yoroi-ergo-connector/package-lock.json') }} + path: packages/yoroi-connector/node_modules + key: ${{ runner.os }}-build-${{ env.cache-name }}-node-${{ steps.nvm.outputs.NVMRC }}-${{ hashFiles('packages/yoroi-connector/package-lock.json') }} restore-keys: | ${{ runner.os }}-build-${{ env.cache-name }}- ${{ runner.os }}-build- @@ -210,8 +210,8 @@ jobs: # https://github.com/actions/cache/blob/main/examples.md#node---npm # It is recommended to cache the NPM cache (~/.npm) instead of node_modules. # But we put node version into the cache key and cache node_modules. - path: packages/yoroi-ergo-connector/node_modules - key: ${{ runner.os }}-build-${{ env.cache-name }}-node-${{ steps.nvm.outputs.NVMRC }}-${{ hashFiles('packages/yoroi-ergo-connector/package-lock.json') }} + path: packages/yoroi-connector/node_modules + key: ${{ runner.os }}-build-${{ env.cache-name }}-node-${{ steps.nvm.outputs.NVMRC }}-${{ hashFiles('packages/yoroi-connector/package-lock.json') }} restore-keys: | ${{ runner.os }}-build-${{ env.cache-name }}- ${{ runner.os }}-build- @@ -301,8 +301,8 @@ jobs: # https://github.com/actions/cache/blob/main/examples.md#node---npm # It is recommended to cache the NPM cache (~/.npm) instead of node_modules. # But we put node version into the cache key and cache node_modules. - path: packages/yoroi-ergo-connector/node_modules - key: ${{ runner.os }}-build-${{ env.cache-name }}-node-${{ steps.nvm.outputs.NVMRC }}-${{ hashFiles('packages/yoroi-ergo-connector/package-lock.json') }} + path: packages/yoroi-connector/node_modules + key: ${{ runner.os }}-build-${{ env.cache-name }}-node-${{ steps.nvm.outputs.NVMRC }}-${{ hashFiles('packages/yoroi-connector/package-lock.json') }} restore-keys: | ${{ runner.os }}-build-${{ env.cache-name }}- ${{ runner.os }}-build- diff --git a/install-all.sh b/install-all.sh index dbdbe7c4c0..2efa699cb1 100644 --- a/install-all.sh +++ b/install-all.sh @@ -1,5 +1,5 @@ npm i \ && npm i --prefix packages/yoroi-extension \ -&& npm i --prefix packages/yoroi-ergo-connector \ -&& npm i --prefix packages/yoroi-ergo-connector/example-ergo \ -&& npm i --prefix packages/yoroi-ergo-connector/example-cardano \ No newline at end of file +&& npm i --prefix packages/yoroi-connector \ +&& npm i --prefix packages/yoroi-connector/example-ergo \ +&& npm i --prefix packages/yoroi-connector/example-cardano \ No newline at end of file diff --git a/packages/yoroi-connector/package-lock.json b/packages/yoroi-connector/package-lock.json index 75bdab2f16..8c8cd2ac7b 100644 --- a/packages/yoroi-connector/package-lock.json +++ b/packages/yoroi-connector/package-lock.json @@ -1,5 +1,5 @@ { - "name": "yoroi-ergo-connector", + "name": "yoroi-connector", "version": "0.8.0", "lockfileVersion": 1, "requires": true, diff --git a/packages/yoroi-connector/package.json b/packages/yoroi-connector/package.json index efd44f49b4..726a5f258b 100644 --- a/packages/yoroi-connector/package.json +++ b/packages/yoroi-connector/package.json @@ -1,5 +1,5 @@ { - "name": "yoroi-ergo-connector", + "name": "yoroi-connector", "version": "0.8.0", "description": "", "scripts": { @@ -8,8 +8,8 @@ "cardano": "npm start --prefix example-cardano", "prod:compress": "node ../../scripts/compress", "prod:custom": "node ./build.js", - "prod:nightly": "npm run prod:custom -- --yoroiExtensionId=poonlenmfdfbjfeeballhiibknlknepo && npm run prod:compress -- --env 'nightly' --app-id 'yoroi-ergo-connector-nightly' --zip-only --codebase 'https://yoroiwallet.com/dw/yoroi-ergo-connector-nightly.crx' --key ./keys/nightly-key.pem", - "prod:stable": "npm run prod:custom -- --yoroiExtensionId=ffnbelfdoeiohenkjibnmadjiehjhajb && npm run prod:compress -- --env '' --app-id 'yoroi-ergo-connector' --zip-only --codebase 'https://yoroiwallet.com/dw/yoroi-ergo-connector.crx' --key ./keys/production-key.pem" + "prod:nightly": "npm run prod:custom -- --yoroiExtensionId=poonlenmfdfbjfeeballhiibknlknepo && npm run prod:compress -- --env 'nightly' --app-id 'yoroi-connector-nightly' --zip-only --codebase 'https://yoroiwallet.com/dw/yoroi-ergo-connector-nightly.crx' --key ./keys/nightly-key.pem", + "prod:stable": "npm run prod:custom -- --yoroiExtensionId=ffnbelfdoeiohenkjibnmadjiehjhajb && npm run prod:compress -- --env '' --app-id 'yoroi-connector' --zip-only --codebase 'https://yoroiwallet.com/dw/yoroi-ergo-connector.crx' --key ./keys/production-key.pem" }, "devDependencies": { "crx": "5.0.1", diff --git a/packages/yoroi-extension/.storybook/main.js b/packages/yoroi-extension/.storybook/main.js index 68fc08d6cc..3f9c1cea88 100644 --- a/packages/yoroi-extension/.storybook/main.js +++ b/packages/yoroi-extension/.storybook/main.js @@ -4,8 +4,8 @@ module.exports = { stories: [ '../app/components/**/*.stories.js', '../app/containers/**/*.stories.js', - '../app/ergo-connector/components/**/*.stories.js', - '../app/ergo-connector/containers/**/*.stories.js', + '../app/connector/components/**/*.stories.js', + '../app/connector/containers/**/*.stories.js', ], addons: [ '@storybook/addon-knobs/register', diff --git a/packages/yoroi-extension/app/actions/index.js b/packages/yoroi-extension/app/actions/index.js index 0fb40f0443..d997c011d9 100644 --- a/packages/yoroi-extension/app/actions/index.js +++ b/packages/yoroi-extension/app/actions/index.js @@ -24,7 +24,7 @@ import jormungandrActionsMap from './jormungandr/index'; import type { AdaActionsMap } from './ada/index'; import type { ErgoActionsMap } from './ergo/index'; import type { JormungandrActionsMap } from './jormungandr/index'; -import ConnectorActionsMap from '../ergo-connector/actions/connector-actions'; +import ConnectorActionsMap from '../connector/actions/connector-actions'; import ServerConnectionActions from './server-connection-actions'; export type ActionsMap = {| diff --git a/packages/yoroi-extension/app/api/ada/index.js b/packages/yoroi-extension/app/api/ada/index.js index bfc8f9d9f5..229596b228 100644 --- a/packages/yoroi-extension/app/api/ada/index.js +++ b/packages/yoroi-extension/app/api/ada/index.js @@ -163,7 +163,7 @@ import { getAllSchemaTables, mapToTables, raii, } from './lib/storage/database/u import { GetDerivationSpecific, } from './lib/storage/database/walletTypes/common/api/read'; import { bytesToHex, hexToBytes, hexToUtf } from '../../coreUtils'; import type { PersistedSubmittedTransaction } from '../localStorage'; -import type { ForeignUtxoFetcher } from '../../ergo-connector/stores/ConnectorStore'; +import type { ForeignUtxoFetcher } from '../../connector/stores/ConnectorStore'; // ADA specific Request / Response params diff --git a/packages/yoroi-extension/app/api/ergo/lib/state-fetch/mockNetwork.js b/packages/yoroi-extension/app/api/ergo/lib/state-fetch/mockNetwork.js index 650abe8f28..e70d9fed83 100644 --- a/packages/yoroi-extension/app/api/ergo/lib/state-fetch/mockNetwork.js +++ b/packages/yoroi-extension/app/api/ergo/lib/state-fetch/mockNetwork.js @@ -25,7 +25,7 @@ import { derivePath } from '../../../common/lib/crypto/keys/keyRepository'; import { RollbackApiError, } from '../../../common/errors'; import { getErgoBaseConfig } from '../../../ada/lib/storage/database/prepackaged/networks'; import { RustModule } from '../../../ada/lib/cardanoCrypto/rustLoader'; -import { parseEIP0004Data } from '../../../../../chrome/extension/ergo-connector/utils'; +import { parseEIP0004Data } from '../../../../../chrome/extension/connector/utils'; // note: this function assumes mainnet export function getErgoAddress( diff --git a/packages/yoroi-extension/app/api/localStorage/index.js b/packages/yoroi-extension/app/api/localStorage/index.js index 35e8192762..691a431d12 100644 --- a/packages/yoroi-extension/app/api/localStorage/index.js +++ b/packages/yoroi-extension/app/api/localStorage/index.js @@ -14,7 +14,7 @@ import { TabIdKeys, } from '../../utils/tabManager'; import type { ComplexityLevelType } from '../../types/complexityLevelType'; -import type { WhitelistEntry } from '../../../chrome/extension/ergo-connector/types'; +import type { WhitelistEntry } from '../../../chrome/extension/connector/types'; import type { CatalystRoundInfoResponse } from '../ada/lib/state-fetch/types' const networkForLocalStorage = String(environment.getNetworkName()); diff --git a/packages/yoroi-extension/app/components/dapp-connector/ConnectedWebsites/ConnectedWebsitesPage.js b/packages/yoroi-extension/app/components/dapp-connector/ConnectedWebsites/ConnectedWebsitesPage.js index 87520d40f6..3e660370ac 100644 --- a/packages/yoroi-extension/app/components/dapp-connector/ConnectedWebsites/ConnectedWebsitesPage.js +++ b/packages/yoroi-extension/app/components/dapp-connector/ConnectedWebsites/ConnectedWebsitesPage.js @@ -2,7 +2,7 @@ import type { Node } from 'react'; import { Component } from 'react'; import { observer } from 'mobx-react'; -import type { WhitelistEntry } from '../../../../chrome/extension/ergo-connector/types' +import type { WhitelistEntry } from '../../../../chrome/extension/connector/types' import styles from './ConnectedWebsitesPage.scss' import { ReactComponent as NoItemsFoundImg } from '../../../assets/images/dapp-connector/no-websites-connected.inline.svg' import type { $npm$ReactIntl$IntlFormat } from 'react-intl'; diff --git a/packages/yoroi-extension/app/ergo-connector/App.js b/packages/yoroi-extension/app/connector/App.js similarity index 100% rename from packages/yoroi-extension/app/ergo-connector/App.js rename to packages/yoroi-extension/app/connector/App.js diff --git a/packages/yoroi-extension/app/ergo-connector/Routes.js b/packages/yoroi-extension/app/connector/Routes.js similarity index 100% rename from packages/yoroi-extension/app/ergo-connector/Routes.js rename to packages/yoroi-extension/app/connector/Routes.js diff --git a/packages/yoroi-extension/app/ergo-connector/actions/connector-actions.js b/packages/yoroi-extension/app/connector/actions/connector-actions.js similarity index 90% rename from packages/yoroi-extension/app/ergo-connector/actions/connector-actions.js rename to packages/yoroi-extension/app/connector/actions/connector-actions.js index c3978e3e17..dd1edf7c85 100644 --- a/packages/yoroi-extension/app/ergo-connector/actions/connector-actions.js +++ b/packages/yoroi-extension/app/connector/actions/connector-actions.js @@ -1,6 +1,6 @@ // @flow import { AsyncAction, Action } from '../../actions/lib/Action'; -import type { WhitelistEntry } from '../../../chrome/extension/ergo-connector/types'; +import type { WhitelistEntry } from '../../../chrome/extension/connector/types'; // ======= CONNECTOR ACTIONS ======= export default class ConnectorActions { diff --git a/packages/yoroi-extension/app/ergo-connector/actions/index.js b/packages/yoroi-extension/app/connector/actions/index.js similarity index 100% rename from packages/yoroi-extension/app/ergo-connector/actions/index.js rename to packages/yoroi-extension/app/connector/actions/index.js diff --git a/packages/yoroi-extension/app/ergo-connector/api/index.js b/packages/yoroi-extension/app/connector/api/index.js similarity index 99% rename from packages/yoroi-extension/app/ergo-connector/api/index.js rename to packages/yoroi-extension/app/connector/api/index.js index 4b3a562cd8..558b38b152 100644 --- a/packages/yoroi-extension/app/ergo-connector/api/index.js +++ b/packages/yoroi-extension/app/connector/api/index.js @@ -2,7 +2,7 @@ import { PublicDeriver } from '../../api/ada/lib/storage/models/PublicDeriver'; import type { WalletChecksum } from '@emurgo/cip4-js'; -import type { WalletAuthEntry } from '../../../chrome/extension/ergo-connector/types'; +import type { WalletAuthEntry } from '../../../chrome/extension/connector/types'; import { RustModule } from '../../api/ada/lib/cardanoCrypto/rustLoader'; import { asGetSigningKey } from '../../api/ada/lib/storage/models/PublicDeriver/traits'; diff --git a/packages/yoroi-extension/app/ergo-connector/assets/images/arrow-expand.inline.svg b/packages/yoroi-extension/app/connector/assets/images/arrow-expand.inline.svg similarity index 100% rename from packages/yoroi-extension/app/ergo-connector/assets/images/arrow-expand.inline.svg rename to packages/yoroi-extension/app/connector/assets/images/arrow-expand.inline.svg diff --git a/packages/yoroi-extension/app/ergo-connector/assets/images/arrow_back.inline.svg b/packages/yoroi-extension/app/connector/assets/images/arrow_back.inline.svg similarity index 100% rename from packages/yoroi-extension/app/ergo-connector/assets/images/arrow_back.inline.svg rename to packages/yoroi-extension/app/connector/assets/images/arrow_back.inline.svg diff --git a/packages/yoroi-extension/app/ergo-connector/assets/images/no-websites-connected.inline.svg b/packages/yoroi-extension/app/connector/assets/images/no-websites-connected.inline.svg similarity index 100% rename from packages/yoroi-extension/app/ergo-connector/assets/images/no-websites-connected.inline.svg rename to packages/yoroi-extension/app/connector/assets/images/no-websites-connected.inline.svg diff --git a/packages/yoroi-extension/app/ergo-connector/assets/images/yoroi_logo.inline.svg b/packages/yoroi-extension/app/connector/assets/images/yoroi_logo.inline.svg similarity index 100% rename from packages/yoroi-extension/app/ergo-connector/assets/images/yoroi_logo.inline.svg rename to packages/yoroi-extension/app/connector/assets/images/yoroi_logo.inline.svg diff --git a/packages/yoroi-extension/app/ergo-connector/components/ProgressBar.js b/packages/yoroi-extension/app/connector/components/ProgressBar.js similarity index 100% rename from packages/yoroi-extension/app/ergo-connector/components/ProgressBar.js rename to packages/yoroi-extension/app/connector/components/ProgressBar.js diff --git a/packages/yoroi-extension/app/ergo-connector/components/ProgressBar.scss b/packages/yoroi-extension/app/connector/components/ProgressBar.scss similarity index 100% rename from packages/yoroi-extension/app/ergo-connector/components/ProgressBar.scss rename to packages/yoroi-extension/app/connector/components/ProgressBar.scss diff --git a/packages/yoroi-extension/app/ergo-connector/components/connect/ConnectPage.js b/packages/yoroi-extension/app/connector/components/connect/ConnectPage.js similarity index 99% rename from packages/yoroi-extension/app/ergo-connector/components/connect/ConnectPage.js rename to packages/yoroi-extension/app/connector/components/connect/ConnectPage.js index e5ed79cd3e..d8947482bf 100644 --- a/packages/yoroi-extension/app/ergo-connector/components/connect/ConnectPage.js +++ b/packages/yoroi-extension/app/connector/components/connect/ConnectPage.js @@ -14,7 +14,7 @@ import LoadingSpinner from '../../../components/widgets/LoadingSpinner'; import type { PublicDeriverCache, ConnectingMessage, -} from '../../../../chrome/extension/ergo-connector/types'; +} from '../../../../chrome/extension/connector/types'; import { LoadingWalletStates } from '../../types'; import ProgressBar from '../ProgressBar'; import type { TokenLookupKey } from '../../../api/common/lib/MultiToken'; diff --git a/packages/yoroi-extension/app/ergo-connector/components/connect/ConnectPage.scss b/packages/yoroi-extension/app/connector/components/connect/ConnectPage.scss similarity index 100% rename from packages/yoroi-extension/app/ergo-connector/components/connect/ConnectPage.scss rename to packages/yoroi-extension/app/connector/components/connect/ConnectPage.scss diff --git a/packages/yoroi-extension/app/ergo-connector/components/connect/WalletCard.js b/packages/yoroi-extension/app/connector/components/connect/WalletCard.js similarity index 98% rename from packages/yoroi-extension/app/ergo-connector/components/connect/WalletCard.js rename to packages/yoroi-extension/app/connector/components/connect/WalletCard.js index 09d59ad2fb..e31bbe8a50 100644 --- a/packages/yoroi-extension/app/ergo-connector/components/connect/WalletCard.js +++ b/packages/yoroi-extension/app/connector/components/connect/WalletCard.js @@ -4,7 +4,7 @@ import type { Node } from 'react'; import styles from './WalletCard.scss'; import WalletAccountIcon from '../../../components/topbar/WalletAccountIcon'; import type { WalletChecksum } from '@emurgo/cip4-js'; -import type { PublicDeriverCache } from '../../../../chrome/extension/ergo-connector/types'; +import type { PublicDeriverCache } from '../../../../chrome/extension/connector/types'; import type { TokenLookupKey } from '../../../api/common/lib/MultiToken'; import type { TokenRow } from '../../../api/ada/lib/storage/database/primitives/tables'; import { assetNameFromIdentifier, getTokenName } from '../../../stores/stateless/tokenHelpers'; diff --git a/packages/yoroi-extension/app/ergo-connector/components/connect/WalletCard.scss b/packages/yoroi-extension/app/connector/components/connect/WalletCard.scss similarity index 100% rename from packages/yoroi-extension/app/ergo-connector/components/connect/WalletCard.scss rename to packages/yoroi-extension/app/connector/components/connect/WalletCard.scss diff --git a/packages/yoroi-extension/app/ergo-connector/components/layout/Layout.js b/packages/yoroi-extension/app/connector/components/layout/Layout.js similarity index 100% rename from packages/yoroi-extension/app/ergo-connector/components/layout/Layout.js rename to packages/yoroi-extension/app/connector/components/layout/Layout.js diff --git a/packages/yoroi-extension/app/ergo-connector/components/layout/Layout.scss b/packages/yoroi-extension/app/connector/components/layout/Layout.scss similarity index 100% rename from packages/yoroi-extension/app/ergo-connector/components/layout/Layout.scss rename to packages/yoroi-extension/app/connector/components/layout/Layout.scss diff --git a/packages/yoroi-extension/app/ergo-connector/components/signin/AddCollateralPage.js b/packages/yoroi-extension/app/connector/components/signin/AddCollateralPage.js similarity index 100% rename from packages/yoroi-extension/app/ergo-connector/components/signin/AddCollateralPage.js rename to packages/yoroi-extension/app/connector/components/signin/AddCollateralPage.js diff --git a/packages/yoroi-extension/app/ergo-connector/components/signin/CardanoSignTxPage.js b/packages/yoroi-extension/app/connector/components/signin/CardanoSignTxPage.js similarity index 99% rename from packages/yoroi-extension/app/ergo-connector/components/signin/CardanoSignTxPage.js rename to packages/yoroi-extension/app/connector/components/signin/CardanoSignTxPage.js index 14c5bbc3de..187d3f859e 100644 --- a/packages/yoroi-extension/app/ergo-connector/components/signin/CardanoSignTxPage.js +++ b/packages/yoroi-extension/app/connector/components/signin/CardanoSignTxPage.js @@ -34,7 +34,7 @@ import { calculateAndFormatValue } from '../../../utils/unit-of-account'; import type { PublicDeriverCache, WhitelistEntry, -} from '../../../../chrome/extension/ergo-connector/types'; +} from '../../../../chrome/extension/connector/types'; import type { CardanoConnectorSignRequest, SignSubmissionErrorType } from '../../types'; import CardanoUtxoDetails from './CardanoUtxoDetails'; import { Box } from '@mui/system'; diff --git a/packages/yoroi-extension/app/ergo-connector/components/signin/CardanoUtxoDetails.js b/packages/yoroi-extension/app/connector/components/signin/CardanoUtxoDetails.js similarity index 100% rename from packages/yoroi-extension/app/ergo-connector/components/signin/CardanoUtxoDetails.js rename to packages/yoroi-extension/app/connector/components/signin/CardanoUtxoDetails.js diff --git a/packages/yoroi-extension/app/ergo-connector/components/signin/SignTxPage.js b/packages/yoroi-extension/app/connector/components/signin/SignTxPage.js similarity index 99% rename from packages/yoroi-extension/app/ergo-connector/components/signin/SignTxPage.js rename to packages/yoroi-extension/app/connector/components/signin/SignTxPage.js index c224180f45..e05fc3d57d 100644 --- a/packages/yoroi-extension/app/ergo-connector/components/signin/SignTxPage.js +++ b/packages/yoroi-extension/app/connector/components/signin/SignTxPage.js @@ -26,8 +26,8 @@ import type { UnitOfAccountSettingType } from '../../../types/unitOfAccountType' import ExplorableHashContainer from '../../../containers/widgets/ExplorableHashContainer'; import { SelectedExplorer } from '../../../domain/SelectedExplorer'; import { calculateAndFormatValue } from '../../../utils/unit-of-account'; -import { mintedTokenInfo } from '../../../../chrome/extension/ergo-connector/utils'; -import type { PublicDeriverCache, Tx, WhitelistEntry } from '../../../../chrome/extension/ergo-connector/types'; +import { mintedTokenInfo } from '../../../../chrome/extension/connector/utils'; +import type { PublicDeriverCache, Tx, WhitelistEntry } from '../../../../chrome/extension/connector/types'; import { Logger } from '../../../utils/logging'; import UtxoDetails from './UtxoDetails'; import SignTxTabs from './SignTxTabs'; diff --git a/packages/yoroi-extension/app/ergo-connector/components/signin/SignTxTabs.js b/packages/yoroi-extension/app/connector/components/signin/SignTxTabs.js similarity index 100% rename from packages/yoroi-extension/app/ergo-connector/components/signin/SignTxTabs.js rename to packages/yoroi-extension/app/connector/components/signin/SignTxTabs.js diff --git a/packages/yoroi-extension/app/ergo-connector/components/signin/UtxoDetails.js b/packages/yoroi-extension/app/connector/components/signin/UtxoDetails.js similarity index 98% rename from packages/yoroi-extension/app/ergo-connector/components/signin/UtxoDetails.js rename to packages/yoroi-extension/app/connector/components/signin/UtxoDetails.js index 69ed6c3b3e..605884b486 100644 --- a/packages/yoroi-extension/app/ergo-connector/components/signin/UtxoDetails.js +++ b/packages/yoroi-extension/app/connector/components/signin/UtxoDetails.js @@ -19,8 +19,8 @@ import { MultiToken } from '../../../api/common/lib/MultiToken'; import ExplorableHashContainer from '../../../containers/widgets/ExplorableHashContainer'; import { SelectedExplorer } from '../../../domain/SelectedExplorer'; import { calculateAndFormatValue } from '../../../utils/unit-of-account'; -import { mintedTokenInfo } from '../../../../chrome/extension/ergo-connector/utils'; -import type { Tx } from '../../../../chrome/extension/ergo-connector/types'; +import { mintedTokenInfo } from '../../../../chrome/extension/connector/utils'; +import type { Tx } from '../../../../chrome/extension/connector/types'; import { Logger } from '../../../utils/logging'; import { Box } from '@mui/system'; import { Typography } from '@mui/material'; diff --git a/packages/yoroi-extension/app/ergo-connector/containers/ConnectContainer.js b/packages/yoroi-extension/app/connector/containers/ConnectContainer.js similarity index 99% rename from packages/yoroi-extension/app/ergo-connector/containers/ConnectContainer.js rename to packages/yoroi-extension/app/connector/containers/ConnectContainer.js index 8ce459acb1..2998a1e931 100644 --- a/packages/yoroi-extension/app/ergo-connector/containers/ConnectContainer.js +++ b/packages/yoroi-extension/app/connector/containers/ConnectContainer.js @@ -10,7 +10,7 @@ import type { ConnectingMessage, WhitelistEntry, ConnectResponseData, -} from '../../../chrome/extension/ergo-connector/types'; +} from '../../../chrome/extension/connector/types'; import { LoadingWalletStates } from '../types'; import { genLookupOrFail } from '../../stores/stateless/tokenHelpers'; import type { TokenInfoMap } from '../../stores/toplevel/TokenInfoStore'; diff --git a/packages/yoroi-extension/app/ergo-connector/containers/ConnectContainer.stories.js b/packages/yoroi-extension/app/connector/containers/ConnectContainer.stories.js similarity index 100% rename from packages/yoroi-extension/app/ergo-connector/containers/ConnectContainer.stories.js rename to packages/yoroi-extension/app/connector/containers/ConnectContainer.stories.js diff --git a/packages/yoroi-extension/app/ergo-connector/containers/SignTxContainer.js b/packages/yoroi-extension/app/connector/containers/SignTxContainer.js similarity index 99% rename from packages/yoroi-extension/app/ergo-connector/containers/SignTxContainer.js rename to packages/yoroi-extension/app/connector/containers/SignTxContainer.js index 3d8a60d96c..54a06e0b88 100644 --- a/packages/yoroi-extension/app/ergo-connector/containers/SignTxContainer.js +++ b/packages/yoroi-extension/app/connector/containers/SignTxContainer.js @@ -13,7 +13,7 @@ import type { SigningMessage, PublicDeriverCache, WhitelistEntry, -} from '../../../chrome/extension/ergo-connector/types'; +} from '../../../chrome/extension/connector/types'; import { genLookupOrFail, genLookupOrNull } from '../../stores/stateless/tokenHelpers'; import type { TokenInfoMap } from '../../stores/toplevel/TokenInfoStore'; import type { TokenRow } from '../../api/ada/lib/storage/database/primitives/tables'; diff --git a/packages/yoroi-extension/app/ergo-connector/containers/SignTxContainer.stories.js b/packages/yoroi-extension/app/connector/containers/SignTxContainer.stories.js similarity index 100% rename from packages/yoroi-extension/app/ergo-connector/containers/SignTxContainer.stories.js rename to packages/yoroi-extension/app/connector/containers/SignTxContainer.stories.js diff --git a/packages/yoroi-extension/app/ergo-connector/routes-config.js b/packages/yoroi-extension/app/connector/routes-config.js similarity index 100% rename from packages/yoroi-extension/app/ergo-connector/routes-config.js rename to packages/yoroi-extension/app/connector/routes-config.js diff --git a/packages/yoroi-extension/app/ergo-connector/stores/ConnectorStore.js b/packages/yoroi-extension/app/connector/stores/ConnectorStore.js similarity index 99% rename from packages/yoroi-extension/app/ergo-connector/stores/ConnectorStore.js rename to packages/yoroi-extension/app/connector/stores/ConnectorStore.js index 93606e6ae0..39af7f020e 100644 --- a/packages/yoroi-extension/app/ergo-connector/stores/ConnectorStore.js +++ b/packages/yoroi-extension/app/connector/stores/ConnectorStore.js @@ -19,7 +19,7 @@ import type { TxSignWindowRetrieveData, WhitelistEntry, GetUtxosRequest, -} from '../../../chrome/extension/ergo-connector/types'; +} from '../../../chrome/extension/connector/types'; import type { ActionsMap } from '../actions/index'; import type { StoresMap } from './index'; import type { @@ -49,7 +49,7 @@ import type { ISignRequest } from '../../api/common/lib/transactions/ISignReques import { ErgoExternalTxSignRequest } from '../../api/ergo/lib/transactions/ErgoExternalTxSignRequest'; import { RustModule } from '../../api/ada/lib/cardanoCrypto/rustLoader'; import { toRemoteUtxo } from '../../api/ergo/lib/transactions/utils'; -import { mintedTokenInfo } from '../../../chrome/extension/ergo-connector/utils'; +import { mintedTokenInfo } from '../../../chrome/extension/connector/utils'; import { Logger } from '../../utils/logging'; import { asAddressedUtxo, multiTokenFromCardanoValue, multiTokenFromRemote, } from '../../api/ada/transactions/utils'; import { genTimeToSlot, } from '../../api/ada/lib/storage/bridge/timeUtils'; @@ -60,7 +60,7 @@ import { connectorSendTxCardano, connectorGenerateReorgTx, connectorRecordSubmittedCardanoTransaction, -} from '../../../chrome/extension/ergo-connector/api'; +} from '../../../chrome/extension/connector/api'; import { getWalletChecksum } from '../../api/export/utils'; import { WalletTypeOption } from '../../api/ada/lib/storage/models/ConceptualWallet/interfaces'; import { loadSubmittedTransactions } from '../../api/localStorage'; diff --git a/packages/yoroi-extension/app/ergo-connector/stores/ada/index.js b/packages/yoroi-extension/app/connector/stores/ada/index.js similarity index 100% rename from packages/yoroi-extension/app/ergo-connector/stores/ada/index.js rename to packages/yoroi-extension/app/connector/stores/ada/index.js diff --git a/packages/yoroi-extension/app/ergo-connector/stores/ergo/index.js b/packages/yoroi-extension/app/connector/stores/ergo/index.js similarity index 100% rename from packages/yoroi-extension/app/ergo-connector/stores/ergo/index.js rename to packages/yoroi-extension/app/connector/stores/ergo/index.js diff --git a/packages/yoroi-extension/app/ergo-connector/stores/index.js b/packages/yoroi-extension/app/connector/stores/index.js similarity index 100% rename from packages/yoroi-extension/app/ergo-connector/stores/index.js rename to packages/yoroi-extension/app/connector/stores/index.js diff --git a/packages/yoroi-extension/app/ergo-connector/stores/toplevel/ConnectorCoinPriceStore.js b/packages/yoroi-extension/app/connector/stores/toplevel/ConnectorCoinPriceStore.js similarity index 100% rename from packages/yoroi-extension/app/ergo-connector/stores/toplevel/ConnectorCoinPriceStore.js rename to packages/yoroi-extension/app/connector/stores/toplevel/ConnectorCoinPriceStore.js diff --git a/packages/yoroi-extension/app/ergo-connector/stores/toplevel/ConnectorLoadingStore.js b/packages/yoroi-extension/app/connector/stores/toplevel/ConnectorLoadingStore.js similarity index 100% rename from packages/yoroi-extension/app/ergo-connector/stores/toplevel/ConnectorLoadingStore.js rename to packages/yoroi-extension/app/connector/stores/toplevel/ConnectorLoadingStore.js diff --git a/packages/yoroi-extension/app/ergo-connector/stores/toplevel/ExplorerStore.js b/packages/yoroi-extension/app/connector/stores/toplevel/ExplorerStore.js similarity index 100% rename from packages/yoroi-extension/app/ergo-connector/stores/toplevel/ExplorerStore.js rename to packages/yoroi-extension/app/connector/stores/toplevel/ExplorerStore.js diff --git a/packages/yoroi-extension/app/ergo-connector/stores/toplevel/ProfileStore.js b/packages/yoroi-extension/app/connector/stores/toplevel/ProfileStore.js similarity index 100% rename from packages/yoroi-extension/app/ergo-connector/stores/toplevel/ProfileStore.js rename to packages/yoroi-extension/app/connector/stores/toplevel/ProfileStore.js diff --git a/packages/yoroi-extension/app/ergo-connector/types.js b/packages/yoroi-extension/app/connector/types.js similarity index 100% rename from packages/yoroi-extension/app/ergo-connector/types.js rename to packages/yoroi-extension/app/connector/types.js diff --git a/packages/yoroi-extension/app/containers/dapp-connector/ConnectedWebsitesContainer.js b/packages/yoroi-extension/app/containers/dapp-connector/ConnectedWebsitesContainer.js index 6553146e5f..19da59de3f 100644 --- a/packages/yoroi-extension/app/containers/dapp-connector/ConnectedWebsitesContainer.js +++ b/packages/yoroi-extension/app/containers/dapp-connector/ConnectedWebsitesContainer.js @@ -21,7 +21,7 @@ import FullscreenLayout from '../../components/layout/FullscreenLayout' import { ConceptualWallet } from '../../api/ada/lib/storage/models/ConceptualWallet' import type { ConceptualWalletSettingsCache } from '../../stores/toplevel/WalletSettingsStore'; import type { TokenInfoMap } from '../../stores/toplevel/TokenInfoStore'; -import type { WhitelistEntry } from '../../../chrome/extension/ergo-connector/types' +import type { WhitelistEntry } from '../../../chrome/extension/connector/types' import { PublicDeriver } from '../../api/ada/lib/storage/models/PublicDeriver' import { asGetPublicKey } from '../../api/ada/lib/storage/models/PublicDeriver/traits'; import environment from '../../environment' diff --git a/packages/yoroi-extension/app/stores/DappConnectorStore.js b/packages/yoroi-extension/app/stores/DappConnectorStore.js index d057fe833c..1f6e9813a2 100644 --- a/packages/yoroi-extension/app/stores/DappConnectorStore.js +++ b/packages/yoroi-extension/app/stores/DappConnectorStore.js @@ -9,10 +9,10 @@ import type { ConnectedSites, ConnectRetrieveData, RemoveWalletFromWhitelistData, -} from '../../chrome/extension/ergo-connector/types'; +} from '../../chrome/extension/connector/types'; import type { ActionsMap } from '../actions/index'; import type { StoresMap } from './index'; -import { getConnectedSites } from '../ergo-connector/stores/ConnectorStore'; +import { getConnectedSites } from '../connector/stores/ConnectorStore'; // Need to run only once - Connecting wallets let initedConnecting = false; diff --git a/packages/yoroi-extension/app/types/injectedPropsType.js b/packages/yoroi-extension/app/types/injectedPropsType.js index d5986ee10c..c7082cfae1 100644 --- a/packages/yoroi-extension/app/types/injectedPropsType.js +++ b/packages/yoroi-extension/app/types/injectedPropsType.js @@ -1,8 +1,8 @@ // @flow import type { StoresMap } from '../stores/index'; import type { ActionsMap } from '../actions/index'; -import type { StoresMap as StoresConnectorMap } from '../ergo-connector/stores/index'; -import type { ActionsMap as ActionsConnectorMap } from '../ergo-connector/actions/index'; +import type { StoresMap as StoresConnectorMap } from '../connector/stores/index'; +import type { ActionsMap as ActionsConnectorMap } from '../connector/actions/index'; type InjectedProps = {| +stores: StoresMap, diff --git a/packages/yoroi-extension/chrome/extension/background.js b/packages/yoroi-extension/chrome/extension/background.js index c1e50dc99d..93ea399203 100644 --- a/packages/yoroi-extension/chrome/extension/background.js +++ b/packages/yoroi-extension/chrome/extension/background.js @@ -24,7 +24,7 @@ import type { TxSignWindowRetrieveData, WalletAuthEntry, WhitelistEntry, -} from './ergo-connector/types'; +} from './connector/types'; import { APIErrorCodes, asPaginate, @@ -34,7 +34,7 @@ import { asValue, ConnectorError, DataSignErrorCodes, -} from './ergo-connector/types'; +} from './connector/types'; import { connectorCreateCardanoTx, connectorGenerateReorgTx, @@ -56,7 +56,7 @@ import { connectorSignData, connectorGetAssets, getTokenMetadataFromIds, -} from './ergo-connector/api'; +} from './connector/api'; import { updateTransactions as ergoUpdateTransactions } from '../../app/api/ergo/lib/storage/bridge/updateTransactions'; import { updateTransactions as cardanoUpdateTransactions @@ -82,12 +82,12 @@ import { getCardanoHaskellBaseConfig, isCardanoHaskell } from '../../app/api/ada/lib/storage/database/prepackaged/networks'; -import { authSignHexPayload } from '../../app/ergo-connector/api'; +import { authSignHexPayload } from '../../app/connector/api'; import type { RemoteUnspentOutput } from '../../app/api/ada/lib/state-fetch/types'; import { NotEnoughMoneyToSendError, } from '../../app/api/common/errors'; import { asAddressedUtxo as asAddressedUtxoCardano, } from '../../app/api/ada/transactions/utils'; -import ConnectorStore from '../../app/ergo-connector/stores/ConnectorStore'; -import type { ForeignUtxoFetcher } from '../../app/ergo-connector/stores/ConnectorStore'; +import ConnectorStore from '../../app/connector/stores/ConnectorStore'; +import type { ForeignUtxoFetcher } from '../../app/connector/stores/ConnectorStore'; import { find721metadata } from '../../app/utils/nftMetadata'; /*:: diff --git a/packages/yoroi-extension/chrome/extension/ergo-connector/api.js b/packages/yoroi-extension/chrome/extension/connector/api.js similarity index 99% rename from packages/yoroi-extension/chrome/extension/ergo-connector/api.js rename to packages/yoroi-extension/chrome/extension/connector/api.js index e0c32f51bb..12c4ee43be 100644 --- a/packages/yoroi-extension/chrome/extension/ergo-connector/api.js +++ b/packages/yoroi-extension/chrome/extension/connector/api.js @@ -80,9 +80,9 @@ import type { import type { CardanoAddressedUtxo, } from '../../../app/api/ada/transactions/types'; import { coinSelectionForValues } from '../../../app/api/ada/transactions/shelley/coinSelection'; import { derivePrivateByAddressing } from '../../../app/api/ada/lib/cardanoCrypto/utils'; -import { cip8Sign } from '../../../app/ergo-connector/api'; +import { cip8Sign } from '../../../app/connector/api'; import type { PersistedSubmittedTransaction } from '../../../app/api/localStorage'; -import type { ForeignUtxoFetcher } from '../../../app/ergo-connector/stores/ConnectorStore'; +import type { ForeignUtxoFetcher } from '../../../app/connector/stores/ConnectorStore'; import { GetToken } from '../../../app/api/ada/lib/storage/database/primitives/api/read'; import { getAllSchemaTables, diff --git a/packages/yoroi-extension/chrome/extension/ergo-connector/index.js b/packages/yoroi-extension/chrome/extension/connector/index.js similarity index 88% rename from packages/yoroi-extension/chrome/extension/ergo-connector/index.js rename to packages/yoroi-extension/chrome/extension/connector/index.js index 71b3189b47..433f74d5e5 100644 --- a/packages/yoroi-extension/chrome/extension/ergo-connector/index.js +++ b/packages/yoroi-extension/chrome/extension/connector/index.js @@ -5,11 +5,11 @@ import { action, configure } from 'mobx'; import { RouterStore, syncHistoryWithStore } from 'mobx-react-router'; import { createHashHistory } from 'history'; import { setupApi } from '../../../app/api/index'; -import createStores from '../../../app/ergo-connector/stores/index'; +import createStores from '../../../app/connector/stores/index'; import { translations } from '../../../app/i18n/translations'; -import actions from '../../../app/ergo-connector/actions/index'; +import actions from '../../../app/connector/actions/index'; import { Action } from '../../../app/actions/lib/Action'; -import App from '../../../app/ergo-connector/App'; +import App from '../../../app/connector/App'; import BigNumber from 'bignumber.js'; import { addCloseListener, TabIdKeys } from '../../../app/utils/tabManager'; diff --git a/packages/yoroi-extension/chrome/extension/ergo-connector/types.js b/packages/yoroi-extension/chrome/extension/connector/types.js similarity index 100% rename from packages/yoroi-extension/chrome/extension/ergo-connector/types.js rename to packages/yoroi-extension/chrome/extension/connector/types.js diff --git a/packages/yoroi-extension/chrome/extension/ergo-connector/utils.js b/packages/yoroi-extension/chrome/extension/connector/utils.js similarity index 100% rename from packages/yoroi-extension/chrome/extension/ergo-connector/utils.js rename to packages/yoroi-extension/chrome/extension/connector/utils.js diff --git a/packages/yoroi-extension/chrome/views/ergo-connector/main_window.html b/packages/yoroi-extension/chrome/views/connector/main_window.html similarity index 100% rename from packages/yoroi-extension/chrome/views/ergo-connector/main_window.html rename to packages/yoroi-extension/chrome/views/connector/main_window.html diff --git a/packages/yoroi-extension/scripts/build.js b/packages/yoroi-extension/scripts/build.js index f47b4d5b4f..99f7fadfc3 100644 --- a/packages/yoroi-extension/scripts/build.js +++ b/packages/yoroi-extension/scripts/build.js @@ -20,12 +20,12 @@ const shouldInjectConnector = argv.dontInjectConnector === undefined; const buildAndCopyInjector = (destDir: string, buildType: string) => { console.log('[Build injector]'); console.log('-'.repeat(80)); - shell.pushd('../yoroi-ergo-connector') + shell.pushd('../yoroi-connector') exec('npm run prod:custom -- --yoroiExtensionId=self'); shell.popd(); let injectScript: string; try { - const data = fs.readFileSync('../yoroi-ergo-connector/build/inject.js'); + const data = fs.readFileSync('../yoroi-connector/build/inject.js'); injectScript = Buffer.from(data).toString('utf-8'); } catch (e) { console.error('Failed to read the connector inject script!', e); diff --git a/packages/yoroi-extension/webpack/commonConfig.js b/packages/yoroi-extension/webpack/commonConfig.js index 9674585ce7..957389f3ac 100644 --- a/packages/yoroi-extension/webpack/commonConfig.js +++ b/packages/yoroi-extension/webpack/commonConfig.js @@ -34,7 +34,7 @@ const plugins = (folder /*: string */, _networkName /*: string */) /*: * */ => { }), new HtmlWebpackPlugin({ filename: path.join(__dirname, `../${folder}/main_window_connector.html`), - template: path.join(__dirname, '../chrome/views/ergo-connector/main_window.html'), + template: path.join(__dirname, '../chrome/views/connector/main_window.html'), chunks: ['ergo'], alwaysWriteToDisk: true, title: 'Yoroi dApp Connector', diff --git a/packages/yoroi-extension/webpack/devConfig.js b/packages/yoroi-extension/webpack/devConfig.js index 6b2a630797..cc6f5d43d1 100644 --- a/packages/yoroi-extension/webpack/devConfig.js +++ b/packages/yoroi-extension/webpack/devConfig.js @@ -37,7 +37,7 @@ const baseDevConfig = ( ergo: [ customPath, hotScript, - path.join(__dirname, '../chrome/extension/ergo-connector/index') + path.join(__dirname, '../chrome/extension/connector/index') ], ledger: [ customPath, diff --git a/packages/yoroi-extension/webpack/prodConfig.js b/packages/yoroi-extension/webpack/prodConfig.js index 67c9b575c6..9d1f7e15cb 100644 --- a/packages/yoroi-extension/webpack/prodConfig.js +++ b/packages/yoroi-extension/webpack/prodConfig.js @@ -34,7 +34,7 @@ const baseProdConfig = (env /*: EnvParams */) /*: * */ => ({ ], ergo: [ customPath, - path.join(__dirname, '../chrome/extension/ergo-connector/index') + path.join(__dirname, '../chrome/extension/connector/index') ], ledger: [ customPath, diff --git a/run-cardano-example-dapp.sh b/run-cardano-example-dapp.sh index 03a135210d..d1831dc746 100644 --- a/run-cardano-example-dapp.sh +++ b/run-cardano-example-dapp.sh @@ -1,3 +1,3 @@ nvm i \ -&& npm install --prefix packages/yoroi-ergo-connector/example-cardano \ -&& npm start --prefix packages/yoroi-ergo-connector/example-cardano \ No newline at end of file +&& npm install --prefix packages/yoroi-connector/example-cardano \ +&& npm start --prefix packages/yoroi-connector/example-cardano \ No newline at end of file From cb1c72c522106d92ab8b1ccdea456be8d33eee3a Mon Sep 17 00:00:00 2001 From: Ahmed Ibrahim Date: Mon, 17 Oct 2022 13:46:28 +0200 Subject: [PATCH 011/172] Update all locales --- .../components/connect/ConnectPage.js | 18 +++++++++--------- .../app/i18n/locales/cs-CZ.json | 8 ++++---- .../app/i18n/locales/el-GR.json | 8 ++++---- .../app/i18n/locales/en-US.json | 18 +++++++++--------- .../app/i18n/locales/es-ES.json | 8 ++++---- .../app/i18n/locales/fr-FR.json | 8 ++++---- .../app/i18n/locales/hr-HR.json | 8 ++++---- .../app/i18n/locales/id-ID.json | 8 ++++---- .../app/i18n/locales/it-IT.json | 8 ++++---- .../app/i18n/locales/ja-JP.json | 8 ++++---- .../app/i18n/locales/ko-KR.json | 8 ++++---- .../app/i18n/locales/nl-NL.json | 8 ++++---- .../app/i18n/locales/pt-BR.json | 8 ++++---- .../app/i18n/locales/ru-RU.json | 8 ++++---- .../app/i18n/locales/sk-SK.json | 8 ++++---- .../app/i18n/locales/tr-TR.json | 8 ++++---- .../app/i18n/locales/zh-Hans.json | 8 ++++---- .../app/i18n/locales/zh-Hant.json | 8 ++++---- 18 files changed, 82 insertions(+), 82 deletions(-) diff --git a/packages/yoroi-extension/app/connector/components/connect/ConnectPage.js b/packages/yoroi-extension/app/connector/components/connect/ConnectPage.js index d8947482bf..b271c792d8 100644 --- a/packages/yoroi-extension/app/connector/components/connect/ConnectPage.js +++ b/packages/yoroi-extension/app/connector/components/connect/ConnectPage.js @@ -33,35 +33,35 @@ import { ReactComponent as NoDappIcon } from '../../../assets/images/dapp-conne const messages = defineMessages({ subtitle: { - id: 'ergo-connector.label.connect', + id: 'connector.label.connect', defaultMessage: '!!!Connect to', }, connectWallet: { - id: 'ergo-connector.label.connectWallet', + id: 'connector.label.connectWallet', defaultMessage: '!!!Connect Wallet', }, connectWalletAuthRequest: { - id: 'ergo-connector.label.connectWalletAuthRequest', + id: 'connector.label.connectWalletAuthRequest', defaultMessage: '!!!The dApp requests to use your wallet identity for authentication. Enter your spending password to confirm.', }, connectWalletNoHardwareSupported: { - id: 'ergo-connector.label.connectWalletNoHardwareSupported', + id: 'connector.label.connectWalletNoHardwareSupported', defaultMessage: '!!!Note, hardware wallets are not supported for the dapp connecting yet.', }, yourWallets: { - id: 'ergo-connector.label.yourWallets', + id: 'connector.label.yourWallets', defaultMessage: '!!!Your Wallets', }, selectAllWallets: { - id: 'ergo-connector.label.selectAllWallets', + id: 'connector.label.selectAllWallets', defaultMessage: '!!!Select all wallets', }, connectInfo: { - id: 'ergo-connector.connect.info', + id: 'connector.connect.info', defaultMessage: '!!!Your connection preferences will be saved to your Yoroi dApp list.', }, noWalletsFound: { - id: 'ergo-connector.connect.noWalletsFound', + id: 'connector.connect.noWalletsFound', defaultMessage: '!!!Ooops, no {network} wallets found', }, incorrectWalletPasswordError: { @@ -69,7 +69,7 @@ const messages = defineMessages({ defaultMessage: '!!!Incorrect wallet password.', }, createWallet: { - id: 'ergo-connector.connect.createWallet', + id: 'connector.connect.createWallet', defaultMessage: '!!!create wallet', }, }); diff --git a/packages/yoroi-extension/app/i18n/locales/cs-CZ.json b/packages/yoroi-extension/app/i18n/locales/cs-CZ.json index 057298ffe5..7de349255b 100644 --- a/packages/yoroi-extension/app/i18n/locales/cs-CZ.json +++ b/packages/yoroi-extension/app/i18n/locales/cs-CZ.json @@ -74,10 +74,10 @@ "daedalusTransfer.waiting.title.label": "Daedalus wallet is being restored", "daedalusTransfer.waiting.warning": "This may take a long time or fail on poor internet connections", "decryption.label": "Decryption password", - "ergo-connector.connect.info": "Your connection preferences will be saved to your Yoroi dApp list.", - "ergo-connector.connect.noWalletsFound": "No wallets found", - "ergo-connector.label.connect": "Connect to", - "ergo-connector.label.selectAllWallets": "Select all wallets", + "connector.connect.info": "Your connection preferences will be saved to your Yoroi dApp list.", + "connector.connect.noWalletsFound": "No wallets found", + "connector.label.connect": "Connect to", + "connector.label.selectAllWallets": "Select all wallets", "global.blog.learnMore": "You can read our {blogLink} to learn more.", "global.connector.connectedWebsites": "Connected Websites", "global.connector.messageReadOnly": "We are granting read-only to view utxos/addresses.", diff --git a/packages/yoroi-extension/app/i18n/locales/el-GR.json b/packages/yoroi-extension/app/i18n/locales/el-GR.json index ee57fa9108..10783cc010 100644 --- a/packages/yoroi-extension/app/i18n/locales/el-GR.json +++ b/packages/yoroi-extension/app/i18n/locales/el-GR.json @@ -74,10 +74,10 @@ "daedalusTransfer.waiting.title.label": "Γίνεται επαναφορά του πορτοφολιού Daedalus", "daedalusTransfer.waiting.warning": "Αυτό ίσως χρειαστεί αρκετή ώρα ή ίσως αποτύχει σε περιπτώσεις κακής σύνδεσης στο διαδίκτυο", "decryption.label": "Decryption password", - "ergo-connector.connect.info": "Your connection preferences will be saved to your Yoroi dApp list.", - "ergo-connector.connect.noWalletsFound": "No wallets found", - "ergo-connector.label.connect": "Connect to", - "ergo-connector.label.selectAllWallets": "Select all wallets", + "connector.connect.info": "Your connection preferences will be saved to your Yoroi dApp list.", + "connector.connect.noWalletsFound": "No wallets found", + "connector.label.connect": "Connect to", + "connector.label.selectAllWallets": "Select all wallets", "global.blog.learnMore": "You can read our {blogLink} to learn more.", "global.connector.connectedWebsites": "Connected Websites", "global.connector.messageReadOnly": "We are granting read-only to view utxos/addresses.", diff --git a/packages/yoroi-extension/app/i18n/locales/en-US.json b/packages/yoroi-extension/app/i18n/locales/en-US.json index a4bf0bc24c..763cbf1f71 100644 --- a/packages/yoroi-extension/app/i18n/locales/en-US.json +++ b/packages/yoroi-extension/app/i18n/locales/en-US.json @@ -99,15 +99,15 @@ "daedalusTransfer.waiting.warning": "This may take a long time or fail on poor internet connections", "decryption.label": "Decryption password", "connector.signIn.tabs.utxoAddreses": "UTXO addresses", - "ergo-connector.connect.info": "Your connection preferences will be saved to your Yoroi dApp list.", - "ergo-connector.connect.noWalletsFound": "Ooops, no {network} wallets found.", - "ergo-connector.connect.createWallet": "create wallet", - "ergo-connector.label.connect": "Connect to", - "ergo-connector.label.connectWallet": "Connect Wallet", - "ergo-connector.label.connectWalletAuthRequest": "Enter your spending password to allow the dApp to identify you via your wallet", - "ergo-connector.label.connectWalletNoHardwareSupported": "Note, hardware wallets are not supported for the dapp connecting yet.", - "ergo-connector.label.selectAllWallets": "Select all wallets", - "ergo-connector.label.yourWallets": "Your Wallets", + "connector.connect.info": "Your connection preferences will be saved to your Yoroi dApp list.", + "connector.connect.noWalletsFound": "Ooops, no {network} wallets found.", + "connector.connect.createWallet": "create wallet", + "connector.label.connect": "Connect to", + "connector.label.connectWallet": "Connect Wallet", + "connector.label.connectWalletAuthRequest": "Enter your spending password to allow the dApp to identify you via your wallet", + "connector.label.connectWalletNoHardwareSupported": "Note, hardware wallets are not supported for the dapp connecting yet.", + "connector.label.selectAllWallets": "Select all wallets", + "connector.label.yourWallets": "Your Wallets", "global.blog.learnMore": "You can read our {blogLink} to learn more.", "global.labels.minAda": "Min-ADA", "global.connector.connectedWebsites": "Connected Websites", diff --git a/packages/yoroi-extension/app/i18n/locales/es-ES.json b/packages/yoroi-extension/app/i18n/locales/es-ES.json index 220b391d1a..20b3c3399b 100644 --- a/packages/yoroi-extension/app/i18n/locales/es-ES.json +++ b/packages/yoroi-extension/app/i18n/locales/es-ES.json @@ -74,10 +74,10 @@ "daedalusTransfer.waiting.title.label": "La billetera de Daedalus está siendo restaurada", "daedalusTransfer.waiting.warning": "Esto puede tomar algo de tiempo (o fallar) si la conexión a Internet es deficiente", "decryption.label": "Contraseña de descifrado", - "ergo-connector.connect.info": "Tus preferencias de conexión se guardarán en tu lista de dApps de Yoroi.", - "ergo-connector.connect.noWalletsFound": "Ninguna billetera encontrada", - "ergo-connector.label.connect": "Conectarse a", - "ergo-connector.label.selectAllWallets": "Seleccionar todas las billeteras", + "connector.connect.info": "Tus preferencias de conexión se guardarán en tu lista de dApps de Yoroi.", + "connector.connect.noWalletsFound": "Ninguna billetera encontrada", + "connector.label.connect": "Conectarse a", + "connector.label.selectAllWallets": "Seleccionar todas las billeteras", "global.blog.learnMore": "Puedes leer nuestro {blogLink} para conocer más.", "global.connector.connectedWebsites": "Páginas web conectadas", "global.connector.messageReadOnly": "Estamos concediendo solo permiso de lectura para ver utxos/direcciones.", diff --git a/packages/yoroi-extension/app/i18n/locales/fr-FR.json b/packages/yoroi-extension/app/i18n/locales/fr-FR.json index c076525099..b72ff5f21d 100644 --- a/packages/yoroi-extension/app/i18n/locales/fr-FR.json +++ b/packages/yoroi-extension/app/i18n/locales/fr-FR.json @@ -74,10 +74,10 @@ "daedalusTransfer.waiting.title.label": "Le wallet Daedalus est en cours de récupération", "daedalusTransfer.waiting.warning": "Cela peut prendre du temps ou échouer si vous avez une mauvaise connexion internet", "decryption.label": "Mot de passe de déchiffrage", - "ergo-connector.connect.info": "Vos préférences de connexion seront enregistrées dans votre liste Yoroi dApp.", - "ergo-connector.connect.noWalletsFound": "Pas de portefeuilles trouvés", - "ergo-connector.label.connect": "Se connecter à", - "ergo-connector.label.selectAllWallets": "Sélectionner tous les portefeuilles", + "connector.connect.info": "Vos préférences de connexion seront enregistrées dans votre liste Yoroi dApp.", + "connector.connect.noWalletsFound": "Pas de portefeuilles trouvés", + "connector.label.connect": "Se connecter à", + "connector.label.selectAllWallets": "Sélectionner tous les portefeuilles", "global.blog.learnMore": "Pour en savoir plus, vous pouvez lire notre {blogLink}.", "global.connector.connectedWebsites": "Sites web connectés", "global.connector.messageReadOnly": "Nous accordons la possibilité de consulter les utxos/adresses en lecture seule.", diff --git a/packages/yoroi-extension/app/i18n/locales/hr-HR.json b/packages/yoroi-extension/app/i18n/locales/hr-HR.json index 010e48fa84..395aa1d88d 100644 --- a/packages/yoroi-extension/app/i18n/locales/hr-HR.json +++ b/packages/yoroi-extension/app/i18n/locales/hr-HR.json @@ -74,10 +74,10 @@ "daedalusTransfer.waiting.title.label": "Daedalus wallet is being restored", "daedalusTransfer.waiting.warning": "This may take a long time or fail on poor internet connections", "decryption.label": "Decryption password", - "ergo-connector.connect.info": "Your connection preferences will be saved to your Yoroi dApp list.", - "ergo-connector.connect.noWalletsFound": "No wallets found", - "ergo-connector.label.connect": "Connect to", - "ergo-connector.label.selectAllWallets": "Select all wallets", + "connector.connect.info": "Your connection preferences will be saved to your Yoroi dApp list.", + "connector.connect.noWalletsFound": "No wallets found", + "connector.label.connect": "Connect to", + "connector.label.selectAllWallets": "Select all wallets", "global.blog.learnMore": "You can read our {blogLink} to learn more.", "global.connector.connectedWebsites": "Connected Websites", "global.connector.messageReadOnly": "We are granting read-only to view utxos/addresses.", diff --git a/packages/yoroi-extension/app/i18n/locales/id-ID.json b/packages/yoroi-extension/app/i18n/locales/id-ID.json index d2e53cfd13..c577241dfc 100644 --- a/packages/yoroi-extension/app/i18n/locales/id-ID.json +++ b/packages/yoroi-extension/app/i18n/locales/id-ID.json @@ -74,10 +74,10 @@ "daedalusTransfer.waiting.title.label": "Wallet Daedalus sedang dipulihkan", "daedalusTransfer.waiting.warning": "Ini mungkin akan memakan waktu lama atau akan gagal ketika koneksi internet buruk", "decryption.label": "Decryption password", - "ergo-connector.connect.info": "Your connection preferences will be saved to your Yoroi dApp list.", - "ergo-connector.connect.noWalletsFound": "No wallets found", - "ergo-connector.label.connect": "Connect to", - "ergo-connector.label.selectAllWallets": "Select all wallets", + "connector.connect.info": "Your connection preferences will be saved to your Yoroi dApp list.", + "connector.connect.noWalletsFound": "No wallets found", + "connector.label.connect": "Connect to", + "connector.label.selectAllWallets": "Select all wallets", "global.blog.learnMore": "You can read our {blogLink} to learn more.", "global.connector.connectedWebsites": "Connected Websites", "global.connector.messageReadOnly": "We are granting read-only to view utxos/addresses.", diff --git a/packages/yoroi-extension/app/i18n/locales/it-IT.json b/packages/yoroi-extension/app/i18n/locales/it-IT.json index 5d3ff93c07..fc326c2271 100644 --- a/packages/yoroi-extension/app/i18n/locales/it-IT.json +++ b/packages/yoroi-extension/app/i18n/locales/it-IT.json @@ -74,10 +74,10 @@ "daedalusTransfer.waiting.title.label": "Il portafoglio Daedalus è in fase di ripristino", "daedalusTransfer.waiting.warning": "Questo potrebbe richiedere tempi lunghi o anche fallire su connessioni lente", "decryption.label": "Decodifica password", - "ergo-connector.connect.info": "Your connection preferences will be saved to your Yoroi dApp list.", - "ergo-connector.connect.noWalletsFound": "No wallets found", - "ergo-connector.label.connect": "Connect to", - "ergo-connector.label.selectAllWallets": "Select all wallets", + "connector.connect.info": "Your connection preferences will be saved to your Yoroi dApp list.", + "connector.connect.noWalletsFound": "No wallets found", + "connector.label.connect": "Connect to", + "connector.label.selectAllWallets": "Select all wallets", "global.blog.learnMore": "Potete leggere il nostro {blogLink} per saperne di più.", "global.connector.connectedWebsites": "Connected Websites", "global.connector.messageReadOnly": "We are granting read-only to view utxos/addresses.", diff --git a/packages/yoroi-extension/app/i18n/locales/ja-JP.json b/packages/yoroi-extension/app/i18n/locales/ja-JP.json index 97de7c3656..54f2a9a4a2 100644 --- a/packages/yoroi-extension/app/i18n/locales/ja-JP.json +++ b/packages/yoroi-extension/app/i18n/locales/ja-JP.json @@ -74,10 +74,10 @@ "daedalusTransfer.waiting.title.label": "ダイダロスウォレットを復元中です...", "daedalusTransfer.waiting.warning": "ネットワーク環境が不安定の場合は時間がかかる場合があります", "decryption.label": "Decryption password", - "ergo-connector.connect.info": "Your connection preferences will be saved to your Yoroi dApp list.", - "ergo-connector.connect.noWalletsFound": "No wallets found", - "ergo-connector.label.connect": "Connect to", - "ergo-connector.label.selectAllWallets": "Select all wallets", + "connector.connect.info": "Your connection preferences will be saved to your Yoroi dApp list.", + "connector.connect.noWalletsFound": "No wallets found", + "connector.label.connect": "Connect to", + "connector.label.selectAllWallets": "Select all wallets", "global.blog.learnMore": "You can read our {blogLink} to learn more.", "global.connector.connectedWebsites": "Connected Websites", "global.connector.messageReadOnly": "We are granting read-only to view utxos/addresses.", diff --git a/packages/yoroi-extension/app/i18n/locales/ko-KR.json b/packages/yoroi-extension/app/i18n/locales/ko-KR.json index a6f4fb82b8..b4a0e77f4a 100644 --- a/packages/yoroi-extension/app/i18n/locales/ko-KR.json +++ b/packages/yoroi-extension/app/i18n/locales/ko-KR.json @@ -74,10 +74,10 @@ "daedalusTransfer.waiting.title.label": "Daedalus 지갑 복원 중...", "daedalusTransfer.waiting.warning": "이것은 인터넷 연결이 좋지 않을 경우 시간이 오래 걸리거나 실패할 수 있습니다.", "decryption.label": "Decryption password", - "ergo-connector.connect.info": "Your connection preferences will be saved to your Yoroi dApp list.", - "ergo-connector.connect.noWalletsFound": "No wallets found", - "ergo-connector.label.connect": "Connect to", - "ergo-connector.label.selectAllWallets": "Select all wallets", + "connector.connect.info": "Your connection preferences will be saved to your Yoroi dApp list.", + "connector.connect.noWalletsFound": "No wallets found", + "connector.label.connect": "Connect to", + "connector.label.selectAllWallets": "Select all wallets", "global.blog.learnMore": "You can read our {blogLink} to learn more.", "global.connector.connectedWebsites": "Connected Websites", "global.connector.messageReadOnly": "We are granting read-only to view utxos/addresses.", diff --git a/packages/yoroi-extension/app/i18n/locales/nl-NL.json b/packages/yoroi-extension/app/i18n/locales/nl-NL.json index 0b1a8f80cb..14d4dcf480 100644 --- a/packages/yoroi-extension/app/i18n/locales/nl-NL.json +++ b/packages/yoroi-extension/app/i18n/locales/nl-NL.json @@ -74,10 +74,10 @@ "daedalusTransfer.waiting.title.label": "De Daedalus portemonnee wordt hersteld", "daedalusTransfer.waiting.warning": "Dit kan lang duren of zelfs mislukken bij een slechte internetverbinding", "decryption.label": "Decoderingswachtwoord", - "ergo-connector.connect.info": "Your connection preferences will be saved to your Yoroi dApp list.", - "ergo-connector.connect.noWalletsFound": "No wallets found", - "ergo-connector.label.connect": "Connect to", - "ergo-connector.label.selectAllWallets": "Select all wallets", + "connector.connect.info": "Your connection preferences will be saved to your Yoroi dApp list.", + "connector.connect.noWalletsFound": "No wallets found", + "connector.label.connect": "Connect to", + "connector.label.selectAllWallets": "Select all wallets", "global.blog.learnMore": "U kunt onze {blogLink} lezen voor meer informatie.", "global.connector.connectedWebsites": "Verbonden websites", "global.connector.messageReadOnly": "U kunt utxos/addressen alleen bekijken.", diff --git a/packages/yoroi-extension/app/i18n/locales/pt-BR.json b/packages/yoroi-extension/app/i18n/locales/pt-BR.json index 26b9388898..f49d510fac 100644 --- a/packages/yoroi-extension/app/i18n/locales/pt-BR.json +++ b/packages/yoroi-extension/app/i18n/locales/pt-BR.json @@ -74,10 +74,10 @@ "daedalusTransfer.waiting.title.label": "Carteira Daedalus está sendo restaurada", "daedalusTransfer.waiting.warning": "Isso pode levar muito tempo ou falhar em conexões de baixa qualidade", "decryption.label": "Senha de decifração", - "ergo-connector.connect.info": "Your connection preferences will be saved to your Yoroi dApp list.", - "ergo-connector.connect.noWalletsFound": "No wallets found", - "ergo-connector.label.connect": "Connect to", - "ergo-connector.label.selectAllWallets": "Select all wallets", + "connector.connect.info": "Your connection preferences will be saved to your Yoroi dApp list.", + "connector.connect.noWalletsFound": "No wallets found", + "connector.label.connect": "Connect to", + "connector.label.selectAllWallets": "Select all wallets", "global.blog.learnMore": "Você pode ler nosso {blogLink} para saber mais.", "global.connector.connectedWebsites": "Connected Websites", "global.connector.messageReadOnly": "We are granting read-only to view utxos/addresses.", diff --git a/packages/yoroi-extension/app/i18n/locales/ru-RU.json b/packages/yoroi-extension/app/i18n/locales/ru-RU.json index c9900d60d9..78e5531f68 100644 --- a/packages/yoroi-extension/app/i18n/locales/ru-RU.json +++ b/packages/yoroi-extension/app/i18n/locales/ru-RU.json @@ -74,10 +74,10 @@ "daedalusTransfer.waiting.title.label": "Кошелек Daedalus восстанавливается", "daedalusTransfer.waiting.warning": "Это может занять много времени или потерпеть неудачу при плохом интернет-соединении", "decryption.label": "Decryption password", - "ergo-connector.connect.info": "Your connection preferences will be saved to your Yoroi dApp list.", - "ergo-connector.connect.noWalletsFound": "No wallets found", - "ergo-connector.label.connect": "Connect to", - "ergo-connector.label.selectAllWallets": "Select all wallets", + "connector.connect.info": "Your connection preferences will be saved to your Yoroi dApp list.", + "connector.connect.noWalletsFound": "No wallets found", + "connector.label.connect": "Connect to", + "connector.label.selectAllWallets": "Select all wallets", "global.blog.learnMore": "You can read our {blogLink} to learn more.", "global.connector.connectedWebsites": "Connected Websites", "global.connector.messageReadOnly": "We are granting read-only to view utxos/addresses.", diff --git a/packages/yoroi-extension/app/i18n/locales/sk-SK.json b/packages/yoroi-extension/app/i18n/locales/sk-SK.json index b3d54cc43c..dae22b21c3 100644 --- a/packages/yoroi-extension/app/i18n/locales/sk-SK.json +++ b/packages/yoroi-extension/app/i18n/locales/sk-SK.json @@ -74,10 +74,10 @@ "daedalusTransfer.waiting.title.label": "Daedalus wallet is being restored", "daedalusTransfer.waiting.warning": "This may take a long time or fail on poor internet connections", "decryption.label": "Decryption password", - "ergo-connector.connect.info": "Your connection preferences will be saved to your Yoroi dApp list.", - "ergo-connector.connect.noWalletsFound": "No wallets found", - "ergo-connector.label.connect": "Connect to", - "ergo-connector.label.selectAllWallets": "Select all wallets", + "connector.connect.info": "Your connection preferences will be saved to your Yoroi dApp list.", + "connector.connect.noWalletsFound": "No wallets found", + "connector.label.connect": "Connect to", + "connector.label.selectAllWallets": "Select all wallets", "global.blog.learnMore": "You can read our {blogLink} to learn more.", "global.connector.connectedWebsites": "Connected Websites", "global.connector.messageReadOnly": "We are granting read-only to view utxos/addresses.", diff --git a/packages/yoroi-extension/app/i18n/locales/tr-TR.json b/packages/yoroi-extension/app/i18n/locales/tr-TR.json index 65caeb6c2b..0373595442 100644 --- a/packages/yoroi-extension/app/i18n/locales/tr-TR.json +++ b/packages/yoroi-extension/app/i18n/locales/tr-TR.json @@ -74,10 +74,10 @@ "daedalusTransfer.waiting.title.label": "Daedalus cüzdanı geri yükleniyor", "daedalusTransfer.waiting.warning": "Bu, zayıf internet bağlantısıyla uzun zaman alabilir veya başarısız olabilir", "decryption.label": "Şifre çözme şifresi", - "ergo-connector.connect.info": "Your connection preferences will be saved to your Yoroi dApp list.", - "ergo-connector.connect.noWalletsFound": "No wallets found", - "ergo-connector.label.connect": "Connect to", - "ergo-connector.label.selectAllWallets": "Select all wallets", + "connector.connect.info": "Your connection preferences will be saved to your Yoroi dApp list.", + "connector.connect.noWalletsFound": "No wallets found", + "connector.label.connect": "Connect to", + "connector.label.selectAllWallets": "Select all wallets", "global.blog.learnMore": "Daha fazla bilgi edinmek için {blogLink} sayfasına bakabilirsiniz.", "global.connector.connectedWebsites": "Connected Websites", "global.connector.messageReadOnly": "We are granting read-only to view utxos/addresses.", diff --git a/packages/yoroi-extension/app/i18n/locales/zh-Hans.json b/packages/yoroi-extension/app/i18n/locales/zh-Hans.json index 2006e6cb55..d8b994a4b1 100644 --- a/packages/yoroi-extension/app/i18n/locales/zh-Hans.json +++ b/packages/yoroi-extension/app/i18n/locales/zh-Hans.json @@ -74,10 +74,10 @@ "daedalusTransfer.waiting.title.label": "正在恢复 Daedalus 钱包...", "daedalusTransfer.waiting.warning": "这会花费较长时间,网络不佳可能失败", "decryption.label": "解密密码", - "ergo-connector.connect.info": "你的连接设置会保存在Yoroi dApp列表中", - "ergo-connector.connect.noWalletsFound": "未找到钱包", - "ergo-connector.label.connect": "已连接", - "ergo-connector.label.selectAllWallets": "选择所有钱包", + "connector.connect.info": "你的连接设置会保存在Yoroi dApp列表中", + "connector.connect.noWalletsFound": "未找到钱包", + "connector.label.connect": "已连接", + "connector.label.selectAllWallets": "选择所有钱包", "global.blog.learnMore": "您可以阅读我们的{blogLink} 以了解更多。", "global.connector.connectedWebsites": "已连接的网站", "global.connector.messageReadOnly": "We are granting read-only to view utxos/addresses.", diff --git a/packages/yoroi-extension/app/i18n/locales/zh-Hant.json b/packages/yoroi-extension/app/i18n/locales/zh-Hant.json index 92ecc3cc5c..c031966b0b 100644 --- a/packages/yoroi-extension/app/i18n/locales/zh-Hant.json +++ b/packages/yoroi-extension/app/i18n/locales/zh-Hant.json @@ -74,10 +74,10 @@ "daedalusTransfer.waiting.title.label": "正在還原 Daedalus 錢包...", "daedalusTransfer.waiting.warning": "這可能需要很長時間,或在互聯網連接不良時失敗", "decryption.label": "Decryption password", - "ergo-connector.connect.info": "Your connection preferences will be saved to your Yoroi dApp list.", - "ergo-connector.connect.noWalletsFound": "No wallets found", - "ergo-connector.label.connect": "Connect to", - "ergo-connector.label.selectAllWallets": "Select all wallets", + "connector.connect.info": "Your connection preferences will be saved to your Yoroi dApp list.", + "connector.connect.noWalletsFound": "No wallets found", + "connector.label.connect": "Connect to", + "connector.label.selectAllWallets": "Select all wallets", "global.blog.learnMore": "You can read our {blogLink} to learn more.", "global.connector.connectedWebsites": "Connected Websites", "global.connector.messageReadOnly": "We are granting read-only to view utxos/addresses.", From 326f67ccf18253308437c08057bc2140b1a1859d Mon Sep 17 00:00:00 2001 From: Ahmed Ibrahim Date: Mon, 17 Oct 2022 13:51:14 +0200 Subject: [PATCH 012/172] Rename ergoConnectorExtensionId to 'connectorExtensionId' --- packages/yoroi-connector/README.md | 4 ++-- packages/yoroi-extension/app/environment.js | 4 ++-- packages/yoroi-extension/app/i18n/locales/de-DE.json | 8 ++++---- .../yoroi-extension/chrome/extension/background.js | 4 ++-- packages/yoroi-extension/package.json | 6 +++--- packages/yoroi-extension/scripts/build.js | 2 +- packages/yoroi-extension/webpack/commonConfig.js | 10 +++++----- packages/yoroi-extension/webpack/devConfig.js | 4 ++-- packages/yoroi-extension/webpack/prodConfig.js | 4 ++-- 9 files changed, 23 insertions(+), 23 deletions(-) diff --git a/packages/yoroi-connector/README.md b/packages/yoroi-connector/README.md index d7eca7adac..91a77c78ee 100644 --- a/packages/yoroi-connector/README.md +++ b/packages/yoroi-connector/README.md @@ -9,7 +9,7 @@ The implementation will follow our [EIP-0012](https://github.com/ergoplatform/ei 1. Run the Yoroi Extension and get its extension ID 1. Use `npm run prod:custom -- --yoroiExtensionId=extension-id-here` 1. Select "load unpacked" in your browser and select the build folder (or ZIP file also works in prod/nightly builds) -1. Note the extension ID of the connector extension. Now, when you re-build Yoroi passing `--ergoConnectorExtensionId=connector-extension-id-here` as a build argument. -Example: `npm run dev:stable -- --ergoConnectorExtensionId=ebnncddeiookdmpglbhiamljhpdgbjcm` +1. Note the extension ID of the connector extension. Now, when you re-build Yoroi passing `--connectorExtensionId=connector-extension-id-here` as a build argument. +Example: `npm run dev:stable -- --connectorExtensionId=ebnncddeiookdmpglbhiamljhpdgbjcm` 1. Build the example project in the `example` folder (`npm install && npm run start`) 1. Open the page from the example project diff --git a/packages/yoroi-extension/app/environment.js b/packages/yoroi-extension/app/environment.js index e375c84103..08eb9added 100644 --- a/packages/yoroi-extension/app/environment.js +++ b/packages/yoroi-extension/app/environment.js @@ -41,7 +41,7 @@ export const environment = (( getWalletRefreshInterval: () => CONFIG.app.walletRefreshInterval, getServerStatusRefreshInterval: () => CONFIG.app.serverStatusRefreshInterval, userAgentInfo, - ergoConnectorExtensionId: process.env.ERGO_CONNECTOR_EXTENSION_ID ?? '', + connectorExtensionId: process.env.CONNECTOR_EXTENSION_ID ?? '', } ): { getNetworkName: void => Network, @@ -58,7 +58,7 @@ export const environment = (( getWalletRefreshInterval: void => number, getServerStatusRefreshInterval: void => number, userAgentInfo: UserAgentInfo, - ergoConnectorExtensionId: string, + connectorExtensionId: string, isLight: boolean, ... }); diff --git a/packages/yoroi-extension/app/i18n/locales/de-DE.json b/packages/yoroi-extension/app/i18n/locales/de-DE.json index 009bc2d244..a74d9e93e0 100644 --- a/packages/yoroi-extension/app/i18n/locales/de-DE.json +++ b/packages/yoroi-extension/app/i18n/locales/de-DE.json @@ -74,10 +74,10 @@ "daedalusTransfer.waiting.title.label": "Daedalus Wallet wird wiederhergestellt", "daedalusTransfer.waiting.warning": "Dies kann lange dauern oder bei schlechten Internet-Verbindungen fehlschlagen", "decryption.label": "Entschlüsselungs-Kennwort", - "ergo-connector.connect.info": "Your connection preferences will be saved to your Yoroi dApp list.", - "ergo-connector.connect.noWalletsFound": "No wallets found", - "ergo-connector.label.connect": "Connect to", - "ergo-connector.label.selectAllWallets": "Select all wallets", + "connector.connect.info": "Your connection preferences will be saved to your Yoroi dApp list.", + "connector.connect.noWalletsFound": "No wallets found", + "connector.label.connect": "Connect to", + "connector.label.selectAllWallets": "Select all wallets", "global.blog.learnMore": "Mehr darüber kannst Du in unserem {blogLink} lesen.", "global.connector.connectedWebsites": "Verbundene Webseiten", "global.connector.messageReadOnly": "Wir gewähren Lesezugriff um die utxos/Adressen zu sehen.", diff --git a/packages/yoroi-extension/chrome/extension/background.js b/packages/yoroi-extension/chrome/extension/background.js index 93ea399203..7a2158b815 100644 --- a/packages/yoroi-extension/chrome/extension/background.js +++ b/packages/yoroi-extension/chrome/extension/background.js @@ -820,7 +820,7 @@ async function confirmConnect( // generic communication to the entire connector chrome.runtime.onMessageExternal.addListener((message, sender) => { - if (sender.id === environment.ergoConnectorExtensionId) { + if (sender.id === environment.connectorExtensionId) { if (message.type === 'open_browseraction_menu') { chrome.windows.getLastFocused(currentWindow => { if (currentWindow == null) return; // should not happen @@ -838,7 +838,7 @@ chrome.runtime.onMessageExternal.addListener((message, sender) => { // per-page connection to injected code in the connector chrome.runtime.onConnectExternal.addListener(port => { - if (port.sender.id === environment.ergoConnectorExtensionId) { + if (port.sender.id === environment.connectorExtensionId) { handleInjectorConnect(port); } else { // disconnect? diff --git a/packages/yoroi-extension/package.json b/packages/yoroi-extension/package.json index 45ee260259..c995afecb1 100644 --- a/packages/yoroi-extension/package.json +++ b/packages/yoroi-extension/package.json @@ -16,11 +16,11 @@ "prod:compress": "babel-node ../../scripts/compress", "prod:unsigned": "npm run prod:build -- --env ${CARDANO_NETWORK:-testnet} && npm run prod:compress -- --env ${CARDANO_NETWORK:-testnet} --app-id yoroi-${CARDANO_NETWORK:-testnet} --zip-only --codebase https://yoroiwallet.com/dw/yoroi-${CARDANO_NETWORK:-testnet}-extension.crx", "prod:unsigned:light": "npm run prod:build:light -- --env ${CARDANO_NETWORK:-testnet} && npm run prod:compress -- --env ${CARDANO_NETWORK:-testnet} --app-id yoroi-${CARDANO_NETWORK:-testnet} --zip-only --codebase https://yoroiwallet.com/dw/yoroi-${CARDANO_NETWORK:-testnet}-extension.crx", - "prod:nightly": "npm run prod:build -- --env 'mainnet' --nightly --ergoConnectorExtensionId=chifollcalpmjdiokipacefnpmbgjnle && npm run -s prod:compress -- --env 'mainnet' --app-id 'yoroi-nightly' --zip-only --codebase 'https://yoroiwallet.com/dw/yoroi-nightly-extension.crx' --key \"'${YOROI_NIGHTLY_PEM:-./nightly-key.pem}'\"", - "prod:nightly:light": "npm run prod:build:light -- --env 'mainnet' --nightly --ergoConnectorExtensionId=chifollcalpmjdiokipacefnpmbgjnle && npm run -s prod:compress -- --env 'mainnet' --app-id 'yoroi-nightly' --zip-only --codebase 'https://yoroiwallet.com/dw/yoroi-nightly-extension.crx' --key \"'${YOROI_NIGHTLY_PEM:-./nightly-key.pem}'\"", + "prod:nightly": "npm run prod:build -- --env 'mainnet' --nightly --connectorExtensionId=chifollcalpmjdiokipacefnpmbgjnle && npm run -s prod:compress -- --env 'mainnet' --app-id 'yoroi-nightly' --zip-only --codebase 'https://yoroiwallet.com/dw/yoroi-nightly-extension.crx' --key \"'${YOROI_NIGHTLY_PEM:-./nightly-key.pem}'\"", + "prod:nightly:light": "npm run prod:build:light -- --env 'mainnet' --nightly --connectorExtensionId=chifollcalpmjdiokipacefnpmbgjnle && npm run -s prod:compress -- --env 'mainnet' --app-id 'yoroi-nightly' --zip-only --codebase 'https://yoroiwallet.com/dw/yoroi-nightly-extension.crx' --key \"'${YOROI_NIGHTLY_PEM:-./nightly-key.pem}'\"", "prod:stable": "npm run prod:build -- --env 'mainnet' && npm run prod:compress -- --env 'mainnet' --app-id 'yoroi' --zip-only --codebase 'https://yoroiwallet.com/dw/yoroi-extension.crx' --key ./production-key.pem", "prod:stable:light": "npm run prod:build:light -- --env 'mainnet' && npm run prod:compress -- --env 'mainnet' --app-id 'yoroi' --zip-only --codebase 'https://yoroiwallet.com/dw/yoroi-extension.crx' --key ./production-key.pem", - "prod:nightly-win": "npm run prod:build-win -- --env=mainnet --nightly --ergoConnectorExtensionId=chifollcalpmjdiokipacefnpmbgjnle && npm run -s prod:compress -- --env=mainnet --app-id=yoroi-nightly --zip-only --codebase=https://yoroiwallet.com/dw/yoroi-nightly-extension.crx --key=\"${YOROI_NIGHTLY_PEM:-./nightly-key.pem}\"", + "prod:nightly-win": "npm run prod:build-win -- --env=mainnet --nightly --connectorExtensionId=chifollcalpmjdiokipacefnpmbgjnle && npm run -s prod:compress -- --env=mainnet --app-id=yoroi-nightly --zip-only --codebase=https://yoroiwallet.com/dw/yoroi-nightly-extension.crx --key=\"${YOROI_NIGHTLY_PEM:-./nightly-key.pem}\"", "prod:stable-win": "npm run prod:build-win -- --env=mainnet && npm run prod:compress -- --env=mainnet --app-id=yoroi --zip-only --codebase=https://yoroiwallet.com/dw/yoroi-extension.crx --key=./production-key.pem", "keygen": "crx keygen", "clean": "rimraf build/ dev/ *.zip *.crx", diff --git a/packages/yoroi-extension/scripts/build.js b/packages/yoroi-extension/scripts/build.js index 99f7fadfc3..68c3f3af42 100644 --- a/packages/yoroi-extension/scripts/build.js +++ b/packages/yoroi-extension/scripts/build.js @@ -106,7 +106,7 @@ export function buildDev(env: string) { config.baseDevConfig( argv.env, isNightly, - argv.ergoConnectorExtensionId, + argv.connectorExtensionId, !shouldInjectConnector ), webpack, diff --git a/packages/yoroi-extension/webpack/commonConfig.js b/packages/yoroi-extension/webpack/commonConfig.js index 957389f3ac..7efc6448dc 100644 --- a/packages/yoroi-extension/webpack/commonConfig.js +++ b/packages/yoroi-extension/webpack/commonConfig.js @@ -213,11 +213,11 @@ const definePlugin = ( networkName /*: string */, isProd /*: boolean */, isNightly /*: boolean */, - ergoConnectorExtensionId /*: ?string */, + connectorExtensionId /*: ?string */, isLight /*: boolean */ = false ) /*: * */ => { - const ERGO_CONNECTOR_EXTENSION_ID = (() => { - if (ergoConnectorExtensionId != null) return ergoConnectorExtensionId; + const CONNECTOR_EXTENSION_ID = (() => { + if (connectorExtensionId != null) return connectorExtensionId; if (isNightly) return 'chifollcalpmjdiokipacefnpmbgjnle'; if (isProd) return 'ebnncddeiookdmpglbhiamljhpdgbjcm'; // TODO: real value for this @@ -225,7 +225,7 @@ const definePlugin = ( console.warn('Build has no connector ID set and so the connector will not work'); return ''; })(); - console.log(`dapp connector ID set to ${ERGO_CONNECTOR_EXTENSION_ID}`); + console.log(`dapp connector ID set to ${CONNECTOR_EXTENSION_ID}`); return { 'process.env': { @@ -234,7 +234,7 @@ const definePlugin = ( BRANCH: JSON.stringify(shell.exec('git rev-parse --abbrev-ref HEAD', { silent: true }).trim()), NIGHTLY: isNightly, POOLS_UI_URL_FOR_YOROI: JSON.stringify(manifestEnvs.POOLS_UI_URL_FOR_YOROI), - ERGO_CONNECTOR_EXTENSION_ID: JSON.stringify(ERGO_CONNECTOR_EXTENSION_ID), + CONNECTOR_EXTENSION_ID: JSON.stringify(CONNECTOR_EXTENSION_ID), IS_LIGHT: isLight , } }; diff --git a/packages/yoroi-extension/webpack/devConfig.js b/packages/yoroi-extension/webpack/devConfig.js index cc6f5d43d1..21eef25fc1 100644 --- a/packages/yoroi-extension/webpack/devConfig.js +++ b/packages/yoroi-extension/webpack/devConfig.js @@ -15,7 +15,7 @@ const hotScript = const baseDevConfig = ( networkName /*: string */, isNightly /*: boolean */, - ergoConnectorExtensionId /*: ?string */, + connectorExtensionId /*: ?string */, isLight /* : ?boolean */ = false ) /*: * */ => ({ mode: 'development', @@ -68,7 +68,7 @@ const baseDevConfig = ( networkName, false, isNightly, - ergoConnectorExtensionId, + connectorExtensionId, Boolean(isLight) )), new webpack.HotModuleReplacementPlugin(), diff --git a/packages/yoroi-extension/webpack/prodConfig.js b/packages/yoroi-extension/webpack/prodConfig.js index 9d1f7e15cb..3df959c870 100644 --- a/packages/yoroi-extension/webpack/prodConfig.js +++ b/packages/yoroi-extension/webpack/prodConfig.js @@ -14,7 +14,7 @@ type EnvParams = {| networkName: string, nightly: "true" | "false", publicPath?: string, - ergoConnectorExtensionId?: ?string, + connectorExtensionId?: ?string, isLight: "true" | "false" |}; */ @@ -53,7 +53,7 @@ const baseProdConfig = (env /*: EnvParams */) /*: * */ => ({ env.networkName, true, JSON.parse(env.nightly), - env.ergoConnectorExtensionId, + env.connectorExtensionId, JSON.parse(env.isLight) )), new webpack.IgnorePlugin(/[^/]+\/[\S]+.dev$/), From 23a72f4cf0677843455e157aebf74e4582974d7a Mon Sep 17 00:00:00 2001 From: Ahmed Ibrahim Date: Tue, 18 Oct 2022 13:22:42 +0200 Subject: [PATCH 013/172] Add connectorCall util --- .../ergo-connector/stores/ConnectorStore.js | 78 ++++++++----------- 1 file changed, 32 insertions(+), 46 deletions(-) diff --git a/packages/yoroi-extension/app/ergo-connector/stores/ConnectorStore.js b/packages/yoroi-extension/app/ergo-connector/stores/ConnectorStore.js index 93606e6ae0..8ac5e7d24b 100644 --- a/packages/yoroi-extension/app/ergo-connector/stores/ConnectorStore.js +++ b/packages/yoroi-extension/app/ergo-connector/stores/ConnectorStore.js @@ -19,6 +19,7 @@ import type { TxSignWindowRetrieveData, WhitelistEntry, GetUtxosRequest, + GetConnectionProtocolData, } from '../../../chrome/extension/ergo-connector/types'; import type { ActionsMap } from '../actions/index'; import type { StoresMap } from './index'; @@ -79,60 +80,45 @@ import type { IGetAllUtxosResponse } from '../../api/ada/lib/storage/models/Publ import type { IFetcher } from '../../api/ada/lib/state-fetch/IFetcher'; import type { NetworkRow } from '../../api/ada/lib/storage/database/primitives/tables'; -// Need to run only once - Connecting wallets -let initedConnecting = false; -function sendMsgConnect(): Promise { +function connectorCall(message: T): Promise { return new Promise((resolve, reject) => { - if (!initedConnecting) - window.chrome.runtime.sendMessage(( - { type: 'connect_retrieve_data' }: ConnectRetrieveData), - response => { - if (window.chrome.runtime.lastError) { - // eslint-disable-next-line prefer-promise-reject-errors - reject('Could not establish connection: connect_retrieve_data '); - } - - resolve(response); - initedConnecting = true; + window.chrome.runtime.sendMessage( + message, + response => { + if (window.chrome.runtime.lastError) { + // eslint-disable-next-line prefer-promise-reject-errors + reject(`Could not establish connection: ${JSON.stringify(typeof message === 'object' ? message : '')}`); } - ); - }); + resolve(response); + } + ); + }) +} + +// Need to run only once - Connecting wallets +let initedConnecting = false; +async function sendMsgConnect(): Promise { + if (!initedConnecting) { + const res = await connectorCall({ type: 'connect_retrieve_data' }) + initedConnecting = true + return res + } } // Need to run only once - Sign Tx Confirmation let initedSigning = false; -function sendMsgSigningTx(): Promise { - return new Promise((resolve, reject) => { - if (!initedSigning) - window.chrome.runtime.sendMessage( - ({ type: 'tx_sign_window_retrieve_data' }: TxSignWindowRetrieveData), - response => { - if (window.chrome.runtime.lastError) { - // eslint-disable-next-line prefer-promise-reject-errors - reject('Could not establish connection: connect_retrieve_data '); - } - - resolve(response); - initedSigning = true; - } - ); - }); +async function sendMsgSigningTx(): Promise { + if (!initedSigning) { + const res = await connectorCall({ + type: 'tx_sign_window_retrieve_data', + }); + initedSigning = true; + return res; + } } -export function getProtocol(): Promise { - return new Promise((resolve, reject) => { - window.chrome.runtime.sendMessage( - ({ type: 'get_protocol' }), - response => { - if (window.chrome.runtime.lastError) { - // eslint-disable-next-line prefer-promise-reject-errors - reject('Could not establish connection: get_protocol '); - } - - resolve(response); - } - ); - }); +export async function getProtocol(): Promise { + return connectorCall({ type: 'get_protocol' }) } export function getUtxosAndAddresses( From c43035a045f66750df8ae4c33f2e00d578816fef Mon Sep 17 00:00:00 2001 From: Ahmed Ibrahim Date: Tue, 18 Oct 2022 13:26:01 +0200 Subject: [PATCH 014/172] Update dapp connector store --- .../ergo-connector/stores/ConnectorStore.js | 2 +- .../app/stores/DappConnectorStore.js | 24 ++++++------------- 2 files changed, 8 insertions(+), 18 deletions(-) diff --git a/packages/yoroi-extension/app/ergo-connector/stores/ConnectorStore.js b/packages/yoroi-extension/app/ergo-connector/stores/ConnectorStore.js index 8ac5e7d24b..d99f45e476 100644 --- a/packages/yoroi-extension/app/ergo-connector/stores/ConnectorStore.js +++ b/packages/yoroi-extension/app/ergo-connector/stores/ConnectorStore.js @@ -80,7 +80,7 @@ import type { IGetAllUtxosResponse } from '../../api/ada/lib/storage/models/Publ import type { IFetcher } from '../../api/ada/lib/state-fetch/IFetcher'; import type { NetworkRow } from '../../api/ada/lib/storage/database/primitives/tables'; -function connectorCall(message: T): Promise { +export function connectorCall(message: T): Promise { return new Promise((resolve, reject) => { window.chrome.runtime.sendMessage( message, diff --git a/packages/yoroi-extension/app/stores/DappConnectorStore.js b/packages/yoroi-extension/app/stores/DappConnectorStore.js index d057fe833c..b5ce9be201 100644 --- a/packages/yoroi-extension/app/stores/DappConnectorStore.js +++ b/packages/yoroi-extension/app/stores/DappConnectorStore.js @@ -12,29 +12,19 @@ import type { } from '../../chrome/extension/ergo-connector/types'; import type { ActionsMap } from '../actions/index'; import type { StoresMap } from './index'; -import { getConnectedSites } from '../ergo-connector/stores/ConnectorStore'; +import { connectorCall, getConnectedSites } from '../ergo-connector/stores/ConnectorStore'; // Need to run only once - Connecting wallets let initedConnecting = false; -function sendMsgConnect(): Promise { - return new Promise((resolve, reject) => { - if (!initedConnecting) - window.chrome.runtime.sendMessage(( - { type: 'connect_retrieve_data' }: ConnectRetrieveData), - response => { - if (window.chrome.runtime.lastError) { - // eslint-disable-next-line prefer-promise-reject-errors - reject('Could not establish connection: connect_retrieve_data '); - } - resolve(response); - initedConnecting = true; - } - ); - }); +async function sendMsgConnect(): Promise { + if (!initedConnecting) { + const res = await connectorCall({ type: 'connect_retrieve_data' }) + initedConnecting = true + return res + } } - type GetWhitelistFunc = void => Promise>; type SetWhitelistFunc = {| whitelist: Array | void, From 70184de6a353d86e3fef9da434143a61b8a8a5dc Mon Sep 17 00:00:00 2001 From: Ahmed Ibrahim Date: Wed, 19 Oct 2022 12:38:49 +0200 Subject: [PATCH 015/172] Remove legacy code releated to passing the passing the extension Id --- packages/yoroi-connector/src/background.js | 126 ------------------ packages/yoroi-extension/app/environment.js | 2 - .../chrome/extension/background.js | 27 ---- packages/yoroi-extension/package.json | 6 +- packages/yoroi-extension/scripts/build.js | 1 - .../yoroi-extension/webpack/commonConfig.js | 13 -- packages/yoroi-extension/webpack/devConfig.js | 2 - .../yoroi-extension/webpack/prodConfig.js | 2 - 8 files changed, 3 insertions(+), 176 deletions(-) delete mode 100644 packages/yoroi-connector/src/background.js diff --git a/packages/yoroi-connector/src/background.js b/packages/yoroi-connector/src/background.js deleted file mode 100644 index d0c64b87a7..0000000000 --- a/packages/yoroi-connector/src/background.js +++ /dev/null @@ -1,126 +0,0 @@ -const onConnectorIconClicked = () => { - // note: we send a message instead of a browser action because the UI is managed by the Yoroi extension -- not be the connector - chrome.runtime.sendMessage(extensionId, { type: "open_browseraction_menu" }); -}; - -chrome.browserAction.onClicked.addListener(debounce(onConnectorIconClicked, 500, { leading: true })); - -/** - * This is a copy of debounce from the lodash library - * We inline it so that - * 1) we don't need the dependency - * 2) background scripts can't load modules (only background pages) - */ -function debounce(func, wait, options) { - let lastArgs, - lastThis, - maxWait, - result, - timerId, - lastCallTime - - let lastInvokeTime = 0 - let leading = options.leading - let trailing = true - - function invokeFunc(time) { - const args = lastArgs - const thisArg = lastThis - - lastArgs = lastThis = undefined - lastInvokeTime = time - result = func.apply(thisArg, args) - return result - } - - function startTimer(pendingFunc, wait) { - return setTimeout(pendingFunc, wait) - } - - function cancelTimer(id) { - clearTimeout(id) - } - - function leadingEdge(time) { - // Reset any `maxWait` timer. - lastInvokeTime = time - // Start the timer for the trailing edge. - timerId = startTimer(timerExpired, wait) - // Invoke the leading edge. - return leading ? invokeFunc(time) : result - } - - function remainingWait(time) { - const timeSinceLastCall = time - lastCallTime - const timeSinceLastInvoke = time - lastInvokeTime - const timeWaiting = wait - timeSinceLastCall - - return timeWaiting - } - - function shouldInvoke(time) { - const timeSinceLastCall = time - lastCallTime - const timeSinceLastInvoke = time - lastInvokeTime - - // Either this is the first call, activity has stopped and we're at the - // trailing edge, the system time has gone backwards and we're treating - // it as the trailing edge, or we've hit the `maxWait` limit. - return (lastCallTime === undefined || (timeSinceLastCall >= wait) || - (timeSinceLastCall < 0)) - } - - function timerExpired() { - const time = Date.now() - if (shouldInvoke(time)) { - return trailingEdge(time) - } - // Restart the timer. - timerId = startTimer(timerExpired, remainingWait(time)) - } - - function trailingEdge(time) { - timerId = undefined - - lastArgs = lastThis = undefined - return result - } - - function cancel() { - if (timerId !== undefined) { - cancelTimer(timerId) - } - lastInvokeTime = 0 - lastArgs = lastCallTime = lastThis = timerId = undefined - } - - function flush() { - return timerId === undefined ? result : trailingEdge(Date.now()) - } - - function pending() { - return timerId !== undefined - } - - function debounced(...args) { - const time = Date.now() - const isInvoking = shouldInvoke(time) - - lastArgs = args - lastThis = this - lastCallTime = time - - if (isInvoking) { - if (timerId === undefined) { - return leadingEdge(lastCallTime) - } - } - if (timerId === undefined) { - timerId = startTimer(timerExpired, wait) - } - return result - } - debounced.cancel = cancel - debounced.flush = flush - debounced.pending = pending - return debounced -} diff --git a/packages/yoroi-extension/app/environment.js b/packages/yoroi-extension/app/environment.js index 08eb9added..ce035f74ed 100644 --- a/packages/yoroi-extension/app/environment.js +++ b/packages/yoroi-extension/app/environment.js @@ -41,7 +41,6 @@ export const environment = (( getWalletRefreshInterval: () => CONFIG.app.walletRefreshInterval, getServerStatusRefreshInterval: () => CONFIG.app.serverStatusRefreshInterval, userAgentInfo, - connectorExtensionId: process.env.CONNECTOR_EXTENSION_ID ?? '', } ): { getNetworkName: void => Network, @@ -58,7 +57,6 @@ export const environment = (( getWalletRefreshInterval: void => number, getServerStatusRefreshInterval: void => number, userAgentInfo: UserAgentInfo, - connectorExtensionId: string, isLight: boolean, ... }); diff --git a/packages/yoroi-extension/chrome/extension/background.js b/packages/yoroi-extension/chrome/extension/background.js index 7a2158b815..3e4005b835 100644 --- a/packages/yoroi-extension/chrome/extension/background.js +++ b/packages/yoroi-extension/chrome/extension/background.js @@ -818,33 +818,6 @@ async function confirmConnect( }); } -// generic communication to the entire connector -chrome.runtime.onMessageExternal.addListener((message, sender) => { - if (sender.id === environment.connectorExtensionId) { - if (message.type === 'open_browseraction_menu') { - chrome.windows.getLastFocused(currentWindow => { - if (currentWindow == null) return; // should not happen - const bounds = getBoundsForWindow(currentWindow); - chrome.windows.create({ - ...popupProps, - url: chrome.extension.getURL(`/main_window_connector.html#/settings`), - left: (bounds.width + bounds.positionX) - popupProps.width, - top: bounds.positionY + 80, - }); - }); - } - } -}); - -// per-page connection to injected code in the connector -chrome.runtime.onConnectExternal.addListener(port => { - if (port.sender.id === environment.connectorExtensionId) { - handleInjectorConnect(port); - } else { - // disconnect? - } -}); - // per-page connection to injected code by Yoroi with connector chrome.runtime.onConnect.addListener(port => { handleInjectorConnect(port); diff --git a/packages/yoroi-extension/package.json b/packages/yoroi-extension/package.json index c995afecb1..7402c1d809 100644 --- a/packages/yoroi-extension/package.json +++ b/packages/yoroi-extension/package.json @@ -16,11 +16,11 @@ "prod:compress": "babel-node ../../scripts/compress", "prod:unsigned": "npm run prod:build -- --env ${CARDANO_NETWORK:-testnet} && npm run prod:compress -- --env ${CARDANO_NETWORK:-testnet} --app-id yoroi-${CARDANO_NETWORK:-testnet} --zip-only --codebase https://yoroiwallet.com/dw/yoroi-${CARDANO_NETWORK:-testnet}-extension.crx", "prod:unsigned:light": "npm run prod:build:light -- --env ${CARDANO_NETWORK:-testnet} && npm run prod:compress -- --env ${CARDANO_NETWORK:-testnet} --app-id yoroi-${CARDANO_NETWORK:-testnet} --zip-only --codebase https://yoroiwallet.com/dw/yoroi-${CARDANO_NETWORK:-testnet}-extension.crx", - "prod:nightly": "npm run prod:build -- --env 'mainnet' --nightly --connectorExtensionId=chifollcalpmjdiokipacefnpmbgjnle && npm run -s prod:compress -- --env 'mainnet' --app-id 'yoroi-nightly' --zip-only --codebase 'https://yoroiwallet.com/dw/yoroi-nightly-extension.crx' --key \"'${YOROI_NIGHTLY_PEM:-./nightly-key.pem}'\"", - "prod:nightly:light": "npm run prod:build:light -- --env 'mainnet' --nightly --connectorExtensionId=chifollcalpmjdiokipacefnpmbgjnle && npm run -s prod:compress -- --env 'mainnet' --app-id 'yoroi-nightly' --zip-only --codebase 'https://yoroiwallet.com/dw/yoroi-nightly-extension.crx' --key \"'${YOROI_NIGHTLY_PEM:-./nightly-key.pem}'\"", + "prod:nightly": "npm run prod:build -- --env 'mainnet' --nightly && npm run -s prod:compress -- --env 'mainnet' --app-id 'yoroi-nightly' --zip-only --codebase 'https://yoroiwallet.com/dw/yoroi-nightly-extension.crx' --key \"'${YOROI_NIGHTLY_PEM:-./nightly-key.pem}'\"", + "prod:nightly:light": "npm run prod:build:light -- --env 'mainnet' --nightly && npm run -s prod:compress -- --env 'mainnet' --app-id 'yoroi-nightly' --zip-only --codebase 'https://yoroiwallet.com/dw/yoroi-nightly-extension.crx' --key \"'${YOROI_NIGHTLY_PEM:-./nightly-key.pem}'\"", "prod:stable": "npm run prod:build -- --env 'mainnet' && npm run prod:compress -- --env 'mainnet' --app-id 'yoroi' --zip-only --codebase 'https://yoroiwallet.com/dw/yoroi-extension.crx' --key ./production-key.pem", "prod:stable:light": "npm run prod:build:light -- --env 'mainnet' && npm run prod:compress -- --env 'mainnet' --app-id 'yoroi' --zip-only --codebase 'https://yoroiwallet.com/dw/yoroi-extension.crx' --key ./production-key.pem", - "prod:nightly-win": "npm run prod:build-win -- --env=mainnet --nightly --connectorExtensionId=chifollcalpmjdiokipacefnpmbgjnle && npm run -s prod:compress -- --env=mainnet --app-id=yoroi-nightly --zip-only --codebase=https://yoroiwallet.com/dw/yoroi-nightly-extension.crx --key=\"${YOROI_NIGHTLY_PEM:-./nightly-key.pem}\"", + "prod:nightly-win": "npm run prod:build-win -- --env=mainnet --nightly && npm run -s prod:compress -- --env=mainnet --app-id=yoroi-nightly --zip-only --codebase=https://yoroiwallet.com/dw/yoroi-nightly-extension.crx --key=\"${YOROI_NIGHTLY_PEM:-./nightly-key.pem}\"", "prod:stable-win": "npm run prod:build-win -- --env=mainnet && npm run prod:compress -- --env=mainnet --app-id=yoroi --zip-only --codebase=https://yoroiwallet.com/dw/yoroi-extension.crx --key=./production-key.pem", "keygen": "crx keygen", "clean": "rimraf build/ dev/ *.zip *.crx", diff --git a/packages/yoroi-extension/scripts/build.js b/packages/yoroi-extension/scripts/build.js index 68c3f3af42..e7cf5aacb0 100644 --- a/packages/yoroi-extension/scripts/build.js +++ b/packages/yoroi-extension/scripts/build.js @@ -106,7 +106,6 @@ export function buildDev(env: string) { config.baseDevConfig( argv.env, isNightly, - argv.connectorExtensionId, !shouldInjectConnector ), webpack, diff --git a/packages/yoroi-extension/webpack/commonConfig.js b/packages/yoroi-extension/webpack/commonConfig.js index 7efc6448dc..24a7f0aa4c 100644 --- a/packages/yoroi-extension/webpack/commonConfig.js +++ b/packages/yoroi-extension/webpack/commonConfig.js @@ -213,20 +213,8 @@ const definePlugin = ( networkName /*: string */, isProd /*: boolean */, isNightly /*: boolean */, - connectorExtensionId /*: ?string */, isLight /*: boolean */ = false ) /*: * */ => { - const CONNECTOR_EXTENSION_ID = (() => { - if (connectorExtensionId != null) return connectorExtensionId; - - if (isNightly) return 'chifollcalpmjdiokipacefnpmbgjnle'; - if (isProd) return 'ebnncddeiookdmpglbhiamljhpdgbjcm'; // TODO: real value for this - - console.warn('Build has no connector ID set and so the connector will not work'); - return ''; - })(); - console.log(`dapp connector ID set to ${CONNECTOR_EXTENSION_ID}`); - return { 'process.env': { NODE_ENV: JSON.stringify(isProd ? 'production' : 'development'), @@ -234,7 +222,6 @@ const definePlugin = ( BRANCH: JSON.stringify(shell.exec('git rev-parse --abbrev-ref HEAD', { silent: true }).trim()), NIGHTLY: isNightly, POOLS_UI_URL_FOR_YOROI: JSON.stringify(manifestEnvs.POOLS_UI_URL_FOR_YOROI), - CONNECTOR_EXTENSION_ID: JSON.stringify(CONNECTOR_EXTENSION_ID), IS_LIGHT: isLight , } }; diff --git a/packages/yoroi-extension/webpack/devConfig.js b/packages/yoroi-extension/webpack/devConfig.js index 21eef25fc1..608dd79b9b 100644 --- a/packages/yoroi-extension/webpack/devConfig.js +++ b/packages/yoroi-extension/webpack/devConfig.js @@ -15,7 +15,6 @@ const hotScript = const baseDevConfig = ( networkName /*: string */, isNightly /*: boolean */, - connectorExtensionId /*: ?string */, isLight /* : ?boolean */ = false ) /*: * */ => ({ mode: 'development', @@ -68,7 +67,6 @@ const baseDevConfig = ( networkName, false, isNightly, - connectorExtensionId, Boolean(isLight) )), new webpack.HotModuleReplacementPlugin(), diff --git a/packages/yoroi-extension/webpack/prodConfig.js b/packages/yoroi-extension/webpack/prodConfig.js index 3df959c870..f6b1fb62bf 100644 --- a/packages/yoroi-extension/webpack/prodConfig.js +++ b/packages/yoroi-extension/webpack/prodConfig.js @@ -14,7 +14,6 @@ type EnvParams = {| networkName: string, nightly: "true" | "false", publicPath?: string, - connectorExtensionId?: ?string, isLight: "true" | "false" |}; */ @@ -53,7 +52,6 @@ const baseProdConfig = (env /*: EnvParams */) /*: * */ => ({ env.networkName, true, JSON.parse(env.nightly), - env.connectorExtensionId, JSON.parse(env.isLight) )), new webpack.IgnorePlugin(/[^/]+\/[\S]+.dev$/), From f393ac2235b0667f737fe135fa5763d5356a26ba Mon Sep 17 00:00:00 2001 From: vantuz-subhuman Date: Thu, 20 Oct 2022 18:44:26 +0300 Subject: [PATCH 016/172] tiny dapp example fix --- packages/yoroi-ergo-connector/example-cardano/index.js | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/packages/yoroi-ergo-connector/example-cardano/index.js b/packages/yoroi-ergo-connector/example-cardano/index.js index 8c36426acf..4e0b3da5f7 100644 --- a/packages/yoroi-ergo-connector/example-cardano/index.js +++ b/packages/yoroi-ergo-connector/example-cardano/index.js @@ -908,11 +908,7 @@ function toggleConnectionUI(status) { } } -const onload = window.onload; -window.onload = function () { - if (onload) { - onload(); - } +function onload() { if (typeof window.cardano === 'undefined') { alertError('Cardano API not found'); } else { @@ -933,4 +929,5 @@ window.onload = function () { } ); } -}; +} +setTimeout(onload, 1000); \ No newline at end of file From 6870a6f3daf75d957e6e00210f1f950f15990408 Mon Sep 17 00:00:00 2001 From: vantuz-subhuman Date: Tue, 25 Oct 2022 15:16:30 +0300 Subject: [PATCH 017/172] prototyping --- .../example-cardano/index.js | 122 ++++++++++++++++++ 1 file changed, 122 insertions(+) diff --git a/packages/yoroi-ergo-connector/example-cardano/index.js b/packages/yoroi-ergo-connector/example-cardano/index.js index 4e0b3da5f7..8470c7840f 100644 --- a/packages/yoroi-ergo-connector/example-cardano/index.js +++ b/packages/yoroi-ergo-connector/example-cardano/index.js @@ -908,7 +908,129 @@ function toggleConnectionUI(status) { } } +function bldr(b) { + return new Proxy(b, { + get(target, name, receiver) { + let rv = Reflect.get(target, name, receiver); + return typeof rv === 'function' ? (...args) => { + let res = rv.bind(b)(...args); + b.free(); + return name === 'build' ? res : bldr(res); + } : rv; + } + }); +} + +function WasmScope(cb) { + let scope = []; + function prox(x) { + return typeof x === 'object' || typeof x === 'function' ? new Proxy(x, { + get(target, name, receiver) { + let rv = Reflect.get(target, name, receiver); + if (typeof rv !== 'function' || rv.prototype != null) { + return prox(rv); + } + return function(...args) { + const res = rv.bind(x)(...args); + if (res.ptr != null && res.free != null) { + scope.push(res); + } + return prox(res); + } + } + }) : x; + } + let result = cb(prox(CardanoWasm)); + scope.forEach(x => x.free()); + return result; +} + +function wfree(...args) { + args.forEach(x => x.free()); +} + +function foo1() { + return WasmScope(Wasm => { + return Wasm.BigNum.from_str('1000000') + .checked_add(Wasm.BigNum.from_str('2000000')) + .to_str(); + }); +} + +function foo2() { + for (let i = 0; i < 1000; i++) { + setInterval(() => { + let arr = []; + for (let i = 0; i < 1000; i++) { + const a = CardanoWasm.BigNum.from_str('72'); + const b = CardanoWasm.BigNum.from_str('1000'); + const c = CardanoWasm.BigNum.from_str('172'); + const d = CardanoWasm.BigNum.from_str('10000'); + const e = CardanoWasm.UnitInterval.new(a, b); + const f = CardanoWasm.UnitInterval.new(c, d); + const g = CardanoWasm.BigNum.from_str('172000'); + const h = CardanoWasm.BigNum.from_str('123456'); + const i = CardanoWasm.BigNum.from_str('44000'); + const j = CardanoWasm.LinearFee.new(h, i); + const k = CardanoWasm.BigNum.from_str('2000000'); + const l = CardanoWasm.ExUnitPrices.new(e, f); + const m = CardanoWasm.BigNum.from_str('4000000'); + let config = bldr(CardanoWasm.TransactionBuilderConfigBuilder.new()) + .ex_unit_prices(l) + .coins_per_utxo_byte(g) + .fee_algo(j) + .key_deposit(k) + .pool_deposit(m) + .max_tx_size(123456765) + .max_value_size(123456765) + .build(); + let builder = CardanoWasm.TransactionBuilder.new(config); + arr.push(builder); + wfree(a, b, c, d, e, f, g, h, i, j, k, l, m, config); + } + console.log(arr.length); + arr.forEach(x => x.free()); + }, 1000); + } +} + +function foo3() { + for (let i = 0; i < 1000; i++) { + setInterval(() => { + WasmScope(CardanoWasm => { + let arr = []; + for (let i = 0; i < 1000; i++) { + let config = CardanoWasm.TransactionBuilderConfigBuilder.new() + .ex_unit_prices(CardanoWasm.ExUnitPrices.new( + CardanoWasm.UnitInterval.new( + CardanoWasm.BigNum.from_str('72'), + CardanoWasm.BigNum.from_str('1000'), + ), + CardanoWasm.UnitInterval.new( + CardanoWasm.BigNum.from_str('172'), + CardanoWasm.BigNum.from_str('10000'), + ))) + .coins_per_utxo_byte(CardanoWasm.BigNum.from_str('172000')) + .fee_algo(CardanoWasm.LinearFee.new( + CardanoWasm.BigNum.from_str('123456'), + CardanoWasm.BigNum.from_str('44000'), + )) + .key_deposit(CardanoWasm.BigNum.from_str('2000000')) + .pool_deposit(CardanoWasm.BigNum.from_str('4000000')) + .max_tx_size(123456765) + .max_value_size(123456765) + .build(); + let builder = CardanoWasm.TransactionBuilder.new(config); + arr.push(builder); + } + console.log(arr.length); + }); + }, 1000); + } +} + function onload() { + foo3(); if (typeof window.cardano === 'undefined') { alertError('Cardano API not found'); } else { From 1052b5bbf3c1b2f69f2db7db9e8582dfa4e7562b Mon Sep 17 00:00:00 2001 From: vantuz-subhuman Date: Fri, 28 Oct 2022 13:32:14 +0300 Subject: [PATCH 018/172] prototyping --- .../example-cardano/index.js | 32 +++++++++++-------- .../example-cardano/package-lock.json | 6 ++-- .../example-cardano/package.json | 2 +- 3 files changed, 22 insertions(+), 18 deletions(-) diff --git a/packages/yoroi-ergo-connector/example-cardano/index.js b/packages/yoroi-ergo-connector/example-cardano/index.js index 8470c7840f..6fde7abda0 100644 --- a/packages/yoroi-ergo-connector/example-cardano/index.js +++ b/packages/yoroi-ergo-connector/example-cardano/index.js @@ -908,17 +908,8 @@ function toggleConnectionUI(status) { } } -function bldr(b) { - return new Proxy(b, { - get(target, name, receiver) { - let rv = Reflect.get(target, name, receiver); - return typeof rv === 'function' ? (...args) => { - let res = rv.bind(b)(...args); - b.free(); - return name === 'build' ? res : bldr(res); - } : rv; - } - }); +function isWasm(o) { + return o.ptr != null && o.free != null; } function WasmScope(cb) { @@ -932,7 +923,7 @@ function WasmScope(cb) { } return function(...args) { const res = rv.bind(x)(...args); - if (res.ptr != null && res.free != null) { + if (isWasm(res)) { scope.push(res); } return prox(res); @@ -942,6 +933,10 @@ function WasmScope(cb) { } let result = cb(prox(CardanoWasm)); scope.forEach(x => x.free()); + console.log(`[WasmScope] freed objects:`, scope.length); + if (isWasm(result)) { + throw new Error('A wasm object cannot be returned from wasm scope'); + } return result; } @@ -957,6 +952,15 @@ function foo1() { }); } +function foo12() { + WasmScope(Wasm => { + return Wasm.TransactionBuilderConfigBuilder.new() + .max_value_size(123456) + .max_tx_size(234567) + .pool_deposit(Wasm.BigNum.from_str('123')); + }); +} + function foo2() { for (let i = 0; i < 1000; i++) { setInterval(() => { @@ -975,7 +979,7 @@ function foo2() { const k = CardanoWasm.BigNum.from_str('2000000'); const l = CardanoWasm.ExUnitPrices.new(e, f); const m = CardanoWasm.BigNum.from_str('4000000'); - let config = bldr(CardanoWasm.TransactionBuilderConfigBuilder.new()) + let config = CardanoWasm.TransactionBuilderConfigBuilder.new() .ex_unit_prices(l) .coins_per_utxo_byte(g) .fee_algo(j) @@ -1030,7 +1034,7 @@ function foo3() { } function onload() { - foo3(); + foo12(); if (typeof window.cardano === 'undefined') { alertError('Cardano API not found'); } else { diff --git a/packages/yoroi-ergo-connector/example-cardano/package-lock.json b/packages/yoroi-ergo-connector/example-cardano/package-lock.json index 8c25c042ac..4145bff9fc 100644 --- a/packages/yoroi-ergo-connector/example-cardano/package-lock.json +++ b/packages/yoroi-ergo-connector/example-cardano/package-lock.json @@ -10,9 +10,9 @@ "integrity": "sha512-iGDh2M6pFuXg9kyW+U//963LKylSLFpLG5hZvUppCjhkiDwsYquQPyamxCQlLASYySS3gGKAki2eWG9qIHKCew==" }, "@emurgo/cardano-serialization-lib-browser": { - "version": "11.0.5", - "resolved": "https://registry.npmjs.org/@emurgo/cardano-serialization-lib-browser/-/cardano-serialization-lib-browser-11.0.5.tgz", - "integrity": "sha512-iDXn6pjK3TSrFyUnLMf5lJzBgdf2aV2NTfM+Xc9t9j625W7/f/oQghUIBNpdJlHa0v11oPYFYRY5T1nFgb2mHA==", + "version": "11.1.1-alpha.1", + "resolved": "https://registry.npmjs.org/@emurgo/cardano-serialization-lib-browser/-/cardano-serialization-lib-browser-11.1.1-alpha.1.tgz", + "integrity": "sha512-R/pVuu9fvnL11eUJ/5O9UDKhwSsAZKlEqKl2hfDoq69giBcsrlFohVrhZFiDt6Nuyic9k5XfsNMCXjYxKJJ3qQ==", "dev": true }, "@emurgo/cip4-js": { diff --git a/packages/yoroi-ergo-connector/example-cardano/package.json b/packages/yoroi-ergo-connector/example-cardano/package.json index cb6f2fcde3..2df3aa1d3c 100644 --- a/packages/yoroi-ergo-connector/example-cardano/package.json +++ b/packages/yoroi-ergo-connector/example-cardano/package.json @@ -11,7 +11,7 @@ "start": "webpack-dev-server" }, "devDependencies": { - "@emurgo/cardano-serialization-lib-browser": "11.0.5", + "@emurgo/cardano-serialization-lib-browser": "11.1.1-alpha.1", "webpack": "^4.29.3", "webpack-cli": "^3.1.0", "webpack-dev-server": "^3.1.5", From ebe8c19fd7a212c8c64a7f622a3eb96d61141b7c Mon Sep 17 00:00:00 2001 From: Denis Date: Fri, 28 Oct 2022 18:35:59 +0300 Subject: [PATCH 019/172] Fixes after merging develop --- .../pages/walletTransactionsHistoryPage.js | 104 +++++++++++------- .../features/step_definitions/common-steps.js | 6 +- .../general-settings-steps.js | 36 +----- .../step_definitions/tx-history-steps.js | 13 ++- .../features/support/webdriver.js | 5 - 5 files changed, 74 insertions(+), 90 deletions(-) diff --git a/packages/yoroi-extension/features/pages/walletTransactionsHistoryPage.js b/packages/yoroi-extension/features/pages/walletTransactionsHistoryPage.js index fc3f710380..8ba0fed94c 100644 --- a/packages/yoroi-extension/features/pages/walletTransactionsHistoryPage.js +++ b/packages/yoroi-extension/features/pages/walletTransactionsHistoryPage.js @@ -4,41 +4,6 @@ import type { LocatorObject } from '../support/webdriver'; import { getMethod } from '../support/helpers/helpers'; import { By } from 'selenium-webdriver'; -export const getTopTx = async (customWorld: any): Promise => { - const actualTxsList = await customWorld.getElementsBy(transactionComponent); - return actualTxsList[0]; -}; - -export const getTxStatus = async (tx: webdriver$WebElement): Promise => { - const statusElement = await tx.findElement( - getMethod(transactionStatus.method)(transactionStatus.locator) - ); - return await statusElement.getText(); -}; -export const getNotificationMessage = async ( - customWorld: any, - translatedMessage: string -): Promise => { - const messageParentElement = await customWorld.driver.findElement( - By.xpath('//div[contains(@role, "tooltip")]') - ); - return await messageParentElement.findElement( - By.xpath(`//span[contains(text(), "${translatedMessage}")]`) - ); -} -export const parseTxInfo = async (addressList: webdriver$WebElement): Promise> => { - const addressInfoRow = await addressList.findElements(By.css('.Transaction_addressItem')); - - const result = []; - for (const row of addressInfoRow) { - const rowInfo = await row.findElements(By.xpath('*')); - const rowInfoText = await Promise.all(rowInfo.map(async column => await column.getText())); - result.push(rowInfoText); - } - - return result; -} - export const walletSummaryBox: LocatorObject = { locator: 'walletSummary_box', method: 'id' }; export const transactionComponent: LocatorObject = { locator: '.Transaction_component', @@ -65,10 +30,6 @@ export const showMoreButton: LocatorObject = { locator: '.WalletTransactionsList_component .MuiButton-primary', method: 'css', }; -export const transactionListElement: LocatorObject = { - locator: '.Transaction_component', - method: 'css', -}; export const pendingTransactionElement: LocatorObject = { locator: '.Transaction_pendingLabel', method: 'css', @@ -89,3 +50,68 @@ export const transactionIdText: LocatorObject = { locator: '.txid', method: 'css', }; +export const txStatus: LocatorObject = { locator: 'txStatus', method: 'id' }; +export const txFee: LocatorObject = { locator: 'txFee', method: 'id' }; +export const txAmount: LocatorObject = { locator: 'transactionAmount', method: 'id' }; + +export const getLastTx = async ( + customWorld: any +): Promise => { + const allTxs = await customWorld.findElements(transactionComponent); + return allTxs[0]; +}; + +export const getLastTxStatus = async (customWorld: any): Promise => { + const lastTx = await getLastTx(customWorld); + const statusElement = await lastTx.findElement(getMethod(txStatus.method)(txStatus.locator)); + return await statusElement.getText(); +}; + +export const getLastTxFee = async (customWorld: any): Promise => { + const lastTx = await getLastTx(customWorld); + const feeElement = await lastTx.findElement(getMethod(txFee.method)(txFee.locator)); + return await feeElement.getText(); +}; + +export const getLastTxAmount = async (customWorld: any): Promise => { + const lastTx = await getLastTx(customWorld); + const amountElement = await lastTx.findElement(getMethod(txAmount.method)(txAmount.locator)); + return await amountElement.getText(); +}; + +export const getTxAmount = async (txElement: webdriver$WebElement): Promise => { + const amountElement = await txElement.findElement(getMethod(txAmount.method)(txAmount.locator)); + return await amountElement.getText(); +}; + +export const getTxStatus = async (tx: webdriver$WebElement): Promise => { + const statusElement = await tx.findElement( + getMethod(transactionStatus.method)(transactionStatus.locator) + ); + return await statusElement.getText(); +}; + +export const getNotificationMessage = async ( + customWorld: any, + translatedMessage: string +): Promise => { + const messageParentElement = await customWorld.driver.findElement( + By.xpath('//div[contains(@role, "tooltip")]') + ); + return await messageParentElement.findElement( + By.xpath(`//span[contains(text(), "${translatedMessage}")]`) + ); +}; + +export const parseTxInfo = async (addressList: webdriver$WebElement): Promise> => { + const addressInfoRow = await addressList.findElements(By.css('.Transaction_addressItem')); + + const result = []; + for (const row of addressInfoRow) { + const rowInfo = await row.findElements(By.xpath('*')); + const rowInfoText = await Promise.all(rowInfo.map(async column => await column.getText())); + result.push(rowInfoText); + } + + return result; +} \ No newline at end of file diff --git a/packages/yoroi-extension/features/step_definitions/common-steps.js b/packages/yoroi-extension/features/step_definitions/common-steps.js index f63f432fc5..02ef9c6fc9 100644 --- a/packages/yoroi-extension/features/step_definitions/common-steps.js +++ b/packages/yoroi-extension/features/step_definitions/common-steps.js @@ -85,7 +85,7 @@ import { walletRecoveryPhraseDisplayDialog } from '../pages/createWalletPage'; import * as helpers from '../support/helpers/helpers'; -import { walletSummaryBox } from '../pages/walletTransactionsPage'; +import { walletSummaryBox } from '../pages/walletTransactionsHistoryPage'; import { walletNameText, walletPlate } from '../pages/walletPage'; import { continueButton, @@ -780,10 +780,6 @@ Then(/^Revamp. I go to the wallet ([^"]*)$/, async function (walletName) { await this.waitForElement(walletSummaryBox); }); -Then(/^I should see the dashboard screen$/, async function () { - await this.waitForElement({ locator: '.StakingDashboard_page', method: 'css' }); -}); - When(/^I go to General Settings$/, async function () { await goToSettings(this); await selectSubmenuSettings(this, 'general'); diff --git a/packages/yoroi-extension/features/step_definitions/general-settings-steps.js b/packages/yoroi-extension/features/step_definitions/general-settings-steps.js index a11c8e7c79..0529c32dce 100644 --- a/packages/yoroi-extension/features/step_definitions/general-settings-steps.js +++ b/packages/yoroi-extension/features/step_definitions/general-settings-steps.js @@ -3,7 +3,6 @@ import { When, Then } from 'cucumber'; import { camelCase } from 'lodash'; import i18n from '../support/helpers/i18n-helpers'; -import { By, WebElement } from 'selenium-webdriver'; import { expect } from 'chai'; import { generalSettingsComponent, @@ -24,39 +23,6 @@ import { loadingSpinnerWindow } from '../pages/commonComponentsPage'; const axios = require('axios'); -export async function selectSubmenuSettings(customWorld: Object, buttonName: string) { - const formattedButtonName = camelCase(buttonName); - const buttonSelector = `.SubMenuItem_component.${formattedButtonName}`; - await customWorld.click({ locator: buttonSelector, method: 'css' }); - await customWorld.waitForElement({ - locator: `.SubMenuItem_component.SubMenuItem_active.${formattedButtonName}`, - method: 'css', - }); -} - -export async function goToSettings(customWorld: Object) { - await navigateTo.call(customWorld, '/settings'); - await navigateTo.call(customWorld, '/settings/general'); - - await waitUntilUrlEquals.call(customWorld, '/settings/general'); - await customWorld.waitForElement({ locator: '.SettingsLayout_component', method: 'css' }); -} - -export async function getComplexityLevelButton( - customWorld: Object, - isLow: boolean = true -): Promise { - await customWorld.waitForElement({ locator: '.ComplexityLevelForm_cardsWrapper', method: 'css' }); - const levels = await customWorld.driver.findElements(By.css('.ComplexityLevelForm_card')); - let card; - if (isLow) { - card = levels[0]; - } else { - card = levels[levels.length - 1]; - } - return await card.findElement(By.xpath('.//button')); -} - When(/^I navigate to the general settings screen$/, async function () { await goToSettings(this); }); @@ -147,7 +113,7 @@ Then( parseFloat(adaAmount.replace('\n', '').replace(' ADA', '')).toFixed(2) ); - const expectedValue = (await adaValue) * value; + const expectedValue = adaValue * value; expect(amountDisplayFiatValue).to.equal(`${expectedValue} ${currency}`); } ); diff --git a/packages/yoroi-extension/features/step_definitions/tx-history-steps.js b/packages/yoroi-extension/features/step_definitions/tx-history-steps.js index 28376625b1..076e258aac 100644 --- a/packages/yoroi-extension/features/step_definitions/tx-history-steps.js +++ b/packages/yoroi-extension/features/step_definitions/tx-history-steps.js @@ -8,7 +8,8 @@ import i18n from '../support/helpers/i18n-helpers'; import { confirmationCountText, failedTransactionElement, - getTopTx, + getLastTx, + getTxAmount, getTxStatus, noTransactionsComponent, numberOfTransactions, @@ -16,12 +17,12 @@ import { pendingTransactionElement, showMoreButton, transactionAddressListElement, - transactionComponent, transactionIdText, + transactionComponent, + transactionIdText, } from '../pages/walletTransactionsHistoryPage'; import { summaryTab } from '../pages/walletPage'; -import { displayInfo , txSuccessfulStatuses } from '../support/helpers/common-constants'; +import { displayInfo , txSuccessfulStatuses, adaToFiatPrices } from '../support/helpers/common-constants'; import { getMethod } from '../support/helpers/helpers'; -import { adaToFiatPrices } from '../support/helpers/common-constants'; const axios = require('axios'); @@ -211,7 +212,7 @@ Then(/^I wait for (\d+) minute\(s\) the last transaction is confirmed$/, async f this.webDriverLogger.info(`Step: I wait for ${minutes} minute(s) the last transaction is confirmed`); const startTime = Date.now(); while (startTime + waitTimeMs > Date.now()){ - const topTx = await getTopTx(this); + const topTx = await getLastTx(this); const topTxState = await getTxStatus(topTx); if(txSuccessfulStatuses.includes(topTxState.toLowerCase())){ const endTime = Date.now(); @@ -231,7 +232,7 @@ Then( const response = await axios(adaToFiatPrices); const rate = await response.data.ticker.prices[currency]; - const allTxsList = await this.findElements(txRowComponent); + const allTxsList = await this.findElements(transactionComponent); for (const txListElement of allTxsList) { const txAmount = await getTxAmount(txListElement); expect(txAmount).to.contain(currency); diff --git a/packages/yoroi-extension/features/support/webdriver.js b/packages/yoroi-extension/features/support/webdriver.js index ee7d1c755e..6d1b18f92f 100644 --- a/packages/yoroi-extension/features/support/webdriver.js +++ b/packages/yoroi-extension/features/support/webdriver.js @@ -412,11 +412,6 @@ function CustomWorld(cmdInput: WorldInput) { const actions = this.driver.actions(); await actions.move({ origin: locator }).perform(); }; - - this.scrollIntoView = async (locator: LocatorObject) => { - const element = await this.getElementBy(locator); - await this.driver.executeScript('arguments[0].scrollIntoView();', element); - }; } // no need to await From 492d0bbc75716489a012ff66cf64f0876eda8686 Mon Sep 17 00:00:00 2001 From: Denis Date: Fri, 28 Oct 2022 18:45:36 +0300 Subject: [PATCH 020/172] Removed useless const --- .../mock-chain/mockCardanoImporter.js | 21 ------------------- 1 file changed, 21 deletions(-) diff --git a/packages/yoroi-extension/features/mock-chain/mockCardanoImporter.js b/packages/yoroi-extension/features/mock-chain/mockCardanoImporter.js index 79bde47438..c097bd9d42 100644 --- a/packages/yoroi-extension/features/mock-chain/mockCardanoImporter.js +++ b/packages/yoroi-extension/features/mock-chain/mockCardanoImporter.js @@ -2238,26 +2238,6 @@ const getUtxoData = (txHash: string, txIndex: number): UtxoData | null => { }; }; -const currentADAPrice = { - error: null, - ticker: { - from: 'ADA', - timestamp: 1659640203000, - signature: - '5ead08f0e91be35413d5a9b25da1727779aa3a3298b87a343a449b65ef24285d4b128d58e9806bfb209b4bcb83f620de347b93534553d0410c8092cc66c83d0a', - prices: { - BRL: 2.5935456329171314, - BTC: 0.000022075, - CNY: 3.358264434856802, - ETH: 0.00031116608241096773, - EUR: 0.48543447946200424, - JPY: 66.128348113336, - KRW: 648.4642598773457, - USD: 0.4975722571017442, - }, - }, -}; - export default { utxoForAddresses, utxoSumForAddresses, @@ -2270,5 +2250,4 @@ export default { getRewardHistory, getAccountState, getUtxoData, - currentADAPrice, }; \ No newline at end of file From effea36a7bb515638dc845e2b880e4171e0a6da6 Mon Sep 17 00:00:00 2001 From: Denis Date: Sat, 29 Oct 2022 14:14:16 +0300 Subject: [PATCH 021/172] Little update --- .../features/mock-chain/mockCardanoServer.js | 25 ++++++++++++++++--- .../general-settings-steps.js | 2 +- .../support/helpers/common-constants.js | 5 +--- 3 files changed, 23 insertions(+), 9 deletions(-) diff --git a/packages/yoroi-extension/features/mock-chain/mockCardanoServer.js b/packages/yoroi-extension/features/mock-chain/mockCardanoServer.js index 98ee373423..156975993c 100644 --- a/packages/yoroi-extension/features/mock-chain/mockCardanoServer.js +++ b/packages/yoroi-extension/features/mock-chain/mockCardanoServer.js @@ -25,17 +25,17 @@ import type { } from '../../app/api/common/lib/state-fetch/currencySpecificTypes'; import type { ServerStatusResponse } from '../../app/api/common/lib/state-fetch/types'; import chai from 'chai'; +import axios from 'axios' import mockImporter from './mockCardanoImporter'; import { installCoinPriceRequestHandlers } from './coinPriceRequestHandler'; import { Ports } from '../../scripts/connections'; import { getCircularReplacer, getLogDate } from '../support/helpers/helpers'; -import { adaToFiatPrices, testRunsDataDir } from '../support/helpers/common-constants'; +import { adaToFiatPricesMainUrl, testRunsDataDir } from '../support/helpers/common-constants'; const simpleNodeLogger = require('simple-node-logger'); const fs = require('fs'); -const axios = require('axios'); // MockData should always be consistent with the following values const addressesLimit = 50; @@ -94,6 +94,11 @@ export function getMockServer(settings: { ... }): typeof MockServer { const dir = `${testRunsDataDir}_cardanoMockServerLogs`; + const getCurrencyToFiatCurrentPriceUrl = (from: string) => `${adaToFiatPricesMainUrl}${from}/current`; + const getCurrencyToFiatByTimestampPriceUrl = ( + from: string, + timestamp: string + ) => `${adaToFiatPricesMainUrl}${from}/${timestamp}`; if (!fs.existsSync(dir)) { fs.mkdirSync(dir, { recursive: true }); } @@ -280,7 +285,13 @@ export function getMockServer(settings: { server.get('/api/price/:from/current', async (req, res) => { logger.info(`mockCardanoServer: /api/price/${req.params.from}/current -> request`); - const cardanoResponsePrice = (await axios(adaToFiatPrices)).data; + const cardanoResponsePrice = ( + await axios( + getCurrencyToFiatCurrentPriceUrl(req.params.from), + { + method: 'get' + }) + ).data; logger.info(`mockCardanoServer: GET: /api/price/${req.params.from}/current <- response`); logger.info(JSON.stringify(cardanoResponsePrice)); res.send(cardanoResponsePrice); @@ -288,7 +299,13 @@ export function getMockServer(settings: { server.get('/api/price/:from/:timestamps', async (req, res) => { logger.info(`mockCardanoServer: /api/price/${req.params.from}/${req.params.timestamps} -> request`); - const cardanoResponsePrice = (await axios(adaToFiatPrices)).data; + const cardanoResponsePrice = ( + await axios( + getCurrencyToFiatByTimestampPriceUrl(req.params.from, req.params.timestamps), + { + method: 'get' + }) + ).data; logger.info(`mockCardanoServer: GET: /api/price/${req.params.from}/${req.params.timestamps} <- response`); logger.info(JSON.stringify(cardanoResponsePrice)); res.send(cardanoResponsePrice); diff --git a/packages/yoroi-extension/features/step_definitions/general-settings-steps.js b/packages/yoroi-extension/features/step_definitions/general-settings-steps.js index 0529c32dce..b3d80f0d2d 100644 --- a/packages/yoroi-extension/features/step_definitions/general-settings-steps.js +++ b/packages/yoroi-extension/features/step_definitions/general-settings-steps.js @@ -96,7 +96,7 @@ When( await this.waitForElement(currencySelector); await this.scrollIntoView(currencySelector); await this.click(currencySelector); - await this.waitForElementNotPresent(loadingSpinnerWindow) + await this.waitForElementNotPresent(loadingSpinnerWindow); } ); diff --git a/packages/yoroi-extension/features/support/helpers/common-constants.js b/packages/yoroi-extension/features/support/helpers/common-constants.js index 2187db4c25..c42e6c9da1 100644 --- a/packages/yoroi-extension/features/support/helpers/common-constants.js +++ b/packages/yoroi-extension/features/support/helpers/common-constants.js @@ -11,10 +11,7 @@ export const emailOptions = { headers: { 'Mailsac-Key': mailsacAPIKey }, }; -export const adaToFiatPrices = { - method: 'get', - url: `https://iohk-mainnet.yoroiwallet.com/api/price/ADA/current`, -} +export const adaToFiatPricesMainUrl = `https://iohk-mainnet.yoroiwallet.com/api/price/`; export const commonWalletPassword = 'asdfasdfasdf'; export const txSuccessfulStatuses = ['high', 'medium', 'low']; From 38d521fc3b46d5c9f14f3ed00cd83e8c9af93098 Mon Sep 17 00:00:00 2001 From: Denis Date: Mon, 31 Oct 2022 13:10:07 +0300 Subject: [PATCH 022/172] Updated scripts --- packages/yoroi-extension/package.json | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/packages/yoroi-extension/package.json b/packages/yoroi-extension/package.json index 45ee260259..dbc04ffb17 100644 --- a/packages/yoroi-extension/package.json +++ b/packages/yoroi-extension/package.json @@ -33,9 +33,9 @@ "test:build": "npm run prod:build -- --env 'test' && npm run prod:compress -- --env 'test' --app-id 'yoroi' --codebase 'https://yoroiwallet.com/dw/yoroi-test-extension.crx' --key ./e2etest-key.pem", "test:build:mainnet": "npm run prod:build -- --env 'mainnet' && npm run prod:compress -- --env 'test' --app-id 'yoroi' --codebase 'https://yoroiwallet.com/dw/yoroi-test-extension.crx' --key ./e2etest-key.pem", "test:run:base": "NODE_ENV=cucumber cucumber-js --require-module '@babel/register' --compiler es6:@babel/register -f json:./reports/cucumberReport.json ", - "test:run:e2e:chrome": "npm run test:run:base -- --world-parameters '{\"browser\":\"chrome\"}' features/*.feature --tags 'not @ignore' --tags 'not @dApp'", - "test:run:e2e:brave": "npm run test:run:base -- --world-parameters '{\"browser\":\"brave\"}' features/*.feature --tags 'not @ignore' --tags 'not @dApp'", - "test:run:e2e:firefox": "npm run test:run:base -- --world-parameters '{\"browser\":\"firefox\"}' features/*.feature --tags 'not @ignore' --tags 'not @dApp'", + "test:run:e2e:chrome": "npm run test:run:base -- --world-parameters '{\"browser\":\"chrome\"}' features/*.feature --tags 'not @ignore' --tags 'not @dApp' --tags 'not @smoke' --tags 'not @Trezor'", + "test:run:e2e:brave": "npm run test:run:base -- --world-parameters '{\"browser\":\"brave\"}' features/*.feature --tags 'not @ignore' --tags 'not @dApp' --tags 'not @smoke' --tags 'not @Trezor'", + "test:run:e2e:firefox": "npm run test:run:base -- --world-parameters '{\"browser\":\"firefox\"}' features/*.feature --tags 'not @ignore' --tags 'not @dApp' --tags 'not @smoke' --tags 'not @Trezor'", "test:run:e2e:dApp:chrome": "npm run test:run:base -- --world-parameters '{\"browser\":\"chrome\"}' features/*.feature --tags '@dApp'", "test:run:e2e:dApp:brave": "npm run test:run:base -- --world-parameters '{\"browser\":\"brave\"}' features/*.feature --tags '@dApp'", "test:run:e2e:dApp:firefox": "npm run test:run:base -- --world-parameters '{\"browser\":\"firefox\"}' features/*.feature --tags '@dApp'", @@ -173,10 +173,6 @@ }, "dependencies": { "@cardano-foundation/ledgerjs-hw-app-cardano": "5.1.0", - "@ledgerhq/hw-transport-u2f": "5.36.0-deprecated", - "@ledgerhq/hw-transport-webauthn": "5.36.0-deprecated", - "@ledgerhq/hw-transport-webusb": "5.49.0", - "@ledgerhq/hw-transport-webhid": "5.51.1", "@download/blockies": "1.0.3", "@emotion/react": "^11.4.1", "@emotion/styled": "^11.3.0", @@ -185,6 +181,10 @@ "@emurgo/cip14-js": "2.0.0", "@emurgo/cip4-js": "1.0.5", "@emurgo/js-chain-libs": "0.7.1", + "@ledgerhq/hw-transport-u2f": "5.36.0-deprecated", + "@ledgerhq/hw-transport-webauthn": "5.36.0-deprecated", + "@ledgerhq/hw-transport-webhid": "5.51.1", + "@ledgerhq/hw-transport-webusb": "5.49.0", "@mui/lab": "^5.0.0-alpha.51", "@mui/material": "^5.0.4", "@svgr/webpack": "5.5.0", From a3a8053b5ca504b95d33b3b3cbcdf6e550bd2d9d Mon Sep 17 00:00:00 2001 From: Denis Date: Mon, 31 Oct 2022 15:51:10 +0300 Subject: [PATCH 023/172] New workflow for regression tests --- .github/workflows/tests.yml | 92 +++++++++++++++++++++++++++++++++++++ 1 file changed, 92 insertions(+) diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 4f00e0127f..9300e78541 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -330,6 +330,98 @@ jobs: SECOND_SMOKE_TEST_WALLET_FF: ${{ secrets.SECOND_SMOKE_TEST_WALLET_FF }} run: xvfb-run -a -e /dev/stdout -s "-screen 0 1920x1080x24" npm run test:run:e2e:smoke:${{ matrix.browser }} + - name: Archive tests screenshots and logs + if: ${{ failure() }} + uses: actions/upload-artifact@v3 + with: + name: testRunsData_${{ matrix.browser }} + path: ./packages/yoroi-extension/testRunsData_${{ matrix.browser }} + + E2E_regression_tests: + if: github.event.review && (github.event.review.state == 'approved' || contains(github.event.review.body, '/check') || contains(github.event.review.body, '/regression-check')) + runs-on: ubuntu-22.04 + strategy: + matrix: + browser: [ 'chrome', 'firefox' ] + fail-fast: false + steps: + - name: Forcefully update the Chrome browser + if: matrix.browser=='chrome' + run: | + wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | sudo apt-key add - + sudo sh -c 'echo "deb [arch=amd64] https://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google-chrome.list' + sudo apt-get update + sudo apt-get --only-upgrade install google-chrome-stable + + - name: Install Firefox Developer Edition + if: matrix.browser=='firefox' + run: | + wget -c "https://download.mozilla.org/?product=firefox-devedition-latest-ssl&os=linux64&lang=en-US" -O - | sudo tar -xj -C /opt + sudo rm -rf /opt/firefoxdev + sudo mv /opt/firefox /opt/firefoxdev + echo "FIREFOX_DEV=/opt/firefoxdev/firefox-bin" >> $GITHUB_ENV + + + - uses: actions/checkout@v3 + + - name: Read .nvmrc + id: nvm + run: echo "NVMRC=$(cat .nvmrc)" >> $GITHUB_OUTPUT + + - name: Setup node + uses: actions/setup-node@v3 + with: + node-version: '${{ steps.nvm.outputs.NVMRC }}' + - name: Cache extension node modules + # https://docs.github.com/en/actions/guides/caching-dependencies-to-speed-up-workflows + uses: actions/cache@v3 + env: + cache-name: cache-yoroi-extension-node-modules + with: + # https://github.com/actions/cache/blob/main/examples.md#node---npm + # It is recommended to cache the NPM cache (~/.npm) instead of node_modules. + # But we put node version into the cache key and cache node_modules. + path: packages/yoroi-extension/node_modules + key: ${{ runner.os }}-build-${{ env.cache-name }}-node-${{ steps.nvm.outputs.NVMRC }}-${{ hashFiles('packages/yoroi-extension/package-lock.json') }} + restore-keys: | + ${{ runner.os }}-build-${{ env.cache-name }}- + ${{ runner.os }}-build- + ${{ runner.os }}- + + - name: Cache connector node modules + # https://docs.github.com/en/actions/guides/caching-dependencies-to-speed-up-workflows + uses: actions/cache@v3 + env: + cache-name: cache-yoroi-connector-node-modules + with: + # https://github.com/actions/cache/blob/main/examples.md#node---npm + # It is recommended to cache the NPM cache (~/.npm) instead of node_modules. + # But we put node version into the cache key and cache node_modules. + path: packages/yoroi-ergo-connector/node_modules + key: ${{ runner.os }}-build-${{ env.cache-name }}-node-${{ steps.nvm.outputs.NVMRC }}-${{ hashFiles('packages/yoroi-ergo-connector/package-lock.json') }} + restore-keys: | + ${{ runner.os }}-build-${{ env.cache-name }}- + ${{ runner.os }}-build- + ${{ runner.os }}- + + - name: npm install + run: | + . install-all.sh + + - name: Build the test version using emulators + working-directory: ./packages/yoroi-extension + run: npm run test:build + + - name: Create the report's folder + working-directory: ./packages/yoroi-extension + run: | + mkdir reports + touch ./reports/cucumberReports.json + + - name: Run tests + working-directory: ./packages/yoroi-extension + run: xvfb-run -a -e /dev/stdout -s "-screen 0 1920x1080x24" npm run test:run:e2e:trezor:${{ matrix.browser }} + - name: Archive tests screenshots and logs if: ${{ failure() }} uses: actions/upload-artifact@v3 From ad01f17cc2c2fc7df43ce88da7bc1b4f1fdd8623 Mon Sep 17 00:00:00 2001 From: Denis Date: Mon, 31 Oct 2022 17:00:36 +0300 Subject: [PATCH 024/172] Edited scripts to run --- .github/workflows/tests.yml | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 9300e78541..712f5ad8bd 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -419,8 +419,11 @@ jobs: touch ./reports/cucumberReports.json - name: Run tests - working-directory: ./packages/yoroi-extension - run: xvfb-run -a -e /dev/stdout -s "-screen 0 1920x1080x24" npm run test:run:e2e:trezor:${{ matrix.browser }} + uses: GabrielBB/xvfb-action@v1 + with: + working-directory: ./packages/yoroi-extension + run: npm run test:run:e2e:${{ matrix.browser }} + options: -screen 0 1920x1080x24 - name: Archive tests screenshots and logs if: ${{ failure() }} From a80d0e7880b72030123d9a68d7e6db1a0c741451 Mon Sep 17 00:00:00 2001 From: Denis Date: Mon, 31 Oct 2022 17:32:22 +0300 Subject: [PATCH 025/172] Updated all tests flows --- .github/workflows/tests.yml | 66 ++++++++++++++++++++++++------------- 1 file changed, 44 insertions(+), 22 deletions(-) diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 712f5ad8bd..49a627a704 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -9,17 +9,20 @@ jobs: if: github.event.review && (github.event.review.state == 'approved' || contains(github.event.review.body, '/check') || contains(github.event.review.body, '/release-check')) runs-on: ubuntu-latest steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v3 + - name: Read .nvmrc - run: echo ::set-output name=NVMRC::$(cat .nvmrc) id: nvm + run: echo "NVMRC=$(cat .nvmrc)" >> $GITHUB_OUTPUT + - name: Setup node - uses: actions/setup-node@v1 + uses: actions/setup-node@v3 with: node-version: '${{ steps.nvm.outputs.NVMRC }}' + - name: Cache node modules # https://docs.github.com/en/actions/guides/caching-dependencies-to-speed-up-workflows - uses: actions/cache@v2 + uses: actions/cache@v3 env: cache-name: cache-yoroi-extension-node-modules with: @@ -32,9 +35,11 @@ jobs: ${{ runner.os }}-build-${{ env.cache-name }}- ${{ runner.os }}-build- ${{ runner.os }}- + - name: npm install run: | . install-all.sh + - name: tests run: | npm run test @@ -46,27 +51,33 @@ jobs: matrix: browser: ['chrome', 'firefox'] fail-fast: false + steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v3 + - name: Forcefully update the Chrome browser if: matrix.browser=='chrome' run: brew update && brew upgrade --cask google-chrome + - name: Forcefully install Firefox for Developers browser if: matrix.browser=='firefox' run: | brew update brew tap homebrew/cask-versions && brew install --cask firefox-developer-edition echo "FIREFOX_DEV=/Applications/Firefox Developer Edition.app/Contents/MacOS/firefox-bin" >> $GITHUB_ENV + - name: Read .nvmrc - run: echo ::set-output name=NVMRC::$(cat .nvmrc) id: nvm + run: echo "NVMRC=$(cat .nvmrc)" >> $GITHUB_OUTPUT + - name: Setup node - uses: actions/setup-node@v1 + uses: actions/setup-node@v3 with: node-version: '${{ steps.nvm.outputs.NVMRC }}' + - name: Cache extension node modules # https://docs.github.com/en/actions/guides/caching-dependencies-to-speed-up-workflows - uses: actions/cache@v2 + uses: actions/cache@v3 env: cache-name: cache-yoroi-extension-node-modules with: @@ -79,9 +90,10 @@ jobs: ${{ runner.os }}-build-${{ env.cache-name }}- ${{ runner.os }}-build- ${{ runner.os }}- + - name: Cache connector node modules # https://docs.github.com/en/actions/guides/caching-dependencies-to-speed-up-workflows - uses: actions/cache@v2 + uses: actions/cache@v3 env: cache-name: cache-yoroi-connector-node-modules with: @@ -94,27 +106,32 @@ jobs: ${{ runner.os }}-build-${{ env.cache-name }}- ${{ runner.os }}-build- ${{ runner.os }}- + - name: npm install run: | . install-all.sh + - name: Build the test version working-directory: ./packages/yoroi-extension run: npm run test:build + - name: Create the report's folder working-directory: ./packages/yoroi-extension run: | mkdir reports touch ./reports/cucumberReports.json + - name: Run dapp connector tests working-directory: ./packages/yoroi-extension env: MAILSAC_API_KEY: ${{ secrets.MAILSAC_API_KEY }} run: npm run test:run:e2e:dApp:${{ matrix.browser }} + - name: Archive tests screenshots and logs if: ${{ failure() }} uses: actions/upload-artifact@v3 with: - name: testRunsData_${{ matrix.browser }} + name: testRunsData_E2E_tests_dApp_${{ matrix.browser }} path: ./packages/yoroi-extension/testRunsData_${{ matrix.browser }} Trezor_Model_T_emulator: @@ -124,6 +141,7 @@ jobs: matrix: browser: ['chrome', 'firefox'] fail-fast: false + steps: - name: Forcefully update the Chrome browser if: matrix.browser=='chrome' @@ -178,13 +196,14 @@ jobs: - uses: actions/checkout@v3 - name: Read .nvmrc - run: echo ::set-output name=NVMRC::$(cat .nvmrc) id: nvm + run: echo "NVMRC=$(cat .nvmrc)" >> $GITHUB_OUTPUT - name: Setup node uses: actions/setup-node@v3 with: node-version: '${{ steps.nvm.outputs.NVMRC }}' + - name: Cache extension node modules # https://docs.github.com/en/actions/guides/caching-dependencies-to-speed-up-workflows uses: actions/cache@v3 @@ -221,7 +240,7 @@ jobs: run: | . install-all.sh - - name: Build the test version using emulators + - name: Build the test version working-directory: ./packages/yoroi-extension run: npm run test:build @@ -239,7 +258,7 @@ jobs: if: ${{ failure() }} uses: actions/upload-artifact@v3 with: - name: testRunsData_${{ matrix.browser }} + name: testRunsData_Trezor_Model_T_emulator_${{ matrix.browser }} path: ./packages/yoroi-extension/testRunsData_${{ matrix.browser }} E2E_smoke_tests: @@ -249,8 +268,10 @@ jobs: matrix: browser: ['chrome', 'firefox'] fail-fast: false + steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v3 + - name: Forcefully update the Chrome browser if: matrix.browser=='chrome' run: | @@ -268,17 +289,17 @@ jobs: echo "FIREFOX_DEV=/opt/firefoxdev/firefox-bin" >> $GITHUB_ENV - name: Read .nvmrc - run: echo ::set-output name=NVMRC::$(cat .nvmrc) id: nvm + run: echo "NVMRC=$(cat .nvmrc)" >> $GITHUB_OUTPUT - name: Setup node - uses: actions/setup-node@v2 + uses: actions/setup-node@v3 with: node-version: '${{ steps.nvm.outputs.NVMRC }}' - name: Cache extension node modules # https://docs.github.com/en/actions/guides/caching-dependencies-to-speed-up-workflows - uses: actions/cache@v2 + uses: actions/cache@v3 env: cache-name: cache-yoroi-extension-node-modules with: @@ -294,7 +315,7 @@ jobs: - name: Cache connector node modules # https://docs.github.com/en/actions/guides/caching-dependencies-to-speed-up-workflows - uses: actions/cache@v2 + uses: actions/cache@v3 env: cache-name: cache-yoroi-connector-node-modules with: @@ -334,7 +355,7 @@ jobs: if: ${{ failure() }} uses: actions/upload-artifact@v3 with: - name: testRunsData_${{ matrix.browser }} + name: testRunsData_E2E_smoke_tests_${{ matrix.browser }} path: ./packages/yoroi-extension/testRunsData_${{ matrix.browser }} E2E_regression_tests: @@ -344,6 +365,7 @@ jobs: matrix: browser: [ 'chrome', 'firefox' ] fail-fast: false + steps: - name: Forcefully update the Chrome browser if: matrix.browser=='chrome' @@ -360,7 +382,6 @@ jobs: sudo rm -rf /opt/firefoxdev sudo mv /opt/firefox /opt/firefoxdev echo "FIREFOX_DEV=/opt/firefoxdev/firefox-bin" >> $GITHUB_ENV - - uses: actions/checkout@v3 @@ -372,6 +393,7 @@ jobs: uses: actions/setup-node@v3 with: node-version: '${{ steps.nvm.outputs.NVMRC }}' + - name: Cache extension node modules # https://docs.github.com/en/actions/guides/caching-dependencies-to-speed-up-workflows uses: actions/cache@v3 @@ -408,7 +430,7 @@ jobs: run: | . install-all.sh - - name: Build the test version using emulators + - name: Build the test version working-directory: ./packages/yoroi-extension run: npm run test:build @@ -429,5 +451,5 @@ jobs: if: ${{ failure() }} uses: actions/upload-artifact@v3 with: - name: testRunsData_${{ matrix.browser }} + name: testRunsData_E2E_regression_tests_${{ matrix.browser }} path: ./packages/yoroi-extension/testRunsData_${{ matrix.browser }} \ No newline at end of file From 9f58ba60651d5d86175ffd231a0667812ed95122 Mon Sep 17 00:00:00 2001 From: Denis Date: Mon, 31 Oct 2022 18:59:58 +0300 Subject: [PATCH 026/172] Using secrets.MAILSAC_API_KEY --- .github/workflows/tests.yml | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 49a627a704..4ecd6fcd59 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -441,11 +441,10 @@ jobs: touch ./reports/cucumberReports.json - name: Run tests - uses: GabrielBB/xvfb-action@v1 - with: - working-directory: ./packages/yoroi-extension - run: npm run test:run:e2e:${{ matrix.browser }} - options: -screen 0 1920x1080x24 + working-directory: ./packages/yoroi-extension + env: + MAILSAC_API_KEY: ${{secrets.MAILSAC_API_KEY}} + run: xvfb-run --auto-servernum -s -screen 0 1920x1080x24 npm run test:run:e2e:${{ matrix.browser }} - name: Archive tests screenshots and logs if: ${{ failure() }} From 4fb58ee688280cc42cab8bbe5b26528d2b2a295c Mon Sep 17 00:00:00 2001 From: Denis Date: Mon, 31 Oct 2022 21:55:48 +0300 Subject: [PATCH 027/172] Made tests more robust --- packages/yoroi-extension/features/pages/basicSetupPage.js | 5 +++++ packages/yoroi-extension/features/pages/walletPage.js | 5 +++++ .../step_definitions/addresses-generation-steps.js | 1 + .../features/step_definitions/common-steps.js | 6 +++++- .../features/step_definitions/settings-ui-steps.js | 5 ++++- .../features/step_definitions/wallet-paper-steps.js | 7 ++++--- .../yoroi-extension/features/wallet-paper-creation.feature | 2 +- 7 files changed, 25 insertions(+), 6 deletions(-) diff --git a/packages/yoroi-extension/features/pages/basicSetupPage.js b/packages/yoroi-extension/features/pages/basicSetupPage.js index 65b1edeb7f..d2d7312ec1 100644 --- a/packages/yoroi-extension/features/pages/basicSetupPage.js +++ b/packages/yoroi-extension/features/pages/basicSetupPage.js @@ -5,6 +5,11 @@ import { By } from 'selenium-webdriver'; const LANGUAGE_SELECTION_FORM = '.LanguageSelectionForm_component'; +export const loadingSpinnerComponent: LocatorObject = { + locator: '.LoadingSpinner_component', + method: 'css', +}; + // language select page export const languageSelectionForm: LocatorObject = { locator: LANGUAGE_SELECTION_FORM, diff --git a/packages/yoroi-extension/features/pages/walletPage.js b/packages/yoroi-extension/features/pages/walletPage.js index 9a06a1e49d..6093f84d45 100644 --- a/packages/yoroi-extension/features/pages/walletPage.js +++ b/packages/yoroi-extension/features/pages/walletPage.js @@ -66,3 +66,8 @@ export const walletNavBackButton: LocatorObject = { locator: '.NavBar_navbar .NavBar_title .NavBarBack_backButton', method: 'css', }; + +export const walletSyncingOverlayComponent: LocatorObject = { + locator: '.WalletSyncingOverlay_component', + method: 'css', +}; \ No newline at end of file diff --git a/packages/yoroi-extension/features/step_definitions/addresses-generation-steps.js b/packages/yoroi-extension/features/step_definitions/addresses-generation-steps.js index 919d27c5f3..d29dfcc163 100644 --- a/packages/yoroi-extension/features/step_definitions/addresses-generation-steps.js +++ b/packages/yoroi-extension/features/step_definitions/addresses-generation-steps.js @@ -106,6 +106,7 @@ Then(/^I see every generated address is unique$/, async function () { Then(/^I should see the addresses exactly list them$/, async function (table) { const rows = table.hashes(); + await this.waitForElement(generateAddressButton); const waitUntilAddressesAppeared = rows.map(async (row, index) => { const addressLocator = getGeneratedAddress(index); await this.scrollIntoView(addressLocator); diff --git a/packages/yoroi-extension/features/step_definitions/common-steps.js b/packages/yoroi-extension/features/step_definitions/common-steps.js index ed9871a03f..733b7db0aa 100644 --- a/packages/yoroi-extension/features/step_definitions/common-steps.js +++ b/packages/yoroi-extension/features/step_definitions/common-steps.js @@ -84,11 +84,12 @@ import { walletRecoveryPhraseDisplayDialog } from '../pages/createWalletPage'; import * as helpers from '../support/helpers/helpers'; -import { walletNameText, walletPlate } from '../pages/walletPage'; +import { walletNameText, walletPlate, walletSyncingOverlayComponent } from '../pages/walletPage'; import { continueButton, getTosCheckbox, languageSelectionForm, + loadingSpinnerComponent, termsOfUseComponent, walletAddComponent, } from '../pages/basicSetupPage'; @@ -370,6 +371,8 @@ async function restoreWallet ( await customWorld.waitForElement(verifyRestoredInfoDialog); await checkWalletPlate(customWorld, walletName, restoreInfo); customWorld.webDriverLogger.info(`Step:restoreWallet: Wallet plate is checked`); + await customWorld.waitForElementNotPresent(walletSyncingOverlayComponent); + customWorld.webDriverLogger.info(`Step:restoreWallet: Wallet is fully synchronized`); } async function checkWalletPlate( @@ -564,6 +567,7 @@ Given(/^I import a snapshot named ([^"]*)$/, async function (snapshotName) { await this.driver.navigate().refresh(); // wait for page to refresh await this.driver.sleep(oneSecond + halfSecond); + await this.waitForElementNotPresent(loadingSpinnerComponent); await this.waitForElement(yoroiModern); }); diff --git a/packages/yoroi-extension/features/step_definitions/settings-ui-steps.js b/packages/yoroi-extension/features/step_definitions/settings-ui-steps.js index a4b84ccf3a..3e131f9440 100644 --- a/packages/yoroi-extension/features/step_definitions/settings-ui-steps.js +++ b/packages/yoroi-extension/features/step_definitions/settings-ui-steps.js @@ -136,7 +136,10 @@ Then(/^I should see support screen$/, async function () { Then(/^I should see blockchain screen$/, async function () { await this.waitForElement(explorerSettingsDropdown); - await this.waitForElement(cardanoPaymentsURLTitle); + // The payment URL is not shown on Firefox https://emurgo.atlassian.net/browse/YOEXT-98 + if (this.getBrowser() !== 'firefox'){ + await this.waitForElement(cardanoPaymentsURLTitle); + } }); When(/^I click on remove wallet$/, async function () { diff --git a/packages/yoroi-extension/features/step_definitions/wallet-paper-steps.js b/packages/yoroi-extension/features/step_definitions/wallet-paper-steps.js index e6bafba44b..3399f6bcb6 100644 --- a/packages/yoroi-extension/features/step_definitions/wallet-paper-steps.js +++ b/packages/yoroi-extension/features/step_definitions/wallet-paper-steps.js @@ -10,16 +10,17 @@ import { getAddressesAmountButton, paperWalletDialogSelect, } from '../pages/newWalletPages'; -import { fakeAddresses } from '../support/helpers/common-constants'; +import { fakeAddresses, halfSecond } from '../support/helpers/common-constants'; // ========== Paper wallet ========== -Then(/^I open Number of Adddresses selection dropdown$/, async function () { +Then(/^I open Number of Addresses selection dropdown$/, async function () { await this.click(paperWalletDialogSelect); }); Then(/^I select 2 addresses$/, async function () { - return this.click(getAddressesAmountButton('2')); + await this.click(getAddressesAmountButton('2')); + await this.driver.sleep(halfSecond); }); Then(/^I click the create paper wallet button$/, async function () { diff --git a/packages/yoroi-extension/features/wallet-paper-creation.feature b/packages/yoroi-extension/features/wallet-paper-creation.feature index dffab80e88..964f985806 100644 --- a/packages/yoroi-extension/features/wallet-paper-creation.feature +++ b/packages/yoroi-extension/features/wallet-paper-creation.feature @@ -9,7 +9,7 @@ Feature: Wallet Paper creation When I click the create button Then I select the currency cardano Then I select Paper Wallet - Then I open Number of Adddresses selection dropdown + Then I open Number of Addresses selection dropdown And I select 2 addresses Then I click the create paper wallet button Then I enter the paper wallet password "cool password" From cad192d5eaea904ebc77978f4cf6dc369ff72a46 Mon Sep 17 00:00:00 2001 From: Denis Date: Mon, 31 Oct 2022 22:35:33 +0300 Subject: [PATCH 028/172] Changed the "Run tests" step --- .github/workflows/tests.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 4ecd6fcd59..2ba6b59f0b 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -444,7 +444,7 @@ jobs: working-directory: ./packages/yoroi-extension env: MAILSAC_API_KEY: ${{secrets.MAILSAC_API_KEY}} - run: xvfb-run --auto-servernum -s -screen 0 1920x1080x24 npm run test:run:e2e:${{ matrix.browser }} + run: xvfb-run -a -e /dev/stdout -s "-screen 0 1920x1080x24" npm run test:run:e2e:${{ matrix.browser }} - name: Archive tests screenshots and logs if: ${{ failure() }} From 330120a70d3cb8c221ee3eb3beaef920067de864 Mon Sep 17 00:00:00 2001 From: Denis Date: Tue, 1 Nov 2022 16:12:03 +0300 Subject: [PATCH 029/172] Improved working with email --- .../features/pages/supportPage.js | 2 +- .../addresses-generation-steps.js | 6 +- .../step_definitions/support-steps.js | 59 ++++----- .../support/helpers/common-constants.js | 8 +- .../features/support/helpers/email-helper.js | 122 ++++++++++++++++++ 5 files changed, 157 insertions(+), 40 deletions(-) create mode 100644 packages/yoroi-extension/features/support/helpers/email-helper.js diff --git a/packages/yoroi-extension/features/pages/supportPage.js b/packages/yoroi-extension/features/pages/supportPage.js index 29d3c432ce..5ef64522c5 100644 --- a/packages/yoroi-extension/features/pages/supportPage.js +++ b/packages/yoroi-extension/features/pages/supportPage.js @@ -2,7 +2,7 @@ import type { LocatorObject } from '../support/webdriver'; -export const iframe: LocatorObject = { locator: '#webWidget', method: 'css' }; +export const iframe: LocatorObject = { locator: 'webWidget', method: 'id' }; export const supportButton: LocatorObject = { locator: '.MuiButtonBase-root', diff --git a/packages/yoroi-extension/features/step_definitions/addresses-generation-steps.js b/packages/yoroi-extension/features/step_definitions/addresses-generation-steps.js index d29dfcc163..21447c13ce 100644 --- a/packages/yoroi-extension/features/step_definitions/addresses-generation-steps.js +++ b/packages/yoroi-extension/features/step_definitions/addresses-generation-steps.js @@ -22,16 +22,15 @@ import { walletAddressRow, getAddressFromAddressRow, } from '../pages/walletReceivePage'; -import { halfSecond, oneSecond } from '../support/helpers/common-constants'; Given(/^Revamp. I go to the receive screen$/, async function () { await this.click(receiveTab); - await this.driver.sleep(oneSecond + halfSecond); + await this.waitForElement(generateAddressButton); }); Given(/^I go to the receive screen$/, async function () { await this.click(receiveTab); - await this.driver.sleep(oneSecond + halfSecond); + await this.waitForElement(generateAddressButton); }); When(/^I click on the Generate new address button$/, async function () { @@ -106,7 +105,6 @@ Then(/^I see every generated address is unique$/, async function () { Then(/^I should see the addresses exactly list them$/, async function (table) { const rows = table.hashes(); - await this.waitForElement(generateAddressButton); const waitUntilAddressesAppeared = rows.map(async (row, index) => { const addressLocator = getGeneratedAddress(index); await this.scrollIntoView(addressLocator); diff --git a/packages/yoroi-extension/features/step_definitions/support-steps.js b/packages/yoroi-extension/features/step_definitions/support-steps.js index f9a5f080e5..26ceb97112 100644 --- a/packages/yoroi-extension/features/step_definitions/support-steps.js +++ b/packages/yoroi-extension/features/step_definitions/support-steps.js @@ -12,12 +12,15 @@ import { submitButton, platformSelector, acceptCheckbox, + iframe, } from '../pages/supportPage'; -import { By } from 'selenium-webdriver'; - -import { mailsacEmail, emailOptions, mailsacAPIKey } from '../support/helpers/common-constants'; - -const axios = require('axios'); +import { halfMinute, mailsacEmail } from '../support/helpers/common-constants'; +import { + deleteAllEmails, + deleteEmail, + getEmailBody, + getLastEmail, waitForNewEmail, +} from '../support/helpers/email-helper'; When(/^I click on Support button$/, async function () { this.webDriverLogger.info(`Step: I click on Support button`); @@ -33,9 +36,12 @@ When(/^I send a new Support request with text "(.+)"$/, async function (text) { this.webDriverLogger.info( `Step: I send a new Support request with email address ${mailsacEmail} and text ${text}` ); + this.webDriverLogger.info(`Step: Deleting all emails before sending`); + await deleteAllEmails(); // Switch to iframe - await this.driver.switchTo().frame(this.driver.findElement(By.id('webWidget'))); + const supportIFrame = await this.findElement(iframe); + await this.driver.switchTo().frame(supportIFrame); // enter email address await this.waitForElement(emailInput); @@ -57,56 +63,51 @@ When(/^I send a new Support request with text "(.+)"$/, async function (text) { // submit await this.click(submitButton); + // Switch back to main window + await this.driver.switchTo().defaultContent(); }); Then(/^I see the message was sent to support$/, async function () { this.webDriverLogger.info(`Step: I see the message was sent to support`); + // Switch to iframe + const supportIFrame = await this.findElement(iframe); + await this.driver.switchTo().frame(supportIFrame); + await this.driver.sleep(2000); + await this.waitForElementNotPresent(submitButton); await this.waitForElement(frameTitle); const frameTitleText = await this.getText(frameTitle); expect(frameTitleText).to.be.equal('Message sent'); const successElemText = await this.getText(successText); + // Switch back to main window + await this.driver.switchTo().defaultContent(); expect(successElemText).to.be.equal('Thanks for reaching out'); }); Then(/^I check the email inbox for validation$/, async function () { this.webDriverLogger.info(`Step: I check the email inbox for validation`); - // wait for email to arrive - await this.driver.sleep(1000); - - this.webDriverLogger.info(`Step: I get the last email received`); + await waitForNewEmail(halfMinute); - this.webDriverLogger.info(`Get emails list`); - const resEmails = await axios(emailOptions); - this.webDriverLogger.info(`Data: ${JSON.stringify(resEmails.data)}`); + const lastEmail = await getLastEmail(); + this.webDriverLogger.info(`Step: -> I get the last email received`); - const lastEmail = resEmails.data[0]; expect(lastEmail.from[0].address).to.be.equal('support@emurgohelpdesk.zendesk.com'); expect(lastEmail.subject).to.be.equal('[Request received]'); const emailId = lastEmail._id; - const resFirst = await axios({ - method: 'get', - url: `https://mailsac.com/api/text/${mailsacEmail}/${emailId}`, - headers: { 'Mailsac-Key': mailsacAPIKey }, - }); - this.webDriverLogger.info(`Data: Get last email body: ${resFirst.data}`); + const lastEmailBody = await getEmailBody(emailId); + this.webDriverLogger.info(`Step: -> Get last email body:\n${lastEmailBody}`); - const bodyList = resFirst.data.split('\n'); + const bodyList = lastEmailBody.split('\n'); expect(bodyList[0]).to.match( /Your request (.+) has been received and is being reviewed by our support staff./ ); expect(bodyList[2]).to.equal('To add additional comments, reply to this email.'); expect(bodyList[5]).to.equal('This email is a service from EMURGO.'); - this.webDriverLogger.info(`Delete email`); - const resDel = await axios.delete( - `https://mailsac.com/api/addresses/${mailsacEmail}/messages/${emailId}`, - { - headers: { 'Mailsac-Key': mailsacAPIKey }, - } - ); - this.webDriverLogger.info(`Data: ${JSON.stringify(resDel.data)}`); + this.webDriverLogger.info(`Step: -> Delete email`); + const resDel = await deleteEmail(emailId); + this.webDriverLogger.info(`Step: -> Delete email response:\n${JSON.stringify(resDel)}`); }); diff --git a/packages/yoroi-extension/features/support/helpers/common-constants.js b/packages/yoroi-extension/features/support/helpers/common-constants.js index af8cfda02e..a783ae3826 100644 --- a/packages/yoroi-extension/features/support/helpers/common-constants.js +++ b/packages/yoroi-extension/features/support/helpers/common-constants.js @@ -4,12 +4,8 @@ export const testRunsDataDir = './testRunsData'; export const snapshotsDir = './features/yoroi_snapshots/'; export const mailsacAPIKey = process.env.MAILSAC_API_KEY; -export const mailsacEmail = 'emurgoqa@mailsac.com'; -export const emailOptions = { - method: 'get', - url: `https://mailsac.com/api/addresses/${mailsacEmail}/messages`, - headers: { 'Mailsac-Key': mailsacAPIKey }, -}; +export const mailsacEmail = 'qaemurgo@mailsac.com'; +export const mailsacRequestMainPart = `https://mailsac.com/api/addresses/${mailsacEmail}/`; export const commonWalletPassword = 'asdfasdfasdf'; export const txSuccessfulStatuses = ['high', 'medium', 'low']; diff --git a/packages/yoroi-extension/features/support/helpers/email-helper.js b/packages/yoroi-extension/features/support/helpers/email-helper.js new file mode 100644 index 0000000000..77239973c8 --- /dev/null +++ b/packages/yoroi-extension/features/support/helpers/email-helper.js @@ -0,0 +1,122 @@ +// @flow + +import axios from 'axios'; +import { + defaultRepeatPeriod, + defaultWaitTimeout, + mailsacAPIKey, + mailsacEmail, + mailsacRequestMainPart +} from './common-constants'; +import * as helpers from './helpers'; + +type EmailRequestType = + 'all' | + 'getLast' | + 'count' | + 'deleteAll' | + 'deleteById' | + 'check' | + 'getMessageText'; +type EmailRequest = {| + method: string, + url: string, + headers: any, +|}; + +const _buildEmailRequest = (request: EmailRequestType, messageId?: string): EmailRequest => { + switch (request) { + case 'count': + return { + method: 'get', + url: `${mailsacRequestMainPart}message-count`, + headers: { 'Mailsac-Key': mailsacAPIKey }, + }; + case 'getLast': + return { + method: 'get', + url: `${mailsacRequestMainPart}messages/${messageId}`, + headers: { 'Mailsac-Key': mailsacAPIKey }, + }; + case 'deleteById': + return { + method: 'delete', + url: `${mailsacRequestMainPart}messages/${messageId}`, + headers: { 'Mailsac-Key': mailsacAPIKey }, + }; + case 'check': + return { + method: 'get', + url: `https://mailsac.com/api/me`, + headers: { 'Mailsac-Key': mailsacAPIKey }, + }; + case 'getMessageText': + return { + method: 'get', + url: `https://mailsac.com/api/text/${mailsacEmail}/${messageId}`, + headers: { 'Mailsac-Key': mailsacAPIKey }, + }; + default: + return { + method: 'get', + url: `${mailsacRequestMainPart}messages`, + headers: { 'Mailsac-Key': mailsacAPIKey }, + }; + } + +}; + +export const getAllEmails = async (): Promise => { + const response = await axios(_buildEmailRequest('all')); + + return response.data; +}; + +export const getLastEmail = async (): Promise => { + const allMessages = await getAllEmails(); + + return allMessages[0]; +}; + +export const getEmailBody = async (messageId: string): Promise => { + const response = await axios(_buildEmailRequest('getMessageText', messageId)); + + return response.data; +}; + +export const waitForNewEmail = async ( + timeout: number = defaultWaitTimeout, + repeatPeriod: number = defaultRepeatPeriod +): Promise => { + const countRequest = _buildEmailRequest('count'); + const amountBefore = (await axios(countRequest)).data.count; + let newAmount = 0; + const endTime = Date.now() + timeout; + + while (endTime >= Date.now()) { + newAmount = (await axios(countRequest)).data.count; + if (amountBefore < newAmount) return true; + await helpers.sleep(repeatPeriod); + } + throw new Error(`There is no new email after ${timeout / 1000} seconds. Emails in total: ${newAmount}`); +}; + +export const deleteAllEmails = async () => { + const allMessages = await getAllEmails(); + for (const message of allMessages) { + const messageId = message._id; + await deleteEmail(messageId); + } +}; + +export const deleteEmail = async (messageId) => { + const response = await axios(_buildEmailRequest('deleteById', messageId)); + + return response.data; +}; + +export const checkEmail = async () => { + const response = await axios(_buildEmailRequest('check')); + + return response.data; +}; \ No newline at end of file From 3f920965bdad7bc034b6176c81a538f13f84ab4e Mon Sep 17 00:00:00 2001 From: Denis Date: Tue, 1 Nov 2022 16:17:42 +0300 Subject: [PATCH 030/172] flow fixes --- .../features/support/helpers/email-helper.js | 11 +++-------- 1 file changed, 3 insertions(+), 8 deletions(-) diff --git a/packages/yoroi-extension/features/support/helpers/email-helper.js b/packages/yoroi-extension/features/support/helpers/email-helper.js index 77239973c8..13392a1394 100644 --- a/packages/yoroi-extension/features/support/helpers/email-helper.js +++ b/packages/yoroi-extension/features/support/helpers/email-helper.js @@ -18,13 +18,8 @@ type EmailRequestType = 'deleteById' | 'check' | 'getMessageText'; -type EmailRequest = {| - method: string, - url: string, - headers: any, -|}; -const _buildEmailRequest = (request: EmailRequestType, messageId?: string): EmailRequest => { +const _buildEmailRequest = (request: EmailRequestType, messageId: string = ''): any => { switch (request) { case 'count': return { @@ -109,13 +104,13 @@ export const deleteAllEmails = async () => { } }; -export const deleteEmail = async (messageId) => { +export const deleteEmail = async (messageId: string): Promise => { const response = await axios(_buildEmailRequest('deleteById', messageId)); return response.data; }; -export const checkEmail = async () => { +export const checkEmail = async (): Promise => { const response = await axios(_buildEmailRequest('check')); return response.data; From fb43bcdfa5a3c4bd0adc26e2e81ab36bb537561f Mon Sep 17 00:00:00 2001 From: Denis Date: Tue, 1 Nov 2022 18:51:02 +0300 Subject: [PATCH 031/172] added straight sleep --- .../features/step_definitions/addresses-generation-steps.js | 2 ++ 1 file changed, 2 insertions(+) diff --git a/packages/yoroi-extension/features/step_definitions/addresses-generation-steps.js b/packages/yoroi-extension/features/step_definitions/addresses-generation-steps.js index 21447c13ce..baa8ba1c64 100644 --- a/packages/yoroi-extension/features/step_definitions/addresses-generation-steps.js +++ b/packages/yoroi-extension/features/step_definitions/addresses-generation-steps.js @@ -22,6 +22,7 @@ import { walletAddressRow, getAddressFromAddressRow, } from '../pages/walletReceivePage'; +import { oneSecond } from '../support/helpers/common-constants'; Given(/^Revamp. I go to the receive screen$/, async function () { await this.click(receiveTab); @@ -104,6 +105,7 @@ Then(/^I see every generated address is unique$/, async function () { }); Then(/^I should see the addresses exactly list them$/, async function (table) { + await this.driver.sleep(2 * oneSecond); const rows = table.hashes(); const waitUntilAddressesAppeared = rows.map(async (row, index) => { const addressLocator = getGeneratedAddress(index); From 639fd6c10aa641d40cc9973cce9be92676fc5f89 Mon Sep 17 00:00:00 2001 From: Denis Date: Tue, 1 Nov 2022 19:00:07 +0300 Subject: [PATCH 032/172] ignore the support tests for now --- packages/yoroi-extension/features/support.feature | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/yoroi-extension/features/support.feature b/packages/yoroi-extension/features/support.feature index 53f83c8f43..b95b0e7bb1 100644 --- a/packages/yoroi-extension/features/support.feature +++ b/packages/yoroi-extension/features/support.feature @@ -8,7 +8,7 @@ Feature: Wallet UI Support Then Revamp. I switch to revamp version And I should see the Support button -@support-1 +@support-1 @ignore Scenario: Contact Support successful When I click on Support button And I send a new Support request with text "Autotests. This is the test message from the extension." From 6f9a26ed7c37d45a3e82fd9b391ed26023dbd425 Mon Sep 17 00:00:00 2001 From: yushi Date: Wed, 2 Nov 2022 16:46:08 +0800 Subject: [PATCH 033/172] bug fix: component must be observer --- .../yoroi-extension/app/components/common/AmountDisplay.js | 3 +++ 1 file changed, 3 insertions(+) diff --git a/packages/yoroi-extension/app/components/common/AmountDisplay.js b/packages/yoroi-extension/app/components/common/AmountDisplay.js index d145516917..7307496ae1 100644 --- a/packages/yoroi-extension/app/components/common/AmountDisplay.js +++ b/packages/yoroi-extension/app/components/common/AmountDisplay.js @@ -1,4 +1,5 @@ // @flow +import { observer } from 'mobx-react'; import { BigNumber } from 'bignumber.js'; import { Component } from 'react'; import { getTokenName } from '../../stores/stateless/tokenHelpers'; @@ -20,6 +21,8 @@ type Props = {| +unitOfAccountSetting: UnitOfAccountSettingType, +getCurrentPrice: (from: string, to: string) => ?string, |} + +@observer export default class AmountDisplay extends Component { static defaultProps: {| showAmount: boolean, showFiat: boolean |} = { showAmount: true, From 5d9421c4be32489427568c4169e2dea210b37a3a Mon Sep 17 00:00:00 2001 From: yushi Date: Wed, 2 Nov 2022 16:47:33 +0800 Subject: [PATCH 034/172] increase coin price data freshness threshold --- packages/yoroi-extension/app/api/ada/lib/test-config.js | 2 +- packages/yoroi-extension/config/development.json | 2 +- packages/yoroi-extension/config/mainnet.json | 2 +- packages/yoroi-extension/config/shelley-testnet.json | 2 +- packages/yoroi-extension/config/test.json | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/packages/yoroi-extension/app/api/ada/lib/test-config.js b/packages/yoroi-extension/app/api/ada/lib/test-config.js index 67ece3a48c..9fc93cbae1 100644 --- a/packages/yoroi-extension/app/api/ada/lib/test-config.js +++ b/packages/yoroi-extension/app/api/ada/lib/test-config.js @@ -17,7 +17,7 @@ const CONFIG: ConfigType = { addressRequestSize: 50, txsBodiesRequestSize: 150, coinPriceRefreshInterval: 60000, - coinPriceFreshnessThreshold: 120000, + coinPriceFreshnessThreshold: 10*60*1000, pubKeyData: '', pubKeyMaster: '', }, diff --git a/packages/yoroi-extension/config/development.json b/packages/yoroi-extension/config/development.json index e494dbfb14..f056b552d2 100644 --- a/packages/yoroi-extension/config/development.json +++ b/packages/yoroi-extension/config/development.json @@ -14,7 +14,7 @@ "addressRequestSize": 50, "txsBodiesRequestSize": 150, "coinPriceRefreshInterval": 60000, - "coinPriceFreshnessThreshold": 900000, + "coinPriceFreshnessThreshold": 600000, "pubKeyData": "0e011fe7149bff8e3802168261aec6da54febee37da6a41d6179fa545868421e", "pubKeyMaster": "ab9e4f1c4d996a0e9cdda8546bf5ee1dd8397fd7ab287c331ff171c7e4e0e9e2" } diff --git a/packages/yoroi-extension/config/mainnet.json b/packages/yoroi-extension/config/mainnet.json index 6477c221e1..9902c9451f 100644 --- a/packages/yoroi-extension/config/mainnet.json +++ b/packages/yoroi-extension/config/mainnet.json @@ -13,7 +13,7 @@ "addressRequestSize": 50, "txsBodiesRequestSize": 150, "coinPriceRefreshInterval": 60000, - "coinPriceFreshnessThreshold": 900000, + "coinPriceFreshnessThreshold": 600000, "pubKeyData": "0e011fe7149bff8e3802168261aec6da54febee37da6a41d6179fa545868421e", "pubKeyMaster": "ab9e4f1c4d996a0e9cdda8546bf5ee1dd8397fd7ab287c331ff171c7e4e0e9e2" } diff --git a/packages/yoroi-extension/config/shelley-testnet.json b/packages/yoroi-extension/config/shelley-testnet.json index 67daa8766b..47b60f76a1 100644 --- a/packages/yoroi-extension/config/shelley-testnet.json +++ b/packages/yoroi-extension/config/shelley-testnet.json @@ -13,7 +13,7 @@ "addressRequestSize": 50, "txsBodiesRequestSize": 150, "coinPriceRefreshInterval": 60000, - "coinPriceFreshnessThreshold": 120000, + "coinPriceFreshnessThreshold": 600000, "pubKeyData": "0e011fe7149bff8e3802168261aec6da54febee37da6a41d6179fa545868421e", "pubKeyMaster": "ab9e4f1c4d996a0e9cdda8546bf5ee1dd8397fd7ab287c331ff171c7e4e0e9e2" } diff --git a/packages/yoroi-extension/config/test.json b/packages/yoroi-extension/config/test.json index 9436ee077b..21833fcc3c 100644 --- a/packages/yoroi-extension/config/test.json +++ b/packages/yoroi-extension/config/test.json @@ -14,7 +14,7 @@ "addressRequestSize": 50, "txsBodiesRequestSize": 150, "coinPriceRefreshInterval": 60000, - "coinPriceFreshnessThreshold": 120000, + "coinPriceFreshnessThreshold": 600000, "pubKeyData": "0e011fe7149bff8e3802168261aec6da54febee37da6a41d6179fa545868421e", "pubKeyMaster": "ab9e4f1c4d996a0e9cdda8546bf5ee1dd8397fd7ab287c331ff171c7e4e0e9e2" } From 401e55bd76beffad0cd1d4a93786b7aacf6fd8e4 Mon Sep 17 00:00:00 2001 From: yushi Date: Wed, 2 Nov 2022 16:49:06 +0800 Subject: [PATCH 035/172] fix unit of accounting settings e2e test --- .../features/step_definitions/general-settings-steps.js | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/packages/yoroi-extension/features/step_definitions/general-settings-steps.js b/packages/yoroi-extension/features/step_definitions/general-settings-steps.js index b3d80f0d2d..c7a40aa990 100644 --- a/packages/yoroi-extension/features/step_definitions/general-settings-steps.js +++ b/packages/yoroi-extension/features/step_definitions/general-settings-steps.js @@ -18,7 +18,7 @@ import { secondThemeSelected, } from '../pages/settingsPage'; import type { LocatorObject } from '../support/webdriver'; -import { adaToFiatPrices } from '../support/helpers/common-constants'; +import { adaToFiatPricesMainUrl } from '../support/helpers/common-constants'; import { loadingSpinnerWindow } from '../pages/commonComponentsPage'; const axios = require('axios'); @@ -103,9 +103,11 @@ When( Then( /^I see the correct conversion value for (USD|JPY|EUR|CNY|KRW|BTC|ETH|BRL) on header$/, async function (currency) { + await new Promise(resolve=>{setTimeout(resolve, 1000)}); + const amountDisplayFiatValue = await this.getText(amountDisplayFiat); - const response = await axios(adaToFiatPrices); + const response = await axios(`${adaToFiatPricesMainUrl}ADA/current`); const value = await response.data.ticker.prices[currency]; const adaAmount = await this.getText(amountDisplayADA); @@ -114,7 +116,7 @@ Then( ); const expectedValue = adaValue * value; - expect(amountDisplayFiatValue).to.equal(`${expectedValue} ${currency}`); + expect(amountDisplayFiatValue).to.equal(`${expectedValue.toFixed(2)} ${currency}`); } ); From 0896ae022a0e72acd82aaa8ed2ae951d41ac107b Mon Sep 17 00:00:00 2001 From: yushi Date: Wed, 2 Nov 2022 17:23:27 +0800 Subject: [PATCH 036/172] fix coin price freshness threshold value --- packages/yoroi-extension/app/api/ada/lib/test-config.js | 2 +- packages/yoroi-extension/config/development.json | 2 +- packages/yoroi-extension/config/mainnet.json | 2 +- packages/yoroi-extension/config/shelley-testnet.json | 2 +- packages/yoroi-extension/config/test.json | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/packages/yoroi-extension/app/api/ada/lib/test-config.js b/packages/yoroi-extension/app/api/ada/lib/test-config.js index 9fc93cbae1..7d22156c8b 100644 --- a/packages/yoroi-extension/app/api/ada/lib/test-config.js +++ b/packages/yoroi-extension/app/api/ada/lib/test-config.js @@ -17,7 +17,7 @@ const CONFIG: ConfigType = { addressRequestSize: 50, txsBodiesRequestSize: 150, coinPriceRefreshInterval: 60000, - coinPriceFreshnessThreshold: 10*60*1000, + coinPriceFreshnessThreshold: 900000, pubKeyData: '', pubKeyMaster: '', }, diff --git a/packages/yoroi-extension/config/development.json b/packages/yoroi-extension/config/development.json index f056b552d2..e494dbfb14 100644 --- a/packages/yoroi-extension/config/development.json +++ b/packages/yoroi-extension/config/development.json @@ -14,7 +14,7 @@ "addressRequestSize": 50, "txsBodiesRequestSize": 150, "coinPriceRefreshInterval": 60000, - "coinPriceFreshnessThreshold": 600000, + "coinPriceFreshnessThreshold": 900000, "pubKeyData": "0e011fe7149bff8e3802168261aec6da54febee37da6a41d6179fa545868421e", "pubKeyMaster": "ab9e4f1c4d996a0e9cdda8546bf5ee1dd8397fd7ab287c331ff171c7e4e0e9e2" } diff --git a/packages/yoroi-extension/config/mainnet.json b/packages/yoroi-extension/config/mainnet.json index 9902c9451f..6477c221e1 100644 --- a/packages/yoroi-extension/config/mainnet.json +++ b/packages/yoroi-extension/config/mainnet.json @@ -13,7 +13,7 @@ "addressRequestSize": 50, "txsBodiesRequestSize": 150, "coinPriceRefreshInterval": 60000, - "coinPriceFreshnessThreshold": 600000, + "coinPriceFreshnessThreshold": 900000, "pubKeyData": "0e011fe7149bff8e3802168261aec6da54febee37da6a41d6179fa545868421e", "pubKeyMaster": "ab9e4f1c4d996a0e9cdda8546bf5ee1dd8397fd7ab287c331ff171c7e4e0e9e2" } diff --git a/packages/yoroi-extension/config/shelley-testnet.json b/packages/yoroi-extension/config/shelley-testnet.json index 47b60f76a1..2e4a501bd2 100644 --- a/packages/yoroi-extension/config/shelley-testnet.json +++ b/packages/yoroi-extension/config/shelley-testnet.json @@ -13,7 +13,7 @@ "addressRequestSize": 50, "txsBodiesRequestSize": 150, "coinPriceRefreshInterval": 60000, - "coinPriceFreshnessThreshold": 600000, + "coinPriceFreshnessThreshold": 900000, "pubKeyData": "0e011fe7149bff8e3802168261aec6da54febee37da6a41d6179fa545868421e", "pubKeyMaster": "ab9e4f1c4d996a0e9cdda8546bf5ee1dd8397fd7ab287c331ff171c7e4e0e9e2" } diff --git a/packages/yoroi-extension/config/test.json b/packages/yoroi-extension/config/test.json index 21833fcc3c..137e41d961 100644 --- a/packages/yoroi-extension/config/test.json +++ b/packages/yoroi-extension/config/test.json @@ -14,7 +14,7 @@ "addressRequestSize": 50, "txsBodiesRequestSize": 150, "coinPriceRefreshInterval": 60000, - "coinPriceFreshnessThreshold": 600000, + "coinPriceFreshnessThreshold": 900000, "pubKeyData": "0e011fe7149bff8e3802168261aec6da54febee37da6a41d6179fa545868421e", "pubKeyMaster": "ab9e4f1c4d996a0e9cdda8546bf5ee1dd8397fd7ab287c331ff171c7e4e0e9e2" } From 8ad1cda815abe78defb1850c3071c356073d8f5a Mon Sep 17 00:00:00 2001 From: yushi Date: Wed, 2 Nov 2022 21:31:11 +0800 Subject: [PATCH 037/172] delay after selecting fiat --- .../features/step_definitions/general-settings-steps.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/yoroi-extension/features/step_definitions/general-settings-steps.js b/packages/yoroi-extension/features/step_definitions/general-settings-steps.js index c7a40aa990..bcbeb50009 100644 --- a/packages/yoroi-extension/features/step_definitions/general-settings-steps.js +++ b/packages/yoroi-extension/features/step_definitions/general-settings-steps.js @@ -97,14 +97,14 @@ When( await this.scrollIntoView(currencySelector); await this.click(currencySelector); await this.waitForElementNotPresent(loadingSpinnerWindow); + + await new Promise(resolve=>{setTimeout(resolve, 1000)}); } ); Then( /^I see the correct conversion value for (USD|JPY|EUR|CNY|KRW|BTC|ETH|BRL) on header$/, async function (currency) { - await new Promise(resolve=>{setTimeout(resolve, 1000)}); - const amountDisplayFiatValue = await this.getText(amountDisplayFiat); const response = await axios(`${adaToFiatPricesMainUrl}ADA/current`); From 47cbb33e15c6dea82756f0d1b141cc53f66c7a5a Mon Sep 17 00:00:00 2001 From: yushi Date: Wed, 2 Nov 2022 21:54:59 +0800 Subject: [PATCH 038/172] fix e2e test for tx amount is fiat --- .../features/step_definitions/tx-history-steps.js | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/packages/yoroi-extension/features/step_definitions/tx-history-steps.js b/packages/yoroi-extension/features/step_definitions/tx-history-steps.js index 076e258aac..fadec5370d 100644 --- a/packages/yoroi-extension/features/step_definitions/tx-history-steps.js +++ b/packages/yoroi-extension/features/step_definitions/tx-history-steps.js @@ -21,7 +21,7 @@ import { transactionIdText, } from '../pages/walletTransactionsHistoryPage'; import { summaryTab } from '../pages/walletPage'; -import { displayInfo , txSuccessfulStatuses, adaToFiatPrices } from '../support/helpers/common-constants'; +import { displayInfo , txSuccessfulStatuses, adaToFiatPricesMainUrl } from '../support/helpers/common-constants'; import { getMethod } from '../support/helpers/helpers'; const axios = require('axios'); @@ -229,12 +229,15 @@ Then(/^I wait for (\d+) minute\(s\) the last transaction is confirmed$/, async f Then( /^I validate the transaction amount to (USD|JPY|EUR|CNY|KRW|BTC|ETH|BRL) currency pairing$/, async function (currency) { - const response = await axios(adaToFiatPrices); - const rate = await response.data.ticker.prices[currency]; + const TIMESTAMP = '1555773413000'; // the timestamp of the first tx of this wallet + const response = await axios(`${adaToFiatPricesMainUrl}ADA/${TIMESTAMP}`); + + const rate = response.data.tickers[0].prices[currency]; const allTxsList = await this.findElements(transactionComponent); for (const txListElement of allTxsList) { const txAmount = await getTxAmount(txListElement); + expect(txAmount).to.contain(currency); const amountList = txAmount.split('\n'); From a209522063fe7bd72ca6045e817d58d0c2f8f2d2 Mon Sep 17 00:00:00 2001 From: Denis Date: Thu, 3 Nov 2022 12:33:03 +0300 Subject: [PATCH 039/172] Added direct sleep and fixed calculating the final number --- .../step_definitions/general-settings-steps.js | 11 +++++++---- .../features/step_definitions/tx-history-steps.js | 13 +++++++++++-- 2 files changed, 18 insertions(+), 6 deletions(-) diff --git a/packages/yoroi-extension/features/step_definitions/general-settings-steps.js b/packages/yoroi-extension/features/step_definitions/general-settings-steps.js index bcbeb50009..701bd68087 100644 --- a/packages/yoroi-extension/features/step_definitions/general-settings-steps.js +++ b/packages/yoroi-extension/features/step_definitions/general-settings-steps.js @@ -18,7 +18,7 @@ import { secondThemeSelected, } from '../pages/settingsPage'; import type { LocatorObject } from '../support/webdriver'; -import { adaToFiatPricesMainUrl } from '../support/helpers/common-constants'; +import { adaToFiatPricesMainUrl, oneSecond } from '../support/helpers/common-constants'; import { loadingSpinnerWindow } from '../pages/commonComponentsPage'; const axios = require('axios'); @@ -98,7 +98,7 @@ When( await this.click(currencySelector); await this.waitForElementNotPresent(loadingSpinnerWindow); - await new Promise(resolve=>{setTimeout(resolve, 1000)}); + await this.driver.sleep(oneSecond); } ); @@ -115,8 +115,11 @@ Then( parseFloat(adaAmount.replace('\n', '').replace(' ADA', '')).toFixed(2) ); - const expectedValue = adaValue * value; - expect(amountDisplayFiatValue).to.equal(`${expectedValue.toFixed(2)} ${currency}`); + const expectedValueNotFixed = adaValue * value; + const expectedValue = expectedValueNotFixed < 1 + ? expectedValueNotFixed.toFixed(6) + : expectedValueNotFixed.toFixed(2); + expect(amountDisplayFiatValue).to.equal(`${expectedValue} ${currency}`); } ); diff --git a/packages/yoroi-extension/features/step_definitions/tx-history-steps.js b/packages/yoroi-extension/features/step_definitions/tx-history-steps.js index fadec5370d..6c54b31896 100644 --- a/packages/yoroi-extension/features/step_definitions/tx-history-steps.js +++ b/packages/yoroi-extension/features/step_definitions/tx-history-steps.js @@ -21,7 +21,12 @@ import { transactionIdText, } from '../pages/walletTransactionsHistoryPage'; import { summaryTab } from '../pages/walletPage'; -import { displayInfo , txSuccessfulStatuses, adaToFiatPricesMainUrl } from '../support/helpers/common-constants'; +import { + displayInfo, + txSuccessfulStatuses, + adaToFiatPricesMainUrl, + oneSecond, +} from '../support/helpers/common-constants'; import { getMethod } from '../support/helpers/helpers'; const axios = require('axios'); @@ -234,6 +239,7 @@ Then( const rate = response.data.tickers[0].prices[currency]; + await this.driver.sleep(oneSecond); const allTxsList = await this.findElements(transactionComponent); for (const txListElement of allTxsList) { const txAmount = await getTxAmount(txListElement); @@ -244,7 +250,10 @@ Then( const fiatAmount = amountList[0].replace(currency, ''); const adaAmount = parseFloat(amountList[1].replace('ADA', '')); - const expectedValue = parseFloat((adaAmount * rate).toFixed(6)); + const expectedValueNotFixed = adaAmount * rate; + const expectedValue = expectedValueNotFixed < 1 + ? expectedValueNotFixed.toFixed(6) + : expectedValueNotFixed.toFixed(2); expect(fiatAmount).to.contain(`${expectedValue}`); } } From d2ad88778ebdc33d94dbfaca8c46ce14d29e3bcc Mon Sep 17 00:00:00 2001 From: Denis Date: Mon, 7 Nov 2022 19:02:54 +0300 Subject: [PATCH 040/172] Little fix after merging --- .../yoroi-extension/features/mock-chain/mockCardanoServer.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/yoroi-extension/features/mock-chain/mockCardanoServer.js b/packages/yoroi-extension/features/mock-chain/mockCardanoServer.js index 050be6bf06..549f186918 100644 --- a/packages/yoroi-extension/features/mock-chain/mockCardanoServer.js +++ b/packages/yoroi-extension/features/mock-chain/mockCardanoServer.js @@ -353,7 +353,7 @@ export function getMockServer(settings: { methodLogger.logRequest(); const bestBlockHash = await mockImporter.mockUtxoApi.getBestBlock(); const safeBlockHash = await mockImporter.mockUtxoApi.getSafeBlock(); - res.send({ + const response = { safeBlock: { hash: safeBlockHash }, bestBlock: { hash: bestBlockHash }, }; From 998acf8e33c34dbfb16bb471f4992f67f82dcc9a Mon Sep 17 00:00:00 2001 From: Ahmed Ibrahim Date: Tue, 15 Nov 2022 14:22:30 +0200 Subject: [PATCH 041/172] Add date picker --- packages/yoroi-extension/app/api/ada/index.js | 1 + .../app/components/wallet/export/DateRange.js | 41 ++ .../wallet/export/ExportTransactionDialog.js | 8 + .../app/stores/toplevel/TransactionsStore.js | 6 +- packages/yoroi-extension/package-lock.json | 491 ++++++++++++------ packages/yoroi-extension/package.json | 10 +- 6 files changed, 400 insertions(+), 157 deletions(-) create mode 100644 packages/yoroi-extension/app/components/wallet/export/DateRange.js diff --git a/packages/yoroi-extension/app/api/ada/index.js b/packages/yoroi-extension/app/api/ada/index.js index bfc8f9d9f5..7e08e32b16 100644 --- a/packages/yoroi-extension/app/api/ada/index.js +++ b/packages/yoroi-extension/app/api/ada/index.js @@ -2285,6 +2285,7 @@ export default class AdaApi { const fetchedTxs = await getAllTransactions({ publicDeriver: request.publicDeriver, }); + console.log(JSON.parse(JSON.stringify({fetchedTxs}))) Logger.debug(`${nameof(AdaApi)}::${nameof(this.getTransactionRowsToExport)}: success`); return convertAdaTransactionsToExportRows( fetchedTxs.txs, diff --git a/packages/yoroi-extension/app/components/wallet/export/DateRange.js b/packages/yoroi-extension/app/components/wallet/export/DateRange.js new file mode 100644 index 0000000000..9a57da9ec6 --- /dev/null +++ b/packages/yoroi-extension/app/components/wallet/export/DateRange.js @@ -0,0 +1,41 @@ +// @flow +import { Component } from 'react' +import TextField from '@mui/material/TextField'; +import Box from '@mui/material/Box'; +import { LocalizationProvider } from '@mui/x-date-pickers-pro'; +import { AdapterDayjs } from '@mui/x-date-pickers-pro/AdapterDayjs'; +import { DateRangePicker } from '@mui/x-date-pickers-pro/DateRangePicker'; +import { observer } from 'mobx-react'; + +type Props = {| + date: string, // todo: Add correct type + setDate(): void +|} + +@observer +export default class ExportTransactionDialog extends Component { + render() { + const { date, setDate } = this.props; + return ( + + { + setDate(newDate); + }} + renderInput={(startProps, endProps) => ( + <> + + to + + + )} + /> + + ) + } +} + diff --git a/packages/yoroi-extension/app/components/wallet/export/ExportTransactionDialog.js b/packages/yoroi-extension/app/components/wallet/export/ExportTransactionDialog.js index a0dab525b0..3690842733 100644 --- a/packages/yoroi-extension/app/components/wallet/export/ExportTransactionDialog.js +++ b/packages/yoroi-extension/app/components/wallet/export/ExportTransactionDialog.js @@ -14,6 +14,7 @@ import globalMessages from '../../../i18n/global-messages'; import styles from './ExportTransactionDialog.scss'; import CheckboxLabel from '../../common/CheckboxLabel'; +import DateRange from './DateRange' const messages = defineMessages({ dialogTitle: { @@ -46,6 +47,11 @@ export default class ExportTransactionDialog extends Component { intl: intlShape.isRequired }; + state = { + startDate: null, + endDate: null, + } + render(): Node { const { intl } = this.context; const { @@ -56,6 +62,7 @@ export default class ExportTransactionDialog extends Component { toggleIncludeTxIds, shouldIncludeTxIds } = this.props; + const { startDate, endDate } = this.state; const infoBlock = (
@@ -79,6 +86,7 @@ export default class ExportTransactionDialog extends Component { onClose={cancel} > {infoBlock} +
{ this.getTransactionRowsToExportRequest.reset(); this.exportTransactions.reset(); - const continuation = await this.exportTransactionsToFile({ - publicDeriver: request.publicDeriver, - exportRequest: request.exportRequest, - }); + const continuation = await this.exportTransactionsToFile(request); /** Intentionally added delay to feel smooth flow */ setTimeout(async () => { @@ -718,6 +715,7 @@ export default class TransactionsStore extends Store { ...request.exportRequest, getDefaultToken: networkId => this.stores.tokenInfoStore.getDefaultTokenInfo(networkId), }); + console.log(JSON.parse(JSON.stringify(rows))) /** * NOTE: The rewards export currently supports only Haskell Shelley diff --git a/packages/yoroi-extension/package-lock.json b/packages/yoroi-extension/package-lock.json index 1128989dd1..e62b0e41a5 100644 --- a/packages/yoroi-extension/package-lock.json +++ b/packages/yoroi-extension/package-lock.json @@ -2679,6 +2679,343 @@ } } }, + "@mui/x-date-pickers": { + "version": "5.0.8", + "resolved": "https://registry.npmjs.org/@mui/x-date-pickers/-/x-date-pickers-5.0.8.tgz", + "integrity": "sha512-L+9WOyoxIPxj86dk4G/zyVsiakQjBX0MJTIPMNSRitxFi4I6T8KlasdpGUHfnni/EAjqR36w0d/BDwCjc/7gPQ==", + "requires": { + "@babel/runtime": "^7.18.9", + "@date-io/core": "^2.15.0", + "@date-io/date-fns": "^2.15.0", + "@date-io/dayjs": "^2.15.0", + "@date-io/luxon": "^2.15.0", + "@date-io/moment": "^2.15.0", + "@mui/utils": "^5.10.3", + "@types/react-transition-group": "^4.4.5", + "clsx": "^1.2.1", + "prop-types": "^15.7.2", + "react-transition-group": "^4.4.5", + "rifm": "^0.12.1" + }, + "dependencies": { + "@babel/runtime": { + "version": "7.20.1", + "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.20.1.tgz", + "integrity": "sha512-mrzLkl6U9YLF8qpqI7TB82PESyEGjm/0Ly91jG575eVxMMlb8fYfOXFZIJ8XfLrJZQbm7dlKry2bJmXBUEkdFg==", + "requires": { + "regenerator-runtime": "^0.13.10" + } + }, + "@date-io/core": { + "version": "2.16.0", + "resolved": "https://registry.npmjs.org/@date-io/core/-/core-2.16.0.tgz", + "integrity": "sha512-DYmSzkr+jToahwWrsiRA2/pzMEtz9Bq1euJwoOuYwuwIYXnZFtHajY2E6a1VNVDc9jP8YUXK1BvnZH9mmT19Zg==" + }, + "@date-io/date-fns": { + "version": "2.16.0", + "resolved": "https://registry.npmjs.org/@date-io/date-fns/-/date-fns-2.16.0.tgz", + "integrity": "sha512-bfm5FJjucqlrnQcXDVU5RD+nlGmL3iWgkHTq3uAZWVIuBu6dDmGa3m8a6zo2VQQpu8ambq9H22UyUpn7590joA==", + "requires": { + "@date-io/core": "^2.16.0" + } + }, + "@date-io/dayjs": { + "version": "2.16.0", + "resolved": "https://registry.npmjs.org/@date-io/dayjs/-/dayjs-2.16.0.tgz", + "integrity": "sha512-y5qKyX2j/HG3zMvIxTobYZRGnd1FUW2olZLS0vTj7bEkBQkjd2RO7/FEwDY03Z1geVGlXKnzIATEVBVaGzV4Iw==", + "requires": { + "@date-io/core": "^2.16.0" + } + }, + "@date-io/luxon": { + "version": "2.16.1", + "resolved": "https://registry.npmjs.org/@date-io/luxon/-/luxon-2.16.1.tgz", + "integrity": "sha512-aeYp5K9PSHV28946pC+9UKUi/xMMYoaGelrpDibZSgHu2VWHXrr7zWLEr+pMPThSs5vt8Ei365PO+84pCm37WQ==", + "requires": { + "@date-io/core": "^2.16.0" + } + }, + "@date-io/moment": { + "version": "2.16.1", + "resolved": "https://registry.npmjs.org/@date-io/moment/-/moment-2.16.1.tgz", + "integrity": "sha512-JkxldQxUqZBfZtsaCcCMkm/dmytdyq5pS1RxshCQ4fHhsvP5A7gSqPD22QbVXMcJydi3d3v1Y8BQdUKEuGACZQ==", + "requires": { + "@date-io/core": "^2.16.0" + } + }, + "@mui/utils": { + "version": "5.10.14", + "resolved": "https://registry.npmjs.org/@mui/utils/-/utils-5.10.14.tgz", + "integrity": "sha512-12p59+wDZpA++XVJmKwqsZmrA1nmUQ5d0a1yQWtcDjxNyER1EDzozYN/db+FY2i5ceQh2TynPTEwGms2mXDwFg==", + "requires": { + "@babel/runtime": "^7.20.1", + "@types/prop-types": "^15.7.5", + "@types/react-is": "^16.7.1 || ^17.0.0", + "prop-types": "^15.8.1", + "react-is": "^18.2.0" + }, + "dependencies": { + "prop-types": { + "version": "15.8.1", + "resolved": "https://registry.npmjs.org/prop-types/-/prop-types-15.8.1.tgz", + "integrity": "sha512-oj87CgZICdulUohogVAR7AjlC0327U4el4L6eAvOqCeudMDVU0NThNaV+b9Df4dXgSP1gXMTnPdhfe/2qDH5cg==", + "requires": { + "loose-envify": "^1.4.0", + "object-assign": "^4.1.1", + "react-is": "^16.13.1" + }, + "dependencies": { + "react-is": { + "version": "16.13.1", + "resolved": "https://registry.npmjs.org/react-is/-/react-is-16.13.1.tgz", + "integrity": "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==" + } + } + } + } + }, + "@types/prop-types": { + "version": "15.7.5", + "resolved": "https://registry.npmjs.org/@types/prop-types/-/prop-types-15.7.5.tgz", + "integrity": "sha512-JCB8C6SnDoQf0cNycqd/35A7MjcnK+ZTqE7judS6o7utxUCg6imJg3QK2qzHKszlTjcj2cn+NwMB2i96ubpj7w==" + }, + "@types/react-transition-group": { + "version": "4.4.5", + "resolved": "https://registry.npmjs.org/@types/react-transition-group/-/react-transition-group-4.4.5.tgz", + "integrity": "sha512-juKD/eiSM3/xZYzjuzH6ZwpP+/lejltmiS3QEzV/vmb/Q8+HfDmxu+Baga8UEMGBqV88Nbg4l2hY/K2DkyaLLA==", + "requires": { + "@types/react": "*" + } + }, + "clsx": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/clsx/-/clsx-1.2.1.tgz", + "integrity": "sha512-EcR6r5a8bj6pu3ycsa/E/cKVGuTgZJZdsyUYHOksG/UHIiKfjxzRxYJpyVBwYaQeOvghal9fcc4PidlgzugAQg==" + }, + "react-is": { + "version": "18.2.0", + "resolved": "https://registry.npmjs.org/react-is/-/react-is-18.2.0.tgz", + "integrity": "sha512-xWGDIW6x921xtzPkhiULtthJHoJvBbF3q26fzloPCK0hsvxtPVelvftw3zjbHWSkR2km9Z+4uxbDDK/6Zw9B8w==" + }, + "react-transition-group": { + "version": "4.4.5", + "resolved": "https://registry.npmjs.org/react-transition-group/-/react-transition-group-4.4.5.tgz", + "integrity": "sha512-pZcd1MCJoiKiBR2NRxeCRg13uCXbydPnmB4EOeRrY7480qNWO8IIgQG6zlDkm6uRMsURXPuKq0GWtiM59a5Q6g==", + "requires": { + "@babel/runtime": "^7.5.5", + "dom-helpers": "^5.0.1", + "loose-envify": "^1.4.0", + "prop-types": "^15.6.2" + } + }, + "regenerator-runtime": { + "version": "0.13.10", + "resolved": "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.13.10.tgz", + "integrity": "sha512-KepLsg4dU12hryUO7bp/axHAKvwGOCV0sGloQtpagJ12ai+ojVDqkeGSiRX1zlq+kjIMZ1t7gpze+26QqtdGqw==" + }, + "rifm": { + "version": "0.12.1", + "resolved": "https://registry.npmjs.org/rifm/-/rifm-0.12.1.tgz", + "integrity": "sha512-OGA1Bitg/dSJtI/c4dh90svzaUPt228kzFsUkJbtA2c964IqEAwWXeL9ZJi86xWv3j5SMqRvGULl7bA6cK0Bvg==" + } + } + }, + "@mui/x-date-pickers-pro": { + "version": "5.0.8", + "resolved": "https://registry.npmjs.org/@mui/x-date-pickers-pro/-/x-date-pickers-pro-5.0.8.tgz", + "integrity": "sha512-B3r8ZmCelPZA1jIzUtbu0JYz8Ap3MU5LVupwUc26iUFLeXRD5ujsTsZX3lnNlWK+Uw7tPKABIFVZA3YyUmYPMw==", + "requires": { + "@babel/runtime": "^7.18.9", + "@date-io/date-fns": "^2.15.0", + "@date-io/dayjs": "^2.15.0", + "@date-io/luxon": "^2.15.0", + "@date-io/moment": "^2.15.0", + "@mui/utils": "^5.10.3", + "@mui/x-date-pickers": "5.0.8", + "@mui/x-license-pro": "5.17.11", + "clsx": "^1.2.1", + "prop-types": "^15.7.2", + "react-transition-group": "^4.4.5", + "rifm": "^0.12.1" + }, + "dependencies": { + "@babel/runtime": { + "version": "7.20.1", + "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.20.1.tgz", + "integrity": "sha512-mrzLkl6U9YLF8qpqI7TB82PESyEGjm/0Ly91jG575eVxMMlb8fYfOXFZIJ8XfLrJZQbm7dlKry2bJmXBUEkdFg==", + "requires": { + "regenerator-runtime": "^0.13.10" + } + }, + "@date-io/core": { + "version": "2.16.0", + "resolved": "https://registry.npmjs.org/@date-io/core/-/core-2.16.0.tgz", + "integrity": "sha512-DYmSzkr+jToahwWrsiRA2/pzMEtz9Bq1euJwoOuYwuwIYXnZFtHajY2E6a1VNVDc9jP8YUXK1BvnZH9mmT19Zg==" + }, + "@date-io/date-fns": { + "version": "2.16.0", + "resolved": "https://registry.npmjs.org/@date-io/date-fns/-/date-fns-2.16.0.tgz", + "integrity": "sha512-bfm5FJjucqlrnQcXDVU5RD+nlGmL3iWgkHTq3uAZWVIuBu6dDmGa3m8a6zo2VQQpu8ambq9H22UyUpn7590joA==", + "requires": { + "@date-io/core": "^2.16.0" + } + }, + "@date-io/dayjs": { + "version": "2.16.0", + "resolved": "https://registry.npmjs.org/@date-io/dayjs/-/dayjs-2.16.0.tgz", + "integrity": "sha512-y5qKyX2j/HG3zMvIxTobYZRGnd1FUW2olZLS0vTj7bEkBQkjd2RO7/FEwDY03Z1geVGlXKnzIATEVBVaGzV4Iw==", + "requires": { + "@date-io/core": "^2.16.0" + } + }, + "@date-io/luxon": { + "version": "2.16.1", + "resolved": "https://registry.npmjs.org/@date-io/luxon/-/luxon-2.16.1.tgz", + "integrity": "sha512-aeYp5K9PSHV28946pC+9UKUi/xMMYoaGelrpDibZSgHu2VWHXrr7zWLEr+pMPThSs5vt8Ei365PO+84pCm37WQ==", + "requires": { + "@date-io/core": "^2.16.0" + } + }, + "@date-io/moment": { + "version": "2.16.1", + "resolved": "https://registry.npmjs.org/@date-io/moment/-/moment-2.16.1.tgz", + "integrity": "sha512-JkxldQxUqZBfZtsaCcCMkm/dmytdyq5pS1RxshCQ4fHhsvP5A7gSqPD22QbVXMcJydi3d3v1Y8BQdUKEuGACZQ==", + "requires": { + "@date-io/core": "^2.16.0" + } + }, + "@mui/utils": { + "version": "5.10.14", + "resolved": "https://registry.npmjs.org/@mui/utils/-/utils-5.10.14.tgz", + "integrity": "sha512-12p59+wDZpA++XVJmKwqsZmrA1nmUQ5d0a1yQWtcDjxNyER1EDzozYN/db+FY2i5ceQh2TynPTEwGms2mXDwFg==", + "requires": { + "@babel/runtime": "^7.20.1", + "@types/prop-types": "^15.7.5", + "@types/react-is": "^16.7.1 || ^17.0.0", + "prop-types": "^15.8.1", + "react-is": "^18.2.0" + }, + "dependencies": { + "prop-types": { + "version": "15.8.1", + "resolved": "https://registry.npmjs.org/prop-types/-/prop-types-15.8.1.tgz", + "integrity": "sha512-oj87CgZICdulUohogVAR7AjlC0327U4el4L6eAvOqCeudMDVU0NThNaV+b9Df4dXgSP1gXMTnPdhfe/2qDH5cg==", + "requires": { + "loose-envify": "^1.4.0", + "object-assign": "^4.1.1", + "react-is": "^16.13.1" + }, + "dependencies": { + "react-is": { + "version": "16.13.1", + "resolved": "https://registry.npmjs.org/react-is/-/react-is-16.13.1.tgz", + "integrity": "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==" + } + } + } + } + }, + "@types/prop-types": { + "version": "15.7.5", + "resolved": "https://registry.npmjs.org/@types/prop-types/-/prop-types-15.7.5.tgz", + "integrity": "sha512-JCB8C6SnDoQf0cNycqd/35A7MjcnK+ZTqE7judS6o7utxUCg6imJg3QK2qzHKszlTjcj2cn+NwMB2i96ubpj7w==" + }, + "clsx": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/clsx/-/clsx-1.2.1.tgz", + "integrity": "sha512-EcR6r5a8bj6pu3ycsa/E/cKVGuTgZJZdsyUYHOksG/UHIiKfjxzRxYJpyVBwYaQeOvghal9fcc4PidlgzugAQg==" + }, + "react-is": { + "version": "18.2.0", + "resolved": "https://registry.npmjs.org/react-is/-/react-is-18.2.0.tgz", + "integrity": "sha512-xWGDIW6x921xtzPkhiULtthJHoJvBbF3q26fzloPCK0hsvxtPVelvftw3zjbHWSkR2km9Z+4uxbDDK/6Zw9B8w==" + }, + "react-transition-group": { + "version": "4.4.5", + "resolved": "https://registry.npmjs.org/react-transition-group/-/react-transition-group-4.4.5.tgz", + "integrity": "sha512-pZcd1MCJoiKiBR2NRxeCRg13uCXbydPnmB4EOeRrY7480qNWO8IIgQG6zlDkm6uRMsURXPuKq0GWtiM59a5Q6g==", + "requires": { + "@babel/runtime": "^7.5.5", + "dom-helpers": "^5.0.1", + "loose-envify": "^1.4.0", + "prop-types": "^15.6.2" + } + }, + "regenerator-runtime": { + "version": "0.13.10", + "resolved": "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.13.10.tgz", + "integrity": "sha512-KepLsg4dU12hryUO7bp/axHAKvwGOCV0sGloQtpagJ12ai+ojVDqkeGSiRX1zlq+kjIMZ1t7gpze+26QqtdGqw==" + }, + "rifm": { + "version": "0.12.1", + "resolved": "https://registry.npmjs.org/rifm/-/rifm-0.12.1.tgz", + "integrity": "sha512-OGA1Bitg/dSJtI/c4dh90svzaUPt228kzFsUkJbtA2c964IqEAwWXeL9ZJi86xWv3j5SMqRvGULl7bA6cK0Bvg==" + } + } + }, + "@mui/x-license-pro": { + "version": "5.17.11", + "resolved": "https://registry.npmjs.org/@mui/x-license-pro/-/x-license-pro-5.17.11.tgz", + "integrity": "sha512-Eu5ECjxDK5wyQEqMpTX3BwKqEGtwfdNyqH7mE+4sXt/75ALO41vzOv/6z3EoKVh7Lz32pnVV797wrOOBdmUrwA==", + "requires": { + "@babel/runtime": "^7.18.9", + "@mui/utils": "^5.10.3" + }, + "dependencies": { + "@babel/runtime": { + "version": "7.20.1", + "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.20.1.tgz", + "integrity": "sha512-mrzLkl6U9YLF8qpqI7TB82PESyEGjm/0Ly91jG575eVxMMlb8fYfOXFZIJ8XfLrJZQbm7dlKry2bJmXBUEkdFg==", + "requires": { + "regenerator-runtime": "^0.13.10" + } + }, + "@mui/utils": { + "version": "5.10.14", + "resolved": "https://registry.npmjs.org/@mui/utils/-/utils-5.10.14.tgz", + "integrity": "sha512-12p59+wDZpA++XVJmKwqsZmrA1nmUQ5d0a1yQWtcDjxNyER1EDzozYN/db+FY2i5ceQh2TynPTEwGms2mXDwFg==", + "requires": { + "@babel/runtime": "^7.20.1", + "@types/prop-types": "^15.7.5", + "@types/react-is": "^16.7.1 || ^17.0.0", + "prop-types": "^15.8.1", + "react-is": "^18.2.0" + } + }, + "@types/prop-types": { + "version": "15.7.5", + "resolved": "https://registry.npmjs.org/@types/prop-types/-/prop-types-15.7.5.tgz", + "integrity": "sha512-JCB8C6SnDoQf0cNycqd/35A7MjcnK+ZTqE7judS6o7utxUCg6imJg3QK2qzHKszlTjcj2cn+NwMB2i96ubpj7w==" + }, + "prop-types": { + "version": "15.8.1", + "resolved": "https://registry.npmjs.org/prop-types/-/prop-types-15.8.1.tgz", + "integrity": "sha512-oj87CgZICdulUohogVAR7AjlC0327U4el4L6eAvOqCeudMDVU0NThNaV+b9Df4dXgSP1gXMTnPdhfe/2qDH5cg==", + "requires": { + "loose-envify": "^1.4.0", + "object-assign": "^4.1.1", + "react-is": "^16.13.1" + }, + "dependencies": { + "react-is": { + "version": "16.13.1", + "resolved": "https://registry.npmjs.org/react-is/-/react-is-16.13.1.tgz", + "integrity": "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==" + } + } + }, + "react-is": { + "version": "18.2.0", + "resolved": "https://registry.npmjs.org/react-is/-/react-is-18.2.0.tgz", + "integrity": "sha512-xWGDIW6x921xtzPkhiULtthJHoJvBbF3q26fzloPCK0hsvxtPVelvftw3zjbHWSkR2km9Z+4uxbDDK/6Zw9B8w==" + }, + "regenerator-runtime": { + "version": "0.13.10", + "resolved": "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.13.10.tgz", + "integrity": "sha512-KepLsg4dU12hryUO7bp/axHAKvwGOCV0sGloQtpagJ12ai+ojVDqkeGSiRX1zlq+kjIMZ1t7gpze+26QqtdGqw==" + } + } + }, "@nodelib/fs.scandir": { "version": "2.1.5", "resolved": "https://registry.npmjs.org/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz", @@ -7473,12 +7810,6 @@ "defer-to-connect": "^2.0.0" } }, - "@testim/chrome-version": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/@testim/chrome-version/-/chrome-version-1.1.2.tgz", - "integrity": "sha512-1c4ZOETSRpI0iBfIFUqU4KqwBAB2lHUAlBjZz/YqOHqwM9dTTzjV6Km0ZkiEiSCx/tLr1BtESIKyWWMww+RUqw==", - "dev": true - }, "@tootallnate/once": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/@tootallnate/once/-/once-1.1.2.tgz", @@ -8029,16 +8360,6 @@ "integrity": "sha512-7tFImggNeNBVMsn0vLrpn1H1uPrUBdnARPTpZoitY37ZrdJREzf7I16tMrlK3hen349gr1NYh8CmZQa7CTG6Aw==", "dev": true }, - "@types/yauzl": { - "version": "2.10.0", - "resolved": "https://registry.npmjs.org/@types/yauzl/-/yauzl-2.10.0.tgz", - "integrity": "sha512-Cn6WYCm0tXv8p6k+A8PvbDG763EDpBoTzHdA+Q/MF6H3sapGjCm9NzoaJncJS9tUKSuCoDs9XHxYYsQDgxR6kw==", - "dev": true, - "optional": true, - "requires": { - "@types/node": "*" - } - }, "@webassemblyjs/ast": { "version": "1.9.0", "resolved": "https://registry.npmjs.org/@webassemblyjs/ast/-/ast-1.9.0.tgz", @@ -10630,50 +10951,6 @@ "integrity": "sha512-p3KULyQg4S7NIHixdwbGX+nFHkoBiA4YQmyWtjb8XngSKV124nJmRysgAeujbUVb15vh+RvFUfCPqU7rXk+hZg==", "dev": true }, - "chromedriver": { - "version": "105.0.0", - "resolved": "https://registry.npmjs.org/chromedriver/-/chromedriver-105.0.0.tgz", - "integrity": "sha512-BX3GOUW5m6eiW9cVVF8hw+EFxvrGqYCxbwOqnpk8PjbNFqL5xjy7yel+e6ilJPjckAYFutMKs8XJvOs/W85vvg==", - "dev": true, - "requires": { - "@testim/chrome-version": "^1.1.2", - "axios": "^0.27.2", - "del": "^6.0.0", - "extract-zip": "^2.0.1", - "https-proxy-agent": "^5.0.0", - "proxy-from-env": "^1.1.0", - "tcp-port-used": "^1.0.1" - }, - "dependencies": { - "axios": { - "version": "0.27.2", - "resolved": "https://registry.npmjs.org/axios/-/axios-0.27.2.tgz", - "integrity": "sha512-t+yRIyySRTp/wua5xEr+z1q60QmLq8ABsS5O9Me1AsE5dfKqgnCFzwiCZZ/cGNd1lq4/7akDWMxdhVlucjmnOQ==", - "dev": true, - "requires": { - "follow-redirects": "^1.14.9", - "form-data": "^4.0.0" - } - }, - "follow-redirects": { - "version": "1.15.1", - "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.1.tgz", - "integrity": "sha512-yLAMQs+k0b2m7cVxpS1VKJVvoz7SS9Td1zss3XRwXj+ZDH00RJgnuLx7E44wx02kQLrdM3aOOy+FpzS7+8OizA==", - "dev": true - }, - "form-data": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.0.tgz", - "integrity": "sha512-ETEklSGi5t0QMZuiXoA/Q6vcnxcLQP5vdugSpuAyi6SVGi2clPPp+xgEhuMaHC+zGgn31Kd235W35f7Hykkaww==", - "dev": true, - "requires": { - "asynckit": "^0.4.0", - "combined-stream": "^1.0.8", - "mime-types": "^2.1.12" - } - } - } - }, "ci-info": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-2.0.0.tgz", @@ -12536,6 +12813,11 @@ } } }, + "dayjs": { + "version": "1.11.6", + "resolved": "https://registry.npmjs.org/dayjs/-/dayjs-1.11.6.tgz", + "integrity": "sha512-zZbY5giJAinCG+7AGaw0wIhNZ6J8AhWuSXKvuc1KAyMiRsvGQWqh4L+MomvhdAYjN+lqvVCMq1I41e3YHvXkyQ==" + }, "debug": { "version": "4.3.2", "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.2.tgz", @@ -12674,22 +12956,6 @@ } } }, - "del": { - "version": "6.1.1", - "resolved": "https://registry.npmjs.org/del/-/del-6.1.1.tgz", - "integrity": "sha512-ua8BhapfP0JUJKC/zV9yHHDW/rDoDxP4Zhn3AkA6/xT6gY7jYXJiaeyBZznYVujhZZET+UgcbZiQ7sN3WqcImg==", - "dev": true, - "requires": { - "globby": "^11.0.1", - "graceful-fs": "^4.2.4", - "is-glob": "^4.0.1", - "is-path-cwd": "^2.2.0", - "is-path-inside": "^3.0.2", - "p-map": "^4.0.0", - "rimraf": "^3.0.2", - "slash": "^3.0.0" - } - }, "delayed-stream": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", @@ -14578,29 +14844,6 @@ } } }, - "extract-zip": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/extract-zip/-/extract-zip-2.0.1.tgz", - "integrity": "sha512-GDhU9ntwuKyGXdZBUgTIe+vXnWj0fppUEtMDL0+idd5Sta8TGpHssn/eusA9mrPr9qNDym6SxAYZjNvCn/9RBg==", - "dev": true, - "requires": { - "@types/yauzl": "^2.9.1", - "debug": "^4.1.1", - "get-stream": "^5.1.0", - "yauzl": "^2.10.0" - }, - "dependencies": { - "get-stream": { - "version": "5.2.0", - "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-5.2.0.tgz", - "integrity": "sha512-nBF+F1rAZVCu/p7rjzgA+Yb4lfYXrpl7a6VmJrU8wF9I1CKvP/QwPNZHnOlwbTkY6dvtFIzFMSyQXbLoTQPRpA==", - "dev": true, - "requires": { - "pump": "^3.0.0" - } - } - } - }, "extsprintf": { "version": "1.3.0", "resolved": "https://registry.npmjs.org/extsprintf/-/extsprintf-1.3.0.tgz", @@ -16927,12 +17170,6 @@ "integrity": "sha1-vd7XARQpCCjAoDnnLvJfWq7ENUo=", "dev": true }, - "ip-regex": { - "version": "4.3.0", - "resolved": "https://registry.npmjs.org/ip-regex/-/ip-regex-4.3.0.tgz", - "integrity": "sha512-B9ZWJxHHOHUhUjCPrMpLD4xEq35bUTClHM1S6CBU5ixQnkZmwipwgc96vAd7AAGM9TGHvJR+Uss+/Ak6UphK+Q==", - "dev": true - }, "ipaddr.js": { "version": "1.9.1", "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz", @@ -17233,12 +17470,6 @@ "integrity": "sha512-2rRIahhZr2UWb45fIOuvZGpFtz0TyOZLf32KxBbSoUCeZR495zCKlWUKKUByk3geS2eAs7ZAABt0Y/Rx0GiQGA==", "dev": true }, - "is-path-cwd": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/is-path-cwd/-/is-path-cwd-2.2.0.tgz", - "integrity": "sha512-w942bTcih8fdJPJmQHFzkS76NEP8Kzzvmw92cXsazb8intwLqPibPPdXf4ANdKV3rYMuuQYGIWtvz9JilB3NFQ==", - "dev": true - }, "is-path-inside": { "version": "3.0.3", "resolved": "https://registry.npmjs.org/is-path-inside/-/is-path-inside-3.0.3.tgz", @@ -17344,12 +17575,6 @@ "resolved": "https://registry.npmjs.org/is-typedarray/-/is-typedarray-1.0.0.tgz", "integrity": "sha1-5HnICFjfDBsR3dppQPlgEfzaSpo=" }, - "is-url": { - "version": "1.2.4", - "resolved": "https://registry.npmjs.org/is-url/-/is-url-1.2.4.tgz", - "integrity": "sha512-ITvGim8FhRiYe4IQ5uHSkj7pVaPDrCTkNd3yq3cV7iZAcJdHTUMPMEHcqSOy9xZ9qFenQCvi+2wjH9a1nXqHww==", - "dev": true - }, "is-utf8": { "version": "0.2.1", "resolved": "https://registry.npmjs.org/is-utf8/-/is-utf8-0.2.1.tgz", @@ -17388,17 +17613,6 @@ "integrity": "sha512-VjSeb/lHmkoyd8ryPVIKvOCn4D1koMqY+vqyjjUfc3xyKtP4dYOxM44sZrnqQSzSds3xyOrUTLTC9LVCVgLngw==", "dev": true }, - "is2": { - "version": "2.0.7", - "resolved": "https://registry.npmjs.org/is2/-/is2-2.0.7.tgz", - "integrity": "sha512-4vBQoURAXC6hnLFxD4VW7uc04XiwTTl/8ydYJxKvPwkWQrSjInkuM5VZVg6BGr1/natq69zDuvO9lGpLClJqvA==", - "dev": true, - "requires": { - "deep-is": "^0.1.3", - "ip-regex": "^4.1.0", - "is-url": "^1.2.4" - } - }, "isarray": { "version": "0.0.1", "resolved": "https://registry.npmjs.org/isarray/-/isarray-0.0.1.tgz", @@ -26211,27 +26425,6 @@ "readable-stream": "^3.1.1" } }, - "tcp-port-used": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/tcp-port-used/-/tcp-port-used-1.0.2.tgz", - "integrity": "sha512-l7ar8lLUD3XS1V2lfoJlCBaeoaWo/2xfYt81hM7VlvR4RrMVFqfmzfhLVk40hAb368uitje5gPtBRL1m/DGvLA==", - "dev": true, - "requires": { - "debug": "4.3.1", - "is2": "^2.0.6" - }, - "dependencies": { - "debug": { - "version": "4.3.1", - "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.1.tgz", - "integrity": "sha512-doEwdvm4PCeK4K3RQN2ZC2BYUBaxwLARCqZmMjtF8a51J2Rb0xpVloFRnCODwqjpwnAoao4pelN8l3RJdv3gRQ==", - "dev": true, - "requires": { - "ms": "2.1.2" - } - } - } - }, "telejson": { "version": "5.3.3", "resolved": "https://registry.npmjs.org/telejson/-/telejson-5.3.3.tgz", diff --git a/packages/yoroi-extension/package.json b/packages/yoroi-extension/package.json index 45ee260259..fc4346dea8 100644 --- a/packages/yoroi-extension/package.json +++ b/packages/yoroi-extension/package.json @@ -173,10 +173,6 @@ }, "dependencies": { "@cardano-foundation/ledgerjs-hw-app-cardano": "5.1.0", - "@ledgerhq/hw-transport-u2f": "5.36.0-deprecated", - "@ledgerhq/hw-transport-webauthn": "5.36.0-deprecated", - "@ledgerhq/hw-transport-webusb": "5.49.0", - "@ledgerhq/hw-transport-webhid": "5.51.1", "@download/blockies": "1.0.3", "@emotion/react": "^11.4.1", "@emotion/styled": "^11.3.0", @@ -185,8 +181,13 @@ "@emurgo/cip14-js": "2.0.0", "@emurgo/cip4-js": "1.0.5", "@emurgo/js-chain-libs": "0.7.1", + "@ledgerhq/hw-transport-u2f": "5.36.0-deprecated", + "@ledgerhq/hw-transport-webauthn": "5.36.0-deprecated", + "@ledgerhq/hw-transport-webhid": "5.51.1", + "@ledgerhq/hw-transport-webusb": "5.49.0", "@mui/lab": "^5.0.0-alpha.51", "@mui/material": "^5.0.4", + "@mui/x-date-pickers-pro": "^5.0.8", "@svgr/webpack": "5.5.0", "async-mutex": "^0.3.1", "axios": "0.21.1", @@ -204,6 +205,7 @@ "classnames": "2.2.6", "crypto-browserify": "3.12.0", "crypto-random-string": "3.3.1", + "dayjs": "^1.11.6", "downshift": "^6.1.7", "dropbox": "4.0.30", "ergo-lib-wasm-browser": "^0.14.0", From fd3d0813e2e919527b92e0a6a2394ccf7ad3287b Mon Sep 17 00:00:00 2001 From: Ahmed Ibrahim Date: Tue, 15 Nov 2022 14:32:19 +0200 Subject: [PATCH 042/172] Add start and ending date --- .../app/components/wallet/export/DateRange.js | 39 +- .../wallet/export/ExportTransactionDialog.js | 12 +- packages/yoroi-extension/package-lock.json | 340 ++++++++---------- packages/yoroi-extension/package.json | 2 +- 4 files changed, 174 insertions(+), 219 deletions(-) diff --git a/packages/yoroi-extension/app/components/wallet/export/DateRange.js b/packages/yoroi-extension/app/components/wallet/export/DateRange.js index 9a57da9ec6..0dd31440a0 100644 --- a/packages/yoroi-extension/app/components/wallet/export/DateRange.js +++ b/packages/yoroi-extension/app/components/wallet/export/DateRange.js @@ -1,10 +1,9 @@ // @flow import { Component } from 'react' import TextField from '@mui/material/TextField'; -import Box from '@mui/material/Box'; -import { LocalizationProvider } from '@mui/x-date-pickers-pro'; -import { AdapterDayjs } from '@mui/x-date-pickers-pro/AdapterDayjs'; -import { DateRangePicker } from '@mui/x-date-pickers-pro/DateRangePicker'; +import { AdapterDayjs } from '@mui/x-date-pickers/AdapterDayjs'; +import { LocalizationProvider } from '@mui/x-date-pickers/LocalizationProvider'; +import { DatePicker } from '@mui/x-date-pickers/DatePicker'; import { observer } from 'mobx-react'; type Props = {| @@ -15,24 +14,24 @@ type Props = {| @observer export default class ExportTransactionDialog extends Component { render() { - const { date, setDate } = this.props; + const { date, setStartDate, setEndDate } = this.props; return ( - - { - setDate(newDate); + + { + setStartDate(newValue); }} - renderInput={(startProps, endProps) => ( - <> - - to - - - )} + renderInput={(params) => } + /> + { + setEndDate(newValue); + }} + renderInput={(params) => } /> ) diff --git a/packages/yoroi-extension/app/components/wallet/export/ExportTransactionDialog.js b/packages/yoroi-extension/app/components/wallet/export/ExportTransactionDialog.js index 3690842733..110dfde122 100644 --- a/packages/yoroi-extension/app/components/wallet/export/ExportTransactionDialog.js +++ b/packages/yoroi-extension/app/components/wallet/export/ExportTransactionDialog.js @@ -50,7 +50,7 @@ export default class ExportTransactionDialog extends Component { state = { startDate: null, endDate: null, - } + } render(): Node { const { intl } = this.context; @@ -86,7 +86,15 @@ export default class ExportTransactionDialog extends Component { onClose={cancel} > {infoBlock} - + { + this.setState({ startDate: date })} + } + setEndDate={(date) => { + this.setState({ endDate: date })} + } + />
Date: Wed, 16 Nov 2022 18:19:51 +0800 Subject: [PATCH 043/172] remove dead code --- .../ergo-connector/stores/ConnectorStore.js | 79 +------------------ .../chrome/extension/ergo-connector/types.js | 4 - 2 files changed, 1 insertion(+), 82 deletions(-) diff --git a/packages/yoroi-extension/app/ergo-connector/stores/ConnectorStore.js b/packages/yoroi-extension/app/ergo-connector/stores/ConnectorStore.js index 93606e6ae0..702ac19e1e 100644 --- a/packages/yoroi-extension/app/ergo-connector/stores/ConnectorStore.js +++ b/packages/yoroi-extension/app/ergo-connector/stores/ConnectorStore.js @@ -310,9 +310,6 @@ export default class ConnectorStore extends Store { if (response.sign.type === 'tx/cardano') { this.createAdaTransaction(); } - if (response.sign.type === 'tx-create-req/cardano') { - this.generateAdaTransaction(); - } if (response.sign.type === 'tx-reorg/cardano') { this.generateReorgTransaction(); } @@ -393,8 +390,7 @@ export default class ConnectorStore extends Store { } else if ( signingMessage.sign.type === 'tx' || signingMessage.sign.type === 'tx_input' || - signingMessage.sign.type === 'tx/cardano' || - signingMessage.sign.type === 'tx-create-req/cardano' + signingMessage.sign.type === 'tx/cardano' ) { sendData = { type: 'sign_confirmed', @@ -463,7 +459,6 @@ export default class ConnectorStore extends Store { if ( this.signingMessage?.sign.type !== 'tx/cardano' && - this.signingMessage?.sign.type !== 'tx-create-req/cardano' && this.signingMessage?.sign.type !== 'tx-reorg/cardano' ) { await this._getTxAssets(filteredWallets); @@ -483,9 +478,6 @@ export default class ConnectorStore extends Store { if (this.signingMessage?.sign.type === 'tx/cardano') { this.createAdaTransaction(); } - if (this.signingMessage?.sign.type === 'tx-create-req/cardano') { - this.generateAdaTransaction(); - } if (this.signingMessage?.sign.type === 'tx-reorg/cardano') { this.generateReorgTransaction(); } @@ -767,75 +759,6 @@ export default class ConnectorStore extends Store { }; } - generateAdaTransaction: void => Promise = async () => { - if (this.signingMessage == null) return; - const { signingMessage } = this; - const selectedWallet = this.wallets.find( - wallet => wallet.publicDeriver.getPublicDeriverId() === signingMessage.publicDeriverId - ); - - if (selectedWallet == null) return undefined; - if (!signingMessage.sign.tx) return undefined; - - const network = selectedWallet.publicDeriver.getParent().getNetworkInfo(); - - if (isCardanoHaskell(network)) { - const withUtxos = asGetAllUtxos(selectedWallet.publicDeriver); - if (withUtxos == null) { - throw new Error(`missing utxo functionality`); - } - - const withHasUtxoChains = asHasUtxoChains(withUtxos); - if (withHasUtxoChains == null) { - throw new Error(`missing chains functionality`); - } - - const fullConfig = getCardanoHaskellBaseConfig(network); - const timeToSlot = await genTimeToSlot(fullConfig); - const absSlotNumber = new BigNumber(timeToSlot({ - time: new Date(), - }).slot); - - const foreignUtxoFetcher: ForeignUtxoFetcher = ConnectorStore.createForeignUtxoFetcher( - this.stores.substores.ada.stateFetchStore.fetcher, - selectedWallet.publicDeriver.getParent().getNetworkInfo(), - ) - const result = await this.api.ada.createUnsignedTxForConnector( - { - publicDeriver: withHasUtxoChains, - absSlotNumber, - cardanoTxRequest: (signingMessage.sign: any).tx, - submittedTxs: [], - utxos: [], - }, - foreignUtxoFetcher, - ); - const fee = { - tokenId: result.fee().getDefaultEntry().identifier, - networkId: result.fee().getDefaultEntry().networkId, - amount: result.fee().getDefaultEntry().amount.toString(), - }; - const { amount, total } = await this._calculateAmountAndTotal( - selectedWallet.publicDeriver, - result.inputs(), - result.outputs(), - fee, - [], - ); - runInAction(() => { - this.adaTransaction = { - inputs: result.inputs(), - outputs: result.outputs(), - fee, - amount, - total, - }; - }); - } else { - throw new Error(`${nameof(ConnectorStore)}::${nameof(this.createAdaTransaction)} unexpected wallet type`); - } - } - generateReorgTransaction: void => Promise = async () => { if (this.signingMessage == null) return; const { signingMessage } = this; diff --git a/packages/yoroi-extension/chrome/extension/ergo-connector/types.js b/packages/yoroi-extension/chrome/extension/ergo-connector/types.js index 598961c76a..a78b796dfb 100644 --- a/packages/yoroi-extension/chrome/extension/ergo-connector/types.js +++ b/packages/yoroi-extension/chrome/extension/ergo-connector/types.js @@ -462,10 +462,6 @@ export type PendingSignData = {| type: 'tx/cardano', uid: RpcUid, tx: CardanoTx, -|} | {| - type: 'tx-create-req/cardano', - uid: RpcUid, - tx: CardanoTxRequest, |} | {| type: 'tx-reorg/cardano', uid: RpcUid, From 0e40974f9225ee7795c7b276549e4972058de711 Mon Sep 17 00:00:00 2001 From: yushi Date: Wed, 16 Nov 2022 18:36:52 +0800 Subject: [PATCH 044/172] remove useless connector actions --- .../app/ergo-connector/actions/connector-actions.js | 2 -- .../app/ergo-connector/containers/ConnectContainer.js | 4 ---- .../app/ergo-connector/containers/ConnectContainer.stories.js | 1 - .../app/ergo-connector/stores/ConnectorStore.js | 2 -- 4 files changed, 9 deletions(-) diff --git a/packages/yoroi-extension/app/ergo-connector/actions/connector-actions.js b/packages/yoroi-extension/app/ergo-connector/actions/connector-actions.js index c3978e3e17..72537c74e7 100644 --- a/packages/yoroi-extension/app/ergo-connector/actions/connector-actions.js +++ b/packages/yoroi-extension/app/ergo-connector/actions/connector-actions.js @@ -4,8 +4,6 @@ import type { WhitelistEntry } from '../../../chrome/extension/ergo-connector/ty // ======= CONNECTOR ACTIONS ======= export default class ConnectorActions { - getResponse: AsyncAction = new AsyncAction(); - getSigningMsg: AsyncAction = new AsyncAction(); refreshActiveSites: AsyncAction = new AsyncAction(); refreshWallets: AsyncAction = new AsyncAction(); closeWindow: Action = new Action(); diff --git a/packages/yoroi-extension/app/ergo-connector/containers/ConnectContainer.js b/packages/yoroi-extension/app/ergo-connector/containers/ConnectContainer.js index e721daf94f..7e6fdad795 100644 --- a/packages/yoroi-extension/app/ergo-connector/containers/ConnectContainer.js +++ b/packages/yoroi-extension/app/ergo-connector/containers/ConnectContainer.js @@ -195,9 +195,6 @@ export default class ConnectContainer extends Component< @computed get generated(): {| actions: {| connector: {| - getResponse: {| - trigger: (params: void) => Promise, - |}, refreshWallets: {| trigger: (params: void) => Promise, |}, @@ -269,7 +266,6 @@ export default class ConnectContainer extends Component< }, actions: { connector: { - getResponse: { trigger: actions.connector.getResponse.trigger }, refreshWallets: { trigger: actions.connector.refreshWallets.trigger }, closeWindow: { trigger: actions.connector.closeWindow.trigger }, getConnectorWhitelist: { trigger: actions.connector.getConnectorWhitelist.trigger }, diff --git a/packages/yoroi-extension/app/ergo-connector/containers/ConnectContainer.stories.js b/packages/yoroi-extension/app/ergo-connector/containers/ConnectContainer.stories.js index 3c92c72120..3964ecab00 100644 --- a/packages/yoroi-extension/app/ergo-connector/containers/ConnectContainer.stories.js +++ b/packages/yoroi-extension/app/ergo-connector/containers/ConnectContainer.stories.js @@ -92,7 +92,6 @@ export const Generic = (): Node => { }, actions: { connector: { - getResponse: { trigger: async (req) => action('getResponse')(req) }, getConnectorWhitelist: { trigger: async (req) => action('getConnectorWhitelist')(req) }, updateConnectorWhitelist: { trigger: async (req) => action('updateConnectorWhitelist')(req) }, refreshWallets: { trigger: async (req) => action('refreshWallets')(req) }, diff --git a/packages/yoroi-extension/app/ergo-connector/stores/ConnectorStore.js b/packages/yoroi-extension/app/ergo-connector/stores/ConnectorStore.js index 702ac19e1e..ae4a697d51 100644 --- a/packages/yoroi-extension/app/ergo-connector/stores/ConnectorStore.js +++ b/packages/yoroi-extension/app/ergo-connector/stores/ConnectorStore.js @@ -249,7 +249,6 @@ export default class ConnectorStore extends Store { setup(): void { super.setup(); - this.actions.connector.getResponse.listen(this._getConnectingMsg); this.actions.connector.getConnectorWhitelist.listen(this._getConnectorWhitelist); this.actions.connector.updateConnectorWhitelist.listen(this._updateConnectorWhitelist); this.actions.connector.removeWalletFromWhitelist.listen(this._removeWalletFromWhitelist); @@ -257,7 +256,6 @@ export default class ConnectorStore extends Store { this._confirmSignInTx(password); }); this.actions.connector.cancelSignInTx.listen(this._cancelSignInTx); - this.actions.connector.getSigningMsg.listen(this._getSigningMsg); this.actions.connector.refreshActiveSites.listen(this._refreshActiveSites); this.actions.connector.refreshWallets.listen(this._getWallets); this.actions.connector.closeWindow.listen(this._closeWindow); From e7c58fcbe87d897e359dabe5d622f73cb3a721c4 Mon Sep 17 00:00:00 2001 From: yushi Date: Wed, 16 Nov 2022 18:59:01 +0800 Subject: [PATCH 045/172] remove useless action listen and trigger --- .../app/ergo-connector/containers/ConnectContainer.js | 5 ----- .../ergo-connector/containers/ConnectContainer.stories.js | 1 - .../app/ergo-connector/stores/ConnectorStore.js | 1 - 3 files changed, 7 deletions(-) diff --git a/packages/yoroi-extension/app/ergo-connector/containers/ConnectContainer.js b/packages/yoroi-extension/app/ergo-connector/containers/ConnectContainer.js index 7e6fdad795..a9ef8b26a7 100644 --- a/packages/yoroi-extension/app/ergo-connector/containers/ConnectContainer.js +++ b/packages/yoroi-extension/app/ergo-connector/containers/ConnectContainer.js @@ -57,7 +57,6 @@ export default class ConnectContainer extends Component< // eslint-disable-next-line camelcase UNSAFE_componentWillMount() { this.generated.actions.connector.refreshWallets.trigger(); - this.generated.actions.connector.getConnectorWhitelist.trigger(); window.addEventListener('unload', this.onUnload); } @@ -201,9 +200,6 @@ export default class ConnectContainer extends Component< closeWindow: {| trigger: (params: void) => void, |}, - getConnectorWhitelist: {| - trigger: (params: void) => Promise, - |}, updateHideBalance: {| trigger: (params: void) => Promise, |}, @@ -268,7 +264,6 @@ export default class ConnectContainer extends Component< connector: { refreshWallets: { trigger: actions.connector.refreshWallets.trigger }, closeWindow: { trigger: actions.connector.closeWindow.trigger }, - getConnectorWhitelist: { trigger: actions.connector.getConnectorWhitelist.trigger }, updateConnectorWhitelist: { trigger: actions.connector.updateConnectorWhitelist.trigger }, updateHideBalance: { trigger: actions.profile.updateHideBalance.trigger }, }, diff --git a/packages/yoroi-extension/app/ergo-connector/containers/ConnectContainer.stories.js b/packages/yoroi-extension/app/ergo-connector/containers/ConnectContainer.stories.js index 3964ecab00..f7450fb2c7 100644 --- a/packages/yoroi-extension/app/ergo-connector/containers/ConnectContainer.stories.js +++ b/packages/yoroi-extension/app/ergo-connector/containers/ConnectContainer.stories.js @@ -92,7 +92,6 @@ export const Generic = (): Node => { }, actions: { connector: { - getConnectorWhitelist: { trigger: async (req) => action('getConnectorWhitelist')(req) }, updateConnectorWhitelist: { trigger: async (req) => action('updateConnectorWhitelist')(req) }, refreshWallets: { trigger: async (req) => action('refreshWallets')(req) }, closeWindow: { trigger: action('closeWindow') }, diff --git a/packages/yoroi-extension/app/ergo-connector/stores/ConnectorStore.js b/packages/yoroi-extension/app/ergo-connector/stores/ConnectorStore.js index ae4a697d51..c40dfd413e 100644 --- a/packages/yoroi-extension/app/ergo-connector/stores/ConnectorStore.js +++ b/packages/yoroi-extension/app/ergo-connector/stores/ConnectorStore.js @@ -249,7 +249,6 @@ export default class ConnectorStore extends Store { setup(): void { super.setup(); - this.actions.connector.getConnectorWhitelist.listen(this._getConnectorWhitelist); this.actions.connector.updateConnectorWhitelist.listen(this._updateConnectorWhitelist); this.actions.connector.removeWalletFromWhitelist.listen(this._removeWalletFromWhitelist); this.actions.connector.confirmSignInTx.listen((password) => { From 90a9ac73a0813da31326e7c4d9ef06392c0e4fa5 Mon Sep 17 00:00:00 2001 From: Ahmed Ibrahim Date: Wed, 16 Nov 2022 21:32:34 +0200 Subject: [PATCH 046/172] Move CSS styles into JS file --- .../wallet/export/ExportTransactionDialog.js | 32 +++++++++++-------- .../export/ExportTransactionDialog.scss | 11 ------- 2 files changed, 19 insertions(+), 24 deletions(-) delete mode 100644 packages/yoroi-extension/app/components/wallet/export/ExportTransactionDialog.scss diff --git a/packages/yoroi-extension/app/components/wallet/export/ExportTransactionDialog.js b/packages/yoroi-extension/app/components/wallet/export/ExportTransactionDialog.js index 110dfde122..6053b10242 100644 --- a/packages/yoroi-extension/app/components/wallet/export/ExportTransactionDialog.js +++ b/packages/yoroi-extension/app/components/wallet/export/ExportTransactionDialog.js @@ -4,17 +4,15 @@ import { Component } from 'react'; import { observer } from 'mobx-react'; import classnames from 'classnames'; import { defineMessages, intlShape } from 'react-intl'; - import LocalizableError from '../../../i18n/LocalizableError'; import type { $npm$ReactIntl$IntlFormat } from 'react-intl'; import Dialog from '../../widgets/Dialog'; import DialogCloseButton from '../../widgets/DialogCloseButton'; import ErrorBlock from '../../widgets/ErrorBlock'; import globalMessages from '../../../i18n/global-messages'; - -import styles from './ExportTransactionDialog.scss'; import CheckboxLabel from '../../common/CheckboxLabel'; import DateRange from './DateRange' +import { Box } from '@mui/system'; const messages = defineMessages({ dialogTitle: { @@ -65,9 +63,19 @@ export default class ExportTransactionDialog extends Component { const { startDate, endDate } = this.state; const infoBlock = ( -
+ {intl.formatMessage(messages.infoText1)} -
); + ); const dialogActions = [{ label: intl.formatMessage(globalMessages.exportButtonLabel), @@ -78,7 +86,7 @@ export default class ExportTransactionDialog extends Component { return ( { this.setState({ endDate: date })} } /> -
- -
+ {error && }
); } diff --git a/packages/yoroi-extension/app/components/wallet/export/ExportTransactionDialog.scss b/packages/yoroi-extension/app/components/wallet/export/ExportTransactionDialog.scss deleted file mode 100644 index a2fe40ab12..0000000000 --- a/packages/yoroi-extension/app/components/wallet/export/ExportTransactionDialog.scss +++ /dev/null @@ -1,11 +0,0 @@ -.infoBlock { - font-weight: 400; - font-size: 15px; - opacity: 0.7; - text-align: center; - padding: 10px 0 0 0; -} - -.includeTxIds { - margin-top: 20px; -} \ No newline at end of file From a65db224613baa2d238271bc298407054c85780e Mon Sep 17 00:00:00 2001 From: Ahmed Ibrahim Date: Wed, 16 Nov 2022 22:35:52 +0200 Subject: [PATCH 047/172] Add date interval validation --- .../app/components/wallet/export/DateRange.js | 33 +++++++++++++++---- 1 file changed, 26 insertions(+), 7 deletions(-) diff --git a/packages/yoroi-extension/app/components/wallet/export/DateRange.js b/packages/yoroi-extension/app/components/wallet/export/DateRange.js index 0dd31440a0..3624817eea 100644 --- a/packages/yoroi-extension/app/components/wallet/export/DateRange.js +++ b/packages/yoroi-extension/app/components/wallet/export/DateRange.js @@ -15,24 +15,43 @@ type Props = {| export default class ExportTransactionDialog extends Component { render() { const { date, setStartDate, setEndDate } = this.props; + const invalidInterval = ( + date.startDate && date.endDate && date.startDate.isAfter(date.endDate) + ); return ( { - setStartDate(newValue); + onChange={(newDate) => { + setStartDate(newDate); }} - renderInput={(params) => } + renderInput={(params) => ( + + )} /> { - setEndDate(newValue); + value={date.endDate} + onChange={(newDate) => { + setEndDate(newDate); }} - renderInput={(params) => } + renderInput={(params) => ( + + )} /> + {/* + {invalidInterval && 'Invalid Interval'} + */} ) } From 922f22ad7fd160cbabc03f6b5486d09f5e4f5dc3 Mon Sep 17 00:00:00 2001 From: yushi Date: Thu, 17 Nov 2022 11:55:57 +0800 Subject: [PATCH 048/172] remove unused imports --- .../app/ergo-connector/stores/ConnectorStore.js | 4 ---- 1 file changed, 4 deletions(-) diff --git a/packages/yoroi-extension/app/ergo-connector/stores/ConnectorStore.js b/packages/yoroi-extension/app/ergo-connector/stores/ConnectorStore.js index c40dfd413e..27bf484457 100644 --- a/packages/yoroi-extension/app/ergo-connector/stores/ConnectorStore.js +++ b/packages/yoroi-extension/app/ergo-connector/stores/ConnectorStore.js @@ -29,16 +29,13 @@ import type { import { LoadingWalletStates } from '../types'; import { getWallets } from '../../api/common/index'; import { - getCardanoHaskellBaseConfig, getErgoBaseConfig, isCardanoHaskell, isErgo, } from '../../api/ada/lib/storage/database/prepackaged/networks'; import { - asGetAllUtxos, asGetBalance, asGetPublicKey, - asHasUtxoChains, asGetSigningKey, asHasLevels, } from '../../api/ada/lib/storage/models/PublicDeriver/traits'; @@ -52,7 +49,6 @@ import { toRemoteUtxo } from '../../api/ergo/lib/transactions/utils'; import { mintedTokenInfo } from '../../../chrome/extension/ergo-connector/utils'; import { Logger } from '../../utils/logging'; import { asAddressedUtxo, multiTokenFromCardanoValue, multiTokenFromRemote, } from '../../api/ada/transactions/utils'; -import { genTimeToSlot, } from '../../api/ada/lib/storage/bridge/timeUtils'; import { connectorGetUsedAddresses, connectorGetUnusedAddresses, From 87476cf30a4d609c7ad6db81cf2eb16c5dff0f59 Mon Sep 17 00:00:00 2001 From: Ahmed Ibrahim Date: Thu, 17 Nov 2022 09:41:15 +0200 Subject: [PATCH 049/172] Filter tx rows between two selected dates --- .../wallet/export/ExportTransactionDialog.js | 2 +- .../app/stores/toplevel/TransactionsStore.js | 16 ++++++++++++++-- 2 files changed, 15 insertions(+), 3 deletions(-) diff --git a/packages/yoroi-extension/app/components/wallet/export/ExportTransactionDialog.js b/packages/yoroi-extension/app/components/wallet/export/ExportTransactionDialog.js index 6053b10242..d1cbd61271 100644 --- a/packages/yoroi-extension/app/components/wallet/export/ExportTransactionDialog.js +++ b/packages/yoroi-extension/app/components/wallet/export/ExportTransactionDialog.js @@ -81,7 +81,7 @@ export default class ExportTransactionDialog extends Component { label: intl.formatMessage(globalMessages.exportButtonLabel), primary: true, isSubmitting: isActionProcessing || false, - onClick: submit, + onClick: () => submit({ startDate, endDate }), }]; return ( diff --git a/packages/yoroi-extension/app/stores/toplevel/TransactionsStore.js b/packages/yoroi-extension/app/stores/toplevel/TransactionsStore.js index b13d622471..81cbd365af 100644 --- a/packages/yoroi-extension/app/stores/toplevel/TransactionsStore.js +++ b/packages/yoroi-extension/app/stores/toplevel/TransactionsStore.js @@ -59,6 +59,12 @@ import { } from '../../api/localStorage'; import { assuranceLevels } from '../../config/transactionAssuranceConfig'; import { transactionTypes } from '../../api/ada/transactions/types'; +import dayjs from 'dayjs' +import isSameOrAfter from 'dayjs/plugin/isSameOrAfter'; +import isSameOrBefore from 'dayjs/plugin/isSameOrBefore'; + +dayjs.extend(isSameOrAfter) +dayjs.extend(isSameOrBefore) export type TxRequests = {| publicDeriver: PublicDeriver<>, @@ -712,10 +718,9 @@ export default class TransactionsStore extends Store { if (!withLevels) return; const rows = await this.api[apiType].getTransactionRowsToExport({ publicDeriver: withLevels, - ...request.exportRequest, getDefaultToken: networkId => this.stores.tokenInfoStore.getDefaultTokenInfo(networkId), }); - console.log(JSON.parse(JSON.stringify(rows))) + /** * NOTE: The rewards export currently supports only Haskell Shelley @@ -759,6 +764,13 @@ export default class TransactionsStore extends Store { respTxRows.push(...rows); }).promise; + const { startDate, endDate } = request.exportRequest; + if (startDate && endDate) { + respTxRows = respTxRows.filter(row => { + const txDate = dayjs(row.date); + return txDate.isSameOrAfter(startDate) && txDate.isSameOrBefore(endDate) + }) + } respTxRows = respTxRows.sort((a, b) => { return b.date - a.date; }); From 16df42281cc0a775fe0b2be91fb2c68495a64d2e Mon Sep 17 00:00:00 2001 From: Ahmed Ibrahim Date: Thu, 17 Nov 2022 10:12:20 +0200 Subject: [PATCH 050/172] Include start and end date --- .../app/stores/toplevel/TransactionsStore.js | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/packages/yoroi-extension/app/stores/toplevel/TransactionsStore.js b/packages/yoroi-extension/app/stores/toplevel/TransactionsStore.js index 81cbd365af..c396a437c9 100644 --- a/packages/yoroi-extension/app/stores/toplevel/TransactionsStore.js +++ b/packages/yoroi-extension/app/stores/toplevel/TransactionsStore.js @@ -63,6 +63,7 @@ import dayjs from 'dayjs' import isSameOrAfter from 'dayjs/plugin/isSameOrAfter'; import isSameOrBefore from 'dayjs/plugin/isSameOrBefore'; +// Todo: should be removed dayjs.extend(isSameOrAfter) dayjs.extend(isSameOrBefore) @@ -765,10 +766,15 @@ export default class TransactionsStore extends Store { }).promise; const { startDate, endDate } = request.exportRequest; - if (startDate && endDate) { + if (startDate || endDate) { + const dateFormat = 'MM-DD-YYYY' respTxRows = respTxRows.filter(row => { - const txDate = dayjs(row.date); - return txDate.isSameOrAfter(startDate) && txDate.isSameOrBefore(endDate) + const txDate = dayjs(row.date).format(dateFormat) + if ( + (startDate !== null && startDate.isAfter(txDate, 'day')) || + (endDate !== null && endDate.isBefore(txDate, 'day')) + ) return false; + return true }) } respTxRows = respTxRows.sort((a, b) => { From 81ce7755a809303a02cf340b0e1c887fcc2d02e9 Mon Sep 17 00:00:00 2001 From: Ahmed Ibrahim Date: Thu, 17 Nov 2022 10:50:28 +0200 Subject: [PATCH 051/172] Add intl & disable export for invalid interval --- .../app/components/wallet/export/DateRange.js | 109 +++++++++++------- .../wallet/export/ExportTransactionDialog.js | 8 +- .../app/i18n/locales/en-US.json | 3 + .../app/stores/toplevel/TransactionsStore.js | 6 - 4 files changed, 75 insertions(+), 51 deletions(-) diff --git a/packages/yoroi-extension/app/components/wallet/export/DateRange.js b/packages/yoroi-extension/app/components/wallet/export/DateRange.js index 3624817eea..72cae089f0 100644 --- a/packages/yoroi-extension/app/components/wallet/export/DateRange.js +++ b/packages/yoroi-extension/app/components/wallet/export/DateRange.js @@ -5,55 +5,80 @@ import { AdapterDayjs } from '@mui/x-date-pickers/AdapterDayjs'; import { LocalizationProvider } from '@mui/x-date-pickers/LocalizationProvider'; import { DatePicker } from '@mui/x-date-pickers/DatePicker'; import { observer } from 'mobx-react'; +import { Dayjs } from 'dayjs' +import { defineMessages, intlShape } from 'react-intl'; +import type { $npm$ReactIntl$IntlFormat } from 'react-intl'; + +const messages = defineMessages({ + startDate: { + id: 'wallet.transaction.export.dialog.date.start.label', + defaultMessage: '!!!Start Date', + }, + endDate: { + id: 'wallet.transaction.export.dialog.date.end.label', + defaultMessage: '!!!End Date', + }, + invalidInterval: { + id: 'wallet.transaction.export.dialog.date.error.invalidInterval', + defaultMessage: 'Invalid interval', + }, +}); type Props = {| - date: string, // todo: Add correct type - setDate(): void + date: { + startDate: Dayjs | null, + endDate: Dayjs | null, + }, + setStartDate(Dayjs | null): void, + setEndDate(Dayjs | null): void |} @observer export default class ExportTransactionDialog extends Component { - render() { - const { date, setStartDate, setEndDate } = this.props; - const invalidInterval = ( - date.startDate && date.endDate && date.startDate.isAfter(date.endDate) - ); - return ( - - { - setStartDate(newDate); - }} - renderInput={(params) => ( - - )} + + static contextTypes: {|intl: $npm$ReactIntl$IntlFormat|} = { + intl: intlShape.isRequired + }; + + render() { + const { intl } = this.context; + const { date, setStartDate, setEndDate } = this.props; + const invalidInterval = ( + date.startDate && date.endDate && date.startDate.isAfter(date.endDate) + ); + return ( + + { + setStartDate(newDate); + }} + renderInput={(params) => ( + - { - setEndDate(newDate); - }} - renderInput={(params) => ( - - )} + )} + /> + { + setEndDate(newDate); + }} + renderInput={(params) => ( + - {/* - {invalidInterval && 'Invalid Interval'} - */} - - ) - } + )} + /> + + ) + } } diff --git a/packages/yoroi-extension/app/components/wallet/export/ExportTransactionDialog.js b/packages/yoroi-extension/app/components/wallet/export/ExportTransactionDialog.js index d1cbd61271..818ddd1040 100644 --- a/packages/yoroi-extension/app/components/wallet/export/ExportTransactionDialog.js +++ b/packages/yoroi-extension/app/components/wallet/export/ExportTransactionDialog.js @@ -2,7 +2,6 @@ import type { Node } from 'react'; import { Component } from 'react'; import { observer } from 'mobx-react'; -import classnames from 'classnames'; import { defineMessages, intlShape } from 'react-intl'; import LocalizableError from '../../../i18n/LocalizableError'; import type { $npm$ReactIntl$IntlFormat } from 'react-intl'; @@ -61,7 +60,6 @@ export default class ExportTransactionDialog extends Component { shouldIncludeTxIds } = this.props; const { startDate, endDate } = this.state; - const infoBlock = ( { label: intl.formatMessage(globalMessages.exportButtonLabel), primary: true, isSubmitting: isActionProcessing || false, + disabled: ( + (startDate === null && endDate === null) || + (startDate && endDate && startDate.isAfter(endDate)) + ) , onClick: () => submit({ startDate, endDate }), }]; return ( , From c46bcb1ee19d53cda40e0c7dc9ce67a0d5c62d07 Mon Sep 17 00:00:00 2001 From: Ahmed Ibrahim Date: Thu, 17 Nov 2022 17:38:18 +0200 Subject: [PATCH 052/172] Add DateRange prop types & remove logs --- packages/yoroi-extension/app/api/ada/index.js | 1 - .../yoroi-extension/app/components/wallet/export/DateRange.js | 4 ++-- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/packages/yoroi-extension/app/api/ada/index.js b/packages/yoroi-extension/app/api/ada/index.js index 7e08e32b16..bfc8f9d9f5 100644 --- a/packages/yoroi-extension/app/api/ada/index.js +++ b/packages/yoroi-extension/app/api/ada/index.js @@ -2285,7 +2285,6 @@ export default class AdaApi { const fetchedTxs = await getAllTransactions({ publicDeriver: request.publicDeriver, }); - console.log(JSON.parse(JSON.stringify({fetchedTxs}))) Logger.debug(`${nameof(AdaApi)}::${nameof(this.getTransactionRowsToExport)}: success`); return convertAdaTransactionsToExportRows( fetchedTxs.txs, diff --git a/packages/yoroi-extension/app/components/wallet/export/DateRange.js b/packages/yoroi-extension/app/components/wallet/export/DateRange.js index 72cae089f0..140d1aa86f 100644 --- a/packages/yoroi-extension/app/components/wallet/export/DateRange.js +++ b/packages/yoroi-extension/app/components/wallet/export/DateRange.js @@ -25,10 +25,10 @@ const messages = defineMessages({ }); type Props = {| - date: { + date: {| startDate: Dayjs | null, endDate: Dayjs | null, - }, + |}, setStartDate(Dayjs | null): void, setEndDate(Dayjs | null): void |} From 402506cf1bec4c5614485280260fa044c0ea807e Mon Sep 17 00:00:00 2001 From: Ahmed Ibrahim Date: Sat, 19 Nov 2022 12:41:03 +0200 Subject: [PATCH 053/172] Fix flow & improve date filter --- .../actions/common/transactions-actions.js | 6 ++++- .../app/components/wallet/export/DateRange.js | 11 +++++----- .../wallet/export/ExportTransactionDialog.js | 18 +++++++++------ .../app/stores/toplevel/TransactionsStore.js | 22 +++++++------------ 4 files changed, 30 insertions(+), 27 deletions(-) diff --git a/packages/yoroi-extension/app/actions/common/transactions-actions.js b/packages/yoroi-extension/app/actions/common/transactions-actions.js index da5514504d..63669cef54 100644 --- a/packages/yoroi-extension/app/actions/common/transactions-actions.js +++ b/packages/yoroi-extension/app/actions/common/transactions-actions.js @@ -1,10 +1,14 @@ // @flow import { AsyncAction, Action } from '../lib/Action'; import { PublicDeriver } from '../../api/ada/lib/storage/models/PublicDeriver/index'; +import { Dayjs } from 'dayjs'; // ======= TRANSACTIONS ACTIONS ======= -export type TransactionRowsToExportRequest = void; +export type TransactionRowsToExportRequest = {| + startDate: typeof Dayjs, + endDate: typeof Dayjs, +|}; export default class TransactionsActions { loadMoreTransactions: AsyncAction> = new AsyncAction(); diff --git a/packages/yoroi-extension/app/components/wallet/export/DateRange.js b/packages/yoroi-extension/app/components/wallet/export/DateRange.js index 140d1aa86f..4f2677b3f7 100644 --- a/packages/yoroi-extension/app/components/wallet/export/DateRange.js +++ b/packages/yoroi-extension/app/components/wallet/export/DateRange.js @@ -1,5 +1,6 @@ // @flow import { Component } from 'react' +import type { Node } from 'react' import TextField from '@mui/material/TextField'; import { AdapterDayjs } from '@mui/x-date-pickers/AdapterDayjs'; import { LocalizationProvider } from '@mui/x-date-pickers/LocalizationProvider'; @@ -26,11 +27,11 @@ const messages = defineMessages({ type Props = {| date: {| - startDate: Dayjs | null, - endDate: Dayjs | null, + startDate: typeof Dayjs | null, + endDate: typeof Dayjs | null, |}, - setStartDate(Dayjs | null): void, - setEndDate(Dayjs | null): void + setStartDate(typeof Dayjs | null): void, + setEndDate(typeof Dayjs | null): void |} @observer @@ -40,7 +41,7 @@ export default class ExportTransactionDialog extends Component { intl: intlShape.isRequired }; - render() { + render(): Node { const { intl } = this.context; const { date, setStartDate, setEndDate } = this.props; const invalidInterval = ( diff --git a/packages/yoroi-extension/app/components/wallet/export/ExportTransactionDialog.js b/packages/yoroi-extension/app/components/wallet/export/ExportTransactionDialog.js index 818ddd1040..1e483d4cbd 100644 --- a/packages/yoroi-extension/app/components/wallet/export/ExportTransactionDialog.js +++ b/packages/yoroi-extension/app/components/wallet/export/ExportTransactionDialog.js @@ -5,6 +5,7 @@ import { observer } from 'mobx-react'; import { defineMessages, intlShape } from 'react-intl'; import LocalizableError from '../../../i18n/LocalizableError'; import type { $npm$ReactIntl$IntlFormat } from 'react-intl'; +import type { TransactionRowsToExportRequest } from '../../../actions/common/transactions-actions'; import Dialog from '../../widgets/Dialog'; import DialogCloseButton from '../../widgets/DialogCloseButton'; import ErrorBlock from '../../widgets/ErrorBlock'; @@ -12,6 +13,7 @@ import globalMessages from '../../../i18n/global-messages'; import CheckboxLabel from '../../common/CheckboxLabel'; import DateRange from './DateRange' import { Box } from '@mui/system'; +import { Dayjs } from 'dayjs'; const messages = defineMessages({ dialogTitle: { @@ -31,20 +33,25 @@ const messages = defineMessages({ type Props = {| +isActionProcessing: ?boolean, +error: ?LocalizableError, - +submit: void => PossiblyAsync, + +submit: TransactionRowsToExportRequest => PossiblyAsync, +toggleIncludeTxIds: void => void, +shouldIncludeTxIds: boolean, +cancel: void => void, |}; +type State = {| + startDate: typeof Dayjs | null, + endDate: typeof Dayjs | null, +|} + @observer -export default class ExportTransactionDialog extends Component { +export default class ExportTransactionDialog extends Component { static contextTypes: {|intl: $npm$ReactIntl$IntlFormat|} = { intl: intlShape.isRequired }; - state = { + state: State = { startDate: null, endDate: null, } @@ -79,10 +86,7 @@ export default class ExportTransactionDialog extends Component { label: intl.formatMessage(globalMessages.exportButtonLabel), primary: true, isSubmitting: isActionProcessing || false, - disabled: ( - (startDate === null && endDate === null) || - (startDate && endDate && startDate.isAfter(endDate)) - ) , + disabled: !startDate || !endDate || startDate.isAfter(endDate), onClick: () => submit({ startDate, endDate }), }]; diff --git a/packages/yoroi-extension/app/stores/toplevel/TransactionsStore.js b/packages/yoroi-extension/app/stores/toplevel/TransactionsStore.js index f967fe5865..ff8afbe5b8 100644 --- a/packages/yoroi-extension/app/stores/toplevel/TransactionsStore.js +++ b/packages/yoroi-extension/app/stores/toplevel/TransactionsStore.js @@ -60,6 +60,9 @@ import { import { assuranceLevels } from '../../config/transactionAssuranceConfig'; import { transactionTypes } from '../../api/ada/transactions/types'; import dayjs from 'dayjs' +import isBetween from 'dayjs/plugin/isBetween' + +dayjs.extend(isBetween) export type TxRequests = {| publicDeriver: PublicDeriver<>, @@ -760,20 +763,11 @@ export default class TransactionsStore extends Store { }).promise; const { startDate, endDate } = request.exportRequest; - if (startDate || endDate) { - const dateFormat = 'MM-DD-YYYY' - respTxRows = respTxRows.filter(row => { - const txDate = dayjs(row.date).format(dateFormat) - if ( - (startDate !== null && startDate.isAfter(txDate, 'day')) || - (endDate !== null && endDate.isBefore(txDate, 'day')) - ) return false; - return true - }) - } - respTxRows = respTxRows.sort((a, b) => { - return b.date - a.date; - }); + respTxRows = respTxRows.filter(row => { + const txDate = dayjs(row.date) + // 4th param `[]` means that the start and end date are included + return txDate.isBetween(startDate, endDate, 'day', '[]') + }).sort((a, b) => b.date - a.date); if (respTxRows.length < 1) { throw new LocalizableError(globalMessages.noTransactionsFound); From 93cecf68589c6ad5857c05df74c25f43d4ec54ca Mon Sep 17 00:00:00 2001 From: Denis Date: Tue, 22 Nov 2022 13:20:57 +0300 Subject: [PATCH 054/172] removed unused --- .../features/step_definitions/settings-ui-steps.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/yoroi-extension/features/step_definitions/settings-ui-steps.js b/packages/yoroi-extension/features/step_definitions/settings-ui-steps.js index c53460d826..a4b84ccf3a 100644 --- a/packages/yoroi-extension/features/step_definitions/settings-ui-steps.js +++ b/packages/yoroi-extension/features/step_definitions/settings-ui-steps.js @@ -2,7 +2,7 @@ import { When, Given, Then } from 'cucumber'; import i18n from '../support/helpers/i18n-helpers'; -import { By, Key } from 'selenium-webdriver'; +import { Key } from 'selenium-webdriver'; import { truncateLongName } from '../../app/utils/formatters'; import { expect } from 'chai'; import { checkErrorByTranslationId } from './common-steps'; From 9098e5507202512871ef8671b4bc508c59630332 Mon Sep 17 00:00:00 2001 From: Denis Date: Tue, 22 Nov 2022 13:39:24 +0300 Subject: [PATCH 055/172] removed empty file --- packages/yoroi-extension/features/pages/walletTransactionsPage.js | 0 1 file changed, 0 insertions(+), 0 deletions(-) delete mode 100644 packages/yoroi-extension/features/pages/walletTransactionsPage.js diff --git a/packages/yoroi-extension/features/pages/walletTransactionsPage.js b/packages/yoroi-extension/features/pages/walletTransactionsPage.js deleted file mode 100644 index e69de29bb2..0000000000 From 116f115d55d76761c33de203d00b08c9031f961a Mon Sep 17 00:00:00 2001 From: Ahmed Ibrahim Date: Wed, 23 Nov 2022 15:04:11 +0200 Subject: [PATCH 056/172] Removed dead code --- .../ergo-connector/stores/ConnectorStore.js | 1 + .../app/stores/DappConnectorStore.js | 29 ++----------------- 2 files changed, 3 insertions(+), 27 deletions(-) diff --git a/packages/yoroi-extension/app/ergo-connector/stores/ConnectorStore.js b/packages/yoroi-extension/app/ergo-connector/stores/ConnectorStore.js index d99f45e476..4884a92b9f 100644 --- a/packages/yoroi-extension/app/ergo-connector/stores/ConnectorStore.js +++ b/packages/yoroi-extension/app/ergo-connector/stores/ConnectorStore.js @@ -88,6 +88,7 @@ export function connectorCall(message: T): Promise { if (window.chrome.runtime.lastError) { // eslint-disable-next-line prefer-promise-reject-errors reject(`Could not establish connection: ${JSON.stringify(typeof message === 'object' ? message : '')}`); + return; } resolve(response); } diff --git a/packages/yoroi-extension/app/stores/DappConnectorStore.js b/packages/yoroi-extension/app/stores/DappConnectorStore.js index b5ce9be201..c70254c8c9 100644 --- a/packages/yoroi-extension/app/stores/DappConnectorStore.js +++ b/packages/yoroi-extension/app/stores/DappConnectorStore.js @@ -1,29 +1,17 @@ /* eslint-disable promise/always-return */ // @flow -import { observable, action, runInAction, computed } from 'mobx'; +import { observable, computed } from 'mobx'; import Request from './lib/LocalizedRequest'; import Store from './base/Store'; import type { ConnectingMessage, WhitelistEntry, ConnectedSites, - ConnectRetrieveData, RemoveWalletFromWhitelistData, } from '../../chrome/extension/ergo-connector/types'; import type { ActionsMap } from '../actions/index'; import type { StoresMap } from './index'; -import { connectorCall, getConnectedSites } from '../ergo-connector/stores/ConnectorStore'; - -// Need to run only once - Connecting wallets -let initedConnecting = false; - -async function sendMsgConnect(): Promise { - if (!initedConnecting) { - const res = await connectorCall({ type: 'connect_retrieve_data' }) - initedConnecting = true - return res - } -} +import { getConnectedSites } from '../ergo-connector/stores/ConnectorStore'; type GetWhitelistFunc = void => Promise>; type SetWhitelistFunc = {| @@ -63,19 +51,6 @@ export default class ConnectorStore extends Store { super.teardown(); } - // ========== connecting wallets ========== // - @action - _getConnectingMsg: () => Promise = async () => { - await sendMsgConnect() - .then(response => { - runInAction(() => { - this.connectingMessage = response; - }); - }) - // eslint-disable-next-line no-console - .catch(err => console.error(err)); - }; - // ========== whitelist ========== // @computed get currentConnectorWhitelist(): Array { let { result } = this.getConnectorWhitelist; From f094f73c3058305fed733ac9a9915094ca72f7e6 Mon Sep 17 00:00:00 2001 From: Ahmed Ibrahim Date: Wed, 23 Nov 2022 15:05:16 +0200 Subject: [PATCH 057/172] Move the DappConnectorStore to the toplevel stores --- packages/yoroi-extension/app/stores/index.js | 2 +- .../app/stores/{ => toplevel}/DappConnectorStore.js | 12 ++++++------ 2 files changed, 7 insertions(+), 7 deletions(-) rename packages/yoroi-extension/app/stores/{ => toplevel}/DappConnectorStore.js (90%) diff --git a/packages/yoroi-extension/app/stores/index.js b/packages/yoroi-extension/app/stores/index.js index d239898c24..0089420290 100644 --- a/packages/yoroi-extension/app/stores/index.js +++ b/packages/yoroi-extension/app/stores/index.js @@ -33,7 +33,7 @@ import CoinPriceStore from './toplevel/CoinPriceStore'; import TokenInfoStore from './toplevel/TokenInfoStore'; import ExplorerStore from './toplevel/ExplorerStore'; import ServerConnectionStore from './toplevel/ServerConnectionStore'; -import ConnectorStore from './DappConnectorStore' +import ConnectorStore from './toplevel/DappConnectorStore' /** Map of var name to class. Allows dynamic lookup of class so we can init all stores one loop */ const storeClasses = Object.freeze({ stateFetchStore: StateFetchStore, diff --git a/packages/yoroi-extension/app/stores/DappConnectorStore.js b/packages/yoroi-extension/app/stores/toplevel/DappConnectorStore.js similarity index 90% rename from packages/yoroi-extension/app/stores/DappConnectorStore.js rename to packages/yoroi-extension/app/stores/toplevel/DappConnectorStore.js index c70254c8c9..5aa5402b15 100644 --- a/packages/yoroi-extension/app/stores/DappConnectorStore.js +++ b/packages/yoroi-extension/app/stores/toplevel/DappConnectorStore.js @@ -1,17 +1,17 @@ /* eslint-disable promise/always-return */ // @flow import { observable, computed } from 'mobx'; -import Request from './lib/LocalizedRequest'; -import Store from './base/Store'; +import Request from '../lib/LocalizedRequest'; +import Store from '../base/Store'; import type { ConnectingMessage, WhitelistEntry, ConnectedSites, RemoveWalletFromWhitelistData, -} from '../../chrome/extension/ergo-connector/types'; -import type { ActionsMap } from '../actions/index'; -import type { StoresMap } from './index'; -import { getConnectedSites } from '../ergo-connector/stores/ConnectorStore'; +} from '../../../chrome/extension/ergo-connector/types'; +import type { ActionsMap } from '../../actions/index'; +import type { StoresMap } from '../index'; +import { getConnectedSites } from '../../ergo-connector/stores/ConnectorStore'; type GetWhitelistFunc = void => Promise>; type SetWhitelistFunc = {| From e429fdc9483cbabe9f68f381308b53e4242abc09 Mon Sep 17 00:00:00 2001 From: yushi Date: Mon, 28 Nov 2022 19:08:15 +0800 Subject: [PATCH 058/172] minimize ledger manual test panel when double-clicked --- .../ledger/components/manual-test/TestBlock.scss | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/packages/yoroi-extension/ledger/components/manual-test/TestBlock.scss b/packages/yoroi-extension/ledger/components/manual-test/TestBlock.scss index 8ed73b1cc4..3ca180633e 100644 --- a/packages/yoroi-extension/ledger/components/manual-test/TestBlock.scss +++ b/packages/yoroi-extension/ledger/components/manual-test/TestBlock.scss @@ -1,4 +1,5 @@ .component { + overflow: hidden; position: absolute; display: flex; z-index: 1; @@ -50,8 +51,8 @@ } } .visible { - opacity: 1; } .hidden { - opacity: 0; -} \ No newline at end of file + width: 10px; + height: 10px; +} From 37ed9b4e7868c19495fcd0a3b553312beeecbe4a Mon Sep 17 00:00:00 2001 From: Ruslan Dudin Date: Wed, 7 Dec 2022 23:15:29 +0300 Subject: [PATCH 059/172] Update dependabot.yml --- .github/dependabot.yml | 1 - 1 file changed, 1 deletion(-) diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 2067caaa96..fe9b4738fe 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -20,5 +20,4 @@ updates: - dependency-name: "chromedriver" assignees: - "vsubhuman" - - "javimaravillas" rebase-strategy: disabled From 6dedccf59ac4a433cba95c7b89488344b32a23d9 Mon Sep 17 00:00:00 2001 From: Ruslan Dudin Date: Wed, 7 Dec 2022 23:15:59 +0300 Subject: [PATCH 060/172] Update dependabot.yml --- .github/dependabot.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/dependabot.yml b/.github/dependabot.yml index fe9b4738fe..9f9a747b34 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -4,10 +4,10 @@ updates: directory: "/packages/yoroi-extension" schedule: interval: weekly - day: monday + day: friday time: 03:00 timezone: UTC - open-pull-requests-limit: 10 + open-pull-requests-limit: 5 allow: - dependency-name: "@cardano-foundation/ledgerjs-hw-app-cardano" - dependency-name: "@emurgo/*" From eb0121612a2400888eac549ad54c51247ba1b173 Mon Sep 17 00:00:00 2001 From: Ruslan Dudin Date: Wed, 7 Dec 2022 23:18:15 +0300 Subject: [PATCH 061/172] Update dependabot.yml --- .github/dependabot.yml | 1 - 1 file changed, 1 deletion(-) diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 9f9a747b34..321fef0154 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -12,7 +12,6 @@ updates: - dependency-name: "@cardano-foundation/ledgerjs-hw-app-cardano" - dependency-name: "@emurgo/*" - dependency-name: "cardano-*" - - dependency-name: "ergo-*" - dependency-name: "lodash" - dependency-name: "mobx*" - dependency-name: "react*" From 16d67c03a7e982a1483787236e877098f67173bf Mon Sep 17 00:00:00 2001 From: Ruslan Dudin Date: Thu, 8 Dec 2022 00:19:45 +0300 Subject: [PATCH 062/172] Update dependabot.yml --- .github/dependabot.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 321fef0154..5b483b2a78 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -5,7 +5,7 @@ updates: schedule: interval: weekly day: friday - time: 03:00 + time: "03:00" timezone: UTC open-pull-requests-limit: 5 allow: From 103dfb536612ec0f948ab16a3eaabe7d9fc803b5 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 7 Dec 2022 21:26:53 +0000 Subject: [PATCH 063/172] Bump chromedriver from 107.0.3 to 108.0.0 in /packages/yoroi-extension Bumps [chromedriver](https://github.com/giggio/node-chromedriver) from 107.0.3 to 108.0.0. - [Release notes](https://github.com/giggio/node-chromedriver/releases) - [Commits](https://github.com/giggio/node-chromedriver/compare/107.0.3...108.0.0) --- updated-dependencies: - dependency-name: chromedriver dependency-type: direct:development update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] --- packages/yoroi-extension/package-lock.json | 132 ++++++++++++--------- 1 file changed, 73 insertions(+), 59 deletions(-) diff --git a/packages/yoroi-extension/package-lock.json b/packages/yoroi-extension/package-lock.json index 674abed53c..bfa5452e39 100644 --- a/packages/yoroi-extension/package-lock.json +++ b/packages/yoroi-extension/package-lock.json @@ -8599,7 +8599,7 @@ "any-promise": { "version": "1.3.0", "resolved": "https://registry.npmjs.org/any-promise/-/any-promise-1.3.0.tgz", - "integrity": "sha1-q8av7tzqUugJzcA3au0845Y10X8=", + "integrity": "sha512-7UvmKalWRt1wgjL1RrGxoSJW/0QZFIegpeGvZG9kjp8vrRu55XTHbwnqq2GpXm9uLbcuhxm3IqX9OB4MZR1b2A==", "dev": true }, "anymatch": { @@ -9761,7 +9761,7 @@ "becke-ch--regex--s0-0-v1--base--pl--lib": { "version": "1.4.0", "resolved": "https://registry.npmjs.org/becke-ch--regex--s0-0-v1--base--pl--lib/-/becke-ch--regex--s0-0-v1--base--pl--lib-1.4.0.tgz", - "integrity": "sha1-Qpzuu/pffpNueNc/vcfacWKyDiA=", + "integrity": "sha512-FnWonOyaw7Vivg5nIkrUll9HSS5TjFbyuURAiDssuL6VxrBe3ERzudRxOcWRhZYlP89UArMDikz7SapRPQpmZQ==", "dev": true }, "before-after-hook": { @@ -10736,9 +10736,9 @@ "dev": true }, "chromedriver": { - "version": "107.0.3", - "resolved": "https://registry.npmjs.org/chromedriver/-/chromedriver-107.0.3.tgz", - "integrity": "sha512-jmzpZgctCRnhYAn0l/NIjP4vYN3L8GFVbterTrRr2Ly3W5rFMb9H8EKGuM5JCViPKSit8FbE718kZTEt3Yvffg==", + "version": "108.0.0", + "resolved": "https://registry.npmjs.org/chromedriver/-/chromedriver-108.0.0.tgz", + "integrity": "sha512-/kb0rb0dlC4RfXh2BOT7RV87K6d+It3VV5YXebLzO5a8t2knNffiTE23XPJQCH+l1xmgoW8/sOX/NB9irskvOQ==", "dev": true, "requires": { "@testim/chrome-version": "^1.1.3", @@ -10751,9 +10751,9 @@ }, "dependencies": { "axios": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/axios/-/axios-1.2.0.tgz", - "integrity": "sha512-zT7wZyNYu3N5Bu0wuZ6QccIf93Qk1eV8LOewxgjOZFd2DenOs98cJ7+Y6703d0wkaXGY6/nZd4EweJaHz9uzQw==", + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/axios/-/axios-1.2.1.tgz", + "integrity": "sha512-I88cFiGu9ryt/tfVEi4kX2SITsvDddTajXTOFmt2uK1ZVA8LytjtdeyefdQWEf5PU8w+4SSJDoYnggflB5tW4A==", "dev": true, "requires": { "follow-redirects": "^1.15.0", @@ -12310,9 +12310,9 @@ }, "dependencies": { "ansi-regex": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-3.0.0.tgz", - "integrity": "sha1-7QMXwyIGT3lGbAKWa922Bas32Zg=", + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-3.0.1.tgz", + "integrity": "sha512-+O9Jct8wf++lXxxFc4hc8LsjaSq0HFzzL7cVsw8pRDIPdjKD2mT4ytDZlLuSBZ4cLKZFXIrMGO7DbQCtMJJMKw==", "dev": true }, "cli-table3": { @@ -12348,25 +12348,25 @@ "escape-string-regexp": { "version": "1.0.5", "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", - "integrity": "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=", + "integrity": "sha512-vbRorB5FUQWvla16U8R/qgaFIya2qGzwDrNmCZuYKrbdSUMG6I1ZCGQRefkRVhuOkIGVne7BQ35DSfo1qvJqFg==", "dev": true }, "indent-string": { "version": "3.2.0", "resolved": "https://registry.npmjs.org/indent-string/-/indent-string-3.2.0.tgz", - "integrity": "sha1-Sl/W0nzDMvN+VBmlBNu4NxBckok=", + "integrity": "sha512-BYqTHXTGUIvg7t1r4sJNKcbDZkL92nkXA8YtRpbjFHRHGDL/NtUeiBJMeE60kIFN/Mg8ESaWQvftaYMGJzQZCQ==", "dev": true }, "is-fullwidth-code-point": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-2.0.0.tgz", - "integrity": "sha1-o7MKXE8ZkYMWeqq5O+764937ZU8=", + "integrity": "sha512-VHskAKYM8RfSFXwee5t5cbN5PZeq1Wrh6qd5bkyiXIf6UQcN6w/A0eXM9r6t8d+GYOh+o6ZhiEnb88LN/Y8m2w==", "dev": true }, "path-key": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/path-key/-/path-key-2.0.1.tgz", - "integrity": "sha1-QRyttXTFoUDTpLGRDUDYDMn0C0A=", + "integrity": "sha512-fEHGKCSmUSDPv4uoj8AlD+joPlq3peND+HRYyxFz4KPw4z926S/b8rIuFs2FYJg3BwsxJf6A9/3eIdLaYC+9Dw==", "dev": true }, "semver": { @@ -12378,7 +12378,7 @@ "shebang-command": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-1.2.0.tgz", - "integrity": "sha1-RKrGW2lbAzmJaMOfNj/uXer98eo=", + "integrity": "sha512-EV3L1+UQWGor21OmnvojK36mhg+TyIKDh3iFBKBohr5xeXIhNBcx8oWdgkTEEQ+BEFFYdLRuqMfd5L84N1V5Vg==", "dev": true, "requires": { "shebang-regex": "^1.0.0" @@ -12387,7 +12387,7 @@ "shebang-regex": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-1.0.0.tgz", - "integrity": "sha1-2kL0l0DAtC2yypcoVxyxkMmO/qM=", + "integrity": "sha512-wpoSFAxys6b2a2wHZ1XpDSgD7N9iVjg29Ph9uV/uaP9Ex/KXlkTZTeddxDPSYQpgvzKLGJke2UU0AzoGCjNIvQ==", "dev": true }, "string-width": { @@ -12403,7 +12403,7 @@ "strip-ansi": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-4.0.0.tgz", - "integrity": "sha1-qEeQIusaw2iocTibY1JixQXuNo8=", + "integrity": "sha512-4XaJ2zQdCzROZDivEVIDPkcQn8LMFSa8kj8Gxb/Lnwzv9A8VctNZ+lfivC/sV3ivW8ElJTERXZoPBRrZKkNKow==", "dev": true, "requires": { "ansi-regex": "^3.0.0" @@ -12498,7 +12498,7 @@ "cucumber-tag-expressions": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/cucumber-tag-expressions/-/cucumber-tag-expressions-1.1.1.tgz", - "integrity": "sha1-f1x7cACbwrZmWRv+ZIVFeL7e6Fo=", + "integrity": "sha512-V9jv81sR/HaJ87FoidrvHkviXId7KmBcUi7aQPfi+W3nRO30N6GqH6lcp8K+nyiT1DgemRJBPDDeBMS93xJqMQ==", "dev": true }, "currently-unhandled": { @@ -13541,14 +13541,14 @@ } }, "es5-ext": { - "version": "0.10.53", - "resolved": "https://registry.npmjs.org/es5-ext/-/es5-ext-0.10.53.tgz", - "integrity": "sha512-Xs2Stw6NiNHWypzRTY1MtaG/uJlwCk8kH81920ma8mvN8Xq1gsfhZvpkImLQArw8AHnv8MT2I45J3c0R8slE+Q==", + "version": "0.10.62", + "resolved": "https://registry.npmjs.org/es5-ext/-/es5-ext-0.10.62.tgz", + "integrity": "sha512-BHLqn0klhEpnOKSrzn/Xsz2UIW8j+cGmo9JLzr8BiUapV8hPL9+FliFqjwr9ngW7jWdnxv6eO+/LqyhJVqgrjA==", "dev": true, "requires": { - "es6-iterator": "~2.0.3", - "es6-symbol": "~3.1.3", - "next-tick": "~1.0.0" + "es6-iterator": "^2.0.3", + "es6-symbol": "^3.1.3", + "next-tick": "^1.1.0" } }, "es5-shim": { @@ -13565,7 +13565,7 @@ "es6-iterator": { "version": "2.0.3", "resolved": "https://registry.npmjs.org/es6-iterator/-/es6-iterator-2.0.3.tgz", - "integrity": "sha1-p96IkUGgWpSwhUQDstCg+/qY87c=", + "integrity": "sha512-zw4SRzoUkd+cl+ZoE15A9o1oQd920Bb0iOJMQkQhl3jNc03YqVjAhG7scf9C5KWRU/R13Orf588uCC6525o02g==", "dev": true, "requires": { "d": "1", @@ -14570,18 +14570,18 @@ } }, "ext": { - "version": "1.6.0", - "resolved": "https://registry.npmjs.org/ext/-/ext-1.6.0.tgz", - "integrity": "sha512-sdBImtzkq2HpkdRLtlLWDa6w4DX22ijZLKx8BMPUuKe1c5lbN6xwQDQCxSfxBQnHZ13ls/FH0MQZx/q/gr6FQg==", + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/ext/-/ext-1.7.0.tgz", + "integrity": "sha512-6hxeJYaL110a9b5TEJSj0gojyHQAmA2ch5Os+ySCiA1QGdS697XWY1pzsrSjqA9LDEEgdB/KypIlR59RcLuHYw==", "dev": true, "requires": { - "type": "^2.5.0" + "type": "^2.7.2" }, "dependencies": { "type": { - "version": "2.5.0", - "resolved": "https://registry.npmjs.org/type/-/type-2.5.0.tgz", - "integrity": "sha512-180WMDQaIMm3+7hGXWf12GtdniDEy7nYcyFMKJn/eZz/6tSLXrUN9V0wKSbMjej0I1WHWbpREDEKHtqPQa9NNw==", + "version": "2.7.2", + "resolved": "https://registry.npmjs.org/type/-/type-2.7.2.tgz", + "integrity": "sha512-dzlvlNlt6AXU7EBSfpAscydQ7gXB+pPGsPnfJnZpiNJBDj7IaJzQlBZYGdEi4R9HmPdBv2XmWJ6YUtoTa7lmCw==", "dev": true } } @@ -14796,7 +14796,7 @@ "figures": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/figures/-/figures-2.0.0.tgz", - "integrity": "sha1-OrGi0qYsi/tDGgyUy3l6L84nyWI=", + "integrity": "sha512-Oa2M9atig69ZkfwiApY8F2Yy+tzMbazyvqv21R0NsSC8floSOC09BbT1ITWAdoMGQvJ/aZnR1KMwdx9tvHnTNA==", "dev": true, "requires": { "escape-string-regexp": "^1.0.5" @@ -14805,7 +14805,7 @@ "escape-string-regexp": { "version": "1.0.5", "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", - "integrity": "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=", + "integrity": "sha512-vbRorB5FUQWvla16U8R/qgaFIya2qGzwDrNmCZuYKrbdSUMG6I1ZCGQRefkRVhuOkIGVne7BQ35DSfo1qvJqFg==", "dev": true } } @@ -16051,7 +16051,7 @@ "gherkin": { "version": "5.1.0", "resolved": "https://registry.npmjs.org/gherkin/-/gherkin-5.1.0.tgz", - "integrity": "sha1-aEu7A63STq9731RPWAM+so+zxtU=", + "integrity": "sha512-axTCsxH0m0cixijLvo7s9591h5pMb8ifQxFDun5FnfFhVsUhxgdnH0H7TSK7q8I4ASUU18DJ/tmlnMegMuLUUQ==", "dev": true }, "glob": { @@ -16764,7 +16764,7 @@ "httpolyglot": { "version": "0.1.2", "resolved": "https://registry.npmjs.org/httpolyglot/-/httpolyglot-0.1.2.tgz", - "integrity": "sha1-5NNH/omEpi9GfUBg31J/GFH2mXs=", + "integrity": "sha512-ouHI1AaQMLgn4L224527S5+vq6hgvqPteurVfbm7ChViM3He2Wa8KP1Ny7pTYd7QKnDSPKcN8JYfC8r/lmsE3A==", "dev": true }, "https-browserify": { @@ -17256,7 +17256,7 @@ "is-generator": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/is-generator/-/is-generator-1.0.3.tgz", - "integrity": "sha1-wUwhBX7TbjKNuANHlmxpP4hjifM=", + "integrity": "sha512-G56jBpbJeg7ds83HW1LuShNs8J73Fv3CPz/bmROHOHlnKkN8sWb9ujiagjmxxMUywftgq48HlBZELKKqFLk0oA==", "dev": true }, "is-generator-fn": { @@ -19707,7 +19707,7 @@ "knuth-shuffle-seeded": { "version": "1.0.6", "resolved": "https://registry.npmjs.org/knuth-shuffle-seeded/-/knuth-shuffle-seeded-1.0.6.tgz", - "integrity": "sha1-AfG2VzOqdUDuCNiwF0Fk0iCB5OE=", + "integrity": "sha512-9pFH0SplrfyKyojCLxZfMcvkhf5hH0d+UwR9nTVJ/DDQJGuzcXjTwB7TP7sDfehSudlGGaOLblmEWqv04ERVWg==", "dev": true, "requires": { "seed-random": "~2.2.0" @@ -19955,7 +19955,7 @@ "lodash.omit": { "version": "4.5.0", "resolved": "https://registry.npmjs.org/lodash.omit/-/lodash.omit-4.5.0.tgz", - "integrity": "sha1-brGa5aHuHdnfC5aeZs4Lf6MLXmA=", + "integrity": "sha512-XeqSp49hNGmlkj2EJlfrQFIzQ6lXdNro9sddtQzcJY8QaoC2GO0DT7xaIokHeyM+mIT0mPMlPvkYzg2xCuHdZg==", "dev": true }, "lodash.set": { @@ -21177,9 +21177,9 @@ "dev": true }, "next-tick": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/next-tick/-/next-tick-1.0.0.tgz", - "integrity": "sha1-yobR/ogoFpsBICCOPchCS524NCw=", + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/next-tick/-/next-tick-1.1.0.tgz", + "integrity": "sha512-CXdUiJembsNjuToQvxayPZF9Vqht7hewsvy2sOWafLvi2awflj9mOC6bHIg50orX8IJvWKY9wYQ/zB2kogPslQ==", "dev": true }, "nice-try": { @@ -22177,7 +22177,7 @@ "pad-right": { "version": "0.2.2", "resolved": "https://registry.npmjs.org/pad-right/-/pad-right-0.2.2.tgz", - "integrity": "sha1-b7ySQEXSRPKiokRQMGDTv8YAl3Q=", + "integrity": "sha512-4cy8M95ioIGolCoMmm2cMntGR1lPLEbOMzOKu8bzjuJP6JpzEMQcDHmh7hHLYGgob+nKe1YHFMaG4V59HQa89g==", "dev": true, "requires": { "repeat-string": "^1.5.2" @@ -25128,7 +25128,7 @@ "seed-random": { "version": "2.2.0", "resolved": "https://registry.npmjs.org/seed-random/-/seed-random-2.2.0.tgz", - "integrity": "sha1-KpsZ4lCoFwmSMaW5mk2vgLf77VQ=", + "integrity": "sha512-34EQV6AAHQGhoc0tn/96a9Fsi6v2xdqe/dMUwljGRaFOzR3EgRmECvD0O8vi8X+/uQ50LGHfkNu/Eue5TPKZkQ==", "dev": true }, "selenium-webdriver": { @@ -25760,12 +25760,20 @@ "dev": true }, "stack-generator": { - "version": "2.0.5", - "resolved": "https://registry.npmjs.org/stack-generator/-/stack-generator-2.0.5.tgz", - "integrity": "sha512-/t1ebrbHkrLrDuNMdeAcsvynWgoH/i4o8EGGfX7dEYDoTXOYVAkEpFdtshlvabzc6JlJ8Kf9YdFEoz7JkzGN9Q==", + "version": "2.0.10", + "resolved": "https://registry.npmjs.org/stack-generator/-/stack-generator-2.0.10.tgz", + "integrity": "sha512-mwnua/hkqM6pF4k8SnmZ2zfETsRUpWXREfA/goT8SLCV4iOFa4bzOX2nDipWAZFPTjLvQB82f5yaodMVhK0yJQ==", "dev": true, "requires": { - "stackframe": "^1.1.1" + "stackframe": "^1.3.4" + }, + "dependencies": { + "stackframe": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/stackframe/-/stackframe-1.3.4.tgz", + "integrity": "sha512-oeVtt7eWQS+Na6F//S4kJ2K2VbRlS9D43mAlMyVpVWovy9o+jfgH8O9agzANzaiLjclA0oYzUXEM4PurhSUChw==", + "dev": true + } } }, "stack-utils": { @@ -25797,19 +25805,25 @@ "dev": true }, "stacktrace-gps": { - "version": "3.0.4", - "resolved": "https://registry.npmjs.org/stacktrace-gps/-/stacktrace-gps-3.0.4.tgz", - "integrity": "sha512-qIr8x41yZVSldqdqe6jciXEaSCKw1U8XTXpjDuy0ki/apyTn/r3w9hDAAQOhZdxvsC93H+WwwEu5cq5VemzYeg==", + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/stacktrace-gps/-/stacktrace-gps-3.1.2.tgz", + "integrity": "sha512-GcUgbO4Jsqqg6RxfyTHFiPxdPqF+3LFmQhm7MgCuYQOYuWyqxo5pwRPz5d/u6/WYJdEnWfK4r+jGbyD8TSggXQ==", "dev": true, "requires": { "source-map": "0.5.6", - "stackframe": "^1.1.1" + "stackframe": "^1.3.4" }, "dependencies": { "source-map": { "version": "0.5.6", "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.6.tgz", - "integrity": "sha1-dc449SvwczxafwwRjYEzSiu19BI=", + "integrity": "sha512-MjZkVp0NHr5+TPihLcadqnlVoGIoWo4IBHptutGh9wI3ttUYvCG26HkSuDi+K6lsZ25syXJXcctwgyVCt//xqA==", + "dev": true + }, + "stackframe": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/stackframe/-/stackframe-1.3.4.tgz", + "integrity": "sha512-oeVtt7eWQS+Na6F//S4kJ2K2VbRlS9D43mAlMyVpVWovy9o+jfgH8O9agzANzaiLjclA0oYzUXEM4PurhSUChw==", "dev": true } } @@ -26722,7 +26736,7 @@ "thenify-all": { "version": "1.6.0", "resolved": "https://registry.npmjs.org/thenify-all/-/thenify-all-1.6.0.tgz", - "integrity": "sha1-GhkY1ALY/D+Y+/I02wvMjMEOlyY=", + "integrity": "sha512-RNxQH/qI8/t3thXJDwcstUO4zeqo64+Uy/+sNVRBx4Xn2OX+OZ9oP+iJnNFqplFra2ZUVeKCSa2oVWi3T4uVmA==", "dev": true, "requires": { "thenify": ">= 3.1.0 < 4" @@ -26839,7 +26853,7 @@ "title-case": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/title-case/-/title-case-2.1.1.tgz", - "integrity": "sha1-PhJyFtpY0rxb7PE3q5Ha46fNj6o=", + "integrity": "sha512-EkJoZ2O3zdCz3zJsYCsxyq2OC5hrxR9mfdd5I+w8h/tmFfeOxJ+vvkxsKxdmN0WtS9zLdHEgfgVOiMVgv+Po4Q==", "dev": true, "requires": { "no-case": "^2.2.0", @@ -26849,7 +26863,7 @@ "lower-case": { "version": "1.1.4", "resolved": "https://registry.npmjs.org/lower-case/-/lower-case-1.1.4.tgz", - "integrity": "sha1-miyr0bno4K6ZOkv31YdcOcQujqw=", + "integrity": "sha512-2Fgx1Ycm599x+WGpIYwJOvsjmXFzTSc34IwDWALRA/8AopUKAVPwfJ+h5+f85BCp0PWmmJcWzEpxOpoXycMpdA==", "dev": true }, "no-case": { @@ -27607,7 +27621,7 @@ "upper-case": { "version": "1.1.3", "resolved": "https://registry.npmjs.org/upper-case/-/upper-case-1.1.3.tgz", - "integrity": "sha1-9rRQHC7EzdJrp4vnIilh3ndiFZg=", + "integrity": "sha512-WRbjgmYzgXkCV7zNVpy5YgrHgbBv126rMALQQMrmzOVC4GM2waQ9x7xtm8VU+1yF2kWyPzI9zbZ48n4vSxwfSA==", "dev": true }, "uri-js": { @@ -27742,7 +27756,7 @@ "util-arity": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/util-arity/-/util-arity-1.1.0.tgz", - "integrity": "sha1-WdAa8f2z/t4KxOYysKtfbOl8kzA=", + "integrity": "sha512-kkyIsXKwemfSy8ZEoaIz06ApApnWsk5hQO0vLjZS6UkBiGiW++Jsyb8vSBoc0WKlffGoGs5yYy/j5pp8zckrFA==", "dev": true }, "util-deprecate": { From 7da0b9f0655e42b3096b8ec17162c7cae3dd0ae6 Mon Sep 17 00:00:00 2001 From: vantuz-subhuman Date: Fri, 9 Dec 2022 14:28:36 +0300 Subject: [PATCH 064/172] flow fixes --- .../app/connector/components/connect/ConnectPage.js | 4 ---- 1 file changed, 4 deletions(-) diff --git a/packages/yoroi-extension/app/connector/components/connect/ConnectPage.js b/packages/yoroi-extension/app/connector/components/connect/ConnectPage.js index 53119e7b20..1a45eed5e8 100644 --- a/packages/yoroi-extension/app/connector/components/connect/ConnectPage.js +++ b/packages/yoroi-extension/app/connector/components/connect/ConnectPage.js @@ -3,10 +3,6 @@ import { Component } from 'react'; import type { Node } from 'react'; import type { $npm$ReactIntl$IntlFormat } from 'react-intl'; -import type { - PublicDeriverCache, - ConnectingMessage, -} from '../../../../chrome/extension/ergo-connector/types'; import type { TokenLookupKey } from '../../../api/common/lib/MultiToken'; import type { TokenRow } from '../../../api/ada/lib/storage/database/primitives/tables'; import type { WalletChecksum } from '@emurgo/cip4-js'; From 2be7568298bb0904f219cfe6efa3aafdbf7c100e Mon Sep 17 00:00:00 2001 From: vantuz-subhuman Date: Fri, 9 Dec 2022 15:08:15 +0300 Subject: [PATCH 065/172] tiny new naming fixes --- package.json | 2 +- packages/yoroi-connector/README.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/package.json b/package.json index 8885e4e8ce..c52ae6338f 100644 --- a/package.json +++ b/package.json @@ -6,7 +6,7 @@ "flow": "lerna run flow --stream", "test": "lerna run test --stream", "translations:purge": "lerna run translations:purge -- stream", - "dev:all": "concurrently \"npm run dev:stable --prefix packages/yoroi-extension\" \"npm run cardano --prefix packages/yoroi-ergo-connector\" \"npm run ergo --prefix packages/yoroi-ergo-connector\" " + "dev:all": "concurrently \"npm run dev:stable --prefix packages/yoroi-extension\" \"npm run cardano --prefix packages/yoroi-connector\" \"npm run ergo --prefix packages/yoroi-connector\" " }, "husky": { "hooks": { diff --git a/packages/yoroi-connector/README.md b/packages/yoroi-connector/README.md index 52e0dd63c4..3aaebbce0c 100644 --- a/packages/yoroi-connector/README.md +++ b/packages/yoroi-connector/README.md @@ -6,7 +6,7 @@ This project is used only as an example application. -All related to the dApp is moved to the folder `packages/yoroi-extension/app/ergo-connector`. +All related to the dApp is moved to the folder `packages/yoroi-extension/app/connector`. ### Testing From 406e93fe5b3c2b862ba0c0d7c7128efdbd288b3a Mon Sep 17 00:00:00 2001 From: vantuz-subhuman Date: Fri, 9 Dec 2022 15:32:05 +0300 Subject: [PATCH 066/172] fixing expected fee value --- packages/yoroi-extension/features/trezor-emulator.feature | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/yoroi-extension/features/trezor-emulator.feature b/packages/yoroi-extension/features/trezor-emulator.feature index ecbddca5fa..3fbea1fa5e 100644 --- a/packages/yoroi-extension/features/trezor-emulator.feature +++ b/packages/yoroi-extension/features/trezor-emulator.feature @@ -62,7 +62,7 @@ Feature: Trezor wallet emulator Then I see the deregistration for the transaction And I should see on the Yoroi withdrawal transfer summary screen: | fromAddress | reward | fees | - | stake1u9jz8z7rnjtz4g5p26j953sjzdmsmzxcpzyk0p0e9sa2f5sjeqemq | 5 | 0.193793 | + | stake1u9jz8z7rnjtz4g5p26j953sjzdmsmzxcpzyk0p0e9sa2f5sjeqemq | 5 | 0.198545 | Given The expected transaction is "hKYAgYJYIDZ36Gx7ppmv3BzVfULyRvhvaa79dgJQBqx4MT+tK7ohAAGBglg5AfiMMmOcqBWRIjRN6CEig4T8YKJcOWtIDaUVnSFW21zUiJyEEQ1N6QwNUDtRuETbPm/YeZEjiZW7GgCV8hsCGgACpGUDGhH+lM0EgYIBggBYHFbbXNSInIQRDU3pDA1QO1G4RNs+b9h5kSOJlbsFoVgd4VbbXNSInIQRDU3pDA1QO1G4RNs+b9h5kSOJlbsaAExLQKEAgoJYIDHFsozgC4AMMNymh4uSd8Xls6VSRnf9Dxv6kiJPzsubWEAXpQuoGfhAzvgfp0H9ouqVNr4ZQPpQnFG9frwUkkyzA7dLIl1GmIuFbkJFMp3AakfKpXSZ9s+3dpaw9hYFkKgLglgg6cWNnhkPKitPspqy3T6+Lqi2VU1F/s8JE36FUprlBHBYQICDQmLn20i7qEzQSnFGhJv3Yp2qiAFF/6XxaqOeIvva6u/jxDYC/CFoA3UV4B6thf4QFJZ9owY9EsOhQuu14A319g==" When I confirm Yoroi transfer funds Then I switch to Trezor-connect screen and allow using From 2ba78fa1e19eacc3b7089afcd79c8dc708035c95 Mon Sep 17 00:00:00 2001 From: vantuz-subhuman Date: Fri, 9 Dec 2022 15:55:44 +0300 Subject: [PATCH 067/172] fixing expected fee value --- packages/yoroi-extension/features/trezor-emulator.feature | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/yoroi-extension/features/trezor-emulator.feature b/packages/yoroi-extension/features/trezor-emulator.feature index 3fbea1fa5e..29aefd8c58 100644 --- a/packages/yoroi-extension/features/trezor-emulator.feature +++ b/packages/yoroi-extension/features/trezor-emulator.feature @@ -62,7 +62,7 @@ Feature: Trezor wallet emulator Then I see the deregistration for the transaction And I should see on the Yoroi withdrawal transfer summary screen: | fromAddress | reward | fees | - | stake1u9jz8z7rnjtz4g5p26j953sjzdmsmzxcpzyk0p0e9sa2f5sjeqemq | 5 | 0.198545 | + | stake1u9jz8z7rnjtz4g5p26j953sjzdmsmzxcpzyk0p0e9sa2f5sjeqemq | 5 | 0.189041 | Given The expected transaction is "hKYAgYJYIDZ36Gx7ppmv3BzVfULyRvhvaa79dgJQBqx4MT+tK7ohAAGBglg5AfiMMmOcqBWRIjRN6CEig4T8YKJcOWtIDaUVnSFW21zUiJyEEQ1N6QwNUDtRuETbPm/YeZEjiZW7GgCV8hsCGgACpGUDGhH+lM0EgYIBggBYHFbbXNSInIQRDU3pDA1QO1G4RNs+b9h5kSOJlbsFoVgd4VbbXNSInIQRDU3pDA1QO1G4RNs+b9h5kSOJlbsaAExLQKEAgoJYIDHFsozgC4AMMNymh4uSd8Xls6VSRnf9Dxv6kiJPzsubWEAXpQuoGfhAzvgfp0H9ouqVNr4ZQPpQnFG9frwUkkyzA7dLIl1GmIuFbkJFMp3AakfKpXSZ9s+3dpaw9hYFkKgLglgg6cWNnhkPKitPspqy3T6+Lqi2VU1F/s8JE36FUprlBHBYQICDQmLn20i7qEzQSnFGhJv3Yp2qiAFF/6XxaqOeIvva6u/jxDYC/CFoA3UV4B6thf4QFJZ9owY9EsOhQuu14A319g==" When I confirm Yoroi transfer funds Then I switch to Trezor-connect screen and allow using From 3c2cda413d047144acbc127f4ed312dd35fbec9c Mon Sep 17 00:00:00 2001 From: Denis Date: Fri, 9 Dec 2022 16:33:50 +0300 Subject: [PATCH 068/172] renamed tests features --- .../{connector-cardano.feature => 01-connector-cardano.feature} | 0 ...ture => 02-connector-anonymous-wallet-errors-checking.feature} | 0 ...ure => 03-connector-authorized-wallet-errors-checking.feature} | 0 ...nnector-no-wallets.feature => 04-connector-no-wallets.feature} | 0 ...connector-sign-data.feature => 05-connector-sign-data.feature} | 0 ...get-collateral.feature => 06-connector-get-collateral.feature} | 0 6 files changed, 0 insertions(+), 0 deletions(-) rename packages/yoroi-extension/features/{connector-cardano.feature => 01-connector-cardano.feature} (100%) rename packages/yoroi-extension/features/{connector-anonymous-wallet-errors-checking.feature => 02-connector-anonymous-wallet-errors-checking.feature} (100%) rename packages/yoroi-extension/features/{connector-authorized-wallet-errors-checking.feature => 03-connector-authorized-wallet-errors-checking.feature} (100%) rename packages/yoroi-extension/features/{connector-no-wallets.feature => 04-connector-no-wallets.feature} (100%) rename packages/yoroi-extension/features/{connector-sign-data.feature => 05-connector-sign-data.feature} (100%) rename packages/yoroi-extension/features/{connector-get-collateral.feature => 06-connector-get-collateral.feature} (100%) diff --git a/packages/yoroi-extension/features/connector-cardano.feature b/packages/yoroi-extension/features/01-connector-cardano.feature similarity index 100% rename from packages/yoroi-extension/features/connector-cardano.feature rename to packages/yoroi-extension/features/01-connector-cardano.feature diff --git a/packages/yoroi-extension/features/connector-anonymous-wallet-errors-checking.feature b/packages/yoroi-extension/features/02-connector-anonymous-wallet-errors-checking.feature similarity index 100% rename from packages/yoroi-extension/features/connector-anonymous-wallet-errors-checking.feature rename to packages/yoroi-extension/features/02-connector-anonymous-wallet-errors-checking.feature diff --git a/packages/yoroi-extension/features/connector-authorized-wallet-errors-checking.feature b/packages/yoroi-extension/features/03-connector-authorized-wallet-errors-checking.feature similarity index 100% rename from packages/yoroi-extension/features/connector-authorized-wallet-errors-checking.feature rename to packages/yoroi-extension/features/03-connector-authorized-wallet-errors-checking.feature diff --git a/packages/yoroi-extension/features/connector-no-wallets.feature b/packages/yoroi-extension/features/04-connector-no-wallets.feature similarity index 100% rename from packages/yoroi-extension/features/connector-no-wallets.feature rename to packages/yoroi-extension/features/04-connector-no-wallets.feature diff --git a/packages/yoroi-extension/features/connector-sign-data.feature b/packages/yoroi-extension/features/05-connector-sign-data.feature similarity index 100% rename from packages/yoroi-extension/features/connector-sign-data.feature rename to packages/yoroi-extension/features/05-connector-sign-data.feature diff --git a/packages/yoroi-extension/features/connector-get-collateral.feature b/packages/yoroi-extension/features/06-connector-get-collateral.feature similarity index 100% rename from packages/yoroi-extension/features/connector-get-collateral.feature rename to packages/yoroi-extension/features/06-connector-get-collateral.feature From 1eb3da39bdcccd2f0ce241eb2e267bde0bec90f4 Mon Sep 17 00:00:00 2001 From: Denis Date: Fri, 9 Dec 2022 16:34:56 +0300 Subject: [PATCH 069/172] DevBackendServe -> DevBackendServer --- packages/yoroi-extension/chrome/constants.js | 2 +- packages/yoroi-extension/chrome/manifest.test.js | 4 ++-- .../features/mock-chain/mockCardanoServer.js | 6 +++--- .../features/mock-chain/mockJormungandrServer.js | 4 ++-- .../features/step_definitions/connector-steps.js | 4 ++-- packages/yoroi-extension/scripts/connections.js | 2 +- 6 files changed, 11 insertions(+), 11 deletions(-) diff --git a/packages/yoroi-extension/chrome/constants.js b/packages/yoroi-extension/chrome/constants.js index ddf68e7fe3..886f9304cf 100644 --- a/packages/yoroi-extension/chrome/constants.js +++ b/packages/yoroi-extension/chrome/constants.js @@ -34,7 +34,7 @@ export function genCSP(request: {| scriptSrc.push(portToPermission(Ports.ReactDevTools)); connectSrc.push(portToPermission(Ports.WebpackDev)); - connectSrc.push(portToPermission(Ports.DevBackendServe)); + connectSrc.push(portToPermission(Ports.DevBackendServer)); connectSrc.push(portToPermission(Ports.ReactDevTools)); connectSrc.push(portToSocketPermission(Ports.WebpackDev)); diff --git a/packages/yoroi-extension/chrome/manifest.test.js b/packages/yoroi-extension/chrome/manifest.test.js index cde260c367..7dd8b076e2 100644 --- a/packages/yoroi-extension/chrome/manifest.test.js +++ b/packages/yoroi-extension/chrome/manifest.test.js @@ -18,8 +18,8 @@ export default (isDebug: boolean, shouldInjectConnector: boolean): * => buildMan isDev: isDebug, additional: { 'connect-src': [ - portToPermission(Ports.DevBackendServe), - portToSocketPermission(Ports.DevBackendServe), + portToPermission(Ports.DevBackendServer), + portToSocketPermission(Ports.DevBackendServer), portToPermission(Ports.ErgoMockServer), portToSocketPermission(Ports.ErgoMockServer), ], diff --git a/packages/yoroi-extension/features/mock-chain/mockCardanoServer.js b/packages/yoroi-extension/features/mock-chain/mockCardanoServer.js index 029a0522ee..c9237e6db3 100644 --- a/packages/yoroi-extension/features/mock-chain/mockCardanoServer.js +++ b/packages/yoroi-extension/features/mock-chain/mockCardanoServer.js @@ -426,10 +426,10 @@ export function getMockServer(settings: { installCoinPriceRequestHandlers(server); - MockServer = server.listen(Ports.DevBackendServe, () => { + MockServer = server.listen(Ports.DevBackendServer, () => { // eslint-disable-next-line no-console - console.log(`JSON Server is running at ${Ports.DevBackendServe}`); - logger.info(`mockCardanoServer: JSON Server is running at ${Ports.DevBackendServe}`); + console.log(`JSON Server is running at ${Ports.DevBackendServer}`); + logger.info(`mockCardanoServer: JSON Server is running at ${Ports.DevBackendServer}`); }); } return MockServer; diff --git a/packages/yoroi-extension/features/mock-chain/mockJormungandrServer.js b/packages/yoroi-extension/features/mock-chain/mockJormungandrServer.js index 91b6a13b40..f1554f1afd 100644 --- a/packages/yoroi-extension/features/mock-chain/mockJormungandrServer.js +++ b/packages/yoroi-extension/features/mock-chain/mockJormungandrServer.js @@ -176,9 +176,9 @@ export function getMockServer( installCoinPriceRequestHandlers(server); - MockServer = server.listen(Ports.DevBackendServe, () => { + MockServer = server.listen(Ports.DevBackendServer, () => { // eslint-disable-next-line no-console - console.log(`JSON Server is running at ${Ports.DevBackendServe}`); + console.log(`JSON Server is running at ${Ports.DevBackendServer}`); }); } return MockServer; diff --git a/packages/yoroi-extension/features/step_definitions/connector-steps.js b/packages/yoroi-extension/features/step_definitions/connector-steps.js index 55d0445cee..357c71954b 100644 --- a/packages/yoroi-extension/features/step_definitions/connector-steps.js +++ b/packages/yoroi-extension/features/step_definitions/connector-steps.js @@ -33,7 +33,7 @@ import { connectorButton } from '../pages/sidebarPage'; const userRejectMsg = 'user reject'; const userRejectSigningMsg = 'User rejected'; -const mockDAppUrl = `http://localhost:${Ports.DevBackendServe}/mock-dapp`; +const mockDAppUrl = `http://localhost:${Ports.DevBackendServer}/mock-dapp`; const connectorPopUpIsDisplayed = async (customWorld: Object) => { await customWorld.driver.sleep(2000); @@ -174,7 +174,7 @@ When(/^I request signing the transaction:$/, async function (table) { const fields = table.hashes()[0]; const normalizedAmount = `${parseFloat(fields.amount) * parseFloat('1000000')}`; this.webDriverLogger.info( - `Step: I request signing the transaction: ${normalizedAmount} to address: ${fields.address}` + `Step: I request signing the transaction: ${normalizedAmount} to address: ${fields.toAddress}` ); await this.mockDAppPage.requestSigningTx(normalizedAmount, fields.toAddress); }); diff --git a/packages/yoroi-extension/scripts/connections.js b/packages/yoroi-extension/scripts/connections.js index f66967e4c2..27b80ebfbe 100644 --- a/packages/yoroi-extension/scripts/connections.js +++ b/packages/yoroi-extension/scripts/connections.js @@ -12,7 +12,7 @@ function serverToPermission(server /*: string */)/*: string */ { const Ports = { WebpackDev: 3000, - DevBackendServe: 21000, + DevBackendServer: 21000, ErgoMockServer: 21001, ReactDevTools: 8097, }; From 52e8010388cf8fde570b1c5fd5f25aa08e779cd2 Mon Sep 17 00:00:00 2001 From: Denis Date: Fri, 9 Dec 2022 18:47:17 +0300 Subject: [PATCH 070/172] Removed magic value.Added check for null response. --- .../yoroi-extension/features/mock-dApp-webpage/index.js | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/packages/yoroi-extension/features/mock-dApp-webpage/index.js b/packages/yoroi-extension/features/mock-dApp-webpage/index.js index 4af6c2269d..0e78aec779 100644 --- a/packages/yoroi-extension/features/mock-dApp-webpage/index.js +++ b/packages/yoroi-extension/features/mock-dApp-webpage/index.js @@ -498,7 +498,7 @@ export class MockDAppWebpage { async getCollateralUtxos(amount: string): Promise { this.logger.info(`MockDApp: Getting Collateral Utxos`); - Buffer.from( + const convertedAmount = Buffer.from( CardanoWasm.Value.new(CardanoWasm.BigNum.from_str(amount)).to_bytes() ).toString('hex'); @@ -506,15 +506,18 @@ export class MockDAppWebpage { const callback = args[args.length - 1]; window.api - .getCollateralUtxos('1a004ac4a0') + .getCollateralUtxos(args[0]) // eslint-disable-next-line promise/always-return .then(utxosResponse => { + if (utxosResponse == null || utxosResponse.length === 0) { + callback({ success: false, errMsg: 'NO COLLATERAL UTXOS' }); + } callback({ success: true, retValue: utxosResponse }); }) .catch(error => { callback({ success: false, errMsg: error.message }); }); - }); + }, convertedAmount); if (collateralResponse.success) { const utxos = this._mapCborUtxos(collateralResponse.retValue); return JSON.stringify(utxos, undefined, 2); From 5e551d99dad9c1b542ac37e08808b26a11df8d60 Mon Sep 17 00:00:00 2001 From: Denis Date: Fri, 9 Dec 2022 18:47:51 +0300 Subject: [PATCH 071/172] Added output with 1 ADA --- .../features/mock-chain/mockCardanoImporter.js | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/packages/yoroi-extension/features/mock-chain/mockCardanoImporter.js b/packages/yoroi-extension/features/mock-chain/mockCardanoImporter.js index 64f2b00018..dd44a14501 100644 --- a/packages/yoroi-extension/features/mock-chain/mockCardanoImporter.js +++ b/packages/yoroi-extension/features/mock-chain/mockCardanoImporter.js @@ -1457,7 +1457,7 @@ export const generateTransaction = (): {| ChainDerivations.EXTERNAL, 1, ]), - amount: '1', + amount: '4500000', //amount: '1', assets: [], }, { @@ -1466,7 +1466,16 @@ export const generateTransaction = (): {| // addr1qyv7qlaucathxkwkc503ujw0rv9lfj2rkj96feyst2rs9ey4tr5knj4fu4adelzqhxg8adu5xca4jra0gtllfrpcawyqzajfkn address: '0119e07fbcc7577359d6c51f1e49cf1b0bf4c943b48ba4e4905a8702e49558e969caa9e57adcfc40b9907eb794363b590faf42fff48c38eb88', - amount: '5500000', + amount: '1000000', + assets: [], + }, + { + // 0'/0/0 + // eslint-disable-next-line max-len + // addr1qyv7qlaucathxkwkc503ujw0rv9lfj2rkj96feyst2rs9ey4tr5knj4fu4adelzqhxg8adu5xca4jra0gtllfrpcawyqzajfkn + address: + '0119e07fbcc7577359d6c51f1e49cf1b0bf4c943b48ba4e4905a8702e49558e969caa9e57adcfc40b9907eb794363b590faf42fff48c38eb88', + amount: '4500000', assets: [], }, ], From 6fa722d889fd6af835004c1f068044fe27bf198f Mon Sep 17 00:00:00 2001 From: Denis Date: Fri, 9 Dec 2022 18:48:21 +0300 Subject: [PATCH 072/172] Updated tests to request collateral for 1 ADA --- .../06-connector-get-collateral.feature | 19 +++++-------------- 1 file changed, 5 insertions(+), 14 deletions(-) diff --git a/packages/yoroi-extension/features/06-connector-get-collateral.feature b/packages/yoroi-extension/features/06-connector-get-collateral.feature index 246e3535fb..42fc65c4ef 100644 --- a/packages/yoroi-extension/features/06-connector-get-collateral.feature +++ b/packages/yoroi-extension/features/06-connector-get-collateral.feature @@ -5,26 +5,23 @@ Feature: dApp connector get collateral Given I have opened the extension And I have completed the basic setup Then I should see the Create wallet screen + Given There is a Shelley wallet stored named shelley-simple-15 + Then Revamp. I switch to revamp version + Then I open the mock dApp tab @dApp-1023 Scenario: dApp, anonymous wallet, get collateral (DAPP-1023) - Given There is a Shelley wallet stored named shelley-simple-15 - Then Revamp. I switch to revamp version - Then I open the mock dApp tab And I request anonymous access to Yoroi Then I should see the connector popup for connection And I select the only wallet named shelley-simple-15 with 5.5 balance Then The popup window should be closed And The access request should succeed And The wallet shelley-simple-15 is connected to the website localhost - Then The dApp should see collateral: {"utxo_id":"3677e75c7ba699bfdc6cd57d42f246f86f63aefd76025006ac78313fad2bba211","tx_hash":"3677e75c7ba699bfdc6cd57d42f246f86f63aefd76025006ac78313fad2bba21","tx_index":1,"receiver":"addr1qyv7qlaucathxkwkc503ujw0rv9lfj2rkj96feyst2rs9ey4tr5knj4fu4adelzqhxg8adu5xca4jra0gtllfrpcawyqzajfkn","amount":"5500000","assets":[]} for 490000 + Then The dApp should see collateral: {"utxo_id":"3677e75c7ba699bfdc6cd57d42f246f86f63aefd76025006ac78313fad2bba211","tx_hash":"3677e75c7ba699bfdc6cd57d42f246f86f63aefd76025006ac78313fad2bba21","tx_index":1,"receiver":"addr1qyv7qlaucathxkwkc503ujw0rv9lfj2rkj96feyst2rs9ey4tr5knj4fu4adelzqhxg8adu5xca4jra0gtllfrpcawyqzajfkn","amount":"1000000","assets":[]} for 1000000 @dApp-1024 Scenario: dApp, authorized wallet, get collateral (DAPP-1024) - Given There is a Shelley wallet stored named shelley-simple-15 - Then Revamp. I switch to revamp version - Then I open the mock dApp tab And I request access to Yoroi Then I should see the connector popup for connection And I select the only wallet named shelley-simple-15 with 5.5 balance @@ -32,13 +29,10 @@ Feature: dApp connector get collateral Then The popup window should be closed And The access request should succeed And The wallet shelley-simple-15 is connected to the website localhost - Then The dApp should see collateral: {"utxo_id":"3677e75c7ba699bfdc6cd57d42f246f86f63aefd76025006ac78313fad2bba211","tx_hash":"3677e75c7ba699bfdc6cd57d42f246f86f63aefd76025006ac78313fad2bba21","tx_index":1,"receiver":"addr1qyv7qlaucathxkwkc503ujw0rv9lfj2rkj96feyst2rs9ey4tr5knj4fu4adelzqhxg8adu5xca4jra0gtllfrpcawyqzajfkn","amount":"5500000","assets":[]} for 490000 + Then The dApp should see collateral: {"utxo_id":"3677e75c7ba699bfdc6cd57d42f246f86f63aefd76025006ac78313fad2bba211","tx_hash":"3677e75c7ba699bfdc6cd57d42f246f86f63aefd76025006ac78313fad2bba21","tx_index":1,"receiver":"addr1qyv7qlaucathxkwkc503ujw0rv9lfj2rkj96feyst2rs9ey4tr5knj4fu4adelzqhxg8adu5xca4jra0gtllfrpcawyqzajfkn","amount":"1000000","assets":[]} for 1000000 @dApp-1025 Scenario: dApp, authorized wallet, get collateral, connector popup (DAPP-1025) - Given There is a Shelley wallet stored named shelley-simple-15 - Then Revamp. I switch to revamp version - Then I open the mock dApp tab And I request access to Yoroi Then I should see the connector popup for connection And I select the only wallet named shelley-simple-15 with 5.5 balance @@ -58,9 +52,6 @@ Feature: dApp connector get collateral @dApp-1026 Scenario: dApp, anonymous wallet, get collateral, connector popup (DAPP-1026) - Given There is a Shelley wallet stored named shelley-simple-15 - Then Revamp. I switch to revamp version - Then I open the mock dApp tab And I request anonymous access to Yoroi Then I should see the connector popup for connection And I select the only wallet named shelley-simple-15 with 5.5 balance From fb65ac653f0e0c07d29ca981a5cd8b27bd86816f Mon Sep 17 00:00:00 2001 From: Denis Date: Fri, 9 Dec 2022 20:13:19 +0300 Subject: [PATCH 073/172] added 1 more UTXO with 1 ADA --- .../features/mock-chain/mockCardanoImporter.js | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/packages/yoroi-extension/features/mock-chain/mockCardanoImporter.js b/packages/yoroi-extension/features/mock-chain/mockCardanoImporter.js index dd44a14501..134f1d2852 100644 --- a/packages/yoroi-extension/features/mock-chain/mockCardanoImporter.js +++ b/packages/yoroi-extension/features/mock-chain/mockCardanoImporter.js @@ -1457,7 +1457,7 @@ export const generateTransaction = (): {| ChainDerivations.EXTERNAL, 1, ]), - amount: '4500000', //amount: '1', + amount: '4500000', assets: [], }, { @@ -1475,7 +1475,16 @@ export const generateTransaction = (): {| // addr1qyv7qlaucathxkwkc503ujw0rv9lfj2rkj96feyst2rs9ey4tr5knj4fu4adelzqhxg8adu5xca4jra0gtllfrpcawyqzajfkn address: '0119e07fbcc7577359d6c51f1e49cf1b0bf4c943b48ba4e4905a8702e49558e969caa9e57adcfc40b9907eb794363b590faf42fff48c38eb88', - amount: '4500000', + amount: '1000000', + assets: [], + }, + { + // 0'/0/0 + // eslint-disable-next-line max-len + // addr1qyv7qlaucathxkwkc503ujw0rv9lfj2rkj96feyst2rs9ey4tr5knj4fu4adelzqhxg8adu5xca4jra0gtllfrpcawyqzajfkn + address: + '0119e07fbcc7577359d6c51f1e49cf1b0bf4c943b48ba4e4905a8702e49558e969caa9e57adcfc40b9907eb794363b590faf42fff48c38eb88', + amount: '3500000', assets: [], }, ], From 570121cf79004671c2ebeda43c9153b8a5903adc Mon Sep 17 00:00:00 2001 From: Denis Date: Mon, 12 Dec 2022 13:39:40 +0300 Subject: [PATCH 074/172] added new mocked wallet for collateral --- .../features/mock-chain/TestWallets.js | 6 ++ .../mock-chain/mockCardanoImporter.js | 70 ++++++++++++++++--- 2 files changed, 67 insertions(+), 9 deletions(-) diff --git a/packages/yoroi-extension/features/mock-chain/TestWallets.js b/packages/yoroi-extension/features/mock-chain/TestWallets.js index 2be92e61b6..645fb7e678 100644 --- a/packages/yoroi-extension/features/mock-chain/TestWallets.js +++ b/packages/yoroi-extension/features/mock-chain/TestWallets.js @@ -37,6 +37,7 @@ function createWallet(payload: {| export type WalletNames = 'shelley-simple-24' | 'shelley-simple-15' | + 'shelley-collateral' | 'shelley-delegated' | 'shelley-ledger-delegated' | 'shelley-only-registered' | @@ -128,6 +129,11 @@ export const testWallets: { [key: WalletNames]: RestorationInput, ... } = Object mnemonic: 'eight country switch draw meat scout mystery blade tip drift useless good keep usage title', plate: 'ZDDC-9858', }), + createWallet({ + name: ('shelley-collateral': WalletNames), + mnemonic: 'deal calm cloth world refuse pledge grant tuna inner body fat afford absorb off barely', + plate: 'HLBZ-9462', + }), createWallet({ name: ('shelley-delegated': WalletNames), mnemonic: 'parrot offer switch thank film high drop salute task train squirrel coral consider coyote evolve', diff --git a/packages/yoroi-extension/features/mock-chain/mockCardanoImporter.js b/packages/yoroi-extension/features/mock-chain/mockCardanoImporter.js index 134f1d2852..06e29f25b2 100644 --- a/packages/yoroi-extension/features/mock-chain/mockCardanoImporter.js +++ b/packages/yoroi-extension/features/mock-chain/mockCardanoImporter.js @@ -84,6 +84,7 @@ export const generateTransaction = (): {| cip1852TrezorTx2: RemoteTransaction, cip1852TrezorTx3: RemoteTransaction, shelleySimple15: RemoteTransaction, + shelleyCollateral: RemoteTransaction, shelleyDelegatedTx1: RemoteTransaction, shelleyDelegatedTx2: RemoteTransaction, shelleyLedgerDelegatedTx1: RemoteTransaction, @@ -1466,34 +1467,81 @@ export const generateTransaction = (): {| // addr1qyv7qlaucathxkwkc503ujw0rv9lfj2rkj96feyst2rs9ey4tr5knj4fu4adelzqhxg8adu5xca4jra0gtllfrpcawyqzajfkn address: '0119e07fbcc7577359d6c51f1e49cf1b0bf4c943b48ba4e4905a8702e49558e969caa9e57adcfc40b9907eb794363b590faf42fff48c38eb88', - amount: '1000000', + amount: '5500000', + assets: [], + }, + ], + height: 304, + block_hash: '304', + tx_ordinal: 0, + time: '2019-04-20T15:16:53.000Z', + epoch: 0, + slot: 304, + last_update: '2019-05-20T23:18:11.899Z', + tx_state: 'Successful', + }; + + // ===================== + // shelley-collateral + // ===================== + + const shelleyCollateral = { + hash: '021657dfc7f9e33d0ca9cb33b0487138d2f74286e9e00f19946f27e9a8c6f607', + inputs: [ + { + // Ae2tdPwUPEZ2y4rAdJG2coM4MXeNNAAKDztXXztz8LrcYRZ8waYoa7pWXgj + address: getSingleAddressString(testWallets['dump-wallet'].mnemonic, [ + WalletTypePurpose.BIP44, + CoinTypes.CARDANO, + 0 + HARD_DERIVATION_START, + ChainDerivations.EXTERNAL, + 1, + ]), + txHash: distributorTx.hash, + id: distributorTx.hash + '17', + index: 17, + amount: '7000000', + assets: [], + }, + ], + outputs: [ + { + // Ae2tdPwUPEZ2y4rAdJG2coM4MXeNNAAKDztXXztz8LrcYRZ8waYoa7pWXgj + address: getSingleAddressString(testWallets['dump-wallet'].mnemonic, [ + WalletTypePurpose.BIP44, + CoinTypes.CARDANO, + 0 + HARD_DERIVATION_START, + ChainDerivations.EXTERNAL, + 1, + ]), + amount: '5000000', assets: [], }, { // 0'/0/0 // eslint-disable-next-line max-len - // addr1qyv7qlaucathxkwkc503ujw0rv9lfj2rkj96feyst2rs9ey4tr5knj4fu4adelzqhxg8adu5xca4jra0gtllfrpcawyqzajfkn + // addr1q9nv4vttp9f00pttk2unp4jhprd67sgffkg9ak0sawvxa68vfz8ymjd9j2vdea8088ut8jpx4c6tr08dwuzs07leyrtsuc6l06 address: - '0119e07fbcc7577359d6c51f1e49cf1b0bf4c943b48ba4e4905a8702e49558e969caa9e57adcfc40b9907eb794363b590faf42fff48c38eb88', + '0166cab16b0952f7856bb2b930d65708dbaf41094d905ed9f0eb986ee8ec488e4dc9a59298dcf4ef39f8b3c826ae34b1bced770507fbf920d7', amount: '1000000', assets: [], }, { // 0'/0/0 // eslint-disable-next-line max-len - // addr1qyv7qlaucathxkwkc503ujw0rv9lfj2rkj96feyst2rs9ey4tr5knj4fu4adelzqhxg8adu5xca4jra0gtllfrpcawyqzajfkn + // addr1q9nv4vttp9f00pttk2unp4jhprd67sgffkg9ak0sawvxa68vfz8ymjd9j2vdea8088ut8jpx4c6tr08dwuzs07leyrtsuc6l06 address: - '0119e07fbcc7577359d6c51f1e49cf1b0bf4c943b48ba4e4905a8702e49558e969caa9e57adcfc40b9907eb794363b590faf42fff48c38eb88', - amount: '3500000', + '0166cab16b0952f7856bb2b930d65708dbaf41094d905ed9f0eb986ee8ec488e4dc9a59298dcf4ef39f8b3c826ae34b1bced770507fbf920d7', + amount: '1000000', assets: [], }, ], - height: 304, - block_hash: '304', + height: 305, + block_hash: '305', tx_ordinal: 0, time: '2019-04-20T15:16:53.000Z', epoch: 0, - slot: 304, + slot: 305, last_update: '2019-05-20T23:18:11.899Z', tx_state: 'Successful', }; @@ -1941,6 +1989,7 @@ export const generateTransaction = (): {| cip1852TrezorTx2, cip1852TrezorTx3, shelleySimple15, + shelleyCollateral, shelleyDelegatedTx1, shelleyDelegatedTx2, shelleyLedgerDelegatedTx1, @@ -1983,6 +2032,7 @@ export function addTransaction(tx: MockTx): void { if (txOrdinal == null) return true; if (txOrdinal > newTxOrdinal) return true; if (txOrdinal < newTxOrdinal) return false; + console.log(`DEBUG::\nepoch -> ${epoch}\nslot -> ${slot}\ntxOrdinal -> ${txOrdinal}`); throw new Error(`Transaction ${tx.hash} occurs at same position as an existing transactions`); }); if (insertionIndex === -1) { @@ -2031,6 +2081,8 @@ export function resetChain(chainToUse: $Values): void { addTransaction(txs.cip1852TrezorTx3); // shelley-simple-15 addTransaction(txs.shelleySimple15); + // shelley-collateral + addTransaction(txs.shelleyCollateral); // shelley-delegated addTransaction(txs.shelleyDelegatedTx1); addTransaction(txs.shelleyDelegatedTx2); From 7f0fda80d6c11ee8d69ddec8e4343dc6d7821a81 Mon Sep 17 00:00:00 2001 From: Denis Date: Mon, 12 Dec 2022 13:40:31 +0300 Subject: [PATCH 075/172] using the new collateral wallet --- .../06-connector-get-collateral.feature | 27 ++++++++++++------- 1 file changed, 18 insertions(+), 9 deletions(-) diff --git a/packages/yoroi-extension/features/06-connector-get-collateral.feature b/packages/yoroi-extension/features/06-connector-get-collateral.feature index 42fc65c4ef..cc2b193267 100644 --- a/packages/yoroi-extension/features/06-connector-get-collateral.feature +++ b/packages/yoroi-extension/features/06-connector-get-collateral.feature @@ -5,34 +5,40 @@ Feature: dApp connector get collateral Given I have opened the extension And I have completed the basic setup Then I should see the Create wallet screen - Given There is a Shelley wallet stored named shelley-simple-15 - Then Revamp. I switch to revamp version - Then I open the mock dApp tab @dApp-1023 Scenario: dApp, anonymous wallet, get collateral (DAPP-1023) + Given There is a Shelley wallet stored named shelley-collateral + Then Revamp. I switch to revamp version + Then I open the mock dApp tab And I request anonymous access to Yoroi Then I should see the connector popup for connection - And I select the only wallet named shelley-simple-15 with 5.5 balance + And I select the only wallet named shelley-collateral with 2 balance Then The popup window should be closed And The access request should succeed - And The wallet shelley-simple-15 is connected to the website localhost - Then The dApp should see collateral: {"utxo_id":"3677e75c7ba699bfdc6cd57d42f246f86f63aefd76025006ac78313fad2bba211","tx_hash":"3677e75c7ba699bfdc6cd57d42f246f86f63aefd76025006ac78313fad2bba21","tx_index":1,"receiver":"addr1qyv7qlaucathxkwkc503ujw0rv9lfj2rkj96feyst2rs9ey4tr5knj4fu4adelzqhxg8adu5xca4jra0gtllfrpcawyqzajfkn","amount":"1000000","assets":[]} for 1000000 + And The wallet shelley-collateral is connected to the website localhost + Then The dApp should see collateral: {"utxo_id":"021657dfc7f9e33d0ca9cb33b0487138d2f74286e9e00f19946f27e9a8c6f6071","tx_hash":"021657dfc7f9e33d0ca9cb33b0487138d2f74286e9e00f19946f27e9a8c6f607","tx_index":1,"receiver":"addr1q9nv4vttp9f00pttk2unp4jhprd67sgffkg9ak0sawvxa68vfz8ymjd9j2vdea8088ut8jpx4c6tr08dwuzs07leyrtsuc6l06","amount":"1000000","assets":[]} for 1000000 @dApp-1024 Scenario: dApp, authorized wallet, get collateral (DAPP-1024) + Given There is a Shelley wallet stored named shelley-collateral + Then Revamp. I switch to revamp version + Then I open the mock dApp tab And I request access to Yoroi Then I should see the connector popup for connection - And I select the only wallet named shelley-simple-15 with 5.5 balance + And I select the only wallet named shelley-collateral with 2 balance Then I enter the spending password asdfasdfasdf and click confirm Then The popup window should be closed And The access request should succeed - And The wallet shelley-simple-15 is connected to the website localhost - Then The dApp should see collateral: {"utxo_id":"3677e75c7ba699bfdc6cd57d42f246f86f63aefd76025006ac78313fad2bba211","tx_hash":"3677e75c7ba699bfdc6cd57d42f246f86f63aefd76025006ac78313fad2bba21","tx_index":1,"receiver":"addr1qyv7qlaucathxkwkc503ujw0rv9lfj2rkj96feyst2rs9ey4tr5knj4fu4adelzqhxg8adu5xca4jra0gtllfrpcawyqzajfkn","amount":"1000000","assets":[]} for 1000000 + And The wallet shelley-collateral is connected to the website localhost + Then The dApp should see collateral: {"utxo_id":"021657dfc7f9e33d0ca9cb33b0487138d2f74286e9e00f19946f27e9a8c6f6071","tx_hash":"021657dfc7f9e33d0ca9cb33b0487138d2f74286e9e00f19946f27e9a8c6f607","tx_index":1,"receiver":"addr1q9nv4vttp9f00pttk2unp4jhprd67sgffkg9ak0sawvxa68vfz8ymjd9j2vdea8088ut8jpx4c6tr08dwuzs07leyrtsuc6l06","amount":"1000000","assets":[]} for 1000000 @dApp-1025 Scenario: dApp, authorized wallet, get collateral, connector popup (DAPP-1025) + Given There is a Shelley wallet stored named shelley-simple-15 + Then Revamp. I switch to revamp version + Then I open the mock dApp tab And I request access to Yoroi Then I should see the connector popup for connection And I select the only wallet named shelley-simple-15 with 5.5 balance @@ -52,6 +58,9 @@ Feature: dApp connector get collateral @dApp-1026 Scenario: dApp, anonymous wallet, get collateral, connector popup (DAPP-1026) + Given There is a Shelley wallet stored named shelley-simple-15 + Then Revamp. I switch to revamp version + Then I open the mock dApp tab And I request anonymous access to Yoroi Then I should see the connector popup for connection And I select the only wallet named shelley-simple-15 with 5.5 balance From 63666b67c80cce33b659ef753da12ec4813d2fe0 Mon Sep 17 00:00:00 2001 From: Denis Date: Mon, 12 Dec 2022 13:42:47 +0300 Subject: [PATCH 076/172] getCollateralUtxos -> getCollateral --- .../features/mock-dApp-webpage/index.js | 33 ++++++++++++++++--- .../step_definitions/connector-steps.js | 4 +-- 2 files changed, 30 insertions(+), 7 deletions(-) diff --git a/packages/yoroi-extension/features/mock-dApp-webpage/index.js b/packages/yoroi-extension/features/mock-dApp-webpage/index.js index 0e78aec779..19fc89bb77 100644 --- a/packages/yoroi-extension/features/mock-dApp-webpage/index.js +++ b/packages/yoroi-extension/features/mock-dApp-webpage/index.js @@ -495,7 +495,7 @@ export class MockDAppWebpage { return signingResult; } - async getCollateralUtxos(amount: string): Promise { + async getCollateral(amount: string): Promise { this.logger.info(`MockDApp: Getting Collateral Utxos`); const convertedAmount = Buffer.from( @@ -506,7 +506,7 @@ export class MockDAppWebpage { const callback = args[args.length - 1]; window.api - .getCollateralUtxos(args[0]) + .getCollateral(args[0]) // eslint-disable-next-line promise/always-return .then(utxosResponse => { if (utxosResponse == null || utxosResponse.length === 0) { @@ -528,12 +528,35 @@ export class MockDAppWebpage { async addCollateral(amount: string) { this.logger.info(`MockDApp: Requesting collateral: data="${amount}"`); - const utxosHex = Buffer.from( + const amountHex = Buffer.from( CardanoWasm.Value.new(CardanoWasm.BigNum.from_str(amount)).to_bytes() ).toString('hex'); this.driver.executeScript(utxos => { - window.collateralPromise = window.api.getCollateralUtxos(utxos); - }, utxosHex); + window.collateralPromise = window.api.getCollateral(utxos); + }, amountHex); + } + + async getCollateralResult(): Promise { + this.logger.info(`MockDApp: Getting collateral data result`); + const collateralResult = await this.driver.executeAsyncScript((...args) => { + const callback = args[args.length - 1]; + window.collateralPromise + .then(utxosResponse => { + if (utxosResponse == null || utxosResponse.length === 0) { + callback({ success: false, errMsg: 'NO COLLATERAL UTXOS' }); + } + callback({ success: true, retValue: utxosResponse }); + }) + .catch(error => { + callback({ success: false, errMsg: error.message }); + }); + }); + if (collateralResult.success) { + const utxos = this._mapCborUtxos(collateralResult.retValue); + return JSON.stringify(utxos, undefined, 2); + } + this.logger.error(`MockDApp: -> The error is received: ${collateralResult.errMsg}`); + throw new MockDAppWebpageError(collateralResult.errMsg); } } diff --git a/packages/yoroi-extension/features/step_definitions/connector-steps.js b/packages/yoroi-extension/features/step_definitions/connector-steps.js index 357c71954b..83e63b61b4 100644 --- a/packages/yoroi-extension/features/step_definitions/connector-steps.js +++ b/packages/yoroi-extension/features/step_definitions/connector-steps.js @@ -384,7 +384,7 @@ Then(/^The dApp should see collateral: (.+) for (.+)$/, async function (expected this.webDriverLogger.info( `Step: The dApp should see collateral: ${expectedCollateral} for ${utxosAmount}` ); - const collateral = await this.mockDAppPage.getCollateralUtxos(utxosAmount); + const collateral = await this.mockDAppPage.getCollateral(utxosAmount); const collateralJson = JSON.parse(collateral)[0]; const expectedUtxos = JSON.parse(expectedCollateral); expect(collateralJson, 'Collateral is different to expected').to.be.deep.equal(expectedUtxos); @@ -394,7 +394,7 @@ Then(/^The dApp should see collateral: (.+) for (.+)$/, async function (expected Then(/^The dApp should receive collateral$/, async function (table) { const fields = table.hashes()[0]; const utxosAmount = fields.forAmount; - const collateral = await this.mockDAppPage.getCollateralUtxos(utxosAmount); + const collateral = await this.mockDAppPage.getCollateralResult(); const collateralJson = JSON.parse(collateral)[0]; expect(collateralJson.amount, 'Amount is different').to.equal(fields.amount); expect(collateralJson.receiver, 'Receiver is different').to.equal(fields.receiver); From 0b81d27c8f6ffa4253ad2326b9e244662f8fab99 Mon Sep 17 00:00:00 2001 From: Denis Date: Mon, 12 Dec 2022 20:50:44 +0300 Subject: [PATCH 077/172] updated findNewWindows --- packages/yoroi-extension/features/support/windowManager.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/yoroi-extension/features/support/windowManager.js b/packages/yoroi-extension/features/support/windowManager.js index c2b7e187c6..1f165acf6e 100644 --- a/packages/yoroi-extension/features/support/windowManager.js +++ b/packages/yoroi-extension/features/support/windowManager.js @@ -162,10 +162,10 @@ export class WindowManager { return newWindowHandles.filter(handle => !oldHandles.includes(handle)); } - async findNewWindows(): Promise> { + async findNewWindows(tries: number = 50): Promise> { this.logger.info(`WindowManager: Finding a new window`); let newWindowHandles: Array = []; - for (let i = 0; i < 50; i++) { + for (let i = 0; i < tries; i++) { this.logger.info(`WindowManager: -> Try ${i} to find a new window`); await new Promise(resolve => setTimeout(resolve, 100)); newWindowHandles = await this.getAllWindowHandles(); From 2220340a8d8a2af047e9bb48d4f00ff74893bb92 Mon Sep 17 00:00:00 2001 From: Denis Date: Mon, 12 Dec 2022 20:55:15 +0300 Subject: [PATCH 078/172] updated asking for collateral --- .../features/step_definitions/connector-steps.js | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/packages/yoroi-extension/features/step_definitions/connector-steps.js b/packages/yoroi-extension/features/step_definitions/connector-steps.js index 83e63b61b4..99ba33a453 100644 --- a/packages/yoroi-extension/features/step_definitions/connector-steps.js +++ b/packages/yoroi-extension/features/step_definitions/connector-steps.js @@ -375,9 +375,15 @@ Then(/^The user reject for signing data is received$/, async function () { expect(signingResult.info).to.equal(userRejectSigningMsg, 'Wrong error message'); }); -When(/^I ask to get Collateral for (.+) Utxos$/, async function (utxos) { - this.webDriverLogger.info(`Step: I ask to get Collateral for ${utxos} Utxos`); - await this.mockDAppPage.addCollateral(utxos); +When(/^I ask to get Collateral for (.+) ADA$/, async function (amount) { + this.webDriverLogger.info(`Step: I ask to get Collateral for ${amount} ADA`); + const amountString = (parseFloat(amount) * 1000000).toString(); + await this.mockDAppPage.addCollateral(amountString); + const newWindow = this.windowManager.findNewWindows(20); + if (newWindow.length == 0) { + this.webDriverLogger.info(`Step: -> Asking again for collateral`); + this.mockDAppPage.addCollateral(amountString); + } }); Then(/^The dApp should see collateral: (.+) for (.+)$/, async function (expectedCollateral, utxosAmount) { @@ -393,7 +399,6 @@ Then(/^The dApp should see collateral: (.+) for (.+)$/, async function (expected Then(/^The dApp should receive collateral$/, async function (table) { const fields = table.hashes()[0]; - const utxosAmount = fields.forAmount; const collateral = await this.mockDAppPage.getCollateralResult(); const collateralJson = JSON.parse(collateral)[0]; expect(collateralJson.amount, 'Amount is different').to.equal(fields.amount); From bed4cb74a6045a423a78967f35c343f1bdbebc57 Mon Sep 17 00:00:00 2001 From: Denis Date: Mon, 12 Dec 2022 20:56:44 +0300 Subject: [PATCH 079/172] updated mockdApp page --- .../features/mock-dApp-webpage/index.js | 25 ++++++++----------- 1 file changed, 10 insertions(+), 15 deletions(-) diff --git a/packages/yoroi-extension/features/mock-dApp-webpage/index.js b/packages/yoroi-extension/features/mock-dApp-webpage/index.js index 19fc89bb77..d48b3b6da8 100644 --- a/packages/yoroi-extension/features/mock-dApp-webpage/index.js +++ b/packages/yoroi-extension/features/mock-dApp-webpage/index.js @@ -171,12 +171,12 @@ export class MockDAppWebpage { throw new MockDAppWebpageError(changeAddresses.errMsg); } - async _getUTXOs(): Promise> { + async _getUTXOs(amount?: string): Promise> { this.logger.info(`MockDApp: Getting UTXOs`); const walletUTXOsResponse = await this.driver.executeAsyncScript((...args) => { const callback = args[args.length - 1]; window.api - .getUtxos() + .getUtxos(args[0]) .then(utxosResponse => { // eslint-disable-next-line promise/always-return if (utxosResponse.length === 0) { @@ -188,7 +188,7 @@ export class MockDAppWebpage { .catch(error => { callback({ success: false, errMsg: JSON.stringify(error) }); }); - }); + }, amount); this.logger.info( `MockDApp: -> The walletUTXOsResponse: ${JSON.stringify(walletUTXOsResponse)}` ); @@ -353,7 +353,7 @@ export class MockDAppWebpage { this.logger.info( `MockDApp: Requesting signing the transaction: amount="${amount}", toAddress="${toAddress}"` ); - const UTXOs = await this._getUTXOs(); + const UTXOs = await this._getUTXOs(amount); const changeAddress = await this._getChangeAddress(); const txBuilder = this._transactionBuilder(); const utxo = UTXOs[0]; @@ -466,13 +466,9 @@ export class MockDAppWebpage { } this.logger.info(`MockDApp: -> Payload HEX: ${payloadHex}`); - this.driver.executeScript( - (addr, plHex) => { - window.signDataPromise = window.api.signData(addr, plHex); - }, - address, - payloadHex - ); + const scriptString = `window.signDataPromise = window.api.signData(${JSON.stringify(address)}, ${JSON.stringify(payloadHex)});`; + + this.driver.executeScript(scriptString); } async getSigningDataResult(): Promise { @@ -526,15 +522,14 @@ export class MockDAppWebpage { throw new MockDAppWebpageError(collateralResponse.errMsg); } - async addCollateral(amount: string) { + addCollateral(amount: string) { this.logger.info(`MockDApp: Requesting collateral: data="${amount}"`); const amountHex = Buffer.from( CardanoWasm.Value.new(CardanoWasm.BigNum.from_str(amount)).to_bytes() ).toString('hex'); + const scriptString = `window.collateralPromise = window.api.getCollateral(${JSON.stringify(amountHex)});`; - this.driver.executeScript(utxos => { - window.collateralPromise = window.api.getCollateral(utxos); - }, amountHex); + this.driver.executeScript(scriptString); } async getCollateralResult(): Promise { From 43223503cadb357b56f577bd792117f1a35ea2bf Mon Sep 17 00:00:00 2001 From: Denis Date: Mon, 12 Dec 2022 20:59:22 +0300 Subject: [PATCH 080/172] updated the feature --- .../features/06-connector-get-collateral.feature | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/packages/yoroi-extension/features/06-connector-get-collateral.feature b/packages/yoroi-extension/features/06-connector-get-collateral.feature index cc2b193267..361e0ea56a 100644 --- a/packages/yoroi-extension/features/06-connector-get-collateral.feature +++ b/packages/yoroi-extension/features/06-connector-get-collateral.feature @@ -46,15 +46,15 @@ Feature: dApp connector get collateral Then The popup window should be closed And The access request should succeed And The wallet shelley-simple-15 is connected to the website localhost - Then I ask to get Collateral for 2000000 Utxos + Then I ask to get Collateral for 1 ADA Then I should see the connector popup to Add Collateral with fee info | fee | | 0.171177 | Then I enter the spending password asdfasdfasdf and click confirm Then The popup window should be closed Then The dApp should receive collateral - | forAmount | amount | receiver | - | 2000000 | 1000000 | addr1qy245684mdhpwzs0p37jz8pymn5g9v37rqjy78c59f06xau4tr5knj4fu4adelzqhxg8adu5xca4jra0gtllfrpcawyqdqef6t | + | amount | receiver | + | 1000000 | addr1qy245684mdhpwzs0p37jz8pymn5g9v37rqjy78c59f06xau4tr5knj4fu4adelzqhxg8adu5xca4jra0gtllfrpcawyqdqef6t | @dApp-1026 Scenario: dApp, anonymous wallet, get collateral, connector popup (DAPP-1026) @@ -67,12 +67,12 @@ Feature: dApp connector get collateral Then The popup window should be closed And The access request should succeed And The wallet shelley-simple-15 is connected to the website localhost - Then I ask to get Collateral for 2000000 Utxos + Then I ask to get Collateral for 1 ADA Then I should see the connector popup to Add Collateral with fee info | fee | | 0.171177 | Then I enter the spending password asdfasdfasdf and click confirm Then The popup window should be closed Then The dApp should receive collateral - | forAmount | amount | receiver | - | 2000000 | 1000000 | addr1qy245684mdhpwzs0p37jz8pymn5g9v37rqjy78c59f06xau4tr5knj4fu4adelzqhxg8adu5xca4jra0gtllfrpcawyqdqef6t | \ No newline at end of file + | amount | receiver | + | 1000000 | addr1qy245684mdhpwzs0p37jz8pymn5g9v37rqjy78c59f06xau4tr5knj4fu4adelzqhxg8adu5xca4jra0gtllfrpcawyqdqef6t | \ No newline at end of file From e3f2feb8b03698e98ff867165a4759165bc1f7aa Mon Sep 17 00:00:00 2001 From: Denis Date: Wed, 14 Dec 2022 13:22:02 +0300 Subject: [PATCH 081/172] getting background logs --- .../features/step_definitions/common-steps.js | 11 ++++++++-- .../features/support/webdriver.js | 5 ++++- .../features/support/windowManager.js | 21 +++++++++++++++++++ 3 files changed, 34 insertions(+), 3 deletions(-) diff --git a/packages/yoroi-extension/features/step_definitions/common-steps.js b/packages/yoroi-extension/features/step_definitions/common-steps.js index ed9871a03f..63da93bad3 100644 --- a/packages/yoroi-extension/features/step_definitions/common-steps.js +++ b/packages/yoroi-extension/features/step_definitions/common-steps.js @@ -106,7 +106,7 @@ import { uriPromptForm, } from '../pages/uriPromptPage'; import { yoroiModern } from '../pages/mainWindowPage'; -import { extensionTabName, WindowManager } from '../support/windowManager'; +import { backgroungTabName, extensionTabName, WindowManager } from '../support/windowManager'; import { MockDAppWebpage } from '../mock-dApp-webpage'; const simpleNodeLogger = require('simple-node-logger'); @@ -237,6 +237,13 @@ After(async function (scenario) { if (this.getBrowser() !== 'firefox') { await getLogs(this.driver, 'failedStep', logging.Type.BROWSER); await getLogs(this.driver, 'failedStep', logging.Type.DRIVER); + // getting logs from background + const currentTabName = this.windowManager.getCurrentWindowName(); + const backgroundPageUrl = `${this.getExtensionUrl()}/background.html`; + await this.windowManager.openNewWindow(backgroungTabName, backgroundPageUrl); + await this.windowManager.switchTo(backgroungTabName); + await getLogs(this.driver, 'background', logging.Type.BROWSER); + await this.windowManager.switchTo(currentTabName); } } await this.windowManager.switchTo(extensionTabName); @@ -331,7 +338,7 @@ async function getLogs(driver, name, loggingType) { const dir = await createDirInTestRunsData(driver, `${log}Logs`); const consoleLogPath = `${dir}/${testProgress.step}_${testProgress.lineNum}-${name}-${log}-log.json`; - const logEntries = await driver.manage().logs().get(loggingType); + const logEntries = await driver.manage().logs().get(loggingType, logging.Level.ALL); const jsonLogs = logEntries.map(l => l.toJSON()); await fsAsync.writeFile(consoleLogPath, JSON.stringify(jsonLogs)); } diff --git a/packages/yoroi-extension/features/support/webdriver.js b/packages/yoroi-extension/features/support/webdriver.js index ffc8f00901..8f2272cc89 100644 --- a/packages/yoroi-extension/features/support/webdriver.js +++ b/packages/yoroi-extension/features/support/webdriver.js @@ -1,7 +1,7 @@ // @flow import { setWorldConstructor } from 'cucumber'; -import { Builder, Key, until, error, promise, WebElement } from 'selenium-webdriver'; +import { Builder, Key, until, error, promise, WebElement, logging } from 'selenium-webdriver'; import chrome from 'selenium-webdriver/chrome'; import firefox from 'selenium-webdriver/firefox'; import path from 'path'; @@ -57,8 +57,11 @@ function getBraveBuilder() { } function getChromeBuilder() { + const prefs = new logging.Preferences(); + prefs.setLevel(logging.Type.BROWSER, logging.Level.ALL); return new Builder() .forBrowser('chrome') + .setLoggingPrefs(prefs) .setChromeOptions( new chrome.Options() .addExtensions(encode(path.resolve(__dirname, '../../Yoroi-test.crx'))) diff --git a/packages/yoroi-extension/features/support/windowManager.js b/packages/yoroi-extension/features/support/windowManager.js index 1f165acf6e..1f034c6e45 100644 --- a/packages/yoroi-extension/features/support/windowManager.js +++ b/packages/yoroi-extension/features/support/windowManager.js @@ -15,6 +15,7 @@ export const popupConnectorName = 'popupConnectorWindow'; export const extensionTabName = 'Yoroi'; export const faqTabName = 'Yoroi - EMURGO'; export const trezorConnectTabName = 'Trezor'; +export const backgroungTabName = 'background'; export class WindowManager { windowHandles: Array; @@ -74,6 +75,15 @@ export class WindowManager { return handles; } + _getTitleByHandle(handle: string): Array { + this.logger.info(`WindowManager: Getting a title by the handle "${handle}"`); + const handles = this.windowHandles.filter(customHandle => customHandle.handle === handle); + this.logger.info( + `WindowManager: -> The titles for the handle "${handle}" are ${JSON.stringify(handles)}` + ); + return handles; + } + async _getCurrentWindowHandle(): Promise { this.logger.info(`WindowManager: Getting the current handle`); const currentHandle = await this.driver.getWindowHandle(); @@ -99,6 +109,17 @@ export class WindowManager { return { title: windowName, handle: currentWindowHandle }; } + async getCurrentWindowName(): Promise { + this.logger.info(`WindowManager: Getting the window name from window manager`); + const currentHandle = await this._getCurrentWindowHandle(); + const handles = this._getTitleByHandle(currentHandle); + if (handles.length === 1) { + return handles[0].title; + } else { + throw new WindowManagerError(`Too many titles for the handle ${currentHandle}`); + } + } + async _openNewWithCheck( type: WindowType, windowName: string, From 0383c22fc50f9b8c09cc4383ee21b466bb6b51dc Mon Sep 17 00:00:00 2001 From: Denis Date: Wed, 14 Dec 2022 13:22:37 +0300 Subject: [PATCH 082/172] added logs for CardanoMockImporter --- .../mock-chain/mockCardanoImporter.js | 73 ++++++++++++------- 1 file changed, 48 insertions(+), 25 deletions(-) diff --git a/packages/yoroi-extension/features/mock-chain/mockCardanoImporter.js b/packages/yoroi-extension/features/mock-chain/mockCardanoImporter.js index 06e29f25b2..469a99c53f 100644 --- a/packages/yoroi-extension/features/mock-chain/mockCardanoImporter.js +++ b/packages/yoroi-extension/features/mock-chain/mockCardanoImporter.js @@ -42,6 +42,20 @@ import { } from '../../app/config/numbersConfig'; import { testWallets } from './TestWallets'; import { CoreAddressTypes } from '../../app/api/ada/lib/storage/database/primitives/enums'; +import { getLogDate } from '../support/helpers/helpers'; +import { testRunsDataDir } from '../support/helpers/common-constants'; + +const simpleNodeLogger = require('simple-node-logger'); +const fs = require('fs'); + +// logging +const dir = `${testRunsDataDir}_cardanoMockServerLogs`; + if (!fs.existsSync(dir)) { + fs.mkdirSync(dir, { recursive: true }); + } +const loggerPath = `${dir}/cardanoMockImporterLog_${getLogDate()}.log`; + +const logger = simpleNodeLogger.createSimpleFileLogger(loggerPath); // based on abandon x 14 + share const genesisTransaction = '52929ce6f1ab83b439e65f6613bad9590bd264c0d6c4f910e36e2369bb987b35'; @@ -93,6 +107,7 @@ export const generateTransaction = (): {| shelleyOnlyRegisteredTx2: RemoteTransaction, delegateMangledWallet: RemoteTransaction, |} => { + logger.info(`mockCardanoServer: Generate transactions`); /** * To simplify, our genesis is a single address which gives all its ada to a "distributor" * The distributor gives ADA to a bunch of addresses to setup the tests @@ -1426,11 +1441,11 @@ export const generateTransaction = (): {| }; // ===================== - // shelley-simple-15 + // shelley-collateral // ===================== - const shelleySimple15 = { - hash: '3677e75c7ba699bfdc6cd57d42f246f86f63aefd76025006ac78313fad2bba21', + const shelleyCollateral = { + hash: '021657dfc7f9e33d0ca9cb33b0487138d2f74286e9e00f19946f27e9a8c6f607', inputs: [ { // Ae2tdPwUPEZ2y4rAdJG2coM4MXeNNAAKDztXXztz8LrcYRZ8waYoa7pWXgj @@ -1444,7 +1459,7 @@ export const generateTransaction = (): {| txHash: distributorTx.hash, id: distributorTx.hash + '16', index: 16, - amount: '10000000', + amount: '7000000', assets: [], }, ], @@ -1458,16 +1473,25 @@ export const generateTransaction = (): {| ChainDerivations.EXTERNAL, 1, ]), - amount: '4500000', + amount: '5000000', assets: [], }, { // 0'/0/0 // eslint-disable-next-line max-len - // addr1qyv7qlaucathxkwkc503ujw0rv9lfj2rkj96feyst2rs9ey4tr5knj4fu4adelzqhxg8adu5xca4jra0gtllfrpcawyqzajfkn + // addr1q9nv4vttp9f00pttk2unp4jhprd67sgffkg9ak0sawvxa68vfz8ymjd9j2vdea8088ut8jpx4c6tr08dwuzs07leyrtsuc6l06 address: - '0119e07fbcc7577359d6c51f1e49cf1b0bf4c943b48ba4e4905a8702e49558e969caa9e57adcfc40b9907eb794363b590faf42fff48c38eb88', - amount: '5500000', + '0166cab16b0952f7856bb2b930d65708dbaf41094d905ed9f0eb986ee8ec488e4dc9a59298dcf4ef39f8b3c826ae34b1bced770507fbf920d7', + amount: '1000000', + assets: [], + }, + { + // 0'/0/0 + // eslint-disable-next-line max-len + // addr1q9nv4vttp9f00pttk2unp4jhprd67sgffkg9ak0sawvxa68vfz8ymjd9j2vdea8088ut8jpx4c6tr08dwuzs07leyrtsuc6l06 + address: + '0166cab16b0952f7856bb2b930d65708dbaf41094d905ed9f0eb986ee8ec488e4dc9a59298dcf4ef39f8b3c826ae34b1bced770507fbf920d7', + amount: '1000000', assets: [], }, ], @@ -1482,11 +1506,11 @@ export const generateTransaction = (): {| }; // ===================== - // shelley-collateral + // shelley-simple-15 // ===================== - const shelleyCollateral = { - hash: '021657dfc7f9e33d0ca9cb33b0487138d2f74286e9e00f19946f27e9a8c6f607', + const shelleySimple15 = { + hash: '3677e75c7ba699bfdc6cd57d42f246f86f63aefd76025006ac78313fad2bba21', inputs: [ { // Ae2tdPwUPEZ2y4rAdJG2coM4MXeNNAAKDztXXztz8LrcYRZ8waYoa7pWXgj @@ -1500,7 +1524,7 @@ export const generateTransaction = (): {| txHash: distributorTx.hash, id: distributorTx.hash + '17', index: 17, - amount: '7000000', + amount: '10000000', assets: [], }, ], @@ -1514,25 +1538,16 @@ export const generateTransaction = (): {| ChainDerivations.EXTERNAL, 1, ]), - amount: '5000000', - assets: [], - }, - { - // 0'/0/0 - // eslint-disable-next-line max-len - // addr1q9nv4vttp9f00pttk2unp4jhprd67sgffkg9ak0sawvxa68vfz8ymjd9j2vdea8088ut8jpx4c6tr08dwuzs07leyrtsuc6l06 - address: - '0166cab16b0952f7856bb2b930d65708dbaf41094d905ed9f0eb986ee8ec488e4dc9a59298dcf4ef39f8b3c826ae34b1bced770507fbf920d7', - amount: '1000000', + amount: '4500000', assets: [], }, { // 0'/0/0 // eslint-disable-next-line max-len - // addr1q9nv4vttp9f00pttk2unp4jhprd67sgffkg9ak0sawvxa68vfz8ymjd9j2vdea8088ut8jpx4c6tr08dwuzs07leyrtsuc6l06 + // addr1qyv7qlaucathxkwkc503ujw0rv9lfj2rkj96feyst2rs9ey4tr5knj4fu4adelzqhxg8adu5xca4jra0gtllfrpcawyqzajfkn address: - '0166cab16b0952f7856bb2b930d65708dbaf41094d905ed9f0eb986ee8ec488e4dc9a59298dcf4ef39f8b3c826ae34b1bced770507fbf920d7', - amount: '1000000', + '0119e07fbcc7577359d6c51f1e49cf1b0bf4c943b48ba4e4905a8702e49558e969caa9e57adcfc40b9907eb794363b590faf42fff48c38eb88', + amount: '5500000', assets: [], }, ], @@ -2008,6 +2023,7 @@ const transactions: Array = []; const mockUtxoApi: MockUtxoApi = new MockUtxoApi(transactions, 1); export function addTransaction(tx: MockTx): void { + logger.info(`mockCardanoImporter: Adding the transaction\n${JSON.stringify(tx)}`); // need to insert txs in order they appear in the blockchain // note: pending transactions always go at the end if (tx.epoch == null || tx.slot == null || tx.tx_ordinal == null) { @@ -2039,6 +2055,7 @@ export function addTransaction(tx: MockTx): void { transactions.push(tx); return; } + logger.info(`mockCardanoImporter: Inserting the transaction\n${JSON.stringify(tx)} with slice`); transactions.splice(insertionIndex, 0, tx); } @@ -2114,6 +2131,7 @@ export function resetChain(chainToUse: $Values): void { const apiStatuses: Array = []; const setServerStatus = (serverStatus: ServerStatusResponse) => { + logger.info(`mockCardanoImporter: Set server status\n${JSON.stringify(serverStatus)}`); apiStatuses[0] = serverStatus; }; @@ -2149,6 +2167,7 @@ export function appMaintenanceFinish() { } function getApiStatus(): ServerStatusResponse { + logger.info(`mockCardanoImporter: Get api statuses\n${JSON.stringify(apiStatuses[0])}`); return apiStatuses[0]; } @@ -2165,6 +2184,7 @@ const utxoForAddresses: AddressUtxoFunc = genUtxoForAddresses( ); const utxoSumForAddresses: UtxoSumFunc = genUtxoSumForAddresses(utxoForAddresses); const sendTx = (request: SignedRequestInternal): SignedResponse => { + logger.info(`mockCardanoImporter: Send TX\n${JSON.stringify(request)}`); const remoteTx = toRemoteByronTx(transactions, request); addTransaction(remoteTx); @@ -2175,6 +2195,7 @@ const getPoolInfo: PoolInfoFunc = genGetPoolInfo(); const getRewardHistory: RewardHistoryFunc = async ( _body: RewardHistoryRequest ): Promise => { + logger.info(`mockCardanoImporter: Get reward history\n${JSON.stringify(_body)}`); return { e19558e969caa9e57adcfc40b9907eb794363b590faf42fff48c38eb88: [ { @@ -2208,6 +2229,7 @@ const getRewardHistory: RewardHistoryFunc = async ( }; const getAccountState: AccountStateFunc = async request => { + logger.info(`mockCardanoImporter: Get account state`); const totalRewards = new BigNumber(5000000); const totalWithdrawals = new BigNumber(0); @@ -2298,6 +2320,7 @@ const mockScriptOutputs = [ ]; const getUtxoData = (txHash: string, txIndex: number): UtxoData | null => { + logger.info(`mockCardanoImporter: Get UTXO data for \ntxHash: ${JSON.stringify(txHash)}, txIndex: ${JSON.stringify(txIndex)}`); const output = mockScriptOutputs.find( entry => entry.txHash === txHash && entry.txIndex === txIndex ); From e95923a51888ec92e6e46ead7f5b90db060e178f Mon Sep 17 00:00:00 2001 From: Denis Date: Wed, 14 Dec 2022 14:09:06 +0300 Subject: [PATCH 083/172] fixed collecting background logs --- .../features/step_definitions/common-steps.js | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/yoroi-extension/features/step_definitions/common-steps.js b/packages/yoroi-extension/features/step_definitions/common-steps.js index 63da93bad3..87f93b7d71 100644 --- a/packages/yoroi-extension/features/step_definitions/common-steps.js +++ b/packages/yoroi-extension/features/step_definitions/common-steps.js @@ -238,12 +238,12 @@ After(async function (scenario) { await getLogs(this.driver, 'failedStep', logging.Type.BROWSER); await getLogs(this.driver, 'failedStep', logging.Type.DRIVER); // getting logs from background - const currentTabName = this.windowManager.getCurrentWindowName(); + await this.windowManager.switchTo(extensionTabName); const backgroundPageUrl = `${this.getExtensionUrl()}/background.html`; - await this.windowManager.openNewWindow(backgroungTabName, backgroundPageUrl); + await this.windowManager.openNewTab(backgroungTabName, backgroundPageUrl); await this.windowManager.switchTo(backgroungTabName); await getLogs(this.driver, 'background', logging.Type.BROWSER); - await this.windowManager.switchTo(currentTabName); + await this.windowManager.switchTo(extensionTabName); } } await this.windowManager.switchTo(extensionTabName); From 395a9e95ceea79cbe26bec1de6c891358238f00e Mon Sep 17 00:00:00 2001 From: Denis Date: Wed, 14 Dec 2022 15:11:12 +0300 Subject: [PATCH 084/172] updated collecting background console.log --- .../features/step_definitions/common-steps.js | 5 ++--- .../features/step_definitions/connector-steps.js | 9 ++++++++- packages/yoroi-extension/features/support/webdriver.js | 4 ++++ 3 files changed, 14 insertions(+), 4 deletions(-) diff --git a/packages/yoroi-extension/features/step_definitions/common-steps.js b/packages/yoroi-extension/features/step_definitions/common-steps.js index 87f93b7d71..20a8fcb2d7 100644 --- a/packages/yoroi-extension/features/step_definitions/common-steps.js +++ b/packages/yoroi-extension/features/step_definitions/common-steps.js @@ -238,9 +238,6 @@ After(async function (scenario) { await getLogs(this.driver, 'failedStep', logging.Type.BROWSER); await getLogs(this.driver, 'failedStep', logging.Type.DRIVER); // getting logs from background - await this.windowManager.switchTo(extensionTabName); - const backgroundPageUrl = `${this.getExtensionUrl()}/background.html`; - await this.windowManager.openNewTab(backgroungTabName, backgroundPageUrl); await this.windowManager.switchTo(backgroungTabName); await getLogs(this.driver, 'background', logging.Type.BROWSER); await this.windowManager.switchTo(extensionTabName); @@ -524,6 +521,8 @@ async function acceptUriPrompt(world: any) { Given(/^I have opened the extension$/, async function () { this.webDriverLogger.info(`Step: I have opened the extension`); await this.get(this.getExtensionUrl()); + await this.windowManager.openNewTab(backgroungTabName, this.getBackgroundUrl()); + await this.windowManager.switchTo(extensionTabName); const browserName = await this.getBrowser(); if (browserName === 'firefox') { await this.driver.manage().window().maximize(); diff --git a/packages/yoroi-extension/features/step_definitions/connector-steps.js b/packages/yoroi-extension/features/step_definitions/connector-steps.js index 99ba33a453..bc7bc19f22 100644 --- a/packages/yoroi-extension/features/step_definitions/connector-steps.js +++ b/packages/yoroi-extension/features/step_definitions/connector-steps.js @@ -28,7 +28,12 @@ import { } from '../pages/connector-signingTxPage'; import { getSigningData, signMessageTitle } from '../pages/connector-signingDataPage'; import { addCollateralTitle } from '../pages/connector-getCollateralPage'; -import { mockDAppName, extensionTabName, popupConnectorName } from '../support/windowManager'; +import { + backgroungTabName, + mockDAppName, + extensionTabName, + popupConnectorName +} from '../support/windowManager'; import { connectorButton } from '../pages/sidebarPage'; const userRejectMsg = 'user reject'; @@ -45,6 +50,8 @@ const connectorPopUpIsDisplayed = async (customWorld: Object) => { Given(/^I have opened the mock dApp$/, async function () { this.webDriverLogger.info(`Step: I have opened the mock dApp`); await this.get(mockDAppUrl); + await this.windowManager.openNewTab(backgroungTabName, this.getBackgroundUrl()); + await this.windowManager.switchTo(mockDAppName); }); Then(/^I open the mock dApp tab$/, async function () { diff --git a/packages/yoroi-extension/features/support/webdriver.js b/packages/yoroi-extension/features/support/webdriver.js index 8f2272cc89..5c23a13e18 100644 --- a/packages/yoroi-extension/features/support/webdriver.js +++ b/packages/yoroi-extension/features/support/webdriver.js @@ -169,6 +169,10 @@ function CustomWorld(cmdInput: WorldInput) { return `moz-extension://${firefoxExtensionId}/main_window.html`; }; + this.getBackgroundUrl = (): string => { + return `${this.getExtensionUrl()}/background.html` + }; + this.get = async (url: string) => { for (let i = 0; i < 6; i++) { try { From 622de8b6aed7597b088f381abb4a46bb034e0bff Mon Sep 17 00:00:00 2001 From: Denis Date: Wed, 14 Dec 2022 23:13:56 +0300 Subject: [PATCH 085/172] added method getInfoFromIndexedDB --- .../features/support/webdriver.js | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/packages/yoroi-extension/features/support/webdriver.js b/packages/yoroi-extension/features/support/webdriver.js index 5c23a13e18..b242983082 100644 --- a/packages/yoroi-extension/features/support/webdriver.js +++ b/packages/yoroi-extension/features/support/webdriver.js @@ -416,6 +416,42 @@ function CustomWorld(cmdInput: WorldInput) { const element = await this.getElementBy(locator); await this.driver.executeScript('arguments[0].scrollIntoView();', element); }; + + this.getInfoFromIndexedDB = async (tableName: string) => { + await this.driver.executeScript(() => { + window.allDBsPromise = window.indexedDB.databases(); + }); + + const allDBs = await this.driver.executeAsyncScript((...args) => { + const callback = args[args.length - 1]; + window.allDBsPromise + .then(reponse => { + callback(reponse); + }) + .catch(error => { + callback(error); + }); + }); + const {name, version} = allDBs[0]; + + await this.driver.executeScript((dbName, dbVersion, table) => { + const request = window.indexedDB.open(dbName, dbVersion); + request.onsuccess = function (event) { + const db = event.target.result; + window.tableContent = db + .transaction(table, "readonly") + .objectStore(table) + .getAll(); + } + }, + name, + version, + tableName + ); + const tableContent = await this.driver.executeScript(() => window.tableContent.result); + + return tableContent; + }; } // no need to await From bf0a7cc339ea42654735bf1868cfe9508be4cb14 Mon Sep 17 00:00:00 2001 From: Denis Date: Wed, 14 Dec 2022 23:31:17 +0300 Subject: [PATCH 086/172] little fixes --- .../features/mock-chain/mockCardanoImporter.js | 1 - packages/yoroi-extension/features/mock-dApp-webpage/index.js | 4 ++-- .../features/step_definitions/connector-steps.js | 5 ----- 3 files changed, 2 insertions(+), 8 deletions(-) diff --git a/packages/yoroi-extension/features/mock-chain/mockCardanoImporter.js b/packages/yoroi-extension/features/mock-chain/mockCardanoImporter.js index 469a99c53f..9366546370 100644 --- a/packages/yoroi-extension/features/mock-chain/mockCardanoImporter.js +++ b/packages/yoroi-extension/features/mock-chain/mockCardanoImporter.js @@ -2048,7 +2048,6 @@ export function addTransaction(tx: MockTx): void { if (txOrdinal == null) return true; if (txOrdinal > newTxOrdinal) return true; if (txOrdinal < newTxOrdinal) return false; - console.log(`DEBUG::\nepoch -> ${epoch}\nslot -> ${slot}\ntxOrdinal -> ${txOrdinal}`); throw new Error(`Transaction ${tx.hash} occurs at same position as an existing transactions`); }); if (insertionIndex === -1) { diff --git a/packages/yoroi-extension/features/mock-dApp-webpage/index.js b/packages/yoroi-extension/features/mock-dApp-webpage/index.js index d48b3b6da8..d7ddf6adb1 100644 --- a/packages/yoroi-extension/features/mock-dApp-webpage/index.js +++ b/packages/yoroi-extension/features/mock-dApp-webpage/index.js @@ -522,14 +522,14 @@ export class MockDAppWebpage { throw new MockDAppWebpageError(collateralResponse.errMsg); } - addCollateral(amount: string) { + async addCollateral(amount: string) { this.logger.info(`MockDApp: Requesting collateral: data="${amount}"`); const amountHex = Buffer.from( CardanoWasm.Value.new(CardanoWasm.BigNum.from_str(amount)).to_bytes() ).toString('hex'); const scriptString = `window.collateralPromise = window.api.getCollateral(${JSON.stringify(amountHex)});`; - this.driver.executeScript(scriptString); + await this.driver.executeScript(scriptString); } async getCollateralResult(): Promise { diff --git a/packages/yoroi-extension/features/step_definitions/connector-steps.js b/packages/yoroi-extension/features/step_definitions/connector-steps.js index bc7bc19f22..b4761264a0 100644 --- a/packages/yoroi-extension/features/step_definitions/connector-steps.js +++ b/packages/yoroi-extension/features/step_definitions/connector-steps.js @@ -386,11 +386,6 @@ When(/^I ask to get Collateral for (.+) ADA$/, async function (amount) { this.webDriverLogger.info(`Step: I ask to get Collateral for ${amount} ADA`); const amountString = (parseFloat(amount) * 1000000).toString(); await this.mockDAppPage.addCollateral(amountString); - const newWindow = this.windowManager.findNewWindows(20); - if (newWindow.length == 0) { - this.webDriverLogger.info(`Step: -> Asking again for collateral`); - this.mockDAppPage.addCollateral(amountString); - } }); Then(/^The dApp should see collateral: (.+) for (.+)$/, async function (expectedCollateral, utxosAmount) { From 5fd3977c13410df5548f159260115eb59b63ad8e Mon Sep 17 00:00:00 2001 From: Ahmed Ibrahim Date: Thu, 15 Dec 2022 13:55:22 +0200 Subject: [PATCH 087/172] Disable future dates & reset state when the dialog closes --- .../app/components/wallet/export/DateRange.js | 12 +++++------- .../wallet/export/ExportTransactionDialog.js | 15 ++++++++++++++- 2 files changed, 19 insertions(+), 8 deletions(-) diff --git a/packages/yoroi-extension/app/components/wallet/export/DateRange.js b/packages/yoroi-extension/app/components/wallet/export/DateRange.js index 4f2677b3f7..6f95fea954 100644 --- a/packages/yoroi-extension/app/components/wallet/export/DateRange.js +++ b/packages/yoroi-extension/app/components/wallet/export/DateRange.js @@ -6,7 +6,7 @@ import { AdapterDayjs } from '@mui/x-date-pickers/AdapterDayjs'; import { LocalizationProvider } from '@mui/x-date-pickers/LocalizationProvider'; import { DatePicker } from '@mui/x-date-pickers/DatePicker'; import { observer } from 'mobx-react'; -import { Dayjs } from 'dayjs' +import dayjs, { Dayjs } from 'dayjs' import { defineMessages, intlShape } from 'react-intl'; import type { $npm$ReactIntl$IntlFormat } from 'react-intl'; @@ -44,21 +44,19 @@ export default class ExportTransactionDialog extends Component { render(): Node { const { intl } = this.context; const { date, setStartDate, setEndDate } = this.props; - const invalidInterval = ( - date.startDate && date.endDate && date.startDate.isAfter(date.endDate) - ); + return ( { setStartDate(newDate); }} renderInput={(params) => ( )} @@ -66,14 +64,14 @@ export default class ExportTransactionDialog extends Component { { setEndDate(newDate); }} renderInput={(params) => ( )} diff --git a/packages/yoroi-extension/app/components/wallet/export/ExportTransactionDialog.js b/packages/yoroi-extension/app/components/wallet/export/ExportTransactionDialog.js index 1e483d4cbd..bed62f34c7 100644 --- a/packages/yoroi-extension/app/components/wallet/export/ExportTransactionDialog.js +++ b/packages/yoroi-extension/app/components/wallet/export/ExportTransactionDialog.js @@ -56,6 +56,15 @@ export default class ExportTransactionDialog extends Component { endDate: null, } + componentWillUnmount() { + const { + toggleIncludeTxIds, + shouldIncludeTxIds + } = this.props; + // Reset `includeTxIds` state + if (shouldIncludeTxIds) toggleIncludeTxIds() + } + render(): Node { const { intl } = this.context; const { @@ -86,7 +95,11 @@ export default class ExportTransactionDialog extends Component { label: intl.formatMessage(globalMessages.exportButtonLabel), primary: true, isSubmitting: isActionProcessing || false, - disabled: !startDate || !endDate || startDate.isAfter(endDate), + disabled: ( + !startDate || !endDate || + startDate.isAfter(endDate) || + !startDate.isValid() || !endDate.isValid() + ), onClick: () => submit({ startDate, endDate }), }]; From b3b85d9d0049963019da092e1594a1751a4189a8 Mon Sep 17 00:00:00 2001 From: Ahmed Ibrahim Date: Sun, 18 Dec 2022 13:25:51 +0200 Subject: [PATCH 088/172] Use Moment instead of DayJS for locals support --- .../actions/common/transactions-actions.js | 6 +- .../app/components/wallet/export/DateRange.js | 76 ++++++++++--------- .../wallet/export/ExportTransactionDialog.js | 7 +- .../app/stores/toplevel/TransactionsStore.js | 8 +- packages/yoroi-extension/package-lock.json | 5 -- packages/yoroi-extension/package.json | 1 - 6 files changed, 49 insertions(+), 54 deletions(-) diff --git a/packages/yoroi-extension/app/actions/common/transactions-actions.js b/packages/yoroi-extension/app/actions/common/transactions-actions.js index 63669cef54..9a0a095c03 100644 --- a/packages/yoroi-extension/app/actions/common/transactions-actions.js +++ b/packages/yoroi-extension/app/actions/common/transactions-actions.js @@ -1,13 +1,13 @@ // @flow import { AsyncAction, Action } from '../lib/Action'; import { PublicDeriver } from '../../api/ada/lib/storage/models/PublicDeriver/index'; -import { Dayjs } from 'dayjs'; +import { Moment } from 'moment' // ======= TRANSACTIONS ACTIONS ======= export type TransactionRowsToExportRequest = {| - startDate: typeof Dayjs, - endDate: typeof Dayjs, + startDate: typeof Moment, + endDate: typeof Moment, |}; export default class TransactionsActions { diff --git a/packages/yoroi-extension/app/components/wallet/export/DateRange.js b/packages/yoroi-extension/app/components/wallet/export/DateRange.js index 6f95fea954..d8a2020566 100644 --- a/packages/yoroi-extension/app/components/wallet/export/DateRange.js +++ b/packages/yoroi-extension/app/components/wallet/export/DateRange.js @@ -2,13 +2,13 @@ import { Component } from 'react' import type { Node } from 'react' import TextField from '@mui/material/TextField'; -import { AdapterDayjs } from '@mui/x-date-pickers/AdapterDayjs'; +import { AdapterMoment } from '@mui/x-date-pickers/AdapterMoment'; import { LocalizationProvider } from '@mui/x-date-pickers/LocalizationProvider'; import { DatePicker } from '@mui/x-date-pickers/DatePicker'; import { observer } from 'mobx-react'; -import dayjs, { Dayjs } from 'dayjs' import { defineMessages, intlShape } from 'react-intl'; import type { $npm$ReactIntl$IntlFormat } from 'react-intl'; +import moment from 'moment'; const messages = defineMessages({ startDate: { @@ -27,11 +27,11 @@ const messages = defineMessages({ type Props = {| date: {| - startDate: typeof Dayjs | null, - endDate: typeof Dayjs | null, + startDate: Date | null, + endDate: Date | null, |}, - setStartDate(typeof Dayjs | null): void, - setEndDate(typeof Dayjs | null): void + setStartDate(Date | null): void, + setEndDate(Date| null): void |} @observer @@ -45,37 +45,41 @@ export default class ExportTransactionDialog extends Component { const { intl } = this.context; const { date, setStartDate, setEndDate } = this.props; + const dates = [ + { + id: 1, + label: messages.startDate, + value: date.startDate, + setDateHandler: setStartDate, + minDate: undefined, + }, + { + id: 2, + label: messages.endDate, + value: date.endDate, + setDateHandler: setEndDate, + minDate: date.startDate !== null ? date.startDate : undefined, + }, + ] + return ( - - { - setStartDate(newDate); - }} - renderInput={(params) => ( - - )} - /> - { - setEndDate(newDate); - }} - renderInput={(params) => ( - - )} - /> + + {dates.map(({ id, label, value, setDateHandler, minDate }) => ( + ( + + )} + /> + ))} ) } diff --git a/packages/yoroi-extension/app/components/wallet/export/ExportTransactionDialog.js b/packages/yoroi-extension/app/components/wallet/export/ExportTransactionDialog.js index bed62f34c7..76aaa07d22 100644 --- a/packages/yoroi-extension/app/components/wallet/export/ExportTransactionDialog.js +++ b/packages/yoroi-extension/app/components/wallet/export/ExportTransactionDialog.js @@ -13,7 +13,7 @@ import globalMessages from '../../../i18n/global-messages'; import CheckboxLabel from '../../common/CheckboxLabel'; import DateRange from './DateRange' import { Box } from '@mui/system'; -import { Dayjs } from 'dayjs'; +import { Moment } from 'moment' const messages = defineMessages({ dialogTitle: { @@ -40,8 +40,8 @@ type Props = {| |}; type State = {| - startDate: typeof Dayjs | null, - endDate: typeof Dayjs | null, + startDate: typeof Moment | null, + endDate: typeof Moment | null, |} @observer @@ -76,6 +76,7 @@ export default class ExportTransactionDialog extends Component { shouldIncludeTxIds } = this.props; const { startDate, endDate } = this.state; + console.log({startDate}) const infoBlock = ( , @@ -764,9 +761,8 @@ export default class TransactionsStore extends Store { const { startDate, endDate } = request.exportRequest; respTxRows = respTxRows.filter(row => { - const txDate = dayjs(row.date) // 4th param `[]` means that the start and end date are included - return txDate.isBetween(startDate, endDate, 'day', '[]') + return moment(row.date).isBetween(startDate, endDate, 'day', '[]') }).sort((a, b) => b.date - a.date); if (respTxRows.length < 1) { diff --git a/packages/yoroi-extension/package-lock.json b/packages/yoroi-extension/package-lock.json index 4755845eb7..354d73d889 100644 --- a/packages/yoroi-extension/package-lock.json +++ b/packages/yoroi-extension/package-lock.json @@ -12694,11 +12694,6 @@ } } }, - "dayjs": { - "version": "1.11.6", - "resolved": "https://registry.npmjs.org/dayjs/-/dayjs-1.11.6.tgz", - "integrity": "sha512-zZbY5giJAinCG+7AGaw0wIhNZ6J8AhWuSXKvuc1KAyMiRsvGQWqh4L+MomvhdAYjN+lqvVCMq1I41e3YHvXkyQ==" - }, "debug": { "version": "4.3.2", "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.2.tgz", diff --git a/packages/yoroi-extension/package.json b/packages/yoroi-extension/package.json index 9536e44e30..6891307c50 100644 --- a/packages/yoroi-extension/package.json +++ b/packages/yoroi-extension/package.json @@ -205,7 +205,6 @@ "classnames": "2.2.6", "crypto-browserify": "3.12.0", "crypto-random-string": "3.3.1", - "dayjs": "^1.11.6", "downshift": "^6.1.7", "dropbox": "4.0.30", "ergo-lib-wasm-browser": "^0.14.0", From 5168a83957df2d488c7841a6725163374abcd61f Mon Sep 17 00:00:00 2001 From: Ahmed Ibrahim Date: Tue, 27 Dec 2022 14:18:38 +0200 Subject: [PATCH 089/172] Set default wallet for the revamp --- .../wallet/transactions/TransactionRevamp.js | 2 +- .../app/containers/wallet/MyWalletsPage.js | 3 -- .../app/containers/wallet/Wallet.js | 27 +++++++--- .../app/stores/stateless/sidebarCategories.js | 3 +- packages/yoroi-extension/package-lock.json | 50 +++++++++---------- 5 files changed, 47 insertions(+), 38 deletions(-) diff --git a/packages/yoroi-extension/app/components/wallet/transactions/TransactionRevamp.js b/packages/yoroi-extension/app/components/wallet/transactions/TransactionRevamp.js index 0cc8fcd40e..a7fefda7a9 100644 --- a/packages/yoroi-extension/app/components/wallet/transactions/TransactionRevamp.js +++ b/packages/yoroi-extension/app/components/wallet/transactions/TransactionRevamp.js @@ -471,7 +471,7 @@ export default class TransactionRevamp extends Component { {this.generateAddressButton(request.address.address)} - + {renderAmount(request.address.value.getDefaultEntry())} {request.address.value.nonDefaultEntries().map(entry => ( diff --git a/packages/yoroi-extension/app/containers/wallet/MyWalletsPage.js b/packages/yoroi-extension/app/containers/wallet/MyWalletsPage.js index cab2a26524..3a3000f052 100644 --- a/packages/yoroi-extension/app/containers/wallet/MyWalletsPage.js +++ b/packages/yoroi-extension/app/containers/wallet/MyWalletsPage.js @@ -105,13 +105,10 @@ class MyWalletsPage extends Component { const { uiDialogs } = stores; const sidebarContainer = - const wallets = this.generated.stores.wallets.publicDerivers; - const navbarTitle = ( ); - const navbarElementClassic = ( { }; componentDidMount() { + + const publicDeriver = this.generated.stores.wallets.selected; + const publicDerivers = this.generated.stores.wallets.publicDerivers; + const isRevamp = this.generated.stores.profile.currentTheme === THEMES.YOROI_REVAMP + + if (publicDeriver == null && isRevamp) { + this.generated.actions.wallets.setActiveWallet.trigger({ wallet: publicDerivers[0] }) + } + // reroute to the default path for the wallet const newRoute = this.checkRoute(); if (newRoute != null) { @@ -66,16 +75,14 @@ class Wallet extends Component { } checkRoute(): void | string { - let categories; - if (this.generated.stores.profile.currentTheme === THEMES.YOROI_REVAMP) { - categories = allCategories.filter(c => c.route !== ROUTES.WALLETS.DELEGATION_DASHBOARD); - } else { - categories = allCategories; - } + const isRevamp = this.generated.stores.profile.currentTheme === THEMES.YOROI_REVAMP + const categories = isRevamp ? + allCategories.filter(c => c.route !== ROUTES.WALLETS.DELEGATION_DASHBOARD) + : allCategories; + // void -> this route is fine for this wallet type // string -> what you should be redirected to const publicDeriver = this.generated.stores.wallets.selected; - if (publicDeriver == null) throw new Error(`${nameof(Wallet)} no public deriver`); const spendableBalance = this.generated.stores.transactions.getBalanceRequest.result; const walletHasAssets = !!(spendableBalance?.nonDefaultEntries().length); @@ -291,7 +298,8 @@ class Wallet extends Component { }, wallets: { selected: stores.wallets.selected, - firstSync: stores.wallets.firstSync + publicDerivers: stores.wallets.publicDerivers, + firstSync: stores.wallets.firstSync, }, walletSettings: { getWalletWarnings: settingStore.getWalletWarnings, @@ -320,6 +328,9 @@ class Wallet extends Component { goToRoute: { trigger: actions.router.goToRoute.trigger }, redirect: { trigger: actions.router.redirect.trigger }, }, + wallets: { + setActiveWallet: { trigger: actions.wallets.setActiveWallet.trigger }, + } }, SidebarContainerProps: ({ actions, stores }: InjectedOrGenerated), NavBarContainerProps: ({ actions, stores }: InjectedOrGenerated), diff --git a/packages/yoroi-extension/app/stores/stateless/sidebarCategories.js b/packages/yoroi-extension/app/stores/stateless/sidebarCategories.js index e4052fd464..e242ff37bf 100644 --- a/packages/yoroi-extension/app/stores/stateless/sidebarCategories.js +++ b/packages/yoroi-extension/app/stores/stateless/sidebarCategories.js @@ -50,6 +50,7 @@ export const MY_WALLETS: SidebarCategory = registerCategory({ request.selected == null && matchRoute(ROUTES.WALLETS.ADD, request.currentRoute) === false, }); + export const WALLETS_ROOT: SidebarCategory = registerCategory({ className: 'wallets', route: ROUTES.WALLETS.ROOT, @@ -125,7 +126,7 @@ export type SidebarCategoryRevamp = {| export const allCategoriesRevamp: Array = [ { className: 'wallets', - route: ROUTES.MY_WALLETS, + route: ROUTES.WALLETS.ROOT, icon: walletIcon, label: globalMessages.walletLabel, isVisible: _request => true, diff --git a/packages/yoroi-extension/package-lock.json b/packages/yoroi-extension/package-lock.json index 8a73689c44..008f86da4d 100644 --- a/packages/yoroi-extension/package-lock.json +++ b/packages/yoroi-extension/package-lock.json @@ -8599,7 +8599,7 @@ "any-promise": { "version": "1.3.0", "resolved": "https://registry.npmjs.org/any-promise/-/any-promise-1.3.0.tgz", - "integrity": "sha512-7UvmKalWRt1wgjL1RrGxoSJW/0QZFIegpeGvZG9kjp8vrRu55XTHbwnqq2GpXm9uLbcuhxm3IqX9OB4MZR1b2A==", + "integrity": "sha1-q8av7tzqUugJzcA3au0845Y10X8=", "dev": true }, "anymatch": { @@ -9761,7 +9761,7 @@ "becke-ch--regex--s0-0-v1--base--pl--lib": { "version": "1.4.0", "resolved": "https://registry.npmjs.org/becke-ch--regex--s0-0-v1--base--pl--lib/-/becke-ch--regex--s0-0-v1--base--pl--lib-1.4.0.tgz", - "integrity": "sha512-FnWonOyaw7Vivg5nIkrUll9HSS5TjFbyuURAiDssuL6VxrBe3ERzudRxOcWRhZYlP89UArMDikz7SapRPQpmZQ==", + "integrity": "sha1-Qpzuu/pffpNueNc/vcfacWKyDiA=", "dev": true }, "before-after-hook": { @@ -12348,25 +12348,25 @@ "escape-string-regexp": { "version": "1.0.5", "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", - "integrity": "sha512-vbRorB5FUQWvla16U8R/qgaFIya2qGzwDrNmCZuYKrbdSUMG6I1ZCGQRefkRVhuOkIGVne7BQ35DSfo1qvJqFg==", + "integrity": "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=", "dev": true }, "indent-string": { "version": "3.2.0", "resolved": "https://registry.npmjs.org/indent-string/-/indent-string-3.2.0.tgz", - "integrity": "sha512-BYqTHXTGUIvg7t1r4sJNKcbDZkL92nkXA8YtRpbjFHRHGDL/NtUeiBJMeE60kIFN/Mg8ESaWQvftaYMGJzQZCQ==", + "integrity": "sha1-Sl/W0nzDMvN+VBmlBNu4NxBckok=", "dev": true }, "is-fullwidth-code-point": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-2.0.0.tgz", - "integrity": "sha512-VHskAKYM8RfSFXwee5t5cbN5PZeq1Wrh6qd5bkyiXIf6UQcN6w/A0eXM9r6t8d+GYOh+o6ZhiEnb88LN/Y8m2w==", + "integrity": "sha1-o7MKXE8ZkYMWeqq5O+764937ZU8=", "dev": true }, "path-key": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/path-key/-/path-key-2.0.1.tgz", - "integrity": "sha512-fEHGKCSmUSDPv4uoj8AlD+joPlq3peND+HRYyxFz4KPw4z926S/b8rIuFs2FYJg3BwsxJf6A9/3eIdLaYC+9Dw==", + "integrity": "sha1-QRyttXTFoUDTpLGRDUDYDMn0C0A=", "dev": true }, "semver": { @@ -12378,7 +12378,7 @@ "shebang-command": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-1.2.0.tgz", - "integrity": "sha512-EV3L1+UQWGor21OmnvojK36mhg+TyIKDh3iFBKBohr5xeXIhNBcx8oWdgkTEEQ+BEFFYdLRuqMfd5L84N1V5Vg==", + "integrity": "sha1-RKrGW2lbAzmJaMOfNj/uXer98eo=", "dev": true, "requires": { "shebang-regex": "^1.0.0" @@ -12387,7 +12387,7 @@ "shebang-regex": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-1.0.0.tgz", - "integrity": "sha512-wpoSFAxys6b2a2wHZ1XpDSgD7N9iVjg29Ph9uV/uaP9Ex/KXlkTZTeddxDPSYQpgvzKLGJke2UU0AzoGCjNIvQ==", + "integrity": "sha1-2kL0l0DAtC2yypcoVxyxkMmO/qM=", "dev": true }, "string-width": { @@ -12403,7 +12403,7 @@ "strip-ansi": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-4.0.0.tgz", - "integrity": "sha512-4XaJ2zQdCzROZDivEVIDPkcQn8LMFSa8kj8Gxb/Lnwzv9A8VctNZ+lfivC/sV3ivW8ElJTERXZoPBRrZKkNKow==", + "integrity": "sha1-qEeQIusaw2iocTibY1JixQXuNo8=", "dev": true, "requires": { "ansi-regex": "^3.0.0" @@ -12498,7 +12498,7 @@ "cucumber-tag-expressions": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/cucumber-tag-expressions/-/cucumber-tag-expressions-1.1.1.tgz", - "integrity": "sha512-V9jv81sR/HaJ87FoidrvHkviXId7KmBcUi7aQPfi+W3nRO30N6GqH6lcp8K+nyiT1DgemRJBPDDeBMS93xJqMQ==", + "integrity": "sha1-f1x7cACbwrZmWRv+ZIVFeL7e6Fo=", "dev": true }, "currently-unhandled": { @@ -13565,7 +13565,7 @@ "es6-iterator": { "version": "2.0.3", "resolved": "https://registry.npmjs.org/es6-iterator/-/es6-iterator-2.0.3.tgz", - "integrity": "sha512-zw4SRzoUkd+cl+ZoE15A9o1oQd920Bb0iOJMQkQhl3jNc03YqVjAhG7scf9C5KWRU/R13Orf588uCC6525o02g==", + "integrity": "sha1-p96IkUGgWpSwhUQDstCg+/qY87c=", "dev": true, "requires": { "d": "1", @@ -14796,7 +14796,7 @@ "figures": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/figures/-/figures-2.0.0.tgz", - "integrity": "sha512-Oa2M9atig69ZkfwiApY8F2Yy+tzMbazyvqv21R0NsSC8floSOC09BbT1ITWAdoMGQvJ/aZnR1KMwdx9tvHnTNA==", + "integrity": "sha1-OrGi0qYsi/tDGgyUy3l6L84nyWI=", "dev": true, "requires": { "escape-string-regexp": "^1.0.5" @@ -14805,7 +14805,7 @@ "escape-string-regexp": { "version": "1.0.5", "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", - "integrity": "sha512-vbRorB5FUQWvla16U8R/qgaFIya2qGzwDrNmCZuYKrbdSUMG6I1ZCGQRefkRVhuOkIGVne7BQ35DSfo1qvJqFg==", + "integrity": "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=", "dev": true } } @@ -16051,7 +16051,7 @@ "gherkin": { "version": "5.1.0", "resolved": "https://registry.npmjs.org/gherkin/-/gherkin-5.1.0.tgz", - "integrity": "sha512-axTCsxH0m0cixijLvo7s9591h5pMb8ifQxFDun5FnfFhVsUhxgdnH0H7TSK7q8I4ASUU18DJ/tmlnMegMuLUUQ==", + "integrity": "sha1-aEu7A63STq9731RPWAM+so+zxtU=", "dev": true }, "glob": { @@ -16764,7 +16764,7 @@ "httpolyglot": { "version": "0.1.2", "resolved": "https://registry.npmjs.org/httpolyglot/-/httpolyglot-0.1.2.tgz", - "integrity": "sha512-ouHI1AaQMLgn4L224527S5+vq6hgvqPteurVfbm7ChViM3He2Wa8KP1Ny7pTYd7QKnDSPKcN8JYfC8r/lmsE3A==", + "integrity": "sha1-5NNH/omEpi9GfUBg31J/GFH2mXs=", "dev": true }, "https-browserify": { @@ -17256,7 +17256,7 @@ "is-generator": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/is-generator/-/is-generator-1.0.3.tgz", - "integrity": "sha512-G56jBpbJeg7ds83HW1LuShNs8J73Fv3CPz/bmROHOHlnKkN8sWb9ujiagjmxxMUywftgq48HlBZELKKqFLk0oA==", + "integrity": "sha1-wUwhBX7TbjKNuANHlmxpP4hjifM=", "dev": true }, "is-generator-fn": { @@ -19707,7 +19707,7 @@ "knuth-shuffle-seeded": { "version": "1.0.6", "resolved": "https://registry.npmjs.org/knuth-shuffle-seeded/-/knuth-shuffle-seeded-1.0.6.tgz", - "integrity": "sha512-9pFH0SplrfyKyojCLxZfMcvkhf5hH0d+UwR9nTVJ/DDQJGuzcXjTwB7TP7sDfehSudlGGaOLblmEWqv04ERVWg==", + "integrity": "sha1-AfG2VzOqdUDuCNiwF0Fk0iCB5OE=", "dev": true, "requires": { "seed-random": "~2.2.0" @@ -19955,7 +19955,7 @@ "lodash.omit": { "version": "4.5.0", "resolved": "https://registry.npmjs.org/lodash.omit/-/lodash.omit-4.5.0.tgz", - "integrity": "sha512-XeqSp49hNGmlkj2EJlfrQFIzQ6lXdNro9sddtQzcJY8QaoC2GO0DT7xaIokHeyM+mIT0mPMlPvkYzg2xCuHdZg==", + "integrity": "sha1-brGa5aHuHdnfC5aeZs4Lf6MLXmA=", "dev": true }, "lodash.set": { @@ -22177,7 +22177,7 @@ "pad-right": { "version": "0.2.2", "resolved": "https://registry.npmjs.org/pad-right/-/pad-right-0.2.2.tgz", - "integrity": "sha512-4cy8M95ioIGolCoMmm2cMntGR1lPLEbOMzOKu8bzjuJP6JpzEMQcDHmh7hHLYGgob+nKe1YHFMaG4V59HQa89g==", + "integrity": "sha1-b7ySQEXSRPKiokRQMGDTv8YAl3Q=", "dev": true, "requires": { "repeat-string": "^1.5.2" @@ -25128,7 +25128,7 @@ "seed-random": { "version": "2.2.0", "resolved": "https://registry.npmjs.org/seed-random/-/seed-random-2.2.0.tgz", - "integrity": "sha512-34EQV6AAHQGhoc0tn/96a9Fsi6v2xdqe/dMUwljGRaFOzR3EgRmECvD0O8vi8X+/uQ50LGHfkNu/Eue5TPKZkQ==", + "integrity": "sha1-KpsZ4lCoFwmSMaW5mk2vgLf77VQ=", "dev": true }, "selenium-webdriver": { @@ -26736,7 +26736,7 @@ "thenify-all": { "version": "1.6.0", "resolved": "https://registry.npmjs.org/thenify-all/-/thenify-all-1.6.0.tgz", - "integrity": "sha512-RNxQH/qI8/t3thXJDwcstUO4zeqo64+Uy/+sNVRBx4Xn2OX+OZ9oP+iJnNFqplFra2ZUVeKCSa2oVWi3T4uVmA==", + "integrity": "sha1-GhkY1ALY/D+Y+/I02wvMjMEOlyY=", "dev": true, "requires": { "thenify": ">= 3.1.0 < 4" @@ -26853,7 +26853,7 @@ "title-case": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/title-case/-/title-case-2.1.1.tgz", - "integrity": "sha512-EkJoZ2O3zdCz3zJsYCsxyq2OC5hrxR9mfdd5I+w8h/tmFfeOxJ+vvkxsKxdmN0WtS9zLdHEgfgVOiMVgv+Po4Q==", + "integrity": "sha1-PhJyFtpY0rxb7PE3q5Ha46fNj6o=", "dev": true, "requires": { "no-case": "^2.2.0", @@ -26863,7 +26863,7 @@ "lower-case": { "version": "1.1.4", "resolved": "https://registry.npmjs.org/lower-case/-/lower-case-1.1.4.tgz", - "integrity": "sha512-2Fgx1Ycm599x+WGpIYwJOvsjmXFzTSc34IwDWALRA/8AopUKAVPwfJ+h5+f85BCp0PWmmJcWzEpxOpoXycMpdA==", + "integrity": "sha1-miyr0bno4K6ZOkv31YdcOcQujqw=", "dev": true }, "no-case": { @@ -27621,7 +27621,7 @@ "upper-case": { "version": "1.1.3", "resolved": "https://registry.npmjs.org/upper-case/-/upper-case-1.1.3.tgz", - "integrity": "sha512-WRbjgmYzgXkCV7zNVpy5YgrHgbBv126rMALQQMrmzOVC4GM2waQ9x7xtm8VU+1yF2kWyPzI9zbZ48n4vSxwfSA==", + "integrity": "sha1-9rRQHC7EzdJrp4vnIilh3ndiFZg=", "dev": true }, "uri-js": { @@ -27756,7 +27756,7 @@ "util-arity": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/util-arity/-/util-arity-1.1.0.tgz", - "integrity": "sha512-kkyIsXKwemfSy8ZEoaIz06ApApnWsk5hQO0vLjZS6UkBiGiW++Jsyb8vSBoc0WKlffGoGs5yYy/j5pp8zckrFA==", + "integrity": "sha1-WdAa8f2z/t4KxOYysKtfbOl8kzA=", "dev": true }, "util-deprecate": { From 5c2d1d2c366525a3cf3e758873451aec03912eb1 Mon Sep 17 00:00:00 2001 From: Ahmed Ibrahim Date: Tue, 27 Dec 2022 15:32:56 +0200 Subject: [PATCH 090/172] Switch to first wallet when switching to the revamp from settings --- .../general-setting/ThemeSettingsBlock.js | 9 +++-- .../categories/GeneralSettingsPage.js | 36 +++++++++---------- .../app/containers/wallet/Wallet.js | 4 +-- 3 files changed, 23 insertions(+), 26 deletions(-) diff --git a/packages/yoroi-extension/app/components/settings/categories/general-setting/ThemeSettingsBlock.js b/packages/yoroi-extension/app/components/settings/categories/general-setting/ThemeSettingsBlock.js index a731289b31..f34bd334cf 100644 --- a/packages/yoroi-extension/app/components/settings/categories/general-setting/ThemeSettingsBlock.js +++ b/packages/yoroi-extension/app/components/settings/categories/general-setting/ThemeSettingsBlock.js @@ -73,9 +73,8 @@ const messages = defineMessages({ type Props = {| +currentTheme: Theme, - +selectTheme: ({| theme: string |}) => PossiblyAsync, + +onSubmit: (theme: string) => PossiblyAsync, +onExternalLinkClick: MouseEvent => void, - +switchToFirstWallet: void => void, |}; const NEW_THEME = THEMES.YOROI_REVAMP @@ -89,7 +88,7 @@ export default class ThemeSettingsBlock extends Component { render(): Node { const { currentTheme, - selectTheme, + onSubmit, onExternalLinkClick, } = this.props; const { intl } = this.context; @@ -121,7 +120,7 @@ export default class ThemeSettingsBlock extends Component { value={currentTheme === NEW_THEME ? NEW_THEME : OLD_THEME} onChange={(e) => { const theme = e.target.value === NEW_THEME ? NEW_THEME : THEMES.YOROI_MODERN - selectTheme({ theme }) + onSubmit(theme) }} sx={{ display: 'flex', @@ -177,7 +176,7 @@ export default class ThemeSettingsBlock extends Component { row value={currentTheme} onChange={(e) => { - selectTheme({ theme: e.target.value }) + onSubmit(e.target.value) }} > diff --git a/packages/yoroi-extension/app/containers/settings/categories/GeneralSettingsPage.js b/packages/yoroi-extension/app/containers/settings/categories/GeneralSettingsPage.js index 266bdf8b7c..a0a6b0a8b3 100644 --- a/packages/yoroi-extension/app/containers/settings/categories/GeneralSettingsPage.js +++ b/packages/yoroi-extension/app/containers/settings/categories/GeneralSettingsPage.js @@ -12,7 +12,7 @@ import AboutYoroiSettingsBlock from '../../../components/settings/categories/gen import UnitOfAccountSettings from '../../../components/settings/categories/general-setting/UnitOfAccountSettings'; import LocalizableError from '../../../i18n/LocalizableError'; import type { LanguageType } from '../../../i18n/translations'; -import type { Theme } from '../../../styles/utils'; +import { Theme, THEMES } from '../../../styles/utils'; import { PublicDeriver } from '../../../api/ada/lib/storage/models/PublicDeriver'; import { ReactComponent as AdaCurrency } from '../../../assets/images/currencies/ADA.inline.svg'; import { unitOfAccountDisabledValue } from '../../../types/unitOfAccountType'; @@ -64,22 +64,6 @@ export default class GeneralSettingsPage extends Component) => void = publicDeriver => { - this.generated.actions.router.goToRoute.trigger({ - route: this.generated.stores.app.currentRoute, - publicDeriver, - }); - }; - - handleSwitchToFirstWallet: void => void = () => { - const selectedWallet = this.generated.stores.wallets.selected; - if (selectedWallet == null) { - const wallets = this.generated.stores.wallets.publicDerivers; - const firstWallet = wallets[0]; - this.switchWallet(firstWallet); - } - }; - onSelectUnitOfAccount: string => Promise = async (value) => { const unitOfAccount = (value === 'ADA') ? unitOfAccountDisabledValue @@ -143,8 +127,19 @@ export default class GeneralSettingsPage extends Component { + if (theme === THEMES.YOROI_REVAMP) { + const publicDeriver = this.generated.stores.wallets.selected; + const publicDerivers = this.generated.stores.wallets.publicDerivers; + + if (publicDeriver == null && publicDerivers.length !== 0) { + this.generated.actions.wallets.setActiveWallet.trigger({ + wallet: publicDerivers[0], + }); + } + } + this.generated.actions.profile.updateTheme.trigger({ theme }) + }} onExternalLinkClick={handleExternalLinkClick} /> { }; componentDidMount() { - const publicDeriver = this.generated.stores.wallets.selected; const publicDerivers = this.generated.stores.wallets.publicDerivers; const isRevamp = this.generated.stores.profile.currentTheme === THEMES.YOROI_REVAMP - if (publicDeriver == null && isRevamp) { + if (publicDeriver == null && isRevamp && publicDerivers.length !== 0) { this.generated.actions.wallets.setActiveWallet.trigger({ wallet: publicDerivers[0] }) } @@ -83,6 +82,7 @@ class Wallet extends Component { // void -> this route is fine for this wallet type // string -> what you should be redirected to const publicDeriver = this.generated.stores.wallets.selected; + if (publicDeriver == null && !isRevamp) throw new Error(`${nameof(Wallet)} no public deriver`); const spendableBalance = this.generated.stores.transactions.getBalanceRequest.result; const walletHasAssets = !!(spendableBalance?.nonDefaultEntries().length); From 9c9d03c75dc4b37098cf3d2468e124fad054e001 Mon Sep 17 00:00:00 2001 From: Ahmed Ibrahim Date: Tue, 27 Dec 2022 15:39:14 +0200 Subject: [PATCH 091/172] Remove MUI disableUnderline error from the console --- packages/yoroi-extension/app/components/common/TextField.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/yoroi-extension/app/components/common/TextField.js b/packages/yoroi-extension/app/components/common/TextField.js index 7900d6a2b4..2456380262 100644 --- a/packages/yoroi-extension/app/components/common/TextField.js +++ b/packages/yoroi-extension/app/components/common/TextField.js @@ -76,6 +76,7 @@ function TextField({ theme.name === 'classic' ? { shrink: true, ...InputLabelProps } : { ...InputLabelProps } } InputProps={{ + disableUnderline: revamp, ...(theme.name === 'classic' ? { notched: false } : {}), endAdornment: type === 'password' ? ( @@ -112,7 +113,6 @@ function TextField({ {Boolean(error) === true ? : done === true ? : null} ), - disableUnderline: revamp, placeholder: placeholder != null ? placeholder : '', }} {...props} From 86cb747d192f057c7589ccd45df34bd244aed854 Mon Sep 17 00:00:00 2001 From: Denis Date: Thu, 29 Dec 2022 12:05:18 +0300 Subject: [PATCH 092/172] fixes --- .../features/mock-chain/TestWallets.js | 12 ++--- .../mock-chain/mockCardanoImporter.js | 6 +-- .../features/step_definitions/common-steps.js | 3 +- .../step_definitions/connector-steps.js | 9 +--- .../features/support/webdriver.js | 44 ++++++++++++------- 5 files changed, 39 insertions(+), 35 deletions(-) diff --git a/packages/yoroi-extension/features/mock-chain/TestWallets.js b/packages/yoroi-extension/features/mock-chain/TestWallets.js index 645fb7e678..ee3e6679eb 100644 --- a/packages/yoroi-extension/features/mock-chain/TestWallets.js +++ b/packages/yoroi-extension/features/mock-chain/TestWallets.js @@ -36,8 +36,8 @@ function createWallet(payload: {| export type WalletNames = 'shelley-simple-24' | - 'shelley-simple-15' | 'shelley-collateral' | + 'shelley-simple-15' | 'shelley-delegated' | 'shelley-ledger-delegated' | 'shelley-only-registered' | @@ -124,16 +124,16 @@ export const testWallets: { [key: WalletNames]: RestorationInput, ... } = Object mnemonic: 'reunion walnut update express purse defense slice barrel estate olympic february flock give team alert coast luggage exhaust notable bag december split furnace sponsor', plate: 'DSKC-9213', }), - createWallet({ - name: ('shelley-simple-15': WalletNames), - mnemonic: 'eight country switch draw meat scout mystery blade tip drift useless good keep usage title', - plate: 'ZDDC-9858', - }), createWallet({ name: ('shelley-collateral': WalletNames), mnemonic: 'deal calm cloth world refuse pledge grant tuna inner body fat afford absorb off barely', plate: 'HLBZ-9462', }), + createWallet({ + name: ('shelley-simple-15': WalletNames), + mnemonic: 'eight country switch draw meat scout mystery blade tip drift useless good keep usage title', + plate: 'ZDDC-9858', + }), createWallet({ name: ('shelley-delegated': WalletNames), mnemonic: 'parrot offer switch thank film high drop salute task train squirrel coral consider coyote evolve', diff --git a/packages/yoroi-extension/features/mock-chain/mockCardanoImporter.js b/packages/yoroi-extension/features/mock-chain/mockCardanoImporter.js index 9366546370..d3dc3065cf 100644 --- a/packages/yoroi-extension/features/mock-chain/mockCardanoImporter.js +++ b/packages/yoroi-extension/features/mock-chain/mockCardanoImporter.js @@ -2003,8 +2003,8 @@ export const generateTransaction = (): {| cip1852TrezorTx1, cip1852TrezorTx2, cip1852TrezorTx3, - shelleySimple15, shelleyCollateral, + shelleySimple15, shelleyDelegatedTx1, shelleyDelegatedTx2, shelleyLedgerDelegatedTx1, @@ -2095,10 +2095,10 @@ export function resetChain(chainToUse: $Values): void { addTransaction(txs.cip1852TrezorTx1); addTransaction(txs.cip1852TrezorTx2); addTransaction(txs.cip1852TrezorTx3); - // shelley-simple-15 - addTransaction(txs.shelleySimple15); // shelley-collateral addTransaction(txs.shelleyCollateral); + // shelley-simple-15 + addTransaction(txs.shelleySimple15); // shelley-delegated addTransaction(txs.shelleyDelegatedTx1); addTransaction(txs.shelleyDelegatedTx2); diff --git a/packages/yoroi-extension/features/step_definitions/common-steps.js b/packages/yoroi-extension/features/step_definitions/common-steps.js index 20a8fcb2d7..d09ea0eb79 100644 --- a/packages/yoroi-extension/features/step_definitions/common-steps.js +++ b/packages/yoroi-extension/features/step_definitions/common-steps.js @@ -238,6 +238,7 @@ After(async function (scenario) { await getLogs(this.driver, 'failedStep', logging.Type.BROWSER); await getLogs(this.driver, 'failedStep', logging.Type.DRIVER); // getting logs from background + await this.windowManager.openNewTab(backgroungTabName, this.getBackgroundUrl()); await this.windowManager.switchTo(backgroungTabName); await getLogs(this.driver, 'background', logging.Type.BROWSER); await this.windowManager.switchTo(extensionTabName); @@ -521,8 +522,6 @@ async function acceptUriPrompt(world: any) { Given(/^I have opened the extension$/, async function () { this.webDriverLogger.info(`Step: I have opened the extension`); await this.get(this.getExtensionUrl()); - await this.windowManager.openNewTab(backgroungTabName, this.getBackgroundUrl()); - await this.windowManager.switchTo(extensionTabName); const browserName = await this.getBrowser(); if (browserName === 'firefox') { await this.driver.manage().window().maximize(); diff --git a/packages/yoroi-extension/features/step_definitions/connector-steps.js b/packages/yoroi-extension/features/step_definitions/connector-steps.js index b4761264a0..a9c1fc3f5b 100644 --- a/packages/yoroi-extension/features/step_definitions/connector-steps.js +++ b/packages/yoroi-extension/features/step_definitions/connector-steps.js @@ -28,12 +28,7 @@ import { } from '../pages/connector-signingTxPage'; import { getSigningData, signMessageTitle } from '../pages/connector-signingDataPage'; import { addCollateralTitle } from '../pages/connector-getCollateralPage'; -import { - backgroungTabName, - mockDAppName, - extensionTabName, - popupConnectorName -} from '../support/windowManager'; +import { mockDAppName, extensionTabName, popupConnectorName } from '../support/windowManager'; import { connectorButton } from '../pages/sidebarPage'; const userRejectMsg = 'user reject'; @@ -50,8 +45,6 @@ const connectorPopUpIsDisplayed = async (customWorld: Object) => { Given(/^I have opened the mock dApp$/, async function () { this.webDriverLogger.info(`Step: I have opened the mock dApp`); await this.get(mockDAppUrl); - await this.windowManager.openNewTab(backgroungTabName, this.getBackgroundUrl()); - await this.windowManager.switchTo(mockDAppName); }); Then(/^I open the mock dApp tab$/, async function () { diff --git a/packages/yoroi-extension/features/support/webdriver.js b/packages/yoroi-extension/features/support/webdriver.js index b242983082..b40f692791 100644 --- a/packages/yoroi-extension/features/support/webdriver.js +++ b/packages/yoroi-extension/features/support/webdriver.js @@ -41,24 +41,28 @@ function encode(file) { const firefoxExtensionId = 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa'; const firefoxUuidMapping = `{"{530f7c6c-6077-4703-8f71-cb368c663e35}":"${firefoxExtensionId}"}`; +const prefs = new logging.Preferences(); +prefs.setLevel(logging.Type.BROWSER, logging.Level.ALL); + function getBraveBuilder() { - return new Builder().forBrowser('chrome').setChromeOptions( - new chrome.Options() - .setChromeBinaryPath('/usr/bin/brave-browser') - .addArguments( - '--no-sandbox', // Disables the sandbox for all process types that are normally sandboxed. Meant to be used as a browser-level switch for testing purposes only - '--disable-gpu', // Disables GPU hardware acceleration. If software renderer is not in place, then the GPU process won't launch - '--disable-dev-shm-usage', // The /dev/shm partition is too small in certain VM environments, causing Chrome to fail or crash - '--disable-setuid-sandbox', // Disable the setuid sandbox (Linux only) - '--start-maximized' // Starts the browser maximized, regardless of any previous settings - ) - .addExtensions(encode(path.resolve(__dirname, '../../Yoroi-test.crx'))) + return new Builder() + .forBrowser('chrome') + .setLoggingPrefs(prefs) + .setChromeOptions( + new chrome.Options() + .setChromeBinaryPath('/usr/bin/brave-browser') + .addArguments( + '--no-sandbox', // Disables the sandbox for all process types that are normally sandboxed. Meant to be used as a browser-level switch for testing purposes only + '--disable-gpu', // Disables GPU hardware acceleration. If software renderer is not in place, then the GPU process won't launch + '--disable-dev-shm-usage', // The /dev/shm partition is too small in certain VM environments, causing Chrome to fail or crash + '--disable-setuid-sandbox', // Disable the setuid sandbox (Linux only) + '--start-maximized' // Starts the browser maximized, regardless of any previous settings + ) + .addExtensions(encode(path.resolve(__dirname, '../../Yoroi-test.crx'))) ); } function getChromeBuilder() { - const prefs = new logging.Preferences(); - prefs.setLevel(logging.Type.BROWSER, logging.Level.ALL); return new Builder() .forBrowser('chrome') .setLoggingPrefs(prefs) @@ -90,6 +94,7 @@ function getFirefoxBuilder() { * The config is deprecated and may be removed in the future. */ .setPreference('xpinstall.signatures.required', false) + .setPreference('devtools.console.stdout.content', true) .setPreference('extensions.webextensions.uuids', firefoxUuidMapping); return new Builder() @@ -147,6 +152,10 @@ function CustomWorld(cmdInput: WorldInput) { this.trezorEmuLogger = undefined; + this.chromeExtIdUrl = `chrome-extension://bdlknlffjjmjckcldekkbejaogpkjphg`; + + this.firefoxExtIdUrl = `moz-extension://${firefoxExtensionId}`; + this.addToLoggers = (logger: any) => { this._allLoggers.push(logger); } ; @@ -164,13 +173,16 @@ function CustomWorld(cmdInput: WorldInput) { * so we can just hardcode this value if we keep e2etest-key.pem file * https://stackoverflow.com/a/10089780/3329806 */ - return 'chrome-extension://bdlknlffjjmjckcldekkbejaogpkjphg/main_window.html'; + return `${this.chromeExtIdUrl}/main_window.html`; } - return `moz-extension://${firefoxExtensionId}/main_window.html`; + return `${this.firefoxExtIdUrl}/main_window.html`; }; this.getBackgroundUrl = (): string => { - return `${this.getExtensionUrl()}/background.html` + if (cmdInput.parameters.browser === 'chrome' || cmdInput.parameters.browser === 'brave') { + return `${this.chromeExtIdUrl}/background.html`; + } + return `${this.firefoxExtIdUrl}/background.html`; }; this.get = async (url: string) => { From d6fdc3b30db2d13dcb855bef604a7236627afff3 Mon Sep 17 00:00:00 2001 From: Ahmed Ibrahim Date: Thu, 5 Jan 2023 16:08:00 +0200 Subject: [PATCH 093/172] Redirect the user from My Wallets page on revamp --- .../app/containers/wallet/MyWalletsPage.js | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/packages/yoroi-extension/app/containers/wallet/MyWalletsPage.js b/packages/yoroi-extension/app/containers/wallet/MyWalletsPage.js index 3a3000f052..3e0e9eaa48 100644 --- a/packages/yoroi-extension/app/containers/wallet/MyWalletsPage.js +++ b/packages/yoroi-extension/app/containers/wallet/MyWalletsPage.js @@ -48,6 +48,7 @@ import NavBarRevamp from '../../components/topbar/NavBarRevamp' import { withLayout } from '../../styles/context/layout' import type { LayoutComponentMap } from '../../styles/context/layout' import { Box } from '@mui/system' +import { THEMES } from '../../styles/utils' export type GeneratedData = typeof MyWalletsPage.prototype.generated; @@ -76,7 +77,14 @@ class MyWalletsPage extends Component { } componentDidMount () { - this.generated.actions.wallets.unselectWallet.trigger(); + const isRevamp = this.generated.stores.profile.currentTheme === THEMES.YOROI_REVAMP + if (isRevamp) { + this.generated.actions.router.goToRoute.trigger({ + route: ROUTES.WALLETS.ROOT, + }); + } else { + this.generated.actions.wallets.unselectWallet.trigger(); + } } handleWalletNavItemClick: PublicDeriver<> => void = ( @@ -418,7 +426,10 @@ class MyWalletsPage extends Component { |}, |}, stores: {| - profile: {| shouldHideBalance: boolean |}, + profile: {| + shouldHideBalance: boolean, + currentTheme: Theme, + |}, uiDialogs: {| isOpen: any => boolean |}, @@ -459,6 +470,7 @@ class MyWalletsPage extends Component { stores: { profile: { shouldHideBalance: stores.profile.shouldHideBalance, + currentTheme: stores.profile.currentTheme, }, uiDialogs: { isOpen: stores.uiDialogs.isOpen, From 38a06074fa8f72aa780e5c41aa5aa753b6d264f4 Mon Sep 17 00:00:00 2001 From: Ahmed Ibrahim Date: Fri, 6 Jan 2023 14:19:03 +0200 Subject: [PATCH 094/172] Read & save last selected wallet into the local storage --- .../app/api/localStorage/index.js | 14 ++++++++ .../categories/GeneralSettingsPage.js | 1 + .../app/containers/wallet/MyWalletsPage.js | 21 ++++++----- .../app/containers/wallet/Wallet.js | 19 +++++----- .../app/stores/base/BaseProfileStore.js | 4 +++ .../app/stores/toplevel/WalletStore.js | 36 +++++++++++++++---- 6 files changed, 69 insertions(+), 26 deletions(-) diff --git a/packages/yoroi-extension/app/api/localStorage/index.js b/packages/yoroi-extension/app/api/localStorage/index.js index 691a431d12..5d29cfa566 100644 --- a/packages/yoroi-extension/app/api/localStorage/index.js +++ b/packages/yoroi-extension/app/api/localStorage/index.js @@ -37,6 +37,7 @@ const storageKeys = { CATALYST_ROUND_INFO: networkForLocalStorage + '-CATALYST_ROUND_INFO', // ========== CONNECTOR ========== // ERGO_CONNECTOR_WHITELIST: 'connector_whitelist', + SELECTED_WALLET: 'SELECTED_WALLET', }; export type SetCustomUserThemeRequest = {| @@ -119,6 +120,19 @@ export default class LocalStorageApi { unsetUserTheme: void => Promise = () => removeLocalItem(storageKeys.THEME); + // ========== Select Wallet ========== // + + getSelectedWalletId: void => number | null = () => { + const id = localStorage.getItem(storageKeys.SELECTED_WALLET); + if (!id) return null + if (isNaN(Number(id))) throw new Error(`Invalid wallet Id: ${id}`); + return Number(id) + } + + setSelectedWalletId: number => void = (id) => { + localStorage.setItem(storageKeys.SELECTED_WALLET, id.toString()) + } + // ========== Custom User Theme ========== // getCustomUserTheme: void => Promise = () => getLocalItem(storageKeys.CUSTOM_THEME); diff --git a/packages/yoroi-extension/app/containers/settings/categories/GeneralSettingsPage.js b/packages/yoroi-extension/app/containers/settings/categories/GeneralSettingsPage.js index a0a6b0a8b3..e53acc72bd 100644 --- a/packages/yoroi-extension/app/containers/settings/categories/GeneralSettingsPage.js +++ b/packages/yoroi-extension/app/containers/settings/categories/GeneralSettingsPage.js @@ -135,6 +135,7 @@ export default class GeneralSettingsPage extends Component +type Props = InjectedOrGenerated; type InjectedProps = {| +renderLayoutComponent: LayoutComponentMap => Node |}; type AllProps = {| ...Props, ...InjectedProps |}; @@ -77,7 +76,7 @@ class MyWalletsPage extends Component { } componentDidMount () { - const isRevamp = this.generated.stores.profile.currentTheme === THEMES.YOROI_REVAMP + const isRevamp = this.generated.stores.profile.isRevampTheme; if (isRevamp) { this.generated.actions.router.goToRoute.trigger({ route: ROUTES.WALLETS.ROOT, @@ -428,7 +427,7 @@ class MyWalletsPage extends Component { stores: {| profile: {| shouldHideBalance: boolean, - currentTheme: Theme, + isRevampTheme: boolean, |}, uiDialogs: {| isOpen: any => boolean @@ -470,7 +469,7 @@ class MyWalletsPage extends Component { stores: { profile: { shouldHideBalance: stores.profile.shouldHideBalance, - currentTheme: stores.profile.currentTheme, + isRevampTheme: stores.profile.isRevampTheme, }, uiDialogs: { isOpen: stores.uiDialogs.isOpen, diff --git a/packages/yoroi-extension/app/containers/wallet/Wallet.js b/packages/yoroi-extension/app/containers/wallet/Wallet.js index 940b4f5145..d7f98b03d0 100644 --- a/packages/yoroi-extension/app/containers/wallet/Wallet.js +++ b/packages/yoroi-extension/app/containers/wallet/Wallet.js @@ -30,8 +30,6 @@ import NavBarTitle from '../../components/topbar/NavBarTitle'; import SubMenu from '../../components/topbar/SubMenu'; import type { GeneratedData as NavBarContainerRevampData } from '../NavBarContainerRevamp'; import WalletSyncingOverlay from '../../components/wallet/syncingOverlay/WalletSyncingOverlay'; -import { THEMES } from '../../styles/utils'; -import type { Theme } from '../../styles/utils'; export type GeneratedData = typeof Wallet.prototype.generated; @@ -58,10 +56,13 @@ class Wallet extends Component { componentDidMount() { const publicDeriver = this.generated.stores.wallets.selected; const publicDerivers = this.generated.stores.wallets.publicDerivers; - const isRevamp = this.generated.stores.profile.currentTheme === THEMES.YOROI_REVAMP + const isRevamp = this.generated.stores.profile.isRevampTheme; if (publicDeriver == null && isRevamp && publicDerivers.length !== 0) { - this.generated.actions.wallets.setActiveWallet.trigger({ wallet: publicDerivers[0] }) + this.generated.actions.wallets.setActiveWallet.trigger({ + wallet: publicDerivers[0], + formCacheFirst: true, + }) } // reroute to the default path for the wallet @@ -74,7 +75,7 @@ class Wallet extends Component { } checkRoute(): void | string { - const isRevamp = this.generated.stores.profile.currentTheme === THEMES.YOROI_REVAMP + const isRevamp = this.generated.stores.profile.isRevampTheme; const categories = isRevamp ? allCategories.filter(c => c.route !== ROUTES.WALLETS.DELEGATION_DASHBOARD) : allCategories; @@ -117,7 +118,7 @@ class Wallet extends Component { if (this.generated.stores.wallets.firstSync === publicDeriver.getPublicDeriverId()) { return ( this.navigateToMyWallets(ROUTES.MY_WALLETS)} /> ) @@ -279,7 +280,8 @@ class Wallet extends Component { |}, |}, profile: {| - currentTheme: Theme, + isRevampTheme: boolean, + isClassicTheme: boolean, |}, |} |} { @@ -320,7 +322,8 @@ class Wallet extends Component { })(), }, profile: { - currentTheme: stores.profile.currentTheme, + isRevampTheme: stores.profile.isRevampTheme, + isClassicTheme: stores.profile.isClassicTheme, } }, actions: { diff --git a/packages/yoroi-extension/app/stores/base/BaseProfileStore.js b/packages/yoroi-extension/app/stores/base/BaseProfileStore.js index 9eab767a54..731bf5f0c7 100644 --- a/packages/yoroi-extension/app/stores/base/BaseProfileStore.js +++ b/packages/yoroi-extension/app/stores/base/BaseProfileStore.js @@ -276,6 +276,10 @@ export default class BaseProfileStore return THEMES.YOROI_MODERN; } + @computed get isRevampTheme(): boolean { + return this.currentTheme === THEMES.YOROI_REVAMP + } + @computed get isModernTheme(): boolean { return this.currentTheme === THEMES.YOROI_MODERN; } diff --git a/packages/yoroi-extension/app/stores/toplevel/WalletStore.js b/packages/yoroi-extension/app/stores/toplevel/WalletStore.js index d2e40609b6..357b04907f 100644 --- a/packages/yoroi-extension/app/stores/toplevel/WalletStore.js +++ b/packages/yoroi-extension/app/stores/toplevel/WalletStore.js @@ -97,7 +97,17 @@ export default class WalletStore extends Store { @observable publicDerivers: Array>; @observable selected: null | PublicDeriver<>; + + @observable getSelectedWalletIdReq: Request<(void) => Promise> = new Request< + (void) => Promise + >(this.api.localStorage.getSelectedWalletId); + + @observable setSelectedWalletIdReq: Request<(number) => Promise> = new Request< + (number) => Promise + >(this.api.localStorage.setSelectedWalletId); + @observable getInitialWallets: Request = new Request(getWallets); + @observable createWalletRequest: Request> = new Request< DeferredCall >(async create => { @@ -157,6 +167,7 @@ export default class WalletStore extends Store { 'visibilitychange', debounce((_e) => this._pollRefresh(), this.ON_VISIBLE_DEBOUNCE_WAIT) ); + } @action @@ -374,13 +385,24 @@ export default class WalletStore extends Store { // =================== ACTIVE WALLET ==================== // - @action _setActiveWallet: ({| wallet: PublicDeriver<> |}) => void = ({ wallet }) => { - this.actions.profile.setSelectedNetwork.trigger(wallet.getParent().getNetworkInfo()); - - this.selected = wallet; - // do not await on purpose since the UI will handle adding loaders while refresh is happening - this.refreshWalletFromRemote(wallet); - }; + @action _setActiveWallet: ({| wallet: PublicDeriver<>, formCacheFirst?: boolean |}) => void = + ({ wallet, formCacheFirst }) => { + const lastSelectedWallet = this._getLastSelectedWallet(); + const walletToSelect = formCacheFirst && lastSelectedWallet ? lastSelectedWallet : wallet; + + this.actions.profile.setSelectedNetwork.trigger(walletToSelect.getParent().getNetworkInfo()); + this.selected = walletToSelect; + // Cache select wallet + // this.setSelectedWalletIdReq.execute(walletToSelect.getPublicDeriverId()); + this.api.localStorage.setSelectedWalletId(walletToSelect.getPublicDeriverId()) + // do not await on purpose since the UI will handle adding loaders while refresh is happening + this.refreshWalletFromRemote(walletToSelect); + }; + + _getLastSelectedWallet: void => ?PublicDeriver<> = () => { + const walletId = this.api.localStorage.getSelectedWalletId(); + return this.publicDerivers.find(pd => pd.getPublicDeriverId() === walletId); + } @action _unsetActiveWallet: void => void = () => { this.actions.profile.setSelectedNetwork.trigger(undefined); From 5a7e9389db3eff68aee64e23c43988ada9efd207 Mon Sep 17 00:00:00 2001 From: Ahmed Ibrahim Date: Fri, 6 Jan 2023 14:21:26 +0200 Subject: [PATCH 095/172] Remove unused async requestes --- .../app/stores/toplevel/WalletStore.js | 11 ----------- 1 file changed, 11 deletions(-) diff --git a/packages/yoroi-extension/app/stores/toplevel/WalletStore.js b/packages/yoroi-extension/app/stores/toplevel/WalletStore.js index 357b04907f..91e29028a2 100644 --- a/packages/yoroi-extension/app/stores/toplevel/WalletStore.js +++ b/packages/yoroi-extension/app/stores/toplevel/WalletStore.js @@ -95,17 +95,7 @@ export default class WalletStore extends Store { @observable firstSync: ?number; @observable publicDerivers: Array>; - @observable selected: null | PublicDeriver<>; - - @observable getSelectedWalletIdReq: Request<(void) => Promise> = new Request< - (void) => Promise - >(this.api.localStorage.getSelectedWalletId); - - @observable setSelectedWalletIdReq: Request<(number) => Promise> = new Request< - (number) => Promise - >(this.api.localStorage.setSelectedWalletId); - @observable getInitialWallets: Request = new Request(getWallets); @observable createWalletRequest: Request> = new Request< @@ -393,7 +383,6 @@ export default class WalletStore extends Store { this.actions.profile.setSelectedNetwork.trigger(walletToSelect.getParent().getNetworkInfo()); this.selected = walletToSelect; // Cache select wallet - // this.setSelectedWalletIdReq.execute(walletToSelect.getPublicDeriverId()); this.api.localStorage.setSelectedWalletId(walletToSelect.getPublicDeriverId()) // do not await on purpose since the UI will handle adding loaders while refresh is happening this.refreshWalletFromRemote(walletToSelect); From a3fdd70051a7c418986a2f2614951569ce3d1b6f Mon Sep 17 00:00:00 2001 From: vantuz-subhuman Date: Fri, 6 Jan 2023 19:28:28 +0300 Subject: [PATCH 096/172] small fixes --- .../yoroi-connector/example-cardano/index.js | 5 +- .../components/widgets/CopyableAddress.scss | 2 +- packages/yoroi-extension/package-lock.json | 50 +++++++++---------- 3 files changed, 29 insertions(+), 28 deletions(-) diff --git a/packages/yoroi-connector/example-cardano/index.js b/packages/yoroi-connector/example-cardano/index.js index 373b87d69c..ebc1e29003 100644 --- a/packages/yoroi-connector/example-cardano/index.js +++ b/packages/yoroi-connector/example-cardano/index.js @@ -21,7 +21,6 @@ const getUtxos = document.querySelector("#get-utxos"); const submitTx = document.querySelector("#submit-tx"); const signTx = document.querySelector("#sign-tx"); const showUtxos = document.querySelector("#show-utxos"); -const createTx = document.querySelector("#create-tx"); const getCollateralUtxos = document.querySelector("#get-collateral-utxos"); const signData = document.querySelector("#sign-data"); const alertEl = document.querySelector("#alert"); @@ -1055,7 +1054,7 @@ function renderJonsResponse(title, response) { ); } -window.onload = () => { +const onload = () => { if (typeof window.cardano === "undefined") { alertError("Cardano API not found"); } else { @@ -1082,3 +1081,5 @@ window.onload = () => { ); } }; + +setTimeout(onload, 100); diff --git a/packages/yoroi-extension/app/components/widgets/CopyableAddress.scss b/packages/yoroi-extension/app/components/widgets/CopyableAddress.scss index 6c1c092827..fb0f1d1e0d 100644 --- a/packages/yoroi-extension/app/components/widgets/CopyableAddress.scss +++ b/packages/yoroi-extension/app/components/widgets/CopyableAddress.scss @@ -6,7 +6,7 @@ cursor: pointer; object-fit: contain; display: inline-flex; - margin-left: 5px; + margin-left: 2px; width: 32px; height: 32px; border-radius: 50%; diff --git a/packages/yoroi-extension/package-lock.json b/packages/yoroi-extension/package-lock.json index b197117120..c87061355f 100644 --- a/packages/yoroi-extension/package-lock.json +++ b/packages/yoroi-extension/package-lock.json @@ -8599,7 +8599,7 @@ "any-promise": { "version": "1.3.0", "resolved": "https://registry.npmjs.org/any-promise/-/any-promise-1.3.0.tgz", - "integrity": "sha512-7UvmKalWRt1wgjL1RrGxoSJW/0QZFIegpeGvZG9kjp8vrRu55XTHbwnqq2GpXm9uLbcuhxm3IqX9OB4MZR1b2A==", + "integrity": "sha1-q8av7tzqUugJzcA3au0845Y10X8=", "dev": true }, "anymatch": { @@ -9761,7 +9761,7 @@ "becke-ch--regex--s0-0-v1--base--pl--lib": { "version": "1.4.0", "resolved": "https://registry.npmjs.org/becke-ch--regex--s0-0-v1--base--pl--lib/-/becke-ch--regex--s0-0-v1--base--pl--lib-1.4.0.tgz", - "integrity": "sha512-FnWonOyaw7Vivg5nIkrUll9HSS5TjFbyuURAiDssuL6VxrBe3ERzudRxOcWRhZYlP89UArMDikz7SapRPQpmZQ==", + "integrity": "sha1-Qpzuu/pffpNueNc/vcfacWKyDiA=", "dev": true }, "before-after-hook": { @@ -12348,25 +12348,25 @@ "escape-string-regexp": { "version": "1.0.5", "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", - "integrity": "sha512-vbRorB5FUQWvla16U8R/qgaFIya2qGzwDrNmCZuYKrbdSUMG6I1ZCGQRefkRVhuOkIGVne7BQ35DSfo1qvJqFg==", + "integrity": "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=", "dev": true }, "indent-string": { "version": "3.2.0", "resolved": "https://registry.npmjs.org/indent-string/-/indent-string-3.2.0.tgz", - "integrity": "sha512-BYqTHXTGUIvg7t1r4sJNKcbDZkL92nkXA8YtRpbjFHRHGDL/NtUeiBJMeE60kIFN/Mg8ESaWQvftaYMGJzQZCQ==", + "integrity": "sha1-Sl/W0nzDMvN+VBmlBNu4NxBckok=", "dev": true }, "is-fullwidth-code-point": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-2.0.0.tgz", - "integrity": "sha512-VHskAKYM8RfSFXwee5t5cbN5PZeq1Wrh6qd5bkyiXIf6UQcN6w/A0eXM9r6t8d+GYOh+o6ZhiEnb88LN/Y8m2w==", + "integrity": "sha1-o7MKXE8ZkYMWeqq5O+764937ZU8=", "dev": true }, "path-key": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/path-key/-/path-key-2.0.1.tgz", - "integrity": "sha512-fEHGKCSmUSDPv4uoj8AlD+joPlq3peND+HRYyxFz4KPw4z926S/b8rIuFs2FYJg3BwsxJf6A9/3eIdLaYC+9Dw==", + "integrity": "sha1-QRyttXTFoUDTpLGRDUDYDMn0C0A=", "dev": true }, "semver": { @@ -12378,7 +12378,7 @@ "shebang-command": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-1.2.0.tgz", - "integrity": "sha512-EV3L1+UQWGor21OmnvojK36mhg+TyIKDh3iFBKBohr5xeXIhNBcx8oWdgkTEEQ+BEFFYdLRuqMfd5L84N1V5Vg==", + "integrity": "sha1-RKrGW2lbAzmJaMOfNj/uXer98eo=", "dev": true, "requires": { "shebang-regex": "^1.0.0" @@ -12387,7 +12387,7 @@ "shebang-regex": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-1.0.0.tgz", - "integrity": "sha512-wpoSFAxys6b2a2wHZ1XpDSgD7N9iVjg29Ph9uV/uaP9Ex/KXlkTZTeddxDPSYQpgvzKLGJke2UU0AzoGCjNIvQ==", + "integrity": "sha1-2kL0l0DAtC2yypcoVxyxkMmO/qM=", "dev": true }, "string-width": { @@ -12403,7 +12403,7 @@ "strip-ansi": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-4.0.0.tgz", - "integrity": "sha512-4XaJ2zQdCzROZDivEVIDPkcQn8LMFSa8kj8Gxb/Lnwzv9A8VctNZ+lfivC/sV3ivW8ElJTERXZoPBRrZKkNKow==", + "integrity": "sha1-qEeQIusaw2iocTibY1JixQXuNo8=", "dev": true, "requires": { "ansi-regex": "^3.0.0" @@ -12498,7 +12498,7 @@ "cucumber-tag-expressions": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/cucumber-tag-expressions/-/cucumber-tag-expressions-1.1.1.tgz", - "integrity": "sha512-V9jv81sR/HaJ87FoidrvHkviXId7KmBcUi7aQPfi+W3nRO30N6GqH6lcp8K+nyiT1DgemRJBPDDeBMS93xJqMQ==", + "integrity": "sha1-f1x7cACbwrZmWRv+ZIVFeL7e6Fo=", "dev": true }, "currently-unhandled": { @@ -13565,7 +13565,7 @@ "es6-iterator": { "version": "2.0.3", "resolved": "https://registry.npmjs.org/es6-iterator/-/es6-iterator-2.0.3.tgz", - "integrity": "sha512-zw4SRzoUkd+cl+ZoE15A9o1oQd920Bb0iOJMQkQhl3jNc03YqVjAhG7scf9C5KWRU/R13Orf588uCC6525o02g==", + "integrity": "sha1-p96IkUGgWpSwhUQDstCg+/qY87c=", "dev": true, "requires": { "d": "1", @@ -14796,7 +14796,7 @@ "figures": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/figures/-/figures-2.0.0.tgz", - "integrity": "sha512-Oa2M9atig69ZkfwiApY8F2Yy+tzMbazyvqv21R0NsSC8floSOC09BbT1ITWAdoMGQvJ/aZnR1KMwdx9tvHnTNA==", + "integrity": "sha1-OrGi0qYsi/tDGgyUy3l6L84nyWI=", "dev": true, "requires": { "escape-string-regexp": "^1.0.5" @@ -14805,7 +14805,7 @@ "escape-string-regexp": { "version": "1.0.5", "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", - "integrity": "sha512-vbRorB5FUQWvla16U8R/qgaFIya2qGzwDrNmCZuYKrbdSUMG6I1ZCGQRefkRVhuOkIGVne7BQ35DSfo1qvJqFg==", + "integrity": "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=", "dev": true } } @@ -16051,7 +16051,7 @@ "gherkin": { "version": "5.1.0", "resolved": "https://registry.npmjs.org/gherkin/-/gherkin-5.1.0.tgz", - "integrity": "sha512-axTCsxH0m0cixijLvo7s9591h5pMb8ifQxFDun5FnfFhVsUhxgdnH0H7TSK7q8I4ASUU18DJ/tmlnMegMuLUUQ==", + "integrity": "sha1-aEu7A63STq9731RPWAM+so+zxtU=", "dev": true }, "glob": { @@ -16764,7 +16764,7 @@ "httpolyglot": { "version": "0.1.2", "resolved": "https://registry.npmjs.org/httpolyglot/-/httpolyglot-0.1.2.tgz", - "integrity": "sha512-ouHI1AaQMLgn4L224527S5+vq6hgvqPteurVfbm7ChViM3He2Wa8KP1Ny7pTYd7QKnDSPKcN8JYfC8r/lmsE3A==", + "integrity": "sha1-5NNH/omEpi9GfUBg31J/GFH2mXs=", "dev": true }, "https-browserify": { @@ -17256,7 +17256,7 @@ "is-generator": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/is-generator/-/is-generator-1.0.3.tgz", - "integrity": "sha512-G56jBpbJeg7ds83HW1LuShNs8J73Fv3CPz/bmROHOHlnKkN8sWb9ujiagjmxxMUywftgq48HlBZELKKqFLk0oA==", + "integrity": "sha1-wUwhBX7TbjKNuANHlmxpP4hjifM=", "dev": true }, "is-generator-fn": { @@ -19707,7 +19707,7 @@ "knuth-shuffle-seeded": { "version": "1.0.6", "resolved": "https://registry.npmjs.org/knuth-shuffle-seeded/-/knuth-shuffle-seeded-1.0.6.tgz", - "integrity": "sha512-9pFH0SplrfyKyojCLxZfMcvkhf5hH0d+UwR9nTVJ/DDQJGuzcXjTwB7TP7sDfehSudlGGaOLblmEWqv04ERVWg==", + "integrity": "sha1-AfG2VzOqdUDuCNiwF0Fk0iCB5OE=", "dev": true, "requires": { "seed-random": "~2.2.0" @@ -19955,7 +19955,7 @@ "lodash.omit": { "version": "4.5.0", "resolved": "https://registry.npmjs.org/lodash.omit/-/lodash.omit-4.5.0.tgz", - "integrity": "sha512-XeqSp49hNGmlkj2EJlfrQFIzQ6lXdNro9sddtQzcJY8QaoC2GO0DT7xaIokHeyM+mIT0mPMlPvkYzg2xCuHdZg==", + "integrity": "sha1-brGa5aHuHdnfC5aeZs4Lf6MLXmA=", "dev": true }, "lodash.set": { @@ -22182,7 +22182,7 @@ "pad-right": { "version": "0.2.2", "resolved": "https://registry.npmjs.org/pad-right/-/pad-right-0.2.2.tgz", - "integrity": "sha512-4cy8M95ioIGolCoMmm2cMntGR1lPLEbOMzOKu8bzjuJP6JpzEMQcDHmh7hHLYGgob+nKe1YHFMaG4V59HQa89g==", + "integrity": "sha1-b7ySQEXSRPKiokRQMGDTv8YAl3Q=", "dev": true, "requires": { "repeat-string": "^1.5.2" @@ -25133,7 +25133,7 @@ "seed-random": { "version": "2.2.0", "resolved": "https://registry.npmjs.org/seed-random/-/seed-random-2.2.0.tgz", - "integrity": "sha512-34EQV6AAHQGhoc0tn/96a9Fsi6v2xdqe/dMUwljGRaFOzR3EgRmECvD0O8vi8X+/uQ50LGHfkNu/Eue5TPKZkQ==", + "integrity": "sha1-KpsZ4lCoFwmSMaW5mk2vgLf77VQ=", "dev": true }, "selenium-webdriver": { @@ -26741,7 +26741,7 @@ "thenify-all": { "version": "1.6.0", "resolved": "https://registry.npmjs.org/thenify-all/-/thenify-all-1.6.0.tgz", - "integrity": "sha512-RNxQH/qI8/t3thXJDwcstUO4zeqo64+Uy/+sNVRBx4Xn2OX+OZ9oP+iJnNFqplFra2ZUVeKCSa2oVWi3T4uVmA==", + "integrity": "sha1-GhkY1ALY/D+Y+/I02wvMjMEOlyY=", "dev": true, "requires": { "thenify": ">= 3.1.0 < 4" @@ -26858,7 +26858,7 @@ "title-case": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/title-case/-/title-case-2.1.1.tgz", - "integrity": "sha512-EkJoZ2O3zdCz3zJsYCsxyq2OC5hrxR9mfdd5I+w8h/tmFfeOxJ+vvkxsKxdmN0WtS9zLdHEgfgVOiMVgv+Po4Q==", + "integrity": "sha1-PhJyFtpY0rxb7PE3q5Ha46fNj6o=", "dev": true, "requires": { "no-case": "^2.2.0", @@ -26868,7 +26868,7 @@ "lower-case": { "version": "1.1.4", "resolved": "https://registry.npmjs.org/lower-case/-/lower-case-1.1.4.tgz", - "integrity": "sha512-2Fgx1Ycm599x+WGpIYwJOvsjmXFzTSc34IwDWALRA/8AopUKAVPwfJ+h5+f85BCp0PWmmJcWzEpxOpoXycMpdA==", + "integrity": "sha1-miyr0bno4K6ZOkv31YdcOcQujqw=", "dev": true }, "no-case": { @@ -27626,7 +27626,7 @@ "upper-case": { "version": "1.1.3", "resolved": "https://registry.npmjs.org/upper-case/-/upper-case-1.1.3.tgz", - "integrity": "sha512-WRbjgmYzgXkCV7zNVpy5YgrHgbBv126rMALQQMrmzOVC4GM2waQ9x7xtm8VU+1yF2kWyPzI9zbZ48n4vSxwfSA==", + "integrity": "sha1-9rRQHC7EzdJrp4vnIilh3ndiFZg=", "dev": true }, "uri-js": { @@ -27761,7 +27761,7 @@ "util-arity": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/util-arity/-/util-arity-1.1.0.tgz", - "integrity": "sha512-kkyIsXKwemfSy8ZEoaIz06ApApnWsk5hQO0vLjZS6UkBiGiW++Jsyb8vSBoc0WKlffGoGs5yYy/j5pp8zckrFA==", + "integrity": "sha1-WdAa8f2z/t4KxOYysKtfbOl8kzA=", "dev": true }, "util-deprecate": { From 9dab88b7e9ce365316d2be81dbc78668c57142d2 Mon Sep 17 00:00:00 2001 From: vantuz-subhuman Date: Fri, 6 Jan 2023 19:29:05 +0300 Subject: [PATCH 097/172] is-foreign --- .../app/connector/stores/ConnectorStore.js | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/packages/yoroi-extension/app/connector/stores/ConnectorStore.js b/packages/yoroi-extension/app/connector/stores/ConnectorStore.js index 38c144f6b9..da73d2d430 100644 --- a/packages/yoroi-extension/app/connector/stores/ConnectorStore.js +++ b/packages/yoroi-extension/app/connector/stores/ConnectorStore.js @@ -611,6 +611,13 @@ export default class ConnectorStore extends Store { } } + const ownAddresses = new Set([ + ...response.utxos.map(utxo => utxo.address), + ...response.usedAddresses, + ...response.unusedAddresses, + response.changeAddress + ]) + const outputs = []; for (let i = 0; i < txBody.outputs().len(); i++) { const output = txBody.outputs().get(i); @@ -618,6 +625,7 @@ export default class ConnectorStore extends Store { outputs.push( { address, + isForeign: !ownAddresses.has(address), value: multiTokenFromCardanoValue( output.amount(), selectedWallet.publicDeriver.getParent().getDefaultToken(), @@ -631,13 +639,6 @@ export default class ConnectorStore extends Store { amount: txBody.fee().to_str(), }; - const ownAddresses = new Set([ - ...response.utxos.map(utxo => utxo.address), - ...response.usedAddresses, - ...response.unusedAddresses, - response.changeAddress - ]) - const { amount, total } = await this._calculateAmountAndTotal( selectedWallet.publicDeriver, inputs, From e3c7ae7b3452355a552c1fb4af4b03313cc6a88f Mon Sep 17 00:00:00 2001 From: vantuz-subhuman Date: Mon, 9 Jan 2023 16:19:33 +0300 Subject: [PATCH 098/172] Moving the `WasmScope` into the rust-module --- .../example-cardano/index.js | 1059 ----------------- .../api/ada/lib/cardanoCrypto/rustLoader.js | 64 + 2 files changed, 64 insertions(+), 1059 deletions(-) delete mode 100644 packages/yoroi-ergo-connector/example-cardano/index.js diff --git a/packages/yoroi-ergo-connector/example-cardano/index.js b/packages/yoroi-ergo-connector/example-cardano/index.js deleted file mode 100644 index 6fde7abda0..0000000000 --- a/packages/yoroi-ergo-connector/example-cardano/index.js +++ /dev/null @@ -1,1059 +0,0 @@ -import * as CardanoWasm from '@emurgo/cardano-serialization-lib-browser'; -import { textPartFromWalletChecksumImagePart } from '@emurgo/cip4-js'; -import { createIcon } from '@download/blockies'; -import { getTtl } from './utils'; -import { Bech32Prefix } from '../../yoroi-extension/app/config/stringConfig'; -import { bytesToHex, hexToBytes } from './coreUtils'; - -const cardanoAccessBtnRow = document.querySelector('#request-button-row'); -const cardanoAuthCheck = document.querySelector('#check-identification'); -const cardanoAccessBtn = document.querySelector('#request-access'); -const connectionStatus = document.querySelector('#connection-status'); -const walletPlateSpan = document.querySelector('#wallet-plate'); -const walletIconSpan = document.querySelector('#wallet-icon'); -const getUnUsedAddresses = document.querySelector('#get-unused-addresses'); -const getUsedAddresses = document.querySelector('#get-used-addresses'); -const getChangeAddress = document.querySelector('#get-change-address'); -const getRewardAddresses = document.querySelector('#get-reward-addresses'); -const getAccountBalance = document.querySelector('#get-balance'); -const isEnabledBtn = document.querySelector('#is-enabled'); -const getUtxos = document.querySelector('#get-utxos'); -const submitTx = document.querySelector('#submit-tx'); -const signTx = document.querySelector('#sign-tx'); -const createTx = document.querySelector('#create-tx'); -const getCollateralUtxos = document.querySelector('#get-collateral-utxos'); -const signData = document.querySelector('#sign-data'); -const alertEl = document.querySelector('#alert'); -const spinner = document.querySelector('#spinner'); -const getNFTs = document.getElementById('nfts'); -const getNetworkId = document.getElementById('get-network-id'); - -let accessGranted = false; -let cardanoApi; -let returnType = 'cbor'; -let utxos; -let usedAddresses; -let unusedAddresses; -let changeAddress; -let unsignedTransactionHex; -let transactionHex; - -function isCBOR() { - return returnType === 'cbor'; -} - -const mkcolor = (primary, secondary, spots) => ({ primary, secondary, spots }); -const COLORS = [ - mkcolor('#E1F2FF', '#17D1AA', '#A80B32'), - mkcolor('#E1F2FF', '#FA5380', '#0833B2'), - mkcolor('#E1F2FF', '#F06EF5', '#0804F7'), - mkcolor('#E1F2FF', '#EBB687', '#852D62'), - mkcolor('#E1F2FF', '#F59F9A', '#085F48'), -]; - -function createBlockiesIcon(seed) { - const colorIdx = hexToBytes(seed)[0] % COLORS.length; - const color = COLORS[colorIdx]; - return createIcon({ - seed, - size: 7, - scale: 5, - bgcolor: color.primary, - color: color.secondary, - spotcolor: color.spots, - }); -} - -toggleSpinner('show'); - -function onApiConnectied(api) { - toggleSpinner('hide'); - let walletDisplay = 'an anonymous Yoroi Wallet'; - - api.experimental.setReturnType(returnType); - - const auth = api.experimental.auth && api.experimental.auth(); - const authEnabled = auth && auth.isEnabled(); - - if (authEnabled) { - const walletId = auth.getWalletId(); - const pubkey = auth.getWalletPubkey(); - console.log('Auth acquired successfully: ', JSON.stringify({ walletId, pubkey })); - const walletPlate = textPartFromWalletChecksumImagePart(walletId); - walletDisplay = `Yoroi Wallet ${walletPlate}`; - walletIconSpan.appendChild(createBlockiesIcon(walletId)); - } - - alertSuccess(`You have access to ${walletDisplay} now`); - walletPlateSpan.innerHTML = walletDisplay; - toggleConnectionUI('status'); - accessGranted = true; - window.cardanoApi = cardanoApi = api; - - api.experimental.onDisconnect(() => { - alertWarrning(`Disconnected from ${walletDisplay}`); - toggleConnectionUI('button'); - walletPlateSpan.innerHTML = ''; - walletIconSpan.innerHTML = ''; - }); - - if (authEnabled) { - console.log('Testing auth signatures'); - const messageJson = JSON.stringify({ - type: 'this is a random test message object', - rndValue: Math.random(), - }); - const messageHex = bytesToHex(messageJson); - console.log( - 'Signing randomized message: ', - JSON.stringify({ - messageJson, - messageHex, - }) - ); - const start = performance.now(); - auth.signHexPayload(messageHex).then( - sig => { - const elapsed = performance.now() - start; - console.log(`Signature created in ${elapsed} ms`); - console.log('Signature received: ', sig); - console.log('Verifying signature against the message'); - auth.checkHexPayload(messageHex, sig).then( - r => { - console.log('Signature matches message: ', r); - }, - e => { - console.error('Sig check failed', e); - } - ); - }, - err => { - console.error('Sig failed', err); - } - ); - } -} - -function reduceWasmMultiasset(multiasset, reducer, initValue) { - let result = initValue; - if (multiasset) { - const policyIds = multiasset.keys(); - for (let i = 0; i < policyIds.len(); i++) { - const policyId = policyIds.get(i); - const assets = multiasset.get(policyId); - const assetNames = assets.keys(); - for (let j = 0; j < assetNames.len(); j++) { - const name = assetNames.get(j); - const amount = assets.get(name); - const policyIdHex = bytesToHex(policyId.to_bytes()); - const encodedName = bytesToHex(name.name()); - result = reducer(result, { - policyId: policyIdHex, - name: encodedName, - amount: amount.to_str(), - assetId: `${policyIdHex}.${encodedName}`, - }); - } - } - } - return result; -} - -cardanoAccessBtn.addEventListener('click', () => { - toggleSpinner('show'); - const requestIdentification = cardanoAuthCheck.checked; - cardano.yoroi.enable({ requestIdentification }).then( - function (api) { - onApiConnectied(api); - }, - function (err) { - toggleSpinner('hide'); - alertError(`Error: ${err}`); - } - ); -}); - -isEnabledBtn.addEventListener('click', () => { - window.cardano.yoroi.isEnabled().then(function (isEnabled) { - alertSuccess(`Is Yoroi connection enabled: ${isEnabled}`); - }); -}); - -getNetworkId.addEventListener('click', () => { - if (!accessGranted) { - alertError('Should request access first'); - } else { - toggleSpinner('show'); - cardanoApi.getNetworkId().then(networkId => { - console.log('[getNetworkId]', networkId); - toggleSpinner('hide'); - }); - } -}); - -getAccountBalance.addEventListener('click', () => { - if (!accessGranted) { - alertError('Should request access first'); - } else { - toggleSpinner('show'); - const tokenId = '*'; - cardanoApi.getBalance(tokenId).then(function (balance) { - console.log('[getBalance]', balance); - toggleSpinner('hide'); - let balanceJson = balance; - if (isCBOR()) { - if (tokenId !== '*') { - alertSuccess(`Asset Balance: ${balance} (asset: ${tokenId})`); - return; - } - const value = CardanoWasm.Value.from_bytes(hexToBytes(balance)); - balanceJson = { default: value.coin().to_str() }; - balanceJson.assets = reduceWasmMultiasset( - value.multiasset(), - (res, asset) => { - res[asset.assetId] = asset.amount; - return res; - }, - {} - ); - } - alertSuccess(`Account Balance: ${JSON.stringify(balanceJson, null, 2)}`); - }); - } -}); - -function addressesFromCborIfNeeded(addresses) { - return isCBOR() - ? addresses.map(a => CardanoWasm.Address.from_bytes(hexToBytes(a)).to_bech32()) - : addresses; -} - -function addressToCbor(address) { - return bytesToHex(CardanoWasm.Address.from_bech32(address).to_bytes()); -} - -getUnUsedAddresses.addEventListener('click', () => { - if (!accessGranted) { - alertError('Should request access first'); - } else { - toggleSpinner('show'); - cardanoApi.getUnusedAddresses().then(function (addresses) { - toggleSpinner('hide'); - if (addresses.length === 0) { - alertWarrning('No unused addresses'); - return; - } - addresses = addressesFromCborIfNeeded(addresses); - unusedAddresses = addresses; - alertSuccess(`Address: `); - alertEl.innerHTML = - '

Unused addresses:

' + JSON.stringify(addresses, undefined, 2) + '
'; - }); - } -}); - -getUsedAddresses.addEventListener('click', () => { - if (!accessGranted) { - alertError('Should request access first'); - } else { - toggleSpinner('show'); - cardanoApi.getUsedAddresses({ page: 0, limit: 5 }).then(function (addresses) { - toggleSpinner('hide'); - if (addresses.length === 0) { - alertWarrning('No used addresses'); - return; - } - usedAddresses = addressesFromCborIfNeeded(addresses); - alertSuccess(`Address: ${usedAddresses.concat(',')}`); - alertEl.innerHTML = - '

Used addresses:

' + JSON.stringify(usedAddresses, undefined, 2) + '
'; - }); - } -}); - -getChangeAddress.addEventListener('click', () => { - if (!accessGranted) { - alertError('Should request access first'); - } else { - toggleSpinner('show'); - cardanoApi.getChangeAddress().then(function (address) { - toggleSpinner('hide'); - if (address.length === 0) { - alertWarrning('No change addresses'); - return; - } - changeAddress = addressesFromCborIfNeeded([address])[0]; - alertSuccess(`Address: `); - alertEl.innerHTML = - '

Change address:

' + JSON.stringify(address, undefined, 2) + '
'; - }); - } -}); - -getRewardAddresses.addEventListener('click', () => { - if (!accessGranted) { - alertError('Should request access first'); - } else { - toggleSpinner('show'); - cardanoApi.getRewardAddresses().then(function (addresses) { - toggleSpinner('hide'); - if (addresses.length === 0) { - alertWarrning('No change addresses'); - return; - } - addresses = addressesFromCborIfNeeded(addresses); - alertSuccess(`Address: ${addresses.concat(',')}`); - alertEl.innerHTML = - '

Reward addresses:

' + JSON.stringify(addresses, undefined, 2) + '
'; - }); - } -}); - -function mapCborUtxos(cborUtxos) { - return cborUtxos.map(hex => { - const u = CardanoWasm.TransactionUnspentOutput.from_bytes(hexToBytes(hex)); - const input = u.input(); - const output = u.output(); - const txHash = bytesToHex(input.transaction_id().to_bytes()); - const txIndex = input.index(); - const value = output.amount(); - return { - utxo_id: `${txHash}${txIndex}`, - tx_hash: txHash, - tx_index: txIndex, - receiver: output.address().to_bech32(), - amount: value.coin().to_str(), - assets: reduceWasmMultiasset( - value.multiasset(), - (res, asset) => { - res.push(asset); - return res; - }, - [] - ), - }; - }); -} - -function valueRequestObjectToWasmHex(requestObj) { - const { amount, assets } = requestObj; - const result = CardanoWasm.Value.new(CardanoWasm.BigNum.from_str(String(amount))); - if (assets != null) { - if (typeof assets !== 'object') { - throw 'Assets is expected to be an object like `{ [policyId]: { [assetName]: amount } }`'; - } - const wmasset = CardanoWasm.MultiAsset.new(); - for (const [policyId, assets2] of Object.entries(assets)) { - if (typeof assets2 !== 'object') { - throw 'Assets is expected to be an object like `{ [policyId]: { [assetName]: amount } }`'; - } - const wassets = CardanoWasm.Assets.new(); - for (const [assetName, amount] of Object.entries(assets2)) { - wassets.insert( - CardanoWasm.AssetName.new(hexToBytes(assetName)), - CardanoWasm.BigNum.from_str(String(amount)) - ); - } - wmasset.insert(CardanoWasm.ScriptHash.from_bytes(hexToBytes(policyId)), wassets); - } - result.set_multiasset(wmasset); - } - return bytesToHex(result.to_bytes()); -} - -window._getUtxos = function (value) { - if (!accessGranted) { - alertError('Should request access first'); - return; - } - toggleSpinner('show'); - if (value != null && typeof value !== 'string') { - value = valueRequestObjectToWasmHex(value); - } - cardanoApi.getUtxos(value).then(utxosResponse => { - toggleSpinner('hide'); - if (utxosResponse.length === 0) { - alertWarrning('NO UTXOS'); - } else { - utxos = isCBOR() ? mapCborUtxos(utxosResponse) : utxosResponse; - alertSuccess( - `

UTxO (${utxos.length}):

` + JSON.stringify(utxos, undefined, 2) + '
' - ); - } - }); -}; - -getUtxos.addEventListener('click', () => { - window._getUtxos(); -}); - -submitTx.addEventListener('click', () => { - if (!accessGranted) { - alertError('Should request access first'); - return; - } - if (!transactionHex) { - alertError('Should sign tx first'); - return; - } - - toggleSpinner('show'); - cardanoApi - .submitTx(transactionHex) - .then(txId => { - toggleSpinner('hide'); - alertSuccess(`Transaction ${txId} submitted`); - }) - .catch(error => { - toggleSpinner('hide'); - alertWarrning(`Transaction submission failed: ${JSON.stringify(error)}`); - }); -}); - -const AMOUNT_TO_SEND = '1000000'; -const SEND_TO_ADDRESS = - 'addr_test1qz8xh9w6f2vdnp89xzqlxnusldhz6kdm4rp970gl8swwjjkr3y3kdut55a40jff00qmg74686vz44v6k363md06qkq0q4lztj0'; - -signTx.addEventListener('click', () => { - toggleSpinner('show'); - - if (!accessGranted) { - alertError('Should request access first'); - return; - } - - if (!unsignedTransactionHex) { - if (!utxos) { - alertError('Should request utxos first'); - return; - } - - if (!changeAddress) { - alertError('Should request change address first'); - } - - const txBuilder = CardanoWasm.TransactionBuilder.new( - CardanoWasm.TransactionBuilderConfigBuilder.new() - // all of these are taken from the mainnet genesis settings - // linear fee parameters (a*size + b) - .fee_algo( - CardanoWasm.LinearFee.new( - CardanoWasm.BigNum.from_str('44'), - CardanoWasm.BigNum.from_str('155381') - ) - ) - .coins_per_utxo_word(CardanoWasm.BigNum.from_str('34482')) - .pool_deposit(CardanoWasm.BigNum.from_str('500000000')) - .key_deposit(CardanoWasm.BigNum.from_str('2000000')) - .max_value_size(5000) - .max_tx_size(16384) - .build() - ); - - // add a keyhash input - for ADA held in a Shelley-era normal address (Base, Enterprise, Pointer) - const utxo = utxos[0]; - - const addr = CardanoWasm.Address.from_bech32(utxo.receiver); - - const baseAddr = CardanoWasm.BaseAddress.from_address(addr); - const keyHash = baseAddr.payment_cred().to_keyhash(); - txBuilder.add_key_input( - keyHash, - CardanoWasm.TransactionInput.new( - CardanoWasm.TransactionHash.from_bytes(hexToBytes(utxo.tx_hash)), // tx hash - utxo.tx_index // index - ), - CardanoWasm.Value.new(CardanoWasm.BigNum.from_str(utxo.amount)) - ); - - const shelleyOutputAddress = CardanoWasm.Address.from_bech32(SEND_TO_ADDRESS); - const shelleyChangeAddress = CardanoWasm.Address.from_bech32(changeAddress); - - // add output to the tx - txBuilder.add_output( - CardanoWasm.TransactionOutput.new( - shelleyOutputAddress, - CardanoWasm.Value.new(CardanoWasm.BigNum.from_str(AMOUNT_TO_SEND)) - ) - ); - - const ttl = getTtl(); - txBuilder.set_ttl(ttl); - - // calculate the min fee required and send any change to an address - txBuilder.add_change_if_needed(shelleyChangeAddress); - - unsignedTransactionHex = bytesToHex(txBuilder.build_tx().to_bytes()); - } - - // Experimental feature, false by default, in which case only the witness set is returned. - const returnTx = true; - - cardanoApi - .signTx({ - tx: unsignedTransactionHex, - returnTx, - }) - .then(responseHex => { - toggleSpinner('hide'); - console.log(`[signTx] response: ${responseHex}`); - - if (returnTx) { - const signedTx = CardanoWasm.Transaction.from_bytes(hexToBytes(responseHex)); - const wit = signedTx.witness_set(); - - const wkeys = wit.vkeys(); - for (let i = 0; i < wkeys.len(); i++) { - const wk = wkeys.get(i); - const vk = wk.vkey(); - console.log(`[signTx] wit vkey ${i}:`, { - vkBytes: bytesToHex(vk.to_bytes()), - vkPubBech: vk.public_key().to_bech32(), - vkPubHashBech: vk.public_key().hash().to_bech32(Bech32Prefix.PAYMENT_KEY_HASH), - }); - } - - transactionHex = responseHex; - } else { - const witnessSet = CardanoWasm.TransactionWitnessSet.from_bytes(hexToBytes(responseHex)); - const tx = CardanoWasm.Transaction.from_bytes(hexToBytes(unsignedTransactionHex)); - const transaction = CardanoWasm.Transaction.new(tx.body(), witnessSet, tx.auxiliary_data()); - transactionHex = bytesToHex(transaction.to_bytes()); - } - - unsignedTransactionHex = null; - alertSuccess('Signing tx succeeded: ' + transactionHex); - }) - .catch(error => { - console.error(error); - toggleSpinner('hide'); - alertWarrning('Signing tx fails'); - }); -}); - -createTx.addEventListener('click', () => { - toggleSpinner('show'); - - if (!accessGranted) { - alertError('Should request access first'); - return; - } - - if (!utxos || utxos.length === 0) { - alertError('Should request utxos first'); - return; - } - - if (!usedAddresses || usedAddresses.length === 0) { - alertError('Should request used addresses first'); - return; - } - - const randomUtxo = utxos[Math.floor(Math.random() * utxos.length)]; - if (!randomUtxo) { - alertError('Failed to select a random utxo from the available list!'); - return; - } - - console.log('[createTx] Including random utxo input: ', randomUtxo); - - const usedAddress = usedAddresses[0]; - const keyHash = CardanoWasm.BaseAddress.from_address(CardanoWasm.Address.from_bech32(usedAddress)) - .payment_cred() - .to_keyhash(); - - const keyHashBech = keyHash.to_bech32(Bech32Prefix.PAYMENT_KEY_HASH); - - const scripts = CardanoWasm.NativeScripts.new(); - scripts.add(CardanoWasm.NativeScript.new_script_pubkey(CardanoWasm.ScriptPubkey.new(keyHash))); - scripts.add(CardanoWasm.NativeScript.new_timelock_start(CardanoWasm.TimelockStart.new(42))); - - const mintScript = CardanoWasm.NativeScript.new_script_all(CardanoWasm.ScriptAll.new(scripts)); - const mintScriptHex = bytesToHex(mintScript.to_bytes()); - - function convertAssetNameToHEX(name) { - return bytesToHex(name); - } - - const tokenAssetName = 'V42'; - const nftAssetName = `V42/NFT#${Math.floor(Math.random() * 1000000000)}`; - const tokenAssetNameHex = convertAssetNameToHEX(tokenAssetName); - const nftAssetNameHex = convertAssetNameToHEX(nftAssetName); - - const expectedPolicyId = bytesToHex(mintScript.hash().to_bytes()); - - console.log('[createTx] Including mint request: ', { - keyHashBech, - mintScriptHex, - assetNameHex: tokenAssetNameHex, - expectedPolicyId, - }); - - const outputHex = bytesToHex( - CardanoWasm.TransactionOutput.new( - CardanoWasm.Address.from_bech32(randomUtxo.receiver), - CardanoWasm.Value.new(CardanoWasm.BigNum.from_str('1000000')) - ).to_bytes() - ); - - const includeInputs = []; - const includeOutputs = []; - const includeTargets = []; - - let targetAddress = randomUtxo.receiver; - let targetDataHash = null; - - /****** FLAGS ******/ - let includeDefaultInputs = true; - let includeDefaultOutputs = true; - let includeDefaultTargets = true; - let includeAssetTargets = true; - //-----------------// - const nativeScriptInputUtxoId = null; - const plutusScriptInputUtxoId = null; - const createPlutusTarget = false; - /****** ******/ - - if (includeDefaultInputs) { - includeInputs.push(randomUtxo.utxo_id); - } - - // noinspection StatementWithEmptyBodyJS - if (includeDefaultOutputs) { - includeOutputs.push(outputHex); - } - - // noinspection PointlessBooleanExpressionJS - if (nativeScriptInputUtxoId != null) { - const nscripts = CardanoWasm.NativeScripts.new(); - nscripts.add(CardanoWasm.NativeScript.new_timelock_start(CardanoWasm.TimelockStart.new(1234))); - nscripts.add(CardanoWasm.NativeScript.new_timelock_start(CardanoWasm.TimelockStart.new(1))); - const nativeScript = CardanoWasm.NativeScript.new_script_all( - CardanoWasm.ScriptAll.new(nscripts) - ); - - const scriptHash = nativeScript.hash(); - console.log(`[createTx] Native script hash: ${bytesToHex(scriptHash.to_bytes())}`); - const nativeScriptAddress = CardanoWasm.EnterpriseAddress.new( - 0, - CardanoWasm.StakeCredential.from_scripthash(scriptHash) - ) - .to_address() - .to_bech32(); - console.log(`[createTx] Native script address: ${nativeScriptAddress}`); - - includeInputs.push({ - id: nativeScriptInputUtxoId, - witness: { - nativeScript: bytesToHex(nativeScript.to_bytes()), - }, - }); - } - - // noinspection PointlessBooleanExpressionJS - if (plutusScriptInputUtxoId != null || createPlutusTarget) { - const plutusScript = CardanoWasm.PlutusScript.from_bytes( - hexToBytes('4e4d01000033222220051200120011') - ); - - const plutusScriptHash = plutusScript.hash(); - console.log(`[createTx] Plutus script hash: ${bytesToHex(plutusScriptHash.to_bytes())}`); - const plutusScriptAddress = CardanoWasm.EnterpriseAddress.new( - 0, - CardanoWasm.StakeCredential.from_scripthash(plutusScriptHash) - ) - .to_address() - .to_bech32(); - console.log(`[createTx] Plutus script address: ${plutusScriptAddress}`); - - const datum = CardanoWasm.PlutusData.new_empty_constr_plutus_data(CardanoWasm.BigNum.zero()); - const datumHash = bytesToHex(CardanoWasm.hash_plutus_data(datum).to_bytes()); - console.log(`[createTx] Plutus datum hash: ${datumHash}`); - - if (createPlutusTarget) { - targetAddress = plutusScriptAddress; - targetDataHash = datumHash; - } - - // noinspection PointlessBooleanExpressionJS - if (plutusScriptInputUtxoId != null) { - const redeemer = CardanoWasm.Redeemer.new( - CardanoWasm.RedeemerTag.new_spend(), - CardanoWasm.BigNum.zero(), - CardanoWasm.PlutusData.new_empty_constr_plutus_data(CardanoWasm.BigNum.zero()), - CardanoWasm.ExUnits.new( - CardanoWasm.BigNum.from_str('1700'), - CardanoWasm.BigNum.from_str('476468') - ) - ); - - includeInputs.push({ - id: plutusScriptInputUtxoId, - witness: { - plutusScript: bytesToHex(plutusScript.to_bytes()), - datum: bytesToHex(datum.to_bytes()), - redeemer: bytesToHex(redeemer.to_bytes()), - }, - }); - } - } - - if (includeDefaultTargets) { - includeTargets.push({ - address: targetAddress, - value: '2000000', - dataHash: targetDataHash, - mintRequest: [ - { - script: mintScriptHex, - assetName: tokenAssetNameHex, - amount: '42', - }, - { - script: mintScriptHex, - storeScriptOnChain: true, - assetName: nftAssetNameHex, - metadata: { - tag: 721, - json: JSON.stringify({ - name: nftAssetName, - description: `V42 NFT Collection`, - mediaType: 'image/png', - image: 'ipfs://QmRhTTbUrPYEw3mJGGhQqQST9k86v1DPBiTTWJGKDJsVFw', - files: [ - { - name: nftAssetName, - mediaType: 'image/png', - src: 'ipfs://QmRhTTbUrPYEw3mJGGhQqQST9k86v1DPBiTTWJGKDJsVFw', - }, - ], - }), - }, - }, - ], - }); - } - - const txReq = { - validityIntervalStart: 2000, - includeInputs, - includeOutputs, - includeTargets, - }; - - if (includeAssetTargets) { - const utxosWithAssets = utxos.filter(u => u.assets.length > 0); - const utxoWithAssets = utxosWithAssets[Math.floor(Math.random() * utxosWithAssets.length)]; - - if (utxoWithAssets) { - const asset = utxoWithAssets.assets[0]; - console.log('[createTx] Including asset:', asset); - txReq.includeTargets.push({ - // do not specify value, the connector will use minimum value - address: randomUtxo.receiver, - assets: { - [asset.assetId]: '1', - }, - ensureRequiredMinimalValue: true, - }); - } - } - - cardanoApi.experimental - .createTx(txReq, true) - .then(txHex => { - toggleSpinner('hide'); - alertSuccess('Creating tx succeeds: ' + txHex); - unsignedTransactionHex = txHex; - }) - .catch(error => { - console.error(error); - toggleSpinner('hide'); - alertWarrning('Creating tx fails'); - }); -}); - -getCollateralUtxos.addEventListener('click', () => { - toggleSpinner('show'); - - if (!accessGranted) { - alertError('Should request access first'); - return; - } - - const amount = '4900000'; - cardanoApi - .getCollateralUtxos( - Buffer.from(CardanoWasm.Value.new(CardanoWasm.BigNum.from_str(amount)).to_bytes()).toString( - 'hex' - ) - ) - .then(utxosResponse => { - toggleSpinner('hide'); - let utxos = isCBOR() ? mapCborUtxos(utxosResponse) : utxosResponse; - alertSuccess( - `

Collateral UTxO (${utxos.length}):

` +
-          JSON.stringify(utxos, undefined, 2) +
-          '
' - ); - }) - .catch(error => { - console.error(error); - toggleSpinner('hide'); - alertWarrning(`Getting collateral UTXOs tx fails: ${JSON.stringify(error)}`); - }); -}); - -signData.addEventListener('click', () => { - toggleSpinner('show'); - - if (!accessGranted) { - alertError('Should request access first'); - return; - } - - let address; - if (usedAddresses && usedAddresses.length > 0) { - address = usedAddresses[0]; - } else if (unusedAddresses && unusedAddresses.length > 0) { - address = unusedAddresses[0]; - } else { - alertError('Should request used or unused addresses first'); - return; - } - - if (isCBOR()) { - address = addressToCbor(address); - } - - const payload = document.querySelector('#sign-data-payload').value; - let payloadHex; - if (payload.startsWith('0x')) { - payloadHex = Buffer.from(payload.replace('^0x', ''), 'hex').toString('hex'); - } else { - payloadHex = Buffer.from(payload, 'utf8').toString('hex'); - } - - console.log('[signData][address] ', address); - cardanoApi - .signData(address, payloadHex) - .then(sig => { - alertSuccess('Signature:' + JSON.stringify(sig)); - }) - .catch(error => { - console.error(error); - alertError(error.info); - }) - .then(() => { - toggleSpinner('hide'); - }); -}); - -getNFTs.addEventListener('click', async () => { - toggleSpinner('show'); - - if (!accessGranted) { - alertError('Should request access first'); - return; - } - - try { - const response = await cardanoApi.experimental.listNFTs(); - renderJonsResponse(`NFTs (${Object.keys(response).length})`, response); - } catch (error) { - console.error(error); - alertError(error.message); - } - toggleSpinner('hide'); -}) - -function alertError(text) { - toggleSpinner('hide'); - alertEl.className = 'alert alert-danger'; - alertEl.innerHTML = text; -} - -function alertSuccess(text) { - alertEl.className = 'alert alert-success'; - alertEl.innerHTML = text; -} - -function alertWarrning(text) { - alertEl.className = 'alert alert-warning'; - alertEl.innerHTML = text; -} - -function renderJonsResponse (title, response) { - alertSuccess( - `

${title}:

` + JSON.stringify(response, undefined, 2) + '
' - ) -} - -function toggleSpinner(status) { - if (status === 'show') { - spinner.className = 'spinner-border'; - alertEl.className = 'd-none'; - } else { - spinner.className = 'd-none'; - } -} - -function toggleConnectionUI(status) { - if (status === 'button') { - connectionStatus.classList.add('d-none'); - cardanoAccessBtnRow.classList.remove('d-none'); - } else { - cardanoAccessBtnRow.classList.add('d-none'); - connectionStatus.classList.remove('d-none'); - } -} - -function isWasm(o) { - return o.ptr != null && o.free != null; -} - -function WasmScope(cb) { - let scope = []; - function prox(x) { - return typeof x === 'object' || typeof x === 'function' ? new Proxy(x, { - get(target, name, receiver) { - let rv = Reflect.get(target, name, receiver); - if (typeof rv !== 'function' || rv.prototype != null) { - return prox(rv); - } - return function(...args) { - const res = rv.bind(x)(...args); - if (isWasm(res)) { - scope.push(res); - } - return prox(res); - } - } - }) : x; - } - let result = cb(prox(CardanoWasm)); - scope.forEach(x => x.free()); - console.log(`[WasmScope] freed objects:`, scope.length); - if (isWasm(result)) { - throw new Error('A wasm object cannot be returned from wasm scope'); - } - return result; -} - -function wfree(...args) { - args.forEach(x => x.free()); -} - -function foo1() { - return WasmScope(Wasm => { - return Wasm.BigNum.from_str('1000000') - .checked_add(Wasm.BigNum.from_str('2000000')) - .to_str(); - }); -} - -function foo12() { - WasmScope(Wasm => { - return Wasm.TransactionBuilderConfigBuilder.new() - .max_value_size(123456) - .max_tx_size(234567) - .pool_deposit(Wasm.BigNum.from_str('123')); - }); -} - -function foo2() { - for (let i = 0; i < 1000; i++) { - setInterval(() => { - let arr = []; - for (let i = 0; i < 1000; i++) { - const a = CardanoWasm.BigNum.from_str('72'); - const b = CardanoWasm.BigNum.from_str('1000'); - const c = CardanoWasm.BigNum.from_str('172'); - const d = CardanoWasm.BigNum.from_str('10000'); - const e = CardanoWasm.UnitInterval.new(a, b); - const f = CardanoWasm.UnitInterval.new(c, d); - const g = CardanoWasm.BigNum.from_str('172000'); - const h = CardanoWasm.BigNum.from_str('123456'); - const i = CardanoWasm.BigNum.from_str('44000'); - const j = CardanoWasm.LinearFee.new(h, i); - const k = CardanoWasm.BigNum.from_str('2000000'); - const l = CardanoWasm.ExUnitPrices.new(e, f); - const m = CardanoWasm.BigNum.from_str('4000000'); - let config = CardanoWasm.TransactionBuilderConfigBuilder.new() - .ex_unit_prices(l) - .coins_per_utxo_byte(g) - .fee_algo(j) - .key_deposit(k) - .pool_deposit(m) - .max_tx_size(123456765) - .max_value_size(123456765) - .build(); - let builder = CardanoWasm.TransactionBuilder.new(config); - arr.push(builder); - wfree(a, b, c, d, e, f, g, h, i, j, k, l, m, config); - } - console.log(arr.length); - arr.forEach(x => x.free()); - }, 1000); - } -} - -function foo3() { - for (let i = 0; i < 1000; i++) { - setInterval(() => { - WasmScope(CardanoWasm => { - let arr = []; - for (let i = 0; i < 1000; i++) { - let config = CardanoWasm.TransactionBuilderConfigBuilder.new() - .ex_unit_prices(CardanoWasm.ExUnitPrices.new( - CardanoWasm.UnitInterval.new( - CardanoWasm.BigNum.from_str('72'), - CardanoWasm.BigNum.from_str('1000'), - ), - CardanoWasm.UnitInterval.new( - CardanoWasm.BigNum.from_str('172'), - CardanoWasm.BigNum.from_str('10000'), - ))) - .coins_per_utxo_byte(CardanoWasm.BigNum.from_str('172000')) - .fee_algo(CardanoWasm.LinearFee.new( - CardanoWasm.BigNum.from_str('123456'), - CardanoWasm.BigNum.from_str('44000'), - )) - .key_deposit(CardanoWasm.BigNum.from_str('2000000')) - .pool_deposit(CardanoWasm.BigNum.from_str('4000000')) - .max_tx_size(123456765) - .max_value_size(123456765) - .build(); - let builder = CardanoWasm.TransactionBuilder.new(config); - arr.push(builder); - } - console.log(arr.length); - }); - }, 1000); - } -} - -function onload() { - foo12(); - if (typeof window.cardano === 'undefined') { - alertError('Cardano API not found'); - } else { - console.log('Cardano API detected, checking connection status'); - cardano.yoroi.enable({ requestIdentification: true, onlySilent: true }).then( - api => { - console.log('successful silent reconnection'); - onApiConnectied(api); - }, - err => { - if (String(err).includes('onlySilent:fail')) { - console.log('no silent re-connection available'); - } else { - console.error('Silent reconnection failed for unknown reason!', err); - } - toggleSpinner('hide'); - toggleConnectionUI('button'); - } - ); - } -} -setTimeout(onload, 1000); \ No newline at end of file diff --git a/packages/yoroi-extension/app/api/ada/lib/cardanoCrypto/rustLoader.js b/packages/yoroi-extension/app/api/ada/lib/cardanoCrypto/rustLoader.js index da5730b5ba..23893fa1b9 100644 --- a/packages/yoroi-extension/app/api/ada/lib/cardanoCrypto/rustLoader.js +++ b/packages/yoroi-extension/app/api/ada/lib/cardanoCrypto/rustLoader.js @@ -13,6 +13,10 @@ const MAX_TX_BYTES = 16384; type RustModuleLoadFlags = 'dontLoadMessagesSigning'; +function isWasmPointer(o: any): boolean { + return o.ptr != null && o.free != null; +} + class Module { _wasmv2: WasmV2; _wasmv3: WasmV3; @@ -39,6 +43,66 @@ class Module { } } + /** + * The argument to this function is an async callback. + * The callback will receive a link to the `RustModule` class. + * Any wasm pointer created within the callback will be automatically destroyed + * after the callback ends, but only if it was created using the passed module. + * + * NOTE: If you use an external module reference to create wasm objects within the callback, + * then they will not be able to get intercepted and removed. + * + * NOTE: The return from the callback will be returned from this function call, + * BUT the result cannot be a wasm object as all pointers are getting destroyed + * before this function returns. If the result will be detected to be a wasm pointer, + * an exception will be raised. + */ + async WasmScope(callback: Module => Promise): Promise { + /* + * The main idea here is that we create a proxy of some root object (module itself) + * and then we intercept every single field-getting access, including all functions, + * and we check if the result of the function call is a Wasm pointer object. + * If we detect a pointer - we add it into the tracked scope and free at the end of the call. + * This way ANY wasm pointer produced within the callback will be automatically destroyed, + * but only as long as it's created using the injected proxied module reference. + */ + const scope = []; + function recursiveProxy(originalObject: E): E { + const proxyHandler: Proxy$traps = { + // We are intercepting when any field is trying to be accessed on the original object + get(target: E, name: string, receiver: Proxy): any { + // Get the actual field value from the original object + const realValue = Reflect.get(target, name, receiver); + /* If the real value of the field is not a function, + * then we just want to recursively wrap it in a same proxy. + */ + if (typeof realValue !== 'function' || realValue.prototype != null) { + return recursiveProxy(realValue); + } + return function(...args: any[]): any { + const res = realValue.bind(originalObject)(...args); + if (isWasmPointer(res)) { + scope.push(res); + } + return recursiveProxy(res); + } + } + }; + // We only proxy objects and functions, the check is mostly for primitive values + return typeof originalObject === 'object' || typeof originalObject === 'function' + ? new Proxy(originalObject, proxyHandler) : originalObject; + } + // We are proxying the `RustModule` itself to pass it into the callback. + // Note that we create a new proxy every time, because each proxy instance + // is linked to the specific scope that will be destroyed. + const result = await callback(recursiveProxy(Module)); + scope.forEach(x => x.free()); + if (isWasmPointer(result)) { + throw new Error('A wasm object cannot be returned from wasm scope, all pointers are destroyed.'); + } + return result; + } + // Need to expose through a getter to get Flow to detect the type correctly get WalletV2(): WasmV2 { return this._wasmv2; From 6866f10dc0bc5961f9b6e7266ccbada9a1b48405 Mon Sep 17 00:00:00 2001 From: Ahmed Ibrahim Date: Mon, 9 Jan 2023 16:45:00 +0200 Subject: [PATCH 099/172] Add getLastSelectedWallet method & fix flow --- .../categories/GeneralSettingsPage.js | 21 ++++++++++++---- .../app/containers/wallet/MyWalletsPage.js | 4 +++- .../wallet/MyWalletsPage.stories.js | 1 + .../app/containers/wallet/Wallet.js | 24 +++++++++++++------ .../app/containers/wallet/Wallet.mock.js | 9 +++++-- .../app/stores/toplevel/TokenInfoStore.js | 2 +- .../app/stores/toplevel/WalletStore.js | 17 ++++++------- 7 files changed, 52 insertions(+), 26 deletions(-) diff --git a/packages/yoroi-extension/app/containers/settings/categories/GeneralSettingsPage.js b/packages/yoroi-extension/app/containers/settings/categories/GeneralSettingsPage.js index e53acc72bd..53bdd3c9d0 100644 --- a/packages/yoroi-extension/app/containers/settings/categories/GeneralSettingsPage.js +++ b/packages/yoroi-extension/app/containers/settings/categories/GeneralSettingsPage.js @@ -12,7 +12,8 @@ import AboutYoroiSettingsBlock from '../../../components/settings/categories/gen import UnitOfAccountSettings from '../../../components/settings/categories/general-setting/UnitOfAccountSettings'; import LocalizableError from '../../../i18n/LocalizableError'; import type { LanguageType } from '../../../i18n/translations'; -import { Theme, THEMES } from '../../../styles/utils'; +import { THEMES } from '../../../styles/utils'; +import type { Theme } from '../../../styles/utils'; import { PublicDeriver } from '../../../api/ada/lib/storage/models/PublicDeriver'; import { ReactComponent as AdaCurrency } from '../../../assets/images/currencies/ADA.inline.svg'; import { unitOfAccountDisabledValue } from '../../../types/unitOfAccountType'; @@ -129,13 +130,14 @@ export default class GeneralSettingsPage extends Component { if (theme === THEMES.YOROI_REVAMP) { - const publicDeriver = this.generated.stores.wallets.selected; - const publicDerivers = this.generated.stores.wallets.publicDerivers; + const { wallets } = this.generated.stores; + const publicDeriver = wallets.selected; + const publicDerivers = wallets.publicDerivers; if (publicDeriver == null && publicDerivers.length !== 0) { + const lastSelectedWallet = wallets.getLastSelectedWallet(); this.generated.actions.wallets.setActiveWallet.trigger({ - wallet: publicDerivers[0], - formCacheFirst: true, + wallet: lastSelectedWallet ?? publicDerivers[0], }); } } @@ -178,6 +180,13 @@ export default class GeneralSettingsPage extends Component void, |}, |}, + wallets: {| + setActiveWallet: {| + trigger: (params: {| + wallet: PublicDeriver<>, + |}) => void, + |}, + |}, |}, stores: {| app: {| currentRoute: string |}, @@ -202,6 +211,7 @@ export default class GeneralSettingsPage extends Component, publicDerivers: Array>, + getLastSelectedWallet: void => ?PublicDeriver<>, |}, coinPriceStore: {| getCurrentPrice: ( @@ -244,6 +254,7 @@ export default class GeneralSettingsPage extends Component { |}, wallets: {| unselectWallet: {| trigger: (params: void) => void |}, - setActiveWallet: {| trigger: (params: {| wallet: PublicDeriver<> |}) => void |}, + setActiveWallet: {| trigger: (params: {| + wallet: PublicDeriver<>, + |}) => void |}, |}, |}, stores: {| diff --git a/packages/yoroi-extension/app/containers/wallet/MyWalletsPage.stories.js b/packages/yoroi-extension/app/containers/wallet/MyWalletsPage.stories.js index be829b9c0e..f1536829ca 100644 --- a/packages/yoroi-extension/app/containers/wallet/MyWalletsPage.stories.js +++ b/packages/yoroi-extension/app/containers/wallet/MyWalletsPage.stories.js @@ -98,6 +98,7 @@ const genBaseProps: {| stores: { profile: { shouldHideBalance: false, + isRevampTheme: false, }, wallets: { publicDerivers: request.publicDerivers, diff --git a/packages/yoroi-extension/app/containers/wallet/Wallet.js b/packages/yoroi-extension/app/containers/wallet/Wallet.js index d7f98b03d0..e4cb462450 100644 --- a/packages/yoroi-extension/app/containers/wallet/Wallet.js +++ b/packages/yoroi-extension/app/containers/wallet/Wallet.js @@ -54,15 +54,16 @@ class Wallet extends Component { }; componentDidMount() { - const publicDeriver = this.generated.stores.wallets.selected; - const publicDerivers = this.generated.stores.wallets.publicDerivers; + const { wallets } = this.generated.stores; + const publicDeriver = wallets.selected; + const publicDerivers = wallets.publicDerivers; const isRevamp = this.generated.stores.profile.isRevampTheme; if (publicDeriver == null && isRevamp && publicDerivers.length !== 0) { + const lastSelectedWallet = wallets.getLastSelectedWallet(); this.generated.actions.wallets.setActiveWallet.trigger({ - wallet: publicDerivers[0], - formCacheFirst: true, - }) + wallet: lastSelectedWallet ?? publicDerivers[0], + }); } // reroute to the default path for the wallet @@ -83,7 +84,7 @@ class Wallet extends Component { // void -> this route is fine for this wallet type // string -> what you should be redirected to const publicDeriver = this.generated.stores.wallets.selected; - if (publicDeriver == null && !isRevamp) throw new Error(`${nameof(Wallet)} no public deriver`); + if (publicDeriver == null) return; const spendableBalance = this.generated.stores.transactions.getBalanceRequest.result; const walletHasAssets = !!(spendableBalance?.nonDefaultEntries().length); @@ -104,7 +105,6 @@ class Wallet extends Component { } return firstValidCategory.route; } - return undefined; } navigateToMyWallets: string => void = destination => { @@ -263,6 +263,13 @@ class Wallet extends Component { |}) => void, |}, |}, + wallets: {| + setActiveWallet: {| + trigger: (params: {| + wallet: PublicDeriver<>, + |}) => void, + |}, + |}, |}, stores: {| app: {| currentRoute: string |}, @@ -271,7 +278,9 @@ class Wallet extends Component { |}, wallets: {| selected: null | PublicDeriver<>, + publicDerivers: Array>, firstSync: ?number, + getLastSelectedWallet: void => ?PublicDeriver<>, |}, router: {| location: any |}, transactions: {| @@ -302,6 +311,7 @@ class Wallet extends Component { selected: stores.wallets.selected, publicDerivers: stores.wallets.publicDerivers, firstSync: stores.wallets.firstSync, + getLastSelectedWallet: stores.wallets.getLastSelectedWallet, }, walletSettings: { getWalletWarnings: settingStore.getWalletWarnings, diff --git a/packages/yoroi-extension/app/containers/wallet/Wallet.mock.js b/packages/yoroi-extension/app/containers/wallet/Wallet.mock.js index ec2485738e..7bda93871b 100644 --- a/packages/yoroi-extension/app/containers/wallet/Wallet.mock.js +++ b/packages/yoroi-extension/app/containers/wallet/Wallet.mock.js @@ -13,7 +13,6 @@ import WalletStore from '../../stores/toplevel/WalletStore'; import type { GeneratedData } from './Wallet'; import { mockFromDefaults, getDefaultEntryTokenInfo, } from '../../stores/toplevel/TokenInfoStore'; import { defaultAssets, } from '../../api/ada/lib/storage/database/prepackaged/networks'; -import { THEMES } from '../../styles/utils'; export const mockWalletProps: { selected: null | PublicDeriver<>, @@ -37,11 +36,14 @@ export const mockWalletProps: { currentRoute: request.location, }, profile: { - currentTheme: THEMES.YOROI_CLASSIC, + isRevampTheme: false, + isClassicTheme: false, }, wallets: { selected: request.selected, + publicDerivers: request.selected ? [request.selected] : [], firstSync: null, + getLastSelectedWallet: () => request.selected, }, transactions: { getBalanceRequest: { @@ -62,6 +64,9 @@ export const mockWalletProps: { goToRoute: { trigger: action('goToRoute') }, redirect: { trigger: action('redirect') }, }, + wallets: { + setActiveWallet: { trigger: action('setActiveWallet') } + } }, SidebarContainerProps: { generated: { diff --git a/packages/yoroi-extension/app/stores/toplevel/TokenInfoStore.js b/packages/yoroi-extension/app/stores/toplevel/TokenInfoStore.js index 77da714681..1da6bf12be 100644 --- a/packages/yoroi-extension/app/stores/toplevel/TokenInfoStore.js +++ b/packages/yoroi-extension/app/stores/toplevel/TokenInfoStore.js @@ -71,7 +71,7 @@ export default class TokenInfoStore< setup(): void { super.setup(); this.tokenInfo = new Map(); - // the Ergo connector doesn't have this action + // the connector doesn't have this action if (this.actions.wallets?.setActiveWallet) { this.actions.wallets.setActiveWallet.listen( ({ wallet }) => { this.fetchMissingTokenInfoForWallet(wallet) } diff --git a/packages/yoroi-extension/app/stores/toplevel/WalletStore.js b/packages/yoroi-extension/app/stores/toplevel/WalletStore.js index 91e29028a2..8a0677eb27 100644 --- a/packages/yoroi-extension/app/stores/toplevel/WalletStore.js +++ b/packages/yoroi-extension/app/stores/toplevel/WalletStore.js @@ -375,20 +375,17 @@ export default class WalletStore extends Store { // =================== ACTIVE WALLET ==================== // - @action _setActiveWallet: ({| wallet: PublicDeriver<>, formCacheFirst?: boolean |}) => void = - ({ wallet, formCacheFirst }) => { - const lastSelectedWallet = this._getLastSelectedWallet(); - const walletToSelect = formCacheFirst && lastSelectedWallet ? lastSelectedWallet : wallet; - - this.actions.profile.setSelectedNetwork.trigger(walletToSelect.getParent().getNetworkInfo()); - this.selected = walletToSelect; + @action _setActiveWallet: ({| wallet: PublicDeriver<> |}) => void = + ({ wallet }) => { + this.actions.profile.setSelectedNetwork.trigger(wallet.getParent().getNetworkInfo()); + this.selected = wallet; // Cache select wallet - this.api.localStorage.setSelectedWalletId(walletToSelect.getPublicDeriverId()) + this.api.localStorage.setSelectedWalletId(wallet.getPublicDeriverId()) // do not await on purpose since the UI will handle adding loaders while refresh is happening - this.refreshWalletFromRemote(walletToSelect); + this.refreshWalletFromRemote(wallet); }; - _getLastSelectedWallet: void => ?PublicDeriver<> = () => { + getLastSelectedWallet: void => ?PublicDeriver<> = () => { const walletId = this.api.localStorage.getSelectedWalletId(); return this.publicDerivers.find(pd => pd.getPublicDeriverId() === walletId); } From 55af39c2998269853fb679fccb06e43ab61f773b Mon Sep 17 00:00:00 2001 From: vantuz-subhuman Date: Mon, 9 Jan 2023 18:52:08 +0300 Subject: [PATCH 100/172] Extracting proxy handler as static per scope --- .../api/ada/lib/cardanoCrypto/rustLoader.js | 67 ++++++++++++------- packages/yoroi-extension/package-lock.json | 50 +++++++------- 2 files changed, 66 insertions(+), 51 deletions(-) diff --git a/packages/yoroi-extension/app/api/ada/lib/cardanoCrypto/rustLoader.js b/packages/yoroi-extension/app/api/ada/lib/cardanoCrypto/rustLoader.js index 23893fa1b9..7cf77ff5a4 100644 --- a/packages/yoroi-extension/app/api/ada/lib/cardanoCrypto/rustLoader.js +++ b/packages/yoroi-extension/app/api/ada/lib/cardanoCrypto/rustLoader.js @@ -2,8 +2,12 @@ import typeof * as WasmV2 from 'cardano-wallet-browser'; import typeof * as WasmV3 from '@emurgo/js-chain-libs/js_chain_libs'; +import type { + BigNum, + LinearFee, + TransactionBuilder +} from '@emurgo/cardano-serialization-lib-browser/cardano_serialization_lib'; import typeof * as WasmV4 from '@emurgo/cardano-serialization-lib-browser/cardano_serialization_lib'; -import type { BigNum, LinearFee, TransactionBuilder } from '@emurgo/cardano-serialization-lib-browser/cardano_serialization_lib'; import typeof * as SigmaRust from 'ergo-lib-wasm-browser'; import typeof * as WasmMessageSigning from '@emurgo/cardano-message-signing-browser/cardano_message_signing'; @@ -13,8 +17,8 @@ const MAX_TX_BYTES = 16384; type RustModuleLoadFlags = 'dontLoadMessagesSigning'; -function isWasmPointer(o: any): boolean { - return o.ptr != null && o.free != null; +function isWasmPointer(o: ?any): boolean { + return o != null && o.ptr != null && o.free != null; } class Module { @@ -67,35 +71,46 @@ class Module { * but only as long as it's created using the injected proxied module reference. */ const scope = []; - function recursiveProxy(originalObject: E): E { - const proxyHandler: Proxy$traps = { - // We are intercepting when any field is trying to be accessed on the original object - get(target: E, name: string, receiver: Proxy): any { - // Get the actual field value from the original object - const realValue = Reflect.get(target, name, receiver); - /* If the real value of the field is not a function, - * then we just want to recursively wrap it in a same proxy. - */ - if (typeof realValue !== 'function' || realValue.prototype != null) { - return recursiveProxy(realValue); - } - return function(...args: any[]): any { - const res = realValue.bind(originalObject)(...args); - if (isWasmPointer(res)) { - scope.push(res); - } - return recursiveProxy(res); + const proxyHandler: Proxy$traps = { + // We are intercepting when any field is trying to be accessed on the original object + get(target: E, name: string, receiver: Proxy): any { + if (name === '____is_wasm_proxy') { + return true; + } + // Get the actual field value from the original object + const realValue = Reflect.get(target, name, receiver); + if (name === 'prototype') { + return realValue; + } + /* If the real value of the field is not a function, + * then we just want to recursively wrap it in a same proxy. + */ + if (typeof realValue !== 'function' || realValue.prototype != null) { + return recursiveProxy(realValue); + } + return function(...args: any[]): any { + const res = realValue.bind(target)(...args); + if (isWasmPointer(res)) { + scope.push(res); } + return recursiveProxy(res); + } + } + }; + function recursiveProxy(originalObject: E): E { + // Make sure the original object is not already a proxy + if (originalObject.____is_wasm_proxy !== true) { + // We only proxy objects and functions, the check is mostly for primitive values + if (typeof originalObject === 'object' || typeof originalObject === 'function') { + return new Proxy(originalObject, proxyHandler); } - }; - // We only proxy objects and functions, the check is mostly for primitive values - return typeof originalObject === 'object' || typeof originalObject === 'function' - ? new Proxy(originalObject, proxyHandler) : originalObject; + } + return originalObject; } // We are proxying the `RustModule` itself to pass it into the callback. // Note that we create a new proxy every time, because each proxy instance // is linked to the specific scope that will be destroyed. - const result = await callback(recursiveProxy(Module)); + const result = await callback(recursiveProxy(RustModule)); scope.forEach(x => x.free()); if (isWasmPointer(result)) { throw new Error('A wasm object cannot be returned from wasm scope, all pointers are destroyed.'); diff --git a/packages/yoroi-extension/package-lock.json b/packages/yoroi-extension/package-lock.json index b197117120..c87061355f 100644 --- a/packages/yoroi-extension/package-lock.json +++ b/packages/yoroi-extension/package-lock.json @@ -8599,7 +8599,7 @@ "any-promise": { "version": "1.3.0", "resolved": "https://registry.npmjs.org/any-promise/-/any-promise-1.3.0.tgz", - "integrity": "sha512-7UvmKalWRt1wgjL1RrGxoSJW/0QZFIegpeGvZG9kjp8vrRu55XTHbwnqq2GpXm9uLbcuhxm3IqX9OB4MZR1b2A==", + "integrity": "sha1-q8av7tzqUugJzcA3au0845Y10X8=", "dev": true }, "anymatch": { @@ -9761,7 +9761,7 @@ "becke-ch--regex--s0-0-v1--base--pl--lib": { "version": "1.4.0", "resolved": "https://registry.npmjs.org/becke-ch--regex--s0-0-v1--base--pl--lib/-/becke-ch--regex--s0-0-v1--base--pl--lib-1.4.0.tgz", - "integrity": "sha512-FnWonOyaw7Vivg5nIkrUll9HSS5TjFbyuURAiDssuL6VxrBe3ERzudRxOcWRhZYlP89UArMDikz7SapRPQpmZQ==", + "integrity": "sha1-Qpzuu/pffpNueNc/vcfacWKyDiA=", "dev": true }, "before-after-hook": { @@ -12348,25 +12348,25 @@ "escape-string-regexp": { "version": "1.0.5", "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", - "integrity": "sha512-vbRorB5FUQWvla16U8R/qgaFIya2qGzwDrNmCZuYKrbdSUMG6I1ZCGQRefkRVhuOkIGVne7BQ35DSfo1qvJqFg==", + "integrity": "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=", "dev": true }, "indent-string": { "version": "3.2.0", "resolved": "https://registry.npmjs.org/indent-string/-/indent-string-3.2.0.tgz", - "integrity": "sha512-BYqTHXTGUIvg7t1r4sJNKcbDZkL92nkXA8YtRpbjFHRHGDL/NtUeiBJMeE60kIFN/Mg8ESaWQvftaYMGJzQZCQ==", + "integrity": "sha1-Sl/W0nzDMvN+VBmlBNu4NxBckok=", "dev": true }, "is-fullwidth-code-point": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-2.0.0.tgz", - "integrity": "sha512-VHskAKYM8RfSFXwee5t5cbN5PZeq1Wrh6qd5bkyiXIf6UQcN6w/A0eXM9r6t8d+GYOh+o6ZhiEnb88LN/Y8m2w==", + "integrity": "sha1-o7MKXE8ZkYMWeqq5O+764937ZU8=", "dev": true }, "path-key": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/path-key/-/path-key-2.0.1.tgz", - "integrity": "sha512-fEHGKCSmUSDPv4uoj8AlD+joPlq3peND+HRYyxFz4KPw4z926S/b8rIuFs2FYJg3BwsxJf6A9/3eIdLaYC+9Dw==", + "integrity": "sha1-QRyttXTFoUDTpLGRDUDYDMn0C0A=", "dev": true }, "semver": { @@ -12378,7 +12378,7 @@ "shebang-command": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-1.2.0.tgz", - "integrity": "sha512-EV3L1+UQWGor21OmnvojK36mhg+TyIKDh3iFBKBohr5xeXIhNBcx8oWdgkTEEQ+BEFFYdLRuqMfd5L84N1V5Vg==", + "integrity": "sha1-RKrGW2lbAzmJaMOfNj/uXer98eo=", "dev": true, "requires": { "shebang-regex": "^1.0.0" @@ -12387,7 +12387,7 @@ "shebang-regex": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-1.0.0.tgz", - "integrity": "sha512-wpoSFAxys6b2a2wHZ1XpDSgD7N9iVjg29Ph9uV/uaP9Ex/KXlkTZTeddxDPSYQpgvzKLGJke2UU0AzoGCjNIvQ==", + "integrity": "sha1-2kL0l0DAtC2yypcoVxyxkMmO/qM=", "dev": true }, "string-width": { @@ -12403,7 +12403,7 @@ "strip-ansi": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-4.0.0.tgz", - "integrity": "sha512-4XaJ2zQdCzROZDivEVIDPkcQn8LMFSa8kj8Gxb/Lnwzv9A8VctNZ+lfivC/sV3ivW8ElJTERXZoPBRrZKkNKow==", + "integrity": "sha1-qEeQIusaw2iocTibY1JixQXuNo8=", "dev": true, "requires": { "ansi-regex": "^3.0.0" @@ -12498,7 +12498,7 @@ "cucumber-tag-expressions": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/cucumber-tag-expressions/-/cucumber-tag-expressions-1.1.1.tgz", - "integrity": "sha512-V9jv81sR/HaJ87FoidrvHkviXId7KmBcUi7aQPfi+W3nRO30N6GqH6lcp8K+nyiT1DgemRJBPDDeBMS93xJqMQ==", + "integrity": "sha1-f1x7cACbwrZmWRv+ZIVFeL7e6Fo=", "dev": true }, "currently-unhandled": { @@ -13565,7 +13565,7 @@ "es6-iterator": { "version": "2.0.3", "resolved": "https://registry.npmjs.org/es6-iterator/-/es6-iterator-2.0.3.tgz", - "integrity": "sha512-zw4SRzoUkd+cl+ZoE15A9o1oQd920Bb0iOJMQkQhl3jNc03YqVjAhG7scf9C5KWRU/R13Orf588uCC6525o02g==", + "integrity": "sha1-p96IkUGgWpSwhUQDstCg+/qY87c=", "dev": true, "requires": { "d": "1", @@ -14796,7 +14796,7 @@ "figures": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/figures/-/figures-2.0.0.tgz", - "integrity": "sha512-Oa2M9atig69ZkfwiApY8F2Yy+tzMbazyvqv21R0NsSC8floSOC09BbT1ITWAdoMGQvJ/aZnR1KMwdx9tvHnTNA==", + "integrity": "sha1-OrGi0qYsi/tDGgyUy3l6L84nyWI=", "dev": true, "requires": { "escape-string-regexp": "^1.0.5" @@ -14805,7 +14805,7 @@ "escape-string-regexp": { "version": "1.0.5", "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", - "integrity": "sha512-vbRorB5FUQWvla16U8R/qgaFIya2qGzwDrNmCZuYKrbdSUMG6I1ZCGQRefkRVhuOkIGVne7BQ35DSfo1qvJqFg==", + "integrity": "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=", "dev": true } } @@ -16051,7 +16051,7 @@ "gherkin": { "version": "5.1.0", "resolved": "https://registry.npmjs.org/gherkin/-/gherkin-5.1.0.tgz", - "integrity": "sha512-axTCsxH0m0cixijLvo7s9591h5pMb8ifQxFDun5FnfFhVsUhxgdnH0H7TSK7q8I4ASUU18DJ/tmlnMegMuLUUQ==", + "integrity": "sha1-aEu7A63STq9731RPWAM+so+zxtU=", "dev": true }, "glob": { @@ -16764,7 +16764,7 @@ "httpolyglot": { "version": "0.1.2", "resolved": "https://registry.npmjs.org/httpolyglot/-/httpolyglot-0.1.2.tgz", - "integrity": "sha512-ouHI1AaQMLgn4L224527S5+vq6hgvqPteurVfbm7ChViM3He2Wa8KP1Ny7pTYd7QKnDSPKcN8JYfC8r/lmsE3A==", + "integrity": "sha1-5NNH/omEpi9GfUBg31J/GFH2mXs=", "dev": true }, "https-browserify": { @@ -17256,7 +17256,7 @@ "is-generator": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/is-generator/-/is-generator-1.0.3.tgz", - "integrity": "sha512-G56jBpbJeg7ds83HW1LuShNs8J73Fv3CPz/bmROHOHlnKkN8sWb9ujiagjmxxMUywftgq48HlBZELKKqFLk0oA==", + "integrity": "sha1-wUwhBX7TbjKNuANHlmxpP4hjifM=", "dev": true }, "is-generator-fn": { @@ -19707,7 +19707,7 @@ "knuth-shuffle-seeded": { "version": "1.0.6", "resolved": "https://registry.npmjs.org/knuth-shuffle-seeded/-/knuth-shuffle-seeded-1.0.6.tgz", - "integrity": "sha512-9pFH0SplrfyKyojCLxZfMcvkhf5hH0d+UwR9nTVJ/DDQJGuzcXjTwB7TP7sDfehSudlGGaOLblmEWqv04ERVWg==", + "integrity": "sha1-AfG2VzOqdUDuCNiwF0Fk0iCB5OE=", "dev": true, "requires": { "seed-random": "~2.2.0" @@ -19955,7 +19955,7 @@ "lodash.omit": { "version": "4.5.0", "resolved": "https://registry.npmjs.org/lodash.omit/-/lodash.omit-4.5.0.tgz", - "integrity": "sha512-XeqSp49hNGmlkj2EJlfrQFIzQ6lXdNro9sddtQzcJY8QaoC2GO0DT7xaIokHeyM+mIT0mPMlPvkYzg2xCuHdZg==", + "integrity": "sha1-brGa5aHuHdnfC5aeZs4Lf6MLXmA=", "dev": true }, "lodash.set": { @@ -22182,7 +22182,7 @@ "pad-right": { "version": "0.2.2", "resolved": "https://registry.npmjs.org/pad-right/-/pad-right-0.2.2.tgz", - "integrity": "sha512-4cy8M95ioIGolCoMmm2cMntGR1lPLEbOMzOKu8bzjuJP6JpzEMQcDHmh7hHLYGgob+nKe1YHFMaG4V59HQa89g==", + "integrity": "sha1-b7ySQEXSRPKiokRQMGDTv8YAl3Q=", "dev": true, "requires": { "repeat-string": "^1.5.2" @@ -25133,7 +25133,7 @@ "seed-random": { "version": "2.2.0", "resolved": "https://registry.npmjs.org/seed-random/-/seed-random-2.2.0.tgz", - "integrity": "sha512-34EQV6AAHQGhoc0tn/96a9Fsi6v2xdqe/dMUwljGRaFOzR3EgRmECvD0O8vi8X+/uQ50LGHfkNu/Eue5TPKZkQ==", + "integrity": "sha1-KpsZ4lCoFwmSMaW5mk2vgLf77VQ=", "dev": true }, "selenium-webdriver": { @@ -26741,7 +26741,7 @@ "thenify-all": { "version": "1.6.0", "resolved": "https://registry.npmjs.org/thenify-all/-/thenify-all-1.6.0.tgz", - "integrity": "sha512-RNxQH/qI8/t3thXJDwcstUO4zeqo64+Uy/+sNVRBx4Xn2OX+OZ9oP+iJnNFqplFra2ZUVeKCSa2oVWi3T4uVmA==", + "integrity": "sha1-GhkY1ALY/D+Y+/I02wvMjMEOlyY=", "dev": true, "requires": { "thenify": ">= 3.1.0 < 4" @@ -26858,7 +26858,7 @@ "title-case": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/title-case/-/title-case-2.1.1.tgz", - "integrity": "sha512-EkJoZ2O3zdCz3zJsYCsxyq2OC5hrxR9mfdd5I+w8h/tmFfeOxJ+vvkxsKxdmN0WtS9zLdHEgfgVOiMVgv+Po4Q==", + "integrity": "sha1-PhJyFtpY0rxb7PE3q5Ha46fNj6o=", "dev": true, "requires": { "no-case": "^2.2.0", @@ -26868,7 +26868,7 @@ "lower-case": { "version": "1.1.4", "resolved": "https://registry.npmjs.org/lower-case/-/lower-case-1.1.4.tgz", - "integrity": "sha512-2Fgx1Ycm599x+WGpIYwJOvsjmXFzTSc34IwDWALRA/8AopUKAVPwfJ+h5+f85BCp0PWmmJcWzEpxOpoXycMpdA==", + "integrity": "sha1-miyr0bno4K6ZOkv31YdcOcQujqw=", "dev": true }, "no-case": { @@ -27626,7 +27626,7 @@ "upper-case": { "version": "1.1.3", "resolved": "https://registry.npmjs.org/upper-case/-/upper-case-1.1.3.tgz", - "integrity": "sha512-WRbjgmYzgXkCV7zNVpy5YgrHgbBv126rMALQQMrmzOVC4GM2waQ9x7xtm8VU+1yF2kWyPzI9zbZ48n4vSxwfSA==", + "integrity": "sha1-9rRQHC7EzdJrp4vnIilh3ndiFZg=", "dev": true }, "uri-js": { @@ -27761,7 +27761,7 @@ "util-arity": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/util-arity/-/util-arity-1.1.0.tgz", - "integrity": "sha512-kkyIsXKwemfSy8ZEoaIz06ApApnWsk5hQO0vLjZS6UkBiGiW++Jsyb8vSBoc0WKlffGoGs5yYy/j5pp8zckrFA==", + "integrity": "sha1-WdAa8f2z/t4KxOYysKtfbOl8kzA=", "dev": true }, "util-deprecate": { From 0a59cb3209a42fbe700dbdac8a9bd888c7e783f8 Mon Sep 17 00:00:00 2001 From: vantuz-subhuman Date: Mon, 9 Jan 2023 19:46:24 +0300 Subject: [PATCH 101/172] more comments --- .../api/ada/lib/cardanoCrypto/rustLoader.js | 82 ++++++++++++------- 1 file changed, 53 insertions(+), 29 deletions(-) diff --git a/packages/yoroi-extension/app/api/ada/lib/cardanoCrypto/rustLoader.js b/packages/yoroi-extension/app/api/ada/lib/cardanoCrypto/rustLoader.js index 7cf77ff5a4..7e6f36f6f9 100644 --- a/packages/yoroi-extension/app/api/ada/lib/cardanoCrypto/rustLoader.js +++ b/packages/yoroi-extension/app/api/ada/lib/cardanoCrypto/rustLoader.js @@ -63,41 +63,65 @@ class Module { */ async WasmScope(callback: Module => Promise): Promise { /* - * The main idea here is that we create a proxy of some root object (module itself) - * and then we intercept every single field-getting access, including all functions, - * and we check if the result of the function call is a Wasm pointer object. - * If we detect a pointer - we add it into the tracked scope and free at the end of the call. + * The main idea here is that we create a proxy of the root object (module itself) + * and then we recursively intercept every single function call and we check + * whether the result of the call is a Wasm pointer object. If we detect a pointer, + * we add it into the tracked scope and free at the end of the execution. * This way ANY wasm pointer produced within the callback will be automatically destroyed, * but only as long as it's created using the injected proxied module reference. */ const scope = []; - const proxyHandler: Proxy$traps = { - // We are intercepting when any field is trying to be accessed on the original object - get(target: E, name: string, receiver: Proxy): any { - if (name === '____is_wasm_proxy') { - return true; - } - // Get the actual field value from the original object - const realValue = Reflect.get(target, name, receiver); - if (name === 'prototype') { - return realValue; - } - /* If the real value of the field is not a function, - * then we just want to recursively wrap it in a same proxy. - */ - if (typeof realValue !== 'function' || realValue.prototype != null) { - return recursiveProxy(realValue); - } - return function(...args: any[]): any { - const res = realValue.bind(target)(...args); - if (isWasmPointer(res)) { - scope.push(res); + function recursiveProxy(originalObject: E): E { + const proxyHandler: Proxy$traps = { + // We are intercepting when any field is trying to be accessed on the original object + get(target: E, name: string, receiver: Proxy): any { + // Synthetic flag to identify our own proxies + if (name === '____is_wasm_proxy') { + return true; } - return recursiveProxy(res); + // Get the actual field value from the original object + const realValue = Reflect.get(target, name, receiver); + // Never proxy the prototype field + if (name === 'prototype') { + return realValue; + } + // In case the real field value is a function, we implement a special wrapper + if (typeof realValue === 'function' && realValue.prototype == null) { + /* Note that we're also checking that the function has no prototype. + * The reason for this is that a field like `RustModule.WalletV4.BigNum` + * also has a type `function`, because it's a class constructor, + * but it is never used as a constructor directly, and instead only used + * to access static fields, including Rust constructor functions like `.new()`. + * The only thing that distinguishes it from a regular function is that + * it has a non-null prototype, that's why we check for it and rather wrap + * classes as regular objects. + */ + /* + * A wrapper function is returned instead. + */ + return function (...args: any[]): any { + // Call the actual function bound to the original object. + const res = realValue.bind(target)(...args); + if (isWasmPointer(res)) { + /* + * If the result of the function call is a wasm pointer object, + * we track it in our hidder scope array so we can free it after + * the callack is finished. This is pretty much the main point + * of this entire scope thing. + */ + scope.push(res); + } + // The result of the function call is then also recursively proxied. + // Whether it's a wasm object or not. + return recursiveProxy(res); + } + } + /* If the real value of the field ISN'T a function or IS a class, + * then we just want to recursively wrap it in a similar proxy. + */ + return recursiveProxy(realValue); } - } - }; - function recursiveProxy(originalObject: E): E { + }; // Make sure the original object is not already a proxy if (originalObject.____is_wasm_proxy !== true) { // We only proxy objects and functions, the check is mostly for primitive values From 37adb9241ff4efab5571d095597da2bbf1ca7512 Mon Sep 17 00:00:00 2001 From: vantuz-subhuman Date: Mon, 9 Jan 2023 19:54:36 +0300 Subject: [PATCH 102/172] Extracted scope-creating function for better readability --- .../api/ada/lib/cardanoCrypto/rustLoader.js | 159 ++++++++++-------- 1 file changed, 85 insertions(+), 74 deletions(-) diff --git a/packages/yoroi-extension/app/api/ada/lib/cardanoCrypto/rustLoader.js b/packages/yoroi-extension/app/api/ada/lib/cardanoCrypto/rustLoader.js index 7e6f36f6f9..8d91d7cfbb 100644 --- a/packages/yoroi-extension/app/api/ada/lib/cardanoCrypto/rustLoader.js +++ b/packages/yoroi-extension/app/api/ada/lib/cardanoCrypto/rustLoader.js @@ -21,6 +21,88 @@ function isWasmPointer(o: ?any): boolean { return o != null && o.ptr != null && o.free != null; } +function createWasmScope(): { + proxiedModule: Module, + free: () => void; +} { + /* + * The main idea here is that we create a proxy of the root object (module itself) + * and then we recursively intercept every single function call and we check + * whether the result of the call is a Wasm pointer object. If we detect a pointer, + * we add it into the tracked scope and free at the end of the execution. + * This way ANY wasm pointer produced within the callback will be automatically destroyed, + * but only as long as it's created using the injected proxied module reference. + */ + const scope = []; + function recursiveProxy(originalObject: E): E { + const proxyHandler: Proxy$traps = { + // We are intercepting when any field is trying to be accessed on the original object + get(target: E, name: string, receiver: Proxy): any { + // Synthetic flag to identify our own proxies + if (name === '____is_wasm_proxy') { + return true; + } + // Get the actual field value from the original object + const realValue = Reflect.get(target, name, receiver); + // Never proxy the prototype field + if (name === 'prototype') { + return realValue; + } + // In case the real field value is a function, we implement a special wrapper + if (typeof realValue === 'function' && realValue.prototype == null) { + /* Note that we're also checking that the function has no prototype. + * The reason for this is that a field like `RustModule.WalletV4.BigNum` + * also has a type `function`, because it's a class constructor, + * but it is never used as a constructor directly, and instead only used + * to access static fields, including Rust constructor functions like `.new()`. + * The only thing that distinguishes it from a regular function is that + * it has a non-null prototype, that's why we check for it and rather wrap + * classes as regular objects. + */ + /* + * A wrapper function is returned instead. + */ + return function (...args: any[]): any { + // Call the actual function bound to the original object. + const res = realValue.bind(target)(...args); + if (isWasmPointer(res)) { + /* + * If the result of the function call is a wasm pointer object, + * we track it in our hidder scope array so we can free it after + * the callack is finished. This is pretty much the main point + * of this entire scope thing. + */ + scope.push(res); + } + // The result of the function call is then also recursively proxied. + // Whether it's a wasm object or not. + return recursiveProxy(res); + } + } + /* If the real value of the field ISN'T a function or IS a class, + * then we just want to recursively wrap it in a similar proxy. + */ + return recursiveProxy(realValue); + } + }; + // We only proxy objects and functions, the check is mostly for primitive values + if (typeof originalObject === 'object' || typeof originalObject === 'function') { + // Make sure the original object is not already a proxy + if (originalObject.____is_wasm_proxy !== true) { + return new Proxy(originalObject, proxyHandler); + } + } + return originalObject; + } + // We are proxying the `RustModule` itself to pass it into the callback. + // Note that we create a new proxy every time, because each proxy instance + // is linked to the specific scope that will be destroyed. + return { + proxiedModule: recursiveProxy(RustModule), + free: () => { scope.forEach(x => x.free()); }, + } +} + class Module { _wasmv2: WasmV2; _wasmv3: WasmV3; @@ -62,80 +144,9 @@ class Module { * an exception will be raised. */ async WasmScope(callback: Module => Promise): Promise { - /* - * The main idea here is that we create a proxy of the root object (module itself) - * and then we recursively intercept every single function call and we check - * whether the result of the call is a Wasm pointer object. If we detect a pointer, - * we add it into the tracked scope and free at the end of the execution. - * This way ANY wasm pointer produced within the callback will be automatically destroyed, - * but only as long as it's created using the injected proxied module reference. - */ - const scope = []; - function recursiveProxy(originalObject: E): E { - const proxyHandler: Proxy$traps = { - // We are intercepting when any field is trying to be accessed on the original object - get(target: E, name: string, receiver: Proxy): any { - // Synthetic flag to identify our own proxies - if (name === '____is_wasm_proxy') { - return true; - } - // Get the actual field value from the original object - const realValue = Reflect.get(target, name, receiver); - // Never proxy the prototype field - if (name === 'prototype') { - return realValue; - } - // In case the real field value is a function, we implement a special wrapper - if (typeof realValue === 'function' && realValue.prototype == null) { - /* Note that we're also checking that the function has no prototype. - * The reason for this is that a field like `RustModule.WalletV4.BigNum` - * also has a type `function`, because it's a class constructor, - * but it is never used as a constructor directly, and instead only used - * to access static fields, including Rust constructor functions like `.new()`. - * The only thing that distinguishes it from a regular function is that - * it has a non-null prototype, that's why we check for it and rather wrap - * classes as regular objects. - */ - /* - * A wrapper function is returned instead. - */ - return function (...args: any[]): any { - // Call the actual function bound to the original object. - const res = realValue.bind(target)(...args); - if (isWasmPointer(res)) { - /* - * If the result of the function call is a wasm pointer object, - * we track it in our hidder scope array so we can free it after - * the callack is finished. This is pretty much the main point - * of this entire scope thing. - */ - scope.push(res); - } - // The result of the function call is then also recursively proxied. - // Whether it's a wasm object or not. - return recursiveProxy(res); - } - } - /* If the real value of the field ISN'T a function or IS a class, - * then we just want to recursively wrap it in a similar proxy. - */ - return recursiveProxy(realValue); - } - }; - // Make sure the original object is not already a proxy - if (originalObject.____is_wasm_proxy !== true) { - // We only proxy objects and functions, the check is mostly for primitive values - if (typeof originalObject === 'object' || typeof originalObject === 'function') { - return new Proxy(originalObject, proxyHandler); - } - } - return originalObject; - } - // We are proxying the `RustModule` itself to pass it into the callback. - // Note that we create a new proxy every time, because each proxy instance - // is linked to the specific scope that will be destroyed. - const result = await callback(recursiveProxy(RustModule)); - scope.forEach(x => x.free()); + const scope = createWasmScope(); + const result = await callback(scope.proxiedModule); + scope.free(); if (isWasmPointer(result)) { throw new Error('A wasm object cannot be returned from wasm scope, all pointers are destroyed.'); } From 2cd403fa4ba6ba593ebc47c419045f83a6958b0d Mon Sep 17 00:00:00 2001 From: Ahmed Ibrahim Date: Mon, 9 Jan 2023 19:19:55 +0200 Subject: [PATCH 103/172] Update browsers icons --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index fecaf5a14c..5fe22e75b3 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ | Firefox | Chrome | Edge | |---|----|----| -| [](https://addons.mozilla.org/en-US/firefox/addon/yoroi/) | [](https://chrome.google.com/webstore/detail/yoroi/ffnbelfdoeiohenkjibnmadjiehjhajb) | [](https://microsoftedge.microsoft.com/addons/detail/yoroi/akoiaibnepcedcplijmiamnaigbepmcb) | +| [](https://addons.mozilla.org/en-US/firefox/addon/yoroi/) | [](https://chrome.google.com/webstore/detail/yoroi/ffnbelfdoeiohenkjibnmadjiehjhajb) | [](https://microsoftedge.microsoft.com/addons/detail/yoroi/akoiaibnepcedcplijmiamnaigbepmcb) | Looking for Yoroi Mobile? See [here](https://github.com/Emurgo/yoroi-mobile) From e50110b536bc5a2f334e9e1ea8ed4f53c10ffa04 Mon Sep 17 00:00:00 2001 From: vantuz-subhuman Date: Mon, 9 Jan 2023 22:15:40 +0300 Subject: [PATCH 104/172] Tiny renaming --- .../app/api/ada/lib/cardanoCrypto/rustLoader.js | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/yoroi-extension/app/api/ada/lib/cardanoCrypto/rustLoader.js b/packages/yoroi-extension/app/api/ada/lib/cardanoCrypto/rustLoader.js index 8d91d7cfbb..41edf882ca 100644 --- a/packages/yoroi-extension/app/api/ada/lib/cardanoCrypto/rustLoader.js +++ b/packages/yoroi-extension/app/api/ada/lib/cardanoCrypto/rustLoader.js @@ -22,7 +22,7 @@ function isWasmPointer(o: ?any): boolean { } function createWasmScope(): { - proxiedModule: Module, + RustModule: Module, free: () => void; } { /* @@ -98,7 +98,7 @@ function createWasmScope(): { // Note that we create a new proxy every time, because each proxy instance // is linked to the specific scope that will be destroyed. return { - proxiedModule: recursiveProxy(RustModule), + RustModule: recursiveProxy(RustModule), free: () => { scope.forEach(x => x.free()); }, } } @@ -145,7 +145,7 @@ class Module { */ async WasmScope(callback: Module => Promise): Promise { const scope = createWasmScope(); - const result = await callback(scope.proxiedModule); + const result = await callback(scope.RustModule); scope.free(); if (isWasmPointer(result)) { throw new Error('A wasm object cannot be returned from wasm scope, all pointers are destroyed.'); From 10ff22f5d34cfb89ecf61bc29a79f666e4eefd36 Mon Sep 17 00:00:00 2001 From: vantuz-subhuman Date: Tue, 10 Jan 2023 15:07:36 +0300 Subject: [PATCH 105/172] more comments --- .../app/api/ada/lib/cardanoCrypto/rustLoader.js | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/packages/yoroi-extension/app/api/ada/lib/cardanoCrypto/rustLoader.js b/packages/yoroi-extension/app/api/ada/lib/cardanoCrypto/rustLoader.js index 41edf882ca..89dc67716c 100644 --- a/packages/yoroi-extension/app/api/ada/lib/cardanoCrypto/rustLoader.js +++ b/packages/yoroi-extension/app/api/ada/lib/cardanoCrypto/rustLoader.js @@ -21,6 +21,12 @@ function isWasmPointer(o: ?any): boolean { return o != null && o.ptr != null && o.free != null; } +/** + * Creates a new proxied RustModule scope. + * Return fields: + * - RustModule - the proxied module + * - free() - the function that will free all the wasm pointers created within the scope so far. + */ function createWasmScope(): { RustModule: Module, free: () => void; From a6b9247f18ef7e2e49f3cc957360a8646c55b6cf Mon Sep 17 00:00:00 2001 From: vantuz-subhuman Date: Tue, 10 Jan 2023 15:23:20 +0300 Subject: [PATCH 106/172] Flow fixes --- .../app/api/ada/lib/cardanoCrypto/rustLoader.js | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/packages/yoroi-extension/app/api/ada/lib/cardanoCrypto/rustLoader.js b/packages/yoroi-extension/app/api/ada/lib/cardanoCrypto/rustLoader.js index 89dc67716c..1031369c9c 100644 --- a/packages/yoroi-extension/app/api/ada/lib/cardanoCrypto/rustLoader.js +++ b/packages/yoroi-extension/app/api/ada/lib/cardanoCrypto/rustLoader.js @@ -27,10 +27,10 @@ function isWasmPointer(o: ?any): boolean { * - RustModule - the proxied module * - free() - the function that will free all the wasm pointers created within the scope so far. */ -function createWasmScope(): { +function createWasmScope(): {| RustModule: Module, free: () => void; -} { +|} { /* * The main idea here is that we create a proxy of the root object (module itself) * and then we recursively intercept every single function call and we check @@ -41,6 +41,9 @@ function createWasmScope(): { */ const scope = []; function recursiveProxy(originalObject: E): E { + if (originalObject == null) { + return originalObject; + } const proxyHandler: Proxy$traps = { // We are intercepting when any field is trying to be accessed on the original object get(target: E, name: string, receiver: Proxy): any { @@ -95,7 +98,8 @@ function createWasmScope(): { if (typeof originalObject === 'object' || typeof originalObject === 'function') { // Make sure the original object is not already a proxy if (originalObject.____is_wasm_proxy !== true) { - return new Proxy(originalObject, proxyHandler); + // $FlowFixMe[incompatible-return] + return new Proxy(originalObject, proxyHandler); } } return originalObject; From 314b5460751dddd6bce6678aa45033ab9008c5f4 Mon Sep 17 00:00:00 2001 From: vantuz-subhuman Date: Tue, 10 Jan 2023 17:40:58 +0300 Subject: [PATCH 107/172] Fixed async handling --- .../app/api/ada/lib/cardanoCrypto/rustLoader.js | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/packages/yoroi-extension/app/api/ada/lib/cardanoCrypto/rustLoader.js b/packages/yoroi-extension/app/api/ada/lib/cardanoCrypto/rustLoader.js index 1031369c9c..6ae072e359 100644 --- a/packages/yoroi-extension/app/api/ada/lib/cardanoCrypto/rustLoader.js +++ b/packages/yoroi-extension/app/api/ada/lib/cardanoCrypto/rustLoader.js @@ -153,14 +153,17 @@ class Module { * before this function returns. If the result will be detected to be a wasm pointer, * an exception will be raised. */ - async WasmScope(callback: Module => Promise): Promise { + WasmScope(callback: Module => T): T { const scope = createWasmScope(); - const result = await callback(scope.RustModule); - scope.free(); - if (isWasmPointer(result)) { - throw new Error('A wasm object cannot be returned from wasm scope, all pointers are destroyed.'); + const result = callback(scope.RustModule); + function resolve(res): T { + scope.free(); + if (isWasmPointer(res)) { + throw new Error('A wasm object cannot be returned from wasm scope, all pointers are destroyed.'); + } + return res; } - return result; + return typeof result.then === 'function' ? result.then(resolve) : resolve(result); } // Need to expose through a getter to get Flow to detect the type correctly From 8ba9eaff2a6aa1309c6eb25cb4c3544dbead67da Mon Sep 17 00:00:00 2001 From: vantuz-subhuman Date: Tue, 10 Jan 2023 19:35:54 +0300 Subject: [PATCH 108/172] Adding wasm-scope usage --- .../api/ada/lib/state-fetch/remoteFetcher.js | 7 +- .../lib/storage/bridge/updateTransactions.js | 695 ++++++++---------- 2 files changed, 322 insertions(+), 380 deletions(-) diff --git a/packages/yoroi-extension/app/api/ada/lib/state-fetch/remoteFetcher.js b/packages/yoroi-extension/app/api/ada/lib/state-fetch/remoteFetcher.js index 5e74121cba..893704736f 100644 --- a/packages/yoroi-extension/app/api/ada/lib/state-fetch/remoteFetcher.js +++ b/packages/yoroi-extension/app/api/ada/lib/state-fetch/remoteFetcher.js @@ -56,6 +56,7 @@ import { RustModule } from '../cardanoCrypto/rustLoader'; import type { ConfigType } from '../../../../../config/config-types'; import { bech32, } from 'bech32'; +import { bytesToHex } from '../../../../coreUtils'; // populated by ConfigWebpackPlugin declare var CONFIG: ConfigType; @@ -103,9 +104,9 @@ export class RemoteFetcher implements IFetcher { }); return result.map(utxo => { if (utxo.receiver.startsWith('addr')) { - const fixedAddr = Buffer.from( - RustModule.WalletV4.Address.from_bech32(utxo.receiver).to_bytes() - ).toString('hex'); + const fixedAddr = RustModule.WasmScope(Module => bytesToHex( + Module.WalletV4.Address.from_bech32(utxo.receiver).to_bytes() + )); return { ...utxo, receiver: fixedAddr, diff --git a/packages/yoroi-extension/app/api/ada/lib/storage/bridge/updateTransactions.js b/packages/yoroi-extension/app/api/ada/lib/storage/bridge/updateTransactions.js index 99bd8d3382..76fd89c16d 100644 --- a/packages/yoroi-extension/app/api/ada/lib/storage/bridge/updateTransactions.js +++ b/packages/yoroi-extension/app/api/ada/lib/storage/bridge/updateTransactions.js @@ -3,155 +3,115 @@ import BigNumber from 'bignumber.js'; import { isEqual } from 'lodash'; import ObjectHash from 'object-hash'; -import type { - lf$Database, lf$Transaction, -} from 'lovefield'; +import type { lf$Database, lf$Transaction, } from 'lovefield'; -import { - getAllSchemaTables, - raii, - mapToTables, -} from '../database/utils'; +import { getAllSchemaTables, mapToTables, raii, } from '../database/utils'; import type { - BlockInsert, BlockRow, - TransactionInsert, TransactionRow, + AddressRow, + BlockInsert, + BlockRow, + CardanoAssetMintMetadata, CardanoByronTransactionInsert, CardanoShelleyTransactionInsert, - NetworkRow, DbBlock, - AddressRow, - TokenRow, + NetworkRow, TokenListInsert, - CardanoAssetMintMetadata, + TokenRow, + TransactionInsert, + TransactionRow, } from '../database/primitives/tables'; +import { TransactionType, } from '../database/primitives/tables'; +import type { CertificateRelationType, CoreAddressT, TxStatusCodesType, } from '../database/primitives/enums'; import { - TransactionType, -} from '../database/primitives/tables'; -import type { - TxStatusCodesType, - CertificateRelationType, - CoreAddressT, + CertificateRelation, + CoreAddressTypes, + PRIMARY_ASSET_CONSTANTS, + TxStatusCodes, } from '../database/primitives/enums'; import { + AssociateToken, GetAddress, GetBlock, + GetCertificates, + GetDerivationsByPath, GetEncryptionMeta, + GetKeyDerivation, GetPathWithSpecific, - GetDerivationsByPath, + GetToken, GetTransaction, GetTxAndBlock, - GetCertificates, - GetKeyDerivation, - GetToken, - AssociateToken, } from '../database/primitives/api/read'; +import type { AddCertificateRequest } from '../database/primitives/api/write'; import { - ModifyAddress, - ModifyTransaction, FreeBlocks, + ModifyAddress, ModifyToken, ModifyTokenList, + ModifyTransaction, } from '../database/primitives/api/write'; -import type { AddCertificateRequest } from '../database/primitives/api/write'; -import { ModifyCardanoByronTx, ModifyCardanoShelleyTx } from '../database/transactionModels/multipart/api/write'; +import { ModifyCardanoByronTx, ModifyCardanoShelleyTx } from '../database/transactionModels/multipart/api/write'; import { digestForHash, } from '../database/primitives/api/utils'; +import { MarkUtxo, } from '../database/transactionModels/utxo/api/write'; import { - MarkUtxo, -} from '../database/transactionModels/utxo/api/write'; -import { - GetUtxoTxOutputsWithTx, - GetUtxoInputs, AssociateTxWithUtxoIOs, createTokenListIdGenFunction, + GetUtxoInputs, + GetUtxoTxOutputsWithTx, } from '../database/transactionModels/utxo/api/read'; +import { AssociateTxWithAccountingIOs, } from '../database/transactionModels/account/api/read'; import { - AssociateTxWithAccountingIOs, -} from '../database/transactionModels/account/api/read'; -import { - CardanoByronAssociateTxWithIOs, CardanoShelleyAssociateTxWithIOs, + CardanoByronAssociateTxWithIOs, + CardanoShelleyAssociateTxWithIOs, } from '../database/transactionModels/multipart/api/read'; +import type { UserAnnotation, } from '../../../transactions/types'; +import type { ToAbsoluteSlotNumberFunc, } from '../../../../common/lib/storage/bridge/timeUtils'; import type { - UserAnnotation, -} from '../../../transactions/types'; -import type { - ToAbsoluteSlotNumberFunc, -} from '../../../../common/lib/storage/bridge/timeUtils'; -import type { - UtxoTransactionInputInsert, UtxoTransactionOutputInsert, + UtxoTransactionInputInsert, + UtxoTransactionOutputInsert, } from '../database/transactionModels/utxo/tables'; -import type { - AccountingTransactionInputInsert, -} from '../database/transactionModels/account/tables'; -import { - TxStatusCodes, - CoreAddressTypes, - CertificateRelation, - PRIMARY_ASSET_CONSTANTS, -} from '../database/primitives/enums'; -import { - asScanAddresses, asHasLevels, -} from '../models/PublicDeriver/traits'; +import type { AccountingTransactionInputInsert, } from '../database/transactionModels/account/tables'; +import { asHasLevels, asScanAddresses, } from '../models/PublicDeriver/traits'; import type { IHasLevels } from '../models/ConceptualWallet/interfaces'; import { ConceptualWallet } from '../models/ConceptualWallet/index'; -import type { - IPublicDeriver, -} from '../models/PublicDeriver/interfaces'; +import type { IPublicDeriver, } from '../models/PublicDeriver/interfaces'; import { + GetKeyForPublicDeriver, GetLastSyncForPublicDeriver, GetPublicDeriver, - GetKeyForPublicDeriver, } from '../database/walletTypes/core/api/read'; import { ModifyDisplayCutoff, } from '../database/walletTypes/bip44/api/write'; import { AddDerivationTree, } from '../database/walletTypes/common/api/write'; import { GetDerivationSpecific, } from '../database/walletTypes/common/api/read'; import { getCardanoHaskellBaseConfig, } from '../database/prepackaged/networks'; -import { - ModifyLastSyncInfo, - DeleteAllTransactions, -} from '../database/walletTypes/core/api/write'; +import { DeleteAllTransactions, ModifyLastSyncInfo, } from '../database/walletTypes/core/api/write'; import type { LastSyncInfoRow, } from '../database/walletTypes/core/tables'; import type { CardanoByronTxIO, CardanoShelleyTxIO } from '../database/transactionModels/multipart/tables'; -import { - rawGetAddressRowsForWallet, -} from './traitUtils'; -import { - genToAbsoluteSlotNumber, -} from './timeUtils'; -import { - rawGenHashToIdsFunc, rawGenFindOwnAddress, -} from '../../../../common/lib/storage/bridge/hashMapper'; -import type { - HashToIdsFunc, FindOwnAddressFunc, -} from '../../../../common/lib/storage/bridge/hashMapper'; +import { rawGetAddressRowsForWallet, } from './traitUtils'; +import { genToAbsoluteSlotNumber, } from './timeUtils'; +import type { FindOwnAddressFunc, HashToIdsFunc, } from '../../../../common/lib/storage/bridge/hashMapper'; +import { rawGenFindOwnAddress, rawGenHashToIdsFunc, } from '../../../../common/lib/storage/bridge/hashMapper'; import { CARDANO_STABLE_SIZE } from '../../../../../config/numbersConfig'; import { RollbackApiError } from '../../../../common/errors'; import { getFromUserPerspective, identifierToCardanoAsset, } from '../../../transactions/utils'; import type { - HistoryFunc, BestBlockFunc, - RemoteTxState, - RemoteTransaction, + BestBlockFunc, + HistoryFunc, + MultiAssetMintMetadataFunc, RemoteCertificate, - TokenInfoFunc, - MultiAssetMintMetadataFunc -} from '../../state-fetch/types'; -import { - ShelleyCertificateTypes, - RemoteTransactionTypes, + RemoteTransaction, + RemoteTxState, + TokenInfoFunc } from '../../state-fetch/types'; -import type { - FilterFunc, -} from '../../../../common/lib/state-fetch/currencySpecificTypes'; +import { RemoteTransactionTypes, ShelleyCertificateTypes, } from '../../state-fetch/types'; +import type { FilterFunc, } from '../../../../common/lib/state-fetch/currencySpecificTypes'; import { addressToKind, } from './utils'; import { RustModule } from '../../cardanoCrypto/rustLoader'; import { Bech32Prefix } from '../../../../../config/stringConfig'; -import { - MultiToken, -} from '../../../../common/lib/MultiToken'; -import type { - DefaultTokenEntry, -} from '../../../../common/lib/MultiToken'; +import type { DefaultTokenEntry, } from '../../../../common/lib/MultiToken'; +import { MultiToken, } from '../../../../common/lib/MultiToken'; import { UtxoStorageApi } from '../models/utils'; +import { bytesToHex, hexToBytes } from '../../../../../coreUtils'; type TokensMintMetadata = {| ...{[key: string]: TokenMintMetadata[]} @@ -365,40 +325,42 @@ export async function rawGetTransactions( ) { continue; } - const mir = RustModule.WalletV4.MoveInstantaneousRewardsCert.from_bytes( - Buffer.from(cert.certificate.Payload, 'hex') - ).move_instantaneous_reward(); - - for (const relatedAddr of cert.relatedAddresses) { - // recall: length of this list is usually just 1 - for (const addr of addresses.accountingAddresses) { - if (relatedAddr.AddressId === addr.AddressId) { - // this address got some rewards inside the cert - const rewardAddr = RustModule.WalletV4.RewardAddress.from_address( - RustModule.WalletV4.Address.from_bytes( - Buffer.from(addr.Hash, 'hex') - ) - ); - if (rewardAddr == null) continue; // should never happen - const rewardAmount = mir.as_to_stake_creds() - ?.get(rewardAddr.payment_cred()); - // happens if the MIR is to another pot - if (rewardAmount == null) continue; - const isPositive = rewardAmount.is_positive(); - const rewardAmountBigInt = isPositive - ? rewardAmount.as_positive() - : rewardAmount.as_negative(); - if (rewardAmountBigInt == null) continue; - const rewardAmountStr = - (isPositive ? '' : '-') + rewardAmountBigInt.to_str(); - implicitOutputSum.add({ - identifier: defaultToken.defaultIdentifier, - networkId: defaultToken.defaultNetworkId, - amount: new BigNumber(rewardAmountStr), - }); + + RustModule.WasmScope(Module => { + const mir = Module.WalletV4.MoveInstantaneousRewardsCert.from_bytes( + Buffer.from(cert.certificate.Payload, 'hex') + ).move_instantaneous_reward().as_to_stake_creds(); + + for (const relatedAddr of cert.relatedAddresses) { + // recall: length of this list is usually just 1 + for (const addr of addresses.accountingAddresses) { + if (relatedAddr.AddressId === addr.AddressId) { + // this address got some rewards inside the cert + const rewardAddr = Module.WalletV4.RewardAddress.from_address( + Module.WalletV4.Address.from_bytes( + Buffer.from(addr.Hash, 'hex') + ) + ); + if (rewardAddr == null) continue; // should never happen + const rewardAmount = mir?.get(rewardAddr.payment_cred()); + // happens if the MIR is to another pot + if (rewardAmount == null) continue; + const isPositive = rewardAmount.is_positive(); + const rewardAmountBigInt = isPositive + ? rewardAmount.as_positive() + : rewardAmount.as_negative(); + if (rewardAmountBigInt == null) continue; + const rewardAmountStr = + (isPositive ? '' : '-') + rewardAmountBigInt.to_str(); + implicitOutputSum.add({ + identifier: defaultToken.defaultIdentifier, + networkId: defaultToken.defaultNetworkId, + amount: new BigNumber(rewardAmountStr), + }); + } } } - } + }); } return implicitOutputSum; } @@ -2461,7 +2423,7 @@ async function certificateToDb( return id; }; const tryGetKey = async ( - stakeCredentials: RustModule.WalletV4.StakeCredential + stakeCredentialHex: string ): Promise => { // an operator/owner key might belong to the wallet // however, these keys are plain ED25519 hashes @@ -2471,25 +2433,33 @@ async function certificateToDb( // since we don't know what address it would be // and in most cases, people generate these addresses through the CLI anyway { - const rewardAddress = RustModule.WalletV4.RewardAddress.new( - request.network, - stakeCredentials - ); - const ownAddress = await findOwnAddress( - Buffer.from(rewardAddress.to_address().to_bytes()).toString('hex') - ); + const rewardAddressHex = RustModule.WasmScope(Module => { + const stakeCredential = Module.WalletV4.StakeCredential + .from_bytes(hexToBytes(stakeCredentialHex)); + return bytesToHex( + Module.WalletV4.RewardAddress + .new(request.network, stakeCredential) + .to_address() + .to_bytes() + ); + }); + const ownAddress = await findOwnAddress(rewardAddressHex); if (ownAddress != null) { return ownAddress; } } { - const enterpriseAddress = RustModule.WalletV4.EnterpriseAddress.new( - request.network, - stakeCredentials - ); - const ownAddress = await findOwnAddress(( - Buffer.from(enterpriseAddress.to_address().to_bytes()).toString('hex') - )); + const enterpriseAddressHex = RustModule.WasmScope(Module => { + const stakeCredential = Module.WalletV4.StakeCredential + .from_bytes(hexToBytes(stakeCredentialHex)); + return Buffer.from( + Module.WalletV4.EnterpriseAddress + .new(request.network, stakeCredential) + .to_address() + .to_bytes() + ).toString('hex'); + }); + const ownAddress = await findOwnAddress(enterpriseAddressHex); if (ownAddress != null) return ownAddress; } return undefined; @@ -2500,26 +2470,24 @@ async function certificateToDb( const cert = request.certificates[i]; switch (cert.kind) { case ShelleyCertificateTypes.StakeRegistration: { - const stakeCredentials = RustModule.WalletV4.RewardAddress.from_address( - RustModule.WalletV4.Address.from_bytes( - Buffer.from(cert.rewardAddress, 'hex') - ) - )?.payment_cred(); - if (stakeCredentials == null) throw new Error(`${nameof(certificateToDb)} not a valid reward account`); - const certificate = RustModule.WalletV4.StakeRegistration.new( - stakeCredentials - ); - const address = RustModule.WalletV4.RewardAddress.new( - request.network, - stakeCredentials - ); - const addrBytes = Buffer.from(address.to_address().to_bytes()).toString('hex'); - const addressId = await addressToId(addrBytes); + const [addressHex, certificateHex] = RustModule.WasmScope(Module => { + const stakeCredentials = Module.WalletV4.RewardAddress.from_address( + Module.WalletV4.Address.from_bytes(hexToBytes(cert.rewardAddress)) + )?.payment_cred(); + if (stakeCredentials == null) throw new Error(`${nameof(certificateToDb)} not a valid reward account`); + return [ + bytesToHex(Module.WalletV4.RewardAddress + .new(request.network, stakeCredentials).to_address().to_bytes()), + bytesToHex(Module.WalletV4.StakeRegistration + .new(stakeCredentials).to_bytes()), + ]; + }); + const addressId = await addressToId(addressHex); result.push((txId: number) => ({ certificate: { Ordinal: cert.certIndex, Kind: RustModule.WalletV4.CertificateKind.StakeRegistration, - Payload: Buffer.from(certificate.to_bytes()).toString('hex'), + Payload: certificateHex, TransactionId: txId, }, relatedAddresses: (certId: number) => [{ @@ -2531,26 +2499,24 @@ async function certificateToDb( break; } case ShelleyCertificateTypes.StakeDeregistration: { - const stakeCredentials = RustModule.WalletV4.RewardAddress.from_address( - RustModule.WalletV4.Address.from_bytes( - Buffer.from(cert.rewardAddress, 'hex') - ) - )?.payment_cred(); - if (stakeCredentials == null) throw new Error(`${nameof(certificateToDb)} not a valid reward account`); - const certificate = RustModule.WalletV4.StakeRegistration.new( - stakeCredentials - ); - const address = RustModule.WalletV4.RewardAddress.new( - request.network, - stakeCredentials - ); - const addrBytes = Buffer.from(address.to_address().to_bytes()).toString('hex'); - const addressId = await addressToId(addrBytes); + const [addressHex, certificateHex] = RustModule.WasmScope(Module => { + const stakeCredentials = Module.WalletV4.RewardAddress.from_address( + Module.WalletV4.Address.from_bytes(hexToBytes(cert.rewardAddress)) + )?.payment_cred(); + if (stakeCredentials == null) throw new Error(`${nameof(certificateToDb)} not a valid reward account`); + return [ + bytesToHex(Module.WalletV4.RewardAddress + .new(request.network, stakeCredentials).to_address().to_bytes()), + bytesToHex(Module.WalletV4.StakeRegistration + .new(stakeCredentials).to_bytes()), + ]; + }); + const addressId = await addressToId(addressHex); result.push((txId: number) => ({ certificate: { Ordinal: cert.certIndex, Kind: RustModule.WalletV4.CertificateKind.StakeDeregistration, - Payload: Buffer.from(certificate.to_bytes()).toString('hex'), + Payload: certificateHex, TransactionId: txId, }, relatedAddresses: (certId: number) => [{ @@ -2566,26 +2532,24 @@ async function certificateToDb( AddressId: number, Relation: CertificateRelationType, |}> = []; - - const rewardAddress = RustModule.WalletV4.RewardAddress.from_address( - RustModule.WalletV4.Address.from_bytes( - Buffer.from(cert.rewardAddress, 'hex') - ) - ); - if (rewardAddress == null) throw new Error(`${nameof(certificateToDb)} not a valid reward account`); - const stakeCredentials = rewardAddress.payment_cred(); - const poolKeyHash = RustModule.WalletV4.Ed25519KeyHash.from_bytes( - Buffer.from(cert.poolKeyHash, 'hex') - ); - const certificate = RustModule.WalletV4.StakeDelegation.new( - stakeCredentials, - poolKeyHash - ); - - { // pool key - const poolKeyId = await tryGetKey( - RustModule.WalletV4.StakeCredential.from_keyhash(poolKeyHash) + const [addressHex, certificateHex, stakeCredentialHex] = RustModule.WasmScope(Module => { + const rewardAddress = Module.WalletV4.RewardAddress.from_address( + Module.WalletV4.Address.from_bytes(hexToBytes(cert.rewardAddress)) ); + if (rewardAddress == null) throw new Error(`${nameof(certificateToDb)} not a valid reward account`); + const stakeCredentials = rewardAddress.payment_cred(); + const poolKeyHash = Module.WalletV4.Ed25519KeyHash + .from_bytes(hexToBytes(cert.poolKeyHash)); + return [ + bytesToHex(rewardAddress.to_address().to_bytes()), + bytesToHex(Module.WalletV4.StakeDelegation + .new(stakeCredentials, poolKeyHash).to_bytes()), + bytesToHex(Module.WalletV4.StakeCredential + .from_keyhash(poolKeyHash).to_bytes()), + ] + }); + { // pool key + const poolKeyId = await tryGetKey(stakeCredentialHex); if (poolKeyId != null) { relatedAddressesInfo.push({ AddressId: poolKeyId, @@ -2595,8 +2559,7 @@ async function certificateToDb( } { // delegator - const addrBytes = Buffer.from(rewardAddress.to_address().to_bytes()).toString('hex'); - const addressId = await addressToId(addrBytes); + const addressId = await addressToId(addressHex); relatedAddressesInfo.push({ AddressId: addressId, Relation: CertificateRelation.SIGNER @@ -2607,7 +2570,7 @@ async function certificateToDb( certificate: { Ordinal: cert.certIndex, Kind: RustModule.WalletV4.CertificateKind.StakeDelegation, - Payload: Buffer.from(certificate.to_bytes()).toString('hex'), + Payload: certificateHex, TransactionId: txId, }, relatedAddresses: (certId: number) => relatedAddressesInfo.map(info => ({ @@ -2622,14 +2585,93 @@ async function certificateToDb( AddressId: number, Relation: CertificateRelationType, |}> = []; + const ownerStakeCredentialHexes = []; + const [operatorStakeCredentialHex, certificateHex] = RustModule.WasmScope(Module => { + const rewardAddress = Module.WalletV4.RewardAddress.from_address( + Module.WalletV4.Address.from_bytes(hexToBytes(cert.poolParams.rewardAccount)) + ); + if (rewardAddress == null) throw new Error(`${nameof(certificateToDb)} registration address not a reward address`); + + const operatorKey = Module.WalletV4.Ed25519KeyHash + .from_bytes(hexToBytes(cert.poolParams.operator)); + + // pool owners + const owners = Module.WalletV4.Ed25519KeyHashes.new(); + for (let j = 0; j < cert.poolParams.poolOwners.length; j++) { + const owner = cert.poolParams.poolOwners[j]; + // The owners property of the pool parameter is a set of stake key hashes + // of the owners. But the values returned from the backend are a set of + // stake addresses which are "a single header byte identifying their type + // and the network, followed by 28 bytes of payload identifying either a + // stake key hash or a script hash" (CIP19). So we convert the stake + // address to a key hash (equivalent to removing the header byte). + const ownerKey = Module.WalletV4.RewardAddress.from_address( + Module.WalletV4.Address.from_bytes( + Buffer.from(owner, 'hex') + ) + )?.payment_cred().to_keyhash(); + if (!ownerKey) { + throw new Error(`${nameof(certificateToDb)} expect the pool owner to be a key hash`); + } + owners.add(ownerKey); + const ownerStakeCredentialHex = bytesToHex(Module.WalletV4.StakeCredential + .from_keyhash(ownerKey).to_bytes()); + ownerStakeCredentialHexes.push(ownerStakeCredentialHex); + } - const operatorKey = RustModule.WalletV4.Ed25519KeyHash.from_bytes( - Buffer.from(cert.poolParams.operator, 'hex') - ); - { // operator - const operatorId = await tryGetKey( - RustModule.WalletV4.StakeCredential.from_keyhash(operatorKey) + let poolMetadata = null; + if (cert.poolParams.poolMetadata != null) { + const metadata = cert.poolParams.poolMetadata; + poolMetadata = Module.WalletV4.PoolMetadata.new( + Module.WalletV4.URL.new(metadata.url), + Module.WalletV4.PoolMetadataHash.from_bytes( + Buffer.from(metadata.metadataHash, 'hex') + ) + ); + } + + const certificate = Module.WalletV4.PoolRegistration.new( + Module.WalletV4.PoolParams.new( + operatorKey, + Module.WalletV4.VRFKeyHash.from_bytes( + Buffer.from(cert.poolParams.vrfKeyHash, 'hex') + ), + Module.WalletV4.BigNum.from_str(cert.poolParams.pledge), + Module.WalletV4.BigNum.from_str(cert.poolParams.cost), + Module.WalletV4.UnitInterval.new( + // TODO: dummy data since db-sync doesn't support this yet + Module.WalletV4.BigNum.from_str('1'), + Module.WalletV4.BigNum.from_str('1'), + // Module.WalletV4.BigNum.from_str(cert.poolParams.margin.numerator), + // Module.WalletV4.BigNum.from_str(cert.poolParams.margin.denominator), + ), + rewardAddress, + owners, + Module.WalletV4.Relays.new(), + poolMetadata + ) ); + + return [ + bytesToHex(Module.WalletV4.StakeCredential + .from_keyhash(operatorKey).to_bytes()), + bytesToHex(certificate.to_bytes()), + ]; + }); + + { // owners + for (const ownerStakeCredentialHex of ownerStakeCredentialHexes) { + const ownerId = await tryGetKey(ownerStakeCredentialHex); + if (ownerId != null) { + relatedAddressesInfo.push({ + AddressId: ownerId, + Relation: CertificateRelation.OWNER + }); + } + } + } + { // operator + const operatorId = await tryGetKey(operatorStakeCredentialHex); if (operatorId != null) { relatedAddressesInfo.push({ AddressId: operatorId, @@ -2637,125 +2679,19 @@ async function certificateToDb( }); } } - - // reward_account - const rewardAddress = RustModule.WalletV4.Address.from_bytes( - Buffer.from(cert.poolParams.rewardAccount, 'hex') - ); - { + { // reward const addressId = await addressToId(cert.poolParams.rewardAccount); relatedAddressesInfo.push({ AddressId: addressId, Relation: CertificateRelation.REWARD_ADDRESS }); } - const wasmRewardAddress = RustModule.WalletV4.RewardAddress.from_address(rewardAddress); - if (wasmRewardAddress == null) throw new Error(`${nameof(certificateToDb)} registration address not a reward address`); - - // pool owners - const owners = RustModule.WalletV4.Ed25519KeyHashes.new(); - for (let j = 0; j < cert.poolParams.poolOwners.length; j++) { - const owner = cert.poolParams.poolOwners[j]; - // The owners property of the pool parameter is a set of stake key hashes - // of the owners. But the values returned from the backend are a set of - // stake addresses which are "a single header byte identifying their type - // and the network, followed by 28 bytes of payload identifying either a - // stake key hash or a script hash" (CIP19). So we convert the stake - // address to a key hash (equivalent to removing the header byte). - const ownerKey = RustModule.WalletV4.RewardAddress.from_address( - RustModule.WalletV4.Address.from_bytes( - Buffer.from(owner, 'hex') - ) - )?.payment_cred().to_keyhash(); - if (!ownerKey) { - throw new Error(`${nameof(certificateToDb)} expect the pool owner to be a key hash`); - } - owners.add(ownerKey); - const ownerId = await tryGetKey( - RustModule.WalletV4.StakeCredential.from_keyhash(ownerKey) - ); - if (ownerId != null) { - relatedAddressesInfo.push({ - AddressId: ownerId, - Relation: CertificateRelation.OWNER - }); - } - } - - const relays = RustModule.WalletV4.Relays.new(); - for (let j = 0; j < cert.poolParams.relays.length; j++) { - // TODO: skip for now -- not really important - // const relay = cert.poolParams.relays[i]; - // if (relay.ipv4 != null || relay.ipv6 != null) { - // relays.add(RustModule.WalletV4.Relay.new_single_host_addr( - // RustModule.WalletV4.SingleHostAddr.new( - // relay.port == null ? undefined : Number.parseInt(relay.port, 10), - // relay.ipv4, // TODO: how to encode? - // relay.ipv6, - // ) - // )); - // continue; - // } - // if (relay.dnsName != null && relay.port != null) { - // relays.add(RustModule.WalletV4.Relay.new_single_host_name( - // RustModule.WalletV4.SingleHostName.new( - // relay.port == null ? undefined : Number.parseInt(relay.port, 10), - // relay.dnsName, - // ) - // )); - // continue; - // } - // if (relay.dnsName != null) { - // relays.add(RustModule.WalletV4.Relay.new_multi_host_name( - // RustModule.WalletV4.MultiHostName.new( - // relay.dnsName, - // ) - // )); - // continue; - // } - // TODO: what to do about dnsSrvName ? - } - - const poolMetadata = (() => { - if (cert.poolParams.poolMetadata == null) { - return undefined; - } - const metadata = cert.poolParams.poolMetadata; - return RustModule.WalletV4.PoolMetadata.new( - RustModule.WalletV4.URL.new(metadata.url), - RustModule.WalletV4.PoolMetadataHash.from_bytes( - Buffer.from(metadata.metadataHash, 'hex') - ) - ); - })(); - - const certificate = RustModule.WalletV4.PoolRegistration.new( - RustModule.WalletV4.PoolParams.new( - operatorKey, - RustModule.WalletV4.VRFKeyHash.from_bytes( - Buffer.from(cert.poolParams.vrfKeyHash, 'hex') - ), - RustModule.WalletV4.BigNum.from_str(cert.poolParams.pledge), - RustModule.WalletV4.BigNum.from_str(cert.poolParams.cost), - RustModule.WalletV4.UnitInterval.new( - // TODO: dummy data since db-sync doesn't support this yet - RustModule.WalletV4.BigNum.from_str('1'), - RustModule.WalletV4.BigNum.from_str('1'), - // RustModule.WalletV4.BigNum.from_str(cert.poolParams.margin.numerator), - // RustModule.WalletV4.BigNum.from_str(cert.poolParams.margin.denominator), - ), - wasmRewardAddress, - owners, - relays, - poolMetadata - ) - ); result.push((txId: number) => ({ certificate: { Ordinal: cert.certIndex, Kind: RustModule.WalletV4.CertificateKind.PoolRegistration, - Payload: Buffer.from(certificate.to_bytes()).toString('hex'), + Payload: certificateHex, TransactionId: txId, }, relatedAddresses: (certId: number) => relatedAddressesInfo.map(info => ({ @@ -2770,30 +2706,32 @@ async function certificateToDb( AddressId: number, Relation: CertificateRelationType, |}> = []; + const [stakeCredentialHex, certificateHex] = RustModule.WasmScope(Module => { + const poolKeyHash = Module.WalletV4.Ed25519KeyHash + .from_bytes(hexToBytes(cert.poolKeyHash)); + return [ + bytesToHex(Module.WalletV4.StakeCredential + .from_keyhash(poolKeyHash).to_bytes()), + bytesToHex(Module.WalletV4.PoolRetirement + .new(poolKeyHash, cert.epoch).to_bytes()), + ]; + }); - const poolKeyHash = RustModule.WalletV4.Ed25519KeyHash.from_bytes( - Buffer.from(cert.poolKeyHash, 'hex') - ); - const certificate = RustModule.WalletV4.PoolRetirement.new( - poolKeyHash, - cert.epoch - ); - - const poolKeyId = await tryGetKey( - RustModule.WalletV4.StakeCredential.from_keyhash(poolKeyHash) - ); - if (poolKeyId != null) { - relatedAddressesInfo.push({ - AddressId: poolKeyId, - Relation: CertificateRelation.POOL_KEY - }); + { + const poolKeyId = await tryGetKey(stakeCredentialHex); + if (poolKeyId != null) { + relatedAddressesInfo.push({ + AddressId: poolKeyId, + Relation: CertificateRelation.POOL_KEY + }); + } } result.push((txId: number) => ({ certificate: { Ordinal: cert.certIndex, Kind: RustModule.WalletV4.CertificateKind.PoolRetirement, - Payload: Buffer.from(certificate.to_bytes()).toString('hex'), + Payload: certificateHex, TransactionId: txId, }, relatedAddresses: (certId: number) => relatedAddressesInfo.map(info => ({ @@ -2804,24 +2742,22 @@ async function certificateToDb( break; } case ShelleyCertificateTypes.GenesisKeyDelegation: { - const genesisKeyHash = RustModule.WalletV4.GenesisDelegateHash.from_bytes( - Buffer.from(cert.genesisDelegateHash, 'hex') - ); - const certificate = RustModule.WalletV4.GenesisKeyDelegation.new( - RustModule.WalletV4.GenesisHash.from_bytes( - Buffer.from(cert.genesishash, 'hex') - ), - genesisKeyHash, - RustModule.WalletV4.VRFKeyHash.from_bytes( - Buffer.from(cert.vrfKeyHash, 'hex') - ), - ); + const certificateHex = RustModule.WasmScope(Module => bytesToHex( + Module.WalletV4.GenesisKeyDelegation.new( + Module.WalletV4.GenesisHash + .from_bytes(hexToBytes(cert.genesishash)), + Module.WalletV4.GenesisDelegateHash + .from_bytes(hexToBytes(cert.genesisDelegateHash)), + Module.WalletV4.VRFKeyHash + .from_bytes(hexToBytes(cert.vrfKeyHash)), + ).to_bytes() + )); result.push((txId: number) => ({ certificate: { Ordinal: cert.certIndex, Kind: RustModule.WalletV4.CertificateKind.GenesisKeyDelegation, - Payload: Buffer.from(certificate.to_bytes()).toString('hex'), + Payload: certificateHex, TransactionId: txId, }, relatedAddresses: (_certId: number) => [] @@ -2833,45 +2769,48 @@ async function certificateToDb( AddressId: number, Relation: CertificateRelationType, |}> = []; - - const certPot = RustModule.WalletV4.MIRToStakeCredentials.new(); - for (const key of Object.keys(cert.rewards)) { - const rewardAddress = RustModule.WalletV4.RewardAddress.from_address( - RustModule.WalletV4.Address.from_bytes( - Buffer.from(key, 'hex') + const certificateHex = RustModule.WasmScope(Module => { + const certPot = Module.WalletV4.MIRToStakeCredentials.new(); + for (const addressHex of Object.keys(cert.rewards)) { + const rewardAddress = Module.WalletV4.RewardAddress.from_address( + Module.WalletV4.Address.from_bytes(hexToBytes(addressHex)) + ); + if (rewardAddress == null) throw new Error(`${nameof(certificateToDb)} not a valid reward account`); + const stakeCredentials = rewardAddress.payment_cred(); + if (stakeCredentials == null) throw new Error(`${nameof(certificateToDb)} not a valid reward account`); + certPot.insert( + stakeCredentials, + Module.WalletV4.Int.new( + Module.WalletV4.BigNum.from_str(cert.rewards[addressHex]) + ), + ); + } + const certificate = Module.WalletV4.MoveInstantaneousRewardsCert.new( + Module.WalletV4.MoveInstantaneousReward.new_to_stake_creds( + cert.pot, + certPot, ) ); - if (rewardAddress == null) throw new Error(`${nameof(certificateToDb)} not a valid reward account`); - const stakeCredentials = rewardAddress.payment_cred(); - if (stakeCredentials == null) throw new Error(`${nameof(certificateToDb)} not a valid reward account`); - certPot.insert( - stakeCredentials, - RustModule.WalletV4.Int.new( - RustModule.WalletV4.BigNum.from_str(cert.rewards[key]) - ), - ); + return bytesToHex(certificate.to_bytes()); + }); - const rewardAddrKey = await findOwnAddress( - Buffer.from(rewardAddress.to_address().to_bytes()).toString('hex') - ); - if (rewardAddrKey != null) { - relatedAddressesInfo.push({ - AddressId: rewardAddrKey, - Relation: CertificateRelation.REWARD_ADDRESS - }); + { + for (const addressHex of Object.keys(cert.rewards)) { + const rewardAddrKey = await findOwnAddress(addressHex); + if (rewardAddrKey != null) { + relatedAddressesInfo.push({ + AddressId: rewardAddrKey, + Relation: CertificateRelation.REWARD_ADDRESS + }); + } } } - const certificate = RustModule.WalletV4.MoveInstantaneousRewardsCert.new( - RustModule.WalletV4.MoveInstantaneousReward.new_to_stake_creds( - cert.pot, - certPot, - ) - ); + result.push((txId: number) => ({ certificate: { Ordinal: cert.certIndex, Kind: RustModule.WalletV4.CertificateKind.MoveInstantaneousRewardsCert, - Payload: Buffer.from(certificate.to_bytes()).toString('hex'), + Payload: certificateHex, TransactionId: txId, }, relatedAddresses: (certId: number) => relatedAddressesInfo.map(info => ({ @@ -2952,13 +2891,15 @@ function toRequestAddresses( .filter(address => address.Type === CoreAddressTypes.CARDANO_ENTERPRISE) .reduce( (list, next) => { - const wasmAddr = RustModule.WalletV4.Address.from_bytes(Buffer.from(next.Hash, 'hex')); - const enterpriseWasm = RustModule.WalletV4.EnterpriseAddress.from_address(wasmAddr); - if (enterpriseWasm == null) return list; - const keyHash = enterpriseWasm.payment_cred().to_keyhash(); - if (keyHash == null) return list; - list.push(keyHash.to_bech32(Bech32Prefix.PAYMENT_KEY_HASH)); - return list; + return RustModule.WasmScope(Module => { + const wasmAddr = Module.WalletV4.Address.from_bytes(Buffer.from(next.Hash, 'hex')); + const enterpriseWasm = Module.WalletV4.EnterpriseAddress.from_address(wasmAddr); + if (enterpriseWasm == null) return list; + const keyHash = enterpriseWasm.payment_cred().to_keyhash(); + if (keyHash == null) return list; + list.push(keyHash.to_bech32(Bech32Prefix.PAYMENT_KEY_HASH)); + return list; + }); }, [] ), From 6f3790bacb1fa23eb4c684c105bd9e6664cb6bf5 Mon Sep 17 00:00:00 2001 From: vantuz-subhuman Date: Tue, 10 Jan 2023 19:36:09 +0300 Subject: [PATCH 109/172] flow fixes --- .../app/api/ada/lib/cardanoCrypto/rustLoader.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/packages/yoroi-extension/app/api/ada/lib/cardanoCrypto/rustLoader.js b/packages/yoroi-extension/app/api/ada/lib/cardanoCrypto/rustLoader.js index 6ae072e359..b7c7869c01 100644 --- a/packages/yoroi-extension/app/api/ada/lib/cardanoCrypto/rustLoader.js +++ b/packages/yoroi-extension/app/api/ada/lib/cardanoCrypto/rustLoader.js @@ -156,13 +156,14 @@ class Module { WasmScope(callback: Module => T): T { const scope = createWasmScope(); const result = callback(scope.RustModule); - function resolve(res): T { + function resolve(res: T): T { scope.free(); if (isWasmPointer(res)) { throw new Error('A wasm object cannot be returned from wasm scope, all pointers are destroyed.'); } return res; } + // $FlowFixMe[incompatible-type] return typeof result.then === 'function' ? result.then(resolve) : resolve(result); } From 6d584d00f0b28bb2667c8e2dbbf6297b3c4f8c2e Mon Sep 17 00:00:00 2001 From: vantuz-subhuman Date: Tue, 10 Jan 2023 21:29:54 +0300 Subject: [PATCH 110/172] adding proper error handling --- .../api/ada/lib/cardanoCrypto/rustLoader.js | 29 +++++++++++++++---- 1 file changed, 24 insertions(+), 5 deletions(-) diff --git a/packages/yoroi-extension/app/api/ada/lib/cardanoCrypto/rustLoader.js b/packages/yoroi-extension/app/api/ada/lib/cardanoCrypto/rustLoader.js index b7c7869c01..c4f8e07ca6 100644 --- a/packages/yoroi-extension/app/api/ada/lib/cardanoCrypto/rustLoader.js +++ b/packages/yoroi-extension/app/api/ada/lib/cardanoCrypto/rustLoader.js @@ -21,6 +21,10 @@ function isWasmPointer(o: ?any): boolean { return o != null && o.ptr != null && o.free != null; } +function isPromise(o: ?any): boolean { + return o != null && (typeof o.then === 'function') && (typeof o.catch === 'function'); +} + /** * Creates a new proxied RustModule scope. * Return fields: @@ -109,7 +113,14 @@ function createWasmScope(): {| // is linked to the specific scope that will be destroyed. return { RustModule: recursiveProxy(RustModule), - free: () => { scope.forEach(x => x.free()); }, + free: () => { + scope.forEach(x => { + // Checking just to avoid a null-pointer crash + if (x.ptr !== 0) { + x.free() + } + }); + }, } } @@ -155,16 +166,24 @@ class Module { */ WasmScope(callback: Module => T): T { const scope = createWasmScope(); - const result = callback(scope.RustModule); - function resolve(res: T): T { + function onSuccess(res: T): T { scope.free(); if (isWasmPointer(res)) { throw new Error('A wasm object cannot be returned from wasm scope, all pointers are destroyed.'); } return res; } - // $FlowFixMe[incompatible-type] - return typeof result.then === 'function' ? result.then(resolve) : resolve(result); + function onFailure(err: Error): void { + scope.free(); + throw err; + } + let result; + try { + result = callback(scope.RustModule); + } catch (e) { onFailure(e); } + return isPromise(result) + ? result.then(onSuccess, onFailure) + : onSuccess(result); } // Need to expose through a getter to get Flow to detect the type correctly From e5c8b6b48075dffe38fc8bc3edb0f566a8023173 Mon Sep 17 00:00:00 2001 From: vantuz-subhuman Date: Tue, 10 Jan 2023 21:33:10 +0300 Subject: [PATCH 111/172] rolling back unnecessary changes in imports --- .../lib/storage/bridge/updateTransactions.js | 149 +++++++++++------- 1 file changed, 95 insertions(+), 54 deletions(-) diff --git a/packages/yoroi-extension/app/api/ada/lib/storage/bridge/updateTransactions.js b/packages/yoroi-extension/app/api/ada/lib/storage/bridge/updateTransactions.js index 76fd89c16d..18856d5c73 100644 --- a/packages/yoroi-extension/app/api/ada/lib/storage/bridge/updateTransactions.js +++ b/packages/yoroi-extension/app/api/ada/lib/storage/bridge/updateTransactions.js @@ -3,113 +3,154 @@ import BigNumber from 'bignumber.js'; import { isEqual } from 'lodash'; import ObjectHash from 'object-hash'; -import type { lf$Database, lf$Transaction, } from 'lovefield'; +import type { + lf$Database, lf$Transaction, +} from 'lovefield'; -import { getAllSchemaTables, mapToTables, raii, } from '../database/utils'; +import { + getAllSchemaTables, + raii, + mapToTables, +} from '../database/utils'; import type { - AddressRow, - BlockInsert, - BlockRow, - CardanoAssetMintMetadata, + BlockInsert, BlockRow, + TransactionInsert, TransactionRow, CardanoByronTransactionInsert, CardanoShelleyTransactionInsert, - DbBlock, NetworkRow, - TokenListInsert, + DbBlock, + AddressRow, TokenRow, - TransactionInsert, - TransactionRow, + TokenListInsert, + CardanoAssetMintMetadata, } from '../database/primitives/tables'; -import { TransactionType, } from '../database/primitives/tables'; -import type { CertificateRelationType, CoreAddressT, TxStatusCodesType, } from '../database/primitives/enums'; import { - CertificateRelation, - CoreAddressTypes, - PRIMARY_ASSET_CONSTANTS, - TxStatusCodes, + TransactionType, +} from '../database/primitives/tables'; +import type { + TxStatusCodesType, + CertificateRelationType, + CoreAddressT, } from '../database/primitives/enums'; import { - AssociateToken, GetAddress, GetBlock, - GetCertificates, - GetDerivationsByPath, GetEncryptionMeta, - GetKeyDerivation, GetPathWithSpecific, - GetToken, + GetDerivationsByPath, GetTransaction, GetTxAndBlock, + GetCertificates, + GetKeyDerivation, + GetToken, + AssociateToken, } from '../database/primitives/api/read'; -import type { AddCertificateRequest } from '../database/primitives/api/write'; import { - FreeBlocks, ModifyAddress, + ModifyTransaction, + FreeBlocks, ModifyToken, ModifyTokenList, - ModifyTransaction, } from '../database/primitives/api/write'; -import { ModifyCardanoByronTx, ModifyCardanoShelleyTx } from '../database/transactionModels/multipart/api/write'; +import type { AddCertificateRequest } from '../database/primitives/api/write'; +import { ModifyCardanoByronTx, ModifyCardanoShelleyTx } from '../database/transactionModels/multipart/api/write'; import { digestForHash, } from '../database/primitives/api/utils'; -import { MarkUtxo, } from '../database/transactionModels/utxo/api/write'; import { + MarkUtxo, +} from '../database/transactionModels/utxo/api/write'; +import { + GetUtxoTxOutputsWithTx, + GetUtxoInputs, AssociateTxWithUtxoIOs, createTokenListIdGenFunction, - GetUtxoInputs, - GetUtxoTxOutputsWithTx, } from '../database/transactionModels/utxo/api/read'; -import { AssociateTxWithAccountingIOs, } from '../database/transactionModels/account/api/read'; import { - CardanoByronAssociateTxWithIOs, - CardanoShelleyAssociateTxWithIOs, + AssociateTxWithAccountingIOs, +} from '../database/transactionModels/account/api/read'; +import { + CardanoByronAssociateTxWithIOs, CardanoShelleyAssociateTxWithIOs, } from '../database/transactionModels/multipart/api/read'; -import type { UserAnnotation, } from '../../../transactions/types'; -import type { ToAbsoluteSlotNumberFunc, } from '../../../../common/lib/storage/bridge/timeUtils'; import type { - UtxoTransactionInputInsert, - UtxoTransactionOutputInsert, + UserAnnotation, +} from '../../../transactions/types'; +import type { + ToAbsoluteSlotNumberFunc, +} from '../../../../common/lib/storage/bridge/timeUtils'; +import type { + UtxoTransactionInputInsert, UtxoTransactionOutputInsert, } from '../database/transactionModels/utxo/tables'; -import type { AccountingTransactionInputInsert, } from '../database/transactionModels/account/tables'; -import { asHasLevels, asScanAddresses, } from '../models/PublicDeriver/traits'; +import type { + AccountingTransactionInputInsert, +} from '../database/transactionModels/account/tables'; +import { + TxStatusCodes, + CoreAddressTypes, + CertificateRelation, + PRIMARY_ASSET_CONSTANTS, +} from '../database/primitives/enums'; +import { + asScanAddresses, asHasLevels, +} from '../models/PublicDeriver/traits'; import type { IHasLevels } from '../models/ConceptualWallet/interfaces'; import { ConceptualWallet } from '../models/ConceptualWallet/index'; -import type { IPublicDeriver, } from '../models/PublicDeriver/interfaces'; +import type { + IPublicDeriver, +} from '../models/PublicDeriver/interfaces'; import { - GetKeyForPublicDeriver, GetLastSyncForPublicDeriver, GetPublicDeriver, + GetKeyForPublicDeriver, } from '../database/walletTypes/core/api/read'; import { ModifyDisplayCutoff, } from '../database/walletTypes/bip44/api/write'; import { AddDerivationTree, } from '../database/walletTypes/common/api/write'; import { GetDerivationSpecific, } from '../database/walletTypes/common/api/read'; import { getCardanoHaskellBaseConfig, } from '../database/prepackaged/networks'; -import { DeleteAllTransactions, ModifyLastSyncInfo, } from '../database/walletTypes/core/api/write'; +import { + ModifyLastSyncInfo, + DeleteAllTransactions, +} from '../database/walletTypes/core/api/write'; import type { LastSyncInfoRow, } from '../database/walletTypes/core/tables'; import type { CardanoByronTxIO, CardanoShelleyTxIO } from '../database/transactionModels/multipart/tables'; -import { rawGetAddressRowsForWallet, } from './traitUtils'; -import { genToAbsoluteSlotNumber, } from './timeUtils'; -import type { FindOwnAddressFunc, HashToIdsFunc, } from '../../../../common/lib/storage/bridge/hashMapper'; -import { rawGenFindOwnAddress, rawGenHashToIdsFunc, } from '../../../../common/lib/storage/bridge/hashMapper'; +import { + rawGetAddressRowsForWallet, +} from './traitUtils'; +import { + genToAbsoluteSlotNumber, +} from './timeUtils'; +import { + rawGenHashToIdsFunc, rawGenFindOwnAddress, +} from '../../../../common/lib/storage/bridge/hashMapper'; +import type { + HashToIdsFunc, FindOwnAddressFunc, +} from '../../../../common/lib/storage/bridge/hashMapper'; import { CARDANO_STABLE_SIZE } from '../../../../../config/numbersConfig'; import { RollbackApiError } from '../../../../common/errors'; import { getFromUserPerspective, identifierToCardanoAsset, } from '../../../transactions/utils'; import type { - BestBlockFunc, - HistoryFunc, - MultiAssetMintMetadataFunc, - RemoteCertificate, - RemoteTransaction, + HistoryFunc, BestBlockFunc, RemoteTxState, - TokenInfoFunc + RemoteTransaction, + RemoteCertificate, + TokenInfoFunc, + MultiAssetMintMetadataFunc +} from '../../state-fetch/types'; +import { + ShelleyCertificateTypes, + RemoteTransactionTypes, } from '../../state-fetch/types'; -import { RemoteTransactionTypes, ShelleyCertificateTypes, } from '../../state-fetch/types'; -import type { FilterFunc, } from '../../../../common/lib/state-fetch/currencySpecificTypes'; +import type { + FilterFunc, +} from '../../../../common/lib/state-fetch/currencySpecificTypes'; import { addressToKind, } from './utils'; import { RustModule } from '../../cardanoCrypto/rustLoader'; import { Bech32Prefix } from '../../../../../config/stringConfig'; -import type { DefaultTokenEntry, } from '../../../../common/lib/MultiToken'; -import { MultiToken, } from '../../../../common/lib/MultiToken'; +import { + MultiToken, +} from '../../../../common/lib/MultiToken'; +import type { + DefaultTokenEntry, +} from '../../../../common/lib/MultiToken'; import { UtxoStorageApi } from '../models/utils'; import { bytesToHex, hexToBytes } from '../../../../../coreUtils'; From 627ae66f65bda9eb7c3f82c508874cf87b45726c Mon Sep 17 00:00:00 2001 From: vantuz-subhuman Date: Tue, 10 Jan 2023 21:38:08 +0300 Subject: [PATCH 112/172] flow fixes --- .../app/api/ada/lib/cardanoCrypto/rustLoader.js | 3 ++- .../app/api/ada/lib/storage/bridge/updateTransactions.js | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/packages/yoroi-extension/app/api/ada/lib/cardanoCrypto/rustLoader.js b/packages/yoroi-extension/app/api/ada/lib/cardanoCrypto/rustLoader.js index c4f8e07ca6..c64c5150b4 100644 --- a/packages/yoroi-extension/app/api/ada/lib/cardanoCrypto/rustLoader.js +++ b/packages/yoroi-extension/app/api/ada/lib/cardanoCrypto/rustLoader.js @@ -180,8 +180,9 @@ class Module { let result; try { result = callback(scope.RustModule); - } catch (e) { onFailure(e); } + } catch (e) { onFailure(e); throw e; } return isPromise(result) + // $FlowFixMe[incompatible-use] ? result.then(onSuccess, onFailure) : onSuccess(result); } diff --git a/packages/yoroi-extension/app/api/ada/lib/storage/bridge/updateTransactions.js b/packages/yoroi-extension/app/api/ada/lib/storage/bridge/updateTransactions.js index 18856d5c73..fcf8b5b187 100644 --- a/packages/yoroi-extension/app/api/ada/lib/storage/bridge/updateTransactions.js +++ b/packages/yoroi-extension/app/api/ada/lib/storage/bridge/updateTransactions.js @@ -2660,7 +2660,7 @@ async function certificateToDb( ownerStakeCredentialHexes.push(ownerStakeCredentialHex); } - let poolMetadata = null; + let poolMetadata = undefined; if (cert.poolParams.poolMetadata != null) { const metadata = cert.poolParams.poolMetadata; poolMetadata = Module.WalletV4.PoolMetadata.new( From 265eb1dc6682d4714c5be25d23a62e6f544fe731 Mon Sep 17 00:00:00 2001 From: vantuz-subhuman Date: Tue, 10 Jan 2023 22:46:41 +0300 Subject: [PATCH 113/172] comment fix --- .../app/api/ada/lib/cardanoCrypto/rustLoader.js | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/packages/yoroi-extension/app/api/ada/lib/cardanoCrypto/rustLoader.js b/packages/yoroi-extension/app/api/ada/lib/cardanoCrypto/rustLoader.js index c64c5150b4..94055470e9 100644 --- a/packages/yoroi-extension/app/api/ada/lib/cardanoCrypto/rustLoader.js +++ b/packages/yoroi-extension/app/api/ada/lib/cardanoCrypto/rustLoader.js @@ -151,8 +151,8 @@ class Module { } /** - * The argument to this function is an async callback. - * The callback will receive a link to the `RustModule` class. + * The argument to this function is a callback. + * The callback will receive a link to a `RustModule` instance. * Any wasm pointer created within the callback will be automatically destroyed * after the callback ends, but only if it was created using the passed module. * @@ -163,6 +163,11 @@ class Module { * BUT the result cannot be a wasm object as all pointers are getting destroyed * before this function returns. If the result will be detected to be a wasm pointer, * an exception will be raised. + * + * NOTE: the callback can be an async function or any function that returns a promise. + * In that case the return of this function will also be a promise that will resolve + * to the same result from the callback. The wasm pointers will be destroyed once the + * callback promise resolves. */ WasmScope(callback: Module => T): T { const scope = createWasmScope(); From ae87286ed93f40e374737ca6e3d8aa806ea7d461 Mon Sep 17 00:00:00 2001 From: Ahmed Ibrahim Date: Wed, 11 Jan 2023 12:55:06 +0200 Subject: [PATCH 114/172] Remove wallet dropdown & quick access feature --- .../app/api/localStorage/index.js | 2 - .../add-wallet/wallet-list/star.inline.svg | 6 -- .../add-wallet/wallet-list/stared.inline.svg | 6 -- .../topbar/NavDropdownContentRevamp.js | 45 --------- .../topbar/NavDropdownContentRevamp.scss | 32 ------- .../components/topbar/NavDropdownRevamp.js | 64 ------------- .../components/topbar/NavDropdownRevamp.scss | 26 ------ .../components/topbar/NavDropdownRowRevamp.js | 73 --------------- .../topbar/NavDropdownRowRevamp.scss | 38 -------- .../topbar/NavWalletDetailsRevamp.js | 5 +- .../components/topbar/NoWalletsAccessList.js | 42 --------- .../topbar/NoWalletsAccessList.scss | 28 ------ .../topbar/QuickAccessListHeader.js | 49 ---------- .../topbar/QuickAccessWalletCard.js | 91 ------------------- .../topbar/QuickAccessWalletCard.scss | 62 ------------- .../topbar/QuickAccessWalletsList.js | 33 ------- .../topbar/QuickAccessWalletsList.scss | 9 -- .../app/components/topbar/WalletCard.js | 31 ------- .../app/components/topbar/WalletCard.scss | 18 ---- .../app/components/topbar/WalletListDialog.js | 25 ----- .../app/containers/NavBarContainerRevamp.js | 67 +------------- .../categories/RemoveWalletDialogContainer.js | 3 +- .../app/i18n/locales/en-US.json | 4 - .../app/stores/toplevel/ProfileStore.js | 2 +- 24 files changed, 7 insertions(+), 754 deletions(-) delete mode 100644 packages/yoroi-extension/app/assets/images/add-wallet/wallet-list/star.inline.svg delete mode 100644 packages/yoroi-extension/app/assets/images/add-wallet/wallet-list/stared.inline.svg delete mode 100644 packages/yoroi-extension/app/components/topbar/NavDropdownContentRevamp.js delete mode 100644 packages/yoroi-extension/app/components/topbar/NavDropdownContentRevamp.scss delete mode 100644 packages/yoroi-extension/app/components/topbar/NavDropdownRevamp.js delete mode 100644 packages/yoroi-extension/app/components/topbar/NavDropdownRevamp.scss delete mode 100644 packages/yoroi-extension/app/components/topbar/NavDropdownRowRevamp.js delete mode 100644 packages/yoroi-extension/app/components/topbar/NavDropdownRowRevamp.scss delete mode 100644 packages/yoroi-extension/app/components/topbar/NoWalletsAccessList.js delete mode 100644 packages/yoroi-extension/app/components/topbar/NoWalletsAccessList.scss delete mode 100644 packages/yoroi-extension/app/components/topbar/QuickAccessListHeader.js delete mode 100644 packages/yoroi-extension/app/components/topbar/QuickAccessWalletCard.js delete mode 100644 packages/yoroi-extension/app/components/topbar/QuickAccessWalletCard.scss delete mode 100644 packages/yoroi-extension/app/components/topbar/QuickAccessWalletsList.js delete mode 100644 packages/yoroi-extension/app/components/topbar/QuickAccessWalletsList.scss diff --git a/packages/yoroi-extension/app/api/localStorage/index.js b/packages/yoroi-extension/app/api/localStorage/index.js index 691a431d12..61a38ad860 100644 --- a/packages/yoroi-extension/app/api/localStorage/index.js +++ b/packages/yoroi-extension/app/api/localStorage/index.js @@ -46,7 +46,6 @@ export type SetCustomUserThemeRequest = {| export type WalletsNavigation = {| ergo: number[], cardano: number[], - quickAccess: number[], |} /** @@ -286,7 +285,6 @@ export default class LocalStorageApi { if(Array.isArray(result)) return { cardano: [], ergo: [], - quickAccess: [], } return result diff --git a/packages/yoroi-extension/app/assets/images/add-wallet/wallet-list/star.inline.svg b/packages/yoroi-extension/app/assets/images/add-wallet/wallet-list/star.inline.svg deleted file mode 100644 index 56462429f6..0000000000 --- a/packages/yoroi-extension/app/assets/images/add-wallet/wallet-list/star.inline.svg +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/packages/yoroi-extension/app/assets/images/add-wallet/wallet-list/stared.inline.svg b/packages/yoroi-extension/app/assets/images/add-wallet/wallet-list/stared.inline.svg deleted file mode 100644 index 43a43becfb..0000000000 --- a/packages/yoroi-extension/app/assets/images/add-wallet/wallet-list/stared.inline.svg +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/packages/yoroi-extension/app/components/topbar/NavDropdownContentRevamp.js b/packages/yoroi-extension/app/components/topbar/NavDropdownContentRevamp.js deleted file mode 100644 index 8539546f85..0000000000 --- a/packages/yoroi-extension/app/components/topbar/NavDropdownContentRevamp.js +++ /dev/null @@ -1,45 +0,0 @@ -// @flow -import { Component } from 'react'; -import type { Node } from 'react'; -import { observer } from 'mobx-react'; -import styles from './NavDropdownContentRevamp.scss'; -import { intlShape } from 'react-intl'; -import type { $npm$ReactIntl$IntlFormat } from 'react-intl'; -import globalMessages from '../../i18n/global-messages'; -import { Button } from '@mui/material'; - -type Props = {| - +openWalletInfoDialog: void => void, - +contentComponents?: ?Node, - +walletsCount?: number, -|}; - -@observer -export default class NavDropdownContentRevamp extends Component { - static contextTypes: {| intl: $npm$ReactIntl$IntlFormat |} = { - intl: intlShape.isRequired, - }; - static defaultProps: {| contentComponents: void, walletsCount: void |} = { - contentComponents: undefined, - walletsCount: undefined, - }; - - render(): Node { - const { contentComponents, walletsCount, openWalletInfoDialog } = this.props; - const { intl } = this.context; - - return ( -
-
- {contentComponents} -
- -
-
-
- ); - } -} diff --git a/packages/yoroi-extension/app/components/topbar/NavDropdownContentRevamp.scss b/packages/yoroi-extension/app/components/topbar/NavDropdownContentRevamp.scss deleted file mode 100644 index dff7f62386..0000000000 --- a/packages/yoroi-extension/app/components/topbar/NavDropdownContentRevamp.scss +++ /dev/null @@ -1,32 +0,0 @@ -.wrapper { - position: absolute; - padding-top: 33px; - top: 30px; - width: 100%; - right: 0; - z-index: 1; -} - -.card { - overflow: hidden; - - border-radius: 8px; - background-color: #FFF; - width: 100%; - border: 1px solid #eaedf2; - box-shadow: 0 10px 30px 0 rgba(24, 26, 30, 0.12); -} - -.footer { - border-top: 1px solid #dce0e9; - display: flex; - justify-content: center; - button { - padding: 20px 0; - color: var(--yoroi-palette-secondary-300); - text-transform: uppercase; - font-size: 14px; - text-align: center; - font-weight: 500; - } -} diff --git a/packages/yoroi-extension/app/components/topbar/NavDropdownRevamp.js b/packages/yoroi-extension/app/components/topbar/NavDropdownRevamp.js deleted file mode 100644 index 72fab3e5f0..0000000000 --- a/packages/yoroi-extension/app/components/topbar/NavDropdownRevamp.js +++ /dev/null @@ -1,64 +0,0 @@ -// @flow -import React, { Component } from 'react'; -import type { Node, ElementRef } from 'react'; -import { observer } from 'mobx-react'; -import styles from './NavDropdownRevamp.scss'; - -import NavDropdownContentRevamp from './NavDropdownContentRevamp'; - -type Props = {| - +headerComponent?: ?Node, - +contentComponents?: ?Node, - +walletsCount?: number, - +openWalletInfoDialog: void => void, -|}; - -type State = {| - isExpanded: boolean, -|}; - -@observer -export default class NavDropdownRevamp extends Component { - static defaultProps: {| contentComponents: void, headerComponent: void, walletsCount: void |} = { - headerComponent: undefined, - contentComponents: undefined, - walletsCount: undefined, - }; - - state: State = { - isExpanded: false, - }; - - buttonRef: ?ElementRef<*>; - - constructor(props: Props) { - super(props); - this.buttonRef = React.createRef(); - } - - toggleExpansion: void => void = () => { - this.setState(prevState => ({ isExpanded: !prevState.isExpanded })); - }; - - render(): Node { - const { headerComponent, contentComponents, walletsCount, openWalletInfoDialog } = this.props; - const { isExpanded } = this.state; - - return ( -
-
{headerComponent}
- {isExpanded ? ( - - ) : null} -
- ); - } -} diff --git a/packages/yoroi-extension/app/components/topbar/NavDropdownRevamp.scss b/packages/yoroi-extension/app/components/topbar/NavDropdownRevamp.scss deleted file mode 100644 index d19f2fba91..0000000000 --- a/packages/yoroi-extension/app/components/topbar/NavDropdownRevamp.scss +++ /dev/null @@ -1,26 +0,0 @@ -.wrapper { - position: relative; - display: flex; - align-items: center; -} -.wrapperHovered { - border: 1px solid #eaedf2; - border-radius: 8px; -} -.icon { - width: 20px; - margin-right: 20px; - height: 20px; -} -.component { - flex: 1; -} - -.toggle { - margin-left: auto; - transition: background-color 0.4s; - &:hover { - cursor: pointer; - background-color: #ededed; - } -} diff --git a/packages/yoroi-extension/app/components/topbar/NavDropdownRowRevamp.js b/packages/yoroi-extension/app/components/topbar/NavDropdownRowRevamp.js deleted file mode 100644 index f88e3f83bf..0000000000 --- a/packages/yoroi-extension/app/components/topbar/NavDropdownRowRevamp.js +++ /dev/null @@ -1,73 +0,0 @@ -// @flow -import { Component } from 'react'; -import type { Node } from 'react'; -import { observer } from 'mobx-react'; -import { intlShape } from 'react-intl'; -import classnames from 'classnames'; -import styles from './NavDropdownRowRevamp.scss'; -import type { $npm$ReactIntl$IntlFormat } from 'react-intl'; - -type Props = {| - +title?: string, - +plateComponent?: ?Node, - +detailComponent: ?Node, - /** - * null -> never synced - * undefined -> don't display sync info - */ - +syncTime?: void | null | string, - +isCurrentWallet?: boolean, - +onSelect?: void => void, -|}; - -@observer -export default class NavDropdownRowRevamp extends Component { - static contextTypes: {| intl: $npm$ReactIntl$IntlFormat |} = { - intl: intlShape.isRequired, - }; - - static defaultProps: {| - isCurrentWallet: boolean, - onSelect: void, - plateComponent: void, - syncTime: void, - title: void, - |} = { - title: undefined, - plateComponent: undefined, - syncTime: undefined, - onSelect: undefined, - isCurrentWallet: false, - }; - - render(): Node { - const { title, plateComponent, isCurrentWallet } = this.props; - - const wrapperClassname = classnames( - styles.wrapper, - isCurrentWallet !== null && isCurrentWallet === true && styles.currentWrapper, - plateComponent === undefined && title !== undefined && styles.titleWrapper - ); - - const titleSection = this.getHead(); - return
{titleSection}
; - } - - getHead: void => Node = () => { - if (this.props.plateComponent != null && this.props.onSelect != null) { - if (this.props.isCurrentWallet !== true) { - return ( - - ); - } - return
{this.props.plateComponent}
; - } - return ( -
-

{this.props.title}

-
- ); - }; -} diff --git a/packages/yoroi-extension/app/components/topbar/NavDropdownRowRevamp.scss b/packages/yoroi-extension/app/components/topbar/NavDropdownRowRevamp.scss deleted file mode 100644 index b3e4537ad5..0000000000 --- a/packages/yoroi-extension/app/components/topbar/NavDropdownRowRevamp.scss +++ /dev/null @@ -1,38 +0,0 @@ -.wrapper { - padding: 20px 20px 20px 30px; - display: flex; - background-color: var(--yoroi-palette-common-white); -} - -.titleWrapper { - padding: 24px 100px 40px 40px; -} - -.title { - color: var(--yoroi-palette-gray-600); - font-size: 18px; - font-weight: 500; - line-height: 22px; - text-align: left; -} - -.currentWrapper { - background-color: var(--yoroi-palette-gray-50); -} - -.head { - min-width: 300px; -} -button { - &:hover { - cursor: pointer; - } -} - -.details { - flex: 1; -} - -.syncLabel { - color: var(--yoroi-palette-gray-600); -} diff --git a/packages/yoroi-extension/app/components/topbar/NavWalletDetailsRevamp.js b/packages/yoroi-extension/app/components/topbar/NavWalletDetailsRevamp.js index 7df79ff5af..da63bcf6a9 100644 --- a/packages/yoroi-extension/app/components/topbar/NavWalletDetailsRevamp.js +++ b/packages/yoroi-extension/app/components/topbar/NavWalletDetailsRevamp.js @@ -87,6 +87,7 @@ export default class NavWalletDetailsRevamp extends Component { plate, unitOfAccountSetting, getCurrentPrice, + openWalletInfoDialog } = this.props; const totalAmount = this.getTotalAmount(); @@ -97,7 +98,7 @@ export default class NavWalletDetailsRevamp extends Component { return (
-
+
-
+ diff --git a/packages/yoroi-extension/app/components/topbar/NoWalletsAccessList.js b/packages/yoroi-extension/app/components/topbar/NoWalletsAccessList.js deleted file mode 100644 index 1f293a585f..0000000000 --- a/packages/yoroi-extension/app/components/topbar/NoWalletsAccessList.js +++ /dev/null @@ -1,42 +0,0 @@ -// @flow -import { Component } from 'react'; -import type { Node } from 'react'; -import { observer } from 'mobx-react'; -import { defineMessages, intlShape } from 'react-intl'; -import type { $npm$ReactIntl$IntlFormat } from 'react-intl'; -import styles from './NoWalletsAccessList.scss'; -import QuickAccessListheader from './QuickAccessListHeader'; - -const messages = defineMessages({ - noWallets: { - id: 'wallet.nav.noWalletsAccessList.noWallets', - defaultMessage: '!!!No wallets added to this list yet', - }, - goToWallets: { - id: 'wallet.nav.noWalletsAccessList.goToWallets', - defaultMessage: '!!!Go to all my wallets and star those you use most often', - }, -}); - -type Props = {||}; - -@observer -export default class NoWalletsAccessList extends Component { - static contextTypes: {| intl: $npm$ReactIntl$IntlFormat |} = { - intl: intlShape.isRequired, - }; - - render(): Node { - const { intl } = this.context; - - return ( -
- -
-

{intl.formatMessage(messages.noWallets)}

-

{intl.formatMessage(messages.goToWallets)}

-
-
- ); - } -} diff --git a/packages/yoroi-extension/app/components/topbar/NoWalletsAccessList.scss b/packages/yoroi-extension/app/components/topbar/NoWalletsAccessList.scss deleted file mode 100644 index 127f3e8018..0000000000 --- a/packages/yoroi-extension/app/components/topbar/NoWalletsAccessList.scss +++ /dev/null @@ -1,28 +0,0 @@ -@import '../../themes/mixins/loading-spinner'; - -.wrapper { - flex: 1; - display: flex; - flex-direction: column; - justify-content: center; - padding: 40px 36px; - text-align: center; -} - -.content { - padding: 60px 0; -} - -.noWallets { - color: var(--yoroi-palette-gray-600); - font-size: 1rem; - margin-bottom: 4px; - color: inherit; - line-height: 22px; -} -.goToWallets { - color: var(--yoroi-palette-gray-600); - font-size: 12px; - line-height: 20px; - color: inherit; -} diff --git a/packages/yoroi-extension/app/components/topbar/QuickAccessListHeader.js b/packages/yoroi-extension/app/components/topbar/QuickAccessListHeader.js deleted file mode 100644 index 02ae57f3c0..0000000000 --- a/packages/yoroi-extension/app/components/topbar/QuickAccessListHeader.js +++ /dev/null @@ -1,49 +0,0 @@ -// @flow -import { Component } from 'react'; -import type { Node } from 'react'; -import { observer } from 'mobx-react'; -import { defineMessages, intlShape } from 'react-intl'; -import type { $npm$ReactIntl$IntlFormat } from 'react-intl'; -import { ReactComponent as StarIcon } from '../../assets/images/add-wallet/wallet-list/stared.inline.svg'; -import { Box } from '@mui/system'; -import { Typography } from '@mui/material'; - -const messages = defineMessages({ - quickAccess: { - id: 'wallet.nav.noWalletsAccessList.quickAccess', - defaultMessage: '!!!Quick access wallets', - }, -}); - -type Props = {||}; - -@observer -export default class QuickAccessListheader extends Component { - static contextTypes: {| intl: $npm$ReactIntl$IntlFormat |} = { - intl: intlShape.isRequired, - }; - - render(): Node { - const { intl } = this.context; - - return ( - svg': { marginRight: '8px' } - }} - > - - {intl.formatMessage(messages.quickAccess)} - - - ); - } -} diff --git a/packages/yoroi-extension/app/components/topbar/QuickAccessWalletCard.js b/packages/yoroi-extension/app/components/topbar/QuickAccessWalletCard.js deleted file mode 100644 index 65348748bc..0000000000 --- a/packages/yoroi-extension/app/components/topbar/QuickAccessWalletCard.js +++ /dev/null @@ -1,91 +0,0 @@ -// @flow -import { Component } from 'react'; -import type { Node } from 'react'; -import { observer } from 'mobx-react'; -import { intlShape } from 'react-intl'; -import type { $npm$ReactIntl$IntlFormat } from 'react-intl'; -import styles from './QuickAccessWalletCard.scss' -import { getType } from '../../utils/walletInfo'; -import { constructPlate } from './WalletCard'; -import { MultiToken } from '../../api/common/lib/MultiToken'; -import AmountDisplay from '../common/AmountDisplay'; -import type { WalletChecksum } from '@emurgo/cip4-js'; -import type { ConceptualWallet } from '../../api/ada/lib/storage/models/ConceptualWallet'; -import type { TokenLookupKey } from '../../api/common/lib/MultiToken'; -import type { TokenRow } from '../../api/ada/lib/storage/database/primitives/tables'; -import type { UnitOfAccountSettingType } from '../../types/unitOfAccountType'; - -type Props = {| - +plate: null | WalletChecksum, - +wallet: {| - conceptualWallet: ConceptualWallet, - conceptualWalletName: string, - |}, - +rewards: null | void | MultiToken, - +shouldHideBalance: boolean, - +walletAmount: null | MultiToken, - +getTokenInfo: ($ReadOnly>) => $ReadOnly, - +unitOfAccountSetting: UnitOfAccountSettingType, - +getCurrentPrice: (from: string, to: string) => ?string, -|} - -@observer -export default class QuickAccessWalletCard extends Component { - static contextTypes: {| intl: $npm$ReactIntl$IntlFormat |} = { - intl: intlShape.isRequired, - }; - - render(): Node { - const { intl } = this.context; - const { - shouldHideBalance, - unitOfAccountSetting, - getCurrentPrice, - } = this.props; - - const [, iconComponent] = this.props.plate - ? constructPlate(this.props.plate, 0, styles.main) - : []; - - const typeText = [getType(this.props.wallet.conceptualWallet)] - .filter(text => text != null) - .map(text => intl.formatMessage(text)) - .join(' - '); - const totalAmount = this.getTotalAmount(); - - return ( -
-
-
{this.props.wallet.conceptualWalletName}
- {' · '} -
{typeText}
-
-
-
{iconComponent}
-
-
- -
-
-
-
- ) - } - - getTotalAmount: void => null | MultiToken = () => { - if (this.props.rewards === undefined) { - return this.props.walletAmount; - } - if (this.props.rewards === null || this.props.walletAmount === null) { - return null; - } - return this.props.rewards.joinAddCopy(this.props.walletAmount); - }; -} diff --git a/packages/yoroi-extension/app/components/topbar/QuickAccessWalletCard.scss b/packages/yoroi-extension/app/components/topbar/QuickAccessWalletCard.scss deleted file mode 100644 index d74e3eb71a..0000000000 --- a/packages/yoroi-extension/app/components/topbar/QuickAccessWalletCard.scss +++ /dev/null @@ -1,62 +0,0 @@ -@import '../../themes/mixins/loading-spinner'; - -.component { - margin-top: 20px; - - .header { - display: flex; - color: var(--yoroi-palette-gray-900); - font-size: 14px; - letter-spacing: 0; - line-height: 22px; - margin-bottom: 8px; - - .name { - margin-right: 4px; - } - - .type { - margin-left: 4px; - } - } - - .body { - display: flex; - align-items: center; - margin-top: 0px; - - .isLoading { - position: relative; - display: flex; - align-items: center; - justify-content: center; - margin-left: 15px; - } - - .amount { - margin-left: 12px; - flex: 1; - - & > p:nth-child(2) { - margin-top: 5px; - } - } - - .fixedAmount { - margin-left: 12px; - color: var(--yoroi-palette-gray-600); - font-size: 14px; - letter-spacing: 0; - line-height: 22px; - } - } -} - -.main { - flex: 1; - canvas { - width: 32px !important; - height: 32px !important; - border-radius: 50%; - } -} \ No newline at end of file diff --git a/packages/yoroi-extension/app/components/topbar/QuickAccessWalletsList.js b/packages/yoroi-extension/app/components/topbar/QuickAccessWalletsList.js deleted file mode 100644 index dcaa05700f..0000000000 --- a/packages/yoroi-extension/app/components/topbar/QuickAccessWalletsList.js +++ /dev/null @@ -1,33 +0,0 @@ -// @flow -import { Component } from 'react'; -import type { Node } from 'react'; -import { observer } from 'mobx-react'; -import QuickAccessListheader from './QuickAccessListHeader'; -import styles from './QuickAccessWalletsList.scss' -import QuickAccessWalletCard from './QuickAccessWalletCard'; -import type { UnitOfAccountSettingType } from '../../types/unitOfAccountType'; - -type Props = {| - +wallets: Array, - +unitOfAccountSetting: UnitOfAccountSettingType, - +getCurrentPrice: (from: string, to: string) => ?string, -|} -@observer -export default class QuickAccessWalletsList extends Component { - render(): Node { - return ( -
- -
- {this.props.wallets.map(wallet => ( - - ))} -
-
- ) - } -} diff --git a/packages/yoroi-extension/app/components/topbar/QuickAccessWalletsList.scss b/packages/yoroi-extension/app/components/topbar/QuickAccessWalletsList.scss deleted file mode 100644 index e3281ff76d..0000000000 --- a/packages/yoroi-extension/app/components/topbar/QuickAccessWalletsList.scss +++ /dev/null @@ -1,9 +0,0 @@ -.component { - padding: 40px 24px 24px 24px; - height: 330px; - overflow: auto; - - .walletsList { - margin-top: 20px; - } -} \ No newline at end of file diff --git a/packages/yoroi-extension/app/components/topbar/WalletCard.js b/packages/yoroi-extension/app/components/topbar/WalletCard.js index 3420ef1ad8..1daac160d1 100644 --- a/packages/yoroi-extension/app/components/topbar/WalletCard.js +++ b/packages/yoroi-extension/app/components/topbar/WalletCard.js @@ -18,12 +18,8 @@ import { import type { TokenLookupKey } from '../../api/common/lib/MultiToken'; import type { TokenRow } from '../../api/ada/lib/storage/database/primitives/tables'; import { ReactComponent as DragIcon } from '../../assets/images/add-wallet/wallet-list/drag.inline.svg'; -import { ReactComponent as StarIcon } from '../../assets/images/add-wallet/wallet-list/star.inline.svg'; -import { ReactComponent as StaredIcon } from '../../assets/images/add-wallet/wallet-list/stared.inline.svg'; - import { Draggable } from 'react-beautiful-dnd'; import type { UnitOfAccountSettingType } from '../../types/unitOfAccountType'; -import { Tooltip, Typography } from '@mui/material'; import AmountDisplay from '../common/AmountDisplay'; import { PublicDeriver } from '../../api/ada/lib/storage/models/PublicDeriver'; @@ -32,10 +28,6 @@ const messages = defineMessages({ id: 'wallet.topbar.dialog.tokenTypes', defaultMessage: '!!!Token types', }, - quickAccessTooltip: { - id: 'wallet.topbar.dialog.quickAccess', - defaultMessage: '!!!Add to quick acceess wallets list', - } }); type Props = {| @@ -55,8 +47,6 @@ type Props = {| +idx: number, +unitOfAccountSetting: UnitOfAccountSettingType, +getCurrentPrice: (from: string, to: string) => ?string, - +toggleQuickAccess: string => void, - +isInQuickAccess: boolean, |}; type State = {| +isActionsShow: boolean |}; @@ -195,28 +185,7 @@ export default class WalletCard extends Component {
- {!this.props.isInQuickAccess && - - {intl.formatMessage(messages.quickAccessTooltip)} - - } - placement="bottom-end" - > - - } - {this.props.isInQuickAccess && - } )} diff --git a/packages/yoroi-extension/app/components/topbar/WalletCard.scss b/packages/yoroi-extension/app/components/topbar/WalletCard.scss index 8fe353752d..f2934dabff 100644 --- a/packages/yoroi-extension/app/components/topbar/WalletCard.scss +++ b/packages/yoroi-extension/app/components/topbar/WalletCard.scss @@ -101,24 +101,6 @@ } } -.quickAccessToggle { - svg { - max-width: 24px; - max-height: 24px; - color: var(--yoroi-palette-gray-600); - } - - width: 40px; - height: 40px; - border-radius: 50%; - display: flex; - align-items: center; - justify-content: center; - &:hover { - background: #eaedf2; - } -} - .showActions { opacity: 1; } diff --git a/packages/yoroi-extension/app/components/topbar/WalletListDialog.js b/packages/yoroi-extension/app/components/topbar/WalletListDialog.js index 8b756646a2..44a7fdada4 100644 --- a/packages/yoroi-extension/app/components/topbar/WalletListDialog.js +++ b/packages/yoroi-extension/app/components/topbar/WalletListDialog.js @@ -123,30 +123,11 @@ export default class WalletListDialog extends Component { await this.props.updateSortedWalletList({ ergo: ergoWalletsId, cardano: cardanoWalletsId, - quickAccess: this.props.walletsNavigation.quickAccess || [], }); } ); } - toggleQuickAccess: number => Promise = async (walletId) => { - if(!walletId || typeof walletId !== 'number') throw new Error('Invalid wallet id.') - const currentQuickAccessList = this.props.walletsNavigation.quickAccess - let updatedQuickAccessList = [...currentQuickAccessList]; - // Remove wallet - if(currentQuickAccessList.indexOf(walletId) !== -1) { - updatedQuickAccessList = updatedQuickAccessList.filter(id => id !== walletId) - } else { - // Add wallet - updatedQuickAccessList.push(walletId) - } - - await this.props.updateSortedWalletList({ - ...this.props.walletsNavigation, - quickAccess: updatedQuickAccessList - }); - } - onDragEnd: (network: 'ergo' | 'cardano' ,result:Object) => any = async (network, result) => { const { destination, source } = result; if (!destination || destination.index === source.index) { @@ -169,7 +150,6 @@ export default class WalletListDialog extends Component { await this.props.updateSortedWalletList({ ergo: this.state.ergoWalletsIdx, cardano: this.state.cardanoWalletsIdx, - quickAccess: this.props.walletsNavigation.quickAccess || [], }); } ); @@ -201,7 +181,6 @@ export default class WalletListDialog extends Component { getCurrentPrice, } = this.props; - const quickAccessList = new Set(this.props.walletsNavigation.quickAccess) const walletsTotal = this.renderWalletsTotal(); return ( @@ -248,8 +227,6 @@ export default class WalletListDialog extends Component { this.setState({ selectedWallet: wallet.wallet })} isCurrentWallet={this.isCurrentWallet(wallet.wallet, 'local')} {...wallet} @@ -281,8 +258,6 @@ export default class WalletListDialog extends Component { this.setState({ selectedWallet: wallet.wallet })} isCurrentWallet={this.isCurrentWallet(wallet.wallet, 'local')} {...wallet} diff --git a/packages/yoroi-extension/app/containers/NavBarContainerRevamp.js b/packages/yoroi-extension/app/containers/NavBarContainerRevamp.js index 37cf4db245..5c00ca097b 100644 --- a/packages/yoroi-extension/app/containers/NavBarContainerRevamp.js +++ b/packages/yoroi-extension/app/containers/NavBarContainerRevamp.js @@ -5,8 +5,6 @@ import type { Node } from 'react'; import { observer } from 'mobx-react'; import type { InjectedOrGenerated } from '../types/injectedPropsType'; import NavBarRevamp from '../components/topbar/NavBarRevamp'; -import NoWalletsDropdown from '../components/topbar/NoWalletsDropdown'; -import NavDropdownRevamp from '../components/topbar/NavDropdownRevamp'; import { ROUTES } from '../routes-config'; import { ConceptualWallet } from '../api/ada/lib/storage/models/ConceptualWallet/index'; import { asGetPublicKey } from '../api/ada/lib/storage/models/PublicDeriver/traits'; @@ -23,13 +21,11 @@ import BuySellDialog from '../components/buySell/BuySellDialog'; import { genLookupOrFail, getTokenName } from '../stores/stateless/tokenHelpers'; import NavWalletDetailsRevamp from '../components/topbar/NavWalletDetailsRevamp'; import BuySellAdaButton from '../components/topbar/BuySellAdaButton'; -import NoWalletsAccessList from '../components/topbar/NoWalletsAccessList'; import WalletListDialog from '../components/topbar/WalletListDialog'; import { networks, isErgo } from '../api/ada/lib/storage/database/prepackaged/networks'; import { addressToDisplayString } from '../api/ada/lib/storage/bridge/utils'; import { getReceiveAddress } from '../stores/stateless/addressStores'; import type { UnitOfAccountSettingType } from '../types/unitOfAccountType'; -import QuickAccessWalletsList from '../components/topbar/QuickAccessWalletsList' import type { WalletsNavigation } from '../api/localStorage'; export type GeneratedData = typeof NavBarContainerRevamp.prototype.generated; @@ -65,22 +61,12 @@ export default class NavBarContainerRevamp extends Component { render(): Node { const { stores } = this.generated; const { profile } = stores; - const walletsStore = stores.wallets; - const wallets = this.generated.stores.wallets.publicDerivers; const DropdownHead = () => { const publicDeriver = walletsStore.selected; - if (publicDeriver == null) { - // TODO: Remove style since for now, we don't have a selected wallet by default - return ( -
- -
- ); - } + if (publicDeriver == null) return null; const parent = publicDeriver.getParent(); - const settingsCache = this.generated.stores.walletSettings.getConceptualWalletSettingsCache( parent ); @@ -108,55 +94,6 @@ export default class NavBarContainerRevamp extends Component { )} unitOfAccountSetting={profile.unitOfAccount} getCurrentPrice={this.generated.stores.coinPriceStore.getCurrentPrice} - /> - ); - }; - - const QuickAccessList = () => { - const quickAccessWallets = this.generated.stores.profile.walletsNavigation.quickAccess - if (!quickAccessWallets || quickAccessWallets.length === 0) return - - const publicDerivers = this.generated.stores.wallets.publicDerivers; - const walletsMap = [] - publicDerivers.forEach(wallet => { - const parent = wallet.getParent(); - const id = wallet.getPublicDeriverId() - if (quickAccessWallets.indexOf(id) === -1) return - const walletTxRequests = this.generated.stores.transactions.getTxRequests(wallet); - const balance = walletTxRequests.requests.getBalanceRequest.result || null; - const settingsCache = this.generated.stores.walletSettings.getConceptualWalletSettingsCache( - parent - ); - const withPubKey = asGetPublicKey(wallet); - const plate = - withPubKey == null - ? null - : this.generated.stores.wallets.getPublicKeyCache(withPubKey).plate; - walletsMap.push({ - walletAmount: balance, - getTokenInfo: genLookupOrFail(this.generated.stores.tokenInfoStore.tokenInfo), - wallet: settingsCache, - shouldHideBalance: this.generated.stores.profile.shouldHideBalance, - plate, - rewards: this.getRewardBalance(wallet), - }) - }) - - return ( - - ) - } - - const DropdownComponent = () => { - return ( - } - contentComponents={} - walletsCount={wallets.length} openWalletInfoDialog={() => { this.generated.actions.dialogs.open.trigger({ dialog: WalletListDialog }); }} @@ -170,7 +107,7 @@ export default class NavBarContainerRevamp extends Component { } + walletDetails={} buyButton={ diff --git a/packages/yoroi-extension/app/containers/settings/categories/RemoveWalletDialogContainer.js b/packages/yoroi-extension/app/containers/settings/categories/RemoveWalletDialogContainer.js index eed5c51322..2daf762c56 100644 --- a/packages/yoroi-extension/app/containers/settings/categories/RemoveWalletDialogContainer.js +++ b/packages/yoroi-extension/app/containers/settings/categories/RemoveWalletDialogContainer.js @@ -62,9 +62,9 @@ class RemoveWalletDialogContainer extends Component { removeWalletRevamp: void => Promise = async () => { const settingsActions = this.generated.actions.walletSettings; - const selectedWalletId = this.props.publicDeriver?.getPublicDeriverId(); const walletsNavigation = this.generated.stores.profile.walletsNavigation; + if (this.props.publicDeriver) { const walletType = getWalletType(this.props.publicDeriver) const newWalletsNavigation = { @@ -73,7 +73,6 @@ class RemoveWalletDialogContainer extends Component { [walletType]: walletsNavigation[walletType].filter( walletId => walletId !== selectedWalletId ), - quickAccess: walletsNavigation.quickAccess.filter(walletId => walletId !== selectedWalletId) } await this.generated.actions.profile.updateSortedWalletList.trigger(newWalletsNavigation); trackRemoveWallet(); diff --git a/packages/yoroi-extension/app/i18n/locales/en-US.json b/packages/yoroi-extension/app/i18n/locales/en-US.json index 6437951904..859a7abb8e 100644 --- a/packages/yoroi-extension/app/i18n/locales/en-US.json +++ b/packages/yoroi-extension/app/i18n/locales/en-US.json @@ -640,9 +640,6 @@ "wallet.nav.allWalletsLabel": "All wallets", "wallet.nav.changeWallet": "Change wallet", "wallet.nav.backButton": "Back to my wallets", - "wallet.nav.noWalletsAccessList.goToWallets": "Go to all my wallets and star those you use most often", - "wallet.nav.noWalletsAccessList.noWallets": "No wallets added to this list yet", - "wallet.nav.noWalletsAccessList.quickAccess": "Quick access wallets", "wallet.nav.type.ledger": "Ledger wallet", "wallet.nav.type.paper": "Paper wallet", "wallet.nav.type.standard": "Standard wallet", @@ -856,7 +853,6 @@ "wallet.topbar.dialog.totalBalance": "Total Balance", "wallet.topbar.dialog.ergo": "Ergo, ERG", "wallet.topbar.dialog.cardano": "Cardano, ADA", - "wallet.topbar.dialog.quickAccess": "Add to quick acceess wallets list", "wallet.transaction.address.from": "From address", "wallet.transaction.address.to": "To address", "wallet.transaction.address.type": "Address Type", diff --git a/packages/yoroi-extension/app/stores/toplevel/ProfileStore.js b/packages/yoroi-extension/app/stores/toplevel/ProfileStore.js index d741b2b85c..e2791246da 100644 --- a/packages/yoroi-extension/app/stores/toplevel/ProfileStore.js +++ b/packages/yoroi-extension/app/stores/toplevel/ProfileStore.js @@ -254,7 +254,7 @@ export default class ProfileStore extends BaseProfileStore Promise = async () => { await this.getWalletsNavigationRequest.execute(); From 52352435c5b0f4b2d0cda30ba0cea5355c847c77 Mon Sep 17 00:00:00 2001 From: Ahmed Ibrahim Date: Wed, 11 Jan 2023 13:36:17 +0200 Subject: [PATCH 115/172] Fix flow --- .../yoroi-extension/app/connector/stores/ConnectorStore.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/yoroi-extension/app/connector/stores/ConnectorStore.js b/packages/yoroi-extension/app/connector/stores/ConnectorStore.js index da73d2d430..fb113f3a48 100644 --- a/packages/yoroi-extension/app/connector/stores/ConnectorStore.js +++ b/packages/yoroi-extension/app/connector/stores/ConnectorStore.js @@ -618,7 +618,7 @@ export default class ConnectorStore extends Store { response.changeAddress ]) - const outputs = []; + const outputs: Array<{| address: string, isForeign: boolean, value: MultiToken |}> = []; for (let i = 0; i < txBody.outputs().len(); i++) { const output = txBody.outputs().get(i); const address = Buffer.from(output.address().to_bytes()).toString('hex'); @@ -642,7 +642,7 @@ export default class ConnectorStore extends Store { const { amount, total } = await this._calculateAmountAndTotal( selectedWallet.publicDeriver, inputs, - outputs, + outputs.map(({ address, value }) => ({ address, value })), fee, response.utxos, ownAddresses, From c6cdeb59595a92935e382acf74849a959d6616c0 Mon Sep 17 00:00:00 2001 From: Ahmed Ibrahim Date: Thu, 12 Jan 2023 14:15:53 +0200 Subject: [PATCH 116/172] Open txs page if the user is on the add wallet page --- .../app/stores/stateless/sidebarCategories.js | 39 +++++++++++++------ 1 file changed, 27 insertions(+), 12 deletions(-) diff --git a/packages/yoroi-extension/app/stores/stateless/sidebarCategories.js b/packages/yoroi-extension/app/stores/stateless/sidebarCategories.js index e242ff37bf..f4aba36b88 100644 --- a/packages/yoroi-extension/app/stores/stateless/sidebarCategories.js +++ b/packages/yoroi-extension/app/stores/stateless/sidebarCategories.js @@ -110,27 +110,32 @@ export const NOTICE_BOARD: SidebarCategory = registerCategory({ isVisible: _request => !environment.isProduction(), }); +type isVisibleFunc = ({| + hasAnyWallets: boolean, + selected: null | PublicDeriver<>, + currentRoute: string, + |}) => boolean; + export type SidebarCategoryRevamp = {| +className: string, +route: string, +icon: string, +label?: MessageDescriptor, - +isVisible: ({| - hasAnyWallets: boolean, - selected: null | PublicDeriver<>, - currentRoute: string, - |}) => boolean, + +isVisible: isVisibleFunc, |}; // TODO: Fix routes and isVisible prop export const allCategoriesRevamp: Array = [ - { - className: 'wallets', - route: ROUTES.WALLETS.ROOT, - icon: walletIcon, - label: globalMessages.walletLabel, - isVisible: _request => true, - }, + // Open `/wallets` only if the user is on any other page other than `/wallets/add` + makeWalletCategory( + ROUTES.WALLETS.ROOT, + ({ currentRoute }) => currentRoute !== ROUTES.WALLETS.ADD + ), + // Open `/wallets/transactions` if the user is on the `/wallet/add` + makeWalletCategory( + ROUTES.WALLETS.TRANSACTIONS, + ({ currentRoute }) => currentRoute === ROUTES.WALLETS.ADD + ), { className: 'staking', route: ROUTES.STAKING, @@ -198,3 +203,13 @@ export const allCategoriesRevamp: Array = [ // isVisible: _request => true, // }, ]; + +function makeWalletCategory(route: string, isVisible: isVisibleFunc): SidebarCategoryRevamp { + return { + className: 'wallets', + route, + icon: walletIcon, + label: globalMessages.walletLabel, + isVisible, + } +}; \ No newline at end of file From 2b91ad20c61a1e7e6bcf2894ecd72671b5e797ae Mon Sep 17 00:00:00 2001 From: Ahmed Ibrahim Date: Thu, 12 Jan 2023 16:16:52 +0200 Subject: [PATCH 117/172] Refractor the transfer page --- packages/yoroi-extension/app/Routes.js | 5 +++ .../app/containers/transfer/Transfer.js | 43 ++++--------------- .../app/containers/wallet/Wallet.js | 4 +- .../containers/wallet/voting/VotingPage.js | 1 - packages/yoroi-extension/app/routes-config.js | 1 + .../app/stores/stateless/topbarCategories.js | 2 +- 6 files changed, 17 insertions(+), 39 deletions(-) diff --git a/packages/yoroi-extension/app/Routes.js b/packages/yoroi-extension/app/Routes.js index bc4672a430..4a257b5fc4 100644 --- a/packages/yoroi-extension/app/Routes.js +++ b/packages/yoroi-extension/app/Routes.js @@ -352,6 +352,11 @@ const WalletsSubpages = (stores, actions) => ( path={ROUTES.WALLETS.CATALYST_VOTING} component={(props) => } /> + } + /> ); diff --git a/packages/yoroi-extension/app/containers/transfer/Transfer.js b/packages/yoroi-extension/app/containers/transfer/Transfer.js index 31bb4d4cdf..c14748beee 100644 --- a/packages/yoroi-extension/app/containers/transfer/Transfer.js +++ b/packages/yoroi-extension/app/containers/transfer/Transfer.js @@ -23,12 +23,9 @@ import type { $npm$ReactIntl$IntlFormat } from 'react-intl'; import { PublicDeriver } from '../../api/ada/lib/storage/models/PublicDeriver/index'; import { CoinTypes } from '../../config/numbersConfig'; import HorizontalLine from '../../components/widgets/HorizontalLine'; -import NavBarContainerRevamp from '../NavBarContainerRevamp'; import { withLayout } from '../../styles/context/layout'; import type { LayoutComponentMap } from '../../styles/context/layout'; import type { GeneratedData as NavBarContainerRevampData } from '../NavBarContainerRevamp'; -import SubMenu from '../../components/topbar/SubMenu'; -import { allSubcategoriesRevamp } from '../../stores/stateless/topbarCategories'; export type GeneratedData = typeof Transfer.prototype.generated; @@ -52,19 +49,7 @@ class Transfer extends Component { render(): Node { const sidebarContainer = ; - - const menu = ( - ({ - className: category.className, - label: this.context.intl.formatMessage(category.label), - route: category.route, - }))} - onItemClick={route => this.generated.actions.router.goToRoute.trigger({ route })} - isActiveItem={route => this.generated.stores.app.currentRoute.startsWith(route)} - /> - ); - const navbarClassic = ( + const navbar = ( { } /> ); - - const navbarRevamp = ( - - } - menu={menu} - /> - ); - - const navbar = this.props.renderLayoutComponent({ - CLASSIC: navbarClassic, - REVAMP: navbarRevamp, - }); - - return ( + const content = this.getContent(); + const transferClassic = ( } navbar={navbar} sidebar={sidebarContainer} showInContainer > - {this.getContent()} + {content} ); + + return this.props.renderLayoutComponent({ + CLASSIC: transferClassic, + REVAMP: content, + }) } getContent: void => Node = () => { diff --git a/packages/yoroi-extension/app/containers/wallet/Wallet.js b/packages/yoroi-extension/app/containers/wallet/Wallet.js index e4cb462450..bf4797a04f 100644 --- a/packages/yoroi-extension/app/containers/wallet/Wallet.js +++ b/packages/yoroi-extension/app/containers/wallet/Wallet.js @@ -77,9 +77,7 @@ class Wallet extends Component { checkRoute(): void | string { const isRevamp = this.generated.stores.profile.isRevampTheme; - const categories = isRevamp ? - allCategories.filter(c => c.route !== ROUTES.WALLETS.DELEGATION_DASHBOARD) - : allCategories; + const categories = isRevamp ? allSubcategoriesRevamp : allCategories; // void -> this route is fine for this wallet type // string -> what you should be redirected to diff --git a/packages/yoroi-extension/app/containers/wallet/voting/VotingPage.js b/packages/yoroi-extension/app/containers/wallet/voting/VotingPage.js index 845ff26264..6f2ae5952f 100644 --- a/packages/yoroi-extension/app/containers/wallet/voting/VotingPage.js +++ b/packages/yoroi-extension/app/containers/wallet/voting/VotingPage.js @@ -292,7 +292,6 @@ export default class VotingPage extends Component { const round = catalystRoundInfo?.currentFund?.id || catalystRoundInfo?.nextFund?.id || 5 const fundName = catalystRoundInfo?.currentFund?.name || round.toString(); return ( - //
{activeDialog} = [ }, { className: 'claimTransfer', - route: ROUTES.TRANSFER.ROOT, + route: ROUTES.WALLETS.TRANSFER, label: messages.claimTransfer, isVisible: _request => true, } From 6112a42ffd6b0c6d78c495a3e0cf4c660dbbd8d7 Mon Sep 17 00:00:00 2001 From: Ahmed Ibrahim Date: Fri, 13 Jan 2023 16:16:09 +0200 Subject: [PATCH 118/172] Add revamp layout for the voting page --- packages/yoroi-extension/app/Routes.js | 9 ++-- .../containers/wallet/voting/VotingPage.js | 53 +++++++++++++++++-- packages/yoroi-extension/app/routes-config.js | 8 ++- .../app/stores/stateless/sidebarCategories.js | 2 +- .../app/stores/stateless/topbarCategories.js | 2 +- 5 files changed, 64 insertions(+), 10 deletions(-) diff --git a/packages/yoroi-extension/app/Routes.js b/packages/yoroi-extension/app/Routes.js index 4a257b5fc4..533f7c3dda 100644 --- a/packages/yoroi-extension/app/Routes.js +++ b/packages/yoroi-extension/app/Routes.js @@ -227,7 +227,6 @@ export const Routes = ( ) )} /> - ( @@ -237,7 +236,6 @@ export const Routes = ( ) )} /> - } /> + } + /> @@ -354,7 +357,7 @@ const WalletsSubpages = (stores, actions) => ( /> } /> diff --git a/packages/yoroi-extension/app/containers/wallet/voting/VotingPage.js b/packages/yoroi-extension/app/containers/wallet/voting/VotingPage.js index 6f2ae5952f..703e224fd8 100644 --- a/packages/yoroi-extension/app/containers/wallet/voting/VotingPage.js +++ b/packages/yoroi-extension/app/containers/wallet/voting/VotingPage.js @@ -1,5 +1,5 @@ // @flow -import type { Node } from 'react'; +import type { Node, ComponentType } from 'react'; import { Component } from 'react'; import { observer } from 'mobx-react'; import { computed } from 'mobx'; @@ -29,6 +29,13 @@ import { isTrezorTWallet, } from '../../../api/ada/lib/storage/models/ConceptualWallet/index'; import type { CatalystRoundInfoResponse } from '../../../api/ada/lib/state-fetch/types' +import TopBarLayout from '../../../components/layout/TopBarLayout'; +import BannerContainer from '../../banners/BannerContainer'; +import SidebarContainer from '../../SidebarContainer'; +import NavBarContainerRevamp from '../../NavBarContainerRevamp'; +import NavBarTitle from '../../../components/topbar/NavBarTitle'; +import globalMessages from '../../../i18n/global-messages'; +import { withLayout } from '../../../styles/context/layout'; export type GeneratedData = typeof VotingPage.prototype.generated; type Props = {| @@ -75,7 +82,7 @@ const messages: * = defineMessages({ }); @observer -export default class VotingPage extends Component { +class VotingPage extends Component { static contextTypes: {| intl: $npm$ReactIntl$IntlFormat |} = { intl: intlShape.isRequired }; onClose: void => void = () => { @@ -117,6 +124,32 @@ export default class VotingPage extends Component { } render(): Node { + const { intl } = this.context; + const pageContent = this.getPageContent(); + const revampLayout = ( + } + sidebar={} + navbar={ + } + /> + } + showInContainer + showAsCard + > + {pageContent} + + ); + + return this.props.renderLayoutComponent({ + CLASSIC: pageContent, + REVAMP: revampLayout, + }); + } + + getPageContent(): Node { const { intl } = this.context const { uiDialogs, @@ -308,6 +341,9 @@ export default class VotingPage extends Component { @computed get generated(): {| VotingRegistrationDialogProps: InjectedOrGenerated, + BannerContainerProps: InjectedOrGenerated, + NavBarContainerRevampProps: InjectedOrGenerated, + SidebarContainerProps: InjectedOrGenerated, actions: {| dialogs: {| closeActiveDialog: {| @@ -405,6 +441,15 @@ export default class VotingPage extends Component { actions, stores, }: InjectedOrGenerated), + SidebarContainerProps: ({ actions, stores }: InjectedOrGenerated), + NavBarContainerRevampProps: ({ + actions, + stores, + }: InjectedOrGenerated), + BannerContainerProps: ({ actions, stores }: InjectedOrGenerated), }); - } -} + }; +}; + + +export default (withLayout(VotingPage): ComponentType); \ No newline at end of file diff --git a/packages/yoroi-extension/app/routes-config.js b/packages/yoroi-extension/app/routes-config.js index b93b498fbb..56dce7a6b8 100644 --- a/packages/yoroi-extension/app/routes-config.js +++ b/packages/yoroi-extension/app/routes-config.js @@ -47,7 +47,6 @@ export const ROUTES = { ADAPOOL_DELEGATION_SIMPLE: '/wallets/delegation-simple', CARDANO_DELEGATION: '/wallets/cardano-delegation', CATALYST_VOTING: '/wallets/voting', - TRANSFER: '/wallets/transfer', }, SETTINGS: { ROOT: '/settings', @@ -92,5 +91,12 @@ export const ROUTES = { YOROI_PALETTE: '/experimental/yoroi-palette', YOROI_COMPONENTS: '/experimental/components', THEMES: '/experimental/themes' + }, + // Revamp specific routes: + REVAMP: { + // `transfer` the `wallet` + TRANSFER: '/wallets/transfer', + // `voting` is part of the sidebar + CATALYST_VOTING: '/voting', } }; diff --git a/packages/yoroi-extension/app/stores/stateless/sidebarCategories.js b/packages/yoroi-extension/app/stores/stateless/sidebarCategories.js index f4aba36b88..7b2f86d929 100644 --- a/packages/yoroi-extension/app/stores/stateless/sidebarCategories.js +++ b/packages/yoroi-extension/app/stores/stateless/sidebarCategories.js @@ -161,7 +161,7 @@ export const allCategoriesRevamp: Array = [ }, { className: 'voting', - route: ROUTES.WALLETS.CATALYST_VOTING, + route: ROUTES.REVAMP.CATALYST_VOTING, icon: votingIcon, label: globalMessages.sidebarVoting, // $FlowFixMe[prop-missing] diff --git a/packages/yoroi-extension/app/stores/stateless/topbarCategories.js b/packages/yoroi-extension/app/stores/stateless/topbarCategories.js index 04ad658b93..766086492a 100644 --- a/packages/yoroi-extension/app/stores/stateless/topbarCategories.js +++ b/packages/yoroi-extension/app/stores/stateless/topbarCategories.js @@ -165,7 +165,7 @@ export const allSubcategoriesRevamp: Array = [ }, { className: 'claimTransfer', - route: ROUTES.WALLETS.TRANSFER, + route: ROUTES.REVAMP.TRANSFER, label: messages.claimTransfer, isVisible: _request => true, } From f70b6800d3bbddd90e09c308ae6e169d14879cdf Mon Sep 17 00:00:00 2001 From: Ahmed Ibrahim Date: Mon, 16 Jan 2023 13:06:41 +0200 Subject: [PATCH 119/172] Fix flow --- .../app/containers/wallet/NFTsWrapper.js | 1 - .../containers/wallet/voting/VotingPage.js | 13 +++-- .../wallet/voting/VotingPage.stories.js | 54 ++++++++++++++++++- 3 files changed, 62 insertions(+), 6 deletions(-) diff --git a/packages/yoroi-extension/app/containers/wallet/NFTsWrapper.js b/packages/yoroi-extension/app/containers/wallet/NFTsWrapper.js index 6fd96c29f1..abe8f46c6a 100644 --- a/packages/yoroi-extension/app/containers/wallet/NFTsWrapper.js +++ b/packages/yoroi-extension/app/containers/wallet/NFTsWrapper.js @@ -79,7 +79,6 @@ export default class NFTsWrapper extends Component { BannerContainerProps: InjectedOrGenerated, SidebarContainerProps: InjectedOrGenerated, NavBarContainerRevampProps: InjectedOrGenerated, - stores: {| router: {| location: any |}, tokenInfoStore: {| diff --git a/packages/yoroi-extension/app/containers/wallet/voting/VotingPage.js b/packages/yoroi-extension/app/containers/wallet/voting/VotingPage.js index 703e224fd8..db98eb5096 100644 --- a/packages/yoroi-extension/app/containers/wallet/voting/VotingPage.js +++ b/packages/yoroi-extension/app/containers/wallet/voting/VotingPage.js @@ -36,10 +36,17 @@ import NavBarContainerRevamp from '../../NavBarContainerRevamp'; import NavBarTitle from '../../../components/topbar/NavBarTitle'; import globalMessages from '../../../i18n/global-messages'; import { withLayout } from '../../../styles/context/layout'; +import type { LayoutComponentMap } from '../../../styles/context/layout' +import type { GeneratedData as SidebarContainerData } from '../../SidebarContainer' +import type { GeneratedData as BannerContainerData } from '../../banners/BannerContainer' +import type { GeneratedData as NavBarContainerRevampData } from '../../NavBarContainerRevamp'; export type GeneratedData = typeof VotingPage.prototype.generated; -type Props = {| - ...InjectedOrGenerated, +type Props = InjectedOrGenerated +type InjectedProps = {| +renderLayoutComponent: LayoutComponentMap => Node |}; +type AllProps = {| + ...Props, + ...InjectedProps, |}; const messages: * = defineMessages({ @@ -82,7 +89,7 @@ const messages: * = defineMessages({ }); @observer -class VotingPage extends Component { +class VotingPage extends Component { static contextTypes: {| intl: $npm$ReactIntl$IntlFormat |} = { intl: intlShape.isRequired }; onClose: void => void = () => { diff --git a/packages/yoroi-extension/app/containers/wallet/voting/VotingPage.stories.js b/packages/yoroi-extension/app/containers/wallet/voting/VotingPage.stories.js index fa5a1333d7..a313ef6bf1 100644 --- a/packages/yoroi-extension/app/containers/wallet/voting/VotingPage.stories.js +++ b/packages/yoroi-extension/app/containers/wallet/voting/VotingPage.stories.js @@ -32,6 +32,7 @@ import { MultiToken } from '../../../api/common/lib/MultiToken'; import BigNumber from 'bignumber.js'; import type { ShelleyCip1852CacheValue } from '../../../../stories/helpers/cardano/ShelleyCip1852Mocks'; import { CATALYST_MIN_AMOUNT } from '../../../config/numbersConfig'; +import { ServerStatusErrors } from '../../../types/serverStatusErrorType'; export default { title: `${__filename.split('.')[0]}`, @@ -50,7 +51,7 @@ const defaultProps: ({| VotingRegistrationDialogProps?: *, balance: ?MultiToken, hasAnyPending: boolean, -|}) => * = request => ({ +|}) => any = request => ({ balance: request.balance, hasAnyPending: request.hasAnyPending, stores: { @@ -86,6 +87,55 @@ const defaultProps: ({| }, }, VotingRegistrationDialogProps: request.VotingRegistrationDialogProps || (null: any), + SidebarContainerProps: { + generated: { + stores: { + wallets: { + hasAnyWallets: true, + selected: null, + }, + app: { currentRoute: ROUTES.MY_WALLETS }, + profile: { + isSidebarExpanded: false, + }, + }, + actions: { + profile: { + toggleSidebar: { trigger: async (req) => action('toggleSidebar')(req) }, + }, + router: { + goToRoute: { trigger: action('goToRoute') }, + }, + }, + }, + }, + BannerContainerProps: { + generated: { + stores: { + serverConnectionStore: { + checkAdaServerStatus: select( + 'checkAdaServerStatus', + ServerStatusErrors, + ServerStatusErrors.Healthy, + ), + serverTime: undefined, + }, + tokenInfoStore: { + tokenInfo: mockFromDefaults(defaultAssets), + }, + wallets: { + selected: null, + }, + }, + actions: Object.freeze({}), + }, + }, + NavBarContainerRevampProps: { + generated: { + stores: {}, + actions: {}, + } + } }); const genVotingRegistrationDialogProps: ({| @@ -421,7 +471,7 @@ export const Register = (): Node => { }) } }) - } + }, }))} /> ) From 5ff5ebd644838a6a40ad14ad1399c8aff5c0fa79 Mon Sep 17 00:00:00 2001 From: Ahmed Ibrahim Date: Tue, 17 Jan 2023 13:06:40 +0200 Subject: [PATCH 120/172] Add suspense wrapper at the subpage level --- packages/yoroi-extension/app/Routes.js | 32 ++++++++++++------- .../containers/wallet/staking/StakingPage.js | 5 ++- .../wallet/staking/StakingPageContainer.js | 1 + 3 files changed, 23 insertions(+), 15 deletions(-) create mode 100644 packages/yoroi-extension/app/containers/wallet/staking/StakingPageContainer.js diff --git a/packages/yoroi-extension/app/Routes.js b/packages/yoroi-extension/app/Routes.js index bc4672a430..6c00bb964b 100644 --- a/packages/yoroi-extension/app/Routes.js +++ b/packages/yoroi-extension/app/Routes.js @@ -11,6 +11,9 @@ import type { GeneratedData as WalletData } from './containers/wallet/Wallet'; import type { GeneratedData as ReceiveData } from './containers/wallet/Receive'; import type { ConfigType } from '../config/config-types'; import type { GeneratedData as AssetsData } from './containers/wallet/AssetsWrapper'; +import LoadingPage from './containers/LoadingPage'; +import StakingPage from './containers/wallet/staking/StakingPage'; +import Wallet from './containers/wallet/Wallet'; // PAGES const WalletAddPagePromise = () => import('./containers/wallet/WalletAddPage'); @@ -38,15 +41,15 @@ const TermsOfUseSettingsPage = React.lazy(TermsOfUseSettingsPagePromise); const SupportSettingsPagePromise = () => import('./containers/settings/categories/SupportSettingsPage'); const SupportSettingsPage = React.lazy(SupportSettingsPagePromise); +//! Todo: Remove unnecessary promises // Dynamic container loading - resolver loads file relative to '/app/' directory const LoadingPagePromise = () => import('./containers/LoadingPage'); -const LoadingPage = React.lazy(LoadingPagePromise); const NightlyPagePromise = () => import('./containers/profile/NightlyPage'); const NightlyPage = React.lazy(NightlyPagePromise); const WalletPromise = () => import('./containers/wallet/Wallet'); -const Wallet = React.lazy(WalletPromise); +const WalletLazy = React.lazy(WalletPromise); const MyWalletsPagePromise = () => import('./containers/wallet/MyWalletsPage'); const MyWalletsPage = React.lazy(MyWalletsPagePromise); @@ -97,7 +100,7 @@ const WalletSwitchPromise = () => import('./containers/WalletSwitch'); const WalletSwitch = React.lazy(WalletSwitchPromise); const StakingPagePromise = () => import('./containers/wallet/staking/StakingPage'); -const StakingPage = React.lazy(StakingPagePromise); +const StakingPageLazy = React.lazy(StakingPagePromise); const AssetsWrapperPromise = () => import('./containers/wallet/AssetsWrapper'); const AssetsWrapper = React.lazy(AssetsWrapperPromise); @@ -310,9 +313,7 @@ const WalletsSubpages = (stores, actions) => ( { - return - }} + component={(props) => } /> ( /> ) -/* eslint-enable max-len */ export function wrapSettings( settingsProps: InjectedOrGenerated, @@ -435,7 +435,9 @@ export function wrapSettings( - {children} + + {children} + ); } @@ -448,7 +450,9 @@ export function wrapAssets( - {children} + + {children} + ); } @@ -461,7 +465,9 @@ export function wrapNFTs( - {children} + + {children} + ); } @@ -474,7 +480,9 @@ export function wrapWallet( - {children} + + {children} + ); } @@ -490,4 +498,4 @@ export function wrapReceive( {children} ); -} +} \ No newline at end of file diff --git a/packages/yoroi-extension/app/containers/wallet/staking/StakingPage.js b/packages/yoroi-extension/app/containers/wallet/staking/StakingPage.js index 18e9d8d47d..e6b773b073 100644 --- a/packages/yoroi-extension/app/containers/wallet/staking/StakingPage.js +++ b/packages/yoroi-extension/app/containers/wallet/staking/StakingPage.js @@ -442,9 +442,8 @@ class StakingPage extends Component { onNext={() => { // note: purposely don't await // since the next dialog will properly render the spinner - this.generated.actions.ada.delegationTransaction.createWithdrawalTxForWallet.trigger( - { publicDeriver } - ); + const { delegationTransaction } = this.generated.actions.ada; + delegationTransaction.createWithdrawalTxForWallet.trigger({ publicDeriver }); this.generated.actions.dialogs.open.trigger({ dialog: WithdrawalTxDialogContainer, }); diff --git a/packages/yoroi-extension/app/containers/wallet/staking/StakingPageContainer.js b/packages/yoroi-extension/app/containers/wallet/staking/StakingPageContainer.js new file mode 100644 index 0000000000..46e7f7c045 --- /dev/null +++ b/packages/yoroi-extension/app/containers/wallet/staking/StakingPageContainer.js @@ -0,0 +1 @@ +// @flow From 2092bdb397fd40f883e9da51b47ca049d7befd0a Mon Sep 17 00:00:00 2001 From: Denis Date: Thu, 19 Jan 2023 12:16:51 +0300 Subject: [PATCH 121/172] added preview network --- .../storage/database/prepackaged/explorers.js | 22 ++++++++- .../storage/database/prepackaged/networks.js | 48 ++++++++++++++++++- .../option-dialog/PickCurrencyOptionDialog.js | 21 ++++++++ .../app/containers/wallet/WalletAddPage.js | 1 + .../dialogs/PickCurrencyDialogContainer.js | 2 + .../app/stores/stateless/topbarCategories.js | 1 + .../chrome/manifest.development.js | 1 + .../chrome/manifest.mainnet.js | 1 + .../chrome/manifest.shelley-testnet.js | 1 + packages/yoroi-extension/package-lock.json | 14 +++--- .../yoroi-extension/scripts/connections.js | 1 + 11 files changed, 103 insertions(+), 10 deletions(-) diff --git a/packages/yoroi-extension/app/api/ada/lib/storage/database/prepackaged/explorers.js b/packages/yoroi-extension/app/api/ada/lib/storage/database/prepackaged/explorers.js index c17081ae23..0e918b0471 100644 --- a/packages/yoroi-extension/app/api/ada/lib/storage/database/prepackaged/explorers.js +++ b/packages/yoroi-extension/app/api/ada/lib/storage/database/prepackaged/explorers.js @@ -163,10 +163,27 @@ const AlonzoTestnetExplorers: Array<$ReadOnly> = [ }, ]; +const CardanoPreviewTestnetExplorers: Array<$ReadOnly> = [ + { + ExplorerId: 5_50, + NetworkId: networks.CardanoPreviewTestnet.NetworkId, + IsBackup: true, + Endpoints: { + address: 'https://preview.cardanoscan.io/address/', + transaction: 'https://preview.cardanoscan.io/transaction/', + pool: 'https://preview.cardanoscan.io/pool/', + stakeAddress: 'https://preview.cardanoscan.io/stakeKey/', + token: 'https://preview.cardanoscan.io/token/', + }, + Name: 'CardanoScan', + }, +]; + export const prepackagedExplorers: Map>> = new Map([ [networks.CardanoMainnet.NetworkId, CardanoMainnetExplorers], [networks.CardanoTestnet.NetworkId, CardanoTestnetExplorers], [networks.CardanoPreprodTestnet.NetworkId, CardanoPreprodTestnetExplorers], + [networks.CardanoPreviewTestnet.NetworkId, CardanoPreviewTestnetExplorers], [networks.JormungandrMainnet.NetworkId, JormungandrExplorers], [networks.ErgoMainnet.NetworkId, ErgoExplorers], [networks.AlonzoTestnet.NetworkId, AlonzoTestnetExplorers], @@ -184,7 +201,10 @@ export const prepackagedDefaultExplorers: CardanoTestnetExplorers.find(explorer => explorer.IsBackup) )], [networks.CardanoPreprodTestnet.NetworkId, getOrThrow( - CardanoTestnetExplorers.find(explorer => explorer.IsBackup) + CardanoPreprodTestnetExplorers.find(explorer => explorer.IsBackup) + )], + [networks.CardanoPreviewTestnet.NetworkId, getOrThrow( + CardanoPreviewTestnetExplorers.find(explorer => explorer.IsBackup) )], [networks.JormungandrMainnet.NetworkId, getOrThrow( JormungandrExplorers.find(explorer => explorer.IsBackup) diff --git a/packages/yoroi-extension/app/api/ada/lib/storage/database/prepackaged/networks.js b/packages/yoroi-extension/app/api/ada/lib/storage/database/prepackaged/networks.js index 12c4b77681..3c38ce1599 100644 --- a/packages/yoroi-extension/app/api/ada/lib/storage/database/prepackaged/networks.js +++ b/packages/yoroi-extension/app/api/ada/lib/storage/database/prepackaged/networks.js @@ -240,6 +240,46 @@ export const networks = Object.freeze({ CoinType: CoinTypes.CARDANO, Fork: CardanoForks.Haskell, }: NetworkRow), + CardanoPreviewTestnet: ({ + NetworkId: 3_00, + NetworkName: 'Cardano Preview Testnet', + Backend: { + BackendService: environment.isTest() + ? 'http://localhost:21000' + : 'https://preview-backend.emurgornd.com', + WebSocket: environment.isTest() + ? 'ws://localhost:21000' + : 'wss://preview-backend.emurgornd.com:443', + TokenInfoService: + 'https://stage-cdn.yoroiwallet.com', + }, + BaseConfig: ([ + Object.freeze({ + StartAt: 0, + ChainNetworkId: '0', + ByronNetworkId: 1, + GenesisDate: '1654041600000', + SlotsPerEpoch: 21600, + SlotDuration: 20, + }), + Object.freeze({ + StartAt: 0, + SlotsPerEpoch: 432000, + SlotDuration: 1, + PerEpochPercentageReward: 69344, + LinearFee: { + coefficient: '44', + constant: '155381', + }, + CoinsPerUtxoWord: '34482', + MinimumUtxoVal: '1000000', + PoolDeposit: '500000000', + KeyDeposit: '2000000', + }) + ]: CardanoHaskellBaseConfig), + CoinType: CoinTypes.CARDANO, + Fork: CardanoForks.Haskell, + }: NetworkRow), }); export function isTestnet( @@ -247,7 +287,8 @@ export function isTestnet( ): boolean { return network.NetworkId === networks.JormungandrMainnet.NetworkId || network.NetworkId === networks.CardanoTestnet.NetworkId - || network.NetworkId === networks.CardanoPreprodTestnet.NetworkId; + || network.NetworkId === networks.CardanoPreprodTestnet.NetworkId + || network.NetworkId === networks.CardanoPreviewTestnet.NetworkId; } @@ -330,7 +371,10 @@ export const defaultAssets: Array< policyId: PRIMARY_ASSET_CONSTANTS.Cardano, assetName: PRIMARY_ASSET_CONSTANTS.Cardano, ticker: - (network === networks.CardanoTestnet || network === networks.CardanoPreprodTestnet || network === networks.AlonzoTestnet) + (network === networks.CardanoTestnet + || network === networks.CardanoPreprodTestnet + || network === networks.CardanoPreviewTestnet + || network === networks.AlonzoTestnet) ? 'TADA' : 'ADA', longName: null, diff --git a/packages/yoroi-extension/app/components/wallet/add/option-dialog/PickCurrencyOptionDialog.js b/packages/yoroi-extension/app/components/wallet/add/option-dialog/PickCurrencyOptionDialog.js index 522b81ef5a..8068f5224f 100644 --- a/packages/yoroi-extension/app/components/wallet/add/option-dialog/PickCurrencyOptionDialog.js +++ b/packages/yoroi-extension/app/components/wallet/add/option-dialog/PickCurrencyOptionDialog.js @@ -37,6 +37,7 @@ type Props = {| +onCardano: void => void, +onCardanoTestnet: void => void, +onCardanoPreprodTestnet: void => void, + +onCardanoPreviewTestnet: void => void, +onErgo: void | (void => void), +onAlonzoTestnet: void => void, +onExternalLinkClick: MouseEvent => void, @@ -97,6 +98,26 @@ export default class PickCurrencyOptionDialog extends Component { /> } + {(!environment.isProduction() || environment.isNightly() || environment.isTest()) && + <> + + {intl.formatMessage(messages.testnetDescription)}
+ this.props.onExternalLinkClick(event)} + > + {intl.formatMessage(globalMessages.learnMore)} + + } + /> + + } {/* */} {/*{(!environment.isProduction() || environment.isNightly() || environment.isTest()) &&*/} {/* { onCardano={() => actions.profile.setSelectedNetwork.trigger(networks.CardanoMainnet)} onCardanoTestnet={() => actions.profile.setSelectedNetwork.trigger(networks.CardanoTestnet)} onCardanoPreprodTestnet={() => actions.profile.setSelectedNetwork.trigger(networks.CardanoPreprodTestnet)} + onCardanoPreviewTestnet={() => actions.profile.setSelectedNetwork.trigger(networks.CardanoPreviewTestnet)} onErgo={(uiDialogs.isOpen(WalletConnectHWOptionDialog) || uiDialogs.isOpen(WalletCreateOptionDialog)) ? undefined : () => actions.profile.setSelectedNetwork.trigger(networks.ErgoMainnet)} diff --git a/packages/yoroi-extension/app/containers/wallet/dialogs/PickCurrencyDialogContainer.js b/packages/yoroi-extension/app/containers/wallet/dialogs/PickCurrencyDialogContainer.js index a1c197612b..71b4eb344a 100644 --- a/packages/yoroi-extension/app/containers/wallet/dialogs/PickCurrencyDialogContainer.js +++ b/packages/yoroi-extension/app/containers/wallet/dialogs/PickCurrencyDialogContainer.js @@ -10,6 +10,7 @@ type Props = {| +onCardano: void => void, +onCardanoTestnet: void => void, +onCardanoPreprodTestnet: void => void, + +onCardanoPreviewTestnet: void => void, +onErgo: void | (void => void), +onAlonzoTestnet: void => void, |}; @@ -25,6 +26,7 @@ export default class PickCurrencyDialogContainer extends Component { onCardano={this.props.onCardano} onCardanoTestnet={this.props.onCardanoTestnet} onCardanoPreprodTestnet={this.props.onCardanoPreprodTestnet} + onCardanoPreviewTestnet={this.props.onCardanoPreviewTestnet} onErgo={this.props.onErgo} onAlonzoTestnet={this.props.onAlonzoTestnet} /> diff --git a/packages/yoroi-extension/app/stores/stateless/topbarCategories.js b/packages/yoroi-extension/app/stores/stateless/topbarCategories.js index 7ac94c6da0..ad56968f12 100644 --- a/packages/yoroi-extension/app/stores/stateless/topbarCategories.js +++ b/packages/yoroi-extension/app/stores/stateless/topbarCategories.js @@ -139,6 +139,7 @@ export const CARDANO_DELEGATION: TopbarCategory = registerCategory({ (environment.isTest() || networkId === networks.CardanoTestnet.NetworkId || networkId === networks.CardanoPreprodTestnet.NetworkId + || networkId === networks.CardanoPreviewTestnet.NetworkId ); }, }); diff --git a/packages/yoroi-extension/chrome/manifest.development.js b/packages/yoroi-extension/chrome/manifest.development.js index 8fd6d372bc..77009311da 100644 --- a/packages/yoroi-extension/chrome/manifest.development.js +++ b/packages/yoroi-extension/chrome/manifest.development.js @@ -19,6 +19,7 @@ export default (isDebug: boolean, shouldInjectConnector: boolean): * => buildMan additional: { 'connect-src': [ serverToPermission(Servers.Primary), + serverToPermission(Servers.Testnet), ], 'frame-src': [ POOLS_UI_URL_FOR_YOROI, diff --git a/packages/yoroi-extension/chrome/manifest.mainnet.js b/packages/yoroi-extension/chrome/manifest.mainnet.js index 529dbb1aa6..3f2773f4aa 100644 --- a/packages/yoroi-extension/chrome/manifest.mainnet.js +++ b/packages/yoroi-extension/chrome/manifest.mainnet.js @@ -21,6 +21,7 @@ export default (isDebug: boolean, shouldInjectConnector: boolean): * => buildMan additional: { 'connect-src': [ serverToPermission(Servers.Primary), + serverToPermission(Servers.Testnet), ], 'frame-src': [ POOLS_UI_URL_FOR_YOROI, diff --git a/packages/yoroi-extension/chrome/manifest.shelley-testnet.js b/packages/yoroi-extension/chrome/manifest.shelley-testnet.js index 4248b18c62..f9872b46bd 100644 --- a/packages/yoroi-extension/chrome/manifest.shelley-testnet.js +++ b/packages/yoroi-extension/chrome/manifest.shelley-testnet.js @@ -20,6 +20,7 @@ export default (isDebug: boolean, shouldInjectConnector: boolean): * => buildMan additional: { 'connect-src': [ serverToPermission(Servers.Primary), + serverToPermission(Servers.Testnet), ], 'frame-src': [ POOLS_UI_URL_FOR_YOROI, diff --git a/packages/yoroi-extension/package-lock.json b/packages/yoroi-extension/package-lock.json index b197117120..d9a914bfe3 100644 --- a/packages/yoroi-extension/package-lock.json +++ b/packages/yoroi-extension/package-lock.json @@ -10736,13 +10736,13 @@ "dev": true }, "chromedriver": { - "version": "108.0.0", - "resolved": "https://registry.npmjs.org/chromedriver/-/chromedriver-108.0.0.tgz", - "integrity": "sha512-/kb0rb0dlC4RfXh2BOT7RV87K6d+It3VV5YXebLzO5a8t2knNffiTE23XPJQCH+l1xmgoW8/sOX/NB9irskvOQ==", + "version": "109.0.0", + "resolved": "https://registry.npmjs.org/chromedriver/-/chromedriver-109.0.0.tgz", + "integrity": "sha512-jdmBq11IUwfThLFiygGTZ89qbROSQI4bICQjvOVQy2Bqr1LwC+MFkhwyZp3YG99eehQbZuTlQmmfCZBfpewTNA==", "dev": true, "requires": { "@testim/chrome-version": "^1.1.3", - "axios": "^1.1.3", + "axios": "^1.2.1", "compare-versions": "^5.0.1", "extract-zip": "^2.0.1", "https-proxy-agent": "^5.0.1", @@ -10751,9 +10751,9 @@ }, "dependencies": { "axios": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/axios/-/axios-1.2.1.tgz", - "integrity": "sha512-I88cFiGu9ryt/tfVEi4kX2SITsvDddTajXTOFmt2uK1ZVA8LytjtdeyefdQWEf5PU8w+4SSJDoYnggflB5tW4A==", + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/axios/-/axios-1.2.3.tgz", + "integrity": "sha512-pdDkMYJeuXLZ6Xj/Q5J3Phpe+jbGdsSzlQaFVkMQzRUL05+6+tetX8TV3p4HrU4kzuO9bt+io/yGQxuyxA/xcw==", "dev": true, "requires": { "follow-redirects": "^1.15.0", diff --git a/packages/yoroi-extension/scripts/connections.js b/packages/yoroi-extension/scripts/connections.js index f66967e4c2..4e90c5a506 100644 --- a/packages/yoroi-extension/scripts/connections.js +++ b/packages/yoroi-extension/scripts/connections.js @@ -20,6 +20,7 @@ const Ports = { const Servers = { // this allows connecting to multiple different backends for different currencies Primary: '*.yoroiwallet.com', + Testnet: '*.emurgornd.com', }; module.exports = { From 702b4865ab704c1e1a4af65c9159b5ee1f401052 Mon Sep 17 00:00:00 2001 From: Ahmed Ibrahim Date: Fri, 20 Jan 2023 18:14:43 +0200 Subject: [PATCH 122/172] Fix the connector & settings page --- packages/yoroi-extension/app/Routes.js | 27 ++++-------------- .../ConnectedWebsitesContainer.js | 28 +++++++++++-------- .../app/containers/transfer/Transfer.js | 16 +++++++---- 3 files changed, 31 insertions(+), 40 deletions(-) diff --git a/packages/yoroi-extension/app/Routes.js b/packages/yoroi-extension/app/Routes.js index 6c00bb964b..e914baae31 100644 --- a/packages/yoroi-extension/app/Routes.js +++ b/packages/yoroi-extension/app/Routes.js @@ -14,6 +14,9 @@ import type { GeneratedData as AssetsData } from './containers/wallet/AssetsWrap import LoadingPage from './containers/LoadingPage'; import StakingPage from './containers/wallet/staking/StakingPage'; import Wallet from './containers/wallet/Wallet'; +import Settings from './containers/settings/Settings'; +import Transfer, { WalletTransferPagePromise } from './containers/transfer/Transfer'; +import ConnectedWebsitesPage, { ConnectedWebsitesPagePromise } from './containers/dapp-connector/ConnectedWebsitesContainer'; // PAGES const WalletAddPagePromise = () => import('./containers/wallet/WalletAddPage'); @@ -26,8 +29,6 @@ const UriPromptPagePromise = () => import('./containers/profile/UriPromptPage'); const UriPromptPage = React.lazy(UriPromptPagePromise); // SETTINGS -const SettingsPromise = () => import('./containers/settings/Settings'); -const Settings = React.lazy(SettingsPromise); const GeneralSettingsPagePromise = () => import('./containers/settings/categories/GeneralSettingsPage'); const GeneralSettingsPage = React.lazy(GeneralSettingsPagePromise); const WalletSettingsPagePromise = () => import('./containers/settings/categories/WalletSettingsPage'); @@ -41,16 +42,10 @@ const TermsOfUseSettingsPage = React.lazy(TermsOfUseSettingsPagePromise); const SupportSettingsPagePromise = () => import('./containers/settings/categories/SupportSettingsPage'); const SupportSettingsPage = React.lazy(SupportSettingsPagePromise); -//! Todo: Remove unnecessary promises -// Dynamic container loading - resolver loads file relative to '/app/' directory -const LoadingPagePromise = () => import('./containers/LoadingPage'); const NightlyPagePromise = () => import('./containers/profile/NightlyPage'); const NightlyPage = React.lazy(NightlyPagePromise); -const WalletPromise = () => import('./containers/wallet/Wallet'); -const WalletLazy = React.lazy(WalletPromise); - const MyWalletsPagePromise = () => import('./containers/wallet/MyWalletsPage'); const MyWalletsPage = React.lazy(MyWalletsPagePromise); @@ -69,9 +64,6 @@ const WalletReceivePage = React.lazy(WalletReceivePagePromise); const URILandingPagePromise = () => import('./containers/uri/URILandingPage'); const URILandingPage = React.lazy(URILandingPagePromise); -const TransferPromise = () => import('./containers/transfer/Transfer'); -const Transfer = React.lazy(TransferPromise); - const ReceivePromise = () => import('./containers/wallet/Receive'); const Receive = React.lazy(ReceivePromise); @@ -99,9 +91,6 @@ const BlockchainSettingsPage = React.lazy(BlockchainSettingsPagePromise); const WalletSwitchPromise = () => import('./containers/WalletSwitch'); const WalletSwitch = React.lazy(WalletSwitchPromise); -const StakingPagePromise = () => import('./containers/wallet/staking/StakingPage'); -const StakingPageLazy = React.lazy(StakingPagePromise); - const AssetsWrapperPromise = () => import('./containers/wallet/AssetsWrapper'); const AssetsWrapper = React.lazy(AssetsWrapperPromise); @@ -120,9 +109,6 @@ const NFTsPageRevamp = React.lazy(NFTsPageRevampPromise); const NFTDetailPageRevampPromise = () => import('./containers/wallet/NFTDetailPageRevamp'); const NFTDetailPageRevamp = React.lazy(NFTDetailPageRevampPromise); -const ConnectedWebsitesPagePromise = () => import('./containers/dapp-connector/ConnectedWebsitesContainer'); -const ConnectedWebsitesPage = React.lazy(ConnectedWebsitesPagePromise); - const YoroiPalettePagePromise = () => import('./containers/experimental/YoroiPalette'); const YoroiPalettePage = React.lazy(YoroiPalettePagePromise); @@ -134,23 +120,20 @@ export const LazyLoadPromises: Array<() => any> = [ LanguageSelectionPagePromise, TermsOfUsePagePromise, UriPromptPagePromise, - SettingsPromise, GeneralSettingsPagePromise, WalletSettingsPagePromise, ExternalStorageSettingsPagePromise, OAuthDropboxPagePromise, TermsOfUseSettingsPagePromise, SupportSettingsPagePromise, - LoadingPagePromise, NightlyPagePromise, - WalletPromise, MyWalletsPagePromise, WalletSummaryPagePromise, WalletSendPagePromise, WalletAssetsPagePromise, WalletReceivePagePromise, URILandingPagePromise, - TransferPromise, + WalletTransferPagePromise, ReceivePromise, StakingDashboardPagePromise, CardanoStakingPagePromise, @@ -160,7 +143,6 @@ export const LazyLoadPromises: Array<() => any> = [ ComplexityLevelPagePromise, BlockchainSettingsPagePromise, WalletSwitchPromise, - StakingPagePromise, AssetsWrapperPromise, TokensPageRevampPromise, TokensDetailPageRevampPromise, @@ -219,6 +201,7 @@ export const Routes = ( } /> import('../../components/dapp-connector/ConnectedWebsites/ConnectedWebsitesPage'); +const ConnectedWebsitesPage = lazy(ConnectedWebsitesPagePromise); + export type GeneratedData = typeof ConnectedWebsitesPageContainer.prototype.generated; type Props = InjectedOrGenerated @@ -103,16 +105,18 @@ class ConnectedWebsitesPageContainer extends Component { navbar={} > - ) + + + ); diff --git a/packages/yoroi-extension/app/containers/transfer/Transfer.js b/packages/yoroi-extension/app/containers/transfer/Transfer.js index 31bb4d4cdf..39bec38089 100644 --- a/packages/yoroi-extension/app/containers/transfer/Transfer.js +++ b/packages/yoroi-extension/app/containers/transfer/Transfer.js @@ -1,5 +1,5 @@ // @flow -import { Component } from 'react'; +import { Component, lazy, Suspense } from 'react'; import type { Node, ComponentType } from 'react'; import { computed } from 'mobx'; import { observer } from 'mobx-react'; @@ -15,7 +15,6 @@ import UnsupportedWallet from '../wallet/UnsupportedWallet'; import NavBarTitle from '../../components/topbar/NavBarTitle'; import NavBarContainer from '../NavBarContainer'; import globalMessages from '../../i18n/global-messages'; -import WalletTransferPage from './WalletTransferPage'; import type { GeneratedData as WalletTransferPageData } from './WalletTransferPage'; import type { GeneratedData as SidebarContainerData } from '../SidebarContainer'; import type { GeneratedData as NavBarContainerData } from '../NavBarContainer'; @@ -30,6 +29,9 @@ import type { GeneratedData as NavBarContainerRevampData } from '../NavBarContai import SubMenu from '../../components/topbar/SubMenu'; import { allSubcategoriesRevamp } from '../../stores/stateless/topbarCategories'; +export const WalletTransferPagePromise = () => import('./WalletTransferPage'); +const WalletTransferPage = lazy(WalletTransferPagePromise); + export type GeneratedData = typeof Transfer.prototype.generated; type Props = {| @@ -113,10 +115,12 @@ class Transfer extends Component { <> - + + + ); From 3e81d2ad49de09e51e0646e8edcc3a1158a8d43c Mon Sep 17 00:00:00 2001 From: vantuz-subhuman Date: Sun, 22 Jan 2023 12:19:30 +0300 Subject: [PATCH 123/172] fixes promise check --- .../app/api/ada/lib/cardanoCrypto/rustLoader.js | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/packages/yoroi-extension/app/api/ada/lib/cardanoCrypto/rustLoader.js b/packages/yoroi-extension/app/api/ada/lib/cardanoCrypto/rustLoader.js index 94055470e9..418be9c46b 100644 --- a/packages/yoroi-extension/app/api/ada/lib/cardanoCrypto/rustLoader.js +++ b/packages/yoroi-extension/app/api/ada/lib/cardanoCrypto/rustLoader.js @@ -21,10 +21,6 @@ function isWasmPointer(o: ?any): boolean { return o != null && o.ptr != null && o.free != null; } -function isPromise(o: ?any): boolean { - return o != null && (typeof o.then === 'function') && (typeof o.catch === 'function'); -} - /** * Creates a new proxied RustModule scope. * Return fields: @@ -186,8 +182,8 @@ class Module { try { result = callback(scope.RustModule); } catch (e) { onFailure(e); throw e; } - return isPromise(result) - // $FlowFixMe[incompatible-use] + return (result instanceof Promise) + // $FlowFixMe[incompatible-return] ? result.then(onSuccess, onFailure) : onSuccess(result); } From 14bc8c9352b97b23c886d81c1c553acb66e15ba0 Mon Sep 17 00:00:00 2001 From: vantuz-subhuman Date: Sun, 22 Jan 2023 13:10:35 +0300 Subject: [PATCH 124/172] proxy check fixed --- .../api/ada/lib/cardanoCrypto/rustLoader.js | 44 ++++++++++++++----- 1 file changed, 33 insertions(+), 11 deletions(-) diff --git a/packages/yoroi-extension/app/api/ada/lib/cardanoCrypto/rustLoader.js b/packages/yoroi-extension/app/api/ada/lib/cardanoCrypto/rustLoader.js index 418be9c46b..17e2d479ef 100644 --- a/packages/yoroi-extension/app/api/ada/lib/cardanoCrypto/rustLoader.js +++ b/packages/yoroi-extension/app/api/ada/lib/cardanoCrypto/rustLoader.js @@ -21,6 +21,35 @@ function isWasmPointer(o: ?any): boolean { return o != null && o.ptr != null && o.free != null; } +/* + * Some classes must not be proxied, as there is no need for it, + * but also it breaks some other libraries working with that type. + * For example, `Buffer.from` fails if the `Uint8Array` is proxied. + */ +const NON_PROXY_CLASSES = Object.freeze([Uint8Array]); +function isNonProxyClass(o: any): boolean { + return NON_PROXY_CLASSES.some(c => o instanceof c); +} + +function isProxyCompatibleType(o: any): boolean { + // We only proxy objects and functions, the check is mostly for primitive values + return typeof o === 'object' || typeof o === 'function' +} + +/* Fake flag name used to identify our own proxies */ +const WASM_PROXY_FAKE_FLAG_NAME = '____is_wasm_proxy'; +function isNotAlreadyAProxy(o: any): boolean { + // Make sure the original object is not already a proxy + return o[WASM_PROXY_FAKE_FLAG_NAME] !== true +} + +function isProxiable(o: ?any): boolean { + return o != null + && isProxyCompatibleType(o) + && !isNonProxyClass(o) + && isNotAlreadyAProxy(o); +} + /** * Creates a new proxied RustModule scope. * Return fields: @@ -41,14 +70,14 @@ function createWasmScope(): {| */ const scope = []; function recursiveProxy(originalObject: E): E { - if (originalObject == null) { + if (!isProxiable(originalObject)) { return originalObject; } const proxyHandler: Proxy$traps = { // We are intercepting when any field is trying to be accessed on the original object get(target: E, name: string, receiver: Proxy): any { // Synthetic flag to identify our own proxies - if (name === '____is_wasm_proxy') { + if (name === WASM_PROXY_FAKE_FLAG_NAME) { return true; } // Get the actual field value from the original object @@ -94,15 +123,8 @@ function createWasmScope(): {| return recursiveProxy(realValue); } }; - // We only proxy objects and functions, the check is mostly for primitive values - if (typeof originalObject === 'object' || typeof originalObject === 'function') { - // Make sure the original object is not already a proxy - if (originalObject.____is_wasm_proxy !== true) { - // $FlowFixMe[incompatible-return] - return new Proxy(originalObject, proxyHandler); - } - } - return originalObject; + // $FlowFixMe[incompatible-return] + return new Proxy(originalObject, proxyHandler); } // We are proxying the `RustModule` itself to pass it into the callback. // Note that we create a new proxy every time, because each proxy instance From 6056e156a8c02d9c8e83b00caf5cd4922bf48a55 Mon Sep 17 00:00:00 2001 From: vantuz-subhuman Date: Sun, 22 Jan 2023 13:14:55 +0300 Subject: [PATCH 125/172] unit test added --- .../ada/lib/cardanoCrypto/rustLoader.test.js | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 packages/yoroi-extension/app/api/ada/lib/cardanoCrypto/rustLoader.test.js diff --git a/packages/yoroi-extension/app/api/ada/lib/cardanoCrypto/rustLoader.test.js b/packages/yoroi-extension/app/api/ada/lib/cardanoCrypto/rustLoader.test.js new file mode 100644 index 0000000000..3dfc2a3ace --- /dev/null +++ b/packages/yoroi-extension/app/api/ada/lib/cardanoCrypto/rustLoader.test.js @@ -0,0 +1,19 @@ +// @flow +import '../test-config'; +import { RustModule } from './rustLoader'; +import { CatalystLabels, generateRegistration } from './catalyst'; +import { bytesToHex } from '../../../../coreUtils'; + +beforeAll(async () => { + await RustModule.load(); +}); + +test('Wasm Scope Simple Address Convert', async () => { + + const addr = 'addr1qf2w3pe8jsyvr9kutpv6e0rzuaym7dvq0rrz9699a7y3wwvz6g3gz764vxla692p4ttcekdw0smpedxuqq7a8t8sv3usrcv98z'; + const addressFixedDirectly = bytesToHex(RustModule.WalletV4.Address.from_bech32(addr).to_bytes()); + const addressFixedInScope = RustModule.WasmScope(Module => { + return bytesToHex(Module.WalletV4.Address.from_bech32(addr).to_bytes()); + }); + expect(addressFixedInScope).toEqual(addressFixedDirectly); +}); From 7564c153557ed8928400261a45945100212e4dcf Mon Sep 17 00:00:00 2001 From: vantuz-subhuman Date: Sun, 22 Jan 2023 13:16:24 +0300 Subject: [PATCH 126/172] unused imports removed --- .../app/api/ada/lib/cardanoCrypto/rustLoader.test.js | 1 - 1 file changed, 1 deletion(-) diff --git a/packages/yoroi-extension/app/api/ada/lib/cardanoCrypto/rustLoader.test.js b/packages/yoroi-extension/app/api/ada/lib/cardanoCrypto/rustLoader.test.js index 3dfc2a3ace..6fc507374f 100644 --- a/packages/yoroi-extension/app/api/ada/lib/cardanoCrypto/rustLoader.test.js +++ b/packages/yoroi-extension/app/api/ada/lib/cardanoCrypto/rustLoader.test.js @@ -1,7 +1,6 @@ // @flow import '../test-config'; import { RustModule } from './rustLoader'; -import { CatalystLabels, generateRegistration } from './catalyst'; import { bytesToHex } from '../../../../coreUtils'; beforeAll(async () => { From c9a6df5413a679b051fff42d8431e1d8de02c9bb Mon Sep 17 00:00:00 2001 From: vantuz-subhuman Date: Sun, 22 Jan 2023 18:07:37 +0300 Subject: [PATCH 127/172] fixed wasm check and added internal api for tests --- .../api/ada/lib/cardanoCrypto/rustLoader.js | 66 ++++++++++++------- .../ada/lib/cardanoCrypto/rustLoader.test.js | 5 +- 2 files changed, 47 insertions(+), 24 deletions(-) diff --git a/packages/yoroi-extension/app/api/ada/lib/cardanoCrypto/rustLoader.js b/packages/yoroi-extension/app/api/ada/lib/cardanoCrypto/rustLoader.js index 17e2d479ef..83fce2c638 100644 --- a/packages/yoroi-extension/app/api/ada/lib/cardanoCrypto/rustLoader.js +++ b/packages/yoroi-extension/app/api/ada/lib/cardanoCrypto/rustLoader.js @@ -18,7 +18,7 @@ const MAX_TX_BYTES = 16384; type RustModuleLoadFlags = 'dontLoadMessagesSigning'; function isWasmPointer(o: ?any): boolean { - return o != null && o.ptr != null && o.free != null; + return o != null && (typeof o.ptr === 'number') && (typeof o.free === 'function'); } /* @@ -58,7 +58,9 @@ function isProxiable(o: ?any): boolean { */ function createWasmScope(): {| RustModule: Module, - free: () => void; + free: () => void, + size: () => number, + isFree: () => boolean, |} { /* * The main idea here is that we create a proxy of the root object (module itself) @@ -68,7 +70,7 @@ function createWasmScope(): {| * This way ANY wasm pointer produced within the callback will be automatically destroyed, * but only as long as it's created using the injected proxied module reference. */ - const scope = []; + const scope: Array<{ ptr: number, free: () => void, ... }> = []; function recursiveProxy(originalObject: E): E { if (!isProxiable(originalObject)) { return originalObject; @@ -139,6 +141,8 @@ function createWasmScope(): {| } }); }, + size: () => scope.length, + isFree: () => scope.every(x => x.ptr === 0), } } @@ -168,6 +172,41 @@ class Module { } } + __WasmScopeInternal(callback: Module => T): {| + result: T, + scopeSize: number, + scopeIsFree: boolean, + |} { + const scope = createWasmScope(); + function onSuccess(result: T): {| + result: T, + scopeSize: number, + scopeIsFree: boolean, + |} { + scope.free(); + if (isWasmPointer(result)) { + throw new Error('A wasm object cannot be returned from wasm scope, all pointers are destroyed.'); + } + return { + result, + scopeSize: scope.size(), + scopeIsFree: scope.isFree(), + }; + } + function onFailure(err: Error): void { + scope.free(); + throw err; + } + let result; + try { + result = callback(scope.RustModule); + } catch (e) { onFailure(e); throw e; } + return (result instanceof Promise) + // $FlowFixMe[incompatible-exact] + ? result.then(onSuccess, onFailure) + : onSuccess(result); + } + /** * The argument to this function is a callback. * The callback will receive a link to a `RustModule` instance. @@ -188,26 +227,7 @@ class Module { * callback promise resolves. */ WasmScope(callback: Module => T): T { - const scope = createWasmScope(); - function onSuccess(res: T): T { - scope.free(); - if (isWasmPointer(res)) { - throw new Error('A wasm object cannot be returned from wasm scope, all pointers are destroyed.'); - } - return res; - } - function onFailure(err: Error): void { - scope.free(); - throw err; - } - let result; - try { - result = callback(scope.RustModule); - } catch (e) { onFailure(e); throw e; } - return (result instanceof Promise) - // $FlowFixMe[incompatible-return] - ? result.then(onSuccess, onFailure) - : onSuccess(result); + return this.__WasmScopeInternal(callback).result; } // Need to expose through a getter to get Flow to detect the type correctly diff --git a/packages/yoroi-extension/app/api/ada/lib/cardanoCrypto/rustLoader.test.js b/packages/yoroi-extension/app/api/ada/lib/cardanoCrypto/rustLoader.test.js index 6fc507374f..ed39f70a19 100644 --- a/packages/yoroi-extension/app/api/ada/lib/cardanoCrypto/rustLoader.test.js +++ b/packages/yoroi-extension/app/api/ada/lib/cardanoCrypto/rustLoader.test.js @@ -11,8 +11,11 @@ test('Wasm Scope Simple Address Convert', async () => { const addr = 'addr1qf2w3pe8jsyvr9kutpv6e0rzuaym7dvq0rrz9699a7y3wwvz6g3gz764vxla692p4ttcekdw0smpedxuqq7a8t8sv3usrcv98z'; const addressFixedDirectly = bytesToHex(RustModule.WalletV4.Address.from_bech32(addr).to_bytes()); - const addressFixedInScope = RustModule.WasmScope(Module => { + const scopeResult = RustModule.__WasmScopeInternal(Module => { return bytesToHex(Module.WalletV4.Address.from_bech32(addr).to_bytes()); }); + const addressFixedInScope = scopeResult.result; expect(addressFixedInScope).toEqual(addressFixedDirectly); + expect(scopeResult.scopeSize).toEqual(1); + expect(scopeResult.scopeIsFree).toEqual(true); }); From eba7f77acad8caec7c67017b40c3f587d8381ae8 Mon Sep 17 00:00:00 2001 From: yushi Date: Tue, 24 Jan 2023 02:19:44 +0800 Subject: [PATCH 128/172] allow required signer to be stake address --- .../chrome/extension/connector/api.js | 25 ++++++++++++++++--- 1 file changed, 21 insertions(+), 4 deletions(-) diff --git a/packages/yoroi-extension/chrome/extension/connector/api.js b/packages/yoroi-extension/chrome/extension/connector/api.js index 12c4ee43be..cdb9f38070 100644 --- a/packages/yoroi-extension/chrome/extension/connector/api.js +++ b/packages/yoroi-extension/chrome/extension/connector/api.js @@ -776,7 +776,7 @@ export async function connectorSignCardanoTx( ...requiredScriptSignKeys, ]); - console.log('totalAdditionalRequiredSignKeys', JSON.stringify(totalAdditionalRequiredSignKeys)); + console.log('totalAdditionalRequiredSignKeys', [...totalAdditionalRequiredSignKeys]); const additionalSignaturesRequired = totalAdditionalRequiredSignKeys.size > 0; const queryAllBaseAddresses = (): Promise> => { @@ -789,9 +789,20 @@ export async function connectorSignCardanoTx( return Promise.resolve([]); } - const [utxos, allBaseAddresses] = await Promise.all([ + const queryAllRewardAddresses = (): Promise> => { + if (additionalSignaturesRequired) { + return getAllAddressesForDisplay({ + publicDeriver, + type: CoreAddressTypes.CARDANO_REWARD, + }); + } + return Promise.resolve([]); + } + + const [utxos, allBaseAddresses, allRewardAddresses] = await Promise.all([ withHasUtxoChains.getAllUtxos(), queryAllBaseAddresses(), + queryAllRewardAddresses(), ]); const requiredTxSignAddresses = new Set(); @@ -822,7 +833,7 @@ export async function connectorSignCardanoTx( console.log('requiredAddress', requiredAddress.to_bech32()); requiredTxSignAddresses.add(bytesToHex(requiredAddress.to_bytes())); } - console.log('requiredTxSignAddresses', JSON.stringify(requiredTxSignAddresses)); + console.log('requiredTxSignAddresses', [...requiredTxSignAddresses]); for (const baseAddress of allBaseAddresses) { const { address, addressing } = baseAddress; if (requiredTxSignAddresses.delete(address)) { @@ -832,7 +843,13 @@ export async function connectorSignCardanoTx( break; } } - console.log('otherRequiredSigners', JSON.stringify(otherRequiredSigners)); + for (const rewardAddress of allRewardAddresses) { + const { address, addressing } = rewardAddress; + if (totalAdditionalRequiredSignKeys.has(address.slice(2))) { + otherRequiredSigners.push({ address, addressing }); + } + } + console.log('otherRequiredSigners', [...otherRequiredSigners]); } const submittedTxs = loadSubmittedTransactions() || []; From 3a179043fe147160ad636b065b5b2340a2259195 Mon Sep 17 00:00:00 2001 From: yushi Date: Tue, 24 Jan 2023 13:51:00 +0800 Subject: [PATCH 129/172] submit tx API should not de-serialize and re-serialize --- .../app/connector/stores/ConnectorStore.js | 2 +- packages/yoroi-extension/chrome/extension/background.js | 9 +++++---- .../yoroi-extension/chrome/extension/connector/api.js | 4 ++-- 3 files changed, 8 insertions(+), 7 deletions(-) diff --git a/packages/yoroi-extension/app/connector/stores/ConnectorStore.js b/packages/yoroi-extension/app/connector/stores/ConnectorStore.js index 38c144f6b9..27c51f2d27 100644 --- a/packages/yoroi-extension/app/connector/stores/ConnectorStore.js +++ b/packages/yoroi-extension/app/connector/stores/ConnectorStore.js @@ -334,7 +334,7 @@ export default class ConnectorStore extends Store { try { await connectorSendTxCardano( wallet.publicDeriver, - signedTx.to_bytes(), + Buffer.from(signedTx.to_bytes()), this.api.localStorage, ); } catch { diff --git a/packages/yoroi-extension/chrome/extension/background.js b/packages/yoroi-extension/chrome/extension/background.js index 3e4005b835..1cdc2463f7 100644 --- a/packages/yoroi-extension/chrome/extension/background.js +++ b/packages/yoroi-extension/chrome/extension/background.js @@ -1321,14 +1321,15 @@ function handleInjectorConnect(port) { async (wallet) => { let id; if (isCardanoHaskell(wallet.getParent().getNetworkInfo())) { - const tx = RustModule.WalletV4.Transaction.from_bytes( - Buffer.from(message.params[0], 'hex'), - ); + const txBuffer = Buffer.from(message.params[0], 'hex'); await connectorSendTxCardano( wallet, - tx.to_bytes(), + txBuffer, localStorageApi, ); + const tx = RustModule.WalletV4.Transaction.from_bytes( + txBuffer + ); id = Buffer.from( RustModule.WalletV4.hash_transaction(tx.body()).to_bytes() ).toString('hex'); diff --git a/packages/yoroi-extension/chrome/extension/connector/api.js b/packages/yoroi-extension/chrome/extension/connector/api.js index cdb9f38070..9ecccd20de 100644 --- a/packages/yoroi-extension/chrome/extension/connector/api.js +++ b/packages/yoroi-extension/chrome/extension/connector/api.js @@ -1022,10 +1022,10 @@ export async function connectorSendTx( export async function connectorSendTxCardano( wallet: IPublicDeriver, - signedTx: Uint8Array, + signedTx: Buffer, localStorage: LocalStorageApi, ): Promise { - const signedTx64 = Buffer.from(signedTx).toString('base64'); + const signedTx64 = signedTx.toString('base64'); const network = wallet.getParent().getNetworkInfo(); const backend = network.Backend.BackendService; if (backend == null) { From 6c60d49e0d449cda70ee848318eca453ac174282 Mon Sep 17 00:00:00 2001 From: yushi Date: Tue, 24 Jan 2023 15:54:02 +0800 Subject: [PATCH 130/172] connector signing tx API uses raw tx body to compute hash --- .../ada/transactions/shelley/transactions.js | 31 ++- .../chrome/extension/connector/api.js | 8 +- packages/yoroi-extension/package-lock.json | 209 ++++-------------- packages/yoroi-extension/package.json | 9 +- 4 files changed, 77 insertions(+), 180 deletions(-) diff --git a/packages/yoroi-extension/app/api/ada/transactions/shelley/transactions.js b/packages/yoroi-extension/app/api/ada/transactions/shelley/transactions.js index 83d64cd552..549214cb3b 100644 --- a/packages/yoroi-extension/app/api/ada/transactions/shelley/transactions.js +++ b/packages/yoroi-extension/app/api/ada/transactions/shelley/transactions.js @@ -33,6 +33,8 @@ import { IPublicDeriver, IGetAllUtxos, IHasUtxoChains } from '../../lib/storage/ import { ConceptualWallet } from '../../lib/storage/models/ConceptualWallet/index'; import { builtSendTokenList } from '../../../common'; import type { TokenRow } from '../../lib/storage/database/primitives/tables'; +import blake2b from 'blake2b'; + /** * based off what the cardano-wallet team found worked empirically * note: slots are 1 second in Shelley mainnet, so this is 2hrs @@ -1145,7 +1147,10 @@ type UtxoOrAddressing = CardanoAddressedUtxo | {| ...Address, ...Addressing |}; export function signTransaction( senderUtxos: Array, - unsignedTx: RustModule.WalletV4.TransactionBuilder | RustModule.WalletV4.TransactionBody, + unsignedTx: + RustModule.WalletV4.TransactionBuilder | + RustModule.WalletV4.TransactionBody | + Buffer, keyLevel: number, signingKey: RustModule.WalletV4.Bip32PrivateKey, stakingKeyWits: Set, @@ -1188,10 +1193,26 @@ export function signTransaction( addIfUnique(otherSigner.address, otherSigner); } - const txBody = unsignedTx instanceof RustModule.WalletV4.TransactionBuilder - ? unsignedTx.build() - : unsignedTx; - const txHash = RustModule.WalletV4.hash_transaction(txBody); + let txBody; + let txHash; + if (unsignedTx instanceof RustModule.WalletV4.TransactionBuilder) { + txBody = unsignedTx.build(); + txHash = RustModule.WalletV4.hash_transaction(txBody); + } else if (unsignedTx instanceof RustModule.WalletV4.TransactionBody) { + txBody = unsignedTx; + txHash = RustModule.WalletV4.hash_transaction(txBody); + } else if (unsignedTx instanceof Buffer) { + // note: we are calculating the tx hash from the raw tx body bytes, which + // probably won't match the serialized `txBody`. But this happens only for + // connector signing and only the witness will be returned so this is more + // likely to match what the client expects. + txBody = RustModule.WalletV4.TransactionBody.from_bytes(unsignedTx); + txHash = RustModule.WalletV4.TransactionHash.from_bytes( + blake2b(256 / 8).update(unsignedTx).digest('binary') + ); + } else { + throw new Error('unexpected tx body type'); + } const vkeyWits = RustModule.WalletV4.Vkeywitnesses.new(); const bootstrapWits = RustModule.WalletV4.BootstrapWitnesses.new(); diff --git a/packages/yoroi-extension/chrome/extension/connector/api.js b/packages/yoroi-extension/chrome/extension/connector/api.js index 9ecccd20de..8d2bfb42b9 100644 --- a/packages/yoroi-extension/chrome/extension/connector/api.js +++ b/packages/yoroi-extension/chrome/extension/connector/api.js @@ -89,6 +89,7 @@ import { raii, } from '../../../app/api/ada/lib/storage/database/utils'; import type { TokenRow } from '../../../app/api/ada/lib/storage/database/primitives/tables'; +import cbor from 'cbor'; function paginateResults(results: T[], paginate: ?Paginate): T[] { if (paginate != null) { @@ -744,16 +745,21 @@ export async function connectorSignCardanoTx( let txBody: RustModule.WalletV4.TransactionBody; let witnessSet: RustModule.WalletV4.TransactionWitnessSet; let auxiliaryData: ?RustModule.WalletV4.AuxiliaryData; + let rawTxBody: Buffer; const bytes = Buffer.from(txHex, 'hex'); try { const fullTx = RustModule.WalletV4.Transaction.from_bytes(bytes); txBody = fullTx.body(); witnessSet = fullTx.witness_set(); auxiliaryData = fullTx.auxiliary_data(); + rawTxBody = cbor.encodeCanonical( + cbor.decodeFirstSync(bytes)[0] + ); } catch (originalErr) { try { // Try parsing as body for backward compatibility txBody = RustModule.WalletV4.TransactionBody.from_bytes(bytes); + rawTxBody = bytes; } catch (_e) { throw originalErr; } @@ -895,7 +901,7 @@ export async function connectorSignCardanoTx( const signedTx = shelleySignTransaction( usedUtxos, - txBody, + rawTxBody, withLevels.getParent().getPublicDeriverLevel(), RustModule.WalletV4.Bip32PrivateKey.from_bytes( Buffer.from(normalizedKey.prvKeyHex, 'hex') diff --git a/packages/yoroi-extension/package-lock.json b/packages/yoroi-extension/package-lock.json index d9a914bfe3..6424402349 100644 --- a/packages/yoroi-extension/package-lock.json +++ b/packages/yoroi-extension/package-lock.json @@ -7568,12 +7568,6 @@ "defer-to-connect": "^2.0.0" } }, - "@testim/chrome-version": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/@testim/chrome-version/-/chrome-version-1.1.3.tgz", - "integrity": "sha512-g697J3WxV/Zytemz8aTuKjTGYtta9+02kva3C1xc7KXB8GdbfE1akGJIsZLyY/FSh2QrnE+fiB7vmWU3XNcb6A==", - "dev": true - }, "@tootallnate/once": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/@tootallnate/once/-/once-1.1.2.tgz", @@ -8129,16 +8123,6 @@ "integrity": "sha512-7tFImggNeNBVMsn0vLrpn1H1uPrUBdnARPTpZoitY37ZrdJREzf7I16tMrlK3hen349gr1NYh8CmZQa7CTG6Aw==", "dev": true }, - "@types/yauzl": { - "version": "2.10.0", - "resolved": "https://registry.npmjs.org/@types/yauzl/-/yauzl-2.10.0.tgz", - "integrity": "sha512-Cn6WYCm0tXv8p6k+A8PvbDG763EDpBoTzHdA+Q/MF6H3sapGjCm9NzoaJncJS9tUKSuCoDs9XHxYYsQDgxR6kw==", - "dev": true, - "optional": true, - "requires": { - "@types/node": "*" - } - }, "@webassemblyjs/ast": { "version": "1.9.0", "resolved": "https://registry.npmjs.org/@webassemblyjs/ast/-/ast-1.9.0.tgz", @@ -8599,7 +8583,7 @@ "any-promise": { "version": "1.3.0", "resolved": "https://registry.npmjs.org/any-promise/-/any-promise-1.3.0.tgz", - "integrity": "sha512-7UvmKalWRt1wgjL1RrGxoSJW/0QZFIegpeGvZG9kjp8vrRu55XTHbwnqq2GpXm9uLbcuhxm3IqX9OB4MZR1b2A==", + "integrity": "sha1-q8av7tzqUugJzcA3au0845Y10X8=", "dev": true }, "anymatch": { @@ -8781,7 +8765,7 @@ "array-equal": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/array-equal/-/array-equal-1.0.0.tgz", - "integrity": "sha1-jCpe8kcv2ep0KwTHenUJO6J1fJM=" + "integrity": "sha512-H3LU5RLiSsGXPhN+Nipar0iR0IofH+8r89G2y1tBKxQ/agagKyAjhkAFDRBfodP2caPrNKHpAWNIM/c9yeL7uA==" }, "array-find-index": { "version": "1.0.2", @@ -9761,7 +9745,7 @@ "becke-ch--regex--s0-0-v1--base--pl--lib": { "version": "1.4.0", "resolved": "https://registry.npmjs.org/becke-ch--regex--s0-0-v1--base--pl--lib/-/becke-ch--regex--s0-0-v1--base--pl--lib-1.4.0.tgz", - "integrity": "sha512-FnWonOyaw7Vivg5nIkrUll9HSS5TjFbyuURAiDssuL6VxrBe3ERzudRxOcWRhZYlP89UArMDikz7SapRPQpmZQ==", + "integrity": "sha1-Qpzuu/pffpNueNc/vcfacWKyDiA=", "dev": true }, "before-after-hook": { @@ -10586,6 +10570,14 @@ "resolved": "https://registry.npmjs.org/caseless/-/caseless-0.12.0.tgz", "integrity": "sha1-G2gcIf+EAzyCZUMJBolCDRhxUdw=" }, + "cbor": { + "version": "8.1.0", + "resolved": "https://registry.npmjs.org/cbor/-/cbor-8.1.0.tgz", + "integrity": "sha512-DwGjNW9omn6EwP70aXsn7FQJx5kO12tX0bZkaTjzdVFM6/7nhA4t0EENocKGx6D2Bch9PE2KzCUf5SceBdeijg==", + "requires": { + "nofilter": "^3.1.0" + } + }, "chacha": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/chacha/-/chacha-2.1.0.tgz", @@ -10735,61 +10727,6 @@ "integrity": "sha512-p3KULyQg4S7NIHixdwbGX+nFHkoBiA4YQmyWtjb8XngSKV124nJmRysgAeujbUVb15vh+RvFUfCPqU7rXk+hZg==", "dev": true }, - "chromedriver": { - "version": "109.0.0", - "resolved": "https://registry.npmjs.org/chromedriver/-/chromedriver-109.0.0.tgz", - "integrity": "sha512-jdmBq11IUwfThLFiygGTZ89qbROSQI4bICQjvOVQy2Bqr1LwC+MFkhwyZp3YG99eehQbZuTlQmmfCZBfpewTNA==", - "dev": true, - "requires": { - "@testim/chrome-version": "^1.1.3", - "axios": "^1.2.1", - "compare-versions": "^5.0.1", - "extract-zip": "^2.0.1", - "https-proxy-agent": "^5.0.1", - "proxy-from-env": "^1.1.0", - "tcp-port-used": "^1.0.1" - }, - "dependencies": { - "axios": { - "version": "1.2.3", - "resolved": "https://registry.npmjs.org/axios/-/axios-1.2.3.tgz", - "integrity": "sha512-pdDkMYJeuXLZ6Xj/Q5J3Phpe+jbGdsSzlQaFVkMQzRUL05+6+tetX8TV3p4HrU4kzuO9bt+io/yGQxuyxA/xcw==", - "dev": true, - "requires": { - "follow-redirects": "^1.15.0", - "form-data": "^4.0.0", - "proxy-from-env": "^1.1.0" - } - }, - "follow-redirects": { - "version": "1.15.2", - "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.2.tgz", - "integrity": "sha512-VQLG33o04KaQ8uYi2tVNbdrWp1QWxNNea+nmIB4EVM28v0hmP17z7aG1+wAkNzVq4KeXTq3221ye5qTJP91JwA==", - "dev": true - }, - "form-data": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.0.tgz", - "integrity": "sha512-ETEklSGi5t0QMZuiXoA/Q6vcnxcLQP5vdugSpuAyi6SVGi2clPPp+xgEhuMaHC+zGgn31Kd235W35f7Hykkaww==", - "dev": true, - "requires": { - "asynckit": "^0.4.0", - "combined-stream": "^1.0.8", - "mime-types": "^2.1.12" - } - }, - "https-proxy-agent": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-5.0.1.tgz", - "integrity": "sha512-dFcAjpTQFgoLMzC2VwU+C/CbS7uRL0lWmxDITmqm7C+7F0Odmj6s9l6alZc6AELXhrnggM2CeWSXHGOdX2YtwA==", - "dev": true, - "requires": { - "agent-base": "6", - "debug": "4" - } - } - } - }, "ci-info": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-2.0.0.tgz", @@ -11081,12 +11018,6 @@ "integrity": "sha1-3dgA2gxmEnOTzKWVDqloo6rxJTs=", "dev": true }, - "compare-versions": { - "version": "5.0.3", - "resolved": "https://registry.npmjs.org/compare-versions/-/compare-versions-5.0.3.tgz", - "integrity": "sha512-4UZlZP8Z99MGEY+Ovg/uJxJuvoXuN4M6B3hKaiackiHrgzQFEe3diJi1mf1PNHbFujM7FvLrK2bpgIaImbtZ1A==", - "dev": true - }, "component-emitter": { "version": "1.3.0", "resolved": "https://registry.npmjs.org/component-emitter/-/component-emitter-1.3.0.tgz", @@ -12348,25 +12279,25 @@ "escape-string-regexp": { "version": "1.0.5", "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", - "integrity": "sha512-vbRorB5FUQWvla16U8R/qgaFIya2qGzwDrNmCZuYKrbdSUMG6I1ZCGQRefkRVhuOkIGVne7BQ35DSfo1qvJqFg==", + "integrity": "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=", "dev": true }, "indent-string": { "version": "3.2.0", "resolved": "https://registry.npmjs.org/indent-string/-/indent-string-3.2.0.tgz", - "integrity": "sha512-BYqTHXTGUIvg7t1r4sJNKcbDZkL92nkXA8YtRpbjFHRHGDL/NtUeiBJMeE60kIFN/Mg8ESaWQvftaYMGJzQZCQ==", + "integrity": "sha1-Sl/W0nzDMvN+VBmlBNu4NxBckok=", "dev": true }, "is-fullwidth-code-point": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-2.0.0.tgz", - "integrity": "sha512-VHskAKYM8RfSFXwee5t5cbN5PZeq1Wrh6qd5bkyiXIf6UQcN6w/A0eXM9r6t8d+GYOh+o6ZhiEnb88LN/Y8m2w==", + "integrity": "sha1-o7MKXE8ZkYMWeqq5O+764937ZU8=", "dev": true }, "path-key": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/path-key/-/path-key-2.0.1.tgz", - "integrity": "sha512-fEHGKCSmUSDPv4uoj8AlD+joPlq3peND+HRYyxFz4KPw4z926S/b8rIuFs2FYJg3BwsxJf6A9/3eIdLaYC+9Dw==", + "integrity": "sha1-QRyttXTFoUDTpLGRDUDYDMn0C0A=", "dev": true }, "semver": { @@ -12378,7 +12309,7 @@ "shebang-command": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-1.2.0.tgz", - "integrity": "sha512-EV3L1+UQWGor21OmnvojK36mhg+TyIKDh3iFBKBohr5xeXIhNBcx8oWdgkTEEQ+BEFFYdLRuqMfd5L84N1V5Vg==", + "integrity": "sha1-RKrGW2lbAzmJaMOfNj/uXer98eo=", "dev": true, "requires": { "shebang-regex": "^1.0.0" @@ -12387,7 +12318,7 @@ "shebang-regex": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-1.0.0.tgz", - "integrity": "sha512-wpoSFAxys6b2a2wHZ1XpDSgD7N9iVjg29Ph9uV/uaP9Ex/KXlkTZTeddxDPSYQpgvzKLGJke2UU0AzoGCjNIvQ==", + "integrity": "sha1-2kL0l0DAtC2yypcoVxyxkMmO/qM=", "dev": true }, "string-width": { @@ -12403,7 +12334,7 @@ "strip-ansi": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-4.0.0.tgz", - "integrity": "sha512-4XaJ2zQdCzROZDivEVIDPkcQn8LMFSa8kj8Gxb/Lnwzv9A8VctNZ+lfivC/sV3ivW8ElJTERXZoPBRrZKkNKow==", + "integrity": "sha1-qEeQIusaw2iocTibY1JixQXuNo8=", "dev": true, "requires": { "ansi-regex": "^3.0.0" @@ -12498,7 +12429,7 @@ "cucumber-tag-expressions": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/cucumber-tag-expressions/-/cucumber-tag-expressions-1.1.1.tgz", - "integrity": "sha512-V9jv81sR/HaJ87FoidrvHkviXId7KmBcUi7aQPfi+W3nRO30N6GqH6lcp8K+nyiT1DgemRJBPDDeBMS93xJqMQ==", + "integrity": "sha1-f1x7cACbwrZmWRv+ZIVFeL7e6Fo=", "dev": true }, "currently-unhandled": { @@ -13565,7 +13496,7 @@ "es6-iterator": { "version": "2.0.3", "resolved": "https://registry.npmjs.org/es6-iterator/-/es6-iterator-2.0.3.tgz", - "integrity": "sha512-zw4SRzoUkd+cl+ZoE15A9o1oQd920Bb0iOJMQkQhl3jNc03YqVjAhG7scf9C5KWRU/R13Orf588uCC6525o02g==", + "integrity": "sha1-p96IkUGgWpSwhUQDstCg+/qY87c=", "dev": true, "requires": { "d": "1", @@ -14677,29 +14608,6 @@ } } }, - "extract-zip": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/extract-zip/-/extract-zip-2.0.1.tgz", - "integrity": "sha512-GDhU9ntwuKyGXdZBUgTIe+vXnWj0fppUEtMDL0+idd5Sta8TGpHssn/eusA9mrPr9qNDym6SxAYZjNvCn/9RBg==", - "dev": true, - "requires": { - "@types/yauzl": "^2.9.1", - "debug": "^4.1.1", - "get-stream": "^5.1.0", - "yauzl": "^2.10.0" - }, - "dependencies": { - "get-stream": { - "version": "5.2.0", - "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-5.2.0.tgz", - "integrity": "sha512-nBF+F1rAZVCu/p7rjzgA+Yb4lfYXrpl7a6VmJrU8wF9I1CKvP/QwPNZHnOlwbTkY6dvtFIzFMSyQXbLoTQPRpA==", - "dev": true, - "requires": { - "pump": "^3.0.0" - } - } - } - }, "extsprintf": { "version": "1.3.0", "resolved": "https://registry.npmjs.org/extsprintf/-/extsprintf-1.3.0.tgz", @@ -14796,7 +14704,7 @@ "figures": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/figures/-/figures-2.0.0.tgz", - "integrity": "sha512-Oa2M9atig69ZkfwiApY8F2Yy+tzMbazyvqv21R0NsSC8floSOC09BbT1ITWAdoMGQvJ/aZnR1KMwdx9tvHnTNA==", + "integrity": "sha1-OrGi0qYsi/tDGgyUy3l6L84nyWI=", "dev": true, "requires": { "escape-string-regexp": "^1.0.5" @@ -14805,7 +14713,7 @@ "escape-string-regexp": { "version": "1.0.5", "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", - "integrity": "sha512-vbRorB5FUQWvla16U8R/qgaFIya2qGzwDrNmCZuYKrbdSUMG6I1ZCGQRefkRVhuOkIGVne7BQ35DSfo1qvJqFg==", + "integrity": "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=", "dev": true } } @@ -16051,7 +15959,7 @@ "gherkin": { "version": "5.1.0", "resolved": "https://registry.npmjs.org/gherkin/-/gherkin-5.1.0.tgz", - "integrity": "sha512-axTCsxH0m0cixijLvo7s9591h5pMb8ifQxFDun5FnfFhVsUhxgdnH0H7TSK7q8I4ASUU18DJ/tmlnMegMuLUUQ==", + "integrity": "sha1-aEu7A63STq9731RPWAM+so+zxtU=", "dev": true }, "glob": { @@ -16764,7 +16672,7 @@ "httpolyglot": { "version": "0.1.2", "resolved": "https://registry.npmjs.org/httpolyglot/-/httpolyglot-0.1.2.tgz", - "integrity": "sha512-ouHI1AaQMLgn4L224527S5+vq6hgvqPteurVfbm7ChViM3He2Wa8KP1Ny7pTYd7QKnDSPKcN8JYfC8r/lmsE3A==", + "integrity": "sha1-5NNH/omEpi9GfUBg31J/GFH2mXs=", "dev": true }, "https-browserify": { @@ -17028,12 +16936,6 @@ "integrity": "sha1-vd7XARQpCCjAoDnnLvJfWq7ENUo=", "dev": true }, - "ip-regex": { - "version": "4.3.0", - "resolved": "https://registry.npmjs.org/ip-regex/-/ip-regex-4.3.0.tgz", - "integrity": "sha512-B9ZWJxHHOHUhUjCPrMpLD4xEq35bUTClHM1S6CBU5ixQnkZmwipwgc96vAd7AAGM9TGHvJR+Uss+/Ak6UphK+Q==", - "dev": true - }, "ipaddr.js": { "version": "1.9.1", "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz", @@ -17256,7 +17158,7 @@ "is-generator": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/is-generator/-/is-generator-1.0.3.tgz", - "integrity": "sha512-G56jBpbJeg7ds83HW1LuShNs8J73Fv3CPz/bmROHOHlnKkN8sWb9ujiagjmxxMUywftgq48HlBZELKKqFLk0oA==", + "integrity": "sha1-wUwhBX7TbjKNuANHlmxpP4hjifM=", "dev": true }, "is-generator-fn": { @@ -17440,12 +17342,6 @@ "resolved": "https://registry.npmjs.org/is-unicode-supported/-/is-unicode-supported-0.1.0.tgz", "integrity": "sha512-knxG2q4UC3u8stRGyAVJCOdxFmv5DZiRcdlIaAQXAbSfJya+OhopNotLQrstBhququ4ZpuKbDc/8S6mgXgPFPw==" }, - "is-url": { - "version": "1.2.4", - "resolved": "https://registry.npmjs.org/is-url/-/is-url-1.2.4.tgz", - "integrity": "sha512-ITvGim8FhRiYe4IQ5uHSkj7pVaPDrCTkNd3yq3cV7iZAcJdHTUMPMEHcqSOy9xZ9qFenQCvi+2wjH9a1nXqHww==", - "dev": true - }, "is-utf8": { "version": "0.2.1", "resolved": "https://registry.npmjs.org/is-utf8/-/is-utf8-0.2.1.tgz", @@ -17484,17 +17380,6 @@ "integrity": "sha512-VjSeb/lHmkoyd8ryPVIKvOCn4D1koMqY+vqyjjUfc3xyKtP4dYOxM44sZrnqQSzSds3xyOrUTLTC9LVCVgLngw==", "dev": true }, - "is2": { - "version": "2.0.9", - "resolved": "https://registry.npmjs.org/is2/-/is2-2.0.9.tgz", - "integrity": "sha512-rZkHeBn9Zzq52sd9IUIV3a5mfwBY+o2HePMh0wkGBM4z4qjvy2GwVxQ6nNXSfw6MmVP6gf1QIlWjiOavhM3x5g==", - "dev": true, - "requires": { - "deep-is": "^0.1.3", - "ip-regex": "^4.1.0", - "is-url": "^1.2.4" - } - }, "isarray": { "version": "0.0.1", "resolved": "https://registry.npmjs.org/isarray/-/isarray-0.0.1.tgz", @@ -19707,7 +19592,7 @@ "knuth-shuffle-seeded": { "version": "1.0.6", "resolved": "https://registry.npmjs.org/knuth-shuffle-seeded/-/knuth-shuffle-seeded-1.0.6.tgz", - "integrity": "sha512-9pFH0SplrfyKyojCLxZfMcvkhf5hH0d+UwR9nTVJ/DDQJGuzcXjTwB7TP7sDfehSudlGGaOLblmEWqv04ERVWg==", + "integrity": "sha1-AfG2VzOqdUDuCNiwF0Fk0iCB5OE=", "dev": true, "requires": { "seed-random": "~2.2.0" @@ -19955,7 +19840,7 @@ "lodash.omit": { "version": "4.5.0", "resolved": "https://registry.npmjs.org/lodash.omit/-/lodash.omit-4.5.0.tgz", - "integrity": "sha512-XeqSp49hNGmlkj2EJlfrQFIzQ6lXdNro9sddtQzcJY8QaoC2GO0DT7xaIokHeyM+mIT0mPMlPvkYzg2xCuHdZg==", + "integrity": "sha1-brGa5aHuHdnfC5aeZs4Lf6MLXmA=", "dev": true }, "lodash.set": { @@ -21527,6 +21412,11 @@ "integrity": "sha1-WuVUHQJGRdMqWPzdyc7s6nrjrC8=", "dev": true }, + "nofilter": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/nofilter/-/nofilter-3.1.0.tgz", + "integrity": "sha512-l2NNj07e9afPnhAhvgVrCD/oy2Ai1yfLpuo3EpiO1jFTsB4sFz6oIfAfSZyQzVpkZQ9xS8ZS5g1jCBgq4Hwo0g==" + }, "nopt": { "version": "2.2.1", "resolved": "https://registry.npmjs.org/nopt/-/nopt-2.2.1.tgz", @@ -22182,7 +22072,7 @@ "pad-right": { "version": "0.2.2", "resolved": "https://registry.npmjs.org/pad-right/-/pad-right-0.2.2.tgz", - "integrity": "sha512-4cy8M95ioIGolCoMmm2cMntGR1lPLEbOMzOKu8bzjuJP6JpzEMQcDHmh7hHLYGgob+nKe1YHFMaG4V59HQa89g==", + "integrity": "sha1-b7ySQEXSRPKiokRQMGDTv8YAl3Q=", "dev": true, "requires": { "repeat-string": "^1.5.2" @@ -25133,7 +25023,7 @@ "seed-random": { "version": "2.2.0", "resolved": "https://registry.npmjs.org/seed-random/-/seed-random-2.2.0.tgz", - "integrity": "sha512-34EQV6AAHQGhoc0tn/96a9Fsi6v2xdqe/dMUwljGRaFOzR3EgRmECvD0O8vi8X+/uQ50LGHfkNu/Eue5TPKZkQ==", + "integrity": "sha1-KpsZ4lCoFwmSMaW5mk2vgLf77VQ=", "dev": true }, "selenium-webdriver": { @@ -26550,27 +26440,6 @@ "readable-stream": "^3.1.1" } }, - "tcp-port-used": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/tcp-port-used/-/tcp-port-used-1.0.2.tgz", - "integrity": "sha512-l7ar8lLUD3XS1V2lfoJlCBaeoaWo/2xfYt81hM7VlvR4RrMVFqfmzfhLVk40hAb368uitje5gPtBRL1m/DGvLA==", - "dev": true, - "requires": { - "debug": "4.3.1", - "is2": "^2.0.6" - }, - "dependencies": { - "debug": { - "version": "4.3.1", - "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.1.tgz", - "integrity": "sha512-doEwdvm4PCeK4K3RQN2ZC2BYUBaxwLARCqZmMjtF8a51J2Rb0xpVloFRnCODwqjpwnAoao4pelN8l3RJdv3gRQ==", - "dev": true, - "requires": { - "ms": "2.1.2" - } - } - } - }, "telejson": { "version": "5.3.3", "resolved": "https://registry.npmjs.org/telejson/-/telejson-5.3.3.tgz", @@ -26741,7 +26610,7 @@ "thenify-all": { "version": "1.6.0", "resolved": "https://registry.npmjs.org/thenify-all/-/thenify-all-1.6.0.tgz", - "integrity": "sha512-RNxQH/qI8/t3thXJDwcstUO4zeqo64+Uy/+sNVRBx4Xn2OX+OZ9oP+iJnNFqplFra2ZUVeKCSa2oVWi3T4uVmA==", + "integrity": "sha1-GhkY1ALY/D+Y+/I02wvMjMEOlyY=", "dev": true, "requires": { "thenify": ">= 3.1.0 < 4" @@ -26858,7 +26727,7 @@ "title-case": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/title-case/-/title-case-2.1.1.tgz", - "integrity": "sha512-EkJoZ2O3zdCz3zJsYCsxyq2OC5hrxR9mfdd5I+w8h/tmFfeOxJ+vvkxsKxdmN0WtS9zLdHEgfgVOiMVgv+Po4Q==", + "integrity": "sha1-PhJyFtpY0rxb7PE3q5Ha46fNj6o=", "dev": true, "requires": { "no-case": "^2.2.0", @@ -26868,7 +26737,7 @@ "lower-case": { "version": "1.1.4", "resolved": "https://registry.npmjs.org/lower-case/-/lower-case-1.1.4.tgz", - "integrity": "sha512-2Fgx1Ycm599x+WGpIYwJOvsjmXFzTSc34IwDWALRA/8AopUKAVPwfJ+h5+f85BCp0PWmmJcWzEpxOpoXycMpdA==", + "integrity": "sha1-miyr0bno4K6ZOkv31YdcOcQujqw=", "dev": true }, "no-case": { @@ -27626,7 +27495,7 @@ "upper-case": { "version": "1.1.3", "resolved": "https://registry.npmjs.org/upper-case/-/upper-case-1.1.3.tgz", - "integrity": "sha512-WRbjgmYzgXkCV7zNVpy5YgrHgbBv126rMALQQMrmzOVC4GM2waQ9x7xtm8VU+1yF2kWyPzI9zbZ48n4vSxwfSA==", + "integrity": "sha1-9rRQHC7EzdJrp4vnIilh3ndiFZg=", "dev": true }, "uri-js": { @@ -27761,7 +27630,7 @@ "util-arity": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/util-arity/-/util-arity-1.1.0.tgz", - "integrity": "sha512-kkyIsXKwemfSy8ZEoaIz06ApApnWsk5hQO0vLjZS6UkBiGiW++Jsyb8vSBoc0WKlffGoGs5yYy/j5pp8zckrFA==", + "integrity": "sha1-WdAa8f2z/t4KxOYysKtfbOl8kzA=", "dev": true }, "util-deprecate": { diff --git a/packages/yoroi-extension/package.json b/packages/yoroi-extension/package.json index 581cbf54d8..49843df000 100644 --- a/packages/yoroi-extension/package.json +++ b/packages/yoroi-extension/package.json @@ -173,10 +173,6 @@ }, "dependencies": { "@cardano-foundation/ledgerjs-hw-app-cardano": "5.1.0", - "@ledgerhq/hw-transport-u2f": "5.36.0-deprecated", - "@ledgerhq/hw-transport-webauthn": "5.36.0-deprecated", - "@ledgerhq/hw-transport-webusb": "5.49.0", - "@ledgerhq/hw-transport-webhid": "5.51.1", "@download/blockies": "1.0.3", "@emotion/react": "^11.4.1", "@emotion/styled": "^11.3.0", @@ -186,6 +182,10 @@ "@emurgo/cip4-js": "1.0.5", "@emurgo/js-chain-libs": "0.7.1", "@emurgo/yoroi-lib": "0.2.0", + "@ledgerhq/hw-transport-u2f": "5.36.0-deprecated", + "@ledgerhq/hw-transport-webauthn": "5.36.0-deprecated", + "@ledgerhq/hw-transport-webhid": "5.51.1", + "@ledgerhq/hw-transport-webusb": "5.49.0", "@mui/lab": "^5.0.0-alpha.51", "@mui/material": "^5.0.4", "@svgr/webpack": "5.5.0", @@ -201,6 +201,7 @@ "bs58check": "2.1.2", "buffer": "6.0.3", "cardano-wallet-browser": "1.2.2", + "cbor": "^8.1.0", "chacha": "2.1.0", "classnames": "2.2.6", "crypto-browserify": "3.12.0", From 1df4943188b436547f4473612b955ab12973cb73 Mon Sep 17 00:00:00 2001 From: Ahmed Ibrahim Date: Tue, 24 Jan 2023 14:25:48 +0200 Subject: [PATCH 131/172] Flow --- packages/yoroi-extension/app/Routes.js | 14 ++++---------- .../dapp-connector/ConnectedWebsitesContainer.js | 2 +- .../app/containers/transfer/Transfer.js | 2 +- .../app/containers/wallet/WalletAddPage.js | 6 ++++-- 4 files changed, 10 insertions(+), 14 deletions(-) diff --git a/packages/yoroi-extension/app/Routes.js b/packages/yoroi-extension/app/Routes.js index e914baae31..a400ce7efc 100644 --- a/packages/yoroi-extension/app/Routes.js +++ b/packages/yoroi-extension/app/Routes.js @@ -17,10 +17,11 @@ import Wallet from './containers/wallet/Wallet'; import Settings from './containers/settings/Settings'; import Transfer, { WalletTransferPagePromise } from './containers/transfer/Transfer'; import ConnectedWebsitesPage, { ConnectedWebsitesPagePromise } from './containers/dapp-connector/ConnectedWebsitesContainer'; +import WalletAddPage, { AddAnotherWalletPromise } from './containers/wallet/WalletAddPage' +import AssetsWrapper from './containers/wallet/AssetsWrapper'; +import NFTsWrapper from './containers/wallet/NFTsWrapper'; // PAGES -const WalletAddPagePromise = () => import('./containers/wallet/WalletAddPage'); -const WalletAddPage = React.lazy(WalletAddPagePromise); const LanguageSelectionPagePromise = () => import('./containers/profile/LanguageSelectionPage'); const LanguageSelectionPage = React.lazy(LanguageSelectionPagePromise); const TermsOfUsePagePromise = () => import('./containers/profile/TermsOfUsePage'); @@ -91,12 +92,6 @@ const BlockchainSettingsPage = React.lazy(BlockchainSettingsPagePromise); const WalletSwitchPromise = () => import('./containers/WalletSwitch'); const WalletSwitch = React.lazy(WalletSwitchPromise); -const AssetsWrapperPromise = () => import('./containers/wallet/AssetsWrapper'); -const AssetsWrapper = React.lazy(AssetsWrapperPromise); - -const NFTsWrapperPromise = () => import('./containers/wallet/NFTsWrapper'); -const NFTsWrapper = React.lazy(NFTsWrapperPromise); - const TokensPageRevampPromise = () => import('./containers/wallet/TokensPageRevamp'); const TokensPageRevamp = React.lazy(TokensPageRevampPromise); @@ -116,7 +111,7 @@ const YoroiThemesPagePromise = () => import('./containers/experimental/yoroiThem const YoroiThemesPage = React.lazy(YoroiThemesPagePromise); export const LazyLoadPromises: Array<() => any> = [ - WalletAddPagePromise, + AddAnotherWalletPromise, LanguageSelectionPagePromise, TermsOfUsePagePromise, UriPromptPagePromise, @@ -143,7 +138,6 @@ export const LazyLoadPromises: Array<() => any> = [ ComplexityLevelPagePromise, BlockchainSettingsPagePromise, WalletSwitchPromise, - AssetsWrapperPromise, TokensPageRevampPromise, TokensDetailPageRevampPromise, NFTsPageRevampPromise, diff --git a/packages/yoroi-extension/app/containers/dapp-connector/ConnectedWebsitesContainer.js b/packages/yoroi-extension/app/containers/dapp-connector/ConnectedWebsitesContainer.js index f3f3caa43f..e450565ca2 100644 --- a/packages/yoroi-extension/app/containers/dapp-connector/ConnectedWebsitesContainer.js +++ b/packages/yoroi-extension/app/containers/dapp-connector/ConnectedWebsitesContainer.js @@ -32,7 +32,7 @@ import type { WalletChecksum } from '@emurgo/cip4-js'; import type { MultiToken } from '../../api/common/lib/MultiToken' -export const ConnectedWebsitesPagePromise = () => import('../../components/dapp-connector/ConnectedWebsites/ConnectedWebsitesPage'); +export const ConnectedWebsitesPagePromise: void => Promise = () => import('../../components/dapp-connector/ConnectedWebsites/ConnectedWebsitesPage'); const ConnectedWebsitesPage = lazy(ConnectedWebsitesPagePromise); export type GeneratedData = typeof ConnectedWebsitesPageContainer.prototype.generated; diff --git a/packages/yoroi-extension/app/containers/transfer/Transfer.js b/packages/yoroi-extension/app/containers/transfer/Transfer.js index 39bec38089..8a41ed2352 100644 --- a/packages/yoroi-extension/app/containers/transfer/Transfer.js +++ b/packages/yoroi-extension/app/containers/transfer/Transfer.js @@ -29,7 +29,7 @@ import type { GeneratedData as NavBarContainerRevampData } from '../NavBarContai import SubMenu from '../../components/topbar/SubMenu'; import { allSubcategoriesRevamp } from '../../stores/stateless/topbarCategories'; -export const WalletTransferPagePromise = () => import('./WalletTransferPage'); +export const WalletTransferPagePromise: void => Promise = () => import('./WalletTransferPage'); const WalletTransferPage = lazy(WalletTransferPagePromise); export type GeneratedData = typeof Transfer.prototype.generated; diff --git a/packages/yoroi-extension/app/containers/wallet/WalletAddPage.js b/packages/yoroi-extension/app/containers/wallet/WalletAddPage.js index a164fc45a8..5b81d31ba5 100644 --- a/packages/yoroi-extension/app/containers/wallet/WalletAddPage.js +++ b/packages/yoroi-extension/app/containers/wallet/WalletAddPage.js @@ -1,6 +1,6 @@ // @flow import type { Node, ComponentType } from 'react'; -import { Component } from 'react'; +import { Component, lazy } from 'react'; import { observer } from 'mobx-react'; import { computed } from 'mobx'; import { intlShape } from 'react-intl'; @@ -13,7 +13,6 @@ import TopBarLayout from '../../components/layout/TopBarLayout'; import BannerContainer from '../banners/BannerContainer'; import type { GeneratedData as BannerContainerData } from '../banners/BannerContainer'; import WalletAdd from '../../components/wallet/WalletAdd'; -import AddAnotherWallet from '../../components/wallet/add/AddAnotherWallet'; import WalletCreateDialogContainer from './dialogs/WalletCreateDialogContainer'; import type { GeneratedData as WalletCreateDialogContainerData } from './dialogs/WalletCreateDialogContainer'; @@ -68,6 +67,9 @@ import NavBarRevamp from '../../components/topbar/NavBarRevamp'; import { withLayout } from '../../styles/context/layout' import type { LayoutComponentMap } from '../../styles/context/layout' +export const AddAnotherWalletPromise: void => Promise = () => import('../../components/wallet/add/AddAnotherWallet'); +const AddAnotherWallet = lazy(AddAnotherWalletPromise); + export type GeneratedData = typeof WalletAddPage.prototype.generated; type Props = InjectedOrGenerated; From 113a2073bf699d4203973b1752d7b39581c67efd Mon Sep 17 00:00:00 2001 From: Ahmed Ibrahim Date: Tue, 24 Jan 2023 14:31:11 +0200 Subject: [PATCH 132/172] Remove staking page wrapper --- packages/yoroi-extension/app/Routes.js | 1 - .../app/containers/wallet/staking/StakingPageContainer.js | 1 - 2 files changed, 2 deletions(-) delete mode 100644 packages/yoroi-extension/app/containers/wallet/staking/StakingPageContainer.js diff --git a/packages/yoroi-extension/app/Routes.js b/packages/yoroi-extension/app/Routes.js index a400ce7efc..f036f4e664 100644 --- a/packages/yoroi-extension/app/Routes.js +++ b/packages/yoroi-extension/app/Routes.js @@ -195,7 +195,6 @@ export const Routes = ( } /> Date: Tue, 24 Jan 2023 15:03:37 +0200 Subject: [PATCH 133/172] Restructure the staking page --- packages/yoroi-extension/app/Routes.js | 3 +- .../containers/wallet/staking/StakingPage.js | 658 +---------------- .../wallet/staking/StakingPageContent.js | 679 ++++++++++++++++++ 3 files changed, 694 insertions(+), 646 deletions(-) create mode 100644 packages/yoroi-extension/app/containers/wallet/staking/StakingPageContent.js diff --git a/packages/yoroi-extension/app/Routes.js b/packages/yoroi-extension/app/Routes.js index f036f4e664..4069763330 100644 --- a/packages/yoroi-extension/app/Routes.js +++ b/packages/yoroi-extension/app/Routes.js @@ -12,7 +12,7 @@ import type { GeneratedData as ReceiveData } from './containers/wallet/Receive'; import type { ConfigType } from '../config/config-types'; import type { GeneratedData as AssetsData } from './containers/wallet/AssetsWrapper'; import LoadingPage from './containers/LoadingPage'; -import StakingPage from './containers/wallet/staking/StakingPage'; +import StakingPage, { StakingPageContentPromise } from './containers/wallet/staking/StakingPage'; import Wallet from './containers/wallet/Wallet'; import Settings from './containers/settings/Settings'; import Transfer, { WalletTransferPagePromise } from './containers/transfer/Transfer'; @@ -112,6 +112,7 @@ const YoroiThemesPage = React.lazy(YoroiThemesPagePromise); export const LazyLoadPromises: Array<() => any> = [ AddAnotherWalletPromise, + StakingPageContentPromise, LanguageSelectionPagePromise, TermsOfUsePagePromise, UriPromptPagePromise, diff --git a/packages/yoroi-extension/app/containers/wallet/staking/StakingPage.js b/packages/yoroi-extension/app/containers/wallet/staking/StakingPage.js index e6b773b073..cb4a539fe5 100644 --- a/packages/yoroi-extension/app/containers/wallet/staking/StakingPage.js +++ b/packages/yoroi-extension/app/containers/wallet/staking/StakingPage.js @@ -1,376 +1,32 @@ // @flow -import type { ComponentType, Node } from 'react'; -import type { $npm$ReactIntl$IntlFormat } from 'react-intl'; +import { Component, Suspense, lazy } from 'react'; +import type { Node } from 'react'; import type { GeneratedData as BannerContainerData } from '../../banners/BannerContainer'; import type { InjectedOrGenerated } from '../../../types/injectedPropsType'; import type { GeneratedData as SidebarContainerData } from '../../SidebarContainer'; import type { GeneratedData as NavBarContainerRevampData } from '../../NavBarContainerRevamp'; -import type { LayoutComponentMap } from '../../../styles/context/layout'; import type { ConfigType } from '../../../../config/config-types'; -import type { TxRequests } from '../../../stores/toplevel/TransactionsStore'; -import type { DelegationRequests, PoolMeta } from '../../../stores/toplevel/DelegationStore'; -import type { GeneratedData as UnmangleTxDialogContainerData } from '../../transfer/UnmangleTxDialogContainer'; -import type { GeneratedData as DeregisterDialogContainerData } from '../../transfer/DeregisterDialogContainer'; -import type { TokenInfoMap } from '../../../stores/toplevel/TokenInfoStore'; -import type { NetworkRow } from '../../../api/ada/lib/storage/database/primitives/tables'; -import type { UnitOfAccountSettingType } from '../../../types/unitOfAccountType'; -import type { AdaDelegationRequests } from '../../../stores/ada/AdaDelegationStore'; -import type { GeneratedData as WithdrawalTxDialogContainerData } from '../../transfer/WithdrawalTxDialogContainer'; -import type { PoolRequest } from '../../../api/jormungandr/lib/storage/bridge/delegationUtils'; -import type { TokenEntry } from '../../../api/common/lib/MultiToken'; -import type { - CurrentTimeRequests, - TimeCalcRequests, -} from '../../../stores/base/BaseCardanoTimeStore'; - -import { Component } from 'react'; import { computed } from 'mobx'; import { observer } from 'mobx-react'; -import { intlShape } from 'react-intl'; -import moment from 'moment'; - import globalMessages from '../../../i18n/global-messages'; import BannerContainer from '../../banners/BannerContainer'; import SidebarContainer from '../../SidebarContainer'; import NavBarContainerRevamp from '../../NavBarContainerRevamp'; import TopBarLayout from '../../../components/layout/TopBarLayout'; import NavBarTitle from '../../../components/topbar/NavBarTitle'; -import { PublicDeriver } from '../../../api/ada/lib/storage/models/PublicDeriver/index'; -import { withLayout } from '../../../styles/context/layout'; -import WalletEmptyBanner from '../WalletEmptyBanner'; -import BuySellDialog from '../../../components/buySell/BuySellDialog'; -import CardanoStakingPage from './CardanoStakingPage'; -import { Box, styled } from '@mui/system'; -import SummaryCard from '../../../components/wallet/staking/dashboard-revamp/SummaryCard'; -import EpochProgressWrapper from '../../../components/wallet/staking/dashboard-revamp/EpochProgressWrapper'; -import OverviewModal from '../../../components/wallet/staking/dashboard-revamp/OverviewDialog'; -import LocalizableError from '../../../i18n/LocalizableError'; -import { MultiToken } from '../../../api/common/lib/MultiToken'; -import { genLookupOrFail } from '../../../stores/stateless/tokenHelpers'; -import UnmangleTxDialogContainer from '../../transfer/UnmangleTxDialogContainer'; -import DeregisterDialogContainer from '../../transfer/DeregisterDialogContainer'; -import { calculateAndFormatValue } from '../../../utils/unit-of-account'; -import { - isCardanoHaskell, - isJormungandr, -} from '../../../api/ada/lib/storage/database/prepackaged/networks'; -import EpochProgressContainer from './EpochProgressContainer'; -import WithdrawalTxDialogContainer from '../../transfer/WithdrawalTxDialogContainer'; -import UndelegateDialog from '../../../components/wallet/staking/dashboard/UndelegateDialog'; -import { generateGraphData } from '../../../utils/graph'; -import { ApiOptions, getApiForNetwork } from '../../../api/common/utils'; -import RewardHistoryDialog from '../../../components/wallet/staking/dashboard-revamp/RewardHistoryDialog'; -import DelegatedStakePoolCard from '../../../components/wallet/staking/dashboard-revamp/DelegatedStakePoolCard'; + +export const StakingPageContentPromise: void => Promise = () => import('./StakingPageContent'); +const StakingPageContent = lazy(StakingPageContentPromise); export type GeneratedData = typeof StakingPage.prototype.generated; // populated by ConfigWebpackPlugin declare var CONFIG: ConfigType; -type Props = {| - ...InjectedOrGenerated, - actions: any, - stores: any, -|}; -type InjectedProps = {| - +renderLayoutComponent: LayoutComponentMap => Node, -|}; +type Props = {| ...InjectedOrGenerated, stores: any, actions: any |}; -type AllProps = {| ...Props, ...InjectedProps |}; @observer -class StakingPage extends Component { - static contextTypes: {| intl: $npm$ReactIntl$IntlFormat |} = { - intl: intlShape.isRequired, - }; - - onClose: void => void = () => { - this.generated.actions.dialogs.closeActiveDialog.trigger(); - }; - - _isRegistered: (PublicDeriver<>) => ?boolean = publicDeriver => { - if (!isCardanoHaskell(publicDeriver.getParent().getNetworkInfo())) { - return undefined; - } - const adaDelegationRequests = this.generated.stores.substores.ada.delegation.getDelegationRequests( - publicDeriver - ); - if (adaDelegationRequests == null) return undefined; - return adaDelegationRequests.getRegistrationHistory.result?.current; - }; - - async componentDidMount() { - const timeStore = this.generated.stores.time; - const publicDeriver = this.generated.stores.wallets.selected; - if (publicDeriver == null) { - throw new Error(`${nameof(StakingPage)} no public deriver. Should never happen`); - } - const timeCalcRequests = timeStore.getTimeCalcRequests(publicDeriver); - await timeCalcRequests.requests.toAbsoluteSlot.execute().promise; - await timeCalcRequests.requests.toRealTime.execute().promise; - await timeCalcRequests.requests.currentEpochLength.execute().promise; - await timeCalcRequests.requests.currentSlotLength.execute().promise; - await timeCalcRequests.requests.timeSinceGenesis.execute().promise; - } - - getErrorInFetch: (PublicDeriver<>) => void | {| error: LocalizableError |} = publicDeriver => { - const delegationStore = this.generated.stores.delegation; - const delegationRequests = delegationStore.getDelegationRequests(publicDeriver); - if (delegationRequests == null) { - throw new Error(`${nameof(StakingPage)} opened for non-reward wallet`); - } - if (delegationRequests.error != null) { - return { error: delegationRequests.error }; - } - if (delegationRequests.getCurrentDelegation.result != null) { - const currentDelegation = delegationRequests.getCurrentDelegation.result; - const currEpochInfo = currentDelegation.currEpoch; - if (currEpochInfo == null) { - return undefined; - } - } - return undefined; - }; - - getEpochLengthInDays: (PublicDeriver<>) => ?number = publicDeriver => { - const timeStore = this.generated.stores.time; - const timeCalcRequests = timeStore.getTimeCalcRequests(publicDeriver); - const getEpochLength = timeCalcRequests.requests.currentEpochLength.result; - if (getEpochLength == null) return null; - - const getSlotLength = timeCalcRequests.requests.currentSlotLength.result; - if (getSlotLength == null) return null; - - const epochLengthInSeconds = getEpochLength() * getSlotLength(); - const epochLengthInDays = epochLengthInSeconds / (60 * 60 * 24); - return epochLengthInDays; - }; - - getUserSummary: ({| - delegationRequests: DelegationRequests, - publicDeriver: PublicDeriver<>, - errorIfPresent: void | {| error: LocalizableError |}, - |}) => Node = request => { - const { actions, stores } = this.generated; - - const showRewardAmount = - request.delegationRequests.getCurrentDelegation.wasExecuted && - request.delegationRequests.getDelegatedBalance.wasExecuted && - request.errorIfPresent == null; - - const defaultToken = request.publicDeriver.getParent().getDefaultToken(); - - const currentlyDelegating = - (request.delegationRequests.getCurrentDelegation.result?.currEpoch?.pools ?? []).length > 0; - - return ( - - actions.dialogs.open.trigger({ - dialog: OverviewModal, - }) - } - unitOfAccount={this.toUnitOfAccount} - getTokenInfo={genLookupOrFail(stores.tokenInfoStore.tokenInfo)} - shouldHideBalance={stores.profile.shouldHideBalance} - totalRewards={ - !showRewardAmount || request.delegationRequests.getDelegatedBalance.result == null - ? undefined - : request.delegationRequests.getDelegatedBalance.result.accountPart - } - totalDelegated={(() => { - if (!showRewardAmount) return undefined; - if (request.delegationRequests.getDelegatedBalance.result == null) return undefined; - - return currentlyDelegating - ? request.delegationRequests.getDelegatedBalance.result.utxoPart.joinAddCopy( - request.delegationRequests.getDelegatedBalance.result.accountPart - ) - : new MultiToken([], defaultToken); - })()} - epochLength={this.getEpochLengthInDays(request.publicDeriver)} - graphData={generateGraphData({ - delegationRequests: request.delegationRequests, - publicDeriver: request.publicDeriver, - currentEpoch: stores.time.getCurrentTimeRequests(request.publicDeriver).currentEpoch, - shouldHideBalance: stores.profile.shouldHideBalance, - getLocalPoolInfo: stores.delegation.getLocalPoolInfo, - tokenInfo: stores.tokenInfoStore.tokenInfo, - })} - onOpenRewardList={() => - actions.dialogs.open.trigger({ - dialog: RewardHistoryDialog, - }) - } - /> - ); - }; - - getStakePoolMeta: (PublicDeriver<>) => Node = publicDeriver => { - const delegationStore = this.generated.stores.delegation; - const delegationRequests = delegationStore.getDelegationRequests(publicDeriver); - if (delegationRequests == null) { - throw new Error(`${nameof(StakingPage)} opened for non-reward wallet`); - } - if ( - !delegationRequests.getCurrentDelegation.wasExecuted || - delegationRequests.getCurrentDelegation.isExecuting || - delegationRequests.getCurrentDelegation.result == null - ) { - return null; - } - if (delegationRequests.getCurrentDelegation.result.currEpoch == null) { - return null; - } - const currentPools = delegationRequests.getCurrentDelegation.result.currEpoch.pools; - const currentPage = this.generated.stores.delegation.selectedPage; - - const currentPool = currentPools[0][currentPage]; - const meta = this.generated.stores.delegation.getLocalPoolInfo( - publicDeriver.getParent().getNetworkInfo(), - String(currentPool) - ); - if (meta == null) { - // server hasn't returned information about the stake pool yet - return null; - } - const { intl } = this.context; - const name = meta.info?.name ?? intl.formatMessage(globalMessages.unknownPoolLabel); - // TODO: remove placeholders - const delegatedPool = { - id: String(currentPool), - name, - roa: '5.1', - poolSize: 2560000, - share: '0.3', - websiteUrl: meta.info?.homepage, - ticker: meta.info?.ticker, - }; - - // TODO: implement this eventually - // const stakePoolMeta = { - // avatar: '', - // websiteUrl: '', - // roa: ' 5.08%', - // socialLinks: { - // fb: '', - // tw: '', - // }, - // }; - - // don't support undelegation for ratio stake since it's a less intuitive UX - const undelegate = - currentPools.length === 1 && isJormungandr(publicDeriver.getParent().getNetworkInfo()) - ? async () => { - this.generated.actions.dialogs.open.trigger({ dialog: UndelegateDialog }); - await this.generated.actions.jormungandr.delegationTransaction.createTransaction.trigger( - { - publicDeriver, - poolRequest: undefined, - } - ); - } - : undefined; - - return ( - - ); - }; - - getEpochProgress: (PublicDeriver<>) => Node | void = publicDeriver => { - const timeStore = this.generated.stores.time; - const timeCalcRequests = timeStore.getTimeCalcRequests(publicDeriver); - const currTimeRequests = timeStore.getCurrentTimeRequests(publicDeriver); - const toAbsoluteSlot = timeCalcRequests.requests.toAbsoluteSlot.result; - if (toAbsoluteSlot == null) return undefined; - const toRealTime = timeCalcRequests.requests.toRealTime.result; - if (toRealTime == null) return undefined; - const timeSinceGenesis = timeCalcRequests.requests.timeSinceGenesis.result; - if (timeSinceGenesis == null) return undefined; - const getEpochLength = timeCalcRequests.requests.currentEpochLength.result; - if (getEpochLength == null) return undefined; - const currentEpoch = currTimeRequests.currentEpoch; - const epochLength = getEpochLength(); - - const getDateFromEpoch = epoch => { - const epochTime = toRealTime({ - absoluteSlotNum: toAbsoluteSlot({ - epoch, - // in Jormungandr, rewards were distributed at the start of the epoch - // in Haskell, rewards are calculated at the start of the epoch but distributed at the end - slot: isJormungandr(publicDeriver.getParent().getNetworkInfo()) ? 0 : getEpochLength(), - }), - timeSinceGenesisFunc: timeSinceGenesis, - }); - const epochMoment = moment(epochTime).format('lll'); - return epochMoment; - }; - - const endEpochDate = getDateFromEpoch(currentEpoch); - const previousEpochDate = getDateFromEpoch(currentEpoch - 1); - - return ( - - ); - }; - - toUnitOfAccount: TokenEntry => void | {| currency: string, amount: string |} = entry => { - const { stores } = this.generated; - const tokenRow = stores.tokenInfoStore.tokenInfo - .get(entry.networkId.toString()) - ?.get(entry.identifier); - if (tokenRow == null) return undefined; - - if (!stores.profile.unitOfAccount.enabled) return undefined; - const currency = stores.profile.unitOfAccount.currency; - - const shiftedAmount = entry.amount.shiftedBy(-tokenRow.Metadata.numberOfDecimals); - const ticker = tokenRow.Metadata.ticker; - if (ticker == null) { - throw new Error('unexpected main token type'); - } - const coinPrice = stores.coinPriceStore.getCurrentPrice(ticker, currency); - if (coinPrice == null) return { currency, amount: '-' }; - return { - currency, - amount: calculateAndFormatValue(shiftedAmount, coinPrice), - }; - }; - +class StakingPage extends Component { render(): Node { const sidebarContainer = ; - const publicDeriver = this.generated.stores.wallets.selected; - if (publicDeriver == null) { - throw new Error(`${nameof(StakingPage)} no public deriver. Should never happen`); - } - const { stores } = this.generated; - const { uiDialogs, delegation: delegationStore } = stores; - const delegationRequests = delegationStore.getDelegationRequests(publicDeriver); - if (delegationRequests == null) { - throw new Error(`${nameof(StakingPage)} opened for non-reward wallet`); - } - const txRequests = stores.transactions.getTxRequests(publicDeriver); - const balance = txRequests.requests.getBalanceRequest.result; - const isWalletWithNoFunds = balance != null && balance.getDefaultEntry().amount.isZero(); - - const errorIfPresent = this.getErrorInFetch(publicDeriver); - - const showRewardAmount = - delegationRequests.getCurrentDelegation.wasExecuted && - delegationRequests.getDelegatedBalance.wasExecuted && - errorIfPresent == null; - - const delegationHistory = delegationRequests.getCurrentDelegation.result?.fullHistory; - const hasNeverDelegated = delegationHistory != null && delegationHistory.length === 0; - return ( } @@ -388,99 +44,13 @@ class StakingPage extends Component { showInContainer showAsCard > - - {isWalletWithNoFunds ? ( - - this.generated.actions.dialogs.open.trigger({ dialog: BuySellDialog }) - } - /> - ) : null} - {hasNeverDelegated ? null : ( - - {this.getUserSummary({ delegationRequests, publicDeriver, errorIfPresent })} - - {errorIfPresent} - {!errorIfPresent && this.getStakePoolMeta(publicDeriver)} - {!errorIfPresent && this.getEpochProgress(publicDeriver)} - - - )} - + - {uiDialogs.isOpen(OverviewModal) ? ( - { - this.generated.actions.dialogs.open.trigger({ - dialog: DeregisterDialogContainer, - }); - } - : undefined - } - /> - ) : null} - {uiDialogs.isOpen(DeregisterDialogContainer) ? ( - { - // note: purposely don't await - // since the next dialog will properly render the spinner - const { delegationTransaction } = this.generated.actions.ada; - delegationTransaction.createWithdrawalTxForWallet.trigger({ publicDeriver }); - this.generated.actions.dialogs.open.trigger({ - dialog: WithdrawalTxDialogContainer, - }); - }} - /> - ) : null} - {uiDialogs.isOpen(UnmangleTxDialogContainer) ? ( - - ) : null} - {uiDialogs.isOpen(WithdrawalTxDialogContainer) ? ( - { - this.generated.actions.ada.delegationTransaction.reset.trigger({ - justTransaction: false, - }); - this.generated.actions.dialogs.closeActiveDialog.trigger(); - }} - /> - ) : null} - {uiDialogs.isOpen(RewardHistoryDialog) ? ( - - ) : null} - + ); } @@ -489,86 +59,6 @@ class StakingPage extends Component { BannerContainerProps: InjectedOrGenerated, NavBarContainerRevampProps: InjectedOrGenerated, SidebarContainerProps: InjectedOrGenerated, - DeregisterDialogContainerProps: InjectedOrGenerated, - UnmangleTxDialogContainerProps: InjectedOrGenerated, - WithdrawalTxDialogContainerProps: InjectedOrGenerated, - actions: {| - ada: {| - delegationTransaction: {| - reset: {| trigger: (params: {| justTransaction: boolean |}) => void |}, - createWithdrawalTxForWallet: {| - trigger: (params: {| publicDeriver: PublicDeriver<> |}) => Promise, - |}, - |}, - |}, - jormungandr: {| - delegationTransaction: {| - createTransaction: {| - trigger: (params: {| - poolRequest: PoolRequest, - publicDeriver: PublicDeriver<>, - |}) => Promise, - |}, - |}, - |}, - dialogs: {| - open: {| - trigger: (params: {| - dialog: any, - params?: any, - |}) => void, - |}, - closeActiveDialog: {| - trigger: (params: void) => void, - |}, - |}, - transactions: {| - closeWalletEmptyBanner: {| - trigger: (params: void) => void, - |}, - closeDelegationBanner: {| - trigger: (params: void) => void, - |}, - |}, - |}, - stores: {| - uiDialogs: {| - getParam: (number | string) => T, - isOpen: any => boolean, - |}, - coinPriceStore: {| - getCurrentPrice: (from: string, to: string) => ?string, - |}, - substores: {| - ada: {| - delegation: {| - getDelegationRequests: (PublicDeriver<>) => void | AdaDelegationRequests, - |}, - |}, - |}, - delegation: {| - selectedPage: number, - getLocalPoolInfo: ($ReadOnly, string) => void | PoolMeta, - getDelegationRequests: (PublicDeriver<>) => void | DelegationRequests, - |}, - profile: {| - shouldHideBalance: boolean, - unitOfAccount: UnitOfAccountSettingType, - |}, - tokenInfoStore: {| - tokenInfo: TokenInfoMap, - |}, - wallets: {| selected: null | PublicDeriver<> |}, - transactions: {| - showWalletEmptyBanner: boolean, - showDelegationBanner: boolean, - getTxRequests: (PublicDeriver<>) => TxRequests, - |}, - time: {| - getCurrentTimeRequests: (PublicDeriver<>) => CurrentTimeRequests, - getTimeCalcRequests: (PublicDeriver<>) => TimeCalcRequests, - |}, - |}, |} { if (this.props.generated !== undefined) { return this.props.generated; @@ -576,139 +66,17 @@ class StakingPage extends Component { if (this.props.stores == null || this.props.actions == null) { throw new Error(`${nameof(StakingPage)} no way to generated props`); } + const { stores, actions } = this.props; - const selected = stores.wallets.selected; - if (selected == null) { - throw new Error(`${nameof(EpochProgressContainer)} no wallet selected`); - } - const api = getApiForNetwork(selected.getParent().getNetworkInfo()); - const time = (() => { - if (api === ApiOptions.ada) { - return { - getTimeCalcRequests: stores.substores.ada.time.getTimeCalcRequests, - getCurrentTimeRequests: stores.substores.ada.time.getCurrentTimeRequests, - }; - } - if (api === ApiOptions.jormungandr) { - return { - getTimeCalcRequests: stores.substores.jormungandr.time.getTimeCalcRequests, - getCurrentTimeRequests: stores.substores.jormungandr.time.getCurrentTimeRequests, - }; - } - return { - getTimeCalcRequests: (undefined: any), - getCurrentTimeRequests: () => { - throw new Error(`${nameof(StakingPage)} api not supported`); - }, - }; - })(); return Object.freeze({ - stores: { - wallets: { - selected: stores.wallets.selected, - }, - profile: { - shouldHideBalance: stores.profile.shouldHideBalance, - unitOfAccount: stores.profile.unitOfAccount, - }, - delegation: { - selectedPage: stores.delegation.selectedPage, - getLocalPoolInfo: stores.delegation.getLocalPoolInfo, - getDelegationRequests: stores.delegation.getDelegationRequests, - }, - uiDialogs: { - isOpen: stores.uiDialogs.isOpen, - getParam: stores.uiDialogs.getParam, - }, - transactions: { - showWalletEmptyBanner: stores.transactions.showWalletEmptyBanner, - showDelegationBanner: stores.transactions.showDelegationBanner, - getTxRequests: stores.transactions.getTxRequests, - }, - tokenInfoStore: { - tokenInfo: stores.tokenInfoStore.tokenInfo, - }, - coinPriceStore: { - getCurrentPrice: stores.coinPriceStore.getCurrentPrice, - }, - substores: { - ada: { - delegation: { - getDelegationRequests: stores.substores.ada.delegation.getDelegationRequests, - }, - }, - }, - time, - }, - actions: { - ada: { - delegationTransaction: { - reset: { - trigger: actions.ada.delegationTransaction.reset.trigger, - }, - createWithdrawalTxForWallet: { - trigger: actions.ada.delegationTransaction.createWithdrawalTxForWallet.trigger, - }, - }, - }, - jormungandr: { - delegationTransaction: { - createTransaction: { - trigger: actions.jormungandr.delegationTransaction.createTransaction.trigger, - }, - }, - }, - transactions: { - closeWalletEmptyBanner: { - trigger: actions.transactions.closeWalletEmptyBanner.trigger, - }, - closeDelegationBanner: { - trigger: actions.transactions.closeDelegationBanner.trigger, - }, - }, - dialogs: { - open: { - trigger: actions.dialogs.open.trigger, - }, - closeActiveDialog: { trigger: actions.dialogs.closeActiveDialog.trigger }, - }, - }, SidebarContainerProps: ({ actions, stores }: InjectedOrGenerated), NavBarContainerRevampProps: ({ actions, stores, }: InjectedOrGenerated), BannerContainerProps: ({ actions, stores }: InjectedOrGenerated), - UnmangleTxDialogContainerProps: ({ - stores, - actions, - }: InjectedOrGenerated), - WithdrawalTxDialogContainerProps: ({ - stores, - actions, - }: InjectedOrGenerated), - DeregisterDialogContainerProps: ({ - stores, - actions, - }: InjectedOrGenerated), }); } } -export default (withLayout(StakingPage): ComponentType); - -const WrapperCards = styled(Box)({ - display: 'flex', - gap: '40px', - justifyContent: 'space-between', - marginBottom: '40px', - height: '556px', -}); - -const RightCardsWrapper = styled(Box)({ - display: 'flex', - flex: '1 1 48.5%', - maxWidth: '48.5%', - flexDirection: 'column', - gap: '40px', -}); +export default StakingPage; \ No newline at end of file diff --git a/packages/yoroi-extension/app/containers/wallet/staking/StakingPageContent.js b/packages/yoroi-extension/app/containers/wallet/staking/StakingPageContent.js new file mode 100644 index 0000000000..b0a048408d --- /dev/null +++ b/packages/yoroi-extension/app/containers/wallet/staking/StakingPageContent.js @@ -0,0 +1,679 @@ +// @flow +import type { ComponentType, Node } from 'react'; +import type { $npm$ReactIntl$IntlFormat } from 'react-intl'; +import type { InjectedOrGenerated } from '../../../types/injectedPropsType'; +import type { LayoutComponentMap } from '../../../styles/context/layout'; +import type { ConfigType } from '../../../../config/config-types'; +import type { TxRequests } from '../../../stores/toplevel/TransactionsStore'; +import type { DelegationRequests, PoolMeta } from '../../../stores/toplevel/DelegationStore'; +import type { GeneratedData as UnmangleTxDialogContainerData } from '../../transfer/UnmangleTxDialogContainer'; +import type { GeneratedData as DeregisterDialogContainerData } from '../../transfer/DeregisterDialogContainer'; +import type { TokenInfoMap } from '../../../stores/toplevel/TokenInfoStore'; +import type { NetworkRow } from '../../../api/ada/lib/storage/database/primitives/tables'; +import type { UnitOfAccountSettingType } from '../../../types/unitOfAccountType'; +import type { AdaDelegationRequests } from '../../../stores/ada/AdaDelegationStore'; +import type { GeneratedData as WithdrawalTxDialogContainerData } from '../../transfer/WithdrawalTxDialogContainer'; +import type { PoolRequest } from '../../../api/jormungandr/lib/storage/bridge/delegationUtils'; +import type { TokenEntry } from '../../../api/common/lib/MultiToken'; +import type { + CurrentTimeRequests, + TimeCalcRequests, +} from '../../../stores/base/BaseCardanoTimeStore'; + +import { Component } from 'react'; +import { computed } from 'mobx'; +import { observer } from 'mobx-react'; +import { intlShape } from 'react-intl'; +import moment from 'moment'; + +import globalMessages from '../../../i18n/global-messages'; +import { PublicDeriver } from '../../../api/ada/lib/storage/models/PublicDeriver/index'; +import { withLayout } from '../../../styles/context/layout'; +import WalletEmptyBanner from '../WalletEmptyBanner'; +import BuySellDialog from '../../../components/buySell/BuySellDialog'; +import CardanoStakingPage from './CardanoStakingPage'; +import { Box, styled } from '@mui/system'; +import SummaryCard from '../../../components/wallet/staking/dashboard-revamp/SummaryCard'; +import EpochProgressWrapper from '../../../components/wallet/staking/dashboard-revamp/EpochProgressWrapper'; +import OverviewModal from '../../../components/wallet/staking/dashboard-revamp/OverviewDialog'; +import LocalizableError from '../../../i18n/LocalizableError'; +import { MultiToken } from '../../../api/common/lib/MultiToken'; +import { genLookupOrFail } from '../../../stores/stateless/tokenHelpers'; +import UnmangleTxDialogContainer from '../../transfer/UnmangleTxDialogContainer'; +import DeregisterDialogContainer from '../../transfer/DeregisterDialogContainer'; +import { calculateAndFormatValue } from '../../../utils/unit-of-account'; +import { + isCardanoHaskell, + isJormungandr, +} from '../../../api/ada/lib/storage/database/prepackaged/networks'; +import EpochProgressContainer from './EpochProgressContainer'; +import WithdrawalTxDialogContainer from '../../transfer/WithdrawalTxDialogContainer'; +import UndelegateDialog from '../../../components/wallet/staking/dashboard/UndelegateDialog'; +import { generateGraphData } from '../../../utils/graph'; +import { ApiOptions, getApiForNetwork } from '../../../api/common/utils'; +import RewardHistoryDialog from '../../../components/wallet/staking/dashboard-revamp/RewardHistoryDialog'; +import DelegatedStakePoolCard from '../../../components/wallet/staking/dashboard-revamp/DelegatedStakePoolCard'; + +export type GeneratedData = typeof StakingPageContent.prototype.generated; +// populated by ConfigWebpackPlugin +declare var CONFIG: ConfigType; +type Props = {| + ...InjectedOrGenerated, + actions: any, + stores: any, +|}; +type InjectedProps = {| + +renderLayoutComponent: LayoutComponentMap => Node, +|}; + +type AllProps = {| ...Props, ...InjectedProps |}; +@observer +class StakingPageContent extends Component { + static contextTypes: {| intl: $npm$ReactIntl$IntlFormat |} = { + intl: intlShape.isRequired, + }; + + onClose: void => void = () => { + this.generated.actions.dialogs.closeActiveDialog.trigger(); + }; + + _isRegistered: (PublicDeriver<>) => ?boolean = publicDeriver => { + if (!isCardanoHaskell(publicDeriver.getParent().getNetworkInfo())) { + return undefined; + } + const delegation = this.generated.stores.substores.ada.delegation; + const adaDelegationRequests = delegation.getDelegationRequests(publicDeriver); + if (adaDelegationRequests == null) return undefined; + return adaDelegationRequests.getRegistrationHistory.result?.current; + }; + + async componentDidMount() { + const timeStore = this.generated.stores.time; + const publicDeriver = this.generated.stores.wallets.selected; + if (publicDeriver == null) { + throw new Error(`${nameof(StakingPageContent)} no public deriver. Should never happen`); + } + const timeCalcRequests = timeStore.getTimeCalcRequests(publicDeriver); + await timeCalcRequests.requests.toAbsoluteSlot.execute().promise; + await timeCalcRequests.requests.toRealTime.execute().promise; + await timeCalcRequests.requests.currentEpochLength.execute().promise; + await timeCalcRequests.requests.currentSlotLength.execute().promise; + await timeCalcRequests.requests.timeSinceGenesis.execute().promise; + } + + getErrorInFetch: (PublicDeriver<>) => void | {| error: LocalizableError |} = publicDeriver => { + const delegationStore = this.generated.stores.delegation; + const delegationRequests = delegationStore.getDelegationRequests(publicDeriver); + if (delegationRequests == null) { + throw new Error(`${nameof(StakingPageContent)} opened for non-reward wallet`); + } + if (delegationRequests.error != null) { + return { error: delegationRequests.error }; + } + if (delegationRequests.getCurrentDelegation.result != null) { + const currentDelegation = delegationRequests.getCurrentDelegation.result; + const currEpochInfo = currentDelegation.currEpoch; + if (currEpochInfo == null) { + return undefined; + } + } + return undefined; + }; + + getEpochLengthInDays: (PublicDeriver<>) => ?number = publicDeriver => { + const timeStore = this.generated.stores.time; + const timeCalcRequests = timeStore.getTimeCalcRequests(publicDeriver); + const getEpochLength = timeCalcRequests.requests.currentEpochLength.result; + if (getEpochLength == null) return null; + + const getSlotLength = timeCalcRequests.requests.currentSlotLength.result; + if (getSlotLength == null) return null; + + const epochLengthInSeconds = getEpochLength() * getSlotLength(); + const epochLengthInDays = epochLengthInSeconds / (60 * 60 * 24); + return epochLengthInDays; + }; + + getUserSummary: ({| + delegationRequests: DelegationRequests, + publicDeriver: PublicDeriver<>, + errorIfPresent: void | {| error: LocalizableError |}, + |}) => Node = request => { + const { actions, stores } = this.generated; + + const showRewardAmount = + request.delegationRequests.getCurrentDelegation.wasExecuted && + request.delegationRequests.getDelegatedBalance.wasExecuted && + request.errorIfPresent == null; + + const defaultToken = request.publicDeriver.getParent().getDefaultToken(); + + const currentlyDelegating = + (request.delegationRequests.getCurrentDelegation.result?.currEpoch?.pools ?? []).length > 0; + + return ( + + actions.dialogs.open.trigger({ + dialog: OverviewModal, + }) + } + unitOfAccount={this.toUnitOfAccount} + getTokenInfo={genLookupOrFail(stores.tokenInfoStore.tokenInfo)} + shouldHideBalance={stores.profile.shouldHideBalance} + totalRewards={ + !showRewardAmount || request.delegationRequests.getDelegatedBalance.result == null + ? undefined + : request.delegationRequests.getDelegatedBalance.result.accountPart + } + totalDelegated={(() => { + if (!showRewardAmount) return undefined; + if (request.delegationRequests.getDelegatedBalance.result == null) return undefined; + + return currentlyDelegating + ? request.delegationRequests.getDelegatedBalance.result.utxoPart.joinAddCopy( + request.delegationRequests.getDelegatedBalance.result.accountPart + ) + : new MultiToken([], defaultToken); + })()} + epochLength={this.getEpochLengthInDays(request.publicDeriver)} + graphData={generateGraphData({ + delegationRequests: request.delegationRequests, + publicDeriver: request.publicDeriver, + currentEpoch: stores.time.getCurrentTimeRequests(request.publicDeriver).currentEpoch, + shouldHideBalance: stores.profile.shouldHideBalance, + getLocalPoolInfo: stores.delegation.getLocalPoolInfo, + tokenInfo: stores.tokenInfoStore.tokenInfo, + })} + onOpenRewardList={() => + actions.dialogs.open.trigger({ + dialog: RewardHistoryDialog, + }) + } + /> + ); + }; + + getStakePoolMeta: (PublicDeriver<>) => Node = publicDeriver => { + const delegationStore = this.generated.stores.delegation; + const delegationRequests = delegationStore.getDelegationRequests(publicDeriver); + if (delegationRequests == null) { + throw new Error(`${nameof(StakingPageContent)} opened for non-reward wallet`); + } + if ( + !delegationRequests.getCurrentDelegation.wasExecuted || + delegationRequests.getCurrentDelegation.isExecuting || + delegationRequests.getCurrentDelegation.result == null + ) { + return null; + } + if (delegationRequests.getCurrentDelegation.result.currEpoch == null) { + return null; + } + const currentPools = delegationRequests.getCurrentDelegation.result.currEpoch.pools; + const currentPage = this.generated.stores.delegation.selectedPage; + + const currentPool = currentPools[0][currentPage]; + const meta = this.generated.stores.delegation.getLocalPoolInfo( + publicDeriver.getParent().getNetworkInfo(), + String(currentPool) + ); + if (meta == null) { + // server hasn't returned information about the stake pool yet + return null; + } + const { intl } = this.context; + const name = meta.info?.name ?? intl.formatMessage(globalMessages.unknownPoolLabel); + // TODO: remove placeholders + const delegatedPool = { + id: String(currentPool), + name, + roa: '5.1', + poolSize: 2560000, + share: '0.3', + websiteUrl: meta.info?.homepage, + ticker: meta.info?.ticker, + }; + + // TODO: implement this eventually + // const stakePoolMeta = { + // avatar: '', + // websiteUrl: '', + // roa: ' 5.08%', + // socialLinks: { + // fb: '', + // tw: '', + // }, + // }; + + // don't support undelegation for ratio stake since it's a less intuitive UX + const undelegate = + currentPools.length === 1 && isJormungandr(publicDeriver.getParent().getNetworkInfo()) + ? async () => { + this.generated.actions.dialogs.open.trigger({ dialog: UndelegateDialog }); + const delegationTransaction = this.generated.actions.jormungandr.delegationTransaction; + await delegationTransaction.createTransaction.trigger( + { + publicDeriver, + poolRequest: undefined, + } + ); + } + : undefined; + + return ( + + ); + }; + + getEpochProgress: (PublicDeriver<>) => Node | void = publicDeriver => { + const timeStore = this.generated.stores.time; + const timeCalcRequests = timeStore.getTimeCalcRequests(publicDeriver); + const currTimeRequests = timeStore.getCurrentTimeRequests(publicDeriver); + const toAbsoluteSlot = timeCalcRequests.requests.toAbsoluteSlot.result; + if (toAbsoluteSlot == null) return undefined; + const toRealTime = timeCalcRequests.requests.toRealTime.result; + if (toRealTime == null) return undefined; + const timeSinceGenesis = timeCalcRequests.requests.timeSinceGenesis.result; + if (timeSinceGenesis == null) return undefined; + const getEpochLength = timeCalcRequests.requests.currentEpochLength.result; + if (getEpochLength == null) return undefined; + const currentEpoch = currTimeRequests.currentEpoch; + const epochLength = getEpochLength(); + + const getDateFromEpoch = epoch => { + const epochTime = toRealTime({ + absoluteSlotNum: toAbsoluteSlot({ + epoch, + // in Jormungandr, rewards were distributed at the start of the epoch + // in Haskell, rewards are calculated at the start of the epoch but distributed at the end + slot: isJormungandr(publicDeriver.getParent().getNetworkInfo()) ? 0 : getEpochLength(), + }), + timeSinceGenesisFunc: timeSinceGenesis, + }); + const epochMoment = moment(epochTime).format('lll'); + return epochMoment; + }; + + const endEpochDate = getDateFromEpoch(currentEpoch); + const previousEpochDate = getDateFromEpoch(currentEpoch - 1); + + return ( + + ); + }; + + toUnitOfAccount: TokenEntry => void | {| currency: string, amount: string |} = entry => { + const { stores } = this.generated; + const tokenRow = stores.tokenInfoStore.tokenInfo + .get(entry.networkId.toString()) + ?.get(entry.identifier); + if (tokenRow == null) return undefined; + + if (!stores.profile.unitOfAccount.enabled) return undefined; + const currency = stores.profile.unitOfAccount.currency; + + const shiftedAmount = entry.amount.shiftedBy(-tokenRow.Metadata.numberOfDecimals); + const ticker = tokenRow.Metadata.ticker; + if (ticker == null) { + throw new Error('unexpected main token type'); + } + const coinPrice = stores.coinPriceStore.getCurrentPrice(ticker, currency); + if (coinPrice == null) return { currency, amount: '-' }; + return { + currency, + amount: calculateAndFormatValue(shiftedAmount, coinPrice), + }; + }; + + render(): Node { + const publicDeriver = this.generated.stores.wallets.selected; + if (publicDeriver == null) { + throw new Error(`${nameof(StakingPageContent)} no public deriver. Should never happen`); + } + const { stores } = this.generated; + const { uiDialogs, delegation: delegationStore } = stores; + const delegationRequests = delegationStore.getDelegationRequests(publicDeriver); + if (delegationRequests == null) { + throw new Error(`${nameof(StakingPageContent)} opened for non-reward wallet`); + } + const txRequests = stores.transactions.getTxRequests(publicDeriver); + const balance = txRequests.requests.getBalanceRequest.result; + const isWalletWithNoFunds = balance != null && balance.getDefaultEntry().amount.isZero(); + + const errorIfPresent = this.getErrorInFetch(publicDeriver); + + const showRewardAmount = + delegationRequests.getCurrentDelegation.wasExecuted && + delegationRequests.getDelegatedBalance.wasExecuted && + errorIfPresent == null; + + const delegationHistory = delegationRequests.getCurrentDelegation.result?.fullHistory; + const hasNeverDelegated = delegationHistory != null && delegationHistory.length === 0; + + return ( + + {isWalletWithNoFunds ? ( + + this.generated.actions.dialogs.open.trigger({ dialog: BuySellDialog }) + } + /> + ) : null} + {hasNeverDelegated ? null : ( + + {this.getUserSummary({ delegationRequests, publicDeriver, errorIfPresent })} + + {errorIfPresent} + {!errorIfPresent && this.getStakePoolMeta(publicDeriver)} + {!errorIfPresent && this.getEpochProgress(publicDeriver)} + + + )} + + {uiDialogs.isOpen(OverviewModal) ? ( + { + this.generated.actions.dialogs.open.trigger({ + dialog: DeregisterDialogContainer, + }); + } + : undefined + } + /> + ) : null} + {uiDialogs.isOpen(DeregisterDialogContainer) ? ( + { + // note: purposely don't await + // since the next dialog will properly render the spinner + const { delegationTransaction } = this.generated.actions.ada; + delegationTransaction.createWithdrawalTxForWallet.trigger({ publicDeriver }); + this.generated.actions.dialogs.open.trigger({ + dialog: WithdrawalTxDialogContainer, + }); + }} + /> + ) : null} + {uiDialogs.isOpen(UnmangleTxDialogContainer) ? ( + + ) : null} + {uiDialogs.isOpen(WithdrawalTxDialogContainer) ? ( + { + this.generated.actions.ada.delegationTransaction.reset.trigger({ + justTransaction: false, + }); + this.generated.actions.dialogs.closeActiveDialog.trigger(); + }} + /> + ) : null} + {uiDialogs.isOpen(RewardHistoryDialog) ? ( + + ) : null} + + ); + } + + @computed get generated(): {| + DeregisterDialogContainerProps: InjectedOrGenerated, + UnmangleTxDialogContainerProps: InjectedOrGenerated, + WithdrawalTxDialogContainerProps: InjectedOrGenerated, + actions: {| + ada: {| + delegationTransaction: {| + reset: {| trigger: (params: {| justTransaction: boolean |}) => void |}, + createWithdrawalTxForWallet: {| + trigger: (params: {| publicDeriver: PublicDeriver<> |}) => Promise, + |}, + |}, + |}, + jormungandr: {| + delegationTransaction: {| + createTransaction: {| + trigger: (params: {| + poolRequest: PoolRequest, + publicDeriver: PublicDeriver<>, + |}) => Promise, + |}, + |}, + |}, + dialogs: {| + open: {| + trigger: (params: {| + dialog: any, + params?: any, + |}) => void, + |}, + closeActiveDialog: {| + trigger: (params: void) => void, + |}, + |}, + transactions: {| + closeWalletEmptyBanner: {| + trigger: (params: void) => void, + |}, + closeDelegationBanner: {| + trigger: (params: void) => void, + |}, + |}, + |}, + stores: {| + uiDialogs: {| + getParam: (number | string) => T, + isOpen: any => boolean, + |}, + coinPriceStore: {| + getCurrentPrice: (from: string, to: string) => ?string, + |}, + substores: {| + ada: {| + delegation: {| + getDelegationRequests: (PublicDeriver<>) => void | AdaDelegationRequests, + |}, + |}, + |}, + delegation: {| + selectedPage: number, + getLocalPoolInfo: ($ReadOnly, string) => void | PoolMeta, + getDelegationRequests: (PublicDeriver<>) => void | DelegationRequests, + |}, + profile: {| + shouldHideBalance: boolean, + unitOfAccount: UnitOfAccountSettingType, + |}, + tokenInfoStore: {| + tokenInfo: TokenInfoMap, + |}, + wallets: {| selected: null | PublicDeriver<> |}, + transactions: {| + showWalletEmptyBanner: boolean, + showDelegationBanner: boolean, + getTxRequests: (PublicDeriver<>) => TxRequests, + |}, + time: {| + getCurrentTimeRequests: (PublicDeriver<>) => CurrentTimeRequests, + getTimeCalcRequests: (PublicDeriver<>) => TimeCalcRequests, + |}, + |}, + |} { + if (this.props.generated !== undefined) { + return this.props.generated; + } + if (this.props.stores == null || this.props.actions == null) { + throw new Error(`${nameof(StakingPageContent)} no way to generated props`); + } + const { stores, actions } = this.props; + + const selected = stores.wallets.selected; + if (selected == null) { + throw new Error(`${nameof(EpochProgressContainer)} no wallet selected`); + } + const api = getApiForNetwork(selected.getParent().getNetworkInfo()); + const time = (() => { + if (api === ApiOptions.ada) { + return { + getTimeCalcRequests: stores.substores.ada.time.getTimeCalcRequests, + getCurrentTimeRequests: stores.substores.ada.time.getCurrentTimeRequests, + }; + } + if (api === ApiOptions.jormungandr) { + return { + getTimeCalcRequests: stores.substores.jormungandr.time.getTimeCalcRequests, + getCurrentTimeRequests: stores.substores.jormungandr.time.getCurrentTimeRequests, + }; + } + return { + getTimeCalcRequests: (undefined: any), + getCurrentTimeRequests: () => { + throw new Error(`${nameof(StakingPageContent)} api not supported`); + }, + }; + })(); + return Object.freeze({ + stores: { + wallets: { + selected: stores.wallets.selected, + }, + profile: { + shouldHideBalance: stores.profile.shouldHideBalance, + unitOfAccount: stores.profile.unitOfAccount, + }, + delegation: { + selectedPage: stores.delegation.selectedPage, + getLocalPoolInfo: stores.delegation.getLocalPoolInfo, + getDelegationRequests: stores.delegation.getDelegationRequests, + }, + uiDialogs: { + isOpen: stores.uiDialogs.isOpen, + getParam: stores.uiDialogs.getParam, + }, + transactions: { + showWalletEmptyBanner: stores.transactions.showWalletEmptyBanner, + showDelegationBanner: stores.transactions.showDelegationBanner, + getTxRequests: stores.transactions.getTxRequests, + }, + tokenInfoStore: { + tokenInfo: stores.tokenInfoStore.tokenInfo, + }, + coinPriceStore: { + getCurrentPrice: stores.coinPriceStore.getCurrentPrice, + }, + substores: { + ada: { + delegation: { + getDelegationRequests: stores.substores.ada.delegation.getDelegationRequests, + }, + }, + }, + time, + }, + actions: { + ada: { + delegationTransaction: { + reset: { + trigger: actions.ada.delegationTransaction.reset.trigger, + }, + createWithdrawalTxForWallet: { + trigger: actions.ada.delegationTransaction.createWithdrawalTxForWallet.trigger, + }, + }, + }, + jormungandr: { + delegationTransaction: { + createTransaction: { + trigger: actions.jormungandr.delegationTransaction.createTransaction.trigger, + }, + }, + }, + transactions: { + closeWalletEmptyBanner: { + trigger: actions.transactions.closeWalletEmptyBanner.trigger, + }, + closeDelegationBanner: { + trigger: actions.transactions.closeDelegationBanner.trigger, + }, + }, + dialogs: { + open: { + trigger: actions.dialogs.open.trigger, + }, + closeActiveDialog: { trigger: actions.dialogs.closeActiveDialog.trigger }, + }, + }, + UnmangleTxDialogContainerProps: ({ + stores, + actions, + }: InjectedOrGenerated), + WithdrawalTxDialogContainerProps: ({ + stores, + actions, + }: InjectedOrGenerated), + DeregisterDialogContainerProps: ({ + stores, + actions, + }: InjectedOrGenerated), + }); + } +} +export default (withLayout(StakingPageContent): ComponentType); + +const WrapperCards = styled(Box)({ + display: 'flex', + gap: '40px', + justifyContent: 'space-between', + marginBottom: '40px', + height: '556px', +}); + +const RightCardsWrapper = styled(Box)({ + display: 'flex', + flex: '1 1 48.5%', + maxWidth: '48.5%', + flexDirection: 'column', + gap: '40px', +}); + From 5c62c4f382acfddf30503e3233c96b1c9bc8bfda Mon Sep 17 00:00:00 2001 From: Thomas Bereczky Date: Tue, 24 Jan 2023 15:12:24 +0100 Subject: [PATCH 134/172] Sonarqube workflow --- .github/workflows/sonarqube.yml | 26 ++++++++++++++++++++++++++ sonar-project.properties | 5 +++++ 2 files changed, 31 insertions(+) create mode 100644 .github/workflows/sonarqube.yml create mode 100644 sonar-project.properties diff --git a/.github/workflows/sonarqube.yml b/.github/workflows/sonarqube.yml new file mode 100644 index 0000000000..8b10a65e52 --- /dev/null +++ b/.github/workflows/sonarqube.yml @@ -0,0 +1,26 @@ +name: SonarQube Checks + +on: + # Trigger analysis when pushing to your main branches, and when creating a pull request. + push: + branches: + - main + - master + - develop + - 'releases/**' + pull_request: + types: [opened, synchronize, reopened] + +jobs: + sonarqube: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + with: + # Disabling shallow clone is recommended for improving relevancy of reporting + fetch-depth: 0 + - name: SonarQube Scan + uses: sonarsource/sonarqube-scan-action@master + env: + SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }} + SONAR_HOST_URL: ${{ secrets.SONAR_HOST_URL }} diff --git a/sonar-project.properties b/sonar-project.properties new file mode 100644 index 0000000000..a86c5f48d5 --- /dev/null +++ b/sonar-project.properties @@ -0,0 +1,5 @@ +sonar.projectKey=Emurgo_yoroi-frontend_AYXkHIRHWigj-SXq5ncX + +# relative paths to source directories. More details and properties are described +# in https://docs.sonarqube.org/latest/project-administration/narrowing-the-focus/ +sonar.sources=. From 02d2fc42e72dca0f38cb1fb02b5dbe24766312d1 Mon Sep 17 00:00:00 2001 From: Ahmed Ibrahim Date: Wed, 25 Jan 2023 15:59:11 +0200 Subject: [PATCH 135/172] Add tx receiver --- .../yoroi-connector/example-cardano/index.js | 79 +++++++++++-------- 1 file changed, 44 insertions(+), 35 deletions(-) diff --git a/packages/yoroi-connector/example-cardano/index.js b/packages/yoroi-connector/example-cardano/index.js index 373b87d69c..b0bb94396a 100644 --- a/packages/yoroi-connector/example-cardano/index.js +++ b/packages/yoroi-connector/example-cardano/index.js @@ -5,30 +5,33 @@ import { getTtl } from "./utils"; import { Bech32Prefix } from "../../yoroi-extension/app/config/stringConfig"; import { bytesToHex, hexToBytes } from "./coreUtils"; -const cardanoAccessBtnRow = document.querySelector("#request-button-row"); -const cardanoAuthCheck = document.querySelector("#check-identification"); -const cardanoAccessBtn = document.querySelector("#request-access"); -const connectionStatus = document.querySelector("#connection-status"); -const walletPlateSpan = document.querySelector("#wallet-plate"); -const walletIconSpan = document.querySelector("#wallet-icon"); -const getUnUsedAddresses = document.querySelector("#get-unused-addresses"); -const getUsedAddresses = document.querySelector("#get-used-addresses"); -const getChangeAddress = document.querySelector("#get-change-address"); -const getRewardAddresses = document.querySelector("#get-reward-addresses"); -const getAccountBalance = document.querySelector("#get-balance"); -const isEnabledBtn = document.querySelector("#is-enabled"); -const getUtxos = document.querySelector("#get-utxos"); -const submitTx = document.querySelector("#submit-tx"); -const signTx = document.querySelector("#sign-tx"); -const showUtxos = document.querySelector("#show-utxos"); -const createTx = document.querySelector("#create-tx"); -const getCollateralUtxos = document.querySelector("#get-collateral-utxos"); -const signData = document.querySelector("#sign-data"); -const alertEl = document.querySelector("#alert"); -const spinner = document.querySelector("#spinner"); -const utxosContainer = document.querySelector("#utxos"); -const getNFTs = document.getElementById("nfts"); -const getNetworkId = document.getElementById("get-network-id"); +const get = (selector) => document.querySelector(selector); +const getAll = (selector) => document.querySelectorAll(selector); + +const cardanoAccessBtnRow = get("#request-button-row"); +const cardanoAuthCheck = get("#check-identification"); +const cardanoAccessBtn = get("#request-access"); +const connectionStatus = get("#connection-status"); +const walletPlateSpan = get("#wallet-plate"); +const walletIconSpan = get("#wallet-icon"); +const getUnUsedAddresses = get("#get-unused-addresses"); +const getUsedAddresses = get("#get-used-addresses"); +const getChangeAddress = get("#get-change-address"); +const getRewardAddresses = get("#get-reward-addresses"); +const getAccountBalance = get("#get-balance"); +const isEnabledBtn = get("#is-enabled"); +const getUtxos = get("#get-utxos"); +const submitTx = get("#submit-tx"); +const signTx = get("#sign-tx"); +const showUtxos = get("#show-utxos"); +const createTx = get("#create-tx"); +const getCollateralUtxos = get("#get-collateral-utxos"); +const signData = get("#sign-data"); +const alertEl = get("#alert"); +const spinner = get("#spinner"); +const utxosContainer = get("#utxos"); +const getNFTs = get("#nfts"); +const getNetworkId = get("#get-network-id"); let accessGranted = false; let cardanoApi; @@ -588,12 +591,12 @@ showUtxos.addEventListener("click", () => { function alertError(text) { toggleSpinner("hide"); - alertEl.className = "alert alert-danger overflow-scroll"; + alertEl.className = "alert alert-danger overflow-auto"; alertEl.innerHTML = text; } function alertSuccess(text) { - alertEl.className = "alert alert-success overflow-scroll"; + alertEl.className = "alert alert-success overflow-auto"; alertEl.innerHTML = text; } @@ -640,17 +643,24 @@ function renderUtxo() { let utxosHTML = ""; for (let idx in utxos) { const utxo = utxos[idx]; + const amountInADA = Number(utxo.amount) / 1000000; + const numOfAssets = utxo.assets.length; + utxosHTML += `
  • -

    ${utxo.utxo_id.slice(0, 50)}

    - ${utxo.amount} +

    ${utxo.utxo_id.slice(0, 25)}

    +
    + ${numOfAssets ? `${utxo.assets.length} Assets` : ''} + ${amountInADA} ADA +
  • `; } utxosHTML += ` + `; utxosContainer.innerHTML = utxosHTML; @@ -662,14 +672,12 @@ function renderUtxo() { "mb-5" ); // Add select utxo handler for each list item - document.querySelectorAll(".utxo-item").forEach((el) => { + getAll(".utxo-item").forEach((el) => { el.addEventListener("click", selectUtxo); }); // Add event handler for create tx button - document - .querySelector("#create-tx") - .addEventListener("click", createTxHandler); + get("#create-tx").addEventListener("click", createTxHandler); } function createTxHandler(e) { @@ -692,7 +700,7 @@ function createTxHandler(e) { const selectedUtxo = utxos[selectedUtxoIdx]; if (!selectedUtxo) { - alertError("Failed to select a random utxo from the available list!"); + alertError("No utxo selected"); return; } @@ -921,10 +929,11 @@ function createTxHandler(e) { if (utxoWithAssets) { const asset = utxoWithAssets.assets[0]; + const receiver = get('#create-tx-receiver').value || selectedUtxo.receiver; console.log("[createTx] Including asset:", asset); txReq.includeTargets.push({ // do not specify value, the connector will use minimum value - address: selectedUtxo.receiver, + address: receiver, assets: { [asset.assetId]: "1", }, @@ -1006,7 +1015,7 @@ signData.addEventListener("click", () => { address = addressToCbor(address); } - const payload = document.querySelector("#sign-data-payload").value; + const payload = get("#sign-data-payload").value; let payloadHex; if (payload.startsWith("0x")) { payloadHex = Buffer.from(payload.replace("^0x", ""), "hex").toString("hex"); From eae1fdc6dc712896ed79bb7f5604ff1ccba4dc20 Mon Sep 17 00:00:00 2001 From: Ahmed Ibrahim Date: Wed, 25 Jan 2023 16:21:58 +0200 Subject: [PATCH 136/172] Send selected utxo to the receiver address --- packages/yoroi-connector/example-cardano/index.js | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/yoroi-connector/example-cardano/index.js b/packages/yoroi-connector/example-cardano/index.js index b0bb94396a..3bf54f2c84 100644 --- a/packages/yoroi-connector/example-cardano/index.js +++ b/packages/yoroi-connector/example-cardano/index.js @@ -750,9 +750,10 @@ function createTxHandler(e) { expectedPolicyId, }); + let receiver = get('#create-tx-receiver').value || selectedUtxo.receiver; const outputHex = bytesToHex( CardanoWasm.TransactionOutput.new( - CardanoWasm.Address.from_bech32(selectedUtxo.receiver), + CardanoWasm.Address.from_bech32(receiver), CardanoWasm.Value.new(CardanoWasm.BigNum.from_str("1000000")) ).to_bytes() ); @@ -761,7 +762,7 @@ function createTxHandler(e) { const includeOutputs = []; const includeTargets = []; - let targetAddress = selectedUtxo.receiver; + let targetAddress = receiver; let targetDataHash = null; /****** FLAGS ******/ @@ -929,7 +930,6 @@ function createTxHandler(e) { if (utxoWithAssets) { const asset = utxoWithAssets.assets[0]; - const receiver = get('#create-tx-receiver').value || selectedUtxo.receiver; console.log("[createTx] Including asset:", asset); txReq.includeTargets.push({ // do not specify value, the connector will use minimum value From 07a1843a14825d77f23be27ca1843d45a38a3997 Mon Sep 17 00:00:00 2001 From: Ruslan Dudin Date: Fri, 27 Jan 2023 21:51:38 +0300 Subject: [PATCH 137/172] Update packages/yoroi-extension/app/api/ada/lib/storage/database/prepackaged/networks.js --- .../app/api/ada/lib/storage/database/prepackaged/networks.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/yoroi-extension/app/api/ada/lib/storage/database/prepackaged/networks.js b/packages/yoroi-extension/app/api/ada/lib/storage/database/prepackaged/networks.js index 3c38ce1599..015ab85ac4 100644 --- a/packages/yoroi-extension/app/api/ada/lib/storage/database/prepackaged/networks.js +++ b/packages/yoroi-extension/app/api/ada/lib/storage/database/prepackaged/networks.js @@ -241,7 +241,7 @@ export const networks = Object.freeze({ Fork: CardanoForks.Haskell, }: NetworkRow), CardanoPreviewTestnet: ({ - NetworkId: 3_00, + NetworkId: 3_50, NetworkName: 'Cardano Preview Testnet', Backend: { BackendService: environment.isTest() From e2c7a8cb08550532e89f971510684ec139d5f7c4 Mon Sep 17 00:00:00 2001 From: Ahmed Ibrahim Date: Tue, 9 Aug 2022 14:25:36 +0200 Subject: [PATCH 138/172] Load zendesk into an iframe --- .../app/components/widgets/Support.js | 81 ++++++++++++------- 1 file changed, 53 insertions(+), 28 deletions(-) diff --git a/packages/yoroi-extension/app/components/widgets/Support.js b/packages/yoroi-extension/app/components/widgets/Support.js index 3d9ad333e2..9b17bad8ae 100644 --- a/packages/yoroi-extension/app/components/widgets/Support.js +++ b/packages/yoroi-extension/app/components/widgets/Support.js @@ -3,51 +3,76 @@ import { Component } from 'react'; import type { Node } from 'react'; import { ReactComponent as SupportIcon } from '../../assets/images/support.inline.svg'; import { IconButton } from '@mui/material'; +import { Box } from '@mui/system'; +import environment from '../../environment'; type Props = {||} +type State = {| + open: boolean, +|} +export default class Support extends Component { -export default class Support extends Component { + state: State = { + open: false, + } + + messageHandler: any => void = (event) => { + if (event.origin === 'null') { + return + } - loadScript(src: string, id: string): void { - const script = document.createElement('script') - script.src = src - script.id = id - document.body?.appendChild(script) + const eventType = event.data; + if (eventType === 'close') { + this.setState({ open: false }) + } } componentDidMount() { - this.loadScript('https://static.zdassets.com/ekr/snippet.js?key=68b95d72-6354-4343-8a64-427979a6f5d6', 'ze-snippet'); - - const interval = setInterval(()=>{ - if (typeof window.zE !== 'undefined' && typeof window.zE.hide === 'function') { - window.zE.hide() - if (interval) { - clearInterval(interval) - } - } - }, 500); + window.addEventListener('message', this.messageHandler, false); + } + + componentWillUnmount() { + window.removeEventListener('message', this.messageHandler); } - openChatBoxSupport(){ - if (typeof window.zE !== 'undefined') { - window.zE.activate() - } + getUrl(): string | null { + if (!environment.userAgentInfo.isExtension()) return null; + const agent = environment.userAgentInfo.isFirefox() ? 'firefox' : 'chrome' + return `https://emurgo.github.io/yoroi-support/?source=${agent}&extensionId=${window.location.hostname}`; } render(): Node { - return ( + const { open } = this.state; + + const url = this.getUrl(); + if (url === null) return null; + + return ( + + {open === false && this.setState({ open: true })} > - - ) + } +