Compare commits

..
Author SHA1 Message Date
Matthew Russell aea238a506 chore: change market so no settlement asset available for colalteral deposit 2023-05-01 15:14:06 -07:00
Matthew Russell 0fc772b1d3 fix: home tests as now first market will have id market-0 2023-05-01 06:53:08 -07:00
Matthew Russell ca071dd432 chore: increase github action timeout 2023-05-01 06:53:08 -07:00
Matthew Russell 7e44a293a2 test: add additional mock for asset query that is now called on dialog open 2023-05-01 06:53:08 -07:00
Matthew Russell 1f1c4ced0b chore: update test helpers with additional fields 2023-05-01 06:53:08 -07:00
Matthew Russell e09a1d8ff8 test: update unit test to use create funcs and remove old types 2023-05-01 06:53:08 -07:00
Matthew Russell 36eaa1d30a chore: re add footer 2023-05-01 06:53:08 -07:00
Matthew Russell 1142e6816c chore: add async renderer for loading state 2023-05-01 06:53:08 -07:00
Matthew Russell e80e1cf4e4 chore: make test creation easier, switch data provider 2023-05-01 06:53:08 -07:00
Matthew Russell 4dbd984dd5 test: add ac for title attr tooltip 2023-05-01 06:53:08 -07:00
Matthew Russell 42fccbe852 feat: add title attribute to show full date 2023-05-01 06:53:08 -07:00
Matthew Russell 2c11b4966d test: fix change from unknown to hyphen, link up AC 2023-05-01 06:53:08 -07:00
Matthew Russell 927694bc5c chore: update imports in unti tests 2023-05-01 06:53:08 -07:00
Matthew Russell a78ecd2ba9 chore: ignore problematic ts errors 2023-05-01 06:53:08 -07:00
Matthew Russell 67763e9f9d test: move mocks so they are co located with queries 2023-05-01 06:53:08 -07:00
Matthew Russell f7edaeee63 feat: move closed markets query for better types when mocking 2023-05-01 06:53:08 -07:00
Matthew Russell 5fa3569912 test: flesh out closed market tests 2023-05-01 06:53:07 -07:00
Matthew Russell 3e55db8665 test: add initial e2e test 2023-05-01 06:53:07 -07:00
Matthew Russell 324fe76491 feat: flatten table row data 2023-05-01 06:53:07 -07:00
Matthew Russell c4723f5b16 test: split components and add tests for table logic 2023-05-01 06:53:07 -07:00
Matthew Russell caee00da6d test: add unit test for bespoke table cells 2023-05-01 06:53:07 -07:00
Matthew Russell 85b04a9c0d feat: move hook to oracles lib, add unit test for hook 2023-05-01 06:53:07 -07:00
Matthew Russell dc6b640e19 feat: add link components 2023-05-01 06:53:07 -07:00
Matthew Russell 469d49405b feat: add table columns, add oracle query 2023-05-01 06:53:07 -07:00
dexturr b88da51c68 chore: update tranches
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-05-01 12:08:18 +00:00
dexturr 2ae56bb113 chore: update tranches
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-05-01 06:07:17 +00:00
dexturr 752af9a983 chore: update tranches
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-05-01 00:17:06 +00:00
dexturr a01df081eb chore: update tranches
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-04-30 18:07:29 +00:00
dexturr c2d14d1abe chore: update tranches
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-04-30 12:10:07 +00:00
dexturr a76ff44ffd chore: update tranches
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-04-30 06:09:37 +00:00
dexturr ac2e262bf3 chore: update tranches
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-04-30 00:16:34 +00:00
dexturr ab180875b1 chore: update tranches
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-04-29 18:07:34 +00:00
dexturr 66d3e89b9e chore: update tranches
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-04-29 12:09:56 +00:00
dexturr c9cce87606 chore: update tranches
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-04-29 06:08:49 +00:00
dexturr 50232ab089 chore: update tranches
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-04-29 00:16:25 +00:00
dexturr e86fb6d0b4 chore: update tranches
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-04-28 18:08:10 +00:00
Sam Keen 473ef3ae83 feat(governance): default font Alpha (#3543) 2023-04-28 17:08:36 +00:00
Edd 77ab719b37 fix(explorer): fix asset links and deterministic order details (#3567) 2023-04-28 16:00:49 +00:00
Edd a10f67d7ab feat(explorer): add epoch to block explorer homepage (#3536) 2023-04-28 13:08:42 +00:00
dexturr 66d2b83513 chore: update tranches
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-04-28 12:09:23 +00:00
dexturr e4fd040933 chore: update tranches
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-04-28 06:08:57 +00:00
dexturr 30c1dbd019 chore: update tranches
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-04-28 00:14:44 +00:00
daro-majandm.ray 5e558c4cd3 test(trading): 7001-COLL-collateral - e2e tests (#3561)
Co-authored-by: m.ray <16125548+MadalinaRaicu@users.noreply.github.com>
2023-04-27 21:28:25 +02:00
dexturr 85060a0421 chore: update tranches
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-04-27 18:10:05 +00:00
Sam Keen b336291b49 fix(governance): use default jsonrpc connector when the provider from useWe… (#3563) 2023-04-27 16:26:00 +00:00
Joe Tsang 0f7bffd38b test(ci): capsule update v0.71.1 (#3559) 2023-04-27 14:37:55 +01:00
dexturr 3665375b75 chore: update tranches
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-04-27 12:09:22 +00:00
m.ray 8572c0a570 feat(trading): data grid dropdown menu in collateral table and vega icons (#3472) 2023-04-27 09:21:05 +00:00
Maciek 6a29dc82ef feat(ledger): add link for download ledger entries to .csv (#3454) 2023-04-27 08:53:28 +00:00
Bartłomiej Głownia c19bcc5e0c feat(trading): add oracle banner e2e tests (#3524) 2023-04-27 09:47:18 +01:00
91 changed files with 2631 additions and 408 deletions
+1 -1
View File
@@ -50,7 +50,7 @@ jobs:
secrets: inherit
lint-test-build:
timeout-minutes: 35
timeout-minutes: 60
needs: node-modules
runs-on: ubuntu-22.04
name: '(CI) lint + unit test + build'
+2 -2
View File
@@ -1,7 +1,7 @@
NX_CHAIN_EXPLORER_URL=https://explorer.vega.trading/.netlify/functions/chain-explorer-api
NX_TENDERMINT_URL=http://localhost:26617
NX_TENDERMINT_WEBSOCKET_URL=wss://localhost:26617/websocket
NX_VEGA_URL=http://localhost:3028/query
NX_VEGA_URL=http://localhost:3008/graphql
NX_VEGA_ENV=CUSTOM
NX_VEGA_CONFIG_URL=
@@ -18,4 +18,4 @@ NX_EXPLORER_PARTIES=1
NX_EXPLORER_VALIDATORS=1
CYPRESS_VEGA_WALLET_API_TOKEN=
CYPRESS_VEGA_URL=http://localhost:3028/query
CYPRESS_VEGA_URL=http://localhost:3008/graphql
+1 -1
View File
@@ -25,7 +25,7 @@ module.exports = defineConfig({
},
env: {
environment: 'CUSTOM',
networkQueryUrl: 'http://localhost:3028/query',
networkQueryUrl: 'http://localhost:3008/graphql',
ethUrl: 'https://sepolia.infura.io/v3/4f846e79e13f44d1b51bbd7ed9edefb8',
commitHash: 'dev',
tsConfig: 'tsconfig.json',
+18 -46
View File
@@ -9,21 +9,22 @@ context('Home Page', function () {
it('should show connected environment stats', function () {
const statTitles = {
0: 'Status',
1: 'Block height',
2: 'Uptime',
3: 'Total nodes',
4: 'Total staked',
5: 'Backlog',
6: 'Trades / second',
7: 'Orders / block',
8: 'Orders / second',
9: 'Transactions / block',
10: 'Block time',
11: 'Time',
12: 'App',
13: 'Tendermint',
14: 'Up since',
15: 'Chain ID',
1: 'Epoch',
2: 'Block height',
3: 'Uptime',
4: 'Total nodes',
5: 'Total staked',
6: 'Backlog',
7: 'Trades / second',
8: 'Orders / block',
9: 'Orders / second',
10: 'Transactions / block',
11: 'Block time',
12: 'Time',
13: 'App',
14: 'Tendermint',
15: 'Up since',
16: 'Chain ID',
};
cy.get('[data-testid="stats-title"]')
@@ -31,42 +32,13 @@ context('Home Page', function () {
cy.wrap($list).should('contain.text', statTitles[index]);
})
.then(($list) => {
cy.wrap($list).should('have.length', 16);
cy.wrap($list).should('have.length', 17);
});
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('contain.text', '2');
cy.get(statsValue)
.eq(4)
.invoke('text')
.should('match', /\d+\.\d\d(?!\d)/i);
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');
cy.get(statsValue)
.eq(12)
.invoke('text')
.should('match', /v\d+\.\d+\.\d+/i);
cy.get(statsValue)
.eq(13)
.invoke('text')
.should('match', /\d+\.\d+\.\d+/i);
cy.get(statsValue).eq(14).should('not.be.empty');
cy.get(statsValue).eq(15).should('not.be.empty');
});
it('Block height should be updating', function () {
cy.get(statsValue)
.eq(1)
.eq(2)
.invoke('text')
.then((blockHeightTxt) => {
cy.get(statsValue)
@@ -6,7 +6,7 @@ const customNodeBtn = 'custom-node';
context.skip('Node switcher', { tags: '@regression' }, function () {
beforeEach('visit home page', function () {
cy.intercept('GET', 'https://static.vega.xyz/assets/capsule-network.json', {
hosts: ['http://localhost:3028/query'],
hosts: ['http://localhost:3008/graphql'],
}).as('nodeData');
cy.visit('/');
cy.wait('@nodeData');
@@ -219,7 +219,7 @@ context.skip('Parties page', { tags: '@regression' }, function () {
balance type asset {id symbol decimals}}}}}}}}';
cy.request({
method: 'POST',
url: `http://localhost:3028/query`,
url: `http://localhost:3008/graphql`,
body: {
query: mutation,
},
@@ -43,7 +43,7 @@ export const AssetLink = ({
if (asDialog) {
open(assetId, e.target as HTMLElement);
} else {
navigate(`${Routes.ASSETS}/${asset?.id}`);
navigate(`/${Routes.ASSETS}/${asset?.id}`);
}
}}
{...props}
@@ -9,7 +9,7 @@ import SizeInMarket from '../size-in-market/size-in-market';
export interface DeterministicOrderDetailsProps {
id: string;
// Version to fetch, with 0 being 'latest' and 1 being 'first'. Defaults to 0
version?: number;
version?: number | null;
}
export const wrapperClasses =
@@ -28,7 +28,7 @@ export const wrapperClasses =
*/
const DeterministicOrderDetails = ({
id,
version = 0,
version = null,
}: DeterministicOrderDetailsProps) => {
const { data, error } = useExplorerDeterministicOrderQuery({
variables: { orderId: id, version },
@@ -71,7 +71,7 @@ export const PartyAccounts = ({ accounts }: PartyAccountsProps) => {
/>
</td>
<td className="text-md">
<AssetLink assetId={account.asset.id} />
<AssetLink assetId={account.asset.id} asDialog={true} />
</td>
</TableRow>
);
+2 -3
View File
@@ -5,7 +5,7 @@ NX_ETHERSCAN_URL=https://sepolia.etherscan.io
NX_FAIRGROUND=false
NX_VEGA_NETWORKS={}
NX_VEGA_URL=http://localhost:3028/query
NX_VEGA_URL=http://localhost:3008/graphql
NX_ETHEREUM_CHAIN_ID=1440
NX_ETH_URL_CONNECT=1
NX_ETH_WALLET_MNEMONIC=ozone access unlock valid olympic save include omit supply green clown session
@@ -20,7 +20,7 @@ NX_WALLETCONNECT_PROJECT_ID=fe8091dc35738863e509fc4947525c72
#Test configuration variables
CYPRESS_FAIRGROUND=false
CYPRESS_VEGA_URL=http://localhost:3028/query
CYPRESS_VEGA_URL=http://localhost:3008/graphql
CYPRESS_ETH_WALLET_MNEMONIC=ozone access unlock valid olympic save include omit supply green clown session
CYPRESS_ETHEREUM_PROVIDER_URL=http://localhost:8545
CYPRESS_EXPLORER_URL=https://explorer.fairground.wtf
@@ -31,6 +31,5 @@ CYPRESS_VEGA_ENV=CUSTOM
CYPRESS_VEGA_PUBLIC_KEY=02eceaba4df2bef76ea10caf728d8a099a2aa846cced25737cccaa9812342f65
CYPRESS_VEGA_PUBLIC_KEY2=7f9cf07d3a9905b1a61a1069f7a758855da428bc0f4a97de87f48644bfc25535
CYPRESS_VEGA_TOKEN_URL=https://token.fairground.wtf
CYPRESS_VEGA_URL=http://localhost:3028/query
CYPRESS_VEGA_WALLET_URL=http://localhost:1789
CYPRESS_VEGA_WALLET_API_TOKEN=
@@ -50,6 +50,8 @@ const liquidityVoteStatus = 'liquidity-votes-status';
const tokenVoteStatus = 'token-votes-status';
const proposalTermsSection = 'proposal';
const vegaWalletPublicKey = Cypress.env('vegaWalletPublicKey');
const fUSDCId =
'816af99af60d684502a40824758f6b5377e6af48e50a9ee8ef478ecb879ea8bc';
const epochTimeout = Cypress.env('epochTimeout');
const proposalTimeout = { timeout: 14000 };
@@ -264,7 +266,7 @@ context(
it('Unable to submit update market proposal without minimum amount of tokens', function () {
vegaWalletTeardown();
vegaWalletFaucetAssetsWithoutCheck(
'fUSDC',
fUSDCId,
'1000000',
vegaWalletPublicKey
);
@@ -290,7 +292,7 @@ context(
// 3001-VOTE-092 3004-PMAC-001
it('Able to submit update market proposal and vote for proposal', function () {
vegaWalletFaucetAssetsWithoutCheck(
'fUSDC',
fUSDCId,
'1000000',
vegaWalletPublicKey
);
@@ -55,7 +55,6 @@ context(
function () {
// 2001-STKE-002, 2001-STKE-032
before('visit staking tab and connect vega wallet', function () {
cy.clearAllLocalStorage();
cy.visit('/');
ethereumWalletConnect();
// this is a workaround for #2422 which can be removed once issue is resolved
@@ -67,6 +66,7 @@ context(
beforeEach(
'teardown wallet & drill into a specific validator',
function () {
cy.clearAllLocalStorage();
cy.reload();
waitForSpinner();
cy.connectVegaWallet();
@@ -131,7 +131,7 @@ context('Home Page - verify elements on page', { tags: '@smoke' }, function () {
.within(() => {
cy.get('span')
.first()
.should('have.text', 'http://localhost:3028/query');
.should('have.text', 'http://localhost:3008/graphql');
cy.getByTestId('link').should('exist');
});
});
@@ -17,10 +17,15 @@ const banner = 'view-banner';
context('View functionality with public key', { tags: '@smoke' }, function () {
before('send asset to wallet', function () {
vegaWalletFaucetAssetsWithoutCheck('fUSDC', '1000000', vegaWalletPubKey);
vegaWalletFaucetAssetsWithoutCheck(
'816af99af60d684502a40824758f6b5377e6af48e50a9ee8ef478ecb879ea8bc',
'1000000',
vegaWalletPubKey
);
});
beforeEach('visit home page', function () {
cy.clearLocalStorage();
cy.visit('/');
waitForSpinner();
cy.connectPublicKey(vegaWalletPubKey);
@@ -13,6 +13,7 @@ context(
{ tags: '@regression' },
function () {
before('navigate to rewards page', function () {
cy.clearLocalStorage();
cy.visit('/');
navigateTo(navigation.rewards);
});
@@ -282,26 +282,30 @@ context(
describe('Vega wallet with assets', function () {
const assets = [
{
id: 'fUSDC',
id: '816af99af60d684502a40824758f6b5377e6af48e50a9ee8ef478ecb879ea8bc',
name: 'USDC (fake)',
symbol: 'fUSDC',
amount: '1000000',
expectedAmount: '10.00',
},
{
id: 'fDAI',
id: '8566db7257222b5b7ef2886394ad28b938b28680a54a169bbc795027b89d6665',
name: 'DAI (fake)',
symbol: 'fDAI',
amount: '200000',
expectedAmount: '2.00',
},
{
id: 'fBTC',
id: '73174a6fb1d5802ba0ac7bd7ab79e0a3a4837b262de0a4e80815a55442692bd0',
name: 'BTC (fake)',
symbol: 'fBTC',
amount: '600000',
expectedAmount: '6.00',
},
{
id: 'fEURO',
id: 'e02d4c15d790d1d2dffaf2dcd1cf06a1fe656656cf4ed18c8ce99f9e83643567',
name: 'EURO (fake)',
symbol: 'fEURO',
amount: '800000',
expectedAmount: '8.00',
},
@@ -322,15 +326,15 @@ context(
});
});
for (const { id, name, expectedAmount } of assets) {
it(`should see ${id} within vega wallet`, () => {
for (const { name, symbol, expectedAmount } of assets) {
it(`should see ${name} within vega wallet`, () => {
cy.get(walletContainer).within(() => {
cy.get(vegaWalletCurrencyTitle)
.contains(id, txTimeout)
.contains(name, txTimeout)
.should('be.visible');
cy.get(vegaWalletCurrencyTitle)
.contains(id)
.contains(name)
.parent()
.siblings()
.invoke('text')
@@ -338,9 +342,9 @@ context(
.should('be.gte', parseFloat(expectedAmount));
cy.get(vegaWalletCurrencyTitle)
.contains(id)
.contains(name)
.parent()
.contains(name);
.contains(symbol);
});
});
}
@@ -54,7 +54,7 @@ export function stakingValidatorPageRemoveStake(stake: string) {
.and('contain', `Remove ${stake} $VEGA tokens at the end of epoch`)
.and('be.visible')
.click();
cy.contains('been removed from validator').should('be.visible');
cy.contains('been removed from validator', txTimeout).should('be.visible');
closeDialog();
}
@@ -185,7 +185,7 @@ export function validateValidatorListTotalStakeAndShare(
) {
cy.contains('Loading...', epochTimeout).should('not.exist');
waitForBeginningOfEpoch();
cy.get(`[row-id="${positionOnList}"]:visible`)
cy.get(`[row-id="${positionOnList}"]`)
.eq(1)
.within(() => {
cy.getByTestId(stakeValidatorListTotalStake, epochTimeout).should(
@@ -221,12 +221,12 @@ export function ensureSpecifiedUnstakedTokensAreAssociated(
}
export function closeStakingDialog() {
cy.get('[data-testid="dialog-title"]:visible').should(
cy.getByTestId('dialog-title').should(
'contain.text',
'At the beginning of the next epoch'
);
cy.get('[data-testid="dialog-content"]:visible')
.first()
cy.getByTestId('dialog-content')
.last()
.within(() => {
cy.get('a').should('have.text', 'Back to Staking').click();
});
@@ -9,7 +9,7 @@ import {
import { ethers, Wallet } from 'ethers';
const associatedAmountInWallet = '[data-testid="associated-amount"]:visible';
const vegaWalletContainer = 'aside [data-testid="vega-wallet"]:visible';
const vegaWalletContainer = 'aside [data-testid="vega-wallet"]';
const vegaWalletMnemonic = Cypress.env('vegaWalletMnemonic');
const vegaWalletPubKey = Cypress.env('vegaWalletPublicKey');
const vegaTokenContractAddress = Cypress.env('vegaTokenContractAddress');
@@ -105,25 +105,24 @@ async function vegaWalletTeardownStaking(stakingBridgeContract: StakingBridge) {
{ timeout: transactionTimeout, log: false }
).then((stakeBalance) => {
if (Number(stakeBalance) != 0) {
cy.get(vegaWalletContainer).within(() => {
cy.getByTestId('currency-value')
.invoke('text')
.then(($associatedAmount) => {
cy.wrap(
stakingBridgeContract.remove_stake(
String(stakeBalance),
vegaWalletPubKey
),
{ timeout: transactionTimeout, log: false }
);
cy.get("[data-testid='currency-value']")
.first()
.invoke('text', {
cy.get('[data-testid="vega-wallet-balance-unstaked"]:visible').within(
() => {
cy.get(associatedAmountInWallet)
.invoke('text')
.then(($walletAmount) => {
cy.wrap(
stakingBridgeContract.remove_stake(
String(stakeBalance),
vegaWalletPubKey
),
{ timeout: transactionTimeout, log: false }
);
cy.get(associatedAmountInWallet, {
timeout: transactionTimeout,
})
.should('not.eq', $associatedAmount);
});
});
}).should('not.have.text', $walletAmount);
});
}
);
}
});
}
+1 -1
View File
@@ -8,7 +8,7 @@ NX_GITHUB_FEEDBACK_URL=https://github.com/vegaprotocol/feedback/discussions
NX_ANNOUNCEMENTS_CONFIG_URL=https://raw.githubusercontent.com/vegaprotocol/announcements/test/announcements.json
NX_VEGA_CONFIG_URL=''
NX_VEGA_URL=http://localhost:3028/query
NX_VEGA_URL=http://localhost:3008/graphql
NX_ETHEREUM_CHAIN_ID=1440
NX_ETH_URL_CONNECT=1
NX_ETH_WALLET_MNEMONIC=ozone access unlock valid olympic save include omit supply green clown session
@@ -14,7 +14,7 @@ export const AppLayout = ({ children }: AppLayoutProps) => {
const { isReadOnly } = useVegaWallet();
const AppLayoutClasses = classNames(
'app w-full max-w-[1500px] mx-auto grid',
'lg:text-body-large',
'font-alpha lg:text-body-large',
{
'grid-rows-[repeat(2,min-content)_1fr_min-content]': !isReadOnly,
'grid-rows-[repeat(3,min-content)_1fr_min-content]': isReadOnly,
@@ -14,13 +14,17 @@ import { ContractsContext } from './contracts-context';
import { createDefaultProvider } from '../../lib/web3-connectors';
import { useEthereumConfig } from '@vegaprotocol/web3';
import { useEnvironment } from '@vegaprotocol/environment';
import { ENV } from '../../config/env';
import { ENV } from '../../config';
/**
* Provides Vega Ethereum contract instances to its children.
*/
export const ContractsProvider = ({ children }: { children: JSX.Element }) => {
const { provider: activeProvider, account } = useWeb3React();
const {
provider: activeProvider,
account,
chainId: activeChainId,
} = useWeb3React();
const { config } = useEthereumConfig();
const { VEGA_ENV, ETHEREUM_PROVIDER_URL } = useEnvironment();
const [contracts, setContracts] =
@@ -39,7 +43,11 @@ export const ContractsProvider = ({ children }: { children: JSX.Element }) => {
ETHEREUM_PROVIDER_URL,
Number(config.chain_id)
);
const provider = activeProvider ? activeProvider : defaultProvider;
const provider =
activeProvider && activeChainId === Number(config.chain_id)
? activeProvider
: defaultProvider;
if (
account &&
@@ -84,7 +92,14 @@ export const ContractsProvider = ({ children }: { children: JSX.Element }) => {
// TODO: hacky quick fix for release to prevent race condition, find a better fix for this.
cancelled = true;
};
}, [activeProvider, account, config, VEGA_ENV, ETHEREUM_PROVIDER_URL]);
}, [
activeProvider,
activeChainId,
account,
config,
VEGA_ENV,
ETHEREUM_PROVIDER_URL,
]);
if (!contracts) {
return (
@@ -1,3 +1,3 @@
# App configuration variables
NX_VEGA_URL=http://localhost:3028/query
NX_VEGA_URL=http://localhost:3008/graphql
NX_VEGA_ENV=LOCAL
+363 -66
View File
@@ -37,8 +37,8 @@
"tranche_start": "2023-04-20T00:00:00.000Z",
"tranche_end": "2023-05-20T00:00:00.000Z",
"total_added": "19242.125",
"total_removed": "397.984073768865",
"locked_amount": "14587.4163594714507360625",
"total_removed": "959.3245960538025",
"locked_amount": "11862.280100983795583625",
"deposits": [
{
"amount": "188",
@@ -221,6 +221,21 @@
"amount": "195.89040769089",
"user": "0xDd7a98557586ce21f770662319C2047C5a3bD605",
"tx": "0x338ca1f2a725add8aa5328efa43ac7cb1e91c35bf01a2312431c0dbb57137387"
},
{
"amount": "96.6447222258",
"user": "0x1447Efc62d5077d7AbB20492dF831Dd6c9Eb1756",
"tx": "0x13b160a21d48eab98cc304bbb46cd675da08afbf6e0ad261c67c10ba34dc4d74"
},
{
"amount": "42.592326391125",
"user": "0x1447Efc62d5077d7AbB20492dF831Dd6c9Eb1756",
"tx": "0x5f544a659ae728cc7b1a29dcda14740425cadf1f47aa74bae92bf2ade3c8093d"
},
{
"amount": "422.1034736680125",
"user": "0xf915Da10e5136352Ba049acB0545Deb119054256",
"tx": "0x5932f574afe019060f5812fc89c7298ab9f768cddebe0a803c27e9914b45dc3d"
}
],
"users": [
@@ -270,11 +285,23 @@
"user": "0x1447Efc62d5077d7AbB20492dF831Dd6c9Eb1756",
"tranche_id": 56,
"tx": "0x300c18b4220d3bc357f054792cb65f05d4005912bf8e5d9580b5b830cc3c0845"
},
{
"amount": "96.6447222258",
"user": "0x1447Efc62d5077d7AbB20492dF831Dd6c9Eb1756",
"tranche_id": 56,
"tx": "0x13b160a21d48eab98cc304bbb46cd675da08afbf6e0ad261c67c10ba34dc4d74"
},
{
"amount": "42.592326391125",
"user": "0x1447Efc62d5077d7AbB20492dF831Dd6c9Eb1756",
"tranche_id": 56,
"tx": "0x5f544a659ae728cc7b1a29dcda14740425cadf1f47aa74bae92bf2ade3c8093d"
}
],
"total_tokens": "1207.5",
"withdrawn_tokens": "202.093666077975",
"remaining_tokens": "1005.406333922025"
"withdrawn_tokens": "341.3307146949",
"remaining_tokens": "866.1692853051"
},
{
"address": "0x33Ce1D9E53AFb7367E34749517C086405a651a95",
@@ -644,10 +671,17 @@
"tx": "0x6840e2b579765303fc31a04f43fcea1d5ccf157b46bbd1e3f3e7f6a2e6cea039"
}
],
"withdrawals": [],
"withdrawals": [
{
"amount": "422.1034736680125",
"user": "0xf915Da10e5136352Ba049acB0545Deb119054256",
"tranche_id": 56,
"tx": "0x5932f574afe019060f5812fc89c7298ab9f768cddebe0a803c27e9914b45dc3d"
}
],
"total_tokens": "1121.25",
"withdrawn_tokens": "0",
"remaining_tokens": "1121.25"
"withdrawn_tokens": "422.1034736680125",
"remaining_tokens": "699.1465263319875"
},
{
"address": "0x237D23FcA6d7B2530C7614a9cB921CF27924911E",
@@ -809,15 +843,25 @@
"tranche_id": 54,
"tranche_start": "2023-04-06T00:00:00.000Z",
"tranche_end": "2023-05-06T00:00:00.000Z",
"total_added": "8976",
"total_removed": "596.64743517951",
"locked_amount": "2615.8875925925923488",
"total_added": "14520",
"total_removed": "731.78640740205",
"locked_amount": "2175.2102777777776272",
"deposits": [
{
"amount": "111",
"user": "0x90Cf7B9958C3BbBCddAb52Ecc408535D4f3C4241",
"tx": "0x1229e077f48b796678436bfa8143cea3ae71df58b589ac922be205c4482be235"
},
{
"amount": "5010",
"user": "0x83D7eD53E7CB97b542F1F71f40561d51F8019C8B",
"tx": "0xf0d2927bb8d9363ddefaad3783f9a0abf8e468316c4baea24766991f6cb8cdac"
},
{
"amount": "534",
"user": "0x2586bA83696a92b5467Aaa0CF9EEC052F28F2c02",
"tx": "0xf970ea0ce3e36fa0014d24bb830dd2ea0dbea06f6e53af486de5ee7e1c63e540"
},
{
"amount": "33",
"user": "0xBf1AaB792D729fA125e6D7122D4b916a1E1C44B1",
@@ -960,6 +1004,11 @@
"user": "0x6F32AA5A6198329c16e438512F992a0548C856f9",
"tx": "0x4027743264e01043ddb16676c6f7914c110df9e7212bd3f21cb6842614ce238f"
},
{
"amount": "135.13897222254",
"user": "0x6F32AA5A6198329c16e438512F992a0548C856f9",
"tx": "0x29905e6ae54245e824fe9ea488f491b1a3c33f6d8b9345cf2b6b00aec305c5bf"
},
{
"amount": "5.46866782407",
"user": "0x92A1e98C6f09970e45645Cbe57c6DcaF4547c8FE",
@@ -1007,6 +1056,36 @@
"withdrawn_tokens": "0",
"remaining_tokens": "111"
},
{
"address": "0x83D7eD53E7CB97b542F1F71f40561d51F8019C8B",
"deposits": [
{
"amount": "5010",
"user": "0x83D7eD53E7CB97b542F1F71f40561d51F8019C8B",
"tranche_id": 54,
"tx": "0xf0d2927bb8d9363ddefaad3783f9a0abf8e468316c4baea24766991f6cb8cdac"
}
],
"withdrawals": [],
"total_tokens": "5010",
"withdrawn_tokens": "0",
"remaining_tokens": "5010"
},
{
"address": "0x2586bA83696a92b5467Aaa0CF9EEC052F28F2c02",
"deposits": [
{
"amount": "534",
"user": "0x2586bA83696a92b5467Aaa0CF9EEC052F28F2c02",
"tranche_id": 54,
"tx": "0xf970ea0ce3e36fa0014d24bb830dd2ea0dbea06f6e53af486de5ee7e1c63e540"
}
],
"withdrawals": [],
"total_tokens": "534",
"withdrawn_tokens": "0",
"remaining_tokens": "534"
},
{
"address": "0xBf1AaB792D729fA125e6D7122D4b916a1E1C44B1",
"deposits": [
@@ -1219,6 +1298,12 @@
"tranche_id": 54,
"tx": "0x4027743264e01043ddb16676c6f7914c110df9e7212bd3f21cb6842614ce238f"
},
{
"amount": "135.13897222254",
"user": "0x6F32AA5A6198329c16e438512F992a0548C856f9",
"tranche_id": 54,
"tx": "0x29905e6ae54245e824fe9ea488f491b1a3c33f6d8b9345cf2b6b00aec305c5bf"
},
{
"amount": "155.03186111556",
"user": "0x6F32AA5A6198329c16e438512F992a0548C856f9",
@@ -1245,8 +1330,8 @@
}
],
"total_tokens": "858",
"withdrawn_tokens": "531.01030786518",
"remaining_tokens": "326.98969213482"
"withdrawn_tokens": "666.14928008772",
"remaining_tokens": "191.85071991228"
},
{
"address": "0x0bBf7580e036eA5D69ABe679CC90117EeC2e3dc1",
@@ -1583,7 +1668,7 @@
"tranche_start": "2023-03-06T00:00:00.000Z",
"tranche_end": "2023-04-06T00:00:00.000Z",
"total_added": "14099",
"total_removed": "3112.49002352036",
"total_removed": "3142.49002352036",
"locked_amount": "0",
"deposits": [
{
@@ -2348,6 +2433,11 @@
}
],
"withdrawals": [
{
"amount": "30",
"user": "0xBe9F912Ad481C61B653463E8F1D2b2b310D49861",
"tx": "0x191a1901917ada560c9c30efd3d24c0ec116b9dc131a6966cc67ad7e3701df3b"
},
{
"amount": "30",
"user": "0x8499411Bff99ddE9A02903008F917EEa0E27B42A",
@@ -2582,10 +2672,17 @@
"tx": "0x20d505a766d3d8e376509ed8003a5b9f35fd0524f0979a5a57c7d3714d01d3e5"
}
],
"withdrawals": [],
"withdrawals": [
{
"amount": "30",
"user": "0xBe9F912Ad481C61B653463E8F1D2b2b310D49861",
"tranche_id": 53,
"tx": "0x191a1901917ada560c9c30efd3d24c0ec116b9dc131a6966cc67ad7e3701df3b"
}
],
"total_tokens": "30",
"withdrawn_tokens": "0",
"remaining_tokens": "30"
"withdrawn_tokens": "30",
"remaining_tokens": "0"
},
{
"address": "0xA9821681fEF27Ed817DF77E476DDDAf0aDac4443",
@@ -4594,7 +4691,7 @@
"tranche_end": "2023-12-05T00:00:00.000Z",
"total_added": "86666.297",
"total_removed": "0",
"locked_amount": "52651.0670675174430414228",
"locked_amount": "51642.2467468320019705714",
"deposits": [
{
"amount": "86666.297",
@@ -4660,7 +4757,7 @@
"tranche_end": "2023-06-01T00:00:00.000Z",
"total_added": "2500",
"total_removed": "0",
"locked_amount": "477.23818426943425",
"locked_amount": "418.87686965811965",
"deposits": [
{
"amount": "2500",
@@ -4693,7 +4790,7 @@
"tranche_end": "2023-11-01T00:00:00.000Z",
"total_added": "15000.000000000000015",
"total_removed": "0",
"locked_amount": "15000.000000000000015",
"locked_amount": "14958.769248188406014958769248188406",
"deposits": [
{
"amount": "1.5e-14",
@@ -4781,7 +4878,7 @@
"tranche_end": "2023-09-01T00:00:00.000Z",
"total_added": "17500",
"total_removed": "0",
"locked_amount": "12054.35568890901775",
"locked_amount": "11650.267021437198",
"deposits": [
{
"amount": "12500",
@@ -5047,8 +5144,8 @@
"tranche_start": "2023-02-01T00:00:00.000Z",
"tranche_end": "2023-08-01T00:00:00.000Z",
"total_added": "37500",
"total_removed": "12704.026146825",
"locked_amount": "19836.24443677102875",
"total_removed": "17836.1796921",
"locked_amount": "18955.98814456722",
"deposits": [
{
"amount": "7500",
@@ -5067,6 +5164,16 @@
"user": "0x20CD77B9FC2f1fEDfb6F184E25f7127BFE991C8b",
"tx": "0x4dc6eefb43f5b1704894582aa926f0c6ecd94550ac354b7d5b5f49b0f17261fd"
},
{
"amount": "4974.3093924",
"user": "0x0B4e6fcE839B01ef43DA6F890FAC7B1Afb004600",
"tx": "0xfce75d8b6bf0d20cbdb1ef29cfabcae4f4504c30b30ca166b4e66d37f7f04339"
},
{
"amount": "157.844152875",
"user": "0x20CD77B9FC2f1fEDfb6F184E25f7127BFE991C8b",
"tx": "0x6bb6303a6a322698e6e295ad38b2a22bd20d8b44306d423a3e513bb0b858ad56"
},
{
"amount": "126.30064455",
"user": "0x20CD77B9FC2f1fEDfb6F184E25f7127BFE991C8b",
@@ -5231,6 +5338,12 @@
"tranche_id": 34,
"tx": "0x4dc6eefb43f5b1704894582aa926f0c6ecd94550ac354b7d5b5f49b0f17261fd"
},
{
"amount": "157.844152875",
"user": "0x20CD77B9FC2f1fEDfb6F184E25f7127BFE991C8b",
"tranche_id": 34,
"tx": "0x6bb6303a6a322698e6e295ad38b2a22bd20d8b44306d423a3e513bb0b858ad56"
},
{
"amount": "126.30064455",
"user": "0x20CD77B9FC2f1fEDfb6F184E25f7127BFE991C8b",
@@ -5395,8 +5508,8 @@
}
],
"total_tokens": "7500",
"withdrawn_tokens": "3468.576868425",
"remaining_tokens": "4031.423131575"
"withdrawn_tokens": "3626.4210213",
"remaining_tokens": "3873.5789787"
},
{
"address": "0x0B4e6fcE839B01ef43DA6F890FAC7B1Afb004600",
@@ -5409,6 +5522,12 @@
}
],
"withdrawals": [
{
"amount": "4974.3093924",
"user": "0x0B4e6fcE839B01ef43DA6F890FAC7B1Afb004600",
"tranche_id": 34,
"tx": "0xfce75d8b6bf0d20cbdb1ef29cfabcae4f4504c30b30ca166b4e66d37f7f04339"
},
{
"amount": "6960.3360957",
"user": "0x0B4e6fcE839B01ef43DA6F890FAC7B1Afb004600",
@@ -5423,8 +5542,8 @@
}
],
"total_tokens": "30000",
"withdrawn_tokens": "9235.4492784",
"remaining_tokens": "20764.5507216"
"withdrawn_tokens": "14209.7586708",
"remaining_tokens": "15790.2413292"
}
]
},
@@ -5434,7 +5553,7 @@
"tranche_end": "2023-12-05T00:00:00.000Z",
"total_added": "129999.45",
"total_removed": "0",
"locked_amount": "52603.029593629619941305",
"locked_amount": "51595.1296945521630417525",
"deposits": [
{
"amount": "129999.45",
@@ -5467,7 +5586,7 @@
"tranche_end": "2024-04-01T00:00:00.000Z",
"total_added": "54144.7663",
"total_removed": "0",
"locked_amount": "50260.38819220796159812442",
"locked_amount": "49631.84975200308971004133",
"deposits": [
{
"amount": "54144.7663",
@@ -5500,7 +5619,7 @@
"tranche_end": "2023-09-03T00:00:00.000Z",
"total_added": "62600",
"total_removed": "0",
"locked_amount": "22080.29597919837872",
"locked_amount": "21351.614193302888218",
"deposits": [
{
"amount": "10000",
@@ -5693,7 +5812,7 @@
"tranche_end": "2023-09-17T00:00:00.000Z",
"total_added": "5000",
"total_removed": "0",
"locked_amount": "1955.382737189244",
"locked_amount": "1897.1813165905632",
"deposits": [
{
"amount": "5000",
@@ -6233,8 +6352,8 @@
"tranche_start": "2022-11-01T00:00:00.000Z",
"tranche_end": "2023-05-01T00:00:00.000Z",
"total_added": "22500",
"total_removed": "7280.725809525",
"locked_amount": "465.2825736648258",
"total_removed": "7438.558452225",
"locked_amount": "0",
"deposits": [
{
"amount": "7500",
@@ -6253,6 +6372,11 @@
"user": "0x20CD77B9FC2f1fEDfb6F184E25f7127BFE991C8b",
"tx": "0xa9dd827abcfaa4b289c6bcf5923d455380c1d4f9ce4ce615415a513df60b1ea8"
},
{
"amount": "157.8326427",
"user": "0x20CD77B9FC2f1fEDfb6F184E25f7127BFE991C8b",
"tx": "0xb76564ca91603758216069d7b139c683037029425e10b1694af25b478c19e26f"
},
{
"amount": "126.2948895",
"user": "0x20CD77B9FC2f1fEDfb6F184E25f7127BFE991C8b",
@@ -6472,6 +6596,12 @@
"tranche_id": 33,
"tx": "0xa9dd827abcfaa4b289c6bcf5923d455380c1d4f9ce4ce615415a513df60b1ea8"
},
{
"amount": "157.8326427",
"user": "0x20CD77B9FC2f1fEDfb6F184E25f7127BFE991C8b",
"tranche_id": 33,
"tx": "0xb76564ca91603758216069d7b139c683037029425e10b1694af25b478c19e26f"
},
{
"amount": "126.2948895",
"user": "0x20CD77B9FC2f1fEDfb6F184E25f7127BFE991C8b",
@@ -6714,8 +6844,8 @@
}
],
"total_tokens": "7500",
"withdrawn_tokens": "7280.725809525",
"remaining_tokens": "219.274190475"
"withdrawn_tokens": "7438.558452225",
"remaining_tokens": "61.441547775"
},
{
"address": "0x2539b51EbDE65a75672aBcfE9439a706a99D18D1",
@@ -6740,7 +6870,7 @@
"tranche_end": "2023-06-02T00:00:00.000Z",
"total_added": "1939928.38",
"total_removed": "1709370.7872515768348",
"locked_amount": "189969.1598120306593902572",
"locked_amount": "167387.8422968911644940364",
"deposits": [
{
"amount": "1852091.69",
@@ -9760,10 +9890,15 @@
"tranche_id": 10,
"tranche_start": "2021-07-15T23:37:11.000Z",
"tranche_end": "2021-07-15T23:37:11.000Z",
"total_added": "6459302.299000000000000001",
"total_removed": "6413483.280000000000000001",
"total_added": "6559302.299000000000000001",
"total_removed": "6513483.280000000000000001",
"locked_amount": "0",
"deposits": [
{
"amount": "100000",
"user": "0xb2d6DEC77558Cf8EdB7c428d23E70Eab0688544f",
"tx": "0xfe7ab31de818986a1984617dea435e8bb02fba8fca50c1e173b5808fc8c2a81e"
},
{
"amount": "100000",
"user": "0xb2d6DEC77558Cf8EdB7c428d23E70Eab0688544f",
@@ -10301,6 +10436,11 @@
}
],
"withdrawals": [
{
"amount": "100000",
"user": "0xb2d6DEC77558Cf8EdB7c428d23E70Eab0688544f",
"tx": "0xfe7ab31de818986a1984617dea435e8bb02fba8fca50c1e173b5808fc8c2a81e"
},
{
"amount": "100000",
"user": "0xb2d6DEC77558Cf8EdB7c428d23E70Eab0688544f",
@@ -10781,6 +10921,12 @@
{
"address": "0xb2d6DEC77558Cf8EdB7c428d23E70Eab0688544f",
"deposits": [
{
"amount": "100000",
"user": "0xb2d6DEC77558Cf8EdB7c428d23E70Eab0688544f",
"tranche_id": 10,
"tx": "0xfe7ab31de818986a1984617dea435e8bb02fba8fca50c1e173b5808fc8c2a81e"
},
{
"amount": "100000",
"user": "0xb2d6DEC77558Cf8EdB7c428d23E70Eab0688544f",
@@ -10981,6 +11127,12 @@
}
],
"withdrawals": [
{
"amount": "100000",
"user": "0xb2d6DEC77558Cf8EdB7c428d23E70Eab0688544f",
"tranche_id": 10,
"tx": "0xfe7ab31de818986a1984617dea435e8bb02fba8fca50c1e173b5808fc8c2a81e"
},
{
"amount": "100000",
"user": "0xb2d6DEC77558Cf8EdB7c428d23E70Eab0688544f",
@@ -11174,8 +11326,8 @@
"tx": "0xac16a4ce688d40a482a59914d68c3a676592f8804ee8f0781b66a4ba5ccfbdfc"
}
],
"total_tokens": "3256651",
"withdrawn_tokens": "3256651",
"total_tokens": "3356651",
"withdrawn_tokens": "3356651",
"remaining_tokens": "0"
},
{
@@ -12240,7 +12392,7 @@
"tranche_start": "2021-09-03T00:00:00.000Z",
"tranche_end": "2022-09-03T00:00:00.000Z",
"total_added": "57278.000000000000000003",
"total_removed": "48182.21518131551",
"total_removed": "50196.35141572991",
"locked_amount": "0",
"deposits": [
{
@@ -22825,6 +22977,16 @@
}
],
"withdrawals": [
{
"amount": "725",
"user": "0x52Dd36AB8e8eec8f6bE968E93679838dc73b19D3",
"tx": "0xbc67aa993d42656a84c7da90e6abcc0a3c00e7e9e21da4013251b0f8582567ca"
},
{
"amount": "1289.1362344144",
"user": "0xab6dE081Af6C78433AFDaC5B756804bcE17e9eC1",
"tx": "0x9e6077e2dc83701a70b2a04028ab533e89cd7f1bb757ea4fe45e1388cfee600d"
},
{
"amount": "25",
"user": "0x363D3d06d70761c34D6EfEB25E409A9549E6970D",
@@ -32334,10 +32496,17 @@
"tx": "0x1a0e42b837a8f3908bc4e36e9b024f48c371b98f066a0db36fd98793cd178f57"
}
],
"withdrawals": [],
"withdrawals": [
{
"amount": "725",
"user": "0x52Dd36AB8e8eec8f6bE968E93679838dc73b19D3",
"tranche_id": 11,
"tx": "0xbc67aa993d42656a84c7da90e6abcc0a3c00e7e9e21da4013251b0f8582567ca"
}
],
"total_tokens": "725",
"withdrawn_tokens": "0",
"remaining_tokens": "725"
"withdrawn_tokens": "725",
"remaining_tokens": "0"
},
{
"address": "0xab6dE081Af6C78433AFDaC5B756804bcE17e9eC1",
@@ -33040,6 +33209,12 @@
}
],
"withdrawals": [
{
"amount": "1289.1362344144",
"user": "0xab6dE081Af6C78433AFDaC5B756804bcE17e9eC1",
"tranche_id": 11,
"tx": "0x9e6077e2dc83701a70b2a04028ab533e89cd7f1bb757ea4fe45e1388cfee600d"
},
{
"amount": "842.29689345648",
"user": "0xab6dE081Af6C78433AFDaC5B756804bcE17e9eC1",
@@ -33084,8 +33259,8 @@
}
],
"total_tokens": "3439",
"withdrawn_tokens": "2149.8637655856",
"remaining_tokens": "1289.1362344144"
"withdrawn_tokens": "3439",
"remaining_tokens": "0"
},
{
"address": "0x23E18CBa049393DFebC5a17e3b5ec9aF584CAE04",
@@ -40567,7 +40742,7 @@
"tranche_end": "2023-06-05T00:00:00.000Z",
"total_added": "3732368.4671",
"total_removed": "715655.108029600523393",
"locked_amount": "316417.783123780845942826482",
"locked_amount": "281718.160082742394755587753",
"deposits": [
{
"amount": "1998.95815",
@@ -41959,8 +42134,8 @@
"tranche_start": "2022-06-05T00:00:00.000Z",
"tranche_end": "2023-12-05T00:00:00.000Z",
"total_added": "15870102.715470999700000001",
"total_removed": "864400.93329864929559852",
"locked_amount": "6421684.7286343349090524101959629311219249",
"total_removed": "866687.25765937723884852",
"locked_amount": "6298642.09325955374430918146676915717356045",
"deposits": [
{
"amount": "16249.93",
@@ -42494,6 +42669,21 @@
"user": "0x20CD77B9FC2f1fEDfb6F184E25f7127BFE991C8b",
"tx": "0x28d2b3f088965906ac3da878c491309729680c302fb98e2a435d07f88d6b962a"
},
{
"amount": "381.93267176186375",
"user": "0x20CD77B9FC2f1fEDfb6F184E25f7127BFE991C8b",
"tx": "0x6d5ce55a076149d5f66e5e84720d3bd46f31e5c79c54632927c1a00d1fdbce37"
},
{
"amount": "980.13570973214325",
"user": "0x20CD77B9FC2f1fEDfb6F184E25f7127BFE991C8b",
"tx": "0x45de80ad7201a69e9ac4f1f964218840867adaf64a7fc6020b51baa5de37816e"
},
{
"amount": "924.25597923393625",
"user": "0x20CD77B9FC2f1fEDfb6F184E25f7127BFE991C8b",
"tx": "0x2e3b57da0245aea9164e96cd7421d82a3f34df2ab34bc9a64b91e629fb5cb31c"
},
{
"amount": "981.387731774910625",
"user": "0x20CD77B9FC2f1fEDfb6F184E25f7127BFE991C8b",
@@ -44620,6 +44810,24 @@
"tranche_id": 2,
"tx": "0x28d2b3f088965906ac3da878c491309729680c302fb98e2a435d07f88d6b962a"
},
{
"amount": "381.93267176186375",
"user": "0x20CD77B9FC2f1fEDfb6F184E25f7127BFE991C8b",
"tranche_id": 2,
"tx": "0x6d5ce55a076149d5f66e5e84720d3bd46f31e5c79c54632927c1a00d1fdbce37"
},
{
"amount": "980.13570973214325",
"user": "0x20CD77B9FC2f1fEDfb6F184E25f7127BFE991C8b",
"tranche_id": 2,
"tx": "0x45de80ad7201a69e9ac4f1f964218840867adaf64a7fc6020b51baa5de37816e"
},
{
"amount": "924.25597923393625",
"user": "0x20CD77B9FC2f1fEDfb6F184E25f7127BFE991C8b",
"tranche_id": 2,
"tx": "0x2e3b57da0245aea9164e96cd7421d82a3f34df2ab34bc9a64b91e629fb5cb31c"
},
{
"amount": "981.387731774910625",
"user": "0x20CD77B9FC2f1fEDfb6F184E25f7127BFE991C8b",
@@ -46128,8 +46336,8 @@
}
],
"total_tokens": "259998.8875",
"withdrawn_tokens": "154502.7650820091405",
"remaining_tokens": "105496.1224179908595"
"withdrawn_tokens": "156789.08944273708375",
"remaining_tokens": "103209.79805726291625"
},
{
"address": "0x89051CAb67Bc7F8CC44F7e270c6EDaf1EC57676c",
@@ -48504,8 +48712,8 @@
"tranche_start": "2021-11-05T00:00:00.000Z",
"tranche_end": "2023-05-05T00:00:00.000Z",
"total_added": "14597706.0446472999",
"total_removed": "6129688.581848831721813882",
"locked_amount": "207013.1123407730577557502438032262",
"total_removed": "6167911.210808830654624182",
"locked_amount": "93420.936997419715583180200347021",
"deposits": [
{
"amount": "129284.449",
@@ -48734,6 +48942,31 @@
"user": "0xDdc5F6484349B242A9B23382Aa21f49B5Dc9a089",
"tx": "0xba1fdde929e0e2d4fe79de4dbac92cb5d20bb8b1dd7e5ff9bab961b728e7dae2"
},
{
"amount": "529.38555487723284925",
"user": "0x4Aa3c35F6CC2d507E5C18205ee57099A4C80B19b",
"tx": "0x0c555d0f3b2b4b3fb50f208d9155b5886c83511a552518af11cadd5d5a06acec"
},
{
"amount": "1358.95419763598962675",
"user": "0x4Aa3c35F6CC2d507E5C18205ee57099A4C80B19b",
"tx": "0x59bc5ab04aa250d84bd2ffe62dba38ed926c26f8ac2497e9414f3a7df2b3a661"
},
{
"amount": "35040.39233886007943262",
"user": "0x66827bCD635f2bB1779d68c46aEB16541bCA6ba8",
"tx": "0x956f4f6e867e23aa7a3f0fb29612074de4edaf259eb1597f61b5289add0bedb2"
},
{
"amount": "4.18758350477578368",
"user": "0x66827bCD635f2bB1779d68c46aEB16541bCA6ba8",
"tx": "0xa83729135615d88392e9ec5164e60ae9fe049b0127c7829c44dc94ee1b28d73e"
},
{
"amount": "1289.709285120855118",
"user": "0x4Aa3c35F6CC2d507E5C18205ee57099A4C80B19b",
"tx": "0x2c531bd9c61e0a3705f161bba2c03703722f1e41533725684fcccb9176117e0e"
},
{
"amount": "1360.32447632896938825",
"user": "0x4Aa3c35F6CC2d507E5C18205ee57099A4C80B19b",
@@ -52052,6 +52285,24 @@
"tranche_id": 3,
"tx": "0xc37374c867eb2543ba3de47bf14990096f3371a93609cfd557a1eeaa3fb3e774"
},
{
"amount": "529.38555487723284925",
"user": "0x4Aa3c35F6CC2d507E5C18205ee57099A4C80B19b",
"tranche_id": 3,
"tx": "0x0c555d0f3b2b4b3fb50f208d9155b5886c83511a552518af11cadd5d5a06acec"
},
{
"amount": "1358.95419763598962675",
"user": "0x4Aa3c35F6CC2d507E5C18205ee57099A4C80B19b",
"tranche_id": 3,
"tx": "0x59bc5ab04aa250d84bd2ffe62dba38ed926c26f8ac2497e9414f3a7df2b3a661"
},
{
"amount": "1289.709285120855118",
"user": "0x4Aa3c35F6CC2d507E5C18205ee57099A4C80B19b",
"tranche_id": 3,
"tx": "0x2c531bd9c61e0a3705f161bba2c03703722f1e41533725684fcccb9176117e0e"
},
{
"amount": "1360.32447632896938825",
"user": "0x4Aa3c35F6CC2d507E5C18205ee57099A4C80B19b",
@@ -54874,8 +55125,8 @@
}
],
"total_tokens": "359123.469575",
"withdrawn_tokens": "353628.4490036538056375",
"remaining_tokens": "5495.0205713461943625"
"withdrawn_tokens": "356806.4980412878832315",
"remaining_tokens": "2316.9715337121167685"
},
{
"address": "0xBdd412797c1B78535Afc5F71503b91fAbD0160fB",
@@ -55105,6 +55356,18 @@
}
],
"withdrawals": [
{
"amount": "35040.39233886007943262",
"user": "0x66827bCD635f2bB1779d68c46aEB16541bCA6ba8",
"tranche_id": 3,
"tx": "0x956f4f6e867e23aa7a3f0fb29612074de4edaf259eb1597f61b5289add0bedb2"
},
{
"amount": "4.18758350477578368",
"user": "0x66827bCD635f2bB1779d68c46aEB16541bCA6ba8",
"tranche_id": 3,
"tx": "0xa83729135615d88392e9ec5164e60ae9fe049b0127c7829c44dc94ee1b28d73e"
},
{
"amount": "5074.06012653876566886",
"user": "0x66827bCD635f2bB1779d68c46aEB16541bCA6ba8",
@@ -55497,8 +55760,8 @@
}
],
"total_tokens": "1266324.603486",
"withdrawn_tokens": "1220819.41847917671599364",
"remaining_tokens": "45505.18500682328400636"
"withdrawn_tokens": "1255863.99840154157120994",
"remaining_tokens": "10460.60508445842879006"
},
{
"address": "0xC5d9221EB9c28A69859264c0A2Fe0d3272228296",
@@ -58526,8 +58789,8 @@
"tranche_start": "2022-06-05T00:00:00.000Z",
"tranche_end": "2023-06-05T00:00:00.000Z",
"total_added": "472355.6199999996",
"total_removed": "43935.8732690563416",
"locked_amount": "50138.206457121953572821564586524",
"total_removed": "44078.8527972103416",
"locked_amount": "44639.852834767825412159812480992",
"deposits": [
{
"amount": "3000",
@@ -65171,6 +65434,16 @@
"user": "0x0a6A5e1da768709A2bF17b2E58B2B73120051D03",
"tx": "0x097e43cb4f64f1cb502f321eceb8b91e6378cac0b3b6fe558fc1d543aec597e2"
},
{
"amount": "61.181050224",
"user": "0xe7770271d882C54C46B9f00137e96a3BbfFD4d94",
"tx": "0x3c7d0394e431000fa5c733213116dc39b0f87a9a32a40e75cec3c2fce7795b0b"
},
{
"amount": "81.79847793",
"user": "0x4d4AA3f302cbA998AAFC03F9d73484434ed9Fd53",
"tx": "0x1e4902d0a3cb7b4f2ba7119dfcaa681a784e1d724c984961767e9feaa078fe54"
},
{
"amount": "168.502276762",
"user": "0x38A292CB98Dc602ECAFF94E8E5fADD9800e4bA13",
@@ -78176,6 +78449,12 @@
}
],
"withdrawals": [
{
"amount": "61.181050224",
"user": "0xe7770271d882C54C46B9f00137e96a3BbfFD4d94",
"tranche_id": 5,
"tx": "0x3c7d0394e431000fa5c733213116dc39b0f87a9a32a40e75cec3c2fce7795b0b"
},
{
"amount": "101.521461192",
"user": "0xe7770271d882C54C46B9f00137e96a3BbfFD4d94",
@@ -78214,8 +78493,8 @@
}
],
"total_tokens": "600",
"withdrawn_tokens": "476.48491248",
"remaining_tokens": "123.51508752"
"withdrawn_tokens": "537.665962704",
"remaining_tokens": "62.334037296"
},
{
"address": "0x79D8ff1699911f065fD97a95a6B47216925C4B0e",
@@ -87309,6 +87588,12 @@
}
],
"withdrawals": [
{
"amount": "81.79847793",
"user": "0x4d4AA3f302cbA998AAFC03F9d73484434ed9Fd53",
"tranche_id": 5,
"tx": "0x1e4902d0a3cb7b4f2ba7119dfcaa681a784e1d724c984961767e9feaa078fe54"
},
{
"amount": "32.02214612",
"user": "0x4d4AA3f302cbA998AAFC03F9d73484434ed9Fd53",
@@ -87335,8 +87620,8 @@
}
],
"total_tokens": "200",
"withdrawn_tokens": "99.05242897",
"remaining_tokens": "100.94757103"
"withdrawn_tokens": "180.8509069",
"remaining_tokens": "19.1490931"
},
{
"address": "0xd9390b46a1749DEe5325A490490491db9a826D1F",
@@ -88271,7 +88556,7 @@
"tranche_start": "2021-12-05T00:00:00.000Z",
"tranche_end": "2022-06-05T00:00:00.000Z",
"total_added": "171288.42",
"total_removed": "69890.5995794947989",
"total_removed": "70140.5995794947989",
"locked_amount": "0",
"deposits": [
{
@@ -92496,6 +92781,11 @@
}
],
"withdrawals": [
{
"amount": "250",
"user": "0x0E3407C9A94effa675471afe7A9D37e687C32141",
"tx": "0x6086c36011fd863c6a34f1a7cd45a798bb1bf6bde6f0e4106c51071c46dbef79"
},
{
"amount": "250",
"user": "0x99492aF57325BA3971542B9ea4036186BE50fa07",
@@ -95770,10 +96060,17 @@
"tx": "0xee02e72ef8e0755982704385da512cc12c8ff0ea7b58056fa3d5a5932394e9ca"
}
],
"withdrawals": [],
"withdrawals": [
{
"amount": "250",
"user": "0x0E3407C9A94effa675471afe7A9D37e687C32141",
"tranche_id": 6,
"tx": "0x6086c36011fd863c6a34f1a7cd45a798bb1bf6bde6f0e4106c51071c46dbef79"
}
],
"total_tokens": "250",
"withdrawn_tokens": "0",
"remaining_tokens": "250"
"withdrawn_tokens": "250",
"remaining_tokens": "0"
},
{
"address": "0x953680303b33898962AB7FadCD485374CeDFf87e",
+2 -2
View File
@@ -8,7 +8,7 @@ NX_VEGA_ENV=CUSTOM
NX_VEGA_EXPLORER_URL=https://explorer.fairground.wtf
NX_VEGA_NETWORKS={\"TESTNET\":\"https://console.fairground.wtf\",\"STAGNET1\":\"https://stagnet1.console.vega.xyz\",\"STAGNET3\":\"https://stagnet3.console.vega.xyz\"}
NX_VEGA_TOKEN_URL=https://token.fairground.wtf
NX_VEGA_URL=http://localhost:3028/query
NX_VEGA_URL=http://localhost:3008/graphql
NX_VEGA_WALLET_URL=http://localhost:1789
NX_ETH_LOCAL_PROVIDER_URL=http://localhost:8545/
NX_ETH_WALLET_MNEMONIC="ozone access unlock valid olympic save include omit supply green clown session"
@@ -27,6 +27,6 @@ CYPRESS_VEGA_ENV=CUSTOM
CYPRESS_VEGA_PUBLIC_KEY=02eceaba4df2bef76ea10caf728d8a099a2aa846cced25737cccaa9812342f65
CYPRESS_VEGA_PUBLIC_KEY2=7f9cf07d3a9905b1a61a1069f7a758855da428bc0f4a97de87f48644bfc25535
CYPRESS_VEGA_TOKEN_URL=https://token.fairground.wtf
CYPRESS_VEGA_URL=http://localhost:3028/query
CYPRESS_VEGA_URL=http://localhost:3008/graphql
CYPRESS_VEGA_WALLET_URL=http://localhost:1789
CYPRESS_VEGA_WALLET_API_TOKEN=
+2 -2
View File
@@ -7,7 +7,7 @@ NX_VEGA_ENV=CUSTOM
NX_VEGA_EXPLORER_URL=https://explorer.fairground.wtf
NX_VEGA_NETWORKS={\"TESTNET\":\"https://console.fairground.wtf\",\"STAGNET1\":\"https://stagnet1.console.vega.xyz\",\"STAGNET3\":\"https://stagnet3.console.vega.xyz\"}
NX_VEGA_TOKEN_URL=https://token.fairground.wtf
NX_VEGA_URL=http://localhost:3028/query
NX_VEGA_URL=http://localhost:3008/graphql
NX_VEGA_WALLET_URL=http://localhost:1789
NX_ETH_LOCAL_PROVIDER_URL=http://localhost:8545/
NX_ETH_WALLET_MNEMONIC="ozone access unlock valid olympic save include omit supply green clown session"
@@ -24,6 +24,6 @@ CYPRESS_VEGA_ENV=CUSTOM
CYPRESS_VEGA_PUBLIC_KEY=02eceaba4df2bef76ea10caf728d8a099a2aa846cced25737cccaa9812342f65
CYPRESS_VEGA_PUBLIC_KEY2=7f9cf07d3a9905b1a61a1069f7a758855da428bc0f4a97de87f48644bfc25535
CYPRESS_VEGA_TOKEN_URL=https://token.fairground.wtf
CYPRESS_VEGA_URL=http://localhost:3028/query
CYPRESS_VEGA_URL=http://localhost:3008/graphql
CYPRESS_VEGA_WALLET_URL=http://localhost:1789
CYPRESS_VEGA_WALLET_API_TOKEN=
@@ -0,0 +1,375 @@
import { aliasGQLQuery } from '@vegaprotocol/cypress';
import { MarketState, MarketStateMapping } from '@vegaprotocol/types';
import { addDays, subDays } from 'date-fns';
import {
chainIdQuery,
statisticsQuery,
createDataConnection,
oracleSpecDataConnectionQuery,
createMarketFragment,
marketsQuery,
marketsDataQuery,
createMarketsDataFragment,
assetQuery,
networkParamsQuery,
} from '@vegaprotocol/mock';
import {
addDecimalsFormatNumber,
getDateTimeFormat,
} from '@vegaprotocol/utils';
describe('Closed markets', { tags: '@smoke' }, () => {
const rowSelector =
'[data-testid="tab-closed-markets"] .ag-center-cols-container .ag-row';
const assetsResult = assetQuery();
// @ts-ignore asset definitely exists
const settlementAsset = assetsResult.assetsConnection.edges[0].node;
const settledMarket = createMarketFragment({
id: '0',
state: MarketState.STATE_SETTLED,
marketTimestamps: {
open: subDays(new Date(), 10).toISOString(),
close: subDays(new Date(), 4).toISOString(),
},
tradableInstrument: {
instrument: {
product: {
dataSourceSpecForTradingTermination: {
id: 'market-1-trading-termination-oracle-id',
},
dataSourceSpecForSettlementData: {
id: 'market-1-settlement-data-oracle-id',
},
settlementAsset,
},
},
},
});
const terminatedMarket = createMarketFragment({
id: '1',
state: MarketState.STATE_TRADING_TERMINATED,
marketTimestamps: {
open: subDays(new Date(), 10).toISOString(),
close: null, // market
},
tradableInstrument: {
instrument: {
metadata: {
tags: [
`settlement-expiry-date:${addDays(new Date(), 4).toISOString()}`,
],
},
},
},
});
const delayedSettledMarket = createMarketFragment({
id: '2',
state: MarketState.STATE_TRADING_TERMINATED,
marketTimestamps: {
open: subDays(new Date(), 10).toISOString(),
close: null, // market
},
tradableInstrument: {
instrument: {
metadata: {
tags: [
`settlement-expiry-date:${subDays(new Date(), 2).toISOString()}`,
],
},
},
},
});
const unknownMarket = createMarketFragment({
id: '3',
state: MarketState.STATE_SETTLED,
});
const closedMarketsResult = [
{
node: settledMarket,
},
{
node: terminatedMarket,
},
{
node: delayedSettledMarket,
},
{ node: unknownMarket },
{
node: createMarketFragment({ id: '4', state: MarketState.STATE_PENDING }),
},
{
node: createMarketFragment({ id: '5', state: MarketState.STATE_ACTIVE }),
},
];
const settledMarketData = createMarketsDataFragment({
market: {
id: settledMarket.id,
},
bestBidPrice: '1000',
bestOfferPrice: '2000',
markPrice: '1500',
});
const closedMarketsDataResult = [
{
node: {
data: settledMarketData,
},
},
{
node: {
data: createMarketsDataFragment({
market: {
id: terminatedMarket.id,
},
}),
},
},
{
node: {
data: createMarketsDataFragment({
market: {
id: delayedSettledMarket.id,
},
}),
},
},
{
node: {
data: createMarketsDataFragment({
market: {
id: unknownMarket.id,
},
}),
},
},
];
const specDataConnection = createDataConnection();
before(() => {
cy.mockGQL((req) => {
aliasGQLQuery(req, 'ChainId', chainIdQuery());
aliasGQLQuery(req, 'Statistics', statisticsQuery());
aliasGQLQuery(req, 'NetworkParams', networkParamsQuery());
aliasGQLQuery(
req,
'Markets',
marketsQuery({
marketsConnection: {
edges: closedMarketsResult,
},
})
);
aliasGQLQuery(
req,
'MarketsData',
marketsDataQuery({
marketsConnection: {
edges: closedMarketsDataResult,
},
})
);
aliasGQLQuery(
req,
'OracleSpecDataConnection',
oracleSpecDataConnectionQuery()
);
});
cy.mockSubscription();
cy.visit('/#/markets/all');
cy.get('[data-testid="Closed markets"]').click();
});
it('renders a settled market', () => {
const expectedMarkets = closedMarketsResult.filter((edge) => {
return [
MarketState.STATE_SETTLED,
MarketState.STATE_TRADING_TERMINATED,
].includes(edge.node.state);
});
const product = settledMarket.tradableInstrument.instrument.product;
// rows should be filtered to only include settled/terminated markets
cy.get(rowSelector).should('have.length', expectedMarkets.length);
// check each column in the first row renders correctly
// 6001-MARK-001
cy.get(rowSelector)
.first()
.find('[col-id="code"]')
.should('have.text', settledMarket.tradableInstrument.instrument.code);
// 6001-MARK-002
cy.get(rowSelector)
.first()
.find('[col-id="name"]')
.should('have.text', settledMarket.tradableInstrument.instrument.name);
// 6001-MARK-003
cy.get(rowSelector)
.first()
.find('[col-id="state"]')
.should('have.text', MarketStateMapping[settledMarket.state]);
// 6001-MARK-004
// 6001-MARK-005
// 6001-MARK-009
// 6001-MARK-008
// 6001-MARK-010
cy.get(rowSelector)
.first()
.find('[col-id="settlementDate"]')
.find('[data-testid="link"]')
.should(($el) => {
const href = $el.attr('href');
expect(href).to.match(
new RegExp(
`/oracles/${product.dataSourceSpecForTradingTermination.id}`
)
);
})
.should('have.text', '4 days ago')
.should(
'have.attr',
'title',
getDateTimeFormat().format(
new Date(settledMarket.marketTimestamps.close)
)
);
// 6001-MARK-011
cy.get(rowSelector)
.first()
.find('[col-id="bestBidPrice"]')
.should(
'have.text',
addDecimalsFormatNumber(
settledMarketData.bestBidPrice,
settledMarket.decimalPlaces
)
);
// 6001-MARK-012
cy.get(rowSelector)
.first()
.find('[col-id="bestOfferPrice"]')
.should(
'have.text',
addDecimalsFormatNumber(
settledMarketData.bestOfferPrice,
settledMarket.decimalPlaces
)
);
// 6001-MARK-013
cy.get(rowSelector).first().find('[col-id="markPrice"]').should(
'have.text',
addDecimalsFormatNumber(
settledMarketData.markPrice,
settledMarket.decimalPlaces
)
);
// 6001-MARK-014
// 6001-MARK-015
// 6001-MARK-016
cy.get(rowSelector)
.first()
.find('[col-id="settlementDataOracleId"]')
.find('[data-testid="link"]')
.should(($el) => {
const href = $el.attr('href');
expect(href).to.match(
new RegExp(`/oracles/${product.dataSourceSpecForSettlementData.id}`)
);
})
.should(
'have.text',
addDecimalsFormatNumber(
// @ts-ignore cannot deep un-partial
specDataConnection.externalData.data.data[0].value,
settledMarket.decimalPlaces
)
);
// 6001-MARK-017
cy.get(rowSelector)
.first()
.find('[col-id="realisedPNL"]')
.should('have.text', '-');
// 6001-MARK-018
cy.get(rowSelector)
.first()
.find('[col-id="settlementAsset"]')
.should('have.text', product.settlementAsset.symbol);
// 6001-MARK-020
cy.get(rowSelector)
.first()
.find('[col-id="id"]')
.should('have.text', settledMarket.id);
});
// test market list for market in terminated state
it('renders a terminated market', () => {
cy.get(rowSelector)
.eq(1)
.find('[col-id="state"]')
.should('have.text', MarketStateMapping[terminatedMarket.state]);
// 6001-MARK-006
// 6001-MARK-007
cy.get(rowSelector)
.eq(1)
.find('[col-id="settlementDate"]')
.find('[data-testid="link"]')
.should('have.text', 'Expected in 4 days');
});
it('renders a terminated market which was expected to have settled', () => {
cy.get(rowSelector)
.eq(2)
.find('[col-id="settlementDate"]')
.should('have.class', 'text-danger')
.find('[data-testid="link"]')
.should('have.text', 'Expected 2 days ago');
});
it('renders terminated market which doesnt have settlement date metadata', () => {
cy.get(rowSelector)
.eq(3)
.find('[col-id="settlementDate"]')
.find('[data-testid="link"]')
.should('have.text', 'Unknown');
});
it('can open asset detail dialog', () => {
cy.mockGQL((req) => {
aliasGQLQuery(req, 'Asset', assetsResult);
});
cy.get(rowSelector)
.first()
.find('[col-id="settlementAsset"]')
.find('button')
.click();
// 6001-MARK-019
cy.get('[data-testid="dialog-title"]').should(
'have.text',
`Asset details - ${settlementAsset.symbol}`
);
});
});
@@ -101,7 +101,7 @@ describe('deposit actions', { tags: '@smoke' }, () => {
cy.mockTradingPage();
cy.mockSubscription();
cy.setVegaWallet();
cy.visit('/');
cy.visit('/#/markets/market-1');
cy.wait('@MarketsCandles');
cy.getByTestId('dialog-close').click();
});
@@ -112,7 +112,6 @@ describe('deposit actions', { tags: '@smoke' }, () => {
'be.visible'
);
cy.contains('[data-testid="deposit"]', 'Deposit to trade').click();
connectEthereumWallet('MetaMask');
cy.getByTestId('deposit-submit').should('be.visible');
});
});
+2 -1
View File
@@ -153,7 +153,7 @@ describe('home', { tags: '@regression' }, () => {
// the choose market overlay is no longer showing
cy.contains('Select a market to get started').should('not.exist');
cy.contains('Loading...').should('not.exist');
cy.url().should('eq', Cypress.config().baseUrl + '/#/markets/market-1');
cy.url().should('eq', Cypress.config().baseUrl + '/#/markets/market-0');
});
});
@@ -172,6 +172,7 @@ describe('home', { tags: '@regression' }, () => {
],
},
};
// @ts-ignore partial deep check failing
const data = marketsDataQuery(override);
cy.mockGQL((req) => {
aliasGQLQuery(req, 'MarketsData', data);
@@ -1,4 +1,5 @@
import { MarketTradingModeMapping } from '@vegaprotocol/types';
import { MarketState } from '@vegaprotocol/types';
const marketInfoBtn = 'Info';
const row = 'key-value-table-row';
@@ -12,7 +13,12 @@ describe('market info is displayed', { tags: '@smoke' }, () => {
});
before(() => {
cy.mockTradingPage();
cy.mockTradingPage(
MarketState.STATE_ACTIVE,
undefined,
undefined,
'COMPROMISED'
);
cy.mockSubscription();
cy.visit('/#/markets/market-0');
cy.wait('@Markets');
@@ -20,6 +26,11 @@ describe('market info is displayed', { tags: '@smoke' }, () => {
cy.wait('@MarketInfo');
});
it('show oracle banner', () => {
cy.getByTestId(marketTitle).contains('Oracle').click();
cy.getByTestId('oracle-status').should('contain.text', 'COMPROMISED');
});
it('current fees displayed', () => {
cy.getByTestId(marketTitle).contains('Current fees').click();
validateMarketDataRow(0, 'Maker Fee', '0.02%');
@@ -222,6 +222,7 @@ describe('markets table', { tags: '@smoke' }, () => {
],
},
};
// @ts-ignore partial deep check failing
const market = marketsQuery(override);
aliasGQLQuery(req, 'Market', market);
aliasGQLQuery(req, 'ProposalOfMarket', {
@@ -1,12 +1,12 @@
import { closeWelcomeDialog } from '../support/helpers';
describe('Settings page', { tags: '@smoke' }, () => {
beforeEach(() => {
cy.clearLocalStorage().then(() => {
cy.mockTradingPage();
cy.mockSubscription();
cy.visit('/');
cy.get('[role=dialog]').within(() => {
cy.getByTestId('dialog-close').click();
});
closeWelcomeDialog();
cy.get('[aria-label="cog icon"]').click();
});
});
@@ -1,17 +1,23 @@
import { checkSorting } from '@vegaprotocol/cypress';
describe('accounts', { tags: '@smoke' }, () => {
before(() => {
cy.clearAllLocalStorage();
beforeEach(() => {
cy.mockTradingPage();
cy.mockWeb3Provider();
cy.mockSubscription();
cy.setVegaWallet();
cy.visit('/#/markets/market-0');
cy.wait('@Assets');
});
it('renders accounts', () => {
// 7001-COLL-001
// 7001-COLL-002
// 7001-COLL-003
// 7001-COLL-004
// 7001-COLL-005
// 7001-COLL-006
// 7001-COLL-007
const tradingAccountRowId = '[row-id="t-0"]';
cy.getByTestId('Collateral').click();
@@ -24,24 +30,85 @@ describe('accounts', { tags: '@smoke' }, () => {
cy.getByTestId('tab-accounts')
.get(tradingAccountRowId)
.find('[col-id="accounts-actions"]')
.should('have.text', '');
.find('[col-id="used"]')
.should('have.text', '1.010.00%');
cy.getByTestId('tab-accounts')
.get(tradingAccountRowId)
.find('[col-id="accounts-actions"]')
.should('have.text', '');
.find('[col-id="available"]')
.should('have.text', '100,000.00');
cy.getByTestId('tab-accounts')
.get(tradingAccountRowId)
.find('[col-id="total"]')
.should('have.text', '100,001.01');
cy.getByTestId('tab-accounts')
.get(tradingAccountRowId)
.find('[col-id="accounts-actions"]')
.should('have.text', ' ');
cy.getByTestId('tab-accounts')
.get(tradingAccountRowId)
.find('[col-id="total"]')
.should('have.text', '100,001.01');
cy.getByTestId('tab-accounts')
.get('[col-id="accounts-actions"]')
.find('[data-testid="dropdown-menu"]')
.eq(1)
.click();
cy.getByTestId('deposit').should('be.visible');
cy.getByTestId('withdraw').should('be.visible');
cy.getByTestId('breakdown').should('be.visible');
cy.getByTestId('Collateral').click({ force: true });
});
it('should open asset details dialog when clicked on symbol', () => {
// 7001-COLL-008
cy.getByTestId('asset').contains('tEURO').click();
cy.get('[data-testid="dialog-content"]:visible').should('exist');
cy.get('[data-testid="dialog-close"]:visible').click();
cy.get('[data-testid$="_label"]').should('have.length', 16);
cy.get('[data-testid="dialog-close"]').click();
});
it('should open asset details dialog when clicked on symbol', () => {
// 7001-COLL-008
cy.getByTestId('asset').contains('tEURO').click();
cy.get('[data-testid$="_label"]').should('have.length', 16);
cy.get('[data-testid="dialog-close"]').click();
});
it('should open usage breakdown dialog when clicked on used', () => {
// 7001-COLL-009
cy.getByTestId('breakdown').contains('1.01').click();
const headers = ['Market', 'Account type', 'Balance'];
cy.getByTestId('usage-breakdown').within(($headers) => {
cy.wrap($headers)
.get('.ag-header-cell-text')
.each(($header, i) => {
cy.wrap($header).should('have.text', headers[i]);
});
});
cy.get('[data-testid="dialog-close"]').click();
});
it('sorting usage breakdown columns should work well', () => {
// 7001-COLL-010
cy.getByTestId('breakdown').contains('1.01').click();
cy.getByTestId('usage-breakdown')
.find('[col-id="type"]')
.eq(1)
.should('have.text', 'Margin');
cy.getByTestId('usage-breakdown')
.find('[col-id="type"]')
.eq(2)
.should('have.text', 'Margin');
cy.getByTestId('usage-breakdown')
.find('[col-id="type"]')
.eq(3)
.should('have.text', 'General');
cy.get('[data-testid="dialog-close"]').click();
});
describe('sorting by ag-grid columns should work well', () => {
@@ -88,5 +88,18 @@ describe('deal ticker order validation', { tags: '@smoke' }, () => {
'Size cannot be lower than 1'
);
});
it('must have total margin available', () => {
// 7001-COLL-011
cy.getByTestId('tab-ticket')
.find('.text-xs')
.eq(5)
.within(() => {
cy.get('[data-state="closed"]').should(
'have.text',
'Total margin available'
);
cy.get('.text-neutral-500').should('have.text', '~100,000.01 tDAI');
});
});
});
});
@@ -455,7 +455,7 @@ describe('amend and cancel order', { tags: '@smoke' }, () => {
});
});
it('must be warned (pre-submit) if the input price has too many digits after the decimal place for the market', () => {
// 7003-MORD-016
// 7003-MORD-013
updateOrder({
id: orderId,
status: Schema.OrderStatus.STATUS_ACTIVE,
+5
View File
@@ -9,3 +9,8 @@ export const selectAsset = (assetIndex: number) => {
// eslint-disable-next-line
cy.wait(100);
};
export const closeWelcomeDialog = () => {
cy.getByTestId('select-market-list').should('exist');
cy.getByTestId('dialog-close').click();
};
@@ -26,6 +26,7 @@ export function updateOrder(
override?: PartialDeep<OrderUpdateFieldsFragment>
): void {
const update: OrdersUpdateSubscription = orderUpdateSubscription({
// @ts-ignore partial deep check failing
orders: [override],
});
if (!sendOrderUpdate) {
+38 -29
View File
@@ -1,6 +1,7 @@
import { aliasGQLQuery } from '@vegaprotocol/cypress';
import * as Schema from '@vegaprotocol/types';
import type { CyHttpMessages } from 'cypress/types/net-stubbing';
import type { Provider, Status } from '@vegaprotocol/oracles';
import {
accountsQuery,
assetQuery,
@@ -45,7 +46,9 @@ const marketDataOverride = (
{
node: {
data: {
// @ts-ignore conflict between incoming and outgoing types
trigger: data.trigger,
// @ts-ignore same as above
marketTradingMode: data.tradingMode,
marketState: data.state,
},
@@ -62,6 +65,7 @@ const marketsDataOverride = (
edges: [
{
node: {
// @ts-ignore conflict between incoming and outgoing types
tradingMode: data.tradingMode,
state: data.state,
},
@@ -155,7 +159,6 @@ const mockTradingPage = (
aliasGQLQuery(req, 'ProposalsList', proposalListQuery());
aliasGQLQuery(req, 'Deposits', depositsQuery());
};
declare global {
// eslint-disable-next-line @typescript-eslint/no-namespace
namespace Cypress {
@@ -164,50 +167,56 @@ declare global {
mockTradingPage(
state?: Schema.MarketState,
tradingMode?: Schema.MarketTradingMode,
trigger?: Schema.AuctionTrigger
trigger?: Schema.AuctionTrigger,
oracleStatus?: Status
): void;
}
}
}
export const addMockTradingPage = () => {
Cypress.Commands.add(
'mockTradingPage',
(state = Schema.MarketState.STATE_ACTIVE, tradingMode, trigger) => {
(
state = Schema.MarketState.STATE_ACTIVE,
tradingMode,
trigger,
oracleStatus
) => {
cy.mockGQL((req) => {
mockTradingPage(req, state, tradingMode, trigger);
});
const oracle: Provider = {
name: 'Another oracle',
url: 'https://zombo.com',
description_markdown:
'Some markdown describing the oracle provider.\n\nTwitter: @FacesPics2\n',
oracle: {
status: oracleStatus || 'GOOD',
status_reason: '',
first_verified: '2022-01-01T00:00:00.000Z',
last_verified: '2022-12-31T00:00:00.000Z',
type: 'public_key',
public_key: ORACLE_PUBKEY,
},
proofs: [
{
format: 'signed_message',
available: true,
type: 'public_key',
public_key: ORACLE_PUBKEY,
message: 'SOMEHEX',
},
],
github_link: `https://github.com/vegaprotocol/well-known/blob/main/oracle-providers/public_key-${ORACLE_PUBKEY}.toml`,
};
// Prevent request to github, return some dummy content
cy.intercept(
'GET',
/^https:\/\/raw.githubusercontent.com\/vegaprotocol\/well-known/,
{
body: [
{
name: 'Another oracle',
url: 'https://zombo.com',
description_markdown:
'Some markdown describing the oracle provider.\n\nTwitter: @FacesPics2\n',
oracle: {
status: 'GOOD',
status_reason: '',
first_verified: '2022-01-01T00:00:00.000Z',
last_verified: '2022-12-31T00:00:00.000Z',
type: 'public_key',
public_key: ORACLE_PUBKEY,
},
proofs: [
{
format: 'signed_message',
available: true,
type: 'public_key',
public_key: ORACLE_PUBKEY,
message: 'SOMEHEX',
},
],
github_link: `https://github.com/vegaprotocol/well-known/blob/main/oracle-providers/public_key-${ORACLE_PUBKEY}.toml`,
},
],
body: [oracle],
}
);
}
+1 -1
View File
@@ -7,7 +7,7 @@ NX_VEGA_ENV=CUSTOM
NX_VEGA_EXPLORER_URL=https://stagnet3.explorer.vega.xyz
NX_VEGA_NETWORKS={\"TESTNET\":\"https://console.fairground.wtf\",\"STAGNET1\":\"https://stagnet1.console.vega.xyz\",\"STAGNET3\":\"https://stagnet3.console.vega.xyz\"}
NX_VEGA_TOKEN_URL=https://token.fairground.wtf
NX_VEGA_URL=http://localhost:3028/query
NX_VEGA_URL=http://localhost:3008/graphql
NX_VEGA_WALLET_URL=http://localhost:1789
NX_VEGA_DOCS_URL=https://docs.vega.xyz/testnet
NX_VEGA_REPO_URL=https://github.com/vegaprotocol/vega/releases
@@ -350,7 +350,10 @@ export const TradePanels = ({
return (
<div className="h-full grid grid-rows-[min-content_1fr_min-content]">
<TradeMarketHeader market={market} onSelect={onSelect} />
<div>
<TradeMarketHeader market={market} onSelect={onSelect} />
<OracleBanner marketId={market?.id || ''} />
</div>
<div className="h-full">
<AutoSizer>
{({ width, height }) => (
@@ -0,0 +1,335 @@
import { act, render, screen, within } from '@testing-library/react';
import { Closed } from './closed';
import { MarketStateMapping } from '@vegaprotocol/types';
import { PositionStatus } from '@vegaprotocol/types';
import { MarketState } from '@vegaprotocol/types';
import { subDays } from 'date-fns';
import type { MockedResponse } from '@apollo/client/testing';
import { MockedProvider } from '@apollo/client/testing';
import type { OracleSpecDataConnectionQuery } from '@vegaprotocol/oracles';
import { OracleSpecDataConnectionDocument } from '@vegaprotocol/oracles';
import type { VegaWalletContextShape } from '@vegaprotocol/wallet';
import { VegaWalletContext } from '@vegaprotocol/wallet';
import type {
PositionsQuery,
PositionFieldsFragment,
} from '@vegaprotocol/positions';
import { PositionsDocument } from '@vegaprotocol/positions';
import { addDecimalsFormatNumber } from '@vegaprotocol/utils';
import type { MarketsDataQuery, MarketsQuery } from '@vegaprotocol/market-list';
import { MarketsDataDocument } from '@vegaprotocol/market-list';
import { MarketsDocument } from '@vegaprotocol/market-list';
import {
createMarketFragment,
marketsQuery,
marketsDataQuery,
createMarketsDataFragment,
} from '@vegaprotocol/mock';
describe('Closed', () => {
let originalNow: typeof Date.now;
const mockNowTimestamp = 1672531200000;
const settlementDateMetaDate = subDays(
new Date(mockNowTimestamp),
3
).toISOString();
const settlementDateTag = `settlement-expiry-date:${settlementDateMetaDate}`;
const pubKey = 'pubKey';
const marketId = 'market-0';
const settlementDataProperty = 'spec-binding';
const settlementDataId = 'settlement-data-oracle-id';
const market = createMarketFragment({
id: marketId,
state: MarketState.STATE_SETTLED,
tradableInstrument: {
instrument: {
metadata: {
tags: [settlementDateTag],
},
product: {
dataSourceSpecForSettlementData: {
id: settlementDataId,
},
dataSourceSpecBinding: {
settlementDataProperty,
},
},
},
},
});
const marketsMock: MockedResponse<MarketsQuery> = {
request: {
query: MarketsDocument,
},
result: {
data: marketsQuery({
marketsConnection: {
edges: [
{
node: market,
},
],
},
}),
},
};
const marketsData = createMarketsDataFragment({
__typename: 'MarketData',
market: {
__typename: 'Market',
id: marketId,
},
bestBidPrice: '1000',
bestOfferPrice: '2000',
markPrice: '1500',
});
const marketsDataMock: MockedResponse<MarketsDataQuery> = {
request: {
query: MarketsDataDocument,
},
result: {
data: marketsDataQuery({
marketsConnection: {
edges: [
{
node: {
data: marketsData,
},
},
],
},
}),
},
};
// Create mock oracle data
const property = {
__typename: 'Property' as const,
name: settlementDataProperty,
value: '12345',
};
const oracleDataMock: MockedResponse<OracleSpecDataConnectionQuery> = {
request: {
query: OracleSpecDataConnectionDocument,
variables: {
oracleSpecId: settlementDataId,
},
},
result: {
data: {
oracleSpec: {
dataConnection: {
edges: [
{
node: {
externalData: {
data: {
data: [property],
},
},
},
},
],
},
},
},
},
};
// Create mock position
const createPosition = (): PositionFieldsFragment => {
return {
__typename: 'Position' as const,
realisedPNL: '1000',
unrealisedPNL: '2000',
openVolume: '3000',
averageEntryPrice: '100',
updatedAt: new Date().toISOString(),
positionStatus: PositionStatus.POSITION_STATUS_UNSPECIFIED,
lossSocializationAmount: '1000',
market: {
__typename: 'Market',
id: marketId,
},
};
};
const position = createPosition();
const positionsMock: MockedResponse<PositionsQuery> = {
request: {
query: PositionsDocument,
variables: {
partyId: pubKey,
},
},
result: {
data: {
party: {
__typename: 'Party',
id: pubKey,
positionsConnection: {
__typename: 'PositionConnection',
edges: [{ __typename: 'PositionEdge', node: position }],
},
},
},
},
};
beforeAll(() => {
originalNow = Date.now;
Date.now = jest.fn().mockReturnValue(mockNowTimestamp);
});
afterAll(() => {
Date.now = originalNow;
});
it('renders correctly formatted and filtered rows', async () => {
await act(async () => {
render(
<MockedProvider
mocks={[marketsMock, marketsDataMock, positionsMock, oracleDataMock]}
>
<VegaWalletContext.Provider
value={{ pubKey } as VegaWalletContextShape}
>
<Closed />
</VegaWalletContext.Provider>
</MockedProvider>
);
});
// screen.debug(document, Infinity);
const headers = screen.getAllByRole('columnheader');
const expectedHeaders = [
'Market',
'Description',
'Status',
'Settlement date',
'Best bid',
'Best offer',
'Mark price',
'Settlement price',
'Realised PNL',
'Settlement asset',
'Market ID',
];
expect(headers).toHaveLength(expectedHeaders.length);
expect(headers.map((h) => h.textContent?.trim())).toEqual(expectedHeaders);
const cells = screen.getAllByRole('gridcell');
const expectedValues = [
market.tradableInstrument.instrument.code,
market.tradableInstrument.instrument.name,
MarketStateMapping[market.state],
'3 days ago',
/* eslint-disable @typescript-eslint/no-non-null-assertion */
addDecimalsFormatNumber(marketsData.bestBidPrice, market.decimalPlaces),
addDecimalsFormatNumber(
marketsData!.bestOfferPrice,
market.decimalPlaces
),
addDecimalsFormatNumber(marketsData!.markPrice, market.decimalPlaces),
/* eslint-enable @typescript-eslint/no-non-null-assertion */
addDecimalsFormatNumber(property.value, market.decimalPlaces),
addDecimalsFormatNumber(position.realisedPNL, market.decimalPlaces),
market.tradableInstrument.instrument.product.settlementAsset.symbol,
market.id,
];
cells.forEach((cell, i) => {
expect(cell).toHaveTextContent(expectedValues[i]);
});
});
it('only renders settled and terminated markets', async () => {
const mixedMarkets = [
{
// inlclude as settled
__typename: 'MarketEdge' as const,
node: createMarketFragment({
id: 'include-0',
state: MarketState.STATE_SETTLED,
}),
},
{
// omit this market
__typename: 'MarketEdge' as const,
node: createMarketFragment({
id: 'discard-0',
state: MarketState.STATE_SUSPENDED,
}),
},
{
// include as terminated
__typename: 'MarketEdge' as const,
node: createMarketFragment({
id: 'include-1',
state: MarketState.STATE_TRADING_TERMINATED,
}),
},
{
// omit this market
__typename: 'MarketEdge' as const,
node: createMarketFragment({
id: 'discard-1',
state: MarketState.STATE_ACTIVE,
}),
},
];
const mixedMarketsMock: MockedResponse<MarketsQuery> = {
request: {
query: MarketsDocument,
},
result: {
data: {
marketsConnection: {
__typename: 'MarketConnection',
edges: mixedMarkets,
},
},
},
};
await act(async () => {
render(
<MockedProvider
mocks={[
mixedMarketsMock,
marketsDataMock,
positionsMock,
oracleDataMock,
]}
>
<VegaWalletContext.Provider
value={{ pubKey } as VegaWalletContextShape}
>
<Closed />
</VegaWalletContext.Provider>
</MockedProvider>
);
});
// check that the number of rows in datagrid is 2
const container = within(
document.querySelector('.ag-center-cols-container') as HTMLElement
);
const expectedRows = mixedMarkets.filter((m) => {
return [
MarketState.STATE_SETTLED,
MarketState.STATE_TRADING_TERMINATED,
].includes(m.node.state);
});
// check rows length is correct
const rows = container.getAllByRole('row');
expect(rows).toHaveLength(expectedRows.length);
// check that only included ids are shown
const cells = screen
.getAllByRole('gridcell')
.filter((cell) => cell.getAttribute('col-id') === 'id')
.map((cell) => cell.textContent?.trim());
expect(cells).toEqual(expectedRows.map((m) => m.node.id));
});
});
@@ -0,0 +1,285 @@
import compact from 'lodash/compact';
import { isAfter } from 'date-fns';
import type {
VegaICellRendererParams,
VegaValueFormatterParams,
} from '@vegaprotocol/datagrid';
import { AgGridDynamic as AgGrid } from '@vegaprotocol/datagrid';
import { useMemo } from 'react';
import { t } from '@vegaprotocol/i18n';
import { MarketState, MarketStateMapping } from '@vegaprotocol/types';
import {
addDecimalsFormatNumber,
getMarketExpiryDate,
} from '@vegaprotocol/utils';
import { usePositionsQuery } from '@vegaprotocol/positions';
import type { MarketMaybeWithData } from '@vegaprotocol/market-list';
import { closedMarketsWithDataProvider } from '@vegaprotocol/market-list';
import { useVegaWallet } from '@vegaprotocol/wallet';
import { useAssetDetailsDialogStore } from '@vegaprotocol/assets';
import type { ColDef } from 'ag-grid-community';
import { SettlementDateCell } from './settlement-date-cell';
import { SettlementPriceCell } from './settlement-price-cell';
import { useDataProvider } from '@vegaprotocol/react-helpers';
import { AsyncRenderer } from '@vegaprotocol/ui-toolkit';
type SettlementAsset =
MarketMaybeWithData['tradableInstrument']['instrument']['product']['settlementAsset'];
interface Row {
id: string;
code: string;
name: string;
decimalPlaces: number;
state: MarketState;
metadata: string[];
closeTimestamp: string | null;
bestBidPrice: string | undefined;
bestOfferPrice: string | undefined;
markPrice: string | undefined;
settlementDataOracleId: string;
settlementDataSpecBinding: string;
tradingTerminationOracleId: string;
settlementAsset: SettlementAsset;
realisedPNL: string | undefined;
}
export const Closed = () => {
const { pubKey } = useVegaWallet();
const {
data: marketData,
loading,
error,
reload,
} = useDataProvider({
dataProvider: closedMarketsWithDataProvider,
variables: undefined,
});
const { data: positionData } = usePositionsQuery({
variables: {
partyId: pubKey || '',
},
skip: !pubKey,
});
// find a position for each market and add the realised pnl to
// a normalized object
const rowData = compact(marketData).map((market) => {
const position = positionData?.party?.positionsConnection?.edges?.find(
(edge) => {
return edge.node.market.id === market.id;
}
);
const row: Row = {
id: market.id,
code: market.tradableInstrument.instrument.code,
name: market.tradableInstrument.instrument.name,
decimalPlaces: market.decimalPlaces,
state: market.state,
metadata: market.tradableInstrument.instrument.metadata.tags ?? [],
closeTimestamp: market.marketTimestamps.close,
bestBidPrice: market.data?.bestBidPrice,
bestOfferPrice: market.data?.bestOfferPrice,
markPrice: market.data?.markPrice,
settlementDataOracleId:
market.tradableInstrument.instrument.product
.dataSourceSpecForSettlementData.id,
settlementDataSpecBinding:
market.tradableInstrument.instrument.product.dataSourceSpecBinding
.settlementDataProperty,
tradingTerminationOracleId:
market.tradableInstrument.instrument.product
.dataSourceSpecForTradingTermination.id,
settlementAsset:
market.tradableInstrument.instrument.product.settlementAsset,
realisedPNL: position?.node.realisedPNL,
};
return row;
});
return (
<div className="h-full relative">
<ClosedMarketsDataGrid rowData={rowData} />
<div className="pointer-events-none absolute inset-0">
<AsyncRenderer
loading={loading}
error={error}
data={marketData}
noDataMessage={t('No markets')}
reload={reload}
/>
</div>
</div>
);
};
const ClosedMarketsDataGrid = ({ rowData }: { rowData: Row[] }) => {
const openAssetDialog = useAssetDetailsDialogStore((store) => store.open);
const colDefs = useMemo(() => {
const cols: ColDef[] = [
{
headerName: t('Market'),
field: 'code',
},
{
headerName: t('Description'),
field: 'name',
},
{
headerName: t('Status'),
field: 'state',
valueFormatter: ({ value }: VegaValueFormatterParams<Row, 'state'>) => {
if (!value) return '-';
return MarketStateMapping[value];
},
},
{
headerName: t('Settlement date'),
colId: 'settlementDate', // colId needed if no field property provided otherwise column order is ruined in tests
valueGetter: ({ data }: { data: Row }) => {
return getMarketExpiryDate(data.metadata);
},
cellRenderer: ({ value, data }: { value: Date | null; data: Row }) => {
return (
<SettlementDateCell
oracleSpecId={data.tradingTerminationOracleId}
metaDate={value}
marketState={data.state}
closeTimestamp={data.closeTimestamp}
/>
);
},
cellClassRules: {
'text-danger': ({
value,
data,
}: {
value: Date | null;
data: Row;
}) => {
const date = data.closeTimestamp
? new Date(data.closeTimestamp)
: value;
if (!date) return false;
if (
// expiry has passed and market is not yet settled
isAfter(new Date(), date) &&
data.state !== MarketState.STATE_SETTLED
) {
return true;
}
return false;
},
},
},
{
headerName: t('Best bid'),
field: 'bestBidPrice',
type: 'numericColumn',
cellClass: 'font-mono ag-right-aligned-cell',
valueFormatter: ({
value,
data,
}: VegaValueFormatterParams<Row, 'bestBidPrice'>) => {
if (!value || !data) return '-';
return addDecimalsFormatNumber(value, data.decimalPlaces);
},
},
{
headerName: t('Best offer'),
field: 'bestOfferPrice',
cellClass: 'font-mono ag-right-aligned-cell',
type: 'numericColumn',
valueFormatter: ({
value,
data,
}: VegaValueFormatterParams<Row, 'bestOfferPrice'>) => {
if (!value || !data) return '-';
return addDecimalsFormatNumber(value, data.decimalPlaces);
},
},
{
headerName: t('Mark price'),
field: 'markPrice',
cellClass: 'font-mono ag-right-aligned-cell',
type: 'numericColumn',
valueFormatter: ({
value,
data,
}: VegaValueFormatterParams<Row, 'markPrice'>) => {
if (!value || !data) return '-';
return addDecimalsFormatNumber(value, data.decimalPlaces);
},
},
{
headerName: t('Settlement price'),
type: 'numericColumn',
field: 'settlementDataOracleId',
// 'tradableInstrument.instrument.product.dataSourceSpecForSettlementData.id',
cellRenderer: ({
value,
data,
}: VegaICellRendererParams<Row, 'settlementDataOracleId'>) => (
<SettlementPriceCell
oracleSpecId={value}
decimalPlaces={data?.decimalPlaces ?? 0}
settlementDataSpecBinding={data?.settlementDataSpecBinding}
/>
),
},
{
headerName: t('Realised PNL'),
field: 'realisedPNL',
cellClass: 'font-mono ag-right-aligned-cell',
type: 'numericColumn',
valueFormatter: ({
value,
data,
}: VegaValueFormatterParams<Row, 'realisedPNL'>) => {
if (!value || !data) return '-';
return addDecimalsFormatNumber(value, data.decimalPlaces);
},
},
{
headerName: t('Settlement asset'),
field: 'settlementAsset',
cellRenderer: ({
value,
data,
}: VegaValueFormatterParams<Row, 'settlementAsset'>) => (
<button
className="underline"
onClick={() => {
if (!value) return;
openAssetDialog(value.id);
}}
>
{value ? value.symbol : '-'}
</button>
),
},
{
headerName: t('Market ID'),
field: 'id',
},
];
return cols;
}, [openAssetDialog]);
return (
<AgGrid
style={{ width: '100%', height: '100%' }}
rowData={rowData}
columnDefs={colDefs}
getRowId={({ data }) => data.id}
defaultColDef={{
flex: 1,
resizable: true,
}}
overlayNoRowsTemplate="No data"
/>
);
};
@@ -5,6 +5,7 @@ import { LocalStoragePersistTabs as Tabs, Tab } from '@vegaprotocol/ui-toolkit';
import { Markets } from './markets';
import { Proposed } from './proposed';
import { usePageTitleStore } from '../../stores';
import { Closed } from './closed';
export const MarketsPage = () => {
const { updateTitle } = usePageTitleStore((store) => ({
@@ -21,6 +22,9 @@ export const MarketsPage = () => {
<Tab id="proposed-markets" name={t('Proposed markets')}>
<Proposed />
</Tab>
<Tab id="closed-markets" name={t('Closed markets')}>
<Closed />
</Tab>
</Tabs>
);
};
@@ -0,0 +1,105 @@
import { render, screen } from '@testing-library/react';
import { MarketState } from '@vegaprotocol/types';
import { addDays, subDays } from 'date-fns';
import type { SettlementDataCellProps } from './settlement-date-cell';
import { SettlementDateCell } from './settlement-date-cell';
describe('SettlementDateCell', () => {
let originalNow: typeof Date.now;
const mockNowTimestamp = 1672531200000;
const createProps = (): SettlementDataCellProps => {
return {
oracleSpecId: 'oracle-spec-id',
metaDate: null,
closeTimestamp: null,
marketState: MarketState.STATE_SETTLED,
};
};
beforeAll(() => {
originalNow = Date.now;
Date.now = jest.fn().mockReturnValue(mockNowTimestamp);
});
afterAll(() => {
Date.now = originalNow;
});
it('renders unknown if date cannot be determined', () => {
const props = createProps();
render(<SettlementDateCell {...props} />);
const link = screen.getByRole('link');
expect(link).toHaveTextContent('Unknown');
expect(link).toHaveAttribute(
'href',
expect.stringContaining(`/oracles/${props.oracleSpecId}`)
);
});
it('renders using close timestamp if provided', () => {
const daysAgo = 3;
const props = createProps();
props.closeTimestamp = subDays(
new Date(mockNowTimestamp),
daysAgo
).toISOString();
render(<SettlementDateCell {...props} />);
const link = screen.getByRole('link');
expect(link).toHaveTextContent(`${daysAgo} days ago`);
expect(link).toHaveAttribute(
'href',
expect.stringContaining(`/oracles/${props.oracleSpecId}`)
);
});
it('renders using meta tag date if no close timestamp provided', () => {
const daysAgo = 4;
const props = createProps();
props.metaDate = subDays(new Date(mockNowTimestamp), daysAgo);
render(<SettlementDateCell {...props} />);
const link = screen.getByRole('link');
expect(link).toHaveTextContent(`${daysAgo} days ago`);
expect(link).toHaveAttribute(
'href',
expect.stringContaining(`/oracles/${props.oracleSpecId}`)
);
});
it('renders past expected settlement date', () => {
const daysAgo = 3;
const props = createProps();
props.metaDate = subDays(new Date(mockNowTimestamp), daysAgo);
props.marketState = MarketState.STATE_TRADING_TERMINATED;
render(<SettlementDateCell {...props} />);
const link = screen.getByRole('link');
expect(link).toHaveTextContent(`Expected ${daysAgo} days ago`);
expect(link).toHaveAttribute(
'href',
expect.stringContaining(`/oracles/${props.oracleSpecId}`)
);
});
it('renders future expected settlement date', () => {
const daysAgo = 3;
const props = createProps();
props.metaDate = addDays(new Date(mockNowTimestamp), daysAgo);
props.marketState = MarketState.STATE_TRADING_TERMINATED;
render(<SettlementDateCell {...props} />);
const link = screen.getByRole('link');
expect(link).toHaveTextContent(`Expected in ${daysAgo} days`);
expect(link).toHaveAttribute(
'href',
expect.stringContaining(`/oracles/${props.oracleSpecId}`)
);
});
});
@@ -0,0 +1,55 @@
import { DApp, EXPLORER_ORACLE, useLinks } from '@vegaprotocol/environment';
import { t } from '@vegaprotocol/i18n';
import { MarketState } from '@vegaprotocol/types';
import { Link } from '@vegaprotocol/ui-toolkit';
import { getDateTimeFormat } from '@vegaprotocol/utils';
import { formatDistanceToNowStrict, isAfter } from 'date-fns';
export interface SettlementDataCellProps {
oracleSpecId: string;
metaDate: Date | null;
closeTimestamp: string | null;
marketState: MarketState;
}
export const SettlementDateCell = ({
oracleSpecId,
metaDate,
closeTimestamp,
marketState,
}: SettlementDataCellProps) => {
const linkCreator = useLinks(DApp.Explorer);
const date = closeTimestamp ? new Date(closeTimestamp) : metaDate;
let text = '';
if (!date) {
text = t('Unknown');
} else {
// pass Date.now() to date constructor for easier mocking
const expiryHasPassed = isAfter(new Date(Date.now()), date);
const distance = formatDistanceToNowStrict(date); // X days/mins ago
if (expiryHasPassed) {
if (marketState !== MarketState.STATE_SETTLED) {
text = t('Expected %s ago', distance);
} else {
text = t('%s ago', distance);
}
} else {
text = t('Expected in %s', distance);
}
}
return (
<Link
href={linkCreator(EXPLORER_ORACLE.replace(':id', oracleSpecId))}
className="underline"
target="_blank"
title={
date ? getDateTimeFormat().format(date) : t('Unknown settlement date')
}
>
{text}
</Link>
);
};
@@ -0,0 +1,113 @@
import { render, screen } from '@testing-library/react';
import type { Property } from '@vegaprotocol/types';
import type { MockedResponse } from '@apollo/client/testing';
import { MockedProvider } from '@apollo/client/testing';
import type { OracleSpecDataConnectionQuery } from '@vegaprotocol/oracles';
import { OracleSpecDataConnectionDocument } from '@vegaprotocol/oracles';
import type { SettlementPriceCellProps } from './settlement-price-cell';
import { SettlementPriceCell } from './settlement-price-cell';
describe('SettlementPriceCell', () => {
const createMock = (
id: string,
property: Property
): MockedResponse<OracleSpecDataConnectionQuery> => {
return {
request: {
query: OracleSpecDataConnectionDocument,
variables: {
oracleSpecId: id,
},
},
result: {
data: {
oracleSpec: {
dataConnection: {
edges: [
{
node: {
externalData: {
data: {
data: [property],
},
},
},
},
],
},
},
},
},
};
};
const createProps = (): SettlementPriceCellProps => {
return {
oracleSpecId: 'oracle-spec-id',
decimalPlaces: 2,
settlementDataSpecBinding: 'settlement-data-spec-binding',
};
};
it('renders fetches and renders the settlment data value', async () => {
const props = createProps();
const property = {
__typename: 'Property' as const,
name: props.settlementDataSpecBinding as string,
value: '1234',
};
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const mock = createMock(props.oracleSpecId!, property);
render(
<MockedProvider mocks={[mock]}>
<SettlementPriceCell {...props} />
</MockedProvider>
);
expect(screen.getByText('-')).toBeInTheDocument();
const link = await screen.findByRole('link');
expect(link).toHaveTextContent('12.34');
expect(link).toHaveAttribute(
'href',
expect.stringContaining(`/oracles/${props.oracleSpecId}`)
);
});
it('renders "-" if no spec value is found', async () => {
const props = createProps();
const property = {
__typename: 'Property' as const,
name: 'no matching spec binding',
value: '1234',
};
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const mock = createMock(props.oracleSpecId!, property);
render(
<MockedProvider mocks={[mock]}>
<SettlementPriceCell {...props} />
</MockedProvider>
);
expect(screen.getByText('-')).toBeInTheDocument();
const link = await screen.findByRole('link');
expect(link).toHaveTextContent('-');
expect(link).toHaveAttribute(
'href',
expect.stringContaining(`/oracles/${props.oracleSpecId}`)
);
});
it('renders "-" with no link if oracle spec id is not provided', () => {
const props = createProps();
props.oracleSpecId = undefined;
render(
<MockedProvider mocks={[]}>
<SettlementPriceCell {...props} />
</MockedProvider>
);
expect(screen.getByText('-')).toBeInTheDocument();
expect(screen.queryByRole('link')).not.toBeInTheDocument();
});
});
@@ -0,0 +1,39 @@
import { DApp, EXPLORER_ORACLE, useLinks } from '@vegaprotocol/environment';
import { t } from '@vegaprotocol/i18n';
import { useOracleSpecBindingData } from '@vegaprotocol/oracles';
import { Link } from '@vegaprotocol/ui-toolkit';
import { addDecimalsFormatNumber } from '@vegaprotocol/utils';
export interface SettlementPriceCellProps {
oracleSpecId: string | undefined;
decimalPlaces: number;
settlementDataSpecBinding: string | undefined;
}
export const SettlementPriceCell = ({
oracleSpecId,
decimalPlaces,
settlementDataSpecBinding,
}: SettlementPriceCellProps) => {
const linkCreator = useLinks(DApp.Explorer);
const { property, loading } = useOracleSpecBindingData(
oracleSpecId,
settlementDataSpecBinding
);
if (!oracleSpecId || loading) {
return <span>-</span>;
}
return (
<Link
href={linkCreator(EXPLORER_ORACLE.replace(':id', oracleSpecId))}
className="underline font-mono"
target="_blank"
>
{property
? addDecimalsFormatNumber(property.value, decimalPlaces)
: t('-')}
</Link>
);
};
@@ -26,7 +26,8 @@ export const OracleBanner = ({ marketId }: { marketId: string }) => {
return (
<NotificationBanner intent={Intent.Danger}>
<div>
Oracle status for this market is {oracle.status}.{' '}
Oracle status for this market is{' '}
<span data-testId="oracle-status">{oracle.status}</span>.{' '}
{oracleStatuses[oracle.status]}
</div>
{oracle.status_reason ? (
@@ -39,7 +39,17 @@ const MARKET_A: PartialMarket = {
symbol: 'ABC',
},
dataSourceSpecForTradingTermination: {
id: '',
__typename: 'DataSourceSpec',
id: 'oracleId',
},
dataSourceSpecForSettlementData: {
__typename: 'DataSourceSpec',
id: 'oracleId',
},
dataSourceSpecBinding: {
__typename: 'DataSourceSpecToFutureBinding',
tradingTerminationProperty: 'trading-termination-property',
settlementDataProperty: 'settlement-data-property',
},
},
metadata: {
@@ -115,7 +125,17 @@ const MARKET_B: PartialMarket = {
symbol: 'XYZ',
},
dataSourceSpecForTradingTermination: {
id: '',
__typename: 'DataSourceSpec',
id: 'oracleId',
},
dataSourceSpecForSettlementData: {
__typename: 'DataSourceSpec',
id: 'oracleId',
},
dataSourceSpecBinding: {
__typename: 'DataSourceSpecToFutureBinding',
tradingTerminationProperty: 'trading-termination-property',
settlementDataProperty: 'settlement-data-property',
},
},
metadata: {
@@ -41,7 +41,17 @@ const MARKET_A: PartialMarket = {
symbol: 'ABC',
},
dataSourceSpecForTradingTermination: {
id: '',
__typename: 'DataSourceSpec',
id: 'oracleId',
},
dataSourceSpecForSettlementData: {
__typename: 'DataSourceSpec',
id: 'oracleId',
},
dataSourceSpecBinding: {
__typename: 'DataSourceSpecToFutureBinding',
tradingTerminationProperty: 'trading-termination-property',
settlementDataProperty: 'settlement-data-property',
},
},
metadata: {
@@ -117,7 +127,17 @@ const MARKET_B: PartialMarket = {
symbol: 'XYZ',
},
dataSourceSpecForTradingTermination: {
id: '',
__typename: 'DataSourceSpec',
id: 'oracleId',
},
dataSourceSpecForSettlementData: {
__typename: 'DataSourceSpec',
id: 'oracleId',
},
dataSourceSpecBinding: {
__typename: 'DataSourceSpecToFutureBinding',
tradingTerminationProperty: 'trading-termination-property',
settlementDataProperty: 'settlement-data-property',
},
},
metadata: {
+5 -1
View File
@@ -299,6 +299,7 @@ export const AccountTable = forwardRef<AgGridReact, AccountTableProps>(
<DropdownMenuTrigger
iconName="more"
className="hover:bg-vega-light-200 dark:hover:bg-vega-dark-200 p-0.5 focus:rounded-full hover:rounded-full"
data-testid="dropdown-menu"
></DropdownMenuTrigger>
}
>
@@ -359,7 +360,10 @@ export const AccountTable = forwardRef<AgGridReact, AccountTableProps>(
}
</AgGrid>
<Dialog size="medium" open={openBreakdown} onChange={setOpenBreakdown}>
<div className="h-[35vh] w-full m-auto flex flex-col">
<div
className="h-[35vh] w-full m-auto flex flex-col"
data-testid="usage-breakdown"
>
<h1 className="text-xl mb-4">
{row?.asset?.symbol} {t('usage breakdown')}
</h1>
+1
View File
@@ -17,6 +17,7 @@ export * from '../market-list/src/lib/market-data.mock';
export * from '../market-list/src/lib/markets-candles.mock';
export * from '../market-list/src/lib/markets-data.mock';
export * from '../market-list/src/lib/markets.mock';
export * from '../oracles/src/lib/oracle-spec-data-connection.mock';
export * from '../orders/src/lib/components/order-data-provider/orders.mock';
export * from '../positions/src/lib/positions.mock';
export * from '../react-helpers/src/hooks/network-params.mock';
+4 -1
View File
@@ -1 +1,4 @@
export const ASSET_ID_FOR_MARKET = 'fUSDC';
export const ASSET_ID_FOR_MARKET =
'816af99af60d684502a40824758f6b5377e6af48e50a9ee8ef478ecb879ea8bc';
export const ASSET_SYMBOL = 'fUSDC';
@@ -4,7 +4,7 @@ import { createLog } from './logging';
import type { ProposalSubmissionBody } from '@vegaprotocol/wallet';
import { getProposal } from './get-proposal';
import { sendVegaTx } from './wallet-client';
import { ASSET_ID_FOR_MARKET } from './contants';
import { ASSET_ID_FOR_MARKET, ASSET_SYMBOL } from './contants';
const log = createLog('propose-market');
@@ -43,7 +43,7 @@ function createNewMarketProposal(): ProposalSubmissionBody {
code: 'TEST.24h',
future: {
settlementAsset: ASSET_ID_FOR_MARKET,
quoteName: ASSET_ID_FOR_MARKET,
quoteName: ASSET_SYMBOL,
dataSourceSpecForSettlementData: {
external: {
oracle: {
+1 -1
View File
@@ -66,7 +66,7 @@ export function addGetAssets() {
cy.request({
method: 'POST',
url: 'http://localhost:3028/query',
url: 'http://localhost:3008/graphql',
body: {
query: print(query),
},
@@ -24,7 +24,7 @@ export function addGetNetworkParameters() {
}`;
cy.request({
method: 'POST',
url: `http://localhost:3028/query`,
url: `http://localhost:3008/graphql`,
body: {
query: mutation,
},
+1 -1
View File
@@ -43,7 +43,7 @@ export function addGetNodes() {
cy.request({
method: 'POST',
url: `http://localhost:3028/query`,
url: `http://localhost:3008/graphql`,
body: {
query: print(query),
},
+11 -1
View File
@@ -35,7 +35,17 @@ export function generateMarket(override?: PartialDeep<Market>): Market {
__typename: 'Asset',
},
dataSourceSpecForTradingTermination: {
id: '',
__typename: 'DataSourceSpec',
id: 'oracleId',
},
dataSourceSpecForSettlementData: {
__typename: 'DataSourceSpec',
id: 'oracleId',
},
dataSourceSpecBinding: {
__typename: 'DataSourceSpecToFutureBinding',
tradingTerminationProperty: 'trading-termination-property',
settlementDataProperty: 'settlement-data-property',
},
quoteName: 'BTC',
__typename: 'Future',
+1
View File
@@ -100,6 +100,7 @@ export const TOKEN_VALIDATOR = '/validators/:id';
// Explorer pages
export const EXPLORER_TX = '/txs/:hash';
export const EXPLORER_ORACLE = '/oracles/:id';
// Etherscan pages
export const ETHERSCAN_ADDRESS = '/address/:hash';
+11 -1
View File
@@ -78,7 +78,17 @@ export const generateFill = (override?: PartialDeep<Trade>) => {
},
quoteName: '',
dataSourceSpecForTradingTermination: {
id: '',
__typename: 'DataSourceSpec',
id: 'oracleId',
},
dataSourceSpecForSettlementData: {
__typename: 'DataSourceSpec',
id: 'oracleId',
},
dataSourceSpecBinding: {
__typename: 'DataSourceSpecToFutureBinding',
tradingTerminationProperty: 'trading-termination-property',
settlementDataProperty: 'settlement-data-property',
},
},
},
+1
View File
@@ -12,4 +12,5 @@ export default {
},
moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx'],
coverageDirectory: '../../coverage/libs/ledger',
setupFilesAfterEnv: ['./src/setup-tests.ts'],
};
@@ -30,7 +30,10 @@ export type LedgerEntry = LedgerEntryFragment & {
};
export type AggregatedLedgerEntriesEdge = Schema.AggregatedLedgerEntriesEdge;
export type AggregatedLedgerEntriesNode = AggregatedLedgerEntriesEdge & {
export type AggregatedLedgerEntriesNode = Omit<
AggregatedLedgerEntriesEdge,
'node'
> & {
node: LedgerEntry;
};
+1 -2
View File
@@ -32,7 +32,7 @@ export const ledgerEntriesQuery = (
return merge(defaultResult, override);
};
const ledgerEntries: LedgerEntryFragment[] = [
export const ledgerEntries: LedgerEntryFragment[] = [
{
vegaTime: '1669224476734364000',
quantity: '0',
@@ -180,7 +180,6 @@ const ledgerEntries: LedgerEntryFragment[] = [
toAccountBalance: '0',
fromAccountBalance: '0',
},
{
vegaTime: '2022-11-24T12:41:22.054428Z',
quantity: '1000000000',
@@ -0,0 +1,85 @@
import { act, render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { LedgerExportLink } from './ledger-export-link';
import * as Types from '@vegaprotocol/types';
import { ledgerEntries } from './ledger-entries.mock';
import type { LedgerEntry } from './ledger-entries-data-provider';
const VEGA_URL = 'https://vega-url.co.uk/querystuff';
const mockEnvironment = jest.fn(() => VEGA_URL);
jest.mock('@vegaprotocol/environment', () => ({
useEnvironment: jest.fn(() => mockEnvironment()),
}));
const asset = {
id: 'assetID',
name: 'assetName',
symbol: 'assetSymbol',
decimals: 1,
quantum: '1',
status: Types.AssetStatus,
source: {
__typename: 'ERC20',
contractAddress: 'contractAddres',
lifetimeLimit: 'lifetimeLimit',
withdrawThreshold: 'withdraw',
},
};
describe('LedgerExportLink', () => {
const partyId = 'partyId';
const entries = ledgerEntries.map((entry) => {
return {
...entry,
asset: entry.assetId
? {
...asset,
id: entry.assetId,
name: `name ${entry.assetId}`,
symbol: `symbol ${entry.assetId}`,
}
: null,
marketSender: null,
marketReceiver: null,
} as LedgerEntry;
});
it('should be properly rendered', async () => {
render(<LedgerExportLink partyId={partyId} entries={entries} />);
await waitFor(() => {
expect(screen.getByRole('link')).toBeInTheDocument();
expect(screen.getByRole('link')).toHaveAttribute(
'href',
`https://vega-url.co.uk/api/v2/ledgerentry/export?partyId=${partyId}&assetId=asset-id`
);
expect(
screen.getByRole('button', { name: /^symbol asset-id/ })
).toBeInTheDocument();
});
});
it('should be properly change link url', async () => {
render(<LedgerExportLink partyId={partyId} entries={entries} />);
await waitFor(() => {
expect(
screen.getByRole('button', { name: /^symbol asset-id/ })
).toBeInTheDocument();
});
act(() => {
userEvent.click(screen.getByRole('button', { name: /^symbol asset-id/ }));
});
await waitFor(() => {
expect(screen.getByRole('menu')).toBeInTheDocument();
});
act(() => {
userEvent.click(
screen.getByRole('menuitem', { name: /^symbol asset-id-2/ })
);
});
await waitFor(() => {
expect(screen.getByRole('link')).toHaveAttribute(
'href',
`https://vega-url.co.uk/api/v2/ledgerentry/export?partyId=${partyId}&assetId=asset-id-2`
);
});
});
});
@@ -0,0 +1,71 @@
import type { LedgerEntry } from './ledger-entries-data-provider';
import { useMemo, useState } from 'react';
import { useEnvironment } from '@vegaprotocol/environment';
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
Link,
Button,
} from '@vegaprotocol/ui-toolkit';
import { t } from '@vegaprotocol/i18n';
const getProtoHost = (vegaurl: string) => {
const loc = new URL(vegaurl);
return `${loc.protocol}//${loc.host}`;
};
export const LedgerExportLink = ({
partyId,
entries,
}: {
partyId: string;
entries: LedgerEntry[];
}) => {
const assets = entries.reduce((aggr, item) => {
if (item.asset && !(item.asset.id in aggr)) {
aggr[item.asset.id] = item.asset.symbol;
}
return aggr;
}, {} as Record<string, string>);
const [assetId, setAssetId] = useState(Object.keys(assets)[0]);
const VEGA_URL = useEnvironment((store) => store.VEGA_URL);
const protohost = VEGA_URL ? getProtoHost(VEGA_URL) : '';
const assetDropDown = useMemo(() => {
return (
<DropdownMenu
trigger={<DropdownMenuTrigger>{assets[assetId]}</DropdownMenuTrigger>}
>
<DropdownMenuContent>
{Object.keys(assets).map((assetKey) => (
<DropdownMenuItem
key={assetKey}
onSelect={() => setAssetId(assetKey)}
>
{assets[assetKey]}
</DropdownMenuItem>
))}
</DropdownMenuContent>
</DropdownMenu>
);
}, [assetId, assets]);
if (!protohost) {
return null;
}
return (
<div className="flex shrink items-stretch gap-2 p-2">
<div className="flex items-center">Export all</div>
{assetDropDown}
<Link
className="text-sm"
title={t('Download all to .csv file')}
href={`${protohost}/api/v2/ledgerentry/export?partyId=${partyId}&assetId=${assetId}`}
>
<Button size="sm">{t('Download')}</Button>
</Link>
</div>
);
};
+6 -1
View File
@@ -3,12 +3,13 @@ import type * as Schema from '@vegaprotocol/types';
import { AsyncRenderer } from '@vegaprotocol/ui-toolkit';
import type { FilterChangedEvent } from 'ag-grid-community';
import type { AgGridReact } from 'ag-grid-react';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useCallback, useEffect, useRef, useState } from 'react';
import { subDays, formatRFC3339 } from 'date-fns';
import type { AggregatedLedgerEntriesNode } from './ledger-entries-data-provider';
import { useLedgerEntriesDataProvider } from './ledger-entries-data-provider';
import { LedgerTable } from './ledger-table';
import type * as Types from '@vegaprotocol/types';
import { LedgerExportLink } from './ledger-export-link';
export interface Filter {
vegaTime?: {
@@ -22,6 +23,7 @@ const defaultFilter = {
value: { start: formatRFC3339(subDays(Date.now(), 7)) },
},
};
export const LedgerManager = ({ partyId }: { partyId: string }) => {
const gridRef = useRef<AgGridReact | null>(null);
const [filter, setFilter] = useState<Filter>(defaultFilter);
@@ -55,6 +57,9 @@ export const LedgerManager = ({ partyId }: { partyId: string }) => {
rowData={extractedData}
onFilterChanged={onFilterChanged}
/>
{extractedData && (
<LedgerExportLink entries={extractedData} partyId={partyId} />
)}
<div className="pointer-events-none absolute inset-0">
<AsyncRenderer
loading={loading}
+1 -1
View File
@@ -49,7 +49,7 @@ export const LedgerTable = forwardRef<AgGridReact, LedgerEntryProps>(
(props, ref) => {
return (
<AgGrid
style={{ width: '100%', height: '100%' }}
style={{ width: '100%', height: 'calc(100% - 50px)' }}
ref={ref}
tooltipShowDelay={500}
defaultColDef={{
+24
View File
@@ -0,0 +1,24 @@
import '@testing-library/jest-dom';
import 'jest-canvas-mock';
import ResizeObserver from 'resize-observer-polyfill';
global.ResizeObserver = ResizeObserver;
global.DOMRect = class DOMRect {
bottom = 0;
left = 0;
right = 0;
top = 0;
constructor(
public x = 0,
public y = 0,
public width = 0,
public height = 0
) {}
static fromRect(other?: DOMRectInit): DOMRect {
return new DOMRect(other?.x, other?.y, other?.width, other?.height);
}
toJSON() {
return JSON.stringify(this);
}
};
+23 -19
View File
@@ -19,25 +19,29 @@ export const useMarketOracle = (marketId: string) => {
marketInfo.tradableInstrument.instrument.product
.dataSourceSpecForSettlementData.data;
return data.find((provider) =>
provider.proofs.some(
(proof) =>
(proof.type === 'eth_address' &&
dataSource.sourceType.__typename ===
'DataSourceDefinitionExternal' &&
dataSource.sourceType.sourceType.signers?.some(
(signer) =>
signer.signer.__typename === 'ETHAddress' &&
signer.signer.address === proof.eth_address
)) ||
(proof.type === 'public_key' &&
dataSource.sourceType.__typename ===
'DataSourceDefinitionExternal' &&
dataSource.sourceType.sourceType.signers?.some(
(signer) =>
signer.signer.__typename === 'PubKey' &&
signer.signer.key === proof.public_key
))
)
provider.proofs.some((proof) => {
if (
proof.type === 'eth_address' &&
dataSource.sourceType.__typename === 'DataSourceDefinitionExternal'
) {
return dataSource.sourceType.sourceType.signers?.some(
(signer) =>
signer.signer.__typename === 'ETHAddress' &&
signer.signer.address === proof.eth_address
);
}
if (
proof.type === 'public_key' &&
dataSource.sourceType.__typename === 'DataSourceDefinitionExternal'
) {
return dataSource.sourceType.sourceType.signers?.some(
(signer) =>
signer.signer.__typename === 'PubKey' &&
signer.signer.key === proof.public_key
);
}
return false;
})
)?.oracle;
}, [data, marketInfo]);
};
+9 -2
View File
@@ -3,12 +3,12 @@ import * as Types from '@vegaprotocol/types';
import { gql } from '@apollo/client';
import * as Apollo from '@apollo/client';
const defaultOptions = {} as const;
export type MarketFieldsFragment = { __typename?: 'Market', id: string, decimalPlaces: number, positionDecimalPlaces: number, state: Types.MarketState, tradingMode: Types.MarketTradingMode, fees: { __typename?: 'Fees', factors: { __typename?: 'FeeFactors', makerFee: string, infrastructureFee: string, liquidityFee: string } }, tradableInstrument: { __typename?: 'TradableInstrument', instrument: { __typename?: 'Instrument', id: string, name: string, code: string, metadata: { __typename?: 'InstrumentMetadata', tags?: Array<string> | null }, product: { __typename?: 'Future', quoteName: string, settlementAsset: { __typename?: 'Asset', id: string, symbol: string, name: string, decimals: number }, dataSourceSpecForTradingTermination: { __typename?: 'DataSourceSpec', id: string } } } }, marketTimestamps: { __typename?: 'MarketTimestamps', open: any, close: any } };
export type MarketFieldsFragment = { __typename?: 'Market', id: string, decimalPlaces: number, positionDecimalPlaces: number, state: Types.MarketState, tradingMode: Types.MarketTradingMode, fees: { __typename?: 'Fees', factors: { __typename?: 'FeeFactors', makerFee: string, infrastructureFee: string, liquidityFee: string } }, tradableInstrument: { __typename?: 'TradableInstrument', instrument: { __typename?: 'Instrument', id: string, name: string, code: string, metadata: { __typename?: 'InstrumentMetadata', tags?: Array<string> | null }, product: { __typename?: 'Future', quoteName: string, settlementAsset: { __typename?: 'Asset', id: string, symbol: string, name: string, decimals: number }, dataSourceSpecForTradingTermination: { __typename?: 'DataSourceSpec', id: string }, dataSourceSpecForSettlementData: { __typename?: 'DataSourceSpec', id: string }, dataSourceSpecBinding: { __typename?: 'DataSourceSpecToFutureBinding', settlementDataProperty: string, tradingTerminationProperty: string } } } }, marketTimestamps: { __typename?: 'MarketTimestamps', open: any, close: any } };
export type MarketsQueryVariables = Types.Exact<{ [key: string]: never; }>;
export type MarketsQuery = { __typename?: 'Query', marketsConnection?: { __typename?: 'MarketConnection', edges: Array<{ __typename?: 'MarketEdge', node: { __typename?: 'Market', id: string, decimalPlaces: number, positionDecimalPlaces: number, state: Types.MarketState, tradingMode: Types.MarketTradingMode, fees: { __typename?: 'Fees', factors: { __typename?: 'FeeFactors', makerFee: string, infrastructureFee: string, liquidityFee: string } }, tradableInstrument: { __typename?: 'TradableInstrument', instrument: { __typename?: 'Instrument', id: string, name: string, code: string, metadata: { __typename?: 'InstrumentMetadata', tags?: Array<string> | null }, product: { __typename?: 'Future', quoteName: string, settlementAsset: { __typename?: 'Asset', id: string, symbol: string, name: string, decimals: number }, dataSourceSpecForTradingTermination: { __typename?: 'DataSourceSpec', id: string } } } }, marketTimestamps: { __typename?: 'MarketTimestamps', open: any, close: any } } }> } | null };
export type MarketsQuery = { __typename?: 'Query', marketsConnection?: { __typename?: 'MarketConnection', edges: Array<{ __typename?: 'MarketEdge', node: { __typename?: 'Market', id: string, decimalPlaces: number, positionDecimalPlaces: number, state: Types.MarketState, tradingMode: Types.MarketTradingMode, fees: { __typename?: 'Fees', factors: { __typename?: 'FeeFactors', makerFee: string, infrastructureFee: string, liquidityFee: string } }, tradableInstrument: { __typename?: 'TradableInstrument', instrument: { __typename?: 'Instrument', id: string, name: string, code: string, metadata: { __typename?: 'InstrumentMetadata', tags?: Array<string> | null }, product: { __typename?: 'Future', quoteName: string, settlementAsset: { __typename?: 'Asset', id: string, symbol: string, name: string, decimals: number }, dataSourceSpecForTradingTermination: { __typename?: 'DataSourceSpec', id: string }, dataSourceSpecForSettlementData: { __typename?: 'DataSourceSpec', id: string }, dataSourceSpecBinding: { __typename?: 'DataSourceSpecToFutureBinding', settlementDataProperty: string, tradingTerminationProperty: string } } } }, marketTimestamps: { __typename?: 'MarketTimestamps', open: any, close: any } } }> } | null };
export const MarketFieldsFragmentDoc = gql`
fragment MarketFields on Market {
@@ -44,6 +44,13 @@ export const MarketFieldsFragmentDoc = gql`
dataSourceSpecForTradingTermination {
id
}
dataSourceSpecForSettlementData {
id
}
dataSourceSpecBinding {
settlementDataProperty
tradingTerminationProperty
}
}
}
}
+16 -42
View File
@@ -25,8 +25,10 @@ export const marketsDataQuery = (
return merge(defaultResult, override);
};
const marketsDataFieldsFragments: MarketsDataFieldsFragment[] = [
{
export const createMarketsDataFragment = (
override?: PartialDeep<MarketsDataFieldsFragment>
): MarketsDataFieldsFragment => {
const defaultResult = {
market: {
id: 'market-0',
__typename: 'Market',
@@ -42,56 +44,28 @@ const marketsDataFieldsFragments: MarketsDataFieldsFragment[] = [
markPrice: '4612690058',
trigger: Schema.AuctionTrigger.AUCTION_TRIGGER_UNSPECIFIED,
__typename: 'MarketData',
},
{
};
return merge(defaultResult, override);
};
const marketsDataFieldsFragments: MarketsDataFieldsFragment[] = [
createMarketsDataFragment(),
createMarketsDataFragment({
market: {
id: 'market-1',
__typename: 'Market',
},
marketTradingMode: Schema.MarketTradingMode.TRADING_MODE_CONTINUOUS,
staticMidPrice: '0',
indicativePrice: '0',
bestStaticBidPrice: '0',
bestStaticOfferPrice: '0',
indicativeVolume: '0',
bestBidPrice: '0',
bestOfferPrice: '0',
markPrice: '8441',
trigger: Schema.AuctionTrigger.AUCTION_TRIGGER_UNSPECIFIED,
__typename: 'MarketData',
},
{
}),
createMarketsDataFragment({
market: {
id: 'market-2',
__typename: 'Market',
},
marketTradingMode: Schema.MarketTradingMode.TRADING_MODE_CONTINUOUS,
staticMidPrice: '0',
indicativePrice: '0',
bestStaticBidPrice: '0',
bestStaticOfferPrice: '0',
indicativeVolume: '0',
bestBidPrice: '0',
bestOfferPrice: '0',
markPrice: '4612690058',
trigger: Schema.AuctionTrigger.AUCTION_TRIGGER_LIQUIDITY_TARGET_NOT_MET,
__typename: 'MarketData',
},
{
}),
createMarketsDataFragment({
market: {
id: 'market-3',
__typename: 'Market',
},
marketTradingMode: Schema.MarketTradingMode.TRADING_MODE_CONTINUOUS,
staticMidPrice: '0',
indicativePrice: '0',
bestStaticBidPrice: '0',
bestStaticOfferPrice: '0',
indicativeVolume: '0',
bestBidPrice: '0',
bestOfferPrice: '0',
markPrice: '4612690058',
trigger: Schema.AuctionTrigger.AUCTION_TRIGGER_LIQUIDITY_TARGET_NOT_MET,
__typename: 'MarketData',
},
}),
];
+13 -1
View File
@@ -13,7 +13,7 @@ import type { MarketData } from './market-data-provider';
import type { MarketCandles } from './markets-candles-provider';
import { useMemo } from 'react';
import * as Schema from '@vegaprotocol/types';
import { filterAndSortMarkets } from './utils';
import { filterAndSortClosedMarkets, filterAndSortMarkets } from './utils';
import { MarketsDocument } from './__generated__/markets';
import type { Candle } from './market-candles-provider';
@@ -72,6 +72,11 @@ export const activeMarketsProvider = makeDerivedDataProvider<Market[], never>(
([markets]) => filterAndSortMarkets(markets)
);
export const closedMarketsProvider = makeDerivedDataProvider<Market[], never>(
[marketsProvider],
([markets]) => filterAndSortClosedMarkets(markets)
);
export type MarketMaybeWithCandles = Market & { candles?: Candle[] };
const addCandles = <T extends Market>(
@@ -111,6 +116,13 @@ export const marketsWithDataProvider = makeDerivedDataProvider<
addData(parts[0] as Market[], parts[1] as MarketData[])
);
export const closedMarketsWithDataProvider = makeDerivedDataProvider<
MarketMaybeWithData[],
never
>([closedMarketsProvider, marketsDataProvider], (parts) =>
addData(parts[0] as Market[], parts[1] as MarketData[])
);
export type MarketMaybeWithDataAndCandles = MarketMaybeWithData &
MarketMaybeWithCandles;
+7
View File
@@ -31,6 +31,13 @@ fragment MarketFields on Market {
dataSourceSpecForTradingTermination {
id
}
dataSourceSpecForSettlementData {
id
}
dataSourceSpecBinding {
settlementDataProperty
tradingTerminationProperty
}
}
}
}
+27 -77
View File
@@ -22,8 +22,10 @@ export const marketsQuery = (
return merge(defaultResult, override);
};
const marketFieldsFragments: MarketFieldsFragment[] = [
{
export const createMarketFragment = (
override?: PartialDeep<MarketFieldsFragment>
): MarketFieldsFragment => {
const defaultFragment = {
id: 'market-0',
decimalPlaces: 5,
positionDecimalPlaces: 0,
@@ -61,8 +63,18 @@ const marketFieldsFragments: MarketFieldsFragment[] = [
__typename: 'Asset',
},
dataSourceSpecForTradingTermination: {
__typename: 'DataSourceSpec',
id: 'oracleId',
},
dataSourceSpecForSettlementData: {
__typename: 'DataSourceSpec',
id: 'oracleId',
},
dataSourceSpecBinding: {
__typename: 'DataSourceSpecBinding',
tradingTerminationProperty: 'trading-termination-property',
settlementDataProperty: 'settlement-data-property',
},
quoteName: 'DAI',
__typename: 'Future',
},
@@ -71,36 +83,20 @@ const marketFieldsFragments: MarketFieldsFragment[] = [
__typename: 'TradableInstrument',
},
__typename: 'Market',
},
{
};
return merge(defaultFragment, override);
};
const marketFieldsFragments: MarketFieldsFragment[] = [
createMarketFragment({ id: 'market-0' }),
createMarketFragment({
id: 'market-1',
decimalPlaces: 2,
positionDecimalPlaces: 0,
tradingMode: Schema.MarketTradingMode.TRADING_MODE_CONTINUOUS,
state: Schema.MarketState.STATE_ACTIVE,
marketTimestamps: {
__typename: 'MarketTimestamps',
close: '',
open: '',
},
fees: {
__typename: 'Fees',
factors: {
__typename: 'FeeFactors',
makerFee: '',
infrastructureFee: '',
liquidityFee: '',
},
},
tradableInstrument: {
instrument: {
id: 'SOLUSD',
name: 'SUSPENDED MARKET',
code: 'SOLUSD',
metadata: {
__typename: 'InstrumentMetadata',
tags: [],
},
product: {
settlementAsset: {
id: 'asset-1',
@@ -109,33 +105,19 @@ const marketFieldsFragments: MarketFieldsFragment[] = [
decimals: 5,
__typename: 'Asset',
},
dataSourceSpecForTradingTermination: {
id: 'oracleId',
},
quoteName: 'USD',
__typename: 'Future',
},
__typename: 'Instrument',
},
__typename: 'TradableInstrument',
},
__typename: 'Market',
},
{
}),
createMarketFragment({
id: 'market-2',
decimalPlaces: 5,
positionDecimalPlaces: 0,
tradingMode: Schema.MarketTradingMode.TRADING_MODE_MONITORING_AUCTION,
state: Schema.MarketState.STATE_SUSPENDED,
marketTimestamps: {
__typename: 'MarketTimestamps',
close: '2022-08-26T11:36:32.252490405Z',
open: null,
},
fees: {
__typename: 'Fees',
factors: {
__typename: 'FeeFactors',
makerFee: '0.0002',
infrastructureFee: '0.0005',
liquidityFee: '0.001',
@@ -143,13 +125,8 @@ const marketFieldsFragments: MarketFieldsFragment[] = [
},
tradableInstrument: {
instrument: {
id: '',
code: 'AAPL.MF21',
name: 'Apple Monthly (30 Jun 2022)',
metadata: {
__typename: 'InstrumentMetadata',
tags: [],
},
product: {
settlementAsset: {
id: 'asset-2',
@@ -158,33 +135,18 @@ const marketFieldsFragments: MarketFieldsFragment[] = [
decimals: 5,
__typename: 'Asset',
},
dataSourceSpecForTradingTermination: {
id: 'oracleId',
},
quoteName: 'USDC',
__typename: 'Future',
},
__typename: 'Instrument',
},
__typename: 'TradableInstrument',
},
__typename: 'Market',
},
{
}),
createMarketFragment({
id: 'market-3',
decimalPlaces: 5,
positionDecimalPlaces: 0,
tradingMode: Schema.MarketTradingMode.TRADING_MODE_CONTINUOUS,
state: Schema.MarketState.STATE_ACTIVE,
marketTimestamps: {
__typename: 'MarketTimestamps',
close: '2022-08-26T11:36:32.252490405Z',
open: null,
},
fees: {
__typename: 'Fees',
factors: {
__typename: 'FeeFactors',
makerFee: '0.0002',
infrastructureFee: '0.0005',
liquidityFee: '0.001',
@@ -192,13 +154,8 @@ const marketFieldsFragments: MarketFieldsFragment[] = [
},
tradableInstrument: {
instrument: {
id: '',
code: 'ETHBTC.QM21',
name: 'ETHBTC Quarterly (30 Jun 2022)',
metadata: {
__typename: 'InstrumentMetadata',
tags: [],
},
product: {
settlementAsset: {
id: 'asset-3',
@@ -207,16 +164,9 @@ const marketFieldsFragments: MarketFieldsFragment[] = [
decimals: 5,
__typename: 'Asset',
},
dataSourceSpecForTradingTermination: {
id: 'oracleId',
},
quoteName: 'BTC',
__typename: 'Future',
},
__typename: 'Instrument',
},
__typename: 'TradableInstrument',
},
__typename: 'Market',
},
}),
];
@@ -43,6 +43,15 @@ export const filterAndSortMarkets = (markets: Market[]) => {
);
};
export const filterAndSortClosedMarkets = (markets: Market[]) => {
return markets.filter((m) => {
return [
MarketState.STATE_SETTLED,
MarketState.STATE_TRADING_TERMINATED,
].includes(m.state);
});
};
export const calcCandleLow = (candles: Candle[]): string | undefined => {
return candles
?.reduce((acc: BigNumber, c) => {
@@ -1,4 +1,7 @@
query Stats {
epoch {
id
}
nodeData {
stakedTotal
totalNodes
@@ -6,11 +6,14 @@ const defaultOptions = {} as const;
export type StatsQueryVariables = Types.Exact<{ [key: string]: never; }>;
export type StatsQuery = { __typename?: 'Query', nodeData?: { __typename?: 'NodeData', stakedTotal: string, totalNodes: number, inactiveNodes: number } | null, statistics: { __typename?: 'Statistics', status: string, blockHeight: string, blockDuration: string, backlogLength: string, txPerBlock: string, tradesPerSecond: string, ordersPerSecond: string, averageOrdersPerBlock: string, vegaTime: any, appVersion: string, chainVersion: string, chainId: string, genesisTime: any } };
export type StatsQuery = { __typename?: 'Query', epoch: { __typename?: 'Epoch', id: string }, nodeData?: { __typename?: 'NodeData', stakedTotal: string, totalNodes: number, inactiveNodes: number } | null, statistics: { __typename?: 'Statistics', status: string, blockHeight: string, blockDuration: string, backlogLength: string, txPerBlock: string, tradesPerSecond: string, ordersPerSecond: string, averageOrdersPerBlock: string, vegaTime: any, appVersion: string, chainVersion: string, chainId: string, genesisTime: any } };
export const StatsDocument = gql`
query Stats {
epoch {
id
}
nodeData {
stakedTotal
totalNodes
@@ -19,10 +19,14 @@ export const StatsManager = ({ className }: StatsManagerProps) => {
return () => stopPolling();
}, [startPolling, stopPolling]);
const getValue = (field: keyof NodeData | keyof Statistics) =>
['stakedTotal', 'totalNodes', 'inactiveNodes'].includes(field)
? data?.nodeData?.[field as keyof NodeData]
: data?.statistics?.[field as keyof Statistics];
const getValue = (field: keyof NodeData | keyof Statistics | 'epoch') => {
if (['stakedTotal', 'totalNodes', 'inactiveNodes'].includes(field)) {
return data?.nodeData?.[field as keyof NodeData];
} else if (field === 'epoch') {
return data?.epoch.id;
}
return data?.statistics?.[field as keyof Statistics];
};
const panels = fieldsDefinition.map(
({ field, title, description, formatter, goodThreshold }) => ({
@@ -50,7 +54,7 @@ export const StatsManager = ({ className }: StatsManagerProps) => {
className={classNames(
'border rounded p-2 relative border-vega-light-200 dark:border-vega-dark-200',
{
'col-span-2': field === 'chainId' || field === 'status',
'col-span-2': field === 'chainId',
},
{
'bg-transparent border-vega-light-200 dark:border-vega-dark-200':
@@ -20,7 +20,7 @@ export type FieldValue = any;
export type GoodThreshold = (...args: FieldValue[]) => boolean;
export interface Stats {
field: keyof NodeData | keyof Statistics;
field: keyof NodeData | keyof Statistics | 'epoch';
title: string;
goodThreshold?: GoodThreshold;
// eslint-disable-next-line
@@ -161,6 +161,11 @@ const VEGA_TIME: Stats = {
description: t('The time on the blockchain'),
};
const EPOCH: Stats = {
field: 'epoch',
title: 'Epoch',
};
const APP_VERSION: Stats = {
field: 'appVersion',
title: t('App'),
@@ -217,6 +222,7 @@ const CHAIN_ID: Stats = {
export const fieldsDefinition: Stats[] = [
STATUS,
EPOCH,
BLOCK_HEIGHT,
UPTIME,
TOTAL_NODES,
+1 -1
View File
@@ -1,6 +1,6 @@
{
"extends": ["plugin:@nrwl/nx/react", "../../.eslintrc.json"],
"ignorePatterns": ["!**/*"],
"ignorePatterns": ["!**/*", "__generated__", "__generated___"],
"overrides": [
{
"files": ["*.ts", "*.tsx", "*.js", "*.jsx"],
+2
View File
@@ -1,2 +1,4 @@
export * from './lib/oracle-schema';
export * from './lib/use-oracle-proofs';
export * from './lib/use-oracle-spec-binding-data';
export * from './lib/__generated__/OracleSpecDataConnection';
@@ -0,0 +1,18 @@
query OracleSpecDataConnection($oracleSpecId: ID!) {
oracleSpec(oracleSpecId: $oracleSpecId) {
dataConnection {
edges {
node {
externalData {
data {
data {
name
value
}
}
}
}
}
}
}
}
@@ -0,0 +1,61 @@
import * as Types from '@vegaprotocol/types';
import { gql } from '@apollo/client';
import * as Apollo from '@apollo/client';
const defaultOptions = {} as const;
export type OracleSpecDataConnectionQueryVariables = Types.Exact<{
oracleSpecId: Types.Scalars['ID'];
}>;
export type OracleSpecDataConnectionQuery = { __typename?: 'Query', oracleSpec?: { __typename?: 'OracleSpec', dataConnection: { __typename?: 'OracleDataConnection', edges?: Array<{ __typename?: 'OracleDataEdge', node: { __typename?: 'OracleData', externalData: { __typename?: 'ExternalData', data: { __typename?: 'Data', data?: Array<{ __typename?: 'Property', name: string, value: string }> | null } } } } | null> | null } } | null };
export const OracleSpecDataConnectionDocument = gql`
query OracleSpecDataConnection($oracleSpecId: ID!) {
oracleSpec(oracleSpecId: $oracleSpecId) {
dataConnection {
edges {
node {
externalData {
data {
data {
name
value
}
}
}
}
}
}
}
}
`;
/**
* __useOracleSpecDataConnectionQuery__
*
* To run a query within a React component, call `useOracleSpecDataConnectionQuery` and pass it any options that fit your needs.
* When your component renders, `useOracleSpecDataConnectionQuery` 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 } = useOracleSpecDataConnectionQuery({
* variables: {
* oracleSpecId: // value for 'oracleSpecId'
* },
* });
*/
export function useOracleSpecDataConnectionQuery(baseOptions: Apollo.QueryHookOptions<OracleSpecDataConnectionQuery, OracleSpecDataConnectionQueryVariables>) {
const options = {...defaultOptions, ...baseOptions}
return Apollo.useQuery<OracleSpecDataConnectionQuery, OracleSpecDataConnectionQueryVariables>(OracleSpecDataConnectionDocument, options);
}
export function useOracleSpecDataConnectionLazyQuery(baseOptions?: Apollo.LazyQueryHookOptions<OracleSpecDataConnectionQuery, OracleSpecDataConnectionQueryVariables>) {
const options = {...defaultOptions, ...baseOptions}
return Apollo.useLazyQuery<OracleSpecDataConnectionQuery, OracleSpecDataConnectionQueryVariables>(OracleSpecDataConnectionDocument, options);
}
export type OracleSpecDataConnectionQueryHookResult = ReturnType<typeof useOracleSpecDataConnectionQuery>;
export type OracleSpecDataConnectionLazyQueryHookResult = ReturnType<typeof useOracleSpecDataConnectionLazyQuery>;
export type OracleSpecDataConnectionQueryResult = Apollo.QueryResult<OracleSpecDataConnectionQuery, OracleSpecDataConnectionQueryVariables>;
@@ -0,0 +1,38 @@
import merge from 'lodash/merge';
import type { PartialDeep } from 'type-fest';
import type { OracleSpecDataConnectionQuery } from './__generated__/OracleSpecDataConnection';
import type { OracleData } from '@vegaprotocol/types';
export function createDataConnection(
override?: PartialDeep<OracleData>
): OracleData {
const defaultDataConnection = {
externalData: {
data: {
broadcastAt: new Date().toISOString(),
data: [
{
name: 'settlement-data-property',
value: '100',
},
],
},
},
};
return merge(defaultDataConnection, override);
}
export function oracleSpecDataConnectionQuery(
override?: PartialDeep<OracleSpecDataConnectionQuery>
): OracleSpecDataConnectionQuery {
const defaultResult = {
oracleSpec: {
dataConnection: {
edges: [{ node: createDataConnection() }],
},
},
};
return merge(defaultResult, override);
}
@@ -0,0 +1,105 @@
import { renderHook, waitFor } from '@testing-library/react';
import type { MockedResponse } from '@apollo/client/testing';
import { MockedProvider } from '@apollo/client/testing';
import type { ReactNode } from 'react';
import { useOracleSpecBindingData } from './use-oracle-spec-binding-data';
import type { Property } from '@vegaprotocol/types';
import type { OracleSpecDataConnectionQuery } from './__generated__/OracleSpecDataConnection';
import { OracleSpecDataConnectionDocument } from './__generated__/OracleSpecDataConnection';
describe('useSettlementPrice', () => {
const setup = (
oracleSpecId: string,
specBinding: string,
mocks: MockedResponse<OracleSpecDataConnectionQuery>[]
) => {
const wrapper = ({ children }: { children: ReactNode }) => (
<MockedProvider mocks={mocks}>{children}</MockedProvider>
);
return renderHook(
() => useOracleSpecBindingData(oracleSpecId, specBinding),
{
wrapper,
}
);
};
const createMock = (
id: string,
property: Property
): MockedResponse<OracleSpecDataConnectionQuery> => {
return {
request: {
query: OracleSpecDataConnectionDocument,
variables: {
oracleSpecId: id,
},
},
result: {
data: {
oracleSpec: {
dataConnection: {
edges: [
{
node: {
externalData: {
data: {
data: [property],
},
},
},
},
],
},
},
},
},
};
};
it('should returns the matching value for the spec binding', async () => {
const oracleSpecId = 'oracle-spec-id';
const specBinding = 'spec-binding';
const value = '123456';
const property = {
__typename: 'Property' as const,
name: specBinding,
value,
};
const mock = createMock(oracleSpecId, property);
const { result } = setup(oracleSpecId, specBinding, [mock]);
expect(result.current.property).toEqual(undefined);
expect(result.current.data).toBe(undefined);
expect(result.current.loading).toBe(true);
expect(result.current.error).toBe(undefined);
await waitFor(() => {
expect(result.current.property).toEqual(property);
expect(result.current.loading).toBe(false);
});
});
it('returns nothing if matching poperty not found', async () => {
const oracleSpecId = 'oracle-spec-id';
const specBinding = 'spec-binding';
const value = '123456';
const property = {
__typename: 'Property' as const,
name: 'does not match',
value,
};
const mock = createMock(oracleSpecId, property);
const { result } = setup(oracleSpecId, specBinding, [mock]);
expect(result.current.property).toEqual(undefined);
expect(result.current.data).toBe(undefined);
expect(result.current.loading).toBe(true);
expect(result.current.error).toBe(undefined);
await waitFor(() => {
expect(result.current.property).toEqual(undefined);
expect(result.current.loading).toBe(false);
});
});
});
@@ -0,0 +1,26 @@
import { useOracleSpecDataConnectionQuery } from './__generated__/OracleSpecDataConnection';
export const useOracleSpecBindingData = (
oracleSpecId: string | undefined,
specBinding: string | undefined
) => {
const { data, loading, error } = useOracleSpecDataConnectionQuery({
variables: {
oracleSpecId: oracleSpecId || '',
},
skip: !oracleSpecId,
});
const dataConnectionEdges = data?.oracleSpec?.dataConnection.edges;
const firstDataConnection = dataConnectionEdges?.[0]?.node;
const property = firstDataConnection?.externalData.data.data?.find(
(d) => d.name === specBinding
);
return {
property,
data,
loading,
error,
};
};
+2 -1
View File
@@ -15,6 +15,7 @@
"**/*.spec.js",
"**/*.test.jsx",
"**/*.spec.jsx",
"**/*.d.ts"
"**/*.d.ts",
"src/lib/use-oracle-spec-binding-data.spec.tsx"
]
}
@@ -49,7 +49,17 @@ export const generateOrder = (partialOrder?: PartialDeep<Order>) => {
name: 'XYZ',
},
dataSourceSpecForTradingTermination: {
id: '',
__typename: 'DataSourceSpec',
id: 'oracleId',
},
dataSourceSpecForSettlementData: {
__typename: 'DataSourceSpec',
id: 'oracleId',
},
dataSourceSpecBinding: {
__typename: 'DataSourceSpecToFutureBinding',
tradingTerminationProperty: 'trading-termination-property',
settlementDataProperty: 'settlement-data-property',
},
},
},
@@ -148,7 +148,17 @@ describe('WithdrawFormContainer', () => {
decimals: 5,
},
dataSourceSpecForTradingTermination: {
id: '',
__typename: 'DataSourceSpec',
id: 'oracleId',
},
dataSourceSpecForSettlementData: {
__typename: 'DataSourceSpec',
id: 'oracleId',
},
dataSourceSpecBinding: {
__typename: 'DataSourceSpecToFutureBinding',
tradingTerminationProperty: 'trading-termination-property',
settlementDataProperty: 'settlement-data-property',
},
quoteName: 'USD',
},
+1 -1
View File
@@ -195,7 +195,7 @@
"ts-jest": "27.1.4",
"ts-node": "10.9.1",
"tslib": "^2.0.0",
"type-fest": "^2.12.2",
"type-fest": "^3.8.0",
"typescript": "^5.0.4",
"url-loader": "^3.0.0"
},
+9 -9
View File
@@ -1,7 +1,7 @@
{
"app_state": {
"assets": {
"fBTC": {
"73174a6fb1d5802ba0ac7bd7ab79e0a3a4837b262de0a4e80815a55442692bd0": {
"min_lp_stake": "1",
"decimals": 5,
"name": "BTC (fake)",
@@ -13,7 +13,7 @@
}
}
},
"fDAI": {
"8566db7257222b5b7ef2886394ad28b938b28680a54a169bbc795027b89d6665": {
"min_lp_stake": "1",
"decimals": 5,
"name": "DAI (fake)",
@@ -25,7 +25,7 @@
}
}
},
"fEURO": {
"e02d4c15d790d1d2dffaf2dcd1cf06a1fe656656cf4ed18c8ce99f9e83643567": {
"min_lp_stake": "1",
"decimals": 5,
"name": "EURO (fake)",
@@ -37,7 +37,7 @@
}
}
},
"fUSDC": {
"816af99af60d684502a40824758f6b5377e6af48e50a9ee8ef478ecb879ea8bc": {
"min_lp_stake": "1",
"decimals": 5,
"name": "USDC (fake)",
@@ -49,7 +49,7 @@
}
}
},
"XYZalpha": {
"62dfb1ab1cd488862b416cf163c75bc9a279226c65ac287c0dd67650daa444ee": {
"min_lp_stake": "1",
"decimals": 5,
"name": "XYZ (α alpha)",
@@ -61,7 +61,7 @@
}
}
},
"XYZbeta": {
"dedb3c42e7bc88d98a7fe0d73c7b9870b34c62c79a713071bd4d645ef7c216ee": {
"min_lp_stake": "1",
"decimals": 5,
"name": "XYZ (β beta)",
@@ -73,7 +73,7 @@
}
}
},
"XYZgamma": {
"a0ea8a48eb5cb024e66be5777bea75165ffcaf0be82d9047e376ce352e202f76": {
"min_lp_stake": "1",
"decimals": 5,
"name": "XYZ (γ gamma)",
@@ -85,7 +85,7 @@
}
}
},
"XYZdelta": {
"9ed5dd08c88e38f1c92cb8f056bd9d0507512c9ea4e6f308936f73646187b8e9": {
"min_lp_stake": "1",
"decimals": 5,
"name": "XYZ (δ delta)",
@@ -97,7 +97,7 @@
}
}
},
"XYZepsilon": {
"bdcde894dcc4ffa11d6192065d84f9dcc75814cf24760ff4f3e50d64eaddbc02": {
"min_lp_stake": "1",
"decimals": 5,
"name": "XYZ (ε epsilon)",
+4 -4
View File
@@ -23637,10 +23637,10 @@ type-fest@^0.8.1:
resolved "https://registry.yarnpkg.com/type-fest/-/type-fest-0.8.1.tgz#09e249ebde851d3b1e48d27c105444667f17b83d"
integrity sha512-4dbzIzqvjtgiM5rw1k5rEHtBANKmdudhGyBEajN01fEyhaAIhsoKNy6y7+IN93IfpFtwY9iqi7kD+xwKhQsNJA==
type-fest@^2.12.2:
version "2.19.0"
resolved "https://registry.yarnpkg.com/type-fest/-/type-fest-2.19.0.tgz#88068015bb33036a598b952e55e9311a60fd3a9b"
integrity sha512-RAH822pAdBgcNMAfWnCBU3CFZcfZ/i1eZjwFU/dsLKumyuuP3niueg2UAukXYF0E2AAoc82ZSSf9J0WQBinzHA==
type-fest@^3.8.0:
version "3.8.0"
resolved "https://registry.yarnpkg.com/type-fest/-/type-fest-3.8.0.tgz#ce80d1ca7c7d11c5540560999cbd410cb5b3a385"
integrity sha512-FVNSzGQz9Th+/9R6Lvv7WIAkstylfHN2/JYxkyhhmKFYh9At2DST8t6L6Lref9eYO8PXFTfG9Sg1Agg0K3vq3Q==
type-is@~1.6.18:
version "1.6.18"