Compare commits

...
24 changed files with 621 additions and 462 deletions
@@ -12,6 +12,7 @@ import {
SPECIAL_CASE_NETWORK,
SPECIAL_CASE_NETWORK_ID,
} from '../../links/party-link/party-link';
import { txSignatureToDeterministicId } from '../lib/deterministic-ids';
type Transfer = components['schemas']['commandsv1Transfer'];
@@ -63,10 +64,16 @@ export const TxDetailsTransfer = ({
return (
<>
<TableWithTbody className="mb-8" allowWrap={true}>
<TableRow modifier="bordered">
<TableRow modifier="bordered" data-testid="type">
<TableCell {...sharedHeaderProps}>{t('Type')}</TableCell>
<TableCell>{getTypeLabelForTransfer(transfer)}</TableCell>
</TableRow>
<TableRow modifier="bordered" data-testid="id">
<TableCell {...sharedHeaderProps}>{t('Transfer ID')}</TableCell>
<TableCell>
{txSignatureToDeterministicId(txData.signature.value)}
</TableCell>
</TableRow>
<TxDetailsShared
txData={txData}
pubKey={pubKey}
@@ -74,7 +81,7 @@ export const TxDetailsTransfer = ({
hideTypeRow={true}
/>
{from ? (
<TableRow modifier="bordered">
<TableRow modifier="bordered" data-testid="from">
<TableCell>{t('From')}</TableCell>
<TableCell>
<PartyLink id={from} />
@@ -82,7 +89,7 @@ export const TxDetailsTransfer = ({
</TableRow>
) : null}
{transfer.to ? (
<TableRow modifier="bordered">
<TableRow modifier="bordered" data-testid="to">
<TableCell>{t('To')}</TableCell>
<TableCell>
<PartyLink id={transfer.to} />
@@ -90,7 +97,7 @@ export const TxDetailsTransfer = ({
</TableRow>
) : null}
{transfer.asset && transfer.amount ? (
<TableRow modifier="bordered">
<TableRow modifier="bordered" data-testid="amount">
<TableCell>{t('Amount')}</TableCell>
<TableCell>
<SizeInAsset assetId={transfer.asset} size={transfer.amount} />
@@ -1,6 +1,15 @@
import { getTypeLabelForTransfer } from './details/tx-transfer';
import type { BlockExplorerTransactionResult } from '../../routes/types/block-explorer-response';
import type { TendermintBlocksResponse } from '../../routes/blocks/tendermint-blocks-response';
import type { components } from '../../../types/explorer';
import {
TxDetailsTransfer,
getTypeLabelForTransfer,
} from './details/tx-transfer';
import { MockedProvider } from '@apollo/client/testing';
import { MemoryRouter } from 'react-router-dom';
import { render } from '@testing-library/react';
type Transfer = components['schemas']['commandsv1Transfer'];
describe('TX: Transfer: getLabelForTransfer', () => {
@@ -56,3 +65,70 @@ describe('TX: Transfer: getLabelForTransfer', () => {
expect(getTypeLabelForTransfer(mock)).toEqual('Transfer');
});
});
describe('TxDetailsTransfer', () => {
const mockBlockData = {
result: {
block: {
header: {
height: '123',
},
},
},
};
const mockTxData: Partial<BlockExplorerTransactionResult> = {
hash: 'test',
submitter:
'e1943eea46fed576cf2be42972f3c5515ad3d0ac7ac013f56677c12a53a1b3ed',
command: {
nonce: '5188810881378065222',
blockHeight: '14951513',
transfer: {
fromAccountType: 'ACCOUNT_TYPE_GENERAL',
to: '78432a2808f20b18a46ccc6a917bdc4d63c2b9e7007f777bdcab5a9f462c5ba6',
toAccountType: 'ACCOUNT_TYPE_GENERAL',
asset:
'dd20590509d30d20bdbbe64dc1090c1140c7690121a9b9940bc66f62dfa2e599',
amount: '4800000000',
reference: '',
oneOff: {
deliverOn: '0',
},
},
},
signature: {
value:
'610c2e196a7d4fed4413b9e82af267b1ff3e30e943df3a3d28096fd60604d430d752fbaf6dd4f84d496be78885bb6118f40560bff7832c06bd7a3d67b718b700',
},
};
it('renders basic transfer details', () => {
const { getByTestId } = render(
<MockedProvider>
<MemoryRouter>
<TxDetailsTransfer
txData={mockTxData as BlockExplorerTransactionResult}
pubKey={mockTxData.command.submitter}
blockData={mockBlockData as TendermintBlocksResponse}
/>
</MemoryRouter>
</MockedProvider>
);
const id = getByTestId('id');
expect(id.children[0].textContent).toEqual('Transfer ID');
expect(id.children[1].textContent).toEqual(
'51f3bab5eb2637651012507a64d497790a734248792c16e5cf36df8984074fbd'
);
const type = getByTestId('type');
expect(type.children[1].textContent).toEqual('Transfer');
const from = getByTestId('from');
expect(from.children[1].textContent).toEqual(mockTxData.submitter);
const to = getByTestId('to');
expect(to.children[1].textContent).toEqual(mockTxData.command.transfer.to);
});
});
@@ -128,9 +128,7 @@ describe('<ProposalReferralProgramDetails />', () => {
it('should not render if there are no relevant fields', () => {
const incompleteProposal = generateProposal({
terms: {
change: {
__typename: 'UpdateReferralProgram',
},
change: {},
},
});
+12 -13
View File
@@ -49,10 +49,10 @@ describe('capsule - without MultiSign', { tags: '@slow' }, () => {
cy.wrap(markets[0]).as('market');
});
cy.visit('/#/portfolio');
cy.connectVegaWallet();
});
it('can deposit', function () {
cy.setOnBoardingViewed();
cy.visit('/#/portfolio');
cy.get('[data-testid="pathname-/portfolio"]').should('exist');
@@ -70,6 +70,8 @@ describe('capsule - without MultiSign', { tags: '@slow' }, () => {
cy.getByTestId('deposit-button').click();
connectEthereumWallet('Unknown');
selectAsset(btcName);
cy.get('[data-testid="rich-select-option"]').eq(btcName).click();
cy.getByTestId('approve-default').should(
'contain.text',
`Before you can make a deposit of your chosen asset, ${btcSymbol}, you need to approve its use in your Ethereum wallet`
@@ -120,7 +122,7 @@ describe('capsule - without MultiSign', { tags: '@slow' }, () => {
cy.get('[data-testid="pathname-/portfolio"]').should('exist');
cy.getByTestId(collateralTab).click();
cy.getByTestId('open-transfer').click();
cy.getByTestId('open-transfer').eq(1).click();
cy.getByTestId('transfer-form').should('be.visible');
cy.getByTestId('transfer-form').find('[name="toAddress"]').select(1);
cy.get('select option')
@@ -147,7 +149,8 @@ describe('capsule - without MultiSign', { tags: '@slow' }, () => {
// 0003-WTXN-011
cy.getByTestId('Withdrawals').click();
cy.getByTestId('withdraw-dialog-button').click();
selectAsset(0);
selectAsset(btcName);
cy.get('[data-testid="rich-select-option"]').eq(btcName).click();
cy.get(amountField).focus();
cy.get(amountField).clear().type('1');
cy.getByTestId('submit-withdrawal').click();
@@ -185,19 +188,15 @@ describe('capsule', { tags: '@slow', testIsolation: true }, () => {
it('shows node health', function () {
// 0006-NETW-010
const regex = /^Operational\d+$/;
const market = this.market;
cy.visit(`/#/markets/${market.id}`);
cy.getByTestId('node-health-trigger').realHover();
cy.getByTestId('node-health')
.children()
.first()
.should('contain.text', 'Operational')
.then(($el) => {
const blockHeight = parseInt($el.text());
// block height will increase over the course of the test run so best
// we can do here is check that its showing something sensible
expect(blockHeight).to.be.greaterThan(0);
});
.invoke('text')
.should('match', regex);
cy.getByTestId('node-health')
.children()
.eq(1)
@@ -239,7 +238,6 @@ describe('capsule', { tags: '@slow', testIsolation: true }, () => {
.should('contain.text', order.size);
cy.getByTestId(openOrdersTab).click();
cy.getByTestId('edit', txTimeout).should('contain.text', 'Edit');
cy.getByTestId('tab-open-orders').within(() => {
cy.get('.ag-center-cols-container')
.children()
@@ -280,8 +278,7 @@ describe('capsule', { tags: '@slow', testIsolation: true }, () => {
cy.visit(`/#/markets/${market.id}`);
cy.getByTestId(toastCloseBtn, txTimeout).click();
cy.getByTestId(openOrdersTab).click();
cy.getByTestId('edit', txTimeout).should('be.visible');
cy.getByTestId('edit').first().should('be.visible').click();
cy.getByTestId('edit').first().click();
cy.getByTestId('dialog-title').should('contain.text', 'Edit order');
cy.get('#limitPrice').focus().clear().type(newPrice);
cy.getByTestId('edit-order').find('[type="submit"]').click();
@@ -350,6 +347,7 @@ describe('capsule', { tags: '@slow', testIsolation: true }, () => {
cy.getByTestId('withdraw-dialog-button').click();
connectEthereumWallet('Unknown');
selectAsset(btcName);
cy.get('[data-testid="rich-select-option"]').eq(btcName).click();
cy.get(amountField).clear().type('1');
cy.getByTestId('submit-withdrawal').click();
cy.getByTestId(toastContent, txTimeout).should(
@@ -437,6 +435,7 @@ describe('capsule', { tags: '@slow', testIsolation: true }, () => {
cy.getByTestId('deposit-button').click();
connectEthereumWallet('Unknown');
selectAsset(btcName);
cy.get('[data-testid="rich-select-option"]').eq(btcName).click();
cy.contains('Deposits of tBTC not approved').should('not.exist');
cy.contains('Use maximum').should('be.visible');
cy.get(amountField).clear().type('20000000');
@@ -69,7 +69,7 @@ describe(
cy.contains('Something went wrong').should('not.exist');
cy.contains('Application error').should('not.exist');
cy.getByTestId('tab-liquidity').within(() => {
cy.get('[col-id="party.id"]').eq(1).should('not.be.empty');
cy.get('[col-id="partyId"]').eq(1).should('not.be.empty');
});
});
}
@@ -12,8 +12,7 @@ const marketSummaryBlock = 'header-summary';
const itemValue = 'item-value';
const itemHeader = 'item-header';
const colCommitmentAmount = '[col-id="commitmentAmount"]';
const colAverageEntryValuation = '[col-id="averageEntryValuation"]';
const colEquityLikeShare = '[col-id="equityLikeShare"]';
const colEquityLikeShare = '[col-id="feeShare.equityLikeShare"]';
const colFee = '[col-id="fee"]';
const colCommitmentAmount_1 = '[col-id="commitmentAmount_1"]';
const colBalance = '[col-id="balance"]';
@@ -24,11 +23,16 @@ const colUpdatedAt = '[col-id="updatedAt"] button';
const headers = [
'Party',
'Commitment (tDAI)',
'Share',
'Proposed fee',
'Market valuation at entry',
'Obligation',
'Supplied',
'Fee',
'Adjusted stake share',
'Share',
'Live supplied liquidity',
'Live time fraction on book',
'Live liquidity quality score (%)',
'Last time fraction on the book',
'Last fee penalty',
'Last bond penalty',
'Status',
'Created',
'Updated',
@@ -64,11 +68,8 @@ describe('liquidity table - trading', { tags: '@smoke' }, () => {
// 5002-LIQP-002
cy.get(rowSelector)
.first()
.find('[col-id="party.id"]')
.should(
'have.text',
'69464e35bcb8e8a2900ca0f87acaf252d50cf2ab2fc73694845a16b7c8a0dc6f'
);
.find('[col-id="partyId"]')
.should('have.text', '69464e…dc6f');
cy.get(rowSelector)
.first()
@@ -82,12 +83,6 @@ describe('liquidity table - trading', { tags: '@smoke' }, () => {
cy.get(rowSelector).first().find(colFee).should('have.text', '0.09%');
// 5002-LIQP-013
cy.get(rowSelector)
.first()
.find(colAverageEntryValuation)
.should('have.text', '685,852.93692');
cy.get(rowSelector)
.first()
.find(colCommitmentAmount_1)
@@ -104,7 +99,8 @@ describe('liquidity table - trading', { tags: '@smoke' }, () => {
cy.get(rowSelector).first().find(colCreatedAt).should('not.be.empty');
cy.get(rowSelector).first().find(colUpdatedAt).should('not.be.empty');
});
it.skip('liquidity status column should be sorted properly', () => {
it('liquidity status column should be sorted properly', () => {
// 5002-LIQP-003
const liquidityColDefault = ['Active', 'Pending'];
const liquidityColAsc = ['Active', 'Pending'];
@@ -220,11 +216,8 @@ describe('liquidity table view', { tags: '@smoke' }, () => {
// 5002-LIQP-011
cy.get(rowSelectorLiquidityActive)
.first()
.find('[col-id="party.id"]')
.should(
'have.text',
'69464e35bcb8e8a2900ca0f87acaf252d50cf2ab2fc73694845a16b7c8a0dc6f'
);
.find('[col-id="partyId"]')
.should('have.text', '69464e…dc6f');
cy.get(rowSelectorLiquidityActive)
.first()
@@ -241,12 +234,6 @@ describe('liquidity table view', { tags: '@smoke' }, () => {
.find(colFee)
.should('have.text', '0.09%');
// 5002-LIQP-013
cy.get(rowSelectorLiquidityActive)
.first()
.find(colAverageEntryValuation)
.should('have.text', '685,852.93692');
cy.get(rowSelectorLiquidityActive)
.first()
.find(colCommitmentAmount_1)
@@ -277,11 +264,8 @@ describe('liquidity table view', { tags: '@smoke' }, () => {
cy.getByTestId('Inactive').click();
cy.get(rowSelectorLiquidityInactive)
.first()
.find('[col-id="party.id"]')
.should(
'have.text',
'cc464e35bcb8e8a2900ca0f87acaf252d50cf2ab2fc73694845a16b7c8a0dc6f'
);
.find('[col-id="partyId"]')
.should('have.text', 'cc464e…dc6f');
cy.get(rowSelectorLiquidityInactive)
.first()
@@ -298,11 +282,6 @@ describe('liquidity table view', { tags: '@smoke' }, () => {
.find(colFee)
.should('have.text', '0.40%');
cy.get(rowSelectorLiquidityInactive)
.first()
.find(colAverageEntryValuation)
.should('have.text', '685,852.93692');
cy.get(rowSelectorLiquidityInactive)
.first()
.find(colCommitmentAmount_1)
+2 -6
View File
@@ -30,11 +30,11 @@ import {
blockStatisticsQuery,
networkParamQuery,
liquidityProvisionsQuery,
liquidityProviderFeeShareQuery,
successorMarketQuery,
parentMarketIdQuery,
successorMarketIdsQuery,
successorMarketProposalDetailsQuery,
liquidityProvidersQuery,
} from '@vegaprotocol/mock';
import type { PartialDeep } from 'type-fest';
import type { MarketDataQuery, MarketsQuery } from '@vegaprotocol/markets';
@@ -162,11 +162,7 @@ const mockTradingPage = (
aliasGQLQuery(req, 'Trades', tradesQuery());
aliasGQLQuery(req, 'Chart', chartQuery());
aliasGQLQuery(req, 'LiquidityProvisions', liquidityProvisionsQuery());
aliasGQLQuery(
req,
'LiquidityProviderFeeShare',
liquidityProviderFeeShareQuery
);
aliasGQLQuery(req, 'LiquidityProviders', liquidityProvidersQuery());
aliasGQLQuery(req, 'Candles', candlesQuery());
aliasGQLQuery(req, 'Withdrawals', withdrawalsQuery());
aliasGQLQuery(req, 'NetworkParams', networkParamsQuery());
+6 -6
View File
@@ -3,21 +3,21 @@ NX_ETHERSCAN_URL=https://sepolia.etherscan.io
NX_GITHUB_FEEDBACK_URL=https://github.com/vegaprotocol/feedback/discussions
NX_HOSTED_WALLET_URL=https://wallet.testnet.vega.xyz
NX_SENTRY_DSN=https://2ffce43721964aafa78277c50654ece4@o286262.ingest.sentry.io/6300613
NX_VEGA_CONFIG_URL=https://raw.githubusercontent.com/vegaprotocol/networks-internal/main/stagnet1/vegawallet-stagnet1.toml
NX_VEGA_ENV=STAGNET1
NX_VEGA_EXPLORER_URL=https://explorer.stagnet1.vega.rocks
NX_VEGA_CONFIG_URL=https://raw.githubusercontent.com/vegaprotocol/networks-internal/main/fairground/vegawallet-fairground.toml
NX_VEGA_ENV=TESTNET
NX_VEGA_EXPLORER_URL=https://explorer.fairground.wtf
NX_VEGA_NETWORKS={\"MAINNET\":\"https://console.vega.xyz\",\"TESTNET\":\"https://console.fairground.wtf\",\"STAGNET1\":\"https://trading.stagnet1.vega.rocks\"}
NX_VEGA_TOKEN_URL=https://governance.stagnet1.vega.rocks
NX_VEGA_TOKEN_URL=https://governance.fairground.wtf
NX_VEGA_WALLET_URL=http://localhost:1789
NX_VEGA_DOCS_URL=https://docs.vega.xyz/testnet
NX_VEGA_REPO_URL=https://github.com/vegaprotocol/vega/releases
NX_ANNOUNCEMENTS_CONFIG_URL=https://raw.githubusercontent.com/vegaprotocol/announcements/fairground/announcements.json
NX_WALLETCONNECT_PROJECT_ID=fe8091dc35738863e509fc4947525c72
NX_VEGA_INCIDENT_URL=https://blog.vega.xyz/tagged/vega-incident-reports
NX_VEGA_CONSOLE_URL=https://console.fairground.wtf
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
NX_WALLETCONNECT_PROJECT_ID=fe8091dc35738863e509fc4947525c72
# Cosmic elevator flags
NX_SUCCESSOR_MARKETS=true
@@ -81,7 +81,7 @@ export const ApplyCodeForm = () => {
if (!res) {
setError('code', {
type: 'required',
message: 'The transaction could not be sent',
message: t('The transaction could not be sent'),
});
}
if (res) {
@@ -98,7 +98,7 @@ export const ApplyCodeForm = () => {
message:
err instanceof Error
? err.message
: 'Your code has been rejected',
: t('Your code has been rejected'),
});
}
});
@@ -152,7 +152,7 @@ export const ApplyCodeForm = () => {
<span className="text-vega-green-500">
<VegaIcon name={VegaIconNames.TICK} size={20} />
</span>{' '}
<span className="pt-1">Code applied</span>
<span className="pt-1">{t('Code applied')}</span>
</h3>
</div>
);
@@ -162,7 +162,7 @@ export const ApplyCodeForm = () => {
if (!pubKey) {
return {
disabled: false,
children: 'Connect wallet',
children: t('Connect wallet'),
type: 'button' as ButtonHTMLAttributes<HTMLButtonElement>['type'],
onClick: ((event) => {
event.preventDefault();
@@ -174,7 +174,7 @@ export const ApplyCodeForm = () => {
if (isReadOnly) {
return {
disabled: true,
children: 'Apply a code',
children: t('Apply a code'),
type: 'submit' as ButtonHTMLAttributes<HTMLButtonElement>['type'],
};
}
@@ -182,14 +182,14 @@ export const ApplyCodeForm = () => {
if (status === 'requested') {
return {
disabled: true,
children: 'Confirm in wallet...',
children: t('Confirm in wallet...'),
type: 'submit' as ButtonHTMLAttributes<HTMLButtonElement>['type'],
};
}
return {
disabled: false,
children: 'Apply a code',
children: t('Apply a code'),
type: 'submit' as ButtonHTMLAttributes<HTMLButtonElement>['type'],
};
};
@@ -198,10 +198,10 @@ export const ApplyCodeForm = () => {
<>
<div className="w-2/3 max-w-md mx-auto bg-vega-clight-800 dark:bg-vega-cdark-800 p-8 rounded-lg">
<h3 className="mb-4 text-2xl text-center calt">
Apply a referral code
{t('Apply a referral code')}
</h3>
<p className="mb-4 text-center text-base">
Enter a referral code to get trading discounts.
{t('Enter a referral code to get trading discounts.')}
</p>
<form
className={classNames('w-full flex flex-col gap-4', {
@@ -210,11 +210,11 @@ export const ApplyCodeForm = () => {
onSubmit={handleSubmit(onSubmit)}
>
<label>
<span className="sr-only">Your referral code</span>
<span className="sr-only">{t('Your referral code')}</span>
<Input
hasError={Boolean(errors.code)}
{...register('code', {
required: 'You have to provide a code to apply it.',
required: t('You have to provide a code to apply it.'),
validate: validateCode,
})}
placeholder="Enter a code"
@@ -236,7 +236,7 @@ export const ApplyCodeForm = () => {
) : null}
{previewData ? (
<div className="mt-10">
<h2 className="text-2xl mb-5">You are joining</h2>
<h2 className="text-2xl mb-5">{t('You are joining')}</h2>
<Statistics data={previewData} as="referee" />
</div>
) : null}
@@ -24,6 +24,7 @@ import {
DISCLAIMER_REFERRAL_DOCS_LINK,
} from './constants';
import { useReferral } from './hooks/use-referral';
import { t } from '@vegaprotocol/i18n';
export const CreateCodeContainer = () => {
return <CreateCodeForm />;
@@ -38,10 +39,13 @@ export const CreateCodeForm = () => {
return (
<div className="w-2/3 max-w-md mx-auto bg-vega-clight-800 dark:bg-vega-cdark-800 p-8 rounded-lg">
<h3 className="mb-4 text-2xl text-center calt">Create a referral code</h3>
<h3 className="mb-4 text-2xl text-center calt">
{t('Create a referral code')}
</h3>
<p className="mb-4 text-center text-base">
Generate a referral code to share with your friends and start earning
commission.
{t(
'Generate a referral code to share with your friends and start earning commission.'
)}
</p>
<div className="w-full flex flex-col">
@@ -56,12 +60,12 @@ export const CreateCodeForm = () => {
}
}}
>
{pubKey ? 'Create a referral code' : 'Connect wallet'}
{pubKey ? t('Create a referral code') : t('Connect wallet')}
</RainbowButton>
</div>
<Dialog
title="Create a referral code"
title={t('Create a referral code')}
open={dialogOpen}
onChange={() => setDialogOpen(false)}
size="small"
@@ -124,21 +128,21 @@ const CreateCodeDialog = ({
const getButtonProps = () => {
if (status === 'idle' || status === 'error') {
return {
children: 'Generate code',
children: t('Generate code'),
onClick: () => onSubmit(),
};
}
if (status === 'loading') {
return {
children: 'Confirm in wallet...',
children: t('Confirm in wallet...'),
disabled: true,
};
}
if (status === 'success') {
return {
children: 'Close',
children: t('Close'),
intent: Intent.Success,
onClick: () => {
refetch();
@@ -151,12 +155,12 @@ const CreateCodeDialog = ({
if (!pubKey || currentStakeAvailable == null || requiredStake == null) {
return (
<div className="flex flex-col gap-4">
<p>You must be connected to the Vega wallet.</p>
<p>{t('You must be connected to the Vega wallet.')}</p>
<TradingButton
intent={Intent.Primary}
onClick={() => setDialogOpen(false)}
>
Close
{t('Close')}
</TradingButton>
</div>
);
@@ -166,16 +170,18 @@ const CreateCodeDialog = ({
return (
<div className="flex flex-col gap-4">
<p>
You need at least{' '}
{addDecimalsFormatNumber(requiredStake.toString(), 18)} VEGA staked to
generate a referral code and participate in the referral program.
{t('You need at least')}{' '}
{addDecimalsFormatNumber(requiredStake.toString(), 18)}{' '}
{t(
'VEGA staked to generate a referral code and participate in the referral program.'
)}
</p>
<TradingAnchorButton
href={createLink(TokenStaticLinks.ASSOCIATE)}
intent={Intent.Primary}
target="_blank"
>
Stake some $VEGA now
{t('Stake some $VEGA now')}
</TradingAnchorButton>
</div>
);
@@ -185,8 +191,9 @@ const CreateCodeDialog = ({
<div className="flex flex-col gap-4">
{(status === 'idle' || status === 'loading' || status === 'error') && (
<p>
Generate a referral code to share with your friends and start earning
commission.
{t(
'Generate a referral code to share with your friends and start earning commission.'
)}
</p>
)}
{status === 'success' && code && (
@@ -201,7 +208,7 @@ const CreateCodeDialog = ({
className="text-sm no-underline"
icon={<VegaIcon name={VegaIconNames.COPY} />}
>
<span>Copy</span>
<span>{t('Copy')}</span>
</TradingButton>
</CopyWithTooltip>
</div>
@@ -214,10 +221,10 @@ const CreateCodeDialog = ({
{err && <InputError>{err}</InputError>}
<div className="flex justify-center pt-5 mt-2 text-sm border-t gap-4 text-default border-default">
<ExternalLink href={ABOUT_REFERRAL_DOCS_LINK}>
About the referral program
{t('About the referral program')}
</ExternalLink>
<ExternalLink href={DISCLAIMER_REFERRAL_DOCS_LINK}>
Disclaimer
{t('Disclaimer')}
</ExternalLink>
</div>
</div>
@@ -3,6 +3,7 @@ import { RainbowButton } from './buttons';
import { AnimatedDudeWithWire } from './graphics/dude';
import { LayoutWithSky } from './layout';
import { Routes } from '../../lib/links';
import { t } from '@vegaprotocol/i18n';
export const ErrorBoundary = () => {
const error = useRouteError();
@@ -39,7 +40,7 @@ export const ErrorBoundary = () => {
variant="border"
className="text-xs"
>
Go back and try again
{t('Go back and try again')}
</RainbowButton>
</p>
</LayoutWithSky>
@@ -60,7 +61,7 @@ export const NotFound = () => {
<h1 className="text-6xl font-alpha calt mb-10">{'Not found'}</h1>
<p className="text-lg mb-10">
{"The page you're looking for doesn't exists."}
{t("The page you're looking for doesn't exists.")}
</p>
<p className="text-lg mb-10">
@@ -69,7 +70,7 @@ export const NotFound = () => {
variant="border"
className="text-xs"
>
Go back and try again
{t('Go back and try again')}
</RainbowButton>
</p>
</div>
@@ -1,3 +1,4 @@
import { t } from '@vegaprotocol/i18n';
import { Table } from './table';
export const HowItWorksTable = () => (
@@ -13,7 +14,9 @@ export const HowItWorksTable = () => (
1
</span>
),
step: 'Referrers generate a code assigned to their key via an on chain transaction',
step: t(
'Referrers generate a code assigned to their key via an on chain transaction'
),
},
{
number: (
@@ -21,7 +24,9 @@ export const HowItWorksTable = () => (
2
</span>
),
step: 'Anyone with the referral link can apply it to their key(s) of choice via an on chain transaction',
step: t(
'Anyone with the referral link can apply it to their key(s) of choice via an on chain transaction'
),
},
{
number: (
@@ -29,7 +34,9 @@ export const HowItWorksTable = () => (
3
</span>
),
step: 'Discounts are applied automatically during trading based on the key(s) used',
step: t(
'Discounts are applied automatically during trading based on the key(s) used'
),
},
{
number: (
@@ -37,7 +44,9 @@ export const HowItWorksTable = () => (
4
</span>
),
step: 'Referrers earn commission based on a percentage of the taker fees their referees pay',
step: t(
'Referrers earn commission based on a percentage of the taker fees their referees pay'
),
},
{
number: (
@@ -45,7 +54,9 @@ export const HowItWorksTable = () => (
5
</span>
),
step: 'The commission is taken from the infrastructure fee, maker fee, and liquidity provider fee, not from the referee',
step: t(
'The commission is taken from the infrastructure fee, maker fee, and liquidity provider fee, not from the referee'
),
},
]}
></Table>
@@ -1,5 +1,6 @@
import classNames from 'classnames';
import { AnimatedDudeWithWire } from './graphics/dude';
import { t } from '@vegaprotocol/i18n';
export const LandingBanner = () => {
return (
@@ -13,16 +14,17 @@ export const LandingBanner = () => {
</div>
<div className="pt-32 sm:w-[50%]">
<h1 className="text-6xl font-alpha calt mb-10">
Earn commission & stake rewards
{t('Earn commission & stake rewards')}
</h1>
<p className="text-lg mb-10">
Invite friends and earn commission in the form of Vega rewards from
the trading fees they pay. Stake those rewards to earn multipliers
on future rewards.
{t(
'Invite friends and earn commission in the form of Vega rewards from the trading fees they pay. Stake those rewards to earn multipliers on future rewards.'
)}
</p>
<p className="text-lg">
Any friends that join using the code will receive discounts off
trading fees.
{t(
'Any friends that join using the code will receive discounts off trading fees.'
)}
</p>
</div>
</div>
@@ -26,6 +26,7 @@ import sortBy from 'lodash/sortBy';
import { useLayoutEffect, useRef, useState } from 'react';
import { useCurrentEpochInfoQuery } from './hooks/__generated__/Epoch';
import BigNumber from 'bignumber.js';
import { t } from '@vegaprotocol/i18n';
export const ReferralStatistics = () => {
const { pubKey } = useVegaWallet();
@@ -116,34 +117,34 @@ export const Statistics = ({
: 0;
const baseCommissionTile = (
<StatTile title="Base commission rate">
<StatTile title={t('Base commission rate')}>
{baseCommissionValue * 100}%
</StatTile>
);
const stakingMultiplierTile = (
<StatTile
title="Staking multiplier"
title={t('Staking multiplier')}
description={`(${addDecimalsFormatNumber(
stakeAvailable?.toString() || 0,
18
)} $VEGA staked)`}
>
{multiplier || 'None'}
{multiplier || t('None')}
</StatTile>
);
const finalCommissionTile = (
<StatTile title="Final commission rate">
<StatTile title={t('Final commission rate')}>
{finalCommissionValue * 100}%
</StatTile>
);
const numberOfTradersValue = data.referees.length;
const numberOfTradersTile = (
<StatTile title="Number of traders">{numberOfTradersValue}</StatTile>
<StatTile title={t('Number of traders')}>{numberOfTradersValue}</StatTile>
);
const codeTile = <CodeTile code={data?.code} />;
const createdAtTile = (
<StatTile title="Created at">
<StatTile title={t('Created at')}>
<span className="text-3xl">
{getDateFormat().format(new Date(data.createdAt))}
</span>
@@ -154,7 +155,10 @@ export const Statistics = ({
.map((r) => new BigNumber(r.totalRefereeGeneratedRewards))
.reduce((all, r) => all.plus(r), new BigNumber(0));
const totalCommissionTile = (
<StatTile title="Total commission (last 30 days)" description="(Quantum)">
<StatTile
title={t('Total commission (last 30 days)')}
description={t('(qUSD)')}
>
{getNumberFormat(0).format(Number(totalCommissionValue))}
</StatTile>
);
@@ -184,29 +188,31 @@ export const Statistics = ({
});
const currentBenefitTierTile = (
<StatTile title="Current tier">
<StatTile title={t('Current tier')}>
{currentBenefitTierValue?.tier || '-'}
</StatTile>
);
const discountFactorTile = (
<StatTile title="Discount">{discountFactorValue * 100}%</StatTile>
<StatTile title={t('Discount')}>{discountFactorValue * 100}%</StatTile>
);
const runningVolumeTile = (
<StatTile title="Combined volume">
<StatTile title={t('Combined volume')}>
{compactNumFormat.format(runningVolumeValue)}
</StatTile>
);
const epochsTile = <StatTile title="Epochs in set">{epochsValue}</StatTile>;
const epochsTile = (
<StatTile title={t('Epochs in set')}>{epochsValue}</StatTile>
);
const nextTierVolumeTile = (
<StatTile title="Volume to next tier">
<StatTile title={t('Volume to next tier')}>
{nextBenefitTierVolumeValue <= 0
? '-'
? '0'
: compactNumFormat.format(nextBenefitTierVolumeValue)}
</StatTile>
);
const nextTierEpochsTile = (
<StatTile title="Epochs to next tier">
{nextBenefitTierEpochsValue <= 0 ? '-' : nextBenefitTierEpochsValue}
<StatTile title={t('Epochs to next tier')}>
{nextBenefitTierEpochsValue <= 0 ? '0' : nextBenefitTierEpochsValue}
</StatTile>
);
@@ -249,7 +255,7 @@ export const Statistics = ({
{/* Referees (only for referrer view) */}
{as === 'referrer' && data.referees.length > 0 && (
<div className="mt-20 mb-20">
<h2 className="text-2xl mb-5">Referees</h2>
<h2 className="text-2xl mb-5">{t('Referees')}</h2>
<div
className={classNames(
collapsed && [
@@ -273,12 +279,12 @@ export const Statistics = ({
<Table
ref={tableRef}
columns={[
{ name: 'party', displayName: 'Trader' },
{ name: 'joined', displayName: 'Date Joined' },
{ name: 'volume', displayName: 'Volume (last 30 days)' },
{ name: 'party', displayName: t('Trader') },
{ name: 'joined', displayName: t('Date Joined') },
{ name: 'volume', displayName: t('Volume (last 30 days)') },
{
name: 'commission',
displayName: 'Commission earned (last 30 days)',
displayName: t('Commission earned (last 30 days)'),
},
]}
data={sortBy(
@@ -22,9 +22,9 @@ import { t } from '@vegaprotocol/i18n';
const Nav = () => (
<div className="flex justify-center border-b border-vega-cdark-500">
<TabLink end to={Routes.REFERRALS}>
I want a code
{t('I want a code')}
</TabLink>
<TabLink to={Routes.REFERRALS_APPLY_CODE}>I have a code</TabLink>
<TabLink to={Routes.REFERRALS_APPLY_CODE}>{t('I have a code')}</TabLink>
</div>
);
@@ -77,7 +77,7 @@ export const Referrals = () => {
</div>
) : error ? (
<div className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 text-center">
<p>Something went wrong</p>
<p>{t('Something went wrong')}</p>
<span className="text-xs">{error.message}</span>
</div>
) : (
@@ -88,7 +88,7 @@ export const Referrals = () => {
<TiersContainer />
<div className="mt-10 mb-5 text-center">
<h2 className="text-2xl">How it works</h2>
<h2 className="text-2xl">{t('How it works')}</h2>
</div>
<div className="md:w-[60%] mx-auto">
<HowItWorksTable />
@@ -98,7 +98,8 @@ export const Referrals = () => {
href={REFERRAL_DOCS_LINK}
target="_blank"
>
Read the terms <VegaIcon name={VegaIconNames.OPEN_EXTERNAL} />
{t('Read the terms')}{' '}
<VegaIcon name={VegaIconNames.OPEN_EXTERNAL} />
</TradingAnchorButton>
</div>
</div>
+17 -13
View File
@@ -7,6 +7,7 @@ import { Tag } from './tag';
import type { ComponentProps, ReactNode } from 'react';
import { ExternalLink } from '@vegaprotocol/ui-toolkit';
import { DApp, TOKEN_PROPOSALS, useLinks } from '@vegaprotocol/environment';
import { t } from '@vegaprotocol/i18n';
const Loading = ({ variant }: { variant: 'large' | 'inline' }) => (
<div
@@ -61,7 +62,7 @@ const StakingTier = ({
<Tag color={color[tier]}>Multiplier {referralRewardMultiplier}x</Tag>
<h3 className="mt-1 mb-1 text-base">{label}</h3>
<p className="text-sm text-vega-clight-100 dark:text-vega-cdark-100">
Stake a minimum of {minimumStakedTokens} $VEGA tokens
{t('Stake a minimum of')} {minimumStakedTokens} {t('$VEGA tokens')}
</p>
</div>
</div>
@@ -81,9 +82,12 @@ export const TiersContainer = () => {
if ((!loading && !details) || error) {
return (
<div className="text-base px-5 py-10 text-center">
We&apos;re sorry but we don&apos;t have an active referral programme
currently running. You can propose a new programme{' '}
<ExternalLink href={governanceLink(TOKEN_PROPOSALS)}>here</ExternalLink>
{t(
"We're sorry but we don't have an active referral programme currently running. You can propose a new programme"
)}{' '}
<ExternalLink href={governanceLink(TOKEN_PROPOSALS)}>
{t('here')}
</ExternalLink>
.
</div>
);
@@ -93,10 +97,10 @@ export const TiersContainer = () => {
<>
{/* Benefit tiers */}
<div className="flex flex-col items-baseline justify-between mt-10 mb-5">
<h2 className="text-2xl">Referral tiers</h2>
<h2 className="text-2xl">{t('Referral tiers')}</h2>
{ends && (
<span className="text-sm text-vega-clight-200 dark:text-vega-cdark-200">
Program ends: {ends}
{t('Program ends:')} {ends}
</span>
)}
</div>
@@ -119,7 +123,7 @@ export const TiersContainer = () => {
{/* Staking tiers */}
<div className="flex flex-row items-baseline justify-between mb-5">
<h2 className="text-2xl">Staking multipliers</h2>
<h2 className="text-2xl">{t('Staking multipliers')}</h2>
</div>
<div className="mb-20 flex flex-col justify-items-stretch lg:flex-row gap-5">
{loading || !stakingTiers || stakingTiers.length === 0 ? (
@@ -170,15 +174,15 @@ const TiersTable = ({
return (
<Table
columns={[
{ name: 'tierElement', displayName: 'Tier' },
{ name: 'tierElement', displayName: t('Tier') },
{
name: 'commission',
displayName: 'Referrer commission',
tooltip: 'A percentage of commission earned by the referrer',
displayName: t('Referrer commission'),
tooltip: t('A percentage of commission earned by the referrer'),
},
{ name: 'discount', displayName: 'Referrer trading discount' },
{ name: 'volume', displayName: 'Min. trading volume' },
{ name: 'epochs', displayName: 'Min. epochs' },
{ name: 'discount', displayName: t('Referrer trading discount') },
{ name: 'volume', displayName: t('Min. trading volume') },
{ name: 'epochs', displayName: t('Min. epochs') },
]}
data={data.map((d) => ({
...d,
+29 -25
View File
@@ -32,39 +32,43 @@ query LiquidityProvisions($marketId: ID!) {
}
}
subscription LiquidityProvisionsUpdate($partyId: ID, $marketId: ID) {
liquidityProvisions(partyId: $partyId, marketId: $marketId) {
id
partyID
createdAt
updatedAt
marketID
commitmentAmount
fee
status
}
}
# Liquidity Provider Share Fee
fragment LiquidityProviderFeeShareFields on LiquidityProviderFeeShare {
party {
id
}
equityLikeShare
averageEntryValuation
averageScore
virtualStake
}
query LiquidityProviderFeeShare($marketId: ID!) {
market(id: $marketId) {
id
data {
market {
id
}
liquidityProviderFeeShare {
...LiquidityProviderFeeShareFields
fragment LiquidityProviderSLAFields on LiquidityProviderSLA {
currentEpochFractionOfTimeOnBook
lastEpochFractionOfTimeOnBook
lastEpochFeePenalty
lastEpochBondPenalty
hysteresisPeriodFeePenalties
requiredLiquidity
notionalVolumeBuys
notionalVolumeSells
}
query LiquidityProviders($marketId: ID!) {
liquidityProviders(marketId: $marketId) {
edges {
node {
...LiquidityProviderFields
}
}
}
}
fragment LiquidityProviderFields on LiquidityProvider {
partyId
marketId
feeShare {
...LiquidityProviderFeeShareFields
}
sla {
...LiquidityProviderSLAFields
}
}
+51 -73
View File
@@ -12,22 +12,18 @@ export type LiquidityProvisionsQueryVariables = Types.Exact<{
export type LiquidityProvisionsQuery = { __typename?: 'Query', market?: { __typename?: 'Market', liquidityProvisionsConnection?: { __typename?: 'LiquidityProvisionsConnection', edges?: Array<{ __typename?: 'LiquidityProvisionsEdge', node: { __typename?: 'LiquidityProvision', id: string, createdAt: any, updatedAt?: any | null, commitmentAmount: string, fee: string, status: Types.LiquidityProvisionStatus, party: { __typename?: 'Party', id: string, accountsConnection?: { __typename?: 'AccountsConnection', edges?: Array<{ __typename?: 'AccountEdge', node: { __typename?: 'AccountBalance', type: Types.AccountType, balance: string } } | null> | null } | null } } } | null> | null } | null } | null };
export type LiquidityProvisionsUpdateSubscriptionVariables = Types.Exact<{
partyId?: Types.InputMaybe<Types.Scalars['ID']>;
marketId?: Types.InputMaybe<Types.Scalars['ID']>;
}>;
export type LiquidityProviderFeeShareFieldsFragment = { __typename?: 'LiquidityProviderFeeShare', equityLikeShare: string, averageEntryValuation: string, averageScore: string, virtualStake: string };
export type LiquidityProviderSLAFieldsFragment = { __typename?: 'LiquidityProviderSLA', currentEpochFractionOfTimeOnBook: string, lastEpochFractionOfTimeOnBook: string, lastEpochFeePenalty: string, lastEpochBondPenalty: string, hysteresisPeriodFeePenalties?: Array<string> | null, requiredLiquidity: string, notionalVolumeBuys: string, notionalVolumeSells: string };
export type LiquidityProvisionsUpdateSubscription = { __typename?: 'Subscription', liquidityProvisions?: Array<{ __typename?: 'LiquidityProvisionUpdate', id: string, partyID: string, createdAt: any, updatedAt?: any | null, marketID: string, commitmentAmount: string, fee: string, status: Types.LiquidityProvisionStatus }> | null };
export type LiquidityProviderFeeShareFieldsFragment = { __typename?: 'LiquidityProviderFeeShare', equityLikeShare: string, averageEntryValuation: string, party: { __typename?: 'Party', id: string } };
export type LiquidityProviderFeeShareQueryVariables = Types.Exact<{
export type LiquidityProvidersQueryVariables = Types.Exact<{
marketId: Types.Scalars['ID'];
}>;
export type LiquidityProviderFeeShareQuery = { __typename?: 'Query', market?: { __typename?: 'Market', id: string, data?: { __typename?: 'MarketData', market: { __typename?: 'Market', id: string }, liquidityProviderFeeShare?: Array<{ __typename?: 'LiquidityProviderFeeShare', equityLikeShare: string, averageEntryValuation: string, party: { __typename?: 'Party', id: string } }> | null } | null } | null };
export type LiquidityProvidersQuery = { __typename?: 'Query', liquidityProviders?: { __typename?: 'LiquidityProviderConnection', edges: Array<{ __typename?: 'LiquidityProviderEdge', node: { __typename?: 'LiquidityProvider', partyId: string, marketId: string, feeShare?: { __typename?: 'LiquidityProviderFeeShare', equityLikeShare: string, averageEntryValuation: string, averageScore: string, virtualStake: string } | null, sla?: { __typename?: 'LiquidityProviderSLA', currentEpochFractionOfTimeOnBook: string, lastEpochFractionOfTimeOnBook: string, lastEpochFeePenalty: string, lastEpochBondPenalty: string, hysteresisPeriodFeePenalties?: Array<string> | null, requiredLiquidity: string, notionalVolumeBuys: string, notionalVolumeSells: string } | null } }> } | null };
export type LiquidityProviderFieldsFragment = { __typename?: 'LiquidityProvider', partyId: string, marketId: string, feeShare?: { __typename?: 'LiquidityProviderFeeShare', equityLikeShare: string, averageEntryValuation: string, averageScore: string, virtualStake: string } | null, sla?: { __typename?: 'LiquidityProviderSLA', currentEpochFractionOfTimeOnBook: string, lastEpochFractionOfTimeOnBook: string, lastEpochFeePenalty: string, lastEpochBondPenalty: string, hysteresisPeriodFeePenalties?: Array<string> | null, requiredLiquidity: string, notionalVolumeBuys: string, notionalVolumeSells: string } | null };
export const LiquidityProvisionFieldsFragmentDoc = gql`
fragment LiquidityProvisionFields on LiquidityProvision {
@@ -52,13 +48,37 @@ export const LiquidityProvisionFieldsFragmentDoc = gql`
`;
export const LiquidityProviderFeeShareFieldsFragmentDoc = gql`
fragment LiquidityProviderFeeShareFields on LiquidityProviderFeeShare {
party {
id
}
equityLikeShare
averageEntryValuation
averageScore
virtualStake
}
`;
export const LiquidityProviderSLAFieldsFragmentDoc = gql`
fragment LiquidityProviderSLAFields on LiquidityProviderSLA {
currentEpochFractionOfTimeOnBook
lastEpochFractionOfTimeOnBook
lastEpochFeePenalty
lastEpochBondPenalty
hysteresisPeriodFeePenalties
requiredLiquidity
notionalVolumeBuys
notionalVolumeSells
}
`;
export const LiquidityProviderFieldsFragmentDoc = gql`
fragment LiquidityProviderFields on LiquidityProvider {
partyId
marketId
feeShare {
...LiquidityProviderFeeShareFields
}
sla {
...LiquidityProviderSLAFields
}
}
${LiquidityProviderFeeShareFieldsFragmentDoc}
${LiquidityProviderSLAFieldsFragmentDoc}`;
export const LiquidityProvisionsDocument = gql`
query LiquidityProvisions($marketId: ID!) {
market(id: $marketId) {
@@ -100,84 +120,42 @@ export function useLiquidityProvisionsLazyQuery(baseOptions?: Apollo.LazyQueryHo
export type LiquidityProvisionsQueryHookResult = ReturnType<typeof useLiquidityProvisionsQuery>;
export type LiquidityProvisionsLazyQueryHookResult = ReturnType<typeof useLiquidityProvisionsLazyQuery>;
export type LiquidityProvisionsQueryResult = Apollo.QueryResult<LiquidityProvisionsQuery, LiquidityProvisionsQueryVariables>;
export const LiquidityProvisionsUpdateDocument = gql`
subscription LiquidityProvisionsUpdate($partyId: ID, $marketId: ID) {
liquidityProvisions(partyId: $partyId, marketId: $marketId) {
id
partyID
createdAt
updatedAt
marketID
commitmentAmount
fee
status
}
}
`;
/**
* __useLiquidityProvisionsUpdateSubscription__
*
* To run a query within a React component, call `useLiquidityProvisionsUpdateSubscription` and pass it any options that fit your needs.
* When your component renders, `useLiquidityProvisionsUpdateSubscription` 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 subscription, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options;
*
* @example
* const { data, loading, error } = useLiquidityProvisionsUpdateSubscription({
* variables: {
* partyId: // value for 'partyId'
* marketId: // value for 'marketId'
* },
* });
*/
export function useLiquidityProvisionsUpdateSubscription(baseOptions?: Apollo.SubscriptionHookOptions<LiquidityProvisionsUpdateSubscription, LiquidityProvisionsUpdateSubscriptionVariables>) {
const options = {...defaultOptions, ...baseOptions}
return Apollo.useSubscription<LiquidityProvisionsUpdateSubscription, LiquidityProvisionsUpdateSubscriptionVariables>(LiquidityProvisionsUpdateDocument, options);
}
export type LiquidityProvisionsUpdateSubscriptionHookResult = ReturnType<typeof useLiquidityProvisionsUpdateSubscription>;
export type LiquidityProvisionsUpdateSubscriptionResult = Apollo.SubscriptionResult<LiquidityProvisionsUpdateSubscription>;
export const LiquidityProviderFeeShareDocument = gql`
query LiquidityProviderFeeShare($marketId: ID!) {
market(id: $marketId) {
id
data {
market {
id
}
liquidityProviderFeeShare {
...LiquidityProviderFeeShareFields
export const LiquidityProvidersDocument = gql`
query LiquidityProviders($marketId: ID!) {
liquidityProviders(marketId: $marketId) {
edges {
node {
...LiquidityProviderFields
}
}
}
}
${LiquidityProviderFeeShareFieldsFragmentDoc}`;
${LiquidityProviderFieldsFragmentDoc}`;
/**
* __useLiquidityProviderFeeShareQuery__
* __useLiquidityProvidersQuery__
*
* To run a query within a React component, call `useLiquidityProviderFeeShareQuery` and pass it any options that fit your needs.
* When your component renders, `useLiquidityProviderFeeShareQuery` returns an object from Apollo Client that contains loading, error, and data properties
* To run a query within a React component, call `useLiquidityProvidersQuery` and pass it any options that fit your needs.
* When your component renders, `useLiquidityProvidersQuery` 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 } = useLiquidityProviderFeeShareQuery({
* const { data, loading, error } = useLiquidityProvidersQuery({
* variables: {
* marketId: // value for 'marketId'
* },
* });
*/
export function useLiquidityProviderFeeShareQuery(baseOptions: Apollo.QueryHookOptions<LiquidityProviderFeeShareQuery, LiquidityProviderFeeShareQueryVariables>) {
export function useLiquidityProvidersQuery(baseOptions: Apollo.QueryHookOptions<LiquidityProvidersQuery, LiquidityProvidersQueryVariables>) {
const options = {...defaultOptions, ...baseOptions}
return Apollo.useQuery<LiquidityProviderFeeShareQuery, LiquidityProviderFeeShareQueryVariables>(LiquidityProviderFeeShareDocument, options);
return Apollo.useQuery<LiquidityProvidersQuery, LiquidityProvidersQueryVariables>(LiquidityProvidersDocument, options);
}
export function useLiquidityProviderFeeShareLazyQuery(baseOptions?: Apollo.LazyQueryHookOptions<LiquidityProviderFeeShareQuery, LiquidityProviderFeeShareQueryVariables>) {
export function useLiquidityProvidersLazyQuery(baseOptions?: Apollo.LazyQueryHookOptions<LiquidityProvidersQuery, LiquidityProvidersQueryVariables>) {
const options = {...defaultOptions, ...baseOptions}
return Apollo.useLazyQuery<LiquidityProviderFeeShareQuery, LiquidityProviderFeeShareQueryVariables>(LiquidityProviderFeeShareDocument, options);
return Apollo.useLazyQuery<LiquidityProvidersQuery, LiquidityProvidersQueryVariables>(LiquidityProvidersDocument, options);
}
export type LiquidityProviderFeeShareQueryHookResult = ReturnType<typeof useLiquidityProviderFeeShareQuery>;
export type LiquidityProviderFeeShareLazyQueryHookResult = ReturnType<typeof useLiquidityProviderFeeShareLazyQuery>;
export type LiquidityProviderFeeShareQueryResult = Apollo.QueryResult<LiquidityProviderFeeShareQuery, LiquidityProviderFeeShareQueryVariables>;
export type LiquidityProvidersQueryHookResult = ReturnType<typeof useLiquidityProvidersQuery>;
export type LiquidityProvidersLazyQueryHookResult = ReturnType<typeof useLiquidityProvidersLazyQuery>;
export type LiquidityProvidersQueryResult = Apollo.QueryResult<LiquidityProvidersQuery, LiquidityProvidersQueryVariables>;
@@ -1,7 +1,9 @@
import type { LiquidityProviderFeeShare } from '@vegaprotocol/types';
import { AccountType } from '@vegaprotocol/types';
import { getLiquidityProvision } from './liquidity-data-provider';
import type { LiquidityProvisionFieldsFragment } from './__generated__/MarketLiquidity';
import type {
LiquidityProviderFieldsFragment,
LiquidityProvisionFieldsFragment,
} from './__generated__/MarketLiquidity';
const input = {
liquidityProvisions: [
@@ -31,28 +33,32 @@ const input = {
__typename: 'LiquidityProvision',
} as LiquidityProvisionFieldsFragment,
],
liquidityFeeShare: [
liquidityProviders: [
{
party: {
id: 'dde288688af2aeb5feb349dd72d3679a7a9be34c7375f6a4a48ef2f6140e7e59',
__typename: 'Party',
partyId:
'dde288688af2aeb5feb349dd72d3679a7a9be34c7375f6a4a48ef2f6140e7e59',
feeShare: {
equityLikeShare: '1',
averageEntryValuation: '12064118310408958216220.7224556301338111',
__typename: 'LiquidityProviderFeeShare',
},
equityLikeShare: '1',
averageEntryValuation: '12064118310408958216220.7224556301338111',
__typename: 'LiquidityProviderFeeShare',
} as LiquidityProviderFeeShare,
} as LiquidityProviderFieldsFragment,
],
};
const result = [
{
__typename: 'LiquidityProvision',
averageEntryValuation: '12064118310408958216220.7224556301338111',
__typename: undefined,
balance: '1.8003328918633596575e+22',
commitmentAmount: '18003328918633596575000',
createdAt: '2022-12-16T09:28:29.071781Z',
equityLikeShare: '1',
feeShare: {
equityLikeShare: '1',
__typename: 'LiquidityProviderFeeShare',
averageEntryValuation: '12064118310408958216220.7224556301338111',
},
fee: '0.001',
partyId: 'dde288688af2aeb5feb349dd72d3679a7a9be34c7375f6a4a48ef2f6140e7e59',
party: {
__typename: 'Party',
accountsConnection: {
@@ -84,13 +90,13 @@ describe('getLiquidityProvision', () => {
it('should return correct array when correct liquidity provision parameters are provided', () => {
const data = getLiquidityProvision(
input.liquidityProvisions,
input.liquidityFeeShare
input.liquidityProviders
);
expect(data).toStrictEqual(result);
});
it('should return empty array when no liquidity provision parameters are provided', () => {
const data = getLiquidityProvision([], input.liquidityFeeShare);
const data = getLiquidityProvision([], input.liquidityProviders);
expect(data).toStrictEqual([]);
});
@@ -5,86 +5,50 @@ import {
} from '@vegaprotocol/data-provider';
import * as Schema from '@vegaprotocol/types';
import BigNumber from 'bignumber.js';
import produce from 'immer';
import {
LiquidityProviderFeeShareDocument,
LiquidityProvidersDocument,
LiquidityProvisionsDocument,
LiquidityProvisionsUpdateDocument,
} from './__generated__/MarketLiquidity';
import type {
LiquidityProviderFeeShareFieldsFragment,
LiquidityProviderFeeShareQuery,
LiquidityProviderFeeShareQueryVariables,
LiquidityProviderFieldsFragment,
LiquidityProvidersQuery,
LiquidityProvidersQueryVariables,
LiquidityProvisionFieldsFragment,
LiquidityProvisionsQuery,
LiquidityProvisionsQueryVariables,
LiquidityProvisionsUpdateSubscription,
} from './__generated__/MarketLiquidity';
export const liquidityProvisionsDataProvider = makeDataProvider<
LiquidityProvisionsQuery,
LiquidityProvisionFieldsFragment[],
LiquidityProvisionsUpdateSubscription,
LiquidityProvisionsUpdateSubscription['liquidityProvisions'],
never,
never,
LiquidityProvisionsQueryVariables
>({
query: LiquidityProvisionsDocument,
subscriptionQuery: LiquidityProvisionsUpdateDocument,
update: (
data: LiquidityProvisionFieldsFragment[] | null,
deltas: LiquidityProvisionsUpdateSubscription['liquidityProvisions']
) => {
return produce(data || [], (draft) => {
deltas?.forEach((delta) => {
const index = draft.findIndex((a) => delta.id === a.id);
if (index !== -1) {
draft[index].commitmentAmount = delta.commitmentAmount;
draft[index].fee = delta.fee;
draft[index].updatedAt = delta.updatedAt;
draft[index].status = delta.status;
} else {
draft.unshift({
id: delta.id,
commitmentAmount: delta.commitmentAmount,
fee: delta.fee,
status: delta.status,
updatedAt: delta.updatedAt,
createdAt: delta.createdAt,
party: {
id: delta.partyID,
},
// TODO add accounts connection to the subscription
});
}
});
});
},
getData: (responseData: LiquidityProvisionsQuery | null) => {
return (
responseData?.market?.liquidityProvisionsConnection?.edges?.map(
(e) => e?.node
) ?? []
).filter((e) => !!e) as LiquidityProvisionFieldsFragment[];
},
getDelta: (
subscriptionData: LiquidityProvisionsUpdateSubscription
): LiquidityProvisionsUpdateSubscription['liquidityProvisions'] => {
return subscriptionData.liquidityProvisions;
).filter((n) => !!n) as LiquidityProvisionFieldsFragment[];
},
});
export const liquidityFeeShareDataProvider = makeDataProvider<
LiquidityProviderFeeShareQuery,
LiquidityProviderFeeShareFieldsFragment[],
export const lpDataProvider = makeDataProvider<
LiquidityProvidersQuery,
LiquidityProviderFieldsFragment[],
never,
never,
LiquidityProviderFeeShareQueryVariables
LiquidityProvidersQueryVariables
>({
query: LiquidityProviderFeeShareDocument,
query: LiquidityProvidersDocument,
getData: (data) => {
return data?.market?.data?.liquidityProviderFeeShare || [];
return (
data?.liquidityProviders?.edges.filter(Boolean).map((e) => e.node) ?? []
);
},
});
@@ -101,17 +65,17 @@ export const lpAggregatedDataProvider = makeDerivedDataProvider<
marketId: variables.marketId,
}),
(callback, client, variables) =>
liquidityFeeShareDataProvider(callback, client, {
lpDataProvider(callback, client, {
marketId: variables.marketId,
}),
],
(
[liquidityProvisions, liquidityFeeShare],
[liquidityProvisions, liquidityProvider],
{ filter }
): LiquidityProvisionData[] => {
return getLiquidityProvision(
liquidityProvisions,
liquidityFeeShare,
liquidityProvider,
filter
);
}
@@ -139,9 +103,17 @@ export const matchFilter = (
return true;
};
export interface LiquidityProvisionData
extends Omit<LiquidityProvisionFieldsFragment, '__typename'> {
assetDecimalPlaces?: number;
balance?: string;
averageEntryValuation?: string;
equityLikeShare?: string;
}
export const getLiquidityProvision = (
liquidityProvisions: LiquidityProvisionFieldsFragment[],
liquidityFeeShare: LiquidityProviderFeeShareFieldsFragment[],
liquidityProvider: LiquidityProviderFieldsFragment[],
filter?: Filter
): LiquidityProvisionData[] => {
return liquidityProvisions
@@ -161,10 +133,8 @@ export const getLiquidityProvision = (
return true;
})
.map((lp) => {
const feeShare = liquidityFeeShare.find(
(f) => f.party.id === lp.party.id
);
if (!feeShare) return lp;
const lpObj = liquidityProvider.find((f) => lp.party.id === f.partyId);
if (!lpObj) return lp;
const accounts = compact(lp.party.accountsConnection?.edges).map(
(e) => e.node
);
@@ -180,17 +150,9 @@ export const getLiquidityProvision = (
.toString() || '0';
return {
...lp,
averageEntryValuation: feeShare?.averageEntryValuation,
equityLikeShare: feeShare?.equityLikeShare,
...lpObj,
balance,
__typename: undefined,
};
});
};
export interface LiquidityProvisionData
extends LiquidityProvisionFieldsFragment {
assetDecimalPlaces?: number;
balance?: string;
averageEntryValuation?: string;
equityLikeShare?: string;
}
@@ -10,8 +10,10 @@ const singleRow = {
commitmentAmount: '56298653179',
fee: '0.001',
status: Schema.LiquidityProvisionStatus.STATUS_ACTIVE,
equityLikeShare: '0.5',
averageEntryValuation: '0.5',
feeShare: {
equityLikeShare: '0.5',
averageEntryValuation: '0.5',
},
supplied: '67895',
obligation: '56785',
} as unknown as LiquidityProvisionData;
@@ -41,13 +43,23 @@ describe('LiquidityTable', () => {
h.querySelector('[ref="eText"]')?.textContent?.trim()
);
const expectedHeaders = [
undefined,
undefined,
undefined,
undefined,
undefined,
'Party',
'Commitment ()',
'Share',
'Proposed fee',
'Market valuation at entry',
'Obligation',
'Supplied',
'Fee',
'Adjusted stake share',
'Share',
'Live supplied liquidity',
'Live time fraction on book',
'Live liquidity quality score (%)',
'Last time fraction on the book',
'Last fee penalty',
'Last bond penalty',
'Status',
'Created',
'Updated',
+172 -86
View File
@@ -8,9 +8,16 @@ import {
import { t } from '@vegaprotocol/i18n';
import type { TypedDataAgGrid } from '@vegaprotocol/datagrid';
import { AgGrid } from '@vegaprotocol/datagrid';
import { TooltipCellComponent } from '@vegaprotocol/ui-toolkit';
import {
CopyWithTooltip,
Tooltip,
TooltipCellComponent,
VegaIcon,
VegaIconNames,
truncateMiddle,
} from '@vegaprotocol/ui-toolkit';
import type {
ColDef,
ColGroupDef,
ITooltipParams,
ValueFormatterParams,
} from 'ag-grid-community';
@@ -24,6 +31,20 @@ const percentageFormatter = ({ value }: ValueFormatterParams) => {
return formatNumberPercentage(new BigNumber(value).times(100), 2) || '-';
};
const copyCellRenderer = ({ value }: { value?: string | null }) => {
if (!value) return '-';
return (
<CopyWithTooltip data-testid="copy-to-clipboard" text={value}>
<button className="flex gap-1">
<Tooltip description={value}>
<span className="break-words">{truncateMiddle(value)}</span>
</Tooltip>
<VegaIcon name={VegaIconNames.COPY} size={12} />
</button>
</CopyWithTooltip>
);
};
const dateValueFormatter = ({ value }: { value?: string | null }) => {
if (!value) {
return '-';
@@ -89,103 +110,168 @@ export const LiquidityTable = ({
)}`;
};
const defs: ColDef[] = [
const defs: ColGroupDef[] = [
{
headerName: t('Party'),
field: 'party.id',
headerTooltip: t('The public key of the party making this commitment.'),
headerName: '',
children: [
{
headerName: t('Party'),
field: 'partyId',
headerTooltip: t(
'The public key of the party making this commitment.'
),
cellRenderer: copyCellRenderer,
},
],
},
{
headerName: t(`Commitment (${symbol})`),
field: 'commitmentAmount',
type: 'rightAligned',
headerTooltip: t(
'The amount committed to the market by this liquidity provider.'
),
valueFormatter: assetDecimalsQuantumFormatter,
tooltipValueGetter: assetDecimalsFormatter,
headerName: t('Commitment details'),
marryChildren: true,
children: [
{
headerName: t(`Commitment (${symbol})`),
field: 'commitmentAmount',
type: 'rightAligned',
headerTooltip: t(
'The amount committed to the market by this liquidity provider.'
),
valueFormatter: assetDecimalsQuantumFormatter,
tooltipValueGetter: assetDecimalsFormatter,
},
{
headerName: t('Obligation'),
field: 'commitmentAmount',
type: 'rightAligned',
headerTooltip: t(
`The liquidity provider's obligation to the market, calculated as the liquidity commitment amount multiplied by the value of the stake_to_ccy_volume network parameter to convert into units of liquidity volume. The obligation can be met by a combination of LP orders and limit orders on the order book.`
),
valueFormatter: stakeToCcyVolumeQuantumFormatter,
tooltipValueGetter: stakeToCcyVolumeFormatter,
},
{
headerName: t('Fee'),
headerTooltip: t(
'The fee percentage (per trade) proposed by each liquidity provider.'
),
field: 'fee',
type: 'rightAligned',
valueFormatter: percentageFormatter,
},
{
headerName: t('Adjusted stake share'),
field: 'feeShare.virtualStake',
type: 'rightAligned',
headerTooltip: t('The virtual stake of the liquidity provider.'),
valueFormatter: assetDecimalsQuantumFormatter,
tooltipValueGetter: assetDecimalsFormatter,
},
{
headerName: t(`Share`),
field: 'feeShare.equityLikeShare',
type: 'rightAligned',
headerTooltip: t(
'The equity-like share of liquidity of the market used to determine allocation of LP fees. Calculated based on share of total liquidity, with a premium added for length of commitment.'
),
valueFormatter: percentageFormatter,
},
],
},
{
headerName: t(`Share`),
field: 'equityLikeShare',
type: 'rightAligned',
headerTooltip: t(
'The equity-like share of liquidity of the market used to determine allocation of LP fees. Calculated based on share of total liquidity, with a premium added for length of commitment.'
),
valueFormatter: percentageFormatter,
headerName: t('Live liquidity details'),
marryChildren: true,
children: [
{
headerName: t('Live supplied liquidity'),
field: 'balance',
type: 'rightAligned',
headerTooltip: t(
`The amount of liquidity volume supplied by the LP order in order to meet the obligation. If the obligation is already met in full by other limit orders from the same Vega key the LP order is not required and this value will be zero. Also note if the target stake for the market is less than the obligation the full value of the obligation may not be required.`
),
valueFormatter: stakeToCcyVolumeQuantumFormatter,
tooltipValueGetter: stakeToCcyVolumeFormatter,
},
{
headerName: t(`Live time fraction on book`),
field: 'sla.currentEpochFractionOfTimeOnBook',
type: 'rightAligned',
headerTooltip: t('Current epoch fraction of time on the book.'),
valueFormatter: percentageFormatter,
},
{
headerName: t('Live liquidity quality score (%)'),
field: 'feeShare.averageScore',
type: 'rightAligned',
headerTooltip: t('The average score of the liquidity provider.'),
valueFormatter: percentageFormatter,
},
],
},
{
headerName: t('Proposed fee'),
headerTooltip: t(
'The fee percentage (per trade) proposed by each liquidity provider.'
),
field: 'fee',
type: 'rightAligned',
valueFormatter: percentageFormatter,
headerName: t('Last epoch SLA details'),
marryChildren: true,
children: [
{
headerName: t(`Last time fraction on the book`),
field: 'sla.lastEpochFractionOfTimeOnBook',
type: 'rightAligned',
headerTooltip: t('Last epoch fraction of time on the book.'),
valueFormatter: percentageFormatter,
},
{
headerName: t(`Last fee penalty`),
field: 'sla.lastEpochFeePenalty',
type: 'rightAligned',
headerTooltip: t('Last epoch fee penalty.'),
valueFormatter: percentageFormatter,
},
{
headerName: t(`Last bond penalty`),
field: 'sla.lastEpochBondPenalty',
type: 'rightAligned',
headerTooltip: t('Last epoch bond penalty.'),
valueFormatter: percentageFormatter,
},
],
},
{
headerName: t('Market valuation at entry'),
field: 'averageEntryValuation',
type: 'rightAligned',
headerTooltip: t(
'The valuation of the market at the time the liquidity commitment was made. Commitments made at a lower valuation earlier in the lifetime of the market would be expected to have a higher equity-like share if the market has grown. If a commitment is amended, value will reflect the average of the market valuations across the lifetime of the commitment.'
),
valueFormatter: assetDecimalsQuantumFormatter,
tooltipValueGetter: assetDecimalsFormatter,
},
{
headerName: t('Obligation'),
field: 'commitmentAmount',
type: 'rightAligned',
headerTooltip: t(
`The liquidity provider's obligation to the market, calculated as the liquidity commitment amount multiplied by the value of the stake_to_ccy_volume network parameter to convert into units of liquidity volume. The obligation can be met by a combination of LP orders and limit orders on the order book.`
),
valueFormatter: stakeToCcyVolumeQuantumFormatter,
tooltipValueGetter: stakeToCcyVolumeFormatter,
},
{
headerName: t('Supplied'),
field: 'balance',
type: 'rightAligned',
headerTooltip: t(
`The amount of liquidity volume supplied by the LP order in order to meet the obligation. If the obligation is already met in full by other limit orders from the same Vega key the LP order is not required and this value will be zero. Also note if the target stake for the market is less than the obligation the full value of the obligation may not be required.`
),
valueFormatter: stakeToCcyVolumeQuantumFormatter,
tooltipValueGetter: stakeToCcyVolumeFormatter,
},
{
headerName: t('Status'),
headerTooltip: t('The current status of this liquidity provision.'),
field: 'status',
valueFormatter: ({ value }) => {
if (!value) return value;
return LiquidityProvisionStatusMapping[
value as LiquidityProvisionStatus
];
},
},
{
headerName: t('Created'),
headerTooltip: t(
'The date and time this liquidity provision was created.'
),
field: 'createdAt',
type: 'rightAligned',
valueFormatter: dateValueFormatter,
},
{
headerName: t('Updated'),
headerTooltip: t(
'The date and time this liquidity provision was last updated.'
),
field: 'updatedAt',
type: 'rightAligned',
valueFormatter: dateValueFormatter,
headerName: '',
marryChildren: true,
children: [
{
headerName: t('Status'),
headerTooltip: t('The current status of this liquidity provision.'),
field: 'status',
valueFormatter: ({ value }) => {
if (!value) return value;
return LiquidityProvisionStatusMapping[
value as LiquidityProvisionStatus
];
},
},
{
headerName: t('Created'),
headerTooltip: t(
'The date and time this liquidity provision was created.'
),
field: 'createdAt',
type: 'rightAligned',
valueFormatter: dateValueFormatter,
},
{
headerName: t('Updated'),
headerTooltip: t(
'The date and time this liquidity provision was last updated.'
),
field: 'updatedAt',
type: 'rightAligned',
valueFormatter: dateValueFormatter,
},
],
},
];
return defs;
}, [assetDecimalPlaces, quantum, stakeToCcyVolume, symbol]);
return (
<AgGrid
overlayNoRowsTemplate={t('No liquidity provisions')}
+52 -31
View File
@@ -2,7 +2,7 @@ import merge from 'lodash/merge';
import * as Schema from '@vegaprotocol/types';
import type { PartialDeep } from 'type-fest';
import type {
LiquidityProviderFeeShareQuery,
LiquidityProvidersQuery,
LiquidityProvisionsQuery,
} from './__generated__/MarketLiquidity';
import type { LiquidityProvisionFieldsFragment } from './__generated__/MarketLiquidity';
@@ -26,40 +26,61 @@ export const liquidityProvisionsQuery = (
return merge(defaultResult, override);
};
export const liquidityProviderFeeShareQuery = (
override?: PartialDeep<LiquidityProviderFeeShareQuery>
): LiquidityProviderFeeShareQuery => {
const defaultResult: LiquidityProviderFeeShareQuery = {
market: {
id: 'market-0',
data: {
market: {
id: 'market-0',
__typename: 'Market',
export const liquidityProvidersQuery = (
override?: PartialDeep<LiquidityProvidersQuery>
): LiquidityProvidersQuery => {
const defaultResult: LiquidityProvidersQuery = {
liquidityProviders: {
edges: [
{
node: {
partyId:
'69464e35bcb8e8a2900ca0f87acaf252d50cf2ab2fc73694845a16b7c8a0dc6f',
marketId:
'5ddb6f1570c0ef7aea41ebfef234dbded4ce2c11722cf033954459c45c30c057',
feeShare: {
equityLikeShare: '1',
averageEntryValuation: '3570452966575.2571864668476351',
averageScore: '0',
virtualStake: '296386536856.9999884883855020',
},
sla: {
currentEpochFractionOfTimeOnBook: '0',
lastEpochFractionOfTimeOnBook: '0',
lastEpochFeePenalty: '1',
lastEpochBondPenalty: '0.05',
hysteresisPeriodFeePenalties: ['1'],
requiredLiquidity: '',
notionalVolumeBuys: '',
notionalVolumeSells: '',
},
},
},
liquidityProviderFeeShare: [
{
party: {
id: '69464e35bcb8e8a2900ca0f87acaf252d50cf2ab2fc73694845a16b7c8a0dc6f',
__typename: 'Party',
{
node: {
partyId:
'cc464e35bcb8e8a2900ca0f87acaf252d50cf2ab2fc73694845a16b7c8a0dc6f',
marketId:
'5ddb6f1570c0ef7aea41ebfef234dbded4ce2c11722cf033954459c45c30c057',
feeShare: {
equityLikeShare: '1',
averageEntryValuation: '3570452966575.2571864668476351',
averageScore: '0',
virtualStake: '296386536856.9999884883855020',
},
equityLikeShare: '1',
averageEntryValuation: '68585293691.5598054356207737',
__typename: 'LiquidityProviderFeeShare',
},
{
party: {
id: 'cc464e35bcb8e8a2900ca0f87acaf252d50cf2ab2fc73694845a16b7c8a0dc6f',
__typename: 'Party',
sla: {
currentEpochFractionOfTimeOnBook: '0',
lastEpochFractionOfTimeOnBook: '0',
lastEpochFeePenalty: '1',
lastEpochBondPenalty: '0.05',
hysteresisPeriodFeePenalties: ['1'],
requiredLiquidity: '',
notionalVolumeBuys: '',
notionalVolumeSells: '',
},
equityLikeShare: '1',
averageEntryValuation: '68585293691.5598054356207737',
__typename: 'LiquidityProviderFeeShare',
},
],
__typename: 'MarketData',
},
__typename: 'Market',
},
],
},
};
return merge(defaultResult, override);
@@ -53,7 +53,10 @@ export const Tooltip = ({
className={tooltipContentClasses}
sideOffset={sideOffset}
>
<div className="relative z-0" data-testid="tooltip-content">
<div
className="relative z-0 break-words"
data-testid="tooltip-content"
>
{description}
</div>
</Content>