Compare commits

...
Author SHA1 Message Date
maciek bfc8446237 chore: floating buttons - back the cancel button on order list 2023-03-08 15:42:12 +01:00
maciek c58a599663 chore: floating buttons - fix failing test 2023-03-08 15:19:03 +01:00
maciek 246da7529e chore: floating buttons - hide buttons on trade, add deposit button for pinned 2023-03-08 15:08:12 +01:00
maciek a85bf127fb chore: floating buttons - hide buttons on trade, add deposit button for pinned 2023-03-08 14:55:47 +01:00
maciek a49e607642 Merge remote-tracking branch 'origin/develop' into chore/2825-buttons-floating-over-table-rows 2023-03-08 14:51:51 +01:00
maciek 201f452fab chore: floating buttons - hide buttons on trade, add deposit button for pinned 2023-03-08 14:51:36 +01:00
Matthew RussellandMadalina Raicu 8f5a2276de fix(trading): order store connection to deal ticket (#3100)
Co-authored-by: Madalina Raicu <madalina@raygroup.uk>
2023-03-08 12:14:56 +00:00
dexturr 46513685c8 chore: update tranches
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-03-08 12:10:32 +00:00
m.ray e66e96f12d fix(trading): add loss socialisation docs links (#3109) 2023-03-08 09:42:25 +00:00
dexturr 31c8365812 chore: update tranches
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-03-08 06:07:09 +00:00
dexturr 460f534c7a chore: update tranches
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-03-08 00:17:38 +00:00
dexturr 24cd080dd4 chore: update tranches
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-03-07 18:08:33 +00:00
maciek fa5b7c8915 chore: make footer lower buttons floating over table rows - resolve conflicts 2023-03-07 17:39:09 +01:00
maciek 27d4888294 chore: make footer lower buttons floating over table rows - resolve conflicts 2023-03-07 17:30:04 +01:00
Bartłomiej Głownia f10c33748f fix(orders): orders table flickering (#3105) 2023-03-07 17:13:34 +01:00
dexturr ac163d0194 chore: update tranches
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-03-07 12:08:15 +00:00
maciek 72c02db088 chore: make footer lower buttons floating over table rows - manage sorting and filtering 2023-03-07 12:07:44 +01:00
maciek 08ae6de505 Merge remote-tracking branch 'origin/develop' into chore/2825-buttons-floating-over-table-rows 2023-03-07 12:03:32 +01:00
maciek 861648c1b3 chore: make footer lower buttons floating over table rows - manage sorting and filtering 2023-03-07 12:03:10 +01:00
Joe Tsang e7616e64f8 test(governance): tranche service (#3099) 2023-03-07 10:42:20 +00:00
maciek b505e5305d Merge remote-tracking branch 'origin/develop' into chore/2825-buttons-floating-over-table-rows 2023-03-07 09:18:15 +01:00
maciek 88bcaf9b72 chore: make footer lower buttons floating over table rows - move hook to react helpers 2023-03-07 09:17:39 +01:00
Matthew Russell adca4600c2 feat(deposits): deposit flow (#3062) 2023-03-07 08:17:02 +00:00
maciek 7bff186e44 chore: make footer lower buttons floating over table rows - move hook to react helpers 2023-03-07 08:58:43 +01:00
maciek 73e951e2a9 Merge remote-tracking branch 'origin/develop' into chore/2825-buttons-floating-over-table-rows 2023-03-07 08:47:21 +01:00
maciek 4916c9cffe chore: make footer lower buttons floating over table rows - move hook to react helpers 2023-03-07 08:39:53 +01:00
dexturr a8eef1cb53 chore: update tranches
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-03-07 06:07:42 +00:00
dexturr 58d4bd1459 chore: update tranches
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-03-07 00:16:09 +00:00
maciek b34c82f830 chore: make footer lower buttons floating over table rows - fix lint error 2023-03-06 23:21:39 +01:00
maciek 3a2f7ae0e8 Merge remote-tracking branch 'origin/develop' into chore/2825-buttons-floating-over-table-rows 2023-03-06 23:03:40 +01:00
maciek e7a648df29 chore: make footer lower buttons floating over table rows - refactor solution 2023-03-06 23:03:22 +01:00
maciek abed44309f chore: make footer lower buttons floating over table rows - refactor solution 2023-03-06 22:49:46 +01:00
dexturr 26020b5f71 chore: update tranches
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-03-06 18:07:54 +00:00
daro-maj 16d345eb4a test(trading): revert nonparallel tests option (#3098) 2023-03-06 17:48:33 +01:00
m.ray 3b3fcab4f4 fix(trading): fills table fees display (#3071) 2023-03-06 17:24:18 +01:00
Matthew Russell f54a629179 feat(positions): positions losses and maintenance warnings (#2985) 2023-03-06 16:01:31 +00:00
maciek 556e8b0dbf chore: make footer lower buttons floating over table rows - fix failling test 2023-03-06 15:56:55 +01:00
maciek 48d246f2da Merge remote-tracking branch 'origin/develop' into chore/2825-buttons-floating-over-table-rows 2023-03-06 14:49:24 +01:00
maciek ff209e0e66 chore: make footer lower buttons floating over table rows - tweaks and fixes 2023-03-06 14:49:08 +01:00
dexturr 56f48671cc chore: update tranches
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-03-06 12:09:18 +00:00
Bartłomiej Głownia a65ee358ff fix(market-depth): orderbook row height calculation (#3068) 2023-03-06 10:21:45 +00:00
maciek 9480d183da chore: make footer lower buttons floating over table rows - rebase and resolve conflicts 2023-03-06 09:48:08 +01:00
maciek 8b206accd6 chore: make footer lower buttons floating over table rows - fix lint errors 2023-03-06 09:33:56 +01:00
dexturr 7b8d814724 chore: update tranches
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-03-06 06:07:28 +00:00
dexturr cd237dc491 chore: update tranches
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-03-06 00:17:15 +00:00
dexturr 9ad00adc5a chore: update tranches
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-03-05 18:07:24 +00:00
Bartłomiej Głownia fab055bb34 chore(orders): fix order table rows flickering on filter change (#3088) 2023-03-05 14:08:16 +00:00
dexturr d66956d080 chore: update tranches
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-03-05 12:07:46 +00:00
dexturr 9848c8ffff chore: update tranches
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-03-05 06:08:12 +00:00
dexturr b0e8ed62d2 chore: update tranches
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-03-05 00:19:08 +00:00
dexturr 289ff3b5b3 chore: update tranches
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-03-04 18:09:11 +00:00
dexturr 1d965187dc chore: update tranches
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-03-04 12:10:27 +00:00
dexturr 8bf3615001 chore: update tranches
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-03-04 06:09:19 +00:00
dexturr 1b77800b62 chore: update tranches
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-03-04 00:16:57 +00:00
dexturr 979dc2904b chore: update tranches
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-03-03 18:09:26 +00:00
m.ray 0fec3bcf3c fix(trading): update order on market trade header (#3082) (#3087) 2023-03-03 17:37:46 +00:00
maciek d3c6b18729 chore: make footer lower buttons floating over table rows - add logic for placeholders 2023-03-03 17:17:46 +01:00
maciek 9d4841bfda Merge remote-tracking branch 'origin/develop' into chore/2825-buttons-floating-over-table-rows 2023-03-03 17:16:00 +01:00
maciek 61a6c42aad chore: make footer lower buttons floating over table rows - add logic for placeholders 2023-03-03 17:15:34 +01:00
Edd 4542e25ec9 feat(explorer): proposal transaction view (#3060) 2023-03-03 14:27:24 +00:00
Edd acd96fbf21 chore(smart-contracts): remove redundant ascii to hex in favour of ethers hexlify (#3066) 2023-03-03 12:21:22 +00:00
Matthew Russell 96bf12d4dd fix(trading): add a timeout to show subscriptions as failed (#3073) 2023-03-03 12:20:51 +00:00
Edd 47b81188d4 fix(explorer): update vega_networks for all explorer envs (#3078) 2023-03-03 12:20:41 +00:00
dexturr efada06256 chore: update tranches
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-03-03 12:10:27 +00:00
daro-maj 311ef41138 test(trading): tests parallel (#3075) 2023-03-03 11:42:12 +01:00
maciek 1b5560ae4e Merge remote-tracking branch 'origin/develop' into chore/2825-buttons-floating-over-table-rows 2023-03-03 09:31:33 +01:00
Maciek 5dd0cafeca chore(trading): catch ethereum errors and capture to sentry (#3064) 2023-03-03 08:39:20 +01:00
dexturr f3d6aa1129 chore: update tranches
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-03-03 06:09:30 +00:00
dexturr 93dbc32f22 chore: update tranches
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-03-03 01:56:44 +00:00
dexturr fd1827ef67 chore: update tranches
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-03-02 18:09:24 +00:00
maciek 33252f6c23 chore: make footer lower buttons floating over table rows 2023-03-02 17:32:30 +01:00
Sam Keen 9c9948e4c1 feat(governance): final wallet not connected views (#3037) 2023-03-02 14:36:04 +00:00
Sam Keen 79b0868ff7 feat(governance): remove graph from tranches page (#3049) 2023-03-02 14:35:46 +00:00
dexturr a8401d4c6f chore: update tranches
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-03-02 12:07:58 +00:00
Maciek c030264211 chore(react-helpers): improve error catching in useResizeObserver (#3058) 2023-03-02 10:32:42 +01:00
Maciek 068f7b3fc3 chore(trading): tweaking catching no market data error (#3044) 2023-03-02 08:25:57 +01:00
dexturr 4430f0c5f6 chore: update tranches
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-03-02 06:09:50 +00:00
dexturr 0a14000708 chore: update tranches
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-03-02 00:15:49 +00:00
Matthew Russell 9ca6fe3cbf fix(trading): env vars for validator testnet (#3061) 2023-03-01 10:08:45 -08:00
dexturr 4f96472375 chore: update tranches
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-03-01 18:07:09 +00:00
m.ray cddf2ba00b fix(trading): edit order strikethrough (#3057) 2023-03-01 16:36:12 +00:00
Ciaran McGhie d01d6f5815 chore(ci): add utils and i18n libs as options for publish to npm workflow (#3055) 2023-03-01 16:35:49 +00:00
Sam Keen 2998e165f6 feat(governance): new env file for multisig on validator-testnet (#3056) 2023-03-01 14:29:47 +00:00
m.ray 886b0cb6d3 fix(trading): deal ticket limit price input and margin warning (#3050) 2023-03-01 14:23:21 +00:00
Edd 6799a06acd chore(explorer): remove commented out query (#3045) 2023-03-01 14:04:54 +00:00
Matthew Russell 47a6bcff78 chore(trading): delete unused styles (#3038) 2023-03-01 14:16:31 +01:00
Edd 06dcd00b53 fix(explorer): add size in market component for remaining order size (#3046) 2023-03-01 14:13:22 +01:00
Edd fd7aa5bd78 fix(explorer): fix inconsistent wss urls for tm (#3053) 2023-03-01 14:12:56 +01:00
Joe Tsang 384cfbc70b chore(governance): update test run files (#3051) 2023-03-01 12:35:13 +00:00
dexturr 9d14f603b3 chore: update tranches
Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-03-01 12:07:47 +00:00
159 changed files with 5964 additions and 2015 deletions
+1 -1
View File
@@ -11,7 +11,7 @@ on:
type: choice
options:
- explorer-e2e
- token-e2e
- governance-e2e
- trading-e2e
tags:
description: 'Test tags to run'
+1 -1
View File
@@ -10,5 +10,5 @@ jobs:
uses: ./.github/workflows/cypress-run.yml
secrets: inherit
with:
projects: '["explorer-e2e","token-e2e","trading-e2e"]'
projects: '["explorer-e2e","governance-e2e","trading-e2e"]'
tags: '@smoke @regression @slow'
+2 -2
View File
@@ -42,10 +42,10 @@ jobs:
affected=$(yarn nx print-affected --base=${{ env.NX_BASE }} --head=${{ env.NX_HEAD }} --select=projects)
echo -n "Affected projects: $affected"
projects=""
if [[ $affected == *"token"* ]]; then projects+='"token-e2e" '; fi
if [[ $affected == *"governance"* ]]; then projects+='"governance-e2e" '; fi
if [[ $affected == *"trading"* ]]; then projects+='"trading-e2e" '; fi
if [[ $affected == *"explorer"* ]]; then projects+='"explorer-e2e" '; fi
if [[ -z "$projects" ]]; then projects+='"token-e2e" "trading-e2e" "explorer-e2e" '; fi
if [[ -z "$projects" ]]; then projects+='"governance-e2e" "trading-e2e" "explorer-e2e" '; fi
projects=${projects%?}
projects=[${projects// /,}]
echo PROJECTS=$projects >> $GITHUB_ENV
+2
View File
@@ -12,6 +12,8 @@ on:
- react-helpers
- tailwindcss-config
- types
- utils
- i18n
jobs:
publish:
+1 -1
View File
@@ -161,7 +161,7 @@ In order to setup and run vegawallet for e2e capsule tests, in a separate termin
bash setup-vegawallet.sh
```
3. copy generated `api-token` and paste the token into `CYPRESS_VEGA_WALLET_API_TOKEN` environment variable in either `apps/token-e2e/.env` or `apps/explorer-e2e/.env` depending on which project needs testing.
3. copy generated `api-token` and paste the token into `CYPRESS_VEGA_WALLET_API_TOKEN` environment variable in either `apps/governance-e2e/.env` or `apps/explorer-e2e/.env` depending on which project needs testing.
Note: The script is only needed if capsule was built for first time or fresh. To run existing wallet service for capsule:
+1 -1
View File
@@ -1,7 +1,7 @@
NX_TENDERMINT_URL=https://tm.n00.stagnet3.vega.xyz
NX_TENDERMINT_WEBSOCKET_URL=wss://tm.n00.stagnet3.vega.xyz/websocket
NX_VEGA_CONFIG_URL=https://static.vega.xyz/assets/stagnet3-network.json
NX_VEGA_NETWORKS={\"MAINNET"\:\"https://explorer.vega.xyz"\,\"TESTNET\":\"https://explorer.fairground.wtf\"}
NX_VEGA_NETWORKS='{"SANDBOX":"https://sandbox.explorer.vega.xyz","STAGNET1":"https://stagnet1.token.vega.xyz", "STAGNET3":"https://stagnet3.explorer.vega.xyz","VALIDATOR_TESTNET":"https://validator-testnet.fairground.wtf","TESTNET":"https://token.fairground.wtf","MAINNET":"https://token.vega.xyz"}'
NX_VEGA_ENV=STAGNET3
NX_GITHUB_FEEDBACK_URL=https://github.com/vegaprotocol/feedback/discussions
NX_HOSTED_WALLET_URL=https://wallet.testnet.vega.xyz
-2
View File
@@ -1,9 +1,7 @@
# App configuration variables
NX_TENDERMINT_URL=http://localhost:26617
NX_TENDERMINT_WEBSOCKET_URL=wss://localhost:26617/websocket
NX_VEGA_NETWORKS={\"MAINNET"\:\"https://explorer.vega.xyz"\,\"TESTNET\":\"https://explorer.fairground.wtf\"}
NX_VEGA_ENV=CUSTOM
NX_GITHUB_FEEDBACK_URL=https://github.com/vegaprotocol/feedback/discussions
NX_ETHERSCAN_URL=https://sepolia.etherscan.io
# App flags
+1 -3
View File
@@ -1,10 +1,8 @@
# App configuration variables
NX_TENDERMINT_URL=https://tm.be.devnet1.vega.xyz/tm
NX_TENDERMINT_WEBSOCKET_URL=wss://tm.be.devnet1.vega.xyz/websocket
NX_TENDERMINT_WEBSOCKET_URL=wss://be.devnet1.vega.xyz/websocket
NX_VEGA_CONFIG_URL=https://static.vega.xyz/assets/devnet-network.json
NX_VEGA_NETWORKS={\"MAINNET"\:\"https://explorer.vega.xyz"\,\"TESTNET\":\"https://explorer.fairground.wtf\"}
NX_VEGA_ENV=DEVNET
NX_GITHUB_FEEDBACK_URL=https://github.com/vegaprotocol/feedback/discussions
NX_BLOCK_EXPLORER=https://be.devnet1.vega.xyz/rest
NX_ETHERSCAN_URL=https://sepolia.etherscan.io
NX_VEGA_GOVERNANCE_URL=https://dev.token.vega.xyz
+2 -4
View File
@@ -1,10 +1,8 @@
# App configuration variables
NX_TENDERMINT_URL=https://be.explorer.vega.xyz
NX_TENDERMINT_WEBSOCKET_URL=wss://be.explorer.vega.xyz
NX_TENDERMINT_WEBSOCKET_URL=wss://be.explorer.vega.xyz/websocket
NX_VEGA_CONFIG_URL=https://static.vega.xyz/assets/mainnet-network.json
NX_VEGA_NETWORKS={\"MAINNET"\:\"https://explorer.vega.xyz"\,\"TESTNET\":\"https://explorer.fairground.wtf\"}
NX_VEGA_ENV=MAINNET
NX_GITHUB_FEEDBACK_URL=https://github.com/vegaprotocol/feedback/discussions
NX_BLOCK_EXPLORER=https://be.explorer.vega.xyz/rest/
NX_ETHERSCAN_URL=https://etherscan.io
NX_VEGA_GOVERNANCE_URL=https://token.vega.xyz
NX_VEGA_GOVERNANCE_URL=https://token.vega.xyz
+1 -3
View File
@@ -1,10 +1,8 @@
# App configuration variables
NX_TENDERMINT_URL=https://tm.be.mainnet-mirror.vega.xyz
NX_TENDERMINT_WEBSOCKET_URL=https://tm.be.mainnet-mirror.vega.xyz
NX_TENDERMINT_WEBSOCKET_URL=wss://be.mainnet-mirror.vega.xyz/websocket
NX_VEGA_CONFIG_URL=https://static.vega.xyz/assets/mirror-network.json
NX_VEGA_NETWORKS='{"DEVNET":"https://dev.token.vega.xyz","STAGNET3":"https://stagnet3.token.vega.xyz","TESTNET":"https://token.fairground.wtf","MAINNET":"https://token.vega.xyz"}'
NX_VEGA_ENV=MIRROR
NX_GITHUB_FEEDBACK_URL=https://github.com/vegaprotocol/feedback/discussions
NX_BLOCK_EXPLORER=https://be.mainnet-mirror.vega.xyz/rest/
NX_ETHERSCAN_URL=https://sepolia.etherscan.io
NX_VEGA_GOVERNANCE_URL=https://mainnet-mirror.token.vega.xyz
+1 -2
View File
@@ -5,8 +5,7 @@ NX_VEGA_EXPLORER_URL=https://sandbox.explorer.vega.xyz
NX_VEGA_DOCS_URL=https://docs.vega.xyz/testnet
NX_ETHEREUM_PROVIDER_URL=https://sepolia.infura.io/v3/4f846e79e13f44d1b51bbd7ed9edefb8
NX_ETHERSCAN_URL=https://sepolia.etherscan.io
NX_VEGA_NETWORKS={\"MAINNET"\:\"https://explorer.vega.xyz"\,\"TESTNET\":\"https://explorer.fairground.wtf\"}
NX_TENDERMINT_URL=https://tm.sandbox.vega.xyz
NX_TENDERMINT_WEBSOCKET_URL=wss://tm.sandbox.vega.xyz/websocket
NX_TENDERMINT_WEBSOCKET_URL=wss://be.sandbox.vega.xyz/websocket
NX_ETHERSCAN_URL=https://sepolia.etherscan.io
NX_VEGA_GOVERNANCE_URL=https://sandbox.token.vega.xyz
-1
View File
@@ -4,7 +4,6 @@ NX_HOSTED_WALLET_URL=https://wallet.testnet.vega.xyz
NX_VEGA_CONFIG_URL=https://static.vega.xyz/assets/stagnet1-network.json
NX_VEGA_ENV=STAGNET1
NX_VEGA_EXPLORER_URL=https://stagnet1.explorer.vega.xyz
NX_VEGA_NETWORKS={\"MAINNET"\:\"https://explorer.vega.xyz"\,\"TESTNET\":\"https://explorer.fairground.wtf\"}
NX_VEGA_TOKEN_URL=https://stagnet1.token.vega.xyz
NX_VEGA_WALLET_URL=http://localhost:1789
NX_TENDERMINT_URL=https://tm.n01.stagnet1.vega.xyz
+1 -3
View File
@@ -1,9 +1,7 @@
NX_TENDERMINT_URL=https://tm.n00.stagnet3.vega.xyz
NX_TENDERMINT_WEBSOCKET_URL=wss://tm.n00.stagnet3.vega.xyz/websocket
NX_TENDERMINT_WEBSOCKET_URL=wss://be.stagnet3.vega.xyz/websocket
NX_VEGA_CONFIG_URL=https://static.vega.xyz/assets/stagnet3-network.json
NX_VEGA_NETWORKS={\"MAINNET"\:\"https://explorer.vega.xyz"\,\"TESTNET\":\"https://explorer.fairground.wtf\"}
NX_VEGA_ENV=STAGNET3
NX_GITHUB_FEEDBACK_URL=https://github.com/vegaprotocol/feedback/discussions
NX_BLOCK_EXPLORER=https://be.stagnet3.vega.xyz/rest
NX_VEGA_GOVERNANCE_URL=https://stagnet3.token.vega.xyz
NX_VEGA_REPO_URL=https://github.com/vegaprotocol/vega-dev-releases/releases/
+2 -5
View File
@@ -1,13 +1,10 @@
# App configuration variables
NX_TENDERMINT_URL=https://tm.be.testnet.vega.xyz
NX_BLOCK_EXPLORER=https://be.testnet.vega.xyz/rest
NX_TENDERMINT_WEBSOCKET_URL=wss://tm.be.testnet.vega.xyz/websocket/
NX_TENDERMINT_WEBSOCKET_URL=wss://be.testnet.vega.xyz/websocket
NX_VEGA_CONFIG_URL=https://static.vega.xyz/assets/testnet-network.json
NX_VEGA_NETWORKS={\"MAINNET"\:\"https://explorer.vega.xyz"\,\"TESTNET\":\"https://explorer.fairground.wtf\"}
NX_VEGA_ENV=TESTNET
NX_GITHUB_FEEDBACK_URL=https://github.com/vegaprotocol/feedback/discussions
NX_VEGA_URL=https://api.n07.testnet.vega.xyz/graphql
NX_HOSTED_WALLET_URL=https://wallet.testnet.vega.xyz
NX_VEGA_NETWORKS={}
NX_ETHERSCAN_URL=https://sepolia.etherscan.io
NX_VEGA_GOVERNANCE_URL=https://token.fairground.wtf
NX_VEGA_GOVERNANCE_URL=https://token.fairground.wtf
+1 -3
View File
@@ -3,12 +3,10 @@ NX_VEGA_ENV=VALIDATOR_TESTNET
NX_VEGA_CONFIG_URL=https://static.vega.xyz/assets/validator-testnet-network.json
NX_VEGA_URL=https://api.validators-testnet.vega.xyz/graphql
NX_VEGA_REST=https://api.validators-testnet.vega.xyz/
NX_VEGA_NETWORKS='{"DEVNET":"https://dev.token.vega.xyz","STAGNET3":"https://stagnet3.token.vega.xyz","TESTNET":"https://token.fairground.wtf","MAINNET":"https://token.vega.xyz"}'
NX_ETHEREUM_PROVIDER_URL=https://sepolia.infura.io/v3/4f846e79e13f44d1b51bbd7ed9edefb8
NX_ETHERSCAN_URL=https://sepolia.etherscan.io
NX_GITHUB_FEEDBACK_URL=https://github.com/vegaprotocol/feedback/discussions
NX_VEGA_GOVERNANCE_URL=https://validator-testnet.governance.vega.xyz
NX_TENDERMINT_URL=https://tm.be.validators-testnet.vega.xyz
NX_BLOCK_EXPLORER=https://be.validators-testnet.vega.xyz/rest
NX_TENDERMINT_WEBSOCKET_URL=wss://tm.be.validators-testnet.vega.xyz/websocket/
NX_TENDERMINT_WEBSOCKET_URL=wss://be.validators-testnet.vega.xyz/websocket
-1
View File
@@ -2,6 +2,5 @@
NX_TENDERMINT_URL=http://localhost:26607/
NX_TENDERMINT_WEBSOCKET_URL=wss://localhost:26607/websocket
NX_VEGA_ENV=CUSTOM
NX_GITHUB_FEEDBACK_URL=https://github.com/vegaprotocol/feedback/discussions
NX_BLOCK_EXPLORER=
NX_ETHERSCAN_URL=https://sepolia.etherscan.io
+5
View File
@@ -0,0 +1,5 @@
function ReactMarkdown({ children }) {
return <div>{children}</div>;
}
export default ReactMarkdown;
@@ -22,29 +22,3 @@ query ExplorerFutureEpoch {
}
}
}
# query ExplorerEpoch($id: ID!) {
#
##### This could be useful for calculating roughly when a future epoch will
##### occur, but epoch not exist results in a total error
# networkParameter(key: "validators.epoch.length") {
# value
# }
#
##### This could be useful for relating where we are in time, but as above
##### the total failure caused by epoch(id) not existing
##### means this is useful
# currentEpoch: epoch {
# id
# }
#
# epoch(id: $id) {
# id
# timestamps {
# start
# end
# firstBlock
# lastBlock
# }
# }
#}
@@ -4,13 +4,14 @@ import { ENV } from '../../../config/env';
import Hash from '../hash';
export type ProposalLinkProps = {
id: string;
text?: string;
};
/**
* Given a proposal ID, generates an external link over to
* the Governance page for more information
*/
const ProposalLink = ({ id }: ProposalLinkProps) => {
const ProposalLink = ({ id, text }: ProposalLinkProps) => {
const { data } = useExplorerProposalQuery({
variables: { id },
});
@@ -20,7 +21,7 @@ const ProposalLink = ({ id }: ProposalLinkProps) => {
return (
<ExternalLink href={`${base}/proposals/${id}`}>
<Hash text={label} />
{text ? text : <Hash text={label} />}
</ExternalLink>
);
};
@@ -101,7 +101,7 @@ const DeterministicOrderDetails = ({
{t('Remaining')}
</h2>
<h5 className="text-lg font-medium text-gray-500 mb-0">
{o.remaining}
<SizeInMarket size={o.remaining} marketId={o.market.id} />
</h5>
</div>
)}
@@ -0,0 +1,7 @@
query ExplorerProposalStatus($id: ID!) {
proposal(id: $id) {
id
state
rejectionReason
}
}
@@ -0,0 +1,19 @@
query ExplorerNewAssetSignatureBundle($id: ID!) {
erc20ListAssetBundle(assetId: $id) {
signatures
nonce
}
asset(id: $id) {
status
}
}
query ExplorerUpdateAssetSignatureBundle($id: ID!) {
erc20SetAssetLimitsBundle(proposalId: $id) {
signatures
nonce
}
asset(id: $id) {
status
}
}
@@ -0,0 +1,50 @@
import * as Types from '@vegaprotocol/types';
import { gql } from '@apollo/client';
import * as Apollo from '@apollo/client';
const defaultOptions = {} as const;
export type ExplorerProposalStatusQueryVariables = Types.Exact<{
id: Types.Scalars['ID'];
}>;
export type ExplorerProposalStatusQuery = { __typename?: 'Query', proposal?: { __typename?: 'Proposal', id?: string | null, state: Types.ProposalState, rejectionReason?: Types.ProposalRejectionReason | null } | null };
export const ExplorerProposalStatusDocument = gql`
query ExplorerProposalStatus($id: ID!) {
proposal(id: $id) {
id
state
rejectionReason
}
}
`;
/**
* __useExplorerProposalStatusQuery__
*
* To run a query within a React component, call `useExplorerProposalStatusQuery` and pass it any options that fit your needs.
* When your component renders, `useExplorerProposalStatusQuery` 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 } = useExplorerProposalStatusQuery({
* variables: {
* id: // value for 'id'
* },
* });
*/
export function useExplorerProposalStatusQuery(baseOptions: Apollo.QueryHookOptions<ExplorerProposalStatusQuery, ExplorerProposalStatusQueryVariables>) {
const options = {...defaultOptions, ...baseOptions}
return Apollo.useQuery<ExplorerProposalStatusQuery, ExplorerProposalStatusQueryVariables>(ExplorerProposalStatusDocument, options);
}
export function useExplorerProposalStatusLazyQuery(baseOptions?: Apollo.LazyQueryHookOptions<ExplorerProposalStatusQuery, ExplorerProposalStatusQueryVariables>) {
const options = {...defaultOptions, ...baseOptions}
return Apollo.useLazyQuery<ExplorerProposalStatusQuery, ExplorerProposalStatusQueryVariables>(ExplorerProposalStatusDocument, options);
}
export type ExplorerProposalStatusQueryHookResult = ReturnType<typeof useExplorerProposalStatusQuery>;
export type ExplorerProposalStatusLazyQueryHookResult = ReturnType<typeof useExplorerProposalStatusLazyQuery>;
export type ExplorerProposalStatusQueryResult = Apollo.QueryResult<ExplorerProposalStatusQuery, ExplorerProposalStatusQueryVariables>;
@@ -0,0 +1,98 @@
import * as Types from '@vegaprotocol/types';
import { gql } from '@apollo/client';
import * as Apollo from '@apollo/client';
const defaultOptions = {} as const;
export type ExplorerNewAssetSignatureBundleQueryVariables = Types.Exact<{
id: Types.Scalars['ID'];
}>;
export type ExplorerNewAssetSignatureBundleQuery = { __typename?: 'Query', erc20ListAssetBundle?: { __typename?: 'Erc20ListAssetBundle', signatures: string, nonce: string } | null, asset?: { __typename?: 'Asset', status: Types.AssetStatus } | null };
export type ExplorerUpdateAssetSignatureBundleQueryVariables = Types.Exact<{
id: Types.Scalars['ID'];
}>;
export type ExplorerUpdateAssetSignatureBundleQuery = { __typename?: 'Query', erc20SetAssetLimitsBundle: { __typename?: 'ERC20SetAssetLimitsBundle', signatures: string, nonce: string }, asset?: { __typename?: 'Asset', status: Types.AssetStatus } | null };
export const ExplorerNewAssetSignatureBundleDocument = gql`
query ExplorerNewAssetSignatureBundle($id: ID!) {
erc20ListAssetBundle(assetId: $id) {
signatures
nonce
}
asset(id: $id) {
status
}
}
`;
/**
* __useExplorerNewAssetSignatureBundleQuery__
*
* To run a query within a React component, call `useExplorerNewAssetSignatureBundleQuery` and pass it any options that fit your needs.
* When your component renders, `useExplorerNewAssetSignatureBundleQuery` 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 } = useExplorerNewAssetSignatureBundleQuery({
* variables: {
* id: // value for 'id'
* },
* });
*/
export function useExplorerNewAssetSignatureBundleQuery(baseOptions: Apollo.QueryHookOptions<ExplorerNewAssetSignatureBundleQuery, ExplorerNewAssetSignatureBundleQueryVariables>) {
const options = {...defaultOptions, ...baseOptions}
return Apollo.useQuery<ExplorerNewAssetSignatureBundleQuery, ExplorerNewAssetSignatureBundleQueryVariables>(ExplorerNewAssetSignatureBundleDocument, options);
}
export function useExplorerNewAssetSignatureBundleLazyQuery(baseOptions?: Apollo.LazyQueryHookOptions<ExplorerNewAssetSignatureBundleQuery, ExplorerNewAssetSignatureBundleQueryVariables>) {
const options = {...defaultOptions, ...baseOptions}
return Apollo.useLazyQuery<ExplorerNewAssetSignatureBundleQuery, ExplorerNewAssetSignatureBundleQueryVariables>(ExplorerNewAssetSignatureBundleDocument, options);
}
export type ExplorerNewAssetSignatureBundleQueryHookResult = ReturnType<typeof useExplorerNewAssetSignatureBundleQuery>;
export type ExplorerNewAssetSignatureBundleLazyQueryHookResult = ReturnType<typeof useExplorerNewAssetSignatureBundleLazyQuery>;
export type ExplorerNewAssetSignatureBundleQueryResult = Apollo.QueryResult<ExplorerNewAssetSignatureBundleQuery, ExplorerNewAssetSignatureBundleQueryVariables>;
export const ExplorerUpdateAssetSignatureBundleDocument = gql`
query ExplorerUpdateAssetSignatureBundle($id: ID!) {
erc20SetAssetLimitsBundle(proposalId: $id) {
signatures
nonce
}
asset(id: $id) {
status
}
}
`;
/**
* __useExplorerUpdateAssetSignatureBundleQuery__
*
* To run a query within a React component, call `useExplorerUpdateAssetSignatureBundleQuery` and pass it any options that fit your needs.
* When your component renders, `useExplorerUpdateAssetSignatureBundleQuery` 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 } = useExplorerUpdateAssetSignatureBundleQuery({
* variables: {
* id: // value for 'id'
* },
* });
*/
export function useExplorerUpdateAssetSignatureBundleQuery(baseOptions: Apollo.QueryHookOptions<ExplorerUpdateAssetSignatureBundleQuery, ExplorerUpdateAssetSignatureBundleQueryVariables>) {
const options = {...defaultOptions, ...baseOptions}
return Apollo.useQuery<ExplorerUpdateAssetSignatureBundleQuery, ExplorerUpdateAssetSignatureBundleQueryVariables>(ExplorerUpdateAssetSignatureBundleDocument, options);
}
export function useExplorerUpdateAssetSignatureBundleLazyQuery(baseOptions?: Apollo.LazyQueryHookOptions<ExplorerUpdateAssetSignatureBundleQuery, ExplorerUpdateAssetSignatureBundleQueryVariables>) {
const options = {...defaultOptions, ...baseOptions}
return Apollo.useLazyQuery<ExplorerUpdateAssetSignatureBundleQuery, ExplorerUpdateAssetSignatureBundleQueryVariables>(ExplorerUpdateAssetSignatureBundleDocument, options);
}
export type ExplorerUpdateAssetSignatureBundleQueryHookResult = ReturnType<typeof useExplorerUpdateAssetSignatureBundleQuery>;
export type ExplorerUpdateAssetSignatureBundleLazyQueryHookResult = ReturnType<typeof useExplorerUpdateAssetSignatureBundleLazyQuery>;
export type ExplorerUpdateAssetSignatureBundleQueryResult = Apollo.QueryResult<ExplorerUpdateAssetSignatureBundleQuery, ExplorerUpdateAssetSignatureBundleQueryVariables>;
@@ -0,0 +1,70 @@
import { t } from '@vegaprotocol/i18n';
import { Lozenge } from '@vegaprotocol/ui-toolkit';
import type { components } from '../../../../../types/explorer';
import type { ExplorerProposalStatusQuery } from './__generated__/Proposal';
import { useExplorerProposalStatusQuery } from './__generated__/Proposal';
type Terms = components['schemas']['vegaProposalTerms'];
export function format(date: string | undefined, def: string) {
if (!date) {
return def;
}
return new Date().toLocaleDateString() || def;
}
export function getDate(
data: ExplorerProposalStatusQuery | undefined,
terms: Terms
): string {
const DEFAULT = t('Unknown');
if (!data?.proposal?.state) {
return DEFAULT;
}
switch (data.proposal.state) {
case 'STATE_DECLINED':
return `${t('Rejected on')}: ${format(terms.closingTimestamp, DEFAULT)}`;
case 'STATE_ENACTED':
return `${t('Vote passed on')}: ${format(
terms.enactmentTimestamp,
DEFAULT
)}`;
case 'STATE_FAILED':
return `${t('Failed on')}: ${format(terms.validationTimestamp, DEFAULT)}`;
case 'STATE_OPEN':
return `${t('Open until')}: ${format(terms.closingTimestamp, DEFAULT)}`;
case 'STATE_PASSED':
return `${t('Passed on')}: ${format(terms.closingTimestamp, DEFAULT)}`;
case 'STATE_REJECTED':
return `${t('Rejected on submission')}`;
case 'STATE_WAITING_FOR_NODE_VOTE':
return `${t('Opening')}...`;
default:
return DEFAULT;
}
}
interface ProposalDateProps {
id: string;
terms: Terms;
}
/**
* Shows the most relevant date for the proposal summary view. Depending on the
* state returned by GraphQL, we show either the validation, closing or enactment
* timestamp
*/
export const ProposalDate = ({ terms, id }: ProposalDateProps) => {
const { data } = useExplorerProposalStatusQuery({
variables: {
id,
},
});
return (
<Lozenge className="font-sans text-xs float-right">
{getDate(data, terms)}
</Lozenge>
);
};
@@ -0,0 +1,117 @@
import { Icon, Tooltip } from '@vegaprotocol/ui-toolkit';
import type { IconProps } from '@vegaprotocol/ui-toolkit';
import { useExplorerProposalStatusQuery } from './__generated__/Proposal';
import type { ExplorerProposalStatusQuery } from './__generated__/Proposal';
import type * as Apollo from '@apollo/client';
import type * as Types from '@vegaprotocol/types';
import { t } from '@vegaprotocol/i18n';
type ProposalQueryResult = Apollo.QueryResult<
ExplorerProposalStatusQuery,
Types.Exact<{
id: string;
}>
>;
interface ProposalStatusIconProps {
id: string;
}
type IconAndLabel = {
icon: IconProps['name'];
label: string;
};
/**
* Select an icon for a given query result. Tolerates queries that don't return
* any data
*
* @param data a data result from useExplorerProposalStatusQuery
* @returns Icon name
*/
export function getIconAndLabelForStatus(
res: ProposalQueryResult
): IconAndLabel {
const DEFAULT: IconAndLabel = {
icon: 'error',
label: t('Proposal state unknown'),
};
if (res.loading) {
return {
icon: 'more',
label: t('Loading data'),
};
}
if (!res?.data?.proposal || res.error) {
return {
icon: 'error',
label: res.error?.message || DEFAULT.label,
};
}
switch (res.data.proposal.state) {
case 'STATE_DECLINED':
return {
icon: 'stop',
label: t('Proposal did not have enough participation to be valid'),
};
case 'STATE_ENACTED':
return {
icon: 'tick-circle',
label: t('Vote passed and the proposal has been enacted'),
};
case 'STATE_FAILED':
return {
icon: 'thumbs-down',
label: t('Proposal became invalid and was not processed'),
};
case 'STATE_OPEN':
return {
// A checklist to indicate in progress
icon: 'form',
label: t('Voting is in progress'),
};
case 'STATE_PASSED':
return {
icon: 'thumbs-up',
label: t(
'Voting is complete and this proposal was approved. It is not yet enacted.'
),
};
case 'STATE_REJECTED':
return {
icon: 'disable',
label: t('The proposal was invalid'),
};
case 'STATE_WAITING_FOR_NODE_VOTE':
return {
// A sparkly thing indicating it's new
icon: 'clean',
label: t('Proposal is being checked by validators'),
};
default:
return DEFAULT;
}
}
/**
*/
export const ProposalStatusIcon = ({ id }: ProposalStatusIconProps) => {
const { icon, label } = getIconAndLabelForStatus(
useExplorerProposalStatusQuery({
variables: {
id,
},
})
);
return (
<div className="float-left mr-3">
<Tooltip description={<p>{label}</p>}>
<Icon name={icon} />
</Tooltip>
</div>
);
};
@@ -0,0 +1,42 @@
import { Loader } from '@vegaprotocol/ui-toolkit';
import { BundleError } from './signature-bundle/bundle-error';
import { BundleExists } from './signature-bundle/bundle-exists';
import { useExplorerNewAssetSignatureBundleQuery } from './__generated__/SignatureBundle';
export interface ProposalSignatureBundleByTypeProps {
id: string;
}
/**
* If a proposal needs a signature bundle, AND that signature bundle exists
* AND that proposal is a New Asset Proposal, render an overview of the
* signature bundle. Or an error.
*
* There is an almost identical component, ProposalSignatureBundleUpdateAsset
*/
export const ProposalSignatureBundleNewAsset = ({
id,
}: ProposalSignatureBundleByTypeProps) => {
const { data, error, loading } = useExplorerNewAssetSignatureBundleQuery({
variables: {
id,
},
});
if (loading) {
return <Loader />;
}
if (data?.erc20ListAssetBundle?.signatures) {
return (
<BundleExists
signatures={data.erc20ListAssetBundle.signatures}
nonce={data.erc20ListAssetBundle.nonce}
status={data.asset?.status}
proposalId={id}
/>
);
} else {
return <BundleError status={data?.asset?.status} error={error} />;
}
};
@@ -0,0 +1,39 @@
import { Loader } from '@vegaprotocol/ui-toolkit';
import type { ProposalSignatureBundleByTypeProps } from './signature-bundle-new';
import { BundleError } from './signature-bundle/bundle-error';
import { BundleExists } from './signature-bundle/bundle-exists';
import { useExplorerUpdateAssetSignatureBundleQuery } from './__generated__/SignatureBundle';
/**
* If a proposal needs a signature bundle, AND that signature bundle exists
* AND that proposal is a Asset Limits Proposal, render an overview of the
* signature bundle. Or an error.
*
* There is an almost identical component, ProposalSignatureBundleNewAsset
*/
export const ProposalSignatureBundleUpdateAsset = ({
id,
}: ProposalSignatureBundleByTypeProps) => {
const { data, error, loading } = useExplorerUpdateAssetSignatureBundleQuery({
variables: {
id,
},
});
if (loading) {
return <Loader />;
}
if (data?.erc20SetAssetLimitsBundle?.signatures) {
return (
<BundleExists
signatures={data.erc20SetAssetLimitsBundle.signatures}
nonce={data.erc20SetAssetLimitsBundle.nonce}
status={data.asset?.status}
proposalId={id}
/>
);
} else {
return <BundleError status={data?.asset?.status} error={error} />;
}
};
@@ -0,0 +1,31 @@
import { ProposalSignatureBundleNewAsset } from './signature-bundle-new';
import { ProposalSignatureBundleUpdateAsset } from './signature-bundle-update';
export function format(date: string | undefined, def: string) {
if (!date) {
return def;
}
return new Date().toLocaleDateString() || def;
}
interface ProposalSignatureBundleProps {
id: string;
type: 'NewAsset' | 'UpdateAsset';
}
/**
* Some proposals, if enacted, generate a signature bundle.
* The queries have to be split due to the way the API returns
* errors, hence this slightly redundant feeling switcher.
*/
export const ProposalSignatureBundle = ({
id,
type,
}: ProposalSignatureBundleProps) => {
return type === 'NewAsset' ? (
<ProposalSignatureBundleNewAsset id={id} />
) : (
<ProposalSignatureBundleUpdateAsset id={id} />
);
};
@@ -0,0 +1,67 @@
import type { ApolloError } from '@apollo/client';
import { MockedProvider } from '@apollo/client/testing';
import { render } from '@testing-library/react';
import { AssetStatus } from '@vegaprotocol/types';
import { MemoryRouter } from 'react-router-dom';
import { BundleError } from './bundle-error';
describe('Bundle Error', () => {
const NON_ENABLED_STATUS: AssetStatus[] = [
AssetStatus.STATUS_PENDING_LISTING,
AssetStatus.STATUS_PROPOSED,
AssetStatus.STATUS_REJECTED,
];
const ENABLED_STATUS: AssetStatus[] = [AssetStatus.STATUS_ENABLED];
it.each(NON_ENABLED_STATUS)(
'shows the apollo error if not enabled and a message is provided',
(status) => {
const screen = render(
<MemoryRouter>
<MockedProvider>
<BundleError
error={{ message: 'test-error-message' } as ApolloError}
status={status}
/>
</MockedProvider>
</MemoryRouter>
);
expect(screen.getByText('test-error-message')).toBeInTheDocument();
}
);
it.each(NON_ENABLED_STATUS)(
'shows some fallback error message if the bundle has not been used and there is no error',
(status) => {
const screen = render(
<MemoryRouter>
<MockedProvider>
<BundleError status={status} />
</MockedProvider>
</MemoryRouter>
);
expect(screen.getByText('No bundle for proposal ID')).toBeInTheDocument();
}
);
it.each(ENABLED_STATUS)(
'hides ProposalLink if the status is enabled',
(status) => {
const screen = render(
<MemoryRouter>
<MockedProvider>
<BundleError
error={{ message: 'irrelevant ' } as ApolloError}
status={status}
/>
</MockedProvider>
</MemoryRouter>
);
expect(screen.getByText('Asset already enabled')).toBeInTheDocument();
}
);
});
@@ -0,0 +1,34 @@
import type { ApolloError } from '@apollo/client';
import type { AssetStatus } from '@vegaprotocol/types';
import { t } from '@vegaprotocol/i18n';
import Hash from '../../../../links/hash';
import { IconForBundleStatus } from './bundle-icon';
export interface BundleErrorProps {
status?: AssetStatus;
error?: ApolloError;
}
/**
* Renders if a proposal signature bundle cannot be found.
* It is also possible that a data node has dropped the bundle
* from its retention so there is a backup case where we check
* the status - if it's already enabled, pretend this isn't an error
*/
export const BundleError = ({ status, error }: BundleErrorProps) => {
return (
<div className="w-auto max-w-lg border-2 border-solid border-vega-light-100 dark:border-vega-dark-200 p-5 mt-5">
<IconForBundleStatus status={status} />
<h1 className="text-xl pb-1">{t('No signature bundle found')}</h1>
<p>
{status === 'STATUS_ENABLED' ? (
t('Asset already enabled')
) : (
<Hash text={error ? error.message : t('No bundle for proposal ID')} />
)}
</p>
</div>
);
};
@@ -0,0 +1,64 @@
import { MockedProvider } from '@apollo/client/testing';
import { render } from '@testing-library/react';
import { AssetStatus } from '@vegaprotocol/types';
import { MemoryRouter } from 'react-router-dom';
import { BundleExists } from './bundle-exists';
describe('Bundle Exists', () => {
const NON_ENABLED_STATUS: AssetStatus[] = [
AssetStatus.STATUS_PENDING_LISTING,
AssetStatus.STATUS_PROPOSED,
AssetStatus.STATUS_REJECTED,
];
const ENABLED_STATUS: AssetStatus[] = [AssetStatus.STATUS_ENABLED];
const MOCK_SIGNATURES =
'0x1760ce4efec01d5bb9fe57c0660a39a27e0b5a1bd39b4d3fc0452bf142a4ef733baaf4dbedd74cd676c759f96ac7f412ec05e136bbff8a81d9f0c2428df8e099004c4d166ece0527d86e202386e8758580790d0a46f6429baaa268b4bf5c11c9e3402e175a9022ae8295e543853c01383ef17cd58458ddfc9c706fca0ecffa0d3d0160eb5234e63a78b9649428ca7659eb693fdde86edfc6c2707ef2e8fbf4c76a9f0eebe183da571a58837e2fa995d7b10955ecf04c138dc0ce964f17c3de1f5c6d0060ec132cc515cf974ead1da38e2ff8d4b870335865e8d4d8c982182bddea18bb513e2d37fd32de7fedc0c4f694e6bcdcf20f8547f19e7d9d25ce32c6ca9ea51e01ad3b92475778d9da7251d3943071f59107c9cd7ad9dd1923c06e88d3352869d919a591bf30732bad2c3fcf30a9f664dbb7a9c65a64875a48cbeb5741bd0a853901';
const MOCK_NONCE =
'18250011763873610289536200551900545467959221115607409799241178172533618346952';
const MOCK_PROPOSAL_ID =
'285923fed8c66ffb416b163e8ec72d3a87b9b8e2570e7ee7fe97d7092a918bc8';
const PROPOSAL_LINK_TEXT = 'Visit our Governance site to submit this';
it.each(NON_ENABLED_STATUS)(
'shows a handy ProposalLink if the status is anything except enabled',
(status) => {
const screen = render(
<MemoryRouter>
<MockedProvider>
<BundleExists
nonce={MOCK_NONCE}
proposalId={MOCK_PROPOSAL_ID}
signatures={MOCK_SIGNATURES}
status={status}
/>
</MockedProvider>
</MemoryRouter>
);
expect(screen.getByText(PROPOSAL_LINK_TEXT)).toBeInTheDocument();
}
);
it.each(ENABLED_STATUS)(
'hides ProposalLink if the status is enabled',
(status) => {
const screen = render(
<MemoryRouter>
<MockedProvider>
<BundleExists
nonce={MOCK_NONCE}
proposalId={MOCK_PROPOSAL_ID}
signatures={MOCK_SIGNATURES}
status={status}
/>
</MockedProvider>
</MemoryRouter>
);
expect(screen.queryAllByText(PROPOSAL_LINK_TEXT)).toEqual([]);
}
);
});
@@ -0,0 +1,46 @@
import { t } from '@vegaprotocol/i18n';
import type { AssetStatus } from '@vegaprotocol/types';
import ProposalLink from '../../../../links/proposal-link/proposal-link';
import { IconForBundleStatus } from './bundle-icon';
import { ProposalSignatureBundleDetails } from './details';
export interface BundleExistsProps {
signatures: string;
nonce: string;
status?: AssetStatus;
proposalId: string;
}
/**
* If a proposal needs a signature bundle, AND that signature bundle exists,
* this component renders that signature bundle.
*
*/
export const BundleExists = ({
signatures,
nonce,
status,
proposalId,
}: BundleExistsProps) => {
return (
<div className="w-auto max-w-lg border-2 border-solid border-vega-light-100 dark:border-vega-dark-200 p-5 mt-5">
<IconForBundleStatus status={status} />
<h1 className="text-xl pb-1">
{status === 'STATUS_ENABLED'
? t('Asset added to bridge')
: t('Signature bundle generated')}
</h1>
<ProposalSignatureBundleDetails signatures={signatures} nonce={nonce} />
{status !== 'STATUS_ENABLED' ? (
<p className="mt-5">
<ProposalLink
id={proposalId}
text={t('Visit our Governance site to submit this')}
/>
</p>
) : null}
</div>
);
};
@@ -0,0 +1,33 @@
import { render } from '@testing-library/react';
import { AssetStatus } from '@vegaprotocol/types';
import { IconForBundleStatus } from './bundle-icon';
describe('Bundle status icon', () => {
const NON_ENABLED_STATUS: AssetStatus[] = [
AssetStatus.STATUS_PENDING_LISTING,
AssetStatus.STATUS_PROPOSED,
AssetStatus.STATUS_REJECTED,
];
const ENABLED_STATUS: AssetStatus[] = [AssetStatus.STATUS_ENABLED];
it.each(NON_ENABLED_STATUS)(
'show a sparkle icon if the bundle is unused',
(status) => {
const screen = render(<IconForBundleStatus status={status} />);
const i = screen.getByRole('img');
expect(i).toHaveAttribute('aria-label');
expect(i.getAttribute('aria-label')).toMatch(/clean/);
}
);
it.each(ENABLED_STATUS)(
'shows a tick if the bundle is already used',
(status) => {
const screen = render(<IconForBundleStatus status={status} />);
const i = screen.getByRole('img');
expect(i).toHaveAttribute('aria-label');
expect(i.getAttribute('aria-label')).toMatch(/tick-circle/);
}
);
});
@@ -0,0 +1,17 @@
import type { AssetStatus } from '@vegaprotocol/types';
import type { IconName } from '@vegaprotocol/ui-toolkit';
import { Icon } from '@vegaprotocol/ui-toolkit';
export interface IconForBundleStatusProps {
status?: AssetStatus;
}
/**
* Naively select an icon for an asset. If it is enabled, we show a tick - anything
* else is assumed to be 'in progress'. There should only be a signature bundle or the
* asset should not exist
*/
export const IconForBundleStatus = ({ status }: IconForBundleStatusProps) => {
const i: IconName = status === 'STATUS_ENABLED' ? 'tick-circle' : 'clean';
return <Icon className="float-left mt-2 mr-3" name={i} />;
};
@@ -0,0 +1,41 @@
import { t } from '@vegaprotocol/i18n';
export interface ProposalSignatureBundleDetailsProps {
signatures: string;
nonce: string;
}
export const ProposalSignatureBundleDetails = ({
signatures,
nonce,
}: ProposalSignatureBundleDetailsProps) => {
return (
<details className="mt-5">
<summary>{t('Signature bundle details')}</summary>
<div className="ml-4">
<h2 className="text-lg mt-2 mb-2">{t('Signatures')}</h2>
<p>
<textarea
className="font-mono bg-neutral-300 text-[11px] leading-3 text-gray-900 w-full p-2 max-w-[615px]"
readOnly={true}
rows={12}
cols={120}
value={signatures}
/>
</p>
<h2 className="text-lg mt-5 mb-2">{t('Nonce')}</h2>
<p>
<textarea
className="font-mono bg-neutral-300 text-[11px] leading-3 text-gray-900 w-full p-2 max-w-[615px]"
readOnly={true}
rows={2}
cols={120}
value={nonce}
/>
</p>
</div>
</details>
);
};
@@ -0,0 +1,90 @@
import type { ProposalTerms } from '../tx-proposal';
import { useState } from 'react';
import type { components } from '../../../../../types/explorer';
import { JsonViewerDialog } from '../../../dialogs/json-viewer-dialog';
import ProposalLink from '../../../links/proposal-link/proposal-link';
import truncate from 'lodash/truncate';
import { ProposalStatusIcon } from './proposal-status-icon';
import ReactMarkdown from 'react-markdown';
import { ProposalDate } from './proposal-date';
import { t } from '@vegaprotocol/i18n';
type Rationale = components['schemas']['vegaProposalRationale'];
type ProposalTermsDialog = {
open: boolean;
title: string;
content: unknown;
};
interface ProposalSummaryProps {
id: string;
rationale?: Rationale;
terms?: ProposalTerms;
}
/**
* Effectively a 'preview' for what the proposal is about, and a link to the
* Token site for full breakdown of votes
*/
export const ProposalSummary = ({
id,
rationale,
terms,
}: ProposalSummaryProps) => {
const [dialog, setDialog] = useState<ProposalTermsDialog>({
open: false,
title: '',
content: null,
});
const openDialog = () => {
if (!terms) return;
setDialog({
open: true,
title: rationale?.title || t('Proposal details'),
content: terms ? terms : {},
});
};
const md =
rationale && rationale.description
? truncate(rationale.description, {
// Limits the description to roughly 5 lines, maximum
length: 350,
})
: '';
return (
<div className="w-auto max-w-lg border-2 border-solid border-vega-light-100 dark:border-vega-dark-200 p-5">
{id && <ProposalStatusIcon id={id} />}
{rationale?.title && <h1 className="text-xl pb-1">{rationale.title}</h1>}
{rationale?.description && (
<p className="pt-2 text-sm leading-tight">
<ReactMarkdown
className="react-markdown-container"
skipHtml={true}
disallowedElements={['img']}
linkTarget="_blank"
>
{md}
</ReactMarkdown>
</p>
)}
<p className="pt-5">
<button className="underline max-md:hidden mr-5" onClick={openDialog}>
{t('View terms')}
</button>{' '}
<ProposalLink id={id} text={t('Full details')} />
{terms && <ProposalDate terms={terms} id={id} />}
</p>
<JsonViewerDialog
open={dialog.open}
onChange={(isOpen) => setDialog({ ...dialog, open: isOpen })}
title={dialog.title}
content={dialog.content}
/>
</div>
);
};
@@ -55,7 +55,7 @@ export const TxDetailsShared = ({
<TableRow modifier="bordered">
<TableCell {...sharedHeaderProps}>{t('Hash')}</TableCell>
<TableCell>
<Hash text={txData.hash} />
<Hash text={txData.hash.toLowerCase()} />
</TableCell>
</TableRow>
<TableRow modifier="bordered">
@@ -24,6 +24,7 @@ import { TxDetailsProtocolUpgrade } from './tx-details-protocol-upgrade';
import { TxDetailsIssueSignatures } from './tx-issue-signatures';
import { TxDetailsNodeAnnounce } from './tx-node-announce';
import { TxDetailsStateVariable } from './tx-state-variable-proposal';
import { TxProposal } from './tx-proposal';
import { TxDetailsTransfer } from './tx-transfer';
interface TxDetailsWrapperProps {
@@ -88,6 +89,8 @@ function getTransactionComponent(txData?: BlockExplorerTransactionResult) {
return TxDetailsOrderAmend;
case 'Validator Heartbeat':
return TxDetailsHeartbeat;
case 'Proposal':
return TxProposal;
case 'Vote on Proposal':
return TxProposalVote;
case 'Batch Market Instructions':
@@ -0,0 +1,115 @@
import type { BlockExplorerTransactionResult } from '../../../routes/types/block-explorer-response';
import type { TendermintBlocksResponse } from '../../../routes/blocks/tendermint-blocks-response';
import { sharedHeaderProps, TxDetailsShared } from './shared/tx-details-shared';
import { TableCell, TableRow, TableWithTbody } from '../../table';
import type { components } from '../../../../types/explorer';
import { txSignatureToDeterministicId } from '../lib/deterministic-ids';
import has from 'lodash/has';
import { ProposalSummary } from './proposal/summary';
import Hash from '../../links/hash';
import { ProposalSignatureBundle } from './proposal/signature-bundle';
import { t } from '@vegaprotocol/i18n';
export type Proposal = components['schemas']['v1ProposalSubmission'];
export type ProposalTerms = components['schemas']['vegaProposalTerms'];
interface TxProposalProps {
txData: BlockExplorerTransactionResult | undefined;
pubKey: string | undefined;
blockData: TendermintBlocksResponse | undefined;
}
/**
* Detects if a given proposal requires a signature bundle to be emitted by the validators for
* the proposal to be completed after it is accepted by the governance vote
*
* @param t The details of the proposal
* @returns boolean True if a signature bundle is required. Used to fetch a signature bundle
*/
export function proposalRequiresSignatureBundle(proposal?: Proposal): boolean {
if (!proposal?.terms) {
return false;
}
return !!['newAsset', 'updateAsset'].filter((requiredIfExists) =>
has(proposal.terms, requiredIfExists)
);
}
/**
* Given a proposal, returns a nice text label for the proposal type
*
* @param terms The details of the proposal
* @returns string Proposal type
*/
export function proposalTypeLabel(terms?: ProposalTerms): string {
if (has(terms, 'newAsset')) {
return t('New asset proposal');
} else if (has(terms, 'updateAsset')) {
return t('Update asset proposal');
} else if (has(terms, 'newMarket')) {
return t('New market proposal');
} else if (has(terms, 'updateMarket')) {
return t('Update market proposal');
} else if (has(terms, 'updateNetworkParameter')) {
return t('Update network parameter');
} else if (has(terms, 'newFreeform')) {
return t('Freeform proposal');
}
// The list above contains all currently known types. This will be triggered if a new
// unrecognised proposal type is added.
return t('Governance proposal');
}
/**
* A proposal. It's more simplistic than man other views because there are already other, better
* ways to view things about a proposal!
*
*/
export const TxProposal = ({ txData, pubKey, blockData }: TxProposalProps) => {
if (!txData || !txData.command.proposalSubmission) {
return <>{t('Awaiting Block Explorer transaction details')}</>;
}
let deterministicId = '';
const proposal: Proposal = txData.command.proposalSubmission;
const sig = txData?.signature?.value;
if (sig) {
deterministicId = txSignatureToDeterministicId(sig);
}
return (
<>
<TableWithTbody className="mb-8" allowWrap={true}>
<TableRow modifier="bordered">
<TableCell {...sharedHeaderProps}>{t('Type')}</TableCell>
<TableCell>{proposalTypeLabel(proposal.terms)}</TableCell>
</TableRow>
{/* TODO: Disable type row */}
<TxDetailsShared
txData={txData}
pubKey={pubKey}
blockData={blockData}
hideTypeRow={true}
/>
<TableRow modifier="bordered">
<TableCell>{t('Proposal ID')}</TableCell>
<TableCell>
<Hash text={deterministicId} />
</TableCell>
</TableRow>
</TableWithTbody>
<ProposalSummary
id={deterministicId}
rationale={proposal.rationale}
terms={proposal?.terms}
/>
{proposalRequiresSignatureBundle(proposal) && (
<ProposalSignatureBundle
id={deterministicId}
type={proposal.terms?.newAsset ? 'NewAsset' : 'UpdateAsset'}
/>
)}
</>
);
};
@@ -9,7 +9,7 @@ import type {
// Note: Long enough that there is a truncated output and a full output
const pubKey =
'67755549e43e95f0697f83b2bf419c6ccc18eee32a8a61b8ba6f59471b86fbef';
const hash = '7416753A30622A9E24A06F0172D6C33A95186B36806D96345C6DC5A23FA3F283';
const hash = '7416753a30622a9e24a06f0172d6c33a95186b36806d96345c6dc5a23fa3f283';
const height = '52987';
const txData: BlockExplorerTransactionResult = {
+9
View File
@@ -2,3 +2,12 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
.react-markdown-container a {
color: #ff077f;
text-decoration: underline;
}
.react-markdown-container a:before {
content: '🔗 ';
}
+2 -2
View File
@@ -19,8 +19,8 @@ module.exports = defineConfig({
supportFile: './src/support/index.js',
video: false,
videoUploadOnPasses: false,
videosFolder: '../../dist/cypress/apps/token-e2e/videos',
screenshotsFolder: '../../dist/cypress/apps/token-e2e/screenshots',
videosFolder: '../../dist/cypress/apps/governance-e2e/videos',
screenshotsFolder: '../../dist/cypress/apps/governance-e2e/screenshots',
chromeWebSecurity: false,
viewportWidth: 1440,
viewportHeight: 900,
@@ -0,0 +1,83 @@
export const trancheData = {
'0': {
tranche_id: 0,
users: [],
initial_balance: 0,
current_balance: 0,
cliff_start: 0,
duration: 0,
},
'1': {
tranche_id: 1,
users: [],
initial_balance: 0,
current_balance: 0,
cliff_start: 1670422330,
duration: 1670453883,
},
'107': {
tranche_id: 107,
users: [],
initial_balance: 0,
current_balance: 0,
cliff_start: 0,
duration: 0,
},
'110': {
tranche_id: 110,
users: [],
initial_balance: 0,
current_balance: 0,
cliff_start: 0,
duration: 0,
},
'154': {
tranche_id: 154,
users: [],
initial_balance: 0,
current_balance: 0,
cliff_start: 0,
duration: 0,
},
'2': {
tranche_id: 2,
users: [
'0x8716c75bb3abe54b959adc529e6355f0422454ed',
'0xc704da0e96a6b910ffa8d3f9f667d3d35db8e5a1',
'0xbb82d4d6e4381ae98f8c33629285867b54d91a03',
'0x82ffe4ed818a6c7d4f0f044998611f24ec916c43',
'0xb0594132540ebc14f17863f8296f4546a7afe4e7',
'0x9015a3db9a922521007a9b495cafda14d8d4128e',
'0x5426f7f717fdbe331bb5a99b908ad2fb75dff711',
'0xf73e7ad8aa300a7f86bcc4d55e6c4ea25546e057',
],
initial_balance: 111300000000000000000,
current_balance: 111297025049610000000,
cliff_start: 1677578461,
duration: 15209600,
},
'3': {
tranche_id: 3,
users: [
'0xbb82d4d6e4381ae98f8c33629285867b54d91a03',
'0x82ffe4ed818a6c7d4f0f044998611f24ec916c43',
'0xb0594132540ebc14f17863f8296f4546a7afe4e7',
'0x9015a3db9a922521007a9b495cafda14d8d4128e',
'0x77a0b7e247b7b8ec99e068a24c401783d6c4dfff',
'0x5426f7f717fdbe331bb5a99b908ad2fb75dff711',
'0xc704da0e96a6b910ffa8d3f9f667d3d35db8e5a1',
],
initial_balance: 21000000000000000000,
current_balance: 21000000000000000000,
cliff_start: 1677578461,
duration: 18628800,
},
'66': {
tranche_id: 66,
users: [],
initial_balance: 0,
current_balance: 0,
cliff_start: 0,
duration: 0,
},
};
@@ -0,0 +1,97 @@
import { trancheData } from '../../fixtures/mocks/tranches';
const tranches = trancheData;
context(
'Tranches page - verify elements on the page',
{ tags: '@smoke' },
function () {
before('visit homepage', function () {
cy.intercept('GET', '**/tranches/stats', { tranches });
cy.visit('/');
});
it('Able to navigate to tranches page', function () {
cy.navigate_to('supply');
cy.url().should('include', '/token/tranches');
cy.get('h1').should('contain.text', 'Vesting tranches');
});
// 1005-VEST-001
// 1005-VEST-002
it('Able to view tranches', function () {
cy.getByTestId('tranche-item')
.should('have.length', 2)
.first()
.within(() => {
cy.get('a')
.should('have.text', 'Tranche 2') // 1005-VEST-003
.and('have.attr', 'href', '/token/tranches/2');
cy.get('span').eq(1).should('have.text', '111.30'); // 1005-VEST-005
cy.contains('Unlocking starts') // 1005-VEST-008
.parent()
.should('contain.text', '28 Feb 2023');
cy.contains('Fully unlocked')
.parent()
.should('contain.text', '23 Aug 2023');
cy.getByTestId('progress-bar').should('exist');
cy.getByTestId('currency-locked') // 1005-VEST-006
.invoke('text')
.should('not.be.empty');
cy.getByTestId('currency-unlocked') // 1005-VEST-007
.invoke('text')
.should('not.be.empty');
});
});
it('Able to see individual tranche data', function () {
cy.get('[href="/token/tranches/2"]').click();
cy.getByTestId('redeemed-tranche-tokens').within(() => {
cy.get('span').eq(1).should('have.text', 0);
});
cy.getByTestId('key-value-table').within(() => {
cy.getByTestId('link')
.should('have.length', 8)
.each((ethLink) => {
cy.wrap(ethLink)
.should('have.attr', 'href')
.and('contain', 'https://sepolia.etherscan.io/address/');
});
cy.getByTestId('redeem-link')
.should('have.length', 8)
.each((redeemLink) => {
cy.wrap(redeemLink)
.should('have.attr', 'href')
.and('contain', '/token/redeem/');
});
});
});
it('Able to view tranches with less than 10 vega', function () {
cy.navigate_to('supply');
cy.getByTestId('show-all-tranches').click();
cy.getByTestId('tranche-item')
.should('have.length', 8)
.first()
.within(() => {
cy.get('a')
.should('have.text', 'Tranche 0')
.and('have.attr', 'href', '/token/tranches/0');
cy.get('span').eq(1).should('have.text', '0.00');
cy.contains('Unlocking starts')
.parent()
.should('contain.text', '01 Jan 1970');
cy.contains('Fully unlocked')
.parent()
.should('contain.text', '01 Jan 1970');
cy.getByTestId('progress-bar').should('exist');
cy.getByTestId('currency-locked')
.invoke('text')
.should('not.be.empty');
cy.getByTestId('currency-unlocked')
.invoke('text')
.should('not.be.empty');
});
});
}
);
@@ -1,13 +1,15 @@
const connectButton = '[data-testid="connect-to-eth-btn"]';
const lockedTokensInVestingContract = '6,499,972.30';
context(
'Vesting Page - verify elements on page',
{ tags: '@smoke' },
function () {
before('navigate to vesting page', function () {
cy.visit('/').navigate_to('vesting');
});
describe('with wallets disconnected', function () {
before('navigate to vesting page', function () {
cy.visit('/').navigate_to('vesting');
});
it('should have vesting tab highlighted', function () {
cy.verify_tab_highlighted('token');
});
@@ -16,10 +18,7 @@ context(
cy.verify_page_header('Vesting');
});
it('should have connect Eth wallet info', function () {
cy.get(connectButton).should('be.visible');
});
// 1005-VEST-018
it('should have connect Eth wallet button', function () {
cy.get(connectButton)
.should('be.visible')
@@ -27,18 +26,101 @@ context(
});
});
describe('with eth wallet connected', function () {
describe('With Eth wallet connected', function () {
before('connect eth wallet', function () {
cy.ethereum_wallet_connect();
cy.visit('/');
cy.getByTestId('view-connected-eth-btn').click();
});
// 1005-VEST-001
// 1005-VEST-002
it('Able to view tranches', function () {
cy.navigate_to('supply');
cy.url().should('include', '/token/tranches');
cy.get('h1').should('contain.text', 'Vesting tranches');
// 1005-VEST-020 1005-VEST-021
it('Tokens in vesting contract for eth wallet is displayed on wallet window', function () {
cy.getByTestId('vega-in-vesting-contract').within(() => {
cy.getByTestId('currency-title')
.should('contain.text', 'VEGA')
.and('contain.text', 'In vesting contract');
cy.getByTestId('currency-value').should(
'have.text',
lockedTokensInVestingContract
);
cy.getByTestId('currency-locked').should(
'have.text',
lockedTokensInVestingContract
);
cy.getByTestId('currency-unlocked').should('have.text', '0.00');
});
});
// 1005-VEST-022 1005-VEST-023
it('Tokens amount displayed in vesting page', function () {
cy.getByTestId(
'redemption-description',
Cypress.env('txTimeout')
).should('exist');
const redemptionText =
'The connected Ethereum wallet (0xEe7D…d94F) has 6,499,972.30 $VEGA tokens in 1 tranche(s) of the vesting contract.';
cy.getByTestId('redemption-description').should(
'have.text',
redemptionText
);
cy.getByTestId('vesting-table').within(() => {
cy.getByTestId('key-value-table-row')
.eq(0)
.within(() => {
cy.get('dt').should('have.text', 'Vesting VEGA');
cy.get('dd').should('have.text', lockedTokensInVestingContract);
});
cy.getByTestId('key-value-table-row')
.eq(1)
.within(() => {
cy.get('dt').should('have.text', 'Locked');
cy.get('dd').should('have.text', lockedTokensInVestingContract);
});
cy.getByTestId('key-value-table-row')
.eq(2)
.within(() => {
cy.get('dt').should('have.text', 'Unlocked');
cy.get('dd').should('have.text', '0.00');
});
cy.getByTestId('key-value-table-row')
.eq(3)
.within(() => {
cy.get('dt').should('have.text', 'Associated');
cy.get('dd').should('have.text', '0.00');
});
});
});
// 1005-VEST-024 1005-VEST-025 1005-VEST-026 1005-VEST-036 1005-VEST-037
it('Tokens locked in individual tranches are displayed', function () {
cy.getByTestId('tranche-table-footer').should(
'have.text',
'All the tokens in this tranche are locked and must be assigned to a tranche before they can be redeemed.'
);
cy.getByTestId('tranche-item').within(() => {
cy.get('a')
.should('have.text', 'Tranche 0')
.and('have.attr', 'href', '/token/tranches/0');
cy.get('span')
.eq(1)
.should('have.text', lockedTokensInVestingContract);
cy.contains('Unlocking starts') // 1005-VEST-008
.parent()
.should('contain.text', '01 Jan 1970');
cy.contains('Fully unlocked')
.parent()
.should('contain.text', '01 Jan 1970');
cy.getByTestId('progress-bar').should('exist');
cy.getByTestId('currency-locked') // 1005-VEST-006
.should('have.text', lockedTokensInVestingContract);
cy.getByTestId('currency-unlocked') // 1005-VEST-007
.invoke('text')
.should('not.be.empty');
cy.getByTestId('tranche-item-footer').should(
'have.text',
'All the tokens in this tranche are locked and can not be redeemed yet.'
);
});
cy.connectVegaWallet();
});
});
}
@@ -11,7 +11,7 @@ export const EthConnectPrompt = () => {
const { appDispatch } = useAppState();
return (
<Button
variant="primary"
variant="default"
onClick={() =>
appDispatch({
type: AppStateActionType.SET_ETH_WALLET_OVERLAY,
@@ -336,6 +336,7 @@
"withdrawLpNoneDeposited": "You have no SLP tokens deposited or rewards accumulated",
"withdrawAllLpSuccessCalloutTitle": "Your SLP tokens and rewards have been sent to your Ethereum address",
"Dissociate VEGA tokens": "Disassociate $VEGA tokens",
"DisassociateVegaTokensFromWallet": "Disassociate $VEGA tokens from your Vega wallet",
"Early Investors": "Early Investors",
"Team": "Team",
"Community": "Community",
@@ -482,6 +483,7 @@
"withdrawFormSubmitButtonIdle": "Withdraw {{amount}} {{symbol}} tokens",
"withdrawFormSubmitButtonPending": "Preparing",
"withdrawalsTitle": "Withdrawals",
"withdrawalsSubtitle": "Connect your Vega wallet to complete a withdrawal. These withdrawals will be completed with an Ethereum transaction.",
"withdrawalsText": "These withdrawals need to be completed with an Ethereum transaction.",
"withdrawalsNone": "You don't have any pending withdrawals.",
"withdrawalsCompleteButton": "Finish withdrawal",
@@ -552,9 +554,6 @@
"resourceNotFound": "Resource Not Found",
"Or": "Or",
"addTokenToWallet": "Show this token in your Ethereum wallet",
"chartBelow": "*Certain activities, for example community incentive tokens, do not have specific dates to be credited and so an approximation has been used. ",
"chartTitle": "Token unlocking schedule",
"chartAbove": "This chart shows the approximate* schedule for how tokens will unlock from vesting tranches over time.",
"date": "Date",
"noEthereumProviderError": "No Ethereum browser extension detected, install MetaMask on desktop or visit from a dApp browser on mobile",
"unsupportedChainIdError": "You're connected to an unsupported network",
@@ -84,6 +84,7 @@ const RedemptionRouter = () => {
fill={true}
variant="primary"
onClick={() => navigate(`${RoutesConfig.REDEEM}/${account}`)}
data-testid="view-connected-eth-btn"
>
{t('View connected Eth Wallet')}
</Button>
@@ -15,7 +15,12 @@ export const DisassociateContainer = () => {
<>
<Heading title={t('pageTitleDisassociate')} />
{!account ? (
<EthConnectPrompt />
<>
<p className="mb-8">{t('DisassociateVegaTokensFromWallet')}</p>
<div className="max-w-[400px]">
<EthConnectPrompt />
</div>
</>
) : (
<DisassociatePage address={account} vegaKey={pubKey ?? ''} />
)}
@@ -73,6 +73,7 @@ export const Tranche = () => {
className="underline"
title={t('View vesting information')}
to={`${Routes.REDEEM}/${user}`}
data-testid="redeem-link"
>
{t('View vesting information')}
</RouterLink>
@@ -1,15 +1,12 @@
import { useWeb3React } from '@web3-react/core';
import React from 'react';
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { SubHeading } from '../../components/heading';
import { TrancheItem } from '../redemption/tranche-item';
import { TrancheLabel } from './tranche-label';
import { VestingChart } from './vesting-chart';
import { ButtonLink } from '@vegaprotocol/ui-toolkit';
import { useEthereumConfig } from '@vegaprotocol/web3';
import type { Tranche } from '../../lib/tranches/tranches-store';
import { TrancheItem } from '../redemption/tranche-item';
import { TrancheLabel } from './tranche-label';
import { useTranches } from '../../lib/tranches/tranches-store';
import type { Tranche } from '../../lib/tranches/tranches-store';
const trancheMinimum = 10;
@@ -18,7 +15,7 @@ const shouldShowTranche = (t: Tranche) =>
export const Tranches = () => {
const tranches = useTranches((state) => state.tranches);
const [showAll, setShowAll] = React.useState<boolean>(false);
const [showAll, setShowAll] = useState<boolean>(false);
const { t } = useTranslation();
const { chainId } = useWeb3React();
const { config } = useEthereumConfig();
@@ -30,10 +27,6 @@ export const Tranches = () => {
return (
<section>
<SubHeading title={t('chartTitle')} />
<p>{t('chartAbove')}</p>
<VestingChart />
<p>{t('chartBelow')}</p>
{tranches?.length ? (
<ul role="list">
{(showAll ? tranches : filteredTranches).map((tranche) => {
@@ -55,8 +48,12 @@ export const Tranches = () => {
) : (
<p>{t('No tranches')}</p>
)}
<section className="text-center mt-4">
<ButtonLink onClick={() => setShowAll(!showAll)}>
<ButtonLink
data-testid="show-all-tranches"
onClick={() => setShowAll(!showAll)}
>
{showAll
? t(
'Showing tranches with <{{trancheMinimum}} VEGA, click to hide these tranches',
@@ -1,149 +0,0 @@
import { format, startOfMonth } from 'date-fns';
import React from 'react';
import { useTranslation } from 'react-i18next';
import {
Area,
AreaChart,
Label,
Legend,
ReferenceLine,
ResponsiveContainer,
Tooltip,
XAxis,
YAxis,
} from 'recharts';
import colors from 'tailwindcss/colors';
import { DATE_FORMAT_LONG } from '../../lib/date-formats';
import data from './data.json';
import { theme } from '@vegaprotocol/tailwindcss-config';
const Colors = theme.colors;
const ORDER = ['community', 'publicSale', 'earlyInvestors', 'team'];
export const VestingChart = () => {
const { t } = useTranslation();
const currentDate = React.useMemo(
() => format(startOfMonth(new Date()), DATE_FORMAT_LONG),
[]
);
return (
<div style={{ marginBottom: 25 }}>
<ResponsiveContainer height={400} width="100%">
<AreaChart data={data}>
<defs>
{[
['pink', Colors.vega.pink.DEFAULT],
['green', Colors.vega.green.DEFAULT],
['orange', Colors.warning],
['yellow', Colors.vega.yellow.DEFAULT],
].map(([key, color]) => (
<linearGradient key={key} id={key} x1="0" y1="0" x2="0" y2="1">
<stop offset="0%" stopColor={color} stopOpacity={0.85} />
<stop offset="100%" stopColor={color} stopOpacity={0} />
</linearGradient>
))}
</defs>
<Tooltip
contentStyle={{ backgroundColor: colors.black }}
separator=":"
// @ts-ignore formatter doesnt seem to allow returning JSX but nonetheless it works
formatter={(value: number) => {
return (
<div
style={{
display: 'flex',
textAlign: 'right',
}}
>
{Intl.NumberFormat().format(value)}
</div>
);
}}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
itemSorter={(label: any) => {
return ORDER.indexOf(label.dataKey) + 1;
}}
/>
<YAxis type="number" width={100}>
<Label
angle={270}
value={t('VEGA').toString()}
position="left"
offset={-5}
fill={colors.white}
/>
</YAxis>
<XAxis dataKey="date">
<Label
value={t('date').toString()}
position="bottom"
offset={5}
fill={colors.white}
/>
</XAxis>
<ReferenceLine
x={currentDate}
stroke={colors.white}
strokeWidth={2}
label={{
position: 'left',
value: currentDate,
fill: colors.white,
}}
/>
<Area
dot={false}
type="linear"
dataKey="team"
stroke={Colors.vega.pink.DEFAULT}
fill="url(#pink)"
yAxisId={0}
strokeWidth={2}
fillOpacity={0.85}
stackId="1"
name={t('Team')}
/>
<Area
dot={false}
type="monotone"
dataKey="earlyInvestors"
stroke={Colors.vega.green.DEFAULT}
fill="url(#green)"
yAxisId={0}
strokeWidth={2}
fillOpacity={0.85}
stackId="1"
name={t('Early Investors')}
/>
<Area
dot={false}
type="monotone"
dataKey="publicSale"
stroke={Colors.vega.yellow.DEFAULT}
fill="url(#yellow)"
yAxisId={0}
strokeWidth={2}
stackId="1"
fillOpacity={0.85}
name={t('Public Sale')}
/>
<Area
dot={false}
type="monotone"
dataKey="community"
stroke={Colors.warning}
fill="url(#orange)"
yAxisId={0}
strokeWidth={2}
fillOpacity={0.85}
stackId="1"
name={t('Community')}
/>
<Legend wrapperStyle={{ position: 'relative' }} />
</AreaChart>
</ResponsiveContainer>
</div>
);
};
@@ -17,12 +17,14 @@ import type { RouteChildProps } from '../index';
const Withdrawals = ({ name }: RouteChildProps) => {
useDocumentTitle(name);
const { t } = useTranslation();
const { pubKey } = useVegaWallet();
return (
<>
<Heading title={t('withdrawalsTitle')} />
{!pubKey && <p className="mb-8">{t('withdrawalsSubtitle')}</p>}
<VegaWalletContainer>
{(currVegaKey) => <WithdrawPendingContainer />}
{() => <WithdrawPendingContainer />}
</VegaWalletContainer>
</>
);
@@ -0,0 +1,5 @@
# App configuration variables
NX_VEGA_CONFIG_URL=https://static.vega.xyz/assets/validator-testnet-network.json
NX_VEGA_URL=https://api.validators-testnet.vega.xyz/graphql
NX_VEGA_NETWORKS='{"TESTNET":"https://multisig-signer.fairground.wtf","MAINNET":"https://multisig-signer.vega.xyz"}'
NX_VEGA_ENV=VALIDATOR_TESTNET
File diff suppressed because it is too large Load Diff
@@ -41,6 +41,7 @@ const completeWithdrawalBtn = 'complete-withdrawal';
const submitTransferBtn = '[type="submit"]';
const transferForm = 'transfer-form';
const depositSubmit = 'deposit-submit';
const approveSubmit = 'approve-submit';
// Because the tests are run on a live network to optimize time, the tests are interdependent and must be run in the given order.
describe('capsule - without MultiSign', { tags: '@slow' }, () => {
@@ -73,13 +74,13 @@ describe('capsule - without MultiSign', { tags: '@slow' }, () => {
cy.getByTestId('deposit-button').click();
connectEthereumWallet('Unknown');
cy.get(assetSelectField, txTimeout).select(btcName, { force: true });
cy.getByTestId('approve-warning').should(
cy.getByTestId('approve-default').should(
'contain.text',
`Deposits of ${btcSymbol} not approved`
`Before you can make a deposit of your chosen asset, ${btcSymbol}, you need to approve its use in your Ethereum wallet`
);
cy.getByTestId(depositSubmit).click();
cy.getByTestId('dialog-title').should('contain.text', 'Approve complete');
cy.get('[data-testid="Return to deposit"]').click();
cy.getByTestId(approveSubmit).click();
cy.getByTestId('approve-pending').should('exist');
cy.getByTestId('approve-confirmed').should('exist');
cy.get(amountField).clear().type('10');
cy.getByTestId(depositSubmit).click();
cy.getByTestId(toastContent, txTimeout).should(
+14 -7
View File
@@ -31,7 +31,13 @@ describe('deposit form validation', { tags: '@smoke' }, () => {
it('handles empty fields', () => {
cy.getByTestId('deposit-submit').click();
cy.getByTestId(formFieldError).should('contain.text', 'Required');
cy.getByTestId(formFieldError).should('have.length', 2);
// once Ethereum wallet is connected and key selected the only field that will
// error is the asset select
cy.getByTestId(formFieldError).should('have.length', 1);
cy.get('[data-testid="input-error-text"][aria-describedby="asset"]').should(
'have.length',
1
);
});
it('unable to select assets not enabled', () => {
@@ -41,12 +47,13 @@ describe('deposit form validation', { tags: '@smoke' }, () => {
cy.get(assetSelectField + ' option:contains(Asset 4)').should('not.exist');
});
it('invalid public key', () => {
cy.get(toAddressField)
.clear()
.type('INVALID_DEPOSIT_TO_ADDRESS')
.next(`[data-testid="${formFieldError}"]`)
.should('have.text', 'Invalid Vega key');
it('invalid public key when entering address manually', () => {
cy.getByTestId('enter-pubkey-manually').click();
cy.get(toAddressField).clear().type('INVALID_DEPOSIT_TO_ADDRESS');
cy.get(`[data-testid="${formFieldError}"][aria-describedby="to"]`).should(
'have.text',
'Invalid Vega key'
);
});
it('invalid amount', () => {
@@ -669,7 +669,7 @@ describe('account validation', { tags: '@regression' }, () => {
'have.text',
'You need ' +
'tDAI' +
' in your wallet to trade in this market. See all your collateral.Make a deposit'
' in your wallet to trade in this market.See all your collateral.Make a deposit'
);
cy.getByTestId('deal-ticket-deposit-dialog-button').should('exist');
});
@@ -20,46 +20,78 @@ describe('positions', { tags: '@smoke' }, () => {
cy.getByTestId('Positions').click();
validatePositionsDisplayed();
});
it('renders position among some graphql errors', () => {
const errors = [
{
message: 'no market data for market: market-2',
path: ['market', 'data'],
extensions: {
code: 13,
type: 'Internal',
describe('renders position among some graphql errors', () => {
it('rows should be displayed despite errors', () => {
const errors = [
{
message:
'no market data for market: 9c55fb644c6f7de5422d40d691a62bffd5898384c70135bab29ba1e3e2e5280a',
path: ['marketsConnection', 'edges'],
extensions: {
code: 13,
type: 'Internal',
},
},
},
];
const marketData = marketsDataQuery();
const edges = marketData.marketsConnection?.edges.map((market) => {
const replace =
market.node.data?.market.id === 'market-2' ? null : market.node.data;
return { ...market, node: { ...market.node, data: replace } };
});
const overrides = {
...marketData,
marketsConnection: { ...marketData.marketsConnection, edges },
};
cy.mockGQL((req) => {
aliasGQLQuery(req, 'MarketsData', overrides, errors);
});
cy.visit('/#/markets/market-0');
const emptyCells = [
'notional',
'markPrice',
'liquidationPrice',
'currentLeverage',
'averageEntryPrice',
];
cy.getByTestId('tab-positions').within(() => {
cy.get('[row-id="market-2"]').within(() => {
emptyCells.forEach((cell) => {
cy.get(`[col-id="${cell}"]`).should('contain.text', '-');
];
const marketData = marketsDataQuery();
const edges = marketData.marketsConnection?.edges.map((market) => {
const replace =
market.node.data?.market.id === 'market-2' ? null : market.node.data;
return { ...market, node: { ...market.node, data: replace } };
});
const overrides = {
...marketData,
marketsConnection: { ...marketData.marketsConnection, edges },
};
cy.mockGQL((req) => {
aliasGQLQuery(req, 'MarketsData', overrides, errors);
});
cy.visit('/#/markets/market-0');
const emptyCells = [
'notional',
'markPrice',
'liquidationPrice',
'currentLeverage',
'averageEntryPrice',
];
cy.getByTestId('tab-positions').within(() => {
cy.get('[row-id="market-2"]').within(() => {
emptyCells.forEach((cell) => {
cy.get(`[col-id="${cell}"]`).should('contain.text', '-');
});
});
});
});
it('error message should be displayed', () => {
const errors = [
{
message:
'no market data for asset: 9c55fb644c6f7de5422d40d691a62bffd5898384c70135bab29ba1e3e2e5280a',
path: ['assets', 'edges'],
extensions: {
code: 13,
type: 'Internal',
},
},
];
const marketData = marketsDataQuery();
const edges = marketData.marketsConnection?.edges.map((market) => {
const replace =
market.node.data?.market.id === 'market-2' ? null : market.node.data;
return { ...market, node: { ...market.node, data: replace } };
});
const overrides = {
...marketData,
marketsConnection: { ...marketData.marketsConnection, edges },
};
cy.mockGQL((req) => {
aliasGQLQuery(req, 'MarketsData', overrides, errors);
});
cy.visit('/#/markets/market-0');
cy.get('.pointer-events-none.absolute.inset-0').contains(
'Something went wrong:'
);
});
});
describe('sorting by ag-grid columns should work well', () => {
@@ -151,7 +151,7 @@ describe('ethereum wallet', { tags: '@smoke' }, () => {
cy.getByTestId('Deposits').click();
cy.getByTestId('deposit-button').click();
connectEthereumWallet('MetaMask');
cy.get('#ethereum-address').should('have.value', ethWalletAddress);
cy.getByTestId('ethereum-address').should('have.text', ethWalletAddress);
cy.getByTestId('disconnect-ethereum-wallet')
.should('have.text', 'Disconnect')
.click();
+3 -4
View File
@@ -1,12 +1,11 @@
NX_ETHEREUM_PROVIDER_URL=https://sepolia.infura.io/v3/4f846e79e13f44d1b51bbd7ed9edefb8
NX_ETHERSCAN_URL=https://sepolia.etherscan.io
NX_HOSTED_WALLET_URL=https://wallet.testnet.vega.xyz
NX_VEGA_CONFIG_URL=https://static.vega.xyz/assets/validator-testnet-network.json
NX_VEGA_ENV=VALIDATOR_TESTNET
NX_VEGA_EXPLORER_URL=https://dev.explorer.vega.xyz
NX_VEGA_NETWORKS='{"DEVNET":"https://dev.token.vega.xyz","STAGNET3":"https://stagnet3.token.vega.xyz","TESTNET":"https://token.fairground.wtf","MAINNET":"https://token.vega.xyz"}'
NX_VEGA_TOKEN_URL=https://token.fairground.wtf
NX_VEGA_EXPLORER_URL=https://validator-testnet.explorer.vega.xyz
NX_VEGA_NETWORKS={\"STAGNET3\":\"https://stagnet3.console.vega.xyz\",\"STAGNET1\":\"https://stagnet1.console.vega.xyz\",\"TESTNET\":\"https://console.fairground.wtf\"}
NX_VEGA_TOKEN_URL=https://validator-testnet.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
@@ -111,11 +111,11 @@ export const TradeMarketHeader = ({
</div>
</HeaderStat>
) : null}
<MarketProposalNotification marketId={market?.id} />
<MarketLiquiditySupplied
marketId={market?.id}
assetDecimals={asset?.decimals || 0}
/>
<MarketProposalNotification marketId={market?.id} />
</Header>
);
};
@@ -2,10 +2,16 @@ import { AsyncRenderer, Button } from '@vegaprotocol/ui-toolkit';
import { useDepositDialog, DepositsTable } from '@vegaprotocol/deposits';
import { depositsProvider } from '@vegaprotocol/deposits';
import { t } from '@vegaprotocol/i18n';
import { useDataProvider } from '@vegaprotocol/react-helpers';
import {
useDataProvider,
useBottomPlaceholder,
} from '@vegaprotocol/react-helpers';
import { useVegaWallet } from '@vegaprotocol/wallet';
import { useRef } from 'react';
import type { AgGridReact } from 'ag-grid-react';
export const DepositsContainer = () => {
const gridRef = useRef<AgGridReact | null>(null);
const { pubKey, isReadOnly } = useVegaWallet();
const { data, loading, error, reload } = useDataProvider({
dataProvider: depositsProvider,
@@ -13,13 +19,15 @@ export const DepositsContainer = () => {
skip: !pubKey,
});
const openDepositDialog = useDepositDialog((state) => state.open);
const bottomPlaceholderProps = useBottomPlaceholder({ gridRef });
return (
<div className="h-full grid grid-rows-[1fr,min-content]">
<div className="h-full">
<div className="h-full relative">
<DepositsTable
rowData={data || []}
noRowsOverlayComponent={() => null}
ref={gridRef}
{...bottomPlaceholderProps}
/>
<div className="pointer-events-none absolute inset-0">
<AsyncRenderer
@@ -33,8 +41,9 @@ export const DepositsContainer = () => {
</div>
</div>
{!isReadOnly && (
<div className="w-full dark:bg-black bg-white absolute bottom-0 h-auto flex justify-end px-[11px] py-2">
<div className="h-auto flex justify-end px-[11px] py-2 bottom-0 right-3 absolute dark:bg-black/75 bg-white/75 rounded">
<Button
variant="primary"
size="sm"
onClick={() => openDepositDialog()}
data-testid="deposit-button"
@@ -20,36 +20,35 @@ export const WithdrawalsContainer = () => {
return (
<VegaWalletContainer>
<div className="h-full relative grid grid-rows-[1fr,min-content]">
<div className="h-full relative">
<WithdrawalsTable
data-testid="withdrawals-history"
rowData={data}
noRowsOverlayComponent={() => null}
<div className="h-full relative">
<WithdrawalsTable
data-testid="withdrawals-history"
rowData={data}
noRowsOverlayComponent={() => null}
/>
<div className="pointer-events-none absolute inset-0">
<AsyncRenderer
data={data}
loading={loading}
error={error}
noDataCondition={(data) => !(data && data.length)}
noDataMessage={t('No withdrawals')}
reload={reload}
/>
<div className="pointer-events-none absolute inset-0">
<AsyncRenderer
data={data}
loading={loading}
error={error}
noDataCondition={(data) => !(data && data.length)}
noDataMessage={t('No withdrawals')}
reload={reload}
/>
</div>
</div>
{!isReadOnly && (
<div className="w-full dark:bg-black bg-white absolute bottom-0 h-auto flex justify-end px-[11px] py-2">
<Button
size="sm"
onClick={() => openWithdrawDialog()}
data-testid="withdraw-dialog-button"
>
{t('Make withdrawal')}
</Button>
</div>
)}
</div>
{!isReadOnly && (
<div className="h-auto flex justify-end px-[11px] py-2 bottom-0 right-3 absolute dark:bg-black/75 bg-white/75 rounded">
<Button
variant="primary"
size="sm"
onClick={() => openWithdrawDialog()}
data-testid="withdraw-dialog-button"
>
{t('Make withdrawal')}
</Button>
</div>
)}
</VegaWalletContainer>
);
};
@@ -8,12 +8,15 @@ import { useVegaWallet } from '@vegaprotocol/wallet';
import type { PinnedAsset } from '@vegaprotocol/accounts';
import { AccountManager, useTransferDialog } from '@vegaprotocol/accounts';
import { useDepositDialog } from '@vegaprotocol/deposits';
import { useParams } from 'react-router-dom';
export const AccountsContainer = ({
pinnedAsset,
}: {
pinnedAsset?: PinnedAsset;
}) => {
const params = useParams();
const hideButtons = 'marketId' in params;
const { pubKey, isReadOnly } = useVegaWallet();
const { open: openAssetDetailsDialog } = useAssetDetailsDialogStore();
const openWithdrawalDialog = useWithdrawalDialog((store) => store.open);
@@ -36,27 +39,30 @@ export const AccountsContainer = ({
}
return (
<div className="h-full relative grid grid-rows-[1fr,min-content]">
<div>
<AccountManager
partyId={pubKey}
onClickAsset={onClickAsset}
onClickWithdraw={openWithdrawalDialog}
onClickDeposit={openDepositDialog}
isReadOnly={isReadOnly}
pinnedAsset={pinnedAsset}
/>
</div>
{!isReadOnly && (
<div className="flex gap-2 justify-end p-2 px-[11px]">
<div className="h-full relative">
<AccountManager
partyId={pubKey}
onClickAsset={onClickAsset}
onClickWithdraw={openWithdrawalDialog}
onClickDeposit={openDepositDialog}
isReadOnly={isReadOnly}
pinnedAsset={pinnedAsset}
/>
{!isReadOnly && !hideButtons && (
<div className="flex gap-2 justify-end p-2 px-[11px] fixed bottom-0 right-2 dark:bg-black/75 bg-white/75 rounded">
<Button
variant="primary"
size="sm"
data-testid="open-transfer-dialog"
onClick={() => openTransferDialog()}
>
{t('Transfer')}
</Button>
<Button size="sm" onClick={() => openDepositDialog()}>
<Button
variant="primary"
size="sm"
onClick={() => openDepositDialog()}
>
{t('Deposit')}
</Button>
</div>
@@ -24,6 +24,7 @@ export const Banner = () => {
<AnnouncementBanner>
<div className="grid grid-cols-[auto_1fr] gap-4 font-alpha calt uppercase text-center text-lg text-white">
<button
className="flex items-center"
onClick={() => update({ shouldDisplayAnnouncementBanner: false })}
>
<Icon name="cross" className="w-6 h-6" ariaLabel="dismiss" />
+1 -1
View File
@@ -14,7 +14,7 @@ export const Footer = () => {
const { blockDiff, datanodeBlockHeight } = useNodeHealth();
return (
<footer className="px-4 py-1 text-xs border-t border-default text-vega-light-300 dark:text-vega-dark-300">
<footer className="px-4 py-1 text-xs border-t border-default text-vega-light-300 dark:text-vega-dark-300 fixed bottom-0 left-0 border-r bg-white dark:bg-black">
{/* Pull left to align with top nav, due to button padding */}
<div className="-ml-2">
{VEGA_URL && (
@@ -177,22 +177,14 @@ export const useEthereumTransactionToasts = () => {
store.remove,
]);
const [dismissTx, deleteTx] = useEthTransactionStore((state) => [
state.dismiss,
state.delete,
]);
const dismissTx = useEthTransactionStore((state) => state.dismiss);
const onClose = useCallback(
(tx: EthStoredTxState) => () => {
const safeToDelete = isFinal(tx);
if (safeToDelete) {
deleteTx(tx.id);
} else {
dismissTx(tx.id);
}
dismissTx(tx.id);
removeToast(`eth-${tx.id}`);
},
[deleteTx, dismissTx, removeToast]
[dismissTx, removeToast]
);
const fromEthTransaction = useCallback(
+1 -1
View File
@@ -72,7 +72,7 @@ function AppBody({ Component }: AppProps) {
const gridClasses = classNames(
'h-full relative z-0 grid',
'grid-rows-[repeat(3,min-content),1fr,min-content]'
'grid-rows-[repeat(3,min-content),1fr]'
);
return (
-58
View File
@@ -1,58 +0,0 @@
.pre-loader {
display: flex;
width: 100%;
min-height: 100vh;
justify-content: center;
align-items: center;
.loader-item {
width: 10px;
height: 10px;
background: black;
}
.pre-loader-center {
align-items: center;
display: flex;
flex-direction: column;
}
.pre-loader-wrapper {
width: 50px;
height: 50px;
display: flex;
flex-wrap: wrap;
}
@for $i from 0 through 16 {
.loader-item:nth-child(#{$i}) {
@if $i % 2 == 0 {
animation-delay: #{$i * 50 * random(5)}ms;
animation-direction: reverse;
} @else {
animation-delay: #{$i * -50 * random(5)}ms;
animation-direction: alternate;
}
}
}
.loader-item {
animation: flickering 0.4s linear alternate infinite;
}
@keyframes flickering {
0% {
opacity: 1;
}
25% {
opacity: 1;
}
26% {
opacity: 0;
}
100% {
opacity: 0;
}
}
}
html.dark {
.pre-loader {
.loader-item {
background: white;
}
}
}
+24 -3
View File
@@ -1,12 +1,16 @@
import { useRef, useMemo, memo, useCallback } from 'react';
import { t } from '@vegaprotocol/i18n';
import { useDataProvider } from '@vegaprotocol/react-helpers';
import {
useDataProvider,
useBottomPlaceholder,
} from '@vegaprotocol/react-helpers';
import { AsyncRenderer } from '@vegaprotocol/ui-toolkit';
import type { AgGridReact } from 'ag-grid-react';
import { useRef, useMemo, memo } from 'react';
import type { AccountFields } from './accounts-data-provider';
import { aggregatedAccountsDataProvider } from './accounts-data-provider';
import type { PinnedAsset } from './accounts-table';
import { AccountTable } from './accounts-table';
import type { RowHeightParams } from 'ag-grid-community';
interface AccountManagerProps {
partyId: string;
@@ -27,7 +31,6 @@ export const AccountManager = ({
}: AccountManagerProps) => {
const gridRef = useRef<AgGridReact | null>(null);
const variables = useMemo(() => ({ partyId }), [partyId]);
const { data, loading, error, reload } = useDataProvider<
AccountFields[],
never
@@ -35,6 +38,22 @@ export const AccountManager = ({
dataProvider: aggregatedAccountsDataProvider,
variables,
});
const setId = useCallback(
(data: AccountFields) => ({
...data,
asset: { ...data.asset, id: `${data.asset.id}-1` },
}),
[]
);
const bottomPlaceholderProps = useBottomPlaceholder<AccountFields>({
gridRef,
setId,
});
const getRowHeight = useCallback(
(params: RowHeightParams) => (params.node.rowPinned ? 32 : 22),
[]
);
return (
<div className="relative h-full">
<AccountTable
@@ -46,6 +65,8 @@ export const AccountManager = ({
isReadOnly={isReadOnly}
noRowsOverlayComponent={() => null}
pinnedAsset={pinnedAsset}
getRowHeight={getRowHeight}
{...bottomPlaceholderProps}
/>
<div className="pointer-events-none absolute inset-0">
<AsyncRenderer
+136 -87
View File
@@ -5,9 +5,12 @@ import type {
VegaICellRendererParams,
VegaValueFormatterParams,
} from '@vegaprotocol/datagrid';
import { ButtonLink, Dialog } from '@vegaprotocol/ui-toolkit';
import { Button, ButtonLink, Dialog } from '@vegaprotocol/ui-toolkit';
import { TooltipCellComponent } from '@vegaprotocol/ui-toolkit';
import { AgGridDynamic as AgGrid } from '@vegaprotocol/datagrid';
import {
AgGridDynamic as AgGrid,
CenteredGridCellWrapper,
} from '@vegaprotocol/datagrid';
import { AgGridColumn } from 'ag-grid-react';
import type { IDatasource, IGetRowsParams } from 'ag-grid-community';
import type { AgGridReact, AgGridReactProps } from 'ag-grid-react';
@@ -86,59 +89,85 @@ export const AccountTable = forwardRef<AgGridReact, AccountTableProps>(
cellRenderer={({
value,
data,
node,
}: VegaICellRendererParams<AccountFields, 'asset.symbol'>) => {
return value ? (
<ButtonLink
data-testid="asset"
onClick={() => {
if (data) {
onClickAsset(data.asset.id);
}
}}
<CenteredGridCellWrapper
className={node.rowPinned ? 'h-[30px]' : undefined}
>
{value}
</ButtonLink>
<ButtonLink
data-testid="asset"
onClick={() => {
if (data) {
onClickAsset(data.asset.id);
}
}}
>
{value}
</ButtonLink>
</CenteredGridCellWrapper>
) : null;
}}
maxWidth={300}
/>
<AgGridColumn
headerName={t('Total')}
type="rightAligned"
field="deposited"
headerTooltip={t(
'This is the total amount of collateral used plus the amount available in your general account.'
)}
valueFormatter={({
value,
data,
}: VegaValueFormatterParams<AccountFields, 'deposited'>) =>
data &&
data.asset &&
isNumeric(value) &&
addDecimalsFormatNumber(value, data.asset.decimals)
}
maxWidth={300}
cellRenderer={({
data,
value,
node,
}: VegaICellRendererParams<AccountFields, 'deposited'>) => {
const valueFormatted =
data &&
data.asset &&
isNumeric(value) &&
addDecimalsFormatNumber(value, data.asset.decimals);
return node.rowPinned ? (
<CenteredGridCellWrapper className="h-[30px] justify-end">
{valueFormatted}
</CenteredGridCellWrapper>
) : (
valueFormatted
);
}}
/>
<AgGridColumn
headerName={t('Used')}
type="rightAligned"
field="used"
headerTooltip={t(
'This is the amount of collateral used from your general account.'
)}
valueFormatter={({
value,
data,
}: VegaValueFormatterParams<AccountFields, 'used'>) =>
data &&
data.asset &&
isNumeric(value) &&
addDecimalsFormatNumber(value, data.asset.decimals)
}
maxWidth={300}
cellRenderer={({
data,
value,
node,
}: VegaICellRendererParams<AccountFields, 'used'>) => {
const valueFormatted =
data &&
data.asset &&
isNumeric(value) &&
addDecimalsFormatNumber(value, data.asset.decimals);
return node.rowPinned ? (
<CenteredGridCellWrapper className="h-[30px] justify-end">
{valueFormatted}
</CenteredGridCellWrapper>
) : (
valueFormatted
);
}}
/>
<AgGridColumn
headerName={t('Available')}
field="available"
type="rightAligned"
headerTooltip={t(
'This is the amount of collateral available in your general account.'
)}
@@ -152,73 +181,93 @@ export const AccountTable = forwardRef<AgGridReact, AccountTableProps>(
addDecimalsFormatNumber(value, data.asset.decimals)
}
maxWidth={300}
cellRenderer={({
data,
value,
node,
}: VegaICellRendererParams<AccountFields, 'available'>) => {
const valueFormatted =
data &&
data.asset &&
isNumeric(value) &&
addDecimalsFormatNumber(value, data.asset.decimals);
return node.rowPinned ? (
<CenteredGridCellWrapper className="h-[30px] justify-end">
{valueFormatted}
</CenteredGridCellWrapper>
) : (
valueFormatted
);
}}
/>
{
<AgGridColumn
colId="breakdown"
headerName=""
sortable={false}
minWidth={200}
type="rightAligned"
cellRenderer={({
data,
}: VegaICellRendererParams<AccountFields>) => {
if (!data) return null;
else {
if (
data.asset.id === pinnedAssetId &&
new BigNumber(data.deposited).isLessThanOrEqualTo(0)
) {
return (
<ButtonLink
<AgGridColumn
colId="breakdown"
headerName=""
sortable={false}
minWidth={200}
type="rightAligned"
cellRenderer={({
data,
}: VegaICellRendererParams<AccountFields>) => {
if (!data) return null;
else {
if (
data.asset.id === pinnedAssetId &&
new BigNumber(data.deposited).isLessThanOrEqualTo(0)
) {
return (
<CenteredGridCellWrapper className="h-[30px] justify-end py-1">
<Button
size="xs"
variant="primary"
data-testid="deposit"
onClick={() => {
onClickDeposit && onClickDeposit(data.asset.id);
}}
>
{t('Deposit to trade')}
</ButtonLink>
);
}
return (
<>
<ButtonLink
data-testid="breakdown"
onClick={() => {
setOpenBreakdown(!openBreakdown);
setBreakdown(data.breakdown || null);
}}
>
{t('Breakdown')}
</ButtonLink>
<span className="mx-1" />
{!props.isReadOnly && (
<ButtonLink
data-testid="deposit"
onClick={() => {
onClickDeposit && onClickDeposit(data.asset.id);
}}
>
{t('Deposit')}
</ButtonLink>
)}
<span className="mx-1" />
{!props.isReadOnly && (
<ButtonLink
data-testid="withdraw"
onClick={() =>
onClickWithdraw && onClickWithdraw(data.asset.id)
}
>
{t('Withdraw')}
</ButtonLink>
)}
</>
</Button>
</CenteredGridCellWrapper>
);
}
}}
/>
}
return (
<>
<ButtonLink
data-testid="breakdown"
onClick={() => {
setOpenBreakdown(!openBreakdown);
setBreakdown(data.breakdown || null);
}}
>
{t('Breakdown')}
</ButtonLink>
<span className="mx-1" />
{!props.isReadOnly && (
<ButtonLink
data-testid="deposit"
onClick={() => {
onClickDeposit && onClickDeposit(data.asset.id);
}}
>
{t('Deposit')}
</ButtonLink>
)}
<span className="mx-1" />
{!props.isReadOnly && (
<ButtonLink
data-testid="withdraw"
onClick={() =>
onClickWithdraw && onClickWithdraw(data.asset.id)
}
>
{t('Withdraw')}
</ButtonLink>
)}
</>
);
}
}}
/>
</AgGrid>
<Dialog size="medium" open={openBreakdown} onChange={setOpenBreakdown}>
<div className="h-[35vh] w-full m-auto flex flex-col">
+1
View File
@@ -8,6 +8,7 @@ export * from './lib/cells/price-cell';
export * from './lib/cells/price-change-cell';
export * from './lib/cells/price-flash-cell';
export * from './lib/cells/vol-cell';
export * from './lib/cells/centered-grid-cell';
export * from './lib/filters/date-range-filter';
export * from './lib/filters/set-filter';
@@ -22,13 +22,15 @@ const agGridDarkVariables = `
border-width: 1px 0;
border-bottom: 1px solid transparent;
}
.ag-theme-balham-dark .ag-row.no-hover, .ag-theme-balham-dark .ag-row.no-hover:hover {
background: black;
}
.ag-theme-balham-dark .ag-react-container {
overflow: hidden;
text-overflow: ellipsis;
}
.ag-theme-balham-dark .ag-cell, .ag-theme-balham-dark .ag-full-width-row .ag-cell-wrapper.ag-row-group {
.ag-theme-balham-dark .ag-cell, .ag-theme-balham-dark .ag-full-width-row .ag-cell-wrapper.ag-row-group {
line-height: calc(min(var(--ag-line-height, 26px), 26px) - 4px);
}
`;
@@ -22,13 +22,15 @@ const agGridLightVariables = `
border-width: 1px 0;
border-bottom: 1px solid transparent;
}
.ag-theme-balham .ag-row.no-hover, .ag-theme-balham .ag-row.no-hover:hover {
background: white;
}
.ag-theme-balham .ag-react-container {
overflow: hidden;
text-overflow: ellipsis;
}
.ag-theme-balham .ag-cell, .ag-theme-balham .ag-full-width-row .ag-cell-wrapper.ag-row-group {
.ag-theme-balham .ag-cell, .ag-theme-balham .ag-full-width-row .ag-cell-wrapper.ag-row-group {
line-height: calc(min(var(--ag-line-height, 26px), 26px) - 4px);
}
`;
@@ -0,0 +1,16 @@
import type { ReactNode } from 'react';
import classNames from 'classnames';
export const CenteredGridCellWrapper = ({
children,
className,
}: {
children: ReactNode;
className?: string;
}) => (
<div
className={classNames('flex h-[20px] p-0 justify-items-center', className)}
>
<div className="self-center">{children}</div>
</div>
);
+1 -2
View File
@@ -61,10 +61,9 @@ export const SetFilter = forwardRef((props: IFilterParams, ref) => {
<div className="ag-filter-body-wrapper">
<fieldset className="ag-simple-filter-body-wrapper">
{Object.keys(props.colDef.filterParams.set).map((key) => (
<label className="flex">
<label className="flex" key={key}>
<input
type="checkbox"
key={key}
value={key}
className="mr-1"
checked={value.includes(key)}
+21
View File
@@ -0,0 +1,21 @@
import type { StateCreator } from 'zustand';
import { act } from 'react-dom/test-utils';
const { create: actualCreate } = jest.requireActual('zustand'); // if using jest
// a variable to hold reset functions for all stores declared in the app
const storeResetFns = new Set<() => void>();
// when creating a store, we get its initial state, create a reset function and add it in the set
export const create =
() =>
<S>(createState: StateCreator<S>) => {
const store = actualCreate(createState);
const initialState = store.getState();
storeResetFns.add(() => store.setState(initialState, true));
return store;
};
// Reset all stores after each test run
beforeEach(() => {
act(() => storeResetFns.forEach((resetFn) => resetFn()));
});
@@ -1,7 +1,7 @@
import { formatNumber } from '@vegaprotocol/utils';
import { t } from '@vegaprotocol/i18n';
import { Notification, Intent } from '@vegaprotocol/ui-toolkit';
import { DepositDialog, useDepositDialog } from '@vegaprotocol/deposits';
import { useDepositDialog } from '@vegaprotocol/deposits';
interface Props {
margin: string;
@@ -16,25 +16,22 @@ interface Props {
export const MarginWarning = ({ margin, balance, asset }: Props) => {
const openDepositDialog = useDepositDialog((state) => state.open);
return (
<>
<Notification
intent={Intent.Warning}
testId="dealticket-warning-margin"
message={`You may not have enough margin available to open this position. ${formatNumber(
margin,
asset.decimals
)} ${asset.symbol} ${t(
'is currently required. You have only'
)} ${formatNumber(balance, asset.decimals)} ${asset.symbol} ${t(
'available.'
)}`}
buttonProps={{
text: t(`Deposit ${asset.symbol}`),
action: () => openDepositDialog(asset.id),
dataTestId: 'deal-ticket-deposit-dialog-button',
}}
/>
<DepositDialog />
</>
<Notification
intent={Intent.Warning}
testId="dealticket-warning-margin"
message={`You may not have enough margin available to open this position. ${formatNumber(
margin,
asset.decimals
)} ${asset.symbol} ${t(
'is currently required. You have only'
)} ${formatNumber(balance, asset.decimals)} ${asset.symbol} ${t(
'available.'
)}`}
buttonProps={{
text: t(`Deposit ${asset.symbol}`),
action: () => openDepositDialog(asset.id),
dataTestId: 'deal-ticket-deposit-dialog-button',
}}
/>
);
};
@@ -7,7 +7,7 @@ interface ZeroBalanceErrorProps {
id: string;
symbol: string;
};
onClickCollateral: () => void;
onClickCollateral?: () => void;
}
export const ZeroBalanceError = ({
@@ -21,8 +21,12 @@ export const ZeroBalanceError = ({
testId="dealticket-error-message-zero-balance"
message={
<>
You need {asset.symbol} in your wallet to trade in this market. See
all your <Link onClick={onClickCollateral}>collateral</Link>.
You need {asset.symbol} in your wallet to trade in this market.
{onClickCollateral && (
<>
See all your <Link onClick={onClickCollateral}>collateral</Link>.
</>
)}
</>
}
buttonProps={{
@@ -1,17 +1,21 @@
import type { UseFormRegister } from 'react-hook-form';
import type { Control } from 'react-hook-form';
import type { Market, MarketData } from '@vegaprotocol/market-list';
import { DealTicketMarketAmount } from './deal-ticket-market-amount';
import { DealTicketLimitAmount } from './deal-ticket-limit-amount';
import * as Schema from '@vegaprotocol/types';
import type { DealTicketFormFields } from './deal-ticket';
import type { OrderObj } from '@vegaprotocol/orders';
import type { OrderFormFields } from '../../hooks/use-order-form';
export interface DealTicketAmountProps {
control: Control<OrderFormFields>;
orderType: Schema.OrderType;
marketData: MarketData;
market: Market;
register: UseFormRegister<DealTicketFormFields>;
sizeError?: string;
priceError?: string;
update: (obj: Partial<OrderObj>) => void;
size: string;
price?: string;
}
export const DealTicketAmount = ({
@@ -47,7 +47,7 @@ export const DealTicketContainer = ({
market={market}
marketData={marketData}
submit={(orderSubmission) => create({ orderSubmission })}
onClickCollateral={onClickCollateral || (() => null)}
onClickCollateral={onClickCollateral}
/>
) : (
<Splash>
@@ -1,5 +1,6 @@
import { Tooltip } from '@vegaprotocol/ui-toolkit';
import type { ReactNode } from 'react';
import { useMemo } from 'react';
import type { OrderSubmissionBody } from '@vegaprotocol/wallet';
import type { Market, MarketData } from '@vegaprotocol/market-list';
import {
@@ -26,7 +27,7 @@ export const DealTicketFeeDetails = ({
marketData,
}: DealTicketFeeDetailsProps) => {
const feeDetails = useFeeDealTicketDetails(order, market, marketData);
const details = getFeeDetailsValues(feeDetails);
const details = useMemo(() => getFeeDetailsValues(feeDetails), [feeDetails]);
return (
<div>
{details.map(({ label, value, labelDescription, symbol }) => (
@@ -2,6 +2,7 @@ import { FormGroup, Input, InputError } from '@vegaprotocol/ui-toolkit';
import { toDecimal, validateAmount } from '@vegaprotocol/utils';
import { t } from '@vegaprotocol/i18n';
import type { DealTicketAmountProps } from './deal-ticket-amount';
import { Controller } from 'react-hook-form';
export type DealTicketLimitAmountProps = Omit<
Omit<DealTicketAmountProps, 'marketData'>,
@@ -9,10 +10,13 @@ export type DealTicketLimitAmountProps = Omit<
>;
export const DealTicketLimitAmount = ({
register,
control,
market,
sizeError,
priceError,
update,
price,
size,
}: DealTicketLimitAmountProps) => {
const priceStep = toDecimal(market?.decimalPlaces);
const sizeStep = toDecimal(market?.positionDecimalPlaces);
@@ -47,22 +51,30 @@ export const DealTicketLimitAmount = ({
labelFor="input-order-size-limit"
className="!mb-1"
>
<Input
id="input-order-size-limit"
className="w-full"
type="number"
step={sizeStep}
min={sizeStep}
data-testid="order-size"
onWheel={(e) => e.currentTarget.blur()}
{...register('size', {
<Controller
name="size"
control={control}
rules={{
required: t('You need to provide a size'),
min: {
value: sizeStep,
message: t('Size cannot be lower than ' + sizeStep),
},
validate: validateAmount(sizeStep, 'Size'),
})}
}}
render={() => (
<Input
id="input-order-size-limit"
className="w-full"
type="number"
value={size}
onChange={(e) => update({ size: e.target.value })}
step={sizeStep}
min={sizeStep}
data-testid="order-size"
onWheel={(e) => e.currentTarget.blur()}
/>
)}
/>
</FormGroup>
</div>
@@ -77,14 +89,10 @@ export const DealTicketLimitAmount = ({
labelAlign="right"
className="!mb-1"
>
<Input
id="input-price-quote"
className="w-full"
type="number"
step={priceStep}
data-testid="order-price"
onWheel={(e) => e.currentTarget.blur()}
{...register('price', {
<Controller
name="price"
control={control}
rules={{
required: t('You need provide a price'),
min: {
value: priceStep,
@@ -92,7 +100,19 @@ export const DealTicketLimitAmount = ({
},
// @ts-ignore this fulfills the interface but still errors
validate: validateAmount(priceStep, 'Price'),
})}
}}
render={() => (
<Input
id="input-price-quote"
className="w-full"
type="number"
value={price}
onChange={(e) => update({ price: e.target.value })}
step={priceStep}
data-testid="order-price"
onWheel={(e) => e.currentTarget.blur()}
/>
)}
/>
</FormGroup>
</div>
@@ -8,6 +8,7 @@ import { Input, InputError, Tooltip } from '@vegaprotocol/ui-toolkit';
import { isMarketInAuction } from '../../utils';
import type { DealTicketAmountProps } from './deal-ticket-amount';
import { getMarketPrice } from '../../utils/get-price';
import { Controller } from 'react-hook-form';
export type DealTicketMarketAmountProps = Omit<
DealTicketAmountProps,
@@ -15,10 +16,12 @@ export type DealTicketMarketAmountProps = Omit<
>;
export const DealTicketMarketAmount = ({
register,
control,
market,
marketData,
sizeError,
update,
size,
}: DealTicketMarketAmountProps) => {
const quoteName = market.tradableInstrument.instrument.product.quoteName;
const sizeStep = toDecimal(market?.positionDecimalPlaces);
@@ -47,22 +50,30 @@ export const DealTicketMarketAmount = ({
</div>
<div className="flex items-center gap-4">
<div className="flex-1">
<Input
id="input-order-size-market"
className="w-full"
type="number"
step={sizeStep}
min={sizeStep}
onWheel={(e) => e.currentTarget.blur()}
data-testid="order-size"
{...register('size', {
<Controller
name="size"
control={control}
rules={{
required: t('You need to provide a size'),
min: {
value: sizeStep,
message: t('Size cannot be lower than ' + sizeStep),
},
validate: validateAmount(sizeStep, 'Size'),
})}
}}
render={() => (
<Input
id="input-order-size-market"
className="w-full"
type="number"
value={size}
onChange={(e) => update({ size: e.target.value })}
step={sizeStep}
min={sizeStep}
onWheel={(e) => e.currentTarget.blur()}
data-testid="order-size"
/>
)}
/>
</div>
<div>@</div>
@@ -1,38 +1,28 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import { VegaWalletContext } from '@vegaprotocol/wallet';
import { fireEvent, render, screen, act } from '@testing-library/react';
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { generateMarket, generateMarketData } from '../../test-helpers';
import { DealTicket } from './deal-ticket';
import * as Schema from '@vegaprotocol/types';
import type { OrderSubmissionBody } from '@vegaprotocol/wallet';
import type { MockedResponse } from '@apollo/client/testing';
import { MockedProvider } from '@apollo/client/testing';
import type { ChainIdQuery } from '@vegaprotocol/react-helpers';
import { ChainIdDocument } from '@vegaprotocol/react-helpers';
import { addDecimal } from '@vegaprotocol/utils';
import { useOrderStore } from '@vegaprotocol/orders';
jest.mock('zustand');
jest.mock('./deal-ticket-fee-details', () => ({
DealTicketFeeDetails: () => <div data-testid="deal-ticket-fee-details" />,
}));
const pubKey = 'pubKey';
const market = generateMarket();
const marketData = generateMarketData();
const submit = jest.fn();
const mockChainId = 'chain-id';
function generateJsx(order?: OrderSubmissionBody['orderSubmission']) {
const chainIdMock: MockedResponse<ChainIdQuery> = {
request: {
query: ChainIdDocument,
},
result: {
data: {
statistics: {
chainId: mockChainId,
},
},
},
};
function generateJsx() {
return (
<MockedProvider mocks={[chainIdMock]}>
<VegaWalletContext.Provider value={{ pubKey: mockChainId } as any}>
<MockedProvider>
<VegaWalletContext.Provider value={{ pubKey, isReadOnly: false } as any}>
<DealTicket market={market} marketData={marketData} submit={submit} />
</VegaWalletContext.Provider>
</MockedProvider>
@@ -41,10 +31,11 @@ function generateJsx(order?: OrderSubmissionBody['orderSubmission']) {
describe('DealTicket', () => {
beforeEach(() => {
window.localStorage.clear();
localStorage.clear();
});
afterEach(() => {
window.localStorage.clear();
localStorage.clear();
jest.clearAllMocks();
});
@@ -61,9 +52,7 @@ describe('DealTicket', () => {
expect(
screen.queryByTestId('order-side-SIDE_SELL')?.querySelector('input')
).not.toBeChecked();
expect(screen.getByTestId('order-size')).toHaveDisplayValue(
String(1 / Math.pow(10, market.positionDecimalPlaces))
);
expect(screen.getByTestId('order-size')).toHaveDisplayValue('0');
expect(screen.getByTestId('order-tif')).toHaveValue(
Schema.OrderTimeInForce.TIME_IN_FORCE_IOC
);
@@ -76,7 +65,49 @@ describe('DealTicket', () => {
);
});
it('handles TIF select box dependent on order type', () => {
it('should use local storage state for initial values', () => {
const expectedOrder = {
marketId: market.id,
type: Schema.OrderType.TYPE_LIMIT,
side: Schema.Side.SIDE_SELL,
size: '0.1',
price: '300.22',
timeInForce: Schema.OrderTimeInForce.TIME_IN_FORCE_IOC,
persist: true,
};
useOrderStore.setState({
orders: {
[expectedOrder.marketId]: expectedOrder,
},
});
render(generateJsx());
// Assert correct defaults are used from store
expect(
screen
.getByTestId(`order-type-${Schema.OrderType.TYPE_LIMIT}`)
.querySelector('input')
).toBeChecked();
expect(
screen.queryByTestId('order-side-SIDE_SELL')?.querySelector('input')
).toBeChecked();
expect(
screen.queryByTestId('order-side-SIDE_BUY')?.querySelector('input')
).not.toBeChecked();
expect(screen.getByTestId('order-size')).toHaveDisplayValue(
expectedOrder.size
);
expect(screen.getByTestId('order-tif')).toHaveValue(
expectedOrder.timeInForce
);
expect(screen.getByTestId('order-price')).toHaveDisplayValue(
expectedOrder.price
);
});
it('handles TIF select box dependent on order type', async () => {
render(generateJsx());
// Only FOK and IOC should be present by default (type market order)
@@ -86,50 +117,72 @@ describe('DealTicket', () => {
)
).toEqual(['Fill or Kill (FOK)', 'Immediate or Cancel (IOC)']);
// IOC should be default
expect(screen.getByTestId('order-tif')).toHaveDisplayValue(
'Immediate or Cancel (IOC)'
);
// Select FOK - FOK should be selected
await userEvent.selectOptions(
screen.getByTestId('order-tif'),
Schema.OrderTimeInForce.TIME_IN_FORCE_FOK
);
expect(screen.getByTestId('order-tif')).toHaveDisplayValue(
'Fill or Kill (FOK)'
);
// Switch to type limit order -> all TIF options should be shown
fireEvent.click(screen.getByTestId('order-type-TYPE_LIMIT'));
await userEvent.click(screen.getByTestId('order-type-TYPE_LIMIT'));
expect(screen.getByTestId('order-tif').children).toHaveLength(
Object.keys(Schema.OrderTimeInForce).length
);
// Select GTC -> GTC should be selected
fireEvent.change(screen.getByTestId('order-tif'), {
target: { value: Schema.OrderTimeInForce.TIME_IN_FORCE_GTC },
});
expect(screen.getByTestId('order-tif')).toHaveValue(
Schema.OrderTimeInForce.TIME_IN_FORCE_GTC
);
// Switch to type market order -> IOC should be selected (default)
fireEvent.click(screen.getByTestId('order-type-TYPE_MARKET'));
expect(screen.getByTestId('order-tif')).toHaveValue(
Schema.OrderTimeInForce.TIME_IN_FORCE_IOC
);
// Select IOC -> IOC should be selected
fireEvent.change(screen.getByTestId('order-tif'), {
target: { value: Schema.OrderTimeInForce.TIME_IN_FORCE_IOC },
});
expect(screen.getByTestId('order-tif')).toHaveValue(
Schema.OrderTimeInForce.TIME_IN_FORCE_IOC
);
// Switch to type limit order -> GTC should be selected
fireEvent.click(screen.getByTestId('order-type-TYPE_LIMIT'));
// expect GTC as LIMIT default
expect(screen.getByTestId('order-tif')).toHaveValue(
Schema.OrderTimeInForce.TIME_IN_FORCE_GTC
);
// Select GTT -> GTT should be selected
fireEvent.change(screen.getByTestId('order-tif'), {
target: { value: Schema.OrderTimeInForce.TIME_IN_FORCE_GTT },
});
await userEvent.selectOptions(
screen.getByTestId('order-tif'),
Schema.OrderTimeInForce.TIME_IN_FORCE_GTT
);
expect(screen.getByTestId('order-tif')).toHaveValue(
Schema.OrderTimeInForce.TIME_IN_FORCE_GTT
);
// Switch to type market order -> IOC should be selected
fireEvent.click(screen.getByTestId('order-type-TYPE_MARKET'));
// Switch back to type market order -> FOK should be preserved from previous selection
await userEvent.click(screen.getByTestId('order-type-TYPE_MARKET'));
expect(screen.getByTestId('order-tif')).toHaveValue(
Schema.OrderTimeInForce.TIME_IN_FORCE_FOK
);
// Select IOC -> IOC should be selected
await userEvent.selectOptions(
screen.getByTestId('order-tif'),
Schema.OrderTimeInForce.TIME_IN_FORCE_IOC
);
expect(screen.getByTestId('order-tif')).toHaveValue(
Schema.OrderTimeInForce.TIME_IN_FORCE_IOC
);
// Switch back type limit order -> GTT should be preserved
await userEvent.click(screen.getByTestId('order-type-TYPE_LIMIT'));
expect(screen.getByTestId('order-tif')).toHaveValue(
Schema.OrderTimeInForce.TIME_IN_FORCE_GTT
);
// Select GFN -> GFN should be selected
await userEvent.selectOptions(
screen.getByTestId('order-tif'),
Schema.OrderTimeInForce.TIME_IN_FORCE_GFN
);
expect(screen.getByTestId('order-tif')).toHaveValue(
Schema.OrderTimeInForce.TIME_IN_FORCE_GFN
);
// Switch to type market order -> IOC should be preserved
await userEvent.click(screen.getByTestId('order-type-TYPE_MARKET'));
expect(screen.getByTestId('order-tif')).toHaveValue(
Schema.OrderTimeInForce.TIME_IN_FORCE_IOC
);
@@ -143,23 +196,20 @@ describe('DealTicket', () => {
screen.getByTestId('order-side-SIDE_BUY')?.querySelector('input')
).toBeChecked();
await act(async () => {
fireEvent.change(screen.getByTestId('order-size'), {
target: { value: '200' },
});
});
await userEvent.type(screen.getByTestId('order-size'), '200');
expect(screen.getByTestId('order-size')).toHaveDisplayValue('200');
fireEvent.change(screen.getByTestId('order-tif'), {
target: { value: Schema.OrderTimeInForce.TIME_IN_FORCE_IOC },
});
await userEvent.selectOptions(
screen.getByTestId('order-tif'),
Schema.OrderTimeInForce.TIME_IN_FORCE_IOC
);
expect(screen.getByTestId('order-tif')).toHaveValue(
Schema.OrderTimeInForce.TIME_IN_FORCE_IOC
);
// Switch to limit order
fireEvent.click(screen.getByTestId('order-type-TYPE_LIMIT'));
await userEvent.click(screen.getByTestId('order-type-TYPE_LIMIT'));
// Check all TIF options shown
expect(screen.getByTestId('order-tif').children).toHaveLength(
@@ -1,7 +1,7 @@
import { t } from '@vegaprotocol/i18n';
import * as Schema from '@vegaprotocol/types';
import { memo, useCallback, useEffect } from 'react';
import { Controller, useForm } from 'react-hook-form';
import { memo, useCallback, useEffect, useState } from 'react';
import { Controller } from 'react-hook-form';
import { DealTicketAmount } from './deal-ticket-amount';
import { DealTicketButton } from './deal-ticket-button';
import { DealTicketFeeDetails } from './deal-ticket-fee-details';
@@ -9,10 +9,12 @@ import { ExpirySelector } from './expiry-selector';
import { SideSelector } from './side-selector';
import { TimeInForceSelector } from './time-in-force-selector';
import { TypeSelector } from './type-selector';
import type { OrderSubmissionBody } from '@vegaprotocol/wallet';
import { useVegaWalletDialogStore } from '@vegaprotocol/wallet';
import { normalizeOrderSubmission } from '@vegaprotocol/wallet';
import { useVegaWallet } from '@vegaprotocol/wallet';
import type { OrderSubmission } from '@vegaprotocol/wallet';
import {
normalizeOrderSubmission,
useVegaWallet,
useVegaWalletDialogStore,
} from '@vegaprotocol/wallet';
import {
ExternalLink,
InputError,
@@ -22,7 +24,7 @@ import {
import { useOrderMarginValidation } from '../../hooks/use-order-margin-validation';
import { MarginWarning } from '../deal-ticket-validation/margin-warning';
import {
getDefaultOrder,
validateExpiration,
validateMarketState,
validateMarketTradingMode,
validateTimeInForce,
@@ -32,26 +34,17 @@ import { ZeroBalanceError } from '../deal-ticket-validation/zero-balance-error';
import { SummaryValidationType } from '../../constants';
import { useHasNoBalance } from '../../hooks/use-has-no-balance';
import type { Market, MarketData } from '@vegaprotocol/market-list';
import {
usePersistedOrderStore,
usePersistedOrderStoreSubscription,
} from '@vegaprotocol/orders';
export type TransactionStatus = 'default' | 'pending';
import { OrderTimeInForce, OrderType } from '@vegaprotocol/types';
import { useOrderForm } from '../../hooks/use-order-form';
import type { OrderObj } from '@vegaprotocol/orders';
export interface DealTicketProps {
market: Market;
marketData: MarketData;
submit: (order: OrderSubmissionBody['orderSubmission']) => void;
submit: (order: OrderSubmission) => void;
onClickCollateral?: () => void;
}
export type DealTicketFormFields = OrderSubmissionBody['orderSubmission'] & {
// This is not a field used in the form but allows us to set a
// summary error message
summary: string;
};
export const DealTicket = ({
market,
marketData,
@@ -59,39 +52,21 @@ export const DealTicket = ({
onClickCollateral,
}: DealTicketProps) => {
const { pubKey, isReadOnly } = useVegaWallet();
const { getPersistedOrder, setPersistedOrder } = usePersistedOrderStore(
(store) => ({
getPersistedOrder: store.getOrder,
setPersistedOrder: store.setOrder,
})
);
// store last used tif for market so that when changing OrderType the previous TIF
// selection for that type is used when switching back
const [lastTIF, setLastTIF] = useState({
[OrderType.TYPE_MARKET]: OrderTimeInForce.TIME_IN_FORCE_IOC,
[OrderType.TYPE_LIMIT]: OrderTimeInForce.TIME_IN_FORCE_GTC,
});
const {
register,
control,
handleSubmit,
watch,
errors,
order,
setError,
clearErrors,
formState: { errors },
setValue,
} = useForm<DealTicketFormFields>({
defaultValues: getPersistedOrder(market.id) || getDefaultOrder(market),
});
const order = watch();
watch((orderData) => {
setPersistedOrder(orderData as DealTicketFormFields);
});
usePersistedOrderStoreSubscription(market.id, (storedOrder) => {
if (order.price !== storedOrder.price) {
clearErrors('price');
setValue('price', storedOrder.price);
}
});
update,
handleSubmit,
} = useOrderForm(market.id);
const marketStateError = validateMarketState(marketData.marketState);
const hasNoBalance = useHasNoBalance(
market.tradableInstrument.instrument.product.settlementAsset.id
@@ -160,7 +135,7 @@ export const DealTicket = ({
]);
const onSubmit = useCallback(
(order: OrderSubmissionBody['orderSubmission']) => {
(order: OrderSubmission) => {
checkForErrors();
submit(
normalizeOrderSubmission(
@@ -173,9 +148,12 @@ export const DealTicket = ({
[checkForErrors, submit, market.decimalPlaces, market.positionDecimalPlaces]
);
// if an order doesn't exist one will be created by the store immediately
if (!order) return null;
return (
<form
onSubmit={isReadOnly ? () => null : handleSubmit(onSubmit)}
onSubmit={isReadOnly ? undefined : handleSubmit(onSubmit)}
className="p-4"
noValidate
>
@@ -188,10 +166,17 @@ export const DealTicket = ({
marketData.trigger
),
}}
render={({ field }) => (
render={() => (
<TypeSelector
value={field.value}
onSelect={field.onChange}
value={order.type}
onSelect={(type) => {
if (type === OrderType.TYPE_NETWORK) return;
update({
type,
// when changing type also update the tif to what was last used of new type
timeInForce: lastTIF[type] || order.timeInForce,
});
}}
market={market}
marketData={marketData}
errorMessage={errors.type?.message}
@@ -201,17 +186,25 @@ export const DealTicket = ({
<Controller
name="side"
control={control}
render={({ field }) => (
<SideSelector value={field.value} onSelect={field.onChange} />
render={() => (
<SideSelector
value={order.side}
onSelect={(side) => {
update({ side });
}}
/>
)}
/>
<DealTicketAmount
control={control}
orderType={order.type}
market={market}
marketData={marketData}
register={register}
sizeError={errors.size?.message}
priceError={errors.price?.message}
update={update}
size={order.size}
price={order.price}
/>
<Controller
name="timeInForce"
@@ -222,11 +215,16 @@ export const DealTicket = ({
marketData.trigger
),
}}
render={({ field }) => (
render={() => (
<TimeInForceSelector
value={field.value}
value={order.timeInForce}
orderType={order.type}
onSelect={field.onChange}
onSelect={(timeInForce) => {
update({ timeInForce });
// Set tif value for the given order type, so that when switching
// types we know the last used TIF for the given order type
setLastTIF((curr) => ({ ...curr, [order.type]: timeInForce }));
}}
market={market}
marketData={marketData}
errorMessage={errors.timeInForce?.message}
@@ -238,12 +236,18 @@ export const DealTicket = ({
<Controller
name="expiresAt"
control={control}
render={({ field }) => (
rules={{
validate: validateExpiration,
}}
render={() => (
<ExpirySelector
value={field.value}
onSelect={field.onChange}
value={order.expiresAt}
onSelect={(expiresAt) =>
update({
expiresAt: expiresAt || undefined,
})
}
errorMessage={errors.expiresAt?.message}
register={register}
/>
)}
/>
@@ -255,7 +259,7 @@ export const DealTicket = ({
order={order}
isReadOnly={isReadOnly}
pubKey={pubKey}
onClickCollateral={onClickCollateral || (() => null)}
onClickCollateral={onClickCollateral}
/>
<DealTicketButton
disabled={Object.keys(errors).length >= 1 || isReadOnly}
@@ -278,10 +282,10 @@ interface SummaryMessageProps {
errorMessage?: string;
market: Market;
marketData: MarketData;
order: OrderSubmissionBody['orderSubmission'];
order: OrderObj;
isReadOnly: boolean;
pubKey: string | null;
onClickCollateral: () => void;
onClickCollateral?: () => void;
}
const SummaryMessage = memo(
({
@@ -369,7 +373,7 @@ const SummaryMessage = memo(
if (balanceError) {
return (
<div className="mb-2">
<MarginWarning balance={balance} margin={margin} asset={asset} />;
<MarginWarning balance={balance} margin={margin} asset={asset} />
</div>
);
}
@@ -1,28 +1,27 @@
import { FormGroup, Input, InputError } from '@vegaprotocol/ui-toolkit';
import { formatForInput } from '@vegaprotocol/utils';
import { t } from '@vegaprotocol/i18n';
import type { UseFormRegister } from 'react-hook-form';
import { validateExpiration } from '../../utils/validate-expiration';
import type { DealTicketFormFields } from '.';
interface ExpirySelectorProps {
value?: string;
onSelect: (expiration: string | null) => void;
errorMessage?: string;
register?: UseFormRegister<DealTicketFormFields>;
}
export const ExpirySelector = ({
value,
onSelect,
errorMessage,
register,
}: ExpirySelectorProps) => {
const date = value ? new Date(value) : new Date();
const dateFormatted = formatForInput(date);
const minDate = formatForInput(date);
return (
<FormGroup label={t('Expiry time/date')} labelFor="expiration">
<FormGroup
label={t('Expiry time/date')}
labelFor="expiration"
compact={true}
>
<Input
data-testid="date-picker-field"
id="expiration"
@@ -30,9 +29,6 @@ export const ExpirySelector = ({
value={dateFormatted}
onChange={(e) => onSelect(e.target.value)}
min={minDate}
{...register?.('expiresAt', {
validate: validateExpiration,
})}
/>
{errorMessage && (
<InputError testId="dealticket-error-message-expiry">
@@ -26,7 +26,11 @@ export const SideSelector = ({ value, onSelect }: SideSelectorProps) => {
};
return (
<FormGroup label={t('Direction')} labelFor="order-side-toggle">
<FormGroup
label={t('Direction')}
labelFor="order-side-toggle"
compact={true}
>
<Toggle
id="order-side-toggle"
name="order-side"
@@ -1,4 +1,3 @@
import { useEffect, useState } from 'react';
import {
FormGroup,
InputError,
@@ -22,15 +21,6 @@ interface TimeInForceSelectorProps {
errorMessage?: string;
}
type OrderType = Schema.OrderType.TYPE_MARKET | Schema.OrderType.TYPE_LIMIT;
type PreviousTimeInForce = {
[key in OrderType]: Schema.OrderTimeInForce;
};
const DEFAULT_TIME_IN_FORCE: PreviousTimeInForce = {
[Schema.OrderType.TYPE_MARKET]: Schema.OrderTimeInForce.TIME_IN_FORCE_IOC,
[Schema.OrderType.TYPE_LIMIT]: Schema.OrderTimeInForce.TIME_IN_FORCE_GTC,
};
export const TimeInForceSelector = ({
value,
orderType,
@@ -47,28 +37,6 @@ export const TimeInForceSelector = ({
timeInForce === Schema.OrderTimeInForce.TIME_IN_FORCE_FOK ||
timeInForce === Schema.OrderTimeInForce.TIME_IN_FORCE_IOC
);
const [previousOrderType, setPreviousOrderType] = useState(
Schema.OrderType.TYPE_MARKET
);
const [previousTimeInForce, setPreviousTimeInForce] =
useState<PreviousTimeInForce>({
...DEFAULT_TIME_IN_FORCE,
[orderType]: value,
});
useEffect(() => {
if (previousOrderType !== orderType) {
setPreviousOrderType(orderType);
const prev = previousTimeInForce[orderType as OrderType];
onSelect(prev);
}
}, [
onSelect,
orderType,
previousTimeInForce,
previousOrderType,
setPreviousOrderType,
]);
const renderError = (errorType: string) => {
if (errorType === MarketModeValidationType.Auction) {
@@ -119,15 +87,25 @@ export const TimeInForceSelector = ({
};
return (
<FormGroup label={t('Time in force')} labelFor="select-time-in-force">
<FormGroup
label={t('Time in force')}
labelFor="select-time-in-force"
compact={true}
>
<Select
id="select-time-in-force"
value={value}
onChange={(e) => {
setPreviousTimeInForce({
...previousTimeInForce,
[orderType]: e.target.value,
});
// setPreviousTimeInForce({
// ...previousTimeInForce,
// [orderType]: e.target.value,
// });
// if (previousOrderType !== orderType) {
// setPreviousOrderType(orderType);
// const prev = previousTimeInForce[orderType as OrderType];
// onSelect(prev);
// }
onSelect(e.target.value as Schema.OrderTimeInForce);
}}
className="w-full"
@@ -74,7 +74,7 @@ export const TypeSelector = ({
};
return (
<FormGroup label={t('Order type')} labelFor="order-type">
<FormGroup label={t('Order type')} labelFor="order-type" compact={true}>
<Toggle
id="order-type"
name="order-type"
@@ -0,0 +1,66 @@
import omit from 'lodash/omit';
import { act, renderHook } from '@testing-library/react';
import { getDefaultOrder, useOrderStore } from '@vegaprotocol/orders';
import { useOrderForm } from './use-order-form';
jest.mock('zustand');
describe('useOrderForm', () => {
const marketId = 'market-id';
const setup = (marketId: string) => {
return renderHook(() => useOrderForm(marketId));
};
it('updates form fields when the order changes', async () => {
const order = getDefaultOrder(marketId);
const { result } = setup(marketId);
// expect default values
expect(result.current.order).toEqual(order);
expect(result.current.getValues()).toEqual(order);
const priceUpdate = {
...order,
price: '100',
size: '22',
};
await act(async () => {
useOrderStore.setState({
orders: {
[marketId]: priceUpdate,
},
});
});
// check order store has updated fields
expect(result.current.order).toEqual(priceUpdate);
// check react-hook-form has updated fields
expect(result.current.getValues()).toEqual(priceUpdate);
});
it('removes persist key on submit', async () => {
const order = {
...getDefaultOrder(marketId),
price: '99',
size: '22',
};
const onSubmit = jest.fn();
const { result } = setup(marketId);
await act(async () => {
useOrderStore.setState({
orders: {
[marketId]: order,
},
});
});
await act(async () => {
result.current.handleSubmit(onSubmit)();
});
expect(onSubmit).toHaveBeenCalledTimes(1);
expect(onSubmit.mock.calls[0][0]).toEqual(omit(order, 'persist'));
expect(onSubmit.mock.calls[0][0].persist).toBeUndefined();
});
});
@@ -0,0 +1,74 @@
import omit from 'lodash/omit';
import type { OrderObj } from '@vegaprotocol/orders';
import { getDefaultOrder, useOrder } from '@vegaprotocol/orders';
import { useEffect } from 'react';
import { useForm } from 'react-hook-form';
import type { OrderSubmission } from '@vegaprotocol/wallet';
import type { Exact } from 'type-fest';
export type OrderFormFields = OrderObj & {
summary: string;
};
/**
* Connects the order store to a react-hook-form instance. Any time a field
* changes in the store the form will be updated so that validation rules
* for those fields are applied
*/
export const useOrderForm = (marketId: string) => {
const [order, update] = useOrder(marketId);
const {
control,
formState: { errors, isSubmitted },
handleSubmit,
setError,
setValue,
clearErrors,
getValues,
} = useForm<OrderFormFields>({
// order can be undefined if there is nothing in the store, it
// will be created but the form still needs some default values
defaultValues: order || getDefaultOrder(marketId),
});
// Keep form fields in sync with the store values,
// inputs are updating the store, fields need updating
// to ensure validation rules are applied
useEffect(() => {
if (!order) return;
const currOrder = getValues();
for (const k in order) {
const key = k as keyof typeof order;
const curr = currOrder[key];
const value = order[key];
if (value !== curr) {
setValue(key, value, {
shouldValidate: isSubmitted, // only apply validation after the form has been submitted and failed
shouldDirty: true,
shouldTouch: true,
});
}
}
}, [order, isSubmitted, getValues, setValue]);
const handleSubmitWrapper = (
cb: <T>(o: Exact<OrderSubmission, T>) => void
) => {
return handleSubmit(() => {
// remove the persist key from the order in the store, the wallet will reject
// an order that contains unrecognized additional keys
cb(omit(order, 'persist'));
});
};
return {
order,
update,
control,
errors,
setError,
clearErrors,
getValues, // returned for test purposes only
handleSubmit: handleSubmitWrapper,
};
};
+2 -1
View File
@@ -17,7 +17,8 @@
"**/*.test.js",
"**/*.spec.jsx",
"**/*.test.jsx",
"jest.config.ts"
"jest.config.ts",
"__mocks__"
],
"include": ["**/*.js", "**/*.jsx", "**/*.ts", "**/*.tsx"]
}
@@ -0,0 +1,215 @@
import type { Asset } from '@vegaprotocol/assets';
import { useEnvironment } from '@vegaprotocol/environment';
import { t } from '@vegaprotocol/i18n';
import { ExternalLink, Intent, Notification } from '@vegaprotocol/ui-toolkit';
import { formatNumber } from '@vegaprotocol/utils';
import type { EthStoredTxState } from '@vegaprotocol/web3';
import { EthTxStatus, useEthTransactionStore } from '@vegaprotocol/web3';
import BigNumber from 'bignumber.js';
import type { DepositBalances } from './use-deposit-balances';
interface ApproveNotificationProps {
isActive: boolean;
selectedAsset?: Asset;
onApprove: () => void;
approved: boolean;
balances: DepositBalances | null;
amount: string;
approveTxId: number | null;
}
export const ApproveNotification = ({
isActive,
selectedAsset,
onApprove,
amount,
balances,
approved,
approveTxId,
}: ApproveNotificationProps) => {
const tx = useEthTransactionStore((state) => {
return state.transactions.find((t) => t?.id === approveTxId);
});
if (!isActive) {
return null;
}
if (!selectedAsset) {
return null;
}
if (!balances) {
return null;
}
const approvePrompt = (
<div className="mb-4">
<Notification
intent={Intent.Warning}
testId="approve-default"
message={t(
`Before you can make a deposit of your chosen asset, ${selectedAsset?.symbol}, you need to approve its use in your Ethereum wallet`
)}
buttonProps={{
size: 'sm',
text: `Approve ${selectedAsset?.symbol}`,
action: onApprove,
dataTestId: 'approve-submit',
}}
/>
</div>
);
const reApprovePrompt = (
<div className="mb-4">
<Notification
intent={Intent.Warning}
testId="reapprove-default"
message={t(
`Approve again to deposit more than ${formatNumber(
balances.allowance.toString()
)}`
)}
buttonProps={{
size: 'sm',
text: `Approve ${selectedAsset?.symbol}`,
action: onApprove,
dataTestId: 'reapprove-submit',
}}
/>
</div>
);
const approvalFeedback = (
<ApprovalTxFeedback
tx={tx}
selectedAsset={selectedAsset}
allowance={balances.allowance}
/>
);
// always show requested and pending states
if (
tx &&
[EthTxStatus.Requested, EthTxStatus.Pending, EthTxStatus.Complete].includes(
tx.status
)
) {
return approvalFeedback;
}
if (!approved) {
return approvePrompt;
}
if (new BigNumber(amount).isGreaterThan(balances.allowance)) {
return reApprovePrompt;
}
if (
tx &&
tx.status === EthTxStatus.Error &&
// @ts-ignore tx.error not typed correctly
tx.error.code === 'ACTION_REJECTED'
) {
return approvePrompt;
}
return approvalFeedback;
};
const ApprovalTxFeedback = ({
tx,
selectedAsset,
allowance,
}: {
tx: EthStoredTxState | undefined;
selectedAsset: Asset;
allowance?: BigNumber;
}) => {
const { ETHERSCAN_URL } = useEnvironment();
if (!tx) return null;
const txLink = tx.txHash && (
<ExternalLink href={`${ETHERSCAN_URL}/tx/${tx.txHash}`}>
{t('View on Etherscan')}
</ExternalLink>
);
if (tx.status === EthTxStatus.Error) {
return (
<div className="mb-4">
<Notification
intent={Intent.Danger}
testId="approve-error"
message={
<p>
{t('Approval failed')} {txLink}
</p>
}
/>
</div>
);
}
if (tx.status === EthTxStatus.Requested) {
return (
<div className="mb-4">
<Notification
intent={Intent.Warning}
testId="approve-requested"
message={t(
`Go to your Ethereum wallet and approve the transaction to enable the use of ${selectedAsset?.symbol}`
)}
/>
</div>
);
}
if (tx.status === EthTxStatus.Pending) {
return (
<div className="mb-4">
<Notification
intent={Intent.Primary}
testId="approve-pending"
message={
<>
<p>
{t(
`Your ${selectedAsset?.symbol} is being confirmed by the Ethereum network. When this is complete, you can continue your deposit`
)}{' '}
</p>
{txLink && <p>{txLink}</p>}
</>
}
/>
</div>
);
}
if (tx.status === EthTxStatus.Confirmed) {
return (
<div className="mb-4">
<Notification
intent={Intent.Success}
testId="approve-confirmed"
message={
<>
<p>
{t(
`You can now make deposits in ${
selectedAsset?.symbol
}, up to a maximum of ${formatNumber(
allowance?.toString() || 0
)}`
)}
</p>
{txLink && <p>{txLink}</p>}
</>
}
/>
</div>
);
}
return null;
};
+1 -9
View File
@@ -4,18 +4,11 @@ import { DepositManager } from './deposit-manager';
import { t } from '@vegaprotocol/i18n';
import { useDataProvider } from '@vegaprotocol/react-helpers';
import { enabledAssetsProvider } from '@vegaprotocol/assets';
import type { DepositDialogStylePropsSetter } from './deposit-dialog';
/**
* Fetches data required for the Deposit page
*/
export const DepositContainer = ({
assetId,
setDialogStyleProps,
}: {
assetId?: string;
setDialogStyleProps?: DepositDialogStylePropsSetter;
}) => {
export const DepositContainer = ({ assetId }: { assetId?: string }) => {
const { VEGA_ENV } = useEnvironment();
const { data, loading, error } = useDataProvider({
dataProvider: enabledAssetsProvider,
@@ -28,7 +21,6 @@ export const DepositContainer = ({
assetId={assetId}
assets={data}
isFaucetable={VEGA_ENV !== Networks.MAINNET}
setDialogStyleProps={setDialogStyleProps}
/>
) : (
<Splash>
+2 -32
View File
@@ -1,8 +1,6 @@
import { create } from 'zustand';
import { t } from '@vegaprotocol/i18n';
import type { Intent } from '@vegaprotocol/ui-toolkit';
import { Dialog } from '@vegaprotocol/ui-toolkit';
import { useCallback, useState } from 'react';
import { DepositContainer } from './deposit-container';
import { useWeb3ConnectStore } from '@vegaprotocol/web3';
import { useAssetDetailsDialogStore } from '@vegaprotocol/assets';
@@ -24,22 +22,6 @@ export const useDepositDialog = create<State & Actions>((set) => ({
close: () => set(() => ({ assetId: undefined, isOpen: false })),
}));
export type DepositDialogStyleProps = {
title: string;
icon?: JSX.Element;
intent?: Intent;
};
export type DepositDialogStylePropsSetter = (
props?: DepositDialogStyleProps
) => void;
const DEFAULT_STYLE: DepositDialogStyleProps = {
title: t('Deposit'),
intent: undefined,
icon: undefined,
};
export const DepositDialog = () => {
const { assetId, isOpen, open, close } = useDepositDialog();
const assetDetailsDialogOpen = useAssetDetailsDialogStore(
@@ -48,25 +30,13 @@ export const DepositDialog = () => {
const connectWalletDialogIsOpen = useWeb3ConnectStore(
(state) => state.isOpen
);
const [dialogStyleProps, _setDialogStyleProps] = useState(DEFAULT_STYLE);
const setDialogStyleProps: DepositDialogStylePropsSetter =
useCallback<DepositDialogStylePropsSetter>(
(props) =>
props
? _setDialogStyleProps(props)
: _setDialogStyleProps(DEFAULT_STYLE),
[_setDialogStyleProps]
);
return (
<Dialog
open={isOpen && !(connectWalletDialogIsOpen || assetDetailsDialogOpen)}
onChange={(isOpen) => (isOpen ? open() : close())}
{...dialogStyleProps}
title={t('Deposit')}
>
<DepositContainer
assetId={assetId}
setDialogStyleProps={setDialogStyleProps}
/>
<DepositContainer assetId={assetId} />
</Dialog>
);
};
+40 -23
View File
@@ -7,6 +7,7 @@ import { useVegaWallet } from '@vegaprotocol/wallet';
import { useWeb3ConnectStore } from '@vegaprotocol/web3';
import { useWeb3React } from '@web3-react/core';
import type { AssetFieldsFragment } from '@vegaprotocol/assets';
import type { DepositBalances } from './use-deposit-balances';
jest.mock('@vegaprotocol/wallet');
jest.mock('@vegaprotocol/web3');
@@ -38,27 +39,34 @@ function generateAsset(): AssetFieldsFragment {
let asset: AssetFieldsFragment;
let props: DepositFormProps;
let balances: DepositBalances;
const MOCK_ETH_ADDRESS = '0x72c22822A19D20DE7e426fB84aa047399Ddd8853';
const MOCK_VEGA_KEY =
'70d14a321e02e71992fd115563df765000ccc4775cbe71a0e2f9ff5a3b9dc680';
beforeEach(() => {
asset = generateAsset();
balances = {
balance: new BigNumber(5),
max: new BigNumber(20),
allowance: new BigNumber(30),
deposited: new BigNumber(10),
};
props = {
assets: [asset],
selectedAsset: undefined,
onSelectAsset: jest.fn(),
balance: new BigNumber(5),
balances,
submitApprove: jest.fn(),
submitDeposit: jest.fn(),
requestFaucet: jest.fn(),
max: new BigNumber(20),
deposited: new BigNumber(10),
allowance: new BigNumber(30),
submitFaucet: jest.fn(),
onDisconnect: jest.fn(),
approveTxId: null,
faucetTxId: null,
isFaucetable: true,
};
(useVegaWallet as jest.Mock).mockReturnValue({ pubKey: null });
(useVegaWallet as jest.Mock).mockReturnValue({ pubKey: null, pubKeys: [] });
(useWeb3React as jest.Mock).mockReturnValue({
isActive: true,
account: MOCK_ETH_ADDRESS,
@@ -71,7 +79,8 @@ describe('Deposit form', () => {
render(<DepositForm {...props} />);
// Assert default values (including) from/to provided by useVegaWallet and useWeb3React
expect(screen.getByLabelText('From (Ethereum address)')).toHaveValue(
expect(screen.getByText('From (Ethereum address)')).toBeInTheDocument();
expect(screen.getByTestId('ethereum-address')).toHaveTextContent(
MOCK_ETH_ADDRESS
);
expect(screen.getByLabelText('Asset')).toHaveValue('');
@@ -145,7 +154,7 @@ describe('Deposit form', () => {
fireEvent.submit(screen.getByTestId('deposit-form'));
expect(
await screen.findByText('Amount is above deposit limit')
await screen.findByText('Amount is above lifetime deposit limit')
).toBeInTheDocument();
});
@@ -153,9 +162,12 @@ describe('Deposit form', () => {
render(
<DepositForm
{...props}
balance={new BigNumber(100)}
max={new BigNumber(100)}
deposited={new BigNumber(10)}
balances={{
...balances,
balance: BigNumber(100),
max: new BigNumber(100),
deposited: new BigNumber(10),
}}
/>
);
@@ -166,7 +178,7 @@ describe('Deposit form', () => {
fireEvent.submit(screen.getByTestId('deposit-form'));
expect(
await screen.findByText('Amount is above approved amount.')
await screen.findByText('Amount is above approved amount')
).toBeInTheDocument();
});
@@ -214,14 +226,17 @@ describe('Deposit form', () => {
render(
<DepositForm
{...props}
allowance={new BigNumber(0)}
balances={{
...balances,
allowance: new BigNumber(0),
}}
selectedAsset={asset}
/>
);
expect(screen.queryByLabelText('Amount')).not.toBeInTheDocument();
expect(screen.getByTestId('approve-warning')).toHaveTextContent(
`Deposits of ${asset.symbol} not approved`
expect(screen.getByTestId('approve-default')).toHaveTextContent(
`Before you can make a deposit of your chosen asset, ${asset.symbol}, you need to approve its use in your Ethereum wallet`
);
fireEvent.click(
@@ -253,10 +268,12 @@ describe('Deposit form', () => {
render(
<DepositForm
{...props}
allowance={new BigNumber(100)}
balance={balance}
max={max}
deposited={deposited}
balances={{
allowance: new BigNumber(100),
balance,
max,
deposited,
}}
selectedAsset={asset}
/>
);
@@ -320,10 +337,10 @@ describe('Deposit form', () => {
expect(
screen.queryByRole('button', { name: 'Connect' })
).not.toBeInTheDocument();
const fromInput = screen.getByLabelText('From (Ethereum address)');
expect(fromInput).toHaveValue(MOCK_ETH_ADDRESS);
expect(fromInput).toBeDisabled();
expect(fromInput).toHaveAttribute('readonly');
expect(screen.getByText('From (Ethereum address)')).toBeInTheDocument();
expect(screen.getByTestId('ethereum-address')).toHaveTextContent(
MOCK_ETH_ADDRESS
);
});
it('prevents submission if you are on the wrong chain', () => {
+159 -146
View File
@@ -1,4 +1,4 @@
import type { Asset } from '@vegaprotocol/assets';
import type { Asset, AssetFieldsFragment } from '@vegaprotocol/assets';
import { AssetOption } from '@vegaprotocol/assets';
import {
ethereumAddress,
@@ -19,13 +19,16 @@ import {
RichSelect,
Notification,
Intent,
ButtonLink,
Select,
} from '@vegaprotocol/ui-toolkit';
import { useVegaWallet } from '@vegaprotocol/wallet';
import { useWeb3React } from '@web3-react/core';
import BigNumber from 'bignumber.js';
import type { ButtonHTMLAttributes } from 'react';
import type { ButtonHTMLAttributes, ReactNode } from 'react';
import { useState } from 'react';
import { useMemo } from 'react';
import type { FieldError } from 'react-hook-form';
import { useWatch } from 'react-hook-form';
import { Controller, useForm } from 'react-hook-form';
import { DepositLimits } from './deposit-limits';
import { useAssetDetailsDialogStore } from '@vegaprotocol/assets';
@@ -34,6 +37,9 @@ import {
useWeb3ConnectStore,
getChainName,
} from '@vegaprotocol/web3';
import type { DepositBalances } from './use-deposit-balances';
import { FaucetNotification } from './faucet-notification';
import { ApproveNotification } from './approve-notification';
interface FormFields {
asset: string;
@@ -45,38 +51,38 @@ interface FormFields {
export interface DepositFormProps {
assets: Asset[];
selectedAsset?: Asset;
balances: DepositBalances | null;
onSelectAsset: (assetId: string) => void;
balance: BigNumber | undefined;
onDisconnect: () => void;
submitApprove: () => void;
approveTxId: number | null;
submitFaucet: () => void;
faucetTxId: number | null;
submitDeposit: (args: {
assetSource: string;
amount: string;
vegaPublicKey: string;
}) => void;
requestFaucet: () => void;
max: BigNumber | undefined;
deposited: BigNumber | undefined;
allowance: BigNumber | undefined;
isFaucetable?: boolean;
}
export const DepositForm = ({
assets,
selectedAsset,
balances,
onSelectAsset,
balance,
max,
deposited,
onDisconnect,
submitApprove,
submitDeposit,
requestFaucet,
allowance,
submitFaucet,
faucetTxId,
approveTxId,
isFaucetable,
}: DepositFormProps) => {
const { open: openAssetDetailsDialog } = useAssetDetailsDialogStore();
const openDialog = useWeb3ConnectStore((store) => store.open);
const { isActive, account } = useWeb3React();
const { pubKey } = useVegaWallet();
const { pubKey, pubKeys: _pubKeys } = useVegaWallet();
const {
register,
handleSubmit,
@@ -91,43 +97,21 @@ export const DepositForm = ({
},
});
const amount = useWatch({ name: 'amount', control });
const onSubmit = async (fields: FormFields) => {
if (!selectedAsset || selectedAsset.source.__typename !== 'ERC20') {
throw new Error('Invalid asset');
}
if (!approved) throw new Error('Deposits not approved');
if (approved) {
submitDeposit({
assetSource: selectedAsset.source.contractAddress,
amount: fields.amount,
vegaPublicKey: fields.to,
});
} else {
submitApprove();
}
submitDeposit({
assetSource: selectedAsset.source.contractAddress,
amount: fields.amount,
vegaPublicKey: fields.to,
});
};
const maxAmount = useMemo(() => {
const maxApproved = allowance ? allowance : new BigNumber(0);
const maxAvailable = balance ? balance : new BigNumber(0);
// limits.max is a lifetime deposit limit, so the actual max value for form
// input is the max minus whats already been deposited
let maxLimit = new BigNumber(Infinity);
// A max limit of zero indicates that there is no limit
if (max && deposited && max.isGreaterThan(0)) {
maxLimit = max.minus(deposited);
}
return {
approved: maxApproved,
available: maxAvailable,
limit: maxLimit,
amount: BigNumber.minimum(maxLimit, maxApproved, maxAvailable),
};
}, [max, deposited, allowance, balance]);
const min = useMemo(() => {
// Min viable amount given asset decimals EG for WEI 0.000000000000000001
const minViableAmount = selectedAsset
@@ -137,8 +121,15 @@ export const DepositForm = ({
return minViableAmount;
}, [selectedAsset]);
const approved = allowance && allowance.isGreaterThan(0) ? true : false;
const formState = getFormState(selectedAsset, isActive, approved);
const pubKeys = useMemo(() => {
return _pubKeys ? _pubKeys.map((pk) => pk.publicKey) : [];
}, [_pubKeys]);
const approved = balances
? balances.allowance.isGreaterThan(0)
? true
: false
: false;
return (
<form
@@ -166,32 +157,23 @@ export const DepositForm = ({
render={() => {
if (isActive && account) {
return (
<>
<Input
id="ethereum-address"
value={account}
readOnly={true}
disabled={true}
{...register('from', {
validate: {
required,
ethereumAddress,
},
})}
/>
<div className="text-sm" aria-describedby="ethereum-address">
<p className="mb-1" data-testid="ethereum-address">
{account}
</p>
<DisconnectEthereumButton
onDisconnect={() => {
setValue('from', ''); // clear from value so required ethereum connection validation works
onDisconnect();
}}
/>
</>
</div>
);
}
return (
<Button
onClick={openDialog}
variant="primary"
fill={true}
type="button"
data-testid="connect-eth-wallet-btn"
>
@@ -238,7 +220,7 @@ export const DepositForm = ({
</InputError>
)}
{isFaucetable && selectedAsset && (
<UseButton onClick={requestFaucet}>
<UseButton onClick={submitFaucet}>
{t(`Get ${selectedAsset.symbol}`)}
</UseButton>
)}
@@ -255,39 +237,55 @@ export const DepositForm = ({
</button>
)}
</FormGroup>
<FaucetNotification
isActive={isActive}
selectedAsset={selectedAsset}
faucetTxId={faucetTxId}
/>
<FormGroup label={t('To (Vega key)')} labelFor="to">
<Input
{...register('to', { validate: { required, vegaPublicKey } })}
id="to"
<AddressField
pubKeys={pubKeys}
onChange={() => setValue('to', '')}
select={
<Select {...register('to')} id="to" defaultValue="">
<option value="" disabled={true}>
{t('Please select')}
</option>
{pubKeys?.length &&
pubKeys.map((pk) => (
<option key={pk} value={pk}>
{pk}
</option>
))}
</Select>
}
input={
<Input
// eslint-disable-next-line jsx-a11y/no-autofocus
autoFocus={true} // focus input immediately after is shown
id="to"
type="text"
{...register('to', {
validate: {
required,
vegaPublicKey,
},
})}
/>
}
/>
{errors.to?.message && (
<InputError intent="danger" forInput="to">
{errors.to.message}
</InputError>
)}
{pubKey && (
<UseButton
onClick={() => {
setValue('to', pubKey);
clearErrors('to');
}}
>
{t('Use connected')}
</UseButton>
)}
</FormGroup>
{selectedAsset && max && deposited && (
{selectedAsset && balances && (
<div className="mb-6">
<DepositLimits
max={max}
deposited={deposited}
balance={balance}
asset={selectedAsset}
allowance={allowance}
/>
<DepositLimits {...balances} asset={selectedAsset} />
</div>
)}
{formState === 'deposit' && (
{approved && (
<FormGroup label={t('Amount')} labelFor="amount">
<Input
type="number"
@@ -299,38 +297,52 @@ export const DepositForm = ({
minSafe: (value) => minSafe(new BigNumber(min))(value),
approved: (v) => {
const value = new BigNumber(v);
if (value.isGreaterThan(maxAmount.approved)) {
if (value.isGreaterThan(balances?.allowance || 0)) {
return t('Amount is above approved amount');
}
return true;
},
limit: (v) => {
const value = new BigNumber(v);
if (value.isGreaterThan(maxAmount.limit)) {
return t('Amount is above deposit limit');
if (!balances) {
return t('Could not verify balances of account'); // this should never happen
}
let lifetimeLimit = new BigNumber(Infinity);
if (balances.max.isGreaterThan(0)) {
lifetimeLimit = balances.max.minus(balances.deposited);
}
if (value.isGreaterThan(lifetimeLimit)) {
return t('Amount is above lifetime deposit limit');
}
return true;
},
balance: (v) => {
const value = new BigNumber(v);
if (value.isGreaterThan(maxAmount.available)) {
if (value.isGreaterThan(balances?.balance || 0)) {
return t('Insufficient amount in Ethereum wallet');
}
return true;
},
maxSafe: (v) => {
return maxSafe(maxAmount.amount)(v);
return maxSafe(balances?.balance || new BigNumber(0))(v);
},
},
})}
/>
{errors.amount?.message && (
<AmountError error={errors.amount} submitApprove={submitApprove} />
<InputError intent="danger" forInput="amount">
{errors.amount.message}
</InputError>
)}
{selectedAsset && balance && (
{selectedAsset && balances && (
<UseButton
onClick={() => {
setValue('amount', balance.toFixed(selectedAsset.decimals));
setValue(
'amount',
balances.balance.toFixed(selectedAsset.decimals)
);
clearErrors('amount');
}}
>
@@ -339,59 +351,31 @@ export const DepositForm = ({
)}
</FormGroup>
)}
<FormButton selectedAsset={selectedAsset} formState={formState} />
<ApproveNotification
isActive={isActive}
approveTxId={approveTxId}
selectedAsset={selectedAsset}
onApprove={submitApprove}
balances={balances}
approved={approved}
amount={amount}
/>
<FormButton approved={approved} selectedAsset={selectedAsset} />
</form>
);
};
const AmountError = ({
error,
submitApprove,
}: {
error: FieldError;
submitApprove: () => void;
}) => {
if (error.type === 'approved') {
return (
<InputError intent="danger" forInput="amount">
{error.message}.
<button onClick={submitApprove} className="underline ml-2">
{t('Update approve amount')}
</button>
</InputError>
);
}
return (
<InputError intent="danger" forInput="amount">
{error.message}
</InputError>
);
};
interface FormButtonProps {
selectedAsset?: Asset;
formState: ReturnType<typeof getFormState>;
approved: boolean;
selectedAsset: AssetFieldsFragment | undefined;
}
const FormButton = ({ selectedAsset, formState }: FormButtonProps) => {
const FormButton = ({ approved, selectedAsset }: FormButtonProps) => {
const { isActive, chainId } = useWeb3React();
const desiredChainId = useWeb3ConnectStore((store) => store.desiredChainId);
const submitText =
formState === 'approve'
? t(`Approve ${selectedAsset ? selectedAsset.symbol : ''}`)
: t('Deposit');
const invalidChain = isActive && chainId !== desiredChainId;
return (
<>
{formState === 'approve' && (
<div className="mb-2">
<Notification
intent={Intent.Warning}
testId="approve-warning"
message={t(`Deposits of ${selectedAsset?.symbol} not approved`)}
/>
</div>
)}
{invalidChain && (
<div className="mb-2">
<Notification
@@ -408,9 +392,9 @@ const FormButton = ({ selectedAsset, formState }: FormButtonProps) => {
data-testid="deposit-submit"
variant={isActive ? 'primary' : 'default'}
fill={true}
disabled={invalidChain}
disabled={invalidChain || (selectedAsset && !approved)}
>
{submitText}
{t('Deposit')}
</Button>
</>
);
@@ -437,7 +421,7 @@ const DisconnectEthereumButton = ({
const [, , removeEagerConnector] = useLocalStorage(ETHEREUM_EAGER_CONNECT);
return (
<UseButton
<ButtonLink
onClick={() => {
connector.deactivate();
removeEagerConnector();
@@ -446,17 +430,46 @@ const DisconnectEthereumButton = ({
data-testid="disconnect-ethereum-wallet"
>
{t('Disconnect')}
</UseButton>
</ButtonLink>
);
};
const getFormState = (
selectedAsset: Asset | undefined,
isActive: boolean,
approved: boolean
) => {
if (!selectedAsset) return 'deposit';
if (!isActive) return 'deposit';
if (approved) return 'deposit';
return 'approve';
interface AddressInputProps {
pubKeys: string[] | null;
select: ReactNode;
input: ReactNode;
onChange: () => void;
}
export const AddressField = ({
pubKeys,
select,
input,
onChange,
}: AddressInputProps) => {
const [isInput, setIsInput] = useState(() => {
if (pubKeys && pubKeys.length <= 1) {
return true;
}
return false;
});
return (
<>
{isInput ? input : select}
{pubKeys && pubKeys.length > 1 && (
<button
type="button"
onClick={() => {
setIsInput((curr) => !curr);
onChange();
}}
className="ml-auto text-sm absolute top-0 right-0 underline"
data-testid="enter-pubkey-manually"
>
{isInput ? t('Select from wallet') : t('Enter manually')}
</button>
)}
</>
);
};

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