Compare commits

..
Author SHA1 Message Date
Bartłomiej Głownia d5ca897f8b Merge branch 'develop' into 4723-remove-dependency-on-apollo-from-wallet-lib 2023-10-04 10:49:22 +02:00
Joe Tsang 14928d318d chore(governance): add e2e tests for market update proposals (#4945) 2023-10-02 20:50:47 +01:00
m.ray a19ea1c939 fix(trading): update filter for market selector to include suspended via governance (#4957) 2023-10-02 18:00:49 +01:00
m.rayandMatthew Russell c65c296db2 feat(trading): ethereum oracle spec in oracle panels (#4914)
Co-authored-by: Matthew Russell <mattrussell36@gmail.com>
2023-10-02 17:48:12 +01:00
Maciek 6c5cd85d96 fix(deal-ticket): prevent empty call estimate position (#4950) 2023-10-02 18:26:10 +02:00
m.ray 8efadda98c fix(trading): remove market value proxy and formatting (#4916) 2023-10-02 16:00:55 +01:00
Maciek 0872a14f44 feat(positions): close position with max possible size (#4940) 2023-10-02 16:38:22 +02:00
Ben 13817e4d57 chore(trading): delete duplicate asset details test (#4954) 2023-10-02 13:57:54 +00:00
Bartłomiej Głownia 7d84d61347 Merge remote-tracking branch 'origin/develop' into 4723-remove-dependency-on-apollo-from-wallet-lib 2023-09-27 08:32:48 +02:00
Bartłomiej Głownia 99855f749a Merge branch 'develop' into 4723-remove-dependency-on-apollo-from-wallet-lib 2023-09-20 12:47:51 +02:00
Bartłomiej Głownia a3351acfb5 feat: rollback tsconfig changes 2023-09-20 10:32:39 +02:00
Bartłomiej Głownia cc2a6fce37 chore: use proper alias for statistics intercept 2023-09-19 12:12:26 +02:00
Bartłomiej Głownia 200cec5ad7 chore: improve chainId mock 2023-09-19 12:12:25 +02:00
Bartłomiej Głownia e5a766d0a3 chore: replace statistics query with fetch 2023-09-19 12:12:25 +02:00
Bartłomiej Głownia c29b549fbc chore: unit test fixes 2023-09-19 12:12:25 +02:00
Bartłomiej Głownia 36243ae571 chore(wallet): remove dependency on apollo from wallet lib 2023-09-19 12:12:24 +02:00
121 changed files with 1325 additions and 1165 deletions
@@ -49,6 +49,37 @@ fragment ExplorerOracleDataSource on OracleSpec {
}
... on DataSourceDefinitionExternal {
sourceType {
... on EthCallSpec {
abi
args
method
requiredConfirmations
address
normalisers {
name
expression
}
trigger {
trigger {
... on EthTimeTrigger {
initial
every
until
}
}
}
filters {
key {
name
type
numberDecimalPlaces
}
conditions {
value
operator
}
}
}
... on DataSourceSpecConfiguration {
signers {
signer {
+34 -3
View File
@@ -5,19 +5,19 @@ import * as Apollo from '@apollo/client';
const defaultOptions = {} as const;
export type ExplorerOracleDataConnectionFragment = { __typename?: 'OracleSpec', dataConnection: { __typename?: 'OracleDataConnection', edges?: Array<{ __typename?: 'OracleDataEdge', node: { __typename?: 'OracleData', externalData: { __typename?: 'ExternalData', data: { __typename?: 'Data', matchedSpecIds?: Array<string> | null, broadcastAt: any, signers?: Array<{ __typename?: 'Signer', signer: { __typename?: 'ETHAddress', address?: string | null } | { __typename?: 'PubKey', key?: string | null } }> | null, data?: Array<{ __typename?: 'Property', name: string, value: string }> | null } } } } | null> | null } };
export type ExplorerOracleDataSourceFragment = { __typename?: 'OracleSpec', dataSourceSpec: { __typename?: 'ExternalDataSourceSpec', spec: { __typename?: 'DataSourceSpec', id: string, createdAt: any, updatedAt?: any | null, status: Types.DataSourceSpecStatus, data: { __typename?: 'DataSourceDefinition', sourceType: { __typename?: 'DataSourceDefinitionExternal', sourceType: { __typename?: 'DataSourceSpecConfiguration', signers?: Array<{ __typename?: 'Signer', signer: { __typename?: 'ETHAddress', address?: string | null } | { __typename?: 'PubKey', key?: string | null } }> | null, filters?: Array<{ __typename?: 'Filter', key: { __typename?: 'PropertyKey', name?: string | null, type: Types.PropertyKeyType, numberDecimalPlaces?: number | null }, conditions?: Array<{ __typename?: 'Condition', value?: string | null, operator: Types.ConditionOperator }> | null }> | null } | { __typename?: 'EthCallSpec' } } | { __typename?: 'DataSourceDefinitionInternal', sourceType: { __typename?: 'DataSourceSpecConfigurationTime', conditions: Array<{ __typename?: 'Condition', value?: string | null, operator: Types.ConditionOperator } | null> } | { __typename?: 'DataSourceSpecConfigurationTimeTrigger' } } } } }, dataConnection: { __typename?: 'OracleDataConnection', edges?: Array<{ __typename?: 'OracleDataEdge', node: { __typename?: 'OracleData', externalData: { __typename?: 'ExternalData', data: { __typename?: 'Data', matchedSpecIds?: Array<string> | null, broadcastAt: any, signers?: Array<{ __typename?: 'Signer', signer: { __typename?: 'ETHAddress', address?: string | null } | { __typename?: 'PubKey', key?: string | null } }> | null, data?: Array<{ __typename?: 'Property', name: string, value: string }> | null } } } } | null> | null } };
export type ExplorerOracleDataSourceFragment = { __typename?: 'OracleSpec', dataSourceSpec: { __typename?: 'ExternalDataSourceSpec', spec: { __typename?: 'DataSourceSpec', id: string, createdAt: any, updatedAt?: any | null, status: Types.DataSourceSpecStatus, data: { __typename?: 'DataSourceDefinition', sourceType: { __typename?: 'DataSourceDefinitionExternal', sourceType: { __typename?: 'DataSourceSpecConfiguration', signers?: Array<{ __typename?: 'Signer', signer: { __typename?: 'ETHAddress', address?: string | null } | { __typename?: 'PubKey', key?: string | null } }> | null, filters?: Array<{ __typename?: 'Filter', key: { __typename?: 'PropertyKey', name?: string | null, type: Types.PropertyKeyType, numberDecimalPlaces?: number | null }, conditions?: Array<{ __typename?: 'Condition', value?: string | null, operator: Types.ConditionOperator }> | null }> | null } | { __typename?: 'EthCallSpec', abi?: Array<string> | null, args?: Array<string> | null, method: string, requiredConfirmations: number, address: string, normalisers?: Array<{ __typename?: 'Normaliser', name: string, expression: string }> | null, trigger: { __typename?: 'EthCallTrigger', trigger: { __typename?: 'EthTimeTrigger', initial?: any | null, every?: number | null, until?: any | null } }, filters?: Array<{ __typename?: 'Filter', key: { __typename?: 'PropertyKey', name?: string | null, type: Types.PropertyKeyType, numberDecimalPlaces?: number | null }, conditions?: Array<{ __typename?: 'Condition', value?: string | null, operator: Types.ConditionOperator }> | null }> | null } } | { __typename?: 'DataSourceDefinitionInternal', sourceType: { __typename?: 'DataSourceSpecConfigurationTime', conditions: Array<{ __typename?: 'Condition', value?: string | null, operator: Types.ConditionOperator } | null> } | { __typename?: 'DataSourceSpecConfigurationTimeTrigger' } } } } }, dataConnection: { __typename?: 'OracleDataConnection', edges?: Array<{ __typename?: 'OracleDataEdge', node: { __typename?: 'OracleData', externalData: { __typename?: 'ExternalData', data: { __typename?: 'Data', matchedSpecIds?: Array<string> | null, broadcastAt: any, signers?: Array<{ __typename?: 'Signer', signer: { __typename?: 'ETHAddress', address?: string | null } | { __typename?: 'PubKey', key?: string | null } }> | null, data?: Array<{ __typename?: 'Property', name: string, value: string }> | null } } } } | null> | null } };
export type ExplorerOracleSpecsQueryVariables = Types.Exact<{ [key: string]: never; }>;
export type ExplorerOracleSpecsQuery = { __typename?: 'Query', oracleSpecsConnection?: { __typename?: 'OracleSpecsConnection', pageInfo: { __typename?: 'PageInfo', hasNextPage: boolean }, edges?: Array<{ __typename?: 'OracleSpecEdge', node: { __typename?: 'OracleSpec', dataSourceSpec: { __typename?: 'ExternalDataSourceSpec', spec: { __typename?: 'DataSourceSpec', id: string, createdAt: any, updatedAt?: any | null, status: Types.DataSourceSpecStatus, data: { __typename?: 'DataSourceDefinition', sourceType: { __typename?: 'DataSourceDefinitionExternal', sourceType: { __typename?: 'DataSourceSpecConfiguration', signers?: Array<{ __typename?: 'Signer', signer: { __typename?: 'ETHAddress', address?: string | null } | { __typename?: 'PubKey', key?: string | null } }> | null, filters?: Array<{ __typename?: 'Filter', key: { __typename?: 'PropertyKey', name?: string | null, type: Types.PropertyKeyType, numberDecimalPlaces?: number | null }, conditions?: Array<{ __typename?: 'Condition', value?: string | null, operator: Types.ConditionOperator }> | null }> | null } | { __typename?: 'EthCallSpec' } } | { __typename?: 'DataSourceDefinitionInternal', sourceType: { __typename?: 'DataSourceSpecConfigurationTime', conditions: Array<{ __typename?: 'Condition', value?: string | null, operator: Types.ConditionOperator } | null> } | { __typename?: 'DataSourceSpecConfigurationTimeTrigger' } } } } }, dataConnection: { __typename?: 'OracleDataConnection', edges?: Array<{ __typename?: 'OracleDataEdge', node: { __typename?: 'OracleData', externalData: { __typename?: 'ExternalData', data: { __typename?: 'Data', matchedSpecIds?: Array<string> | null, broadcastAt: any, signers?: Array<{ __typename?: 'Signer', signer: { __typename?: 'ETHAddress', address?: string | null } | { __typename?: 'PubKey', key?: string | null } }> | null, data?: Array<{ __typename?: 'Property', name: string, value: string }> | null } } } } | null> | null } } } | null> | null } | null };
export type ExplorerOracleSpecsQuery = { __typename?: 'Query', oracleSpecsConnection?: { __typename?: 'OracleSpecsConnection', pageInfo: { __typename?: 'PageInfo', hasNextPage: boolean }, edges?: Array<{ __typename?: 'OracleSpecEdge', node: { __typename?: 'OracleSpec', dataSourceSpec: { __typename?: 'ExternalDataSourceSpec', spec: { __typename?: 'DataSourceSpec', id: string, createdAt: any, updatedAt?: any | null, status: Types.DataSourceSpecStatus, data: { __typename?: 'DataSourceDefinition', sourceType: { __typename?: 'DataSourceDefinitionExternal', sourceType: { __typename?: 'DataSourceSpecConfiguration', signers?: Array<{ __typename?: 'Signer', signer: { __typename?: 'ETHAddress', address?: string | null } | { __typename?: 'PubKey', key?: string | null } }> | null, filters?: Array<{ __typename?: 'Filter', key: { __typename?: 'PropertyKey', name?: string | null, type: Types.PropertyKeyType, numberDecimalPlaces?: number | null }, conditions?: Array<{ __typename?: 'Condition', value?: string | null, operator: Types.ConditionOperator }> | null }> | null } | { __typename?: 'EthCallSpec', abi?: Array<string> | null, args?: Array<string> | null, method: string, requiredConfirmations: number, address: string, normalisers?: Array<{ __typename?: 'Normaliser', name: string, expression: string }> | null, trigger: { __typename?: 'EthCallTrigger', trigger: { __typename?: 'EthTimeTrigger', initial?: any | null, every?: number | null, until?: any | null } }, filters?: Array<{ __typename?: 'Filter', key: { __typename?: 'PropertyKey', name?: string | null, type: Types.PropertyKeyType, numberDecimalPlaces?: number | null }, conditions?: Array<{ __typename?: 'Condition', value?: string | null, operator: Types.ConditionOperator }> | null }> | null } } | { __typename?: 'DataSourceDefinitionInternal', sourceType: { __typename?: 'DataSourceSpecConfigurationTime', conditions: Array<{ __typename?: 'Condition', value?: string | null, operator: Types.ConditionOperator } | null> } | { __typename?: 'DataSourceSpecConfigurationTimeTrigger' } } } } }, dataConnection: { __typename?: 'OracleDataConnection', edges?: Array<{ __typename?: 'OracleDataEdge', node: { __typename?: 'OracleData', externalData: { __typename?: 'ExternalData', data: { __typename?: 'Data', matchedSpecIds?: Array<string> | null, broadcastAt: any, signers?: Array<{ __typename?: 'Signer', signer: { __typename?: 'ETHAddress', address?: string | null } | { __typename?: 'PubKey', key?: string | null } }> | null, data?: Array<{ __typename?: 'Property', name: string, value: string }> | null } } } } | null> | null } } } | null> | null } | null };
export type ExplorerOracleSpecByIdQueryVariables = Types.Exact<{
id: Types.Scalars['ID'];
}>;
export type ExplorerOracleSpecByIdQuery = { __typename?: 'Query', oracleSpec?: { __typename?: 'OracleSpec', dataSourceSpec: { __typename?: 'ExternalDataSourceSpec', spec: { __typename?: 'DataSourceSpec', id: string, createdAt: any, updatedAt?: any | null, status: Types.DataSourceSpecStatus, data: { __typename?: 'DataSourceDefinition', sourceType: { __typename?: 'DataSourceDefinitionExternal', sourceType: { __typename?: 'DataSourceSpecConfiguration', signers?: Array<{ __typename?: 'Signer', signer: { __typename?: 'ETHAddress', address?: string | null } | { __typename?: 'PubKey', key?: string | null } }> | null, filters?: Array<{ __typename?: 'Filter', key: { __typename?: 'PropertyKey', name?: string | null, type: Types.PropertyKeyType, numberDecimalPlaces?: number | null }, conditions?: Array<{ __typename?: 'Condition', value?: string | null, operator: Types.ConditionOperator }> | null }> | null } | { __typename?: 'EthCallSpec' } } | { __typename?: 'DataSourceDefinitionInternal', sourceType: { __typename?: 'DataSourceSpecConfigurationTime', conditions: Array<{ __typename?: 'Condition', value?: string | null, operator: Types.ConditionOperator } | null> } | { __typename?: 'DataSourceSpecConfigurationTimeTrigger' } } } } }, dataConnection: { __typename?: 'OracleDataConnection', edges?: Array<{ __typename?: 'OracleDataEdge', node: { __typename?: 'OracleData', externalData: { __typename?: 'ExternalData', data: { __typename?: 'Data', matchedSpecIds?: Array<string> | null, broadcastAt: any, signers?: Array<{ __typename?: 'Signer', signer: { __typename?: 'ETHAddress', address?: string | null } | { __typename?: 'PubKey', key?: string | null } }> | null, data?: Array<{ __typename?: 'Property', name: string, value: string }> | null } } } } | null> | null } } | null };
export type ExplorerOracleSpecByIdQuery = { __typename?: 'Query', oracleSpec?: { __typename?: 'OracleSpec', dataSourceSpec: { __typename?: 'ExternalDataSourceSpec', spec: { __typename?: 'DataSourceSpec', id: string, createdAt: any, updatedAt?: any | null, status: Types.DataSourceSpecStatus, data: { __typename?: 'DataSourceDefinition', sourceType: { __typename?: 'DataSourceDefinitionExternal', sourceType: { __typename?: 'DataSourceSpecConfiguration', signers?: Array<{ __typename?: 'Signer', signer: { __typename?: 'ETHAddress', address?: string | null } | { __typename?: 'PubKey', key?: string | null } }> | null, filters?: Array<{ __typename?: 'Filter', key: { __typename?: 'PropertyKey', name?: string | null, type: Types.PropertyKeyType, numberDecimalPlaces?: number | null }, conditions?: Array<{ __typename?: 'Condition', value?: string | null, operator: Types.ConditionOperator }> | null }> | null } | { __typename?: 'EthCallSpec', abi?: Array<string> | null, args?: Array<string> | null, method: string, requiredConfirmations: number, address: string, normalisers?: Array<{ __typename?: 'Normaliser', name: string, expression: string }> | null, trigger: { __typename?: 'EthCallTrigger', trigger: { __typename?: 'EthTimeTrigger', initial?: any | null, every?: number | null, until?: any | null } }, filters?: Array<{ __typename?: 'Filter', key: { __typename?: 'PropertyKey', name?: string | null, type: Types.PropertyKeyType, numberDecimalPlaces?: number | null }, conditions?: Array<{ __typename?: 'Condition', value?: string | null, operator: Types.ConditionOperator }> | null }> | null } } | { __typename?: 'DataSourceDefinitionInternal', sourceType: { __typename?: 'DataSourceSpecConfigurationTime', conditions: Array<{ __typename?: 'Condition', value?: string | null, operator: Types.ConditionOperator } | null> } | { __typename?: 'DataSourceSpecConfigurationTimeTrigger' } } } } }, dataConnection: { __typename?: 'OracleDataConnection', edges?: Array<{ __typename?: 'OracleDataEdge', node: { __typename?: 'OracleData', externalData: { __typename?: 'ExternalData', data: { __typename?: 'Data', matchedSpecIds?: Array<string> | null, broadcastAt: any, signers?: Array<{ __typename?: 'Signer', signer: { __typename?: 'ETHAddress', address?: string | null } | { __typename?: 'PubKey', key?: string | null } }> | null, data?: Array<{ __typename?: 'Property', name: string, value: string }> | null } } } } | null> | null } } | null };
export const ExplorerOracleDataConnectionFragmentDoc = gql`
fragment ExplorerOracleDataConnection on OracleSpec {
@@ -72,6 +72,37 @@ export const ExplorerOracleDataSourceFragmentDoc = gql`
}
... on DataSourceDefinitionExternal {
sourceType {
... on EthCallSpec {
abi
args
method
requiredConfirmations
address
normalisers {
name
expression
}
trigger {
trigger {
... on EthTimeTrigger {
initial
every
until
}
}
}
filters {
key {
name
type
numberDecimalPlaces
}
conditions {
value
operator
}
}
}
... on DataSourceSpecConfiguration {
signers {
signer {
+1
View File
@@ -22,6 +22,7 @@ NX_WALLETCONNECT_PROJECT_ID=fe8091dc35738863e509fc4947525c72
NX_VEGA_REST_URL=http://localhost:3008/api/v2/
NX_SUCCESSOR_MARKETS=true
NX_PRODUCT_PERPETUALS=true
NX_UPDATE_MARKET_STATE=true
NX_VEGA_EXPLORER_URL=https://explorer.fairground.wtf
NX_CHROME_EXTENSION_URL=https://chrome.google.com/webstore/detail/vega-wallet-fairground/nmmjkiafpmphlikhefgjbblebfgclikn
@@ -1,21 +0,0 @@
{
"rationale": {
"title": "Add USDT Coin (USDT)",
"description": "Proposal to add USDT Coin (USDT) as an asset"
},
"terms": {
"newAsset": {
"changes": {
"name": "USDT Coin",
"symbol": "USDT",
"decimals": "18",
"quantum": "1",
"erc20": {
"contractAddress": "0xb404c51bbc10dcbe948077f18a4b8e553d160084"
}
}
},
"closingTimestamp": 1662374250,
"enactmentTimestamp": 1662460650
}
}
@@ -0,0 +1,16 @@
{
"rationale": {
"title": "Market resume test",
"description": "E2E test for market resume proposal"
},
"terms": {
"updateMarketState": {
"changes": {
"marketId": "b33bb4157e12355db22e41f277ddd0c10104dec29a4d6960bbcb96d186c40cbd",
"updateType": "MARKET_STATE_UPDATE_TYPE_RESUME"
}
},
"closingTimestamp": 0,
"enactmentTimestamp": 0
}
}
@@ -0,0 +1,16 @@
{
"rationale": {
"title": "Market suspended test",
"description": "E2E test for market suspended proposal"
},
"terms": {
"updateMarketState": {
"changes": {
"marketId": "",
"updateType": "MARKET_STATE_UPDATE_TYPE_SUSPEND"
}
},
"closingTimestamp": 0,
"enactmentTimestamp": 0
}
}
@@ -0,0 +1,17 @@
{
"rationale": {
"title": "Market terminate test",
"description": "E2E test for market terminate proposal"
},
"terms": {
"updateMarketState": {
"changes": {
"marketId": "",
"updateType": "MARKET_STATE_UPDATE_TYPE_TERMINATE",
"price": "100"
}
},
"closingTimestamp": 0,
"enactmentTimestamp": 0
}
}
@@ -1,85 +0,0 @@
{
"instrument": {
"code": "Token.24h",
"future": {
"quoteName": "fBTC",
"dataSourceSpecForSettlementData": {
"external": {
"oracle": {
"signers": [
{
"pubKey": {
"key": "70d14a321e02e71992fd115563df765000ccc4775cbe71a0e2f9ff5a3b9dc680"
}
}
],
"filters": [
{
"key": {
"name": "prices.BTC.value",
"type": "TYPE_INTEGER"
},
"conditions": [
{
"operator": "OPERATOR_GREATER_THAN",
"value": "0"
}
]
}
]
}
}
},
"dataSourceSpecForTradingTermination": {
"external": {
"oracle": {
"signers": [
{
"pubKey": {
"key": "70d14a321e02e71992fd115563df765000ccc4775cbe71a0e2f9ff5a3b9dc680"
}
}
],
"filters": [
{
"key": {
"name": "trading.terminated.ETH5",
"type": "TYPE_BOOLEAN"
},
"conditions": [
{
"operator": "OPERATOR_GREATER_THAN_OR_EQUAL",
"value": "1648684800000000000"
}
]
}
]
}
}
},
"dataSourceSpecBinding": {
"settlementDataProperty": "prices.BTC.value",
"tradingTerminationProperty": "trading.terminated.ETH5"
}
}
},
"metadata": ["sector:energy", "sector:food", "source:docs.vega.xyz"],
"priceMonitoringParameters": {
"triggers": [
{
"horizon": "43200",
"probability": "0.9999999",
"auctionExtension": "600"
}
]
},
"logNormal": {
"tau": 0.0001140771161,
"riskAversionParameter": 0.001,
"params": {
"mu": 0,
"r": 0.016,
"sigma": 0.3
}
}
}
@@ -60,6 +60,17 @@ describe(
before('connect wallets and set approval limit', function () {
cy.visit('/');
ethereumWalletConnect();
cy.createMarket();
navigateTo(navigation.proposals);
cy.getByTestId('closed-proposals').within(() => {
cy.contains('Add Lorem Ipsum market')
.parentsUntil(proposalListItem)
.last()
.within(() => {
cy.getByTestId(viewProposalButton).click();
});
});
getProposalInformationFromTable('ID').invoke('text').as('parentMarketId');
});
beforeEach('visit proposals tab', function () {
@@ -298,9 +309,6 @@ describe(
});
it('Able to see successor market details with new and updated values', function () {
cy.createMarket();
cy.reload();
waitForSpinner();
cy.getByTestId('closed-proposals').within(() => {
cy.contains('Add Lorem Ipsum market')
.parentsUntil(proposalListItem)
@@ -309,14 +317,9 @@ describe(
cy.getByTestId(viewProposalButton).click();
});
});
getProposalInformationFromTable('ID')
.invoke('text')
.as('parentMarketId')
.then(() => {
cy.VegaWalletSubmitProposal(
createSuccessorMarketProposalTxBody(this.parentMarketId)
);
});
cy.VegaWalletSubmitProposal(
createSuccessorMarketProposalTxBody(this.parentMarketId)
);
navigateTo(navigation.proposals);
cy.reload();
getProposalFromTitle('Test successor market proposal details').within(
@@ -434,5 +437,87 @@ describe(
'Minimum Probability Of Trading LP Orders'
).should('contain.text', '1e-8');
});
it('Able to see suspended market proposal', function () {
const proposalPath = 'src/fixtures/proposals/suspend-market-raw.json';
const enactmentTimestamp = createTenDigitUnixTimeStampForSpecifiedDays(3);
const closingTimestamp = createTenDigitUnixTimeStampForSpecifiedDays(2);
submitUniqueRawProposal({
proposalBody: proposalPath,
updateMarketId: this.parentMarketId,
enactmentTimestamp: enactmentTimestamp,
closingTimestamp: closingTimestamp,
});
getProposalFromTitle('Market suspended test').within(() => {
cy.getByTestId(marketProposalType).should(
'have.text',
'Suspend market'
);
cy.getByTestId(viewProposalButton).click();
});
cy.getByTestId(marketProposalType).should('have.text', 'Suspend market');
cy.getByTestId(marketDataToggle).click();
cy.getByTestId('proposal-update-market-state').within(() => {
getProposalInformationFromTable('Market ID')
.invoke('text')
.and('eq', this.parentMarketId);
});
});
it('Able to see resume market proposal', function () {
const proposalPath = 'src/fixtures/proposals/resume-market-raw.json';
const enactmentTimestamp = createTenDigitUnixTimeStampForSpecifiedDays(3);
const closingTimestamp = createTenDigitUnixTimeStampForSpecifiedDays(2);
submitUniqueRawProposal({
proposalBody: proposalPath,
updateMarketId: this.parentMarketId,
enactmentTimestamp: enactmentTimestamp,
closingTimestamp: closingTimestamp,
});
getProposalFromTitle('Market resume test').within(() => {
cy.getByTestId(marketProposalType).should('have.text', 'Resume market');
cy.getByTestId(viewProposalButton).click();
});
cy.getByTestId(marketProposalType).should('have.text', 'Resume market');
cy.getByTestId(marketDataToggle).click();
cy.getByTestId('proposal-update-market-state').within(() => {
getProposalInformationFromTable('Market ID')
.invoke('text')
.and('eq', this.parentMarketId);
});
});
it('Able to see terminate market proposal', function () {
const proposalPath = 'src/fixtures/proposals/terminate-market-raw.json';
const enactmentTimestamp = createTenDigitUnixTimeStampForSpecifiedDays(3);
const closingTimestamp = createTenDigitUnixTimeStampForSpecifiedDays(2);
submitUniqueRawProposal({
proposalBody: proposalPath,
updateMarketId: this.parentMarketId,
enactmentTimestamp: enactmentTimestamp,
closingTimestamp: closingTimestamp,
});
getProposalFromTitle('Market terminate test').within(() => {
cy.getByTestId(marketProposalType).should(
'have.text',
'Terminate market'
);
cy.getByTestId(viewProposalButton).click();
});
cy.getByTestId(marketProposalType).should(
'have.text',
'Terminate market'
);
cy.getByTestId(marketDataToggle).click();
cy.getByTestId('proposal-update-market-state').within(() => {
getProposalInformationFromTable('Market ID')
.invoke('text')
.and('eq', this.parentMarketId);
getProposalDetailsValue('Termination Price').should(
'contain.text',
'0.001 fUSDC'
);
});
});
}
);
@@ -11,7 +11,6 @@ import {
waitForBeginningOfEpoch,
} from '../../support/staking.functions';
import { previousEpochData } from '../../fixtures/mocks/previous-epoch';
import { chainIdQuery, statisticsQuery } from '@vegaprotocol/mock';
const guideLink = 'staking-guide-link';
const validatorTitle = 'validator-node-title';
@@ -38,17 +37,11 @@ const txTimeout = Cypress.env('txTimeout');
context('Validators Page - verify elements on page', function () {
before('navigate to validators page', () => {
cy.mockGQL((req) => {
aliasGQLQuery(req, 'ChainId', chainIdQuery());
aliasGQLQuery(req, 'Statistics', statisticsQuery());
});
cy.mockChainId();
cy.visit('/validators');
});
beforeEach(() => {
cy.mockGQL((req) => {
aliasGQLQuery(req, 'ChainId', chainIdQuery());
aliasGQLQuery(req, 'Statistics', statisticsQuery());
});
cy.mockChainId();
});
describe('with wallets disconnected', { tags: '@smoke' }, function () {
@@ -189,10 +182,7 @@ context('Validators Page - verify elements on page', function () {
{ tags: '@smoke' },
function () {
before('connect wallets and click on validator', function () {
cy.mockGQL((req) => {
aliasGQLQuery(req, 'ChainId', chainIdQuery());
aliasGQLQuery(req, 'Statistics', statisticsQuery());
});
cy.mockChainId();
cy.visit('/validators');
cy.connectVegaWallet();
clickOnValidatorFromList(0);
@@ -4,8 +4,6 @@ import {
vegaWalletFaucetAssetsWithoutCheck,
vegaWalletTeardown,
} from '../../support/wallet-functions';
import { aliasGQLQuery } from '@vegaprotocol/cypress';
import { chainIdQuery, statisticsQuery } from '@vegaprotocol/mock';
const walletContainer = 'aside [data-testid="vega-wallet"]';
const walletHeader = '[data-testid="wallet-header"] h1';
@@ -88,10 +86,7 @@ context(
describe('when vega wallet connected', function () {
before('connect vega wallet', function () {
cy.mockGQL((req) => {
aliasGQLQuery(req, 'ChainId', chainIdQuery());
aliasGQLQuery(req, 'Statistics', statisticsQuery());
});
cy.mockChainId();
cy.visit('/');
cy.wait('@ChainId');
cy.connectVegaWallet();
@@ -276,10 +271,7 @@ context(
];
before('faucet assets to connected vega wallet', function () {
cy.mockGQL((req) => {
aliasGQLQuery(req, 'ChainId', chainIdQuery());
aliasGQLQuery(req, 'Statistics', statisticsQuery());
});
cy.mockChainId();
for (const { id, amount } of assets) {
vegaWalletFaucetAssetsWithoutCheck(id, amount, vegaWalletPublicKey);
}
@@ -54,6 +54,7 @@ export function submitUniqueRawProposal(proposalFields: {
proposalBody?: string;
proposalTitle?: string;
proposalDescription?: string;
updateMarketId?: string;
closingTimestamp?: number;
enactmentTimestamp?: number;
submit?: boolean;
@@ -71,6 +72,10 @@ export function submitUniqueRawProposal(proposalFields: {
if (proposalFields.proposalDescription) {
rawProposal.rationale.description = proposalFields.proposalDescription;
}
if (proposalFields.updateMarketId) {
rawProposal.terms.updateMarketState.changes.marketId =
proposalFields.updateMarketId;
}
if (proposalFields.closingTimestamp) {
rawProposal.terms.closingTimestamp = proposalFields.closingTimestamp;
} else if (
+1 -6
View File
@@ -9,8 +9,6 @@ import './wallet-functions.ts';
import './proposal.functions.ts';
import 'cypress-mochawesome-reporter/register';
import registerCypressGrep from '@cypress/grep';
import { aliasGQLQuery } from '@vegaprotocol/cypress';
import { chainIdQuery, statisticsQuery } from '@vegaprotocol/mock';
import { turnTelemetryOff } from './common.functions.ts';
registerCypressGrep();
@@ -29,10 +27,7 @@ before(() => {
// // Ensuring the telemetry modal doesn't disrupt the tests
turnTelemetryOff();
// Mock chainId fetch which happens on every page for wallet connection
cy.mockGQL((req) => {
aliasGQLQuery(req, 'ChainId', chainIdQuery());
aliasGQLQuery(req, 'Statistics', statisticsQuery());
});
cy.mockChainId();
// Self stake validators so they are displayed
cy.validatorsSelfDelegate();
});
+2 -2
View File
@@ -26,11 +26,11 @@ import {
} from '@vegaprotocol/web3';
import { Web3Provider } from '@vegaprotocol/web3';
import { VegaWalletDialogs } from './components/vega-wallet-dialogs';
import { VegaWalletProvider } from '@vegaprotocol/wallet';
import {
useVegaTransactionManager,
useVegaTransactionUpdater,
VegaWalletProvider,
} from '@vegaprotocol/wallet';
} from '@vegaprotocol/web3';
import { AsyncRenderer } from '@vegaprotocol/ui-toolkit';
import { useEthereumConfig } from '@vegaprotocol/web3';
import {
@@ -4,7 +4,7 @@ import {
getProposalDialogTitle,
} from '@vegaprotocol/proposals';
import type { ProposalEventFieldsFragment } from '@vegaprotocol/proposals';
import type { DialogProps } from '@vegaprotocol/wallet';
import type { DialogProps } from '@vegaprotocol/proposals';
interface ProposalFormTransactionDialogProps {
finalizedProposal: ProposalEventFieldsFragment | null;
@@ -6,7 +6,7 @@ import { ConnectToVega } from '../../../../components/connect-to-vega';
import { VoteButtonsContainer } from './vote-buttons';
import { SubHeading } from '../../../../components/heading';
import type { VoteValue } from '@vegaprotocol/types';
import type { DialogProps, VegaTxState } from '@vegaprotocol/wallet';
import type { DialogProps, VegaTxState } from '@vegaprotocol/proposals';
import type { ProposalFieldsFragment } from '../../proposals/__generated__/Proposals';
import type { ProposalQuery } from '../../proposal/__generated__/Proposal';
import type { VoteState } from './use-user-vote';
@@ -1,7 +1,7 @@
import { render, screen } from '@testing-library/react';
import { VoteTransactionDialog } from './vote-transaction-dialog';
import { VoteState } from './use-user-vote';
import { VegaTxStatus } from '@vegaprotocol/wallet';
import { VegaTxStatus } from '@vegaprotocol/proposals';
describe('VoteTransactionDialog', () => {
const mockTransactionDialog = jest.fn(({ title, content }) => (
@@ -17,7 +17,7 @@ import { VoteState } from './use-user-vote';
import { ProposalMinRequirements, ProposalUserAction } from '../shared';
import { VoteTransactionDialog } from './vote-transaction-dialog';
import { useVoteButtonsQuery } from './__generated__/Stake';
import type { DialogProps, VegaTxState } from '@vegaprotocol/wallet';
import type { DialogProps, VegaTxState } from '@vegaprotocol/proposals';
interface VoteButtonsContainerProps {
voteState: VoteState | null;
@@ -1,6 +1,6 @@
import { t } from '@vegaprotocol/i18n';
import { VoteState } from './use-user-vote';
import type { DialogProps, VegaTxState } from '@vegaprotocol/wallet';
import type { DialogProps, VegaTxState } from '@vegaprotocol/proposals';
interface VoteTransactionDialogProps {
voteState: VoteState;
@@ -64,48 +64,6 @@ describe('accounts', { tags: '@smoke' }, () => {
cy.getByTestId('Collateral').click({ force: true });
});
it('should open asset details dialog when clicked on symbol', () => {
// 7001-COLL-008
// 6501-ASSE-001
// 6501-ASSE-002
// 6501-ASSE-003
// 6501-ASSE-004
// 6501-ASSE-005
// 6501-ASSE-006
// 6501-ASSE-007
// 6501-ASSE-008
// 6501-ASSE-009
// 6501-ASSE-010
// 6501-ASSE-011
// 6501-ASSE-012
// 6501-ASSE-013
const titles = [
'ID',
'Type',
'Name',
'Symbol',
'Decimals',
'Quantum',
'Status',
'Contract address',
'Withdrawal threshold',
'Lifetime limit',
'Infrastructure fee account balance',
'Global reward pool account balance',
'Maker paid fees account balance',
'Maker received fees account balance',
'Liquidity provision fee reward account balance',
'Market proposer reward account balance',
];
cy.get('[col-id="asset.symbol"]').contains('tEURO').click();
cy.get('[data-testid$="_label"]').should('have.length', 16);
cy.get('[data-testid$="_label"]').each((element, index) => {
cy.wrap(element).should('have.text', titles[index]);
});
cy.getByTestId(dialogClose).click();
cy.getByTestId(dialogClose).should('not.exist');
});
it('should open usage breakdown dialog when clicked on used', () => {
// 7001-COLL-009
cy.get('[col-id="used"]').contains('1.01').click();
+1 -4
View File
@@ -7,7 +7,6 @@ import {
assetQuery,
assetsQuery,
candlesQuery,
chainIdQuery,
chartQuery,
depositsQuery,
estimateFeesQuery,
@@ -25,7 +24,6 @@ import {
estimatePositionQuery,
positionsQuery,
proposalListQuery,
statisticsQuery,
tradesQuery,
withdrawalsQuery,
protocolUpgradeProposalsQuery,
@@ -91,8 +89,6 @@ const mockTradingPage = (
tradingMode?: Schema.MarketTradingMode,
trigger?: Schema.AuctionTrigger
) => {
aliasGQLQuery(req, 'ChainId', chainIdQuery());
aliasGQLQuery(req, 'NodeCheck', statisticsQuery());
aliasGQLQuery(req, 'NodeGuard', nodeGuardQuery());
aliasGQLQuery(
req,
@@ -218,6 +214,7 @@ export const addMockTradingPage = () => {
trigger,
oracleStatus
) => {
cy.mockChainId();
cy.mockGQL((req) => {
mockTradingPage(req, state, tradingMode, trigger);
});
+1
View File
@@ -15,6 +15,7 @@ NX_ANNOUNCEMENTS_CONFIG_URL=https://raw.githubusercontent.com/vegaprotocol/annou
NX_VEGA_INCIDENT_URL=https://blog.vega.xyz/tagged/vega-incident-reports
NX_CHROME_EXTENSION_URL=https://chrome.google.com/webstore/detail/vega-wallet-fairground/nmmjkiafpmphlikhefgjbblebfgclikn
NX_MOZILLA_EXTENSION_URL=https://addons.mozilla.org/firefox/addon/vega-wallet-fairground
NX_ORACLE_PROOFS_URL=https://raw.githubusercontent.com/vegaprotocol/well-known/main/__generated__/oracle-proofs.json
# Cosmic elevator flags
NX_SUCCESSOR_MARKETS=true
@@ -10,12 +10,10 @@ import classNames from 'classnames';
import { Navigate, useSearchParams } from 'react-router-dom';
import { useEffect, useRef, useState } from 'react';
import { Button } from './buttons';
import {
useTransactionEventSubscription,
useVegaWallet,
} from '@vegaprotocol/wallet';
import { useVegaWallet } from '@vegaprotocol/wallet';
import { useReferral } from './hooks/use-referral';
import { Routes } from '../../lib/links';
import { useTransactionEventSubscription } from '@vegaprotocol/web3';
export const ApplyCodeForm = () => {
const [status, setStatus] = useState<
@@ -7,6 +7,8 @@ import * as Schema from '@vegaprotocol/types';
import { HeaderStat } from '../header';
import { useCallback, useRef, useState } from 'react';
import * as constants from '../constants';
import { DocsLinks } from '@vegaprotocol/environment';
import { ExternalLink } from '@vegaprotocol/ui-toolkit';
export const MarketState = ({ market }: { market: Market | null }) => {
const [marketState, setMarketState] = useState<Schema.MarketState | null>(
@@ -90,5 +92,20 @@ const getMarketStateTooltip = (state: Schema.MarketState | null) => {
);
}
if (state === Schema.MarketState.STATE_SUSPENDED_VIA_GOVERNANCE) {
return (
<p>
{t(
`This market has been suspended via a governance vote and can be resumed or terminated by further votes.`
)}
{DocsLinks && (
<ExternalLink href={DocsLinks.MARKET_LIFECYCLE} className="ml-1">
{t('Find out more')}
</ExternalLink>
)}
</p>
);
}
return undefined;
};
@@ -1,6 +1,6 @@
import { useVegaWallet } from '@vegaprotocol/wallet';
import { WithdrawFormContainer } from '@vegaprotocol/withdraws';
import { useVegaTransactionStore } from '@vegaprotocol/wallet';
import { useVegaTransactionStore } from '@vegaprotocol/web3';
export const WithdrawContainer = ({ assetId }: { assetId?: string }) => {
const { pubKey } = useVegaWallet();
+1
View File
@@ -5,6 +5,7 @@ const MARKET_TEMPLATE = [
MarketState.STATE_ACTIVE,
MarketState.STATE_SUSPENDED,
MarketState.STATE_PENDING,
MarketState.STATE_SUSPENDED_VIA_GOVERNANCE,
];
export const isMarketActive = (state: MarketState) => {
+4 -2
View File
@@ -4,10 +4,12 @@ import type { AppProps } from 'next/app';
import { t } from '@vegaprotocol/i18n';
import {
useEagerConnect as useVegaEagerConnect,
useVegaTransactionManager,
useVegaTransactionUpdater,
useVegaWallet,
} from '@vegaprotocol/wallet';
import {
useVegaTransactionManager,
useVegaTransactionUpdater,
} from '@vegaprotocol/web3';
import {
useEagerConnect as useEthereumEagerConnect,
useEthTransactionManager,
+2 -1
View File
@@ -7,7 +7,8 @@ import {
} from '@vegaprotocol/network-parameters';
import { useDataProvider } from '@vegaprotocol/data-provider';
import type { Transfer } from '@vegaprotocol/wallet';
import { useVegaTransactionStore, useVegaWallet } from '@vegaprotocol/wallet';
import { useVegaTransactionStore } from '@vegaprotocol/web3';
import { useVegaWallet } from '@vegaprotocol/wallet';
import { useCallback, useMemo } from 'react';
import { accountsDataProvider } from './accounts-data-provider';
import { TransferForm } from './transfer-form';
@@ -62,6 +62,20 @@ const WrappedAssetDetailsDialog = ({ assetId }: { assetId: string }) => (
);
describe('AssetDetailsDialog', () => {
// 7001-COLL-008
// 6501-ASSE-001
// 6501-ASSE-002
// 6501-ASSE-003
// 6501-ASSE-004
// 6501-ASSE-005
// 6501-ASSE-006
// 6501-ASSE-007
// 6501-ASSE-008
// 6501-ASSE-009
// 6501-ASSE-010
// 6501-ASSE-011
// 6501-ASSE-012
// 6501-ASSE-013
it('should show no data message given unknown asset symbol', async () => {
render(<WrappedAssetDetailsDialog assetId={'UNKNOWN_FOR_SURE'} />);
expect((await screen.findByTestId('splash')).textContent).toContain(
-1
View File
@@ -22,7 +22,6 @@ export * from '../markets/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 '../network-parameters/src/network-params.mock';
export * from '../wallet/src/connect-dialog/chain-id.mock';
export * from '../positions/src/lib/estimate-position.mock';
export * from '../trades/src/lib/trades.mock';
export * from '../withdraws/src/lib/withdrawal.mock';
+2 -1
View File
@@ -1,5 +1,5 @@
import { addGetTestIdcommand } from './lib/commands/get-by-test-id';
import { addMockGQLCommand } from './lib/mock-gql';
import { addMockGQLCommand, addMockStatistics } from './lib/mock-gql';
import { addMockSubscription } from './lib/mock-ws';
import { addMockWalletCommand } from './lib/mock-rest';
import { addMockWeb3ProviderCommand } from './lib/commands/mock-web3-provider';
@@ -28,6 +28,7 @@ import { addMockChainId } from './lib/commands/mock-chain-id';
addGetTestIdcommand();
addMockGQLCommand();
addMockStatistics();
addMockSubscription();
addMockWalletCommand();
addMockWeb3ProviderCommand();
+18 -3
View File
@@ -1,6 +1,6 @@
import { aliasGQLQuery } from '../mock-gql';
// eslint-disable-next-line @nx/enforce-module-boundaries
import { chainIdQuery, statisticsQuery } from '@vegaprotocol/mock';
import { statisticsQuery } from '@vegaprotocol/mock';
declare global {
// eslint-disable-next-line @typescript-eslint/no-namespace
@@ -12,11 +12,26 @@ declare global {
}
}
const chainId = 'test-id';
export function addMockChainId() {
Cypress.Commands.add('mockChainId', () => {
const result = {
statistics: {
chainId,
},
};
cy.mockGQL((req) => {
aliasGQLQuery(req, 'ChainId', chainIdQuery());
aliasGQLQuery(req, 'Statistics', statisticsQuery());
aliasGQLQuery(req, 'NodeCheck', statisticsQuery(result));
});
cy.mockStatistics((req) => {
req.reply({
statusCode: 200,
body: result,
headers: {
'Content-Type': 'application/json',
},
});
});
});
}
+11
View File
@@ -8,6 +8,7 @@ declare global {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
interface Chainable<Subject> {
mockGQL(handler: RouteHandler): void;
mockStatistics(handler: RouteHandler): void;
}
}
}
@@ -40,6 +41,16 @@ const extractVariables = (req: CyHttpMessages.IncomingHttpRequest): object => {
);
};
export function addMockStatistics() {
Cypress.Commands.add('mockStatistics', (handler: RouteHandler) => {
cy.intercept(
'GET',
Cypress.env('VEGA_URL').replace('graphql', 'statistics'),
handler
).as('ChainId');
});
}
export function addMockGQLCommand() {
Cypress.Commands.add('mockGQL', (handler: RouteHandler) => {
cy.intercept('POST', Cypress.env('VEGA_URL'), handler).as('GQL');
@@ -1,4 +1,4 @@
import { useVegaTransactionStore } from '@vegaprotocol/wallet';
import { useVegaTransactionStore } from '@vegaprotocol/web3';
import {
isStopOrderType,
useDealTicketFormValues,
@@ -264,7 +264,11 @@ export const DealTicket = ({
orders,
collateralAvailable:
marginAccountBalance || generalAccountBalance ? balance : undefined,
skip: !normalizedOrder,
skip:
!normalizedOrder ||
(normalizedOrder.type !== Schema.OrderType.TYPE_MARKET &&
(!normalizedOrder.price || normalizedOrder.price === '0')) ||
normalizedOrder.size === '0',
});
const assetSymbol = getAsset(market).symbol;
@@ -114,6 +114,20 @@ export const TradingModeTooltip = ({
</section>
);
}
case Schema.MarketTradingMode.TRADING_MODE_SUSPENDED_VIA_GOVERNANCE: {
return (
<section data-testid="trading-mode-suspended-via-governance">
{t(
`This market has been suspended via a governance vote and can be resumed or terminated by further votes.`
)}
{DocsLinks && (
<ExternalLink href={DocsLinks.MARKET_LIFECYCLE} className="ml-1">
{t('Find out more')}
</ExternalLink>
)}
</section>
);
}
case Schema.MarketTradingMode.TRADING_MODE_MONITORING_AUCTION: {
switch (trigger) {
case Schema.AuctionTrigger.AUCTION_TRIGGER_LIQUIDITY_TARGET_NOT_MET: {
@@ -30,9 +30,11 @@ export const usePositionEstimate = ({
fetchPolicy: 'no-cache',
});
useEffect(() => {
if (data) {
if (skip) {
setEstimates(undefined);
} else if (data) {
setEstimates(data);
}
}, [data]);
}, [data, skip]);
return estimates;
};
+1
View File
@@ -80,6 +80,7 @@ export const DocsLinks = VEGA_DOCS_URL
LIQUIDITY: `${VEGA_DOCS_URL}/concepts/liquidity/provision`,
WITHDRAWAL_LIMITS: `${VEGA_DOCS_URL}/concepts/assets/deposits-withdrawals#withdrawal-limits`,
VALIDATOR_SCORES_REWARDS: `${VEGA_DOCS_URL}/concepts/vega-chain/validator-scores-and-rewards`,
MARKET_LIFECYCLE: `${VEGA_DOCS_URL}/concepts/trading-on-vega/market-lifecycle`,
}
: undefined;
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -4,6 +4,10 @@ fragment DataSourceFilter on Filter {
type
numberDecimalPlaces
}
conditions {
value
operator
}
}
fragment DataSource on DataSourceSpec {
@@ -12,6 +16,37 @@ fragment DataSource on DataSourceSpec {
sourceType {
... on DataSourceDefinitionExternal {
sourceType {
... on EthCallSpec {
abi
address
args
method
requiredConfirmations
normalisers {
name
expression
}
trigger {
trigger {
... on EthTimeTrigger {
initial
every
until
}
}
}
filters {
key {
name
type
numberDecimalPlaces
}
conditions {
value
operator
}
}
}
... on DataSourceSpecConfiguration {
signers {
signer {
File diff suppressed because one or more lines are too long
@@ -6,13 +6,21 @@ import { t } from '@vegaprotocol/i18n';
import { marketDataProvider } from '../../market-data-provider';
import { totalFeesPercentage } from '../../market-utils';
import {
Accordion,
AccordionChevron,
AccordionPanel,
CopyWithTooltip,
ExternalLink,
Intent,
KeyValueTable,
KeyValueTableRow,
Lozenge,
Splash,
SyntaxHighlighter,
Tooltip,
VegaIcon,
VegaIconNames,
truncateMiddle,
} from '@vegaprotocol/ui-toolkit';
import {
addDecimalsFormatNumber,
@@ -31,6 +39,7 @@ import { Last24hVolume } from '../last-24h-volume';
import BigNumber from 'bignumber.js';
import type {
DataSourceDefinition,
EthCallSpec,
MarketTradingMode,
SignerKind,
} from '@vegaprotocol/types';
@@ -40,6 +49,7 @@ import {
} from '@vegaprotocol/types';
import {
DApp,
EtherscanLink,
FLAGS,
TOKEN_PROPOSAL,
useEnvironment,
@@ -65,6 +75,7 @@ import {
} from '@vegaprotocol/network-parameters';
import type { DataSourceFragment } from './__generated__/MarketInfo';
import { formatDuration } from 'date-fns';
import * as AccordionPrimitive from '@radix-ui/react-accordion';
type MarketInfoProps = {
market: MarketInfo;
@@ -659,6 +670,97 @@ export const LiquidityMonitoringParametersInfoPanel = ({
return <MarketInfoTable data={marketData} parentData={parentMarketData} />;
};
export const EthOraclePanel = ({ sourceType }: { sourceType: EthCallSpec }) => {
const abis = sourceType.abi?.map((abi) => JSON.parse(abi));
const header = 'uppercase my-1 text-left';
return (
<>
<h3 className={header}>{t('Ethereum Oracle')}</h3>
{sourceType.address && (
<>
<KeyValueTable>
<KeyValueTableRow noBorder>
<div>{t('Address')}</div>
<CopyWithTooltip text={sourceType.address}>
<button
data-testid="copy-eth-oracle-address"
className="uppercase text-right"
>
<span className="flex gap-1">
{truncateMiddle(sourceType.address)}
<VegaIcon name={VegaIconNames.COPY} size={16} />
</span>
</button>
</CopyWithTooltip>
</KeyValueTableRow>
</KeyValueTable>
<div className="my-2">
<EtherscanLink address={sourceType.address}>
{t('View on Etherscan')}
</EtherscanLink>
</div>
</>
)}
<MarketInfoTable
key="eth-call-spec"
data={{
method: sourceType.method,
requiredConfirmations: sourceType.requiredConfirmations,
}}
/>
<Accordion>
<AccordionPanel
itemId="abi"
trigger={
<AccordionPrimitive.Trigger
data-testid="accordion-toggle"
className={classNames(
'w-full pt-2',
'flex items-center gap-2',
'group'
)}
>
<div
data-testid={`abi-dropdown`}
key={'value-dropdown'}
className="flex items-center gap-2 w-full"
>
<div className="underline underline-offset-4 mb-1 uppercase">
{t('ABI specification')}
</div>
<AccordionChevron size={14} />
<div className="flex items-center gap-1"></div>
</div>
</AccordionPrimitive.Trigger>
}
>
<SyntaxHighlighter data={abis} />
</AccordionPanel>
</Accordion>
<h3 className={header}>{t('Normalisers')}</h3>
{sourceType.normalisers?.map((normaliser, i) => (
<MarketInfoTable key={i} data={normaliser} />
))}
<h3 className={header}>{t('Filters')}</h3>
<h3 className={header}>{t('Key')}</h3>
{sourceType.filters?.map((filter, i) => (
<>
<MarketInfoTable key={i} data={filter.key} />
<h3 className={header}>{t('Conditions')}</h3>
{filter.conditions?.map((condition, i) => (
<span>
{ConditionOperatorMapping[condition.operator]} {condition.value}
</span>
))}
</>
))}
</>
);
};
export const LiquidityPriceRangeInfoPanel = ({
market,
parentMarket,
@@ -782,7 +884,7 @@ export const LiquiditySLAParametersInfoPanel = ({
market.liquiditySLAParameters?.slaCompetitionFactor
).times(100)
),
commitmentMinimumTimeFraction:
commitmentMinTimeFraction:
market.liquiditySLAParameters?.commitmentMinTimeFraction &&
formatNumberPercentage(
new BigNumber(
@@ -797,7 +899,7 @@ export const LiquiditySLAParametersInfoPanel = ({
parentMarket.liquiditySLAParameters?.performanceHysteresisEpochs,
slaCompetitionFactor:
parentMarket.liquiditySLAParameters?.slaCompetitionFactor,
commitmentMinimumTimeFraction:
commitmentMinTimeFraction:
parentMarket.liquiditySLAParameters?.commitmentMinTimeFraction,
}
: undefined;
@@ -823,13 +925,13 @@ export const LiquiditySLAParametersInfoPanel = ({
networkParams['market_liquidity_nonPerformanceBondPenaltySlope'],
nonPerformanceBondPenaltyMax:
networkParams['market_liquidity_sla_nonPerformanceBondPenaltyMax'],
maximumLiquidityFeeFactorLevel:
maxLiquidityFeeFactorLevel:
networkParams['market_liquidity_maximumLiquidityFeeFactorLevel'],
stakeToCCYVolume: networkParams['market_liquidity_stakeToCcyVolume'],
earlyExitPenalty: networkParams['market_liquidity_earlyExitPenalty'],
probabilityOfTradingTauScaling:
networkParams['market_liquidity_probabilityOfTrading_tau_scaling'],
minimumProbabilityOfTradingLPOrders:
minProbabilityOfTradingLPOrders:
networkParams['market_liquidity_minimum_probabilityOfTrading_lpOrders'],
feeCalculationTimeStep:
networkParams['market_liquidity_feeCalculationTimeStep'] &&
@@ -931,6 +1033,10 @@ export const OracleInfoPanel = ({
</Lozenge>
)}
{dataSourceSpec?.sourceType.sourceType.__typename === 'EthCallSpec' && (
<EthOraclePanel sourceType={dataSourceSpec?.sourceType.sourceType} />
)}
<div className={wrapperClasses}>
{shouldShowParentData &&
parentDataSourceSpec &&
@@ -945,6 +1051,13 @@ export const OracleInfoPanel = ({
dataSourceSpecId={parentDataSourceSpecId}
/>
{parentDataSourceSpec?.sourceType.sourceType.__typename ===
'EthCallSpec' && (
<EthOraclePanel
sourceType={parentDataSourceSpec?.sourceType.sourceType}
/>
)}
{dataSourceSpecId && (
<ExternalLink
data-testid="oracle-spec-links"
@@ -106,7 +106,7 @@ export const tooltipMapping: Record<string, ReactNode> = {
insurancePoolFraction: t(
'The fraction of the insurance pool balance that is carried over from the parent market to the successor.'
),
commitmentMinimumTimeFraction: t(
commitmentMinTimeFraction: t(
`Specifies the minimum fraction of time LPs must spend 'on the book' providing their committed liquidity. This is a market parameter.`
),
feeCalculationTimeStep: t(
@@ -127,7 +127,7 @@ export const tooltipMapping: Record<string, ReactNode> = {
nonPerformanceBondPenaltyMax: t(
`The maximum amount, as a fraction, that an LP's bond can be slashed by if they fail to reach the minimum SLA. This is a network parameter.`
),
maximumLiquidityFeeFactorLevel: t(
maxLiquidityFeeFactorLevel: t(
'Maximum value that a proposed fee amount can be, which is submitted as part of the LP commitment transaction. Note that a value of 0.05 = 5%. This is a network parameter.'
),
stakeToCCYVolume: t(
@@ -137,12 +137,12 @@ export const tooltipMapping: Record<string, ReactNode> = {
'How long an epoch is. LP rewards from liquidity fees are paid out once per epoch. How much they receive depends on whether they met the liquidity SLA and their previous performance in recent epochs. This is a network parameter.'
),
earlyExitPenalty: t(
`How much an LP forfeits of their bond if they reduce their commitment while the market is below target stake, expressed as a factor. If set to 0 there is no penalty for early exit. If set to 1 an LP's entire bond is forfeited when an LP removes their full commitment. This is a network parameter.`
`The percentage of their bond an LP forfeits if they reduce their commitment while the market is below target stake. If 100%, an LP's entire bond is forfeited when they cancel their full commitment. This is a network parameter.`
),
probabilityOfTradingTauScaling: t(
`Determines how the probability of trading is scaled from the risk model, and is used to measure the relative competitiveness of an LP's supplied volume. This is a network parameter.`
),
minimumProbabilityOfTradingLPOrders: t(
minProbabilityOfTradingLPOrders: t(
'The lower bound for the probability of trading calculation, used to measure liquidity available on a market to determine if LPs are meeting their commitment. This is a network parameter.'
),
};
@@ -1,6 +1,7 @@
import { t } from '@vegaprotocol/i18n';
import { TradingButton } from '@vegaprotocol/ui-toolkit';
import { useVegaTransactionStore, useVegaWallet } from '@vegaprotocol/wallet';
import { useVegaWallet } from '@vegaprotocol/wallet';
import { useVegaTransactionStore } from '@vegaprotocol/web3';
import { useHasAmendableOrder } from '../../order-hooks';
export const OpenOrdersMenu = ({ marketId }: { marketId: string }) => {
@@ -32,12 +32,6 @@ fragment OrderFields on Order {
}
}
query OrderById($orderId: ID!) {
orderByID(id: $orderId) {
...OrderFields
}
}
query Orders(
$partyId: ID!
$marketIds: [ID!]
@@ -153,9 +147,3 @@ query StopOrders($filter: StopOrderFilter) {
}
}
}
query StopOrderById($stopOrderId: ID!) {
stopOrder(id: $stopOrderId) {
...StopOrderFields
}
}
@@ -5,13 +5,6 @@ import * as Apollo from '@apollo/client';
const defaultOptions = {} as const;
export type OrderFieldsFragment = { __typename?: 'Order', id: string, type?: Types.OrderType | null, side: Types.Side, size: string, status: Types.OrderStatus, rejectionReason?: Types.OrderRejectionReason | null, price: string, timeInForce: Types.OrderTimeInForce, remaining: string, expiresAt?: any | null, createdAt: any, updatedAt?: any | null, postOnly?: boolean | null, reduceOnly?: boolean | null, market: { __typename?: 'Market', id: string }, liquidityProvision?: { __typename: 'LiquidityProvision' } | null, peggedOrder?: { __typename: 'PeggedOrder', reference: Types.PeggedReference, offset: string } | null, icebergOrder?: { __typename: 'IcebergOrder', peakSize: string, minimumVisibleSize: string, reservedRemaining: string } | null };
export type OrderByIdQueryVariables = Types.Exact<{
orderId: Types.Scalars['ID'];
}>;
export type OrderByIdQuery = { __typename?: 'Query', orderByID: { __typename?: 'Order', id: string, type?: Types.OrderType | null, side: Types.Side, size: string, status: Types.OrderStatus, rejectionReason?: Types.OrderRejectionReason | null, price: string, timeInForce: Types.OrderTimeInForce, remaining: string, expiresAt?: any | null, createdAt: any, updatedAt?: any | null, postOnly?: boolean | null, reduceOnly?: boolean | null, market: { __typename?: 'Market', id: string }, liquidityProvision?: { __typename: 'LiquidityProvision' } | null, peggedOrder?: { __typename: 'PeggedOrder', reference: Types.PeggedReference, offset: string } | null, icebergOrder?: { __typename: 'IcebergOrder', peakSize: string, minimumVisibleSize: string, reservedRemaining: string } | null } };
export type OrdersQueryVariables = Types.Exact<{
partyId: Types.Scalars['ID'];
marketIds?: Types.InputMaybe<Array<Types.Scalars['ID']> | Types.Scalars['ID']>;
@@ -43,13 +36,6 @@ export type StopOrdersQueryVariables = Types.Exact<{
export type StopOrdersQuery = { __typename?: 'Query', stopOrders?: { __typename?: 'StopOrderConnection', edges?: Array<{ __typename?: 'StopOrderEdge', node?: { __typename?: 'StopOrder', id: string, ocoLinkId?: string | null, expiresAt?: any | null, expiryStrategy?: Types.StopOrderExpiryStrategy | null, triggerDirection: Types.StopOrderTriggerDirection, status: Types.StopOrderStatus, createdAt: any, updatedAt?: any | null, partyId: string, marketId: string, order?: { __typename?: 'Order', id: string, type?: Types.OrderType | null, side: Types.Side, size: string, status: Types.OrderStatus, rejectionReason?: Types.OrderRejectionReason | null, price: string, timeInForce: Types.OrderTimeInForce, remaining: string, expiresAt?: any | null, createdAt: any, updatedAt?: any | null, postOnly?: boolean | null, reduceOnly?: boolean | null, market: { __typename?: 'Market', id: string }, liquidityProvision?: { __typename: 'LiquidityProvision' } | null, peggedOrder?: { __typename: 'PeggedOrder', reference: Types.PeggedReference, offset: string } | null, icebergOrder?: { __typename: 'IcebergOrder', peakSize: string, minimumVisibleSize: string, reservedRemaining: string } | null } | null, trigger: { __typename?: 'StopOrderPrice', price: string } | { __typename?: 'StopOrderTrailingPercentOffset', trailingPercentOffset: string }, submission: { __typename?: 'OrderSubmission', marketId: string, price: string, size: string, side: Types.Side, timeInForce: Types.OrderTimeInForce, expiresAt: any, type: Types.OrderType, reference?: string | null, postOnly?: boolean | null, reduceOnly?: boolean | null, peggedOrder?: { __typename?: 'PeggedOrder', reference: Types.PeggedReference, offset: string } | null } } | null }> | null } | null };
export type StopOrderByIdQueryVariables = Types.Exact<{
stopOrderId: Types.Scalars['ID'];
}>;
export type StopOrderByIdQuery = { __typename?: 'Query', stopOrder?: { __typename?: 'StopOrder', id: string, ocoLinkId?: string | null, expiresAt?: any | null, expiryStrategy?: Types.StopOrderExpiryStrategy | null, triggerDirection: Types.StopOrderTriggerDirection, status: Types.StopOrderStatus, createdAt: any, updatedAt?: any | null, partyId: string, marketId: string, order?: { __typename?: 'Order', id: string, type?: Types.OrderType | null, side: Types.Side, size: string, status: Types.OrderStatus, rejectionReason?: Types.OrderRejectionReason | null, price: string, timeInForce: Types.OrderTimeInForce, remaining: string, expiresAt?: any | null, createdAt: any, updatedAt?: any | null, postOnly?: boolean | null, reduceOnly?: boolean | null, market: { __typename?: 'Market', id: string }, liquidityProvision?: { __typename: 'LiquidityProvision' } | null, peggedOrder?: { __typename: 'PeggedOrder', reference: Types.PeggedReference, offset: string } | null, icebergOrder?: { __typename: 'IcebergOrder', peakSize: string, minimumVisibleSize: string, reservedRemaining: string } | null } | null, trigger: { __typename?: 'StopOrderPrice', price: string } | { __typename?: 'StopOrderTrailingPercentOffset', trailingPercentOffset: string }, submission: { __typename?: 'OrderSubmission', marketId: string, price: string, size: string, side: Types.Side, timeInForce: Types.OrderTimeInForce, expiresAt: any, type: Types.OrderType, reference?: string | null, postOnly?: boolean | null, reduceOnly?: boolean | null, peggedOrder?: { __typename?: 'PeggedOrder', reference: Types.PeggedReference, offset: string } | null } } | null };
export const OrderUpdateFieldsFragmentDoc = gql`
fragment OrderUpdateFields on OrderUpdate {
id
@@ -161,41 +147,6 @@ export const StopOrderFieldsFragmentDoc = gql`
}
${OrderFieldsFragmentDoc}
${OrderSubmissionFieldsFragmentDoc}`;
export const OrderByIdDocument = gql`
query OrderById($orderId: ID!) {
orderByID(id: $orderId) {
...OrderFields
}
}
${OrderFieldsFragmentDoc}`;
/**
* __useOrderByIdQuery__
*
* To run a query within a React component, call `useOrderByIdQuery` and pass it any options that fit your needs.
* When your component renders, `useOrderByIdQuery` 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 } = useOrderByIdQuery({
* variables: {
* orderId: // value for 'orderId'
* },
* });
*/
export function useOrderByIdQuery(baseOptions: Apollo.QueryHookOptions<OrderByIdQuery, OrderByIdQueryVariables>) {
const options = {...defaultOptions, ...baseOptions}
return Apollo.useQuery<OrderByIdQuery, OrderByIdQueryVariables>(OrderByIdDocument, options);
}
export function useOrderByIdLazyQuery(baseOptions?: Apollo.LazyQueryHookOptions<OrderByIdQuery, OrderByIdQueryVariables>) {
const options = {...defaultOptions, ...baseOptions}
return Apollo.useLazyQuery<OrderByIdQuery, OrderByIdQueryVariables>(OrderByIdDocument, options);
}
export type OrderByIdQueryHookResult = ReturnType<typeof useOrderByIdQuery>;
export type OrderByIdLazyQueryHookResult = ReturnType<typeof useOrderByIdLazyQuery>;
export type OrderByIdQueryResult = Apollo.QueryResult<OrderByIdQuery, OrderByIdQueryVariables>;
export const OrdersDocument = gql`
query Orders($partyId: ID!, $marketIds: [ID!], $pagination: Pagination, $filter: OrderFilter) {
party(id: $partyId) {
@@ -320,39 +271,4 @@ export function useStopOrdersLazyQuery(baseOptions?: Apollo.LazyQueryHookOptions
}
export type StopOrdersQueryHookResult = ReturnType<typeof useStopOrdersQuery>;
export type StopOrdersLazyQueryHookResult = ReturnType<typeof useStopOrdersLazyQuery>;
export type StopOrdersQueryResult = Apollo.QueryResult<StopOrdersQuery, StopOrdersQueryVariables>;
export const StopOrderByIdDocument = gql`
query StopOrderById($stopOrderId: ID!) {
stopOrder(id: $stopOrderId) {
...StopOrderFields
}
}
${StopOrderFieldsFragmentDoc}`;
/**
* __useStopOrderByIdQuery__
*
* To run a query within a React component, call `useStopOrderByIdQuery` and pass it any options that fit your needs.
* When your component renders, `useStopOrderByIdQuery` 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 } = useStopOrderByIdQuery({
* variables: {
* stopOrderId: // value for 'stopOrderId'
* },
* });
*/
export function useStopOrderByIdQuery(baseOptions: Apollo.QueryHookOptions<StopOrderByIdQuery, StopOrderByIdQueryVariables>) {
const options = {...defaultOptions, ...baseOptions}
return Apollo.useQuery<StopOrderByIdQuery, StopOrderByIdQueryVariables>(StopOrderByIdDocument, options);
}
export function useStopOrderByIdLazyQuery(baseOptions?: Apollo.LazyQueryHookOptions<StopOrderByIdQuery, StopOrderByIdQueryVariables>) {
const options = {...defaultOptions, ...baseOptions}
return Apollo.useLazyQuery<StopOrderByIdQuery, StopOrderByIdQueryVariables>(StopOrderByIdDocument, options);
}
export type StopOrderByIdQueryHookResult = ReturnType<typeof useStopOrderByIdQuery>;
export type StopOrderByIdLazyQueryHookResult = ReturnType<typeof useStopOrderByIdLazyQuery>;
export type StopOrderByIdQueryResult = Apollo.QueryResult<StopOrderByIdQuery, StopOrderByIdQueryVariables>;
export type StopOrdersQueryResult = Apollo.QueryResult<StopOrdersQuery, StopOrdersQueryVariables>;
@@ -5,11 +5,9 @@ import { OrderListTable } from '../order-list/order-list';
import type { useDataGridEvents } from '@vegaprotocol/datagrid';
import { useDataProvider } from '@vegaprotocol/data-provider';
import { ordersWithMarketProvider } from '../order-data-provider/order-data-provider';
import {
normalizeOrderAmendment,
useVegaTransactionStore,
} from '@vegaprotocol/wallet';
import type { OrderTxUpdateFieldsFragment } from '@vegaprotocol/wallet';
import { normalizeOrderAmendment } from '@vegaprotocol/wallet';
import { useVegaTransactionStore } from '@vegaprotocol/web3';
import type { OrderTxUpdateFieldsFragment } from '@vegaprotocol/web3';
import { OrderEditDialog } from '../order-list/order-edit-dialog';
import type { Order } from '../order-data-provider';
import { OrderViewDialog } from '../order-list/order-view-dialog';
@@ -1,8 +1,6 @@
import type { Story, Meta } from '@storybook/react';
import { OrderListTable } from './order-list';
import { useState } from 'react';
import type { VegaTxState } from '@vegaprotocol/wallet';
import { VegaTransactionDialog, VegaTxStatus } from '@vegaprotocol/wallet';
import { generateOrdersArray } from '../mocks';
import { OrderEditDialog } from './order-edit-dialog';
import type { Order } from '../order-data-provider';
@@ -32,25 +30,15 @@ const Template: Story = (args) => {
};
const Template2: Story = (args) => {
const [open, setOpen] = useState(false);
const [editOrder, setEditOrder] = useState<Order>();
const cancel = () => {
setOpen(!open);
return Promise.resolve();
};
const transaction: VegaTxState = {
status: VegaTxStatus.Requested,
error: null,
txHash: null,
signature: null,
dialogOpen: false,
};
return (
<>
<div style={{ height: 1000 }}>
<OrderListTable
rowData={args.data}
onCancel={cancel}
onCancel={() => {
return;
}}
onEdit={setEditOrder}
onView={() => {
return;
@@ -58,11 +46,6 @@ const Template2: Story = (args) => {
isReadOnly={false}
/>
</div>
<VegaTransactionDialog
isOpen={open}
onChange={setOpen}
transaction={transaction}
/>
{editOrder && (
<OrderEditDialog
isOpen={Boolean(editOrder)}
@@ -2,12 +2,12 @@ import { t } from '@vegaprotocol/i18n';
import { useCallback, useEffect, useState } from 'react';
import { StopOrdersTable } from '../stop-orders-table/stop-orders-table';
import type { useDataGridEvents } from '@vegaprotocol/datagrid';
import { useVegaTransactionStore } from '@vegaprotocol/wallet';
import type { StopOrder } from '../order-data-provider/stop-orders-data-provider';
import { useDataProvider } from '@vegaprotocol/data-provider';
import { stopOrdersWithMarketProvider } from '../order-data-provider/stop-orders-data-provider';
import { OrderViewDialog } from '../order-list/order-view-dialog';
import type { Order, StopOrdersQueryVariables } from '../order-data-provider';
import { useVegaTransactionStore } from '@vegaprotocol/web3';
export interface StopOrdersManagerProps {
partyId: string;
-1
View File
@@ -1,3 +1,2 @@
export * from './__generated__/OrdersSubscription';
export * from './use-has-amendable-order';
export * from './use-order-update';
@@ -1,60 +0,0 @@
import { useApolloClient } from '@apollo/client';
import { useCallback, useEffect, useRef } from 'react';
import { OrderSubDocument } from './__generated__/OrdersSubscription';
import type {
OrderSubSubscription,
OrderSubSubscriptionVariables,
OrderSubFieldsFragment,
} from './__generated__/OrdersSubscription';
import type { Subscription } from 'zen-observable-ts';
import type { VegaTxState } from '@vegaprotocol/wallet';
type WaitFunc = (
orderId: string,
partyId: string
) => Promise<OrderSubFieldsFragment>;
export const useOrderUpdate = (transaction: VegaTxState) => {
const client = useApolloClient();
const subRef = useRef<Subscription | null>(null);
const waitForOrderUpdate = useCallback<WaitFunc>(
(id: string, partyId: string) => {
return new Promise((resolve) => {
subRef.current = client
.subscribe<OrderSubSubscription, OrderSubSubscriptionVariables>({
query: OrderSubDocument,
variables: { partyId },
})
.subscribe(({ data }) => {
if (!data?.orders?.length) {
return;
}
// No types available for the subscription result
const matchingOrder = data.orders.find((order) => {
return order.id === id;
});
if (matchingOrder) {
resolve(matchingOrder);
subRef.current?.unsubscribe();
}
});
});
},
[client]
);
useEffect(() => {
if (!transaction.dialogOpen) {
subRef.current?.unsubscribe();
}
return () => {
subRef.current?.unsubscribe();
};
}, [transaction.dialogOpen]);
return waitForOrderUpdate;
};
+2 -105
View File
@@ -1,110 +1,7 @@
import { Intent } from '@vegaprotocol/ui-toolkit';
import {
getOrderToastIntent,
getOrderToastTitle,
getRejectionReason,
timeInForceLabel,
} from './utils';
import { timeInForceLabel } from './utils';
import * as Types from '@vegaprotocol/types';
describe('WithdrawalsTable', () => {
describe('getOrderToastTitle', () => {
it('should return the correct title', () => {
expect(getOrderToastTitle(Types.OrderStatus.STATUS_ACTIVE)).toBe(
'Order submitted'
);
expect(getOrderToastTitle(Types.OrderStatus.STATUS_FILLED)).toBe(
'Order filled'
);
expect(
getOrderToastTitle(Types.OrderStatus.STATUS_PARTIALLY_FILLED)
).toBe('Order partially filled');
expect(getOrderToastTitle(Types.OrderStatus.STATUS_PARKED)).toBe(
'Order parked'
);
expect(getOrderToastTitle(Types.OrderStatus.STATUS_STOPPED)).toBe(
'Order stopped'
);
expect(getOrderToastTitle(Types.OrderStatus.STATUS_CANCELLED)).toBe(
'Order cancelled'
);
expect(getOrderToastTitle(Types.OrderStatus.STATUS_EXPIRED)).toBe(
'Order expired'
);
expect(getOrderToastTitle(Types.OrderStatus.STATUS_REJECTED)).toBe(
'Order rejected'
);
expect(getOrderToastTitle(undefined)).toBe(undefined);
});
});
describe('getOrderToastIntent', () => {
it('should return the correct intent', () => {
expect(getOrderToastIntent(Types.OrderStatus.STATUS_PARKED)).toBe(
Intent.Warning
);
expect(getOrderToastIntent(Types.OrderStatus.STATUS_EXPIRED)).toBe(
Intent.Warning
);
expect(
getOrderToastIntent(Types.OrderStatus.STATUS_PARTIALLY_FILLED)
).toBe(Intent.Warning);
expect(getOrderToastIntent(Types.OrderStatus.STATUS_REJECTED)).toBe(
Intent.Danger
);
expect(getOrderToastIntent(Types.OrderStatus.STATUS_STOPPED)).toBe(
Intent.Warning
);
expect(getOrderToastIntent(Types.OrderStatus.STATUS_FILLED)).toBe(
Intent.Success
);
expect(getOrderToastIntent(Types.OrderStatus.STATUS_ACTIVE)).toBe(
Intent.Success
);
expect(getOrderToastIntent(Types.OrderStatus.STATUS_CANCELLED)).toBe(
Intent.Success
);
expect(getOrderToastIntent(undefined)).toBe(undefined);
});
});
describe('getRejectionReason', () => {
it('should return the correct rejection reason for insufficient asset balance', () => {
expect(
getRejectionReason({
rejectionReason:
Types.OrderRejectionReason.ORDER_ERROR_INSUFFICIENT_ASSET_BALANCE,
status: Types.OrderStatus.STATUS_REJECTED,
id: '',
createdAt: undefined,
size: '',
price: '',
timeInForce: Types.OrderTimeInForce.TIME_IN_FORCE_FOK,
side: Types.Side.SIDE_BUY,
marketId: '',
})
).toBe('Insufficient asset balance');
});
it('should return the correct rejection reason when order is stopped', () => {
expect(
getRejectionReason({
rejectionReason: null,
status: Types.OrderStatus.STATUS_STOPPED,
id: '',
createdAt: undefined,
size: '',
price: '',
timeInForce: Types.OrderTimeInForce.TIME_IN_FORCE_FOK,
side: Types.Side.SIDE_BUY,
marketId: '',
})
).toBe(
'Your Fill or Kill (FOK) order was not filled and it has been stopped'
);
});
});
describe('utils', () => {
describe('timeInForceLabel', () => {
it('should return the correct label for time in force', () => {
expect(timeInForceLabel(Types.OrderTimeInForce.TIME_IN_FORCE_FOK)).toBe(
-71
View File
@@ -1,7 +1,5 @@
import { t } from '@vegaprotocol/i18n';
import * as Schema from '@vegaprotocol/types';
import type { OrderSubFieldsFragment } from './order-hooks';
import { Intent } from '@vegaprotocol/ui-toolkit';
// More detail in https://docs.vega.xyz/mainnet/graphql/enums/order-time-in-force
export const timeInForceLabel = (tif: string) => {
@@ -22,72 +20,3 @@ export const timeInForceLabel = (tif: string) => {
return t(tif);
}
};
export const getRejectionReason = (
order: OrderSubFieldsFragment
): string | null => {
switch (order.status) {
case Schema.OrderStatus.STATUS_STOPPED:
return t(
`Your ${
Schema.OrderTimeInForceMapping[order.timeInForce]
} order was not filled and it has been stopped`
);
default:
return order.rejectionReason
? t(Schema.OrderRejectionReasonMapping[order.rejectionReason])
: '';
}
};
export const getOrderToastTitle = (
status?: Schema.OrderStatus
): string | undefined => {
if (!status) {
return;
}
switch (status) {
case Schema.OrderStatus.STATUS_ACTIVE:
return t('Order submitted');
case Schema.OrderStatus.STATUS_FILLED:
return t('Order filled');
case Schema.OrderStatus.STATUS_PARTIALLY_FILLED:
return t('Order partially filled');
case Schema.OrderStatus.STATUS_PARKED:
return t('Order parked');
case Schema.OrderStatus.STATUS_STOPPED:
return t('Order stopped');
case Schema.OrderStatus.STATUS_CANCELLED:
return t('Order cancelled');
case Schema.OrderStatus.STATUS_EXPIRED:
return t('Order expired');
case Schema.OrderStatus.STATUS_REJECTED:
return t('Order rejected');
default:
return t('Submission failed');
}
};
export const getOrderToastIntent = (
status?: Schema.OrderStatus
): Intent | undefined => {
if (!status) {
return;
}
switch (status) {
case Schema.OrderStatus.STATUS_PARKED:
case Schema.OrderStatus.STATUS_EXPIRED:
case Schema.OrderStatus.STATUS_PARTIALLY_FILLED:
case Schema.OrderStatus.STATUS_STOPPED:
return Intent.Warning;
case Schema.OrderStatus.STATUS_REJECTED:
return Intent.Danger;
case Schema.OrderStatus.STATUS_FILLED:
case Schema.OrderStatus.STATUS_ACTIVE:
case Schema.OrderStatus.STATUS_CANCELLED:
return Intent.Success;
default:
return;
}
};
@@ -0,0 +1,42 @@
import { render, screen, fireEvent } from '@testing-library/react';
import { PositionsManager } from './positions-manager';
import { positionsMarketsProvider } from './positions-data-providers';
import { singleRow } from './positions.mock';
import { MockedProvider } from '@apollo/client/testing';
import { MAXGOINT64 } from '@vegaprotocol/utils';
const mockCreate = jest.fn();
jest.mock('@vegaprotocol/wallet', () => ({
...jest.requireActual('@vegaprotocol/wallet'),
useVegaWallet: jest.fn(() => ({ pubKey: 'partyId' })),
}));
jest.mock('@vegaprotocol/web3', () => ({
...jest.requireActual('@vegaprotocol/web3'),
useVegaTransactionStore: jest.fn(() => mockCreate),
}));
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const mockUseDataProvider = (args: any) => {
if (args.dataProvider === positionsMarketsProvider) {
return { data: ['market-1', 'market-2'] };
}
return { data: [singleRow] };
};
jest.mock('@vegaprotocol/data-provider', () => ({
...jest.requireActual('@vegaprotocol/data-provider'),
useDataProvider: jest.fn((args) => mockUseDataProvider(args)),
}));
describe('PositionsManager', () => {
it('should close position with max uint64', async () => {
render(<PositionsManager partyIds={['partyId']} isReadOnly={false} />, {
wrapper: MockedProvider,
});
expect(await screen.getByTestId('close-position')).toBeInTheDocument();
fireEvent.click(screen.getByTestId('close-position'));
expect(
mockCreate.mock.lastCall[0].batchMarketInstructions.submissions[0].size
).toEqual(MAXGOINT64);
});
});
+4 -3
View File
@@ -1,7 +1,8 @@
import { useCallback } from 'react';
import { PositionsTable } from './positions-table';
import * as Schema from '@vegaprotocol/types';
import { useVegaTransactionStore } from '@vegaprotocol/wallet';
import { useVegaTransactionStore } from '@vegaprotocol/web3';
import { useVegaWallet } from '@vegaprotocol/wallet';
import { t } from '@vegaprotocol/i18n';
import { useDataProvider } from '@vegaprotocol/data-provider';
import {
@@ -9,7 +10,7 @@ import {
positionsMarketsProvider,
} from './positions-data-providers';
import type { useDataGridEvents } from '@vegaprotocol/datagrid';
import { useVegaWallet } from '@vegaprotocol/wallet';
import { MAXGOINT64 } from '@vegaprotocol/utils';
interface PositionsManagerProps {
partyIds: string[];
@@ -46,7 +47,7 @@ export const PositionsManager = ({
side: openVolume.startsWith('-')
? Schema.Side.SIDE_BUY
: Schema.Side.SIDE_SELL,
size: openVolume.replace('-', ''),
size: MAXGOINT64, // improvement for avoiding leftovers filled in the meantime when close request has been sent
reduceOnly: true,
},
],
@@ -6,6 +6,7 @@ import * as Schema from '@vegaprotocol/types';
import { PositionStatus } from '@vegaprotocol/types';
import type { ICellRendererParams } from 'ag-grid-community';
import { addDecimalsFormatNumber } from '@vegaprotocol/utils';
import { singleRow } from './positions.mock';
jest.mock('./liquidation-price', () => ({
LiquidationPrice: () => (
@@ -13,33 +14,6 @@ jest.mock('./liquidation-price', () => ({
),
}));
const singleRow: Position = {
partyId: 'partyId',
assetId: 'asset-id',
assetSymbol: 'BTC',
averageEntryPrice: '133',
currentLeverage: 1.1,
assetDecimals: 2, // this is settlementAsset.decimals
quantum: '0.1',
lossSocializationAmount: '0',
marginAccountBalance: '12345600',
marketDecimalPlaces: 1,
marketId: 'string',
marketCode: 'ETHBTC.QM21',
marketTradingMode: Schema.MarketTradingMode.TRADING_MODE_CONTINUOUS,
marketState: Schema.MarketState.STATE_ACTIVE,
markPrice: '123',
notional: '12300',
openVolume: '100',
positionDecimalPlaces: 0,
realisedPNL: '123',
status: PositionStatus.POSITION_STATUS_UNSPECIFIED,
totalBalance: '123456',
unrealisedPNL: '456',
updatedAt: '2022-07-27T15:02:58.400Z',
productType: 'Future',
};
describe('Positions', () => {
const renderComponent = async (rowData: Position) => {
await act(async () => {
+29
View File
@@ -10,6 +10,8 @@ import type {
MarginsQuery,
MarginFieldsFragment,
} from '@vegaprotocol/accounts';
import type { Position } from './positions-data-providers';
import * as Schema from '@vegaprotocol/types';
export const positionsQuery = (
override?: PartialDeep<PositionsQuery>
@@ -168,3 +170,30 @@ const marginsFields: MarginFieldsFragment[] = [
},
},
];
export const singleRow: Position = {
partyId: 'partyId',
assetId: 'asset-id',
assetSymbol: 'BTC',
averageEntryPrice: '133',
currentLeverage: 1.1,
assetDecimals: 2, // this is settlementAsset.decimals
quantum: '0.1',
lossSocializationAmount: '0',
marginAccountBalance: '12345600',
marketDecimalPlaces: 1,
marketId: 'string',
marketCode: 'ETHBTC.QM21',
marketTradingMode: Schema.MarketTradingMode.TRADING_MODE_CONTINUOUS,
marketState: Schema.MarketState.STATE_ACTIVE,
markPrice: '123',
notional: '12300',
openVolume: '100',
positionDecimalPlaces: 0,
realisedPNL: '123',
status: PositionStatus.POSITION_STATUS_UNSPECIFIED,
totalBalance: '123456',
unrealisedPNL: '456',
updatedAt: '2022-07-27T15:02:58.400Z',
productType: 'Future',
};
+1
View File
@@ -5,3 +5,4 @@ export * from './protocol-upgrade-countdown';
export * from './protocol-upgrade-in-progress-notification';
export * from './protocol-upgrade-proposal-notification';
export * from './voting-progress';
export * from './vega-transaction-dialog';
@@ -1,8 +1,8 @@
import { render, screen } from '@testing-library/react';
import { WalletError } from '../connectors';
import type { VegaWalletContextShape } from '../context';
import { VegaWalletContext } from '../context';
import { VegaTxStatus } from '../types';
import { WalletError } from '@vegaprotocol/wallet';
import type { VegaWalletContextShape } from '@vegaprotocol/wallet';
import { VegaWalletContext } from '@vegaprotocol/wallet';
import { VegaTxStatus } from '../../lib/proposals-hooks/use-vega-transaction';
import type { VegaTransactionDialogProps } from './vega-transaction-dialog';
import { VegaTransactionDialog } from './vega-transaction-dialog';
@@ -2,9 +2,9 @@ import type { ReactNode } from 'react';
import { t } from '@vegaprotocol/i18n';
import { Dialog, Icon, Intent, Loader } from '@vegaprotocol/ui-toolkit';
import { WalletClientError } from '@vegaprotocol/wallet-client';
import type { VegaTxState } from '../types';
import { VegaTxStatus } from '../types';
import { useVegaWallet } from '../use-vega-wallet';
import type { VegaTxState } from '../../lib/proposals-hooks/use-vega-transaction';
import { VegaTxStatus } from '../../lib/proposals-hooks/use-vega-transaction';
import { useVegaWallet } from '@vegaprotocol/wallet';
export type VegaTransactionContentMap = {
[C in VegaTxStatus]?: JSX.Element;
@@ -1,5 +1,6 @@
export * from './__generated__/Proposal';
export * from './use-proposal-event';
export * from './use-vega-transaction';
export * from './use-proposal-submit';
export * from './use-update-proposal';
export * from './use-update-network-paramaters-toasts';
@@ -7,7 +7,7 @@ import type {
ProposalEventFieldsFragment,
} from './__generated__/Proposal';
import type { Subscription } from 'zen-observable-ts';
import type { VegaTxState } from '@vegaprotocol/wallet';
import type { VegaTxState } from '../proposals-hooks/use-vega-transaction';
export const useProposalEvent = (transaction: VegaTxState) => {
const client = useApolloClient();
@@ -1,10 +1,7 @@
import { useCallback, useState } from 'react';
import * as Sentry from '@sentry/react';
import {
useVegaWallet,
useVegaTransaction,
determineId,
} from '@vegaprotocol/wallet';
import { useVegaWallet, determineId } from '@vegaprotocol/wallet';
import { useVegaTransaction } from './use-vega-transaction';
import { useProposalEvent } from './use-proposal-event';
import type { ProposalSubmission } from '@vegaprotocol/wallet';
import type { ProposalEventFieldsFragment } from './__generated__/Proposal';
@@ -1,11 +1,12 @@
import { act, renderHook } from '@testing-library/react';
import type { VegaWalletContextShape } from './context';
import { VegaWalletContext } from './context';
import type { VegaWalletContextShape, Transaction } from '@vegaprotocol/wallet';
import { VegaWalletContext, WalletError } from '@vegaprotocol/wallet';
import type { ReactNode } from 'react';
import { initialState, useVegaTransaction } from './use-vega-transaction';
import type { Transaction } from './connectors';
import { WalletError } from './connectors';
import { VegaTxStatus } from './types';
import {
initialState,
useVegaTransaction,
VegaTxStatus,
} from './use-vega-transaction';
const mockPubKey = '0x123';
@@ -4,15 +4,27 @@ import {
WalletClientError,
WalletHttpError,
} from '@vegaprotocol/wallet-client';
import { useVegaWallet } from './use-vega-wallet';
import type { VegaTransactionContentMap } from './vega-transaction-dialog';
import { VegaTransactionDialog } from './vega-transaction-dialog';
import { useVegaWallet, WalletError, ClientErrors } from '@vegaprotocol/wallet';
import type { Transaction } from '@vegaprotocol/wallet';
import type { VegaTransactionContentMap } from '../../components/vega-transaction-dialog';
import { VegaTransactionDialog } from '../../components/vega-transaction-dialog';
import type { Intent } from '@vegaprotocol/ui-toolkit';
import type { Transaction } from './connectors';
import { WalletError } from './connectors';
import { ClientErrors } from './connectors';
import type { VegaTxState } from './types';
import { VegaTxStatus } from './types';
export enum VegaTxStatus {
Default = 'Default',
Requested = 'Requested',
Pending = 'Pending',
Error = 'Error',
Complete = 'Complete',
}
export interface VegaTxState {
status: VegaTxStatus;
error: Error | null;
txHash: string | null;
signature: string | null;
dialogOpen: boolean;
}
export interface DialogProps {
intent?: Intent;
@@ -2,7 +2,7 @@ import { useApolloClient } from '@apollo/client';
import { useCallback, useEffect, useRef } from 'react';
import { VoteEventDocument } from './__generated__/VoteSubsciption';
import type { Subscription } from 'zen-observable-ts';
import type { VegaTxState } from '@vegaprotocol/wallet';
import type { VegaTxState } from '../proposals-hooks/use-vega-transaction';
import type {
VoteEventFieldsFragment,
VoteEventSubscription,
@@ -1,6 +1,7 @@
import { useCallback, useState } from 'react';
import * as Sentry from '@sentry/react';
import { useVegaTransaction, useVegaWallet } from '@vegaprotocol/wallet';
import { useVegaTransaction } from '../proposals-hooks/use-vega-transaction';
import { useVegaWallet } from '@vegaprotocol/wallet';
import { useVoteEvent } from './use-vote-event';
import type { VoteValue } from '@vegaprotocol/types';
import type { VoteEventFieldsFragment } from './__generated__/VoteSubsciption';
+146 -20
View File
@@ -505,6 +505,29 @@ export type CoreSnapshotEdge = {
node: CoreSnapshotData;
};
/** Referral program information reported by data node with additional endedAt timestamp. */
export type CurrentReferralProgram = {
__typename?: 'CurrentReferralProgram';
/** Defined tiers in increasing order. First element will give Tier 1, second element will give Tier 2, etc. */
benefitTiers: Array<BenefitTier>;
/** Timestamp as RFC3339Nano, after which when the current epoch ends, the program will end and benefits will be disabled. */
endOfProgramTimestamp: Scalars['Timestamp'];
/** Timestamp as RFC3339Nano when the program ended. If present, the current program has ended and no program is currently running. */
endedAt?: Maybe<Scalars['Timestamp']>;
/** Unique ID generated from the proposal that created this program. */
id: Scalars['ID'];
/**
* Defined staking tiers in increasing order. First element will give Tier 1,
* second element will give Tier 2, and so on. Determines the level of
* benefit a party can expect based on their staking.
*/
stakingTiers: Array<StakingTier>;
/** Incremental version of the program. It is incremented each time the referral program is edited. */
version: Scalars['Int'];
/** Number of epochs over which to evaluate a referral set's running volume. */
windowLength: Scalars['Int'];
};
/** A data source contains the data sent by a data source */
export type Data = {
__typename?: 'Data';
@@ -1607,6 +1630,8 @@ export type LiquidityProvider = {
marketId: Scalars['ID'];
/** Party ID of the liquidity provider */
partyId: Scalars['ID'];
/** SLA performance statistics */
sla?: Maybe<LiquidityProviderSLA>;
};
/** Connection type for retrieving cursor-based paginated liquidity provider information */
@@ -1642,6 +1667,29 @@ export type LiquidityProviderFeeShare = {
virtualStake: Scalars['String'];
};
/** The SLA statistics for each liquidity provider */
export type LiquidityProviderSLA = {
__typename?: 'LiquidityProviderSLA';
/** Indicates how often LP meets the commitment during the current epoch. */
currentEpochFractionOfTimeOnBook: Scalars['String'];
/** Determines how the fee penalties from past epochs affect future fee revenue. */
hysteresisPeriodFeePenalties?: Maybe<Array<Scalars['String']>>;
/** Indicates the bond penalty amount applied in the previous epoch. */
lastEpochBondPenalty: Scalars['String'];
/** Indicates the fee penalty amount applied in the previous epoch. */
lastEpochFeePenalty: Scalars['String'];
/** Indicates how often LP met the commitment in the previous epoch. */
lastEpochFractionOfTimeOnBook: Scalars['String'];
/** Notional volume of orders within the range provided on the buy side of the book. */
notionalVolumeBuys: Scalars['String'];
/** Notional volume of orders within the range provided on the sell side of the book. */
notionalVolumeSells: Scalars['String'];
/** The liquidity provider party ID */
party: Party;
/** Represents the total amount of funds LP must supply. The amount to be supplied is in the markets settlement currency, spread on both buy and sell sides of the order book within a defined range. */
requiredLiquidity: Scalars['String'];
};
/** The command to be sent to the chain for a liquidity provision submission */
export type LiquidityProvision = {
__typename?: 'LiquidityProvision';
@@ -2030,6 +2078,8 @@ export type MarketData = {
lastTradedPrice: Scalars['String'];
/** The equity like share of liquidity fee for each liquidity provider */
liquidityProviderFeeShare?: Maybe<Array<LiquidityProviderFeeShare>>;
/** SLA performance statistics */
liquidityProviderSla?: Maybe<Array<LiquidityProviderSLA>>;
/** The mark price (an unsigned integer) */
markPrice: Scalars['String'];
/** Market of the associated mark price */
@@ -2562,6 +2612,29 @@ export type ObservableLiquidityProviderFeeShare = {
partyId: Scalars['ID'];
};
/** The SLA statistics for each liquidity provider */
export type ObservableLiquidityProviderSLA = {
__typename?: 'ObservableLiquidityProviderSLA';
/** Indicates how often LP meets the commitment during the current epoch. */
currentEpochFractionOfTimeOnBook: Scalars['String'];
/** Determines how the fee penalties from past epochs affect future fee revenue. */
hysteresisPeriodFeePenalties?: Maybe<Array<Scalars['String']>>;
/** Indicates the bond penalty amount applied in the previous epoch. */
lastEpochBondPenalty: Scalars['String'];
/** Indicates the fee penalty amount applied in the previous epoch. */
lastEpochFeePenalty: Scalars['String'];
/** Indicates how often LP meets the commitment during last epoch. */
lastEpochFractionOfTimeOnBook: Scalars['String'];
/** Notional volume of orders within the range provided on the buy side of the book. */
notionalVolumeBuys: Scalars['String'];
/** Notional volume of orders within the range provided on the sell side of the book. */
notionalVolumeSells: Scalars['String'];
/** The liquidity provider party ID */
party: Scalars['ID'];
/** Represents the total amount of funds LP must supply. The amount to be supplied is in the markets settlement currency, spread on both buy and sell sides of the order book within a defined range. */
requiredLiquidity: Scalars['String'];
};
/** Live data of a Market */
export type ObservableMarketData = {
__typename?: 'ObservableMarketData';
@@ -2595,6 +2668,8 @@ export type ObservableMarketData = {
lastTradedPrice: Scalars['String'];
/** The equity like share of liquidity fee for each liquidity provider */
liquidityProviderFeeShare?: Maybe<Array<ObservableLiquidityProviderFeeShare>>;
/** SLA performance statistics */
liquidityProviderSla?: Maybe<Array<ObservableLiquidityProviderSLA>>;
/** The mark price (an unsigned integer) */
markPrice: Scalars['String'];
/** The market growth factor for the last market time window */
@@ -3289,6 +3364,15 @@ export type PartyActivityStreak = {
tradedVolume: Scalars['String'];
};
/** An amount received by a party as a reward or a discount */
export type PartyAmount = {
__typename?: 'PartyAmount';
/** Amount received by the party */
amount: Scalars['String'];
/** Id of the party that received the payment */
partyId: Scalars['String'];
};
/** Connection type for retrieving cursor-based paginated party information */
export type PartyConnection = {
__typename?: 'PartyConnection';
@@ -3861,6 +3945,8 @@ export type ProposalTerms = {
/** Various proposal types that are supported by Vega */
export enum ProposalType {
/** Proposal to cancel a transfer */
TYPE_CANCEL_TRANSFER = 'TYPE_CANCEL_TRANSFER',
/** Proposal to change Vega network parameters */
TYPE_NETWORK_PARAMETERS = 'TYPE_NETWORK_PARAMETERS',
/** Proposal to add a new asset */
@@ -3869,10 +3955,22 @@ export enum ProposalType {
TYPE_NEW_FREE_FORM = 'TYPE_NEW_FREE_FORM',
/** Propose a new market */
TYPE_NEW_MARKET = 'TYPE_NEW_MARKET',
/** Propose a new spot market */
TYPE_NEW_SPOT_MARKET = 'TYPE_NEW_SPOT_MARKET',
/** Propose a new transfer */
TYPE_NEW_TRANSFER = 'TYPE_NEW_TRANSFER',
/** Proposal to update an existing asset */
TYPE_UPDATE_ASSET = 'TYPE_UPDATE_ASSET',
/** Update an existing market */
TYPE_UPDATE_MARKET = 'TYPE_UPDATE_MARKET'
TYPE_UPDATE_MARKET = 'TYPE_UPDATE_MARKET',
/** Proposal for updating the state of a market */
TYPE_UPDATE_MARKET_STATE = 'TYPE_UPDATE_MARKET_STATE',
/** Proposal to update the referral program */
TYPE_UPDATE_REFERRAL_PROGRAM = 'TYPE_UPDATE_REFERRAL_PROGRAM',
/** Update an existing spot market */
TYPE_UPDATE_SPOT_MARKET = 'TYPE_UPDATE_SPOT_MARKET',
/** Proposal to update the volume discount program */
TYPE_UPDATE_VOLUME_DISCOUNT_PROGRAM = 'TYPE_UPDATE_VOLUME_DISCOUNT_PROGRAM'
}
export type ProposalVote = {
@@ -3998,7 +4096,7 @@ export type Query = {
/** List core snapshots */
coreSnapshots?: Maybe<CoreSnapshotConnection>;
/** Get the current referral program */
currentReferralProgram?: Maybe<ReferralProgram>;
currentReferralProgram?: Maybe<CurrentReferralProgram>;
/** Find a deposit using its ID */
deposit?: Maybe<Deposit>;
/** Fetch all deposits */
@@ -4095,6 +4193,8 @@ export type Query = {
protocolUpgradeProposals?: Maybe<ProtocolUpgradeProposalConnection>;
/** Flag indicating whether the data-node is ready to begin the protocol upgrade */
protocolUpgradeStatus?: Maybe<ProtocolUpgradeStatus>;
/** Get referrer fee and discount stats */
referralFeeStats?: Maybe<ReferralSetFeeStats>;
referralSetReferees: ReferralSetRefereeConnection;
/** List referral sets */
referralSets: ReferralSetConnection;
@@ -4259,6 +4359,7 @@ export type QueryestimatePositionArgs = {
marketId: Scalars['ID'];
openVolume: Scalars['String'];
orders?: InputMaybe<Array<OrderInfo>>;
scaleLiquidationPriceToMarketDecimals?: InputMaybe<Scalars['Boolean']>;
};
@@ -4450,6 +4551,14 @@ export type QueryprotocolUpgradeProposalsArgs = {
};
/** Queries allow a caller to read data and filter data via GraphQL. */
export type QueryreferralFeeStatsArgs = {
assetId?: InputMaybe<Scalars['ID']>;
epoch?: InputMaybe<Scalars['Int']>;
marketId?: InputMaybe<Scalars['ID']>;
};
/** Queries allow a caller to read data and filter data via GraphQL. */
export type QueryreferralSetRefereesArgs = {
id?: InputMaybe<Scalars['ID']>;
@@ -4595,6 +4704,8 @@ export type RefereeStats = {
__typename?: 'RefereeStats';
/** Discount factor applied to the party. */
discountFactor: Scalars['String'];
/** Current referee notional taker volume */
epochNotionalTakerVolume: Scalars['String'];
/** Unique ID of the party. */
partyId: Scalars['ID'];
/** Reward factor applied to the party. */
@@ -4606,10 +4717,8 @@ export type ReferralProgram = {
__typename?: 'ReferralProgram';
/** Defined tiers in increasing order. First element will give Tier 1, second element will give Tier 2, etc. */
benefitTiers: Array<BenefitTier>;
/** Timestamp as RFC3339Nano, after which when the current epoch ends, the programs status will become STATE_CLOSED and benefits will be disabled. */
endOfProgramTimestamp: Scalars['Timestamp'];
/** Timestamp as RFC3339Nano when the program ended. If present, the current program has ended and no program is currently running. */
endedAt?: Maybe<Scalars['Timestamp']>;
/** Timestamp as RFC3339, after which when the current epoch ends, the programs will end and benefits will be disabled. */
endOfProgramTimestamp: Scalars['String'];
/** Unique ID generated from the proposal that created this program. */
id: Scalars['ID'];
/**
@@ -4667,6 +4776,25 @@ export type ReferralSetEdge = {
node: ReferralSet;
};
/** Referral rewards and discounts that have been applied on a specific market/asset up to the given epoch. */
export type ReferralSetFeeStats = {
__typename?: 'ReferralSetFeeStats';
/** The settlement asset of the market. */
assetId: Scalars['String'];
/** The epoch for which these stats were valid. */
epoch: Scalars['Int'];
/** The market the fees were paid in */
marketId: Scalars['String'];
/** The total referral discounts applied to all referee taker fees */
refereesDiscountApplied: Array<PartyAmount>;
/** The total referral rewards generated by all referee taker fees. */
referrerRewardsGenerated: Array<ReferrerRewardsGenerated>;
/** The total referral rewards paid to the referrer of the referral set. */
totalRewardsPaid: Array<PartyAmount>;
/** The total volume discounts applied to all referee taker fees */
volumeDiscountApplied: Array<PartyAmount>;
};
/** Data relating to referees that have joined a referral set */
export type ReferralSetReferee = {
__typename?: 'ReferralSetReferee';
@@ -4710,6 +4838,15 @@ export type ReferralSetStats = {
setId: Scalars['ID'];
};
/** Rewards generated for referrers by each of their referees */
export type ReferrerRewardsGenerated = {
__typename?: 'ReferrerRewardsGenerated';
/** The amount of rewards generated per party */
generatedReward: Array<PartyAmount>;
/** ID of the referral set's referrer */
referrerId: Scalars['String'];
};
/** Reward information for a single party */
export type Reward = {
__typename?: 'Reward';
@@ -5152,10 +5289,10 @@ export enum StopOrderRejectionReason {
REJECTION_REASON_MAX_STOP_ORDERS_PER_PARTY_REACHED = 'REJECTION_REASON_MAX_STOP_ORDERS_PER_PARTY_REACHED',
/** Stop orders submission must be reduce only */
REJECTION_REASON_MUST_BE_REDUCE_ONLY = 'REJECTION_REASON_MUST_BE_REDUCE_ONLY',
/** This stop order does not close the position */
REJECTION_REASON_STOP_ORDER_DOES_NOT_CLOSE_POSITION = 'REJECTION_REASON_STOP_ORDER_DOES_NOT_CLOSE_POSITION',
/** Stop orders are not allowed without a position */
REJECTION_REASON_STOP_ORDER_NOT_ALLOWED_WITHOUT_A_POSITION = 'REJECTION_REASON_STOP_ORDER_NOT_ALLOWED_WITHOUT_A_POSITION',
/** This stop order does not close the position */
REJECTION_REASON_STOP_ORDER_NOT_CLOSING_THE_POSITION = 'REJECTION_REASON_STOP_ORDER_NOT_CLOSING_THE_POSITION',
/** Trading is not allowed yet */
REJECTION_REASON_TRADING_NOT_ALLOWED = 'REJECTION_REASON_TRADING_NOT_ALLOWED'
}
@@ -5942,18 +6079,7 @@ export type UpdateProductConfiguration = UpdateFutureProduct | UpdatePerpetualPr
export type UpdateReferralProgram = {
__typename?: 'UpdateReferralProgram';
/** Benefit tiers for the program */
benefitTiers: Array<BenefitTier>;
/** The end time of the program */
endOfProgramTimestamp: Scalars['Timestamp'];
/** ID of the proposal that created the referral program */
id: Scalars['ID'];
/** Determines the level of benefit a party can expect based on their staking */
stakingTiers: Array<StakingTier>;
/** Current version of the referral program */
version: Scalars['Int'];
/** The window legnth to consider for the referral program */
windowLength: Scalars['Int'];
changes: ReferralProgram;
};
/** Update an existing spot market on Vega */
@@ -15,7 +15,7 @@ export function CopyWithTooltip({ children, text }: CopyWithTooltipProps) {
return (
<CopyToClipboard text={text} onCopy={() => setCopied(true)}>
{/* Needs this wrapping div as tooltip component interfers with element used to capture click for copy */}
{/* Needs this wrapping div as tooltip component interferes with element used to capture click for copy */}
<span>
<Tooltip description="Copied" open={copied} align="center">
{children}
+1
View File
@@ -15,3 +15,4 @@ export * from './lib/time';
export * from './lib/validate';
export * from './lib/resolve-network-name';
export * from './lib/is-test-env';
export * from './lib/constants';
+1
View File
@@ -0,0 +1 @@
export const MAXGOINT64 = '9223372036854775807';
@@ -1,5 +0,0 @@
query ChainId {
statistics {
chainId
}
}
-45
View File
@@ -1,45 +0,0 @@
import * as Types from '@vegaprotocol/types';
import { gql } from '@apollo/client';
import * as Apollo from '@apollo/client';
const defaultOptions = {} as const;
export type ChainIdQueryVariables = Types.Exact<{ [key: string]: never; }>;
export type ChainIdQuery = { __typename?: 'Query', statistics: { __typename?: 'Statistics', chainId: string } };
export const ChainIdDocument = gql`
query ChainId {
statistics {
chainId
}
}
`;
/**
* __useChainIdQuery__
*
* To run a query within a React component, call `useChainIdQuery` and pass it any options that fit your needs.
* When your component renders, `useChainIdQuery` 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 } = useChainIdQuery({
* variables: {
* },
* });
*/
export function useChainIdQuery(baseOptions?: Apollo.QueryHookOptions<ChainIdQuery, ChainIdQueryVariables>) {
const options = {...defaultOptions, ...baseOptions}
return Apollo.useQuery<ChainIdQuery, ChainIdQueryVariables>(ChainIdDocument, options);
}
export function useChainIdLazyQuery(baseOptions?: Apollo.LazyQueryHookOptions<ChainIdQuery, ChainIdQueryVariables>) {
const options = {...defaultOptions, ...baseOptions}
return Apollo.useLazyQuery<ChainIdQuery, ChainIdQueryVariables>(ChainIdDocument, options);
}
export type ChainIdQueryHookResult = ReturnType<typeof useChainIdQuery>;
export type ChainIdLazyQueryHookResult = ReturnType<typeof useChainIdLazyQuery>;
export type ChainIdQueryResult = Apollo.QueryResult<ChainIdQuery, ChainIdQueryVariables>;
@@ -1,16 +0,0 @@
import type { ChainIdQuery } from './__generated__/ChainId';
import merge from 'lodash/merge';
import type { PartialDeep } from 'type-fest';
export const chainIdQuery = (
override?: PartialDeep<ChainIdQuery>
): ChainIdQuery => {
const defaultResult = {
statistics: {
__typename: 'Statistics',
chainId: 'test-id',
},
};
return merge(defaultResult, override);
};
@@ -1,6 +1,4 @@
import { act, fireEvent, render, screen } from '@testing-library/react';
import type { MockedResponse } from '@apollo/client/testing';
import { MockedProvider } from '@apollo/client/testing';
import type { VegaWalletConfig } from '../provider';
import { VegaWalletProvider } from '../provider';
import { VegaConnectDialog, CLOSE_DELAY } from './connect-dialog';
@@ -13,8 +11,6 @@ import {
ViewConnector,
WalletError,
} from '../connectors';
import type { ChainIdQuery } from './__generated__/ChainId';
import { ChainIdDocument } from './__generated__/ChainId';
import {
mockBrowserWallet,
clearBrowserWallet,
@@ -26,6 +22,7 @@ const mockUpdateDialogOpen = jest.fn();
const mockCloseVegaDialog = jest.fn();
let mockIsDesktopRunning = true;
const mockChainId = 'chain-id';
jest.mock('../use-is-wallet-service-running', () => ({
useIsWalletServiceRunning: jest
@@ -33,6 +30,10 @@ jest.mock('../use-is-wallet-service-running', () => ({
.mockImplementation(() => mockIsDesktopRunning),
}));
jest.mock('./use-chain-id', () => ({
useChainId: jest.fn().mockImplementation(() => mockChainId),
}));
let defaultProps: VegaConnectDialogProps;
const INITIAL_KEY = 'some-key';
@@ -60,8 +61,6 @@ beforeEach(() => {
});
});
const mockChainId = 'chain-id';
const defaultConfig: VegaWalletConfig = {
network: 'TESTNET',
vegaUrl: 'https://vega.xyz',
@@ -78,24 +77,10 @@ function generateJSX(
props?: Partial<VegaConnectDialogProps>,
config?: Partial<VegaWalletConfig>
) {
const chainIdMock: MockedResponse<ChainIdQuery> = {
request: {
query: ChainIdDocument,
},
result: {
data: {
statistics: {
chainId: mockChainId,
},
},
},
};
return (
<MockedProvider mocks={[chainIdMock]}>
<VegaWalletProvider config={{ ...defaultConfig, ...config }}>
<VegaConnectDialog {...defaultProps} {...props} />
</VegaWalletProvider>
</MockedProvider>
<VegaWalletProvider config={{ ...defaultConfig, ...config }}>
<VegaConnectDialog {...defaultProps} {...props} />
</VegaWalletProvider>
);
}
@@ -35,13 +35,13 @@ import type { Status as JsonRpcStatus } from '../use-json-rpc-connect';
import { useJsonRpcConnect } from '../use-json-rpc-connect';
import type { Status as InjectedStatus } from '../use-injected-connector';
import { useInjectedConnector } from '../use-injected-connector';
import { useChainIdQuery } from './__generated__/ChainId';
import { useVegaWallet } from '../use-vega-wallet';
import { InjectedConnectorForm } from './injected-connector-form';
import { isBrowserWalletInstalled } from '../utils';
import { useIsWalletServiceRunning } from '../use-is-wallet-service-running';
import { SnapStatus, useSnapStatus } from '../use-snap-status';
import { useVegaWalletDialogStore } from './vega-wallet-dialog-store';
import { useChainId } from './use-chain-id';
export const CLOSE_DELAY = 1700;
@@ -82,12 +82,12 @@ export const VegaConnectDialog = ({
// Ensure we have a chain Id so we can compare with wallet chain id.
// This value will already be in the cache, if it failed the app wont render
const { data } = useChainIdQuery();
const chainId = useChainId();
const content = data && (
const content = chainId && (
<ConnectDialogContainer
connectors={connectors}
appChainId={data.statistics.chainId}
appChainId={chainId}
riskMessage={riskMessage}
onClose={onClose}
/>
@@ -0,0 +1,37 @@
import { useEffect, useState } from 'react';
import { useVegaWallet } from '../use-vega-wallet';
const cache: Record<string, string> = {};
export const useChainId = () => {
const { vegaUrl } = useVegaWallet();
const [chainId, setChainId] = useState<undefined | string>(cache[vegaUrl]);
const [fetchAttempt, setFetchAttempt] = useState(1);
useEffect(() => {
let isCancelled = false;
if (cache[vegaUrl]) {
setChainId(cache[vegaUrl]);
return;
}
fetch(vegaUrl.replace('graphql', 'statistics'))
.then((response) => response.json())
.then((response) => {
if (isCancelled) {
return;
}
if (!response?.statistics?.chainId) {
throw new Error('statistics.chainId not present in fetched response');
}
setChainId(response?.statistics?.chainId);
})
.catch(() => {
if (fetchAttempt < 3) {
setFetchAttempt((value) => (value += 1));
}
});
return () => {
isCancelled = true;
};
}, [fetchAttempt, vegaUrl]);
return chainId;
};
-9
View File
@@ -1,18 +1,9 @@
export * from './connectors';
export * from './context';
export * from './use-vega-transaction';
export * from './use-vega-wallet';
export * from './use-vega-transaction-manager';
export * from './use-vega-transaction-store';
export * from './use-vega-transaction-updater';
export * from './use-transaction-result';
export * from './use-eager-connect';
export * from './manage-dialog';
export * from './provider';
export * from './connect-dialog';
export * from './utils';
export * from './storage';
export * from './types';
export * from './vega-transaction-dialog';
export * from './__generated__/TransactionResult';
export * from './__generated__/WithdrawalApproval';
+7
View File
@@ -28,3 +28,10 @@ export * from './lib/web3-provider';
export * from './lib/withdrawal-approval-dialog';
export * from './lib/withdrawal-approval-status';
export * from './lib/default-web3-provider';
export * from './lib/use-vega-transaction-manager';
export * from './lib/use-vega-transaction-store';
export * from './lib/use-vega-transaction-updater';
export * from './lib/use-transaction-result';
export * from './lib/types';
export * from './lib/__generated__/TransactionResult';
export * from './lib/__generated__/WithdrawalApproval';
+74
View File
@@ -0,0 +1,74 @@
query OrderById($orderId: ID!) {
orderByID(id: $orderId) {
id
market {
id
}
type
side
size
status
rejectionReason
price
timeInForce
remaining
expiresAt
createdAt
updatedAt
postOnly
reduceOnly
liquidityProvision {
__typename
}
peggedOrder {
__typename
reference
offset
}
icebergOrder {
__typename
peakSize
minimumVisibleSize
reservedRemaining
}
}
}
query StopOrderById($stopOrderId: ID!) {
stopOrder(id: $stopOrderId) {
id
ocoLinkId
expiresAt
expiryStrategy
triggerDirection
status
createdAt
updatedAt
partyId
marketId
trigger {
... on StopOrderPrice {
price
}
... on StopOrderTrailingPercentOffset {
trailingPercentOffset
}
}
submission {
marketId
price
size
side
timeInForce
expiresAt
type
reference
peggedOrder {
reference
offset
}
postOnly
reduceOnly
}
}
}
+153
View File
@@ -0,0 +1,153 @@
import * as Types from '@vegaprotocol/types';
import { gql } from '@apollo/client';
import * as Apollo from '@apollo/client';
const defaultOptions = {} as const;
export type OrderByIdQueryVariables = Types.Exact<{
orderId: Types.Scalars['ID'];
}>;
export type OrderByIdQuery = { __typename?: 'Query', orderByID: { __typename?: 'Order', id: string, type?: Types.OrderType | null, side: Types.Side, size: string, status: Types.OrderStatus, rejectionReason?: Types.OrderRejectionReason | null, price: string, timeInForce: Types.OrderTimeInForce, remaining: string, expiresAt?: any | null, createdAt: any, updatedAt?: any | null, postOnly?: boolean | null, reduceOnly?: boolean | null, market: { __typename?: 'Market', id: string }, liquidityProvision?: { __typename: 'LiquidityProvision' } | null, peggedOrder?: { __typename: 'PeggedOrder', reference: Types.PeggedReference, offset: string } | null, icebergOrder?: { __typename: 'IcebergOrder', peakSize: string, minimumVisibleSize: string, reservedRemaining: string } | null } };
export type StopOrderByIdQueryVariables = Types.Exact<{
stopOrderId: Types.Scalars['ID'];
}>;
export type StopOrderByIdQuery = { __typename?: 'Query', stopOrder?: { __typename?: 'StopOrder', id: string, ocoLinkId?: string | null, expiresAt?: any | null, expiryStrategy?: Types.StopOrderExpiryStrategy | null, triggerDirection: Types.StopOrderTriggerDirection, status: Types.StopOrderStatus, createdAt: any, updatedAt?: any | null, partyId: string, marketId: string, trigger: { __typename?: 'StopOrderPrice', price: string } | { __typename?: 'StopOrderTrailingPercentOffset', trailingPercentOffset: string }, submission: { __typename?: 'OrderSubmission', marketId: string, price: string, size: string, side: Types.Side, timeInForce: Types.OrderTimeInForce, expiresAt: any, type: Types.OrderType, reference?: string | null, postOnly?: boolean | null, reduceOnly?: boolean | null, peggedOrder?: { __typename?: 'PeggedOrder', reference: Types.PeggedReference, offset: string } | null } } | null };
export const OrderByIdDocument = gql`
query OrderById($orderId: ID!) {
orderByID(id: $orderId) {
id
market {
id
}
type
side
size
status
rejectionReason
price
timeInForce
remaining
expiresAt
createdAt
updatedAt
postOnly
reduceOnly
liquidityProvision {
__typename
}
peggedOrder {
__typename
reference
offset
}
icebergOrder {
__typename
peakSize
minimumVisibleSize
reservedRemaining
}
}
}
`;
/**
* __useOrderByIdQuery__
*
* To run a query within a React component, call `useOrderByIdQuery` and pass it any options that fit your needs.
* When your component renders, `useOrderByIdQuery` 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 } = useOrderByIdQuery({
* variables: {
* orderId: // value for 'orderId'
* },
* });
*/
export function useOrderByIdQuery(baseOptions: Apollo.QueryHookOptions<OrderByIdQuery, OrderByIdQueryVariables>) {
const options = {...defaultOptions, ...baseOptions}
return Apollo.useQuery<OrderByIdQuery, OrderByIdQueryVariables>(OrderByIdDocument, options);
}
export function useOrderByIdLazyQuery(baseOptions?: Apollo.LazyQueryHookOptions<OrderByIdQuery, OrderByIdQueryVariables>) {
const options = {...defaultOptions, ...baseOptions}
return Apollo.useLazyQuery<OrderByIdQuery, OrderByIdQueryVariables>(OrderByIdDocument, options);
}
export type OrderByIdQueryHookResult = ReturnType<typeof useOrderByIdQuery>;
export type OrderByIdLazyQueryHookResult = ReturnType<typeof useOrderByIdLazyQuery>;
export type OrderByIdQueryResult = Apollo.QueryResult<OrderByIdQuery, OrderByIdQueryVariables>;
export const StopOrderByIdDocument = gql`
query StopOrderById($stopOrderId: ID!) {
stopOrder(id: $stopOrderId) {
id
ocoLinkId
expiresAt
expiryStrategy
triggerDirection
status
createdAt
updatedAt
partyId
marketId
trigger {
... on StopOrderPrice {
price
}
... on StopOrderTrailingPercentOffset {
trailingPercentOffset
}
}
submission {
marketId
price
size
side
timeInForce
expiresAt
type
reference
peggedOrder {
reference
offset
}
postOnly
reduceOnly
}
}
}
`;
/**
* __useStopOrderByIdQuery__
*
* To run a query within a React component, call `useStopOrderByIdQuery` and pass it any options that fit your needs.
* When your component renders, `useStopOrderByIdQuery` 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 } = useStopOrderByIdQuery({
* variables: {
* stopOrderId: // value for 'stopOrderId'
* },
* });
*/
export function useStopOrderByIdQuery(baseOptions: Apollo.QueryHookOptions<StopOrderByIdQuery, StopOrderByIdQueryVariables>) {
const options = {...defaultOptions, ...baseOptions}
return Apollo.useQuery<StopOrderByIdQuery, StopOrderByIdQueryVariables>(StopOrderByIdDocument, options);
}
export function useStopOrderByIdLazyQuery(baseOptions?: Apollo.LazyQueryHookOptions<StopOrderByIdQuery, StopOrderByIdQueryVariables>) {
const options = {...defaultOptions, ...baseOptions}
return Apollo.useLazyQuery<StopOrderByIdQuery, StopOrderByIdQueryVariables>(StopOrderByIdDocument, options);
}
export type StopOrderByIdQueryHookResult = ReturnType<typeof useStopOrderByIdQuery>;
export type StopOrderByIdLazyQueryHookResult = ReturnType<typeof useStopOrderByIdLazyQuery>;
export type StopOrderByIdQueryResult = Apollo.QueryResult<StopOrderByIdQuery, StopOrderByIdQueryVariables>;
+4
View File
@@ -0,0 +1,4 @@
import '@testing-library/jest-dom';
import ResizeObserver from 'resize-observer-polyfill';
global.ResizeObserver = ResizeObserver;
@@ -7,7 +7,7 @@ import type { Token } from '@vegaprotocol/smart-contracts';
import type {
DepositBusEventFieldsFragment,
WithdrawalBusEventFieldsFragment,
} from '@vegaprotocol/wallet';
} from './__generated__/TransactionResult';
import type { EthTxState } from './use-ethereum-transaction';
import { EthTxStatus } from './use-ethereum-transaction';
@@ -3,15 +3,13 @@ import type { MockedResponse } from '@apollo/client/testing';
import { MockedProvider } from '@apollo/client/testing';
import type { ReactNode } from 'react';
import { useEthTransactionUpdater } from './use-ethereum-transaction-updater';
import {
DepositBusEventDocument,
VegaWalletContext,
} from '@vegaprotocol/wallet';
import { DepositBusEventDocument } from './__generated__/TransactionResult';
import { VegaWalletContext } from '@vegaprotocol/wallet';
import type {
DepositBusEventSubscription,
DepositBusEventFieldsFragment,
VegaWalletContextShape,
} from '@vegaprotocol/wallet';
} from './__generated__/TransactionResult';
import type { VegaWalletContextShape } from '@vegaprotocol/wallet';
import type { EthTransactionStore } from './use-ethereum-transaction-store';
import { DepositStatus } from '@vegaprotocol/types';
@@ -1,8 +1,6 @@
import { DepositStatus } from '@vegaprotocol/types';
import {
useDepositBusEventSubscription,
useVegaWallet,
} from '@vegaprotocol/wallet';
import { useVegaWallet } from '@vegaprotocol/wallet';
import { useDepositBusEventSubscription } from './__generated__/TransactionResult';
import { useEthTransactionStore } from './use-ethereum-transaction-store';
export const useEthTransactionUpdater = () => {
@@ -16,8 +16,8 @@ import type {
} from './use-ethereum-withdraw-approvals-store';
import type { EthTransactionStore } from './use-ethereum-transaction-store';
import { WithdrawalApprovalDocument } from '@vegaprotocol/wallet';
import type { WithdrawalApprovalQuery } from '@vegaprotocol/wallet';
import { WithdrawalApprovalDocument } from './__generated__/WithdrawalApproval';
import type { WithdrawalApprovalQuery } from './__generated__/WithdrawalApproval';
import { NetworkParamsDocument } from '@vegaprotocol/network-parameters';
import type { NetworkParamsQuery } from '@vegaprotocol/network-parameters';
@@ -15,9 +15,9 @@ import { useWeb3React } from '@web3-react/core';
import type {
WithdrawalApprovalQuery,
WithdrawalApprovalQueryVariables,
} from '@vegaprotocol/wallet';
} from './__generated__/WithdrawalApproval';
import { WithdrawalApprovalDocument } from '@vegaprotocol/wallet';
import { WithdrawalApprovalDocument } from './__generated__/WithdrawalApproval';
import { useEthTransactionStore } from './use-ethereum-transaction-store';
import {
@@ -1,12 +1,12 @@
import { useEthWithdrawApprovalsStore } from './use-ethereum-withdraw-approvals-store';
import type { VegaStoredTxState } from '@vegaprotocol/wallet';
import type { VegaStoredTxState } from './use-vega-transaction-store';
import { ApprovalStatus } from './use-ethereum-withdraw-approvals-store';
import type { EthWithdrawalApprovalState } from './use-ethereum-withdraw-approvals-store';
const mockFindVegaTransaction = jest.fn<VegaStoredTxState, []>();
const mockDismissVegaTransaction = jest.fn();
jest.mock('@vegaprotocol/wallet', () => ({
jest.mock('./use-vega-transaction-store', () => ({
useVegaTransactionStore: {
getState: () => ({
transactions: {
@@ -1,10 +1,10 @@
import { create } from 'zustand';
import produce from 'immer';
import type BigNumber from 'bignumber.js';
import type { WithdrawalBusEventFieldsFragment } from '@vegaprotocol/wallet';
import { useVegaTransactionStore } from '@vegaprotocol/wallet';
import type { WithdrawalBusEventFieldsFragment } from './__generated__/TransactionResult';
import { useVegaTransactionStore } from './use-vega-transaction-store';
import type { WithdrawalApprovalQuery } from '@vegaprotocol/wallet';
import type { WithdrawalApprovalQuery } from './__generated__/WithdrawalApproval';
import { subscribeWithSelector } from 'zustand/middleware';
export enum ApprovalStatus {
@@ -2,7 +2,7 @@ import { useCallback } from 'react';
import { useBridgeContract } from './use-bridge-contract';
import BigNumber from 'bignumber.js';
import { addDecimal } from '@vegaprotocol/utils';
import type { WithdrawalBusEventFieldsFragment } from '@vegaprotocol/wallet';
import type { WithdrawalBusEventFieldsFragment } from './__generated__/TransactionResult';
import { localLoggerFactory } from '@vegaprotocol/logger';
type Asset = Pick<
@@ -1,19 +1,20 @@
import { useVegaTransactionManager } from './use-vega-transaction-manager';
import { renderHook } from '@testing-library/react';
import waitForNextTick from 'flush-promises';
import type { TransactionResponse } from './connectors/vega-connector';
import type { TransactionResponse } from '@vegaprotocol/wallet';
import { VegaTxStatus } from './types';
import type {
VegaTransactionStore,
VegaStoredTxState,
} from './use-vega-transaction-store';
const mockSendTx = jest.fn<Promise<Partial<TransactionResponse> | null>, []>();
const mockSendTx = jest.fn();
const pubKey = 'pubKey';
const mockDisconnect = jest.fn();
jest.mock('./use-vega-wallet', () => ({
jest.mock('@vegaprotocol/wallet', () => ({
...jest.requireActual('@vegaprotocol/wallet'),
useVegaWallet: () => ({
sendTx: mockSendTx,
pubKey,

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