Compare commits

..
Author SHA1 Message Date
Bill He 0189fac442 flex-wrap 2023-11-10 16:03:59 -08:00
Bill He 610c583246 Add additional onboarding entry points 2023-11-10 14:25:17 -08:00
Bill d4bcfc0428 Fix status empty bug (#143) 2023-11-10 09:55:54 -08:00
aleka 7dec32df5e fix 24h sort in market dropdown, table styling (#141) 2023-11-09 16:40:27 -05:00
aleka e09d574d5b show deposit form in mainnet onboarding (#140) 2023-11-09 15:33:16 -05:00
Bill 944fc6dc95 Handle squid rout errors (#139)
* Handle squid route errors

* bump abacus

* add dep

* address comments

* fix max

* disable slippage editor

* parse error message in abacus
2023-11-09 10:34:22 -08:00
aleka 91a97a1c68 add network select menu in restriction modals (dev) (#137) 2023-11-09 09:10:12 -05:00
aleka c5f736d805 fix deposit dialog logic (#136) 2023-11-08 14:01:16 -05:00
aleka 3769f7078c update readme re env mode (#133) 2023-11-07 20:28:56 -08:00
Jared Vu edc9fadfee Add TestFlags provider and class (#132)
* Add TestFlags provider and class

* import order nit

* markets is an object and not array

* Use null coalescing op
2023-11-07 20:28:42 -08:00
aleka 5e2d426cd1 Send native tokens inclusive fee (#118)
* send dv4tnt inclusive of fees
2023-11-07 22:42:41 -05:00
Bill 766209baf1 Onboarding fixes (#131)
* Onboarding fixes

* address comments

* rebase
2023-11-07 17:18:16 -08:00
aleka 906faa554d Surface close position input errors (#130)
* show abacus close position validation errors

* bump abacus version
2023-11-07 19:11:08 -05:00
John Huang c339eeccde TRCL-3077 Added an environment for testing. Expected behavior - when "v4 Staging Forced Update" is selected in iOS app, it should switch to the forced update screen (#99) 2023-11-07 13:33:06 -08:00
aleka bd03fb73ca update mintscan tx link on transfer history table (#128)
* update mintscan tx link on transfer history table

* bump localization + fix icon button padding in header
2023-11-07 16:00:22 -05:00
Rui 31825a8a52 Change "iOS" to "ios" for consistency (#129) 2023-11-07 11:01:41 -08:00
John Huang 8d5bf1a721 TRCL-3128 TradePlaceOrder and TradeCancelOrder are now tracked by Abacus (#115) 2023-11-07 10:34:06 -08:00
aleka 7f3d57b46a support multiple modes (#125) 2023-11-07 12:13:59 -05:00
Bill c292c84c2c Fix decimal overflow bug (#127)
* Fix decimal overflow bug

* use decimals:
2023-11-06 17:48:19 -08:00
Bill 2d37ff676b do not use TESTNET_CHAIN_ID (#126) 2023-11-06 17:39:02 -08:00
Rui 68f3552569 Add app configuration to env.json (#121) 2023-11-06 13:02:38 -08:00
aleka 18b12591ca Update LICENSE (#123) 2023-11-06 11:10:31 -08:00
Bill 3f963ffb07 Add Env var descriptions to readme (#124)
* Add Env var descriptions to readme

* update

* remove examples

* grammar
2023-11-06 10:50:45 -08:00
aleka aac024fd5e showing negative buying power as - (#119) 2023-11-06 13:31:41 -05:00
Christopher-Li 4913c690ec Update all dev4 endpoints to use https and wss (#117)
* Update all dev endpoints to use https and wss

* dev4
2023-11-06 09:33:22 -08:00
Bill b0db577b28 Configurable squid integrator id (#120)
* Configurable squid integrator id

* bump abacus
2023-11-03 14:18:15 -07:00
Bill 9815437a80 Account dropdown onboarding entrypoints (#113)
* Account dropdown onboarding entrypoints

* Update based on latest designs
2023-10-31 14:29:36 -07:00
aleka 890a4b2c0e Padding fixes, markets data null fix, update .env.example (#112)
* update .env.example for token migration

* bump icon size in icon button

* add padding in rewards / fees page, panel changes

* fix markets data crashing

* fix market details overflow on tablet

* fix market filters

* prevent fees table overflow

* remove notifications close button on mobile

* fix nested button console warning

* update ToggleGroup value change logic

* panel hover impact button hover

* update dropdown icon in header
2023-10-31 17:11:46 -04:00
Bill 8d3cc76d14 Configurable URLs (#107)
* Configurable URLs

* add learnmore to tooltip

* Learnmore -> LearnMore
2023-10-31 11:02:45 -07:00
Adam Fraser c7ad4b3028 Remove DSRV from Testnet node config options (#108)
* Remove DSRV from Testnet node config options

* Add Bware to testnet node config
2023-10-31 10:52:49 -07:00
Rui c88d5dd411 Add Android config to wallets.json (#114) 2023-10-31 09:35:59 -07:00
Jared Vu d6ab547055 Update README.md (#111)
* Add README in scripts directory

* Add Cloudflare instructions to README
2023-10-30 15:17:12 -07:00
aleka 2fe6c2bb3b reorder header, center align header, update collapse caret icons (#110) 2023-10-27 23:32:51 -04:00
aleka e6858ca917 show loading state instead of "Unavailable" for place order button (#104)
* show loading instead of unavailable for place order button
2023-10-27 17:39:12 -04:00
aleka d92b49f4fa bump packages, fix missing asset symbol (#106) 2023-10-27 16:47:34 -04:00
aleka e7da21962a add entry point to token migration (#98)
* update migrate panel

* address feedback
2023-10-27 16:14:34 -04:00
aleka b479531e34 update v4 docs link (#102) 2023-10-27 16:13:48 -04:00
Bill 0d4c5a547a Abort key derivation if second signature fails (#109) 2023-10-27 11:41:00 -07:00
Rui 5b235ee53f Add link to help page (#103) 2023-10-27 09:15:31 -07:00
94 changed files with 1896 additions and 989 deletions
+7 -2
View File
@@ -4,6 +4,11 @@ VITE_ALCHEMY_API_KEY=
VITE_PK_ENCRYPTION_KEY=
VITE_WALLETCONNECT2_PROJECT_ID=
VITE_V3_TOKEN_ADDRESS=
VITE_TOKEN_MIGRATION_URI=
VITE_V3_TOKEN_ADDRESS=
AMPLITUDE_API_KEY=
BUGSNAG_API_KEY=
IOS_APP_ID=
INTERCOM_APP_ID=
STATUS_PAGE_SCRIPT_URI=
+4 -1
View File
@@ -1,6 +1,9 @@
Copyright (C) 2023 dYdX Trading Inc.
Subject to your compliance with applicable law, you are granted the right to use the Licensed Work (defined below) under the terms of the GNU Affero General Public License as set forth below; provided, however, that if you violate any such applicable law in your use of the Licensed Work, all of your rights and licenses to use (including any rights to reproduce, distribute, install or modify) the Licensed Work will automatically and immediately terminate.
Subject to your compliance with applicable law and the v4 Terms of Use, available at dydx.exchange/legal, you are granted the right to use the Program or Licensed Work (defined below) under the terms of the GNU Affero General Public License as set forth below; provided, however, that if you violate any such applicable law in your use of the Program or Licensed Work, all of your rights and licenses to use (including any rights to reproduce, distribute, install or modify) the Program or Licensed Work will automatically and immediately terminate.
The “Program” or “Licensed Work” shall mean any of the following: dydxprotocol/cosmos-sdk, dydxprotocol/cometbft, dydxprotocol/v4-chain, dydxprotocol/v4-clients, dydxprotocol/v4-web, dydxprotocol/v4-abacus, dydxprotocol/v4-localization, dydxprotocol/v4-documentation, and any dYdX or dYdX Trading Inc. repository reflecting a copy of, or link to, this license.
The GNU Affero General Public License
+41 -4
View File
@@ -26,7 +26,7 @@ Alternatively, follow the [IPFS Kubo installation guide](https://docs.ipfs.tech
## Part 1: Setting up your local environment
### Step 1: Clone the repo
### 1. Clone the repo
Clone the repository and navigate to its directory:
@@ -35,7 +35,7 @@ git clone https://github.com/dydxprotocol/v4-web.git
cd v4-web
```
### Step 2: Install pnpm and dependencies
### 2. Install pnpm and dependencies
Install pnpm and the project dependencies:
@@ -69,7 +69,24 @@ You'll need to provide a Wallet Connect project id to enable onboarding and wall
- Create a project on https://cloud.walletconnect.com/app
- Copy over the project ID into this [field](https://github.com/dydxprotocol/v4-web/blob/67ecbd75b43e0c264b7b4d2d9b3d969830b0621c/public/configs/env.json#L822C33-L822C46)
## Part 4: Deploying with Vercel
## Part 4: Set Enviornment variables
Set environment variables via `.env`.
- `VITE_BASE_URL` (required): The base URL of the deployment (e.g., `https://www.example.com`).
- `VITE_ALCHEMY_API_KEY` (optional): Add an Alchemy API key for EVM interactions; the app will fall back to public RPCs if not provided.
- `VITE_PK_ENCRYPTION_KEY` (optional): AES encryption key used for signature obfuscation; necessary for enabling the "Remember Me" feature.
- `VITE_V3_TOKEN_ADDRESS` (optional): Address of the V3 $DYDX token.
- `VITE_TOKEN_MIGRATION_URI` (optional): The URL of the token migration website.
- `AMPLITUDE_API_KEY` (optional): Amplitude API key for enabling Amplitude; used with `pnpm run build:inject-amplitude`.
- `BUGSNAG_API_KEY` (optional): API key for enabling Bugsnag; used with `pnpm run build:inject-bugsnag`.
- `IOS_APP_ID` (optional): iOS app ID used for enabling deep linking to the iOS app; used with `pnpm run build:inject-app-deeplinks`.
- `INTERCOM_APP_ID` (optional): Used for enabling Intercom; utilized with `pnpm run build:inject-intercom`.
- `STATUS_PAGE_SCRIPT_URI` (optional): Used for enabling the status page; used with `pnpm run build:inject-statuspage`.
# Deployments
## Deploying with Vercel
### Step 1: Connect your repository to Vercel
@@ -81,12 +98,17 @@ For the "Build & Development Settings", we recommend the following:
- Framework Preset: `Vite`
- Build Command (override): `pnpm run build`
By default, the dev server runs in development mode and the build command runs in production mode. To override the default mode, you can pass in the `--mode` option flag. For example, if you want to build your app for testnet:
```
pnpm run build --mode testnet
```
If you wish to incorporate analytics via Amplitude and Bugsnag, you can use our scripts:
`pnpm run build:inject-amplitude` and `pnpm run build:inject-bugsnag`. You will need to provide your own API keys for these services. In the Environment Variables section, name the variables as `AMPLITUDE_API_KEY` and `BUGSNAG_API_KEY` and provide the respective keys as their values.
For more details, check out Vercel's [official documentation](https://vercel.com/docs).
## Part 5: Deploying to IPFS
## Deploying to IPFS
### web3.storage: deploy to IPFS via web3.storage using the provided script
@@ -118,3 +140,18 @@ To access your content on IPFS:
2. **Public IPFS gateway:** Access your content via a public IPFS gateway, such as [https://dweb.link](https://dweb.link/) or [https://w3s.link/](https://w3s.link/). Use the gateway URL with your CID appended, like `https://dweb.link/ipfs/your_cid`.
Replace `your_cid` with the actual CID.
## Cloudflare Settings
We recommend that you add your website to Cloudflare for additional security settings.
To block OFAC Sanctioned countries:
1. Navigate Websites > Domain > Security > WAF
2. Create Rule with the following settings:
* If incoming requests match
`(ip.geoip.country eq "CU") or (ip.geoip.country eq "IR") or (ip.geoip.country eq "KP") or (ip.geoip.country eq "SY") or (ip.geoip.country eq "MM") or (ip.geoip.subdivision_1_iso_code eq "UA-09") or (ip.geoip.subdivision_1_iso_code eq "UA-14") or (ip.geoip.subdivision_1_iso_code eq "UA-43")`
* This rule will bring up a Cloudflare page when a restricted geography tries to access your site. You will have the option to display:
1. Custom Text
- (e.g. `Because you appear to be a resident of, or trading from, a jurisdiction that violates our terms of use, or have engaged in activity that violates our terms of use, you have been blocked. You may withdraw your funds from the protocol at any time.`)
2. Default Cloudflare WAF block page
+4 -3
View File
@@ -39,9 +39,9 @@
"@cosmjs/proto-signing": "^0.31.0",
"@cosmjs/stargate": "^0.31.0",
"@cosmjs/tendermint-rpc": "^0.31.0",
"@dydxprotocol/v4-abacus": "^1.0.3",
"@dydxprotocol/v4-client-js": "^0.40.3",
"@dydxprotocol/v4-localization": "^0.1.32",
"@dydxprotocol/v4-abacus": "^1.0.24",
"@dydxprotocol/v4-client-js": "^1.0.0",
"@dydxprotocol/v4-localization": "^1.0.5",
"@ethersproject/providers": "^5.7.2",
"@js-joda/core": "^5.5.3",
"@radix-ui/react-collapsible": "^1.0.3",
@@ -96,6 +96,7 @@
"long": "^5.2.3",
"luxon": "^3.3.0",
"qr-code-styling": "1.6.0-rc.1",
"query-string": "^8.1.0",
"react": "^18.2.0",
"react-aria": "^3.25.0",
"react-dom": "^18.2.0",
+18 -19
View File
@@ -27,14 +27,14 @@ dependencies:
specifier: ^0.31.0
version: 0.31.0
'@dydxprotocol/v4-abacus':
specifier: ^1.0.3
version: 1.0.3
specifier: ^1.0.24
version: 1.0.24
'@dydxprotocol/v4-client-js':
specifier: ^0.40.3
version: 0.40.3
specifier: ^1.0.0
version: 1.0.0
'@dydxprotocol/v4-localization':
specifier: ^0.1.32
version: 0.1.32
specifier: ^1.0.5
version: 1.0.5
'@ethersproject/providers':
specifier: ^5.7.2
version: 5.7.2
@@ -197,6 +197,9 @@ dependencies:
qr-code-styling:
specifier: 1.6.0-rc.1
version: 1.6.0-rc.1
query-string:
specifier: ^8.1.0
version: 8.1.0
react:
specifier: ^18.2.0
version: 18.2.0
@@ -979,12 +982,12 @@ packages:
resolution: {integrity: sha512-RpfLEtTlyIxeNPGKcokS+p3BZII/Q3bYxryFRglh5H3A3T8q9fsLYm72VYAMEOOIBLEa8o93kFLiBDUWKrwXZA==}
dev: true
/@dydxprotocol/v4-abacus@1.0.3:
resolution: {integrity: sha512-GuX37/DMMNSke8ZFcw52II7IVJfUgVGHqoi1Uw2cUb+hgIjjSG3OtbyRWedm5r6nqWq8BNLOexI0VVFB6OMVYg==}
/@dydxprotocol/v4-abacus@1.0.24:
resolution: {integrity: sha512-wDGSjkrc3Se6Ev7UTjPgJV7PiyzZSz2mJwOTZikLwH7W3k1iPYGQmaCd7TudFk8h2aSdlEwNsQBCf0sLoyvHaQ==}
dev: false
/@dydxprotocol/v4-client-js@0.40.3:
resolution: {integrity: sha512-nMQd6tYisKDKIbfx0BGJSYEOSt+I+t5SsaBSmlgTdso+w2rCRO9vyxS+u6MF9h4w5FsVRfhHo3e6uTWX48WpGQ==}
/@dydxprotocol/v4-client-js@1.0.0:
resolution: {integrity: sha512-ehfHO+zQy795TcJRwtiawadFHZyh4HnpJNP26hCGsIjLE5q6LLHweQHpK/1N/sXU1PBOuQwc7iaJnFop6gYauQ==}
dependencies:
'@cosmjs/amino': 0.30.1
'@cosmjs/encoding': 0.31.1
@@ -1011,8 +1014,8 @@ packages:
- utf-8-validate
dev: false
/@dydxprotocol/v4-localization@0.1.32:
resolution: {integrity: sha512-ZtXScxgFLjUt0Ag52RyFnQe9aEl1Aky5fp+vMGOBduVkFiCEMRMkSsSgg6grMdyw/x0AbnxOTRkhYoX2MsK9Ow==}
/@dydxprotocol/v4-localization@1.0.5:
resolution: {integrity: sha512-zZm3GFp/ORz9YjigQFVBlcWmaxYY+XEdIw8AWN5nEbsuiA2Jay+/OA7lO9+nV1J1p1T+TgLo9iczIHJsAo3IsA==}
dev: false
/@dydxprotocol/v4-proto@0.4.1:
@@ -7656,7 +7659,7 @@ packages:
resolution: {integrity: sha512-WIdaQ8uW1vIbYvNnAVunkC6yxTrneJC7VQ5UUQ0kuw8b0C0A39KTIpoQHCfc8tV7o9vF4niwRhdXEdfAgQEsQQ==}
dependencies:
cosmos-directory-types: 0.0.6
node-fetch-native: 1.4.0
node-fetch-native: 1.4.1
dev: false
/cosmos-directory-types@0.0.6:
@@ -7875,7 +7878,6 @@ packages:
/decode-uri-component@0.4.1:
resolution: {integrity: sha512-+8VxcR21HhTy8nOt6jf20w0c9CADrw1O8d+VZ/YzzCt4bJ3uBjw+D1q2osAB8RnpwwaeYBxy0HyKQxD5JBMuuQ==}
engines: {node: '>=14.16'}
dev: true
/deep-eql@4.1.3:
resolution: {integrity: sha512-WaEtAOpRA1MQ0eohqZjpGD8zdI0Ovsm8mmFhaDN8dvDZzyoUMcYDnf5Y6iu7HTXxf8JDS23qWa4a+hKCDyOPzw==}
@@ -8945,7 +8947,6 @@ packages:
/filter-obj@5.1.0:
resolution: {integrity: sha512-qWeTREPoT7I0bifpPUXtxkZJ1XJzxWtfoWWkdVGqa+eCr3SHW/Ocp89o8vLvbUuQnadybJpjOKu4V+RwO6sGng==}
engines: {node: '>=14.16'}
dev: true
/find-cache-dir@3.3.2:
resolution: {integrity: sha512-wXZV5emFEjrridIgED11OoUKLxiYjAcqot/NJdAkOhlJ+vGzwhOAfcG5OX1jP+S0PcjEn8bdMJv+g2jwQ3Onig==}
@@ -11287,8 +11288,8 @@ packages:
engines: {node: '>=10.5.0'}
dev: true
/node-fetch-native@1.4.0:
resolution: {integrity: sha512-F5kfEj95kX8tkDhUCYdV8dg3/8Olx/94zB8+ZNthFs6Bz31UpUi8Xh40TN3thLwXgrwXry1pEg9lJ++tLWTcqA==}
/node-fetch-native@1.4.1:
resolution: {integrity: sha512-NsXBU0UgBxo2rQLOeWNZqS3fvflWePMECr8CoSWoSTqCqGbVVsvl9vZu1HfQicYN0g5piV9Gh8RTEvo/uP752w==}
dev: false
/node-fetch@2.6.12:
@@ -11876,7 +11877,6 @@ packages:
decode-uri-component: 0.4.1
filter-obj: 5.1.0
split-on-first: 3.0.0
dev: true
/queue-microtask@1.2.3:
resolution: {integrity: sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A==}
@@ -12701,7 +12701,6 @@ packages:
/split-on-first@3.0.0:
resolution: {integrity: sha512-qxQJTx2ryR0Dw0ITYyekNQWpz6f8dGd7vffGNflQQ3Iqj9NJ6qiZ7ELpZsJ/QBhIVAiDfXdag3+Gp8RvWa62AA==}
engines: {node: '>=12'}
dev: true
/split2@4.2.0:
resolution: {integrity: sha512-UcjcJOWknrNkF6PLX83qcHM6KHgVKNkV62Y8a5uYDVv9ydGQVwAHMKqHdJje1VTWpljG0WYpCDhrCdAOYH4TWg==}
+317 -87
View File
@@ -1,4 +1,9 @@
{
"apps": {
"ios": {
"scheme": "dydxv4"
}
},
"deployments": {
"MAINNET": {
"environments": [
@@ -22,11 +27,11 @@
"dydxprotocol-staging-west",
"dydxprotocol-testnet",
"dydxprotocol-testnet-dydx",
"dydxprotocol-testnet-dsrv",
"dydxprotocol-testnet-nodefleet",
"dydxprotocol-testnet-kingnodes",
"dydxprotocol-testnet-liquify",
"dydxprotocol-testnet-polkachu"
"dydxprotocol-testnet-polkachu",
"dydxprotocol-testnet-bware"
],
"default": "dydxprotocol-testnet"
}
@@ -38,6 +43,7 @@
"dydxChainId": "dydxprotocol-testnet",
"chainName": "dYdX Chain",
"chainLogo": "dydx-chain.png",
"squidIntegratorId": "dYdX-api",
"isMainNet": false,
"tokens": {
"chain": {
@@ -71,7 +77,19 @@
"tos": "https://dydx.exchange/v4-terms",
"privacy": "https://dydx.exchange/privacy",
"mintscan": "https://testnet.mintscan.io/dydx-testnet/txs/{tx_hash}",
"blogs": "https://www.dydx.foundation/blog"
"blogs": "https://www.dydx.foundation/blog",
"foundation": "https://www.dydx.foundation",
"help": "https://help.dydx.exchange/",
"initialMarginFractionLearnMore": "https://help.dydx.exchange/articles/5232637-maximum-position-sizes",
"reduceOnlyLearnMore": "https://help.dydx.exchange/articles/6345793-reduce-only-orders",
"mintscanBase": "https://testnet.mintscan.io/dydx-testnet",
"documentation": "https://docs.dydx.exchange/",
"community": "https://discord.com/invite/dydx",
"governanceLearnMore": "https://help.dydx.exchange",
"stakingLearnMore": "https://help.dydx.exchange",
"keplrDashboard": "https://testnet.keplr.app/",
"accountExportLearnMore": "https://help.dydx.exchange",
"walletLearnMore": "https://www.dydx.academy/video/defi-wallet"
},
"wallets": {
"walletconnect": {
@@ -98,6 +116,7 @@
"dydxChainId": "dydxprotocol-testnet",
"chainName": "dYdX Chain",
"chainLogo": "dydx-chain.png",
"squidIntegratorId": "dYdX-api",
"isMainNet": false,
"tokens": {
"chain": {
@@ -130,7 +149,19 @@
"tos": "https://dydx.exchange/v4-terms",
"privacy": "https://dydx.exchange/privacy",
"mintscan": "https://testnet.mintscan.io/dydx-testnet/txs/{tx_hash}",
"blogs": "https://www.dydx.foundation/blog"
"blogs": "https://www.dydx.foundation/blog",
"foundation": "https://www.dydx.foundation",
"help": "https://help.dydx.exchange/",
"initialMarginFractionLearnMore": "https://help.dydx.exchange/articles/5232637-maximum-position-sizes",
"reduceOnlyLearnMore": "https://help.dydx.exchange/articles/6345793-reduce-only-orders",
"mintscanBase": "https://testnet.mintscan.io/dydx-testnet",
"documentation": "https://docs.dydx.exchange/",
"community": "https://discord.com/invite/dydx",
"governanceLearnMore": "https://help.dydx.exchange",
"stakingLearnMore": "https://help.dydx.exchange",
"keplrDashboard": "https://testnet.keplr.app/",
"accountExportLearnMore": "https://help.dydx.exchange",
"walletLearnMore": "https://www.dydx.academy/video/defi-wallet"
},
"wallets": {
"walletconnect": {
@@ -157,6 +188,7 @@
"dydxChainId": "dydxprotocol-testnet",
"chainName": "dYdX Chain",
"chainLogo": "dydx-chain.png",
"squidIntegratorId": "dYdX-api",
"isMainNet": false,
"tokens": {
"chain": {
@@ -176,8 +208,8 @@
"endpoints": {
"indexers": [
{
"api": "http://indexer.v4dev4.dydx.exchange",
"socket": "ws://indexer.v4dev4.dydx.exchange"
"api": "https://indexer.v4dev4.dydx.exchange",
"socket": "wss://indexer.v4dev4.dydx.exchange"
}
],
"validators": [
@@ -189,7 +221,19 @@
"tos": "https://dydx.exchange/v4-terms",
"privacy": "https://dydx.exchange/privacy",
"mintscan": "https://testnet.mintscan.io/dydx-testnet/txs/{tx_hash}",
"blogs": "https://www.dydx.foundation/blog"
"blogs": "https://www.dydx.foundation/blog",
"foundation": "https://www.dydx.foundation",
"help": "https://help.dydx.exchange/",
"initialMarginFractionLearnMore": "https://help.dydx.exchange/articles/5232637-maximum-position-sizes",
"reduceOnlyLearnMore": "https://help.dydx.exchange/articles/6345793-reduce-only-orders",
"mintscanBase": "https://testnet.mintscan.io/dydx-testnet",
"documentation": "https://docs.dydx.exchange/",
"community": "https://discord.com/invite/dydx",
"governanceLearnMore": "https://help.dydx.exchange",
"stakingLearnMore": "https://help.dydx.exchange",
"keplrDashboard": "https://testnet.keplr.app/",
"accountExportLearnMore": "https://help.dydx.exchange",
"walletLearnMore": "https://www.dydx.academy/video/defi-wallet"
},
"wallets": {
"walletconnect": {
@@ -216,6 +260,7 @@
"dydxChainId": "dydxprotocol-testnet",
"chainName": "dYdX Chain",
"chainLogo": "dydx-chain.png",
"squidIntegratorId": "dYdX-api",
"isMainNet": false,
"tokens": {
"chain": {
@@ -248,7 +293,19 @@
"tos": "https://dydx.exchange/v4-terms",
"privacy": "https://dydx.exchange/privacy",
"mintscan": "https://testnet.mintscan.io/dydx-testnet/txs/{tx_hash}",
"blogs": "https://www.dydx.foundation/blog"
"blogs": "https://www.dydx.foundation/blog",
"foundation": "https://www.dydx.foundation",
"help": "https://help.dydx.exchange/",
"initialMarginFractionLearnMore": "https://help.dydx.exchange/articles/5232637-maximum-position-sizes",
"reduceOnlyLearnMore": "https://help.dydx.exchange/articles/6345793-reduce-only-orders",
"mintscanBase": "https://testnet.mintscan.io/dydx-testnet",
"documentation": "https://docs.dydx.exchange/",
"community": "https://discord.com/invite/dydx",
"governanceLearnMore": "https://help.dydx.exchange",
"stakingLearnMore": "https://help.dydx.exchange",
"keplrDashboard": "https://testnet.keplr.app/",
"accountExportLearnMore": "https://help.dydx.exchange",
"walletLearnMore": "https://www.dydx.academy/video/defi-wallet"
},
"wallets": {
"walletconnect": {
@@ -275,6 +332,80 @@
"dydxChainId": "dydxprotocol-testnet",
"chainName": "dYdX Chain",
"chainLogo": "dydx-chain.png",
"squidIntegratorId": "dYdX-api",
"isMainNet": false,
"tokens": {
"chain": {
"name": "Dv4TNT",
"denom": "adv4tnt",
"decimals": 18,
"image": "/currencies/dydx.png"
},
"usdc": {
"name": "USDC",
"denom": "ibc/8E27BA2D5493AF5636760E354E46004562C46AB7EC0CC4C1CA14E9E20E2545B5",
"gasDenom": "uusdc",
"decimals": 6,
"image": "/currencies/usdc.png"
}
},
"endpoints": {
"indexers": [
{
"api": "https://indexer.v4staging.dydx.exchange",
"socket": "wss://indexer.v4staging.dydx.exchange"
}
],
"faucet": "https://faucet.v4staging.dydx.exchange",
"validators": [
"https://validator.v4staging.dydx.exchange"
],
"0xsquid": "https://testnet.api.squidrouter.com"
},
"links": {
"tos": "https://dydx.exchange/v4-terms",
"privacy": "https://dydx.exchange/privacy",
"mintscan": "https://testnet.mintscan.io/dydx-testnet/txs/{tx_hash}",
"documentation": "https://docs.dydx.exchange/",
"community": "https://discord.com/invite/dydx",
"feedback": "https://docs.google.com/forms/d/e/1FAIpQLSezLsWCKvAYDEb7L-2O4wOON1T56xxro9A2Azvl6IxXHP_15Q/viewform",
"blogs": "https://www.dydx.foundation/blog",
"help": "https://help.dydx.exchange",
"foundation": "https://www.dydx.foundation",
"initialMarginFractionLearnMore": "https://help.dydx.exchange/articles/5232637-maximum-position-sizes",
"reduceOnlyLearnMore": "https://help.dydx.exchange/articles/6345793-reduce-only-orders",
"mintscanBase": "https://testnet.mintscan.io/dydx-testnet",
"governanceLearnMore": "https://help.dydx.exchange",
"stakingLearnMore": "https://help.dydx.exchange",
"keplrDashboard": "https://testnet.keplr.app/",
"accountExportLearnMore": "https://help.dydx.exchange",
"walletLearnMore": "https://www.dydx.academy/video/defi-wallet"
},
"wallets": {
"walletconnect": {
"client": {
"name": "dYdX v4",
"description": "dYdX v4 App",
"iconUrl": "/logos/dydx-x.png"
},
"v2": {
"projectId": "47559b2ec96c09aed9ff2cb54a31ab0e"
}
},
"walletSegue": {
"callbackUrl": "/walletsegue"
},
"images": "/wallets/",
"signTypedDataAction": "dYdX Chain Onboarding",
"signTypedDataDomainName": "dYdX Chain"
}
},
"dydxprotocol-staging-forced-update": {
"name": "v4 Staging Forced Update",
"ethereumChainId": "5",
"dydxChainId": "dydxprotocol-testnet",
"chainName": "dYdX Chain",
"chainLogo": "dydx-chain.png",
"isMainNet": false,
"tokens": {
"chain": {
@@ -308,6 +439,7 @@
"tos": "https://dydx.exchange/v4-terms",
"privacy": "https://dydx.exchange/privacy",
"mintscan": "https://testnet.mintscan.io/dydx-testnet/txs/{tx_hash}",
"mintscanBase": "https://testnet.mintscan.io/dydx-testnet",
"documentation": "https://v4-teacher.vercel.app/",
"community": "https://discord.com/invite/dydx",
"feedback": "https://docs.google.com/forms/d/e/1FAIpQLSezLsWCKvAYDEb7L-2O4wOON1T56xxro9A2Azvl6IxXHP_15Q/viewform",
@@ -330,6 +462,13 @@
"images": "/wallets/",
"signTypedDataAction": "dYdX Chain Onboarding",
"signTypedDataDomainName": "dYdX Chain"
},
"apps": {
"ios": {
"minimalVersion": "1.0",
"build":40000,
"url": "https://apps.apple.com/app/dydx/id1564787350"
}
}
},
"dydxprotocol-staging-west": {
@@ -338,6 +477,7 @@
"dydxChainId": "dydxprotocol-testnet",
"chainName": "dYdX Chain",
"chainLogo": "dydx-chain.png",
"squidIntegratorId": "dYdX-api",
"isMainNet": false,
"tokens": {
"chain": {
@@ -371,10 +511,20 @@
"tos": "https://dydx.exchange/v4-terms",
"privacy": "https://dydx.exchange/privacy",
"mintscan": "https://testnet.mintscan.io/dydx-testnet/txs/{tx_hash}",
"documentation": "https://v4-teacher.vercel.app/",
"documentation": "https://docs.dydx.exchange/",
"community": "https://discord.com/invite/dydx",
"feedback": "https://docs.google.com/forms/d/e/1FAIpQLSezLsWCKvAYDEb7L-2O4wOON1T56xxro9A2Azvl6IxXHP_15Q/viewform",
"blogs": "https://www.dydx.foundation/blog"
"blogs": "https://www.dydx.foundation/blog",
"help": "https://help.dydx.exchange",
"foundation": "https://www.dydx.foundation",
"initialMarginFractionLearnMore": "https://help.dydx.exchange/articles/5232637-maximum-position-sizes",
"reduceOnlyLearnMore": "https://help.dydx.exchange/articles/6345793-reduce-only-orders",
"mintscanBase": "https://testnet.mintscan.io/dydx-testnet",
"governanceLearnMore": "https://help.dydx.exchange",
"stakingLearnMore": "https://help.dydx.exchange",
"keplrDashboard": "https://testnet.keplr.app/",
"accountExportLearnMore": "https://help.dydx.exchange",
"walletLearnMore": "https://www.dydx.academy/video/defi-wallet"
},
"wallets": {
"walletconnect": {
@@ -401,6 +551,7 @@
"dydxChainId": "dydx-testnet-4",
"chainName": "dYdX Chain",
"chainLogo": "dydx-chain.png",
"squidIntegratorId": "dYdX-api",
"isMainNet": false,
"tokens": {
"chain": {
@@ -425,6 +576,7 @@
}
],
"validators": [
"https://dydx-testnet-full-rpc.public.blastapi.io/",
"https://dydx-testnet-rpc.polkachu.com/",
"https://dydx-testnet.nodefleet.org",
"https://test-dydx.kingnodes.com",
@@ -437,10 +589,20 @@
"tos": "https://dydx.exchange/v4-terms",
"privacy": "https://dydx.exchange/privacy",
"mintscan": "https://testnet.mintscan.io/dydx-testnet/txs/{tx_hash}",
"documentation": "https://v4-teacher.vercel.app/",
"documentation": "https://docs.dydx.exchange/",
"community": "https://discord.com/invite/dydx",
"feedback": "https://docs.google.com/forms/d/e/1FAIpQLSezLsWCKvAYDEb7L-2O4wOON1T56xxro9A2Azvl6IxXHP_15Q/viewform",
"blogs": "https://www.dydx.foundation/blog"
"blogs": "https://www.dydx.foundation/blog",
"foundation": "https://www.dydx.foundation",
"help": "https://help.dydx.exchange/",
"initialMarginFractionLearnMore": "https://help.dydx.exchange/articles/5232637-maximum-position-sizes",
"reduceOnlyLearnMore": "https://help.dydx.exchange/articles/6345793-reduce-only-orders",
"mintscanBase": "https://testnet.mintscan.io/dydx-testnet",
"governanceLearnMore": "https://help.dydx.exchange",
"stakingLearnMore": "https://help.dydx.exchange",
"keplrDashboard": "https://testnet.keplr.app/",
"accountExportLearnMore": "https://help.dydx.exchange",
"walletLearnMore": "https://www.dydx.academy/video/defi-wallet"
},
"wallets": {
"walletconnect": {
@@ -467,6 +629,7 @@
"dydxChainId": "dydx-testnet-4",
"chainName": "dYdX Chain",
"chainLogo": "dydx-chain.png",
"squidIntegratorId": "dYdX-api",
"isMainNet": false,
"tokens": {
"chain": {
@@ -501,74 +664,20 @@
"privacy": "https://dydx.exchange/privacy",
"statusPage": "https://status.v4testnet.dydx.exchange/",
"mintscan": "https://testnet.mintscan.io/dydx-testnet/txs/{tx_hash}",
"documentation": "https://v4-teacher.vercel.app/",
"documentation": "https://docs.dydx.exchange/",
"community": "https://discord.com/invite/dydx",
"feedback": "https://docs.google.com/forms/d/e/1FAIpQLSezLsWCKvAYDEb7L-2O4wOON1T56xxro9A2Azvl6IxXHP_15Q/viewform",
"blogs": "https://www.dydx.foundation/blog"
},
"wallets": {
"walletconnect": {
"client": {
"name": "dYdX v4",
"description": "dYdX v4 App",
"iconUrl": "/logos/dydx-x.png"
},
"v2": {
"projectId": "47559b2ec96c09aed9ff2cb54a31ab0e"
}
},
"walletSegue": {
"callbackUrl": "/walletsegue"
},
"images": "/wallets/",
"signTypedDataAction": "dYdX Chain Onboarding",
"signTypedDataDomainName": "dYdX V4"
}
},
"dydxprotocol-testnet-dsrv": {
"name": "v4 Public Testnet/DSRV",
"ethereumChainId": "5",
"dydxChainId": "dydx-testnet-4",
"chainName": "dYdX Chain",
"chainLogo": "dydx-chain.png",
"isMainNet": false,
"tokens": {
"chain": {
"name": "Dv4TNT",
"denom": "adv4tnt",
"decimals": 18,
"image": "/currencies/dydx.png"
},
"usdc": {
"name": "USDC",
"denom": "ibc/8E27BA2D5493AF5636760E354E46004562C46AB7EC0CC4C1CA14E9E20E2545B5",
"gasDenom": "uusdc",
"decimals": 6,
"image": "/currencies/usdc.png"
}
},
"endpoints": {
"indexers": [
{
"api": "https://dydx-testnet.imperator.co",
"socket": "wss://dydx-testnet.imperator.co"
}
],
"validators": [
"https://dydx-testnet-archive.allthatnode.com:26657/XZvMM41hESf8PJrEQiTzbCOMVyFca79R"
],
"0xsquid": "https://testnet.api.squidrouter.com",
"faucet": "https://faucet.v4testnet.dydx.exchange"
},
"links": {
"tos": "https://dydx.exchange/v4-terms",
"privacy": "https://dydx.exchange/privacy",
"statusPage": "https://status.v4testnet.dydx.exchange/",
"mintscan": "https://testnet.mintscan.io/dydx-testnet/txs/{tx_hash}",
"documentation": "https://v4-teacher.vercel.app/",
"community": "https://discord.com/invite/dydx",
"feedback": "https://docs.google.com/forms/d/e/1FAIpQLSezLsWCKvAYDEb7L-2O4wOON1T56xxro9A2Azvl6IxXHP_15Q/viewform",
"blogs": "https://www.dydx.foundation/blog"
"blogs": "https://www.dydx.foundation/blog",
"foundation": "https://www.dydx.foundation",
"help": "https://help.dydx.exchange/",
"initialMarginFractionLearnMore": "https://help.dydx.exchange/articles/5232637-maximum-position-sizes",
"reduceOnlyLearnMore": "https://help.dydx.exchange/articles/6345793-reduce-only-orders",
"mintscanBase": "https://testnet.mintscan.io/dydx-testnet",
"governanceLearnMore": "https://help.dydx.exchange",
"stakingLearnMore": "https://help.dydx.exchange",
"keplrDashboard": "https://testnet.keplr.app/",
"accountExportLearnMore": "https://help.dydx.exchange",
"walletLearnMore": "https://www.dydx.academy/video/defi-wallet"
},
"wallets": {
"walletconnect": {
@@ -595,6 +704,7 @@
"dydxChainId": "dydx-testnet-4",
"chainName": "dYdX Chain",
"chainLogo": "dydx-chain.png",
"squidIntegratorId": "dYdX-api",
"isMainNet": false,
"tokens": {
"chain": {
@@ -629,10 +739,20 @@
"privacy": "https://dydx.exchange/privacy",
"statusPage": "https://status.v4testnet.dydx.exchange/",
"mintscan": "https://testnet.mintscan.io/dydx-testnet/txs/{tx_hash}",
"documentation": "https://v4-teacher.vercel.app/",
"documentation": "https://docs.dydx.exchange/",
"community": "https://discord.com/invite/dydx",
"feedback": "https://docs.google.com/forms/d/e/1FAIpQLSezLsWCKvAYDEb7L-2O4wOON1T56xxro9A2Azvl6IxXHP_15Q/viewform",
"blogs": "https://www.dydx.foundation/blog"
"blogs": "https://www.dydx.foundation/blog",
"foundation": "https://www.dydx.foundation",
"help": "https://help.dydx.exchange/",
"initialMarginFractionLearnMore": "https://help.dydx.exchange/articles/5232637-maximum-position-sizes",
"reduceOnlyLearnMore": "https://help.dydx.exchange/articles/6345793-reduce-only-orders",
"mintscanBase": "https://testnet.mintscan.io/dydx-testnet",
"governanceLearnMore": "https://help.dydx.exchange",
"stakingLearnMore": "https://help.dydx.exchange",
"keplrDashboard": "https://testnet.keplr.app/",
"accountExportLearnMore": "https://help.dydx.exchange",
"walletLearnMore": "https://www.dydx.academy/video/defi-wallet"
},
"wallets": {
"walletconnect": {
@@ -659,6 +779,7 @@
"dydxChainId": "dydx-testnet-4",
"chainName": "dYdX Chain",
"chainLogo": "dydx-chain.png",
"squidIntegratorId": "dYdX-api",
"isMainNet": false,
"tokens": {
"chain": {
@@ -693,10 +814,20 @@
"privacy": "https://dydx.exchange/privacy",
"statusPage": "https://status.v4testnet.dydx.exchange/",
"mintscan": "https://testnet.mintscan.io/dydx-testnet/txs/{tx_hash}",
"documentation": "https://v4-teacher.vercel.app/",
"documentation": "https://docs.dydx.exchange/",
"community": "https://discord.com/invite/dydx",
"feedback": "https://docs.google.com/forms/d/e/1FAIpQLSezLsWCKvAYDEb7L-2O4wOON1T56xxro9A2Azvl6IxXHP_15Q/viewform",
"blogs": "https://www.dydx.foundation/blog"
"blogs": "https://www.dydx.foundation/blog",
"foundation": "https://www.dydx.foundation",
"help": "https://help.dydx.exchange/",
"initialMarginFractionLearnMore": "https://help.dydx.exchange/articles/5232637-maximum-position-sizes",
"reduceOnlyLearnMore": "https://help.dydx.exchange/articles/6345793-reduce-only-orders",
"mintscanBase": "https://testnet.mintscan.io/dydx-testnet",
"governanceLearnMore": "https://help.dydx.exchange",
"stakingLearnMore": "https://help.dydx.exchange",
"keplrDashboard": "https://testnet.keplr.app/",
"accountExportLearnMore": "https://help.dydx.exchange",
"walletLearnMore": "https://www.dydx.academy/video/defi-wallet"
},
"wallets": {
"walletconnect": {
@@ -723,6 +854,7 @@
"dydxChainId": "dydx-testnet-4",
"chainName": "dYdX Chain",
"chainLogo": "dydx-chain.png",
"squidIntegratorId": "dYdX-api",
"isMainNet": false,
"tokens": {
"chain": {
@@ -757,10 +889,20 @@
"privacy": "https://dydx.exchange/privacy",
"statusPage": "https://status.v4testnet.dydx.exchange/",
"mintscan": "https://testnet.mintscan.io/dydx-testnet/txs/{tx_hash}",
"documentation": "https://v4-teacher.vercel.app/",
"documentation": "https://docs.dydx.exchange/",
"community": "https://discord.com/invite/dydx",
"feedback": "https://docs.google.com/forms/d/e/1FAIpQLSezLsWCKvAYDEb7L-2O4wOON1T56xxro9A2Azvl6IxXHP_15Q/viewform",
"blogs": "https://www.dydx.foundation/blog"
"blogs": "https://www.dydx.foundation/blog",
"foundation": "https://www.dydx.foundation",
"help": "https://help.dydx.exchange/",
"initialMarginFractionLearnMore": "https://help.dydx.exchange/articles/5232637-maximum-position-sizes",
"reduceOnlyLearnMore": "https://help.dydx.exchange/articles/6345793-reduce-only-orders",
"mintscanBase": "https://testnet.mintscan.io/dydx-testnet",
"governanceLearnMore": "https://help.dydx.exchange",
"stakingLearnMore": "https://help.dydx.exchange",
"keplrDashboard": "https://testnet.keplr.app/",
"accountExportLearnMore": "https://help.dydx.exchange",
"walletLearnMore": "https://www.dydx.academy/video/defi-wallet"
},
"wallets": {
"walletconnect": {
@@ -787,6 +929,7 @@
"dydxChainId": "dydx-testnet-4",
"chainName": "dYdX Chain",
"chainLogo": "dydx-chain.png",
"squidIntegratorId": "dYdX-api",
"isMainNet": false,
"tokens": {
"chain": {
@@ -821,7 +964,8 @@
"privacy": "https://dydx.exchange/privacy",
"statusPage": "https://status.v4testnet.dydx.exchange/",
"mintscan": "https://testnet.mintscan.io/dydx-testnet/txs/{tx_hash}",
"documentation": "https://v4-teacher.vercel.app/",
"mintscanBase": "https://testnet.mintscan.io/dydx-testnet",
"documentation": "https://docs.dydx.exchange/",
"community": "https://discord.com/invite/dydx",
"feedback": "https://docs.google.com/forms/d/e/1FAIpQLSezLsWCKvAYDEb7L-2O4wOON1T56xxro9A2Azvl6IxXHP_15Q/viewform",
"blogs": "https://www.dydx.foundation/blog"
@@ -845,12 +989,88 @@
"signTypedDataDomainName": "dYdX V4"
}
},
"dydxprotocol-testnet-bware": {
"name": "v4 Public Testnet/BWare",
"ethereumChainId": "5",
"dydxChainId": "dydx-testnet-4",
"chainName": "dYdX Chain",
"chainLogo": "dydx-chain.png",
"squidIntegratorId": "dYdX-api",
"isMainNet": false,
"tokens": {
"chain": {
"name": "Dv4TNT",
"denom": "adv4tnt",
"decimals": 18,
"image": "/currencies/dydx.png"
},
"usdc": {
"name": "USDC",
"denom": "ibc/8E27BA2D5493AF5636760E354E46004562C46AB7EC0CC4C1CA14E9E20E2545B5",
"gasDenom": "uusdc",
"decimals": 6,
"image": "/currencies/usdc.png"
}
},
"endpoints": {
"indexers": [
{
"api": "https://dydx-testnet.imperator.co",
"socket": "wss://dydx-testnet.imperator.co"
}
],
"validators": [
"https://dydx-testnet-full-rpc.public.blastapi.io/"
],
"0xsquid": "https://testnet.api.squidrouter.com",
"faucet": "https://faucet.v4testnet.dydx.exchange"
},
"links": {
"tos": "https://dydx.exchange/v4-terms",
"privacy": "https://dydx.exchange/privacy",
"statusPage": "https://status.v4testnet.dydx.exchange/",
"mintscan": "https://testnet.mintscan.io/dydx-testnet/txs/{tx_hash}",
"documentation": "https://docs.dydx.exchange/",
"community": "https://discord.com/invite/dydx",
"feedback": "https://docs.google.com/forms/d/e/1FAIpQLSezLsWCKvAYDEb7L-2O4wOON1T56xxro9A2Azvl6IxXHP_15Q/viewform",
"blogs": "https://www.dydx.foundation/blog",
"foundation": "https://www.dydx.foundation",
"help": "https://help.dydx.exchange/",
"initialMarginFractionLearnmore": "https://help.dydx.exchange/articles/5232637-maximum-position-sizes",
"reduceOnlyLearnmore": "https://help.dydx.exchange/articles/6345793-reduce-only-orders",
"mintscanBase": "https://testnet.mintscan.io/dydx-testnet",
"governanceLearnmore": "https://help.dydx.exchange",
"stakingLearnmore": "https://help.dydx.exchange",
"keplrDashboard": "https://testnet.keplr.app/",
"accountExportLearnmore": "https://help.dydx.exchange",
"walletLearnmore": "https://www.dydx.academy/video/defi-wallet"
},
"wallets": {
"walletconnect": {
"client": {
"name": "dYdX v4",
"description": "dYdX v4 App",
"iconUrl": "/logos/dydx-x.png"
},
"v2": {
"projectId": "47559b2ec96c09aed9ff2cb54a31ab0e"
}
},
"walletSegue": {
"callbackUrl": "/walletsegue"
},
"images": "/wallets/",
"signTypedDataAction": "dYdX Chain Onboarding",
"signTypedDataDomainName": "dYdX V4"
}
},
"dydxprotocol-mainnet": {
"name": "v4",
"ethereumChainId": "1",
"dydxChainId": "[mainnet chain id]",
"chainName": "dYdX Chain",
"chainLogo": "dydx-chain.png",
"squidIntegratorId": "[mainnet squid integrator id]",
"isMainNet": true,
"tokens": {
"comment": "Change according to mainnet release",
@@ -885,10 +1105,20 @@
"tos": "[HTTP link to TOS]",
"privacy": "[HTTP link to Privacy Policy]",
"mintscan": "[HTTP link to Mintscan, with {tx_hash} placeholder]",
"mintscanBase": "[HTTP link to TOS mintscan base url]",
"feedback": "[HTTP link to feedback form, can be null]",
"blogs": "[HTTP link to blogs, can be null]",
"foundation": "[HTTP link to foundation, can be null]",
"initialMarginFractionLearnMore": "[HTTP link to initial margin fraction learn more, can be null]",
"reduceOnlyLearnMore": "https://help.dydx.exchange/articles/6345793-reduce-only-orders",
"documentation": "[HTTP link to documentation, can be null]",
"community": "[HTTP link to community, can be null]",
"feedback": "[HTTP link to feedback form, can be null]",
"blogs": "[HTTP link to blogs, can be null]"
"help": "[HTTP link to help page, can be null]",
"governanceLearnMore": "[HTTP link to governance learn more, can be null]",
"stakingLearnMore": "[HTTP link to staking learn more, can be null]",
"keplrDashboard": "[HTTP link to keplr dashboard, can be null]",
"accountExportLearnMore": "[HTTP link to account export learn more, can be null]",
"walletLearnMore": "[HTTP link to wallet learn more, can be null]"
},
"wallets": {
"walletconnect": {
+8
View File
@@ -40,6 +40,7 @@
"iosMinVersion": "0",
"imageUrl": "",
"encoding": "=\"#%/<>?@\\^`{|}:&",
"androidPackage": "io.metamask",
"connections": [
{
"type": "walletConnectV2",
@@ -98,6 +99,7 @@
"iosMinVersion": "1.8.0",
"imageUrl": "",
"encoding": "=\"#%/<>?@\\^`{|}:&",
"androidPackage": "org.toshi",
"connections": [
{
"type": "walletSegue",
@@ -155,6 +157,7 @@
"comment": "imToken",
"iosMinVersion": "0",
"imageUrl": "",
"androidPackage": "im.token.app",
"connections": [
{
"type": "walletConnectV2",
@@ -214,6 +217,7 @@
"iosMinVersion": "0",
"encoding": "=\"#%/<>?@\\^`{|}:&",
"imageUrl": "",
"androidPackage": "com.wallet.crypto.trustapp",
"connections": [
{
"type": "walletConnectV2",
@@ -271,6 +275,7 @@
"iosMinVersion": "0",
"encoding": "=\"#%/<>?@\\^`{|}:&",
"imageUrl": "",
"androidPackage": "io.zerion.android",
"connections": [
{
"type": "walletConnectV2",
@@ -327,6 +332,7 @@
"comment": "TokenPocket",
"iosMinVersion": "0",
"imageUrl": "",
"androidPackage": "vip.mytokenpocket",
"connections": [
{
"type": "walletConnectV2",
@@ -383,6 +389,7 @@
"comment": "Rainbow",
"iosMinVersion": "0",
"encoding": "=\"#%/<>?@\\^`{|}:&",
"androidPackage": "me.rainbow",
"backlinked": true,
"imageUrl": "",
"connections": [
@@ -442,6 +449,7 @@
"comment": "1inch",
"iosMinVersion": "0",
"encoding": "=\"#%/<>?@\\^`{|}:&",
"androidPackage": "io.oneinch.android",
"imageUrl": "",
"connections": [
{
+38
View File
@@ -0,0 +1,38 @@
## App Integrations
### Amplitude
Analytics service used to collect data to help the dYdX Product team make informed product decisions.
<b>To use with dydxprotocol/v4-web:</b>
1. Amplitude account with API key.
2. Add API key in Github > Secrets and Variables > Actions as `AMPLITUDE_API_KEY`
3. In your deploy scripts add `pnpm run build:inject-amplitude` after your pnpm build / vite build command.
### Bugsnag
Error handling service used to collect handled/unhandled errors within the app. The information collected is used to help debug and alert the engineering team of crashes/unhandled errors within the app to improve stability.
<b>To use with dydxprotocol/v4-web:</b>
1. Bugsnag account with API key.
2. Add API key in Github > Secrets and Variables > Actions as `BUGSNAG_API_KEY`
3. In your deploy scripts add `pnpm run build:inject-bugsnag` after your pnpm build / vite build command.
4. If you are using with the Amplitude deployment scripts, your build command may look like the following: `pnpm build && pnpm run build:inject-amplitude && pnpm run build:inject-bugsnag`
### StatusPage
Service used to inform users of any status updates to our platform. These status updates are manually set and updated by the On Call engineers.
<b>To use with dydxprotocol/v4-web:</b>
1. StatusPage account and script URI
2. Add API key in Github > Secrets and Variables > Actions as `STATUS_PAGE_SCRIPT_URI`
3. In your deploy scripts add `pnpm run build:inject-statuspage` after your pnpm build / vite build command.
4. If you are using with the Amplitude deployment scripts, your build command may look like the following: `pnpm build && pnpm run build:inject-amplitude && pnpm run build:inject-statuspage`
### Intercom
Service used for live customer support (chat/inbox) as well as home for Help Articles.
<b>To use with dydxprotocol/v4-web:</b>
1. Create Intercom account
2. In Intercom UI
Getting started > Set up Messenger > will give you your API Key on Step 2
Customize Intercom Messenger by adding logo and brand colors
3. Add API key in Github > Secrets and Variables > Actions as `INTERCOM_APP_ID`
4. In your deploy scripts add `pnpm run build:inject-intercom` after your pnpm build / vite build command.
5. If you are using with the Amplitude deployment scripts, your build command may look like the following: `pnpm build && pnpm run build:inject-amplitude && pnpm run build:inject-intercom`
+2
View File
@@ -23,6 +23,7 @@ import { LocalNotificationsProvider } from '@/hooks/useLocalNotifications';
import { RestrictionProvider } from '@/hooks/useRestrictions';
import { SubaccountProvider } from '@/hooks/useSubaccount';
import { SquidProvider } from '@/hooks/useSquid';
import { TestFlagsProvider } from '@/hooks/useTestFlags';
import { GuardedMobileRoute } from '@/components/GuardedMobileRoute';
@@ -123,6 +124,7 @@ const providers = [
wrapProvider(QueryClientProvider, { client: queryClient }),
wrapProvider(GrazProvider),
wrapProvider(WagmiConfig, { config }),
wrapProvider(TestFlagsProvider),
wrapProvider(LocaleProvider),
wrapProvider(RestrictionProvider),
wrapProvider(DydxProvider),
+1 -1
View File
@@ -80,7 +80,7 @@ Styled.TriggerIcon = styled.span`
width: var(--trigger-icon-width);
display: inline-flex;
transition: transform 0.3s var(--ease-out-expo);
transition: rotate 0.3s var(--ease-out-expo);
color: var(--trigger-icon-color);
${Styled.Trigger}[data-state='open'] & {
+1
View File
@@ -225,6 +225,7 @@ Styled.CollapsibleContent = styled(CollapsibleContent)`
`;
Styled.IconButton = styled(IconButton)`
--button-icon-size: 1em;
${Styled.CollapsibleRoot}[data-state='closed'] & {
rotate: -0.5turn;
}
+3
View File
@@ -34,6 +34,7 @@ type PickDialogProps = Pick<
| 'slotHeaderInner'
| 'slotTrigger'
| 'slotFooter'
| 'preventClose'
>;
export const ComboboxDialogMenu = <
@@ -57,6 +58,7 @@ export const ComboboxDialogMenu = <
children,
placement = DialogPlacement.Default,
preventClose,
className,
}: ElementProps<MenuItemValue, MenuGroupValue> &
PickComboxMenuProps<MenuItemValue, MenuGroupValue> &
@@ -72,6 +74,7 @@ export const ComboboxDialogMenu = <
slotTrigger={slotTrigger}
slotFooter={slotFooter}
placement={placement}
preventClose={preventClose}
className={className}
>
<Styled.ComboboxMenu
+3 -1
View File
@@ -33,9 +33,11 @@ export const DropdownHeaderMenu = <MenuItemValue extends string>({
return (
<Root>
<Styled.Trigger className={className}>
<Styled.Trigger className={className} asChild>
<div>
{children}
<Styled.DropdownIconButton iconName={IconName.Caret} isToggle />
</div>
</Styled.Trigger>
<Portal>
<Styled.Content
+10 -1
View File
@@ -24,9 +24,10 @@ import {
CommentIcon,
CopyIcon,
CubeIcon,
DepositIcon,
DepthChartIcon,
DiscordIcon,
EtherscanIcon,
DepthChartIcon,
ExportKeysIcon,
FeedbackIcon,
FileIcon,
@@ -40,6 +41,7 @@ import {
LockIcon,
LogoShortIcon,
MenuIcon,
MigrateIcon,
MintscanIcon,
OrderbookIcon,
OrderCanceledIcon,
@@ -68,6 +70,7 @@ import {
WarningIcon,
WebsiteIcon,
WhitepaperIcon,
WithdrawIcon,
} from '@/icons';
export enum IconName {
@@ -92,6 +95,7 @@ export enum IconName {
Comment = 'Comment',
Copy = 'Copy',
Cube = 'Cube',
Deposit = 'Deposit',
DepthChart = 'DepthChart',
Discord = 'Discord',
Etherscan = 'Etherscan',
@@ -108,6 +112,7 @@ export enum IconName {
Lock = 'Lock',
LogoShort = 'LogoShort',
Menu = 'Menu',
Migrate = 'Migrate',
Mintscan = 'Mintscan',
Onboarding = 'Onboarding',
Orderbook = 'OrderbookIcon',
@@ -137,6 +142,7 @@ export enum IconName {
Warning = 'Warning',
Website = 'Website',
Whitepaper = 'Whitepaper',
Withdraw = 'Withdraw',
}
const icons = {
@@ -161,6 +167,7 @@ const icons = {
[IconName.Comment]: CommentIcon,
[IconName.Copy]: CopyIcon,
[IconName.Cube]: CubeIcon,
[IconName.Deposit]: DepositIcon,
[IconName.DepthChart]: DepthChartIcon,
[IconName.Discord]: DiscordIcon,
[IconName.Etherscan]: EtherscanIcon,
@@ -177,6 +184,7 @@ const icons = {
[IconName.Lock]: LockIcon,
[IconName.LogoShort]: LogoShortIcon,
[IconName.Menu]: MenuIcon,
[IconName.Migrate]: MigrateIcon,
[IconName.Mintscan]: MintscanIcon,
[IconName.Orderbook]: OrderbookIcon,
[IconName.OrderCanceled]: OrderCanceledIcon,
@@ -205,6 +213,7 @@ const icons = {
[IconName.Warning]: WarningIcon,
[IconName.Website]: WebsiteIcon,
[IconName.Whitepaper]: WhitepaperIcon,
[IconName.Withdraw]: WithdrawIcon,
} as Record<IconName, ElementType>;
type ElementProps = {
+1
View File
@@ -67,6 +67,7 @@ const Styled: Record<string, AnyStyledComponent> = {};
const buttonMixin = css`
// Params
--button-icon-size: 1.125em;
--button-padding: 0;
// Rules
> * {
+4 -1
View File
@@ -71,7 +71,7 @@ const NavItem = forwardRef(
)}
</span>
{slotAfter}
{subitems?.length && <Styled.Icon iconName={IconName.Caret} />}
{subitems?.length && <Styled.Icon iconName={IconName.Triangle} />}
</>
);
@@ -525,6 +525,9 @@ Styled.NavItem = styled(NavItem)<{ orientation: 'horizontal' | 'vertical' }>`
`;
Styled.Icon = styled(Icon)`
font-size: 0.375em;
transition: rotate 0.3s var(--ease-out-expo);
${Styled.List}[data-orientation="menu"] & {
rotate: -0.25turn;
}
+52 -27
View File
@@ -8,6 +8,7 @@ import { layoutMixins } from '@/styles/layoutMixins';
type PanelProps = {
slotHeaderContent?: string;
slotHeader?: React.ReactNode;
slotRight?: React.ReactNode;
children?: React.ReactNode;
href?: string;
onHeaderClick?: () => void;
@@ -22,6 +23,7 @@ type PanelStyleProps = {
export const Panel = ({
slotHeaderContent,
slotHeader,
slotRight,
children,
href,
onHeaderClick,
@@ -29,56 +31,80 @@ export const Panel = ({
hasSeparator,
className,
}: PanelProps & PanelStyleProps) => (
<Styled.Panel onClick={onClick}>
{href ? (
<Link to={href}>
{slotHeader ? (
slotHeader
) : (
<Styled.Panel onClick={onClick} className={className}>
<Styled.Left>
{href ? (
<Link to={href}>
{slotHeader ? (
slotHeader
) : (
<Styled.Header role="button" onClick={onHeaderClick} hasSeparator={hasSeparator}>
{slotHeaderContent}
<Styled.Icon iconName={IconName.ChevronRight} />
</Styled.Header>
)}
</Link>
) : slotHeader ? (
slotHeader
) : (
slotHeaderContent && (
<Styled.Header role="button" onClick={onHeaderClick} hasSeparator={hasSeparator}>
{slotHeaderContent}
<Styled.Icon iconName={IconName.ChevronRight} />
</Styled.Header>
)}
</Link>
) : slotHeader ? (
slotHeader
) : (
slotHeaderContent && (
<Styled.Header role="button" onClick={onHeaderClick} hasSeparator={hasSeparator}>
{slotHeaderContent}
</Styled.Header>
)
)}
<Styled.Content className={className}>{children}</Styled.Content>
)
)}
<Styled.Content>{children}</Styled.Content>
</Styled.Left>
{slotRight}
</Styled.Panel>
);
const Styled: Record<string, AnyStyledComponent> = {};
Styled.Panel = styled.section`
${layoutMixins.flexColumn}
Styled.Panel = styled.section<{ onClick?: () => void }>`
--panel-paddingY: 1rem;
--panel-paddingX: 1rem;
--panel-content-paddingY: var(--panel-paddingY);
--panel-content-paddingX: var(--panel-paddingX);
${layoutMixins.row}
background-color: var(--color-layer-3);
border-radius: 0.875rem;
${({ onClick }) =>
onClick &&
css`
cursor: pointer;
&:hover {
button:not(:disabled) {
color: var(--button-hover-textColor);
filter: var(--button-hover-filter);
}
}
`}
`;
Styled.Left = styled.div`
${layoutMixins.flexColumn}
width: 100%;
`;
Styled.Header = styled.header<{ hasSeparator?: boolean }>`
${layoutMixins.spacedRow}
padding: 0.875rem 1rem 0.625rem;
font-size: 0.875rem;
padding: var(--panel-paddingY) var(--panel-paddingX);
${({ hasSeparator }) =>
hasSeparator &&
css`
padding-bottom: 0.625rem;
box-shadow: 0 var(--border-width) var(--border-color);
`}
`;
Styled.Icon = styled(Icon)`
color: var(--color-text-0);
font-size: 0.625rem;
`;
@@ -86,6 +112,5 @@ Styled.Content = styled.div`
${layoutMixins.scrollArea}
${layoutMixins.stickyArea0}
--stickyArea0-background: transparent;
padding: 0.5rem 1rem;
padding: var(--panel-content-paddingY) var(--panel-content-paddingX);
`;
+7 -1
View File
@@ -1,4 +1,4 @@
import { useState } from 'react';
import { useEffect, useRef, useState } from 'react';
import styled, { type AnyStyledComponent, css } from 'styled-components';
import { layoutMixins } from '@/styles/layoutMixins';
@@ -22,6 +22,11 @@ export const SearchInput = ({
}: SearchInputProps) => {
const [isOpen, setIsOpen] = useState(false);
const [value, setValue] = useState('');
const inputRef = useRef<HTMLInputElement | null>(null);
useEffect(() => {
if (isOpen) inputRef?.current?.focus();
}, [inputRef, isOpen]);
return (
<Styled.Search>
@@ -41,6 +46,7 @@ export const SearchInput = ({
/>
<Styled.Input
autoFocus
ref={inputRef}
value={value}
isOpen={isOpen}
type={type}
+12 -8
View File
@@ -831,6 +831,7 @@ Styled.SortArrow = styled.span<{ sortDirection: 'ascending' | 'descending' }>`
Styled.Thead = styled.thead<StyleProps>`
${layoutMixins.stickyHeader}
scroll-snap-align: none;
font: var(--font-mini-book);
> * {
height: var(--stickyArea-topHeight);
@@ -839,18 +840,17 @@ Styled.Thead = styled.thead<StyleProps>`
color: var(--tableHeader-textColor);
background-color: var(--tableHeader-backgroundColor);
@media ${breakpoints.notTablet} {
${({ withInnerBorders, withGradientCardRows }) =>
withInnerBorders &&
!withGradientCardRows &&
css`
${layoutMixins.withInnerHorizontalBorders}
`}
}
${({ withInnerBorders, withGradientCardRows }) =>
withInnerBorders &&
!withGradientCardRows &&
css`
${layoutMixins.withInnerHorizontalBorders}
`}
`;
Styled.Tbody = styled.tbody<StyleProps>`
${layoutMixins.stickyArea2}
font: var(--font-small-book);
// If <table> height is fixed with not enough rows to overflow, vertically center the rows
&:before,
@@ -869,6 +869,10 @@ Styled.Tbody = styled.tbody<StyleProps>`
--stickyArea2-paddingBottom: var(--border-width);
--stickyArea2-paddingLeft: var(--border-width);
--stickyArea2-paddingRight: var(--border-width);
tr:first-of-type {
box-shadow: none;
}
`}
${({ withGradientCardRows }) =>
+15 -4
View File
@@ -7,13 +7,15 @@ import { ButtonShape, ButtonSize } from '@/constants/buttons';
import { useBreakpoints } from '@/hooks';
import { layoutMixins } from '@/styles/layoutMixins';
import { type BaseButtonProps } from '@/components/BaseButton';
import { type BaseButtonProps } from '@/components/BaseButton';
import { ToggleButton } from '@/components/ToggleButton';
type ElementProps<MenuItemValue extends string> = {
items: MenuItem<MenuItemValue>[];
value: MenuItemValue;
onValueChange: (value: MenuItemValue) => void;
onValueChange: (value: any) => void;
onInteraction?: () => void;
ensureSelected?: boolean;
};
type StyleProps = {
@@ -25,10 +27,14 @@ export const ToggleGroup = forwardRef(
{
items,
value,
ensureSelected = true,
onValueChange,
onInteraction,
className,
size,
shape = ButtonShape.Pill,
...buttonProps
}: ElementProps<MenuItemValue> & StyleProps & BaseButtonProps,
ref: Ref<HTMLDivElement>
@@ -40,12 +46,17 @@ export const ToggleGroup = forwardRef(
ref={ref}
type="single"
value={value}
onValueChange={onValueChange}
onValueChange={(newValue: MenuItemValue) => {
if ((ensureSelected && newValue) || !ensureSelected) {
onValueChange(newValue);
}
onInteraction?.();
}}
className={className}
loop
>
{items.map((item) => (
<Item key={item.value} value={item.value} aria-label={item.label} asChild>
<Item key={item.value} value={item.value} asChild>
<ToggleButton
size={size ? size : isTablet ? ButtonSize.Small : ButtonSize.XSmall}
shape={shape}
+19 -2
View File
@@ -2,11 +2,13 @@ import type { ReactNode } from 'react';
import styled, { AnyStyledComponent } from 'styled-components';
import { Content, Portal, Provider, Root, Trigger, Arrow } from '@radix-ui/react-tooltip';
import { STRING_KEYS } from '@/constants/localization';
import { tooltipStrings } from '@/constants/tooltips';
import { useStringGetter } from '@/hooks';
import { useStringGetter, useURLConfigs } from '@/hooks';
import { Icon, IconName } from '@/components/Icon';
import { Link } from '@/components/Link';
import { layoutMixins } from '@/styles/layoutMixins';
import { popoverMixins } from '@/styles/popoverMixins';
@@ -38,20 +40,24 @@ export const WithTooltip = ({
slotTooltip,
}: ElementProps & StyleProps) => {
const stringGetter = useStringGetter();
const urlConfigs = useURLConfigs();
const getTooltipStrings = tooltip && tooltipStrings[tooltip];
if (!getTooltipStrings && !tooltipString && !slotTooltip) return <>{children}</>;
let tooltipTitle;
let tooltipBody;
let tooltipLearnMore;
if (getTooltipStrings) {
const { title, body } = getTooltipStrings({
const { title, body, learnMoreLink } = getTooltipStrings({
stringGetter,
stringParams,
urlConfigs,
});
tooltipTitle = title;
tooltipBody = body;
tooltipLearnMore = learnMoreLink;
} else {
tooltipBody = tooltipString;
}
@@ -72,6 +78,13 @@ export const WithTooltip = ({
<dl>
{tooltipTitle && <dt>{tooltipTitle}</dt>}
{tooltipBody && <dd>{tooltipBody}</dd>}
{tooltipLearnMore && (
<dd>
<Styled.LearnMore href={tooltipLearnMore}>
{stringGetter({ key: STRING_KEYS.LEARN_MORE })}
</Styled.LearnMore>
</dd>
)}
<Styled.Arrow />
</dl>
)}
@@ -142,3 +155,7 @@ Styled.Arrow = styled(Arrow)`
Styled.Icon = styled(Icon)`
color: var(--color-text-0);
`;
Styled.LearnMore = styled(Link)`
--link-color: var(--color-accent);
`;
+4
View File
@@ -8,6 +8,8 @@ import {
WARNINGS_STRING_KEYS,
} from '@dydxprotocol/v4-localization';
import { type LinksConfigs } from '@/hooks/useURLConfigs';
export { TOOLTIP_STRING_KEYS } from '@dydxprotocol/v4-localization';
export enum SupportedLocales {
@@ -79,9 +81,11 @@ export type TooltipStrings = {
[key: string]: ({
stringGetter,
stringParams,
urlConfigs,
}: {
stringGetter: StringGetterFunction;
stringParams?: any;
urlConfigs?: LinksConfigs;
}) => {
title: string;
body: string;
+12 -6
View File
@@ -1,12 +1,18 @@
import environments from '../../public/configs/env.json';
// TODO: Update for Mainnet deployment
export const AVAILABLE_ENVIRONMENTS =
import.meta.env.MODE === 'production'
? environments.deployments.TESTNET
: environments.deployments.DEV;
const CURRENT_MODE = ({
production: 'MAINNET',
testnet: 'TESTNET',
staging: 'DEV',
development: 'DEV',
}[import.meta.env.MODE] ?? 'MAINNET') as 'MAINNET' | 'TESTNET' | 'DEV';
export const CURRENT_ABACUS_DEPLOYMENT = import.meta.env.MODE === 'production' ? 'TESTNET' : 'DEV';
export const isMainnet = CURRENT_MODE === 'MAINNET';
export const isTestnet = CURRENT_MODE === 'TESTNET';
export const isDev = CURRENT_MODE === 'DEV';
export const AVAILABLE_ENVIRONMENTS = environments.deployments[CURRENT_MODE];
export const CURRENT_ABACUS_DEPLOYMENT = CURRENT_MODE;
export const ENVIRONMENT_CONFIG_MAP = environments.environments;
export type DydxNetwork = keyof typeof ENVIRONMENT_CONFIG_MAP;
export const DEFAULT_APP_ENVIRONMENT = AVAILABLE_ENVIRONMENTS.default as DydxNetwork;
-4
View File
@@ -37,7 +37,3 @@ export const HISTORY_ROUTE = `${AppRoute.Portfolio}/${PortfolioRoute.History}/:s
export const DEFAULT_TRADE_ROUTE = `${AppRoute.Trade}/${DEFAULT_MARKETID}`;
export const SETTINGS_ROUTE = `${AppRoute.Settings}/*`;
export const DEFAULT_DOCUMENT_TITLE = 'dYdX';
export enum ExternalLink {
Foundation = 'https://dydx.foundation',
}
+4 -4
View File
@@ -57,10 +57,10 @@ export const tradeTooltips: TooltipStrings = {
title: stringGetter({ key: TOOLTIP_STRING_KEYS.INDEX_PRICE_TITLE }),
body: stringGetter({ key: TOOLTIP_STRING_KEYS.INDEX_PRICE_BODY }),
}),
'initial-margin-fraction': ({ stringGetter }) => ({
'initial-margin-fraction': ({ stringGetter, urlConfigs }) => ({
title: stringGetter({ key: TOOLTIP_STRING_KEYS.INITIAL_MARGIN_FRACTION_TITLE }),
body: stringGetter({ key: TOOLTIP_STRING_KEYS.INITIAL_MARGIN_FRACTION_BODY }),
learnMoreLink: 'https://help.dydx.exchange/articles/5232637-maximum-position-sizes',
learnMoreLink: urlConfigs?.initialMarginFractionLearnMore,
}),
'initial-stop': ({ stringGetter }) => ({
title: stringGetter({ key: TOOLTIP_STRING_KEYS.INITIAL_STOP_TITLE }),
@@ -146,10 +146,10 @@ export const tradeTooltips: TooltipStrings = {
title: stringGetter({ key: TOOLTIP_STRING_KEYS.REALIZED_PNL_TITLE }),
body: stringGetter({ key: TOOLTIP_STRING_KEYS.REALIZED_PNL_BODY }),
}),
'reduce-only': ({ stringGetter }) => ({
'reduce-only': ({ stringGetter, urlConfigs }) => ({
title: stringGetter({ key: TOOLTIP_STRING_KEYS.REDUCE_ONLY_TITLE }),
body: stringGetter({ key: TOOLTIP_STRING_KEYS.REDUCE_ONLY_BODY }),
learnMoreLink: 'https://help.dydx.exchange/articles/6345793-reduce-only-orders',
learnMoreLink: urlConfigs?.reduceOnlyLearnMore,
}),
spread: () => ({
title: 'Spread',
+2
View File
@@ -22,6 +22,7 @@ import { useShouldShowFooter } from './useShouldShowFooter';
import { useSelectedNetwork } from './useSelectedNetwork';
import { useStringGetter } from './useStringGetter';
import { useSubaccount } from './useSubaccount';
import { useURLConfigs } from './useURLConfigs';
export {
useApiState,
@@ -48,4 +49,5 @@ export {
useSelectedNetwork,
useStringGetter,
useSubaccount,
useURLConfigs,
};
+4 -2
View File
@@ -42,6 +42,7 @@ const useAccountsContext = () => {
selectedWalletError,
evmAddress,
signerWagmi,
publicClientWagmi,
dydxAddress: connectedDydxAddress,
signerGraz,
} = useWalletConnection();
@@ -135,8 +136,8 @@ const useAccountsContext = () => {
getSubaccounts: async ({ dydxAddress }: { dydxAddress: DydxAddress }) => {
try {
const response = await compositeClient?.indexerClient.account.getSubaccounts(dydxAddress);
setDydxSubaccounts(response.subaccounts);
return response.subaccounts;
setDydxSubaccounts(response?.subaccounts);
return response?.subaccounts ?? [];
} catch (error) {
// 404 is expected if the user has no subaccounts
if (error.status === 404) {
@@ -296,6 +297,7 @@ const useAccountsContext = () => {
// Wallet connection (EVM)
evmAddress,
signerWagmi,
publicClientWagmi,
// Wallet connection (Cosmos)
signerGraz,
+2 -1
View File
@@ -1,3 +1,4 @@
import { isDev } from '@/constants/networks';
import { WalletType } from '@/constants/wallets';
import { isTruthy } from '@/lib/isTruthy';
@@ -6,7 +7,7 @@ export const useDisplayedWallets = () => {
return [
WalletType.MetaMask,
import.meta.env.MODE !== 'production' && WalletType.Keplr,
isDev && WalletType.Keplr,
WalletType.WalletConnect2,
+10 -1
View File
@@ -66,7 +66,16 @@ const useLocalNotificationsContext = () => {
status: currentStatus,
} of transferNotifications) {
try {
if (currentStatus && currentStatus?.squidTransactionStatus !== 'ongoing') continue;
// skip if error is returned or if the transaction is not ongoing
if (
// @ts-ignore status.errors is not in the type definition but can be returned
currentStatus?.errors ||
currentStatus?.error ||
(currentStatus?.squidTransactionStatus &&
currentStatus?.squidTransactionStatus !== 'ongoing')
) {
continue;
}
const status = await squid?.getStatus({ transactionId: txHash, toChainId, fromChainId });
if (status) statuses[txHash] = status;
+12 -8
View File
@@ -6,8 +6,10 @@ import { MarketFilters, MARKET_FILTER_LABELS, type MarketData } from '@/constant
import { getAssets } from '@/state/assetsSelectors';
import { getPerpetualMarkets } from '@/state/perpetualsSelectors';
import { isTruthy } from '@/lib/isTruthy';
const filterFunctions = {
[MarketFilters.ALL]: (market: MarketData) => true,
[MarketFilters.ALL]: () => true,
[MarketFilters.LAYER_1]: (market: MarketData) => {
return market.asset.tags?.toArray().includes('Layer 1');
},
@@ -28,13 +30,15 @@ export const useMarketsData = (
const allAssets = useSelector(getAssets, shallowEqual) || {};
const markets = useMemo(() => {
return Object.values(allPerpetualMarkets).map((marketData) => ({
asset: allAssets[marketData.assetId],
tickSizeDecimals: marketData.configs?.tickSizeDecimals,
...marketData,
...marketData.perpetual,
...marketData.configs,
})) as MarketData[];
return Object.values(allPerpetualMarkets)
.filter(isTruthy)
.map((marketData) => ({
asset: allAssets[marketData.assetId],
tickSizeDecimals: marketData.configs?.tickSizeDecimals,
...marketData,
...marketData.perpetual,
...marketData.configs,
})) as MarketData[];
}, [allPerpetualMarkets, allAssets]);
const filteredMarkets = useMemo(() => {
+4 -2
View File
@@ -7,9 +7,11 @@ import { AlertType } from '@/constants/alerts';
import { AbacusOrderStatus, ORDER_SIDES } from '@/constants/abacus';
import { DialogTypes } from '@/constants/dialogs';
import { STRING_KEYS, StringKey } from '@/constants/localization';
import { ENVIRONMENT_CONFIG_MAP } from '@/constants/networks';
import { type NotificationTypeConfig, NotificationType } from '@/constants/notifications';
import { ORDER_SIDE_STRINGS } from '@/constants/trade';
import { useSelectedNetwork } from '@/hooks';
import { useLocalNotifications } from '@/hooks/useLocalNotifications';
import { Icon, IconName } from '@/components/Icon';
@@ -23,7 +25,6 @@ import { OrderStatusIcon } from '@/views/OrderStatusIcon';
import { useStringGetter } from './useStringGetter';
import { TransferStatusSteps } from '@/views/TransferStatusSteps';
import { TESTNET_CHAIN_ID } from '@dydxprotocol/v4-client-js';
export const notificationTypes = [
{
@@ -124,6 +125,7 @@ export const notificationTypes = [
useTrigger: ({ trigger }) => {
const stringGetter = useStringGetter();
const { transferNotifications } = useLocalNotifications();
const { selectedNetwork } = useSelectedNetwork();
const getTitleStringKey = useCallback((type: 'deposit' | 'withdrawal', finished: boolean) => {
if (type === 'deposit' && !finished) return STRING_KEYS.DEPOSIT_IN_PROGRESS;
@@ -136,7 +138,7 @@ export const notificationTypes = [
for (const transfer of transferNotifications) {
const { fromChainId, status, txHash, toAmount } = transfer;
const finished = Boolean(status) && status?.squidTransactionStatus !== 'ongoing';
const type = fromChainId === TESTNET_CHAIN_ID ? 'withdrawal' : 'deposit';
const type = fromChainId === ENVIRONMENT_CONFIG_MAP[selectedNetwork].dydxChainId ? 'withdrawal' : 'deposit';
// @ts-ignore status.errors is not in the type definition but can be returned
const error = status?.errors?.length ? status?.errors[0] : status?.error;
+6 -2
View File
@@ -8,7 +8,7 @@ import { getSelectedNetwork } from '@/state/appSelectors';
export const NATIVE_TOKEN_ADDRESS = '0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE';
export const STATUS_ERROR_GRACE_PERIOD = 120_000;
export const STATUS_ERROR_GRACE_PERIOD = 300_000;
const useSquidContext = () => {
const selectedNetwork = useSelector(getSelectedNetwork);
@@ -22,7 +22,11 @@ const useSquidContext = () => {
};
const squid = useMemo(
() => new Squid({ baseUrl: ENVIRONMENT_CONFIG_MAP[selectedNetwork]?.endpoints['0xsquid'] }),
() =>
new Squid({
baseUrl: ENVIRONMENT_CONFIG_MAP[selectedNetwork]?.endpoints['0xsquid'],
integratorId: ENVIRONMENT_CONFIG_MAP[selectedNetwork]?.squidIntegratorId,
}),
[selectedNetwork]
);
+91 -60
View File
@@ -48,7 +48,7 @@ export const useSubaccount = () => useContext(SubaccountContext);
export const useSubaccountContext = ({ localDydxWallet }: { localDydxWallet?: LocalWallet }) => {
const dispatch = useDispatch();
const { usdcDenom } = useTokenConfigs();
const { usdcDenom, usdcDecimals } = useTokenConfigs();
const { compositeClient, faucetClient } = useDydxClient();
const { getFaucetFunds } = useMemo(
@@ -79,16 +79,34 @@ export const useSubaccountContext = ({ localDydxWallet }: { localDydxWallet?: Lo
subaccountClient: SubaccountClient;
assetId?: number;
amount: number;
}) => await compositeClient?.depositToSubaccount(subaccountClient, amount.toString()),
}) => {
try {
return await compositeClient?.depositToSubaccount(
subaccountClient,
amount.toFixed(usdcDecimals)
);
} catch (error) {
log('useSubaccount/depositToSubaccount', error);
throw error;
}
},
withdrawFromSubaccount: async ({
subaccountClient,
amount,
}: {
subaccountClient: SubaccountClient;
amount: number;
}) => await compositeClient?.withdrawFromSubaccount(subaccountClient, amount.toString()),
}) => {
try {
return await compositeClient?.withdrawFromSubaccount(
subaccountClient,
amount.toFixed(usdcDecimals)
);
} catch (error) {
log('useSubaccount/withdrawFromSubaccount', error);
throw error;
}
},
transferFromSubaccountToAddress: async ({
subaccountClient,
assetId = 0,
@@ -99,27 +117,33 @@ export const useSubaccountContext = ({ localDydxWallet }: { localDydxWallet?: Lo
assetId?: number;
amount: number;
recipient: string;
}) =>
await compositeClient?.validatorClient.post.send(
subaccountClient?.wallet,
() =>
new Promise((resolve) => {
const msg =
compositeClient?.validatorClient.post.composer.composeMsgWithdrawFromSubaccount(
subaccountClient.address,
subaccountClient.subaccountNumber,
assetId,
Long.fromNumber(amount * QUANTUM_MULTIPLIER),
recipient
);
}) => {
try {
return await compositeClient?.validatorClient.post.send(
subaccountClient?.wallet,
() =>
new Promise((resolve) => {
const msg =
compositeClient?.validatorClient.post.composer.composeMsgWithdrawFromSubaccount(
subaccountClient.address,
subaccountClient.subaccountNumber,
assetId,
Long.fromNumber(amount * QUANTUM_MULTIPLIER),
recipient
);
resolve([msg]);
}),
false,
undefined,
undefined,
Method.BroadcastTxCommit
),
resolve([msg]);
}),
false,
undefined,
undefined,
Method.BroadcastTxCommit
);
} catch (error) {
log('useSubaccount/transferFromSubaccountToAddress', error);
throw error;
}
},
transferNativeToken: async ({
subaccountClient,
@@ -129,24 +153,30 @@ export const useSubaccountContext = ({ localDydxWallet }: { localDydxWallet?: Lo
subaccountClient: SubaccountClient;
amount: number;
recipient: string;
}) =>
await compositeClient?.validatorClient.post.send(
subaccountClient.wallet,
() =>
new Promise((resolve) => {
const msg = compositeClient?.sendTokenMessage(
subaccountClient.wallet,
amount.toString(),
recipient,
);
}) => {
try {
return await compositeClient?.validatorClient.post.send(
subaccountClient.wallet,
() =>
new Promise((resolve) => {
const msg = compositeClient?.sendTokenMessage(
subaccountClient.wallet,
amount.toString(),
recipient
);
resolve([msg]);
}),
false,
compositeClient?.validatorClient?.post.defaultDydxGasPrice,
undefined,
Method.BroadcastTxCommit
),
resolve([msg]);
}),
false,
compositeClient?.validatorClient?.post.defaultDydxGasPrice,
undefined,
Method.BroadcastTxCommit
);
} catch (error) {
log('useSubaccount/transferNativeToken', error);
throw error;
}
},
sendSquidWithdrawFromSubaccount: async ({
subaccountClient,
@@ -158,20 +188,27 @@ export const useSubaccountContext = ({ localDydxWallet }: { localDydxWallet?: Lo
payload: string;
}) => {
if (!compositeClient) throw new Error('client not initialized');
try {
const transaction = JSON.parse(payload);
const transaction = JSON.parse(payload);
const msg = compositeClient.withdrawFromSubaccountMessage(
subaccountClient,
amount.toFixed(usdcDecimals)
);
const ibcMsg: EncodeObject = {
typeUrl: transaction.msgTypeUrl,
value: transaction.msg,
};
const msg = compositeClient.withdrawFromSubaccountMessage(subaccountClient, amount.toString());
const ibcMsg: EncodeObject = {
typeUrl: transaction.msgTypeUrl,
value: transaction.msg,
};
return await compositeClient.send(
subaccountClient.wallet,
() => Promise.resolve([msg, ibcMsg]),
false
);
return await compositeClient.send(
subaccountClient.wallet,
() => Promise.resolve([msg, ibcMsg]),
false
);
} catch (error) {
log('useSubaccount/sendSquidWithdrawFromSubaccount', error);
throw error;
}
},
}),
[compositeClient]
@@ -313,11 +350,6 @@ export const useSubaccountContext = ({ localDydxWallet }: { localDydxWallet?: Lo
placeOrderParams = abacusStateManager.placeOrder(callback);
}
track(AnalyticsEvent.TradePlaceOrder, {
...placeOrderParams,
isClosePosition,
} as HumanReadablePlaceOrderPayload & { isClosePosition: boolean });
return placeOrderParams;
},
[subaccountClient]
@@ -346,7 +378,6 @@ export const useSubaccountContext = ({ localDydxWallet }: { localDydxWallet?: Lo
}) => {
const callback = (success: boolean, parsingError?: Nullable<ParsingError>) => {
if (success) {
track(AnalyticsEvent.TradeCancelOrder);
onSuccess?.();
} else {
onError?.({ errorStringKey: parsingError?.stringKey });
+46
View File
@@ -0,0 +1,46 @@
import { createContext, useContext, useEffect, useState } from 'react';
import { useLocation } from 'react-router-dom';
import queryString from 'query-string';
class TestFlags {
public queryParams: queryString.ParsedQuery<string>;
constructor() {
this.queryParams = {};
}
setQueryParams(flags: queryString.ParsedQuery<string>) {
this.queryParams = flags;
}
get displayInitializingMarkets() {
return !!this.queryParams.displayInitializingMarkets;
}
}
export const testFlags = new TestFlags();
const useTestFlagsContext = () => {
const [queryParams, setQueryParams] = useState<queryString.ParsedQuery<string>>({});
const location = useLocation();
useEffect(() => {
const parsedQueryParams = queryString.parse(location.search.substring(-1));
testFlags.setQueryParams(parsedQueryParams);
setQueryParams(parsedQueryParams);
}, []);
return {
...queryParams,
};
};
type TestFlagsContextType = ReturnType<typeof useTestFlagsContext>;
const TestFlagsContext = createContext<TestFlagsContextType>({} as TestFlagsContextType);
TestFlagsContext.displayName = 'TestFlags';
export const TestFlagsProvider = ({ ...props }) => (
<TestFlagsContext.Provider value={useTestFlagsContext()} {...props} />
);
export const useTestFlags = () => useContext(TestFlagsContext);
+4
View File
@@ -19,8 +19,10 @@ export const useTokenConfigs = (): {
},
};
usdcDenom: string;
usdcDecimals: number;
usdcLabel: string;
chainTokenDenom: string;
chainTokenDecimals: number;
chainTokenLabel: string;
} => {
const { selectedNetwork } = useSelectedNetwork();
@@ -29,8 +31,10 @@ export const useTokenConfigs = (): {
return {
tokensConfigs,
usdcDenom: tokensConfigs[DydxChainAsset.USDC].denom,
usdcDecimals: tokensConfigs[DydxChainAsset.USDC].decimals,
usdcLabel: tokensConfigs[DydxChainAsset.USDC].name,
chainTokenDenom: tokensConfigs[DydxChainAsset.CHAINTOKEN].denom,
chainTokenDecimals: tokensConfigs[DydxChainAsset.CHAINTOKEN].decimals,
chainTokenLabel: tokensConfigs[DydxChainAsset.CHAINTOKEN].name,
};
};
+50
View File
@@ -0,0 +1,50 @@
import { ENVIRONMENT_CONFIG_MAP } from '@/constants/networks';
import { useSelectedNetwork } from '@/hooks';
const FALLBACK_URL = 'https://help.dydx.exchange/';
export interface LinksConfigs {
tos: string,
privacy: string,
mintscan: string,
mintscanBase: string,
feedback?: string,
help?: string,
blogs?: string,
foundation?: string,
initialMarginFractionLearnMore?: string,
reduceOnlyLearnMore?: string,
documentation?: string,
community?: string,
governanceLearnMore?: string,
stakingLearnMore?: string,
keplrDashboard?: string,
accountExportLearnMore?: string,
walletLearnMore?: string
}
export const useURLConfigs = (): LinksConfigs => {
const { selectedNetwork } = useSelectedNetwork();
const linksConfigs = ENVIRONMENT_CONFIG_MAP[selectedNetwork].links as LinksConfigs;
return {
tos: linksConfigs.tos,
privacy: linksConfigs.privacy,
mintscan: linksConfigs.mintscan,
mintscanBase: linksConfigs.mintscanBase,
feedback: linksConfigs.feedback || FALLBACK_URL,
help: linksConfigs.help || FALLBACK_URL,
blogs: linksConfigs.blogs || FALLBACK_URL,
foundation: linksConfigs.foundation || FALLBACK_URL,
initialMarginFractionLearnMore: linksConfigs.initialMarginFractionLearnMore || FALLBACK_URL,
reduceOnlyLearnMore: linksConfigs.reduceOnlyLearnMore || FALLBACK_URL,
documentation: linksConfigs.documentation || FALLBACK_URL,
community: linksConfigs.community || FALLBACK_URL,
governanceLearnMore: linksConfigs.governanceLearnMore || FALLBACK_URL,
stakingLearnMore: linksConfigs.stakingLearnMore || FALLBACK_URL,
keplrDashboard: linksConfigs.keplrDashboard || FALLBACK_URL,
accountExportLearnMore: linksConfigs.accountExportLearnMore || FALLBACK_URL,
walletLearnMore: linksConfigs.walletLearnMore || FALLBACK_URL,
};
};
+11 -9
View File
@@ -1,4 +1,4 @@
import { useCallback, useEffect, useState } from 'react';
import { useCallback, useEffect, useState, useMemo } from 'react';
import { useSelector } from 'react-redux';
import { LocalStorageKey } from '@/constants/localStorage';
@@ -90,19 +90,21 @@ export const useWalletConnection = () => {
const selectedNetwork = useSelector(getSelectedNetwork);
const walletConnectConfig = ENVIRONMENT_CONFIG_MAP[selectedNetwork].wallets.walletconnect;
const { connectAsync: connectWagmi } =
walletType && walletConnectionType
? useConnectWagmi({
connector: resolveWagmiConnector({
const wagmiConnector = useMemo(
() =>
walletType && walletConnectionType
? resolveWagmiConnector({
walletType,
walletConnection: {
type: walletConnectionType,
},
walletConnectConfig,
}),
})
: useConnectWagmi();
})
: undefined,
[walletConnectConfig, walletType, walletConnectionType]
);
const { connectAsync: connectWagmi } = useConnectWagmi({ connector: wagmiConnector })
const { suggestAndConnect: connectGraz } = useConnectGraz();
const connectWallet = useCallback(
+11
View File
@@ -0,0 +1,11 @@
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 18 18" fill="none">
<g clip-path="url(#clip0_18204_36775)">
<path d="M13.2426 6.25736C14.0817 7.09647 14.6531 8.16557 14.8846 9.32946C15.1162 10.4933 14.9973 11.6997 14.5432 12.7961C14.0891 13.8925 13.32 14.8295 12.3334 15.4888C11.3467 16.1481 10.1866 16.5 8.99993 16.5C7.81324 16.5 6.6532 16.1481 5.66651 15.4888C4.67981 14.8295 3.91078 13.8925 3.45665 12.7961C3.00253 11.6997 2.88371 10.4933 3.11522 9.32946C3.34673 8.16557 3.91817 7.09647 4.75729 6.25736" stroke="#C8C7D8" stroke-width="1.35" stroke-linecap="round"/>
<path d="M11.25 9L9 11.25M9 11.25L6.75 9M9 11.25V1.6875" stroke="#C8C7D8" stroke-width="1.35" stroke-linecap="round" stroke-linejoin="round"/>
</g>
<defs>
<clipPath id="clip0_18204_36775">
<rect width="18" height="18" fill="white"/>
</clipPath>
</defs>
</svg>

After

Width:  |  Height:  |  Size: 886 B

+3
View File
@@ -19,6 +19,7 @@ export { default as CoinsIcon } from './coins.svg';
export { default as CommentIcon } from './comment.svg';
export { default as CopyIcon } from './copy.svg';
export { default as CubeIcon } from './cube.svg';
export { default as DepositIcon } from './deposit.svg';
export { default as DepthChartIcon } from './depth-chart.svg';
export { default as DiscordIcon } from './discord.svg';
export { default as ExportKeysIcon } from './export-keys.svg';
@@ -35,6 +36,7 @@ export { default as LockIcon } from './lock.svg';
export { default as LogoShortIcon } from './logo-short';
export { default as MarketsIcon } from './markets.svg';
export { default as MenuIcon } from './menu.svg';
export { default as MigrateIcon } from './migrate.svg';
export { default as MintscanIcon } from './logos/mintscan.svg';
export { default as OrderbookIcon } from './orderbook.svg';
export { default as OverviewIcon } from './overview.svg';
@@ -58,6 +60,7 @@ export { default as TransferIcon } from './transfer.svg';
export { default as TriangleIcon } from './triangle.svg';
export { default as TryAgainIcon } from './try-again.svg';
export { default as WarningIcon } from './warning.svg';
export { default as WithdrawIcon } from './withdraw.svg';
// Wallets
export { default as BitkeepIcon } from './wallets/bitkeep.svg';
File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 694 KiB

+4
View File
@@ -0,0 +1,4 @@
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 18 18" fill="none">
<path d="M13.2426 6.2573C14.0817 7.09641 14.6531 8.16551 14.8846 9.3294C15.1162 10.4933 14.9973 11.6997 14.5432 12.796C14.0891 13.8924 13.32 14.8295 12.3334 15.4888C11.3467 16.148 10.1866 16.4999 8.99993 16.4999C7.81324 16.4999 6.6532 16.148 5.66651 15.4888C4.67981 14.8295 3.91078 13.8924 3.45665 12.796C3.00253 11.6997 2.88371 10.4933 3.11522 9.3294C3.34673 8.16551 3.91817 7.09641 4.75729 6.2573" stroke="#C8C7D8" stroke-width="1.35" stroke-linecap="round"/>
<path d="M11.25 2.9375L9 0.6875M9 0.6875L6.75 2.9375M9 0.6875V10.25" stroke="#C8C7D8" stroke-width="1.35" stroke-linecap="round" stroke-linejoin="round"/>
</svg>

After

Width:  |  Height:  |  Size: 723 B

+2 -2
View File
@@ -3,7 +3,7 @@ import styled, { type AnyStyledComponent, css } from 'styled-components';
import { AbacusApiStatus } from '@/constants/abacus';
import { ButtonSize } from '@/constants/buttons';
import { STRING_KEYS } from '@/constants/localization';
import { ENVIRONMENT_CONFIG_MAP } from '@/constants/networks';
import { ENVIRONMENT_CONFIG_MAP, isDev } from '@/constants/networks';
import { useApiState, useSelectedNetwork, useStringGetter } from '@/hooks';
import { ChatIcon, LinkOutIcon } from '@/icons';
@@ -75,7 +75,7 @@ export const FooterDesktop = () => {
)}
</Styled.Row>
{import.meta.env.MODE !== 'production' && (
{isDev && (
<Styled.Details
withSeparators
items={[
+29 -14
View File
@@ -8,7 +8,7 @@ import { STRING_KEYS } from '@/constants/localization';
import { AppRoute } from '@/constants/routes';
import { LogoShortIcon, BellStrokeIcon } from '@/icons';
import { useTokenConfigs, useStringGetter } from '@/hooks';
import { useTokenConfigs, useStringGetter, useURLConfigs } from '@/hooks';
import { Icon, IconName } from '@/components/Icon';
import { IconButton } from '@/components/IconButton';
@@ -24,9 +24,11 @@ import { openDialog } from '@/state/dialogs';
import { headerMixins } from '@/styles/headerMixins';
import { layoutMixins } from '@/styles/layoutMixins';
import breakpoints from '@/styles/breakpoints';
export const HeaderDesktop = () => {
const stringGetter = useStringGetter();
const { documentation, community, mintscanBase } = useURLConfigs();
const dispatch = useDispatch();
const { chainTokenLabel } = useTokenConfigs();
@@ -34,26 +36,26 @@ export const HeaderDesktop = () => {
{
group: 'navigation',
items: [
{
value: 'MARKET',
label: stringGetter({ key: STRING_KEYS.MARKET }),
href: AppRoute.Markets,
},
{
value: 'TRADE',
label: stringGetter({ key: STRING_KEYS.TRADE }),
href: AppRoute.Trade,
},
{
value: chainTokenLabel,
label: chainTokenLabel,
href: `/${chainTokenLabel}`,
},
{
value: 'PORTFOLIO',
label: stringGetter({ key: STRING_KEYS.PORTFOLIO }),
href: AppRoute.Portfolio,
},
{
value: 'MARKETS',
label: stringGetter({ key: STRING_KEYS.MARKETS }),
href: AppRoute.Markets,
},
{
value: chainTokenLabel,
label: chainTokenLabel,
href: `/${chainTokenLabel}`,
},
{
value: 'MORE',
label: stringGetter({ key: STRING_KEYS.MORE }),
@@ -62,19 +64,19 @@ export const HeaderDesktop = () => {
value: 'DOCUMENTATION',
slotBefore: <Icon iconName={IconName.Terminal} />,
label: stringGetter({ key: STRING_KEYS.DOCUMENTATION }),
href: 'https://v4-teacher.vercel.app/',
href: documentation,
},
{
value: 'MINTSCAN',
slotBefore: <Icon iconName={IconName.Mintscan} />,
label: stringGetter({ key: STRING_KEYS.MINTSCAN }),
href: 'https://testnet.mintscan.io/dydx-testnet',
href: mintscanBase,
},
{
value: 'COMMUNITY',
slotBefore: <Icon iconName={IconName.Discord} />,
label: stringGetter({ key: STRING_KEYS.COMMUNITY }),
href: 'https://discord.gg/dydx',
href: community,
},
{
value: 'TERMS_OF_USE',
@@ -150,6 +152,7 @@ const Styled: Record<string, AnyStyledComponent> = {};
Styled.Header = styled.header`
--header-horizontal-padding-mobile: 0.5rem;
--trigger-height: 2.25rem;
--logo-width: 3.5rem;
${layoutMixins.container}
@@ -157,6 +160,8 @@ Styled.Header = styled.header`
${layoutMixins.scrollSnapItem}
backdrop-filter: none;
height: var(--page-currentHeaderHeight);
grid-area: Header;
display: grid;
@@ -169,6 +174,14 @@ Styled.Header = styled.header`
)
var(--border-width) 1fr var(--border-width) auto;
@media ${breakpoints.tablet} {
--trigger-height: 3rem;
}
@media ${breakpoints.mobile} {
--navBefore-width: 7rem;
}
font-size: 0.9375rem;
:before {
@@ -179,6 +192,7 @@ Styled.Header = styled.header`
Styled.NavigationMenu = styled(NavigationMenu)`
& {
--navigationMenu-height: var(--stickyArea-topHeight);
--navigationMenu-item-height: var(--trigger-height);
}
${layoutMixins.scrollArea}
@@ -222,4 +236,5 @@ Styled.IconButton = styled(IconButton)<{ size?: string }>`
${headerMixins.button}
--button-border: none;
--button-icon-size: 1rem;
--button-padding: 0 0.5em;
`;
+10 -10
View File
@@ -30,7 +30,7 @@ import {
import { DialogTypes } from '@/constants/dialogs';
import { UNCOMMITTED_ORDER_TIMEOUT_MS } from '@/constants/trade';
import { QUANTUM_MULTIPLIER } from '@/constants/numbers';
import { ENVIRONMENT_CONFIG_MAP, DydxNetwork, isTestnet } from '@/constants/networks';
import { RootStore } from '@/state/_store';
import { addUncommittedOrderClientId, removeUncommittedOrderClientId } from '@/state/account';
@@ -198,8 +198,12 @@ class DydxChainTransactions implements AbacusDYDXChainTransactionsProtocol {
const parsedTx = this.parseToPrimitives(tx);
const hash = parsedTx?.hash;
if (import.meta.env.MODE === 'production') {
console.log(`https://testnet.mintscan.io/dydx-testnet/txs/${hash}`);
if (isTestnet) {
console.log(
`${ENVIRONMENT_CONFIG_MAP[
this.compositeClient.network.getString() as DydxNetwork
]?.links?.mintscan?.replace('{tx_hash}', hash.toString())}`
);
} else console.log(`txHash: ${hash}`);
return JSON.stringify(parsedTx);
@@ -229,7 +233,7 @@ class DydxChainTransactions implements AbacusDYDXChainTransactionsProtocol {
orderFlags,
clobPairId,
goodTilBlock || undefined,
goodTilBlockTime || undefined,
goodTilBlockTime || undefined
);
const parsedTx = this.parseToPrimitives(tx);
@@ -295,15 +299,11 @@ class DydxChainTransactions implements AbacusDYDXChainTransactionsProtocol {
if (!this.localWallet) {
throw new Error('Missing compositeClient or localWallet');
}
const msg = compositeClient?.sendTokenMessage(
this.localWallet,
amount,
recipient,
);
const msg = compositeClient?.sendTokenMessage(this.localWallet, amount, recipient);
resolve([msg]);
}),
this.compositeClient?.validatorClient?.post.defaultDydxGasPrice,
this.compositeClient?.validatorClient?.post.defaultDydxGasPrice
);
const parsedTx = this.parseToPrimitives(tx);
-5
View File
@@ -1,10 +1,5 @@
import type { AbacusFileSystemProtocol, FileLocation, Nullable } from '@/constants/abacus';
export const ENDPOINTS_PATH =
import.meta.env.MODE === 'production'
? 'config/prod/endpoints.json'
: 'config/staging/dev_endpoints.json';
class AbacusFileSystem implements AbacusFileSystemProtocol {
readTextFile(location: FileLocation, path: string): Nullable<string> {
return null;
+1 -1
View File
@@ -41,7 +41,7 @@ import AbacusStateNotifier from './stateNotification';
import AbacusLocalizer from './localizer';
import AbacusFormatter from './formatter';
import AbacusThreading from './threading';
import AbacusFileSystem, { ENDPOINTS_PATH } from './filesystem';
import AbacusFileSystem from './filesystem';
import { LocaleSeparators } from '../numbers';
class AbacusStateManager {
private store: RootStore | undefined;
+2 -7
View File
@@ -56,13 +56,8 @@ class AbacusRest implements AbacusRestProtocol {
.then(async (response) => {
const data = await response.text();
if (response.ok) {
callback(data, response.status);
} else {
// response not OK, call callback with null data and the status, this includes 400/500 status codes
callback(null, response.status);
}
callback(data, response.status);
try {
lastSuccessfulRestRequestByOrigin[new URL(url).origin] = Date.now();
} catch {}
+23 -4
View File
@@ -1,5 +1,6 @@
import type { AbacusWebsocketProtocol } from '@/constants/abacus';
import type { TradingViewBar } from '@/constants/candles';
import { isDev } from '@/constants/networks';
import {
PING_INTERVAL_MS,
@@ -8,11 +9,12 @@ import {
PONG_MESSAGE_TYPE,
} from '@/constants/websocket';
import { lastSuccessfulWebsocketRequestByOrigin } from '@/hooks/useAnalytics';
import { testFlags } from '@/hooks/useTestFlags';
import { subscriptionsByChannelId } from '@/lib/tradingView/dydxfeed/cache';
import { mapCandle } from '@/lib/tradingView/utils';
import { lastSuccessfulWebsocketRequestByOrigin } from '@/hooks/useAnalytics';
import { log } from '../telemetry';
const RECONNECT_INTERVAL_MS = 10_000;
@@ -143,6 +145,23 @@ class AbacusWebsocket implements Omit<AbacusWebsocketProtocol, '__doNotUseOrImpl
break;
}
case 'v4_markets': {
if (testFlags.displayInitializingMarkets) {
shouldProcess = false;
const { contents } = parsedMessage;
Object.keys(contents.markets ?? {}).forEach((market: any) => {
const status = contents.markets[market].status;
if (status === 'INITIALIZING') {
contents.markets[market].status = 'ONLINE';
}
});
this.receivedCallback?.(JSON.stringify(parsedMessage));
}
break;
}
default: {
break;
}
@@ -161,13 +180,13 @@ class AbacusWebsocket implements Omit<AbacusWebsocketProtocol, '__doNotUseOrImpl
this.socket.onclose = (e) => {
this.connectedCallback?.(false);
if (import.meta.env.MODE === 'production') return;
if (!isDev) return;
console.warn('AbacusStateManager > WS > close > ', e);
};
this.socket.onerror = (e) => {
this.connectedCallback?.(false);
if (import.meta.env.MODE === 'production') return;
if (!isDev) return;
console.error('AbacusStateManager > WS > error > ', e);
};
};
+3 -1
View File
@@ -1,5 +1,7 @@
import { isDev } from "@/constants/networks";
export const log = (location: string, error: Error, metadata?: any) => {
if (import.meta.env.MODE !== 'production') {
if (isDev) {
console.warn('telemetry/log:', { location, error, metadata });
}
+16 -8
View File
@@ -46,6 +46,8 @@ import {
WALLET_CONNECT_EXPLORER_RECOMMENDED_IDS,
} from '@/constants/wallets';
import { isTruthy } from './isTruthy';
// Config
export const WAGMI_SUPPORTED_CHAINS: Chain[] = [
@@ -78,13 +80,17 @@ export const WAGMI_SUPPORTED_CHAINS: Chain[] = [
celoAlfajores,
];
const { chains, publicClient, webSocketPublicClient } = configureChains(WAGMI_SUPPORTED_CHAINS, [
// alchemyProvider({ apiKey: import.meta.env.VITE_ALCHEMY_API_KEY }),
jsonRpcProvider({
rpc: (chain) => ({ http: chain.rpcUrls.default.http[0] }),
}),
publicProvider(),
]);
const { chains, publicClient, webSocketPublicClient } = configureChains(
WAGMI_SUPPORTED_CHAINS,
[
import.meta.env.VITE_ALCHEMY_API_KEY &&
alchemyProvider({ apiKey: import.meta.env.VITE_ALCHEMY_API_KEY }),
jsonRpcProvider({
rpc: (chain) => ({ http: chain.rpcUrls.default.http[0] }),
}),
publicProvider(),
].filter(isTruthy)
);
const injectedConnectorOptions = {
chains,
@@ -202,5 +208,7 @@ export const resolveWagmiConnector = ({
? createInjectedConnectorWithProvider(walletConnection.provider)
: walletConnection.type === WalletConnectionType.WalletConnect2 && walletConfig.walletconnect2Id
? createWalletConnect2ConnectorWithId(walletConfig.walletconnect2Id, walletConnectConfig)
: getConnectors(walletConnectConfig).find(({ id }: { id: string }) => id === walletConnectionConfig.wagmiConnectorId);
: getConnectors(walletConnectConfig).find(
({ id }: { id: string }) => id === walletConnectionConfig.wagmiConnectorId
);
};
+21 -13
View File
@@ -17,7 +17,7 @@ import { DialogTypes } from '@/constants/dialogs';
import { STRING_KEYS } from '@/constants/localization';
import { AppRoute, PortfolioRoute, HistoryRoute } from '@/constants/routes';
import { wallets, WalletType } from '@/constants/wallets';
import { useAccounts, useStringGetter } from '@/hooks';
import { useAccounts, useStringGetter, useTokenConfigs } from '@/hooks';
import { getOnboardingState } from '@/state/accountSelectors';
import { openDialog } from '@/state/dialogs';
@@ -37,6 +37,7 @@ const Profile = () => {
const isConnected = onboardingState !== OnboardingState.Disconnected;
const { evmAddress, dydxAddress, walletType } = useAccounts();
const { chainTokenLabel } = useTokenConfigs();
const { data: ensName } = useEnsName({
address: evmAddress,
@@ -137,7 +138,11 @@ const Profile = () => {
layout="grid"
/>
</Panel>
<Styled.RewardsPanel header={stringGetter({ key: STRING_KEYS.REWARDS })} hasSeparator>
<Styled.RewardsPanel
slotHeaderContent={stringGetter({ key: STRING_KEYS.REWARDS })}
href={`/${chainTokenLabel}`}
hasSeparator
>
<Styled.Details
items={[
{ key: 'maker', label: stringGetter({ key: STRING_KEYS.YOU_WILL_EARN }), value: '-' },
@@ -149,8 +154,8 @@ const Profile = () => {
</Styled.EqualGrid>
<Styled.TablePanel
header={stringGetter({ key: STRING_KEYS.HISTORY })}
linkto={`${AppRoute.Portfolio}/${PortfolioRoute.History}/${HistoryRoute.Trades}`}
slotHeaderContent={stringGetter({ key: STRING_KEYS.HISTORY })}
href={`${AppRoute.Portfolio}/${PortfolioRoute.History}/${HistoryRoute.Trades}`}
hasSeparator
>
<FillsTable
@@ -175,7 +180,7 @@ Styled.MobileProfileLayout = styled.div`
${layoutMixins.contentContainerPage}
gap: 1rem;
padding: 1rem;
padding: 1.25rem;
`;
Styled.Header = styled.header`
@@ -273,22 +278,25 @@ Styled.RewardsPanel = styled(Panel)`
`;
Styled.TablePanel = styled(Panel)`
padding: 0;
max-width: calc(100vw - 2rem);
max-height: 10rem;
--panel-content-paddingY: 0;
--panel-content-paddingX: 0;
> div > div {
margin-top: 0.5rem;
--scrollArea-height: 10rem;
border-radius: 0.875rem;
}
table {
max-height: 10rem;
--tableCell-padding: 0.25rem 1rem;
background-color: transparent;
--tableRow-backgroundColor: var(--color-layer-3);
background-color: var(--color-layer-3);
thead {
color: var(--color-text-0);
}
tbody {
background-color: transparent;
tr {
td:nth-child(2),
td:nth-child(3) {
@@ -131,7 +131,7 @@ export const AccountDetailsAndHistory = () => {
key: 'BuyingPower',
labelKey: STRING_KEYS.BUYING_POWER,
type: OutputType.Fiat,
value: buyingPower?.current,
value: MustBigNumber(buyingPower?.current).lt(0) ? undefined : buyingPower?.current, // show '-' when buying power is negative
},
].filter(isTruthy);
+127 -106
View File
@@ -1,12 +1,12 @@
import { useCallback, useEffect, useMemo, useState } from 'react';
import { useCallback, useMemo } from 'react';
import { Nullable } from '@dydxprotocol/v4-abacus';
import styled, { AnyStyledComponent } from 'styled-components';
import { shallowEqual, useSelector } from 'react-redux';
import { FeeTier } from '@/constants/abacus';
import { FEE_DECIMALS, QUANTUM_MULTIPLIER } from '@/constants/numbers';
import { FEE_DECIMALS } from '@/constants/numbers';
import { STRING_KEYS } from '@/constants/localization';
import { useAccounts, useBreakpoints, useStringGetter } from '@/hooks';
import { useBreakpoints, useStringGetter } from '@/hooks';
import { breakpoints } from '@/styles';
import { layoutMixins } from '@/styles/layoutMixins';
import { tableMixins } from '@/styles/tableMixins';
@@ -29,9 +29,8 @@ const EQUALITY_SYMBOL_MAP = {
};
export const Fees = () => {
const { dydxAddress } = useAccounts();
const stringGetter = useStringGetter();
const { isNotTablet } = useBreakpoints();
const { isTablet, isNotTablet } = useBreakpoints();
const userFeeTier = useSelector(getUserFeeTier, shallowEqual);
const userStats = useSelector(getUserStats, shallowEqual);
const feeTiers = useSelector(getFeeTiers, shallowEqual);
@@ -56,28 +55,28 @@ export const Fees = () => {
<Styled.AdditionalConditions>
{!isAdditional && !totalShare && !makerShare && <Output type={OutputType.Text} />}
{!!totalShare && (
<Styled.TextRow>
{isAdditional && <span>{stringGetter({ key: STRING_KEYS.AND })}</span>}
<span>{stringGetter({ key: STRING_KEYS.EXCHANGE_MARKET_SHARE })}</span>
<Styled.Highlighted>{'>'}</Styled.Highlighted>
<Styled.AdditionalConditionsText>
{isAdditional && stringGetter({ key: STRING_KEYS.AND })}{' '}
{stringGetter({ key: STRING_KEYS.EXCHANGE_MARKET_SHARE })}{' '}
<Styled.Highlighted>{'>'}</Styled.Highlighted>{' '}
<Styled.HighlightOutput
type={OutputType.Percent}
value={totalShare}
fractionDigits={0}
/>
</Styled.TextRow>
</Styled.AdditionalConditionsText>
)}
{!!makerShare && (
<Styled.TextRow>
{isAdditional && <span>{stringGetter({ key: STRING_KEYS.AND })}</span>}
<span>{stringGetter({ key: STRING_KEYS.MAKER_MARKET_SHARE })}</span>
<Styled.Highlighted>{'>'}</Styled.Highlighted>
<Styled.AdditionalConditionsText>
{isAdditional && stringGetter({ key: STRING_KEYS.AND })}{' '}
{stringGetter({ key: STRING_KEYS.MAKER_MARKET_SHARE })}{' '}
<Styled.Highlighted>{'>'}</Styled.Highlighted>{' '}
<Styled.HighlightOutput
type={OutputType.Percent}
value={makerShare}
fractionDigits={0}
/>
</Styled.TextRow>
</Styled.AdditionalConditionsText>
)}
</Styled.AdditionalConditions>
),
@@ -103,91 +102,90 @@ export const Fees = () => {
},
]}
/>
<div>
<Styled.FeeTable
label="Fee Tiers"
data={feeTiers || []}
getRowKey={(row: FeeTier) => row.tier}
getRowAttributes={(row: FeeTier) => ({
'data-yours': row.tier === userFeeTier,
})}
columns={(
[
{
columnKey: 'tier',
getCellValue: (row) => row.tier,
label: stringGetter({ key: STRING_KEYS.TIER }),
allowsSorting: false,
renderCell: ({ tier }) => (
<Styled.Tier>
<Styled.Output type={OutputType.Text} value={tier} />
{tier === userFeeTier && (
<Styled.YouTag size={TagSize.Medium}>
{stringGetter({ key: STRING_KEYS.YOU })}
</Styled.YouTag>
)}
</Styled.Tier>
),
},
{
columnKey: 'volume',
getCellValue: (row) => row.volume,
label: stringGetter({ key: STRING_KEYS.VOLUME_30D }),
allowsSorting: false,
renderCell: ({ symbol, volume, makerShare, totalShare }) => (
<>
<span>{`${
symbol in EQUALITY_SYMBOL_MAP
? EQUALITY_SYMBOL_MAP[symbol as keyof typeof EQUALITY_SYMBOL_MAP]
: symbol
} `}</span>
<Styled.HighlightOutput type={OutputType.CompactFiat} value={volume} />
{!isNotTablet &&
AdditionalConditions({ totalShare, makerShare, isAdditional: true })}
</>
),
},
isNotTablet && {
columnKey: 'condition',
getCellValue: (row) => row.volume,
label: stringGetter({ key: STRING_KEYS.ADDITIONAL_CONDITION }),
allowsSorting: false,
renderCell: ({ totalShare, makerShare }) =>
AdditionalConditions({ totalShare, makerShare }),
},
{
columnKey: 'maker',
getCellValue: (row) => row.maker,
label: stringGetter({ key: STRING_KEYS.MAKER }),
allowsSorting: false,
renderCell: ({ maker }) => (
<Styled.HighlightOutput
type={OutputType.SmallPercent}
value={maker}
fractionDigits={FEE_DECIMALS}
/>
),
},
{
columnKey: 'taker',
getCellValue: (row) => row.taker,
label: stringGetter({ key: STRING_KEYS.TAKER }),
allowsSorting: false,
renderCell: ({ taker }) => (
<Styled.HighlightOutput
type={OutputType.SmallPercent}
value={taker}
fractionDigits={FEE_DECIMALS}
/>
),
},
] as ColumnDef<FeeTier>[]
).filter(isTruthy)}
selectionBehavior="replace"
withOuterBorder={isNotTablet}
withInnerBorders
/>
</div>
<Styled.FeeTable
label="Fee Tiers"
data={feeTiers || []}
getRowKey={(row: FeeTier) => row.tier}
getRowAttributes={(row: FeeTier) => ({
'data-yours': row.tier === userFeeTier,
})}
columns={(
[
{
columnKey: 'tier',
getCellValue: (row) => row.tier,
label: stringGetter({ key: STRING_KEYS.TIER }),
allowsSorting: false,
renderCell: ({ tier }) => (
<Styled.Tier>
<Styled.Output type={OutputType.Text} value={tier} />
{tier === userFeeTier && (
<Styled.YouTag size={TagSize.Medium}>
{stringGetter({ key: STRING_KEYS.YOU })}
</Styled.YouTag>
)}
</Styled.Tier>
),
},
{
columnKey: 'volume',
getCellValue: (row) => row.volume,
label: stringGetter({ key: STRING_KEYS.VOLUME_30D }),
allowsSorting: false,
renderCell: ({ symbol, volume, makerShare, totalShare }) => (
<>
<span>{`${
symbol in EQUALITY_SYMBOL_MAP
? EQUALITY_SYMBOL_MAP[symbol as keyof typeof EQUALITY_SYMBOL_MAP]
: symbol
} `}</span>
<Styled.HighlightOutput type={OutputType.CompactFiat} value={volume} />
{isTablet &&
AdditionalConditions({ totalShare, makerShare, isAdditional: true })}
</>
),
},
isNotTablet && {
columnKey: 'condition',
getCellValue: (row) => row.volume,
label: stringGetter({ key: STRING_KEYS.ADDITIONAL_CONDITION }),
allowsSorting: false,
renderCell: ({ totalShare, makerShare }) =>
AdditionalConditions({ totalShare, makerShare }),
},
{
columnKey: 'maker',
getCellValue: (row) => row.maker,
label: stringGetter({ key: STRING_KEYS.MAKER }),
allowsSorting: false,
renderCell: ({ maker }) => (
<Styled.HighlightOutput
type={OutputType.SmallPercent}
value={maker}
fractionDigits={FEE_DECIMALS}
/>
),
},
{
columnKey: 'taker',
getCellValue: (row) => row.taker,
label: stringGetter({ key: STRING_KEYS.TAKER }),
allowsSorting: false,
renderCell: ({ taker }) => (
<Styled.HighlightOutput
type={OutputType.SmallPercent}
value={taker}
fractionDigits={FEE_DECIMALS}
/>
),
},
] as ColumnDef<FeeTier>[]
).filter(isTruthy)}
selectionBehavior="replace"
withOuterBorder={isNotTablet}
withInnerBorders
/>
</Styled.ContentWrapper>
</AttachedExpandingSection>
);
@@ -198,21 +196,43 @@ const Styled: Record<string, AnyStyledComponent> = {};
Styled.ContentWrapper = styled.div`
${layoutMixins.flexColumn}
gap: 1.5rem;
max-width: 100vw;
`;
Styled.AdditionalConditions = styled.div`
${tableMixins.cellContentColumn}
justify-content: end;
color: var(--color-text-0);
font: var(--font-small-book);
> :nth-child(2) {
font: var(--font-base-book);
font: var(--font-small-book);
}
`;
Styled.AdditionalConditionsText = styled.span`
display: flex;
gap: 0.5ch;
@media ${breakpoints.mobile} {
display: inline;
max-width: 8rem;
min-width: 0;
output {
display: inline;
}
}
`;
Styled.FeesDetails = styled(Details)`
gap: 1rem;
@media ${breakpoints.notTablet} {
margin: 0 1.25rem;
}
@media ${breakpoints.tablet} {
padding: 1rem 1rem 0 1rem;
--details-grid-numColumns: 1;
@@ -237,11 +257,7 @@ Styled.FeesDetails = styled(Details)`
}
output {
font: var(--font-medium-book);
@media ${breakpoints.tablet} {
font: var(--font-base-book);
}
font: var(--font-base-book);
}
`;
@@ -271,6 +287,11 @@ Styled.FeeTable = styled(Table)`
font: var(--font-base-book);
@media ${breakpoints.mobile} {
--tableCell-padding: 1rem 1.25rem;
font: var(--font-small-book);
}
tbody tr {
&[data-yours='true'] {
background-color: var(--color-layer-3);
+104 -42
View File
@@ -1,11 +1,13 @@
import { useEffect } from 'react';
import { shallowEqual, useDispatch, useSelector } from 'react-redux';
import styled, { type AnyStyledComponent } from 'styled-components';
import { Navigate, Route, Routes } from 'react-router-dom';
import { OnboardingState } from '@/constants/account';
import { DialogTypes } from '@/constants/dialogs';
import { STRING_KEYS } from '@/constants/localization';
import { HistoryRoute, PortfolioRoute } from '@/constants/routes';
import { useBreakpoints, useDocumentTitle, useStringGetter } from '@/hooks';
import { useAccountBalance, useBreakpoints, useDocumentTitle, useStringGetter } from '@/hooks';
import { FillsTable, FillsTableColumnKey } from '@/views/tables/FillsTable';
import { FundingPaymentsTable } from '@/views/tables/FundingPaymentsTable';
@@ -14,6 +16,9 @@ import { Icon, IconName } from '@/components/Icon';
import { NavigationMenu } from '@/components/NavigationMenu';
import { WithSidebar } from '@/components/WithSidebar';
import { getOnboardingState, getSubaccount } from '@/state/accountSelectors';
import { openDialog } from '@/state/dialogs';
import { PortfolioNavMobile } from './PortfolioNavMobile';
import { Overview } from './Overview';
import { Positions } from './Positions';
@@ -22,11 +27,20 @@ import { Fees } from './Fees';
import { History } from './History';
import { layoutMixins } from '@/styles/layoutMixins';
import { Button } from '@/components/Button';
import { ButtonAction } from '@/constants/buttons';
export default () => {
const dispatch = useDispatch();
const stringGetter = useStringGetter();
const { isTablet, isNotTablet } = useBreakpoints();
const onboardingState = useSelector(getOnboardingState);
const { freeCollateral } = useSelector(getSubaccount, shallowEqual) || {};
const { nativeTokenBalance } = useAccountBalance();
const usdcBalance = freeCollateral?.current || 0;
useDocumentTitle(stringGetter({ key: STRING_KEYS.PORTFOLIO }));
const routesComponent = (
@@ -84,46 +98,74 @@ export default () => {
<WithSidebar
sidebar={
isTablet ? null : (
<Styled.NavigationMenu
items={[
{
group: 'views',
groupLabel: stringGetter({ key: STRING_KEYS.VIEWS }),
items: [
{
value: PortfolioRoute.Overview,
slotBefore: <Styled.Icon iconName={IconName.Overview} />,
label: stringGetter({ key: STRING_KEYS.OVERVIEW }),
href: PortfolioRoute.Overview,
},
{
value: PortfolioRoute.Positions,
slotBefore: <Styled.Icon iconName={IconName.Cube} />,
label: stringGetter({ key: STRING_KEYS.POSITIONS }),
href: PortfolioRoute.Positions,
},
{
value: PortfolioRoute.Orders,
slotBefore: <Styled.Icon iconName={IconName.OrderPending} />,
label: stringGetter({ key: STRING_KEYS.ORDERS }),
href: PortfolioRoute.Orders,
},
{
value: PortfolioRoute.Fees,
slotBefore: <Styled.Icon iconName={IconName.Calculator} />,
label: stringGetter({ key: STRING_KEYS.FEES }),
href: PortfolioRoute.Fees,
},
{
value: PortfolioRoute.History,
slotBefore: <Styled.Icon iconName={IconName.History} />,
label: stringGetter({ key: STRING_KEYS.HISTORY }),
href: PortfolioRoute.History,
},
],
},
]}
/>
<Styled.SideBar>
<Styled.NavigationMenu
items={[
{
group: 'views',
groupLabel: stringGetter({ key: STRING_KEYS.VIEWS }),
items: [
{
value: PortfolioRoute.Overview,
slotBefore: <Styled.Icon iconName={IconName.Overview} />,
label: stringGetter({ key: STRING_KEYS.OVERVIEW }),
href: PortfolioRoute.Overview,
},
{
value: PortfolioRoute.Positions,
slotBefore: <Styled.Icon iconName={IconName.Cube} />,
label: stringGetter({ key: STRING_KEYS.POSITIONS }),
href: PortfolioRoute.Positions,
},
{
value: PortfolioRoute.Orders,
slotBefore: <Styled.Icon iconName={IconName.OrderPending} />,
label: stringGetter({ key: STRING_KEYS.ORDERS }),
href: PortfolioRoute.Orders,
},
{
value: PortfolioRoute.Fees,
slotBefore: <Styled.Icon iconName={IconName.Calculator} />,
label: stringGetter({ key: STRING_KEYS.FEES }),
href: PortfolioRoute.Fees,
},
{
value: PortfolioRoute.History,
slotBefore: <Styled.Icon iconName={IconName.History} />,
label: stringGetter({ key: STRING_KEYS.HISTORY }),
href: PortfolioRoute.History,
},
],
},
]}
/>
{onboardingState === OnboardingState.AccountConnected && (
<Styled.Footer>
<Button
action={ButtonAction.Primary}
onClick={() => dispatch(openDialog({ type: DialogTypes.Deposit }))}
>
{stringGetter({ key: STRING_KEYS.DEPOSIT })}
</Button>
{usdcBalance > 0 && (
<Button
action={ButtonAction.Base}
onClick={() => dispatch(openDialog({ type: DialogTypes.Withdraw }))}
>
{stringGetter({ key: STRING_KEYS.WITHDRAW })}
</Button>
)}
{(usdcBalance > 0 || nativeTokenBalance.gt(0)) && (
<Button
action={ButtonAction.Base}
onClick={() => dispatch(openDialog({ type: DialogTypes.Transfer }))}
>
{stringGetter({ key: STRING_KEYS.TRANSFER })}
</Button>
)}
</Styled.Footer>
)}
</Styled.SideBar>
)
}
>
@@ -139,6 +181,26 @@ Styled.PortfolioMobile = styled.div`
${layoutMixins.expandingColumnWithHeader}
`;
Styled.SideBar = styled.div`
${layoutMixins.flexColumn}
justify-content: space-between;
height: 100%;
`;
Styled.Footer = styled.div`
${layoutMixins.row}
flex-wrap: wrap;
padding: 1rem;
gap: 0.5rem;
> button {
flex-grow: 1;
}
`;
Styled.NavigationMenu = styled(NavigationMenu)`
padding: 0.5rem;
padding-top: 0;
+17 -21
View File
@@ -32,34 +32,25 @@ export const DYDXBalancePanel = () => {
const { chainTokenLabel } = useTokenConfigs();
return (
<Panel
<Styled.Panel
slotHeader={
<Styled.Header>
<Styled.Title>
{/* <AssetIcon symbol="DYDX" /> */}
<AssetIcon symbol={chainTokenLabel} />
{chainTokenLabel}
</Styled.Title>
<Styled.ReceiveAndTransferButtons>
{!canAccountTrade ? (
<OnboardingTriggerButton size={ButtonSize.Small} />
) : (
<>
<Styled.ReceiveButton
slotLeft={<Icon iconName={IconName.Qr} />}
size={ButtonSize.Small}
onClick={() => dispatch(openDialog({ type: DialogTypes.Receive }))}
>
{stringGetter({ key: STRING_KEYS.RECEIVE })}
</Styled.ReceiveButton>
<Button
slotLeft={<Icon iconName={IconName.Send} />}
size={ButtonSize.Small}
action={ButtonAction.Primary}
onClick={() => dispatch(openDialog({ type: DialogTypes.Transfer }))}
>
{stringGetter({ key: STRING_KEYS.TRANSFER })}
</Button>
</>
<Button
slotLeft={<Icon iconName={IconName.Send} />}
size={ButtonSize.Small}
action={ButtonAction.Primary}
onClick={() => dispatch(openDialog({ type: DialogTypes.Transfer }))}
>
{stringGetter({ key: STRING_KEYS.TRANSFER })}
</Button>
)}
</Styled.ReceiveAndTransferButtons>
</Styled.Header>
@@ -117,14 +108,19 @@ export const DYDXBalancePanel = () => {
]}
/>
</Styled.Content>
</Panel>
</Styled.Panel>
);
};
const Styled: Record<string, AnyStyledComponent> = {};
Styled.Panel = styled(Panel)`
--panel-paddingX: 1.5rem;
`;
Styled.Header = styled.div`
${layoutMixins.spacedRow}
gap: 1rem;
padding: 1rem 1.5rem 0;
`;
@@ -177,7 +173,7 @@ Styled.WalletAndStakedBalance = styled(Details)`
--details-item-backgroundColor: var(--color-layer-6);
grid-template-columns: 1fr 1fr;
gap: 0.5rem;
gap: 1rem;
> div {
gap: 1rem;
+224
View File
@@ -0,0 +1,224 @@
import styled, { AnyStyledComponent } from 'styled-components';
import { useSelector } from 'react-redux';
import { ENVIRONMENT_CONFIG_MAP } from '@/constants/networks';
import { STRING_KEYS } from '@/constants/localization';
import { ButtonAction, ButtonSize, ButtonType } from '@/constants/buttons';
import { useAccountBalance, useBreakpoints, useStringGetter } from '@/hooks';
import { layoutMixins } from '@/styles/layoutMixins';
import { Details } from '@/components/Details';
import { Panel } from '@/components/Panel';
import { Button } from '@/components/Button';
import { Link } from '@/components/Link';
import { IconName, Icon } from '@/components/Icon';
import { Output, OutputType } from '@/components/Output';
import { VerticalSeparator } from '@/components/Separator';
import { Tag } from '@/components/Tag';
import { WithReceipt } from '@/components/WithReceipt';
import { getSelectedNetwork } from '@/state/appSelectors';
import { MustBigNumber } from '@/lib/numbers';
const TOKEN_MIGRATION_LEARN_MORE_LINK =
'https://www.dydx.foundation/blog/update-on-exploring-the-future-of-dydx';
export const MigratePanel = () => {
const { isNotTablet } = useBreakpoints();
const stringGetter = useStringGetter();
const selectedNetwork = useSelector(getSelectedNetwork);
const chainId = Number(ENVIRONMENT_CONFIG_MAP[selectedNetwork].ethereumChainId);
// v3 token is only on mainnet
const { balance: tokenBalance } = useAccountBalance({
addressOrDenom: chainId === 1 ? import.meta.env.VITE_V3_TOKEN_ADDRESS : undefined,
chainId: 1,
isCosmosChain: false,
});
return isNotTablet ? (
<Styled.MigratePanel
slotHeader={<Styled.Title>{stringGetter({ key: STRING_KEYS.MIGRATE })}</Styled.Title>}
slotRight={
<Styled.MigrateAction>
<div>
<div>{stringGetter({ key: STRING_KEYS.AVAILABLE_TO_MIGRATE })}</div>
<Styled.Token type={OutputType.Asset} value={tokenBalance} />
</div>
{import.meta.env.VITE_TOKEN_MIGRATION_URI && (
<Button
action={MustBigNumber(tokenBalance).gt(0) ? ButtonAction.Primary : ButtonAction.Base}
type={ButtonType.Link}
href={import.meta.env.VITE_TOKEN_MIGRATION_URI}
slotRight={<Icon iconName={IconName.LinkOut} />}
>
{stringGetter({ key: STRING_KEYS.MIGRATE_NOW })}
</Button>
)}
</Styled.MigrateAction>
}
>
<Styled.Description>
{stringGetter({ key: STRING_KEYS.MIGRATE_DESCRIPTION })}
<Link href={TOKEN_MIGRATION_LEARN_MORE_LINK}>
{stringGetter({ key: STRING_KEYS.LEARN_MORE })}
</Link>
</Styled.Description>
</Styled.MigratePanel>
) : (
<Styled.MigratePanel
slotHeader={
<Styled.MobileMigrateHeader>
<h3>
<Icon iconName={IconName.Migrate} />
{stringGetter({ key: STRING_KEYS.MIGRATE })}
</h3>
<Styled.VerticalSeparator />
<span>
{stringGetter({
key: STRING_KEYS.FROM_TO,
params: { FROM: <b>Ethereum</b>, TO: <b>dYdX Chain</b> },
})}
</span>
</Styled.MobileMigrateHeader>
}
>
<Styled.Column>
<Styled.WithReceipt
slotReceipt={
<Styled.Details
items={[
{
key: 'available-to-migrate',
label: (
<Styled.InlineRow>
{stringGetter({ key: STRING_KEYS.AVAILABLE_TO_MIGRATE })}
<Tag>DYDX</Tag>
</Styled.InlineRow>
),
value: <Output type={OutputType.Asset} value={tokenBalance} />,
},
]}
/>
}
>
{import.meta.env.VITE_TOKEN_MIGRATION_URI && (
<Button
action={tokenBalance ? ButtonAction.Primary : ButtonAction.Base}
size={ButtonSize.Medium}
slotRight={<Icon iconName={IconName.LinkOut} />}
href={import.meta.env.VITE_TOKEN_MIGRATION_URI}
>
{stringGetter({ key: STRING_KEYS.MIGRATE_NOW })}
</Button>
)}
</Styled.WithReceipt>
<Styled.InlineRow>
{stringGetter({ key: STRING_KEYS.WANT_TO_LEARN })}
<Link href={TOKEN_MIGRATION_LEARN_MORE_LINK} withIcon>
{stringGetter({ key: STRING_KEYS.CLICK_HERE })}
</Link>
</Styled.InlineRow>
</Styled.Column>
</Styled.MigratePanel>
);
};
const Styled: Record<string, AnyStyledComponent> = {};
Styled.MigratePanel = styled(Panel)`
--panel-paddingX: 1.5rem;
width: 100%;
`;
Styled.Title = styled.h3`
font: var(--font-medium-book);
color: var(--color-text-2);
padding: 1rem 1.5rem 0;
`;
Styled.MigrateAction = styled.div`
${layoutMixins.flexEqualColumns}
align-items: center;
margin-right: 1rem;
gap: 1rem;
padding: 1rem;
width: 100%;
background-color: var(--color-layer-2);
border: solid var(--border-width) var(--color-border);
border-radius: 0.75rem;
`;
Styled.Token = styled(Output)`
font: var(--font-large-book);
color: var(--color-text-2);
`;
Styled.Description = styled.div`
color: var(--color-text-0);
--link-color: var(--color-text-1);
`;
Styled.Column = styled.div`
${layoutMixins.flexColumn}
gap: 1rem;
align-items: center;
`;
Styled.MobileMigrateHeader = styled.div`
${layoutMixins.inlineRow}
gap: 1ch;
font: var(--font-small-book);
color: var(--color-text-0);
padding: 1rem 1.5rem 0;
h3 {
${layoutMixins.inlineRow}
font: var(--font-large-book);
color: var(--color-text-2);
svg {
font-size: 1.75rem;
}
}
span {
margin-top: 0.2rem;
b {
font-weight: var(--fontWeight-book);
color: var(--color-text-1);
}
}
`;
Styled.VerticalSeparator = styled(VerticalSeparator)`
z-index: 1;
&& {
height: 1.5rem;
}
`;
Styled.Details = styled(Details)`
padding: 0.5rem 1rem;
`;
Styled.WithReceipt = styled(WithReceipt)`
width: 100%;
`;
Styled.InlineRow = styled.div`
${layoutMixins.inlineRow}
color: var(--color-text-0);
--link-color: var(--color-text-1);
`;
+58 -257
View File
@@ -1,186 +1,74 @@
import styled, { AnyStyledComponent } from 'styled-components';
import { useDispatch, useSelector } from 'react-redux';
import { useDispatch } from 'react-redux';
import { ENVIRONMENT_CONFIG_MAP } from '@/constants/networks';
import { STRING_KEYS } from '@/constants/localization';
import { ButtonAction, ButtonSize, ButtonState, ButtonType } from '@/constants/buttons';
import { ButtonAction, ButtonSize } from '@/constants/buttons';
import { DialogTypes } from '@/constants/dialogs';
import { useAccountBalance, useBreakpoints, useStringGetter } from '@/hooks';
import { useBreakpoints, useStringGetter, useURLConfigs } from '@/hooks';
import { breakpoints } from '@/styles';
import { layoutMixins } from '@/styles/layoutMixins';
import { Details } from '@/components/Details';
import { Panel } from '@/components/Panel';
import { IconName } from '@/components/Icon';
import { Button } from '@/components/Button';
import { IconButton } from '@/components/IconButton';
import { Link } from '@/components/Link';
import { Output, OutputType } from '@/components/Output';
import { VerticalSeparator } from '@/components/Separator';
import { WithReceipt } from '@/components/WithReceipt';
import { openDialog } from '@/state/dialogs';
import { getSelectedNetwork } from '@/state/appSelectors';
import { DYDXBalancePanel } from './DYDXBalancePanel';
// TODO: replace placeholder URL with real URLs when avaialble
const GOVERNANCE_HELP_URL = 'https://help.dydx.exchange/';
const STAKING_HELP_URL = 'https://help.dydx.exchange/';
import { MigratePanel } from './MigratePanel';
export const RewardsPage = () => {
const dispatch = useDispatch();
const stringGetter = useStringGetter();
const { governanceLearnMore, stakingLearnMore } = useURLConfigs();
const { isTablet, isNotTablet } = useBreakpoints();
const selectedNetwork = useSelector(getSelectedNetwork);
// const chainId = Number(ENVIRONMENT_CONFIG_MAP[selectedNetwork].ethereumChainId);
// const { balance } = useAccountBalance({
// addressOrDenom: import.meta.env.VITE_V3_TOKEN_ADDRESS,
// assetSymbol: 'DYDX',
// chainId,
// isCosmosChain: false,
// });
// const tokenBalance = import.meta.env.VITE_V3_TOKEN_ADDRESS ? balance : 0;
const panelArrow = (
<Styled.Arrow>
<Styled.IconButton
action={ButtonAction.Base}
iconName={IconName.Arrow}
size={ButtonSize.Small}
/>
</Styled.Arrow>
);
return (
<Styled.Page>
{/* {isNotTablet ? (
<Styled.Migrate>
<Styled.TwoItemRow>
<div>
<Styled.MigrateTitle>
{stringGetter({ key: STRING_KEYS.MIGRATE })}
</Styled.MigrateTitle>
<Styled.Description>
{stringGetter({ key: STRING_KEYS.MIGRATE_DESCRIPTION })}
<Link href={MIGRATE_HELP_URL}>
{stringGetter({ key: STRING_KEYS.LEARN_MORE })} →
</Link>
</Styled.Description>
</div>
<Styled.MigrateAction>
<div>
<div>{stringGetter({ key: STRING_KEYS.AVAILABLE_TO_MIGRATE })}</div>
<div>
<Styled.Token type={OutputType.Asset} value={tokenBalance} />
</div>
</div>
<Button
action={tokenBalance ? ButtonAction.Primary : ButtonAction.Base}
// type={ButtonType.Link}
// href={BRIDGE_URL}
disabled
>
{tokenBalance
? `${stringGetter({ key: STRING_KEYS.MIGRATE_NOW })} →`
: stringGetter({ key: STRING_KEYS.NO_TOKENS_TO_MIGRATE })}
</Button>
</Styled.MigrateAction>
</Styled.TwoItemRow>
</Styled.Migrate>
) : (
<Styled.MobileMigrateCard
slotHeader={
<Styled.MobileMigrateHeader>
<h3>{stringGetter({ key: STRING_KEYS.MIGRATE })}</h3>
<VerticalSeparator />
<span>
{stringGetter({
key: STRING_KEYS.FROM_TO,
params: { FROM: <strong>Ethereum</strong>, TO: <strong>dYdX Chain</strong> },
})}
</span>
</Styled.MobileMigrateHeader>
}
>
<Styled.WithReceipt
slotReceipt={
<Styled.Details
items={[
{
key: 'available-to-migrate',
label: stringGetter({ key: STRING_KEYS.AVAILABLE_TO_MIGRATE }),
value: <Output type={OutputType.Asset} value={tokenBalance} />,
},
]}
/>
}
>
<Button
action={tokenBalance ? ButtonAction.Primary : ButtonAction.Base}
size={ButtonSize.Medium}
disabled
>
{tokenBalance
? `${stringGetter({ key: STRING_KEYS.MIGRATE_NOW })} →`
: stringGetter({ key: STRING_KEYS.NO_TOKENS_TO_MIGRATE })}
</Button>
</Styled.WithReceipt>
<Styled.LearnMore>
{stringGetter({ key: STRING_KEYS.WANT_TO_LEARN })}
<Link href={MIGRATE_HELP_URL}>{stringGetter({ key: STRING_KEYS.CLICK_HERE })}</Link>
</Styled.LearnMore>
</Styled.MobileMigrateCard>
)} */}
{import.meta.env.VITE_V3_TOKEN_ADDRESS && <MigratePanel />}
<Styled.PanelRow>
{isTablet && (
<Styled.BalancePanelContainer>
<DYDXBalancePanel />
</Styled.BalancePanelContainer>
)}
{isTablet && <DYDXBalancePanel />}
<Styled.Panel
slotHeader={<Styled.Title>{stringGetter({ key: STRING_KEYS.GOVERNANCE })}</Styled.Title>}
slotRight={panelArrow}
onClick={() => dispatch(openDialog({ type: DialogTypes.ExternalNavKeplr }))}
>
<Styled.Row>
<Styled.Description>
{stringGetter({ key: STRING_KEYS.GOVERNANCE_DESCRIPTION })}
<Link href={GOVERNANCE_HELP_URL} onClick={(e) => e.stopPropagation()}>
{stringGetter({ key: STRING_KEYS.LEARN_MORE })}
</Link>
</Styled.Description>
{/* TODO: vertically center based on Panel height */}
<Styled.IconButton
action={ButtonAction.Base}
iconName={IconName.Arrow}
size={ButtonSize.Small}
/>
</Styled.Row>
<Styled.Description>
{stringGetter({ key: STRING_KEYS.GOVERNANCE_DESCRIPTION })}
<Link href={governanceLearnMore} onClick={(e) => e.stopPropagation()}>
{stringGetter({ key: STRING_KEYS.LEARN_MORE })}
</Link>
</Styled.Description>
</Styled.Panel>
<Styled.Panel
slotHeader={<Styled.Title>{stringGetter({ key: STRING_KEYS.STAKING })}</Styled.Title>}
slotRight={panelArrow}
onClick={() => dispatch(openDialog({ type: DialogTypes.ExternalNavKeplr }))}
>
<Styled.Row>
<Styled.Description>
{stringGetter({ key: STRING_KEYS.STAKING_DESCRIPTION })}
<Link href={STAKING_HELP_URL} onClick={(e) => e.stopPropagation()}>
{stringGetter({ key: STRING_KEYS.LEARN_MORE })}
</Link>
</Styled.Description>
{/* TODO: vertically center based on Panel height */}
<Styled.IconButton
action={ButtonAction.Base}
iconName={IconName.Arrow}
size={ButtonSize.Small}
/>
</Styled.Row>
<Styled.Description>
{stringGetter({ key: STRING_KEYS.STAKING_DESCRIPTION })}
<Link href={stakingLearnMore} onClick={(e) => e.stopPropagation()}>
{stringGetter({ key: STRING_KEYS.LEARN_MORE })}
</Link>
</Styled.Description>
</Styled.Panel>
{isNotTablet && (
<Styled.BalancePanelContainer>
<DYDXBalancePanel />
</Styled.BalancePanelContainer>
)}
{isNotTablet && <DYDXBalancePanel />}
</Styled.PanelRow>
</Styled.Page>
);
@@ -191,143 +79,56 @@ const Styled: Record<string, AnyStyledComponent> = {};
Styled.Page = styled.div`
${layoutMixins.contentContainerPage}
gap: 1.5rem;
padding: 2rem;
align-items: center;
> * {
--content-max-width: 70rem;
max-width: min(calc(100vw - 4rem), var(--content-max-width));
}
@media ${breakpoints.tablet} {
padding: 1rem;
padding: 1.25rem;
> * {
max-width: calc(100vw - 2.5rem);
width: 100%;
}
}
`;
Styled.Panel = styled(Panel)`
padding: 0 1.5rem 1rem;
@media ${breakpoints.tablet} {
max-width: calc(100vw - 2rem);
}
--panel-paddingX: 1.5rem;
`;
Styled.Row = styled.div`
${layoutMixins.spacedRow}
gap: 1rem;
align-items: center;
Styled.Title = styled.h3`
font: var(--font-medium-book);
color: var(--color-text-2);
padding: 1rem 1.5rem 0;
`;
Styled.Description = styled.div`
color: var(--color-text-0);
a {
color: var(--color-text-1);
}
--link-color: var(--color-text-1);
`;
Styled.Migrate = styled.section`
max-width: min(100vw, var(--content-max-width));
padding: 1.5rem;
background-color: var(--color-layer-3);
border-radius: 0.875rem;
`;
Styled.TwoItemRow = styled(Styled.Row)`
grid-template-columns: 1fr 1fr;
`;
Styled.MigrateAction = styled(Styled.TwoItemRow)`
padding: 1rem;
background-color: var(--color-layer-2);
border: solid var(--border-width) var(--color-border);
border-radius: 0.75rem;
`;
Styled.Token = styled(Output)`
font: var(--font-large-book);
`;
Styled.PanelRow = styled(Styled.Row)`
Styled.PanelRow = styled.div`
${layoutMixins.gridEqualColumns}
gap: 1.5rem;
max-width: min(100vw, var(--content-max-width));
align-items: flex-start;
> section {
cursor: pointer;
}
align-items: flex-start;
@media ${breakpoints.tablet} {
grid-auto-flow: row;
grid-template-columns: 1fr;
max-width: auto;
}
`;
Styled.BalancePanelContainer = styled.div`
width: 21.25rem;
@media ${breakpoints.tablet} {
width: auto;
}
`;
Styled.Title = styled.h3`
${layoutMixins.inlineRow}
padding: 1.25rem 1.5rem 0.5rem;
font: var(--font-medium-book);
color: var(--color-text-2);
`;
Styled.MigrateTitle = styled(Styled.Title)`
padding: 0 0 0.5rem;
`;
Styled.MobileMigrateCard = styled(Styled.Panel)`
${layoutMixins.flexColumn}
gap: 1rem;
align-items: center;
`;
Styled.MobileMigrateHeader = styled(Styled.Title)`
${layoutMixins.inlineRow}
gap: 1ch;
padding-bottom: 1rem;
font: var(--font-small-book);
color: var(--color-text-0);
h3 {
${layoutMixins.inlineRow}
font: var(--font-large-book);
color: var(--color-text-2);
svg {
font-size: 1.75rem;
}
}
span {
margin-top: 0.2rem;
b {
font-weight: var(--fontWeight-book);
color: var(--color-text-1);
}
}
`;
Styled.Details = styled(Details)`
padding: 0.5rem 1rem;
`;
Styled.WithReceipt = styled(WithReceipt)`
width: 100%;
`;
Styled.LearnMore = styled(Styled.Description)`
${layoutMixins.row}
gap: 1ch;
`;
Styled.IconButton = styled(IconButton)`
color: var(--color-text-0);
--color-border: var(--color-layer-6);
`;
Styled.Arrow = styled.div`
padding: 1rem;
`;
+2 -2
View File
@@ -227,8 +227,8 @@ export const HorizontalPanel = ({ isOpen = true, setIsOpen }: ElementProps) => {
},
]}
value={view}
onValueChange={(newView: string) => {
setView((newView || view) as PanelView);
onValueChange={setView}
onInteraction={() => {
setIsOpen?.(true);
}}
/>
+2 -2
View File
@@ -17,7 +17,7 @@ import { MustBigNumber } from '@/lib/numbers';
import { MidMarketPrice } from '@/views/MidMarketPrice';
export const TradeHeaderMobile = () => {
const { name, symbol } = useSelector(getCurrentMarketAssetData, shallowEqual) ?? {};
const { name, id } = useSelector(getCurrentMarketAssetData, shallowEqual) ?? {};
const navigate = useNavigate();
const { market, priceChange24H, priceChange24HPercent } =
@@ -27,7 +27,7 @@ export const TradeHeaderMobile = () => {
<Styled.Header>
<BackButton onClick={() => navigate(AppRoute.Markets)} />
<Styled.MarketName>
<Styled.AssetIcon symbol={symbol} />
<Styled.AssetIcon symbol={id} />
<Styled.Name>
<h3>{name}</h3>
<span>{market}</span>
+2 -1
View File
@@ -2,6 +2,7 @@ import type { PayloadAction } from '@reduxjs/toolkit';
import { AbacusApiStatus } from '@/constants/abacus';
import { DialogTypes } from '@/constants/dialogs';
import { isDev } from '@/constants/networks';
import { setApiState, setSelectedNetwork } from '@/state/app';
import { resetPerpetualsState } from '@/state/perpetuals';
@@ -30,7 +31,7 @@ export default (store: any) => (next: any) => async (action: PayloadAction<any>)
store.dispatch(
openDialog({
type: DialogTypes.ExchangeOffline,
dialogProps: { preventClose: import.meta.env.MODE === 'production' },
dialogProps: { preventClose: !isDev },
})
);
}
+9
View File
@@ -48,6 +48,15 @@ export const getTradeInputErrors = (state: RootState) => {
return currentInput === 'trade' ? getInputErrors(state) : [];
};
/**
* @param state
* @returns input errors for Close position
*/
export const getClosePositionInputErrors = (state: RootState) => {
const currentInput = state.inputs.current;
return currentInput === 'closePosition' ? getInputErrors(state) : [];
};
/**
* @param state
* @returns input errors for Transfer
-4
View File
@@ -18,9 +18,5 @@ export const tradeViewMixins: Record<
tbody {
font: var(--font-small-book);
}
thead tr {
box-shadow: none;
}
`,
};
@@ -151,7 +151,10 @@ export const AccountInfoConnectedState = () => {
),
label: stringGetter({ key: STRING_KEYS.BUYING_POWER }),
type: OutputType.Fiat,
value: buyingPower,
value:
MustBigNumber(buyingPower?.current).lt(0) && buyingPower?.postOrder === null
? undefined
: buyingPower,
},
].map(
({
+1 -1
View File
@@ -29,7 +29,7 @@ export const MarketFilter = ({
<>
{!isSearch && (
<ToggleGroup
items={Object.entries(filters).map(([key, value]) => ({
items={Object.values(filters).map((value) => ({
label: stringGetter({ key: MARKET_FILTER_LABELS[value] }),
value,
}))}
-2
View File
@@ -198,8 +198,6 @@ Styled.Details = styled(Details)`
@media ${breakpoints.tablet} {
${layoutMixins.withOuterAndInnerBorders}
display: grid;
grid-template-columns: repeat(auto-fit, minmax(9rem, 1fr));
font: var(--font-small-book);
> * {
+5 -5
View File
@@ -82,18 +82,18 @@ const MarketsDropdownContent = ({ onRowAction }: { onRowAction?: (market: string
),
},
{
columnKey: 'priceChange24H',
getCellValue: (row) => row.priceChange24H,
columnKey: 'priceChange24HPercent',
getCellValue: (row) => row.priceChange24HPercent,
label: stringGetter({ key: STRING_KEYS._24H }),
renderCell: ({ priceChange24H, priceChange24HPercent }) => (
renderCell: ({ priceChange24HPercent }) => (
<Styled.InlineRow>
{!priceChange24H ? (
{!priceChange24HPercent ? (
<Styled.Output type={OutputType.Text} value={null} />
) : (
<Styled.PriceChangeOutput
type={OutputType.Percent}
value={priceChange24HPercent}
isNegative={MustBigNumber(priceChange24H).isNegative()}
isNegative={MustBigNumber(priceChange24HPercent).isNegative()}
/>
)}
</Styled.InlineRow>
+13 -4
View File
@@ -34,7 +34,7 @@ export const TransferStatusToast = ({
}: ElementProps) => {
const stringGetter = useStringGetter();
const [open, setOpen] = useState<boolean>(false);
const [secondsLeft, setSecondsLeft] = useState<number | undefined>();
const [secondsLeft, setSecondsLeft] = useState<number>(0);
// @ts-ignore status.errors is not in the type definition but can be returned
const error = status?.errors?.length ? status?.errors[0] : status?.error;
@@ -49,14 +49,23 @@ export const TransferStatusToast = ({
if (!status) return <LoadingDots size={3} />;
const inProgressStatusString =
type === 'deposit'
? secondsLeft > 0
? STRING_KEYS.DEPOSIT_STATUS
: STRING_KEYS.DEPOSIT_STATUS_SHORTLY
: secondsLeft > 0
? STRING_KEYS.WITHDRAW_STATUS
: STRING_KEYS.WITHDRAW_STATUS_SHORTLY;
const statusString =
type === 'deposit'
? status?.squidTransactionStatus === 'success'
? STRING_KEYS.DEPOSIT_COMPLETE
: STRING_KEYS.DEPOSIT_STATUS
: inProgressStatusString
: status?.squidTransactionStatus === 'success'
? STRING_KEYS.WITHDRAW_COMPLETE
: STRING_KEYS.WITHDRAW_STATUS;
: inProgressStatusString;
return (
<Styled.Root open={open} onOpenChange={setOpen}>
@@ -168,7 +177,7 @@ Styled.TriggerIcon = styled.span`
width: 0.75em;
display: inline-flex;
transition: transform 0.3s var(--ease-out-expo);
transition: rotate 0.3s var(--ease-out-expo);
${Styled.Trigger}[data-state='open'] & {
rotate: -0.5turn;
+19 -5
View File
@@ -2,7 +2,7 @@ import { useMemo } from 'react';
import styled, { css, keyframes, type AnyStyledComponent } from 'styled-components';
import { StatusResponse } from '@0xsquid/sdk';
import { useStringGetter } from '@/hooks';
import { useStringGetter, useSelectedNetwork, useURLConfigs } from '@/hooks';
import { Link } from '@/components/Link';
import { Icon, IconName } from '@/components/Icon';
@@ -11,6 +11,7 @@ import { LoadingSpinner } from '@/components/Loading/LoadingSpinner';
import { layoutMixins } from '@/styles/layoutMixins';
import { STRING_KEYS } from '@/constants/localization';
import { ENVIRONMENT_CONFIG_MAP } from '@/constants/networks';
type ElementProps = {
status?: StatusResponse;
@@ -26,12 +27,17 @@ enum TransferStatusStep {
export const TransferStatusSteps = ({ status, type }: ElementProps) => {
const stringGetter = useStringGetter();
const { selectedNetwork } = useSelectedNetwork();
const { mintscan: mintscanTxUrl } = useURLConfigs();
const dydxChainId = ENVIRONMENT_CONFIG_MAP[selectedNetwork].dydxChainId;
const { currentStep, steps } = useMemo(() => {
const routeStatus = status?.routeStatus;
const fromChain = status?.fromChain?.chainData?.chainId;
const toChain = status?.toChain?.chainData?.chainId;
const currentStatus = routeStatus?.[routeStatus?.length - 1];
const steps = [
{
label: stringGetter({
@@ -39,7 +45,12 @@ export const TransferStatusSteps = ({ status, type }: ElementProps) => {
type === 'deposit' ? STRING_KEYS.INITIATED_DEPOSIT : STRING_KEYS.INITIATED_WITHDRAWAL,
}),
step: TransferStatusStep.FromChain,
link: status?.fromChain?.transactionUrl,
link:
type === 'deposit'
? status?.fromChain?.transactionUrl
: routeStatus?.[0]?.chainId === dydxChainId && routeStatus[0].txHash
? `${mintscanTxUrl?.replace('{tx_hash}', routeStatus[0].txHash.replace('0x', ''))}`
: undefined,
},
{
label: stringGetter({ key: STRING_KEYS.BRIDGING_TOKENS }),
@@ -54,12 +65,15 @@ export const TransferStatusSteps = ({ status, type }: ElementProps) => {
},
}),
step: TransferStatusStep.ToChain,
link: status?.toChain?.transactionUrl,
link:
type === 'withdrawal'
? status?.toChain?.transactionUrl
: currentStatus?.chainId === dydxChainId && currentStatus?.txHash
? `${mintscanTxUrl?.replace('{tx_hash}', currentStatus.txHash.replace('0x', ''))}`
: undefined,
},
];
const currentStatus = routeStatus?.[routeStatus?.length - 1];
let currentStep = TransferStatusStep.Bridge;
if (!routeStatus?.length) {
+1 -3
View File
@@ -246,9 +246,7 @@ export const FundingChart = ({ selectedLocale }: ElementProps) => {
}[rate] || '',
}))}
value={fundingRateView}
onValueChange={(newRate: FundingRateResolution) => {
if (newRate) setFundingRateView(newRate);
}}
onValueChange={setFundingRateView}
size={ButtonSize.XSmall}
/>
</Styled.FundingRateToggle>
+13 -6
View File
@@ -1,6 +1,7 @@
import { useState } from 'react';
import styled, { type AnyStyledComponent } from 'styled-components';
import { isMainnet } from '@/constants/networks';
import { STRING_KEYS } from '@/constants/localization';
import { useBreakpoints, useStringGetter } from '@/hooks';
@@ -16,7 +17,7 @@ type ElementProps = {
};
export const DepositDialog = ({ setIsOpen }: ElementProps) => {
const [showTestDeposit, setShowTestDeposit] = useState(true);
const [showFaucet, setShowFaucet] = useState(!isMainnet);
const stringGetter = useStringGetter();
const { isMobile } = useBreakpoints();
@@ -27,14 +28,20 @@ export const DepositDialog = ({ setIsOpen }: ElementProps) => {
isOpen
setIsOpen={setIsOpen}
title={stringGetter({ key: STRING_KEYS.DEPOSIT })}
description={showTestDeposit && 'Test funds will be sent directly to your dYdX account.'}
description={showFaucet && 'Test funds will be sent directly to your dYdX account.'}
placement={isMobile ? DialogPlacement.FullScreen : DialogPlacement.Default}
>
<Styled.Content>
{showTestDeposit ? <TestnetDepositForm onDeposit={closeDialog} /> : <DepositForm />}
<Styled.TextToggle onClick={() => setShowTestDeposit(!showTestDeposit)}>
{showTestDeposit ? 'Show deposit form (Under Construction)' : 'Show test faucet'}
</Styled.TextToggle>
{isMainnet || !showFaucet ? (
<DepositForm />
) : (
<TestnetDepositForm onDeposit={closeDialog} />
)}
{!isMainnet && (
<Styled.TextToggle onClick={() => setShowFaucet(!showFaucet)}>
{showFaucet ? 'Show deposit form' : 'Show test faucet'}
</Styled.TextToggle>
)}
</Styled.Content>
</Dialog>
);
+2 -1
View File
@@ -5,6 +5,7 @@ import { shallowEqual, useDispatch, useSelector } from 'react-redux';
import { AbacusApiStatus } from '@/constants/abacus';
import { DialogTypes } from '@/constants/dialogs';
import { STRING_KEYS } from '@/constants/localization';
import { isDev } from '@/constants/networks';
import { useApiState, useStringGetter } from '@/hooks';
import { layoutMixins } from '@/styles/layoutMixins';
@@ -45,7 +46,7 @@ export const ExchangeOfflineDialog = ({ preventClose, setIsOpen }: ElementProps)
>
<Styled.Content>
<p>{statusErrorMessage}</p>
{import.meta.env.MODE !== 'production' && <NetworkSelectMenu />}
{isDev && <NetworkSelectMenu />}
</Styled.Content>
</Dialog>
);
+6 -7
View File
@@ -2,7 +2,7 @@ import styled, { type AnyStyledComponent } from 'styled-components';
import { ButtonAction, ButtonSize, ButtonType } from '@/constants/buttons';
import { STRING_KEYS } from '@/constants/localization';
import { useBreakpoints, useStringGetter } from '@/hooks';
import { useBreakpoints, useStringGetter, useURLConfigs } from '@/hooks';
import { Button } from '@/components/Button';
import { Dialog, DialogPlacement } from '@/components/Dialog';
@@ -15,12 +15,10 @@ type ElementProps = {
setIsOpen: (open: boolean) => void;
};
// TODO: replace placeholder URL with real URLs when avaialble
const KEPLR_DASHBOARD_URL = 'https://testnet.keplr.app/';
const HELP_URL = 'https://help.dydx.exchange/en/articles/2921366-how-do-i-create-an-account-or-sign-up';
export const ExternalNavKeplrDialog = ({ setIsOpen }: ElementProps) => {
const stringGetter = useStringGetter();
const { keplrDashboard, accountExportLearnMore } = useURLConfigs();
const { isTablet } = useBreakpoints();
return (
@@ -31,7 +29,7 @@ export const ExternalNavKeplrDialog = ({ setIsOpen }: ElementProps) => {
placement={isTablet ? DialogPlacement.FullScreen : DialogPlacement.Default}
>
<Styled.Content>
<Styled.Button type={ButtonType.Link} size={ButtonSize.XLarge} href={KEPLR_DASHBOARD_URL}>
<Styled.Button type={ButtonType.Link} size={ButtonSize.XLarge} href={keplrDashboard}>
<span>
{stringGetter({
key: STRING_KEYS.NAVIGATE_TO_KEPLR,
@@ -48,7 +46,7 @@ export const ExternalNavKeplrDialog = ({ setIsOpen }: ElementProps) => {
/>
</Styled.Button>
<Styled.Button type={ButtonType.Link} size={ButtonSize.XLarge} href={HELP_URL}>
<Styled.Button type={ButtonType.Link} size={ButtonSize.XLarge} href={accountExportLearnMore}>
<span>
{stringGetter({
key: STRING_KEYS.LEARN_TO_EXPORT,
@@ -104,4 +102,5 @@ Styled.Button = styled(Button)`
Styled.IconButton = styled(IconButton)`
color: var(--color-text-0);
--color-border: var(--color-layer-6);
`;
+14 -29
View File
@@ -2,10 +2,10 @@ import { useMemo } from 'react';
import styled, { AnyStyledComponent } from 'styled-components';
import { STRING_KEYS } from '@/constants/localization';
import { useStringGetter } from '@/hooks';
import { ChatIcon, FeedbackIcon, FileIcon, TerminalIcon } from '@/icons';
import { useStringGetter, useURLConfigs } from '@/hooks';
import { ComboboxDialogMenu } from '@/components/ComboboxDialogMenu';
import { Icon, IconName } from '@/components/Icon';
import { isTruthy } from '@/lib/isTruthy';
@@ -13,39 +13,24 @@ type ElementProps = {
setIsOpen: (open: boolean) => void;
};
const HELP_LINKS = {
apiDocumentation: 'https://v4-teacher.vercel.app/',
helpCenter: null,
feedback: null,
};
export const HelpDialog = ({ setIsOpen }: ElementProps) => {
const stringGetter = useStringGetter();
const { help: helpCenter, community } = useURLConfigs();
const HELP_ITEMS = useMemo(
() => [
{
group: 'help-items',
items: [
HELP_LINKS.helpCenter && {
helpCenter && {
value: 'help-center',
label: stringGetter({ key: STRING_KEYS.HELP_CENTER }),
description: stringGetter({ key: STRING_KEYS.HELP_CENTER_DESCRIPTION }),
onSelect: () => {
HELP_LINKS.helpCenter && globalThis.open(HELP_LINKS.helpCenter, '_blank');
helpCenter && globalThis.open(helpCenter, '_blank');
setIsOpen(false);
},
slotBefore: <FileIcon />,
},
HELP_LINKS.apiDocumentation && {
value: 'api-documentation',
label: stringGetter({ key: STRING_KEYS.API_DOCUMENTATION }),
description: stringGetter({ key: STRING_KEYS.API_DOCUMENTATION_DESCRIPTION }),
onSelect: () => {
HELP_LINKS.apiDocumentation && globalThis.open(HELP_LINKS.apiDocumentation, '_blank');
setIsOpen(false);
},
slotBefore: <TerminalIcon />,
slotBefore: <Icon iconName={IconName.File} />,
},
globalThis?.Intercom && {
value: 'live-chat',
@@ -55,22 +40,22 @@ export const HelpDialog = ({ setIsOpen }: ElementProps) => {
globalThis.Intercom('show');
setIsOpen(false);
},
slotBefore: <ChatIcon />,
slotBefore: <Icon iconName={IconName.Chat} />,
},
HELP_LINKS.feedback && {
value: 'feedback',
label: stringGetter({ key: STRING_KEYS.PROVIDE_FEEDBACK }),
description: stringGetter({ key: STRING_KEYS.PROVIDE_FEEDBACK_DESCRIPTION }),
community && {
value: 'community',
label: stringGetter({ key: STRING_KEYS.COMMUNITY }),
description: stringGetter({ key: STRING_KEYS.COMMUNITY_DESCRIPTION }),
onSelect: () => {
HELP_LINKS.feedback && globalThis.open(HELP_LINKS.feedback, '_blank');
community && globalThis.open(community, '_blank');
setIsOpen(false);
},
slotBefore: <FeedbackIcon />,
slotBefore: <Icon iconName={IconName.Discord} />,
},
].filter(isTruthy),
},
],
[stringGetter]
[stringGetter, helpCenter, community]
);
return (
+18 -11
View File
@@ -3,6 +3,7 @@ import styled, { AnyStyledComponent, css } from 'styled-components';
import { AnalyticsEvent } from '@/constants/analytics';
import { STRING_KEYS } from '@/constants/localization';
import { isMainnet } from '@/constants/networks';
import { EvmDerivedAccountStatus, OnboardingSteps } from '@/constants/account';
import { wallets } from '@/constants/wallets';
@@ -26,6 +27,7 @@ import { track } from '@/lib/analytics';
import { AcknowledgeTerms } from './OnboardingDialog/AcknowledgeTerms';
import { ChooseWallet } from './OnboardingDialog/ChooseWallet';
import { GenerateKeys } from './OnboardingDialog/GenerateKeys';
import { DepositForm } from '../forms/AccountManagementForms/DepositForm';
type ElementProps = {
setIsOpen?: (open: boolean) => void;
@@ -50,7 +52,7 @@ export const OnboardingDialog = ({ setIsOpen }: ElementProps) => {
disconnect();
}
setIsOpen?.(open);
}
};
return (
<Styled.Dialog
@@ -82,10 +84,7 @@ export const OnboardingDialog = ({ setIsOpen }: ElementProps) => {
description: stringGetter({ key: STRING_KEYS.SIGNATURE_CREATES_COSMOS_WALLET }),
children: (
<Styled.Content>
<GenerateKeys
status={derivationStatus}
setStatus={setDerivationStatus}
/>
<GenerateKeys status={derivationStatus} setStatus={setDerivationStatus} />
</Styled.Content>
),
width: '23rem',
@@ -101,14 +100,22 @@ export const OnboardingDialog = ({ setIsOpen }: ElementProps) => {
},
[OnboardingSteps.DepositFunds]: {
title: stringGetter({ key: STRING_KEYS.DEPOSIT }),
description: 'Test funds will be sent directly to your dYdX account.',
description: !isMainnet && 'Test funds will be sent directly to your dYdX account.',
children: (
<Styled.Content>
<TestnetDepositForm
onDeposit={() => {
track(AnalyticsEvent.TransferFaucet);
}}
/>
{isMainnet ? (
<DepositForm
onDeposit={() => {
track(AnalyticsEvent.TransferDeposit);
}}
/>
) : (
<TestnetDepositForm
onDeposit={() => {
track(AnalyticsEvent.TransferFaucet);
}}
/>
)}
</Styled.Content>
),
},
@@ -13,16 +13,15 @@ import { Button } from '@/components/Button';
import { Icon } from '@/components/Icon';
import { Link } from '@/components/Link';
import { useAccounts, useStringGetter } from '@/hooks';
import { useAccounts, useStringGetter, useURLConfigs } from '@/hooks';
import { useDisplayedWallets } from '@/hooks/useDisplayedWallets';
import { breakpoints } from '@/styles';
import { layoutMixins } from '@/styles/layoutMixins';
const aboutWalletsLink = `https://www.dydx.academy/video/defi-wallet`;
export const ChooseWallet = () => {
const stringGetter = useStringGetter();
const { walletLearnMore } = useURLConfigs();
const displayedWallets = useDisplayedWallets();
@@ -63,7 +62,7 @@ export const ChooseWallet = () => {
</Styled.Wallets>
<Styled.Footer>
<Link href={aboutWalletsLink} withIcon>
<Link href={walletLearnMore} withIcon>
{stringGetter({ key: STRING_KEYS.ABOUT_WALLETS })}
</Link>
</Styled.Footer>
@@ -1,11 +1,13 @@
import styled, { AnyStyledComponent } from 'styled-components';
import { STRING_KEYS } from '@/constants/localization';
import { isDev } from '@/constants/networks';
import { useStringGetter } from '@/hooks';
import { layoutMixins } from '@/styles/layoutMixins';
import { Dialog } from '@/components/Dialog';
import { Icon, IconName } from '@/components/Icon';
import { NetworkSelectMenu } from '@/views/menus/NetworkSelectMenu';
type ElementProps = {
preventClose?: boolean;
@@ -25,6 +27,7 @@ export const RestrictedGeoDialog = ({ preventClose, setIsOpen }: ElementProps) =
>
<Styled.Content>
{stringGetter({ key: STRING_KEYS.REGION_NOT_PERMITTED_SUBTITLE })}
{isDev && <NetworkSelectMenu />}
</Styled.Content>
</Dialog>
);
@@ -1,11 +1,13 @@
import styled, { AnyStyledComponent } from 'styled-components';
import { STRING_KEYS } from '@/constants/localization';
import { isDev } from '@/constants/networks';
import { useStringGetter } from '@/hooks';
import { layoutMixins } from '@/styles/layoutMixins';
import { Dialog } from '@/components/Dialog';
import { Icon, IconName } from '@/components/Icon';
import { NetworkSelectMenu } from '@/views/menus/NetworkSelectMenu';
type ElementProps = {
preventClose?: boolean;
@@ -25,6 +27,7 @@ export const RestrictedWalletDialog = ({ preventClose, setIsOpen }: ElementProps
>
<Styled.Content>
{stringGetter({ key: STRING_KEYS.REGION_NOT_PERMITTED_SUBTITLE })}
{isDev && <NetworkSelectMenu />}
</Styled.Content>
</Dialog>
);
+2 -4
View File
@@ -37,7 +37,7 @@ export const TradeDialog = ({ isOpen, setIsOpen, slotTrigger }: ElementProps) =>
const selectedTradeType = getSelectedTradeType(type);
const { typeOptions } = useSelector(getInputTradeOptions, shallowEqual) ?? {};
const allTradeTypeItems = typeOptions?.toArray()?.map(({ type, stringKey }) => ({
const allTradeTypeItems = (typeOptions?.toArray() ?? []).map(({ type, stringKey }) => ({
value: type,
label: stringGetter({
key: stringKey as StringKey,
@@ -73,9 +73,7 @@ export const TradeDialog = ({ isOpen, setIsOpen, slotTrigger }: ElementProps) =>
<Styled.ToggleGroup
items={allTradeTypeItems}
value={selectedTradeType}
onValueChange={(tradeType: TradeTypes) =>
onTradeTypeChange(tradeType || selectedTradeType)
}
onValueChange={onTradeTypeChange}
/>
),
},
@@ -2,22 +2,21 @@ import { type FormEvent, useCallback, useEffect, useMemo, useState } from 'react
import styled, { type AnyStyledComponent } from 'styled-components';
import { type NumberFormatValues } from 'react-number-format';
import { shallowEqual, useSelector } from 'react-redux';
import { TESTNET_CHAIN_ID } from '@dydxprotocol/v4-client-js';
import { parseUnits } from 'viem'
import { parseUnits } from 'viem';
import erc20 from '@/abi/erc20.json';
import { TransferInputField, TransferInputTokenResource, TransferType } from '@/constants/abacus';
import { AlertType } from '@/constants/alerts';
import { ButtonSize } from '@/constants/buttons';
import { STRING_KEYS } from '@/constants/localization';
import { ENVIRONMENT_CONFIG_MAP } from '@/constants/networks';
import { NumberSign } from '@/constants/numbers';
import type { EvmAddress } from '@/constants/wallets';
import { useAccounts, useDebounce, useStringGetter } from '@/hooks';
import { useAccounts, useDebounce, useStringGetter, useSelectedNetwork } from '@/hooks';
import { useAccountBalance, CHAIN_DEFAULT_TOKEN_ADDRESS } from '@/hooks/useAccountBalance';
import { useLocalNotifications } from '@/hooks/useLocalNotifications';
import { NATIVE_TOKEN_ADDRESS, useSquid } from '@/hooks/useSquid';
import { useWalletConnection } from '@/hooks/useWalletConnection';
import { layoutMixins } from '@/styles/layoutMixins';
import { formMixins } from '@/styles/formMixins';
@@ -54,9 +53,9 @@ export const DepositForm = ({ onDeposit, onError }: DepositFormProps) => {
const stringGetter = useStringGetter();
const [error, setError] = useState<Error | null>(null);
const [isLoading, setIsLoading] = useState(false);
const { selectedNetwork } = useSelectedNetwork();
const { evmAddress, signerWagmi } = useAccounts();
const { publicClientWagmi } = useWalletConnection();
const { evmAddress, signerWagmi, publicClientWagmi } = useAccounts();
const { addTransferNotification } = useLocalNotifications();
@@ -66,6 +65,8 @@ export const DepositForm = ({ onDeposit, onError }: DepositFormProps) => {
chain: chainIdStr,
resources,
summary,
errors: routeErrors,
errorMessage: routeErrorMessage,
} = useSelector(getTransferInputs, shallowEqual) || {};
const chainId = chainIdStr ? parseInt(chainIdStr) : undefined;
@@ -98,7 +99,7 @@ export const DepositForm = ({ onDeposit, onError }: DepositFormProps) => {
useEffect(() => {
const hasInvalidInput =
debouncedAmountBN.isNaN() || debouncedAmountBN.lte(0) || debouncedAmountBN.gte(balanceBN);
debouncedAmountBN.isNaN() || debouncedAmountBN.lte(0) || debouncedAmountBN.gt(balanceBN);
abacusStateManager.setTransferValue({
value: hasInvalidInput ? 0 : debouncedAmount,
@@ -172,7 +173,8 @@ export const DepositForm = ({ onDeposit, onError }: DepositFormProps) => {
const validateTokenApproval = useCallback(async () => {
if (!signerWagmi || !publicClientWagmi) throw new Error('Missing signer');
if (!sourceToken?.address || !sourceToken.decimals) throw new Error('Missing source token address');
if (!sourceToken?.address || !sourceToken.decimals)
throw new Error('Missing source token address');
if (!sourceChain?.rpc) throw new Error('Missing source chain rpc');
if (!requestPayload?.targetAddress) throw new Error('Missing target address');
if (!requestPayload?.value) throw new Error('Missing transaction value');
@@ -182,11 +184,11 @@ export const DepositForm = ({ onDeposit, onError }: DepositFormProps) => {
address: sourceToken.address as EvmAddress,
abi: erc20,
functionName: 'allowance',
args: [evmAddress as EvmAddress, requestPayload.targetAddress as EvmAddress]
args: [evmAddress as EvmAddress, requestPayload.targetAddress as EvmAddress],
});
const sourceAmountBN = parseUnits(debouncedAmount, sourceToken.decimals);
if (sourceAmountBN > (allowance as bigint)) {
const { request } = await publicClientWagmi.simulateContract({
account: evmAddress,
@@ -194,12 +196,12 @@ export const DepositForm = ({ onDeposit, onError }: DepositFormProps) => {
abi: erc20,
functionName: 'approve',
args: [requestPayload.targetAddress as EvmAddress, sourceAmountBN],
})
});
const approveTx = await signerWagmi.writeContract(request);
await publicClientWagmi.waitForTransactionReceipt({
hash: approveTx,
})
});
}
}, [signerWagmi, sourceToken, sourceChain, requestPayload, publicClientWagmi]);
@@ -229,8 +231,7 @@ export const DepositForm = ({ onDeposit, onError }: DepositFormProps) => {
to: requestPayload.targetAddress as EvmAddress,
data: requestPayload.data as EvmAddress,
gasLimit: BigInt(requestPayload.gasLimit),
value:
requestPayload.routeType !== 'SEND' ? BigInt(requestPayload.value) : undefined,
value: requestPayload.routeType !== 'SEND' ? BigInt(requestPayload.value) : undefined,
};
const txHash = await signerWagmi.sendTransaction(tx);
@@ -239,7 +240,7 @@ export const DepositForm = ({ onDeposit, onError }: DepositFormProps) => {
if (txHash) {
addTransferNotification({
txHash: txHash,
toChainId: TESTNET_CHAIN_ID,
toChainId: ENVIRONMENT_CONFIG_MAP[selectedNetwork].dydxChainId,
fromChainId: chainIdStr || undefined,
toAmount: summary?.usdcSize || undefined,
triggeredAt: Date.now(),
@@ -288,6 +289,15 @@ export const DepositForm = ({ onDeposit, onError }: DepositFormProps) => {
return parseWalletError({ error, stringGetter }).message;
}
if (routeErrors) {
return routeErrorMessage
? stringGetter({
key: STRING_KEYS.SOMETHING_WENT_WRONG_WITH_MESSAGE,
params: { ERROR_MESSAGE: routeErrorMessage },
})
: stringGetter({ key: STRING_KEYS.SOMETHING_WENT_WRONG });
}
if (fromAmount) {
if (!chainId) {
return stringGetter({ key: STRING_KEYS.MUST_SPECIFY_CHAIN });
@@ -301,7 +311,16 @@ export const DepositForm = ({ onDeposit, onError }: DepositFormProps) => {
}
return undefined;
}, [error, balance, chainId, fromAmount, sourceToken]);
}, [
error,
routeErrors,
routeErrorMessage,
balance,
chainId,
fromAmount,
sourceToken,
stringGetter,
]);
const isDisabled =
Boolean(errorMessage) ||
@@ -1,5 +1,5 @@
import { type Dispatch, type SetStateAction, useState, type ReactNode } from 'react';
import styled, { type AnyStyledComponent, } from 'styled-components';
import styled, { type AnyStyledComponent } from 'styled-components';
import { shallowEqual, useSelector } from 'react-redux';
import type { RouteData } from '@0xsquid/sdk';
@@ -32,6 +32,8 @@ import { WithReceipt } from '@/components/WithReceipt';
import { getSubaccountBuyingPower, getSubaccountEquity } from '@/state/accountSelectors';
import { getTransferInputs } from '@/state/inputsSelectors';
import { MustBigNumber } from '@/lib/numbers';
import { SlippageEditor } from '../SlippageEditor';
type ElementProps = {
@@ -131,7 +133,7 @@ export const DepositButtonAndReceipt = ({
value: (
<DiffOutput
type={OutputType.Fiat}
value={buyingPower}
value={MustBigNumber(buyingPower).lt(0) ? undefined : buyingPower}
newValue={newBuyingPower}
sign={NumberSign.Positive}
withDiff={Boolean(newBuyingPower) && buyingPower !== newBuyingPower}
@@ -162,6 +164,7 @@ export const DepositButtonAndReceipt = ({
label: <span>{stringGetter({ key: STRING_KEYS.SLIPPAGE })}</span>,
value: (
<SlippageEditor
disabled
slippage={slippage}
setIsEditing={setIsEditingSlipapge}
setSlippage={setSlippage}
@@ -24,11 +24,17 @@ type ElementProps = {
slippage: number;
setIsEditing?: Dispatch<SetStateAction<boolean>>;
setSlippage: (slippage: number) => void;
disabled?: boolean;
};
export type SlippageEditorProps = ElementProps;
export const SlippageEditor = ({ slippage, setIsEditing, setSlippage }: SlippageEditorProps) => {
export const SlippageEditor = ({
disabled,
slippage,
setIsEditing,
setSlippage,
}: SlippageEditorProps) => {
const percentSlippage = slippage * 100;
const [slippageInputValue, setSlippageInputValue] = useState(percentSlippage.toString());
const [editorState, setEditorState] = useState(EditorState.Viewing);
@@ -80,6 +86,10 @@ export const SlippageEditor = ({ slippage, setIsEditing, setSlippage }: Slippage
}
};
if (disabled) {
return <Output type={OutputType.Percent} value={slippage} />;
}
return (
<Styled.WithConfirmationPopover
open={editorState !== EditorState.Viewing}
@@ -3,13 +3,13 @@ import type { ChangeEvent, FormEvent } from 'react';
import styled, { type AnyStyledComponent } from 'styled-components';
import type { NumberFormatValues } from 'react-number-format';
import { shallowEqual, useSelector } from 'react-redux';
import { TESTNET_CHAIN_ID } from '@dydxprotocol/v4-client-js';
import { isAddress } from 'viem';
import { TransferInputField, TransferInputTokenResource, TransferType } from '@/constants/abacus';
import { AlertType } from '@/constants/alerts';
import { ButtonSize } from '@/constants/buttons';
import { STRING_KEYS } from '@/constants/localization';
import { ENVIRONMENT_CONFIG_MAP } from '@/constants/networks';
import { NumberSign } from '@/constants/numbers';
import {
@@ -17,6 +17,7 @@ import {
useDebounce,
useDydxClient,
useRestrictions,
useSelectedNetwork,
useStringGetter,
useSubaccount,
} from '@/hooks';
@@ -46,12 +47,12 @@ import { MustBigNumber } from '@/lib/numbers';
import { TokenSelectMenu } from './TokenSelectMenu';
import { WithdrawButtonAndReceipt } from './WithdrawForm/WithdrawButtonAndReceipt';
import { join } from 'path';
export const WithdrawForm = () => {
const stringGetter = useStringGetter();
const [error, setError] = useState<string>();
const [isLoading, setIsLoading] = useState(false);
const { selectedNetwork } = useSelectedNetwork();
const { sendSquidWithdraw } = useSubaccount();
const { freeCollateral } = useSelector(getSubaccount, shallowEqual) || {};
@@ -67,6 +68,8 @@ export const WithdrawForm = () => {
chain: chainIdStr,
address: toAddress,
resources,
errors: routeErrors,
errorMessage: routeErrorMessage,
} = useSelector(getTransferInputs, shallowEqual) || {};
const isValidAddress = toAddress && isAddress(toAddress);
@@ -164,7 +167,7 @@ export const WithdrawForm = () => {
const hash = `0x${Buffer.from(txHash.hash).toString('hex')}`;
addTransferNotification({
txHash: hash,
fromChainId: TESTNET_CHAIN_ID,
fromChainId: ENVIRONMENT_CONFIG_MAP[selectedNetwork].dydxChainId,
toChainId: chainIdStr || undefined,
toAmount: debouncedAmountBN.toNumber(),
triggeredAt: Date.now(),
@@ -279,6 +282,15 @@ export const WithdrawForm = () => {
});
}
if (routeErrors) {
return routeErrorMessage
? stringGetter({
key: STRING_KEYS.SOMETHING_WENT_WRONG_WITH_MESSAGE,
params: { ERROR_MESSAGE: routeErrorMessage },
})
: stringGetter({ key: STRING_KEYS.SOMETHING_WENT_WRONG });
}
if (!toAddress) return stringGetter({ key: STRING_KEYS.WITHDRAW_MUST_SPECIFY_ADDRESS });
if (sanctionedAddresses.has(toAddress))
@@ -301,12 +313,15 @@ export const WithdrawForm = () => {
return undefined;
}, [
error,
routeErrors,
routeErrorMessage,
freeCollateralBN,
chainIdStr,
debouncedAmountBN,
toToken,
toAddress,
sanctionedAddresses,
stringGetter,
]);
const isDisabled =
@@ -147,6 +147,7 @@ export const WithdrawButtonAndReceipt = ({
label: <span>{stringGetter({ key: STRING_KEYS.SLIPPAGE })}</span>,
value: (
<SlippageEditor
disabled
slippage={slippage}
setIsEditing={setIsEditingSlipapge}
setSlippage={setSlippage}
+32 -8
View File
@@ -4,8 +4,10 @@ import { shallowEqual, useDispatch, useSelector } from 'react-redux';
import {
ClosePositionInputField,
ValidationError,
type HumanReadablePlaceOrderPayload,
type Nullable,
ErrorType,
} from '@/constants/abacus';
import { AlertType } from '@/constants/alerts';
import { ButtonAction, ButtonShape, ButtonSize, ButtonType } from '@/constants/buttons';
@@ -35,13 +37,14 @@ import { PositionPreview } from '@/views/forms/TradeForm/PositionPreview';
import { getCurrentMarketPositionData } from '@/state/accountSelectors';
import { getCurrentMarketAssetData } from '@/state/assetsSelectors';
import { getInputClosePositionData } from '@/state/inputsSelectors';
import { getClosePositionInputErrors, getInputClosePositionData } from '@/state/inputsSelectors';
import { getCurrentMarketConfig, getCurrentMarketId } from '@/state/perpetualsSelectors';
import { closeDialog } from '@/state/dialogs';
import { getCurrentInput } from '@/state/inputsSelectors';
import abacusStateManager from '@/lib/abacus';
import { MustBigNumber } from '@/lib/numbers';
import { getTradeInputAlert } from '@/lib/tradeData';
const MAX_KEY = 'MAX';
@@ -81,15 +84,38 @@ export const ClosePositionForm = ({
const market = useSelector(getCurrentMarketId);
const { id } = useSelector(getCurrentMarketAssetData, shallowEqual) || {};
const { stepSizeDecimals } = useSelector(getCurrentMarketConfig, shallowEqual) || {};
const { stepSizeDecimals, tickSizeDecimals } =
useSelector(getCurrentMarketConfig, shallowEqual) || {};
const { size: sizeData, summary } = useSelector(getInputClosePositionData, shallowEqual) || {};
const { size, percent } = sizeData || {};
const currentInput = useSelector(getCurrentInput);
const closePositionInputErrors = useSelector(getClosePositionInputErrors, shallowEqual);
const currentPositionData = useSelector(getCurrentMarketPositionData, shallowEqual);
const { size: currentPositionSize } = currentPositionData || {};
const { current: currentSize } = currentPositionSize || {};
const currentSizeBN = MustBigNumber(currentSize).abs();
const hasInputErrors = closePositionInputErrors?.some(
(error: ValidationError) => error.type !== ErrorType.warning
);
const inputAlert = getTradeInputAlert({
abacusInputErrors: closePositionInputErrors ?? [],
stringGetter,
stepSizeDecimals,
tickSizeDecimals,
});
let alertContent;
let alertType = AlertType.Error;
if (closePositionError) {
alertContent = closePositionError;
} else if (inputAlert) {
alertContent = inputAlert?.alertString;
alertType = inputAlert?.type;
}
useEffect(() => {
if (currentStep && currentStep !== MobilePlaceOrderSteps.EditOrder) return;
@@ -182,9 +208,7 @@ export const ClosePositionForm = ({
});
};
const alertMessage = closePositionError && (
<AlertMessage type={AlertType.Error}>{closePositionError}</AlertMessage>
);
const alertMessage = alertContent && <AlertMessage type={alertType}>{alertContent}</AlertMessage>;
const inputs = (
<Styled.InputsColumn>
@@ -209,7 +233,7 @@ export const ClosePositionForm = ({
value: value.toString(),
}))}
value={percent?.toString() ?? ''}
onValueChange={(value: any) => onSelectPercentage((value || percent?.toString()) ?? '')}
onValueChange={onSelectPercentage}
shape={ButtonShape.Rectangle}
/>
@@ -265,8 +289,8 @@ export const ClosePositionForm = ({
<PlaceOrderButtonAndReceipt
isLoading={isClosingPosition}
hasValidationErrors={!size}
actionStringKey={!size ? STRING_KEYS.ENTER_AMOUNT : undefined}
hasValidationErrors={hasInputErrors}
actionStringKey={inputAlert?.actionStringKey}
summary={summary ?? undefined}
currentStep={currentStep}
isClosePosition
-1
View File
@@ -322,7 +322,6 @@ export const TradeForm = ({
summary={summary ?? undefined}
currentStep={currentStep}
showDeposit={inputAlert?.errorAction === TradeInputErrorAction.DEPOSIT}
showConnectWallet={inputAlert?.errorAction === TradeInputErrorAction.CONNECT_WALLET}
/>
</Styled.Footer>
</Styled.TradeForm>
@@ -153,9 +153,7 @@ export const MarketLeverageInput = ({
value: MustBigNumber(leverageAmount).toFixed(LEVERAGE_DECIMALS),
}))}
value={MustBigNumber(formattedLeverageValue).abs().toFixed(LEVERAGE_DECIMALS)} // sign agnostic
onValueChange={(option?: number) =>
updateLeverage(option === undefined ? formattedLeverageValue : option)
}
onValueChange={updateLeverage}
shape={ButtonShape.Rectangle}
/>
</>
@@ -7,9 +7,8 @@ import { DialogTypes } from '@/constants/dialogs';
import { STRING_KEYS } from '@/constants/localization';
import { TRADE_TYPE_STRINGS, MobilePlaceOrderSteps } from '@/constants/trade';
import { useStringGetter } from '@/hooks';
import { useStringGetter, useTokenConfigs } from '@/hooks';
import { AssetIcon } from '@/components/AssetIcon';
import { Button } from '@/components/Button';
import { Output, OutputType, ShowSign } from '@/components/Output';
import { WithDetailsReceipt } from '@/components/WithDetailsReceipt';
@@ -47,6 +46,7 @@ export const PlaceOrderButtonAndReceipt = ({
}: ElementProps) => {
const stringGetter = useStringGetter();
const dispatch = useDispatch();
const { chainTokenLabel } = useTokenConfigs();
const canAccountTrade = useSelector(calculateCanAccountTrade);
const subaccountNumber = useSelector(getSubaccountId);
@@ -88,7 +88,14 @@ export const PlaceOrderButtonAndReceipt = ({
{/* <AssetIcon symbol="DYDX" /> */}
</>
),
value: <Output type={OutputType.Asset} value={reward} useGrouping tag={reward ? "Dv4TNT" : ''} />,
value: (
<Output
type={OutputType.Asset}
value={reward}
useGrouping
tag={reward ? chainTokenLabel : ''}
/>
),
tooltip: 'max-reward',
},
{
@@ -111,7 +118,7 @@ export const PlaceOrderButtonAndReceipt = ({
? actionStringKey
: STRING_KEYS.UNAVAILABLE,
buttonAction: ButtonAction.Primary,
buttonState: { isDisabled: !shouldEnableTrade },
buttonState: { isDisabled: !shouldEnableTrade, isLoading: hasMissingData },
},
[MobilePlaceOrderSteps.PreviewOrder]: {
@@ -148,7 +155,10 @@ export const PlaceOrderButtonAndReceipt = ({
const buttonState = currentStep
? buttonStatesPerStep[currentStep].buttonState
: { isDisabled: !shouldEnableTrade || isLoading, isLoading };
: {
isDisabled: !shouldEnableTrade || isLoading,
isLoading: isLoading || hasMissingData,
};
return (
<WithDetailsReceipt detailItems={items}>
+57 -49
View File
@@ -61,38 +61,53 @@ export const TransferForm = ({
const stringGetter = useStringGetter();
const { freeCollateral } = useSelector(getSubaccount, shallowEqual) || {};
const { dydxAddress } = useAccounts();
const {
address: recipientAddress,
size,
fee,
} = useSelector(getTransferInputs, shallowEqual) || {};
const { transfer } = useSubaccount();
const { nativeTokenBalance, usdcBalance } = useAccountBalance();
const { selectedNetwork } = useSelectedNetwork();
const { tokensConfigs, usdcLabel, chainTokenLabel } = useTokenConfigs();
// User Input
const [asset, setAsset] = useState<DydxChainAsset>(selectedAsset);
const {
address: recipientAddress,
size,
fee,
token,
} = useSelector(getTransferInputs, shallowEqual) || {};
// Form states
const [error, setError] = useState<string>();
const [isLoading, setIsLoading] = useState(false);
const balance = asset === DydxChainAsset.USDC ? freeCollateral?.current : nativeTokenBalance;
const newBalance =
asset === DydxChainAsset.USDC
? freeCollateral?.postOrder
: MustBigNumber(nativeTokenBalance)
.minus(size?.size ?? 0)
.toNumber();
const amount = asset === DydxChainAsset.USDC ? size?.usdcSize : size?.size;
// temp fix: TODO: reset fees when changing token in Abacus
const [currentFee, setCurrentFee] = useState(fee);
useEffect(() => {
setCurrentFee(fee);
}, [fee]);
const showNotEnoughGasWarning = fee && asset === DydxChainAsset.USDC && usdcBalance < fee;
const asset = (token ?? selectedAsset) as DydxChainAsset;
const isUSDCSelected = asset === DydxChainAsset.USDC;
const amount = isUSDCSelected ? size?.usdcSize : size?.size;
const showNotEnoughGasWarning = fee && isUSDCSelected && usdcBalance < fee;
const balance = isUSDCSelected ? freeCollateral?.current : nativeTokenBalance;
// BN
const newBalanceBN = isUSDCSelected
? MustBigNumber(freeCollateral?.postOrder)
: nativeTokenBalance.minus(size?.size ?? 0);
const amountBN = MustBigNumber(amount);
const balanceBN = MustBigNumber(balance);
const newBalanceBN = MustBigNumber(newBalance);
const onChangeAsset = (asset: DydxChainAsset) => {
setError(undefined);
setCurrentFee(undefined);
if (asset) {
abacusStateManager.setTransferValue({
value: asset,
field: TransferInputField.token,
});
}
};
useEffect(() => {
abacusStateManager.setTransferValue({
@@ -100,19 +115,13 @@ export const TransferForm = ({
field: TransferInputField.type,
});
onChangeAsset(selectedAsset);
return () => {
abacusStateManager.clearTransferInputValues();
};
}, []);
useEffect(() => {
setError(undefined);
abacusStateManager.setTransferValue({
value: asset,
field: TransferInputField.token,
});
}, [asset]);
const { sanctionedAddresses } = useRestrictions();
const isAddressValid = useMemo(
@@ -134,11 +143,6 @@ export const TransferForm = ({
setError(undefined);
try {
// Subtract fees from amount if sending native tokens
const amountToTransfer = (
asset === DydxChainAsset.CHAINTOKEN ? amountBN.minus(fee) : amountBN
).toNumber();
const screenResults = await screenAddresses({
addresses: [recipientAddress!, dydxAddress!],
});
@@ -157,9 +161,9 @@ export const TransferForm = ({
);
} else {
const txResponse = await transfer(
amountToTransfer,
amountBN.toNumber(),
recipientAddress as string,
tokensConfigs[asset].denom,
tokensConfigs[asset]?.denom
);
if (txResponse?.code === 0) {
@@ -200,7 +204,7 @@ export const TransferForm = ({
const onChangeAmount = (value?: number) => {
abacusStateManager.setTransferValue({
value,
field: asset === DydxChainAsset.USDC ? TransferInputField.usdcSize : TransferInputField.size,
field: isUSDCSelected ? TransferInputField.usdcSize : TransferInputField.size,
});
};
@@ -226,7 +230,7 @@ export const TransferForm = ({
value: DydxChainAsset.CHAINTOKEN,
label: (
<Styled.InlineRow>
{/* <AssetIcon symbol="DYDX" /> */}
<AssetIcon symbol={chainTokenLabel} />
{chainTokenLabel}
</Styled.InlineRow>
),
@@ -249,15 +253,15 @@ export const TransferForm = ({
key: 'amount',
label: (
<span>
{stringGetter({ key: STRING_KEYS.AVAILABLE })} <Tag>{tokensConfigs[asset].name}</Tag>
{stringGetter({ key: STRING_KEYS.AVAILABLE })} <Tag>{tokensConfigs[asset]?.name}</Tag>
</span>
),
value: (
<DiffOutput
type={OutputType.Asset}
value={balanceBN.toString()}
newValue={newBalanceBN.toString()}
value={balanceBN}
sign={NumberSign.Negative}
newValue={newBalanceBN}
hasInvalidNewValue={newBalanceBN.isNegative()}
withDiff={Boolean(amount && balance) && !amountBN.isNaN()}
/>
@@ -340,8 +344,8 @@ export const TransferForm = ({
<Styled.SelectMenu
label={stringGetter({ key: STRING_KEYS.ASSET })}
value={asset}
onValueChange={setAsset}
value={token}
onValueChange={onChangeAsset}
disabled={isLoading}
>
{assetOptions.map(({ value, label }) => (
@@ -355,12 +359,16 @@ export const TransferForm = ({
type={InputType.Number}
onChange={({ floatValue }: NumberFormatValues) => onChangeAmount(floatValue)}
value={amount ?? undefined}
slotRight={renderFormInputButton({
label: stringGetter({ key: STRING_KEYS.MAX }),
isInputEmpty: size?.usdcSize == null,
onClear: () => onChangeAmount(undefined),
onClick: () => onChangeAmount(balanceBN.toNumber()),
})}
slotRight={
isUSDCSelected &&
balanceBN.gt(0) &&
renderFormInputButton({
label: stringGetter({ key: STRING_KEYS.MAX }),
isInputEmpty: size?.usdcSize == null,
onClear: () => onChangeAmount(undefined),
onClick: () => onChangeAmount(balanceBN.toNumber()),
})
}
disabled={isLoading}
/>
</WithDetailsReceipt>
@@ -369,7 +377,7 @@ export const TransferForm = ({
<AlertMessage type={AlertType.Warning}>
{stringGetter({
key: STRING_KEYS.TRANSFER_INSUFFICIENT_GAS,
params: { USDC_BALANCE: `(${usdcBalance})` },
params: { USDC_BALANCE: `(${usdcBalance} USDC)` },
})}
</AlertMessage>
)}
@@ -379,9 +387,9 @@ export const TransferForm = ({
<Styled.Footer>
<TransferButtonAndReceipt
selectedAsset={asset}
fees={fee || undefined}
isDisabled={!isAmountValid || !isAddressValid || !fee || isLoading}
isLoading={isLoading || Boolean(isAmountValid && isAddressValid && !fee)}
fee={currentFee || undefined}
isDisabled={!isAmountValid || !isAddressValid || !currentFee || isLoading}
isLoading={isLoading || Boolean(isAmountValid && isAddressValid && !currentFee)}
/>
</Styled.Footer>
</Styled.Form>
@@ -23,14 +23,14 @@ import { MustBigNumber } from '@/lib/numbers';
type ElementProps = {
selectedAsset: DydxChainAsset;
fees?: number;
fee?: number;
isDisabled?: boolean;
isLoading?: boolean;
};
export const TransferButtonAndReceipt = ({
selectedAsset,
fees,
fee,
isDisabled,
isLoading,
}: ElementProps) => {
@@ -47,43 +47,46 @@ export const TransferButtonAndReceipt = ({
const { current: equity, postOrder: newEquity } = equityInfo || {};
const { current: leverage, postOrder: newLeverage } = leverageInfo || {};
// TODO(@aforaleka): add wallet balance for DYDX
const balance = selectedAsset === DydxChainAsset.USDC ? equity : nativeTokenBalance;
const newBalance =
selectedAsset === DydxChainAsset.USDC
? newEquity
: MustBigNumber(nativeTokenBalance)
.minus(size?.size ?? 0)
.toNumber();
const isUSDCSelected = selectedAsset === DydxChainAsset.USDC;
const balance = isUSDCSelected ? equity : nativeTokenBalance;
const newNativeTokenBalance = nativeTokenBalance
.minus(size?.size ?? 0)
.minus(fee ?? 0) // show balance after fees for button receipt
.toNumber();
const newBalance = isUSDCSelected ? newEquity : newNativeTokenBalance;
const transferDetailItems = [
{
key: 'fees',
label: (
<span>
{stringGetter({ key: STRING_KEYS.FEES })} <Tag>{tokensConfigs[selectedAsset].name}</Tag>
{stringGetter({ key: STRING_KEYS.FEES })} <Tag>{tokensConfigs[selectedAsset]?.name}</Tag>
</span>
),
value: <Output type={OutputType.Asset} value={fees} />,
value: <Output type={OutputType.Asset} value={fee} />,
},
{
key: 'balance',
label: (
<span>
{stringGetter({ key: STRING_KEYS.BALANCE })} <Tag>{tokensConfigs[selectedAsset].name}</Tag>
{stringGetter({ key: STRING_KEYS.BALANCE })}{' '}
<Tag>{tokensConfigs[selectedAsset]?.name}</Tag>
</span>
),
value: (
<DiffOutput
type={OutputType.Asset}
value={balance}
newValue={newBalance}
sign={NumberSign.Negative}
withDiff={Boolean(newBalance) && balance !== newBalance}
newValue={newBalance}
hasInvalidNewValue={MustBigNumber(newBalance).isNegative()}
withDiff={newBalance !== null && !MustBigNumber(balance).eq(newBalance ?? 0)}
/>
),
},
selectedAsset === DydxChainAsset.USDC && {
isUSDCSelected && {
key: 'leverage',
label: <span>{stringGetter({ key: STRING_KEYS.LEVERAGE })}</span>,
value: (
+65 -29
View File
@@ -15,6 +15,7 @@ import {
useTokenConfigs,
useStringGetter,
useAccountBalance,
useURLConfigs,
} from '@/hooks';
import { OnboardingTriggerButton } from '@/views/dialogs/OnboardingTriggerButton';
@@ -35,11 +36,11 @@ import { truncateAddress } from '@/lib/wallet';
import { layoutMixins } from '@/styles/layoutMixins';
import { headerMixins } from '@/styles/headerMixins';
const explorerBaseUri = 'https://testnet.mintscan.io/dydx-testnet';
import { MustBigNumber } from '@/lib/numbers';
export const AccountMenu = () => {
const stringGetter = useStringGetter();
const { mintscanBase } = useURLConfigs();
const { isTablet } = useBreakpoints();
const dispatch = useDispatch();
const onboardingState = useSelector(getOnboardingState);
@@ -49,6 +50,8 @@ export const AccountMenu = () => {
const { evmAddress, walletType, dydxAddress, hdKey } = useAccounts();
const usdcBalance = freeCollateral?.current || 0;
const onRecoverKeys = () => {
dispatch(openDialog({ type: DialogTypes.Onboarding }));
};
@@ -92,7 +95,7 @@ export const AccountMenu = () => {
/>
<IconButton
action={ButtonAction.Base}
href={`${explorerBaseUri}/account/${dydxAddress}`}
href={`${mintscanBase}/account/${dydxAddress}`}
iconName={IconName.LinkOut}
shape={ButtonShape.Square}
type={ButtonType.Link}
@@ -122,7 +125,11 @@ export const AccountMenu = () => {
</Styled.label>
<Styled.BalanceOutput type={OutputType.Asset} value={nativeTokenBalance} />
</div>
<AssetActions asset={DydxChainAsset.CHAINTOKEN} dispatch={dispatch} />
<AssetActions
asset={DydxChainAsset.CHAINTOKEN}
dispatch={dispatch}
hasBalance={nativeTokenBalance.gt(0)}
/>
</div>
<div>
<div>
@@ -135,11 +142,16 @@ export const AccountMenu = () => {
</Styled.label>
<Styled.BalanceOutput
type={OutputType.Asset}
value={freeCollateral?.current || 0}
value={usdcBalance}
fractionDigits={2}
/>
</div>
<AssetActions asset={DydxChainAsset.USDC} dispatch={dispatch} />
<AssetActions
asset={DydxChainAsset.USDC}
dispatch={dispatch}
hasBalance={MustBigNumber(usdcBalance).gt(0)}
withOnboarding
/>
</div>
</Styled.Balances>
</Styled.AccountInfo>
@@ -167,7 +179,7 @@ export const AccountMenu = () => {
// value: 'ViewInExplorer',
// icon: <Icon iconName={IconName.Etherscan} />,
// label: stringGetter({ key: STRING_KEYS.OPEN_IN_ETHERSCAN }),
// onSelect: () => globalThis.open(`${explorerBaseUri}/address/${address}`),
// onSelect: () => globalThis.open(`${mintscanBase}/address/${address}`),
// separator: true,
// },
...(onboardingState === OnboardingState.AccountConnected && hdKey
@@ -212,28 +224,48 @@ export const AccountMenu = () => {
);
};
const AssetActions = memo(({ asset, dispatch }: { asset: DydxChainAsset; dispatch: Dispatch }) => (
<Styled.InlineRow>
{[
// TODO(@rosepuppy): Add withdraw action for USDC
{
dialogType: DialogTypes.Receive,
iconName: IconName.Qr,
},
{ dialogType: DialogTypes.Transfer, iconName: IconName.Send },
].map(({ iconName, dialogType }) => (
<IconButton
key={dialogType}
action={ButtonAction.Base}
shape={ButtonShape.Square}
iconName={iconName}
onClick={() =>
dispatch(openDialog({ type: dialogType, dialogProps: { selectedAsset: asset } }))
}
/>
))}
</Styled.InlineRow>
));
const AssetActions = memo(
({
asset,
dispatch,
withOnboarding,
hasBalance,
}: {
asset: DydxChainAsset;
dispatch: Dispatch;
withOnboarding?: boolean;
hasBalance?: boolean;
}) => (
<Styled.InlineRow>
{[
withOnboarding &&
hasBalance && {
dialogType: DialogTypes.Withdraw,
iconName: IconName.Withdraw,
},
withOnboarding && {
dialogType: DialogTypes.Deposit,
iconName: IconName.Deposit,
},
hasBalance && {
dialogType: DialogTypes.Transfer,
dialogProps: { selectedAsset: asset },
iconName: IconName.Send,
},
]
.filter(isTruthy)
.map(({ iconName, dialogType, dialogProps }) => (
<Styled.IconButton
key={dialogType}
action={ButtonAction.Base}
shape={ButtonShape.Square}
iconName={iconName}
onClick={() => dispatch(openDialog({ type: dialogType, dialogProps }))}
/>
))}
</Styled.InlineRow>
)
);
const Styled: Record<string, AnyStyledComponent> = {};
@@ -351,3 +383,7 @@ Styled.ConnectToChain = styled(Styled.Column)`
font: var(--font-small-book);
}
`;
Styled.IconButton = styled(IconButton)`
--button-padding: 0 0.25rem;
`;
+2
View File
@@ -33,6 +33,8 @@ const Styled: Record<string, AnyStyledComponent> = {};
Styled.DropdownSelectMenu = styled(DropdownSelectMenu)`
${headerMixins.dropdownTrigger}
width: max-content;
& > span:first-of-type {
${layoutMixins.textOverflow}
max-width: 5.625rem;
+6 -5
View File
@@ -1,10 +1,13 @@
import React, { useMemo } from 'react';
import styled from 'styled-components';
import { layoutMixins } from '@/styles/layoutMixins';
import { groupBy } from 'lodash';
import { type Notification, NotificationStatus } from '@/constants/notifications';
import { useBreakpoints } from '@/hooks';
import { useNotifications } from '@/hooks/useNotifications';
import { CloseIcon } from '@/icons';
import { Button } from '@/components/Button';
import { ButtonAction, ButtonSize } from '@/constants/buttons';
@@ -13,10 +16,6 @@ import { DialogPlacement } from '@/components/Dialog';
import { Output, OutputType } from '@/components/Output';
import { IconButton } from '@/components/IconButton';
import { Toolbar } from '@/components/Toolbar';
import { CloseIcon } from '@/icons';
import styled from 'styled-components';
import { layoutMixins } from '@/styles/layoutMixins';
type ElementProps = {
slotTrigger?: React.ReactNode;
@@ -27,6 +26,7 @@ export const NotificationsMenu = ({
slotTrigger,
placement = DialogPlacement.Sidebar,
}: ElementProps) => {
const { isTablet } = useBreakpoints();
const {
notifications,
getDisplayData,
@@ -173,6 +173,7 @@ export const NotificationsMenu = ({
</$FooterToolbar>
}
placement={placement}
preventClose={isTablet}
/>
);
};
+3 -3
View File
@@ -231,7 +231,7 @@ const getOrdersTableColumnDef = ({
key: STRING_KEYS.FILL,
})}`,
renderCell: ({
asset: { symbol: assetSymbol },
asset,
createdAtMilliseconds,
size,
status,
@@ -254,7 +254,7 @@ const getOrdersTableColumnDef = ({
value={createdAtMilliseconds}
/>
<Styled.AssetIconWithStatus>
<Styled.AssetIcon symbol={assetSymbol} />
<Styled.AssetIcon symbol={asset?.id} />
<Styled.StatusDot color={statusIconColor} />
</Styled.AssetIconWithStatus>
</>
@@ -276,7 +276,7 @@ const getOrdersTableColumnDef = ({
type={OutputType.Asset}
value={size}
fractionDigits={TOKEN_DECIMALS}
tag={assetSymbol}
tag={asset?.id}
/>
</Styled.InlineRow>
</TableCell>
+10 -3
View File
@@ -7,7 +7,7 @@ import { ButtonAction } from '@/constants/buttons';
import { DialogTypes } from '@/constants/dialogs';
import { STRING_KEYS, StringGetterFunction } from '@/constants/localization';
import { useBreakpoints, useStringGetter } from '@/hooks';
import { useBreakpoints, useStringGetter, useURLConfigs } from '@/hooks';
import { layoutMixins } from '@/styles/layoutMixins';
import { tradeViewMixins } from '@/styles/tradeViewMixins';
@@ -40,11 +40,13 @@ const getTransferHistoryTableColumnDef = ({
key,
stringGetter,
width,
mintscanTxUrl,
}: {
key: TransferHistoryTableColumnKey;
isTablet?: boolean;
stringGetter: StringGetterFunction;
width?: ColumnSize;
mintscanTxUrl?: string;
}): ColumnDef<SubaccountTransfer> => ({
width,
...(
@@ -98,9 +100,12 @@ const getTransferHistoryTableColumnDef = ({
columnKey: TransferHistoryTableColumnKey.TxHash,
getCellValue: (row) => row.transactionHash,
label: stringGetter({ key: STRING_KEYS.TRANSACTION }),
renderCell: ({ transactionHash, resources }) =>
renderCell: ({ transactionHash }) =>
transactionHash ? (
<Styled.TxHash withIcon href={resources.blockExplorerUrl}>
<Styled.TxHash
withIcon
href={`${mintscanTxUrl?.replace('{tx_hash}', transactionHash)}`}
>
{truncateAddress(transactionHash, '')}
</Styled.TxHash>
) : (
@@ -130,6 +135,7 @@ export const TransferHistoryTable = ({
const stringGetter = useStringGetter();
const dispatch = useDispatch();
const { isMobile, isTablet } = useBreakpoints();
const { mintscan: mintscanTxUrl } = useURLConfigs();
const canAccountTrade = useSelector(calculateCanAccountTrade, shallowEqual);
@@ -146,6 +152,7 @@ export const TransferHistoryTable = ({
isTablet,
stringGetter,
width: columnWidths?.[key],
mintscanTxUrl,
})
)}
slotEmpty={