Compare commits

..
Author SHA1 Message Date
Bill He 8c3f867f06 Learnmore -> LearnMore 2023-10-31 10:58:33 -07:00
Bill He 1a95814925 add learnmore to tooltip 2023-10-31 10:57:21 -07:00
Bill He a6d7a5cb4e Configurable URLs 2023-10-31 10:57:20 -07:00
70 changed files with 502 additions and 1001 deletions
+3 -7
View File
@@ -4,11 +4,7 @@ VITE_ALCHEMY_API_KEY=
VITE_PK_ENCRYPTION_KEY= VITE_PK_ENCRYPTION_KEY=
VITE_V3_TOKEN_ADDRESS= VITE_WALLETCONNECT2_PROJECT_ID=
VITE_TOKEN_MIGRATION_URI=
AMPLITUDE_API_KEY= VITE_V3_TOKEN_ADDRESS=
BUGSNAG_API_KEY= VITE_TOKEN_MIGRATION_URI=
IOS_APP_ID=
INTERCOM_APP_ID=
STATUS_PAGE_SCRIPT_URI=
+1 -4
View File
@@ -1,9 +1,6 @@
Copyright (C) 2023 dYdX Trading Inc. Copyright (C) 2023 dYdX Trading Inc.
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. 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.
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 The GNU Affero General Public License
-20
View File
@@ -69,21 +69,6 @@ You'll need to provide a Wallet Connect project id to enable onboarding and wall
- Create a project on https://cloud.walletconnect.com/app - 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) - Copy over the project ID into this [field](https://github.com/dydxprotocol/v4-web/blob/67ecbd75b43e0c264b7b4d2d9b3d969830b0621c/public/configs/env.json#L822C33-L822C46)
## 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 # Deployments
## Deploying with Vercel ## Deploying with Vercel
@@ -98,11 +83,6 @@ For the "Build & Development Settings", we recommend the following:
- Framework Preset: `Vite` - Framework Preset: `Vite`
- Build Command (override): `pnpm run build` - 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: 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. `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.
+2 -3
View File
@@ -39,9 +39,9 @@
"@cosmjs/proto-signing": "^0.31.0", "@cosmjs/proto-signing": "^0.31.0",
"@cosmjs/stargate": "^0.31.0", "@cosmjs/stargate": "^0.31.0",
"@cosmjs/tendermint-rpc": "^0.31.0", "@cosmjs/tendermint-rpc": "^0.31.0",
"@dydxprotocol/v4-abacus": "^1.0.24", "@dydxprotocol/v4-abacus": "^1.0.3",
"@dydxprotocol/v4-client-js": "^1.0.0", "@dydxprotocol/v4-client-js": "^1.0.0",
"@dydxprotocol/v4-localization": "^1.0.5", "@dydxprotocol/v4-localization": "^1.0.0",
"@ethersproject/providers": "^5.7.2", "@ethersproject/providers": "^5.7.2",
"@js-joda/core": "^5.5.3", "@js-joda/core": "^5.5.3",
"@radix-ui/react-collapsible": "^1.0.3", "@radix-ui/react-collapsible": "^1.0.3",
@@ -96,7 +96,6 @@
"long": "^5.2.3", "long": "^5.2.3",
"luxon": "^3.3.0", "luxon": "^3.3.0",
"qr-code-styling": "1.6.0-rc.1", "qr-code-styling": "1.6.0-rc.1",
"query-string": "^8.1.0",
"react": "^18.2.0", "react": "^18.2.0",
"react-aria": "^3.25.0", "react-aria": "^3.25.0",
"react-dom": "^18.2.0", "react-dom": "^18.2.0",
+19 -18
View File
@@ -1,9 +1,5 @@
lockfileVersion: '6.0' lockfileVersion: '6.0'
settings:
autoInstallPeers: true
excludeLinksFromLockfile: false
dependencies: dependencies:
'@0xsquid/sdk': '@0xsquid/sdk':
specifier: ^1.10.0 specifier: ^1.10.0
@@ -27,14 +23,14 @@ dependencies:
specifier: ^0.31.0 specifier: ^0.31.0
version: 0.31.0 version: 0.31.0
'@dydxprotocol/v4-abacus': '@dydxprotocol/v4-abacus':
specifier: ^1.0.24 specifier: ^1.0.3
version: 1.0.24 version: 1.0.3
'@dydxprotocol/v4-client-js': '@dydxprotocol/v4-client-js':
specifier: ^1.0.0 specifier: ^1.0.0
version: 1.0.0 version: 1.0.0
'@dydxprotocol/v4-localization': '@dydxprotocol/v4-localization':
specifier: ^1.0.5 specifier: ^1.0.0
version: 1.0.5 version: 1.0.0
'@ethersproject/providers': '@ethersproject/providers':
specifier: ^5.7.2 specifier: ^5.7.2
version: 5.7.2 version: 5.7.2
@@ -197,9 +193,6 @@ dependencies:
qr-code-styling: qr-code-styling:
specifier: 1.6.0-rc.1 specifier: 1.6.0-rc.1
version: 1.6.0-rc.1 version: 1.6.0-rc.1
query-string:
specifier: ^8.1.0
version: 8.1.0
react: react:
specifier: ^18.2.0 specifier: ^18.2.0
version: 18.2.0 version: 18.2.0
@@ -982,8 +975,8 @@ packages:
resolution: {integrity: sha512-RpfLEtTlyIxeNPGKcokS+p3BZII/Q3bYxryFRglh5H3A3T8q9fsLYm72VYAMEOOIBLEa8o93kFLiBDUWKrwXZA==} resolution: {integrity: sha512-RpfLEtTlyIxeNPGKcokS+p3BZII/Q3bYxryFRglh5H3A3T8q9fsLYm72VYAMEOOIBLEa8o93kFLiBDUWKrwXZA==}
dev: true dev: true
/@dydxprotocol/v4-abacus@1.0.24: /@dydxprotocol/v4-abacus@1.0.3:
resolution: {integrity: sha512-wDGSjkrc3Se6Ev7UTjPgJV7PiyzZSz2mJwOTZikLwH7W3k1iPYGQmaCd7TudFk8h2aSdlEwNsQBCf0sLoyvHaQ==} resolution: {integrity: sha512-GuX37/DMMNSke8ZFcw52II7IVJfUgVGHqoi1Uw2cUb+hgIjjSG3OtbyRWedm5r6nqWq8BNLOexI0VVFB6OMVYg==}
dev: false dev: false
/@dydxprotocol/v4-client-js@1.0.0: /@dydxprotocol/v4-client-js@1.0.0:
@@ -1014,8 +1007,8 @@ packages:
- utf-8-validate - utf-8-validate
dev: false dev: false
/@dydxprotocol/v4-localization@1.0.5: /@dydxprotocol/v4-localization@1.0.0:
resolution: {integrity: sha512-zZm3GFp/ORz9YjigQFVBlcWmaxYY+XEdIw8AWN5nEbsuiA2Jay+/OA7lO9+nV1J1p1T+TgLo9iczIHJsAo3IsA==} resolution: {integrity: sha512-U7QjOlzpfSAVEchkNDB3xYRx7okzdeYi83XsnHwI+EHa2quFm/2Y2dhrBkT5fqpZmhcwxb/vG8AZmFSToOf9hA==}
dev: false dev: false
/@dydxprotocol/v4-proto@0.4.1: /@dydxprotocol/v4-proto@0.4.1:
@@ -7659,7 +7652,7 @@ packages:
resolution: {integrity: sha512-WIdaQ8uW1vIbYvNnAVunkC6yxTrneJC7VQ5UUQ0kuw8b0C0A39KTIpoQHCfc8tV7o9vF4niwRhdXEdfAgQEsQQ==} resolution: {integrity: sha512-WIdaQ8uW1vIbYvNnAVunkC6yxTrneJC7VQ5UUQ0kuw8b0C0A39KTIpoQHCfc8tV7o9vF4niwRhdXEdfAgQEsQQ==}
dependencies: dependencies:
cosmos-directory-types: 0.0.6 cosmos-directory-types: 0.0.6
node-fetch-native: 1.4.1 node-fetch-native: 1.4.0
dev: false dev: false
/cosmos-directory-types@0.0.6: /cosmos-directory-types@0.0.6:
@@ -7878,6 +7871,7 @@ packages:
/decode-uri-component@0.4.1: /decode-uri-component@0.4.1:
resolution: {integrity: sha512-+8VxcR21HhTy8nOt6jf20w0c9CADrw1O8d+VZ/YzzCt4bJ3uBjw+D1q2osAB8RnpwwaeYBxy0HyKQxD5JBMuuQ==} resolution: {integrity: sha512-+8VxcR21HhTy8nOt6jf20w0c9CADrw1O8d+VZ/YzzCt4bJ3uBjw+D1q2osAB8RnpwwaeYBxy0HyKQxD5JBMuuQ==}
engines: {node: '>=14.16'} engines: {node: '>=14.16'}
dev: true
/deep-eql@4.1.3: /deep-eql@4.1.3:
resolution: {integrity: sha512-WaEtAOpRA1MQ0eohqZjpGD8zdI0Ovsm8mmFhaDN8dvDZzyoUMcYDnf5Y6iu7HTXxf8JDS23qWa4a+hKCDyOPzw==} resolution: {integrity: sha512-WaEtAOpRA1MQ0eohqZjpGD8zdI0Ovsm8mmFhaDN8dvDZzyoUMcYDnf5Y6iu7HTXxf8JDS23qWa4a+hKCDyOPzw==}
@@ -8947,6 +8941,7 @@ packages:
/filter-obj@5.1.0: /filter-obj@5.1.0:
resolution: {integrity: sha512-qWeTREPoT7I0bifpPUXtxkZJ1XJzxWtfoWWkdVGqa+eCr3SHW/Ocp89o8vLvbUuQnadybJpjOKu4V+RwO6sGng==} resolution: {integrity: sha512-qWeTREPoT7I0bifpPUXtxkZJ1XJzxWtfoWWkdVGqa+eCr3SHW/Ocp89o8vLvbUuQnadybJpjOKu4V+RwO6sGng==}
engines: {node: '>=14.16'} engines: {node: '>=14.16'}
dev: true
/find-cache-dir@3.3.2: /find-cache-dir@3.3.2:
resolution: {integrity: sha512-wXZV5emFEjrridIgED11OoUKLxiYjAcqot/NJdAkOhlJ+vGzwhOAfcG5OX1jP+S0PcjEn8bdMJv+g2jwQ3Onig==} resolution: {integrity: sha512-wXZV5emFEjrridIgED11OoUKLxiYjAcqot/NJdAkOhlJ+vGzwhOAfcG5OX1jP+S0PcjEn8bdMJv+g2jwQ3Onig==}
@@ -11288,8 +11283,8 @@ packages:
engines: {node: '>=10.5.0'} engines: {node: '>=10.5.0'}
dev: true dev: true
/node-fetch-native@1.4.1: /node-fetch-native@1.4.0:
resolution: {integrity: sha512-NsXBU0UgBxo2rQLOeWNZqS3fvflWePMECr8CoSWoSTqCqGbVVsvl9vZu1HfQicYN0g5piV9Gh8RTEvo/uP752w==} resolution: {integrity: sha512-F5kfEj95kX8tkDhUCYdV8dg3/8Olx/94zB8+ZNthFs6Bz31UpUi8Xh40TN3thLwXgrwXry1pEg9lJ++tLWTcqA==}
dev: false dev: false
/node-fetch@2.6.12: /node-fetch@2.6.12:
@@ -11877,6 +11872,7 @@ packages:
decode-uri-component: 0.4.1 decode-uri-component: 0.4.1
filter-obj: 5.1.0 filter-obj: 5.1.0
split-on-first: 3.0.0 split-on-first: 3.0.0
dev: true
/queue-microtask@1.2.3: /queue-microtask@1.2.3:
resolution: {integrity: sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A==} resolution: {integrity: sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A==}
@@ -12701,6 +12697,7 @@ packages:
/split-on-first@3.0.0: /split-on-first@3.0.0:
resolution: {integrity: sha512-qxQJTx2ryR0Dw0ITYyekNQWpz6f8dGd7vffGNflQQ3Iqj9NJ6qiZ7ELpZsJ/QBhIVAiDfXdag3+Gp8RvWa62AA==} resolution: {integrity: sha512-qxQJTx2ryR0Dw0ITYyekNQWpz6f8dGd7vffGNflQQ3Iqj9NJ6qiZ7ELpZsJ/QBhIVAiDfXdag3+Gp8RvWa62AA==}
engines: {node: '>=12'} engines: {node: '>=12'}
dev: true
/split2@4.2.0: /split2@4.2.0:
resolution: {integrity: sha512-UcjcJOWknrNkF6PLX83qcHM6KHgVKNkV62Y8a5uYDVv9ydGQVwAHMKqHdJje1VTWpljG0WYpCDhrCdAOYH4TWg==} resolution: {integrity: sha512-UcjcJOWknrNkF6PLX83qcHM6KHgVKNkV62Y8a5uYDVv9ydGQVwAHMKqHdJje1VTWpljG0WYpCDhrCdAOYH4TWg==}
@@ -14099,3 +14096,7 @@ packages:
/zwitch@2.0.4: /zwitch@2.0.4:
resolution: {integrity: sha512-bXE4cR/kVZhKZX/RjPEflHaKVhUVl85noU3v6b8apfQEc1x4A+zBxjZ4lN8LqGd6WZ3dl98pY4o717VFmoPp+A==} resolution: {integrity: sha512-bXE4cR/kVZhKZX/RjPEflHaKVhUVl85noU3v6b8apfQEc1x4A+zBxjZ4lN8LqGd6WZ3dl98pY4o717VFmoPp+A==}
dev: true dev: true
settings:
autoInstallPeers: true
excludeLinksFromLockfile: false
+3 -94
View File
@@ -1,9 +1,4 @@
{ {
"apps": {
"ios": {
"scheme": "dydxv4"
}
},
"deployments": { "deployments": {
"MAINNET": { "MAINNET": {
"environments": [ "environments": [
@@ -43,7 +38,6 @@
"dydxChainId": "dydxprotocol-testnet", "dydxChainId": "dydxprotocol-testnet",
"chainName": "dYdX Chain", "chainName": "dYdX Chain",
"chainLogo": "dydx-chain.png", "chainLogo": "dydx-chain.png",
"squidIntegratorId": "dYdX-api",
"isMainNet": false, "isMainNet": false,
"tokens": { "tokens": {
"chain": { "chain": {
@@ -116,7 +110,6 @@
"dydxChainId": "dydxprotocol-testnet", "dydxChainId": "dydxprotocol-testnet",
"chainName": "dYdX Chain", "chainName": "dYdX Chain",
"chainLogo": "dydx-chain.png", "chainLogo": "dydx-chain.png",
"squidIntegratorId": "dYdX-api",
"isMainNet": false, "isMainNet": false,
"tokens": { "tokens": {
"chain": { "chain": {
@@ -188,7 +181,6 @@
"dydxChainId": "dydxprotocol-testnet", "dydxChainId": "dydxprotocol-testnet",
"chainName": "dYdX Chain", "chainName": "dYdX Chain",
"chainLogo": "dydx-chain.png", "chainLogo": "dydx-chain.png",
"squidIntegratorId": "dYdX-api",
"isMainNet": false, "isMainNet": false,
"tokens": { "tokens": {
"chain": { "chain": {
@@ -208,8 +200,8 @@
"endpoints": { "endpoints": {
"indexers": [ "indexers": [
{ {
"api": "https://indexer.v4dev4.dydx.exchange", "api": "http://indexer.v4dev4.dydx.exchange",
"socket": "wss://indexer.v4dev4.dydx.exchange" "socket": "ws://indexer.v4dev4.dydx.exchange"
} }
], ],
"validators": [ "validators": [
@@ -260,7 +252,6 @@
"dydxChainId": "dydxprotocol-testnet", "dydxChainId": "dydxprotocol-testnet",
"chainName": "dYdX Chain", "chainName": "dYdX Chain",
"chainLogo": "dydx-chain.png", "chainLogo": "dydx-chain.png",
"squidIntegratorId": "dYdX-api",
"isMainNet": false, "isMainNet": false,
"tokens": { "tokens": {
"chain": { "chain": {
@@ -332,7 +323,6 @@
"dydxChainId": "dydxprotocol-testnet", "dydxChainId": "dydxprotocol-testnet",
"chainName": "dYdX Chain", "chainName": "dYdX Chain",
"chainLogo": "dydx-chain.png", "chainLogo": "dydx-chain.png",
"squidIntegratorId": "dYdX-api",
"isMainNet": false, "isMainNet": false,
"tokens": { "tokens": {
"chain": { "chain": {
@@ -400,84 +390,12 @@
"signTypedDataDomainName": "dYdX Chain" "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": {
"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}",
"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",
"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 Chain"
},
"apps": {
"ios": {
"minimalVersion": "1.0",
"build":40000,
"url": "https://apps.apple.com/app/dydx/id1564787350"
}
}
},
"dydxprotocol-staging-west": { "dydxprotocol-staging-west": {
"name": "v4 Staging West", "name": "v4 Staging West",
"ethereumChainId": "5", "ethereumChainId": "5",
"dydxChainId": "dydxprotocol-testnet", "dydxChainId": "dydxprotocol-testnet",
"chainName": "dYdX Chain", "chainName": "dYdX Chain",
"chainLogo": "dydx-chain.png", "chainLogo": "dydx-chain.png",
"squidIntegratorId": "dYdX-api",
"isMainNet": false, "isMainNet": false,
"tokens": { "tokens": {
"chain": { "chain": {
@@ -551,7 +469,6 @@
"dydxChainId": "dydx-testnet-4", "dydxChainId": "dydx-testnet-4",
"chainName": "dYdX Chain", "chainName": "dYdX Chain",
"chainLogo": "dydx-chain.png", "chainLogo": "dydx-chain.png",
"squidIntegratorId": "dYdX-api",
"isMainNet": false, "isMainNet": false,
"tokens": { "tokens": {
"chain": { "chain": {
@@ -629,7 +546,6 @@
"dydxChainId": "dydx-testnet-4", "dydxChainId": "dydx-testnet-4",
"chainName": "dYdX Chain", "chainName": "dYdX Chain",
"chainLogo": "dydx-chain.png", "chainLogo": "dydx-chain.png",
"squidIntegratorId": "dYdX-api",
"isMainNet": false, "isMainNet": false,
"tokens": { "tokens": {
"chain": { "chain": {
@@ -704,7 +620,6 @@
"dydxChainId": "dydx-testnet-4", "dydxChainId": "dydx-testnet-4",
"chainName": "dYdX Chain", "chainName": "dYdX Chain",
"chainLogo": "dydx-chain.png", "chainLogo": "dydx-chain.png",
"squidIntegratorId": "dYdX-api",
"isMainNet": false, "isMainNet": false,
"tokens": { "tokens": {
"chain": { "chain": {
@@ -779,7 +694,6 @@
"dydxChainId": "dydx-testnet-4", "dydxChainId": "dydx-testnet-4",
"chainName": "dYdX Chain", "chainName": "dYdX Chain",
"chainLogo": "dydx-chain.png", "chainLogo": "dydx-chain.png",
"squidIntegratorId": "dYdX-api",
"isMainNet": false, "isMainNet": false,
"tokens": { "tokens": {
"chain": { "chain": {
@@ -854,7 +768,6 @@
"dydxChainId": "dydx-testnet-4", "dydxChainId": "dydx-testnet-4",
"chainName": "dYdX Chain", "chainName": "dYdX Chain",
"chainLogo": "dydx-chain.png", "chainLogo": "dydx-chain.png",
"squidIntegratorId": "dYdX-api",
"isMainNet": false, "isMainNet": false,
"tokens": { "tokens": {
"chain": { "chain": {
@@ -929,7 +842,6 @@
"dydxChainId": "dydx-testnet-4", "dydxChainId": "dydx-testnet-4",
"chainName": "dYdX Chain", "chainName": "dYdX Chain",
"chainLogo": "dydx-chain.png", "chainLogo": "dydx-chain.png",
"squidIntegratorId": "dYdX-api",
"isMainNet": false, "isMainNet": false,
"tokens": { "tokens": {
"chain": { "chain": {
@@ -964,7 +876,6 @@
"privacy": "https://dydx.exchange/privacy", "privacy": "https://dydx.exchange/privacy",
"statusPage": "https://status.v4testnet.dydx.exchange/", "statusPage": "https://status.v4testnet.dydx.exchange/",
"mintscan": "https://testnet.mintscan.io/dydx-testnet/txs/{tx_hash}", "mintscan": "https://testnet.mintscan.io/dydx-testnet/txs/{tx_hash}",
"mintscanBase": "https://testnet.mintscan.io/dydx-testnet",
"documentation": "https://docs.dydx.exchange/", "documentation": "https://docs.dydx.exchange/",
"community": "https://discord.com/invite/dydx", "community": "https://discord.com/invite/dydx",
"feedback": "https://docs.google.com/forms/d/e/1FAIpQLSezLsWCKvAYDEb7L-2O4wOON1T56xxro9A2Azvl6IxXHP_15Q/viewform", "feedback": "https://docs.google.com/forms/d/e/1FAIpQLSezLsWCKvAYDEb7L-2O4wOON1T56xxro9A2Azvl6IxXHP_15Q/viewform",
@@ -995,7 +906,6 @@
"dydxChainId": "dydx-testnet-4", "dydxChainId": "dydx-testnet-4",
"chainName": "dYdX Chain", "chainName": "dYdX Chain",
"chainLogo": "dydx-chain.png", "chainLogo": "dydx-chain.png",
"squidIntegratorId": "dYdX-api",
"isMainNet": false, "isMainNet": false,
"tokens": { "tokens": {
"chain": { "chain": {
@@ -1070,7 +980,6 @@
"dydxChainId": "[mainnet chain id]", "dydxChainId": "[mainnet chain id]",
"chainName": "dYdX Chain", "chainName": "dYdX Chain",
"chainLogo": "dydx-chain.png", "chainLogo": "dydx-chain.png",
"squidIntegratorId": "[mainnet squid integrator id]",
"isMainNet": true, "isMainNet": true,
"tokens": { "tokens": {
"comment": "Change according to mainnet release", "comment": "Change according to mainnet release",
@@ -1105,7 +1014,7 @@
"tos": "[HTTP link to TOS]", "tos": "[HTTP link to TOS]",
"privacy": "[HTTP link to Privacy Policy]", "privacy": "[HTTP link to Privacy Policy]",
"mintscan": "[HTTP link to Mintscan, with {tx_hash} placeholder]", "mintscan": "[HTTP link to Mintscan, with {tx_hash} placeholder]",
"mintscanBase": "[HTTP link to TOS mintscan base url]", "mintscanBase": "[HTTP link to TOS mintsacn base url]",
"feedback": "[HTTP link to feedback form, can be null]", "feedback": "[HTTP link to feedback form, can be null]",
"blogs": "[HTTP link to blogs, can be null]", "blogs": "[HTTP link to blogs, can be null]",
"foundation": "[HTTP link to foundation, can be null]", "foundation": "[HTTP link to foundation, can be null]",
-2
View File
@@ -23,7 +23,6 @@ import { LocalNotificationsProvider } from '@/hooks/useLocalNotifications';
import { RestrictionProvider } from '@/hooks/useRestrictions'; import { RestrictionProvider } from '@/hooks/useRestrictions';
import { SubaccountProvider } from '@/hooks/useSubaccount'; import { SubaccountProvider } from '@/hooks/useSubaccount';
import { SquidProvider } from '@/hooks/useSquid'; import { SquidProvider } from '@/hooks/useSquid';
import { TestFlagsProvider } from '@/hooks/useTestFlags';
import { GuardedMobileRoute } from '@/components/GuardedMobileRoute'; import { GuardedMobileRoute } from '@/components/GuardedMobileRoute';
@@ -124,7 +123,6 @@ const providers = [
wrapProvider(QueryClientProvider, { client: queryClient }), wrapProvider(QueryClientProvider, { client: queryClient }),
wrapProvider(GrazProvider), wrapProvider(GrazProvider),
wrapProvider(WagmiConfig, { config }), wrapProvider(WagmiConfig, { config }),
wrapProvider(TestFlagsProvider),
wrapProvider(LocaleProvider), wrapProvider(LocaleProvider),
wrapProvider(RestrictionProvider), wrapProvider(RestrictionProvider),
wrapProvider(DydxProvider), wrapProvider(DydxProvider),
-1
View File
@@ -225,7 +225,6 @@ Styled.CollapsibleContent = styled(CollapsibleContent)`
`; `;
Styled.IconButton = styled(IconButton)` Styled.IconButton = styled(IconButton)`
--button-icon-size: 1em;
${Styled.CollapsibleRoot}[data-state='closed'] & { ${Styled.CollapsibleRoot}[data-state='closed'] & {
rotate: -0.5turn; rotate: -0.5turn;
} }
-3
View File
@@ -34,7 +34,6 @@ type PickDialogProps = Pick<
| 'slotHeaderInner' | 'slotHeaderInner'
| 'slotTrigger' | 'slotTrigger'
| 'slotFooter' | 'slotFooter'
| 'preventClose'
>; >;
export const ComboboxDialogMenu = < export const ComboboxDialogMenu = <
@@ -58,7 +57,6 @@ export const ComboboxDialogMenu = <
children, children,
placement = DialogPlacement.Default, placement = DialogPlacement.Default,
preventClose,
className, className,
}: ElementProps<MenuItemValue, MenuGroupValue> & }: ElementProps<MenuItemValue, MenuGroupValue> &
PickComboxMenuProps<MenuItemValue, MenuGroupValue> & PickComboxMenuProps<MenuItemValue, MenuGroupValue> &
@@ -74,7 +72,6 @@ export const ComboboxDialogMenu = <
slotTrigger={slotTrigger} slotTrigger={slotTrigger}
slotFooter={slotFooter} slotFooter={slotFooter}
placement={placement} placement={placement}
preventClose={preventClose}
className={className} className={className}
> >
<Styled.ComboboxMenu <Styled.ComboboxMenu
+1 -3
View File
@@ -33,11 +33,9 @@ export const DropdownHeaderMenu = <MenuItemValue extends string>({
return ( return (
<Root> <Root>
<Styled.Trigger className={className} asChild> <Styled.Trigger className={className}>
<div>
{children} {children}
<Styled.DropdownIconButton iconName={IconName.Caret} isToggle /> <Styled.DropdownIconButton iconName={IconName.Caret} isToggle />
</div>
</Styled.Trigger> </Styled.Trigger>
<Portal> <Portal>
<Styled.Content <Styled.Content
+1 -7
View File
@@ -24,10 +24,9 @@ import {
CommentIcon, CommentIcon,
CopyIcon, CopyIcon,
CubeIcon, CubeIcon,
DepositIcon,
DepthChartIcon,
DiscordIcon, DiscordIcon,
EtherscanIcon, EtherscanIcon,
DepthChartIcon,
ExportKeysIcon, ExportKeysIcon,
FeedbackIcon, FeedbackIcon,
FileIcon, FileIcon,
@@ -70,7 +69,6 @@ import {
WarningIcon, WarningIcon,
WebsiteIcon, WebsiteIcon,
WhitepaperIcon, WhitepaperIcon,
WithdrawIcon,
} from '@/icons'; } from '@/icons';
export enum IconName { export enum IconName {
@@ -95,7 +93,6 @@ export enum IconName {
Comment = 'Comment', Comment = 'Comment',
Copy = 'Copy', Copy = 'Copy',
Cube = 'Cube', Cube = 'Cube',
Deposit = 'Deposit',
DepthChart = 'DepthChart', DepthChart = 'DepthChart',
Discord = 'Discord', Discord = 'Discord',
Etherscan = 'Etherscan', Etherscan = 'Etherscan',
@@ -142,7 +139,6 @@ export enum IconName {
Warning = 'Warning', Warning = 'Warning',
Website = 'Website', Website = 'Website',
Whitepaper = 'Whitepaper', Whitepaper = 'Whitepaper',
Withdraw = 'Withdraw',
} }
const icons = { const icons = {
@@ -167,7 +163,6 @@ const icons = {
[IconName.Comment]: CommentIcon, [IconName.Comment]: CommentIcon,
[IconName.Copy]: CopyIcon, [IconName.Copy]: CopyIcon,
[IconName.Cube]: CubeIcon, [IconName.Cube]: CubeIcon,
[IconName.Deposit]: DepositIcon,
[IconName.DepthChart]: DepthChartIcon, [IconName.DepthChart]: DepthChartIcon,
[IconName.Discord]: DiscordIcon, [IconName.Discord]: DiscordIcon,
[IconName.Etherscan]: EtherscanIcon, [IconName.Etherscan]: EtherscanIcon,
@@ -213,7 +208,6 @@ const icons = {
[IconName.Warning]: WarningIcon, [IconName.Warning]: WarningIcon,
[IconName.Website]: WebsiteIcon, [IconName.Website]: WebsiteIcon,
[IconName.Whitepaper]: WhitepaperIcon, [IconName.Whitepaper]: WhitepaperIcon,
[IconName.Withdraw]: WithdrawIcon,
} as Record<IconName, ElementType>; } as Record<IconName, ElementType>;
type ElementProps = { type ElementProps = {
-1
View File
@@ -67,7 +67,6 @@ const Styled: Record<string, AnyStyledComponent> = {};
const buttonMixin = css` const buttonMixin = css`
// Params // Params
--button-icon-size: 1.125em; --button-icon-size: 1.125em;
--button-padding: 0;
// Rules // Rules
> * { > * {
+2 -2
View File
@@ -71,7 +71,7 @@ const NavItem = forwardRef(
)} )}
</span> </span>
{slotAfter} {slotAfter}
{subitems?.length && <Styled.Icon iconName={IconName.Triangle} />} {subitems?.length && <Styled.Icon iconName={IconName.Caret} />}
</> </>
); );
@@ -525,7 +525,7 @@ Styled.NavItem = styled(NavItem)<{ orientation: 'horizontal' | 'vertical' }>`
`; `;
Styled.Icon = styled(Icon)` Styled.Icon = styled(Icon)`
font-size: 0.375em; height: 0.75em;
transition: rotate 0.3s var(--ease-out-expo); transition: rotate 0.3s var(--ease-out-expo);
${Styled.List}[data-orientation="menu"] & { ${Styled.List}[data-orientation="menu"] & {
+5 -23
View File
@@ -31,7 +31,7 @@ export const Panel = ({
hasSeparator, hasSeparator,
className, className,
}: PanelProps & PanelStyleProps) => ( }: PanelProps & PanelStyleProps) => (
<Styled.Panel onClick={onClick} className={className}> <Styled.Panel onClick={onClick}>
<Styled.Left> <Styled.Left>
{href ? ( {href ? (
<Link to={href}> <Link to={href}>
@@ -53,7 +53,7 @@ export const Panel = ({
</Styled.Header> </Styled.Header>
) )
)} )}
<Styled.Content>{children}</Styled.Content> <Styled.Content className={className}>{children}</Styled.Content>
</Styled.Left> </Styled.Left>
{slotRight} {slotRight}
</Styled.Panel> </Styled.Panel>
@@ -61,29 +61,11 @@ export const Panel = ({
const Styled: Record<string, AnyStyledComponent> = {}; const Styled: Record<string, AnyStyledComponent> = {};
Styled.Panel = styled.section<{ onClick?: () => void }>` Styled.Panel = styled.section`
--panel-paddingY: 1rem;
--panel-paddingX: 1rem;
--panel-content-paddingY: var(--panel-paddingY);
--panel-content-paddingX: var(--panel-paddingX);
${layoutMixins.row} ${layoutMixins.row}
background-color: var(--color-layer-3); background-color: var(--color-layer-3);
border-radius: 0.875rem; 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` Styled.Left = styled.div`
@@ -93,7 +75,7 @@ Styled.Left = styled.div`
Styled.Header = styled.header<{ hasSeparator?: boolean }>` Styled.Header = styled.header<{ hasSeparator?: boolean }>`
${layoutMixins.spacedRow} ${layoutMixins.spacedRow}
padding: var(--panel-paddingY) var(--panel-paddingX); padding: 1rem 1rem;
${({ hasSeparator }) => ${({ hasSeparator }) =>
hasSeparator && hasSeparator &&
@@ -112,5 +94,5 @@ Styled.Content = styled.div`
${layoutMixins.scrollArea} ${layoutMixins.scrollArea}
${layoutMixins.stickyArea0} ${layoutMixins.stickyArea0}
--stickyArea0-background: transparent; --stickyArea0-background: transparent;
padding: var(--panel-content-paddingY) var(--panel-content-paddingX); padding: 1rem 1rem;
`; `;
+4 -15
View File
@@ -7,15 +7,13 @@ import { ButtonShape, ButtonSize } from '@/constants/buttons';
import { useBreakpoints } from '@/hooks'; import { useBreakpoints } from '@/hooks';
import { layoutMixins } from '@/styles/layoutMixins'; import { layoutMixins } from '@/styles/layoutMixins';
import { type BaseButtonProps } from '@/components/BaseButton'; import { type BaseButtonProps } from '@/components/BaseButton';
import { ToggleButton } from '@/components/ToggleButton'; import { ToggleButton } from '@/components/ToggleButton';
type ElementProps<MenuItemValue extends string> = { type ElementProps<MenuItemValue extends string> = {
items: MenuItem<MenuItemValue>[]; items: MenuItem<MenuItemValue>[];
value: MenuItemValue; value: MenuItemValue;
onValueChange: (value: any) => void; onValueChange: (value: MenuItemValue) => void;
onInteraction?: () => void;
ensureSelected?: boolean;
}; };
type StyleProps = { type StyleProps = {
@@ -27,14 +25,10 @@ export const ToggleGroup = forwardRef(
{ {
items, items,
value, value,
ensureSelected = true,
onValueChange, onValueChange,
onInteraction,
className, className,
size, size,
shape = ButtonShape.Pill, shape = ButtonShape.Pill,
...buttonProps ...buttonProps
}: ElementProps<MenuItemValue> & StyleProps & BaseButtonProps, }: ElementProps<MenuItemValue> & StyleProps & BaseButtonProps,
ref: Ref<HTMLDivElement> ref: Ref<HTMLDivElement>
@@ -46,17 +40,12 @@ export const ToggleGroup = forwardRef(
ref={ref} ref={ref}
type="single" type="single"
value={value} value={value}
onValueChange={(newValue: MenuItemValue) => { onValueChange={onValueChange}
if ((ensureSelected && newValue) || !ensureSelected) {
onValueChange(newValue);
}
onInteraction?.();
}}
className={className} className={className}
loop loop
> >
{items.map((item) => ( {items.map((item) => (
<Item key={item.value} value={item.value} asChild> <Item key={item.value} value={item.value} aria-label={item.label} asChild>
<ToggleButton <ToggleButton
size={size ? size : isTablet ? ButtonSize.Small : ButtonSize.XSmall} size={size ? size : isTablet ? ButtonSize.Small : ButtonSize.XSmall}
shape={shape} shape={shape}
+6 -12
View File
@@ -1,18 +1,12 @@
import environments from '../../public/configs/env.json'; import environments from '../../public/configs/env.json';
const CURRENT_MODE = ({ // TODO: Update for Mainnet deployment
production: 'MAINNET', export const AVAILABLE_ENVIRONMENTS =
testnet: 'TESTNET', import.meta.env.MODE === 'production'
staging: 'DEV', ? environments.deployments.TESTNET
development: 'DEV', : environments.deployments.DEV;
}[import.meta.env.MODE] ?? 'MAINNET') as 'MAINNET' | 'TESTNET' | 'DEV';
export const isMainnet = CURRENT_MODE === 'MAINNET'; export const CURRENT_ABACUS_DEPLOYMENT = import.meta.env.MODE === 'production' ? 'TESTNET' : 'DEV';
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 const ENVIRONMENT_CONFIG_MAP = environments.environments;
export type DydxNetwork = keyof typeof ENVIRONMENT_CONFIG_MAP; export type DydxNetwork = keyof typeof ENVIRONMENT_CONFIG_MAP;
export const DEFAULT_APP_ENVIRONMENT = AVAILABLE_ENVIRONMENTS.default as DydxNetwork; export const DEFAULT_APP_ENVIRONMENT = AVAILABLE_ENVIRONMENTS.default as DydxNetwork;
-2
View File
@@ -42,7 +42,6 @@ const useAccountsContext = () => {
selectedWalletError, selectedWalletError,
evmAddress, evmAddress,
signerWagmi, signerWagmi,
publicClientWagmi,
dydxAddress: connectedDydxAddress, dydxAddress: connectedDydxAddress,
signerGraz, signerGraz,
} = useWalletConnection(); } = useWalletConnection();
@@ -297,7 +296,6 @@ const useAccountsContext = () => {
// Wallet connection (EVM) // Wallet connection (EVM)
evmAddress, evmAddress,
signerWagmi, signerWagmi,
publicClientWagmi,
// Wallet connection (Cosmos) // Wallet connection (Cosmos)
signerGraz, signerGraz,
+1 -2
View File
@@ -1,4 +1,3 @@
import { isDev } from '@/constants/networks';
import { WalletType } from '@/constants/wallets'; import { WalletType } from '@/constants/wallets';
import { isTruthy } from '@/lib/isTruthy'; import { isTruthy } from '@/lib/isTruthy';
@@ -7,7 +6,7 @@ export const useDisplayedWallets = () => {
return [ return [
WalletType.MetaMask, WalletType.MetaMask,
isDev && WalletType.Keplr, import.meta.env.MODE !== 'production' && WalletType.Keplr,
WalletType.WalletConnect2, WalletType.WalletConnect2,
+1 -10
View File
@@ -66,16 +66,7 @@ const useLocalNotificationsContext = () => {
status: currentStatus, status: currentStatus,
} of transferNotifications) { } of transferNotifications) {
try { try {
// skip if error is returned or if the transaction is not ongoing if (currentStatus && currentStatus?.squidTransactionStatus !== 'ongoing') continue;
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 }); const status = await squid?.getStatus({ transactionId: txHash, toChainId, fromChainId });
if (status) statuses[txHash] = status; if (status) statuses[txHash] = status;
+8 -12
View File
@@ -6,10 +6,8 @@ import { MarketFilters, MARKET_FILTER_LABELS, type MarketData } from '@/constant
import { getAssets } from '@/state/assetsSelectors'; import { getAssets } from '@/state/assetsSelectors';
import { getPerpetualMarkets } from '@/state/perpetualsSelectors'; import { getPerpetualMarkets } from '@/state/perpetualsSelectors';
import { isTruthy } from '@/lib/isTruthy';
const filterFunctions = { const filterFunctions = {
[MarketFilters.ALL]: () => true, [MarketFilters.ALL]: (market: MarketData) => true,
[MarketFilters.LAYER_1]: (market: MarketData) => { [MarketFilters.LAYER_1]: (market: MarketData) => {
return market.asset.tags?.toArray().includes('Layer 1'); return market.asset.tags?.toArray().includes('Layer 1');
}, },
@@ -30,15 +28,13 @@ export const useMarketsData = (
const allAssets = useSelector(getAssets, shallowEqual) || {}; const allAssets = useSelector(getAssets, shallowEqual) || {};
const markets = useMemo(() => { const markets = useMemo(() => {
return Object.values(allPerpetualMarkets) return Object.values(allPerpetualMarkets).map((marketData) => ({
.filter(isTruthy) asset: allAssets[marketData.assetId],
.map((marketData) => ({ tickSizeDecimals: marketData.configs?.tickSizeDecimals,
asset: allAssets[marketData.assetId], ...marketData,
tickSizeDecimals: marketData.configs?.tickSizeDecimals, ...marketData.perpetual,
...marketData, ...marketData.configs,
...marketData.perpetual, })) as MarketData[];
...marketData.configs,
})) as MarketData[];
}, [allPerpetualMarkets, allAssets]); }, [allPerpetualMarkets, allAssets]);
const filteredMarkets = useMemo(() => { const filteredMarkets = useMemo(() => {
+2 -4
View File
@@ -7,11 +7,9 @@ import { AlertType } from '@/constants/alerts';
import { AbacusOrderStatus, ORDER_SIDES } from '@/constants/abacus'; import { AbacusOrderStatus, ORDER_SIDES } from '@/constants/abacus';
import { DialogTypes } from '@/constants/dialogs'; import { DialogTypes } from '@/constants/dialogs';
import { STRING_KEYS, StringKey } from '@/constants/localization'; import { STRING_KEYS, StringKey } from '@/constants/localization';
import { ENVIRONMENT_CONFIG_MAP } from '@/constants/networks';
import { type NotificationTypeConfig, NotificationType } from '@/constants/notifications'; import { type NotificationTypeConfig, NotificationType } from '@/constants/notifications';
import { ORDER_SIDE_STRINGS } from '@/constants/trade'; import { ORDER_SIDE_STRINGS } from '@/constants/trade';
import { useSelectedNetwork } from '@/hooks';
import { useLocalNotifications } from '@/hooks/useLocalNotifications'; import { useLocalNotifications } from '@/hooks/useLocalNotifications';
import { Icon, IconName } from '@/components/Icon'; import { Icon, IconName } from '@/components/Icon';
@@ -25,6 +23,7 @@ import { OrderStatusIcon } from '@/views/OrderStatusIcon';
import { useStringGetter } from './useStringGetter'; import { useStringGetter } from './useStringGetter';
import { TransferStatusSteps } from '@/views/TransferStatusSteps'; import { TransferStatusSteps } from '@/views/TransferStatusSteps';
import { TESTNET_CHAIN_ID } from '@dydxprotocol/v4-client-js';
export const notificationTypes = [ export const notificationTypes = [
{ {
@@ -125,7 +124,6 @@ export const notificationTypes = [
useTrigger: ({ trigger }) => { useTrigger: ({ trigger }) => {
const stringGetter = useStringGetter(); const stringGetter = useStringGetter();
const { transferNotifications } = useLocalNotifications(); const { transferNotifications } = useLocalNotifications();
const { selectedNetwork } = useSelectedNetwork();
const getTitleStringKey = useCallback((type: 'deposit' | 'withdrawal', finished: boolean) => { const getTitleStringKey = useCallback((type: 'deposit' | 'withdrawal', finished: boolean) => {
if (type === 'deposit' && !finished) return STRING_KEYS.DEPOSIT_IN_PROGRESS; if (type === 'deposit' && !finished) return STRING_KEYS.DEPOSIT_IN_PROGRESS;
@@ -138,7 +136,7 @@ export const notificationTypes = [
for (const transfer of transferNotifications) { for (const transfer of transferNotifications) {
const { fromChainId, status, txHash, toAmount } = transfer; const { fromChainId, status, txHash, toAmount } = transfer;
const finished = Boolean(status) && status?.squidTransactionStatus !== 'ongoing'; const finished = Boolean(status) && status?.squidTransactionStatus !== 'ongoing';
const type = fromChainId === ENVIRONMENT_CONFIG_MAP[selectedNetwork].dydxChainId ? 'withdrawal' : 'deposit'; const type = fromChainId === TESTNET_CHAIN_ID ? 'withdrawal' : 'deposit';
// @ts-ignore status.errors is not in the type definition but can be returned // @ts-ignore status.errors is not in the type definition but can be returned
const error = status?.errors?.length ? status?.errors[0] : status?.error; const error = status?.errors?.length ? status?.errors[0] : status?.error;
+2 -6
View File
@@ -8,7 +8,7 @@ import { getSelectedNetwork } from '@/state/appSelectors';
export const NATIVE_TOKEN_ADDRESS = '0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE'; export const NATIVE_TOKEN_ADDRESS = '0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE';
export const STATUS_ERROR_GRACE_PERIOD = 300_000; export const STATUS_ERROR_GRACE_PERIOD = 120_000;
const useSquidContext = () => { const useSquidContext = () => {
const selectedNetwork = useSelector(getSelectedNetwork); const selectedNetwork = useSelector(getSelectedNetwork);
@@ -22,11 +22,7 @@ const useSquidContext = () => {
}; };
const squid = useMemo( 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] [selectedNetwork]
); );
+60 -91
View File
@@ -48,7 +48,7 @@ export const useSubaccount = () => useContext(SubaccountContext);
export const useSubaccountContext = ({ localDydxWallet }: { localDydxWallet?: LocalWallet }) => { export const useSubaccountContext = ({ localDydxWallet }: { localDydxWallet?: LocalWallet }) => {
const dispatch = useDispatch(); const dispatch = useDispatch();
const { usdcDenom, usdcDecimals } = useTokenConfigs(); const { usdcDenom } = useTokenConfigs();
const { compositeClient, faucetClient } = useDydxClient(); const { compositeClient, faucetClient } = useDydxClient();
const { getFaucetFunds } = useMemo( const { getFaucetFunds } = useMemo(
@@ -79,34 +79,16 @@ export const useSubaccountContext = ({ localDydxWallet }: { localDydxWallet?: Lo
subaccountClient: SubaccountClient; subaccountClient: SubaccountClient;
assetId?: number; assetId?: number;
amount: 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 ({ withdrawFromSubaccount: async ({
subaccountClient, subaccountClient,
amount, amount,
}: { }: {
subaccountClient: SubaccountClient; subaccountClient: SubaccountClient;
amount: number; 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 ({ transferFromSubaccountToAddress: async ({
subaccountClient, subaccountClient,
assetId = 0, assetId = 0,
@@ -117,33 +99,27 @@ export const useSubaccountContext = ({ localDydxWallet }: { localDydxWallet?: Lo
assetId?: number; assetId?: number;
amount: number; amount: number;
recipient: string; recipient: string;
}) => { }) =>
try { await compositeClient?.validatorClient.post.send(
return await compositeClient?.validatorClient.post.send( subaccountClient?.wallet,
subaccountClient?.wallet, () =>
() => new Promise((resolve) => {
new Promise((resolve) => { const msg =
const msg = compositeClient?.validatorClient.post.composer.composeMsgWithdrawFromSubaccount(
compositeClient?.validatorClient.post.composer.composeMsgWithdrawFromSubaccount( subaccountClient.address,
subaccountClient.address, subaccountClient.subaccountNumber,
subaccountClient.subaccountNumber, assetId,
assetId, Long.fromNumber(amount * QUANTUM_MULTIPLIER),
Long.fromNumber(amount * QUANTUM_MULTIPLIER), recipient
recipient );
);
resolve([msg]); resolve([msg]);
}), }),
false, false,
undefined, undefined,
undefined, undefined,
Method.BroadcastTxCommit Method.BroadcastTxCommit
); ),
} catch (error) {
log('useSubaccount/transferFromSubaccountToAddress', error);
throw error;
}
},
transferNativeToken: async ({ transferNativeToken: async ({
subaccountClient, subaccountClient,
@@ -153,30 +129,24 @@ export const useSubaccountContext = ({ localDydxWallet }: { localDydxWallet?: Lo
subaccountClient: SubaccountClient; subaccountClient: SubaccountClient;
amount: number; amount: number;
recipient: string; recipient: string;
}) => { }) =>
try { await compositeClient?.validatorClient.post.send(
return await compositeClient?.validatorClient.post.send( subaccountClient.wallet,
subaccountClient.wallet, () =>
() => new Promise((resolve) => {
new Promise((resolve) => { const msg = compositeClient?.sendTokenMessage(
const msg = compositeClient?.sendTokenMessage( subaccountClient.wallet,
subaccountClient.wallet, amount.toString(),
amount.toString(), recipient,
recipient );
);
resolve([msg]); resolve([msg]);
}), }),
false, false,
compositeClient?.validatorClient?.post.defaultDydxGasPrice, compositeClient?.validatorClient?.post.defaultDydxGasPrice,
undefined, undefined,
Method.BroadcastTxCommit Method.BroadcastTxCommit
); ),
} catch (error) {
log('useSubaccount/transferNativeToken', error);
throw error;
}
},
sendSquidWithdrawFromSubaccount: async ({ sendSquidWithdrawFromSubaccount: async ({
subaccountClient, subaccountClient,
@@ -188,27 +158,20 @@ export const useSubaccountContext = ({ localDydxWallet }: { localDydxWallet?: Lo
payload: string; payload: string;
}) => { }) => {
if (!compositeClient) throw new Error('client not initialized'); if (!compositeClient) throw new Error('client not initialized');
try {
const transaction = JSON.parse(payload);
const msg = compositeClient.withdrawFromSubaccountMessage( const transaction = JSON.parse(payload);
subaccountClient,
amount.toFixed(usdcDecimals)
);
const ibcMsg: EncodeObject = {
typeUrl: transaction.msgTypeUrl,
value: transaction.msg,
};
return await compositeClient.send( const msg = compositeClient.withdrawFromSubaccountMessage(subaccountClient, amount.toString());
subaccountClient.wallet, const ibcMsg: EncodeObject = {
() => Promise.resolve([msg, ibcMsg]), typeUrl: transaction.msgTypeUrl,
false value: transaction.msg,
); };
} catch (error) {
log('useSubaccount/sendSquidWithdrawFromSubaccount', error); return await compositeClient.send(
throw error; subaccountClient.wallet,
} () => Promise.resolve([msg, ibcMsg]),
false
);
}, },
}), }),
[compositeClient] [compositeClient]
@@ -350,6 +313,11 @@ export const useSubaccountContext = ({ localDydxWallet }: { localDydxWallet?: Lo
placeOrderParams = abacusStateManager.placeOrder(callback); placeOrderParams = abacusStateManager.placeOrder(callback);
} }
track(AnalyticsEvent.TradePlaceOrder, {
...placeOrderParams,
isClosePosition,
} as HumanReadablePlaceOrderPayload & { isClosePosition: boolean });
return placeOrderParams; return placeOrderParams;
}, },
[subaccountClient] [subaccountClient]
@@ -378,6 +346,7 @@ export const useSubaccountContext = ({ localDydxWallet }: { localDydxWallet?: Lo
}) => { }) => {
const callback = (success: boolean, parsingError?: Nullable<ParsingError>) => { const callback = (success: boolean, parsingError?: Nullable<ParsingError>) => {
if (success) { if (success) {
track(AnalyticsEvent.TradeCancelOrder);
onSuccess?.(); onSuccess?.();
} else { } else {
onError?.({ errorStringKey: parsingError?.stringKey }); onError?.({ errorStringKey: parsingError?.stringKey });
-46
View File
@@ -1,46 +0,0 @@
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,10 +19,8 @@ export const useTokenConfigs = (): {
}, },
}; };
usdcDenom: string; usdcDenom: string;
usdcDecimals: number;
usdcLabel: string; usdcLabel: string;
chainTokenDenom: string; chainTokenDenom: string;
chainTokenDecimals: number;
chainTokenLabel: string; chainTokenLabel: string;
} => { } => {
const { selectedNetwork } = useSelectedNetwork(); const { selectedNetwork } = useSelectedNetwork();
@@ -31,10 +29,8 @@ export const useTokenConfigs = (): {
return { return {
tokensConfigs, tokensConfigs,
usdcDenom: tokensConfigs[DydxChainAsset.USDC].denom, usdcDenom: tokensConfigs[DydxChainAsset.USDC].denom,
usdcDecimals: tokensConfigs[DydxChainAsset.USDC].decimals,
usdcLabel: tokensConfigs[DydxChainAsset.USDC].name, usdcLabel: tokensConfigs[DydxChainAsset.USDC].name,
chainTokenDenom: tokensConfigs[DydxChainAsset.CHAINTOKEN].denom, chainTokenDenom: tokensConfigs[DydxChainAsset.CHAINTOKEN].denom,
chainTokenDecimals: tokensConfigs[DydxChainAsset.CHAINTOKEN].decimals,
chainTokenLabel: tokensConfigs[DydxChainAsset.CHAINTOKEN].name, chainTokenLabel: tokensConfigs[DydxChainAsset.CHAINTOKEN].name,
}; };
}; };
+9 -11
View File
@@ -1,4 +1,4 @@
import { useCallback, useEffect, useState, useMemo } from 'react'; import { useCallback, useEffect, useState } from 'react';
import { useSelector } from 'react-redux'; import { useSelector } from 'react-redux';
import { LocalStorageKey } from '@/constants/localStorage'; import { LocalStorageKey } from '@/constants/localStorage';
@@ -90,21 +90,19 @@ export const useWalletConnection = () => {
const selectedNetwork = useSelector(getSelectedNetwork); const selectedNetwork = useSelector(getSelectedNetwork);
const walletConnectConfig = ENVIRONMENT_CONFIG_MAP[selectedNetwork].wallets.walletconnect; const walletConnectConfig = ENVIRONMENT_CONFIG_MAP[selectedNetwork].wallets.walletconnect;
const wagmiConnector = useMemo(
() => const { connectAsync: connectWagmi } =
walletType && walletConnectionType walletType && walletConnectionType
? resolveWagmiConnector({ ? useConnectWagmi({
connector: resolveWagmiConnector({
walletType, walletType,
walletConnection: { walletConnection: {
type: walletConnectionType, type: walletConnectionType,
}, },
walletConnectConfig, walletConnectConfig,
}) }),
: undefined, })
[walletConnectConfig, walletType, walletConnectionType] : useConnectWagmi();
);
const { connectAsync: connectWagmi } = useConnectWagmi({ connector: wagmiConnector })
const { suggestAndConnect: connectGraz } = useConnectGraz(); const { suggestAndConnect: connectGraz } = useConnectGraz();
const connectWallet = useCallback( const connectWallet = useCallback(
-11
View File
@@ -1,11 +0,0 @@
<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>

Before

Width:  |  Height:  |  Size: 886 B

-2
View File
@@ -19,7 +19,6 @@ export { default as CoinsIcon } from './coins.svg';
export { default as CommentIcon } from './comment.svg'; export { default as CommentIcon } from './comment.svg';
export { default as CopyIcon } from './copy.svg'; export { default as CopyIcon } from './copy.svg';
export { default as CubeIcon } from './cube.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 DepthChartIcon } from './depth-chart.svg';
export { default as DiscordIcon } from './discord.svg'; export { default as DiscordIcon } from './discord.svg';
export { default as ExportKeysIcon } from './export-keys.svg'; export { default as ExportKeysIcon } from './export-keys.svg';
@@ -60,7 +59,6 @@ export { default as TransferIcon } from './transfer.svg';
export { default as TriangleIcon } from './triangle.svg'; export { default as TriangleIcon } from './triangle.svg';
export { default as TryAgainIcon } from './try-again.svg'; export { default as TryAgainIcon } from './try-again.svg';
export { default as WarningIcon } from './warning.svg'; export { default as WarningIcon } from './warning.svg';
export { default as WithdrawIcon } from './withdraw.svg';
// Wallets // Wallets
export { default as BitkeepIcon } from './wallets/bitkeep.svg'; export { default as BitkeepIcon } from './wallets/bitkeep.svg';
-4
View File
@@ -1,4 +0,0 @@
<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>

Before

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 { AbacusApiStatus } from '@/constants/abacus';
import { ButtonSize } from '@/constants/buttons'; import { ButtonSize } from '@/constants/buttons';
import { STRING_KEYS } from '@/constants/localization'; import { STRING_KEYS } from '@/constants/localization';
import { ENVIRONMENT_CONFIG_MAP, isDev } from '@/constants/networks'; import { ENVIRONMENT_CONFIG_MAP } from '@/constants/networks';
import { useApiState, useSelectedNetwork, useStringGetter } from '@/hooks'; import { useApiState, useSelectedNetwork, useStringGetter } from '@/hooks';
import { ChatIcon, LinkOutIcon } from '@/icons'; import { ChatIcon, LinkOutIcon } from '@/icons';
@@ -75,7 +75,7 @@ export const FooterDesktop = () => {
)} )}
</Styled.Row> </Styled.Row>
{isDev && ( {import.meta.env.MODE !== 'production' && (
<Styled.Details <Styled.Details
withSeparators withSeparators
items={[ items={[
-1
View File
@@ -236,5 +236,4 @@ Styled.IconButton = styled(IconButton)<{ size?: string }>`
${headerMixins.button} ${headerMixins.button}
--button-border: none; --button-border: none;
--button-icon-size: 1rem; --button-icon-size: 1rem;
--button-padding: 0 0.5em;
`; `;
+10 -10
View File
@@ -30,7 +30,7 @@ import {
import { DialogTypes } from '@/constants/dialogs'; import { DialogTypes } from '@/constants/dialogs';
import { UNCOMMITTED_ORDER_TIMEOUT_MS } from '@/constants/trade'; import { UNCOMMITTED_ORDER_TIMEOUT_MS } from '@/constants/trade';
import { ENVIRONMENT_CONFIG_MAP, DydxNetwork, isTestnet } from '@/constants/networks'; import { QUANTUM_MULTIPLIER } from '@/constants/numbers';
import { RootStore } from '@/state/_store'; import { RootStore } from '@/state/_store';
import { addUncommittedOrderClientId, removeUncommittedOrderClientId } from '@/state/account'; import { addUncommittedOrderClientId, removeUncommittedOrderClientId } from '@/state/account';
@@ -198,12 +198,8 @@ class DydxChainTransactions implements AbacusDYDXChainTransactionsProtocol {
const parsedTx = this.parseToPrimitives(tx); const parsedTx = this.parseToPrimitives(tx);
const hash = parsedTx?.hash; const hash = parsedTx?.hash;
if (isTestnet) { if (import.meta.env.MODE === 'production') {
console.log( console.log(`https://testnet.mintscan.io/dydx-testnet/txs/${hash}`);
`${ENVIRONMENT_CONFIG_MAP[
this.compositeClient.network.getString() as DydxNetwork
]?.links?.mintscan?.replace('{tx_hash}', hash.toString())}`
);
} else console.log(`txHash: ${hash}`); } else console.log(`txHash: ${hash}`);
return JSON.stringify(parsedTx); return JSON.stringify(parsedTx);
@@ -233,7 +229,7 @@ class DydxChainTransactions implements AbacusDYDXChainTransactionsProtocol {
orderFlags, orderFlags,
clobPairId, clobPairId,
goodTilBlock || undefined, goodTilBlock || undefined,
goodTilBlockTime || undefined goodTilBlockTime || undefined,
); );
const parsedTx = this.parseToPrimitives(tx); const parsedTx = this.parseToPrimitives(tx);
@@ -299,11 +295,15 @@ class DydxChainTransactions implements AbacusDYDXChainTransactionsProtocol {
if (!this.localWallet) { if (!this.localWallet) {
throw new Error('Missing compositeClient or 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]); resolve([msg]);
}), }),
this.compositeClient?.validatorClient?.post.defaultDydxGasPrice this.compositeClient?.validatorClient?.post.defaultDydxGasPrice,
); );
const parsedTx = this.parseToPrimitives(tx); const parsedTx = this.parseToPrimitives(tx);
+5
View File
@@ -1,5 +1,10 @@
import type { AbacusFileSystemProtocol, FileLocation, Nullable } from '@/constants/abacus'; 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 { class AbacusFileSystem implements AbacusFileSystemProtocol {
readTextFile(location: FileLocation, path: string): Nullable<string> { readTextFile(location: FileLocation, path: string): Nullable<string> {
return null; return null;
+1 -1
View File
@@ -41,7 +41,7 @@ import AbacusStateNotifier from './stateNotification';
import AbacusLocalizer from './localizer'; import AbacusLocalizer from './localizer';
import AbacusFormatter from './formatter'; import AbacusFormatter from './formatter';
import AbacusThreading from './threading'; import AbacusThreading from './threading';
import AbacusFileSystem from './filesystem'; import AbacusFileSystem, { ENDPOINTS_PATH } from './filesystem';
import { LocaleSeparators } from '../numbers'; import { LocaleSeparators } from '../numbers';
class AbacusStateManager { class AbacusStateManager {
private store: RootStore | undefined; private store: RootStore | undefined;
+7 -2
View File
@@ -56,8 +56,13 @@ class AbacusRest implements AbacusRestProtocol {
.then(async (response) => { .then(async (response) => {
const data = await response.text(); const data = await response.text();
callback(data, response.status); 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);
}
try { try {
lastSuccessfulRestRequestByOrigin[new URL(url).origin] = Date.now(); lastSuccessfulRestRequestByOrigin[new URL(url).origin] = Date.now();
} catch {} } catch {}
+4 -23
View File
@@ -1,6 +1,5 @@
import type { AbacusWebsocketProtocol } from '@/constants/abacus'; import type { AbacusWebsocketProtocol } from '@/constants/abacus';
import type { TradingViewBar } from '@/constants/candles'; import type { TradingViewBar } from '@/constants/candles';
import { isDev } from '@/constants/networks';
import { import {
PING_INTERVAL_MS, PING_INTERVAL_MS,
@@ -9,12 +8,11 @@ import {
PONG_MESSAGE_TYPE, PONG_MESSAGE_TYPE,
} from '@/constants/websocket'; } from '@/constants/websocket';
import { lastSuccessfulWebsocketRequestByOrigin } from '@/hooks/useAnalytics';
import { testFlags } from '@/hooks/useTestFlags';
import { subscriptionsByChannelId } from '@/lib/tradingView/dydxfeed/cache'; import { subscriptionsByChannelId } from '@/lib/tradingView/dydxfeed/cache';
import { mapCandle } from '@/lib/tradingView/utils'; import { mapCandle } from '@/lib/tradingView/utils';
import { lastSuccessfulWebsocketRequestByOrigin } from '@/hooks/useAnalytics';
import { log } from '../telemetry'; import { log } from '../telemetry';
const RECONNECT_INTERVAL_MS = 10_000; const RECONNECT_INTERVAL_MS = 10_000;
@@ -145,23 +143,6 @@ class AbacusWebsocket implements Omit<AbacusWebsocketProtocol, '__doNotUseOrImpl
break; 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: { default: {
break; break;
} }
@@ -180,13 +161,13 @@ class AbacusWebsocket implements Omit<AbacusWebsocketProtocol, '__doNotUseOrImpl
this.socket.onclose = (e) => { this.socket.onclose = (e) => {
this.connectedCallback?.(false); this.connectedCallback?.(false);
if (!isDev) return; if (import.meta.env.MODE === 'production') return;
console.warn('AbacusStateManager > WS > close > ', e); console.warn('AbacusStateManager > WS > close > ', e);
}; };
this.socket.onerror = (e) => { this.socket.onerror = (e) => {
this.connectedCallback?.(false); this.connectedCallback?.(false);
if (!isDev) return; if (import.meta.env.MODE === 'production') return;
console.error('AbacusStateManager > WS > error > ', e); console.error('AbacusStateManager > WS > error > ', e);
}; };
}; };
+1 -3
View File
@@ -1,7 +1,5 @@
import { isDev } from "@/constants/networks";
export const log = (location: string, error: Error, metadata?: any) => { export const log = (location: string, error: Error, metadata?: any) => {
if (isDev) { if (import.meta.env.MODE !== 'production') {
console.warn('telemetry/log:', { location, error, metadata }); console.warn('telemetry/log:', { location, error, metadata });
} }
+6 -10
View File
@@ -180,7 +180,7 @@ Styled.MobileProfileLayout = styled.div`
${layoutMixins.contentContainerPage} ${layoutMixins.contentContainerPage}
gap: 1rem; gap: 1rem;
padding: 1.25rem; padding: 1rem;
`; `;
Styled.Header = styled.header` Styled.Header = styled.header`
@@ -278,17 +278,13 @@ Styled.RewardsPanel = styled(Panel)`
`; `;
Styled.TablePanel = styled(Panel)` Styled.TablePanel = styled(Panel)`
--panel-content-paddingY: 0; max-width: calc(100vw - 2rem);
--panel-content-paddingX: 0; max-height: 10rem;
margin-top: 0.5rem;
> div > div { padding: 0;
margin-top: 0.5rem; border-radius: 0.875rem;
--scrollArea-height: 10rem;
border-radius: 0.875rem;
}
table { table {
max-height: 10rem;
--tableCell-padding: 0.25rem 1rem; --tableCell-padding: 0.25rem 1rem;
--tableRow-backgroundColor: var(--color-layer-3); --tableRow-backgroundColor: var(--color-layer-3);
background-color: var(--color-layer-3); background-color: var(--color-layer-3);
@@ -131,7 +131,7 @@ export const AccountDetailsAndHistory = () => {
key: 'BuyingPower', key: 'BuyingPower',
labelKey: STRING_KEYS.BUYING_POWER, labelKey: STRING_KEYS.BUYING_POWER,
type: OutputType.Fiat, type: OutputType.Fiat,
value: MustBigNumber(buyingPower?.current).lt(0) ? undefined : buyingPower?.current, // show '-' when buying power is negative value: buyingPower?.current,
}, },
].filter(isTruthy); ].filter(isTruthy);
+106 -131
View File
@@ -1,12 +1,12 @@
import { useCallback, useMemo } from 'react'; import { useCallback, useEffect, useMemo, useState } from 'react';
import { Nullable } from '@dydxprotocol/v4-abacus'; import { Nullable } from '@dydxprotocol/v4-abacus';
import styled, { AnyStyledComponent } from 'styled-components'; import styled, { AnyStyledComponent } from 'styled-components';
import { shallowEqual, useSelector } from 'react-redux'; import { shallowEqual, useSelector } from 'react-redux';
import { FeeTier } from '@/constants/abacus'; import { FeeTier } from '@/constants/abacus';
import { FEE_DECIMALS } from '@/constants/numbers'; import { FEE_DECIMALS, QUANTUM_MULTIPLIER } from '@/constants/numbers';
import { STRING_KEYS } from '@/constants/localization'; import { STRING_KEYS } from '@/constants/localization';
import { useBreakpoints, useStringGetter } from '@/hooks'; import { useAccounts, useBreakpoints, useStringGetter } from '@/hooks';
import { breakpoints } from '@/styles'; import { breakpoints } from '@/styles';
import { layoutMixins } from '@/styles/layoutMixins'; import { layoutMixins } from '@/styles/layoutMixins';
import { tableMixins } from '@/styles/tableMixins'; import { tableMixins } from '@/styles/tableMixins';
@@ -29,8 +29,9 @@ const EQUALITY_SYMBOL_MAP = {
}; };
export const Fees = () => { export const Fees = () => {
const { dydxAddress } = useAccounts();
const stringGetter = useStringGetter(); const stringGetter = useStringGetter();
const { isTablet, isNotTablet } = useBreakpoints(); const { isNotTablet } = useBreakpoints();
const userFeeTier = useSelector(getUserFeeTier, shallowEqual); const userFeeTier = useSelector(getUserFeeTier, shallowEqual);
const userStats = useSelector(getUserStats, shallowEqual); const userStats = useSelector(getUserStats, shallowEqual);
const feeTiers = useSelector(getFeeTiers, shallowEqual); const feeTiers = useSelector(getFeeTiers, shallowEqual);
@@ -55,28 +56,28 @@ export const Fees = () => {
<Styled.AdditionalConditions> <Styled.AdditionalConditions>
{!isAdditional && !totalShare && !makerShare && <Output type={OutputType.Text} />} {!isAdditional && !totalShare && !makerShare && <Output type={OutputType.Text} />}
{!!totalShare && ( {!!totalShare && (
<Styled.AdditionalConditionsText> <Styled.TextRow>
{isAdditional && stringGetter({ key: STRING_KEYS.AND })}{' '} {isAdditional && <span>{stringGetter({ key: STRING_KEYS.AND })}</span>}
{stringGetter({ key: STRING_KEYS.EXCHANGE_MARKET_SHARE })}{' '} <span>{stringGetter({ key: STRING_KEYS.EXCHANGE_MARKET_SHARE })}</span>
<Styled.Highlighted>{'>'}</Styled.Highlighted>{' '} <Styled.Highlighted>{'>'}</Styled.Highlighted>
<Styled.HighlightOutput <Styled.HighlightOutput
type={OutputType.Percent} type={OutputType.Percent}
value={totalShare} value={totalShare}
fractionDigits={0} fractionDigits={0}
/> />
</Styled.AdditionalConditionsText> </Styled.TextRow>
)} )}
{!!makerShare && ( {!!makerShare && (
<Styled.AdditionalConditionsText> <Styled.TextRow>
{isAdditional && stringGetter({ key: STRING_KEYS.AND })}{' '} {isAdditional && <span>{stringGetter({ key: STRING_KEYS.AND })}</span>}
{stringGetter({ key: STRING_KEYS.MAKER_MARKET_SHARE })}{' '} <span>{stringGetter({ key: STRING_KEYS.MAKER_MARKET_SHARE })}</span>
<Styled.Highlighted>{'>'}</Styled.Highlighted>{' '} <Styled.Highlighted>{'>'}</Styled.Highlighted>
<Styled.HighlightOutput <Styled.HighlightOutput
type={OutputType.Percent} type={OutputType.Percent}
value={makerShare} value={makerShare}
fractionDigits={0} fractionDigits={0}
/> />
</Styled.AdditionalConditionsText> </Styled.TextRow>
)} )}
</Styled.AdditionalConditions> </Styled.AdditionalConditions>
), ),
@@ -102,90 +103,91 @@ export const Fees = () => {
}, },
]} ]}
/> />
<div>
<Styled.FeeTable <Styled.FeeTable
label="Fee Tiers" label="Fee Tiers"
data={feeTiers || []} data={feeTiers || []}
getRowKey={(row: FeeTier) => row.tier} getRowKey={(row: FeeTier) => row.tier}
getRowAttributes={(row: FeeTier) => ({ getRowAttributes={(row: FeeTier) => ({
'data-yours': row.tier === userFeeTier, 'data-yours': row.tier === userFeeTier,
})} })}
columns={( columns={(
[ [
{ {
columnKey: 'tier', columnKey: 'tier',
getCellValue: (row) => row.tier, getCellValue: (row) => row.tier,
label: stringGetter({ key: STRING_KEYS.TIER }), label: stringGetter({ key: STRING_KEYS.TIER }),
allowsSorting: false, allowsSorting: false,
renderCell: ({ tier }) => ( renderCell: ({ tier }) => (
<Styled.Tier> <Styled.Tier>
<Styled.Output type={OutputType.Text} value={tier} /> <Styled.Output type={OutputType.Text} value={tier} />
{tier === userFeeTier && ( {tier === userFeeTier && (
<Styled.YouTag size={TagSize.Medium}> <Styled.YouTag size={TagSize.Medium}>
{stringGetter({ key: STRING_KEYS.YOU })} {stringGetter({ key: STRING_KEYS.YOU })}
</Styled.YouTag> </Styled.YouTag>
)} )}
</Styled.Tier> </Styled.Tier>
), ),
}, },
{ {
columnKey: 'volume', columnKey: 'volume',
getCellValue: (row) => row.volume, getCellValue: (row) => row.volume,
label: stringGetter({ key: STRING_KEYS.VOLUME_30D }), label: stringGetter({ key: STRING_KEYS.VOLUME_30D }),
allowsSorting: false, allowsSorting: false,
renderCell: ({ symbol, volume, makerShare, totalShare }) => ( renderCell: ({ symbol, volume, makerShare, totalShare }) => (
<> <>
<span>{`${ <span>{`${
symbol in EQUALITY_SYMBOL_MAP symbol in EQUALITY_SYMBOL_MAP
? EQUALITY_SYMBOL_MAP[symbol as keyof typeof EQUALITY_SYMBOL_MAP] ? EQUALITY_SYMBOL_MAP[symbol as keyof typeof EQUALITY_SYMBOL_MAP]
: symbol : symbol
} `}</span> } `}</span>
<Styled.HighlightOutput type={OutputType.CompactFiat} value={volume} /> <Styled.HighlightOutput type={OutputType.CompactFiat} value={volume} />
{isTablet && {!isNotTablet &&
AdditionalConditions({ totalShare, makerShare, isAdditional: true })} AdditionalConditions({ totalShare, makerShare, isAdditional: true })}
</> </>
), ),
}, },
isNotTablet && { isNotTablet && {
columnKey: 'condition', columnKey: 'condition',
getCellValue: (row) => row.volume, getCellValue: (row) => row.volume,
label: stringGetter({ key: STRING_KEYS.ADDITIONAL_CONDITION }), label: stringGetter({ key: STRING_KEYS.ADDITIONAL_CONDITION }),
allowsSorting: false, allowsSorting: false,
renderCell: ({ totalShare, makerShare }) => renderCell: ({ totalShare, makerShare }) =>
AdditionalConditions({ totalShare, makerShare }), AdditionalConditions({ totalShare, makerShare }),
}, },
{ {
columnKey: 'maker', columnKey: 'maker',
getCellValue: (row) => row.maker, getCellValue: (row) => row.maker,
label: stringGetter({ key: STRING_KEYS.MAKER }), label: stringGetter({ key: STRING_KEYS.MAKER }),
allowsSorting: false, allowsSorting: false,
renderCell: ({ maker }) => ( renderCell: ({ maker }) => (
<Styled.HighlightOutput <Styled.HighlightOutput
type={OutputType.SmallPercent} type={OutputType.SmallPercent}
value={maker} value={maker}
fractionDigits={FEE_DECIMALS} fractionDigits={FEE_DECIMALS}
/> />
), ),
}, },
{ {
columnKey: 'taker', columnKey: 'taker',
getCellValue: (row) => row.taker, getCellValue: (row) => row.taker,
label: stringGetter({ key: STRING_KEYS.TAKER }), label: stringGetter({ key: STRING_KEYS.TAKER }),
allowsSorting: false, allowsSorting: false,
renderCell: ({ taker }) => ( renderCell: ({ taker }) => (
<Styled.HighlightOutput <Styled.HighlightOutput
type={OutputType.SmallPercent} type={OutputType.SmallPercent}
value={taker} value={taker}
fractionDigits={FEE_DECIMALS} fractionDigits={FEE_DECIMALS}
/> />
), ),
}, },
] as ColumnDef<FeeTier>[] ] as ColumnDef<FeeTier>[]
).filter(isTruthy)} ).filter(isTruthy)}
selectionBehavior="replace" selectionBehavior="replace"
withOuterBorder={isNotTablet} withOuterBorder={isNotTablet}
withInnerBorders withInnerBorders
/> />
</div>
</Styled.ContentWrapper> </Styled.ContentWrapper>
</AttachedExpandingSection> </AttachedExpandingSection>
); );
@@ -196,43 +198,21 @@ const Styled: Record<string, AnyStyledComponent> = {};
Styled.ContentWrapper = styled.div` Styled.ContentWrapper = styled.div`
${layoutMixins.flexColumn} ${layoutMixins.flexColumn}
gap: 1.5rem; gap: 1.5rem;
max-width: 100vw;
`; `;
Styled.AdditionalConditions = styled.div` Styled.AdditionalConditions = styled.div`
${tableMixins.cellContentColumn} ${tableMixins.cellContentColumn}
justify-content: end;
color: var(--color-text-0); color: var(--color-text-0);
font: var(--font-small-book);
> :nth-child(2) { > :nth-child(2) {
font: var(--font-small-book); font: var(--font-base-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)` Styled.FeesDetails = styled(Details)`
gap: 1rem; gap: 1rem;
@media ${breakpoints.notTablet} {
margin: 0 1.25rem;
}
@media ${breakpoints.tablet} { @media ${breakpoints.tablet} {
padding: 1rem 1rem 0 1rem; padding: 1rem 1rem 0 1rem;
--details-grid-numColumns: 1; --details-grid-numColumns: 1;
@@ -257,7 +237,11 @@ Styled.FeesDetails = styled(Details)`
} }
output { output {
font: var(--font-base-book); font: var(--font-medium-book);
@media ${breakpoints.tablet} {
font: var(--font-base-book);
}
} }
`; `;
@@ -287,11 +271,6 @@ Styled.FeeTable = styled(Table)`
font: var(--font-base-book); font: var(--font-base-book);
@media ${breakpoints.mobile} {
--tableCell-padding: 1rem 1.25rem;
font: var(--font-small-book);
}
tbody tr { tbody tr {
&[data-yours='true'] { &[data-yours='true'] {
background-color: var(--color-layer-3); background-color: var(--color-layer-3);
@@ -304,10 +283,6 @@ Styled.FeeTable = styled(Table)`
@media ${breakpoints.notTablet} { @media ${breakpoints.notTablet} {
--tableHeader-backgroundColor: var(--color-layer-1); --tableHeader-backgroundColor: var(--color-layer-1);
thead tr {
--border-width: 0;
}
} }
`; `;
+4 -9
View File
@@ -32,11 +32,11 @@ export const DYDXBalancePanel = () => {
const { chainTokenLabel } = useTokenConfigs(); const { chainTokenLabel } = useTokenConfigs();
return ( return (
<Styled.Panel <Panel
slotHeader={ slotHeader={
<Styled.Header> <Styled.Header>
<Styled.Title> <Styled.Title>
<AssetIcon symbol={chainTokenLabel} /> {/* <AssetIcon symbol="DYDX" /> */}
{chainTokenLabel} {chainTokenLabel}
</Styled.Title> </Styled.Title>
<Styled.ReceiveAndTransferButtons> <Styled.ReceiveAndTransferButtons>
@@ -117,19 +117,14 @@ export const DYDXBalancePanel = () => {
]} ]}
/> />
</Styled.Content> </Styled.Content>
</Styled.Panel> </Panel>
); );
}; };
const Styled: Record<string, AnyStyledComponent> = {}; const Styled: Record<string, AnyStyledComponent> = {};
Styled.Panel = styled(Panel)`
--panel-paddingX: 1.5rem;
`;
Styled.Header = styled.div` Styled.Header = styled.div`
${layoutMixins.spacedRow} ${layoutMixins.spacedRow}
gap: 1rem;
padding: 1rem 1.5rem 0; padding: 1rem 1.5rem 0;
`; `;
@@ -182,7 +177,7 @@ Styled.WalletAndStakedBalance = styled(Details)`
--details-item-backgroundColor: var(--color-layer-6); --details-item-backgroundColor: var(--color-layer-6);
grid-template-columns: 1fr 1fr; grid-template-columns: 1fr 1fr;
gap: 1rem; gap: 0.5rem;
> div { > div {
gap: 1rem; gap: 1rem;
+40 -42
View File
@@ -71,7 +71,7 @@ export const MigratePanel = () => {
</Styled.Description> </Styled.Description>
</Styled.MigratePanel> </Styled.MigratePanel>
) : ( ) : (
<Styled.MigratePanel <Styled.MobileMigratePanel
slotHeader={ slotHeader={
<Styled.MobileMigrateHeader> <Styled.MobileMigrateHeader>
<h3> <h3>
@@ -88,52 +88,49 @@ export const MigratePanel = () => {
</Styled.MobileMigrateHeader> </Styled.MobileMigrateHeader>
} }
> >
<Styled.Column> <Styled.WithReceipt
<Styled.WithReceipt slotReceipt={
slotReceipt={ <Styled.Details
<Styled.Details items={[
items={[ {
{ key: 'available-to-migrate',
key: 'available-to-migrate', label: (
label: ( <Styled.InlineRow>
<Styled.InlineRow> {stringGetter({ key: STRING_KEYS.AVAILABLE_TO_MIGRATE })}
{stringGetter({ key: STRING_KEYS.AVAILABLE_TO_MIGRATE })} <Tag>DYDX</Tag>
<Tag>DYDX</Tag> </Styled.InlineRow>
</Styled.InlineRow> ),
), value: <Output type={OutputType.Asset} value={tokenBalance} />,
value: <Output type={OutputType.Asset} value={tokenBalance} />, },
}, ]}
]} />
/> }
} >
> {import.meta.env.VITE_TOKEN_MIGRATION_URI && (
{import.meta.env.VITE_TOKEN_MIGRATION_URI && ( <Button
<Button action={tokenBalance ? ButtonAction.Primary : ButtonAction.Base}
action={tokenBalance ? ButtonAction.Primary : ButtonAction.Base} size={ButtonSize.Medium}
size={ButtonSize.Medium} slotRight={<Icon iconName={IconName.LinkOut} />}
slotRight={<Icon iconName={IconName.LinkOut} />} href={import.meta.env.VITE_TOKEN_MIGRATION_URI}
href={import.meta.env.VITE_TOKEN_MIGRATION_URI} >
> {stringGetter({ key: STRING_KEYS.MIGRATE_NOW })}
{stringGetter({ key: STRING_KEYS.MIGRATE_NOW })} </Button>
</Button> )}
)} </Styled.WithReceipt>
</Styled.WithReceipt> <Styled.InlineRow>
<Styled.InlineRow> {stringGetter({ key: STRING_KEYS.WANT_TO_LEARN })}
{stringGetter({ key: STRING_KEYS.WANT_TO_LEARN })} <Link href={TOKEN_MIGRATION_LEARN_MORE_LINK} withIcon>
<Link href={TOKEN_MIGRATION_LEARN_MORE_LINK} withIcon> {stringGetter({ key: STRING_KEYS.CLICK_HERE })}
{stringGetter({ key: STRING_KEYS.CLICK_HERE })} </Link>
</Link> </Styled.InlineRow>
</Styled.InlineRow> </Styled.MobileMigratePanel>
</Styled.Column>
</Styled.MigratePanel>
); );
}; };
const Styled: Record<string, AnyStyledComponent> = {}; const Styled: Record<string, AnyStyledComponent> = {};
Styled.MigratePanel = styled(Panel)` Styled.MigratePanel = styled(Panel)`
--panel-paddingX: 1.5rem; padding: 1rem 1.5rem;
width: 100%;
`; `;
Styled.Title = styled.h3` Styled.Title = styled.h3`
@@ -166,9 +163,10 @@ Styled.Description = styled.div`
--link-color: var(--color-text-1); --link-color: var(--color-text-1);
`; `;
Styled.Column = styled.div` Styled.MobileMigratePanel = styled(Panel)`
${layoutMixins.flexColumn} ${layoutMixins.flexColumn}
gap: 1rem; gap: 1rem;
align-items: center; align-items: center;
`; `;
+27 -22
View File
@@ -40,7 +40,11 @@ export const RewardsPage = () => {
<Styled.Page> <Styled.Page>
{import.meta.env.VITE_V3_TOKEN_ADDRESS && <MigratePanel />} {import.meta.env.VITE_V3_TOKEN_ADDRESS && <MigratePanel />}
<Styled.PanelRow> <Styled.PanelRow>
{isTablet && <DYDXBalancePanel />} {isTablet && (
<Styled.BalancePanelContainer>
<DYDXBalancePanel />
</Styled.BalancePanelContainer>
)}
<Styled.Panel <Styled.Panel
slotHeader={<Styled.Title>{stringGetter({ key: STRING_KEYS.GOVERNANCE })}</Styled.Title>} slotHeader={<Styled.Title>{stringGetter({ key: STRING_KEYS.GOVERNANCE })}</Styled.Title>}
@@ -68,7 +72,11 @@ export const RewardsPage = () => {
</Styled.Description> </Styled.Description>
</Styled.Panel> </Styled.Panel>
{isNotTablet && <DYDXBalancePanel />} {isNotTablet && (
<Styled.BalancePanelContainer>
<DYDXBalancePanel />
</Styled.BalancePanelContainer>
)}
</Styled.PanelRow> </Styled.PanelRow>
</Styled.Page> </Styled.Page>
); );
@@ -79,26 +87,10 @@ const Styled: Record<string, AnyStyledComponent> = {};
Styled.Page = styled.div` Styled.Page = styled.div`
${layoutMixins.contentContainerPage} ${layoutMixins.contentContainerPage}
gap: 1.5rem; 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: 1.25rem;
> * {
max-width: calc(100vw - 2.5rem);
width: 100%;
}
}
`; `;
Styled.Panel = styled(Panel)` Styled.Panel = styled(Panel)`
--panel-paddingX: 1.5rem; padding: 1rem 1.5rem;
`; `;
Styled.Title = styled.h3` Styled.Title = styled.h3`
@@ -113,14 +105,27 @@ Styled.Description = styled.div`
`; `;
Styled.PanelRow = styled.div` Styled.PanelRow = styled.div`
${layoutMixins.gridEqualColumns} ${layoutMixins.spacedRow}
gap: 1.5rem; gap: 1.5rem;
max-width: min(100vw, var(--content-max-width));
align-items: flex-start; align-items: flex-start;
> section {
cursor: pointer;
}
@media ${breakpoints.tablet} { @media ${breakpoints.tablet} {
grid-auto-flow: row; grid-auto-flow: row;
grid-template-columns: 1fr; grid-template-columns: 1fr;
max-width: auto;
}
`;
Styled.BalancePanelContainer = styled.div`
width: 21.25rem;
@media ${breakpoints.tablet} {
width: auto;
} }
`; `;
@@ -130,5 +135,5 @@ Styled.IconButton = styled(IconButton)`
`; `;
Styled.Arrow = styled.div` Styled.Arrow = styled.div`
padding: 1rem; padding: 1rem 1.5rem;
`; `;
+2 -2
View File
@@ -227,8 +227,8 @@ export const HorizontalPanel = ({ isOpen = true, setIsOpen }: ElementProps) => {
}, },
]} ]}
value={view} value={view}
onValueChange={setView} onValueChange={(newView: string) => {
onInteraction={() => { setView((newView || view) as PanelView);
setIsOpen?.(true); setIsOpen?.(true);
}} }}
/> />
+1 -2
View File
@@ -2,7 +2,6 @@ import type { PayloadAction } from '@reduxjs/toolkit';
import { AbacusApiStatus } from '@/constants/abacus'; import { AbacusApiStatus } from '@/constants/abacus';
import { DialogTypes } from '@/constants/dialogs'; import { DialogTypes } from '@/constants/dialogs';
import { isDev } from '@/constants/networks';
import { setApiState, setSelectedNetwork } from '@/state/app'; import { setApiState, setSelectedNetwork } from '@/state/app';
import { resetPerpetualsState } from '@/state/perpetuals'; import { resetPerpetualsState } from '@/state/perpetuals';
@@ -31,7 +30,7 @@ export default (store: any) => (next: any) => async (action: PayloadAction<any>)
store.dispatch( store.dispatch(
openDialog({ openDialog({
type: DialogTypes.ExchangeOffline, type: DialogTypes.ExchangeOffline,
dialogProps: { preventClose: !isDev }, dialogProps: { preventClose: import.meta.env.MODE === 'production' },
}) })
); );
} }
-9
View File
@@ -48,15 +48,6 @@ export const getTradeInputErrors = (state: RootState) => {
return currentInput === 'trade' ? getInputErrors(state) : []; 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 * @param state
* @returns input errors for Transfer * @returns input errors for Transfer
@@ -151,10 +151,7 @@ export const AccountInfoConnectedState = () => {
), ),
label: stringGetter({ key: STRING_KEYS.BUYING_POWER }), label: stringGetter({ key: STRING_KEYS.BUYING_POWER }),
type: OutputType.Fiat, type: OutputType.Fiat,
value: value: buyingPower,
MustBigNumber(buyingPower?.current).lt(0) && buyingPower?.postOrder === null
? undefined
: buyingPower,
}, },
].map( ].map(
({ ({
+1 -1
View File
@@ -29,7 +29,7 @@ export const MarketFilter = ({
<> <>
{!isSearch && ( {!isSearch && (
<ToggleGroup <ToggleGroup
items={Object.values(filters).map((value) => ({ items={Object.entries(filters).map(([key, value]) => ({
label: stringGetter({ key: MARKET_FILTER_LABELS[value] }), label: stringGetter({ key: MARKET_FILTER_LABELS[value] }),
value, value,
}))} }))}
+2
View File
@@ -198,6 +198,8 @@ Styled.Details = styled(Details)`
@media ${breakpoints.tablet} { @media ${breakpoints.tablet} {
${layoutMixins.withOuterAndInnerBorders} ${layoutMixins.withOuterAndInnerBorders}
display: grid;
grid-template-columns: repeat(auto-fit, minmax(9rem, 1fr));
font: var(--font-small-book); font: var(--font-small-book);
> * { > * {
+3 -12
View File
@@ -34,7 +34,7 @@ export const TransferStatusToast = ({
}: ElementProps) => { }: ElementProps) => {
const stringGetter = useStringGetter(); const stringGetter = useStringGetter();
const [open, setOpen] = useState<boolean>(false); const [open, setOpen] = useState<boolean>(false);
const [secondsLeft, setSecondsLeft] = useState<number>(0); const [secondsLeft, setSecondsLeft] = useState<number | undefined>();
// @ts-ignore status.errors is not in the type definition but can be returned // @ts-ignore status.errors is not in the type definition but can be returned
const error = status?.errors?.length ? status?.errors[0] : status?.error; const error = status?.errors?.length ? status?.errors[0] : status?.error;
@@ -49,23 +49,14 @@ export const TransferStatusToast = ({
if (!status) return <LoadingDots size={3} />; 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 = const statusString =
type === 'deposit' type === 'deposit'
? status?.squidTransactionStatus === 'success' ? status?.squidTransactionStatus === 'success'
? STRING_KEYS.DEPOSIT_COMPLETE ? STRING_KEYS.DEPOSIT_COMPLETE
: inProgressStatusString : STRING_KEYS.DEPOSIT_STATUS
: status?.squidTransactionStatus === 'success' : status?.squidTransactionStatus === 'success'
? STRING_KEYS.WITHDRAW_COMPLETE ? STRING_KEYS.WITHDRAW_COMPLETE
: inProgressStatusString; : STRING_KEYS.WITHDRAW_STATUS;
return ( return (
<Styled.Root open={open} onOpenChange={setOpen}> <Styled.Root open={open} onOpenChange={setOpen}>
+4 -13
View File
@@ -2,7 +2,7 @@ import { useMemo } from 'react';
import styled, { css, keyframes, type AnyStyledComponent } from 'styled-components'; import styled, { css, keyframes, type AnyStyledComponent } from 'styled-components';
import { StatusResponse } from '@0xsquid/sdk'; import { StatusResponse } from '@0xsquid/sdk';
import { useStringGetter, useSelectedNetwork, useURLConfigs } from '@/hooks'; import { useStringGetter } from '@/hooks';
import { Link } from '@/components/Link'; import { Link } from '@/components/Link';
import { Icon, IconName } from '@/components/Icon'; import { Icon, IconName } from '@/components/Icon';
@@ -11,7 +11,6 @@ import { LoadingSpinner } from '@/components/Loading/LoadingSpinner';
import { layoutMixins } from '@/styles/layoutMixins'; import { layoutMixins } from '@/styles/layoutMixins';
import { STRING_KEYS } from '@/constants/localization'; import { STRING_KEYS } from '@/constants/localization';
import { ENVIRONMENT_CONFIG_MAP } from '@/constants/networks';
type ElementProps = { type ElementProps = {
status?: StatusResponse; status?: StatusResponse;
@@ -27,17 +26,12 @@ enum TransferStatusStep {
export const TransferStatusSteps = ({ status, type }: ElementProps) => { export const TransferStatusSteps = ({ status, type }: ElementProps) => {
const stringGetter = useStringGetter(); const stringGetter = useStringGetter();
const { selectedNetwork } = useSelectedNetwork();
const { mintscan: mintscanTxUrl } = useURLConfigs();
const dydxChainId = ENVIRONMENT_CONFIG_MAP[selectedNetwork].dydxChainId;
const { currentStep, steps } = useMemo(() => { const { currentStep, steps } = useMemo(() => {
const routeStatus = status?.routeStatus; const routeStatus = status?.routeStatus;
const fromChain = status?.fromChain?.chainData?.chainId; const fromChain = status?.fromChain?.chainData?.chainId;
const toChain = status?.toChain?.chainData?.chainId; const toChain = status?.toChain?.chainData?.chainId;
const currentStatus = routeStatus?.[routeStatus?.length - 1];
const steps = [ const steps = [
{ {
label: stringGetter({ label: stringGetter({
@@ -60,15 +54,12 @@ export const TransferStatusSteps = ({ status, type }: ElementProps) => {
}, },
}), }),
step: TransferStatusStep.ToChain, step: TransferStatusStep.ToChain,
link: link: status?.toChain?.transactionUrl,
type === 'withdrawal'
? status?.toChain?.transactionUrl
: currentStatus?.chainId === dydxChainId && currentStatus?.txHash
? `${mintscanTxUrl?.replace('{tx_hash}', currentStatus.txHash)}`
: undefined,
}, },
]; ];
const currentStatus = routeStatus?.[routeStatus?.length - 1];
let currentStep = TransferStatusStep.Bridge; let currentStep = TransferStatusStep.Bridge;
if (!routeStatus?.length) { if (!routeStatus?.length) {
+3 -1
View File
@@ -246,7 +246,9 @@ export const FundingChart = ({ selectedLocale }: ElementProps) => {
}[rate] || '', }[rate] || '',
}))} }))}
value={fundingRateView} value={fundingRateView}
onValueChange={setFundingRateView} onValueChange={(newRate: FundingRateResolution) => {
if (newRate) setFundingRateView(newRate);
}}
size={ButtonSize.XSmall} size={ButtonSize.XSmall}
/> />
</Styled.FundingRateToggle> </Styled.FundingRateToggle>
+6 -13
View File
@@ -1,7 +1,6 @@
import { useState } from 'react'; import { useState } from 'react';
import styled, { type AnyStyledComponent } from 'styled-components'; import styled, { type AnyStyledComponent } from 'styled-components';
import { isMainnet } from '@/constants/networks';
import { STRING_KEYS } from '@/constants/localization'; import { STRING_KEYS } from '@/constants/localization';
import { useBreakpoints, useStringGetter } from '@/hooks'; import { useBreakpoints, useStringGetter } from '@/hooks';
@@ -17,7 +16,7 @@ type ElementProps = {
}; };
export const DepositDialog = ({ setIsOpen }: ElementProps) => { export const DepositDialog = ({ setIsOpen }: ElementProps) => {
const [showFaucet, setShowFaucet] = useState(!isMainnet); const [showTestDeposit, setShowTestDeposit] = useState(true);
const stringGetter = useStringGetter(); const stringGetter = useStringGetter();
const { isMobile } = useBreakpoints(); const { isMobile } = useBreakpoints();
@@ -28,20 +27,14 @@ export const DepositDialog = ({ setIsOpen }: ElementProps) => {
isOpen isOpen
setIsOpen={setIsOpen} setIsOpen={setIsOpen}
title={stringGetter({ key: STRING_KEYS.DEPOSIT })} title={stringGetter({ key: STRING_KEYS.DEPOSIT })}
description={showFaucet && 'Test funds will be sent directly to your dYdX account.'} description={showTestDeposit && 'Test funds will be sent directly to your dYdX account.'}
placement={isMobile ? DialogPlacement.FullScreen : DialogPlacement.Default} placement={isMobile ? DialogPlacement.FullScreen : DialogPlacement.Default}
> >
<Styled.Content> <Styled.Content>
{isMainnet || !showFaucet ? ( {showTestDeposit ? <TestnetDepositForm onDeposit={closeDialog} /> : <DepositForm />}
<DepositForm /> <Styled.TextToggle onClick={() => setShowTestDeposit(!showTestDeposit)}>
) : ( {showTestDeposit ? 'Show deposit form (Under Construction)' : 'Show test faucet'}
<TestnetDepositForm onDeposit={closeDialog} /> </Styled.TextToggle>
)}
{!isMainnet && (
<Styled.TextToggle onClick={() => setShowFaucet(!showFaucet)}>
{showFaucet ? 'Show deposit form' : 'Show test faucet'}
</Styled.TextToggle>
)}
</Styled.Content> </Styled.Content>
</Dialog> </Dialog>
); );
+1 -2
View File
@@ -5,7 +5,6 @@ import { shallowEqual, useDispatch, useSelector } from 'react-redux';
import { AbacusApiStatus } from '@/constants/abacus'; import { AbacusApiStatus } from '@/constants/abacus';
import { DialogTypes } from '@/constants/dialogs'; import { DialogTypes } from '@/constants/dialogs';
import { STRING_KEYS } from '@/constants/localization'; import { STRING_KEYS } from '@/constants/localization';
import { isDev } from '@/constants/networks';
import { useApiState, useStringGetter } from '@/hooks'; import { useApiState, useStringGetter } from '@/hooks';
import { layoutMixins } from '@/styles/layoutMixins'; import { layoutMixins } from '@/styles/layoutMixins';
@@ -46,7 +45,7 @@ export const ExchangeOfflineDialog = ({ preventClose, setIsOpen }: ElementProps)
> >
<Styled.Content> <Styled.Content>
<p>{statusErrorMessage}</p> <p>{statusErrorMessage}</p>
{isDev && <NetworkSelectMenu />} {import.meta.env.MODE !== 'production' && <NetworkSelectMenu />}
</Styled.Content> </Styled.Content>
</Dialog> </Dialog>
); );
@@ -1,13 +1,11 @@
import styled, { AnyStyledComponent } from 'styled-components'; import styled, { AnyStyledComponent } from 'styled-components';
import { STRING_KEYS } from '@/constants/localization'; import { STRING_KEYS } from '@/constants/localization';
import { isDev } from '@/constants/networks';
import { useStringGetter } from '@/hooks'; import { useStringGetter } from '@/hooks';
import { layoutMixins } from '@/styles/layoutMixins'; import { layoutMixins } from '@/styles/layoutMixins';
import { Dialog } from '@/components/Dialog'; import { Dialog } from '@/components/Dialog';
import { Icon, IconName } from '@/components/Icon'; import { Icon, IconName } from '@/components/Icon';
import { NetworkSelectMenu } from '@/views/menus/NetworkSelectMenu';
type ElementProps = { type ElementProps = {
preventClose?: boolean; preventClose?: boolean;
@@ -27,7 +25,6 @@ export const RestrictedGeoDialog = ({ preventClose, setIsOpen }: ElementProps) =
> >
<Styled.Content> <Styled.Content>
{stringGetter({ key: STRING_KEYS.REGION_NOT_PERMITTED_SUBTITLE })} {stringGetter({ key: STRING_KEYS.REGION_NOT_PERMITTED_SUBTITLE })}
{isDev && <NetworkSelectMenu />}
</Styled.Content> </Styled.Content>
</Dialog> </Dialog>
); );
@@ -1,13 +1,11 @@
import styled, { AnyStyledComponent } from 'styled-components'; import styled, { AnyStyledComponent } from 'styled-components';
import { STRING_KEYS } from '@/constants/localization'; import { STRING_KEYS } from '@/constants/localization';
import { isDev } from '@/constants/networks';
import { useStringGetter } from '@/hooks'; import { useStringGetter } from '@/hooks';
import { layoutMixins } from '@/styles/layoutMixins'; import { layoutMixins } from '@/styles/layoutMixins';
import { Dialog } from '@/components/Dialog'; import { Dialog } from '@/components/Dialog';
import { Icon, IconName } from '@/components/Icon'; import { Icon, IconName } from '@/components/Icon';
import { NetworkSelectMenu } from '@/views/menus/NetworkSelectMenu';
type ElementProps = { type ElementProps = {
preventClose?: boolean; preventClose?: boolean;
@@ -27,7 +25,6 @@ export const RestrictedWalletDialog = ({ preventClose, setIsOpen }: ElementProps
> >
<Styled.Content> <Styled.Content>
{stringGetter({ key: STRING_KEYS.REGION_NOT_PERMITTED_SUBTITLE })} {stringGetter({ key: STRING_KEYS.REGION_NOT_PERMITTED_SUBTITLE })}
{isDev && <NetworkSelectMenu />}
</Styled.Content> </Styled.Content>
</Dialog> </Dialog>
); );
+3 -1
View File
@@ -73,7 +73,9 @@ export const TradeDialog = ({ isOpen, setIsOpen, slotTrigger }: ElementProps) =>
<Styled.ToggleGroup <Styled.ToggleGroup
items={allTradeTypeItems} items={allTradeTypeItems}
value={selectedTradeType} value={selectedTradeType}
onValueChange={onTradeTypeChange} onValueChange={(tradeType: TradeTypes) =>
onTradeTypeChange(tradeType || selectedTradeType)
}
/> />
), ),
}, },
@@ -2,21 +2,22 @@ import { type FormEvent, useCallback, useEffect, useMemo, useState } from 'react
import styled, { type AnyStyledComponent } from 'styled-components'; import styled, { type AnyStyledComponent } from 'styled-components';
import { type NumberFormatValues } from 'react-number-format'; import { type NumberFormatValues } from 'react-number-format';
import { shallowEqual, useSelector } from 'react-redux'; import { shallowEqual, useSelector } from 'react-redux';
import { parseUnits } from 'viem'; import { TESTNET_CHAIN_ID } from '@dydxprotocol/v4-client-js';
import { parseUnits } from 'viem'
import erc20 from '@/abi/erc20.json'; import erc20 from '@/abi/erc20.json';
import { TransferInputField, TransferInputTokenResource, TransferType } from '@/constants/abacus'; import { TransferInputField, TransferInputTokenResource, TransferType } from '@/constants/abacus';
import { AlertType } from '@/constants/alerts'; import { AlertType } from '@/constants/alerts';
import { ButtonSize } from '@/constants/buttons'; import { ButtonSize } from '@/constants/buttons';
import { STRING_KEYS } from '@/constants/localization'; import { STRING_KEYS } from '@/constants/localization';
import { ENVIRONMENT_CONFIG_MAP } from '@/constants/networks';
import { NumberSign } from '@/constants/numbers'; import { NumberSign } from '@/constants/numbers';
import type { EvmAddress } from '@/constants/wallets'; import type { EvmAddress } from '@/constants/wallets';
import { useAccounts, useDebounce, useStringGetter, useSelectedNetwork } from '@/hooks'; import { useAccounts, useDebounce, useStringGetter } from '@/hooks';
import { useAccountBalance, CHAIN_DEFAULT_TOKEN_ADDRESS } from '@/hooks/useAccountBalance'; import { useAccountBalance, CHAIN_DEFAULT_TOKEN_ADDRESS } from '@/hooks/useAccountBalance';
import { useLocalNotifications } from '@/hooks/useLocalNotifications'; import { useLocalNotifications } from '@/hooks/useLocalNotifications';
import { NATIVE_TOKEN_ADDRESS, useSquid } from '@/hooks/useSquid'; import { NATIVE_TOKEN_ADDRESS, useSquid } from '@/hooks/useSquid';
import { useWalletConnection } from '@/hooks/useWalletConnection';
import { layoutMixins } from '@/styles/layoutMixins'; import { layoutMixins } from '@/styles/layoutMixins';
import { formMixins } from '@/styles/formMixins'; import { formMixins } from '@/styles/formMixins';
@@ -53,9 +54,9 @@ export const DepositForm = ({ onDeposit, onError }: DepositFormProps) => {
const stringGetter = useStringGetter(); const stringGetter = useStringGetter();
const [error, setError] = useState<Error | null>(null); const [error, setError] = useState<Error | null>(null);
const [isLoading, setIsLoading] = useState(false); const [isLoading, setIsLoading] = useState(false);
const { selectedNetwork } = useSelectedNetwork();
const { evmAddress, signerWagmi, publicClientWagmi } = useAccounts(); const { evmAddress, signerWagmi } = useAccounts();
const { publicClientWagmi } = useWalletConnection();
const { addTransferNotification } = useLocalNotifications(); const { addTransferNotification } = useLocalNotifications();
@@ -65,8 +66,6 @@ export const DepositForm = ({ onDeposit, onError }: DepositFormProps) => {
chain: chainIdStr, chain: chainIdStr,
resources, resources,
summary, summary,
errors: routeErrors,
errorMessage: routeErrorMessage,
} = useSelector(getTransferInputs, shallowEqual) || {}; } = useSelector(getTransferInputs, shallowEqual) || {};
const chainId = chainIdStr ? parseInt(chainIdStr) : undefined; const chainId = chainIdStr ? parseInt(chainIdStr) : undefined;
@@ -99,7 +98,7 @@ export const DepositForm = ({ onDeposit, onError }: DepositFormProps) => {
useEffect(() => { useEffect(() => {
const hasInvalidInput = const hasInvalidInput =
debouncedAmountBN.isNaN() || debouncedAmountBN.lte(0) || debouncedAmountBN.gt(balanceBN); debouncedAmountBN.isNaN() || debouncedAmountBN.lte(0) || debouncedAmountBN.gte(balanceBN);
abacusStateManager.setTransferValue({ abacusStateManager.setTransferValue({
value: hasInvalidInput ? 0 : debouncedAmount, value: hasInvalidInput ? 0 : debouncedAmount,
@@ -173,8 +172,7 @@ export const DepositForm = ({ onDeposit, onError }: DepositFormProps) => {
const validateTokenApproval = useCallback(async () => { const validateTokenApproval = useCallback(async () => {
if (!signerWagmi || !publicClientWagmi) throw new Error('Missing signer'); if (!signerWagmi || !publicClientWagmi) throw new Error('Missing signer');
if (!sourceToken?.address || !sourceToken.decimals) if (!sourceToken?.address || !sourceToken.decimals) throw new Error('Missing source token address');
throw new Error('Missing source token address');
if (!sourceChain?.rpc) throw new Error('Missing source chain rpc'); if (!sourceChain?.rpc) throw new Error('Missing source chain rpc');
if (!requestPayload?.targetAddress) throw new Error('Missing target address'); if (!requestPayload?.targetAddress) throw new Error('Missing target address');
if (!requestPayload?.value) throw new Error('Missing transaction value'); if (!requestPayload?.value) throw new Error('Missing transaction value');
@@ -184,11 +182,11 @@ export const DepositForm = ({ onDeposit, onError }: DepositFormProps) => {
address: sourceToken.address as EvmAddress, address: sourceToken.address as EvmAddress,
abi: erc20, abi: erc20,
functionName: 'allowance', functionName: 'allowance',
args: [evmAddress as EvmAddress, requestPayload.targetAddress as EvmAddress], args: [evmAddress as EvmAddress, requestPayload.targetAddress as EvmAddress]
}); });
const sourceAmountBN = parseUnits(debouncedAmount, sourceToken.decimals); const sourceAmountBN = parseUnits(debouncedAmount, sourceToken.decimals);
if (sourceAmountBN > (allowance as bigint)) { if (sourceAmountBN > (allowance as bigint)) {
const { request } = await publicClientWagmi.simulateContract({ const { request } = await publicClientWagmi.simulateContract({
account: evmAddress, account: evmAddress,
@@ -196,12 +194,12 @@ export const DepositForm = ({ onDeposit, onError }: DepositFormProps) => {
abi: erc20, abi: erc20,
functionName: 'approve', functionName: 'approve',
args: [requestPayload.targetAddress as EvmAddress, sourceAmountBN], args: [requestPayload.targetAddress as EvmAddress, sourceAmountBN],
}); })
const approveTx = await signerWagmi.writeContract(request); const approveTx = await signerWagmi.writeContract(request);
await publicClientWagmi.waitForTransactionReceipt({ await publicClientWagmi.waitForTransactionReceipt({
hash: approveTx, hash: approveTx,
}); })
} }
}, [signerWagmi, sourceToken, sourceChain, requestPayload, publicClientWagmi]); }, [signerWagmi, sourceToken, sourceChain, requestPayload, publicClientWagmi]);
@@ -231,7 +229,8 @@ export const DepositForm = ({ onDeposit, onError }: DepositFormProps) => {
to: requestPayload.targetAddress as EvmAddress, to: requestPayload.targetAddress as EvmAddress,
data: requestPayload.data as EvmAddress, data: requestPayload.data as EvmAddress,
gasLimit: BigInt(requestPayload.gasLimit), 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); const txHash = await signerWagmi.sendTransaction(tx);
@@ -240,7 +239,7 @@ export const DepositForm = ({ onDeposit, onError }: DepositFormProps) => {
if (txHash) { if (txHash) {
addTransferNotification({ addTransferNotification({
txHash: txHash, txHash: txHash,
toChainId: ENVIRONMENT_CONFIG_MAP[selectedNetwork].dydxChainId, toChainId: TESTNET_CHAIN_ID,
fromChainId: chainIdStr || undefined, fromChainId: chainIdStr || undefined,
toAmount: summary?.usdcSize || undefined, toAmount: summary?.usdcSize || undefined,
triggeredAt: Date.now(), triggeredAt: Date.now(),
@@ -289,15 +288,6 @@ export const DepositForm = ({ onDeposit, onError }: DepositFormProps) => {
return parseWalletError({ error, stringGetter }).message; 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 (fromAmount) {
if (!chainId) { if (!chainId) {
return stringGetter({ key: STRING_KEYS.MUST_SPECIFY_CHAIN }); return stringGetter({ key: STRING_KEYS.MUST_SPECIFY_CHAIN });
@@ -311,16 +301,7 @@ export const DepositForm = ({ onDeposit, onError }: DepositFormProps) => {
} }
return undefined; return undefined;
}, [ }, [error, balance, chainId, fromAmount, sourceToken]);
error,
routeErrors,
routeErrorMessage,
balance,
chainId,
fromAmount,
sourceToken,
stringGetter,
]);
const isDisabled = const isDisabled =
Boolean(errorMessage) || Boolean(errorMessage) ||
@@ -1,5 +1,5 @@
import { type Dispatch, type SetStateAction, useState, type ReactNode } from 'react'; 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 { shallowEqual, useSelector } from 'react-redux';
import type { RouteData } from '@0xsquid/sdk'; import type { RouteData } from '@0xsquid/sdk';
@@ -32,8 +32,6 @@ import { WithReceipt } from '@/components/WithReceipt';
import { getSubaccountBuyingPower, getSubaccountEquity } from '@/state/accountSelectors'; import { getSubaccountBuyingPower, getSubaccountEquity } from '@/state/accountSelectors';
import { getTransferInputs } from '@/state/inputsSelectors'; import { getTransferInputs } from '@/state/inputsSelectors';
import { MustBigNumber } from '@/lib/numbers';
import { SlippageEditor } from '../SlippageEditor'; import { SlippageEditor } from '../SlippageEditor';
type ElementProps = { type ElementProps = {
@@ -133,7 +131,7 @@ export const DepositButtonAndReceipt = ({
value: ( value: (
<DiffOutput <DiffOutput
type={OutputType.Fiat} type={OutputType.Fiat}
value={MustBigNumber(buyingPower).lt(0) ? undefined : buyingPower} value={buyingPower}
newValue={newBuyingPower} newValue={newBuyingPower}
sign={NumberSign.Positive} sign={NumberSign.Positive}
withDiff={Boolean(newBuyingPower) && buyingPower !== newBuyingPower} withDiff={Boolean(newBuyingPower) && buyingPower !== newBuyingPower}
@@ -164,7 +162,6 @@ export const DepositButtonAndReceipt = ({
label: <span>{stringGetter({ key: STRING_KEYS.SLIPPAGE })}</span>, label: <span>{stringGetter({ key: STRING_KEYS.SLIPPAGE })}</span>,
value: ( value: (
<SlippageEditor <SlippageEditor
disabled
slippage={slippage} slippage={slippage}
setIsEditing={setIsEditingSlipapge} setIsEditing={setIsEditingSlipapge}
setSlippage={setSlippage} setSlippage={setSlippage}
@@ -24,17 +24,11 @@ type ElementProps = {
slippage: number; slippage: number;
setIsEditing?: Dispatch<SetStateAction<boolean>>; setIsEditing?: Dispatch<SetStateAction<boolean>>;
setSlippage: (slippage: number) => void; setSlippage: (slippage: number) => void;
disabled?: boolean;
}; };
export type SlippageEditorProps = ElementProps; export type SlippageEditorProps = ElementProps;
export const SlippageEditor = ({ export const SlippageEditor = ({ slippage, setIsEditing, setSlippage }: SlippageEditorProps) => {
disabled,
slippage,
setIsEditing,
setSlippage,
}: SlippageEditorProps) => {
const percentSlippage = slippage * 100; const percentSlippage = slippage * 100;
const [slippageInputValue, setSlippageInputValue] = useState(percentSlippage.toString()); const [slippageInputValue, setSlippageInputValue] = useState(percentSlippage.toString());
const [editorState, setEditorState] = useState(EditorState.Viewing); const [editorState, setEditorState] = useState(EditorState.Viewing);
@@ -86,10 +80,6 @@ export const SlippageEditor = ({
} }
}; };
if (disabled) {
return <Output type={OutputType.Percent} value={slippage} />;
}
return ( return (
<Styled.WithConfirmationPopover <Styled.WithConfirmationPopover
open={editorState !== EditorState.Viewing} open={editorState !== EditorState.Viewing}
@@ -3,13 +3,13 @@ import type { ChangeEvent, FormEvent } from 'react';
import styled, { type AnyStyledComponent } from 'styled-components'; import styled, { type AnyStyledComponent } from 'styled-components';
import type { NumberFormatValues } from 'react-number-format'; import type { NumberFormatValues } from 'react-number-format';
import { shallowEqual, useSelector } from 'react-redux'; import { shallowEqual, useSelector } from 'react-redux';
import { TESTNET_CHAIN_ID } from '@dydxprotocol/v4-client-js';
import { isAddress } from 'viem'; import { isAddress } from 'viem';
import { TransferInputField, TransferInputTokenResource, TransferType } from '@/constants/abacus'; import { TransferInputField, TransferInputTokenResource, TransferType } from '@/constants/abacus';
import { AlertType } from '@/constants/alerts'; import { AlertType } from '@/constants/alerts';
import { ButtonSize } from '@/constants/buttons'; import { ButtonSize } from '@/constants/buttons';
import { STRING_KEYS } from '@/constants/localization'; import { STRING_KEYS } from '@/constants/localization';
import { ENVIRONMENT_CONFIG_MAP } from '@/constants/networks';
import { NumberSign } from '@/constants/numbers'; import { NumberSign } from '@/constants/numbers';
import { import {
@@ -17,7 +17,6 @@ import {
useDebounce, useDebounce,
useDydxClient, useDydxClient,
useRestrictions, useRestrictions,
useSelectedNetwork,
useStringGetter, useStringGetter,
useSubaccount, useSubaccount,
} from '@/hooks'; } from '@/hooks';
@@ -47,12 +46,12 @@ import { MustBigNumber } from '@/lib/numbers';
import { TokenSelectMenu } from './TokenSelectMenu'; import { TokenSelectMenu } from './TokenSelectMenu';
import { WithdrawButtonAndReceipt } from './WithdrawForm/WithdrawButtonAndReceipt'; import { WithdrawButtonAndReceipt } from './WithdrawForm/WithdrawButtonAndReceipt';
import { join } from 'path';
export const WithdrawForm = () => { export const WithdrawForm = () => {
const stringGetter = useStringGetter(); const stringGetter = useStringGetter();
const [error, setError] = useState<string>(); const [error, setError] = useState<string>();
const [isLoading, setIsLoading] = useState(false); const [isLoading, setIsLoading] = useState(false);
const { selectedNetwork } = useSelectedNetwork();
const { sendSquidWithdraw } = useSubaccount(); const { sendSquidWithdraw } = useSubaccount();
const { freeCollateral } = useSelector(getSubaccount, shallowEqual) || {}; const { freeCollateral } = useSelector(getSubaccount, shallowEqual) || {};
@@ -68,8 +67,6 @@ export const WithdrawForm = () => {
chain: chainIdStr, chain: chainIdStr,
address: toAddress, address: toAddress,
resources, resources,
errors: routeErrors,
errorMessage: routeErrorMessage,
} = useSelector(getTransferInputs, shallowEqual) || {}; } = useSelector(getTransferInputs, shallowEqual) || {};
const isValidAddress = toAddress && isAddress(toAddress); const isValidAddress = toAddress && isAddress(toAddress);
@@ -167,7 +164,7 @@ export const WithdrawForm = () => {
const hash = `0x${Buffer.from(txHash.hash).toString('hex')}`; const hash = `0x${Buffer.from(txHash.hash).toString('hex')}`;
addTransferNotification({ addTransferNotification({
txHash: hash, txHash: hash,
fromChainId: ENVIRONMENT_CONFIG_MAP[selectedNetwork].dydxChainId, fromChainId: TESTNET_CHAIN_ID,
toChainId: chainIdStr || undefined, toChainId: chainIdStr || undefined,
toAmount: debouncedAmountBN.toNumber(), toAmount: debouncedAmountBN.toNumber(),
triggeredAt: Date.now(), triggeredAt: Date.now(),
@@ -282,15 +279,6 @@ 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 (!toAddress) return stringGetter({ key: STRING_KEYS.WITHDRAW_MUST_SPECIFY_ADDRESS });
if (sanctionedAddresses.has(toAddress)) if (sanctionedAddresses.has(toAddress))
@@ -313,15 +301,12 @@ export const WithdrawForm = () => {
return undefined; return undefined;
}, [ }, [
error, error,
routeErrors,
routeErrorMessage,
freeCollateralBN, freeCollateralBN,
chainIdStr, chainIdStr,
debouncedAmountBN, debouncedAmountBN,
toToken, toToken,
toAddress, toAddress,
sanctionedAddresses, sanctionedAddresses,
stringGetter,
]); ]);
const isDisabled = const isDisabled =
@@ -147,7 +147,6 @@ export const WithdrawButtonAndReceipt = ({
label: <span>{stringGetter({ key: STRING_KEYS.SLIPPAGE })}</span>, label: <span>{stringGetter({ key: STRING_KEYS.SLIPPAGE })}</span>,
value: ( value: (
<SlippageEditor <SlippageEditor
disabled
slippage={slippage} slippage={slippage}
setIsEditing={setIsEditingSlipapge} setIsEditing={setIsEditingSlipapge}
setSlippage={setSlippage} setSlippage={setSlippage}
+8 -32
View File
@@ -4,10 +4,8 @@ import { shallowEqual, useDispatch, useSelector } from 'react-redux';
import { import {
ClosePositionInputField, ClosePositionInputField,
ValidationError,
type HumanReadablePlaceOrderPayload, type HumanReadablePlaceOrderPayload,
type Nullable, type Nullable,
ErrorType,
} from '@/constants/abacus'; } from '@/constants/abacus';
import { AlertType } from '@/constants/alerts'; import { AlertType } from '@/constants/alerts';
import { ButtonAction, ButtonShape, ButtonSize, ButtonType } from '@/constants/buttons'; import { ButtonAction, ButtonShape, ButtonSize, ButtonType } from '@/constants/buttons';
@@ -37,14 +35,13 @@ import { PositionPreview } from '@/views/forms/TradeForm/PositionPreview';
import { getCurrentMarketPositionData } from '@/state/accountSelectors'; import { getCurrentMarketPositionData } from '@/state/accountSelectors';
import { getCurrentMarketAssetData } from '@/state/assetsSelectors'; import { getCurrentMarketAssetData } from '@/state/assetsSelectors';
import { getClosePositionInputErrors, getInputClosePositionData } from '@/state/inputsSelectors'; import { getInputClosePositionData } from '@/state/inputsSelectors';
import { getCurrentMarketConfig, getCurrentMarketId } from '@/state/perpetualsSelectors'; import { getCurrentMarketConfig, getCurrentMarketId } from '@/state/perpetualsSelectors';
import { closeDialog } from '@/state/dialogs'; import { closeDialog } from '@/state/dialogs';
import { getCurrentInput } from '@/state/inputsSelectors'; import { getCurrentInput } from '@/state/inputsSelectors';
import abacusStateManager from '@/lib/abacus'; import abacusStateManager from '@/lib/abacus';
import { MustBigNumber } from '@/lib/numbers'; import { MustBigNumber } from '@/lib/numbers';
import { getTradeInputAlert } from '@/lib/tradeData';
const MAX_KEY = 'MAX'; const MAX_KEY = 'MAX';
@@ -84,38 +81,15 @@ export const ClosePositionForm = ({
const market = useSelector(getCurrentMarketId); const market = useSelector(getCurrentMarketId);
const { id } = useSelector(getCurrentMarketAssetData, shallowEqual) || {}; const { id } = useSelector(getCurrentMarketAssetData, shallowEqual) || {};
const { stepSizeDecimals, tickSizeDecimals } = const { stepSizeDecimals } = useSelector(getCurrentMarketConfig, shallowEqual) || {};
useSelector(getCurrentMarketConfig, shallowEqual) || {};
const { size: sizeData, summary } = useSelector(getInputClosePositionData, shallowEqual) || {}; const { size: sizeData, summary } = useSelector(getInputClosePositionData, shallowEqual) || {};
const { size, percent } = sizeData || {}; const { size, percent } = sizeData || {};
const currentInput = useSelector(getCurrentInput); const currentInput = useSelector(getCurrentInput);
const closePositionInputErrors = useSelector(getClosePositionInputErrors, shallowEqual);
const currentPositionData = useSelector(getCurrentMarketPositionData, shallowEqual); const currentPositionData = useSelector(getCurrentMarketPositionData, shallowEqual);
const { size: currentPositionSize } = currentPositionData || {}; const { size: currentPositionSize } = currentPositionData || {};
const { current: currentSize } = currentPositionSize || {}; const { current: currentSize } = currentPositionSize || {};
const currentSizeBN = MustBigNumber(currentSize).abs(); 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(() => { useEffect(() => {
if (currentStep && currentStep !== MobilePlaceOrderSteps.EditOrder) return; if (currentStep && currentStep !== MobilePlaceOrderSteps.EditOrder) return;
@@ -208,7 +182,9 @@ export const ClosePositionForm = ({
}); });
}; };
const alertMessage = alertContent && <AlertMessage type={alertType}>{alertContent}</AlertMessage>; const alertMessage = closePositionError && (
<AlertMessage type={AlertType.Error}>{closePositionError}</AlertMessage>
);
const inputs = ( const inputs = (
<Styled.InputsColumn> <Styled.InputsColumn>
@@ -233,7 +209,7 @@ export const ClosePositionForm = ({
value: value.toString(), value: value.toString(),
}))} }))}
value={percent?.toString() ?? ''} value={percent?.toString() ?? ''}
onValueChange={onSelectPercentage} onValueChange={(value: any) => onSelectPercentage((value || percent?.toString()) ?? '')}
shape={ButtonShape.Rectangle} shape={ButtonShape.Rectangle}
/> />
@@ -289,8 +265,8 @@ export const ClosePositionForm = ({
<PlaceOrderButtonAndReceipt <PlaceOrderButtonAndReceipt
isLoading={isClosingPosition} isLoading={isClosingPosition}
hasValidationErrors={hasInputErrors} hasValidationErrors={!size}
actionStringKey={inputAlert?.actionStringKey} actionStringKey={!size ? STRING_KEYS.ENTER_AMOUNT : undefined}
summary={summary ?? undefined} summary={summary ?? undefined}
currentStep={currentStep} currentStep={currentStep}
isClosePosition isClosePosition
@@ -153,7 +153,9 @@ export const MarketLeverageInput = ({
value: MustBigNumber(leverageAmount).toFixed(LEVERAGE_DECIMALS), value: MustBigNumber(leverageAmount).toFixed(LEVERAGE_DECIMALS),
}))} }))}
value={MustBigNumber(formattedLeverageValue).abs().toFixed(LEVERAGE_DECIMALS)} // sign agnostic value={MustBigNumber(formattedLeverageValue).abs().toFixed(LEVERAGE_DECIMALS)} // sign agnostic
onValueChange={updateLeverage} onValueChange={(option?: number) =>
updateLeverage(option === undefined ? formattedLeverageValue : option)
}
shape={ButtonShape.Rectangle} shape={ButtonShape.Rectangle}
/> />
</> </>
+49 -57
View File
@@ -61,53 +61,38 @@ export const TransferForm = ({
const stringGetter = useStringGetter(); const stringGetter = useStringGetter();
const { freeCollateral } = useSelector(getSubaccount, shallowEqual) || {}; const { freeCollateral } = useSelector(getSubaccount, shallowEqual) || {};
const { dydxAddress } = useAccounts(); const { dydxAddress } = useAccounts();
const {
address: recipientAddress,
size,
fee,
} = useSelector(getTransferInputs, shallowEqual) || {};
const { transfer } = useSubaccount(); const { transfer } = useSubaccount();
const { nativeTokenBalance, usdcBalance } = useAccountBalance(); const { nativeTokenBalance, usdcBalance } = useAccountBalance();
const { selectedNetwork } = useSelectedNetwork(); const { selectedNetwork } = useSelectedNetwork();
const { tokensConfigs, usdcLabel, chainTokenLabel } = useTokenConfigs(); const { tokensConfigs, usdcLabel, chainTokenLabel } = useTokenConfigs();
const { // User Input
address: recipientAddress, const [asset, setAsset] = useState<DydxChainAsset>(selectedAsset);
size,
fee,
token,
} = useSelector(getTransferInputs, shallowEqual) || {};
// Form states // Form states
const [error, setError] = useState<string>(); const [error, setError] = useState<string>();
const [isLoading, setIsLoading] = useState(false); const [isLoading, setIsLoading] = useState(false);
// temp fix: TODO: reset fees when changing token in Abacus const balance = asset === DydxChainAsset.USDC ? freeCollateral?.current : nativeTokenBalance;
const [currentFee, setCurrentFee] = useState(fee); const newBalance =
useEffect(() => { asset === DydxChainAsset.USDC
setCurrentFee(fee); ? freeCollateral?.postOrder
}, [fee]); : MustBigNumber(nativeTokenBalance)
.minus(size?.size ?? 0)
.toNumber();
const amount = asset === DydxChainAsset.USDC ? size?.usdcSize : size?.size;
const asset = (token ?? selectedAsset) as DydxChainAsset; const showNotEnoughGasWarning = fee && asset === DydxChainAsset.USDC && usdcBalance < fee;
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 // BN
const newBalanceBN = isUSDCSelected
? MustBigNumber(freeCollateral?.postOrder)
: nativeTokenBalance.minus(size?.size ?? 0);
const amountBN = MustBigNumber(amount); const amountBN = MustBigNumber(amount);
const balanceBN = MustBigNumber(balance); 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(() => { useEffect(() => {
abacusStateManager.setTransferValue({ abacusStateManager.setTransferValue({
@@ -115,13 +100,19 @@ export const TransferForm = ({
field: TransferInputField.type, field: TransferInputField.type,
}); });
onChangeAsset(selectedAsset);
return () => { return () => {
abacusStateManager.clearTransferInputValues(); abacusStateManager.clearTransferInputValues();
}; };
}, []); }, []);
useEffect(() => {
setError(undefined);
abacusStateManager.setTransferValue({
value: asset,
field: TransferInputField.token,
});
}, [asset]);
const { sanctionedAddresses } = useRestrictions(); const { sanctionedAddresses } = useRestrictions();
const isAddressValid = useMemo( const isAddressValid = useMemo(
@@ -143,6 +134,11 @@ export const TransferForm = ({
setError(undefined); setError(undefined);
try { try {
// Subtract fees from amount if sending native tokens
const amountToTransfer = (
asset === DydxChainAsset.CHAINTOKEN ? amountBN.minus(fee) : amountBN
).toNumber();
const screenResults = await screenAddresses({ const screenResults = await screenAddresses({
addresses: [recipientAddress!, dydxAddress!], addresses: [recipientAddress!, dydxAddress!],
}); });
@@ -161,9 +157,9 @@ export const TransferForm = ({
); );
} else { } else {
const txResponse = await transfer( const txResponse = await transfer(
amountBN.toNumber(), amountToTransfer,
recipientAddress as string, recipientAddress as string,
tokensConfigs[asset]?.denom tokensConfigs[asset].denom,
); );
if (txResponse?.code === 0) { if (txResponse?.code === 0) {
@@ -204,7 +200,7 @@ export const TransferForm = ({
const onChangeAmount = (value?: number) => { const onChangeAmount = (value?: number) => {
abacusStateManager.setTransferValue({ abacusStateManager.setTransferValue({
value, value,
field: isUSDCSelected ? TransferInputField.usdcSize : TransferInputField.size, field: asset === DydxChainAsset.USDC ? TransferInputField.usdcSize : TransferInputField.size,
}); });
}; };
@@ -230,7 +226,7 @@ export const TransferForm = ({
value: DydxChainAsset.CHAINTOKEN, value: DydxChainAsset.CHAINTOKEN,
label: ( label: (
<Styled.InlineRow> <Styled.InlineRow>
<AssetIcon symbol={chainTokenLabel} /> {/* <AssetIcon symbol="DYDX" /> */}
{chainTokenLabel} {chainTokenLabel}
</Styled.InlineRow> </Styled.InlineRow>
), ),
@@ -253,15 +249,15 @@ export const TransferForm = ({
key: 'amount', key: 'amount',
label: ( label: (
<span> <span>
{stringGetter({ key: STRING_KEYS.AVAILABLE })} <Tag>{tokensConfigs[asset]?.name}</Tag> {stringGetter({ key: STRING_KEYS.AVAILABLE })} <Tag>{tokensConfigs[asset].name}</Tag>
</span> </span>
), ),
value: ( value: (
<DiffOutput <DiffOutput
type={OutputType.Asset} type={OutputType.Asset}
value={balanceBN} value={balanceBN.toString()}
newValue={newBalanceBN.toString()}
sign={NumberSign.Negative} sign={NumberSign.Negative}
newValue={newBalanceBN}
hasInvalidNewValue={newBalanceBN.isNegative()} hasInvalidNewValue={newBalanceBN.isNegative()}
withDiff={Boolean(amount && balance) && !amountBN.isNaN()} withDiff={Boolean(amount && balance) && !amountBN.isNaN()}
/> />
@@ -344,8 +340,8 @@ export const TransferForm = ({
<Styled.SelectMenu <Styled.SelectMenu
label={stringGetter({ key: STRING_KEYS.ASSET })} label={stringGetter({ key: STRING_KEYS.ASSET })}
value={token} value={asset}
onValueChange={onChangeAsset} onValueChange={setAsset}
disabled={isLoading} disabled={isLoading}
> >
{assetOptions.map(({ value, label }) => ( {assetOptions.map(({ value, label }) => (
@@ -359,16 +355,12 @@ export const TransferForm = ({
type={InputType.Number} type={InputType.Number}
onChange={({ floatValue }: NumberFormatValues) => onChangeAmount(floatValue)} onChange={({ floatValue }: NumberFormatValues) => onChangeAmount(floatValue)}
value={amount ?? undefined} value={amount ?? undefined}
slotRight={ slotRight={renderFormInputButton({
isUSDCSelected && label: stringGetter({ key: STRING_KEYS.MAX }),
balanceBN.gt(0) && isInputEmpty: size?.usdcSize == null,
renderFormInputButton({ onClear: () => onChangeAmount(undefined),
label: stringGetter({ key: STRING_KEYS.MAX }), onClick: () => onChangeAmount(balanceBN.toNumber()),
isInputEmpty: size?.usdcSize == null, })}
onClear: () => onChangeAmount(undefined),
onClick: () => onChangeAmount(balanceBN.toNumber()),
})
}
disabled={isLoading} disabled={isLoading}
/> />
</WithDetailsReceipt> </WithDetailsReceipt>
@@ -377,7 +369,7 @@ export const TransferForm = ({
<AlertMessage type={AlertType.Warning}> <AlertMessage type={AlertType.Warning}>
{stringGetter({ {stringGetter({
key: STRING_KEYS.TRANSFER_INSUFFICIENT_GAS, key: STRING_KEYS.TRANSFER_INSUFFICIENT_GAS,
params: { USDC_BALANCE: `(${usdcBalance} USDC)` }, params: { USDC_BALANCE: `(${usdcBalance})` },
})} })}
</AlertMessage> </AlertMessage>
)} )}
@@ -387,9 +379,9 @@ export const TransferForm = ({
<Styled.Footer> <Styled.Footer>
<TransferButtonAndReceipt <TransferButtonAndReceipt
selectedAsset={asset} selectedAsset={asset}
fee={currentFee || undefined} fees={fee || undefined}
isDisabled={!isAmountValid || !isAddressValid || !currentFee || isLoading} isDisabled={!isAmountValid || !isAddressValid || !fee || isLoading}
isLoading={isLoading || Boolean(isAmountValid && isAddressValid && !currentFee)} isLoading={isLoading || Boolean(isAmountValid && isAddressValid && !fee)}
/> />
</Styled.Footer> </Styled.Footer>
</Styled.Form> </Styled.Form>
@@ -23,14 +23,14 @@ import { MustBigNumber } from '@/lib/numbers';
type ElementProps = { type ElementProps = {
selectedAsset: DydxChainAsset; selectedAsset: DydxChainAsset;
fee?: number; fees?: number;
isDisabled?: boolean; isDisabled?: boolean;
isLoading?: boolean; isLoading?: boolean;
}; };
export const TransferButtonAndReceipt = ({ export const TransferButtonAndReceipt = ({
selectedAsset, selectedAsset,
fee, fees,
isDisabled, isDisabled,
isLoading, isLoading,
}: ElementProps) => { }: ElementProps) => {
@@ -47,46 +47,43 @@ export const TransferButtonAndReceipt = ({
const { current: equity, postOrder: newEquity } = equityInfo || {}; const { current: equity, postOrder: newEquity } = equityInfo || {};
const { current: leverage, postOrder: newLeverage } = leverageInfo || {}; const { current: leverage, postOrder: newLeverage } = leverageInfo || {};
const isUSDCSelected = selectedAsset === DydxChainAsset.USDC; // TODO(@aforaleka): add wallet balance for DYDX
const balance = selectedAsset === DydxChainAsset.USDC ? equity : nativeTokenBalance;
const balance = isUSDCSelected ? equity : nativeTokenBalance; const newBalance =
const newNativeTokenBalance = nativeTokenBalance selectedAsset === DydxChainAsset.USDC
.minus(size?.size ?? 0) ? newEquity
.minus(fee ?? 0) // show balance after fees for button receipt : MustBigNumber(nativeTokenBalance)
.toNumber(); .minus(size?.size ?? 0)
.toNumber();
const newBalance = isUSDCSelected ? newEquity : newNativeTokenBalance;
const transferDetailItems = [ const transferDetailItems = [
{ {
key: 'fees', key: 'fees',
label: ( label: (
<span> <span>
{stringGetter({ key: STRING_KEYS.FEES })} <Tag>{tokensConfigs[selectedAsset]?.name}</Tag> {stringGetter({ key: STRING_KEYS.FEES })} <Tag>{tokensConfigs[selectedAsset].name}</Tag>
</span> </span>
), ),
value: <Output type={OutputType.Asset} value={fee} />, value: <Output type={OutputType.Asset} value={fees} />,
}, },
{ {
key: 'balance', key: 'balance',
label: ( label: (
<span> <span>
{stringGetter({ key: STRING_KEYS.BALANCE })}{' '} {stringGetter({ key: STRING_KEYS.BALANCE })} <Tag>{tokensConfigs[selectedAsset].name}</Tag>
<Tag>{tokensConfigs[selectedAsset]?.name}</Tag>
</span> </span>
), ),
value: ( value: (
<DiffOutput <DiffOutput
type={OutputType.Asset} type={OutputType.Asset}
value={balance} value={balance}
sign={NumberSign.Negative}
newValue={newBalance} newValue={newBalance}
hasInvalidNewValue={MustBigNumber(newBalance).isNegative()} sign={NumberSign.Negative}
withDiff={newBalance !== null && !MustBigNumber(balance).eq(newBalance ?? 0)} withDiff={Boolean(newBalance) && balance !== newBalance}
/> />
), ),
}, },
isUSDCSelected && { selectedAsset === DydxChainAsset.USDC && {
key: 'leverage', key: 'leverage',
label: <span>{stringGetter({ key: STRING_KEYS.LEVERAGE })}</span>, label: <span>{stringGetter({ key: STRING_KEYS.LEVERAGE })}</span>,
value: ( value: (
+25 -61
View File
@@ -36,7 +36,6 @@ import { truncateAddress } from '@/lib/wallet';
import { layoutMixins } from '@/styles/layoutMixins'; import { layoutMixins } from '@/styles/layoutMixins';
import { headerMixins } from '@/styles/headerMixins'; import { headerMixins } from '@/styles/headerMixins';
import { MustBigNumber } from '@/lib/numbers';
export const AccountMenu = () => { export const AccountMenu = () => {
const stringGetter = useStringGetter(); const stringGetter = useStringGetter();
@@ -50,8 +49,6 @@ export const AccountMenu = () => {
const { evmAddress, walletType, dydxAddress, hdKey } = useAccounts(); const { evmAddress, walletType, dydxAddress, hdKey } = useAccounts();
const usdcBalance = freeCollateral?.current || 0;
const onRecoverKeys = () => { const onRecoverKeys = () => {
dispatch(openDialog({ type: DialogTypes.Onboarding })); dispatch(openDialog({ type: DialogTypes.Onboarding }));
}; };
@@ -125,11 +122,7 @@ export const AccountMenu = () => {
</Styled.label> </Styled.label>
<Styled.BalanceOutput type={OutputType.Asset} value={nativeTokenBalance} /> <Styled.BalanceOutput type={OutputType.Asset} value={nativeTokenBalance} />
</div> </div>
<AssetActions <AssetActions asset={DydxChainAsset.CHAINTOKEN} dispatch={dispatch} />
asset={DydxChainAsset.CHAINTOKEN}
dispatch={dispatch}
hasBalance={nativeTokenBalance.gt(0)}
/>
</div> </div>
<div> <div>
<div> <div>
@@ -142,16 +135,11 @@ export const AccountMenu = () => {
</Styled.label> </Styled.label>
<Styled.BalanceOutput <Styled.BalanceOutput
type={OutputType.Asset} type={OutputType.Asset}
value={usdcBalance} value={freeCollateral?.current || 0}
fractionDigits={2} fractionDigits={2}
/> />
</div> </div>
<AssetActions <AssetActions asset={DydxChainAsset.USDC} dispatch={dispatch} />
asset={DydxChainAsset.USDC}
dispatch={dispatch}
hasBalance={MustBigNumber(usdcBalance).gt(0)}
withOnboarding
/>
</div> </div>
</Styled.Balances> </Styled.Balances>
</Styled.AccountInfo> </Styled.AccountInfo>
@@ -224,48 +212,28 @@ export const AccountMenu = () => {
); );
}; };
const AssetActions = memo( const AssetActions = memo(({ asset, dispatch }: { asset: DydxChainAsset; dispatch: Dispatch }) => (
({ <Styled.InlineRow>
asset, {[
dispatch, // TODO(@rosepuppy): Add withdraw action for USDC
withOnboarding, {
hasBalance, dialogType: DialogTypes.Receive,
}: { iconName: IconName.Qr,
asset: DydxChainAsset; },
dispatch: Dispatch; { dialogType: DialogTypes.Transfer, iconName: IconName.Send },
withOnboarding?: boolean; ].map(({ iconName, dialogType }) => (
hasBalance?: boolean; <IconButton
}) => ( key={dialogType}
<Styled.InlineRow> action={ButtonAction.Base}
{[ shape={ButtonShape.Square}
withOnboarding && iconName={iconName}
hasBalance && { onClick={() =>
dialogType: DialogTypes.Withdraw, dispatch(openDialog({ type: dialogType, dialogProps: { selectedAsset: asset } }))
iconName: IconName.Withdraw, }
}, />
withOnboarding && { ))}
dialogType: DialogTypes.Deposit, </Styled.InlineRow>
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> = {}; const Styled: Record<string, AnyStyledComponent> = {};
@@ -383,7 +351,3 @@ Styled.ConnectToChain = styled(Styled.Column)`
font: var(--font-small-book); font: var(--font-small-book);
} }
`; `;
Styled.IconButton = styled(IconButton)`
--button-padding: 0 0.25rem;
`;
-2
View File
@@ -33,8 +33,6 @@ const Styled: Record<string, AnyStyledComponent> = {};
Styled.DropdownSelectMenu = styled(DropdownSelectMenu)` Styled.DropdownSelectMenu = styled(DropdownSelectMenu)`
${headerMixins.dropdownTrigger} ${headerMixins.dropdownTrigger}
width: max-content;
& > span:first-of-type { & > span:first-of-type {
${layoutMixins.textOverflow} ${layoutMixins.textOverflow}
max-width: 5.625rem; max-width: 5.625rem;
+5 -6
View File
@@ -1,13 +1,10 @@
import React, { useMemo } from 'react'; import React, { useMemo } from 'react';
import styled from 'styled-components';
import { layoutMixins } from '@/styles/layoutMixins';
import { groupBy } from 'lodash'; import { groupBy } from 'lodash';
import { type Notification, NotificationStatus } from '@/constants/notifications'; import { type Notification, NotificationStatus } from '@/constants/notifications';
import { useBreakpoints } from '@/hooks';
import { useNotifications } from '@/hooks/useNotifications'; import { useNotifications } from '@/hooks/useNotifications';
import { CloseIcon } from '@/icons';
import { Button } from '@/components/Button'; import { Button } from '@/components/Button';
import { ButtonAction, ButtonSize } from '@/constants/buttons'; import { ButtonAction, ButtonSize } from '@/constants/buttons';
@@ -16,6 +13,10 @@ import { DialogPlacement } from '@/components/Dialog';
import { Output, OutputType } from '@/components/Output'; import { Output, OutputType } from '@/components/Output';
import { IconButton } from '@/components/IconButton'; import { IconButton } from '@/components/IconButton';
import { Toolbar } from '@/components/Toolbar'; import { Toolbar } from '@/components/Toolbar';
import { CloseIcon } from '@/icons';
import styled from 'styled-components';
import { layoutMixins } from '@/styles/layoutMixins';
type ElementProps = { type ElementProps = {
slotTrigger?: React.ReactNode; slotTrigger?: React.ReactNode;
@@ -26,7 +27,6 @@ export const NotificationsMenu = ({
slotTrigger, slotTrigger,
placement = DialogPlacement.Sidebar, placement = DialogPlacement.Sidebar,
}: ElementProps) => { }: ElementProps) => {
const { isTablet } = useBreakpoints();
const { const {
notifications, notifications,
getDisplayData, getDisplayData,
@@ -173,7 +173,6 @@ export const NotificationsMenu = ({
</$FooterToolbar> </$FooterToolbar>
} }
placement={placement} placement={placement}
preventClose={isTablet}
/> />
); );
}; };
+3 -10
View File
@@ -7,7 +7,7 @@ import { ButtonAction } from '@/constants/buttons';
import { DialogTypes } from '@/constants/dialogs'; import { DialogTypes } from '@/constants/dialogs';
import { STRING_KEYS, StringGetterFunction } from '@/constants/localization'; import { STRING_KEYS, StringGetterFunction } from '@/constants/localization';
import { useBreakpoints, useStringGetter, useURLConfigs } from '@/hooks'; import { useBreakpoints, useStringGetter } from '@/hooks';
import { layoutMixins } from '@/styles/layoutMixins'; import { layoutMixins } from '@/styles/layoutMixins';
import { tradeViewMixins } from '@/styles/tradeViewMixins'; import { tradeViewMixins } from '@/styles/tradeViewMixins';
@@ -40,13 +40,11 @@ const getTransferHistoryTableColumnDef = ({
key, key,
stringGetter, stringGetter,
width, width,
mintscanTxUrl,
}: { }: {
key: TransferHistoryTableColumnKey; key: TransferHistoryTableColumnKey;
isTablet?: boolean; isTablet?: boolean;
stringGetter: StringGetterFunction; stringGetter: StringGetterFunction;
width?: ColumnSize; width?: ColumnSize;
mintscanTxUrl?: string;
}): ColumnDef<SubaccountTransfer> => ({ }): ColumnDef<SubaccountTransfer> => ({
width, width,
...( ...(
@@ -100,12 +98,9 @@ const getTransferHistoryTableColumnDef = ({
columnKey: TransferHistoryTableColumnKey.TxHash, columnKey: TransferHistoryTableColumnKey.TxHash,
getCellValue: (row) => row.transactionHash, getCellValue: (row) => row.transactionHash,
label: stringGetter({ key: STRING_KEYS.TRANSACTION }), label: stringGetter({ key: STRING_KEYS.TRANSACTION }),
renderCell: ({ transactionHash }) => renderCell: ({ transactionHash, resources }) =>
transactionHash ? ( transactionHash ? (
<Styled.TxHash <Styled.TxHash withIcon href={resources.blockExplorerUrl}>
withIcon
href={`${mintscanTxUrl?.replace('{tx_hash}', transactionHash)}`}
>
{truncateAddress(transactionHash, '')} {truncateAddress(transactionHash, '')}
</Styled.TxHash> </Styled.TxHash>
) : ( ) : (
@@ -135,7 +130,6 @@ export const TransferHistoryTable = ({
const stringGetter = useStringGetter(); const stringGetter = useStringGetter();
const dispatch = useDispatch(); const dispatch = useDispatch();
const { isMobile, isTablet } = useBreakpoints(); const { isMobile, isTablet } = useBreakpoints();
const { mintscan: mintscanTxUrl } = useURLConfigs();
const canAccountTrade = useSelector(calculateCanAccountTrade, shallowEqual); const canAccountTrade = useSelector(calculateCanAccountTrade, shallowEqual);
@@ -152,7 +146,6 @@ export const TransferHistoryTable = ({
isTablet, isTablet,
stringGetter, stringGetter,
width: columnWidths?.[key], width: columnWidths?.[key],
mintscanTxUrl,
}) })
)} )}
slotEmpty={ slotEmpty={