Compare commits

...
Author SHA1 Message Date
asiaznik 2208afec2e chore: truncate long ids 2023-03-23 19:59:37 +01:00
asiaznik 0c727f1d68 fix: e2e tests 2023-03-23 19:52:57 +01:00
asiaznik 1b71aa4900 Merge branch 'feat/2909-breadcrumbs' of github.com:vegaprotocol/frontend-monorepo into feat/2909-breadcrumbs 2023-03-23 18:22:43 +01:00
asiaznik c26a6a61b2 feat: home page and improvements 2023-03-23 18:22:22 +01:00
ArtandEdd b2c71cee60 Update libs/ui-toolkit/src/components/breadcrumbs/breadcrumbs.spec.tsx
Co-authored-by: Edd <edd@vega.xyz>
2023-03-22 17:29:13 +01:00
asiaznik 2f0ca962c9 fix: mobile crumb for transactions 2023-03-22 17:24:41 +01:00
asiaznik a402a61ece chore: styling on mobile 2023-03-22 16:30:18 +01:00
asiaznik 028c6bcaa2 fix: lint issues 2023-03-22 16:07:51 +01:00
asiaznik 1c5b3ba8b3 chore: removed "All transactions" link 2023-03-22 15:53:15 +01:00
asiaznik 9e3feb301a feat(ui-toolkit, explorer): breadcrumbs 2023-03-22 15:41:38 +01:00
Dexter EdwardsandMatthew Russell 90ceeebf15 fix(ui-toolkit): anchor button should be same size as button by default (#3172)
Co-authored-by: Matthew Russell <mattrussell36@gmail.com>
2023-03-21 15:24:34 -07:00
dexturr 965f7f6e2d chore: update tranches
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-03-21 18:08:39 +00:00
Ciaran McGhie 18633efec3 chore(ui-toolkit): rework intent colours (#3202) 2023-03-21 16:40:39 +00:00
a0b758334a fix(trading): auction triggers liquidity API change in develop for core 0.69.0 (#3197)
Co-authored-by: Matthew Russell <mattrussell36@gmail.com>
Co-authored-by: Dariusz Majcherczyk <dariusz.majcherczyk@gmail.com>
2023-03-21 09:19:21 -07:00
Bartłomiej Głownia 9f3026aa4b fix(market-depth): fix depth chart data upate, use market depth as mid price source (#3242) 2023-03-21 08:46:04 -07:00
Maciek faa359e2fb chore(trading): 2764 link to mainnet incident reports (#3235) 2023-03-21 08:19:54 -07:00
Bartłomiej Głownia 1d178b940f feat(trading): store current tab selection (#3148) 2023-03-21 15:50:31 +01:00
dexturr b2dd053621 chore: update tranches
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-03-21 12:10:18 +00:00
dexturr 77f5193b7a chore: update tranches
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-03-21 06:07:47 +00:00
dexturr 055a0070db chore: update tranches
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-03-21 00:13:48 +00:00
dexturr 29b221c86a chore: update tranches
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-03-20 18:09:57 +00:00
Dexter Edwards 3e619acd4b feat(ui-toolkit): button icons (#3233) 2023-03-20 14:40:04 +00:00
botond c720719ac5 chore(governance): update announcement banner text (#3234) 2023-03-20 13:52:03 +00:00
Art c676a7c1e2 chore(explorer): move banner up (#3237) 2023-03-20 13:38:31 +00:00
dexturr ca63a671c8 chore: update tranches
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-03-20 12:09:43 +00:00
Maciek 4165f3905f chore(static): update domains in network conf files (#3219) 2023-03-20 09:58:05 +00:00
dexturr a359ccb755 chore: update tranches
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-03-20 06:07:41 +00:00
dexturr e584737005 chore: update tranches
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-03-20 00:17:40 +00:00
dexturr b12c5ed39f chore: update tranches
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-03-19 18:08:07 +00:00
dexturr d3dbd64cf1 chore: update tranches
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-03-19 12:07:36 +00:00
dexturr 2df62bca61 chore: update tranches
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-03-19 06:07:48 +00:00
dexturr fd2a434b46 chore: update tranches
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-03-19 00:17:10 +00:00
dexturr 4e7a78f988 chore: update tranches
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-03-18 18:08:23 +00:00
dexturr 327619652a chore: update tranches
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-03-18 12:07:24 +00:00
dexturr d2339205cc chore: update tranches
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-03-18 06:06:50 +00:00
dexturr 63df4cf465 chore: update tranches
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-03-18 00:13:54 +00:00
dexturr 5e34178291 chore: update tranches
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-03-17 18:06:54 +00:00
dexturr 0c44664aa5 chore: update tranches
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-03-17 12:07:53 +00:00
Bartłomiej Głownia 7ef1d75529 chore(trading): remove red background from trades table (#3214) 2023-03-17 09:52:40 +00:00
Maciek 84795b2d6a chore(trading): split bottom panel into two parts (#3205) 2023-03-17 09:50:43 +00:00
dexturr 300019f108 chore: update tranches
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-03-17 06:09:09 +00:00
dexturr 2d0aebd3fe chore: update tranches
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-03-17 00:14:43 +00:00
dexturr 9e86d2aff5 chore: update tranches
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-03-16 18:09:41 +00:00
daro-maj 0f7e76ae01 test(trading): increase coverage for 0004-ewal (#3210) 2023-03-16 13:29:40 +01:00
dexturr 56732d1503 chore: update tranches
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-03-16 12:08:59 +00:00
Joe Tsang 5c19263653 chore(governance): include slippage factor to proposals (#3204) 2023-03-16 10:41:18 +00:00
dexturr 0d911b3029 chore: update tranches
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-03-16 06:08:43 +00:00
Matthew RussellandEdd 9f059e7862 chore(explorer,governance): update be endpoints (#3183)
Co-authored-by: Edd <edd@vega.xyz>
2023-03-15 20:12:04 -07:00
dexturr 92ea93dadb chore: update tranches
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-03-16 00:16:50 +00:00
daro-maj 6165aefad7 test(trading): fixed settlement asset displayed test (#3209) 2023-03-15 18:38:57 +00:00
dexturr c95369d914 chore: update tranches
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-03-15 18:08:52 +00:00
Maciek 5dbc5d7997 chore(trading): make loading masks in tabs consistent along the app (#3155) 2023-03-15 16:08:48 +01:00
dexturr 47b3d5b55f chore: update tranches
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-03-15 12:07:50 +00:00
Maciek da7c0b84f7 chore(trading): display latency in block height progressing as warn or error (#3169) 2023-03-15 12:49:31 +01:00
Art 67e602ebb1 feat(explorer): try again for tx details (#3195) 2023-03-15 08:24:42 +00:00
Art f407110e95 chore(environment): etherscan link (#3193) 2023-03-15 08:24:20 +00:00
Art 66a85cce2a chore(explorer): market info shared panels (#3192) 2023-03-15 08:21:12 +00:00
Art 93f8450ecb fix(utils): missing flags (#3194) 2023-03-15 08:20:41 +00:00
dexturr 0447a6cf5d chore: update tranches
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-03-15 06:09:39 +00:00
dexturr 498be838c7 chore: update tranches
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-03-15 00:17:07 +00:00
dexturr fc3b1bd9ab chore: update tranches
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-03-14 18:09:59 +00:00
Joe Tsang 090d850647 test(governance): e2e rewards (#3190) 2023-03-14 16:10:58 +00:00
Maciek 95280f5b26 chore(environment): fetch networks configuration from repo (#3145) 2023-03-14 16:02:43 +01:00
m.ray 101ae00a57 fix(trading): hide transfer button in view as mode (#3189) 2023-03-14 15:39:47 +01:00
Bartłomiej Głownia 613cce3683 feat(orders): use default filters in orders list (#3143) 2023-03-14 13:53:51 +01:00
dexturr 41fa18ed45 chore: update tranches
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-03-14 12:10:12 +00:00
Sam Keen c941893cdd fix(governance): ensure validators tables sorting on develop (#3176) 2023-03-14 09:16:12 +00:00
m.ray d049b471d8 chore(trading): mainnet sim 3 live banners (#3184) 2023-03-14 09:04:19 +00:00
m.ray 010ffc0f46 fix(trading): dropdown fix from testnet and validator-testnet (#3185) 2023-03-14 08:55:45 +00:00
dexturr dd56e4083b chore: update tranches
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-03-14 06:08:23 +00:00
dexturr 09d1ba68ba chore: update tranches
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-03-14 00:16:43 +00:00
Matthew Russell 3959daa2b7 chore(trading,explorer,governance): update validator testnet nodes (#3182) 2023-03-13 16:17:10 -07:00
Matthew Russell c599b02c89 fix(trading): add missing block explorer link for complete transfer (#3181) 2023-03-13 18:00:51 -04:00
m.ray e5ebaf02d2 fix(trading): ledger entries table formatting (#3180) 2023-03-13 19:40:08 +00:00
Matthew Russell ae54616c1f chore(trading): move banner above nav (#3161) 2023-03-13 18:38:16 +00:00
m.ray 8f3cf390c5 fix(trading): remove liquidation from positions & format price bounds with market dp (#3173) 2023-03-13 18:17:00 +00:00
m.ray 64cf0c90a7 feat(trading): clarify collateral and breakdown tables (#3113) 2023-03-13 18:15:53 +00:00
dexturr 3edd91eadb chore: update tranches
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-03-13 18:06:59 +00:00
m.ray 676aeb07a4 fix(trading): deal ticket validation on zero account balance and margin warnings (#3177) 2023-03-13 17:58:51 +00:00
dexturr 52ee998bf0 chore: update tranches
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-03-13 12:07:45 +00:00
Eddandasiaznik 727e2cd2ff fix(explorer): neaten validators mobile view (#3160)
Co-authored-by: asiaznik <artur@vegaprotocol.io>
2023-03-13 11:08:53 +00:00
dexturr 06b2dd18f9 chore: update tranches
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-03-13 06:07:23 +00:00
dexturr a189f38cdc chore: update tranches
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-03-13 00:17:26 +00:00
dexturr d18681a5f0 chore: update tranches
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-03-12 18:06:57 +00:00
dexturr 9e2d03853a chore: update tranches
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-03-12 12:07:33 +00:00
dexturr 18c36d5e6b chore: update tranches
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-03-12 06:07:33 +00:00
dexturr dcfb8f9527 chore: update tranches
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-03-12 00:16:12 +00:00
dexturr a64acecf4b chore: update tranches
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-03-11 18:06:56 +00:00
dexturr 0998952196 chore: update tranches
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-03-11 12:08:29 +00:00
dexturr 2fd4d379cf chore: update tranches
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-03-11 06:08:34 +00:00
dexturr c99d055b24 chore: update tranches
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-03-11 00:15:06 +00:00
Edd f1fa13e0bd feat(explorer): show signers in proposal multisig bundles (#3122) 2023-03-10 18:19:37 +00:00
dexturr ae020a8dca chore: update tranches
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-03-10 18:07:16 +00:00
Edd fa871a49c7 fix(explorer): format els as percentage in network param view (#3157) 2023-03-10 16:14:56 +00:00
Edd 4205dd471a fix(explorer,trading): asset details should show quantum in asset dps (#3158) 2023-03-10 16:14:36 +00:00
Eddandasiaznik 1040077c2b feat(explorer,trading,governance): update mainnet sims banner (#3156)
Co-authored-by: asiaznik <artur@vegaprotocol.io>
2023-03-10 16:12:30 +00:00
Art 9d346d7846 feat(ui-toolkit): navigation (#3069) 2023-03-10 16:46:51 +01:00
299 changed files with 11321 additions and 9540 deletions
+1 -1
View File
@@ -3,7 +3,7 @@ NX_TENDERMINT_URL=http://localhost:26617
NX_TENDERMINT_WEBSOCKET_URL=wss://localhost:26617/websocket
NX_VEGA_URL=http://localhost:3028/query
NX_VEGA_ENV=CUSTOM
NX_VEGA_CONFIG_URL=https://static.vega.xyz/assets/capsule-network.json
NX_VEGA_CONFIG_URL=
CYPRESS_VEGA_TENDERMINT_URL=http://localhost:26617
@@ -22,7 +22,6 @@
"governance.proposal.updateAsset.minProposerBalance",
"governance.proposal.updateAsset.minVoterBalance",
"governance.proposal.updateAsset.requiredParticipation",
"governance.proposal.updateMarket.minProposerEquityLikeShare",
"market.fee.factors.infrastructureFee",
"market.fee.factors.makerFee",
"market.liquidity.bondPenaltyParameter",
@@ -77,6 +76,7 @@
"governance.proposal.updateMarket.requiredParticipationLP",
"governance.proposal.updateNetParam.requiredMajority",
"governance.proposal.updateNetParam.requiredParticipation",
"governance.proposal.updateMarket.minProposerEquityLikeShare",
"validators.vote.required"
],
"duration": [
+7 -13
View File
@@ -1,33 +1,27 @@
context('Blocks page', { tags: '@regression' }, function () {
before('visit token home page', function () {
cy.visit('/');
});
describe('Verify elements on page', function () {
const blockNavigation = 'a[href="/blocks"]';
beforeEach(() => {
cy.visit('/blocks');
});
const blockHeight = '[data-testid="block-height"]';
const blockTime = '[data-testid="block-time"]';
const blockHeader = '[data-testid="block-header"]';
const previousBlockBtn = '[data-testid="previous-block"]';
const infiniteScrollWrapper = '[data-testid="infinite-scroll-wrapper"]';
beforeEach('navigate to blocks page', function () {
cy.get(blockNavigation).click();
});
it('Blocks page is displayed', function () {
validateBlocksDisplayed();
});
it('Blocks page is displayed on mobile', function () {
cy.common_switch_to_mobile_and_click_toggle();
cy.get(blockNavigation).click();
cy.switchToMobile();
validateBlocksDisplayed();
});
it('Block validator page is displayed', function () {
waitForBlocksResponse();
cy.get(blockHeight).eq(0).click();
cy.get(blockHeight).eq(0).find('a').click({ force: true });
cy.get('[data-testid="block-validator"]').should('not.be.empty');
cy.get(blockTime).should('not.be.empty');
//TODO: Add assertion for transactions when txs are added
@@ -35,7 +29,7 @@ context('Blocks page', { tags: '@regression' }, function () {
it('Navigate to previous block', function () {
waitForBlocksResponse();
cy.get(blockHeight).eq(0).click();
cy.get(blockHeight).eq(0).find('a').click({ force: true });
cy.get(blockHeader)
.invoke('text')
.then(($blockHeaderTxt) => {
+8 -87
View File
@@ -6,18 +6,10 @@ context('Home Page', function () {
describe('Stats page', { tags: '@smoke' }, function () {
const statsValue = '[data-testid="stats-value"]';
it('Should show connected environment', function () {
const deployedEnv = Cypress.env('environment').toUpperCase();
cy.get('[data-testid="stats-environment"]').should(
'have.text',
`/ ${deployedEnv}`
);
});
it('should show connected environment stats', function () {
const statTitles = {
0: 'Status',
1: 'Height',
1: 'Block height',
2: 'Uptime',
3: 'Total nodes',
4: 'Total staked',
@@ -36,27 +28,27 @@ context('Home Page', function () {
cy.get('[data-testid="stats-title"]')
.each(($list, index) => {
cy.wrap($list).should('have.text', statTitles[index]);
cy.wrap($list).should('contain.text', statTitles[index]);
})
.then(($list) => {
cy.wrap($list).should('have.length', 16);
});
cy.get(statsValue).eq(0).should('have.text', 'CONNECTED');
cy.get(statsValue).eq(0).should('contain.text', 'CONNECTED');
cy.get(statsValue).eq(1).should('not.be.empty');
cy.get(statsValue)
.eq(2)
.invoke('text')
.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('contain.text', '2');
cy.get(statsValue)
.eq(4)
.invoke('text')
.should('match', /\d+\.\d\d(?!\d)/i);
cy.get(statsValue).eq(5).should('have.text', '0');
cy.get(statsValue).eq(6).should('have.text', '0');
cy.get(statsValue).eq(7).should('have.text', '0');
cy.get(statsValue).eq(8).should('have.text', '0');
cy.get(statsValue).eq(5).should('contain.text', '0');
cy.get(statsValue).eq(6).should('contain.text', '0');
cy.get(statsValue).eq(7).should('contain.text', '0');
cy.get(statsValue).eq(8).should('contain.text', '0');
cy.get(statsValue).eq(9).should('not.be.empty');
cy.get(statsValue).eq(10).should('not.be.empty');
cy.get(statsValue).eq(11).should('not.be.empty');
@@ -86,75 +78,4 @@ context('Home Page', function () {
});
});
});
describe('Git info', function () {
it('git info is rendered on the footer of the page', function () {
cy.getByTestId('git-info').within(() => {
cy.getByTestId('git-network-data').within(() => {
cy.contains('Reading network data from').should('be.visible');
cy.get('span').should('have.text', Cypress.env('networkQueryUrl'));
cy.getByTestId('link').should('be.visible');
});
cy.getByTestId('git-eth-data').within(() => {
cy.contains('Reading Ethereum data from').should('be.visible');
cy.get('span').should('have.text', Cypress.env('ethUrl'));
});
cy.getByTestId('git-commit-hash').within(() => {
cy.contains('Version/commit hash:').should('be.visible');
cy.getByTestId('link').should('have.text', Cypress.env('commitHash'));
});
});
});
});
describe('Search bar', function () {
it('Successful search for specific id by block id', function () {
const blockId = '973624';
search(blockId);
cy.url().should('include', blockId);
});
it('Successful search for specific id by tx hash', function () {
const txHash =
'9ED3718AA8308E7E08EC588EE7AADAF49711D2138860D8914B4D81A2054D9FB8';
search(txHash);
cy.url().should('include', txHash);
});
it('Successful search for specific id by tx id', function () {
const txId =
'0x61DCCEBB955087F50D0B85382DAE138EDA9631BF1A4F92E563D528904AA38898';
search(txId);
cy.url().should('include', txId);
});
it('Error message displayed when invalid search by wrong string length', function () {
search('9ED3718AA8308E7E08EC588EE7AADAF497D2138860D8914B4D81A2054D9FB8');
validateSearchError("Something doesn't look right");
});
it('Error message displayed when invalid search by invalid hash', function () {
search(
'9ED3718AA8308E7E08ECht8EE753DAF49711D2138860D8914B4D81A2054D9FB8'
);
validateSearchError('Transaction is not hexadecimal');
});
it('Error message displayed when searching empty field', function () {
cy.get('[data-testid="search"]').clear();
cy.get('[data-testid="search-button"]').click();
validateSearchError('Search required');
});
function search(searchTxt) {
cy.get('[data-testid="search"]').clear().type(searchTxt);
cy.get('[data-testid="search-button"]').click();
}
function validateSearchError(expectedError) {
cy.get('[data-testid="search-error"]').should('have.text', expectedError);
}
});
});
@@ -2,17 +2,14 @@ context('Network parameters page', { tags: '@smoke' }, function () {
before('navigate to network parameter page', function () {
cy.fixture('net_parameter_format_lookup').as('networkParameterFormat');
});
describe('Verify elements on page', function () {
const networkParametersNavigation = 'a[href="/network-parameters"]';
beforeEach(() => {
cy.visit('/network-parameters');
});
const networkParametersHeader = '[data-testid="network-param-header"]';
const tableRows = '[data-testid="key-value-table-row"]';
before('navigate to network parameter page', function () {
cy.visit('/');
cy.get(networkParametersNavigation).click();
});
it('should show network parameter heading at top of page', function () {
cy.get(networkParametersHeader)
.should('have.text', 'Network Parameters')
@@ -201,55 +198,8 @@ context('Network parameters page', { tags: '@smoke' }, function () {
});
});
it('should be able to switch network parameter page - between light and dark mode', function () {
const whiteThemeSelectedMenuOptionColor = 'rgb(255, 7, 127)';
const whiteThemeJsonFieldBackColor = 'rgb(255, 255, 255)';
const whiteThemeSideMenuBackgroundColor = 'rgb(255, 255, 255)';
const darkThemeSelectedMenuOptionColor = 'rgb(215, 251, 80)';
const darkThemeJsonFieldBackColor = 'rgb(38, 38, 38)';
const darkThemeSideMenuBackgroundColor = 'rgb(0, 0, 0)';
const themeSwitcher = '[data-testid="theme-switcher"]';
const jsonFields = '.hljs';
const sideMenuBackground = '.absolute';
// Engage dark mode if not already set
cy.get(sideMenuBackground)
.should('have.css', 'background-color')
.then((background_color) => {
if (background_color.includes(whiteThemeSideMenuBackgroundColor))
cy.get(themeSwitcher).click();
});
// Engage white mode
cy.get(themeSwitcher).click();
// White Mode
cy.get(networkParametersNavigation)
.should('have.css', 'background-color')
.and('include', whiteThemeSelectedMenuOptionColor);
cy.get(jsonFields)
.should('have.css', 'background-color')
.and('include', whiteThemeJsonFieldBackColor);
cy.get(sideMenuBackground)
.should('have.css', 'background-color')
.and('include', whiteThemeSideMenuBackgroundColor);
// Dark Mode
cy.get(themeSwitcher).click();
cy.get(networkParametersNavigation)
.should('have.css', 'background-color')
.and('include', darkThemeSelectedMenuOptionColor);
cy.get(jsonFields)
.should('have.css', 'background-color')
.and('include', darkThemeJsonFieldBackColor);
cy.get(sideMenuBackground)
.should('have.css', 'background-color')
.and('include', darkThemeSideMenuBackgroundColor);
});
it.skip('should be able to see network parameters - on mobile', function () {
cy.common_switch_to_mobile_and_click_toggle();
cy.get(networkParametersNavigation).click();
it('should be able to see network parameters - on mobile', function () {
cy.switchToMobile();
cy.get_network_parameters().then((network_parameters) => {
network_parameters = Object.entries(network_parameters);
network_parameters.forEach((network_parameter) => {
+1 -1
View File
@@ -1,6 +1,6 @@
NX_TENDERMINT_URL=https://tm.n00.stagnet3.vega.xyz
NX_TENDERMINT_WEBSOCKET_URL=wss://tm.n00.stagnet3.vega.xyz/websocket
NX_VEGA_CONFIG_URL=https://static.vega.xyz/assets/stagnet3-network.json
NX_VEGA_CONFIG_URL=https://raw.githubusercontent.com/vegaprotocol/networks-internal/main/stagnet3/vegawallet-stagnet3.toml
NX_VEGA_NETWORKS='{"SANDBOX":"https://sandbox.explorer.vega.xyz","STAGNET1":"https://stagnet1.token.vega.xyz", "STAGNET3":"https://stagnet3.explorer.vega.xyz","VALIDATOR_TESTNET":"https://validator-testnet.fairground.wtf","TESTNET":"https://token.fairground.wtf","MAINNET":"https://token.vega.xyz"}'
NX_VEGA_ENV=STAGNET3
NX_GITHUB_FEEDBACK_URL=https://github.com/vegaprotocol/feedback/discussions
+2 -2
View File
@@ -1,10 +1,10 @@
# App configuration variables
NX_TENDERMINT_URL=https://tm.be.devnet1.vega.xyz/tm
NX_TENDERMINT_WEBSOCKET_URL=wss://be.devnet1.vega.xyz/websocket
NX_VEGA_CONFIG_URL=https://static.vega.xyz/assets/devnet-network.json
NX_VEGA_CONFIG_URL=https://raw.githubusercontent.com/vegaprotocol/networks-internal/main/devnet1/vegawallet-devnet1.toml
NX_VEGA_ENV=DEVNET
NX_BLOCK_EXPLORER=https://be.devnet1.vega.xyz/rest
NX_ETHERSCAN_URL=https://sepolia.etherscan.io
NX_VEGA_GOVERNANCE_URL=https://dev.token.vega.xyz
NX_VEGA_URL=https://api.devnet1.vega.xyz/graphql
NX_VEGA_CONFIG_URL=https://static.vega.xyz/assets/devnet1-network.json
NX_VEGA_CONFIG_URL=https://raw.githubusercontent.com/vegaprotocol/networks-internal/main/devnet1/vegawallet-devnet1.toml
+2 -2
View File
@@ -1,8 +1,8 @@
# App configuration variables
NX_TENDERMINT_URL=https://be.explorer.vega.xyz
NX_TENDERMINT_WEBSOCKET_URL=wss://be.explorer.vega.xyz/websocket
NX_VEGA_CONFIG_URL=https://static.vega.xyz/assets/mainnet-network.json
NX_VEGA_CONFIG_URL=https://raw.githubusercontent.com/vegaprotocol/networks/master/mainnet1/mainnet1.toml
NX_VEGA_ENV=MAINNET
NX_BLOCK_EXPLORER=https://be.explorer.vega.xyz/rest/
NX_ETHERSCAN_URL=https://etherscan.io
NX_VEGA_GOVERNANCE_URL=https://token.vega.xyz
NX_VEGA_GOVERNANCE_URL=https://token.vega.xyz
+1 -1
View File
@@ -1,7 +1,7 @@
# App configuration variables
NX_TENDERMINT_URL=https://tm.be.mainnet-mirror.vega.xyz
NX_TENDERMINT_WEBSOCKET_URL=wss://be.mainnet-mirror.vega.xyz/websocket
NX_VEGA_CONFIG_URL=https://static.vega.xyz/assets/mirror-network.json
NX_VEGA_CONFIG_URL=https://raw.githubusercontent.com/vegaprotocol/networks-internal/main/mainnet-mirror/vegawallet-mainnet-mirror.toml
NX_VEGA_ENV=MIRROR
NX_BLOCK_EXPLORER=https://be.mainnet-mirror.vega.xyz/rest/
NX_ETHERSCAN_URL=https://sepolia.etherscan.io
+1 -1
View File
@@ -1,6 +1,6 @@
# App configuration variables
NX_VEGA_ENV=SANDBOX
NX_VEGA_CONFIG_URL=https://static.vega.xyz/assets/sandbox-network.json
NX_VEGA_CONFIG_URL=https://raw.githubusercontent.com/vegaprotocol/networks-internal/main/sandbox/vegawallet-sandbox.toml
NX_VEGA_EXPLORER_URL=https://sandbox.explorer.vega.xyz
NX_VEGA_DOCS_URL=https://docs.vega.xyz/testnet
NX_ETHEREUM_PROVIDER_URL=https://sepolia.infura.io/v3/4f846e79e13f44d1b51bbd7ed9edefb8
+1 -1
View File
@@ -1,7 +1,7 @@
NX_ETHEREUM_PROVIDER_URL=https://sepolia.infura.io/v3/4f846e79e13f44d1b51bbd7ed9edefb8
NX_ETHERSCAN_URL=https://sepolia.etherscan.io
NX_HOSTED_WALLET_URL=https://wallet.testnet.vega.xyz
NX_VEGA_CONFIG_URL=https://static.vega.xyz/assets/stagnet1-network.json
NX_VEGA_CONFIG_URL=https://raw.githubusercontent.com/vegaprotocol/networks-internal/main/stagnet1/vegawallet-stagnet1.toml
NX_VEGA_ENV=STAGNET1
NX_VEGA_EXPLORER_URL=https://stagnet1.explorer.vega.xyz
NX_VEGA_TOKEN_URL=https://stagnet1.token.vega.xyz
+1 -1
View File
@@ -1,6 +1,6 @@
NX_TENDERMINT_URL=https://tm.n00.stagnet3.vega.xyz
NX_TENDERMINT_WEBSOCKET_URL=wss://be.stagnet3.vega.xyz/websocket
NX_VEGA_CONFIG_URL=https://static.vega.xyz/assets/stagnet3-network.json
NX_VEGA_CONFIG_URL=https://raw.githubusercontent.com/vegaprotocol/networks-internal/main/stagnet3/vegawallet-stagnet3.toml
NX_VEGA_ENV=STAGNET3
NX_BLOCK_EXPLORER=https://be.stagnet3.vega.xyz/rest
NX_VEGA_GOVERNANCE_URL=https://stagnet3.token.vega.xyz
+2 -2
View File
@@ -2,9 +2,9 @@
NX_TENDERMINT_URL=https://tm.be.testnet.vega.xyz
NX_BLOCK_EXPLORER=https://be.testnet.vega.xyz/rest
NX_TENDERMINT_WEBSOCKET_URL=wss://be.testnet.vega.xyz/websocket
NX_VEGA_CONFIG_URL=https://static.vega.xyz/assets/testnet-network.json
NX_VEGA_CONFIG_URL=https://raw.githubusercontent.com/vegaprotocol/networks-internal/main/fairground/vegawallet-fairground.toml
NX_VEGA_ENV=TESTNET
NX_VEGA_URL=https://api.n07.testnet.vega.xyz/graphql
NX_HOSTED_WALLET_URL=https://wallet.testnet.vega.xyz
NX_ETHERSCAN_URL=https://sepolia.etherscan.io
NX_VEGA_GOVERNANCE_URL=https://token.fairground.wtf
NX_VEGA_GOVERNANCE_URL=https://token.fairground.wtf
+5 -5
View File
@@ -1,12 +1,12 @@
# App configuration variables
NX_VEGA_ENV=VALIDATOR_TESTNET
NX_VEGA_CONFIG_URL=https://static.vega.xyz/assets/validator-testnet-network.json
NX_VEGA_URL=https://api.validators-testnet.vega.xyz/graphql
NX_VEGA_REST=https://api.validators-testnet.vega.xyz/
NX_VEGA_CONFIG_URL=https://raw.githubusercontent.com/vegaprotocol/networks/master/testnet2/testnet2.toml
NX_VEGA_URL=https://api-validators-testnet.vega.rocks/graphql
NX_VEGA_REST=https://api-validators-testnet.vega.rocks/
NX_ETHEREUM_PROVIDER_URL=https://sepolia.infura.io/v3/4f846e79e13f44d1b51bbd7ed9edefb8
NX_ETHERSCAN_URL=https://sepolia.etherscan.io
NX_VEGA_GOVERNANCE_URL=https://validator-testnet.governance.vega.xyz
NX_TENDERMINT_URL=https://tm.be.validators-testnet.vega.xyz
NX_BLOCK_EXPLORER=https://be.validators-testnet.vega.xyz/rest
NX_TENDERMINT_URL=https://tm-be.validators-testnet.vega.rocks
NX_BLOCK_EXPLORER=https://be.validators-testnet.vega.rocks/
NX_TENDERMINT_WEBSOCKET_URL=wss://be.validators-testnet.vega.xyz/websocket
+9 -48
View File
@@ -1,60 +1,21 @@
import classnames from 'classnames';
import { NetworkLoader, useInitializeEnv } from '@vegaprotocol/environment';
import { Nav } from './components/nav';
import { Header } from './components/header';
import { Main } from './components/main';
import { TendermintWebsocketProvider } from './contexts/websocket/tendermint-websocket-provider';
import { Footer } from './components/footer/footer';
import { AnnouncementBanner, ExternalLink } from '@vegaprotocol/ui-toolkit';
import {
AssetDetailsDialog,
useAssetDetailsDialogStore,
} from '@vegaprotocol/assets';
import { Loader, Splash } from '@vegaprotocol/ui-toolkit';
import { DEFAULT_CACHE_CONFIG } from '@vegaprotocol/apollo-client';
import { RouterProvider } from 'react-router-dom';
import { router } from './routes/router-config';
const DialogsContainer = () => {
const { isOpen, id, trigger, asJson, setOpen } = useAssetDetailsDialogStore();
return (
<AssetDetailsDialog
assetId={id}
trigger={trigger || null}
asJson={asJson}
open={isOpen}
onChange={setOpen}
/>
);
};
const splashLoading = (
<Splash>
<Loader />
</Splash>
);
function App() {
const layoutClasses = classnames(
'grid grid-rows-[auto_1fr_auto] grid-cols-[1fr] md:grid-rows-[auto_minmax(700px,_1fr)_auto] md:grid-cols-[300px_1fr]',
'min-h-[100vh] mx-auto my-0',
'border-neutral-700 dark:border-neutral-300 lg:border-l lg:border-r',
'bg-white dark:bg-black',
'antialiased text-black dark:text-white',
'overflow-hidden relative'
);
return (
<TendermintWebsocketProvider>
<NetworkLoader cache={DEFAULT_CACHE_CONFIG}>
<AnnouncementBanner>
<div className="font-alpha calt uppercase text-center text-lg text-white">
<span className="pr-4">Mainnet sim 2 is live!</span>
<ExternalLink href="https://fairground.wtf/">
Come help stress test the network
</ExternalLink>
</div>
</AnnouncementBanner>
<div className={layoutClasses}>
<Header />
<Nav />
<Main />
<Footer />
</div>
<DialogsContainer />
<RouterProvider router={router} fallbackElement={splashLoading} />
</NetworkLoader>
</TendermintWebsocketProvider>
);
@@ -10,13 +10,13 @@ export const Footer = () => {
const [nodeSwitcherOpen, setNodeSwitcherOpen] = useState(false);
const { screenSize } = useScreenDimensions();
const showFullFeedbackLabel = useMemo(
() => ['lg', 'xl'].includes(screenSize),
() => ['lg', 'xl', 'xxl', 'xxxl'].includes(screenSize),
[screenSize]
);
return (
<>
<footer className="grid grid-rows-2 grid-cols-[1fr_auto] text-xs md:text-md md:flex md:col-span-2 px-4 py-2 gap-4 border-t border-neutral-700 dark:border-neutral-300">
<footer className="grid grid-rows-2 grid-cols-[1fr_auto] text-xs md:text-md md:flex md:col-span-2 px-4 py-2 gap-4 border-t border-vega-light-200 dark:border-vega-dark-200">
<div className="flex justify-between gap-2 align-middle">
{GIT_COMMIT_HASH && (
<div className="content-center flex border-r border-neutral-700 dark:border-neutral-300 pr-4">
@@ -13,19 +13,18 @@ jest.mock('../search', () => ({
}));
const renderComponent = () => (
<MemoryRouter>
<MemoryRouter initialEntries={['/txs']}>
<Header />
</MemoryRouter>
);
describe('Header', () => {
it('should render heading', () => {
it('should render navigation', () => {
render(renderComponent());
expect(screen.getByTestId('explorer-header')).toHaveTextContent(
'Vega Explorer'
);
expect(screen.getByTestId('navigation')).toHaveTextContent('Explorer');
});
it('should render search', () => {
render(renderComponent());
@@ -1,43 +1,111 @@
import classnames from 'classnames';
import { Link } from 'react-router-dom';
import { ThemeSwitcher, Icon } from '@vegaprotocol/ui-toolkit';
import { matchPath, useLocation, useMatch } from 'react-router-dom';
import {
ThemeSwitcher,
Navigation,
NavigationList,
NavigationItem,
NavigationLink,
NavigationBreakpoint,
NavigationTrigger,
NavigationContent,
} from '@vegaprotocol/ui-toolkit';
import { t } from '@vegaprotocol/i18n';
import { Search } from '../search';
import { Routes } from '../../routes/route-names';
import { NetworkSwitcher } from '@vegaprotocol/environment';
import { useNavStore } from '../nav';
import type { Navigable } from '../../routes/router-config';
import { isNavigable } from '../../routes/router-config';
import { routerConfig } from '../../routes/router-config';
import { useMemo } from 'react';
import compact from 'lodash/compact';
import { Search } from '../search';
const routeToNavigationItem = (r: Navigable) => (
<NavigationItem key={r.handle.name}>
<NavigationLink to={r.path}>{r.handle.text}</NavigationLink>
</NavigationItem>
);
export const Header = () => {
const [open, toggle] = useNavStore((state) => [state.open, state.toggle]);
const headerClasses = classnames(
'md:col-span-2',
'grid grid-rows-2 md:grid-rows-1 grid-cols-[1fr_auto] md:grid-cols-[auto_1fr_auto] items-center',
'p-4 gap-2 md:gap-4',
'border-b border-neutral-700 dark:border-neutral-300 bg-black',
'dark text-white'
);
const isHome = Boolean(useMatch(Routes.HOME));
const pages = routerConfig[0].children || [];
const mainItems = compact(
[Routes.TX, Routes.BLOCKS, Routes.ORACLES, Routes.VALIDATORS].map((n) =>
pages.find((r) => r.path === n)
)
).filter(isNavigable);
const groupedItems = compact(
[
Routes.PARTIES,
Routes.ASSETS,
Routes.MARKETS,
Routes.GOVERNANCE,
Routes.NETWORK_PARAMETERS,
Routes.GENESIS,
].map((n) => pages.find((r) => r.path === n))
).filter(isNavigable);
const { pathname } = useLocation();
/**
* Because the grouped items are displayed in a sub menu under an "Other" item
* we need to determine whether any underlying item is active to highlight the
* trigger in the same fashion as any other top-level `NavigationLink`.
* This function checks whether the current location pathname is one of the
* underlying NavigationLinks.
*/
const isOnOther = useMemo(() => {
for (const path of groupedItems.map((r) => r.path)) {
const matched = matchPath(`${path}/*`, pathname);
if (matched) return true;
}
return false;
}, [groupedItems, pathname]);
return (
<header className={headerClasses}>
<div className="flex h-full items-center sm:items-stretch gap-4">
<Link to={Routes.HOME}>
<h1
className="text-white text-3xl font-alpha uppercase calt mb-0"
data-testid="explorer-header"
>
{t('Vega Explorer')}
</h1>
</Link>
<NetworkSwitcher />
</div>
<button
data-testid="open-menu"
className="md:hidden text-white"
onClick={() => toggle()}
<Navigation
appName="Explorer"
theme="system"
breakpoints={[490, 900]}
actions={
<>
<ThemeSwitcher />
{!isHome && <Search />}
</>
}
onResize={(width, el) => {
if (width < 1157) {
// switch to magnifying glass trigger when width < 1157
el.classList.remove('nav-search-full');
el.classList.add('nav-search-compact');
} else {
el.classList.remove('nav-search-compact');
el.classList.add('nav-search-full');
}
}}
>
<NavigationList hide={[NavigationBreakpoint.Small]}>
<NavigationItem>
<NetworkSwitcher />
</NavigationItem>
</NavigationList>
<NavigationList
hide={[NavigationBreakpoint.Small, NavigationBreakpoint.Narrow]}
>
<Icon name={open ? 'cross' : 'menu'} />
</button>
<Search />
<ThemeSwitcher className="-my-4" />
</header>
{mainItems.map(routeToNavigationItem)}
{groupedItems && groupedItems.length > 0 && (
<NavigationItem>
<NavigationTrigger isActive={Boolean(isOnOther)}>
{t('Other')}
</NavigationTrigger>
<NavigationContent>
<NavigationList>
{groupedItems.map(routeToNavigationItem)}
</NavigationList>
</NavigationContent>
</NavigationItem>
)}
</NavigationList>
</Navigation>
);
};
@@ -1,9 +0,0 @@
import { AppRouter } from '../../routes';
export const Main = () => {
return (
<main className="p-4">
<AppRouter />
</main>
);
};
@@ -1,143 +1,52 @@
import {
addDecimalsFormatNumber,
formatNumberPercentage,
getMarketExpiryDateFormatted,
} from '@vegaprotocol/utils';
import { t } from '@vegaprotocol/i18n';
import type { MarketInfoWithData } from '@vegaprotocol/market-info';
import { MarketInfoTable } from '@vegaprotocol/market-info';
import { LiquidityInfoPanel } from '@vegaprotocol/market-info';
import { LiquidityMonitoringParametersInfoPanel } from '@vegaprotocol/market-info';
import {
MarketStateMapping,
MarketTradingModeMapping,
} from '@vegaprotocol/types';
import { AssetDetailsTable, useAssetDataProvider } from '@vegaprotocol/assets';
import { Splash } from '@vegaprotocol/ui-toolkit';
import BigNumber from 'bignumber.js';
import { useMemo } from 'react';
InstrumentInfoPanel,
KeyDetailsInfoPanel,
LiquidityPriceRangeInfoPanel,
MetadataInfoPanel,
OracleInfoPanel,
RiskFactorsInfoPanel,
RiskModelInfoPanel,
RiskParametersInfoPanel,
SettlementAssetInfoPanel,
} from '@vegaprotocol/market-info';
import { MarketInfoTable } from '@vegaprotocol/market-info';
import { Link } from 'react-router-dom';
export const MarketDetails = ({ market }: { market: MarketInfoWithData }) => {
const quoteUnit = market?.tradableInstrument.instrument.product.quoteName;
const assetId = useMemo(
() => market?.tradableInstrument.instrument.product?.settlementAsset.id,
[market]
);
const { data: asset } = useAssetDataProvider(assetId ?? '');
if (!market) return null;
const keyDetails = {
decimalPlaces: market.decimalPlaces,
positionDecimalPlaces: market.positionDecimalPlaces,
tradingMode: market.tradingMode,
state: MarketStateMapping[market.state],
};
const assetDecimals =
market.tradableInstrument.instrument.product.settlementAsset.decimals;
const liquidityPriceRange = formatNumberPercentage(
new BigNumber(market.lpPriceRange).times(100)
);
const panels = [
{
title: t('Key details'),
content: (
<MarketInfoTable
noBorder={false}
data={{
name: market.tradableInstrument.instrument.name,
marketID: market.id,
tradingMode:
keyDetails.tradingMode &&
MarketTradingModeMapping[keyDetails.tradingMode],
marketDecimalPlaces: market.decimalPlaces,
positionDecimalPlaces: market.positionDecimalPlaces,
settlementAssetDecimalPlaces: assetDecimals,
}}
/>
),
content: <KeyDetailsInfoPanel noBorder={false} market={market} />,
},
{
title: t('Instrument'),
content: (
<MarketInfoTable
noBorder={false}
data={{
marketName: market.tradableInstrument.instrument.name,
code: market.tradableInstrument.instrument.code,
productType:
market.tradableInstrument.instrument.product.__typename,
...market.tradableInstrument.instrument.product,
}}
/>
),
content: <InstrumentInfoPanel noBorder={false} market={market} />,
},
{
title: t('Settlement asset'),
content: asset ? (
<AssetDetailsTable
asset={asset}
inline={true}
noBorder={false}
dtClassName="text-black dark:text-white text-ui !px-0 !font-normal"
ddClassName="text-black dark:text-white text-ui !px-0 !font-normal max-w-full"
/>
) : (
<Splash>{t('No data')}</Splash>
),
content: <SettlementAssetInfoPanel market={market} noBorder={false} />,
},
{
title: t('Metadata'),
content: (
<MarketInfoTable
noBorder={false}
data={{
expiryDate: getMarketExpiryDateFormatted(
market.tradableInstrument.instrument.metadata.tags
),
...market.tradableInstrument.instrument.metadata.tags
?.map((tag) => {
const [key, value] = tag.split(':');
return { [key]: value };
})
.reduce((acc, curr) => ({ ...acc, ...curr }), {}),
}}
/>
),
content: <MetadataInfoPanel noBorder={false} market={market} />,
},
{
title: t('Risk model'),
content: (
<MarketInfoTable
noBorder={false}
data={market.tradableInstrument.riskModel}
unformatted={true}
omits={[]}
/>
),
content: <RiskModelInfoPanel noBorder={false} market={market} />,
},
{
title: t('Risk parameters'),
content: (
<MarketInfoTable
noBorder={false}
data={market.tradableInstrument.riskModel.params}
unformatted={true}
omits={[]}
/>
),
content: <RiskParametersInfoPanel noBorder={false} market={market} />,
},
{
title: t('Risk factors'),
content: (
<MarketInfoTable
noBorder={false}
data={market.riskFactors}
unformatted={true}
omits={['market', '__typename']}
/>
),
content: <RiskFactorsInfoPanel noBorder={false} market={market} />,
},
...(market.priceMonitoringSettings?.parameters?.triggers || []).map(
(trigger, i) => ({
@@ -158,7 +67,10 @@ export const MarketDetails = ({ market }: { market: MarketInfoWithData }) => {
<MarketInfoTable
noBorder={false}
data={{ referencePrice: trigger.referencePrice }}
decimalPlaces={assetDecimals}
decimalPlaces={
market.tradableInstrument.instrument.product.settlementAsset
.decimals
}
/>
</>
),
@@ -166,64 +78,26 @@ export const MarketDetails = ({ market }: { market: MarketInfoWithData }) => {
{
title: t('Liquidity monitoring parameters'),
content: (
<MarketInfoTable
<LiquidityMonitoringParametersInfoPanel
noBorder={false}
data={{
triggeringRatio:
market.liquidityMonitoringParameters.triggeringRatio,
...market.liquidityMonitoringParameters.targetStakeParameters,
}}
market={market}
/>
),
},
{
title: t('Liquidity'),
content: <LiquidityInfoPanel market={market} noBorder={false} />,
},
{
title: t('Liquidity price range'),
content: (
<>
<p className="text-xs mb-4">
{`For liquidity orders to count towards a commitment, they must be
within the liquidity monitoring bounds.`}
</p>
<p className="text-xs mb-4">
{`The liquidity price range is a ${liquidityPriceRange} difference from the mid
price.`}
</p>
<MarketInfoTable
noBorder={false}
data={{
liquidityPriceRange: `${liquidityPriceRange} of mid price`,
lowestPrice:
market.data?.midPrice &&
`${addDecimalsFormatNumber(
new BigNumber(1)
.minus(market.lpPriceRange)
.times(market.data.midPrice)
.toString(),
market.decimalPlaces
)} ${quoteUnit}`,
highestPrice:
market.data?.midPrice &&
`${addDecimalsFormatNumber(
new BigNumber(1)
.plus(market.lpPriceRange)
.times(market.data.midPrice)
.toString(),
market.decimalPlaces
)} ${quoteUnit}`,
}}
></MarketInfoTable>
</>
<LiquidityPriceRangeInfoPanel market={market} noBorder={false} />
),
},
{
title: t('Oracle'),
content: (
<MarketInfoTable
noBorder={false}
data={
market.tradableInstrument.instrument.product.dataSourceSpecBinding
}
>
<OracleInfoPanel noBorder={false} market={market}>
<Link
className="text-xs hover:underline"
to={`/oracles#${market.tradableInstrument.instrument.product.dataSourceSpecForSettlementData.id}`}
@@ -236,7 +110,7 @@ export const MarketDetails = ({ market }: { market: MarketInfoWithData }) => {
>
{t('View termination oracle specification')}
</Link>
</MarketInfoTable>
</OracleInfoPanel>
),
},
];
@@ -244,7 +118,7 @@ export const MarketDetails = ({ market }: { market: MarketInfoWithData }) => {
return (
<>
{panels.map((p) => (
<div className="mb-3">
<div key={p.title} className="mb-3">
<h2 className="font-alpha calt text-xl">{p.title}</h2>
{p.content}
</div>
@@ -1 +0,0 @@
export * from './nav';
@@ -1,181 +0,0 @@
import { NavLink, useLocation } from 'react-router-dom';
import type { Navigable } from '../../routes/router-config';
import routerConfig from '../../routes/router-config';
import classnames from 'classnames';
import { create } from 'zustand';
import {
useCallback,
useEffect,
useLayoutEffect,
useMemo,
useRef,
} from 'react';
import { Icon } from '@vegaprotocol/ui-toolkit';
import first from 'lodash/first';
import last from 'lodash/last';
import { BREAKPOINT_MD } from '../../config/breakpoints';
type NavStore = {
open: boolean;
toggle: () => void;
hide: () => void;
};
export const useNavStore = create<NavStore>()((set, get) => ({
open: false,
toggle: () => set({ open: !get().open }),
hide: () => set({ open: false }),
}));
const NavLinks = ({ links }: { links: Navigable[] }) => {
const navLinks = links.map((r) => (
<li key={r.name}>
<NavLink
to={r.path}
className={({ isActive }) =>
classnames(
'block mb-2 px-2',
'text-lg hover:bg-vega-pink dark:hover:bg-vega-yellow hover:text-white dark:hover:text-black',
{
'bg-vega-pink text-white dark:bg-vega-yellow dark:text-black':
isActive,
}
)
}
>
{r.text}
</NavLink>
</li>
));
return <ul className="pr-8 md:pr-0">{navLinks}</ul>;
};
export const Nav = () => {
const [open, hide] = useNavStore((state) => [state.open, state.hide]);
const location = useLocation();
const navRef = useRef<HTMLElement>(null);
const btnRef = useRef<HTMLButtonElement>(null);
const focusable = useMemo(
() =>
navRef.current
? [
...(navRef.current.querySelectorAll(
'a, button'
) as NodeListOf<HTMLElement>),
]
: [],
// eslint-disable-next-line react-hooks/exhaustive-deps
[navRef.current] // do not remove `navRef.current` from deps
);
const closeNav = useCallback(() => {
hide();
console.log(focusable);
focusable.forEach((fe) =>
fe.setAttribute(
'tabindex',
window.innerWidth > BREAKPOINT_MD ? '0' : '-1'
)
);
}, [focusable, hide]);
// close navigation when location changes
useEffect(() => {
closeNav();
}, [closeNav, location]);
useLayoutEffect(() => {
if (open) {
focusable.forEach((fe) => fe.setAttribute('tabindex', '0'));
}
document.body.style.overflow = open ? 'hidden' : '';
const offset =
document.querySelector('header')?.getBoundingClientRect().top || 0;
if (navRef.current) {
navRef.current.style.height = `calc(100vh - ${offset}px)`;
}
// focus current by default
if (navRef.current && open) {
(navRef.current.querySelector('a[aria-current]') as HTMLElement)?.focus();
}
const closeOnEsc = (e: KeyboardEvent) => {
if (e.key === 'Escape') {
closeNav();
}
};
// tabbing loop
const focusLast = (e: FocusEvent) => {
e.preventDefault();
const isNavElement =
e.relatedTarget && navRef.current?.contains(e.relatedTarget as Node);
if (!isNavElement && open) {
last(focusable)?.focus();
}
};
const focusFirst = (e: FocusEvent) => {
e.preventDefault();
const isNavElement =
e.relatedTarget && navRef.current?.contains(e.relatedTarget as Node);
if (!isNavElement && open) {
first(focusable)?.focus();
}
};
const resetOnDesktop = () => {
focusable.forEach((fe) =>
fe.setAttribute(
'tabindex',
window.innerWidth > BREAKPOINT_MD ? '0' : '-1'
)
);
};
window.addEventListener('resize', resetOnDesktop);
first(focusable)?.addEventListener('focusout', focusLast);
last(focusable)?.addEventListener('focusout', focusFirst);
document.addEventListener('keydown', closeOnEsc);
return () => {
window.removeEventListener('resize', resetOnDesktop);
document.removeEventListener('keydown', closeOnEsc);
first(focusable)?.removeEventListener('focusout', focusLast);
last(focusable)?.removeEventListener('focusout', focusFirst);
};
}, [closeNav, focusable, open]);
return (
<nav
ref={navRef}
className={classnames(
'absolute top-0 z-20 overflow-y-auto',
'transition-[right]',
{
'right-[-200vw] h-full': !open,
'right-0 h-[100vh]': open,
},
'w-full p-4 border-neutral-700 dark:border-neutral-300',
'bg-white dark:bg-black',
'md:static md:border-r'
)}
>
<NavLinks links={routerConfig} />
<button
ref={btnRef}
className="absolute top-0 right-0 p-4 md:hidden"
onClick={() => {
closeNav();
}}
>
<Icon name="cross" />
</button>
</nav>
);
};
@@ -1,4 +1,5 @@
import { t } from '@vegaprotocol/i18n';
import { Button } from '@vegaprotocol/ui-toolkit';
import { StatusMessage } from '../status-message';
interface RenderFetchedProps {
@@ -7,6 +8,7 @@ interface RenderFetchedProps {
loading: boolean | undefined;
className?: string;
errorMessage?: string;
refetch?: () => void;
}
export const RenderFetched = ({
@@ -15,6 +17,7 @@ export const RenderFetched = ({
children,
className,
errorMessage = t('Error retrieving data'),
refetch,
}: RenderFetchedProps) => {
if (loading) {
return (
@@ -23,7 +26,20 @@ export const RenderFetched = ({
}
if (error) {
return <StatusMessage className={className}>{errorMessage}</StatusMessage>;
return (
<>
<StatusMessage className={className}>{errorMessage}</StatusMessage>
{refetch && (
<Button
onClick={() => {
refetch();
}}
>
{t('Try again')}
</Button>
)}
</>
);
}
return children;
@@ -1,32 +0,0 @@
import { t } from '@vegaprotocol/i18n';
import React from 'react';
interface RouteErrorBoundaryProps {
children: React.ReactElement;
}
export class RouteErrorBoundary extends React.Component<
RouteErrorBoundaryProps,
{ hasError: boolean }
> {
constructor(props: RouteErrorBoundaryProps) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError() {
return { hasError: true };
}
override componentDidCatch(error: Error) {
console.log(`Error caught in App error boundary ${error.message}`, error);
}
override render() {
if (this.state.hasError) {
return <h1>{t('Something went wrong')}</h1>;
}
return this.props.children;
}
}
@@ -1,189 +1,70 @@
import {
detectTypeByFetching,
detectTypeFromQuery,
getSearchType,
determineType,
isBlock,
isHexadecimal,
isNetworkParty,
isNonHex,
SearchTypes,
toHex,
toNonHex,
isHash,
} from './detect-search';
import { DATA_SOURCES } from '../../config';
global.fetch = jest.fn();
describe('Detect Search', () => {
it("should detect that it's a hexadecimal", () => {
const expected = true;
const testString =
'0x073ceaab59e5f2dd0561dec4883e7ee5bc7165cd4de34717a3ab8f2cbe3007f9';
const actual = isHexadecimal(testString);
expect(actual).toBe(expected);
});
it("should detect that it's not hexadecimal", () => {
const expected = true;
const testString =
'073ceaab59e5f2dd0561dec4883e7ee5bc7165cd4de34717a3ab8f2cbe3007f9';
const actual = isNonHex(testString);
expect(actual).toBe(expected);
it.each([
['0000000000000000000000000000000000000000000000000000000000000000', true],
['0000000000000000000000000000000000000000000000000000000000000001', true],
[
'LOOONG0000000000000000000000000000000000000000000000000000000000000000',
false,
],
['xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', false],
['something else', false],
])("should detect that it's a hash", (input, expected) => {
expect(isHash(input)).toBe(expected);
});
it("should detect that it's a network party", () => {
const expected = true;
const testString = 'network';
const actual = isNetworkParty(testString);
expect(actual).toBe(expected);
expect(isNetworkParty('network')).toBe(true);
expect(isNetworkParty('web')).toBe(false);
});
it("should detect that it's a block", () => {
const expected = true;
const testString = '3188';
const actual = isBlock(testString);
expect(actual).toBe(expected);
expect(isBlock('123')).toBe(true);
expect(isBlock('x123')).toBe(false);
});
it('should convert from non-hex to hex', () => {
const expected = '0x123';
const testString = '123';
const actual = toHex(testString);
expect(actual).toBe(expected);
});
it('should convert from hex to non-hex', () => {
const expected = '123';
const testString = '0x123';
const actual = toNonHex(testString);
expect(actual).toBe(expected);
});
it("should detect type client side from query if it's a hexadecimal", () => {
const expected = [SearchTypes.Party, SearchTypes.Transaction];
const testString =
'0x4624293CFE3D8B67A0AB448BAFF8FBCF1A1B770D9D5F263761D3D6CBEA94D97F';
const actual = detectTypeFromQuery(testString);
expect(actual).toStrictEqual(expected);
});
it("should detect type client side from query if it's a non hex", () => {
const expected = [SearchTypes.Party, SearchTypes.Transaction];
const testString =
'4624293CFE3D8B67A0AB448BAFF8FBCF1A1B770D9D5F263761D3D6CBEA94D97F';
const actual = detectTypeFromQuery(testString);
expect(actual).toStrictEqual(expected);
});
it("should detect type client side from query if it's a network party", () => {
const expected = [SearchTypes.Party];
const testString = 'network';
const actual = detectTypeFromQuery(testString);
expect(actual).toStrictEqual(expected);
});
it("should detect type client side from query if it's a block (number)", () => {
const expected = [SearchTypes.Block];
const testString = '23432';
const actual = detectTypeFromQuery(testString);
expect(actual).toStrictEqual(expected);
});
it("detectTypeByFetching should call fetch with non-hex query it's a transaction", async () => {
const query = '0xabc';
const type = SearchTypes.Transaction;
// @ts-ignore issue related to polyfill
fetch.mockImplementation(
jest.fn(() =>
Promise.resolve({
ok: true,
json: () =>
Promise.resolve({
transaction: {
hash: query,
},
}),
})
)
);
const result = await detectTypeByFetching(query);
expect(fetch).toHaveBeenCalledWith(
`${DATA_SOURCES.blockExplorerUrl}/transactions/${toNonHex(query)}`
);
expect(result).toBe(type);
});
it("detectTypeByFetching should call fetch with non-hex query it's a party", async () => {
const query = 'abc';
const type = SearchTypes.Party;
// @ts-ignore issue related to polyfill
fetch.mockImplementation(
jest.fn(() =>
Promise.resolve({
ok: false,
})
)
);
const result = await detectTypeByFetching(query);
expect(result).toBe(type);
});
it('getSearchType should return party from fetch response', async () => {
const query =
'0x4624293CFE3D8B67A0AB448BAFF8FBCF1A1B770D9D5F263761D3D6CBEA94D97F';
const expected = SearchTypes.Party;
// @ts-ignore issue related to polyfill
fetch.mockImplementation(
jest.fn(() =>
Promise.resolve({
ok: false,
})
)
);
const result = await getSearchType(query);
expect(result).toBe(expected);
});
it('getSearchType should return transaction from fetch response', async () => {
const query =
'4624293CFE3D8B67A0AB448BAFF8FBCF1A1B770D9D5F263761D3D6CBEA94D97F';
const expected = SearchTypes.Transaction;
// @ts-ignore issue related to polyfill
fetch.mockImplementation(
jest.fn(() =>
Promise.resolve({
ok: true,
json: () =>
Promise.resolve({
transaction: {
hash: query,
},
}),
})
)
);
const result = await getSearchType(query);
expect(result).toBe(expected);
});
it('getSearchType should return undefined from transaction response', async () => {
const query = 'u';
const expected = undefined;
const result = await getSearchType(query);
expect(result).toBe(expected);
});
it('getSearchType should return block if query is number', async () => {
const query = '123';
const expected = SearchTypes.Block;
const result = await getSearchType(query);
expect(result).toBe(expected);
});
it('getSearchType should return party if query is network', async () => {
const query = 'network';
const expected = SearchTypes.Party;
const result = await getSearchType(query);
expect(result).toBe(expected);
});
it.each([
[
'0000000000000000000000000000000000000000000000000000000000000000',
SearchTypes.Transaction,
],
[
'0000000000000000000000000000000000000000000000000000000000000001',
SearchTypes.Party,
],
['123', SearchTypes.Block],
['network', SearchTypes.Party],
['something else', SearchTypes.Unknown],
])(
"detectTypeByFetching should call fetch with non-hex query it's a transaction",
async (input, type) => {
// @ts-ignore issue related to polyfill
fetch.mockImplementation(
jest.fn(() =>
Promise.resolve({
ok:
input ===
'0000000000000000000000000000000000000000000000000000000000000000',
json: () =>
Promise.resolve({
transaction: {
hash: input,
},
}),
})
)
);
const result = await determineType(input);
expect(result).toBe(type);
}
);
});
@@ -1,3 +1,4 @@
import { remove0x } from '@vegaprotocol/utils';
import { DATA_SOURCES } from '../../config';
import type { BlockExplorerTransaction } from '../../routes/types/block-explorer-response';
@@ -6,15 +7,20 @@ export enum SearchTypes {
Party = 'party',
Block = 'block',
Order = 'order',
Unknown = 'unknown',
}
export const TX_LENGTH = 64;
export const HASH_LENGTH = 64;
export const isHash = (value: string) =>
/[0-9a-fA-F]+/.test(remove0x(value)) &&
remove0x(value).length === HASH_LENGTH;
export const isHexadecimal = (search: string) =>
search.startsWith('0x') && search.length === 2 + TX_LENGTH;
search.startsWith('0x') && search.length === 2 + HASH_LENGTH;
export const isNonHex = (search: string) =>
!search.startsWith('0x') && search.length === TX_LENGTH;
!search.startsWith('0x') && search.length === HASH_LENGTH;
export const isBlock = (search: string) => !Number.isNaN(Number(search));
@@ -23,121 +29,44 @@ export const isNetworkParty = (search: string) => search === 'network';
export const toHex = (query: string) =>
isHexadecimal(query) ? query : `0x${query}`;
export const toNonHex = (query: string) =>
isNonHex(query) ? query : `${query.replace('0x', '')}`;
export const toNonHex = remove0x;
export const detectTypeFromQuery = (
query: string
): SearchTypes[] | undefined => {
const i = query.toLowerCase();
if (isHexadecimal(i) || isNonHex(i)) {
return [SearchTypes.Party, SearchTypes.Transaction];
} else if (isNetworkParty(i)) {
return [SearchTypes.Party];
} else if (isBlock(i)) {
return [SearchTypes.Block];
/**
* Determine the type of the given query
*/
export const determineType = async (query: string): Promise<SearchTypes> => {
const value = query.toLowerCase();
if (isHash(value)) {
// it can be either `SearchTypes.Party` or `SearchTypes.Transaction`
if (await isTransactionHash(value)) {
return SearchTypes.Transaction;
} else {
return SearchTypes.Party;
}
} else if (isNetworkParty(value)) {
return SearchTypes.Party;
} else if (isBlock(value)) {
return SearchTypes.Block;
}
return undefined;
return SearchTypes.Unknown;
};
export const detectTypeByFetching = async (
query: string
): Promise<SearchTypes | undefined> => {
const hash = toNonHex(query);
/**
* Checks if given input is a transaction hash by querying the transactions
* endpoint
*/
export const isTransactionHash = async (input: string): Promise<boolean> => {
const hash = remove0x(input);
const request = await fetch(
`${DATA_SOURCES.blockExplorerUrl}/transactions/${hash}`
);
if (request?.ok) {
const body: BlockExplorerTransaction = await request.json();
if (body?.transaction) {
return SearchTypes.Transaction;
return true;
}
}
return SearchTypes.Party;
};
// Code commented out because the current solution to detect a hex is temporary (by process of elimination)
// export const detectTypeByFetching = async (
// query: string,
// type: SearchTypes
// ): Promise<SearchTypes | undefined> => {
// const TYPES = [SearchTypes.Party, SearchTypes.Transaction];
//
// if (!TYPES.includes(type)) {
// throw new Error('Search type provided not recognised');
// }
//
// if (type === SearchTypes.Transaction) {
// const hash = toNonHex(query);
// const request = await fetch(
// `${DATA_SOURCES.blockExplorerUrl}/transactions/${hash}`
// );
//
// if (request?.ok) {
// const body: BlockExplorerTransaction = await request.json();
//
// if (body?.transaction) {
// return SearchTypes.Transaction;
// }
// }
// } else if (type === SearchTypes.Party) {
// const party = toNonHex(query);
//
// const request = await fetch(
// `${DATA_SOURCES.blockExplorerUrl}/transactions?limit=1&filters[tx.submitter]=${party}`
// );
//
// if (request.ok) {
// const body: BlockExplorerTransactions = await request.json();
//
// if (body?.transactions?.length) {
// return SearchTypes.Party;
// }
// }
// }
//
// return undefined;
// };
// export const getSearchType = async (
// query: string
// ): Promise<SearchTypes | undefined> => {
// const searchTypes = detectTypeFromQuery(query);
// const hasResults = searchTypes?.length;
//
// if (hasResults) {
// if (hasResults > 1) {
// const promises = searchTypes.map((type) =>
// detectTypeByFetching(query, type)
// );
// const results = await Promise.all(promises);
// return results.find((result) => result !== undefined);
// }
//
// return searchTypes[0];
// }
//
// return undefined;
// };
export const getSearchType = async (
query: string
): Promise<SearchTypes | undefined> => {
const searchTypes = detectTypeFromQuery(query);
const hasResults = searchTypes?.length;
if (hasResults) {
if (hasResults > 1) {
return await detectTypeByFetching(query);
}
return searchTypes[0];
}
return undefined;
return false;
};
@@ -1,157 +1,82 @@
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
import { Search } from './search';
import {
act,
fireEvent,
render,
screen,
waitFor,
} from '@testing-library/react';
import { SearchForm } from './search';
import { MemoryRouter } from 'react-router-dom';
import { Routes } from '../../routes/route-names';
import { SearchTypes, getSearchType } from './detect-search';
global.fetch = jest.fn();
const mockedNavigate = jest.fn();
const mockGetSearchType = getSearchType as jest.MockedFunction<
typeof getSearchType
>;
jest.mock('react-router-dom', () => ({
...jest.requireActual('react-router-dom'),
useNavigate: () => mockedNavigate,
}));
jest.mock('./detect-search', () => ({
...jest.requireActual('./detect-search'),
getSearchType: jest.fn(),
}));
beforeEach(() => {
mockedNavigate.mockClear();
});
const renderComponent = () => (
<MemoryRouter>
<Search />
</MemoryRouter>
);
const renderComponent = () =>
render(
<MemoryRouter>
<SearchForm />
</MemoryRouter>
);
const getInputs = () => ({
input: screen.getByTestId('search'),
button: screen.getByTestId('search-button'),
});
describe('Search', () => {
describe('SearchForm', () => {
it('should render search input and button', () => {
render(renderComponent());
renderComponent();
expect(screen.getByTestId('search')).toBeInTheDocument();
expect(screen.getByTestId('search-button')).toHaveTextContent('Search');
});
it('should render error if input is not known', async () => {
render(renderComponent());
const { button, input } = getInputs();
fireEvent.change(input, { target: { value: 'asd' } });
fireEvent.click(button);
expect(await screen.findByTestId('search-error')).toHaveTextContent(
'Transaction type is not recognised'
it.each([
[
Routes.TX,
'0000000000000000000000000000000000000000000000000000000000000000',
],
[
Routes.PARTIES,
'0000000000000000000000000000000000000000000000000000000000000001',
],
[Routes.BLOCKS, '123'],
[undefined, 'something else'],
])('should redirect to %s', async (route, input) => {
// @ts-ignore issue related to polyfill
fetch.mockImplementation(
jest.fn(() =>
Promise.resolve({
ok:
input ===
'0000000000000000000000000000000000000000000000000000000000000000',
json: () =>
Promise.resolve({
transaction: {
hash: input,
},
}),
})
)
);
});
it('should render error if no input is given', async () => {
render(renderComponent());
const { button } = getInputs();
fireEvent.click(button);
expect(await screen.findByTestId('search-error')).toHaveTextContent(
'Search query required'
);
});
it('should redirect to transactions page', async () => {
render(renderComponent());
const { button, input } = getInputs();
mockGetSearchType.mockResolvedValue(SearchTypes.Transaction);
fireEvent.change(input, {
target: {
value:
'0x1234567890123456789012345678901234567890123456789012345678901234',
},
renderComponent();
await act(async () => {
fireEvent.change(screen.getByTestId('search'), {
target: {
value: input,
},
});
fireEvent.click(screen.getByTestId('search-button'));
});
fireEvent.click(button);
await waitFor(() => {
expect(mockedNavigate).toBeCalledWith(
`${Routes.TX}/0x1234567890123456789012345678901234567890123456789012345678901234`
);
});
});
it('should redirect to transactions page without proceeding 0x', async () => {
render(renderComponent());
const { button, input } = getInputs();
mockGetSearchType.mockResolvedValue(SearchTypes.Transaction);
fireEvent.change(input, {
target: {
value:
'1234567890123456789012345678901234567890123456789012345678901234',
},
});
fireEvent.click(button);
await waitFor(() => {
expect(mockedNavigate).toBeCalledWith(
`${Routes.TX}/0x1234567890123456789012345678901234567890123456789012345678901234`
);
});
});
it('should redirect to parties page', async () => {
render(renderComponent());
const { button, input } = getInputs();
mockGetSearchType.mockResolvedValue(SearchTypes.Party);
fireEvent.change(input, {
target: {
value:
'0x1234567890123456789012345678901234567890123456789012345678901234',
},
});
fireEvent.click(button);
await waitFor(() => {
expect(mockedNavigate).toBeCalledWith(
`${Routes.PARTIES}/0x1234567890123456789012345678901234567890123456789012345678901234`
);
});
});
it('should redirect to parties page without proceeding 0x', async () => {
render(renderComponent());
const { button, input } = getInputs();
mockGetSearchType.mockResolvedValue(SearchTypes.Party);
fireEvent.change(input, {
target: {
value:
'1234567890123456789012345678901234567890123456789012345678901234',
},
});
fireEvent.click(button);
await waitFor(() => {
expect(mockedNavigate).toBeCalledWith(
`${Routes.PARTIES}/0x1234567890123456789012345678901234567890123456789012345678901234`
);
});
});
it('should redirect to blocks page if passed a number', async () => {
render(renderComponent());
const { button, input } = getInputs();
mockGetSearchType.mockResolvedValue(SearchTypes.Block);
fireEvent.change(input, {
target: {
value: '123',
},
});
fireEvent.click(button);
await waitFor(() => {
expect(mockedNavigate).toBeCalledWith(`${Routes.BLOCKS}/123`);
expect(mockedNavigate).toBeCalledTimes(route ? 1 : 0);
if (route) {
// eslint-disable-next-line jest/no-conditional-expect
expect(mockedNavigate).toBeCalledWith(`${route}/${input}`);
}
});
});
});
@@ -1,84 +1,211 @@
import { useCallback, useState } from 'react';
import { useCallback } from 'react';
import { t } from '@vegaprotocol/i18n';
import { Button, Input, InputError } from '@vegaprotocol/ui-toolkit';
import { useForm } from 'react-hook-form';
import { useNavigate } from 'react-router-dom';
import { getSearchType, SearchTypes, toHex } from './detect-search';
import { Routes } from '../../routes/route-names';
import * as DropdownMenu from '@radix-ui/react-dropdown-menu';
import classNames from 'classnames';
import { remove0x } from '@vegaprotocol/utils';
import { determineType, isBlock, isHash, SearchTypes } from './detect-search';
interface FormFields {
search: string;
}
const MagnifyingGlass = () => (
<svg
className="w-4 h-4"
viewBox="0 0 18 18"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<line
x1="12.8202"
y1="13.1798"
x2="17.0629"
y2="17.4224"
stroke="currentColor"
/>
<circle cx="8" cy="8" r="7.5" stroke="currentColor" />
</svg>
);
const Clear = () => (
<svg
className="w-3 h-3"
viewBox="0 0 12 12"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M11.3748 1.37478L1.37478 11.3748L0.625244 10.6252L10.6252 0.625244L11.3748 1.37478Z"
fill="currentColor"
/>
<path
d="M1.37478 0.625244L11.3748 10.6252L10.6252 11.3748L0.625244 1.37478L1.37478 0.625244Z"
fill="currentColor"
/>
</svg>
);
export const Search = () => {
const { register, handleSubmit } = useForm<FormFields>();
const navigate = useNavigate();
const [error, setError] = useState<Error | null>(null);
const searchForm = <SearchForm />;
const onSubmit = useCallback(
async (fields: FormFields) => {
setError(null);
const query = fields.search;
if (!query) {
return setError(new Error(t('Search query required')));
}
const result = await getSearchType(query);
const urlAsHex = toHex(query);
const unrecognisedError = new Error(
t('Transaction type is not recognised')
);
if (result) {
switch (result) {
case SearchTypes.Party:
return navigate(`${Routes.PARTIES}/${urlAsHex}`);
case SearchTypes.Transaction:
return navigate(`${Routes.TX}/${urlAsHex}`);
case SearchTypes.Block:
return navigate(`${Routes.BLOCKS}/${Number(query)}`);
default:
return setError(unrecognisedError);
}
}
return setError(unrecognisedError);
},
[navigate]
const searchTrigger = (
<DropdownMenu.Root>
<DropdownMenu.Trigger asChild>
<button className="text-vega-light-300 dark:text-vega-dark-300 data-open:text-black dark:data-open:text-white flex items-center">
<MagnifyingGlass />
</button>
</DropdownMenu.Trigger>
<DropdownMenu.Portal>
<DropdownMenu.Content
className={classNames(
'search-dropdown',
'p-2 min-w-[290px] z-20',
'text-vega-light-300 dark:text-vega-dark-300',
'bg-white dark:bg-black',
'border rounded border-vega-light-200 dark:border-vega-dark-200',
'shadow-[8px_8px_16px_0_rgba(0,0,0,0.4)]'
)}
align="end"
sideOffset={10}
>
{searchForm}
</DropdownMenu.Content>
</DropdownMenu.Portal>
</DropdownMenu.Root>
);
return (
<form
onSubmit={handleSubmit(onSubmit)}
className="w-full md:max-w-[620px] justify-self-end"
>
<label htmlFor="search" className="sr-only">
{t('Search by block number or transaction hash')}
</label>
<div className="flex items-stretch gap-2">
<div className="flex grow relative">
<>
<div className="hidden [.nav-search-full_&]:block min-w-[290px]">
{searchForm}
</div>
<div className="hidden [.nav-search-compact_&]:block">
{searchTrigger}
</div>
</>
);
};
export const SearchForm = () => {
const {
register,
handleSubmit,
setValue,
setError,
clearErrors,
formState,
watch,
} = useForm<FormFields>();
const navigate = useNavigate();
const onSubmit = useCallback(
async (fields: FormFields) => {
clearErrors();
const type = await determineType(fields.search);
if (type) {
switch (type) {
case SearchTypes.Party:
return navigate(`${Routes.PARTIES}/${remove0x(fields.search)}`);
case SearchTypes.Transaction:
return navigate(`${Routes.TX}/${remove0x(fields.search)}`);
case SearchTypes.Block:
return navigate(`${Routes.BLOCKS}/${Number(fields.search)}`);
}
}
setError('search', new Error(t('The search term is not a valid query')));
},
[clearErrors, navigate, setError]
);
const searchQuery = watch('search', '');
return (
<form className="block min-w-[200px]" onSubmit={handleSubmit(onSubmit)}>
<div className="flex relative items-stretch gap-2 text-xs">
<div className="relative w-full">
<label htmlFor="search" className="sr-only">
{t('Search by block number or transaction hash')}
</label>
<button
className={classNames(
'absolute top-[50%] translate-y-[-50%] left-2',
'text-vega-light-300 dark:text-vega-dark-300'
)}
>
<MagnifyingGlass />
</button>
<button
onClick={(e) => {
e.preventDefault();
setValue('search', '');
clearErrors();
}}
className={classNames(
{ hidden: searchQuery.length === 0 },
'absolute top-[50%] translate-y-[-50%] right-2',
'text-vega-light-300 dark:text-vega-dark-300'
)}
>
<Clear />
</button>
<Input
{...register('search')}
{...register('search', {
required: t('Search query is required'),
validate: (value) =>
isHash(value) ||
isBlock(value) ||
t('Search query has to be a number or a 64 character hash'),
onBlur: () => clearErrors('search'),
})}
id="search"
data-testid="search"
className="text-white"
hasError={Boolean(error?.message)}
className={classNames(
'pl-8 py-2 text-xs',
{ 'pr-8': searchQuery.length > 1 },
'border rounded border-vega-light-200 dark:border-vega-dark-200',
{
'border-vega-pink dark:border-vega-pink': Boolean(
formState.errors.search
),
}
)}
hasError={Boolean(formState.errors.search)}
type="text"
placeholder={t(
'Enter block number, public key or transaction hash'
)}
/>
{error?.message && (
<div className="bg-white border border-t-0 border-accent absolute top-[100%] flex-1 w-full pb-2 px-2 rounded-b text-black">
<InputError data-testid="search-error" intent="danger">
{error.message}
</InputError>
</div>
)}
</div>
<Button type="submit" size="sm" data-testid="search-button">
{formState.errors.search && (
<div
className={classNames(
'[nav_&]:border [nav_&]:rounded [nav_&]:border-vega-light-300 [nav_&]:dark:border-vega-light-300',
'[.search-dropdown_&]:border [.search-dropdown_&]:rounded [.search-dropdown_&]:border-vega-light-300 [.search-dropdown_&]:dark:border-vega-light-300',
'bg-white dark:bg-black',
'absolute top-[100%] flex-1 w-full pb-2 px-2 text-black dark:text-white'
)}
>
<InputError
data-testid="search-error"
intent="danger"
className="text-xs"
>
{formState.errors.search.message}
</InputError>
</div>
)}
<Button
variant="primary"
type="submit"
size="xs"
data-testid="search-button"
className="[nav_&]:hidden"
>
{t('Search')}
</Button>
</div>
@@ -5,7 +5,6 @@ import type { components } from '../../../../../types/explorer';
import { MockedProvider } from '@apollo/client/testing';
import { MemoryRouter } from 'react-router-dom';
import { TxDetailsChainMultisigSigner } from './tx-multisig-signer';
import { getBlockTime } from './lib/get-block-time';
type Added = components['schemas']['vegaERC20SignerAdded'];
type Removed = components['schemas']['vegaERC20SignerRemoved'];
@@ -61,10 +60,7 @@ describe('Chain Event: multisig signer change', () => {
expect(screen.getByText(t('Add signer'))).toBeInTheDocument();
expect(screen.getByText(`${addedMock.newSigner}`)).toBeInTheDocument();
const expectedDate = getBlockTime(mockBlockTime);
expect(screen.getByText(t('Signer change at'))).toBeInTheDocument();
expect(screen.getByText(expectedDate)).toBeInTheDocument();
});
it('Renders TableRows if all data is provided', () => {
@@ -93,9 +89,6 @@ describe('Chain Event: multisig signer change', () => {
expect(screen.getByText(t('Remove signer'))).toBeInTheDocument();
expect(screen.getByText(`${removedMock.oldSigner}`)).toBeInTheDocument();
const expectedDate = getBlockTime(mockBlockTime);
expect(screen.getByText(t('Signer change at'))).toBeInTheDocument();
expect(screen.getByText(expectedDate)).toBeInTheDocument();
});
});
@@ -6,7 +6,6 @@ import { MockedProvider } from '@apollo/client/testing';
import { MemoryRouter } from 'react-router-dom';
import { TxDetailsChainMultisigThreshold } from './tx-multisig-threshold';
import omit from 'lodash/omit';
import { getBlockTime } from './lib/get-block-time';
type Threshold =
components['schemas']['vegaERC20MultiSigEvent']['thresholdSet'];
@@ -74,9 +73,6 @@ describe('Chain Event: multisig threshold change', () => {
expect(screen.getByText(t('Threshold'))).toBeInTheDocument();
expect(screen.getByText(`66.7%`)).toBeInTheDocument();
const expectedDate = getBlockTime(mockBlockTime);
expect(screen.getByText(t('Threshold change date'))).toBeInTheDocument();
expect(screen.getByText(expectedDate)).toBeInTheDocument();
});
});
@@ -5,6 +5,11 @@ query ExplorerNewAssetSignatureBundle($id: ID!) {
}
asset(id: $id) {
status
source {
... on ERC20 {
contractAddress
}
}
}
}
@@ -15,5 +20,10 @@ query ExplorerUpdateAssetSignatureBundle($id: ID!) {
}
asset(id: $id) {
status
source {
... on ERC20 {
contractAddress
}
}
}
}
@@ -8,14 +8,14 @@ export type ExplorerNewAssetSignatureBundleQueryVariables = Types.Exact<{
}>;
export type ExplorerNewAssetSignatureBundleQuery = { __typename?: 'Query', erc20ListAssetBundle?: { __typename?: 'Erc20ListAssetBundle', signatures: string, nonce: string } | null, asset?: { __typename?: 'Asset', status: Types.AssetStatus } | null };
export type ExplorerNewAssetSignatureBundleQuery = { __typename?: 'Query', erc20ListAssetBundle?: { __typename?: 'Erc20ListAssetBundle', signatures: string, nonce: string } | null, asset?: { __typename?: 'Asset', status: Types.AssetStatus, source: { __typename?: 'BuiltinAsset' } | { __typename?: 'ERC20', contractAddress: string } } | null };
export type ExplorerUpdateAssetSignatureBundleQueryVariables = Types.Exact<{
id: Types.Scalars['ID'];
}>;
export type ExplorerUpdateAssetSignatureBundleQuery = { __typename?: 'Query', erc20SetAssetLimitsBundle: { __typename?: 'ERC20SetAssetLimitsBundle', signatures: string, nonce: string }, asset?: { __typename?: 'Asset', status: Types.AssetStatus } | null };
export type ExplorerUpdateAssetSignatureBundleQuery = { __typename?: 'Query', erc20SetAssetLimitsBundle: { __typename?: 'ERC20SetAssetLimitsBundle', signatures: string, nonce: string }, asset?: { __typename?: 'Asset', status: Types.AssetStatus, source: { __typename?: 'BuiltinAsset' } | { __typename?: 'ERC20', contractAddress: string } } | null };
export const ExplorerNewAssetSignatureBundleDocument = gql`
@@ -26,6 +26,11 @@ export const ExplorerNewAssetSignatureBundleDocument = gql`
}
asset(id: $id) {
status
source {
... on ERC20 {
contractAddress
}
}
}
}
`;
@@ -65,6 +70,11 @@ export const ExplorerUpdateAssetSignatureBundleDocument = gql`
}
asset(id: $id) {
status
source {
... on ERC20 {
contractAddress
}
}
}
}
`;
@@ -110,7 +110,9 @@ export const ProposalStatusIcon = ({ id }: ProposalStatusIconProps) => {
return (
<div className="float-left mr-3">
<Tooltip description={<p>{label}</p>}>
<Icon name={icon} />
<div>
<Icon name={icon} />
</div>
</Tooltip>
</div>
);
@@ -1,10 +1,12 @@
import { Loader } from '@vegaprotocol/ui-toolkit';
import type { ProposalTerms } from '../tx-proposal';
import { BundleError } from './signature-bundle/bundle-error';
import { BundleExists } from './signature-bundle/bundle-exists';
import { useExplorerNewAssetSignatureBundleQuery } from './__generated__/SignatureBundle';
export interface ProposalSignatureBundleByTypeProps {
id: string;
tx?: ProposalTerms['newAsset'] | ProposalTerms['updateAsset'];
}
/**
@@ -16,6 +18,7 @@ export interface ProposalSignatureBundleByTypeProps {
*/
export const ProposalSignatureBundleNewAsset = ({
id,
tx,
}: ProposalSignatureBundleByTypeProps) => {
const { data, error, loading } = useExplorerNewAssetSignatureBundleQuery({
variables: {
@@ -24,7 +27,20 @@ export const ProposalSignatureBundleNewAsset = ({
});
if (loading) {
return <Loader />;
return (
<div className="w-auto max-w-lg p-5 mt-5">
<Loader />
</div>
);
}
if (
!tx?.changes?.erc20 ||
!tx?.changes?.erc20 ||
!('contractAddress' in tx.changes.erc20) ||
tx.changes.erc20.contractAddress === undefined
) {
return null;
}
if (data?.erc20ListAssetBundle?.signatures) {
@@ -32,8 +48,10 @@ export const ProposalSignatureBundleNewAsset = ({
<BundleExists
signatures={data.erc20ListAssetBundle.signatures}
nonce={data.erc20ListAssetBundle.nonce}
assetAddress={tx.changes.erc20.contractAddress}
status={data.asset?.status}
proposalId={id}
tx={tx}
/>
);
} else {
@@ -13,6 +13,7 @@ import { useExplorerUpdateAssetSignatureBundleQuery } from './__generated__/Sign
*/
export const ProposalSignatureBundleUpdateAsset = ({
id,
tx,
}: ProposalSignatureBundleByTypeProps) => {
const { data, error, loading } = useExplorerUpdateAssetSignatureBundleQuery({
variables: {
@@ -24,11 +25,16 @@ export const ProposalSignatureBundleUpdateAsset = ({
return <Loader />;
}
if (data?.asset?.source?.__typename !== 'ERC20') {
return null;
}
if (data?.erc20SetAssetLimitsBundle?.signatures) {
return (
<BundleExists
signatures={data.erc20SetAssetLimitsBundle.signatures}
nonce={data.erc20SetAssetLimitsBundle.nonce}
assetAddress={data.asset.source.contractAddress}
status={data.asset?.status}
proposalId={id}
/>
@@ -1,31 +0,0 @@
import { ProposalSignatureBundleNewAsset } from './signature-bundle-new';
import { ProposalSignatureBundleUpdateAsset } from './signature-bundle-update';
export function format(date: string | undefined, def: string) {
if (!date) {
return def;
}
return new Date().toLocaleDateString() || def;
}
interface ProposalSignatureBundleProps {
id: string;
type: 'NewAsset' | 'UpdateAsset';
}
/**
* Some proposals, if enacted, generate a signature bundle.
* The queries have to be split due to the way the API returns
* errors, hence this slightly redundant feeling switcher.
*/
export const ProposalSignatureBundle = ({
id,
type,
}: ProposalSignatureBundleProps) => {
return type === 'NewAsset' ? (
<ProposalSignatureBundleNewAsset id={id} />
) : (
<ProposalSignatureBundleUpdateAsset id={id} />
);
};
@@ -0,0 +1,17 @@
query ExplorerBundleSigners {
networkParameter(key: "blockchains.ethereumConfig") {
value
}
nodesConnection(pagination: { first: 25 }) {
edges {
node {
id
name
status
ethereumAddress
pubkey
tmPubkey
}
}
}
}
@@ -0,0 +1,57 @@
import * as Types from '@vegaprotocol/types';
import { gql } from '@apollo/client';
import * as Apollo from '@apollo/client';
const defaultOptions = {} as const;
export type ExplorerBundleSignersQueryVariables = Types.Exact<{ [key: string]: never; }>;
export type ExplorerBundleSignersQuery = { __typename?: 'Query', networkParameter?: { __typename?: 'NetworkParameter', value: string } | null, nodesConnection: { __typename?: 'NodesConnection', edges?: Array<{ __typename?: 'NodeEdge', node: { __typename?: 'Node', id: string, name: string, status: Types.NodeStatus, ethereumAddress: string, pubkey: string, tmPubkey: string } } | null> | null } };
export const ExplorerBundleSignersDocument = gql`
query ExplorerBundleSigners {
networkParameter(key: "blockchains.ethereumConfig") {
value
}
nodesConnection(pagination: {first: 25}) {
edges {
node {
id
name
status
ethereumAddress
pubkey
tmPubkey
}
}
}
}
`;
/**
* __useExplorerBundleSignersQuery__
*
* To run a query within a React component, call `useExplorerBundleSignersQuery` and pass it any options that fit your needs.
* When your component renders, `useExplorerBundleSignersQuery` returns an object from Apollo Client that contains loading, error, and data properties
* you can use to render your UI.
*
* @param baseOptions options that will be passed into the query, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options;
*
* @example
* const { data, loading, error } = useExplorerBundleSignersQuery({
* variables: {
* },
* });
*/
export function useExplorerBundleSignersQuery(baseOptions?: Apollo.QueryHookOptions<ExplorerBundleSignersQuery, ExplorerBundleSignersQueryVariables>) {
const options = {...defaultOptions, ...baseOptions}
return Apollo.useQuery<ExplorerBundleSignersQuery, ExplorerBundleSignersQueryVariables>(ExplorerBundleSignersDocument, options);
}
export function useExplorerBundleSignersLazyQuery(baseOptions?: Apollo.LazyQueryHookOptions<ExplorerBundleSignersQuery, ExplorerBundleSignersQueryVariables>) {
const options = {...defaultOptions, ...baseOptions}
return Apollo.useLazyQuery<ExplorerBundleSignersQuery, ExplorerBundleSignersQueryVariables>(ExplorerBundleSignersDocument, options);
}
export type ExplorerBundleSignersQueryHookResult = ReturnType<typeof useExplorerBundleSignersQuery>;
export type ExplorerBundleSignersLazyQueryHookResult = ReturnType<typeof useExplorerBundleSignersLazyQuery>;
export type ExplorerBundleSignersQueryResult = Apollo.QueryResult<ExplorerBundleSignersQuery, ExplorerBundleSignersQueryVariables>;
@@ -8,14 +8,16 @@ import { BundleError } from './bundle-error';
describe('Bundle Error', () => {
const NON_ENABLED_STATUS: AssetStatus[] = [
AssetStatus.STATUS_PENDING_LISTING,
];
const NOT_SHOWN_STATUS: AssetStatus[] = [
AssetStatus.STATUS_PROPOSED,
AssetStatus.STATUS_REJECTED,
];
const ENABLED_STATUS: AssetStatus[] = [AssetStatus.STATUS_ENABLED];
it.each(NON_ENABLED_STATUS)(
'shows the apollo error if not enabled and a message is provided',
it.each(NOT_SHOWN_STATUS)(
'does not render for proposed or rejected bundles',
(status) => {
const screen = render(
<MemoryRouter>
@@ -28,7 +30,24 @@ describe('Bundle Error', () => {
</MemoryRouter>
);
expect(screen.getByText('test-error-message')).toBeInTheDocument();
expect(screen.container).toBeEmptyDOMElement();
}
);
it.each(NON_ENABLED_STATUS)(
'shows the apollo error in a syntax highlighter if not enabled and a message is provided',
(status) => {
const screen = render(
<MemoryRouter>
<MockedProvider>
<BundleError
error={{ message: 'test-error-message' } as ApolloError}
status={status}
/>
</MockedProvider>
</MemoryRouter>
);
expect(screen.getByText('No signature bundle')).toBeInTheDocument();
}
);
@@ -43,7 +62,7 @@ describe('Bundle Error', () => {
</MemoryRouter>
);
expect(screen.getByText('No bundle for proposal ID')).toBeInTheDocument();
expect(screen.getByText('No signature bundle')).toBeInTheDocument();
}
);
@@ -2,8 +2,8 @@ import type { ApolloError } from '@apollo/client';
import type { AssetStatus } from '@vegaprotocol/types';
import { t } from '@vegaprotocol/i18n';
import Hash from '../../../../links/hash';
import { IconForBundleStatus } from './bundle-icon';
import { SyntaxHighlighter } from '@vegaprotocol/ui-toolkit';
export interface BundleErrorProps {
status?: AssetStatus;
@@ -17,18 +17,33 @@ export interface BundleErrorProps {
* the status - if it's already enabled, pretend this isn't an error
*/
export const BundleError = ({ status, error }: BundleErrorProps) => {
if (!status || status === 'STATUS_PROPOSED' || status === 'STATUS_REJECTED') {
// If there is no status, there is no asset and no bundle - ProposalDetails will make it clear why.
// If the asset exists but is just proposed, or rejected, there won't be a signature bundle yet
return null;
}
return (
<div className="w-auto max-w-lg border-2 border-solid border-vega-light-100 dark:border-vega-dark-200 p-5 mt-5">
<IconForBundleStatus status={status} />
<h1 className="text-xl pb-1">{t('No signature bundle found')}</h1>
<h1 className="text-xl pb-1">{t('No signature bundle')}</h1>
<p>
<p className="my-4">
{t(
'No signature bundle was generated as a result of this proposal, or the signature bundle could not be found.'
)}
</p>
<div>
{status === 'STATUS_ENABLED' ? (
t('Asset already enabled')
) : (
<Hash text={error ? error.message : t('No bundle for proposal ID')} />
<details>
<summary>{t('Show server error message')}</summary>
<SyntaxHighlighter data={error} size="smaller" />
</details>
)}
</p>
</div>
</div>
);
};
@@ -32,6 +32,7 @@ describe('Bundle Exists', () => {
nonce={MOCK_NONCE}
proposalId={MOCK_PROPOSAL_ID}
signatures={MOCK_SIGNATURES}
assetAddress={'0x123413423'}
status={status}
/>
</MockedProvider>
@@ -52,6 +53,7 @@ describe('Bundle Exists', () => {
nonce={MOCK_NONCE}
proposalId={MOCK_PROPOSAL_ID}
signatures={MOCK_SIGNATURES}
assetAddress={'0x123413423'}
status={status}
/>
</MockedProvider>
@@ -1,14 +1,17 @@
import { t } from '@vegaprotocol/i18n';
import type { AssetStatus } from '@vegaprotocol/types';
import ProposalLink from '../../../../links/proposal-link/proposal-link';
import { IconForBundleStatus } from './bundle-icon';
import { ProposalSignatureBundleDetails } from './details';
import type { AssetStatus } from '@vegaprotocol/types';
import type { ProposalTerms } from '../../tx-proposal';
import { BundleSigners } from './bundle-signers';
export interface BundleExistsProps {
signatures: string;
nonce: string;
status?: AssetStatus;
assetAddress: string;
proposalId: string;
tx?: ProposalTerms['newAsset'] | ProposalTerms['updateAsset'];
}
/**
@@ -21,7 +24,11 @@ export const BundleExists = ({
nonce,
status,
proposalId,
assetAddress,
tx,
}: BundleExistsProps) => {
// Note if this is wrong, the wrong decoder will be used which will give incorrect data
return (
<div className="w-auto max-w-lg border-2 border-solid border-vega-light-100 dark:border-vega-dark-200 p-5 mt-5">
<IconForBundleStatus status={status} />
@@ -31,7 +38,42 @@ export const BundleExists = ({
: t('Signature bundle generated')}
</h1>
<ProposalSignatureBundleDetails signatures={signatures} nonce={nonce} />
<details className="mt-5">
<summary>{t('Signature bundle details')}</summary>
<div className="ml-4">
<h2 className="text-lg mt-2 mb-2">{t('Signatures')}</h2>
<p>
<textarea
className="font-mono bg-neutral-300 text-[11px] leading-3 text-gray-900 w-full p-2 max-w-[615px]"
readOnly={true}
rows={12}
cols={120}
value={signatures}
/>
</p>
<h2 className="text-lg mt-5 mb-2">{t('Nonce')}</h2>
<p>
<textarea
className="font-mono bg-neutral-300 text-[11px] leading-3 text-gray-900 w-full p-2 max-w-[615px]"
readOnly={true}
rows={2}
cols={120}
value={nonce}
/>
</p>
</div>
</details>
<BundleSigners
signatures={signatures}
nonce={nonce}
tx={tx}
id={proposalId}
assetAddress={assetAddress}
/>
{status !== 'STATUS_ENABLED' ? (
<p className="mt-5">
@@ -1,33 +1,34 @@
import { render } from '@testing-library/react';
import { AssetStatus } from '@vegaprotocol/types';
import { IconForBundleStatus } from './bundle-icon';
import { getIcon } from './bundle-icon';
describe('Bundle status icon', () => {
const NON_ENABLED_STATUS: AssetStatus[] = [
AssetStatus.STATUS_PENDING_LISTING,
AssetStatus.STATUS_PROPOSED,
AssetStatus.STATUS_REJECTED,
];
const ERROR_STATUS: AssetStatus[] = [AssetStatus.STATUS_REJECTED];
const ENABLED_STATUS: AssetStatus[] = [AssetStatus.STATUS_ENABLED];
it.each(NON_ENABLED_STATUS)(
'show a sparkle icon if the bundle is unused',
(status) => {
const screen = render(<IconForBundleStatus status={status} />);
const i = screen.getByRole('img');
expect(i).toHaveAttribute('aria-label');
expect(i.getAttribute('aria-label')).toMatch(/clean/);
expect(getIcon(status)).toEqual('clean');
}
);
it.each(ERROR_STATUS)(
'show an error icon if the bundle is unavailable',
(status) => {
expect(getIcon(status)).toEqual('disable');
}
);
it.each(ENABLED_STATUS)(
'shows a tick if the bundle is already used',
(status) => {
const screen = render(<IconForBundleStatus status={status} />);
const i = screen.getByRole('img');
expect(i).toHaveAttribute('aria-label');
expect(i.getAttribute('aria-label')).toMatch(/tick-circle/);
expect(getIcon(status)).toEqual('tick-circle');
}
);
});
@@ -12,6 +12,26 @@ export interface IconForBundleStatusProps {
* asset should not exist
*/
export const IconForBundleStatus = ({ status }: IconForBundleStatusProps) => {
const i: IconName = status === 'STATUS_ENABLED' ? 'tick-circle' : 'clean';
return <Icon className="float-left mt-2 mr-3" name={i} />;
const i = getIcon(status);
return (
<Icon
className="float-left mt-2 mr-3"
name={i}
data-testid={i}
ariaLabel={status}
/>
);
};
export function getIcon(status?: AssetStatus): IconName {
switch (status) {
case 'STATUS_ENABLED':
return 'tick-circle';
case undefined:
case 'STATUS_REJECTED':
return 'disable';
default:
return 'clean';
}
}
@@ -0,0 +1,94 @@
import type { EncodeListAssetParameters } from '../../../../../lib/encoders/abis/list-asset';
import type { BridgeFunction } from './bundle-signers';
import {
getBridgeAddressFromNetworkParameter,
getSigners,
} from './bundle-signers';
describe('Bundle Signers helpers', () => {
it('getBridgeAddressFromNetworkParameter handles invalid json', () => {
expect(getBridgeAddressFromNetworkParameter('hi')).toEqual(null);
expect(getBridgeAddressFromNetworkParameter('{hi]')).toEqual(null);
expect(getBridgeAddressFromNetworkParameter('{"hi"}')).toEqual(null);
expect(
getBridgeAddressFromNetworkParameter(false as unknown as string)
).toEqual(null);
});
it('getBridgeAddressFromNetworkParameter returns null if bridge adderss is not in expected place', () => {
expect(
getBridgeAddressFromNetworkParameter(`{
"NetworkParamter": false
}`)
).toEqual(null);
expect(
getBridgeAddressFromNetworkParameter(`{
"network_id": "11155111",
"chain_id": "11155111",
"confirmations": 3,
"staking_bridge_contract": {
"address": "0xFFb0A0d4806502ceF491aF1141f66669A1Bd0D03",
"deployment_block_height": 2011705
},
"token_vesting_contract": {
"address": "0x680fF88252FA7071CAce7398e77872d54D781d0B",
"deployment_block_height": 2011709
},
"multisig_control_contract": {
"address": "0x6eBc32d66277D94DB8FF2ccF86E36f37F29a52D3",
"deployment_block_height": 2011699
}
}`)
).toEqual(null);
});
it('getBridgeAddressFromNetworkParameter returns address if the collateral_bridge_contract has an address', () => {
expect(
getBridgeAddressFromNetworkParameter(`{
"network_id": "11155111",
"chain_id": "11155111",
"confirmations": 3,
"collateral_bridge_contract": {
"address": "0x7fe27d970bc8Afc3B11Cc8d9737bfB66B1efd799"
},
"staking_bridge_contract": {
"address": "0xFFb0A0d4806502ceF491aF1141f66669A1Bd0D03",
"deployment_block_height": 2011705
},
"token_vesting_contract": {
"address": "0x680fF88252FA7071CAce7398e77872d54D781d0B",
"deployment_block_height": 2011709
},
"multisig_control_contract": {
"address": "0x6eBc32d66277D94DB8FF2ccF86E36f37F29a52D3",
"deployment_block_height": 2011699
}
}`)
).toEqual('0x7fe27d970bc8Afc3B11Cc8d9737bfB66B1efd799');
});
it('getSigners to return [] in the case of bad inputs', () => {
expect(
getSigners('list_asset', '123', '', {
assetERC20: '123',
assetId: '456',
limit: 'bad',
threshold: 'data',
nonce: 'here',
})
).toEqual([]);
expect(
getSigners('nothing' as unknown as BridgeFunction, '123', '', {
nonce: 'here',
} as unknown as EncodeListAssetParameters)
).toEqual([]);
expect(
getSigners('set_asset_limits', '0x123', '0x456', {
nonce: 'here',
} as unknown as EncodeListAssetParameters)
).toEqual([]);
});
});
@@ -0,0 +1,197 @@
import { encodeListAssetBridgeTx } from '../../../../../lib/encoders/abis/list-asset';
import { recoverAddress } from 'ethers/lib/utils';
import { useExplorerBundleSignersQuery } from './__generated__/BundleSigners';
import type { ProposalTerms } from '../../tx-proposal';
import { DApp, TOKEN_VALIDATOR, useLinks } from '@vegaprotocol/environment';
import { ExternalLink, Icon } from '@vegaprotocol/ui-toolkit';
import { t } from '@vegaprotocol/i18n';
import { IconNames } from '@blueprintjs/icons';
import { encodeUpdateAssetBridgeTx } from '../../../../../lib/encoders/abis/update-asset';
import { prepend0x } from '@vegaprotocol/smart-contracts';
import type { EncodeListAssetParameters } from '../../../../../lib/encoders/abis/list-asset';
import omit from 'lodash/omit';
export type BridgeFunction = 'list_asset' | 'set_asset_limits';
export interface BundleSignersProps {
signatures: string;
assetAddress: string;
nonce: string;
tx?: ProposalTerms['updateAsset'] | ProposalTerms['newAsset'];
id: string;
}
/**
* A logic-heavy component that takes in a signature bundle and returns
* the list of validators that signed the bundle. To do this it requires
* data from quite a few places - a network parameter, the signature bundle,
* the asset that has been modified
*/
export const BundleSigners = ({
signatures,
nonce,
assetAddress,
tx,
id,
}: BundleSignersProps) => {
const tokenLink = useLinks(DApp.Token);
const bridgeFunction: BridgeFunction =
tx?.changes?.erc20 && 'contractAddress' in tx.changes.erc20
? 'list_asset'
: 'set_asset_limits';
const { data } = useExplorerBundleSignersQuery();
const bridgeAddress = getBridgeAddressFromNetworkParameter(
data?.networkParameter?.value
);
const allEthereumKeys =
data?.nodesConnection?.edges
?.filter((n) => n?.node.status === 'NODE_STATUS_VALIDATOR')
.map((s) => s?.node) || [];
if (!tx || !tx.changes?.erc20) {
return null;
}
const { lifetimeLimit, withdrawThreshold } = tx.changes.erc20;
if (
!id ||
allEthereumKeys.length === 0 ||
!bridgeAddress ||
!lifetimeLimit ||
!withdrawThreshold
) {
return null;
}
const signersLowerCase = getSigners(
bridgeFunction,
bridgeAddress,
signatures,
{
assetERC20: assetAddress,
assetId: prepend0x(id),
limit: lifetimeLimit,
threshold: withdrawThreshold,
nonce,
}
);
return (
<>
<h2 className="mt-4 mb-2 text-lg">{t('Signed by validators')}</h2>
<ul>
{allEthereumKeys?.map((n) => {
if (!n) {
return null;
}
const validatorPage = tokenLink(TOKEN_VALIDATOR.replace(':id', n.id));
return signersLowerCase?.indexOf(
n?.ethereumAddress.toLowerCase() || '??'
) !== -1 ? (
<li key={n?.pubkey}>
<ExternalLink href={validatorPage}>
<Icon name={IconNames.ENDORSED} className="ml-1 mr-2" />
{n?.name}
<Icon size={3} name={IconNames.SHARE} className="ml-2" />
</ExternalLink>
</li>
) : (
<li>
<ExternalLink href={validatorPage}>
<Icon name={IconNames.MINUS} className="ml-1 mr-2" />
{n?.name}
<Icon size={3} name={IconNames.SHARE} className="ml-2" />
</ExternalLink>
</li>
);
})}
</ul>
</>
);
};
/**
* Given all of the collated information, this function creates an equivalent unsigned bundle
* and recovers the signers from it, In the case of an error, it returns an empty array.
*
* @param bridgeFunction Decides which data goes in to the digest
* @param bridgeAddress ERC20 bridge address
* @param signatures Long string of signatures
* @param params The object containing all data that the bridge requires for New or Updating assets
* @returns String[] Empty if there was an error or no signers were recovered, otherwise lowercased ETH addresses
*/
export function getSigners(
bridgeFunction: BridgeFunction,
bridgeAddress: string,
signatures: string,
params: EncodeListAssetParameters
): string[] {
try {
if (bridgeFunction === 'list_asset') {
const digest = encodeListAssetBridgeTx(params, bridgeAddress);
// Recover Address from digest can return null, which is handled as an empty array
return recoverAddressesFromDigest(digest, signatures) || [];
} else {
// The params bundles are so similar, rather than force the component to make two different
// styles, just delete the one different property
const p = omit(params, 'assetId');
const digest = encodeUpdateAssetBridgeTx(p, bridgeAddress);
return recoverAddressesFromDigest(digest, signatures) || [];
}
} catch (e) {
// In the worst case, no signing addresses are recovered. This means that all nodes will
// be rendered as if they had not signed the bundle.
return [];
}
}
/**
* Querying for the network parameter value gets us all of the contract details for this network
* encoded as a JSON object. This function pulls out the address for the bridge, or returns null
* in any of the many cases where it may fail
*
* @param networkParameterAsString the stringified JSON object
* @returns null or bridge address as a string
*/
export function getBridgeAddressFromNetworkParameter(
networkParameterAsString: string | undefined
): string | null {
if (!networkParameterAsString) {
return null;
}
try {
const networkParameter = JSON.parse(networkParameterAsString);
return networkParameter.collateral_bridge_contract.address;
} catch (e) {
// There is no good recovery state so return null
return null;
}
}
export function recoverAddressesFromDigest(
digest: string,
unprefixedBundle: string
) {
// Remove 0x from bundle, then split it in to signatures
const sigs = unprefixedBundle.substring(2).match(/.{1,130}/g);
// Convert each of the signatures from hex to a string
const hexSigs = sigs?.map((s) => `0x${s.toString()}`);
if (!hexSigs) {
return null;
}
// toLowerCase is a hack - something somewhere is lowercasing some
// pubkeys
return hexSigs.map((h) => recoverAddress(digest, h).toLowerCase());
}
@@ -1,41 +0,0 @@
import { t } from '@vegaprotocol/i18n';
export interface ProposalSignatureBundleDetailsProps {
signatures: string;
nonce: string;
}
export const ProposalSignatureBundleDetails = ({
signatures,
nonce,
}: ProposalSignatureBundleDetailsProps) => {
return (
<details className="mt-5">
<summary>{t('Signature bundle details')}</summary>
<div className="ml-4">
<h2 className="text-lg mt-2 mb-2">{t('Signatures')}</h2>
<p>
<textarea
className="font-mono bg-neutral-300 text-[11px] leading-3 text-gray-900 w-full p-2 max-w-[615px]"
readOnly={true}
rows={12}
cols={120}
value={signatures}
/>
</p>
<h2 className="text-lg mt-5 mb-2">{t('Nonce')}</h2>
<p>
<textarea
className="font-mono bg-neutral-300 text-[11px] leading-3 text-gray-900 w-full p-2 max-w-[615px]"
readOnly={true}
rows={2}
cols={120}
value={nonce}
/>
</p>
</div>
</details>
);
};
@@ -61,7 +61,7 @@ export const ProposalSummary = ({
{id && <ProposalStatusIcon id={id} />}
{rationale?.title && <h1 className="text-xl pb-1">{rationale.title}</h1>}
{rationale?.description && (
<p className="pt-2 text-sm leading-tight">
<div className="pt-2 text-sm leading-tight">
<ReactMarkdown
className="react-markdown-container"
skipHtml={true}
@@ -70,15 +70,15 @@ export const ProposalSummary = ({
>
{md}
</ReactMarkdown>
</p>
</div>
)}
<p className="pt-5">
<div className="pt-5">
<button className="underline max-md:hidden mr-5" onClick={openDialog}>
{t('View terms')}
</button>{' '}
<ProposalLink id={id} text={t('Full details')} />
{terms && <ProposalDate terms={terms} id={id} />}
</p>
</div>
<JsonViewerDialog
open={dialog.open}
onChange={(isOpen) => setDialog({ ...dialog, open: isOpen })}
@@ -7,8 +7,9 @@ import { txSignatureToDeterministicId } from '../lib/deterministic-ids';
import has from 'lodash/has';
import { ProposalSummary } from './proposal/summary';
import Hash from '../../links/hash';
import { ProposalSignatureBundle } from './proposal/signature-bundle';
import { t } from '@vegaprotocol/i18n';
import { ProposalSignatureBundleNewAsset } from './proposal/signature-bundle-new';
import { ProposalSignatureBundleUpdateAsset } from './proposal/signature-bundle-update';
export type Proposal = components['schemas']['v1ProposalSubmission'];
export type ProposalTerms = components['schemas']['vegaProposalTerms'];
@@ -78,6 +79,12 @@ export const TxProposal = ({ txData, pubKey, blockData }: TxProposalProps) => {
deterministicId = txSignatureToDeterministicId(sig);
}
const tx = proposal.terms?.newAsset || proposal.terms?.updateAsset;
const SignatureBundleComponent = proposal.terms?.newAsset
? ProposalSignatureBundleNewAsset
: ProposalSignatureBundleUpdateAsset;
return (
<>
<TableWithTbody className="mb-8" allowWrap={true}>
@@ -105,10 +112,7 @@ export const TxProposal = ({ txData, pubKey, blockData }: TxProposalProps) => {
terms={proposal?.terms}
/>
{proposalRequiresSignatureBundle(proposal) && (
<ProposalSignatureBundle
id={deterministicId}
type={proposal.terms?.newAsset ? 'NewAsset' : 'UpdateAsset'}
/>
<SignatureBundleComponent id={deterministicId} tx={tx} />
)}
</>
);
@@ -0,0 +1,2 @@
// The subset of ABI types that we use in relevant types
export type AbiType = 'address' | 'bytes' | 'bytes32' | 'uint256' | 'string';
@@ -0,0 +1,31 @@
import { keccak256, defaultAbiCoder, isAddress } from 'ethers/lib/utils';
import type { AbiType } from './abi-types';
export const BRIDGE_COMMAND: AbiType[] = [
// The abi encoded bytes of the message
'bytes',
// The address of the bridge
'address',
];
/**
* ABI encode values for a bridge call, getting back its digest
*
* @param bytes The packed bytes of the command for the bridge
* @param address the Ethereum address of the ERC20 bridge
* @param raw defaults to false. If set, does not keccak256 the output
*/
export function encodeBridgeCommand(
bytes: string,
address: string,
raw = false
) {
if (!isAddress(address)) {
throw new Error('Bridge address must be a hex value');
}
const values = [bytes, address];
const value = defaultAbiCoder.encode(BRIDGE_COMMAND, values);
return raw === true ? value : keccak256(value);
}
@@ -0,0 +1,31 @@
import { encodeBridgeCommand } from './bridge-command';
describe('Bridge command encoder', () => {
const VALID_BYTES =
'0x000000000000000000000000b063f5504610ba4b8db230d9f884bfadc1e31da00b87ac58d4af7fc11c8b417153fcb62631cfd9643835ef28db3f5a1caef0b3790000000000000000000000000000000000000000000000487a9a30453944000000000000000000000000000000000000000000000000000000000000000000010b87ac58d4af7fc11c8b417153fcb62631cfd9643835ef28db3f5a1caef0b37900000000000000000000000000000000000000000000000000000000000000c0000000000000000000000000000000000000000000000000000000000000000a6c6973745f617373657400000000000000000000000000000000000000000000';
const VALID_ADDRESS = '0x7fe27d970bc8Afc3B11Cc8d9737bfB66B1efd799';
it('rejects non valid bridge addresses', () => {
expect(() => {
encodeBridgeCommand(VALID_BYTES, '456789');
}).toThrowError('Bridge address must be a hex value');
});
it('throws if the bytes are not bytes-like', () => {
expect(() => {
encodeBridgeCommand('hello', VALID_ADDRESS);
}).toThrowError(/invalid/);
});
it('keccac256s the value by default', () => {
const res = encodeBridgeCommand(VALID_BYTES, VALID_ADDRESS);
// Magic number: Known output, including 0x
expect(res.length).toEqual(66);
});
it('Does not keccac256 the value if third param is set', () => {
const res = encodeBridgeCommand(VALID_BYTES, VALID_ADDRESS, true);
// Magic number: Known output
expect(res.length).toEqual(706);
});
});
@@ -0,0 +1,76 @@
import { encodeListAsset, encodeListAssetBridgeTx } from './list-asset';
describe('List Asset ABI encoder', () => {
it('throws if asset erc20 address is invalid', () => {
expect(() => {
encodeListAsset({
assetERC20: '123',
assetId: '0x456',
limit: '1',
threshold: '1',
nonce: '1',
});
}).toThrowError('Asset ERC20 and assetID must be hex values');
});
it('throws if assetId is not hex encoded', () => {
expect(() => {
encodeListAsset({
assetERC20: '0x123',
assetId: '456',
limit: '1',
threshold: '1',
nonce: '1',
});
}).toThrowError('Asset ERC20 and assetID must be hex values');
});
it('throws if values to not match expected format', () => {
expect(() => {
encodeListAsset({
assetERC20: '0xb063f5504610ba4b8db230d9f884bfadc1e31da0',
assetId: '0xb063f5504610ba4b8db230d9f884bfadc1e31da0',
limit: 'not a valid number',
threshold: '1',
nonce: '1',
});
}).toThrowError(/incorrect data length/);
});
it('returns an ABI encoded value if inputs are valid', () => {
const EXPECTED_OUTPUT =
'0x000000000000000000000000b063f5504610ba4b8db230d9f884bfadc1e31da00b87ac58d4af7fc11c8b417153fcb62631cfd9643835ef28db3f5a1caef0b37900000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000c0000000000000000000000000000000000000000000000000000000000000000a6c6973745f617373657400000000000000000000000000000000000000000000';
const res = encodeListAsset({
assetERC20: '0xb063f5504610ba4b8db230d9f884bfadc1e31da0',
assetId:
'0x0b87ac58d4af7fc11c8b417153fcb62631cfd9643835ef28db3f5a1caef0b379',
limit: '1',
threshold: '1',
nonce: '1',
});
expect(res).toEqual(EXPECTED_OUTPUT);
});
it('encodeListAssetBridge returns a keccak256 hash of the bridge tx', () => {
const EXPECTED_OUTPUT =
'0xe0e62b27fe4490025d312bb2e37486f56935a3d9442dc34c2b918b2a28a386f2';
const res = encodeListAssetBridgeTx(
{
assetERC20: '0xb063f5504610ba4b8db230d9f884bfadc1e31da0',
assetId:
'0x0b87ac58d4af7fc11c8b417153fcb62631cfd9643835ef28db3f5a1caef0b379',
limit: '1',
threshold: '1',
nonce: '1',
},
'0xb063f5504610ba4b8db230d9f884bfadc1e31da0'
);
// Magic number: keccak256 hash length + '0x'
expect(res.length).toEqual(66);
expect(res).toEqual(EXPECTED_OUTPUT);
});
});
@@ -0,0 +1,76 @@
import { defaultAbiCoder, isAddress, isHexString } from 'ethers/lib/utils';
import { encodeBridgeCommand } from './bridge-command';
import type { AbiType } from './abi-types';
export const METHOD_NAME = 'list_asset';
export const LIST_ASSET_ABI: AbiType[] = [
// Asset address
'address',
// Asset ID on Vega
'bytes32',
// Lifetime limit
'uint256',
// Withdraw threshold
'uint256',
// Nonce
'uint256',
// Contract method name
'string',
];
export interface EncodeListAssetParameters {
// The ETH address of the ERC20 asset
assetERC20: string;
// The Vega ID of the asset, 0x prefixed
assetId: string;
// The number as a string of the asset
limit: string;
// THe number-as-a-string of the withdraw threshold
threshold: string;
// The n-once supplied to the contract
nonce: string;
}
/**
* Generates an ABI encoded function call to list an asset. This is
* used in the Signature Bundle view on some proposals to recover
* which validators signed a multisig bundle. It does this by recovering
* the ERC20 addresses of the signers, then comparing those to the list
* of signers on the bundle. In order to do this, we recreate the signed
* data from the values we know from the transaction. That last part
* is what this function does.
*
* @param EncodeListAssetParameters The arguments for the ABI call
* @returns string encoded message
*/
export function encodeListAsset({
assetERC20,
assetId,
limit,
threshold,
nonce,
}: EncodeListAssetParameters) {
if (!isAddress(assetERC20) || !isHexString(assetId)) {
throw new Error('Asset ERC20 and assetID must be hex values');
}
const values = [assetERC20, assetId, limit, threshold, nonce, METHOD_NAME];
return defaultAbiCoder.encode(LIST_ASSET_ABI, values);
}
/**
* Convenience function that encodes and packs the message as it is encoded by the
* validators in a multisig bundle
*
* @param params Parameters for the List Asset call
* @param bridgeAddress Bridge address for the appropiate network
* @returns keccak256 encoded message digest
*/
export function encodeListAssetBridgeTx(
params: EncodeListAssetParameters,
bridgeAddress: string
) {
return encodeBridgeCommand(encodeListAsset(params), bridgeAddress);
}
@@ -0,0 +1,58 @@
import { encodeUpdateAsset, encodeUpdateAssetBridgeTx } from './update-asset';
describe('Update Asset ABI encoder', () => {
it('throws if asset erc20 address is invalid', () => {
expect(() => {
encodeUpdateAsset({
assetERC20: '123',
limit: '1',
threshold: '1',
nonce: '1',
});
}).toThrowError('Asset ERC20 must be a valid address');
});
it('throws if an input is invalid', () => {
expect(() => {
encodeUpdateAsset({
assetERC20: '0xb063f5504610ba4b8db230d9f884bfadc1e31da0',
limit: 'hello',
threshold: '1',
nonce: '1',
});
}).toThrowError(/invalid BigNumber/);
});
it('returns an ABI encoded value if inputs are valid', () => {
const EXPECTED_OUTPUT =
'0x000000000000000000000000b063f5504610ba4b8db230d9f884bfadc1e31da000000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000a000000000000000000000000000000000000000000000000000000000000000107365745f61737365745f6c696d69747300000000000000000000000000000000';
const res = encodeUpdateAsset({
assetERC20: '0xb063f5504610ba4b8db230d9f884bfadc1e31da0',
limit: '1',
threshold: '1',
nonce: '1',
});
expect(res).toEqual(EXPECTED_OUTPUT);
});
it('encodeUpdateAssetBridge returns a keccak256 hash of the bridge tx', () => {
const EXPECTED_OUTPUT =
'0xeb240131c4558aebfab3da0ddbea1ac0447b9f5670899af2d78795867631d877';
const res = encodeUpdateAssetBridgeTx(
{
assetERC20: '0xb063f5504610ba4b8db230d9f884bfadc1e31da0',
limit: '1',
threshold: '1',
nonce: '1',
},
'0xb063f5504610ba4b8db230d9f884bfadc1e31da0'
);
// Magic number: keccak256 hash length + '0x'
expect(res.length).toEqual(66);
expect(res).toEqual(EXPECTED_OUTPUT);
});
});
@@ -0,0 +1,65 @@
import { defaultAbiCoder, isAddress } from 'ethers/lib/utils';
import { encodeBridgeCommand } from './bridge-command';
import type { AbiType } from './abi-types';
export const METHOD_NAME = 'set_asset_limits';
export const LIST_ASSET_ABI: AbiType[] = [
// Asset address
'address',
// Lifetime limit
'uint256',
// Withdraw threshold
'uint256',
// Nonce
'uint256',
// Contract method name
'string',
];
export interface EncodeUpdateAssetParameters {
// The ETH address of the ERC20 asset
assetERC20: string;
// The number as a string of the asset
limit: string;
// THe number-as-a-string of the withdraw threshold
threshold: string;
// The n-once supplied to the contract
nonce: string;
}
/**
* Generates an ABI encoded function call to list an asset
*
* @param EncodeListAssetParameters The arguments for the ABI call
* @returns string encoded message
*/
export function encodeUpdateAsset({
assetERC20,
limit,
threshold,
nonce,
}: EncodeUpdateAssetParameters) {
if (!isAddress(assetERC20)) {
throw new Error('Asset ERC20 must be a valid address');
}
const values = [assetERC20, limit, threshold, nonce, METHOD_NAME];
return defaultAbiCoder.encode(LIST_ASSET_ABI, values);
}
/**
* Convenience function that encodes and packs the message as it is encoded by the
* validators in a multisig bundle
*
* @param params Parameters for the List Asset call
* @param bridgeAddress Bridge address for the appropiate network
* @returns keccak256 encoded message digest
*/
export function encodeUpdateAssetBridgeTx(
params: EncodeUpdateAssetParameters,
bridgeAddress: string
) {
return encodeBridgeCommand(encodeUpdateAsset(params), bridgeAddress);
}
+8 -3
View File
@@ -1,14 +1,19 @@
import { StatsManager } from '@vegaprotocol/network-stats';
import { SearchForm } from '../../components/search';
import { useDocumentTitle } from '../../hooks/use-document-title';
const Home = () => {
const classnames = 'mt-4 grid grid-cols-1 lg:grid-cols-2 lg:gap-4';
const classnames = 'mt-4 mb-4';
useDocumentTitle();
return (
<section>
<StatsManager className={classnames} />
<div className="p-20 max-sm:py-10 max-sm:px-0">
<SearchForm />
</div>
<div className="px-20 max-sm:px-0">
<StatsManager className={classnames} />
</div>
</section>
);
};
-26
View File
@@ -1,26 +0,0 @@
import React from 'react';
import { useRoutes } from 'react-router-dom';
import { RouteErrorBoundary } from '../components/router-error-boundary';
import routerConfig from './router-config';
import { Loader, Splash } from '@vegaprotocol/ui-toolkit';
export interface RouteChildProps {
name: string;
}
export const AppRouter = () => {
const routes = useRoutes(routerConfig);
const splashLoading = (
<Splash>
<Loader />
</Splash>
);
return (
<RouteErrorBoundary>
<React.Suspense fallback={splashLoading}>{routes}</React.Suspense>
</RouteErrorBoundary>
);
};
+187
View File
@@ -0,0 +1,187 @@
import {
AssetDetailsDialog,
useAssetDetailsDialogStore,
} from '@vegaprotocol/assets';
import { t } from '@vegaprotocol/i18n';
import {
AnnouncementBanner,
BackgroundVideo,
BreadcrumbsContainer,
ButtonLink,
ExternalLink,
Icon,
} from '@vegaprotocol/ui-toolkit';
import classNames from 'classnames';
import { useState } from 'react';
import {
isRouteErrorResponse,
Link,
Outlet,
useMatch,
useRouteError,
} from 'react-router-dom';
import { Footer } from '../components/footer/footer';
import { Header } from '../components/header';
import { Routes } from './route-names';
const DialogsContainer = () => {
const { isOpen, id, trigger, asJson, setOpen } = useAssetDetailsDialogStore();
return (
<AssetDetailsDialog
assetId={id}
trigger={trigger || null}
asJson={asJson}
open={isOpen}
onChange={setOpen}
/>
);
};
const MainnetSimAd = () => {
const [shouldDisplayBanner, setShouldDisplayBanner] = useState<boolean>(true);
// Return an empty div so that the grid layout in _app.page.ts
// renders correctly
if (!shouldDisplayBanner) {
return <div />;
}
return (
<AnnouncementBanner>
<div className="grid grid-cols-[auto_1fr] gap-4 font-alpha calt uppercase text-center text-lg text-white">
<button
className="flex items-center"
onClick={() => setShouldDisplayBanner(false)}
>
<Icon name="cross" className="w-6 h-6" ariaLabel="dismiss" />
</button>
<div>
<span className="pr-4">Mainnet sim 3 is live!</span>
<ExternalLink href="https://fairground.wtf/">Learn more</ExternalLink>
</div>
</div>
</AnnouncementBanner>
);
};
export const Layout = () => {
const isHome = Boolean(useMatch(Routes.HOME));
return (
<>
<div
className={classNames(
'max-w-[1500px] min-h-[100vh]',
'mx-auto my-0',
'grid grid-rows-[auto_1fr_auto] grid-cols-1',
'border-vega-light-200 dark:border-vega-dark-200 lg:border-l lg:border-r',
'antialiased text-black dark:text-white',
'overflow-hidden relative'
)}
>
<div>
<MainnetSimAd />
<Header />
</div>
<div>
<main className="p-4">
{!isHome && <BreadcrumbsContainer className="mb-4" />}
<Outlet />
</main>
</div>
<div>
<Footer />
</div>
</div>
<DialogsContainer />
</>
);
};
export const ErrorBoundary = () => {
const error = useRouteError();
const errorTitle = isRouteErrorResponse(error)
? `${error.status} ${error.statusText}`
: t('Something went wrong');
const errorMessage = isRouteErrorResponse(error)
? error.error?.message
: (error as Error).message || JSON.stringify(error);
return (
<>
<BackgroundVideo className="brightness-50" />
<div
className={classNames(
'max-w-[620px] p-2 mt-[10vh]',
'mx-auto my-0',
'antialiased text-white',
'overflow-hidden relative',
'flex flex-col gap-2'
)}
>
<div className="flex gap-4">
<div>{GHOST}</div>
<h1 className="text-[2.7rem] font-alpha calt break-words uppercase">
{errorTitle}
</h1>
</div>
<div className="text-sm mt-10 overflow-auto break-all font-mono">
{errorMessage}
</div>
<div>
<ButtonLink onClick={() => window.location.reload()}>
{t('Try refreshing')}
</ButtonLink>{' '}
{t('or go back to')}{' '}
<Link className="underline" to="/">
{t('Home')}
</Link>
</div>
</div>
</>
);
};
const GHOST = (
<svg
width="56"
height="85"
viewBox="0 0 56 85"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<path d="M41 0.5H3V60.5H41V0.5Z" fill="white" />
<path d="M15 18.5H13V20.5H15V18.5Z" fill="black" />
<path d="M17 20.5H15V22.5H17V20.5Z" fill="black" />
<path d="M19 18.5H17V20.5H19V18.5Z" fill="black" />
<path d="M15 22.5H13V24.5H15V22.5Z" fill="black" />
<path d="M19 22.5H17V24.5H19V22.5Z" fill="black" />
<path d="M29 28.5H15V30.5H29V28.5Z" fill="black" />
<path d="M27 18.5H25V20.5H27V18.5Z" fill="black" />
<path d="M29 20.5H27V22.5H29V20.5Z" fill="black" />
<path d="M31 18.5H29V20.5H31V18.5Z" fill="black" />
<path d="M27 22.5H25V24.5H27V22.5Z" fill="black" />
<path d="M31 22.5H29V24.5H31V22.5Z" fill="black" />
<path d="M31 26.5H29V28.5H31V26.5Z" fill="black" />
<path d="M19 60.5H17V84.5H19V60.5Z" fill="black" />
<path d="M27 60.5H25V84.5H27V60.5Z" fill="black" />
<path
d="M3 42.5V58.64V60.5V64.5H21V60.5H23V64.5H41V60.5V58.64V42.5H3Z"
fill="#FF077F"
/>
<path d="M35 46.5H41V42.5H3V46.5H31H35Z" fill="#CB0666" />
<path d="M3 32.32V29.5L0 32.5V60.5H2V33.33L3 32.32Z" fill="black" />
<path d="M41 31.8V29.49L54.79 21.53L55.79 23.26L41 31.8Z" fill="black" />
<path d="M36 54.5H35V55.5H36V54.5Z" fill="black" />
<path d="M35 53.5H34V54.5H35V53.5Z" fill="black" />
<path d="M34 48.5H33V53.5H34V48.5Z" fill="black" />
<path d="M38 48.5H37V52.5H38V48.5Z" fill="black" />
<path d="M37 53.5H36V54.5H37V53.5Z" fill="black" />
<path d="M39 52.5H38V53.5H39V52.5Z" fill="black" />
<path
d="M55.7901 23.27L53.0601 22.54L45.1001 8.75L46.8301 7.75L55.7901 23.27Z"
fill="black"
/>
</svg>
);
@@ -8,7 +8,7 @@ import { useScrollToLocation } from '../../hooks/scroll-to-location';
import { useDocumentTitle } from '../../hooks/use-document-title';
import compact from 'lodash/compact';
import { JsonViewerDialog } from '../../components/dialogs/json-viewer-dialog';
import { marketInfoProvider } from '@vegaprotocol/market-info';
import { marketInfoWithDataProvider } from '@vegaprotocol/market-info';
import { PageTitle } from '../../components/page-helpers/page-title';
export const MarketPage = () => {
@@ -17,7 +17,7 @@ export const MarketPage = () => {
const { marketId } = useParams<{ marketId: string }>();
const { data, loading, error } = useDataProvider({
dataProvider: marketInfoProvider,
dataProvider: marketInfoWithDataProvider,
skipUpdates: true,
variables: {
marketId: marketId || '',
@@ -31,6 +31,7 @@ const PERCENTAGE_PARAMS = [
'governance.proposal.updateMarket.requiredParticipationLP',
'governance.proposal.updateNetParam.requiredMajority',
'governance.proposal.updateNetParam.requiredParticipation',
'governance.proposal.updateMarket.minProposerEquityLikeShare',
'validators.vote.required',
];
+205 -76
View File
@@ -8,7 +8,6 @@ import { Oracle } from './oracles/id';
import Party from './parties';
import { Parties } from './parties/home';
import { Party as PartySingle } from './parties/id';
import Txs from './txs';
import { ValidatorsPage } from './validators';
import Genesis from './genesis';
import { Block } from './blocks/id';
@@ -20,19 +19,55 @@ import flags from '../config/flags';
import { t } from '@vegaprotocol/i18n';
import { Routes } from './route-names';
import { NetworkParameters } from './network-parameters';
import type { RouteObject } from 'react-router-dom';
import type { Params, RouteObject } from 'react-router-dom';
import { createBrowserRouter } from 'react-router-dom';
import { Link } from 'react-router-dom';
import { MarketPage, MarketsPage } from './markets';
import type { ReactNode } from 'react';
import { ErrorBoundary, Layout } from './layout';
import compact from 'lodash/compact';
import { AssetLink, MarketLink } from '../components/links';
import { truncateMiddle } from '@vegaprotocol/ui-toolkit';
import { remove0x } from '@vegaprotocol/utils';
export type Navigable = { path: string; name: string; text: string };
type Route = RouteObject & Navigable;
export type Navigable = {
path: string;
handle: {
name: string;
text: string;
};
};
export const isNavigable = (item: RouteObject): item is Navigable =>
(item as Navigable).path !== undefined &&
(item as Navigable).handle !== undefined &&
(item as Navigable).handle.name !== undefined &&
(item as Navigable).handle.text !== undefined;
export type Breadcrumbable = {
handle: { breadcrumb: (data?: Params<string>) => ReactNode | string };
};
export const isBreadcrumbable = (item: RouteObject): item is Breadcrumbable =>
(item as Breadcrumbable).handle !== undefined &&
(item as Breadcrumbable).handle.breadcrumb !== undefined;
type RouteItem =
| RouteObject
| (RouteObject & Navigable)
| (RouteObject & Breadcrumbable);
type Route = RouteItem & {
children?: RouteItem[];
};
const partiesRoutes: Route[] = flags.parties
? [
{
path: Routes.PARTIES,
name: 'Parties',
text: t('Parties'),
element: <Party />,
handle: {
name: t('Parties'),
text: t('Parties'),
breadcrumb: () => <Link to={Routes.PARTIES}>{t('Parties')}</Link>,
},
children: [
{
index: true,
@@ -41,6 +76,13 @@ const partiesRoutes: Route[] = flags.parties
{
path: ':party',
element: <PartySingle />,
handle: {
breadcrumb: (params: Params<string>) => (
<Link to={linkTo(Routes.PARTIES, params.party)}>
{truncateMiddle(params.party as string)}
</Link>
),
},
},
],
},
@@ -51,8 +93,11 @@ const assetsRoutes: Route[] = flags.assets
? [
{
path: Routes.ASSETS,
text: t('Assets'),
name: 'Assets',
handle: {
name: t('Assets'),
text: t('Assets'),
breadcrumb: () => <Link to={Routes.ASSETS}>{t('Assets')}</Link>,
},
children: [
{
index: true,
@@ -61,6 +106,11 @@ const assetsRoutes: Route[] = flags.assets
{
path: ':assetId',
element: <AssetPage />,
handle: {
breadcrumb: (params: Params<string>) => (
<AssetLink assetId={params.assetId as string} />
),
},
},
],
},
@@ -71,8 +121,13 @@ const genesisRoutes: Route[] = flags.genesis
? [
{
path: Routes.GENESIS,
name: 'Genesis',
text: t('Genesis Parameters'),
handle: {
name: t('Genesis'),
text: t('Genesis Parameters'),
breadcrumb: () => (
<Link to={Routes.GENESIS}>{t('Genesis Parameters')}</Link>
),
},
element: <Genesis />,
},
]
@@ -82,8 +137,13 @@ const governanceRoutes: Route[] = flags.governance
? [
{
path: Routes.GOVERNANCE,
name: 'Governance proposals',
text: t('Governance Proposals'),
handle: {
name: t('Governance proposals'),
text: t('Governance Proposals'),
breadcrumb: () => (
<Link to={Routes.GOVERNANCE}>{t('Governance Proposals')}</Link>
),
},
element: <Proposals />,
},
]
@@ -93,8 +153,11 @@ const marketsRoutes: Route[] = flags.markets
? [
{
path: Routes.MARKETS,
name: 'Markets',
text: t('Markets'),
handle: {
name: t('Markets'),
text: t('Markets'),
breadcrumb: () => <Link to={Routes.MARKETS}>{t('Markets')}</Link>,
},
children: [
{
index: true,
@@ -103,6 +166,11 @@ const marketsRoutes: Route[] = flags.markets
{
path: ':marketId',
element: <MarketPage />,
handle: {
breadcrumb: (params: Params<string>) => (
<MarketLink id={params.marketId as string} />
),
},
},
],
},
@@ -113,90 +181,151 @@ const networkParametersRoutes: Route[] = flags.networkParameters
? [
{
path: Routes.NETWORK_PARAMETERS,
name: 'NetworkParameters',
text: t('Network Parameters'),
handle: {
name: t('NetworkParameters'),
text: t('Network Parameters'),
breadcrumb: () => (
<Link to={Routes.NETWORK_PARAMETERS}>
{t('Network Parameters')}
</Link>
),
},
element: <NetworkParameters />,
},
]
: [];
const validators: Route[] = flags.validators
? [
{
path: Routes.VALIDATORS,
name: 'Validators',
text: t('Validators'),
handle: {
name: t('Validators'),
text: t('Validators'),
breadcrumb: () => (
<Link to={Routes.VALIDATORS}>{t('Validators')}</Link>
),
},
element: <ValidatorsPage />,
},
]
: [];
const routerConfig: Route[] = [
const linkTo = (...segments: (string | undefined)[]) =>
compact(segments).join('/');
export const routerConfig: Route[] = [
{
path: Routes.HOME,
name: 'Home',
text: t('Home'),
element: <Home />,
index: true,
},
{
path: Routes.TX,
name: 'Txs',
text: t('Transactions'),
element: <Txs />,
children: [
{
path: 'pending',
element: <PendingTxs />,
},
{
path: ':txHash',
element: <Tx />,
},
{
index: true,
element: <TxsList />,
},
],
},
{
path: Routes.BLOCKS,
name: 'Blocks',
text: t('Blocks'),
element: <BlockPage />,
element: <Layout />,
handle: {
name: t('Home'),
text: t('Home'),
breadcrumb: () => <Link to={Routes.HOME}>{t('Home')}</Link>,
},
errorElement: <ErrorBoundary />,
children: [
{
index: true,
element: <Blocks />,
element: <Home />,
},
{
path: ':block',
element: <Block />,
path: Routes.TX,
handle: {
name: t('Txs'),
text: t('Transactions'),
breadcrumb: () => <Link to={Routes.TX}>{t('Transactions')}</Link>,
},
children: [
{
path: 'pending',
element: <PendingTxs />,
handle: {
breadcrumb: () => (
<Link to={linkTo(Routes.TX, 'pending')}>
{t('Pending transactions')}
</Link>
),
},
},
{
path: ':txHash',
element: <Tx />,
handle: {
breadcrumb: (params: Params<string>) => (
<Link to={linkTo(Routes.TX, params.txHash)}>
{truncateMiddle(remove0x(params.txHash as string))}
</Link>
),
},
},
{
index: true,
element: <TxsList />,
},
],
},
{
path: Routes.BLOCKS,
handle: {
name: t('Blocks'),
text: t('Blocks'),
breadcrumb: () => <Link to={Routes.BLOCKS}>{t('Blocks')}</Link>,
},
element: <BlockPage />,
children: [
{
index: true,
element: <Blocks />,
},
{
path: ':block',
element: <Block />,
handle: {
breadcrumb: (params: Params<string>) => (
<Link to={linkTo(Routes.BLOCKS, params.block)}>
{params.block}
</Link>
),
},
},
],
},
{
path: Routes.ORACLES,
handle: {
name: t('Oracles'),
text: t('Oracles'),
breadcrumb: () => <Link to={Routes.ORACLES}>{t('Oracles')}</Link>,
},
element: <OraclePage />,
children: [
{
index: true,
element: <Oracles />,
},
{
path: ':id',
element: <Oracle />,
handle: {
breadcrumb: (params: Params<string>) => (
<Link to={linkTo(Routes.ORACLES, params.id)}>
{truncateMiddle(params.id as string)}
</Link>
),
},
},
],
},
...partiesRoutes,
...assetsRoutes,
...genesisRoutes,
...governanceRoutes,
...marketsRoutes,
...networkParametersRoutes,
...validators,
],
},
{
path: Routes.ORACLES,
name: 'Oracles',
text: t('Oracles'),
element: <OraclePage />,
children: [
{
index: true,
element: <Oracles />,
},
{
path: ':id',
element: <Oracle />,
},
],
},
...partiesRoutes,
...assetsRoutes,
...genesisRoutes,
...governanceRoutes,
...marketsRoutes,
...networkParametersRoutes,
...validators,
];
export default routerConfig;
export const router = createBrowserRouter(routerConfig);
+3 -16
View File
@@ -1,5 +1,4 @@
import React from 'react';
import { Link, useParams } from 'react-router-dom';
import { useParams } from 'react-router-dom';
import { remove0x } from '@vegaprotocol/utils';
import { useFetch } from '@vegaprotocol/react-helpers';
import { DATA_SOURCES } from '../../../config';
@@ -8,9 +7,6 @@ import { TxDetails } from './tx-details';
import type { BlockExplorerTransaction } from '../../../routes/types/block-explorer-response';
import { toNonHex } from '../../../components/search/detect-search';
import { PageHeader } from '../../../components/page-header';
import { Routes } from '../../../routes/route-names';
import { IconNames } from '@blueprintjs/icons';
import { Icon } from '@vegaprotocol/ui-toolkit';
import { useDocumentTitle } from '../../../hooks/use-document-title';
const Tx = () => {
@@ -22,6 +18,7 @@ const Tx = () => {
const {
state: { data, loading, error },
refetch,
} = useFetch<BlockExplorerTransaction>(
`${DATA_SOURCES.blockExplorerUrl}/transactions/${toNonHex(hash)}`
);
@@ -34,17 +31,6 @@ const Tx = () => {
return (
<section>
<Link
className="font-normal underline underline-offset-4 block mb-5"
to={`/${Routes.TX}`}
>
<Icon
className="text-vega-light-150 dark:text-vega-light-150"
name={IconNames.CHEVRON_LEFT}
/>
All Transactions
</Link>
<PageHeader
title="transaction"
truncateStart={5}
@@ -56,6 +42,7 @@ const Tx = () => {
error={error}
loading={loading}
errorMessage={errorMessage}
refetch={refetch}
>
<TxDetails
className="mb-28"
@@ -21,7 +21,7 @@ import { JsonViewerDialog } from '../../components/dialogs/json-viewer-dialog';
import { PageTitle } from '../../components/page-helpers/page-title';
import BigNumber from 'bignumber.js';
import {
ContractAddressLink,
EtherscanLink,
DApp,
TOKEN_VALIDATOR,
useLinks,
@@ -176,25 +176,14 @@ export const ValidatorsPage = () => {
const validatorName =
v.name && v.name.length > 0 ? v.name : truncateMiddle(v.id);
return (
<li className="mb-5" key={v.id}>
<li className="mb-5 relative" key={v.id}>
<div
data-testid="validator-tile"
validator-id={v.id}
className="border border-vega-light-200 dark:border-vega-dark-200 rounded p-2 overflow-hidden relative flex gap-2 items-start justify-between"
className="border border-vega-light-200 dark:border-vega-dark-200 rounded p-2 overflow-hidden"
>
{v.avatarUrl && (
<div className="w-20">
<ExternalLink href={validatorPage}>
<img
className="w-full"
src={v.avatarUrl}
alt={validatorName}
/>
</ExternalLink>
</div>
)}
<div className="w-full">
<h2 className="font-alpha text-2xl">
<h2 className="font-alpha text-2xl leading-[60px]">
<ExternalLink href={validatorPage}>
{validatorName}
</ExternalLink>
@@ -235,7 +224,7 @@ export const ValidatorsPage = () => {
<KeyValueTableRow>
<div>{t('Ethereum address')}</div>
<div className="break-all text-xs">
<ContractAddressLink address={v.ethereumAddress} />{' '}
<EtherscanLink address={v.ethereumAddress} />{' '}
<CopyWithTooltip text={v.ethereumAddress}>
<button title={t('Copy address to clipboard')}>
<Icon size={3} name="duplicate" />
@@ -315,6 +304,23 @@ export const ValidatorsPage = () => {
</div>
</div>
</KeyValueTableRow>
{v.avatarUrl && (
<KeyValueTableRow>
<div>{t('Avatar')}</div>
<div>
<ExternalLink
href={validatorPage}
className="mx-auto"
>
<img
className="max-w-[75px] md:max-w-[200px] max-h-[80px]"
src={v.avatarUrl}
alt={validatorName}
/>
</ExternalLink>
</div>
</KeyValueTableRow>
)}
</KeyValueTable>
</div>
</div>
+10
View File
@@ -3,3 +3,13 @@
// expect(element).toHaveTextContent(/react/i)
// learn more: https://github.com/testing-library/jest-dom
import '@testing-library/jest-dom';
Object.defineProperty(window, 'ResizeObserver', {
writable: false,
value: jest.fn().mockImplementation(() => ({
observe: jest.fn(),
unobserve: jest.fn(),
connect: jest.fn(),
disconnect: jest.fn(),
})),
});
+1 -4
View File
@@ -1,5 +1,4 @@
import { createRoot } from 'react-dom/client';
import { BrowserRouter } from 'react-router-dom';
import './styles.css';
import App from './app/app';
@@ -10,8 +9,6 @@ const root = rootElement && createRoot(rootElement);
root?.render(
<StrictMode>
<BrowserRouter>
<App />
</BrowserRouter>
<App />
</StrictMode>
);
@@ -2,6 +2,8 @@
"changes": {
"decimalPlaces": "5",
"positionDecimalPlaces": "5",
"linearSlippageFactor": "0.001",
"quadraticSlippageFactor": "0",
"lpPriceRange": "10",
"instrument": {
"name": "Token test market",
@@ -1,5 +1,7 @@
{
"lpPriceRange": "10",
"linearSlippageFactor": "0.001",
"quadraticSlippageFactor": "0",
"instrument": {
"code": "TEST.24h",
"future": {
@@ -0,0 +1,103 @@
const vegaAssetAddress = '0x67175Da1D5e966e40D11c4B2519392B2058373de';
const vegaWalletUnstakedBalance =
'[data-testid="vega-wallet-balance-unstaked"]';
const rewardsTable = 'epoch-total-rewards-table';
const txTimeout = Cypress.env('txTimeout');
const rewardsTimeOut = { timeout: 60000 };
context('rewards - flow', { tags: '@slow' }, function () {
before('set up environment to allow rewards', function () {
cy.visit('/');
cy.wait_for_spinner();
cy.deposit_asset(vegaAssetAddress, '1000');
cy.validatorsSelfDelegate();
cy.ethereum_wallet_connect();
cy.connectVegaWallet();
topUpRewardsPool();
cy.navigate_to('validators');
cy.vega_wallet_teardown();
cy.staking_page_associate_tokens('6000');
cy.get(vegaWalletUnstakedBalance, txTimeout).should(
'contain',
'6,000.0',
txTimeout
);
cy.get('button').contains('Select a validator to nominate').click();
cy.click_on_validator_from_list(0);
cy.staking_validator_page_add_stake('3000');
cy.close_staking_dialog();
cy.navigate_to('validators');
cy.click_on_validator_from_list(1);
cy.staking_validator_page_add_stake('3000');
cy.close_staking_dialog();
cy.navigate_to('rewards');
});
it('Should display rewards per epoch', function () {
cy.getByTestId(rewardsTable, rewardsTimeOut).should('exist');
cy.getByTestId(rewardsTable)
.first()
.within(() => {
cy.getByTestId('asset').should('have.text', 'Vega');
cy.getByTestId('ACCOUNT_TYPE_GLOBAL_REWARD').should('have.text', '1');
cy.getByTestId('ACCOUNT_TYPE_FEES_INFRASTRUCTURE').should(
'have.text',
'0'
);
cy.getByTestId('total').should('have.text', '1');
});
});
it('Should update when epoch starts', function () {
cy.getByTestId(rewardsTable)
.first()
.within(() => {
cy.get('h2').first().invoke('text').as('epochNumber');
});
cy.wait_for_beginning_of_epoch();
cy.get('@epochNumber').then((epochNumber) => {
cy.getByTestId(rewardsTable)
.first()
.within(() => {
cy.get('h2').first().invoke('text').should('not.equal', epochNumber);
});
});
});
// 2002-SINC-009 2002-SINC-010 2002-SINC-011 2002-SINC-012
it('Should display table of rewards earned by connected vega wallet', function () {
cy.getByTestId('epoch-reward-view-toggle-individual').click();
cy.getByTestId('connected-vega-key')
.find('span')
.should('have.text', Cypress.env('vegaWalletPublicKey'));
cy.getByTestId('epoch-individual-rewards-table')
.first()
.within(() => {
cy.get('h2').first().should('contain.text', 'EPOCH');
cy.getByTestId('individual-rewards-asset').should('have.text', 'Vega');
cy.getByTestId('ACCOUNT_TYPE_GLOBAL_REWARD')
.should('contain.text', '0.4415')
.and('contain.text', '(44.15%)');
cy.getByTestId('ACCOUNT_TYPE_FEES_INFRASTRUCTURE')
.should('contain.text', '0.0004')
.and('contain.text', '(44.15%)');
cy.getByTestId('total').should('have.text', '0.4419');
});
});
function topUpRewardsPool() {
// Must ensure that test wallet contains assets already and that the tests are within the start and end epochs
cy.exec(
`vega wallet transaction send --wallet ${Cypress.env(
'vegaWalletName'
)} --pubkey ${Cypress.env(
'vegaWalletPublicKey'
)} -p "./src/fixtures/wallet/passphrase" --network DV '{"transfer":{"fromAccountType":4,"toAccountType":12,"to":"0000000000000000000000000000000000000000000000000000000000000000","asset":"b4f2726571fbe8e33b442dc92ed2d7f0d810e21835b7371a7915a365f07ccd9b","amount":"1000000000000000000","recurring":{"startEpoch":30, "endEpoch": 200, "factor":"1"}}}' --home ${Cypress.env(
'vegaWalletLocation'
)}`,
{ failOnNonZeroExit: false }
)
.its('stderr')
.should('contain', '');
}
});
@@ -14,13 +14,14 @@ const stakeShare = '[data-testid="stake-percentage"]';
const vegaWalletPublicKeyShort = Cypress.env('vegaWalletPublicKeyShort');
const vegaWalletAssociatedBalance = '[data-testid="currency-value"]';
const vegaWalletUnstakedBalance =
'[data-testid="vega-wallet-balance-unstaked"]';
'[data-testid="vega-wallet-balance-unstaked"]:visible';
const vegaWalletStakedBalances =
'[data-testid="vega-wallet-balance-staked-validators"]';
const ethWalletAssociatedBalances =
'[data-testid="eth-wallet-associated-balances"]';
const ethWalletTotalAssociatedBalance = '[data-testid="currency-locked"]';
const ethWalletContainer = '[data-testid="ethereum-wallet"]';
const ethWalletTotalAssociatedBalance =
'[data-testid="currency-locked"]:visible';
const ethWalletContainer = '[data-testid="ethereum-wallet"]:visible';
const vegaWallet = '[data-testid="vega-wallet"]';
const partValidatorId = '…';
const txTimeout = Cypress.env('txTimeout');
@@ -27,7 +27,7 @@ context(
function () {
before('visit withdrawals and connect vega wallet', function () {
cy.updateCapsuleMultiSig(); // When running tests locally, will fail if run without restarting capsule
cy.deposit_asset(usdcEthAddress);
cy.deposit_asset(usdcEthAddress, '100000000000000000000');
});
beforeEach('Navigate to withdrawal page', function () {
@@ -1,60 +1,10 @@
const navSection = 'nav';
const navSupply = '[href="/token/tranches"]';
const navToken = '[href="/token"]';
const navStaking = '[href="/validators"]';
const navRewards = '[href="/rewards"]';
const navWithdraw = '[href="/token/withdraw"]';
const navGovernance = '[href="/proposals"]';
const navRedeem = '[href="/token/redeem"]';
context('Home Page - verify elements on page', { tags: '@smoke' }, function () {
before('visit token home page', function () {
cy.visit('/');
cy.get('nav', { timeout: 10000 }).should('be.visible');
});
describe('with wallets disconnected', function () {
before('wait for page to load', function () {
cy.get(navSection, { timeout: 10000 }).should('be.visible');
});
describe('Navigation tabs', function () {
it('should have proposals tab', function () {
cy.get(navSection).within(() => {
cy.get(navGovernance).should('be.visible');
});
});
it('should have validators tab', function () {
cy.get(navSection).within(() => {
cy.get(navStaking).should('be.visible');
});
});
it('should have rewards tab', function () {
cy.get(navSection).within(() => {
cy.get(navRewards).should('be.visible');
});
});
describe('Token dropdown', function () {
before('click on token dropdown', function () {
cy.get(navSection).within(() => {
cy.getByTestId('state-trigger').realClick();
});
});
it('should have token dropdown', function () {
cy.get(navToken).should('be.visible');
});
it('should have supply & vesting dropdown', function () {
cy.get(navSupply).should('be.visible');
});
it('should have withdraw dropdown', function () {
cy.get(navWithdraw).should('be.visible');
});
it('should have redeem dropdown', function () {
cy.get(navRedeem).should('be.visible');
});
});
});
describe('Links and buttons', function () {
it('should have link for proposal page', function () {
cy.getByTestId('home-proposals').within(() => {
@@ -0,0 +1,284 @@
context(
'Landing pages - verifies required elements',
{ tags: '@smoke' },
() => {
const navbar = 'nav .navbar';
const mobileNav = '[data-testid="menu-drawer"]';
const topLevelLinks = [
{
name: 'Proposals',
selector: '[href="/proposals"]',
tests: () => {
it('should be able to see a working link for - find out more about Vega governance', function () {
const governanceDocsUrl = 'https://vega.xyz/governance';
const proposalDocumentationLink =
'[data-testid="proposal-documentation-link"]';
// 3001-VOTE-001
cy.get(proposalDocumentationLink)
.should('be.visible')
.and('have.text', 'Find out more about Vega governance')
.and('have.attr', 'href')
.and('equal', governanceDocsUrl);
// 3002-PROP-001
cy.request(governanceDocsUrl)
.its('body')
.then((body) => {
if (!body.includes('Govern the network')) {
assert.include(
body,
'Govern the network',
`Checking that governance link destination includes 'Govern the network' text`
);
}
});
});
it('should be able to see button for - new proposal', function () {
// 3001-VOTE-002
const newProposalLink = '[data-testid="new-proposal-link"]';
cy.get(newProposalLink)
.should('be.visible')
.and('have.text', 'New proposal')
.and('have.attr', 'href')
.and('equal', '/proposals/propose');
});
},
},
{
name: 'Validators',
selector: '[href="/validators"]',
tests: () => {
it('Should have Staking Guide link visible', function () {
// 2001-STKE-003
cy.get('[data-testid="staking-guide-link"]')
.should('be.visible')
.and('have.text', 'Read more about staking on Vega')
.and(
'have.attr',
'href',
'https://docs.vega.xyz/mainnet/concepts/vega-chain/#staking-on-vega'
);
});
},
},
{
name: 'Rewards',
selector: '[href="/rewards"]',
header: 'Rewards and fees',
tests: () => {
it('should have epoch warning', () => {
cy.get('[data-testid="callout"]')
.should('be.visible')
.and(
'have.text',
'Rewards are credited less than a minute after the epoch ends.This delay is set by a network parameter'
);
});
it('should have toggle for seeing total vs individual rewards', () => {
cy.get('[data-testid="epoch-reward-view-toggle-total"]').should(
'be.visible'
);
});
},
},
];
const secondLevelLinks = [
{
trigger: true,
name: 'Token',
selector: '[data-testid="state-trigger"]',
},
{
name: 'Token',
selector: '[href="/token"]',
header: 'The $VEGA token',
},
{
name: 'Supply & Vesting',
selector: '[href="/token/tranches"]',
header: 'Vesting tranches',
},
{
name: 'Withdraw',
selector: '[href="/token/withdraw"]',
header: 'Withdrawals',
tests: () => {
it('should have connect Vega wallet button', function () {
cy.get('[data-testid="connect-to-vega-wallet-btn"]')
.should('be.visible')
.and('have.text', 'Connect Vega wallet');
});
},
},
{
name: 'Redeem',
selector: '[href="/token/redeem"]',
header: 'Vesting',
tests: () => {
// 1005-VEST-018
it('should have connect Eth wallet button', function () {
cy.get('[data-testid="connect-to-eth-btn"]')
.should('be.visible')
.and('have.text', 'Connect Ethereum wallet');
});
},
},
{
name: 'Associate',
selector: '[href="/token/associate"]',
header: 'Associate $VEGA tokens with Vega Key',
},
{
name: 'Disassociate',
selector: '[href="/token/disassociate"]',
header: 'Disassociate $VEGA tokens from a Vega key',
},
];
const expand = () => {
const trigger = secondLevelLinks.find((l) => l.trigger).selector;
cy.get(trigger).then((el) => {
if (el.attr('aria-expanded') === 'false') {
el.trigger('click');
}
});
};
const collapse = () => {
const trigger = secondLevelLinks.find((l) => l.trigger).selector;
cy.get(trigger).then((el) => {
if (el.attr('aria-expanded') === 'true') {
el.trigger('click');
}
});
};
const ensureHeader = (text) => {
cy.get('main header h1').should('have.text', text);
};
before(() => {
// goes to HOME
cy.visit('/');
// and waits for it to load
cy.get(navbar, { timeout: 10000 }).should('be.visible');
});
describe('Navigation (desktop)', () => {
for (const { name, selector } of topLevelLinks) {
it(`should have ${name} nav link`, () => {
cy.get(navbar).within(() => {
cy.get(selector).should('be.visible');
cy.get(selector).should('have.text', name);
});
});
}
for (const { name, selector, trigger } of secondLevelLinks) {
it(`should have ${name} ${
trigger ? 'as trigger button' : ''
} second level nav link`, () => {
cy.get(navbar).within(() => {
cy.get(selector).should('be.visible');
cy.get(selector).should('have.text', name);
if (trigger) cy.get(selector).click();
});
});
}
after(() => {
collapse();
});
});
describe('Navigation (mobile)', () => {
beforeEach(() => {
// iphone xr
cy.viewport(414, 896);
});
it('should have burger button', () => {
cy.get('[data-testid="button-menu-drawer"]').should('be.visible');
cy.get('[data-testid="button-menu-drawer"]').click();
cy.get(mobileNav).should('be.visible');
});
for (const { name, selector } of topLevelLinks) {
it(`should have ${name} nav link`, () => {
cy.get(mobileNav).within(() => {
cy.get(selector).should('be.visible');
cy.get(selector).should('have.text', name);
});
});
}
for (const { name, selector, trigger } of secondLevelLinks) {
it(`should have ${name} ${
trigger ? 'as trigger button' : ''
} second level nav link`, () => {
cy.get(mobileNav).within(() => {
cy.get(selector).should('be.visible');
cy.get(selector).should('have.text', name);
});
});
}
after(() => {
cy.get('[data-testid="button-menu-drawer"]').click();
cy.viewport(
Cypress.config('viewportWidth'),
Cypress.config('viewportHeight')
);
});
});
describe('Elements', () => {
for (const { name, selector, header, tests } of topLevelLinks) {
describe(`${name} page`, () => {
it(`navigates to ${name}`, () => {
cy.get(navbar).within(() => {
cy.log(`goes to ${name}`);
cy.get(selector).click();
cy.log(`ensures ${name} is highlighted`);
cy.get(selector).should('have.attr', 'aria-current');
});
});
it('displays header', () => {
ensureHeader(header || name);
});
if (tests) tests.apply(this);
});
}
for (const { name, selector, header, tests } of secondLevelLinks.filter(
(l) => !l.trigger
)) {
describe(`${name} page`, () => {
it(`navigates to ${name}`, () => {
cy.get(navbar).within(() => {
expand();
cy.log(`goes to ${name}`);
cy.get(selector).click();
expand();
cy.log(`ensures ${name} is highlighted`);
cy.get(selector).should('have.attr', 'aria-current');
});
});
it('displays header', () => {
ensureHeader(header || name);
});
if (tests) tests.apply(this);
});
}
after(() => {
collapse();
});
});
}
);
@@ -1,68 +0,0 @@
const proposalDocumentationLink = '[data-testid="proposal-documentation-link"]';
const newProposalButton = '[data-testid="new-proposal-link"]';
const newProposalLink = '[data-testid="new-proposal-link"]';
const governanceDocsUrl = 'https://vega.xyz/governance';
const connectToVegaWalletButton = '[data-testid="connect-to-vega-wallet-btn"]';
context(
'Governance Page - verify elements on page',
{ tags: '@smoke' },
function () {
before('navigate to governance page', function () {
cy.visit('/').navigate_to('proposals');
});
describe('with no network change proposals', function () {
it('should have governance tab highlighted', function () {
cy.verify_tab_highlighted('proposals');
});
it('should have GOVERNANCE header visible', function () {
cy.verify_page_header('Proposals');
});
it('should be able to see a working link for - find out more about Vega governance', function () {
// 3001-VOTE-001
cy.get(proposalDocumentationLink)
.should('be.visible')
.and('have.text', 'Find out more about Vega governance')
.and('have.attr', 'href')
.and('equal', governanceDocsUrl);
// 3002-PROP-001
cy.request(governanceDocsUrl)
.its('body')
.then((body) => {
if (!body.includes('Govern the network')) {
assert.include(
body,
'Govern the network',
`Checking that governance link destination includes 'Govern the network' text`
);
}
});
});
it('should be able to see button for - new proposal', function () {
// 3001-VOTE-002
cy.get(newProposalLink)
.should('be.visible')
.and('have.text', 'New proposal')
.and('have.attr', 'href')
.and('equal', '/proposals/propose');
});
// Skipping this test for now, the new proposal button no longer takes a user directly
// to a proposal form, instead it takes them to a page where they can select a proposal type.
// Keeping this test here for now as it can be repurposed to test the new proposal forms.
it.skip('should be able to see a connect wallet button - if vega wallet disconnected and new proposal button selected', function () {
cy.get(newProposalButton).should('be.visible').click();
cy.get(connectToVegaWalletButton)
.should('be.visible')
.and('have.text', 'Connect Vega wallet');
cy.navigate_to('proposals');
cy.wait_for_spinner();
});
});
}
);
@@ -50,7 +50,7 @@ context('View functionality with public key', { tags: '@smoke' }, function () {
});
it('Able to disconnect via wallet', function () {
cy.getByTestId('manage-vega-wallet').click();
cy.get('aside [data-testid="manage-vega-wallet"]').click();
cy.getByTestId('disconnect').click();
cy.getByTestId(banner).should('not.exist');
});
@@ -1,35 +0,0 @@
const viewToggle = '[data-testid="epoch-reward-view-toggle-total"]';
const warning = '[data-testid="callout"]';
context(
'Rewards Page - verify elements on page',
{ tags: '@regression' },
function () {
before('navigate to rewards page', function () {
cy.visit('/').navigate_to('rewards');
});
describe('with wallets disconnected', function () {
it('should have REWARDS tab highlighted', function () {
cy.verify_tab_highlighted('rewards');
});
it('should have rewards header visible', function () {
cy.verify_page_header('Rewards and fees');
});
it('should have epoch warning', function () {
cy.get(warning)
.should('be.visible')
.and(
'have.text',
'Rewards are credited 5 minutes after the epoch ends.This delay is set by a network parameter'
);
});
it('should have toggle for seeing total vs individual rewards', function () {
cy.get(viewToggle).should('be.visible');
});
});
}
);
@@ -17,8 +17,7 @@ const vegaTokenContractAddress = Cypress.env('vegaTokenContractAddress');
context('Verify elements on Token page', { tags: '@smoke' }, function () {
before('Visit token page', function () {
cy.visit('/');
cy.navigate_to('token');
cy.visit('/token');
});
describe('THE $VEGA TOKEN table', function () {
it('should have TOKEN ADDRESS', function () {
@@ -8,13 +8,7 @@ context(
function () {
before('visit homepage', function () {
cy.intercept('GET', '**/tranches/stats', { tranches });
cy.visit('/');
});
it('Able to navigate to tranches page', function () {
cy.navigate_to('supply');
cy.url().should('include', '/token/tranches');
cy.get('h1').should('contain.text', 'Vesting tranches');
cy.visit('/token/tranches');
});
// 1005-VEST-001
@@ -1,5 +1,4 @@
/// <reference types="cypress" />
const guideLink = '[data-testid="staking-guide-link"]';
const validatorTitle = '[data-testid="validator-node-title"]';
const validatorId = '[data-testid="validator-id"]';
const validatorPubKey = '[data-testid="validator-public-key"]';
@@ -25,31 +24,7 @@ const stakeNumberRegex = /^\d*\.?\d*$/;
context('Staking Page - verify elements on page', function () {
before('navigate to staking page', function () {
cy.visit('/').navigate_to('validators');
});
describe('with wallets disconnected', { tags: '@smoke' }, function () {
describe('description section', function () {
it('Should have validators tab highlighted', function () {
cy.verify_tab_highlighted('validators');
});
it('Should have validators ON VEGA header visible', function () {
cy.verify_page_header('Validators');
});
it('Should have Staking Guide link visible', function () {
// 2001-STKE-003
cy.get(guideLink)
.should('be.visible')
.and('have.text', 'Read more about staking on Vega')
.and(
'have.attr',
'href',
'https://docs.vega.xyz/mainnet/concepts/vega-chain/#staking-on-vega'
);
});
});
cy.visit('/validators');
});
describe(
@@ -108,6 +83,7 @@ context('Staking Page - verify elements on page', function () {
.should('contain', 'Normalised voting power: 0.10%');
});
// 2002-SINC-018
it('Should be able to see validator total penalties', function () {
cy.get('[col-id="totalPenalties"] > div > span > span')
.should('have.length.at.least', 1)
@@ -1,4 +1,3 @@
const connectButton = '[data-testid="connect-to-eth-btn"]';
const lockedTokensInVestingContract = '6,499,972.30';
context(
@@ -6,24 +5,7 @@ context(
{ tags: '@smoke' },
function () {
before('navigate to vesting page', function () {
cy.visit('/').navigate_to('vesting');
});
describe('with wallets disconnected', function () {
it('should have vesting tab highlighted', function () {
cy.verify_tab_highlighted('token');
});
it('should have VESTING header visible', function () {
cy.verify_page_header('Vesting');
});
// 1005-VEST-018
it('should have connect Eth wallet button', function () {
cy.get(connectButton)
.should('be.visible')
.and('have.text', 'Connect Ethereum wallet');
});
cy.visit('/token/redeem');
});
describe('With Eth wallet connected', function () {
@@ -38,15 +20,18 @@ context(
cy.getByTestId('currency-title')
.should('contain.text', 'VEGA')
.and('contain.text', 'In vesting contract');
cy.getByTestId('currency-value').should(
cy.get('[data-testid="currency-value"]:visible').should(
'have.text',
lockedTokensInVestingContract
);
cy.getByTestId('currency-locked').should(
cy.get('[data-testid="currency-locked"]:visible').should(
'have.text',
lockedTokensInVestingContract
);
cy.getByTestId('currency-unlocked').should('have.text', '0.00');
cy.get('[data-testid="currency-unlocked"]:visible').should(
'have.text',
'0.00'
);
});
});
// 1005-VEST-022 1005-VEST-023
@@ -1,18 +1,19 @@
const walletContainer = '[data-testid="ethereum-wallet"]';
const walletContainer = 'aside [data-testid="ethereum-wallet"]';
const walletHeader = '[data-testid="wallet-header"] h1';
const connectToEthButton = '[data-testid="connect-to-eth-wallet-button"]';
const connectToEthButton =
'[data-testid="connect-to-eth-wallet-button"]:visible';
const connectorList = '[data-testid="web3-connector-list"]';
const associate = '[href="/token/associate"]';
const disassociate = '[href="/token/disassociate"]';
const disconnect = '[data-testid="disconnect-from-eth-wallet-button"]';
const accountNo = '[data-testid="ethereum-account-truncated"]';
const currencyTitle = '[data-testid="currency-title"]';
const currencyValue = '[data-testid="currency-value"]';
const vegaInVesting = '[data-testid="vega-in-vesting-contract"]';
const vegaInWallet = '[data-testid="vega-in-wallet"]';
const progressBar = '[data-testid="progress-bar"]';
const currencyLocked = '[data-testid="currency-locked"]';
const currencyUnlocked = '[data-testid="currency-unlocked"]';
const currencyTitle = '[data-testid="currency-title"]:visible';
const currencyValue = '[data-testid="currency-value"]:visible';
const vegaInVesting = '[data-testid="vega-in-vesting-contract"]:visible';
const vegaInWallet = '[data-testid="vega-in-wallet"]:visible';
const progressBar = '[data-testid="progress-bar"]:visible';
const currencyLocked = '[data-testid="currency-locked"]:visible';
const currencyUnlocked = '[data-testid="currency-unlocked"]:visible';
const dialog = '[role="dialog"]';
const dialogHeader = '[data-testid="dialog-title"]';
const dialogCloseBtn = '[data-testid="dialog-close"]';
@@ -1,6 +1,6 @@
import { truncateByChars } from '@vegaprotocol/utils';
const walletContainer = '[data-testid="vega-wallet"]';
const walletContainer = 'aside [data-testid="vega-wallet"]';
const walletHeader = '[data-testid="wallet-header"] h1';
const connectButton = '[data-testid="connect-vega-wallet"]';
const getVegaLink = '[data-testid="link"]';
@@ -14,7 +14,6 @@ const restWallet = '#wallet';
const restPassphrase = '#passphrase';
const restConnectBtn = '[type="submit"]';
const accountNo = '[data-testid="vega-account-truncated"]';
const walletName = '[data-testid="wallet-name"]';
const currencyTitle = '[data-testid="currency-title"]';
const currencyValue = '[data-testid="currency-value"]';
const vegaUnstaked = '[data-testid="vega-wallet-balance-unstaked"] .text-right';
@@ -28,44 +27,24 @@ const vegaWalletCurrencyTitle = '[data-testid="currency-title"]';
const vegaWalletPublicKey = Cypress.env('vegaWalletPublicKey');
const txTimeout = Cypress.env('txTimeout');
const faucetAssets = {
BTCFake: 'fBTC',
DAIFake: 'fDAI',
EUROFake: 'fEURO',
USDCFake: 'fUSDC',
};
context(
'Vega Wallet - verify elements on widget',
{ tags: '@regression' },
function () {
before('visit token home page', function () {
() => {
before('visit token home page', () => {
cy.visit('/');
cy.get(walletContainer, { timeout: 60000 }).should('be.visible');
});
describe('with wallets disconnected', function () {
before('wait for widget to load', function () {
cy.get(walletContainer, { timeout: 10000 }).should('be.visible');
});
it('should have VEGA WALLET header visible', function () {
describe('with wallets disconnected', () => {
it('should have required elements visible', function () {
cy.get(walletContainer).within(() => {
cy.get(walletHeader)
.should('be.visible')
.and('have.text', 'Vega Wallet');
});
});
it('should have Connect Vega button visible', function () {
cy.get(walletContainer).within(() => {
cy.get(connectButton)
.should('be.visible')
.and('have.text', 'Connect Vega wallet to use associated $VEGA');
});
});
it('should have Get a Vega wallet link visible', function () {
cy.get(walletContainer).within(() => {
cy.get(getVegaLink)
.should('be.visible')
.and('have.text', 'Get a Vega wallet')
@@ -74,14 +53,14 @@ context(
});
});
describe('when connect button clicked', function () {
before('click connect vega wallet button', function () {
describe('when connect button clicked', () => {
before('click connect vega wallet button', () => {
cy.get(walletContainer).within(() => {
cy.get(connectButton).click();
});
});
it('should have Connect Vega header visible', function () {
it('should have Connect Vega header visible', () => {
cy.get(dialog).within(() => {
cy.get(walletDialogHeader)
.should('be.visible')
@@ -175,14 +154,6 @@ context(
}
);
it.skip('should have wallet name visible', function () {
cy.get(walletContainer).within(() => {
cy.get(walletName)
.should('be.visible')
.and('have.text', `${Cypress.env('vegaWalletName')} key 1`);
});
});
it('should have Vega Associated currency title visible', function () {
cy.get(walletContainer).within(() => {
cy.get(currencyTitle)
@@ -299,113 +270,71 @@ context(
});
// 2002-SINC-016
describe('when assets exist in vegawallet', function () {
before('send-faucet assets to connected vega wallet', function () {
cy.vega_wallet_faucet_assets_without_check(
faucetAssets.USDCFake,
'1000000',
vegaWalletPublicKey
);
cy.vega_wallet_faucet_assets_without_check(
faucetAssets.BTCFake,
'600000',
vegaWalletPublicKey
);
cy.vega_wallet_faucet_assets_without_check(
faucetAssets.EUROFake,
'800000',
vegaWalletPublicKey
);
cy.vega_wallet_faucet_assets_without_check(
faucetAssets.DAIFake,
'200000',
vegaWalletPublicKey
);
describe('Vega wallet with assets', function () {
const assets = [
{
id: 'fUSDC',
name: 'USDC (fake)',
amount: '1000000',
expectedAmount: '10.00',
},
{
id: 'fDAI',
name: 'DAI (fake)',
amount: '200000',
expectedAmount: '2.00',
},
{
id: 'fBTC',
name: 'BTC (fake)',
amount: '600000',
expectedAmount: '6.00',
},
{
id: 'fEURO',
name: 'EURO (fake)',
amount: '800000',
expectedAmount: '8.00',
},
];
before('faucet assets to connected vega wallet', function () {
for (const { id, amount } of assets) {
cy.vega_wallet_faucet_assets_without_check(
id,
amount,
vegaWalletPublicKey
);
}
cy.reload();
cy.wait_for_spinner();
cy.connectVegaWallet();
cy.ethereum_wallet_connect();
});
it('should see fUSDC assets - within vega wallet', function () {
let currency = { id: faucetAssets.USDCFake, name: 'USDC (fake)' };
cy.get(walletContainer).within(() => {
cy.get(vegaWalletCurrencyTitle)
.contains(currency.id, txTimeout)
.should('be.visible');
for (const { id, name, expectedAmount } of assets) {
it(`should see ${id} within vega wallet`, () => {
cy.get(walletContainer).within(() => {
cy.get(vegaWalletCurrencyTitle)
.contains(id, txTimeout)
.should('be.visible');
cy.get(vegaWalletCurrencyTitle)
.contains(currency.id)
.parent()
.siblings()
.invoke('text')
.should('not.be.empty');
cy.get(vegaWalletCurrencyTitle)
.contains(currency.id)
.parent()
.contains(currency.name);
cy.get(vegaWalletCurrencyTitle)
.contains(id)
.parent()
.siblings()
.within((el) => {
const value = parseFloat(el.text());
cy.wrap(value).should('be.gte', parseFloat(expectedAmount));
});
cy.get(vegaWalletCurrencyTitle)
.contains(id)
.parent()
.contains(name);
});
});
});
it('should see fBTC assets - within vega wallet', function () {
let currency = { id: faucetAssets.BTCFake, name: 'BTC (fake)' };
cy.get(walletContainer).within(() => {
cy.get(vegaWalletCurrencyTitle)
.contains(currency.id, txTimeout)
.should('be.visible');
cy.get(vegaWalletCurrencyTitle)
.contains(currency.id)
.parent()
.siblings()
.within(() => cy.contains_exactly('6.00').should('be.visible'));
cy.get(vegaWalletCurrencyTitle)
.contains(currency.id)
.parent()
.contains(currency.name);
});
});
it('should see fEURO assets - within vega wallet', function () {
let currency = { id: faucetAssets.EUROFake, name: 'EURO (fake)' };
cy.get(walletContainer).within(() => {
cy.get(vegaWalletCurrencyTitle)
.contains(currency.id, txTimeout)
.should('be.visible');
cy.get(vegaWalletCurrencyTitle)
.contains(currency.id)
.parent()
.siblings()
.within(() => cy.contains_exactly('8.00').should('be.visible'));
cy.get(vegaWalletCurrencyTitle)
.contains(currency.id)
.parent()
.contains(currency.name);
});
});
it('should see fDAI assets - within vega wallet', function () {
let currency = { id: faucetAssets.DAIFake, name: 'DAI (fake)' };
cy.get(walletContainer).within(() => {
cy.get(vegaWalletCurrencyTitle)
.contains(currency.id, txTimeout)
.should('be.visible');
cy.get(vegaWalletCurrencyTitle)
.contains(currency.id)
.parent()
.siblings()
.within(() => cy.contains_exactly('2.00').should('be.visible'));
cy.get(vegaWalletCurrencyTitle)
.contains(currency.id)
.parent()
.contains(currency.name);
});
});
}
});
});
}
@@ -1,27 +0,0 @@
const connectToVegaBtn = '[data-testid="connect-to-vega-wallet-btn"]';
context(
'Withdraw Page - verify elements on page',
{ tags: '@smoke' },
function () {
before('navigate to withdrawals page', function () {
cy.visit('/').navigate_to('withdraw');
});
describe('with wallets disconnected', function () {
it('should have withdraw tab highlighted', function () {
cy.verify_tab_highlighted('token');
});
it('should have WITHDRAW header visible', function () {
cy.verify_page_header('Withdrawals');
});
it('should have connect Vega wallet button', function () {
cy.get(connectToVegaBtn)
.should('be.visible')
.and('have.text', 'Connect Vega wallet');
});
});
}
);
@@ -10,7 +10,7 @@ Cypress.Commands.add(
);
const navigation = {
section: 'nav',
section: '[data-testid="navigation"]',
vesting: '[href="/token/redeem"]',
validators: '[href="/validators"]',
rewards: '[href="/rewards"]',
@@ -22,25 +22,32 @@ const navigation = {
};
const topLevelRoutes = ['proposals', 'validators', 'rewards'];
const tokenDropDown = 'state-trigger';
Cypress.Commands.add('navigate_to', (page) => {
const tokenDropDown = 'state-trigger';
if (!topLevelRoutes.includes(page)) {
cy.getByTestId(tokenDropDown, { timeout: 10000 }).click();
cy.getByTestId('token-dropdown').within(() => {
cy.get(navigation[page]).click();
// FIXME: Timeout madness
cy.getByTestId(tokenDropDown, { timeout: 60000 }).eq(0).click();
cy.get('[data-testid="token-dropdown"]:visible').within(() => {
cy.get(navigation[page]).eq(0).click();
});
} else {
return cy.get(navigation.section, { timeout: 10000 }).within(() => {
cy.get(navigation[page]).click();
cy.get(navigation[page]).eq(0).click();
});
}
});
Cypress.Commands.add('verify_tab_highlighted', (page) => {
return cy.get(navigation.section).within(() => {
cy.get(navigation[page]).should('have.attr', 'aria-current');
if (!topLevelRoutes.includes(page)) {
cy.getByTestId(tokenDropDown, { timeout: 10000 }).eq(0).click();
cy.get('[data-testid="token-dropdown"]:visible').within(() => {
cy.get(navigation[page]).should('have.attr', 'aria-current');
});
} else {
cy.get(navigation[page]).should('have.attr', 'aria-current');
}
});
});
@@ -59,7 +66,7 @@ export function associateTokenStartOfTests() {
cy.highlight(`Associating tokens for first time`);
cy.ethereum_wallet_connect();
cy.connectVegaWallet();
cy.get('[href="/token/associate"]').first().click();
cy.get('[href="/token/associate"]:visible').first().click();
cy.getByTestId('associate-radio-wallet', { timeout: 30000 }).click();
cy.getByTestId('token-amount-input', epochTimeout).type('1');
cy.getByTestId('token-input-submit-button', txTimeout)
@@ -3,10 +3,10 @@ const tokenSubmitButton = '[data-testid="token-input-submit-button"]';
const tokenInputApprove = '[data-testid="token-input-approve-button"]';
const addStakeRadioButton = '[data-testid="add-stake-radio"]';
const removeStakeRadioButton = '[data-testid="remove-stake-radio"]';
const ethWalletAssociateButton = '[href="/token/associate"]';
const ethWalletDissociateButton = '[href="/token/disassociate"]';
const ethWalletAssociateButton = '[href="/token/associate"]:visible';
const ethWalletDissociateButton = '[href="/token/disassociate"]:visible';
const vegaWalletUnstakedBalance =
'[data-testid="vega-wallet-balance-unstaked"]';
'[data-testid="vega-wallet-balance-unstaked"]:visible';
const vegaWalletAssociatedBalance = '[data-testid="currency-value"]';
const associateWalletRadioButton = '[data-testid="associate-radio-wallet"]';
const associateContractRadioButton = '[data-testid="associate-radio-contract"]';
@@ -1,5 +1,6 @@
const ethWalletContainer = '[data-testid="ethereum-wallet"]';
const connectToEthButton = '[data-testid="connect-to-eth-wallet-button"]';
const ethWalletContainer = '[data-testid="ethereum-wallet"]:visible';
const connectToEthButton =
'[data-testid="connect-to-eth-wallet-button"]:visible';
const capsuleWalletConnectButton = '[data-testid="web3-connector-Unknown"]';
Cypress.Commands.add('ethereum_wallet_connect', () => {
@@ -7,7 +7,7 @@ import {
} from '@vegaprotocol/smart-contracts';
import { ethers, Wallet } from 'ethers';
const vegaWalletContainer = '[data-testid="vega-wallet"]';
const vegaWalletContainer = 'aside [data-testid="vega-wallet"]';
const vegaWalletMnemonic = Cypress.env('vegaWalletMnemonic');
const vegaWalletPubKey = Cypress.env('vegaWalletPublicKey');
const vegaTokenContractAddress = Cypress.env('vegaTokenContractAddress');
@@ -47,13 +47,14 @@ beforeEach(function () {
cy.wrap(this.vestingContract).as('vestingContract');
});
Cypress.Commands.add('deposit_asset', function (assetEthAddress) {
Cypress.Commands.add('deposit_asset', function (assetEthAddress, amount) {
cy.highlight('Depositing asset into vegawallet');
cy.get('@signer', { log: false }).then((signer) => {
// Approve asset
cy.wrap(
new TokenFaucetable(assetEthAddress, signer).approve(
Erc20BridgeAddress,
'10000000000'
amount + '0'.repeat(19)
)
)
.then((tx) => {
@@ -67,7 +68,7 @@ Cypress.Commands.add('deposit_asset', function (assetEthAddress) {
cy.wrap(
bridge.deposit_asset(
assetEthAddress,
'1000000000',
amount + '0'.repeat(18),
'0x' + vegaWalletPubKey
),
{ timeout: transactionTimeout, log: false }
@@ -95,7 +96,7 @@ Cypress.Commands.add('faucet_asset', function (assetEthAddress) {
});
Cypress.Commands.add('vega_wallet_teardown', function () {
cy.get('[data-testid="associated-amount"]')
cy.get('aside [data-testid="associated-amount"]')
.should('be.visible')
.invoke('text')
.as('associatedAmount');
@@ -109,10 +110,9 @@ Cypress.Commands.add('vega_wallet_teardown', function () {
}
});
cy.get(vegaWalletContainer).within(() => {
cy.get('[data-testid="associated-amount"]', { timeout: 30000 }).should(
'contain.text',
'0.00'
);
cy.get('[data-testid="vega-wallet-balance-unstaked"]', {
timeout: 30000,
}).should('contain.text', '0.00');
});
});
+1 -1
View File
@@ -1,6 +1,6 @@
# App configuration variables
NX_VEGA_ENV=STAGNET3
NX_VEGA_CONFIG_URL=https://static.vega.xyz/assets/stagnet3-network.json
NX_VEGA_CONFIG_URL=https://raw.githubusercontent.com/vegaprotocol/networks-internal/main/stagnet3/vegawallet-stagnet3.toml
NX_VEGA_URL=https://api.stagnet3.vega.xyz/graphql
NX_ETHEREUM_PROVIDER_URL=https://sepolia.infura.io/v3/4f846e79e13f44d1b51bbd7ed9edefb8
NX_ETHERSCAN_URL=https://sepolia.etherscan.io
+2 -2
View File
@@ -1,6 +1,6 @@
# App configuration variables
NX_VEGA_ENV=DEVNET
NX_VEGA_CONFIG_URL=https://static.vega.xyz/assets/devnet-network.json
NX_VEGA_CONFIG_URL=https://raw.githubusercontent.com/vegaprotocol/networks-internal/main/devnet1/vegawallet-devnet1.toml
NX_VEGA_URL=https://api.n00.devnet1.vega.xyz/graphql
NX_VEGA_NETWORKS='{"DEVNET":"https://dev.token.vega.xyz","STAGNET3":"https://stagnet3.token.vega.xyz","TESTNET":"https://token.fairground.wtf","MAINNET":"https://token.vega.xyz"}'
NX_ETHEREUM_PROVIDER_URL=https://sepolia.infura.io/v3/4f846e79e13f44d1b51bbd7ed9edefb8
@@ -9,4 +9,4 @@ NX_GITHUB_FEEDBACK_URL=https://github.com/vegaprotocol/feedback/discussions
NX_VEGA_EXPLORER_URL=https://dev.explorer.vega.xyz
NX_VEGA_DOCS_URL=https://docs.vega.xyz/testnet
NX_DELEGATIONS_PAGINATION=50
NX_TRANCHES_SERVICE_URL=https://tranches-devnet1-k8s.ops.vega.xyz
NX_TRANCHES_SERVICE_URL=https://tranches-devnet1-k8s.ops.vega.xyz
+2 -2
View File
@@ -1,6 +1,6 @@
# App configuration variables
NX_VEGA_ENV=MAINNET
NX_VEGA_CONFIG_URL=https://static.vega.xyz/assets/mainnet-network.json
NX_VEGA_CONFIG_URL=https://raw.githubusercontent.com/vegaprotocol/networks/master/mainnet1/mainnet1.toml
NX_VEGA_URL=https://api.vega.xyz/query
NX_VEGA_NETWORKS='{"DEVNET":"https://dev.token.vega.xyz","STAGNET3":"https://stagnet3.token.vega.xyz","TESTNET":"https://token.fairground.wtf","MAINNET":"https://token.vega.xyz"}'
NX_ETHEREUM_PROVIDER_URL=https://mainnet.infura.io/v3/4f846e79e13f44d1b51bbd7ed9edefb8
@@ -10,4 +10,4 @@ NX_VEGA_EXPLORER_URL=https://explorer.vega.xyz
NX_VEGA_DOCS_URL=https://docs.vega.xyz/mainnet
NX_SENTRY_DSN=https://4b8c8a8ba07742648aa4dfe1b8d17e40:87edc2605e544f888305d7fc4a9141bd@o286262.ingest.sentry.io/5882996
NX_DELEGATIONS_PAGINATION=50
NX_TRANCHES_SERVICE_URL=https://tranches-mainnet-k8s.ops.vega.xyz
NX_TRANCHES_SERVICE_URL=https://tranches-mainnet-k8s.ops.vega.xyz
+1 -1
View File
@@ -1,6 +1,6 @@
# App configuration variables
NX_VEGA_ENV=MIRROR
NX_VEGA_CONFIG_URL=https://static.vega.xyz/assets/mirror-network.json
NX_VEGA_CONFIG_URL=https://raw.githubusercontent.com/vegaprotocol/networks-internal/main/mainnet-mirror/vegawallet-mainnet-mirror.toml
NX_VEGA_URL=https://api.n00.mainnet-mirror.vega.xyz/graphql
NX_VEGA_NETWORKS='{"DEVNET":"https://dev.token.vega.xyz","STAGNET3":"https://stagnet3.token.vega.xyz","TESTNET":"https://token.fairground.wtf","MAINNET":"https://token.vega.xyz"}'
NX_ETHEREUM_PROVIDER_URL=https://sepolia.infura.io/v3/4f846e79e13f44d1b51bbd7ed9edefb8
+1 -1
View File
@@ -2,7 +2,7 @@
NX_VEGA_URL=https://api.sandbox.vega.xyz/graphql
NX_VEGA_ENV=SANDBOX
NX_VEGA_NETWORKS='{"DEVNET":"https://dev.token.vega.xyz","STAGNET3":"https://stagnet3.token.vega.xyz","STAGNET1":"https://stagnet1.token.vega.xyz","TESTNET":"https://token.fairground.wtf","MAINNET":"https://token.vega.xyz"}'
NX_VEGA_CONFIG_URL=https://static.vega.xyz/assets/sandbox-network.json
NX_VEGA_CONFIG_URL=https://raw.githubusercontent.com/vegaprotocol/networks-internal/main/sandbox/vegawallet-sandbox.toml
NX_VEGA_EXPLORER_URL=https://sandbox.explorer.vega.xyz
NX_VEGA_DOCS_URL=https://docs.vega.xyz/testnet
NX_DELEGATIONS_PAGINATION=50
+2 -2
View File
@@ -2,8 +2,8 @@
NX_VEGA_URL=https://api.n00.stagnet1.vega.xyz/graphql
NX_VEGA_ENV=STAGNET1
NX_VEGA_NETWORKS='{"DEVNET":"https://dev.token.vega.xyz","STAGNET3":"https://stagnet3.token.vega.xyz","STAGNET1":"https://stagnet1.token.vega.xyz","TESTNET":"https://token.fairground.wtf","MAINNET":"https://token.vega.xyz"}'
NX_VEGA_CONFIG_URL=https://static.vega.xyz/assets/stagnet1-network.json
NX_VEGA_CONFIG_URL=https://raw.githubusercontent.com/vegaprotocol/networks-internal/main/stagnet1/vegawallet-stagnet1.toml
NX_VEGA_EXPLORER_URL=https://stagnet1.explorer.vega.xyz
NX_VEGA_DOCS_URL=https://docs.vega.xyz/testnet
NX_DELEGATIONS_PAGINATION=50
NX_TRANCHES_SERVICE_URL=https://tranches-stagnet1-k8s.ops.vega.xyz
NX_TRANCHES_SERVICE_URL=https://tranches-stagnet1-k8s.ops.vega.xyz
+2 -2
View File
@@ -2,9 +2,9 @@
NX_VEGA_URL=https://api.stagnet3.vega.xyz/graphql
NX_VEGA_ENV=STAGNET3
NX_VEGA_NETWORKS='{"DEVNET":"https://dev.token.vega.xyz","STAGNET3":"https://stagnet3.token.vega.xyz","TESTNET":"https://token.fairground.wtf","MAINNET":"https://token.vega.xyz"}'
NX_VEGA_CONFIG_URL=https://static.vega.xyz/assets/stagnet3-network.json
NX_VEGA_CONFIG_URL=https://raw.githubusercontent.com/vegaprotocol/networks-internal/main/stagnet3/vegawallet-stagnet3.toml
NX_VEGA_EXPLORER_URL=https://stagnet3.explorer.vega.xyz
NX_VEGA_DOCS_URL=https://docs.vega.xyz/testnet
NX_HOSTED_WALLET_URL=https://wallet.testnet.vega.xyz
NX_DELEGATIONS_PAGINATION=50
NX_TRANCHES_SERVICE_URL=https://tranches-stagnet3-k8s.ops.vega.xyz
NX_TRANCHES_SERVICE_URL=https://tranches-stagnet3-k8s.ops.vega.xyz
+2 -2
View File
@@ -1,6 +1,6 @@
# App configuration variables
NX_VEGA_ENV=TESTNET
NX_VEGA_CONFIG_URL=https://static.vega.xyz/assets/testnet-network.json
NX_VEGA_CONFIG_URL=https://raw.githubusercontent.com/vegaprotocol/networks-internal/main/fairground/vegawallet-fairground.toml
NX_VEGA_URL=https://api.n08.testnet.vega.xyz/graphql
NX_VEGA_NETWORKS='{"DEVNET":"https://dev.token.vega.xyz","STAGNET3":"https://stagnet3.token.vega.xyz","TESTNET":"https://token.fairground.wtf","MAINNET":"https://token.vega.xyz"}'
NX_ETHEREUM_PROVIDER_URL=https://sepolia.infura.io/v3/4f846e79e13f44d1b51bbd7ed9edefb8
@@ -10,4 +10,4 @@ NX_VEGA_EXPLORER_URL=https://explorer.fairground.wtf
NX_VEGA_DOCS_URL=https://docs.vega.xyz/testnet
NX_HOSTED_WALLET_URL=https://wallet.testnet.vega.xyz
NX_DELEGATIONS_PAGINATION=50
NX_TRANCHES_SERVICE_URL=https://tranches-testnet-k8s.ops.vega.xyz
NX_TRANCHES_SERVICE_URL=https://tranches-testnet-k8s.ops.vega.xyz
+3 -3
View File
@@ -1,8 +1,8 @@
# App configuration variables
NX_VEGA_ENV=VALIDATOR_TESTNET
NX_VEGA_CONFIG_URL=https://static.vega.xyz/assets/validator-testnet-network.json
NX_VEGA_URL=https://api.validators-testnet.vega.xyz/graphql
NX_VEGA_REST=https://api.validators-testnet.vega.xyz/
NX_VEGA_CONFIG_URL=https://raw.githubusercontent.com/vegaprotocol/networks/master/testnet2/testnet2.toml
NX_VEGA_URL=https://api-validators-testnet.vega.rocks/graphql
NX_VEGA_REST=https://api-validators-testnet.vega.rocks/
NX_VEGA_NETWORKS='{"DEVNET":"https://dev.token.vega.xyz","STAGNET3":"https://stagnet3.token.vega.xyz","TESTNET":"https://token.fairground.wtf","MAINNET":"https://token.vega.xyz"}'
NX_ETHEREUM_PROVIDER_URL=https://sepolia.infura.io/v3/4f846e79e13f44d1b51bbd7ed9edefb8
NX_ETHERSCAN_URL=https://sepolia.etherscan.io
@@ -1,126 +0,0 @@
import classNames from 'classnames';
import { NavLink } from 'react-router-dom';
import {
AppStateActionType,
useAppState,
} from '../../contexts/app-state/app-state-context';
import * as Dialog from '@radix-ui/react-dialog';
import { EthWallet } from '../eth-wallet';
import { VegaWallet } from '../vega-wallet';
import { useTranslation } from 'react-i18next';
interface Route {
name: string;
path: string;
}
const DrawerSection = ({ children }: { children: React.ReactNode }) => (
<div className="px-4 my-4">{children}</div>
);
const IconLine = ({ inverted }: { inverted: boolean }) => (
<span className={`block w-6 h-[2px] ${inverted ? 'bg-black' : 'bg-white'}`} />
);
const DrawerNavLinks = ({
isInverted,
routes,
}: {
isInverted?: boolean;
routes: Route[];
}) => {
const { appDispatch } = useAppState();
const { t } = useTranslation();
const linkProps = {
end: true,
onClick: () =>
appDispatch({ type: AppStateActionType.SET_DRAWER, isOpen: false }),
};
const navClasses = classNames('flex flex-col');
return (
<nav className={navClasses}>
{routes.map(({ name, path }) => {
return (
<NavLink
{...linkProps}
to={{ pathname: path }}
className={({ isActive }) =>
classNames({
'bg-vega-yellow text-black': !isInverted && isActive,
'bg-transparent text-white hover:text-vega-yellow':
!isInverted && !isActive,
'bg-black text-white': isInverted && isActive,
'bg-transparent text-black hover:text-white':
isInverted && !isActive,
'border-t border-white p-4': true,
})
}
>
{t(name)}
</NavLink>
);
})}
</nav>
);
};
export const NavDrawer = ({
inverted,
routes,
}: {
inverted: boolean;
routes: Route[];
}) => {
const { appState, appDispatch } = useAppState();
const drawerContentClasses = classNames(
'drawer-content', // needed for css animation
// Positions the modal in the center of screen
'fixed w-[80vw] max-w-[420px] top-0 right-0',
'flex flex-col flex-nowrap justify-between h-full bg-banner overflow-y-scroll border-l border-white',
'bg-black text-neutral-200'
);
return (
<>
<button
onClick={() =>
appDispatch({
type: AppStateActionType.SET_DRAWER,
isOpen: true,
})
}
className="flex flex-col flex-nowrap gap-1"
>
<IconLine inverted={inverted} />
<IconLine inverted={inverted} />
<IconLine inverted={inverted} />
</button>
<Dialog.Root
open={appState.drawerOpen}
onOpenChange={(isOpen) =>
appDispatch({
type: AppStateActionType.SET_DRAWER,
isOpen,
})
}
>
<Dialog.Portal>
<Dialog.Overlay className="fixed inset-0 bg-white/15" />
<Dialog.Content className={drawerContentClasses}>
<div>
<DrawerSection>
<EthWallet />
</DrawerSection>
<DrawerSection>
<VegaWallet />
</DrawerSection>
</div>
<DrawerNavLinks routes={routes} />
</Dialog.Content>
</Dialog.Portal>
</Dialog.Root>
</>
);
};
@@ -1,50 +0,0 @@
import { useState } from 'react';
import Routes, { TOKEN_DROPDOWN_ROUTES } from '../../routes/routes';
import { useTranslation } from 'react-i18next';
import type { NavbarTheme } from './nav-link';
import { AppNavLink } from './nav-link';
import {
NavDropdownMenu,
NavDropdownMenuContent,
NavDropdownMenuItem,
NavDropdownMenuTrigger,
} from '@vegaprotocol/ui-toolkit';
export const NavDropDown = ({ navbarTheme }: { navbarTheme: NavbarTheme }) => {
const { t } = useTranslation();
const [isOpen, setOpen] = useState(false);
return (
<NavDropdownMenu open={isOpen} onOpenChange={(open) => setOpen(open)}>
<AppNavLink
name={
<NavDropdownMenuTrigger
className="w-auto flex items-center -m-3 p-3 cursor-pointer"
data-testid="state-trigger"
onClick={() => setOpen(!isOpen)}
>
{t('Token')}
</NavDropdownMenuTrigger>
}
testId="token-dd"
path={Routes.TOKEN}
navbarTheme={navbarTheme}
/>
<NavDropdownMenuContent data-testid="token-dropdown">
{TOKEN_DROPDOWN_ROUTES.map((r) => (
<NavDropdownMenuItem key={r.name} onClick={() => setOpen(false)}>
<AppNavLink
testId={r.name}
name={t(r.name)}
path={r.path}
navbarTheme={'inherit'}
subNav={true}
end={true}
fullWidth={true}
/>
</NavDropdownMenuItem>
))}
</NavDropdownMenuContent>
</NavDropdownMenu>
);
};
@@ -1,57 +0,0 @@
import classNames from 'classnames';
import { NavLink } from 'react-router-dom';
import type { HTMLAttributeAnchorTarget, ReactNode } from 'react';
import { getNavLinkClassNames } from '@vegaprotocol/ui-toolkit';
export type NavbarTheme = 'inherit' | 'dark' | 'yellow';
interface AppNavLinkProps {
name: ReactNode | string;
path: string;
navbarTheme: NavbarTheme;
testId?: string;
target?: HTMLAttributeAnchorTarget;
end?: boolean;
fullWidth?: boolean;
subNav?: boolean;
}
export const AppNavLink = ({
name,
path,
navbarTheme,
target,
testId,
end = false,
fullWidth = false,
subNav = false,
}: AppNavLinkProps) => {
const borderClasses = classNames(
'absolute h-0.5 w-full bottom-[-1px] left-0',
{
'bg-black dark:bg-vega-yellow': navbarTheme !== 'yellow',
'bg-black': navbarTheme === 'yellow',
}
);
return (
<NavLink
key={path}
data-testid={testId}
to={{ pathname: path }}
className={getNavLinkClassNames(navbarTheme, fullWidth, subNav)}
target={target}
end={end}
>
{({ isActive }) => {
return (
<div className={subNav ? 'inline-block relative pb-1' : undefined}>
{name}
{isActive && (
<span data-testid="link-active" className={borderClasses} />
)}
</div>
);
}}
</NavLink>
);
};
@@ -1,25 +0,0 @@
@keyframes slideIn {
from {
transform: translateX(100%);
}
to {
transform: translateX(0);
}
}
@keyframes slideOut {
from {
transform: translateX(0);
}
to {
transform: translateX(100%);
}
}
.drawer-content[data-state='open'] {
animation: slideIn 150ms ease-out forwards;
}
.drawer-content[data-state='closed'] {
animation: slideOut 150ms ease-in forwards;
}

Some files were not shown because too many files have changed in this diff Show More