chore(test fixes): use api token in test (#2316)

* chore: clean jsonrpc wallet api methods - remove permission methods

* chore: clean jsonrpc wallet api methods - remove permission methods

* chore: clean jsonrpc wallet api methods - remove permission methods

* chore: clean jsonrpc wallet api methods - fix failing unit test

* chore: update vega_version

* chore: update vega to v0.63.0 in workflows

* chore: mock api-token in connect wallet response

* chore: fix token env in workflow

* chore: remove dummy wallet leftovers

* chore: fix asset tests

* chore: fix remaining explorer tests

* chore: increase tx timeout

* chore: remove smoke test temporarily

* chore: remove other governance smoke test

* chore: remove smoke staking test

* chore: move validator tests to regression

* chore: revert regression change because they are also running

* chore: move vega wallet tests to slow

* chore: skip tests instead

Co-authored-by: maciek <maciek@vegaprotocol.io>
Co-authored-by: Rado <szpiechrados@gmail.com>
This commit is contained in:
Joe Tsang 2022-12-05 16:51:53 +00:00 committed by GitHub
parent 8697561ed6
commit 777d330f8e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
41 changed files with 290 additions and 347 deletions

View File

@ -15,14 +15,3 @@ runs:
run: | run: |
wget 'https://github.com/vegaprotocol/vega/releases/download/${{ inputs.version }}/vega-linux-amd64.zip' -q wget 'https://github.com/vegaprotocol/vega/releases/download/${{ inputs.version }}/vega-linux-amd64.zip' -q
unzip vega-linux-amd64.zip -d ${{ inputs.gobin }} unzip vega-linux-amd64.zip -d ${{ inputs.gobin }}
- name: Checkout vegawallet-dummy
uses: actions/checkout@v3
with:
repository: 'vegaprotocol/vegawallet-dummy'
path: './dummy'
- name: Install vegawallet-dummy binaries
shell: bash
run: go install
working-directory: ./dummy

View File

@ -1,6 +1,10 @@
inputs: inputs:
passphrase: passphrase:
description: 'Wallet password' description: 'Wallet password'
outputs:
token:
description: 'api-token of wallet'
value: ${{ steps.generate-api-token.outputs.api-token }}
runs: runs:
using: 'composite' using: 'composite'
steps: steps:
@ -20,6 +24,15 @@ runs:
shell: bash shell: bash
run: vega wallet network import --force --from-file ./frontend-monorepo/vegacapsule/wallet-config.toml --home ~/.vegacapsule/testnet/wallet run: vega wallet network import --force --from-file ./frontend-monorepo/vegacapsule/wallet-config.toml --home ~/.vegacapsule/testnet/wallet
- name: Init api-token
shell: bash
run: vega wallet api-token init --home ~/.vegacapsule/testnet/wallet --passphrase-file passphrase
- name: Generate api-token
id: generate-api-token
shell: bash
run: echo api-token=$(vega wallet api-token generate --wallet-name capsule_wallet --tokens-passphrase-file passphrase --wallet-passphrase-file passphrase --home ~/.vegacapsule/testnet/wallet | grep -Eo '[a-zA-Z0-9]{64}') >> $GITHUB_OUTPUT
- name: Start service using capsule network - name: Start service using capsule network
shell: bash shell: bash
run: vegawallet-dummy service run --network DV --wallet capsule_wallet --passphrase-file ./passphrase --home ~/.vegacapsule/testnet/wallet & run: vega wallet service run -n DV --load-tokens --tokens-passphrase-file passphrase --no-version-check --automatic-consent --home ~/.vegacapsule/testnet/wallet &

View File

@ -3,6 +3,10 @@ inputs:
description: 'Recovery phrase' description: 'Recovery phrase'
passphrase: passphrase:
description: 'Wallet password' description: 'Wallet password'
outputs:
token:
description: 'api-token of wallet'
value: ${{ steps.generate-api-token.outputs.api-token }}
runs: runs:
using: 'composite' using: 'composite'
steps: steps:
@ -30,6 +34,15 @@ runs:
shell: bash shell: bash
run: vega wallet network import --from-url="https://raw.githubusercontent.com/vegaprotocol/networks-internal/main/stagnet3/vegawallet-stagnet3.toml" --force --home ~/.vegacapsule/testnet/wallet run: vega wallet network import --from-url="https://raw.githubusercontent.com/vegaprotocol/networks-internal/main/stagnet3/vegawallet-stagnet3.toml" --force --home ~/.vegacapsule/testnet/wallet
- name: Init api-token
shell: bash
run: vega wallet api-token init --home ~/.vegacapsule/testnet/wallet --passphrase-file passphrase
- name: Generate api-token
id: generate-api-token
shell: bash
run: echo api-token=$(vega wallet api-token generate --wallet-name UI_Trading_Test --tokens-passphrase-file passphrase --wallet-passphrase-file passphrase --home ~/.vegacapsule/testnet/wallet | grep -Eo '[a-zA-Z0-9]{64}') >> $GITHUB_OUTPUT
- name: Start service using stagnet3 network - name: Start service using stagnet3 network
shell: bash shell: bash
run: vegawallet-dummy service run --network stagnet3 --wallet UI_Trading_Test --passphrase-file ./passphrase --home ~/.vegacapsule/testnet/wallet & run: vega wallet service run -n stagnet3 --load-tokens --tokens-passphrase-file passphrase --no-version-check --automatic-consent --home ~/.vegacapsule/testnet/wallet &

View File

@ -28,7 +28,7 @@ on:
default: false default: false
env: env:
GOBIN: /home/runner/go/bin GOBIN: /home/runner/go/bin
VEGA_VERSION: 'v0.62.1' VEGA_VERSION: 'v0.63.1'
jobs: jobs:
manual: manual:

View File

@ -13,7 +13,7 @@ jobs:
secrets: inherit secrets: inherit
with: with:
project: '[console-lite-e2e, explorer-e2e, liquidity-provision-dashboard-e2e, stats-e2e, token-e2e, trading-e2e]' project: '[console-lite-e2e, explorer-e2e, liquidity-provision-dashboard-e2e, stats-e2e, token-e2e, trading-e2e]'
vega-version: 'v0.62.1' vega-version: 'v0.63.1'
gobin: /home/runner/go/bin gobin: /home/runner/go/bin
tags: --env.grepTags '[ @smoke, @regression, @slow ]' tags: --env.grepTags '[ @smoke, @regression, @slow ]'
night-run: true night-run: true

View File

@ -14,7 +14,7 @@ on:
env: env:
GOBIN: /home/runner/go/bin GOBIN: /home/runner/go/bin
VEGA_VERSION: 'v0.62.1' VEGA_VERSION: 'v0.63.1'
jobs: jobs:
pr: pr:

View File

@ -66,6 +66,7 @@ jobs:
###### ######
- name: Set up Vegawallet - name: Set up Vegawallet
id: setup-vega
uses: ./frontend-monorepo/.github/actions/setup-vegawallet uses: ./frontend-monorepo/.github/actions/setup-vegawallet
with: with:
recovery: ${{ secrets.TRADING_TEST_VEGA_WALLET_RECOVERY }} recovery: ${{ secrets.TRADING_TEST_VEGA_WALLET_RECOVERY }}
@ -83,3 +84,4 @@ jobs:
CYPRESS_TRADING_TEST_VEGA_WALLET_PASSPHRASE: ${{ secrets.CYPRESS_TRADING_TEST_VEGA_WALLET_PASSPHRASE }} CYPRESS_TRADING_TEST_VEGA_WALLET_PASSPHRASE: ${{ secrets.CYPRESS_TRADING_TEST_VEGA_WALLET_PASSPHRASE }}
CYPRESS_SLACK_WEBHOOK: ${{ secrets.CYPRESS_SLACK_WEBHOOK }} CYPRESS_SLACK_WEBHOOK: ${{ secrets.CYPRESS_SLACK_WEBHOOK }}
CYPRESS_ETH_WALLET_MNEMONIC: ${{ secrets.CYPRESS_ETH_WALLET_MNEMONIC }} CYPRESS_ETH_WALLET_MNEMONIC: ${{ secrets.CYPRESS_ETH_WALLET_MNEMONIC }}
CYPRESS_VEGA_WALLET_API_TOKEN: ${{ steps.setup-vega.outputs.token }}

View File

@ -76,6 +76,7 @@ jobs:
###### ######
- name: Set up Vegawallet for docker - name: Set up Vegawallet for docker
id: setup-vega
uses: ./frontend-monorepo/.github/actions/setup-vegawallet-docker uses: ./frontend-monorepo/.github/actions/setup-vegawallet-docker
with: with:
passphrase: ${{ secrets.CYPRESS_TRADING_TEST_VEGA_WALLET_PASSPHRASE }} passphrase: ${{ secrets.CYPRESS_TRADING_TEST_VEGA_WALLET_PASSPHRASE }}
@ -97,6 +98,7 @@ jobs:
CYPRESS_SLACK_WEBHOOK: ${{ secrets.CYPRESS_SLACK_WEBHOOK }} CYPRESS_SLACK_WEBHOOK: ${{ secrets.CYPRESS_SLACK_WEBHOOK }}
CYPRESS_ETH_WALLET_MNEMONIC: ${{ secrets.CYPRESS_ETH_WALLET_MNEMONIC }} CYPRESS_ETH_WALLET_MNEMONIC: ${{ secrets.CYPRESS_ETH_WALLET_MNEMONIC }}
CYPRESS_NIGHTLY_RUN: ${{ inputs.night-run }} CYPRESS_NIGHTLY_RUN: ${{ inputs.night-run }}
CYPRESS_VEGA_WALLET_API_TOKEN: ${{ steps.setup-vega.outputs.token }}
###### ######
## Upload logs ## Upload logs

View File

@ -72,6 +72,7 @@ jobs:
###### ######
- name: Set up Vegawallet for docker - name: Set up Vegawallet for docker
id: setup-vega
uses: ./frontend-monorepo/.github/actions/setup-vegawallet-docker uses: ./frontend-monorepo/.github/actions/setup-vegawallet-docker
with: with:
passphrase: ${{ secrets.CYPRESS_TRADING_TEST_VEGA_WALLET_PASSPHRASE }} passphrase: ${{ secrets.CYPRESS_TRADING_TEST_VEGA_WALLET_PASSPHRASE }}
@ -92,6 +93,7 @@ jobs:
CYPRESS_TRADING_TEST_VEGA_WALLET_PASSPHRASE: ${{ secrets.CYPRESS_TRADING_TEST_VEGA_WALLET_PASSPHRASE }} CYPRESS_TRADING_TEST_VEGA_WALLET_PASSPHRASE: ${{ secrets.CYPRESS_TRADING_TEST_VEGA_WALLET_PASSPHRASE }}
CYPRESS_SLACK_WEBHOOK: ${{ secrets.CYPRESS_SLACK_WEBHOOK }} CYPRESS_SLACK_WEBHOOK: ${{ secrets.CYPRESS_SLACK_WEBHOOK }}
CYPRESS_ETH_WALLET_MNEMONIC: ${{ secrets.CYPRESS_ETH_WALLET_MNEMONIC }} CYPRESS_ETH_WALLET_MNEMONIC: ${{ secrets.CYPRESS_ETH_WALLET_MNEMONIC }}
CYPRESS_VEGA_WALLET_API_TOKEN: ${{ steps.setup-vega.outputs.token }}
###### ######
## Upload logs ## Upload logs

View File

@ -67,6 +67,7 @@ jobs:
###### ######
- name: Set up Vegawallet - name: Set up Vegawallet
id: setup-vega
uses: ./frontend-monorepo/.github/actions/setup-vegawallet uses: ./frontend-monorepo/.github/actions/setup-vegawallet
with: with:
recovery: ${{ secrets.TRADING_TEST_VEGA_WALLET_RECOVERY }} recovery: ${{ secrets.TRADING_TEST_VEGA_WALLET_RECOVERY }}
@ -84,3 +85,4 @@ jobs:
CYPRESS_TRADING_TEST_VEGA_WALLET_PASSPHRASE: ${{ secrets.CYPRESS_TRADING_TEST_VEGA_WALLET_PASSPHRASE }} CYPRESS_TRADING_TEST_VEGA_WALLET_PASSPHRASE: ${{ secrets.CYPRESS_TRADING_TEST_VEGA_WALLET_PASSPHRASE }}
CYPRESS_SLACK_WEBHOOK: ${{ secrets.CYPRESS_SLACK_WEBHOOK }} CYPRESS_SLACK_WEBHOOK: ${{ secrets.CYPRESS_SLACK_WEBHOOK }}
CYPRESS_ETH_WALLET_MNEMONIC: ${{ secrets.CYPRESS_ETH_WALLET_MNEMONIC }} CYPRESS_ETH_WALLET_MNEMONIC: ${{ secrets.CYPRESS_ETH_WALLET_MNEMONIC }}
CYPRESS_VEGA_WALLET_API_TOKEN: ${{ steps.setup-vega.outputs.token }}

View File

@ -88,7 +88,7 @@ Run `nx test my-app` to execute the unit tests with [Jest](https://jestjs.io), o
### Using wallet ### Using wallet
To run tests locally using your own wallets make sure you have generated at least two public keys and update the following environment variables in `cypress.config.js` to match your wallet. You should also use [vegawallet-dummy](https://github.com/vegaprotocol/vegawallet-dummy) to avoid being prompted in CLI during test execution. To run tests locally using your own wallets make sure you have generated at least two public keys and update the following environment variables in `cypress.config.js` to match your wallet.
1. Set `VEGA_PUBLIC_KEY` and `TRUNCATED_VEGA_PUBLIC_KEY` to your first public key. 1. Set `VEGA_PUBLIC_KEY` and `TRUNCATED_VEGA_PUBLIC_KEY` to your first public key.
2. Set `VEGA_PUBLIC_KEY2` and `TRUNCATED_VEGA_PUBLIC_KEY2` to your second public key. 2. Set `VEGA_PUBLIC_KEY2` and `TRUNCATED_VEGA_PUBLIC_KEY2` to your second public key.

View File

@ -7,3 +7,4 @@ NX_ETHERSCAN_URL=https://sepolia.etherscan.io
NX_VEGA_EXPLORER_URL=https://stagnet3.explorer.vega.xyz NX_VEGA_EXPLORER_URL=https://stagnet3.explorer.vega.xyz
NX_VEGA_WALLET_URL=http://localhost:1789 NX_VEGA_WALLET_URL=http://localhost:1789
CYPRESS_VEGA_ENV=STAGNET3 CYPRESS_VEGA_ENV=STAGNET3
CYPRESS_VEGA_WALLET_API_TOKEN=

View File

@ -16,3 +16,5 @@ NX_EXPLORER_TXS_LIST=0
NX_EXPLORER_NETWORK_PARAMETERS=1 NX_EXPLORER_NETWORK_PARAMETERS=1
NX_EXPLORER_PARTIES=1 NX_EXPLORER_PARTIES=1
NX_EXPLORER_VALIDATORS=1 NX_EXPLORER_VALIDATORS=1
CYPRESS_VEGA_WALLET_API_TOKEN=

View File

@ -47,34 +47,37 @@ context('Asset page', { tags: '@regression' }, function () {
.then((assetsListedInJson) => { .then((assetsListedInJson) => {
const assetInfo = this.assetsInfo[assetName]; const assetInfo = this.assetsInfo[assetName];
assert.equal(assetsListedInJson.name, assetInfo.name); assert.equal(assetsListedInJson.name, assetInfo.node.name);
assert.equal(assetsListedInJson.id, assetInfo.id); assert.equal(assetsListedInJson.id, assetInfo.node.id);
assert.equal(assetsListedInJson.decimals, assetInfo.decimals); assert.equal(
assert.equal(assetsListedInJson.symbol, assetInfo.symbol); assetsListedInJson.decimals,
assetInfo.node.decimals
);
assert.equal(assetsListedInJson.symbol, assetInfo.node.symbol);
assert.equal( assert.equal(
assetsListedInJson.source.__typename, assetsListedInJson.source.__typename,
assetInfo.source.__typename assetInfo.node.source.__typename
); );
if (assetInfo.source.__typename == 'ERC20') { if (assetInfo.node.source.__typename == 'ERC20') {
assert.equal( assert.equal(
assetsListedInJson.source.contractAddress, assetsListedInJson.source.contractAddress,
assetInfo.source.contractAddress assetInfo.node.source.contractAddress
); );
} }
if (assetInfo.source.__typename == 'BuiltinAsset') { if (assetInfo.node.source.__typename == 'BuiltinAsset') {
assert.equal( assert.equal(
assetsListedInJson.source.maxFaucetAmountMint, assetsListedInJson.source.maxFaucetAmountMint,
assetInfo.source.maxFaucetAmountMint assetInfo.node.source.maxFaucetAmountMint
); );
} }
let knownAssetTypes = ['BuiltinAsset', 'ERC20']; let knownAssetTypes = ['BuiltinAsset', 'ERC20'];
assert.include( assert.include(
knownAssetTypes, knownAssetTypes,
assetInfo.source.__typename, assetInfo.node.source.__typename,
`Checking that current asset type of ${assetInfo.source.__typename} / `Checking that current asset type of ${assetInfo.node.source.__typename} /
is one of: ${knownAssetTypes}: / is one of: ${knownAssetTypes}: /
If fail then we need to add extra tests for un-encountered asset types` If fail then we need to add extra tests for un-encountered asset types`
); );

View File

@ -50,7 +50,7 @@ context('Home Page', function () {
.invoke('text') .invoke('text')
.should('match', /\d+d \d+h \d+m \d+s/i); .should('match', /\d+d \d+h \d+m \d+s/i);
cy.get(statsValue).eq(3).should('have.text', '2'); cy.get(statsValue).eq(3).should('have.text', '2');
cy.get(statsValue).eq(4).should('have.text', '0'); cy.get(statsValue).eq(4).should('have.text', '2');
cy.get(statsValue) cy.get(statsValue)
.eq(5) .eq(5)
.invoke('text') .invoke('text')

View File

@ -279,9 +279,9 @@ context('Validator page', { tags: '@smoke' }, function () {
Cypress.Commands.add('get_nodes', () => { Cypress.Commands.add('get_nodes', () => {
const mutation = const mutation =
'{nodes { id name infoUrl avatarUrl pubkey tmPubkey ethereumAddress \ '{nodesConnection { edges { node { id name infoUrl avatarUrl pubkey tmPubkey ethereumAddress \
location stakedByOperator stakedByDelegates stakedTotal pendingStake \ location stakedByOperator stakedByDelegates stakedTotal pendingStake \
epochData { total offline online __typename } status name __typename}}'; epochData { total offline online __typename } status name __typename}}}}';
cy.request({ cy.request({
method: 'POST', method: 'POST',
url: `http://localhost:3028/query`, url: `http://localhost:3028/query`,
@ -290,7 +290,7 @@ context('Validator page', { tags: '@smoke' }, function () {
}, },
headers: { 'content-type': 'application/json' }, headers: { 'content-type': 'application/json' },
}) })
.its(`body.data.nodes`) .its(`body.data.nodesConnection.edges`)
.then(function (response) { .then(function (response) {
let nodes = []; let nodes = [];
response.forEach((node) => { response.forEach((node) => {

View File

@ -15,3 +15,4 @@ NX_VEGA_DOCS_URL=https://docs.vega.xyz/mainnet
#Test configuration variables #Test configuration variables
CYPRESS_FAIRGROUND=false CYPRESS_FAIRGROUND=false
CYPRESS_VEGA_WALLET_API_TOKEN=

View File

@ -130,7 +130,7 @@ context(
beforeEach('visit governance tab', function () { beforeEach('visit governance tab', function () {
cy.reload(); cy.reload();
cy.wait_for_spinner(); cy.wait_for_spinner();
cy.vega_wallet_connect(); cy.connectVegaWallet();
cy.ethereum_wallet_connect(); cy.ethereum_wallet_connect();
cy.navigate_to('governance'); cy.navigate_to('governance');
cy.wait_for_spinner(); cy.wait_for_spinner();
@ -427,82 +427,78 @@ context(
}); });
// 3001-VOTE-080 3001-VOTE-090 // 3001-VOTE-080 3001-VOTE-090
it( it('Newly created proposal details - ability to vote for and against proposal - with minimum required tokens associated', function () {
'Newly created proposal details - ability to vote for and against proposal - with minimum required tokens associated', createRawProposal(this.minProposerBalance);
{ tags: '@smoke' }, cy.get('@rawProposal').then((rawProposal) => {
function () { cy.get_submitted_proposal_from_proposal_list(
createRawProposal(this.minProposerBalance); rawProposal.rationale.title
cy.get('@rawProposal').then((rawProposal) => { ).within(() => cy.get(viewProposalButton).click());
cy.get_submitted_proposal_from_proposal_list( });
rawProposal.rationale.title // 3001-VOTE-080
).within(() => cy.get(viewProposalButton).click()); cy.get(voteButtons).contains('against').should('be.visible');
}); cy.get(voteButtons).contains('for').should('be.visible');
// 3001-VOTE-080 cy.vote_for_proposal('for');
cy.get(voteButtons).contains('against').should('be.visible'); cy.get_governance_proposal_date_format_for_specified_days(
cy.get(voteButtons).contains('for').should('be.visible'); '0',
cy.vote_for_proposal('for'); 'shortMonth'
cy.get_governance_proposal_date_format_for_specified_days( ).then((votedDate) => {
'0', // 3001-VOTE-051
'shortMonth' // 3001-VOTE-093
).then((votedDate) => { cy.contains('You voted:')
// 3001-VOTE-051 .siblings()
// 3001-VOTE-093 .contains('For')
cy.contains('You voted:') .siblings()
.siblings() .contains(votedDate)
.contains('For')
.siblings()
.contains(votedDate)
.should('be.visible');
});
cy.get(proposalVoteProgressForPercentage)
.contains('100.00%')
.and('be.visible');
cy.get(proposalVoteProgressAgainstPercentage)
.contains('0.00%')
.and('be.visible');
cy.get(proposalVoteProgressForTokens)
.contains('1.00')
.and('be.visible');
cy.get(proposalVoteProgressAgainstTokens)
.contains('0.00')
.and('be.visible');
cy.get_proposal_information_from_table('Tokens for proposal')
.should('have.text', parseFloat(this.minProposerBalance).toFixed(2))
.and('be.visible');
cy.get_proposal_information_from_table('Tokens against proposal')
.should('have.text', '0.00')
.and('be.visible');
// 3001-VOTE-061
cy.get_proposal_information_from_table('Participation required')
.contains(`${this.requiredParticipation}%`)
.should('be.visible'); .should('be.visible');
// 3001-VOTE-066 });
cy.get_proposal_information_from_table('Majority Required') cy.get(proposalVoteProgressForPercentage)
.contains(`${parseFloat(this.requiredMajority).toFixed(2)}%`) .contains('100.00%')
.should('be.visible'); .and('be.visible');
cy.get_proposal_information_from_table('Number of voting parties') cy.get(proposalVoteProgressAgainstPercentage)
.should('have.text', '1') .contains('0.00%')
.and('be.visible'); .and('be.visible');
cy.get(changeVoteButton).should('be.visible').click(); cy.get(proposalVoteProgressForTokens)
cy.vote_for_proposal('for'); .contains('1.00')
// 3001-VOTE-064 .and('be.visible');
cy.get_proposal_information_from_table('Tokens for proposal') cy.get(proposalVoteProgressAgainstTokens)
.should('have.text', parseFloat(this.minProposerBalance).toFixed(2)) .contains('0.00')
.and('be.visible'); .and('be.visible');
cy.wait_for_spinner(); cy.get_proposal_information_from_table('Tokens for proposal')
cy.get(changeVoteButton).should('be.visible').click(); .should('have.text', parseFloat(this.minProposerBalance).toFixed(2))
cy.vote_for_proposal('against'); .and('be.visible');
cy.get(proposalVoteProgressAgainstPercentage) cy.get_proposal_information_from_table('Tokens against proposal')
.contains('100.00%') .should('have.text', '0.00')
.and('be.visible'); .and('be.visible');
cy.get_proposal_information_from_table('Tokens against proposal') // 3001-VOTE-061
.should('have.text', parseFloat(this.minProposerBalance).toFixed(2)) cy.get_proposal_information_from_table('Participation required')
.and('be.visible'); .contains(`${this.requiredParticipation}%`)
cy.get_proposal_information_from_table('Number of voting parties') .should('be.visible');
.should('have.text', '1') // 3001-VOTE-066
.and('be.visible'); cy.get_proposal_information_from_table('Majority Required')
} .contains(`${parseFloat(this.requiredMajority).toFixed(2)}%`)
); .should('be.visible');
cy.get_proposal_information_from_table('Number of voting parties')
.should('have.text', '1')
.and('be.visible');
cy.get(changeVoteButton).should('be.visible').click();
cy.vote_for_proposal('for');
// 3001-VOTE-064
cy.get_proposal_information_from_table('Tokens for proposal')
.should('have.text', parseFloat(this.minProposerBalance).toFixed(2))
.and('be.visible');
cy.wait_for_spinner();
cy.get(changeVoteButton).should('be.visible').click();
cy.vote_for_proposal('against');
cy.get(proposalVoteProgressAgainstPercentage)
.contains('100.00%')
.and('be.visible');
cy.get_proposal_information_from_table('Tokens against proposal')
.should('have.text', parseFloat(this.minProposerBalance).toFixed(2))
.and('be.visible');
cy.get_proposal_information_from_table('Number of voting parties')
.should('have.text', '1')
.and('be.visible');
});
// 3001-VOTE-042, 3001-VOTE-057, 3001-VOTE-058, 3001-VOTE-059, 3001-VOTE-060 // 3001-VOTE-042, 3001-VOTE-057, 3001-VOTE-058, 3001-VOTE-059, 3001-VOTE-060
it('Newly created proposal details - ability to increase associated tokens - by voting again after association', function () { it('Newly created proposal details - ability to increase associated tokens - by voting again after association', function () {
@ -738,42 +734,38 @@ context(
}); });
// 1005-PROP-009 // 1005-PROP-009
it( it('Unable to vote on a freeform proposal - when some but not enough vega associated', function () {
'Unable to vote on a freeform proposal - when some but not enough vega associated', const proposalTitle = generateProposalTitle();
{ tags: '@smoke' },
function () {
const proposalTitle = generateProposalTitle();
cy.ensure_specified_unstaked_tokens_are_associated( cy.ensure_specified_unstaked_tokens_are_associated(
this.minProposerBalance this.minProposerBalance
);
cy.go_to_make_new_proposal(governanceProposalType.FREEFORM);
cy.enter_unique_freeform_proposal_body('50', proposalTitle);
cy.get(newProposalSubmitButton).should('be.visible').click();
cy.wait_for_proposal_submitted();
cy.wait_for_proposal_sync();
cy.staking_page_disassociate_tokens('0.0001');
cy.get(vegaWallet).within(() => {
cy.get(vegaWalletAssociatedBalance, txTimeout).should(
'contain',
'0.9999'
); );
cy.go_to_make_new_proposal(governanceProposalType.FREEFORM); });
cy.enter_unique_freeform_proposal_body('50', proposalTitle); cy.navigate_to('governance');
cy.get(newProposalSubmitButton).should('be.visible').click(); cy.wait_for_spinner();
cy.wait_for_proposal_submitted(); cy.get_submitted_proposal_from_proposal_list(proposalTitle).within(() =>
cy.wait_for_proposal_sync(); cy.get(viewProposalButton).click()
cy.staking_page_disassociate_tokens('0.0001'); );
cy.get(vegaWallet).within(() => { cy.contains('Vote breakdown').should('be.visible', {
cy.get(vegaWalletAssociatedBalance, txTimeout).should( timeout: 10000,
'contain', });
'0.9999' cy.get(voteButtons).should('not.exist');
); cy.getByTestId('min-proposal-requirements').should(
}); 'have.text',
cy.navigate_to('governance'); `You must have at least ${this.minVoterBalance} VEGA associated to vote on this proposal`
cy.wait_for_spinner(); );
cy.get_submitted_proposal_from_proposal_list(proposalTitle).within( });
() => cy.get(viewProposalButton).click()
);
cy.contains('Vote breakdown').should('be.visible', {
timeout: 10000,
});
cy.get(voteButtons).should('not.exist');
cy.getByTestId('min-proposal-requirements').should(
'have.text',
`You must have at least ${this.minVoterBalance} VEGA associated to vote on this proposal`
);
}
);
it('Unable to vote on a proposal - when vega wallet disconnected - option to connect from within', function () { it('Unable to vote on a proposal - when vega wallet disconnected - option to connect from within', function () {
createRawProposal(this.minProposerBalance); createRawProposal(this.minProposerBalance);

View File

@ -48,7 +48,7 @@ context(
beforeEach('visit governance tab', function () { beforeEach('visit governance tab', function () {
cy.reload(); cy.reload();
cy.wait_for_spinner(); cy.wait_for_spinner();
cy.vega_wallet_connect(); cy.connectVegaWallet();
cy.ethereum_wallet_connect(); cy.ethereum_wallet_connect();
cy.navigate_to('governance'); cy.navigate_to('governance');
cy.wait_for_spinner(); cy.wait_for_spinner();

View File

@ -43,7 +43,7 @@ context(
function () { function () {
cy.reload(); cy.reload();
cy.wait_for_spinner(); cy.wait_for_spinner();
cy.vega_wallet_connect(); cy.connectVegaWallet();
cy.ethereum_wallet_connect(); cy.ethereum_wallet_connect();
cy.vega_wallet_teardown(); cy.vega_wallet_teardown();
cy.navigate_to('staking'); cy.navigate_to('staking');
@ -285,72 +285,68 @@ context(
}); });
// 2001-STKE-041 // 2001-STKE-041
it( it('Able to remove part of a stake against a validator', function () {
'Able to remove part of a stake against a validator', cy.staking_page_associate_tokens('4');
{ tags: '@smoke' },
function () {
cy.staking_page_associate_tokens('4');
cy.get(vegaWalletUnstakedBalance, txTimeout).should( cy.get(vegaWalletUnstakedBalance, txTimeout).should(
'contain', 'contain',
4.0, 4.0,
txTimeout txTimeout
); );
cy.get('button').contains('Select a validator to nominate').click(); cy.get('button').contains('Select a validator to nominate').click();
cy.click_on_validator_from_list(0); cy.click_on_validator_from_list(0);
cy.staking_validator_page_add_stake('3'); cy.staking_validator_page_add_stake('3');
cy.get(stakeNextEpochValue, epochTimeout) cy.get(stakeNextEpochValue, epochTimeout)
.contains(3.0, epochTimeout) .contains(3.0, epochTimeout)
.should('be.visible'); .should('be.visible');
cy.get(vegaWalletUnstakedBalance, txTimeout).should( cy.get(vegaWalletUnstakedBalance, txTimeout).should(
'contain', 'contain',
1.0, 1.0,
txTimeout txTimeout
); );
cy.navigate_to('staking'); cy.navigate_to('staking');
// 2001-STKE-040 // 2001-STKE-040
cy.click_on_validator_from_list(0); cy.click_on_validator_from_list(0);
// 2001-STKE-044, 2001-STKE-048 // 2001-STKE-044, 2001-STKE-048
cy.staking_validator_page_remove_stake('1'); cy.staking_validator_page_remove_stake('1');
// 2001-STKE-049 // 2001-STKE-049
cy.get(stakeNextEpochValue, epochTimeout).contains(2.0, epochTimeout); cy.get(stakeNextEpochValue, epochTimeout).contains(2.0, epochTimeout);
cy.get(vegaWalletUnstakedBalance, txTimeout).should( cy.get(vegaWalletUnstakedBalance, txTimeout).should(
'contain', 'contain',
2.0, 2.0,
txTimeout txTimeout
); );
cy.get(vegaWalletStakedBalances, txTimeout).should( cy.get(vegaWalletStakedBalances, txTimeout).should(
'contain', 'contain',
2.0, 2.0,
txTimeout txTimeout
); );
cy.get(stakeNextEpochValue, epochTimeout) cy.get(stakeNextEpochValue, epochTimeout)
.contains(2.0, epochTimeout) .contains(2.0, epochTimeout)
.should('be.visible'); .should('be.visible');
cy.get(stakeThisEpochValue, epochTimeout) cy.get(stakeThisEpochValue, epochTimeout)
.contains(2.0, epochTimeout) .contains(2.0, epochTimeout)
.should('be.visible'); .should('be.visible');
cy.get(totalStake, epochTimeout).should('contain.text', '2'); cy.get(totalStake, epochTimeout).should('contain.text', '2');
cy.get(stakeShare, epochTimeout).should('have.text', '100%'); cy.get(stakeShare, epochTimeout).should('have.text', '100%');
cy.navigate_to('staking'); cy.navigate_to('staking');
cy.validate_validator_list_total_stake_and_share('0', '2.00', '100%'); cy.validate_validator_list_total_stake_and_share('0', '2.00', '100%');
} });
);
// 2001-STKE-045 // 2001-STKE-045
it('Able to remove a full stake against a validator', function () { it('Able to remove a full stake against a validator', function () {

View File

@ -37,7 +37,7 @@ context(
function () { function () {
cy.reload(); cy.reload();
cy.wait_for_spinner(); cy.wait_for_spinner();
cy.vega_wallet_connect(); cy.connectVegaWallet();
cy.ethereum_wallet_connect(); cy.ethereum_wallet_connect();
cy.vega_wallet_teardown(); cy.vega_wallet_teardown();
cy.navigate_to('staking'); cy.navigate_to('staking');

View File

@ -35,7 +35,7 @@ context(
cy.visit('/'); cy.visit('/');
cy.navigate_to('withdrawals'); cy.navigate_to('withdrawals');
cy.wait_for_spinner(); cy.wait_for_spinner();
cy.vega_wallet_connect(); cy.connectVegaWallet();
cy.ethereum_wallet_connect(); cy.ethereum_wallet_connect();
cy.vega_wallet_teardown(); cy.vega_wallet_teardown();
}); });

View File

@ -104,10 +104,10 @@ context('Staking Page - verify elements on page', function () {
// 2001-STKE-050 // 2001-STKE-050
describe( describe(
'Should be able to see static information about a validator', 'Should be able to see static information about a validator',
{ tags: '@smoke' }, { tags: '@slow' },
function () { function () {
before('connect wallets and click on validator', function () { before('connect wallets and click on validator', function () {
cy.vega_wallet_connect(); cy.connectVegaWallet();
cy.click_on_validator_from_list(0); cy.click_on_validator_from_list(0);
}); });

View File

@ -2,7 +2,7 @@ import { truncateByChars } from '@vegaprotocol/react-helpers';
const walletContainer = '[data-testid="vega-wallet"]'; const walletContainer = '[data-testid="vega-wallet"]';
const walletHeader = '[data-testid="wallet-header"] h1'; const walletHeader = '[data-testid="wallet-header"] h1';
const connectButton = '[data-testid="connect-vega"]'; const connectButton = '[data-testid="connect-vega-wallet"]';
const getVegaLink = '[data-testid="link"]'; const getVegaLink = '[data-testid="link"]';
const dialog = '[role="dialog"]'; const dialog = '[role="dialog"]';
const dialogHeader = '[data-testid="dialog-title"]'; const dialogHeader = '[data-testid="dialog-title"]';
@ -150,7 +150,7 @@ context(
describe('when vega wallet connected', function () { describe('when vega wallet connected', function () {
before('connect vega wallet', function () { before('connect vega wallet', function () {
cy.visit('/'); cy.visit('/');
cy.vega_wallet_connect(); cy.connectVegaWallet();
cy.vega_wallet_teardown(); cy.vega_wallet_teardown();
}); });
@ -288,7 +288,7 @@ context(
}); });
// 2002-SINC-016 // 2002-SINC-016
describe('when assets exist in vegawallet', function () { describe.skip('when assets exist in vegawallet', function () {
before('send-faucet assets to connected vega wallet', function () { before('send-faucet assets to connected vega wallet', function () {
cy.vega_wallet_faucet_assets_without_check( cy.vega_wallet_faucet_assets_without_check(
faucetAssets.USDCFake, faucetAssets.USDCFake,
@ -310,7 +310,7 @@ context(
'200000', '200000',
vegaWalletPublicKey vegaWalletPublicKey
); );
cy.vega_wallet_connect(); cy.connectVegaWallet();
cy.ethereum_wallet_connect(); cy.ethereum_wallet_connect();
}); });

View File

@ -1,20 +1,3 @@
const vegaWalletContainer = '[data-testid="vega-wallet"]';
const vegaWalletNameElement = '[data-testid="wallet-name"]';
Cypress.Commands.add('vega_wallet_connect', () => {
cy.highlight('Connecting Vega Wallet');
cy.get(vegaWalletContainer, { timeout: 6000 }).within(() => {
cy.get('button')
.contains('Connect Vega wallet to use associated $VEGA')
.should('be.enabled')
.and('be.visible')
.click({ force: true });
});
cy.getByTestId('connector-jsonRpc').click();
cy.get(vegaWalletNameElement).should('be.visible');
cy.getByTestId('wallet-dialog-title').should('not.exist');
});
Cypress.Commands.add( Cypress.Commands.add(
'vega_wallet_faucet_assets_without_check', 'vega_wallet_faucet_assets_without_check',
function (asset, amount, vegaWalletPublicKey) { function (asset, amount, vegaWalletPublicKey) {

View File

@ -84,7 +84,7 @@ const VegaWalletNotConnected = () => {
openVegaWalletDialog(); openVegaWalletDialog();
}} }}
fill={true} fill={true}
data-testid="connect-vega" data-testid="connect-vega-wallet"
> >
{t('connectVegaWalletToUseAssociated')} {t('connectVegaWalletToUseAssociated')}
</Button> </Button>

View File

@ -13,3 +13,4 @@ NX_VEGA_DOCS_URL=https://docs.vega.xyz/testnet
CYPRESS_VEGA_URL=https://api.stagnet3.vega.xyz/graphql CYPRESS_VEGA_URL=https://api.stagnet3.vega.xyz/graphql
CYPRESS_EXPLORER_URL=https://stagnet3.explorer.vega.xyz CYPRESS_EXPLORER_URL=https://stagnet3.explorer.vega.xyz
CYPRESS_VEGA_ENV=STAGNET3 CYPRESS_VEGA_ENV=STAGNET3
CYPRESS_VEGA_WALLET_API_TOKEN=

View File

@ -1,4 +1,4 @@
import { aliasQuery } from '@vegaprotocol/cypress'; import { aliasQuery, mockConnectWallet } from '@vegaprotocol/cypress';
import { generateNetworkParameters } from '../support/mocks/generate-network-parameters'; import { generateNetworkParameters } from '../support/mocks/generate-network-parameters';
const connectEthWalletBtn = 'connect-eth-wallet-btn'; const connectEthWalletBtn = 'connect-eth-wallet-btn';
@ -18,12 +18,14 @@ describe('vega wallet v1', { tags: '@smoke' }, () => {
it('can connect', () => { it('can connect', () => {
cy.getByTestId(connectVegaBtn).click(); cy.getByTestId(connectVegaBtn).click();
mockConnectWallet();
cy.contains('Connect Vega wallet'); cy.contains('Connect Vega wallet');
cy.contains('Hosted Fairground wallet'); cy.contains('Hosted Fairground wallet');
cy.getByTestId('connectors-list') cy.getByTestId('connectors-list')
.find('[data-testid="connector-jsonRpc"]') .find('[data-testid="connector-jsonRpc"]')
.click(); .click();
cy.wait('@walletGQL');
cy.getByTestId(manageVegaBtn).should('exist'); cy.getByTestId(manageVegaBtn).should('exist');
}); });
@ -66,10 +68,12 @@ describe('vega wallet v2', { tags: '@smoke' }, () => {
}); });
it('can connect', () => { it('can connect', () => {
mockConnectWallet();
cy.getByTestId(connectVegaBtn).click(); cy.getByTestId(connectVegaBtn).click();
cy.getByTestId('connectors-list') cy.getByTestId('connectors-list')
.find('[data-testid="connector-jsonRpc"]') .find('[data-testid="connector-jsonRpc"]')
.click(); .click();
cy.wait('@walletGQL');
cy.getByTestId(dialogContent).should('not.exist'); cy.getByTestId(dialogContent).should('not.exist');
cy.getByTestId(manageVegaBtn).should('exist'); cy.getByTestId(manageVegaBtn).should('exist');
}); });

View File

@ -4,7 +4,7 @@ import {
Schema, Schema,
} from '@vegaprotocol/types'; } from '@vegaprotocol/types';
import { generateEstimateOrder } from '../support/mocks/generate-fees'; import { generateEstimateOrder } from '../support/mocks/generate-fees';
import { aliasQuery } from '@vegaprotocol/cypress'; import { aliasQuery, mockConnectWallet } from '@vegaprotocol/cypress';
import { testOrder } from '../support/deal-ticket-transaction'; import { testOrder } from '../support/deal-ticket-transaction';
import type { OrderSubmission } from '@vegaprotocol/wallet'; import type { OrderSubmission } from '@vegaprotocol/wallet';
@ -393,6 +393,7 @@ describe('deal ticket validation', { tags: '@smoke' }, () => {
}); });
it('order connect vega wallet button should connect', () => { it('order connect vega wallet button should connect', () => {
mockConnectWallet();
cy.getByTestId(toggleLimit).click(); cy.getByTestId(toggleLimit).click();
cy.getByTestId(orderPriceField).clear().type('101'); cy.getByTestId(orderPriceField).clear().type('101');
cy.getByTestId('order-connect-wallet').click(); cy.getByTestId('order-connect-wallet').click();
@ -400,6 +401,7 @@ describe('deal ticket validation', { tags: '@smoke' }, () => {
cy.getByTestId('connectors-list') cy.getByTestId('connectors-list')
.find('[data-testid="connector-jsonRpc"]') .find('[data-testid="connector-jsonRpc"]')
.click(); .click();
cy.wait('@walletGQL');
cy.getByTestId(placeOrderBtn).should('be.visible'); cy.getByTestId(placeOrderBtn).should('be.visible');
cy.getByTestId(toggleLimit).children('input').should('be.checked'); cy.getByTestId(toggleLimit).children('input').should('be.checked');
cy.getByTestId(orderPriceField).should('have.value', '101'); cy.getByTestId(orderPriceField).should('have.value', '101');

View File

@ -8,7 +8,6 @@ export const generateChainId = (
const defaultResult = { const defaultResult = {
statistics: { statistics: {
__typename: 'Statistics', __typename: 'Statistics',
// this needs to match the network set up for vegawallet-dummy in .github/actions/setup-vegawallet/action.yml
chainId: 'stagnet3', chainId: 'stagnet3',
}, },
}; };

View File

@ -8,7 +8,6 @@ export const generateStatistics = (
const defaultResult = { const defaultResult = {
statistics: { statistics: {
__typename: 'Statistics', __typename: 'Statistics',
// this needs to match the network set up for vegawallet-dummy in .github/actions/setup-vegawallet/action.yml
chainId: 'stagnet3', chainId: 'stagnet3',
blockHeight: '11', blockHeight: '11',
}, },

View File

@ -2,6 +2,7 @@ import { addGetTestIdcommand } from './lib/commands/get-by-test-id';
import { import {
addMockGQLCommand, addMockGQLCommand,
addMockGQLSubscriptionCommand, addMockGQLSubscriptionCommand,
addMockWalletGQLCommand,
} from './lib/commands/mock-gql'; } from './lib/commands/mock-gql';
import { addMockWeb3ProviderCommand } from './lib/commands/mock-web3-provider'; import { addMockWeb3ProviderCommand } from './lib/commands/mock-web3-provider';
import { addSlackCommand } from './lib/commands/slack'; import { addSlackCommand } from './lib/commands/slack';
@ -18,6 +19,7 @@ addGetTestIdcommand();
addSlackCommand(); addSlackCommand();
addMockGQLCommand(); addMockGQLCommand();
addMockGQLSubscriptionCommand(); addMockGQLSubscriptionCommand();
addMockWalletGQLCommand();
addMockWeb3ProviderCommand(); addMockWeb3ProviderCommand();
addHighlightLog(); addHighlightLog();
addVegaWalletReceiveFaucetedAsset(); addVegaWalletReceiveFaucetedAsset();
@ -29,6 +31,7 @@ addVegaWalletConnect();
addMockTransactionResponse(); addMockTransactionResponse();
export * from './lib/graphql-test-utils'; export * from './lib/graphql-test-utils';
export { mockConnectWallet } from './lib/commands/vega-wallet-connect';
export type { onMessage } from './lib/commands/mock-gql'; export type { onMessage } from './lib/commands/mock-gql';
Cypress.on( Cypress.on(

View File

@ -12,11 +12,11 @@ export function addGetAssetInformation() {
// @ts-ignore - ignoring Cypress type error which gets resolved when Cypress uses the command // @ts-ignore - ignoring Cypress type error which gets resolved when Cypress uses the command
Cypress.Commands.add('get_asset_information', () => { Cypress.Commands.add('get_asset_information', () => {
const mutation = const mutation =
'{ assets {name id symbol decimals source{__typename \ '{ assetsConnection{edges{node{name id symbol decimals source{__typename \
... on ERC20{contractAddress} \ ... on ERC20{contractAddress} \
... on BuiltinAsset{maxFaucetAmountMint}} \ ... on BuiltinAsset{maxFaucetAmountMint}} \
infrastructureFeeAccount{__typename type balance} \ infrastructureFeeAccount{__typename type balance} \
globalRewardPoolAccount {balance}}}'; globalRewardPoolAccount {balance}}}}}';
cy.request({ cy.request({
method: 'POST', method: 'POST',
url: `http://localhost:3028/query`, url: `http://localhost:3028/query`,
@ -25,11 +25,11 @@ export function addGetAssetInformation() {
}, },
headers: { 'content-type': 'application/json' }, headers: { 'content-type': 'application/json' },
}) })
.its(`body.data.assets`) .its('body.data.assetsConnection.edges')
.then(function (response) { .then(function (response) {
// @ts-ignore - ignoring Cypress type error which gets resolved when Cypress uses the command // @ts-ignore - ignoring Cypress type error which gets resolved when Cypress uses the command
const object = response.reduce(function (assets, entry) { const object = response.reduce(function (assets, entry) {
assets[entry.name] = entry; assets[entry.node.name] = entry;
return assets; return assets;
}, {}); }, {});
return object; return object;

View File

@ -12,10 +12,17 @@ declare global {
interface Chainable<Subject> { interface Chainable<Subject> {
mockGQL(handler: RouteHandler): void; mockGQL(handler: RouteHandler): void;
mockGQLSubscription(mocks?: Record<string, onMessage>): void; mockGQLSubscription(mocks?: Record<string, onMessage>): void;
mockWalletGQL(handler: RouteHandler): void;
} }
} }
} }
export function addMockWalletGQLCommand() {
Cypress.Commands.add('mockWalletGQL', (handler: RouteHandler): void => {
cy.intercept('POST', '**/api/v2/requests', handler).as('walletGQL');
});
}
export function addMockGQLCommand() { export function addMockGQLCommand() {
Cypress.Commands.add('mockGQL', (handler: RouteHandler) => { Cypress.Commands.add('mockGQL', (handler: RouteHandler) => {
cy.intercept('POST', '**/graphql', handler).as('GQL'); cy.intercept('POST', '**/graphql', handler).as('GQL');

View File

@ -1,3 +1,5 @@
import { aliasWalletQuery } from '../graphql-test-utils';
declare global { declare global {
// eslint-disable-next-line @typescript-eslint/no-namespace // eslint-disable-next-line @typescript-eslint/no-namespace
namespace Cypress { namespace Cypress {
@ -8,14 +10,26 @@ declare global {
} }
} }
export const mockConnectWallet = () => {
const data = {
token: Cypress.env('VEGA_WALLET_API_TOKEN'),
};
console.log('mockConnectWallet', data);
cy.mockWalletGQL((req) => {
aliasWalletQuery(req, 'client.connect_wallet', data);
});
};
export function addVegaWalletConnect() { export function addVegaWalletConnect() {
// @ts-ignore - ignoring Cypress type error which gets resolved when Cypress uses the command // @ts-ignore - ignoring Cypress type error which gets resolved when Cypress uses the command
Cypress.Commands.add('connectVegaWallet', () => { Cypress.Commands.add('connectVegaWallet', () => {
mockConnectWallet();
cy.highlight(`Connecting Vega Wallet`); cy.highlight(`Connecting Vega Wallet`);
cy.get('[data-testid=connect-vega-wallet]').click(); cy.get('[data-testid=connect-vega-wallet]').click();
cy.get('[data-testid=connectors-list]') cy.get('[data-testid=connectors-list]')
.find('[data-testid="connector-jsonRpc"]') .find('[data-testid="connector-jsonRpc"]')
.click(); .click();
cy.wait('@walletGQL');
cy.get('[data-testid=dialog-content]').should( cy.get('[data-testid=dialog-content]').should(
'contain.text', 'contain.text',
'Successfully connected' 'Successfully connected'

View File

@ -25,3 +25,31 @@ export const aliasQuery = (
} }
} }
}; };
const hasMethod = (req: CyHttpMessages.IncomingHttpRequest, method: string) => {
const { body } = req;
return 'method' in body && body.method === method;
};
// Alias wallet query if method matches
export const aliasWalletQuery = (
req: CyHttpMessages.IncomingHttpRequest,
method: string,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
data?: any
) => {
const body = {
jsonrpc: '2.0',
id: '0',
result: data,
};
if (hasMethod(req, method)) {
req.alias = method;
if (data !== undefined) {
req.reply({
statusCode: 200,
body: body,
});
}
}
};

View File

@ -205,8 +205,6 @@ describe('VegaConnectDialog', () => {
let spyOnGetChainId: jest.SpyInstance; let spyOnGetChainId: jest.SpyInstance;
let spyOnConnectWallet: jest.SpyInstance; let spyOnConnectWallet: jest.SpyInstance;
let spyOnConnect: jest.SpyInstance; let spyOnConnect: jest.SpyInstance;
let spyOnGetPermissions: jest.SpyInstance;
let spyOnRequestPermissions: jest.SpyInstance;
beforeEach(() => { beforeEach(() => {
spyOnCheckCompat = jest spyOnCheckCompat = jest
@ -218,24 +216,6 @@ describe('VegaConnectDialog', () => {
spyOnConnectWallet = jest spyOnConnectWallet = jest
.spyOn(connectors.jsonRpc, 'connectWallet') .spyOn(connectors.jsonRpc, 'connectWallet')
.mockImplementation(() => delayedResolve({ token: 'token' })); .mockImplementation(() => delayedResolve({ token: 'token' }));
spyOnGetPermissions = jest
.spyOn(connectors.jsonRpc, 'getPermissions')
.mockImplementation(() =>
delayedResolve({
permissions: {
public_keys: 'none',
},
})
);
spyOnRequestPermissions = jest
.spyOn(connectors.jsonRpc, 'requestPermissions')
.mockImplementation(() =>
delayedResolve({
permissions: {
public_keys: 'read',
},
})
);
spyOnConnect = jest spyOnConnect = jest
.spyOn(connectors.jsonRpc, 'connect') .spyOn(connectors.jsonRpc, 'connect')
.mockImplementation(() => .mockImplementation(() =>
@ -277,19 +257,6 @@ describe('VegaConnectDialog', () => {
jest.advanceTimersByTime(delay); jest.advanceTimersByTime(delay);
}); });
// Perms check
expect(spyOnGetPermissions).toHaveBeenCalled();
await act(async () => {
jest.advanceTimersByTime(delay);
});
// Await user perms update
expect(screen.getByText('Update permissions')).toBeInTheDocument();
expect(spyOnRequestPermissions).toHaveBeenCalled();
await act(async () => {
jest.advanceTimersByTime(delay);
});
// Connect (list keys) // Connect (list keys)
expect(spyOnConnect).toHaveBeenCalled(); expect(spyOnConnect).toHaveBeenCalled();
await act(async () => { await act(async () => {

View File

@ -2,7 +2,6 @@ import capitalize from 'lodash/capitalize';
import { createDocsLinks, t } from '@vegaprotocol/react-helpers'; import { createDocsLinks, t } from '@vegaprotocol/react-helpers';
import { import {
ButtonLink, ButtonLink,
Cross,
Diamond, Diamond,
Link, Link,
Loader, Loader,
@ -127,21 +126,6 @@ const Connecting = ({
); );
} }
if (status === Status.RequestingPerms) {
return (
<>
<ConnectDialogTitle>{t('Update permissions')}</ConnectDialogTitle>
<Center>
<Cross />
</Center>
<p className="text-center">
{t(`${window.location.host} now has access to your Wallet, however you don't
have sufficient permissions to retrieve your public keys. Go to your wallet to approve new permissions.`)}
</p>
</>
);
}
return null; return null;
}; };

View File

@ -10,8 +10,6 @@ const VERSION = 'v2';
enum Methods { enum Methods {
ConnectWallet = 'client.connect_wallet', ConnectWallet = 'client.connect_wallet',
DisconnectWallet = 'client.disconnect_wallet', DisconnectWallet = 'client.disconnect_wallet',
GetPermissions = 'client.get_permissions',
RequestPermisssions = 'client.request_permissions',
ListKeys = 'client.list_keys', ListKeys = 'client.list_keys',
SendTransaction = 'client.send_transaction', SendTransaction = 'client.send_transaction',
GetChainId = 'client.get_chain_id', GetChainId = 'client.get_chain_id',
@ -45,22 +43,6 @@ const GetChainIdSchema = BaseSchema.extend({
}), }),
}); });
const GetPermissionsSchema = BaseSchema.extend({
result: z.object({
permissions: z.object({
public_keys: z.enum(['none', 'read', 'write']),
}),
}),
});
const RequestPermissionsSchema = BaseSchema.extend({
result: z.object({
permissions: z.object({
public_keys: z.enum(['none', 'read', 'write']),
}),
}),
});
const SendTransactionSchema = BaseSchema.extend({ const SendTransactionSchema = BaseSchema.extend({
result: z.object({ result: z.object({
receivedAt: z.string(), receivedAt: z.string(),
@ -84,8 +66,6 @@ type Response =
| z.infer<typeof ConnectWalletSchema> | z.infer<typeof ConnectWalletSchema>
| z.infer<typeof ListKeysSchema> | z.infer<typeof ListKeysSchema>
| z.infer<typeof GetChainIdSchema> | z.infer<typeof GetChainIdSchema>
| z.infer<typeof GetPermissionsSchema>
| z.infer<typeof RequestPermissionsSchema>
| z.infer<typeof SendTransactionSchema> | z.infer<typeof SendTransactionSchema>
| { error: JsonRpcError }; | { error: JsonRpcError };
@ -155,47 +135,6 @@ export class JsonRpcConnector implements VegaConnector {
} }
} }
async getPermissions() {
const cfg = getConfig();
if (!cfg?.token) {
throw ClientErrors.NO_TOKEN;
}
const result = await this.request(Methods.GetPermissions, {
token: cfg.token,
});
if ('error' in result) {
throw this.wrapError(result.error);
}
const parseResult = GetPermissionsSchema.safeParse(result);
if (parseResult.success) {
return parseResult.data.result;
} else {
throw ClientErrors.INVALID_RESPONSE;
}
}
async requestPermissions() {
const cfg = getConfig();
if (!cfg?.token) {
throw ClientErrors.NO_TOKEN;
}
const result = await this.request(Methods.RequestPermisssions, {
token: cfg.token,
requestedPermissions: {
public_keys: 'read',
},
});
if ('error' in result) {
throw this.wrapError(result.error);
}
const parseResult = RequestPermissionsSchema.safeParse(result);
if (parseResult.success) {
return parseResult.data.result;
} else {
throw ClientErrors.INVALID_RESPONSE;
}
}
// connect actually calling list_keys here, not to be confused with connect_wallet // connect actually calling list_keys here, not to be confused with connect_wallet
// which retrieves the session token // which retrieves the session token
async connect() { async connect() {

View File

@ -9,6 +9,7 @@ import type {
} from './connectors/vega-connector'; } from './connectors/vega-connector';
import { VegaWalletContext } from './context'; import { VegaWalletContext } from './context';
import { WALLET_KEY } from './storage'; import { WALLET_KEY } from './storage';
import { WalletError } from './connectors/vega-connector';
interface VegaWalletProviderProps { interface VegaWalletProviderProps {
children: ReactNode; children: ReactNode;
@ -50,6 +51,9 @@ export const VegaWalletProvider = ({ children }: VegaWalletProviderProps) => {
return null; return null;
} }
} catch (err) { } catch (err) {
if (err instanceof WalletError) {
throw err;
}
return null; return null;
} }
}, []); }, []);

View File

@ -10,7 +10,6 @@ export enum Status {
GettingChainId = 'GettingChainId', GettingChainId = 'GettingChainId',
Connecting = 'Connecting', Connecting = 'Connecting',
GettingPerms = 'GettingPerms', GettingPerms = 'GettingPerms',
RequestingPerms = 'RequestingPerms',
ListingKeys = 'ListingKeys', ListingKeys = 'ListingKeys',
Connected = 'Connected', Connected = 'Connected',
Error = 'Error', Error = 'Error',
@ -48,15 +47,7 @@ export const useJsonRpcConnect = (onConnect: () => void) => {
setStatus(Status.Connecting); setStatus(Status.Connecting);
await connector.connectWallet(); await connector.connectWallet();
// Check wallet is permitted to reveal its public keys
setStatus(Status.GettingPerms); setStatus(Status.GettingPerms);
const permsResult = await connector.getPermissions();
if (permsResult.permissions.public_keys === 'none') {
// Automatically request new perms. User will again be prompted to permit this change
// and enter their password
setStatus(Status.RequestingPerms);
await connector.requestPermissions();
}
// Call connect in the wallet provider. The connector will be stored for // Call connect in the wallet provider. The connector will be stored for
// future actions such as sending transactions // future actions such as sending transactions