Compare commits

..
64 changed files with 562 additions and 1135 deletions
+2 -10
View File
@@ -11,7 +11,6 @@
## Prerequisites
- Node.js version 18 and `pnpm` installed on your system
- Wallet Connect account
For deploying with Vercel, create an account with [Vercel](https://vercel.com/signup) if you don't have one already.
@@ -62,14 +61,7 @@ pnpm ladle
This will automatically open your default browser at `http://localhost:61000`.
## Part 3: Configuring environment
Add or modify the relevant endpoints, links and options in `/public/configs/env.json`.
You'll need to provide a Wallet Connect project id to enable onboarding and wallet connection:
- Create a project on https://cloud.walletconnect.com/app
- Copy over the project ID into this [field](https://github.com/dydxprotocol/v4-web/blob/67ecbd75b43e0c264b7b4d2d9b3d969830b0621c/public/configs/env.json#L822C33-L822C46)
## Part 4: Deploying with Vercel
## Part 3: Deploying with Vercel
### Step 1: Connect your repository to Vercel
@@ -86,7 +78,7 @@ If you wish to incorporate analytics via Amplitude and Bugsnag, you can use our
For more details, check out Vercel's [official documentation](https://vercel.com/docs).
## Part 5: Deploying to IPFS
## Part 4: Deploying to IPFS
### web3.storage: deploy to IPFS via web3.storage using the provided script
+3 -3
View File
@@ -38,9 +38,9 @@
"@cosmjs/proto-signing": "^0.31.0",
"@cosmjs/stargate": "^0.31.0",
"@cosmjs/tendermint-rpc": "^0.31.0",
"@dydxprotocol/v4-abacus": "^0.7.2",
"@dydxprotocol/v4-client-js": "^0.40.3",
"@dydxprotocol/v4-localization": "^0.1.30",
"@dydxprotocol/v4-abacus": "^0.6.4",
"@dydxprotocol/v4-client-js": "^0.36.1",
"@dydxprotocol/v4-localization": "^0.1.28",
"@ethersproject/providers": "^5.7.2",
"@js-joda/core": "^5.5.3",
"@radix-ui/react-collapsible": "^1.0.3",
+28 -29
View File
@@ -1,9 +1,5 @@
lockfileVersion: '6.0'
settings:
autoInstallPeers: true
excludeLinksFromLockfile: false
dependencies:
'@0xsquid/sdk':
specifier: ^1.10.0
@@ -27,14 +23,14 @@ dependencies:
specifier: ^0.31.0
version: 0.31.0
'@dydxprotocol/v4-abacus':
specifier: ^0.7.2
version: 0.7.2
specifier: ^0.6.4
version: 0.6.4
'@dydxprotocol/v4-client-js':
specifier: ^0.40.3
version: 0.40.3
specifier: ^0.36.1
version: 0.36.1
'@dydxprotocol/v4-localization':
specifier: ^0.1.30
version: 0.1.30
specifier: ^0.1.28
version: 0.1.28
'@ethersproject/providers':
specifier: ^5.7.2
version: 5.7.2
@@ -645,7 +641,7 @@ packages:
/@confio/ics23@0.6.8:
resolution: {integrity: sha512-wB6uo+3A50m0sW/EWcU64xpV/8wShZ6bMTa7pF8eYsTrSkQA7oLUIJcs/wb8g4y2Oyq701BaGiO6n/ak5WXO1w==}
dependencies:
'@noble/hashes': 1.3.2
'@noble/hashes': 1.3.1
protobufjs: 6.11.4
dev: false
@@ -717,7 +713,7 @@ packages:
'@cosmjs/encoding': 0.30.1
'@cosmjs/math': 0.30.1
'@cosmjs/utils': 0.30.1
'@noble/hashes': 1.3.2
'@noble/hashes': 1.3.1
bn.js: 5.2.1
elliptic: 6.5.4
libsodium-wrappers: 0.7.11
@@ -979,12 +975,12 @@ packages:
resolution: {integrity: sha512-RpfLEtTlyIxeNPGKcokS+p3BZII/Q3bYxryFRglh5H3A3T8q9fsLYm72VYAMEOOIBLEa8o93kFLiBDUWKrwXZA==}
dev: true
/@dydxprotocol/v4-abacus@0.7.2:
resolution: {integrity: sha512-5foamomN82FH6ko3EuzwFlSoAEY6Sal8fDgvZo2RsB19Ks6SFgFDeeOcEDdfoa3DNwvl8yW0C9cfxeQ+BfU8uA==}
/@dydxprotocol/v4-abacus@0.6.4:
resolution: {integrity: sha512-eH+/9Q/OnQtwzBwM1BJyXybFPdivGmFQWrxM71MFWGs6uIQGbZX775mpoa8deweSTyQ/QrRLRQ1mP2BPDgBQYg==}
dev: false
/@dydxprotocol/v4-client-js@0.40.3:
resolution: {integrity: sha512-nMQd6tYisKDKIbfx0BGJSYEOSt+I+t5SsaBSmlgTdso+w2rCRO9vyxS+u6MF9h4w5FsVRfhHo3e6uTWX48WpGQ==}
/@dydxprotocol/v4-client-js@0.36.1:
resolution: {integrity: sha512-KJ3MtWI61wmm+xZtXQd7/hYKIoVFG32TRdyyVaXXO8vpW9Oqd0JD8QSM/wuegkciAh5YmP/BrDzYuu77zHO6yg==}
dependencies:
'@cosmjs/amino': 0.30.1
'@cosmjs/encoding': 0.31.1
@@ -993,15 +989,14 @@ packages:
'@cosmjs/stargate': 0.30.1
'@cosmjs/tendermint-rpc': 0.30.1
'@cosmjs/utils': 0.31.1
'@dydxprotocol/v4-proto': 0.4.1
'@dydxprotocol/v4-proto': 0.2.1
'@osmonauts/lcd': 0.6.0
'@scure/bip32': 1.3.2
'@scure/bip32': 1.3.1
'@scure/bip39': 1.2.1
axios: 1.1.3
bech32: 1.1.4
bignumber.js: 9.1.1
ethereum-cryptography: 2.1.2
ethers: 6.6.1
long: 4.0.0
protobufjs: 6.11.4
ws: 8.13.0(bufferutil@4.0.7)(utf-8-validate@5.0.10)
@@ -1011,12 +1006,12 @@ packages:
- utf-8-validate
dev: false
/@dydxprotocol/v4-localization@0.1.30:
resolution: {integrity: sha512-xTlQuQmPz7wfGkjd07giYMAxRrolDbJE3DryJSIMB6R1MBq1wLzAcwp/iR/nELRwilRX9c44Tap0gGt+oAajiQ==}
/@dydxprotocol/v4-localization@0.1.28:
resolution: {integrity: sha512-g6LwjX7EIRm9HISfSX0H6yhktBCZby5opP/yI2aIUvn2OYyB25WcjLEuEvzW5Bh9XXiLijgLf3Tk91wPKWuFbA==}
dev: false
/@dydxprotocol/v4-proto@0.4.1:
resolution: {integrity: sha512-2pBkokufWcxfIpiXE6QuQOBXUe154OTp6ojCIdOPW9TFLxzchoygxXnb5dL6rAQVNj9Qbg+hhXBllutt4m99dw==}
/@dydxprotocol/v4-proto@0.2.1:
resolution: {integrity: sha512-Q5b/g331DoyMjBpO2/jtrxUX3WF5UaIKZp/unK332xuefHNFnkMYtZ05p0V71iSdO35tBdz8yt0VYP2WtUsp+w==}
dependencies:
protobufjs: 6.11.4
dev: false
@@ -4709,8 +4704,8 @@ packages:
resolution: {integrity: sha512-osvveYtyzdEVbt3OfwwXFr4P2iVBL5u1Q3q4ONBfDY/UpOuXmOlbgwc1xECEboY8wIays8Yt6onaWMUdUbfl0A==}
dependencies:
'@noble/curves': 1.1.0
'@noble/hashes': 1.3.2
'@scure/base': 1.1.3
'@noble/hashes': 1.3.1
'@scure/base': 1.1.1
dev: false
/@scure/bip32@1.3.2:
@@ -4732,7 +4727,7 @@ packages:
resolution: {integrity: sha512-Z3/Fsz1yr904dduJD0NpiyRHhRYHdcnyh73FZWiV+/qhWi83wNJ3NWolYqCEN+ZWsUz2TWwajJggcRE9r1zUYg==}
dependencies:
'@noble/hashes': 1.3.2
'@scure/base': 1.1.3
'@scure/base': 1.1.1
dev: false
/@solana/buffer-layout@4.0.1:
@@ -4746,8 +4741,8 @@ packages:
resolution: {integrity: sha512-up5VG1dK+GPhykmuMIozJZBbVqpm77vbOG6/r5dS7NBGZonwHfTLdBbsYc3rjmaQ4DpCXUa3tUc4RZHRORvZrw==}
dependencies:
'@babel/runtime': 7.22.10
'@noble/curves': 1.2.0
'@noble/hashes': 1.3.2
'@noble/curves': 1.1.0
'@noble/hashes': 1.3.1
'@solana/buffer-layout': 4.0.1
agentkeepalive: 4.5.0
bigint-buffer: 1.1.5
@@ -7145,7 +7140,7 @@ packages:
/bip39@3.1.0:
resolution: {integrity: sha512-c9kiwdk45Do5GL0vJMe7tS95VjCii65mYAH7DfWl3uW8AVzXKQVUm64i3hzVybBDMp9r7j9iNxR85+ul8MdN/A==}
dependencies:
'@noble/hashes': 1.3.2
'@noble/hashes': 1.3.1
dev: false
/bl@5.1.0:
@@ -14100,3 +14095,7 @@ packages:
/zwitch@2.0.4:
resolution: {integrity: sha512-bXE4cR/kVZhKZX/RjPEflHaKVhUVl85noU3v6b8apfQEc1x4A+zBxjZ4lN8LqGd6WZ3dl98pY4o717VFmoPp+A==}
dev: true
settings:
autoInstallPeers: true
excludeLinksFromLockfile: false
Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

+80 -67
View File
@@ -40,16 +40,14 @@
"isMainNet": false,
"tokens": {
"chain": {
"name": "Dv4TNT",
"denom": "adv4tnt",
"decimals": 18,
"name": "DYDX",
"denom": "dv4tnt",
"image": "/currencies/dydx.png"
},
"usdc": {
"name": "USDC",
"denom": "ibc/8E27BA2D5493AF5636760E354E46004562C46AB7EC0CC4C1CA14E9E20E2545B5",
"gasDenom": "uusdc",
"decimals": 6,
"image": "/currencies/usdc.png"
}
},
@@ -79,6 +77,9 @@
"description": "dYdX v4 App",
"iconUrl": "/logos/dydx-x.png"
},
"v1": {
"bridgeUrl": "wss://api.stage.dydx.exchange/wc/"
},
"v2": {
"projectId": "47559b2ec96c09aed9ff2cb54a31ab0e"
}
@@ -100,16 +101,14 @@
"isMainNet": false,
"tokens": {
"chain": {
"name": "Dv4TNT",
"denom": "adv4tnt",
"decimals": 18,
"name": "DYDX",
"denom": "dv4tnt",
"image": "/currencies/dydx.png"
},
"usdc": {
"name": "USDC",
"denom": "ibc/8E27BA2D5493AF5636760E354E46004562C46AB7EC0CC4C1CA14E9E20E2545B5",
"gasDenom": "uusdc",
"decimals": 6,
"image": "/currencies/usdc.png"
}
},
@@ -121,7 +120,7 @@
}
],
"validators": [
"http://54.92.118.111"
"http://35.75.227.118"
],
"0xsquid": "https://testnet.api.0xsquid.com"
},
@@ -138,6 +137,9 @@
"description": "dYdX v4 App",
"iconUrl": "/logos/dydx-x.png"
},
"v1": {
"bridgeUrl": "wss://api.stage.dydx.exchange/wc/"
},
"v2": {
"projectId": "47559b2ec96c09aed9ff2cb54a31ab0e"
}
@@ -159,16 +161,14 @@
"isMainNet": false,
"tokens": {
"chain": {
"name": "Dv4TNT",
"denom": "adv4tnt",
"decimals": 18,
"name": "DYDX",
"denom": "dv4tnt",
"image": "/currencies/dydx.png"
},
"usdc": {
"name": "USDC",
"denom": "ibc/8E27BA2D5493AF5636760E354E46004562C46AB7EC0CC4C1CA14E9E20E2545B5",
"gasDenom": "uusdc",
"decimals": 6,
"image": "/currencies/usdc.png"
}
},
@@ -197,6 +197,9 @@
"description": "dYdX v4 App",
"iconUrl": "/logos/dydx-x.png"
},
"v1": {
"bridgeUrl": "wss://api.stage.dydx.exchange/wc/"
},
"v2": {
"projectId": "47559b2ec96c09aed9ff2cb54a31ab0e"
}
@@ -218,16 +221,14 @@
"isMainNet": false,
"tokens": {
"chain": {
"name": "Dv4TNT",
"denom": "adv4tnt",
"decimals": 18,
"name": "DYDX",
"denom": "dv4tnt",
"image": "/currencies/dydx.png"
},
"usdc": {
"name": "USDC",
"denom": "ibc/8E27BA2D5493AF5636760E354E46004562C46AB7EC0CC4C1CA14E9E20E2545B5",
"gasDenom": "uusdc",
"decimals": 6,
"image": "/currencies/usdc.png"
}
},
@@ -256,6 +257,9 @@
"description": "dYdX v4 App",
"iconUrl": "/logos/dydx-x.png"
},
"v1": {
"bridgeUrl": "wss://api.stage.dydx.exchange/wc/"
},
"v2": {
"projectId": "47559b2ec96c09aed9ff2cb54a31ab0e"
}
@@ -277,16 +281,14 @@
"isMainNet": false,
"tokens": {
"chain": {
"name": "Dv4TNT",
"denom": "adv4tnt",
"decimals": 18,
"name": "DYDX",
"denom": "dv4tnt",
"image": "/currencies/dydx.png"
},
"usdc": {
"name": "USDC",
"denom": "ibc/8E27BA2D5493AF5636760E354E46004562C46AB7EC0CC4C1CA14E9E20E2545B5",
"gasDenom": "uusdc",
"decimals": 6,
"image": "/currencies/usdc.png"
}
},
@@ -319,6 +321,9 @@
"description": "dYdX v4 App",
"iconUrl": "/logos/dydx-x.png"
},
"v1": {
"bridgeUrl": "wss://api.stage.dydx.exchange/wc/"
},
"v2": {
"projectId": "47559b2ec96c09aed9ff2cb54a31ab0e"
}
@@ -340,16 +345,14 @@
"isMainNet": false,
"tokens": {
"chain": {
"name": "Dv4TNT",
"denom": "adv4tnt",
"decimals": 18,
"name": "DYDX",
"denom": "dv4tnt",
"image": "/currencies/dydx.png"
},
"usdc": {
"name": "USDC",
"denom": "ibc/8E27BA2D5493AF5636760E354E46004562C46AB7EC0CC4C1CA14E9E20E2545B5",
"gasDenom": "uusdc",
"decimals": 6,
"image": "/currencies/usdc.png"
}
},
@@ -382,6 +385,9 @@
"description": "dYdX v4 App",
"iconUrl": "/logos/dydx-x.png"
},
"v1": {
"bridgeUrl": "wss://api.stage.dydx.exchange/wc/"
},
"v2": {
"projectId": "47559b2ec96c09aed9ff2cb54a31ab0e"
}
@@ -397,22 +403,20 @@
"dydxprotocol-testnet": {
"name": "v4 Public Testnet",
"ethereumChainId": "5",
"dydxChainId": "dydx-testnet-4",
"dydxChainId": "dydx-testnet-3",
"chainName": "dYdX Chain",
"chainLogo": "dydx-chain.png",
"isMainNet": false,
"tokens": {
"chain": {
"name": "Dv4TNT",
"denom": "adv4tnt",
"decimals": 18,
"name": "DYDX",
"denom": "dv4tnt",
"image": "/currencies/dydx.png"
},
"usdc": {
"name": "USDC",
"denom": "ibc/8E27BA2D5493AF5636760E354E46004562C46AB7EC0CC4C1CA14E9E20E2545B5",
"gasDenom": "uusdc",
"decimals": 6,
"image": "/currencies/usdc.png"
}
},
@@ -447,6 +451,9 @@
"description": "dYdX v4 App",
"iconUrl": "/logos/dydx-x.png"
},
"v1": {
"bridgeUrl": "wss://api.stage.dydx.exchange/wc/"
},
"v2": {
"projectId": "47559b2ec96c09aed9ff2cb54a31ab0e"
}
@@ -455,29 +462,27 @@
"callbackUrl": "/walletsegue"
},
"images": "/wallets/",
"signTypedDataAction": "dYdX Chain Onboarding",
"signTypedDataAction": "dYdX V4 Onboarding",
"signTypedDataDomainName": "dYdX V4"
}
},
"dydxprotocol-testnet-dydx": {
"name": "v4 Public Testnet/dYdX",
"ethereumChainId": "5",
"dydxChainId": "dydx-testnet-4",
"dydxChainId": "dydx-testnet-3",
"chainName": "dYdX Chain",
"chainLogo": "dydx-chain.png",
"isMainNet": false,
"tokens": {
"chain": {
"name": "Dv4TNT",
"denom": "adv4tnt",
"decimals": 18,
"name": "DYDX",
"denom": "dv4tnt",
"image": "/currencies/dydx.png"
},
"usdc": {
"name": "USDC",
"denom": "ibc/8E27BA2D5493AF5636760E354E46004562C46AB7EC0CC4C1CA14E9E20E2545B5",
"gasDenom": "uusdc",
"decimals": 6,
"image": "/currencies/usdc.png"
}
},
@@ -511,6 +516,9 @@
"description": "dYdX v4 App",
"iconUrl": "/logos/dydx-x.png"
},
"v1": {
"bridgeUrl": "wss://api.stage.dydx.exchange/wc/"
},
"v2": {
"projectId": "47559b2ec96c09aed9ff2cb54a31ab0e"
}
@@ -519,29 +527,27 @@
"callbackUrl": "/walletsegue"
},
"images": "/wallets/",
"signTypedDataAction": "dYdX Chain Onboarding",
"signTypedDataAction": "dYdX V4 Onboarding",
"signTypedDataDomainName": "dYdX V4"
}
},
"dydxprotocol-testnet-dsrv": {
"name": "v4 Public Testnet/DSRV",
"ethereumChainId": "5",
"dydxChainId": "dydx-testnet-4",
"dydxChainId": "dydx-testnet-3",
"chainName": "dYdX Chain",
"chainLogo": "dydx-chain.png",
"isMainNet": false,
"tokens": {
"chain": {
"name": "Dv4TNT",
"denom": "adv4tnt",
"decimals": 18,
"name": "DYDX",
"denom": "dv4tnt",
"image": "/currencies/dydx.png"
},
"usdc": {
"name": "USDC",
"denom": "ibc/8E27BA2D5493AF5636760E354E46004562C46AB7EC0CC4C1CA14E9E20E2545B5",
"gasDenom": "uusdc",
"decimals": 6,
"image": "/currencies/usdc.png"
}
},
@@ -575,6 +581,9 @@
"description": "dYdX v4 App",
"iconUrl": "/logos/dydx-x.png"
},
"v1": {
"bridgeUrl": "wss://api.stage.dydx.exchange/wc/"
},
"v2": {
"projectId": "47559b2ec96c09aed9ff2cb54a31ab0e"
}
@@ -583,29 +592,27 @@
"callbackUrl": "/walletsegue"
},
"images": "/wallets/",
"signTypedDataAction": "dYdX Chain Onboarding",
"signTypedDataAction": "dYdX V4 Onboarding",
"signTypedDataDomainName": "dYdX V4"
}
},
"dydxprotocol-testnet-nodefleet": {
"name": "v4 Public Testnet/nodefleet",
"ethereumChainId": "5",
"dydxChainId": "dydx-testnet-4",
"dydxChainId": "dydx-testnet-3",
"chainName": "dYdX Chain",
"chainLogo": "dydx-chain.png",
"isMainNet": false,
"tokens": {
"chain": {
"name": "Dv4TNT",
"denom": "adv4tnt",
"decimals": 18,
"name": "DYDX",
"denom": "dv4tnt",
"image": "/currencies/dydx.png"
},
"usdc": {
"name": "USDC",
"denom": "ibc/8E27BA2D5493AF5636760E354E46004562C46AB7EC0CC4C1CA14E9E20E2545B5",
"gasDenom": "uusdc",
"decimals": 6,
"image": "/currencies/usdc.png"
}
},
@@ -639,6 +646,9 @@
"description": "dYdX v4 App",
"iconUrl": "/logos/dydx-x.png"
},
"v1": {
"bridgeUrl": "wss://api.stage.dydx.exchange/wc/"
},
"v2": {
"projectId": "47559b2ec96c09aed9ff2cb54a31ab0e"
}
@@ -647,29 +657,27 @@
"callbackUrl": "/walletsegue"
},
"images": "/wallets/",
"signTypedDataAction": "dYdX Chain Onboarding",
"signTypedDataAction": "dYdX V4 Onboarding",
"signTypedDataDomainName": "dYdX V4"
}
},
"dydxprotocol-testnet-kingnodes": {
"name": "v4 Public Testnet/KingNodes",
"ethereumChainId": "5",
"dydxChainId": "dydx-testnet-4",
"dydxChainId": "dydx-testnet-3",
"chainName": "dYdX Chain",
"chainLogo": "dydx-chain.png",
"isMainNet": false,
"tokens": {
"chain": {
"name": "Dv4TNT",
"denom": "adv4tnt",
"decimals": 18,
"name": "DYDX",
"denom": "dv4tnt",
"image": "/currencies/dydx.png"
},
"usdc": {
"name": "USDC",
"denom": "ibc/8E27BA2D5493AF5636760E354E46004562C46AB7EC0CC4C1CA14E9E20E2545B5",
"gasDenom": "uusdc",
"decimals": 6,
"image": "/currencies/usdc.png"
}
},
@@ -703,6 +711,9 @@
"description": "dYdX v4 App",
"iconUrl": "/logos/dydx-x.png"
},
"v1": {
"bridgeUrl": "wss://api.stage.dydx.exchange/wc/"
},
"v2": {
"projectId": "47559b2ec96c09aed9ff2cb54a31ab0e"
}
@@ -711,29 +722,27 @@
"callbackUrl": "/walletsegue"
},
"images": "/wallets/",
"signTypedDataAction": "dYdX Chain Onboarding",
"signTypedDataAction": "dYdX V4 Onboarding",
"signTypedDataDomainName": "dYdX V4"
}
},
"dydxprotocol-testnet-liquify": {
"name": "v4 Public Testnet/Liquify",
"ethereumChainId": "5",
"dydxChainId": "dydx-testnet-4",
"dydxChainId": "dydx-testnet-3",
"chainName": "dYdX Chain",
"chainLogo": "dydx-chain.png",
"isMainNet": false,
"tokens": {
"chain": {
"name": "Dv4TNT",
"denom": "adv4tnt",
"decimals": 18,
"name": "DYDX",
"denom": "dv4tnt",
"image": "/currencies/dydx.png"
},
"usdc": {
"name": "USDC",
"denom": "ibc/8E27BA2D5493AF5636760E354E46004562C46AB7EC0CC4C1CA14E9E20E2545B5",
"gasDenom": "uusdc",
"decimals": 6,
"image": "/currencies/usdc.png"
}
},
@@ -767,6 +776,9 @@
"description": "dYdX v4 App",
"iconUrl": "/logos/dydx-x.png"
},
"v1": {
"bridgeUrl": "wss://api.stage.dydx.exchange/wc/"
},
"v2": {
"projectId": "47559b2ec96c09aed9ff2cb54a31ab0e"
}
@@ -775,11 +787,11 @@
"callbackUrl": "/walletsegue"
},
"images": "/wallets/",
"signTypedDataAction": "dYdX Chain Onboarding",
"signTypedDataAction": "dYdX V4 Onboarding",
"signTypedDataDomainName": "dYdX V4"
}
},
"dydxprotocol-mainnet": {
"dydxprotocol-mainet": {
"name": "v4",
"ethereumChainId": "1",
"dydxChainId": "[mainnet chain id]",
@@ -789,16 +801,14 @@
"tokens": {
"comment": "Change according to mainnet release",
"chain": {
"name": "TokenName",
"denom": "tokenDenom",
"decimals": 18,
"name": "DYDX",
"denom": "dv4tnt",
"image": "/currencies/dydx.png"
},
"usdc": {
"name": "USDC",
"denom": "ibc/8E27BA2D5493AF5636760E354E46004562C46AB7EC0CC4C1CA14E9E20E2545B5",
"gasDenom": "uusdc",
"decimals": 6,
"image": "/currencies/usdc.png"
}
},
@@ -831,6 +841,9 @@
"description": "[Description of the app]",
"iconUrl": "[Relative URL of the icon URL]"
},
"v1": {
"bridgeUrl": "[Bridge URL]"
},
"v2": {
"projectId": "[Project ID]"
}
@@ -844,4 +857,4 @@
}
}
}
}
}
+2 -18
View File
@@ -7,20 +7,13 @@ import { GrazProvider } from 'graz';
import { AppRoute, DEFAULT_TRADE_ROUTE } from '@/constants/routes';
import {
useBreakpoints,
useTokenConfigs,
useInitializePage,
useShouldShowFooter,
useAnalytics,
} from '@/hooks';
import { useBreakpoints, useInitializePage, useShouldShowFooter, useAnalytics } from '@/hooks';
import { DydxProvider } from '@/hooks/useDydxClient';
import { AccountsProvider } from '@/hooks/useAccounts';
import { DialogAreaProvider, useDialogArea } from '@/hooks/useDialogArea';
import { LocaleProvider } from '@/hooks/useLocaleSeparators';
import { NotificationsProvider } from '@/hooks/useNotifications';
import { LocalNotificationsProvider } from '@/hooks/useLocalNotifications';
import { RestrictionProvider } from '@/hooks/useRestrictions';
import { SubaccountProvider } from '@/hooks/useSubaccount';
import { SquidProvider } from '@/hooks/useSquid';
@@ -33,8 +26,6 @@ import ProfilePage from '@/pages/Profile';
import { SettingsPage } from '@/pages/settings/Settings';
import TradePage from '@/pages/trade/Trade';
import { RewardsPage } from '@/pages/rewards/RewardsPage';
import { TermsOfUsePage } from '@/pages/TermsOfUsePage';
import { PrivacyPolicyPage } from '@/pages/PrivacyPolicyPage';
import { HeaderDesktop } from '@/layout/Header/HeaderDesktop';
import { FooterDesktop } from '@/layout/Footer/FooterDesktop';
@@ -63,7 +54,6 @@ const Content = () => {
const { isTablet, isNotTablet } = useBreakpoints();
const isShowingHeader = isNotTablet;
const isShowingFooter = useShouldShowFooter();
const { chainTokenLabel } = useTokenConfigs();
return (
<Styled.Content isShowingHeader={isShowingHeader} isShowingFooter={isShowingFooter}>
@@ -76,9 +66,8 @@ const Content = () => {
<Route path=":market" element={<TradePage />} />
<Route path={AppRoute.Trade} element={<TradePage />} />
</Route>
<Route path={AppRoute.Markets} element={<MarketsPage />} />
<Route path={`/${chainTokenLabel}`} element={<RewardsPage />} />
<Route path={AppRoute.Rewards} element={<RewardsPage />} />
{isTablet && (
<>
<Route path={AppRoute.Alerts} element={<AlertsPage />} />
@@ -90,10 +79,6 @@ const Content = () => {
<Route element={<GuardedMobileRoute />}>
<Route path={`${AppRoute.Portfolio}/*`} element={<PortfolioPage />} />
</Route>
<Route path={AppRoute.Terms} element={<TermsOfUsePage />} />
<Route path={AppRoute.Privacy} element={<PrivacyPolicyPage />} />
<Route path="*" element={<Navigate to={DEFAULT_TRADE_ROUTE} replace />} />
</Routes>
</Suspense>
@@ -124,7 +109,6 @@ const providers = [
wrapProvider(GrazProvider),
wrapProvider(WagmiConfig, { config }),
wrapProvider(LocaleProvider),
wrapProvider(RestrictionProvider),
wrapProvider(DydxProvider),
wrapProvider(AccountsProvider),
wrapProvider(SubaccountProvider),
+1 -8
View File
@@ -6,8 +6,6 @@ import {
AddressConnectorIcon,
ArrowIcon,
Bar3Icon,
BellIcon,
BellStrokeIcon,
BoxCloseIcon,
CalculatorIcon,
CaretIcon,
@@ -73,8 +71,6 @@ export enum IconName {
AddressConnector = 'AddressConnector',
Arrow = 'Arrow',
Bar3 = 'Bar3',
Bell = 'Bell',
BellStroked = 'BellStroked',
BoxClose = 'BoxClose',
Calculator = 'Calculator',
Caret = 'Caret',
@@ -141,8 +137,6 @@ const icons = {
[IconName.AddressConnector]: AddressConnectorIcon,
[IconName.Arrow]: ArrowIcon,
[IconName.Bar3]: Bar3Icon,
[IconName.Bell]: BellIcon,
[IconName.BellStroked]: BellStrokeIcon,
[IconName.BoxClose]: BoxCloseIcon,
[IconName.Calculator]: CalculatorIcon,
[IconName.Caret]: CaretIcon,
@@ -219,8 +213,7 @@ export const Icon = styled(
iconComponent: Component = iconName && icons[iconName],
className,
...props
}: ElementProps & StyleProps) =>
Component ? <Component className={className} {...props} /> : null
}: ElementProps & StyleProps) => (Component ? <Component className={className} {...props} /> : null)
)`
width: 1em;
height: 1em;
-10
View File
@@ -207,16 +207,6 @@ const InputStyle = css`
color: var(--color-text-0);
opacity: 1;
}
// Input autofill Styles
&:-webkit-autofill,
&:-webkit-autofill:focus {
transition: background-color 600000s 0s, color 600000s 0s;
}
&[data-autocompleted] {
background-color: var(--input-backgroundColor) !important;
}
`;
Styled.NumericFormat = styled(NumericFormat)`
+10 -28
View File
@@ -59,6 +59,16 @@ export const TransactionType = Abacus.exchange.dydx.abacus.protocols.Transaction
const transactionTypes = [...TransactionType.values()] as const;
export type TransactionTypes = (typeof transactionTypes)[number];
export type NetworkConfig = {
chainId: string;
indexerUrl: string;
indexerSocketUrl: string;
validatorUrl: string;
faucetUrl?: string | null;
};
export type ConnectNetworkEvent = CustomEvent<Partial<NetworkConfig>>;
// ------ State ------
export type AbacusApiState = Abacus.exchange.dydx.abacus.state.manager.ApiState;
export const AbacusApiStatus = Abacus.exchange.dydx.abacus.state.manager.ApiStatus;
@@ -68,13 +78,8 @@ export const Changes = Abacus.exchange.dydx.abacus.state.changes.Changes;
export type PerpetualStateChanges = Abacus.exchange.dydx.abacus.state.changes.StateChanges;
export const AsyncAbacusStateManager =
Abacus.exchange.dydx.abacus.state.manager.AsyncAbacusStateManager;
// ------ Parsing Errors ------ //
export type ParsingError = Abacus.exchange.dydx.abacus.responses.ParsingError;
export type ParsingErrors = kollections.List<ParsingError>;
export const ParsingErrorType = Abacus.exchange.dydx.abacus.responses.ParsingErrorType;
const parsingErrorTypes = [...ParsingErrorType.values()] as const;
export type ParsingErrorTypes = (typeof parsingErrorTypes)[number];
// ------ Perpetuals/Markets ------ //
export type PerpetualState = Abacus.exchange.dydx.abacus.output.PerpetualState;
@@ -194,12 +199,6 @@ export type RiskLevels = (typeof riskLevels)[number];
// ------ Notifications ------ //
export type AbacusNotification = Abacus.exchange.dydx.abacus.output.Notification;
// ------ Restrictions ------ //
export type UsageRestriction = Abacus.exchange.dydx.abacus.output.UsageRestriction;
export const RestrictionType = Abacus.exchange.dydx.abacus.output.Restriction;
const restrictionTypes = [...RestrictionType.values()] as const;
export type RestrictionTypes = (typeof restrictionTypes)[number];
// ------ Enum Conversions ------ //
type IfEquals<X, Y, A, B> = (<T>() => T extends X ? 1 : 2) extends <T>() => T extends Y ? 1 : 2
? A
@@ -257,20 +256,3 @@ export const TRADE_TYPES: Record<
[AbacusOrderType.liquidation.name]: null,
[AbacusOrderType.trailingStop.name]: null,
};
// Custom types involving Abacus
export type NetworkConfig = Partial<{
indexerUrl: Nullable<string>;
websocketUrl: Nullable<string>;
validatorUrl: Nullable<string>;
chainId: Nullable<string>;
faucetUrl: Nullable<string>;
USDC_DENOM: Nullable<string>;
USDC_DECIMALS: Nullable<number>;
USDC_GAS_DENOM: Nullable<string>;
CHAINTOKEN_DENOM: Nullable<string>;
CHAINTOKEN_DECIMALS: Nullable<number>;
}>;
export type ConnectNetworkEvent = CustomEvent<Partial<NetworkConfig>>;
-3
View File
@@ -10,10 +10,7 @@ export enum DialogTypes {
MobileSignIn = 'MobileSignIn',
Onboarding = 'Onboarding',
OrderDetails = 'OrderDetails',
RateLimit = 'RateLimit',
Receive = 'Receive',
RestrictedGeo = 'RestrictedGeo',
RestrictedWallet = 'RestrictedWallet',
Trade = 'Trade',
Transfer = 'Transfer',
Withdraw = 'Withdraw',
+1 -1
View File
@@ -24,6 +24,6 @@ export enum LocalStorageKey {
}
export const LOCAL_STORAGE_VERSIONS = {
[LocalStorageKey.EvmDerivedAddresses]: 'v2',
[LocalStorageKey.EvmDerivedAddresses]: 'v1',
// TODO: version all localStorage keys
};
+1 -2
View File
@@ -7,8 +7,7 @@ export enum AppRoute {
Profile = '/profile',
Alerts = '/alerts',
Settings = '/settings',
Terms = '/terms',
Privacy = '/privacy',
Rewards = '/DV4TNT',
}
export enum PortfolioRoute {
+28 -38
View File
@@ -1,5 +1,5 @@
import type { ExternalProvider } from '@ethersproject/providers';
import { type onboarding } from '@dydxprotocol/v4-client-js';
import { USDC_DENOM, type onboarding, DYDX_DENOM } from '@dydxprotocol/v4-client-js';
import type { suggestChain } from 'graz';
import { STRING_KEYS } from '@/constants/localization';
@@ -92,24 +92,6 @@ export enum WalletType {
OtherWallet = 'OTHER_WALLET',
}
const WALLET_CONNECT_EXPLORER_RECOMMENDED_WALLETS = {
Metamask: 'c57ca95b47569778a828d19178114f4db188b89b763c899ba0be274e97267d96',
imToken: 'ef333840daf915aafdc4a004525502d6d49d77bd9c65e0642dbaefb3c2893bef',
TokenPocket: '20459438007b75f4f4acb98bf29aa3b800550309646d375da5fd4aac6c2a2c66',
Trust: '4622a2b2d6af1c9844944291e5e7351a6aa24cd7b23099efac1b2fd875da31a0',
Rainbow: '1ae92b26df02f0abca6304df07debccd18262fdf5fe82daa81593582dac9a369',
Zerion: 'ecc4036f814562b41a5268adc86270fba1365471402006302e70169465b7ac18',
Ledger: '19177a98252e07ddfc9af2083ba8e07ef627cb6103467ffebb3f8f4205fd7927',
Fireblocks: '5864e2ced7c293ed18ac35e0db085c09ed567d67346ccb6f58a0327a75137489',
Uniswap: 'c03dfee351b6fcc421b4494ea33b9d4b92a984f87aa76d1663bb28705e95034a',
Robinhood: '8837dd9413b1d9b585ee937d27a816590248386d9dbf59f5cd3422dbbb65683e',
'1inch': 'c286eebc742a537cd1d6818363e9dc53b21759a1e8e5d9b263d0c03ec7703576',
};
export const WALLET_CONNECT_EXPLORER_RECOMMENDED_IDS = Object.values(
WALLET_CONNECT_EXPLORER_RECOMMENDED_WALLETS
);
type WalletConfig = {
type: WalletType;
stringKey: string;
@@ -143,6 +125,7 @@ export const wallets: Record<WalletType, WalletConfig> = {
icon: BitkeepIcon,
connectionTypes: [WalletConnectionType.InjectedEip1193, WalletConnectionType.WalletConnect2],
matchesInjectedEip1193: (provider) => provider.isBitKeep, // isBitKeepChrome, isBitEthereum
walletconnect2Id: '38f5d18bd8522c244bdd70cb4a68e0e718865155811c043f052fb9f1c51de662',
},
[WalletType.BitPie]: {
type: WalletType.BitPie,
@@ -175,6 +158,7 @@ export const wallets: Record<WalletType, WalletConfig> = {
icon: Coin98Icon,
connectionTypes: [WalletConnectionType.InjectedEip1193, WalletConnectionType.WalletConnect2],
matchesInjectedEip1193: (provider) => provider.isCoin98,
walletconnect2Id: '2a3c89040ac3b723a1972a33a125b1db11e258a6975d3a61252cd64e6ea5ea01',
},
[WalletType.HuobiWallet]: {
type: WalletType.HuobiWallet,
@@ -182,6 +166,7 @@ export const wallets: Record<WalletType, WalletConfig> = {
icon: HuobiIcon,
connectionTypes: [WalletConnectionType.InjectedEip1193, WalletConnectionType.WalletConnect2],
matchesInjectedEip1193: (provider) => provider.isHbWallet,
walletconnect2Id: '797c615e2c556b610c048eb35535f212c0dd58de5d03e763120e90a7d1350a77',
},
[WalletType.ImToken]: {
type: WalletType.ImToken,
@@ -189,7 +174,7 @@ export const wallets: Record<WalletType, WalletConfig> = {
icon: ImTokenIcon,
connectionTypes: [WalletConnectionType.InjectedEip1193, WalletConnectionType.WalletConnect2],
matchesInjectedEip1193: (provider) => provider.isImToken,
walletconnect2Id: WALLET_CONNECT_EXPLORER_RECOMMENDED_WALLETS.imToken,
walletconnect2Id: 'ef333840daf915aafdc4a004525502d6d49d77bd9c65e0642dbaefb3c2893bef',
},
[WalletType.MathWallet]: {
type: WalletType.MathWallet,
@@ -205,7 +190,7 @@ export const wallets: Record<WalletType, WalletConfig> = {
icon: MetaMaskIcon,
connectionTypes: [WalletConnectionType.InjectedEip1193, WalletConnectionType.WalletConnect2],
matchesInjectedEip1193: isMetaMask,
walletconnect2Id: WALLET_CONNECT_EXPLORER_RECOMMENDED_WALLETS.Metamask,
walletconnect2Id: 'c57ca95b47569778a828d19178114f4db188b89b763c899ba0be274e97267d96',
},
[WalletType.Rainbow]: {
type: WalletType.Rainbow,
@@ -213,7 +198,7 @@ export const wallets: Record<WalletType, WalletConfig> = {
icon: RainbowIcon,
connectionTypes: [WalletConnectionType.InjectedEip1193, WalletConnectionType.WalletConnect2],
matchesInjectedEip1193: (provider) => provider.isRainbowWallet,
walletconnect2Id: WALLET_CONNECT_EXPLORER_RECOMMENDED_WALLETS.Rainbow,
walletconnect2Id: '1ae92b26df02f0abca6304df07debccd18262fdf5fe82daa81593582dac9a369',
},
[WalletType.TokenPocket]: {
type: WalletType.TokenPocket,
@@ -221,7 +206,7 @@ export const wallets: Record<WalletType, WalletConfig> = {
icon: TokenPocketIcon,
connectionTypes: [WalletConnectionType.InjectedEip1193, WalletConnectionType.WalletConnect2],
matchesInjectedEip1193: (provider) => provider.isTokenPocket,
walletconnect2Id: WALLET_CONNECT_EXPLORER_RECOMMENDED_WALLETS.TokenPocket,
walletconnect2Id: '20459438007b75f4f4acb98bf29aa3b800550309646d375da5fd4aac6c2a2c66',
},
[WalletType.TrustWallet]: {
type: WalletType.TrustWallet,
@@ -229,7 +214,7 @@ export const wallets: Record<WalletType, WalletConfig> = {
icon: TrustWalletIcon,
connectionTypes: [WalletConnectionType.InjectedEip1193, WalletConnectionType.WalletConnect2],
matchesInjectedEip1193: (provider) => provider.isTrust,
walletconnect2Id: WALLET_CONNECT_EXPLORER_RECOMMENDED_WALLETS.Trust,
walletconnect2Id: '4622a2b2d6af1c9844944291e5e7351a6aa24cd7b23099efac1b2fd875da31a0',
},
[WalletType.WalletConnect2]: {
type: WalletType.WalletConnect2,
@@ -302,10 +287,10 @@ export type DydxAddress = `dydx${string}`;
export const DYDX_CHAIN_INFO: Parameters<typeof suggestChain>[0] = {
rpc: 'https://dydx-testnet-archive.allthatnode.com:26657',
rest: 'https://dydx-testnet-archive.allthatnode.com:1317',
chainId: 'dydx-testnet-4',
chainId: 'dydx-testnet-3',
chainName: 'dYdX Public Testnet',
chainSymbolImageUrl:
'https://raw.githubusercontent.com/chainapsis/keplr-chain-registry/main/images/dydx-testnet-4/chain.png',
'https://raw.githubusercontent.com/chainapsis/keplr-chain-registry/main/images/dydx-testnet-3/chain.png',
bech32Config: {
bech32PrefixAccPub: 'dydxpub',
bech32PrefixValPub: 'dydxvaloperpub',
@@ -319,31 +304,26 @@ export const DYDX_CHAIN_INFO: Parameters<typeof suggestChain>[0] = {
},
stakeCurrency: {
coinDenom: 'DV4TNT',
coinDecimals: 18,
coinMinimalDenom: 'adv4tnt',
coinDecimals: 6,
coinMinimalDenom: 'dv4tnt',
},
currencies: [
{
coinDenom: 'DV4TNT',
coinDecimals: 18,
coinMinimalDenom: 'adv4tnt',
coinDecimals: 6,
coinMinimalDenom: 'dv4tnt',
},
{
coinDenom: 'USDC',
coinDecimals: 6,
coinMinimalDenom: 'ibc/8E27BA2D5493AF5636760E354E46004562C46AB7EC0CC4C1CA14E9E20E2545B5',
coinDecimals: 6,
},
],
feeCurrencies: [
{
coinDenom: 'DV4TNT',
coinDecimals: 18,
coinMinimalDenom: 'adv4tnt',
},
{
coinDenom: 'USDC',
coinDecimals: 6,
coinMinimalDenom: 'ibc/8E27BA2D5493AF5636760E354E46004562C46AB7EC0CC4C1CA14E9E20E2545B5',
coinMinimalDenom: 'dv4tnt',
},
],
features: [],
@@ -352,5 +332,15 @@ export const DYDX_CHAIN_INFO: Parameters<typeof suggestChain>[0] = {
// TODO: export this type from abacus instead
export enum DydxChainAsset {
USDC = 'usdc',
CHAINTOKEN = 'chain',
DYDX = 'dydx',
}
export const DYDX_CHAIN_ASSET_COIN_DENOM: Record<DydxChainAsset, string> = {
[DydxChainAsset.USDC]: USDC_DENOM,
[DydxChainAsset.DYDX]: DYDX_DENOM,
};
export const DYDX_CHAIN_ASSET_TAGS: Record<DydxChainAsset, string> = {
[DydxChainAsset.USDC]: 'USDC',
[DydxChainAsset.DYDX]: 'Dv4TNT',
};
-4
View File
@@ -1,6 +1,5 @@
import { useApiState } from './useApiState';
import { useBreakpoints } from './useBreakpoints';
import { useTokenConfigs } from './useTokenConfigs';
import { useCommandMenu } from './useCommandMenu';
import { useCurrentMarketId } from './useCurrentMarketId';
import { useDebounce } from './useDebounce';
@@ -17,7 +16,6 @@ import { useLocalStorage } from './useLocalStorage';
import { useNow } from './useNow';
import { useOnClickOutside } from './useOnClickOutside';
import { usePageTitlePriceUpdates } from './usePageTitlePriceUpdates';
import { useRestrictions } from './useRestrictions';
import { useShouldShowFooter } from './useShouldShowFooter';
import { useSelectedNetwork } from './useSelectedNetwork';
import { useStringGetter } from './useStringGetter';
@@ -26,7 +24,6 @@ import { useSubaccount } from './useSubaccount';
export {
useApiState,
useBreakpoints,
useTokenConfigs,
useCommandMenu,
useCurrentMarketId,
useDebounce,
@@ -43,7 +40,6 @@ export {
useNow,
useOnClickOutside,
usePageTitlePriceUpdates,
useRestrictions,
useShouldShowFooter,
useSelectedNetwork,
useStringGetter,
+3 -3
View File
@@ -33,7 +33,7 @@ export const useTradingView = ({
const marketIds = useSelector(getMarketIds, shallowEqual);
const selectedLocale = useSelector(getSelectedLocale);
const selectedNetwork = useSelector(getSelectedNetwork);
const { getCandlesForDatafeed, isConnected: isClientConnected } = useDydxClient();
const { getCandlesForDatafeed } = useDydxClient();
const [savedTvChartConfig, setTvChartConfig] = useLocalStorage<object | undefined>({
key: LocalStorageKey.TradingViewChartConfig,
@@ -44,7 +44,7 @@ export const useTradingView = ({
const hasMarkets = marketIds.length > 0;
useEffect(() => {
if (hasMarkets && isClientConnected) {
if (hasMarkets) {
const widgetOptions = getWidgetOptions();
const widgetOverrides = getWidgetOverrides(appTheme);
const options = {
@@ -75,7 +75,7 @@ export const useTradingView = ({
tvWidgetRef.current = null;
setIsChartReady(false);
};
}, [getCandlesForDatafeed, isClientConnected, hasMarkets, selectedLocale, selectedNetwork]);
}, [getCandlesForDatafeed, hasMarkets, selectedLocale, selectedNetwork]);
return { savedResolution };
};
+12 -8
View File
@@ -5,6 +5,8 @@ import { StargateClient } from '@cosmjs/stargate';
import { useQuery } from 'react-query';
import { formatUnits } from 'viem';
import { USDC_DENOM, DYDX_DENOM } from '@dydxprotocol/v4-client-js';
import { ENVIRONMENT_CONFIG_MAP } from '@/constants/networks';
import { QUANTUM_MULTIPLIER } from '@/constants/numbers';
import { EvmAddress } from '@/constants/wallets';
@@ -16,7 +18,6 @@ import { getBalances, getStakingBalances } from '@/state/accountSelectors';
import { getSelectedNetwork } from '@/state/appSelectors';
import { useAccounts } from './useAccounts';
import { useTokenConfigs } from './useTokenConfigs';
type UseAccountBalanceProps = {
// Token Items
@@ -51,7 +52,6 @@ export const useAccountBalance = ({
const selectedNetwork = useSelector(getSelectedNetwork);
const balances = useSelector(getBalances, shallowEqual);
const { chainTokenDenom, usdcDenom } = useTokenConfigs();
const evmChainId = Number(ENVIRONMENT_CONFIG_MAP[selectedNetwork].ethereumChainId);
const stakingBalances = useSelector(getStakingBalances, shallowEqual);
@@ -93,14 +93,18 @@ export const useAccountBalance = ({
const { formatted: evmBalance } = evmQuery.data || {};
const balance = !assetSymbol ? '0' : isCosmosChain ? cosmosQuery.data : evmBalance;
const nativeTokenCoinBalance = balances?.[chainTokenDenom];
const nativeTokenBalance = MustBigNumber(nativeTokenCoinBalance?.amount);
const nativeTokenCoinBalance = balances?.[DYDX_DENOM];
const nativeTokenBalance = MustBigNumber(nativeTokenCoinBalance?.amount)
.div(QUANTUM_MULTIPLIER)
.toNumber();
const usdcCoinBalance = balances?.[usdcDenom];
const usdcBalance = MustBigNumber(usdcCoinBalance?.amount).toNumber();
const usdcCoinBalance = balances?.[USDC_DENOM];
const usdcBalance = MustBigNumber(usdcCoinBalance?.amount).div(QUANTUM_MULTIPLIER).toNumber();
const nativeStakingCoinBalanace = stakingBalances?.[chainTokenDenom];
const nativeStakingBalance = MustBigNumber(nativeStakingCoinBalanace?.amount).toNumber();
const nativeStakingCoinBalanace = stakingBalances?.[DYDX_DENOM];
const nativeStakingBalance = MustBigNumber(nativeStakingCoinBalanace?.amount)
.div(QUANTUM_MULTIPLIER)
.toNumber();
return {
balance,
+15 -24
View File
@@ -2,23 +2,21 @@ import { useCallback, useContext, createContext, useEffect, useState, useMemo }
import { useDispatch } from 'react-redux';
import { AES, enc } from 'crypto-js';
import { LocalWallet, type Subaccount } from '@dydxprotocol/v4-client-js';
import { LocalWallet, USDC_DENOM, type Subaccount } from '@dydxprotocol/v4-client-js';
import { OnboardingGuard, OnboardingState, type EvmDerivedAddresses } from '@/constants/account';
import { DialogTypes } from '@/constants/dialogs';
import { LocalStorageKey, LOCAL_STORAGE_VERSIONS } from '@/constants/localStorage';
import { DydxAddress, EvmAddress, PrivateInformation } from '@/constants/wallets';
import { setOnboardingState, setOnboardingGuard } from '@/state/account';
import { forceOpenDialog } from '@/state/dialogs';
import abacusStateManager from '@/lib/abacus';
import { log } from '@/lib/telemetry';
import { useDydxClient } from './useDydxClient';
import { useLocalStorage } from './useLocalStorage';
import { useRestrictions } from './useRestrictions';
import { useWalletConnection } from './useWalletConnection';
import { useDydxClient } from './useDydxClient';
const AccountsContext = createContext<ReturnType<typeof useAccountsContext> | undefined>(undefined);
@@ -59,9 +57,7 @@ const useAccountsContext = () => {
forgetEvmSignature(previousEvmAddress);
}
if (evmAddress) {
abacusStateManager.setTransfersSourceAddress(evmAddress);
}
if (evmAddress) abacusStateManager.setTransfersSourceAddress(evmAddress);
setPreviousEvmAddress(evmAddress);
}, [evmAddress]);
@@ -130,8 +126,16 @@ const useAccountsContext = () => {
// dYdX subaccounts
const [dydxSubaccounts, setDydxSubaccounts] = useState<Subaccount[] | undefined>();
const { getSubaccounts } = useMemo(
const { getAccountBalance, getSubaccounts } = useMemo(
() => ({
getAccountBalance: async ({
dydxAddress,
denom = USDC_DENOM,
}: {
dydxAddress: DydxAddress;
denom?: string;
}) => await compositeClient?.validatorClient.get.getAccountBalance(dydxAddress, denom),
getSubaccounts: async ({ dydxAddress }: { dydxAddress: DydxAddress }) => {
try {
const response = await compositeClient?.indexerClient.account.getSubaccounts(dydxAddress);
@@ -213,6 +217,7 @@ const useAccountsContext = () => {
}, [evmAddress, evmDerivedAddresses, signerWagmi, connectedDydxAddress, signerGraz]);
// abacus
// TODO: useAbacus({ dydxAddress })
useEffect(() => {
if (dydxAddress) abacusStateManager.setAccount(localDydxWallet);
else abacusStateManager.attemptDisconnectAccount();
@@ -253,21 +258,6 @@ const useAccountsContext = () => {
);
}, [dydxSubaccounts]);
// Restrictions
const { isBadActor, sanctionedAddresses } = useRestrictions();
useEffect(() => {
if (
dydxAddress &&
(isBadActor ||
sanctionedAddresses.has(dydxAddress) ||
(evmAddress && sanctionedAddresses.has(evmAddress)))
) {
dispatch(forceOpenDialog({ type: DialogTypes.RestrictedWallet }));
disconnect();
}
}, [isBadActor, evmAddress, dydxAddress, sanctionedAddresses]);
// Disconnect wallet / accounts
const disconnectLocalDydxWallet = () => {
setLocalDydxWallet(undefined);
@@ -318,6 +308,7 @@ const useAccountsContext = () => {
disconnect,
// dydxClient Account methods
getAccountBalance,
getSubaccounts,
};
};
+2 -5
View File
@@ -44,9 +44,6 @@ export const useCurrentMarketId = () => {
}, [validId]);
useEffect(() => {
// Check for marketIds otherwise Abacus will silently fail its isMarketValid check
if (marketIds) {
abacusStateManager.setMarket(marketId ?? DEFAULT_MARKETID);
}
}, [selectedNetwork, marketIds, marketId]);
abacusStateManager.setMarket(marketId ?? DEFAULT_MARKETID);
}, [selectedNetwork, marketId]);
};
+6 -41
View File
@@ -13,17 +13,12 @@ import {
import type { ResolutionString } from 'public/tradingview/charting_library';
import type { ConnectNetworkEvent, NetworkConfig } from '@/constants/abacus';
import type { NetworkConfig, ConnectNetworkEvent } from '@/constants/abacus';
import { type Candle, RESOLUTION_MAP } from '@/constants/candles';
import { ENVIRONMENT_CONFIG_MAP } from '@/constants/networks';
import { DydxChainAsset } from '@/constants/wallets';
import { getSelectedNetwork } from '@/state/appSelectors';
import { log } from '@/lib/telemetry';
import { useRestrictions } from './useRestrictions';
type DydxContextType = ReturnType<typeof useDydxClientContext>;
const DydxContext = createContext<DydxContextType>({} as DydxContextType);
DydxContext.displayName = 'dYdXClient';
@@ -38,9 +33,8 @@ const useDydxClientContext = () => {
// ------ Network ------ //
const selectedNetwork = useSelector(getSelectedNetwork);
const tokensConfigs = ENVIRONMENT_CONFIG_MAP[selectedNetwork].tokens;
const [networkConfig, setNetworkConfig] = useState<NetworkConfig>();
const [networkConfig, setNetworkConfig] = useState<Partial<NetworkConfig>>();
useEffect(() => {
const onConnectNetwork = (event: ConnectNetworkEvent) => setNetworkConfig(event.detail);
@@ -60,22 +54,15 @@ const useDydxClientContext = () => {
if (
networkConfig?.chainId &&
networkConfig?.indexerUrl &&
networkConfig?.websocketUrl &&
networkConfig?.indexerSocketUrl &&
networkConfig?.validatorUrl
) {
try {
const initializedClient = await CompositeClient.connect(
new Network(
selectedNetwork,
new IndexerConfig(networkConfig.indexerUrl, networkConfig.websocketUrl),
new ValidatorConfig(networkConfig.validatorUrl, networkConfig.chainId,
{
USDC_DENOM: tokensConfigs[DydxChainAsset.USDC].denom,
USDC_DECIMALS: tokensConfigs[DydxChainAsset.USDC].decimals,
USDC_GAS_DENOM: tokensConfigs[DydxChainAsset.USDC].gasDenom,
CHAINTOKEN_DENOM: tokensConfigs[DydxChainAsset.CHAINTOKEN].denom,
CHAINTOKEN_DECIMALS: tokensConfigs[DydxChainAsset.CHAINTOKEN].decimals,
}, {
new IndexerConfig(networkConfig.indexerUrl, networkConfig.indexerSocketUrl),
new ValidatorConfig(networkConfig.validatorUrl, networkConfig.chainId, {
broadcastPollIntervalMs: 3_000,
broadcastTimeoutMs: 60_000,
})
@@ -191,27 +178,7 @@ const useDydxClientContext = () => {
[requestCandles]
);
const { updateSanctionedAddresses } = useRestrictions();
const screenAddresses = useCallback(
async ({ addresses }: { addresses: string[] }) => {
if (compositeClient) {
const promises = addresses.map((address) =>
compositeClient.indexerClient.utility.screen(address)
);
const results = await Promise.all(promises);
const screenedAddresses = Object.fromEntries(
addresses.map((address, index) => [address, results[index]?.restricted])
);
updateSanctionedAddresses(screenedAddresses);
return screenedAddresses;
}
},
[compositeClient]
);
// ------ Subacount Methods ------ //
return {
// Client initialization
@@ -219,13 +186,11 @@ const useDydxClientContext = () => {
networkConfig,
compositeClient,
faucetClient,
isConnected: !!compositeClient,
// Wallet Methods
getWalletFromEvmSignature,
// Public Methods
getCandlesForDatafeed,
screenAddresses,
};
};
-2
View File
@@ -10,7 +10,6 @@ import { useLocalStorage } from '@/hooks';
import { initializeLocalization } from '@/state/app';
import abacusStateManager from '@/lib/abacus';
import { validateAgainstAvailableEnvironments } from '@/lib/network';
export const useInitializePage = () => {
const dispatch = useDispatch();
@@ -19,7 +18,6 @@ export const useInitializePage = () => {
const [localStorageNetwork] = useLocalStorage<DydxNetwork>({
key: LocalStorageKey.SelectedNetwork,
defaultValue: DEFAULT_APP_ENVIRONMENT,
validateFn: validateAgainstAvailableEnvironments,
});
useEffect(() => {
+20 -36
View File
@@ -4,14 +4,15 @@ import { useSelector, shallowEqual, useDispatch } from 'react-redux';
import { groupBy } from 'lodash';
import { AlertType } from '@/constants/alerts';
import { AbacusOrderStatus, ORDER_SIDES } from '@/constants/abacus';
import { AbacusOrderStatus, ORDER_SIDES, ORDER_STATUS_STRINGS } from '@/constants/abacus';
import { DialogTypes } from '@/constants/dialogs';
import { STRING_KEYS, StringKey } from '@/constants/localization';
import { STRING_KEYS } from '@/constants/localization';
import { type NotificationTypeConfig, NotificationType } from '@/constants/notifications';
import { ORDER_SIDE_STRINGS } from '@/constants/trade';
import { ORDER_SIDE_STRINGS, TRADE_TYPE_STRINGS, TradeTypes } from '@/constants/trade';
import { useLocalNotifications } from '@/hooks/useLocalNotifications';
import { AlertMessage } from '@/components/AlertMessage';
import { Icon, IconName } from '@/components/Icon';
import { Output, OutputType } from '@/components/Output';
import { TransferStatusToast } from '@/views/TransferStatus';
@@ -68,11 +69,11 @@ export const notificationTypes = [
<OrderStatusIcon status={order.status} totalFilled={order.totalFilled ?? 0} />
),
title: `${stringGetter({
key: order.resources.typeStringKey as StringKey,
key: TRADE_TYPE_STRINGS[order.type.rawValue as TradeTypes].tradeTypeKey,
})} ${
order.status === AbacusOrderStatus.open && (order?.totalFilled ?? 0) > 0
? stringGetter({ key: STRING_KEYS.PARTIALLY_FILLED })
: stringGetter({ key: order.resources.statusStringKey as StringKey })
: stringGetter({ key: ORDER_STATUS_STRINGS[order.status.name] })
}`,
description: `${stringGetter({
key: ORDER_SIDE_STRINGS[ORDER_SIDES[order.side.name]],
@@ -90,34 +91,18 @@ export const notificationTypes = [
}, [orderIds]);
},
// useNotificationAction: () => {
// const dispatch = useDispatch();
// const orders = useSelector(getSubaccountOrders, shallowEqual) || [];
// const ordersByOrderId = Object.fromEntries(orders.map((order) => [order.id, order]));
useNotificationAction: () => {
const dispatch = useDispatch();
// const fills = useSelector(getSubaccountFills, shallowEqual) || [];
// const fillsByOrderId = groupBy(fills, (fill) => fill.orderId);
// return (id) => {
// if (ordersByOrderId[id]) {
// dispatch(
// openDialog({
// type: DialogTypes.OrderDetails,
// dialogProps: { orderId: id },
// })
// );
// } else if (fillsByOrderId[id]) {
// const fillId = fillsByOrderId[id][0].id;
// dispatch(
// openDialog({
// type: DialogTypes.FillDetails,
// dialogProps: { fillId },
// })
// );
// }
// };
// },
return (orderId) => {
dispatch(
openDialog({
type: DialogTypes.OrderDetails,
dialogProps: { orderId },
})
);
};
},
} as NotificationTypeConfig<string, [string, number]>,
{
type: NotificationType.SquidTransfer,
@@ -153,8 +138,7 @@ export const notificationTypes = [
{stringGetter({
key: STRING_KEYS.SOMETHING_WENT_WRONG_WITH_MESSAGE,
params: {
ERROR_MESSAGE:
error.message || stringGetter({ key: STRING_KEYS.UNKNOWN_ERROR }),
ERROR_MESSAGE: error.message || stringGetter({ key: STRING_KEYS.UNKNOWN_ERROR }),
},
})}
</Styled.ErrorMessage>
@@ -198,8 +182,8 @@ Styled.TransferText = styled.span`
display: inline-flex;
align-items: center;
gap: 0.5ch;
`;
`
Styled.ErrorMessage = styled.div`
max-width: 13rem;
`;
`;
-53
View File
@@ -1,53 +0,0 @@
import { createContext, useCallback, useContext, useEffect, useMemo, useState } from 'react';
import { shallowEqual, useDispatch, useSelector } from 'react-redux';
import { RestrictionType } from '@/constants/abacus';
import { DialogTypes } from '@/constants/dialogs';
import { getRestrictionType } from '@/state/accountSelectors';
import { forceOpenDialog } from '@/state/dialogs';
import { isTruthy } from '@/lib/isTruthy';
const useRestrictionContext = () => {
const dispatch = useDispatch();
const restrictionType = useSelector(getRestrictionType, shallowEqual);
const [sanctionedAddresses, setSanctionedAddresses] = useState<string[]>([]);
useEffect(() => {
if (restrictionType === RestrictionType.GEO_RESTRICTED) {
dispatch(
forceOpenDialog({ type: DialogTypes.RestrictedGeo, dialogProps: { preventClose: true } })
);
}
}, [restrictionType, dispatch]);
const updateSanctionedAddresses = useCallback(
(screenedAddresses: { [address: string]: boolean }) => {
const toAdd = Object.entries(screenedAddresses)
.filter(([, isSanctioned]) => isSanctioned)
.map(([address]) => address);
if (toAdd.length) {
setSanctionedAddresses([...sanctionedAddresses, ...toAdd]);
}
},
[sanctionedAddresses]
);
return {
isBadActor: restrictionType === RestrictionType.USER_RESTRICTED,
isGeoRestricted: restrictionType === RestrictionType.GEO_RESTRICTED,
updateSanctionedAddresses,
sanctionedAddresses: useMemo(() => new Set(sanctionedAddresses), [sanctionedAddresses]),
};
};
type RestrictionContextType = ReturnType<typeof useRestrictionContext>;
const RestrictionContext = createContext<RestrictionContextType>({} as RestrictionContextType);
RestrictionContext.displayName = 'Restriction';
export const RestrictionProvider = ({ ...props }) => (
<RestrictionContext.Provider value={useRestrictionContext()} {...props} />
);
export const useRestrictions = () => useContext(RestrictionContext);
+1 -4
View File
@@ -2,15 +2,13 @@ import { useCallback } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { LocalStorageKey } from '@/constants/localStorage';
import { DEFAULT_APP_ENVIRONMENT, DydxNetwork, ENVIRONMENT_CONFIG_MAP } from '@/constants/networks';
import { DEFAULT_APP_ENVIRONMENT, DydxNetwork } from '@/constants/networks';
import { useAccounts, useLocalStorage } from '@/hooks';
import { setSelectedNetwork } from '@/state/app';
import { getSelectedNetwork } from '@/state/appSelectors';
import { validateAgainstAvailableEnvironments } from '@/lib/network';
export const useSelectedNetwork = (): {
switchNetwork: (network: DydxNetwork) => void;
selectedNetwork: DydxNetwork;
@@ -22,7 +20,6 @@ export const useSelectedNetwork = (): {
const [, setLocalStorageNetwork] = useLocalStorage<DydxNetwork>({
key: LocalStorageKey.SelectedNetwork,
defaultValue: DEFAULT_APP_ENVIRONMENT,
validateFn: validateAgainstAvailableEnvironments,
});
const switchNetwork = useCallback(
+18 -23
View File
@@ -3,10 +3,15 @@ import { shallowEqual, useSelector, useDispatch } from 'react-redux';
import type { Nullable } from '@dydxprotocol/v4-abacus';
import Long from 'long';
import type { IndexedTx } from '@cosmjs/stargate';
import type { EncodeObject } from '@cosmjs/proto-signing';
import type { EncodeObject, Coin } from '@cosmjs/proto-signing';
import { Method } from '@cosmjs/tendermint-rpc';
import { type LocalWallet, SubaccountClient } from '@dydxprotocol/v4-client-js';
import {
type LocalWallet,
SubaccountClient,
DYDX_DENOM,
USDC_DENOM,
} from '@dydxprotocol/v4-client-js';
import type {
AccountBalance,
@@ -29,9 +34,9 @@ import { MustBigNumber } from '@/lib/numbers';
import { log } from '@/lib/telemetry';
import { useAccounts } from './useAccounts';
import { useTokenConfigs } from './useTokenConfigs';
import { useDydxClient } from './useDydxClient';
type SubaccountContextType = ReturnType<typeof useSubaccountContext>;
const SubaccountContext = createContext<SubaccountContextType>({} as SubaccountContextType);
SubaccountContext.displayName = 'Subaccount';
@@ -48,7 +53,6 @@ export const useSubaccount = () => useContext(SubaccountContext);
export const useSubaccountContext = ({ localDydxWallet }: { localDydxWallet?: LocalWallet }) => {
const dispatch = useDispatch();
const { usdcDenom } = useTokenConfigs();
const { compositeClient, faucetClient } = useDydxClient();
const { getFaucetFunds } = useMemo(
@@ -88,7 +92,7 @@ export const useSubaccountContext = ({ localDydxWallet }: { localDydxWallet?: Lo
}: {
subaccountClient: SubaccountClient;
amount: number;
}) => await compositeClient?.withdrawFromSubaccount(subaccountClient, amount.toString()),
}) => await compositeClient?.withdrawFromSubaccount(subaccountClient, amount),
transferFromSubaccountToAddress: async ({
subaccountClient,
@@ -131,21 +135,12 @@ export const useSubaccountContext = ({ localDydxWallet }: { localDydxWallet?: Lo
amount: number;
recipient: string;
}) =>
await compositeClient?.validatorClient.post.send(
subaccountClient.wallet,
() =>
new Promise((resolve) => {
const msg = compositeClient?.sendTokenMessage(
subaccountClient.wallet,
amount.toString(),
recipient,
);
resolve([msg]);
}),
await compositeClient?.validatorClient.post.sendToken(
subaccountClient,
recipient,
DYDX_DENOM,
Long.fromNumber(amount * QUANTUM_MULTIPLIER),
false,
compositeClient?.validatorClient?.post.defaultDydxGasPrice,
undefined,
Method.BroadcastTxCommit
),
@@ -162,7 +157,7 @@ export const useSubaccountContext = ({ localDydxWallet }: { localDydxWallet?: Lo
const transaction = JSON.parse(payload);
const msg = compositeClient.withdrawFromSubaccountMessage(subaccountClient, amount.toString());
const msg = compositeClient.withdrawFromSubaccountMessage(subaccountClient, amount);
const ibcMsg: EncodeObject = {
typeUrl: transaction.msgTypeUrl,
value: transaction.msg,
@@ -216,7 +211,7 @@ export const useSubaccountContext = ({ localDydxWallet }: { localDydxWallet?: Lo
);
const balances = useSelector(getBalances, shallowEqual);
const usdcCoinBalance = balances?.[usdcDenom];
const usdcCoinBalance = balances?.[USDC_DENOM];
useEffect(() => {
if (usdcCoinBalance) {
@@ -253,7 +248,8 @@ export const useSubaccountContext = ({ localDydxWallet }: { localDydxWallet?: Lo
if (!subaccountClient) {
return;
}
return (await (coinDenom === usdcDenom
return (await (coinDenom === USDC_DENOM
? transferFromSubaccountToAddress
: transferNativeToken)({ subaccountClient, amount, recipient })) as IndexedTx;
},
@@ -279,7 +275,6 @@ export const useSubaccountContext = ({ localDydxWallet }: { localDydxWallet?: Lo
await getFaucetFunds({ dydxAddress, subaccountNumber });
} catch (error) {
log('useSubaccount/getFaucetFunds', error);
throw error;
}
}, [dydxAddress, getFaucetFunds, subaccountNumber]);
-36
View File
@@ -1,36 +0,0 @@
import { ENVIRONMENT_CONFIG_MAP } from '@/constants/networks';
import { DydxChainAsset } from '@/constants/wallets';
import { useSelectedNetwork } from '@/hooks';
export const useTokenConfigs = (): {
tokensConfigs: {
[DydxChainAsset.USDC]: {
denom: string;
name: string;
decimals: number;
gasDenom?: string;
},
[DydxChainAsset.CHAINTOKEN]: {
denom: string;
name: string;
decimals: number;
gasDenom?: string;
},
};
usdcDenom: string;
usdcLabel: string;
chainTokenDenom: string;
chainTokenLabel: string;
} => {
const { selectedNetwork } = useSelectedNetwork();
const tokensConfigs = ENVIRONMENT_CONFIG_MAP[selectedNetwork].tokens;
return {
tokensConfigs,
usdcDenom: tokensConfigs[DydxChainAsset.USDC].denom,
usdcLabel: tokensConfigs[DydxChainAsset.USDC].name,
chainTokenDenom: tokensConfigs[DydxChainAsset.CHAINTOKEN].denom,
chainTokenLabel: tokensConfigs[DydxChainAsset.CHAINTOKEN].name,
};
};
+1 -10
View File
@@ -1,8 +1,6 @@
import { useCallback, useEffect, useState } from 'react';
import { useSelector } from 'react-redux';
import { LocalStorageKey } from '@/constants/localStorage';
import { ENVIRONMENT_CONFIG_MAP } from '@/constants/networks';
import {
type DydxAddress,
@@ -30,8 +28,6 @@ import {
WalletType as CosmosWalletType,
} from 'graz';
import { getSelectedNetwork } from '@/state/appSelectors';
import { resolveWagmiConnector } from '@/lib/wagmi';
import { getWalletConnection, parseWalletError } from '@/lib/wallet';
import { log } from '@/lib/telemetry';
@@ -88,9 +84,6 @@ export const useWalletConnection = () => {
// Wallet connection
const selectedNetwork = useSelector(getSelectedNetwork);
const walletConnectConfig = ENVIRONMENT_CONFIG_MAP[selectedNetwork].wallets.walletconnect;
const { connectAsync: connectWagmi } =
walletType && walletConnectionType
? useConnectWagmi({
@@ -99,7 +92,6 @@ export const useWalletConnection = () => {
walletConnection: {
type: walletConnectionType,
},
walletConnectConfig,
}),
})
: useConnectWagmi();
@@ -135,7 +127,6 @@ export const useWalletConnection = () => {
connector: resolveWagmiConnector({
walletType,
walletConnection,
walletConnectConfig,
}),
});
}
@@ -226,7 +217,7 @@ export const useWalletConnection = () => {
evmAddressWagmi,
signerWagmi,
publicClientWagmi,
// Wallet connection (Cosmos)
dydxAddress,
dydxAddressGraz,
-3
View File
@@ -1,3 +0,0 @@
<svg width="16" height="18" viewBox="0 0 16 18" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M10.3811 13.235C11.9338 13.0512 13.4593 12.6847 14.9261 12.1433C13.6839 10.7673 12.9975 8.97875 13.0003 7.125V6.54167V6.5C13.0003 5.17392 12.4735 3.90215 11.5358 2.96447C10.5981 2.02678 9.32636 1.5 8.00028 1.5C6.67419 1.5 5.40242 2.02678 4.46474 2.96447C3.52706 3.90215 3.00028 5.17392 3.00028 6.5V7.125C3.00279 8.97886 2.3161 10.7675 1.07361 12.1433C2.51778 12.6767 4.04027 13.0475 5.61944 13.235M10.3811 13.235C8.79943 13.4226 7.20112 13.4226 5.61944 13.235M10.3811 13.235C10.5012 13.6099 10.5311 14.0078 10.4683 14.3964C10.4055 14.785 10.2518 15.1533 10.0198 15.4713C9.78772 15.7893 9.48386 16.048 9.13293 16.2263C8.78201 16.4047 8.39392 16.4976 8.00028 16.4976C7.60663 16.4976 7.21854 16.4047 6.86762 16.2263C6.51669 16.048 6.21283 15.7893 5.98079 15.4713C5.74875 15.1533 5.59508 14.785 5.53229 14.3964C5.46949 14.0078 5.49936 13.6099 5.61944 13.235" stroke="currentColor" stroke-width="1.25" stroke-linecap="round" stroke-linejoin="round"/>
</svg>

Before

Width:  |  Height:  |  Size: 1.0 KiB

+1 -1
View File
@@ -1 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 22 24"><path fill="currentColor" d="M11 0C8.5 0 6.101.948 4.333 2.636 2.565 4.324 1.57 6.613 1.57 9v5.379l-1.11 1.06c-.22.21-.37.477-.43.768-.061.291-.03.593.089.867s.32.508.578.673c.259.165.562.253.873.253h18.86c.31 0 .614-.088.873-.253.258-.165.46-.399.578-.673.12-.274.15-.576.09-.867a1.48 1.48 0 0 0-.43-.768l-1.111-1.06V9c0-2.387-.993-4.676-2.762-6.364C15.9.948 13.501 0 11 0Zm0 24a4.83 4.83 0 0 1-3.334-1.318 4.399 4.399 0 0 1-1.38-3.182h9.428a4.399 4.399 0 0 1-1.38 3.182A4.83 4.83 0 0 1 11 24Z"/></svg>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 22 24"><path fill="currentColor" d="M11 0C8.5 0 6.101.948 4.333 2.636 2.565 4.324 1.57 6.613 1.57 9v5.379l-1.11 1.06c-.22.21-.37.477-.43.768-.061.291-.03.593.089.867s.32.508.578.673c.259.165.562.253.873.253h18.86c.31 0 .614-.088.873-.253.258-.165.46-.399.578-.673.12-.274.15-.576.09-.867a1.48 1.48 0 0 0-.43-.768l-1.111-1.06V9c0-2.387-.993-4.676-2.762-6.364C15.9.948 13.501 0 11 0Zm0 24a4.83 4.83 0 0 1-3.334-1.318 4.399 4.399 0 0 1-1.38-3.182h9.428a4.399 4.399 0 0 1-1.38 3.182A4.83 4.83 0 0 1 11 24Z"/></svg>

Before

Width:  |  Height:  |  Size: 564 B

After

Width:  |  Height:  |  Size: 563 B

-1
View File
@@ -2,7 +2,6 @@ export { default as AddressConnectorIcon } from './address-connector.svg';
export { default as ArrowIcon } from './arrow.svg';
export { default as Bar3Icon } from './bar3.svg';
export { default as BellIcon } from './bell.svg';
export { default as BellStrokeIcon } from './bell-stroke.svg';
export { default as BoxCloseIcon } from './box-close.svg';
export { default as CalculatorIcon } from './calculator.svg';
export { default as CaretIcon } from './caret-down.svg';
-6
View File
@@ -15,12 +15,9 @@ import { ExternalNavKeplrDialog } from '@/views/dialogs/ExternalNavKeplrDialog';
import { MnemonicExportDialog } from '@/views/dialogs/MnemonicExportDialog';
import { MobileSignInDialog } from '@/views/dialogs/MobileSignInDialog';
import { OnboardingDialog } from '@/views/dialogs/OnboardingDialog';
import { RateLimitDialog } from '@/views/dialogs/RateLimitDialog';
import { ReceiveDialog } from '@/views/dialogs/ReceiveDialog';
import { RestrictedGeoDialog } from '@/views/dialogs/RestrictedGeoDialog';
import { TradeDialog } from '@/views/dialogs/TradeDialog';
import { TransferDialog } from '@/views/dialogs/TransferDialog';
import { RestrictedWalletDialog } from '@/views/dialogs/RestrictedWalletDialog';
import { WithdrawDialog } from '@/views/dialogs/WithdrawDialog';
import { OrderDetailsDialog } from '@/views/dialogs/DetailsDialog/OrderDetailsDialog';
@@ -56,10 +53,7 @@ export const DialogManager = () => {
[DialogTypes.MobileSignIn]: <MobileSignInDialog {...modalProps} />,
[DialogTypes.Onboarding]: <OnboardingDialog {...modalProps} />,
[DialogTypes.OrderDetails]: <OrderDetailsDialog {...modalProps} />,
[DialogTypes.RateLimit]: <RateLimitDialog {...modalProps} />,
[DialogTypes.Receive]: <ReceiveDialog {...modalProps} />,
[DialogTypes.RestrictedGeo]: <RestrictedGeoDialog {...modalProps} />,
[DialogTypes.RestrictedWallet]: <RestrictedWalletDialog {...modalProps} />,
[DialogTypes.Trade]: <TradeDialog {...modalProps} />,
[DialogTypes.Transfer]: <TransferDialog {...modalProps} />,
[DialogTypes.Withdraw]: <WithdrawDialog {...modalProps} />,
+10 -15
View File
@@ -6,9 +6,8 @@ import { ButtonShape } from '@/constants/buttons';
import { DialogTypes } from '@/constants/dialogs';
import { STRING_KEYS } from '@/constants/localization';
import { AppRoute } from '@/constants/routes';
import { LogoShortIcon, BellStrokeIcon } from '@/icons';
import { useTokenConfigs, useStringGetter } from '@/hooks';
import { useStringGetter } from '@/hooks';
import { LogoShortIcon, BellIcon } from '@/icons';
import { Icon, IconName } from '@/components/Icon';
import { IconButton } from '@/components/IconButton';
@@ -28,7 +27,6 @@ import { layoutMixins } from '@/styles/layoutMixins';
export const HeaderDesktop = () => {
const stringGetter = useStringGetter();
const dispatch = useDispatch();
const { chainTokenLabel } = useTokenConfigs();
const navItems = [
{
@@ -45,9 +43,9 @@ export const HeaderDesktop = () => {
href: AppRoute.Trade,
},
{
value: chainTokenLabel,
label: chainTokenLabel,
href: `/${chainTokenLabel}`,
value: 'Dv4TNT',
label: 'Dv4TNT',
href: AppRoute.Rewards,
},
{
value: 'PORTFOLIO',
@@ -80,13 +78,13 @@ export const HeaderDesktop = () => {
value: 'TERMS_OF_USE',
slotBefore: <Icon iconName={IconName.File} />,
label: stringGetter({ key: STRING_KEYS.TERMS_OF_USE }),
href: AppRoute.Terms,
href: 'https://dydx.exchange/terms',
},
{
value: 'PRIVACY_POLICY',
slotBefore: <Icon iconName={IconName.Privacy} />,
label: stringGetter({ key: STRING_KEYS.PRIVACY_POLICY }),
href: AppRoute.Privacy,
href: 'https://dydx.exchange/privacy',
},
{
value: 'HELP',
@@ -133,9 +131,7 @@ export const HeaderDesktop = () => {
<VerticalSeparator />
<NotificationsMenu
slotTrigger={
<Styled.IconButton shape={ButtonShape.Rectangle} iconComponent={BellStrokeIcon} />
}
slotTrigger={<Styled.IconButton shape={ButtonShape.Rectangle} iconComponent={BellIcon} />}
/>
<VerticalSeparator />
@@ -169,7 +165,7 @@ Styled.Header = styled.header`
)
var(--border-width) 1fr var(--border-width) auto;
font-size: 0.9375rem;
font-size: 0.9375em;
:before {
backdrop-filter: blur(10px);
@@ -218,8 +214,7 @@ Styled.NavAfter = styled.div`
}
`;
Styled.IconButton = styled(IconButton)<{ size?: string }>`
Styled.IconButton = styled(IconButton)`
${headerMixins.button}
--button-border: none;
--button-icon-size: 1rem;
`;
+34 -49
View File
@@ -14,6 +14,8 @@ import {
OrderSide,
OrderTimeInForce,
OrderExecution,
DYDX_DENOM,
GAS_PRICE_DYDX_DENOM,
} from '@dydxprotocol/v4-client-js';
import {
@@ -59,42 +61,22 @@ class DydxChainTransactions implements AbacusDYDXChainTransactionsProtocol {
}
async connectNetwork(
paramsInJson: Nullable<string>,
indexerUrl: string,
indexerSocketUrl: string,
validatorUrl: string,
chainId: string,
faucetUrl: Nullable<string> | undefined,
callback: (p0: Nullable<string>) => void
): Promise<void> {
try {
const parsedParams = paramsInJson ? JSON.parse(paramsInJson) : {};
const {
indexerUrl,
websocketUrl,
validatorUrl,
chainId,
USDC_DENOM,
USDC_DECIMALS,
USDC_GAS_DENOM,
CHAINTOKEN_DENOM,
CHAINTOKEN_DECIMALS,
} = parsedParams;
const compositeClient = await CompositeClient.connect(
new Network(
chainId,
new IndexerConfig(indexerUrl, websocketUrl),
new ValidatorConfig(
validatorUrl,
chainId,
{
USDC_DENOM,
USDC_DECIMALS,
USDC_GAS_DENOM,
CHAINTOKEN_DENOM,
CHAINTOKEN_DECIMALS,
},
{
broadcastPollIntervalMs: 3_000,
broadcastTimeoutMs: 60_000,
}
)
new IndexerConfig(indexerUrl, indexerSocketUrl),
new ValidatorConfig(validatorUrl, chainId, {
broadcastPollIntervalMs: 3_000,
broadcastTimeoutMs: 60_000,
})
)
);
@@ -102,7 +84,13 @@ class DydxChainTransactions implements AbacusDYDXChainTransactionsProtocol {
// Dispatch custom event to notify other parts of the app that the network has been connected
const customEvent = new CustomEvent('abacus:connectNetwork', {
detail: parsedParams,
detail: {
indexerUrl,
indexerSocketUrl,
validatorUrl,
chainId,
faucetUrl,
},
});
globalThis.dispatchEvent(customEvent);
@@ -111,7 +99,9 @@ class DydxChainTransactions implements AbacusDYDXChainTransactionsProtocol {
this.store?.dispatch(
openDialog({ type: DialogTypes.ExchangeOffline, dialogProps: { preventClose: true } })
);
log('DydxChainTransactions/connectNetwork', error);
return;
}
}
@@ -223,13 +213,13 @@ class DydxChainTransactions implements AbacusDYDXChainTransactionsProtocol {
params ?? {};
try {
const tx = await this.compositeClient?.cancelRawOrder(
const tx = await this.compositeClient?.cancelOrder(
new SubaccountClient(this.localWallet, subaccountNumber),
clientId,
orderFlags,
clobPairId,
goodTilBlock || undefined,
goodTilBlockTime || undefined,
goodTilBlock ?? undefined,
goodTilBlockTime ?? undefined
);
const parsedTx = this.parseToPrimitives(tx);
@@ -261,7 +251,7 @@ class DydxChainTransactions implements AbacusDYDXChainTransactionsProtocol {
const msg = compositeClient.withdrawFromSubaccountMessage(subaccountClient, amount);
resolve([msg]);
})
}),
);
const parsedTx = this.parseToPrimitives(tx);
@@ -276,9 +266,7 @@ class DydxChainTransactions implements AbacusDYDXChainTransactionsProtocol {
}
}
async simulateTransferNativeTokenTransaction(
params: HumanReadableTransferPayload
): Promise<string> {
async simulateTransferNativeTokenTransaction(params: HumanReadableTransferPayload): Promise<string> {
if (!this.compositeClient || !this.localWallet) {
throw new Error('Missing compositeClient or localWallet');
}
@@ -292,18 +280,16 @@ class DydxChainTransactions implements AbacusDYDXChainTransactionsProtocol {
this.localWallet,
() =>
new Promise((resolve) => {
if (!this.localWallet) {
throw new Error('Missing compositeClient or localWallet');
}
const msg = compositeClient?.sendTokenMessage(
this.localWallet,
amount,
const msg = compositeClient?.validatorClient.post.composer.composeMsgSendToken(
subaccountClient.address,
recipient,
DYDX_DENOM,
Long.fromNumber(amount * QUANTUM_MULTIPLIER)
);
resolve([msg]);
}),
this.compositeClient?.validatorClient?.post.defaultDydxGasPrice,
GAS_PRICE_DYDX_DENOM,
);
const parsedTx = this.parseToPrimitives(tx);
@@ -411,10 +397,9 @@ class DydxChainTransactions implements AbacusDYDXChainTransactionsProtocol {
break;
case QueryType.GetAccountBalances:
if (!this.localWallet?.address) throw new Error('Missing localWallet');
const accountBalances =
await this.compositeClient?.validatorClient.get.getAccountBalances(
this.localWallet.address
);
const accountBalances = await this.compositeClient?.validatorClient.get.getAccountBalances(
this.localWallet.address
);
const parsedAccountBalances = this.parseToPrimitives(accountBalances);
callback(JSON.stringify(parsedAccountBalances));
break;
-5
View File
@@ -47,11 +47,6 @@ class AbacusRest implements AbacusRestProtocol {
body,
};
if (!url) {
callback(null, 0);
return;
}
fetch(url, options)
.then(async (response) => {
const data = await response.text();
-5
View File
@@ -25,7 +25,6 @@ import {
setFundingPayments,
setHistoricalPnl,
setLatestOrder,
setRestrictionType,
setSubaccount,
setTransfers,
setWallet,
@@ -122,10 +121,6 @@ class AbacusStateNotifier implements AbacusStateNotificationProtocol {
);
}
if (changes.has(Changes.restriction)) {
dispatch(setRestrictionType(updatedState.restriction));
}
subaccountNumbers?.forEach((subaccountId: number) => {
if (subaccountId !== null) {
if (changes.has(Changes.subaccount)) {
-4
View File
@@ -1,4 +0,0 @@
import { type DydxNetwork, ENVIRONMENT_CONFIG_MAP } from '@/constants/networks';
export const validateAgainstAvailableEnvironments = (value: DydxNetwork) =>
Object.keys(ENVIRONMENT_CONFIG_MAP).includes(value);
+36 -45
View File
@@ -36,15 +36,7 @@ import { CoinbaseWalletConnector } from 'wagmi/connectors/coinbaseWallet';
import { InjectedConnector } from 'wagmi/connectors/injected';
import { MetaMaskConnector } from 'wagmi/connectors/metaMask';
import { WalletConnectConnector } from 'wagmi/connectors/walletConnect';
import {
type WalletConnection,
WalletConnectionType,
type WalletType,
walletConnectionTypes,
wallets,
WALLET_CONNECT_EXPLORER_RECOMMENDED_IDS,
} from '@/constants/wallets';
import { WalletConnectLegacyConnector } from 'wagmi/connectors/walletConnectLegacy';
// Config
@@ -95,46 +87,44 @@ const injectedConnectorOptions = {
},
};
type WalletConnectConfig = {
client: {
name: string;
description: string;
iconUrl: string;
};
v2: {
projectId: string;
};
};
const getWalletconnect2ConnectorOptions = (
config: WalletConnectConfig
): ConstructorParameters<typeof WalletConnectConnector>[0] => ({
const walletconnect2ConnectorOptions: ConstructorParameters<typeof WalletConnectConnector>[0] = {
chains,
options: {
projectId: config.v2.projectId,
projectId: import.meta.env.VITE_WALLETCONNECT2_PROJECT_ID,
metadata: {
name: config.client.name,
description: config.client.description,
name: 'dYdX',
description: '',
url: import.meta.env.VITE_BASE_URL,
icons: [config.client.iconUrl],
icons: [`${import.meta.env.VITE_BASE_URL}/cbw-image.png}`],
},
showQrModal: true,
qrModalOptions: {
themeMode: 'dark' as const,
themeVariables: {
'--wcm-accent-color': '#5973fe',
'--wcm-font-family': 'var(--fontFamily-base)',
'--w3m-accent-color': '#5973fe',
'--w3m-background-color': '#5973fe',
'--w3m-color-bg-1': 'var(--color-layer-3)',
'--w3m-color-bg-2': 'var(--color-layer-4)',
'--w3m-color-bg-3': 'var(--color-layer-5)',
'--w3m-font-family': 'var(--fontFamily-base)',
'--w3m-font-feature-settings': 'none',
'--w3m-overlay-backdrop-filter': 'blur(6px)',
// '--w3m-logo-image-url': 'https://trade.dydx.exchange/cbw-image.png',
},
explorerRecommendedWalletIds: WALLET_CONNECT_EXPLORER_RECOMMENDED_IDS,
enableExplorer: true,
explorerAllowList: [],
explorerDenyList: [],
chainImages: {},
},
},
});
};
const getConnectors = (walletConnectConfig: WalletConnectConfig) => [
const connectors = [
new MetaMaskConnector({
chains,
options: {
shimDisconnect: true,
shimChainChangedDisconnect: false,
},
}),
new CoinbaseWalletConnector({
@@ -144,7 +134,7 @@ const getConnectors = (walletConnectConfig: WalletConnectConfig) => [
reloadOnDisconnect: false,
},
}),
new WalletConnectConnector(getWalletconnect2ConnectorOptions(walletConnectConfig)),
new WalletConnectConnector(walletconnect2ConnectorOptions),
new InjectedConnector(injectedConnectorOptions),
];
@@ -166,34 +156,35 @@ const createInjectedConnectorWithProvider = (provider: ExternalProvider) =>
provider as unknown as Awaited<ReturnType<InjectedConnector['getProvider']>>;
})(injectedConnectorOptions) as InjectedConnector;
const createWalletConnect2ConnectorWithId = (
walletconnectId: string,
walletConnectConfig: WalletConnectConfig
) => {
const walletconnect2ConnectorOptions = getWalletconnect2ConnectorOptions(walletConnectConfig);
return new WalletConnectConnector({
const createWalletConnect2ConnectorWithId = (walletconnect2Id: string) =>
new WalletConnectConnector({
...walletconnect2ConnectorOptions,
options: {
...walletconnect2ConnectorOptions.options,
qrModalOptions: {
...walletconnect2ConnectorOptions.options.qrModalOptions,
explorerRecommendedWalletIds: [walletconnectId],
explorerRecommendedWalletIds: [walletconnect2Id],
explorerExcludedWalletIds: 'ALL',
chainImages: {},
},
},
});
};
// Custom connector from wallet selection
import {
type WalletConnection,
WalletConnectionType,
type WalletType,
walletConnectionTypes,
wallets,
} from '@/constants/wallets';
export const resolveWagmiConnector = ({
walletType,
walletConnection,
walletConnectConfig,
}: {
walletType: WalletType;
walletConnection: WalletConnection;
walletConnectConfig: WalletConnectConfig;
}) => {
const walletConfig = wallets[walletType];
const walletConnectionConfig = walletConnectionTypes[walletConnection.type];
@@ -201,6 +192,6 @@ export const resolveWagmiConnector = ({
return walletConnection.type === WalletConnectionType.InjectedEip1193 && walletConnection.provider
? createInjectedConnectorWithProvider(walletConnection.provider)
: walletConnection.type === WalletConnectionType.WalletConnect2 && walletConfig.walletconnect2Id
? createWalletConnect2ConnectorWithId(walletConfig.walletconnect2Id, walletConnectConfig)
: getConnectors(walletConnectConfig).find(({ id }: { id: string }) => id === walletConnectionConfig.wagmiConnectorId);
? createWalletConnect2ConnectorWithId(walletConfig.walletconnect2Id)
: connectors.find(({ id }: { id: string }) => id === walletConnectionConfig.wagmiConnectorId);
};
-17
View File
@@ -1,17 +0,0 @@
import styled, { AnyStyledComponent } from 'styled-components';
import { articleMixins } from '@/styles/articleMixins';
export const PrivacyPolicyPage = () => (
<Styled.Article>
<header>
<h1>Privacy Policy</h1>
</header>
</Styled.Article>
);
const Styled: Record<string, AnyStyledComponent> = {};
Styled.Article = styled.article`
${articleMixins.article}
`;
-17
View File
@@ -1,17 +0,0 @@
import styled, { AnyStyledComponent } from 'styled-components';
import { articleMixins } from '@/styles/articleMixins';
export const TermsOfUsePage = () => (
<Styled.Article>
<header>
<h1>Terms of Use</h1>
</header>
</Styled.Article>
);
const Styled: Record<string, AnyStyledComponent> = {};
Styled.Article = styled.article`
${articleMixins.article}
`;
@@ -2,7 +2,6 @@ import { useMemo, useState } from 'react';
import styled, { AnyStyledComponent, css } from 'styled-components';
import { shallowEqual, useSelector } from 'react-redux';
import { TooltipContextType } from '@visx/xychart';
import BigNumber from 'bignumber.js';
import type { Nullable } from '@/constants/abacus';
import { OnboardingState } from '@/constants/account';
@@ -26,6 +25,7 @@ import { OnboardingTriggerButton } from '@/views/dialogs/OnboardingTriggerButton
import { isTruthy } from '@/lib/isTruthy';
import { MustBigNumber } from '@/lib/numbers';
export const usePortfolioValues = ({
equity,
visibleData,
@@ -140,12 +140,7 @@ export const AccountDetailsAndHistory = () => {
<Styled.AccountValue>
<Styled.WithLabel label={accountValueLabel}>
<Styled.AccountEquity>
<Output
type={OutputType.Fiat}
value={accountEquity}
roundingMode={BigNumber.ROUND_FLOOR}
withBaseFont
/>
<Output type={OutputType.Fiat} value={accountEquity} withBaseFont />
</Styled.AccountEquity>
<Styled.PnlDiff isPositive={MustBigNumber(pnlDiff).gte(0)}>
{pnlDiff && <TriangleIndicator value={MustBigNumber(pnlDiff)} />}
+4 -10
View File
@@ -3,7 +3,7 @@ import styled, { AnyStyledComponent } from 'styled-components';
import { shallowEqual, useDispatch, useSelector } from 'react-redux';
import { layoutMixins } from '@/styles/layoutMixins';
import { useAccountBalance, useAccounts, useTokenConfigs, useStringGetter } from '@/hooks';
import { useAccountBalance, useAccounts, useStringGetter } from '@/hooks';
import { ButtonAction, ButtonSize } from '@/constants/buttons';
import { DialogTypes } from '@/constants/dialogs';
@@ -30,7 +30,6 @@ export const DYDXBalancePanel = () => {
const { walletType } = useAccounts();
const canAccountTrade = useSelector(calculateCanAccountTrade, shallowEqual);
const { nativeTokenBalance, nativeStakingBalance } = useAccountBalance();
const { chainTokenLabel } = useTokenConfigs();
return (
<Panel
@@ -38,7 +37,7 @@ export const DYDXBalancePanel = () => {
<Styled.Header>
<Styled.Title>
{/* <AssetIcon symbol="DYDX" /> */}
{chainTokenLabel}
Dv4TNT
</Styled.Title>
<Styled.ReceiveAndTransferButtons>
{!canAccountTrade ? (
@@ -107,13 +106,7 @@ export const DYDXBalancePanel = () => {
{
key: 'totalBalance',
label: 'Total balance',
value: (
<Output
type={OutputType.Asset}
value={nativeTokenBalance + nativeStakingBalance}
tag={chainTokenLabel}
/>
),
value: <Output type={OutputType.Asset} value={nativeTokenBalance + nativeStakingBalance} tag="Dv4TNT" />,
},
]}
/>
@@ -181,6 +174,7 @@ Styled.WalletAndStakedBalance = styled(Details)`
grid-template-columns: 1fr 1fr;
gap: 0.5rem;
> div {
gap: 1rem;
+4
View File
@@ -3,6 +3,7 @@ import { configureStore } from '@reduxjs/toolkit';
import abacusStateManager from '@/lib/abacus';
import appMiddleware from './appMiddleware';
import localizationMiddleware from './localizationMiddleware';
import routerMiddleware from './routerMiddleware';
import { accountSlice } from './account';
import { appSlice } from './app';
@@ -12,6 +13,7 @@ import { dialogsSlice } from './dialogs';
import { inputsSlice } from './inputs';
import { layoutSlice } from './layout';
import { localizationSlice } from './localization';
import { navigationSlice } from './navigation';
import { perpetualsSlice } from './perpetuals';
export const commandMenuSlices = [layoutSlice, localizationSlice];
@@ -26,6 +28,7 @@ export const store = configureStore({
inputs: inputsSlice.reducer,
layout: layoutSlice.reducer,
localization: localizationSlice.reducer,
navigation: navigationSlice.reducer,
perpetuals: perpetualsSlice.reducer,
},
@@ -35,6 +38,7 @@ export const store = configureStore({
}),
appMiddleware,
localizationMiddleware,
routerMiddleware,
],
devTools: process.env.NODE_ENV !== 'production',
+18 -40
View File
@@ -12,7 +12,6 @@ import type {
SubaccountTransfers,
HistoricalPnlPeriods,
SubAccountHistoricalPNLs,
UsageRestriction,
} from '@/constants/abacus';
import { OnboardingGuard, OnboardingState } from '@/constants/account';
@@ -22,46 +21,34 @@ import { WalletType } from '@/constants/wallets';
import { getLocalStorage } from '@/lib/localStorage';
export type AccountState = {
balances?: Record<string, AccountBalance>;
stakingBalances?: Record<string, AccountBalance>;
wallet?: Nullable<Wallet>;
walletType?: WalletType;
subaccount?: Nullable<Subaccount>;
fills?: SubaccountFills;
fundingPayments?: SubaccountFundingPayments;
transfers?: SubaccountTransfers;
historicalPnl?: SubAccountHistoricalPNLs;
onboardingGuards: Record<OnboardingGuard, boolean | undefined>;
onboardingState: OnboardingState;
clearedOrderIds?: string[];
hasUnseenFillUpdates: boolean;
hasUnseenOrderUpdates: boolean;
historicalPnl?: SubAccountHistoricalPNLs;
latestOrder?: Nullable<SubaccountOrder>;
historicalPnlPeriod?: HistoricalPnlPeriods;
onboardingGuards: Record<OnboardingGuard, boolean | undefined>;
onboardingState: OnboardingState;
subaccount?: Nullable<Subaccount>;
uncommittedOrderClientIds: number[];
restriction?: Nullable<UsageRestriction>;
wallet?: Nullable<Wallet>;
walletType?: WalletType;
historicalPnlPeriod?: HistoricalPnlPeriods;
balances?: Record<string, AccountBalance>;
stakingBalances?: Record<string, AccountBalance>;
};
const initialState: AccountState = {
// Wallet
balances: undefined,
wallet: undefined,
walletType: getLocalStorage<WalletType>({
key: LocalStorageKey.OnboardingSelectedWalletType,
}),
// Subaccount
subaccount: undefined,
fills: undefined,
fundingPayments: undefined,
transfers: undefined,
clearedOrderIds: undefined,
hasUnseenFillUpdates: false,
hasUnseenOrderUpdates: false,
historicalPnl: undefined,
// Onboarding
latestOrder: undefined,
onboardingGuards: {
[OnboardingGuard.hasAcknowledgedTerms]: Boolean(
getLocalStorage<boolean>({
@@ -72,17 +59,12 @@ const initialState: AccountState = {
[OnboardingGuard.hasPreviousTransactions]: undefined,
},
onboardingState: OnboardingState.Disconnected,
// UI
clearedOrderIds: undefined,
hasUnseenFillUpdates: false,
hasUnseenOrderUpdates: false,
latestOrder: undefined,
subaccount: undefined,
uncommittedOrderClientIds: [],
historicalPnlPeriod: undefined,
// Restriction
restriction: undefined,
wallet: undefined,
walletType: getLocalStorage<WalletType>({
key: LocalStorageKey.OnboardingSelectedWalletType,
}),
};
export const accountSlice = createSlice({
@@ -142,9 +124,6 @@ export const accountSlice = createSlice({
state.historicalPnl = action.payload;
}
},
setRestrictionType: (state, action: PayloadAction<Nullable<UsageRestriction>>) => {
state.restriction = action.payload;
},
setSubaccount: (state, action: PayloadAction<Nullable<Subaccount>>) => {
const existingOrderIds = state.subaccount?.orders
? state.subaccount.orders.toArray().map((order) => order.id)
@@ -199,7 +178,6 @@ export const {
setOnboardingGuard,
setOnboardingState,
setHistoricalPnl,
setRestrictionType,
setSubaccount,
setWallet,
viewedFills,
-10
View File
@@ -342,13 +342,3 @@ export const getBalances = (state: RootState) => state.account?.balances;
* @returns user wallet staking balances
* */
export const getStakingBalances = (state: RootState) => state.account?.stakingBalances;
/**
* @returns UsageRestriction of the current session
*/
export const getUsageRestriction = (state: RootState) => state.account.restriction;
/**
* @returns RestrictionType from the current session
*/
export const getRestrictionType = (state: RootState) => state.account.restriction?.restriction;
+1 -2
View File
@@ -2,10 +2,10 @@ import { createSlice, PayloadAction } from '@reduxjs/toolkit';
import { AbacusApiState } from '@/constants/abacus';
import { LocalStorageKey } from '@/constants/localStorage';
import { DEFAULT_APP_ENVIRONMENT, type DydxNetwork } from '@/constants/networks';
import { getLocalStorage } from '@/lib/localStorage';
import { validateAgainstAvailableEnvironments } from '@/lib/network';
export interface AppState {
apiState: AbacusApiState | undefined;
@@ -19,7 +19,6 @@ const initialState: AppState = {
selectedNetwork: getLocalStorage({
key: LocalStorageKey.SelectedNetwork,
defaultValue: DEFAULT_APP_ENVIRONMENT,
validateFn: validateAgainstAvailableEnvironments,
}),
};
+24 -23
View File
@@ -23,38 +23,39 @@ export const dialogsSlice = createSlice({
name: 'Dialogs',
initialState,
reducers: {
openDialog: (state: DialogsState, action: PayloadAction<DialogInfo<DialogTypes>>) => {
if (state.activeDialog?.type === action.payload.type) return;
addDialogToQueue: (state: DialogsState, action: PayloadAction<DialogInfo<DialogTypes>>) => {
const dialogQueue = state.dialogQueue;
dialogQueue.push(action.payload);
if (state.activeDialog) {
state.dialogQueue.push(action.payload);
} else {
state.activeDialog = action.payload;
}
},
closeDialog: (state: DialogsState) => {
state.activeDialog = state.dialogQueue.shift();
},
forceOpenDialog: (state: DialogsState, action: PayloadAction<DialogInfo<DialogTypes>>) => {
if (state.activeDialog) {
state.dialogQueue.unshift(state.activeDialog);
}
state.activeDialog = action.payload;
},
closeDialogInTradeBox: (state: DialogsState) => {
state.activeTradeBoxDialog = undefined;
return {
...state,
dialogQueue,
};
},
closeDialog: (state: DialogsState) => ({
...state,
activeDialog: state.dialogQueue.shift(),
}),
openDialog: (state: DialogsState, action: PayloadAction<DialogInfo<DialogTypes>>) => ({
...state,
activeDialog: action.payload,
}),
closeDialogInTradeBox: (state: DialogsState) => ({
...state,
activeTradeBoxDialog: undefined,
}),
openDialogInTradeBox: (
state: DialogsState,
action: PayloadAction<DialogInfo<TradeBoxDialogTypes>>
) => {
state.activeTradeBoxDialog = action.payload;
},
) => ({
...state,
activeTradeBoxDialog: action.payload,
}),
},
});
export const {
forceOpenDialog,
addDialogToQueue,
closeDialog,
closeDialogInTradeBox,
openDialog,
+42
View File
@@ -0,0 +1,42 @@
import { createSlice } from '@reduxjs/toolkit';
export interface NavigationState {
tradeLocation: {
hash: string;
key: string;
pathname: string;
search: string;
state: any;
};
}
export const CLEAR_TRADE_LOCATION = {
hash: '',
key: '',
pathname: '',
search: '',
state: null,
};
const initialState: NavigationState = {
tradeLocation: {
hash: '',
key: '',
pathname: '',
search: '',
state: null,
},
};
export const navigationSlice = createSlice({
name: 'Navigation',
initialState,
reducers: {
setTradeLocation: (state, { payload }) => ({
...state,
tradeLocation: payload,
}),
},
});
export const { setTradeLocation } = navigationSlice.actions;
+33
View File
@@ -0,0 +1,33 @@
import type { PayloadAction } from '@reduxjs/toolkit';
import { LocalStorageKey } from '@/constants/localStorage';
import { closeDialogInTradeBox } from '@/state/dialogs';
import { setTradeLocation } from '@/state/navigation';
import abacusStateManager from '@/lib/abacus';
import { setLocalStorage } from '@/lib/localStorage';
import { getMarketIdFromLocation } from '@/lib/tradeData';
export default (store: any) => (next: any) => async (action: PayloadAction<any>) => {
next(action);
const { type, payload } = action;
switch (type) {
case setTradeLocation.type: {
const marketId = getMarketIdFromLocation(payload);
if (marketId) {
abacusStateManager.setMarket(marketId);
store.dispatch(closeDialogInTradeBox());
setLocalStorage({ key: LocalStorageKey.LastViewedMarket, value: marketId });
}
break;
}
default: {
break;
}
}
};
-53
View File
@@ -1,53 +0,0 @@
import {
css,
type FlattenInterpolation,
type FlattenSimpleInterpolation,
type ThemeProps,
} from 'styled-components';
export const articleMixins: Record<
string,
FlattenSimpleInterpolation | FlattenInterpolation<ThemeProps<any>>
> = {
article: css`
padding: 2rem;
overflow-wrap: break-word;
user-select: text;
margin: 0 auto;
width: 60rem;
max-width: 100vw;
header {
color: var(--color-text-0);
margin-bottom: 2rem;
h1 {
font: var(--font-extra-book);
color: var(--color-text-2);
}
}
h2 {
font: var(--font-large-book);
color: var(--color-text-2);
padding: 0.5rem 0;
}
h3,
strong {
font-weight: 700;
}
strong {
color: var(--color-text-2);
}
p {
padding: 0.5rem 0;
}
ul {
padding: 0.5rem 1rem;
}
`,
};
@@ -75,14 +75,16 @@ export const AccountInfoConnectedState = () => {
<Styled.Header>
<span>{stringGetter({ key: STRING_KEYS.ACCOUNT })}</span>
<Styled.TransferButtons>
<Styled.Button
state={{ isDisabled: !dydxAccounts }}
onClick={() => dispatch(openDialog({ type: DialogTypes.Withdraw }))}
shape={ButtonShape.Pill}
size={ButtonSize.XSmall}
>
{stringGetter({ key: STRING_KEYS.WITHDRAW })}
</Styled.Button>
{import.meta.env.MODE !== 'production' && (
<Styled.Button
state={{ isDisabled: !dydxAccounts }}
onClick={() => dispatch(openDialog({ type: DialogTypes.Withdraw }))}
shape={ButtonShape.Pill}
size={ButtonSize.XSmall}
>
{stringGetter({ key: STRING_KEYS.WITHDRAW })}
</Styled.Button>
)}
<Styled.Button
state={{ isDisabled: !dydxAccounts }}
onClick={() => dispatch(openDialog({ type: DialogTypes.Deposit }))}
+1 -5
View File
@@ -25,11 +25,7 @@ import { TimeSeriesChart } from '@/components/visx/TimeSeriesChart';
import { AxisLabelOutput } from '@/components/visx/AxisLabelOutput';
// import { TooltipContent } from '@/components/visx/TooltipContent';
import {
getSubaccount,
getSubaccountHistoricalPnl,
getSubaccountId,
} from '@/state/accountSelectors';
import { getSubaccount, getSubaccountHistoricalPnl, getSubaccountId } from '@/state/accountSelectors';
import abacusStateManager from '@/lib/abacus';
import { formatRelativeTime } from '@/lib/dateTime';
+6 -3
View File
@@ -32,9 +32,12 @@ export const DepositDialog = ({ setIsOpen }: ElementProps) => {
>
<Styled.Content>
{showTestDeposit ? <TestnetDepositForm onDeposit={closeDialog} /> : <DepositForm />}
<Styled.TextToggle onClick={() => setShowTestDeposit(!showTestDeposit)}>
{showTestDeposit ? 'Show deposit form (Under Construction)' : 'Show test faucet'}
</Styled.TextToggle>
{/* TODO TRCL-1693 - uncomment when deposit form is ready */}
{import.meta.env.MODE !== 'production' && (
<Styled.TextToggle onClick={() => setShowTestDeposit(!showTestDeposit)}>
{showTestDeposit ? 'Show deposit form (Under Construction)' : 'Show test faucet'}
</Styled.TextToggle>
)}
</Styled.Content>
</Dialog>
);
@@ -5,7 +5,6 @@ import { shallowEqual, useDispatch, useSelector } from 'react-redux';
import { AbacusApiStatus } from '@/constants/abacus';
import { DialogTypes } from '@/constants/dialogs';
import { STRING_KEYS } from '@/constants/localization';
import { useApiState, useStringGetter } from '@/hooks';
import { layoutMixins } from '@/styles/layoutMixins';
@@ -2,7 +2,6 @@ import styled, { type AnyStyledComponent } from 'styled-components';
import { useAccounts, useStringGetter } from '@/hooks';
import { AppRoute } from '@/constants/routes';
import { STRING_KEYS } from '@/constants/localization';
import { ButtonAction } from '@/constants/buttons';
@@ -30,12 +29,12 @@ export const AcknowledgeTerms = ({ onContinue }: ElementProps) => {
key: STRING_KEYS.LEGAL_UPDATES_DESCRIPTION,
params: {
TOU: (
<Styled.Link href={`/#${AppRoute.Terms}`}>
<Styled.Link href="https://dydx.exchange/v4-terms">
{stringGetter({ key: STRING_KEYS.TERMS_OF_USE })}
</Styled.Link>
),
PRIVACY_POLICY: (
<Styled.Link href={`/#${AppRoute.Privacy}`}>
<Styled.Link href="https://dydx.exchange/privacy">
{stringGetter({ key: STRING_KEYS.PRIVACY_POLICY })}
</Styled.Link>
),
@@ -264,6 +264,7 @@ const Styled: Record<string, AnyStyledComponent> = {};
Styled.StatusCardsContainer = styled.div`
display: grid;
margin-top: 1rem;
gap: 1rem;
`;
-42
View File
@@ -1,42 +0,0 @@
import styled, { AnyStyledComponent } from 'styled-components';
import { STRING_KEYS } from '@/constants/localization';
import { useStringGetter } from '@/hooks';
import { layoutMixins } from '@/styles/layoutMixins';
import { Dialog } from '@/components/Dialog';
import { Icon, IconName } from '@/components/Icon';
type ElementProps = {
preventClose?: boolean;
setIsOpen?: (open: boolean) => void;
};
export const RateLimitDialog = ({ preventClose, setIsOpen }: ElementProps) => {
const stringGetter = useStringGetter();
return (
<Dialog
isOpen
preventClose={preventClose}
setIsOpen={setIsOpen}
title={stringGetter({ key: STRING_KEYS.RATE_LIMIT_REACHED_ERROR_TITLE })}
slotIcon={<Styled.Icon iconName={IconName.Warning} />}
>
<Styled.Content>
{stringGetter({ key: STRING_KEYS.RATE_LIMIT_REACHED_ERROR_MESSAGE })}
</Styled.Content>
</Dialog>
);
};
const Styled: Record<string, AnyStyledComponent> = {};
Styled.Icon = styled(Icon)`
color: var(--color-warning);
`;
Styled.Content = styled.div`
${layoutMixins.column}
gap: 1rem;
`;
+5 -7
View File
@@ -6,7 +6,7 @@ import { DydxChainAsset } from '@/constants/wallets';
import { formMixins } from '@/styles/formMixins';
import { layoutMixins } from '@/styles/layoutMixins';
import { useAccounts, useTokenConfigs, useStringGetter } from '@/hooks';
import { useAccounts, useStringGetter } from '@/hooks';
import { AssetIcon } from '@/components/AssetIcon';
import { CopyButton } from '@/components/CopyButton';
@@ -24,10 +24,9 @@ type ElementProps = {
setIsOpen: (open: boolean) => void;
};
export const ReceiveDialog = ({ selectedAsset = DydxChainAsset.CHAINTOKEN, setIsOpen }: ElementProps) => {
export const ReceiveDialog = ({ selectedAsset = DydxChainAsset.DYDX, setIsOpen }: ElementProps) => {
const stringGetter = useStringGetter();
const { dydxAddress } = useAccounts();
const { chainTokenLabel, usdcLabel } = useTokenConfigs();
const [asset, setAsset] = useState(selectedAsset);
@@ -36,17 +35,16 @@ export const ReceiveDialog = ({ selectedAsset = DydxChainAsset.CHAINTOKEN, setIs
value: DydxChainAsset.USDC,
label: (
<Styled.InlineRow>
<AssetIcon symbol="USDC" /> {usdcLabel}
<AssetIcon symbol="USDC" /> USDC
</Styled.InlineRow>
),
},
{
value: DydxChainAsset.CHAINTOKEN,
value: DydxChainAsset.DYDX,
label: (
<Styled.InlineRow>
{/* TODO: conditionally display the native token assetIcon */}
{/* <AssetIcon symbol="DYDX" /> */}
{chainTokenLabel}
Dv4TNT
</Styled.InlineRow>
),
},
-42
View File
@@ -1,42 +0,0 @@
import styled, { AnyStyledComponent } from 'styled-components';
import { STRING_KEYS } from '@/constants/localization';
import { useStringGetter } from '@/hooks';
import { layoutMixins } from '@/styles/layoutMixins';
import { Dialog } from '@/components/Dialog';
import { Icon, IconName } from '@/components/Icon';
type ElementProps = {
preventClose?: boolean;
setIsOpen?: (open: boolean) => void;
};
export const RestrictedGeoDialog = ({ preventClose, setIsOpen }: ElementProps) => {
const stringGetter = useStringGetter();
return (
<Dialog
isOpen
preventClose={preventClose}
setIsOpen={setIsOpen}
title={stringGetter({ key: STRING_KEYS.REGION_NOT_PERMITTED_TITLE })}
slotIcon={<Styled.Icon iconName={IconName.Warning} />}
>
<Styled.Content>
{stringGetter({ key: STRING_KEYS.REGION_NOT_PERMITTED_SUBTITLE })}
</Styled.Content>
</Dialog>
);
};
const Styled: Record<string, AnyStyledComponent> = {};
Styled.Icon = styled(Icon)`
color: var(--color-warning);
`;
Styled.Content = styled.div`
${layoutMixins.column}
gap: 1rem;
`;
@@ -1,42 +0,0 @@
import styled, { AnyStyledComponent } from 'styled-components';
import { STRING_KEYS } from '@/constants/localization';
import { useStringGetter } from '@/hooks';
import { layoutMixins } from '@/styles/layoutMixins';
import { Dialog } from '@/components/Dialog';
import { Icon, IconName } from '@/components/Icon';
type ElementProps = {
preventClose?: boolean;
setIsOpen?: (open: boolean) => void;
};
export const RestrictedWalletDialog = ({ preventClose, setIsOpen }: ElementProps) => {
const stringGetter = useStringGetter();
return (
<Dialog
isOpen
preventClose={preventClose}
setIsOpen={setIsOpen}
title={stringGetter({ key: STRING_KEYS.WALLET_RESTRICTED_ERROR_TITLE })}
slotIcon={<Styled.Icon iconName={IconName.Warning} />}
>
<Styled.Content>
{stringGetter({ key: STRING_KEYS.REGION_NOT_PERMITTED_SUBTITLE })}
</Styled.Content>
</Dialog>
);
};
const Styled: Record<string, AnyStyledComponent> = {};
Styled.Icon = styled(Icon)`
color: var(--color-warning);
`;
Styled.Content = styled.div`
${layoutMixins.column}
gap: 1rem;
`;
@@ -10,16 +10,9 @@ import { TransferInputField, TransferInputTokenResource, TransferType } from '@/
import { AlertType } from '@/constants/alerts';
import { ButtonSize } from '@/constants/buttons';
import { STRING_KEYS } from '@/constants/localization';
import { NumberSign } from '@/constants/numbers';
import { NumberSign, QUANTUM_MULTIPLIER } from '@/constants/numbers';
import {
useAccounts,
useDebounce,
useDydxClient,
useRestrictions,
useStringGetter,
useSubaccount,
} from '@/hooks';
import { useDebounce, useStringGetter, useSubaccount } from '@/hooks';
import { useLocalNotifications } from '@/hooks/useLocalNotifications';
import { layoutMixins } from '@/styles/layoutMixins';
@@ -46,11 +39,10 @@ import { MustBigNumber } from '@/lib/numbers';
import { TokenSelectMenu } from './TokenSelectMenu';
import { WithdrawButtonAndReceipt } from './WithdrawForm/WithdrawButtonAndReceipt';
import { join } from 'path';
export const WithdrawForm = () => {
const stringGetter = useStringGetter();
const [error, setError] = useState<string>();
const [error, setError] = useState<Error | null>(null);
const [isLoading, setIsLoading] = useState(false);
const { sendSquidWithdraw } = useSubaccount();
@@ -79,11 +71,9 @@ export const WithdrawForm = () => {
const { addTransferNotification } = useLocalNotifications();
// Async Data
const debouncedAmountBN = useMemo(() => MustBigNumber(debouncedAmount), [debouncedAmount]);
const freeCollateralBN = useMemo(
() => MustBigNumber(freeCollateral?.current),
[freeCollateral?.current]
);
const debouncedAmountBN = MustBigNumber(debouncedAmount);
const withdrawAmountBN = MustBigNumber(withdrawAmount);
const freeCollateralBN = MustBigNumber(freeCollateral?.current);
useEffect(() => {
abacusStateManager.setTransferValue({
@@ -115,85 +105,50 @@ export const WithdrawForm = () => {
value: debouncedAmount,
field: TransferInputField.usdcSize,
});
setError(undefined);
setError(null);
}
} catch (error) {
setError(error.message);
setError(error);
} finally {
setIsLoading(false);
}
};
setTransferValue();
}, [debouncedAmountBN]);
const { screenAddresses } = useDydxClient();
const { dydxAddress } = useAccounts();
}, [debouncedAmountBN.toNumber()]);
const onSubmit = useCallback(
async (e: FormEvent) => {
try {
e.preventDefault();
if (!requestPayload?.data || !debouncedAmountBN.toNumber() || !toAddress || !dydxAddress) {
if (!requestPayload?.data || !debouncedAmountBN.toNumber()) {
throw new Error('Invalid request payload');
}
setIsLoading(true);
setError(undefined);
const txHash = await sendSquidWithdraw(debouncedAmountBN.toNumber(), requestPayload?.data);
const screenResults = await screenAddresses({
addresses: [toAddress, dydxAddress],
});
if (txHash?.hash) {
const hash = `0x${Buffer.from(txHash.hash).toString('hex')}`;
if (screenResults?.[dydxAddress]) {
setError(
stringGetter({
key: STRING_KEYS.WALLET_RESTRICTED_WITHDRAWAL_TRANSFER_ORIGINATION_ERROR_MESSAGE,
})
);
} else if (screenResults?.[toAddress]) {
setError(
stringGetter({
key: STRING_KEYS.WALLET_RESTRICTED_WITHDRAWAL_TRANSFER_DESTINATION_ERROR_MESSAGE,
})
);
} else {
const txHash = await sendSquidWithdraw(debouncedAmountBN.toNumber(), requestPayload.data);
if (txHash?.hash) {
const hash = `0x${Buffer.from(txHash.hash).toString('hex')}`;
addTransferNotification({
txHash: hash,
fromChainId: TESTNET_CHAIN_ID,
toChainId: chainIdStr || undefined,
toAmount: debouncedAmountBN.toNumber(),
triggeredAt: Date.now(),
});
abacusStateManager.clearTransferInputValues();
setWithdrawAmount('');
}
addTransferNotification({
txHash: hash,
fromChainId: TESTNET_CHAIN_ID,
toChainId: chainIdStr || undefined,
toAmount: debouncedAmountBN.toNumber(),
triggeredAt: Date.now(),
});
abacusStateManager.clearTransferInputValues();
setWithdrawAmount('');
}
} catch (error) {
if (error?.code === 429) {
setError(stringGetter({ key: STRING_KEYS.RATE_LIMIT_REACHED_ERROR_MESSAGE }));
} else {
setError(
error.message
? stringGetter({
key: STRING_KEYS.SOMETHING_WENT_WRONG_WITH_MESSAGE,
params: {
ERROR_MESSAGE:
error.message || stringGetter({ key: STRING_KEYS.UNKNOWN_ERROR }),
},
})
: stringGetter({ key: STRING_KEYS.SOMETHING_WENT_WRONG })
);
}
setError(error);
} finally {
setIsLoading(false);
}
},
[requestPayload, debouncedAmountBN, chainIdStr, toAddress, screenAddresses, stringGetter]
[requestPayload, debouncedAmountBN, chainIdStr]
);
const onChangeAddress = useCallback((e: ChangeEvent<HTMLInputElement>) => {
@@ -224,7 +179,7 @@ export const WithdrawForm = () => {
const onClickMax = useCallback(() => {
setWithdrawAmount(freeCollateralBN.toString());
}, [freeCollateralBN, setWithdrawAmount]);
}, [freeCollateral?.current, setWithdrawAmount]);
const onSelectChain = useCallback((chain: string) => {
if (chain) {
@@ -260,7 +215,7 @@ export const WithdrawForm = () => {
value={freeCollateral?.current}
newValue={freeCollateral?.postOrder}
sign={NumberSign.Negative}
hasInvalidNewValue={MustBigNumber(withdrawAmount).minus(freeCollateralBN).isNegative()}
hasInvalidNewValue={withdrawAmountBN.minus(freeCollateralBN).isNegative()}
withDiff={
Boolean(withdrawAmount) && !debouncedAmountBN.isNaN() && !debouncedAmountBN.isZero()
}
@@ -269,23 +224,18 @@ export const WithdrawForm = () => {
},
];
const { sanctionedAddresses } = useRestrictions();
const errorMessage = useMemo(() => {
if (error) {
return stringGetter({
key: STRING_KEYS.SOMETHING_WENT_WRONG_WITH_MESSAGE,
params: { ERROR_MESSAGE: error },
});
return error?.message
? stringGetter({
key: STRING_KEYS.SOMETHING_WENT_WRONG_WITH_MESSAGE,
params: { ERROR_MESSAGE: error.message },
})
: stringGetter({ key: STRING_KEYS.SOMETHING_WENT_WRONG });
}
if (!toAddress) return stringGetter({ key: STRING_KEYS.WITHDRAW_MUST_SPECIFY_ADDRESS });
if (sanctionedAddresses.has(toAddress))
return stringGetter({
key: STRING_KEYS.TRANSFER_INVALID_DYDX_ADDRESS,
});
if (debouncedAmountBN) {
if (!chainIdStr) {
return stringGetter({ key: STRING_KEYS.WITHDRAW_MUST_SPECIFY_CHAIN });
@@ -299,15 +249,7 @@ export const WithdrawForm = () => {
}
return undefined;
}, [
error,
freeCollateralBN,
chainIdStr,
debouncedAmountBN,
toToken,
toAddress,
sanctionedAddresses,
]);
}, [error, freeCollateralBN, chainIdStr, debouncedAmountBN, toToken]);
const isDisabled =
!!errorMessage ||
@@ -315,8 +257,7 @@ export const WithdrawForm = () => {
!chainIdStr ||
!toAddress ||
debouncedAmountBN.isNaN() ||
debouncedAmountBN.isZero() ||
isLoading;
debouncedAmountBN.isZero();
return (
<Styled.Form onSubmit={onSubmit}>
@@ -29,7 +29,7 @@ export const AdvancedTradeOptions = () => {
const currentTradeFormConfig = useSelector(getInputTradeOptions, shallowEqual);
const inputTradeData = useSelector(getInputTradeData, shallowEqual);
const { execution, goodTil, postOnly, reduceOnly, timeInForce, type } = inputTradeData || {};
const { execution, goodTil, postOnly, reduceOnly, timeInForce } = inputTradeData || {};
const { executionOptions, needsGoodUntil, needsPostOnly, needsReduceOnly, timeInForceOptions } =
currentTradeFormConfig || {};
@@ -37,7 +37,6 @@ export const AdvancedTradeOptions = () => {
const { duration, unit } = goodTil || {};
const needsExecution = executionOptions || needsPostOnly || needsReduceOnly;
const hasTimeInForce = timeInForceOptions?.toArray()?.length;
return (
<Styled.Collapsible
@@ -48,7 +47,7 @@ export const AdvancedTradeOptions = () => {
>
<Styled.AdvancedInputsContainer>
<Styled.AdvancedInputsRow needsGoodUntil={needsGoodUntil}>
{hasTimeInForce && (
{timeInForceOptions?.toArray() && (
<Styled.SelectMenu
value={timeInForce}
onValueChange={(selectedTimeInForceOption: string) =>
@@ -73,9 +72,7 @@ export const AdvancedTradeOptions = () => {
id="trade-good-til-time"
type={InputType.Number}
decimals={INTEGER_DECIMALS}
label={stringGetter({
key: hasTimeInForce ? STRING_KEYS.TIME : STRING_KEYS.GOOD_TIL_TIME,
})}
label={stringGetter({ key: STRING_KEYS.TIME })}
onChange={({ value }: NumberFormatValues) => {
abacusStateManager.setTradeValue({
value: Number(value),
+45 -77
View File
@@ -3,6 +3,8 @@ import styled, { type AnyStyledComponent } from 'styled-components';
import { type NumberFormatValues } from 'react-number-format';
import { shallowEqual, useSelector } from 'react-redux';
import type { SyntheticInputEvent } from 'react-number-format/types/types';
import { debounce } from 'lodash';
import { StdFee } from '@cosmjs/stargate';
import { validation } from '@dydxprotocol/v4-client-js';
import { TransferInputField, TransferType } from '@/constants/abacus';
@@ -10,18 +12,19 @@ import { AlertType } from '@/constants/alerts';
import { ButtonShape, ButtonSize } from '@/constants/buttons';
import { STRING_KEYS } from '@/constants/localization';
import { ENVIRONMENT_CONFIG_MAP } from '@/constants/networks';
import { NumberSign } from '@/constants/numbers';
import { DydxChainAsset } from '@/constants/wallets';
import { NumberSign, QUANTUM_MULTIPLIER } from '@/constants/numbers';
import {
DYDX_CHAIN_ASSET_COIN_DENOM,
DYDX_CHAIN_ASSET_TAGS,
DydxChainAsset,
} from '@/constants/wallets';
import {
useAccountBalance,
useAccounts,
useDydxClient,
useRestrictions,
useSelectedNetwork,
useStringGetter,
useSubaccount,
useTokenConfigs,
} from '@/hooks';
import { formMixins } from '@/styles/formMixins';
@@ -54,7 +57,7 @@ type TransferFormProps = {
};
export const TransferForm = ({
selectedAsset = DydxChainAsset.CHAINTOKEN,
selectedAsset = DydxChainAsset.DYDX,
onDone,
className,
}: TransferFormProps) => {
@@ -69,13 +72,12 @@ export const TransferForm = ({
const { transfer } = useSubaccount();
const { nativeTokenBalance, usdcBalance } = useAccountBalance();
const { selectedNetwork } = useSelectedNetwork();
const { tokensConfigs, usdcLabel, chainTokenLabel } = useTokenConfigs();
// User Input
const [asset, setAsset] = useState<DydxChainAsset>(selectedAsset);
// Form states
const [error, setError] = useState<string>();
const [error, setError] = useState<Error | undefined>();
const [isLoading, setIsLoading] = useState(false);
const balance = asset === DydxChainAsset.USDC ? freeCollateral?.current : nativeTokenBalance;
@@ -94,6 +96,16 @@ export const TransferForm = ({
const balanceBN = MustBigNumber(balance);
const newBalanceBN = MustBigNumber(newBalance);
const isAddressValid = useMemo(
() =>
recipientAddress &&
dydxAddress !== recipientAddress &&
validation.isValidAddress(recipientAddress),
[recipientAddress]
);
const isAmountValid = balance && amount && amountBN.gt(0) && newBalanceBN.gte(0);
useEffect(() => {
abacusStateManager.setTransferValue({
value: TransferType.transferOut.rawValue,
@@ -113,21 +125,6 @@ export const TransferForm = ({
});
}, [asset]);
const { sanctionedAddresses } = useRestrictions();
const isAddressValid = useMemo(
() =>
recipientAddress &&
dydxAddress !== recipientAddress &&
validation.isValidAddress(recipientAddress) &&
!sanctionedAddresses.has(recipientAddress),
[recipientAddress, sanctionedAddresses, dydxAddress]
);
const isAmountValid = balance && amount && amountBN.gt(0) && newBalanceBN.gte(0);
const { screenAddresses } = useDydxClient();
const onTransfer = async () => {
if (!isAmountValid || !isAddressValid || !fee) return;
setIsLoading(true);
@@ -136,54 +133,23 @@ export const TransferForm = ({
try {
// Subtract fees from amount if sending native tokens
const amountToTransfer = (
asset === DydxChainAsset.CHAINTOKEN ? amountBN.minus(fee) : amountBN
asset === DydxChainAsset.DYDX ? amountBN.minus(fee) : amountBN
).toNumber();
const screenResults = await screenAddresses({
addresses: [recipientAddress!, dydxAddress!],
});
const txResponse = await transfer(
amountToTransfer,
recipientAddress as string,
DYDX_CHAIN_ASSET_COIN_DENOM[asset]
);
if (screenResults?.[dydxAddress!]) {
setError(
stringGetter({
key: STRING_KEYS.WALLET_RESTRICTED_WITHDRAWAL_TRANSFER_ORIGINATION_ERROR_MESSAGE,
})
);
} else if (screenResults?.[recipientAddress!]) {
setError(
stringGetter({
key: STRING_KEYS.WALLET_RESTRICTED_WITHDRAWAL_TRANSFER_DESTINATION_ERROR_MESSAGE,
})
);
if (txResponse?.code === 0) {
console.log('TransferForm > txReceipt > ', txResponse?.hash);
onDone?.();
} else {
const txResponse = await transfer(
amountToTransfer,
recipientAddress as string,
tokensConfigs[asset].denom,
);
if (txResponse?.code === 0) {
console.log('TransferForm > txReceipt > ', txResponse?.hash);
onDone?.();
} else {
throw new Error(txResponse?.rawLog ?? 'Transaction did not commit.');
}
throw new Error(txResponse?.rawLog ?? 'Transaction did not commit.');
}
} catch (error) {
if (error?.code === 429) {
setError(stringGetter({ key: STRING_KEYS.RATE_LIMIT_REACHED_ERROR_MESSAGE }));
} else {
setError(
error.message
? stringGetter({
key: STRING_KEYS.SOMETHING_WENT_WRONG_WITH_MESSAGE,
params: {
ERROR_MESSAGE: error.message || stringGetter({ key: STRING_KEYS.UNKNOWN_ERROR }),
},
})
: stringGetter({ key: STRING_KEYS.SOMETHING_WENT_WRONG })
);
}
setError(error);
log('TransferForm/onTransfer', error);
} finally {
setIsLoading(false);
@@ -218,16 +184,16 @@ export const TransferForm = ({
value: DydxChainAsset.USDC,
label: (
<Styled.InlineRow>
<AssetIcon symbol="USDC" /> {usdcLabel}
<AssetIcon symbol="USDC" /> {DYDX_CHAIN_ASSET_TAGS[DydxChainAsset.USDC]}
</Styled.InlineRow>
),
},
{
value: DydxChainAsset.CHAINTOKEN,
value: DydxChainAsset.DYDX,
label: (
<Styled.InlineRow>
{/* <AssetIcon symbol="DYDX" /> */}
{chainTokenLabel}
{DYDX_CHAIN_ASSET_TAGS[DydxChainAsset.DYDX]}
</Styled.InlineRow>
),
},
@@ -249,7 +215,7 @@ export const TransferForm = ({
key: 'amount',
label: (
<span>
{stringGetter({ key: STRING_KEYS.AVAILABLE })} <Tag>{tokensConfigs[asset].name}</Tag>
{stringGetter({ key: STRING_KEYS.AVAILABLE })} <Tag>{DYDX_CHAIN_ASSET_TAGS[asset]}</Tag>
</span>
),
value: (
@@ -265,6 +231,13 @@ export const TransferForm = ({
},
];
const addressValidationErrorMessage = stringGetter({
key:
dydxAddress === recipientAddress
? STRING_KEYS.TRANSFER_TO_YOURSELF
: STRING_KEYS.TRANSFER_INVALID_DYDX_ADDRESS,
});
const renderFormInputButton = ({
label,
isInputEmpty,
@@ -329,12 +302,7 @@ export const TransferForm = ({
{recipientAddress && !isAddressValid && (
<Styled.AddressValidationAlertMessage type={AlertType.Error}>
{stringGetter({
key:
dydxAddress === recipientAddress
? STRING_KEYS.TRANSFER_TO_YOURSELF
: STRING_KEYS.TRANSFER_INVALID_DYDX_ADDRESS,
})}
{addressValidationErrorMessage}
</Styled.AddressValidationAlertMessage>
)}
@@ -374,13 +342,13 @@ export const TransferForm = ({
</AlertMessage>
)}
{error && <AlertMessage type={AlertType.Error}>{error}</AlertMessage>}
{error && <AlertMessage type={AlertType.Error}>{error.message}</AlertMessage>}
<Styled.Footer>
<TransferButtonAndReceipt
selectedAsset={asset}
fees={fee || undefined}
isDisabled={!isAmountValid || !isAddressValid || !fee || isLoading}
isDisabled={!isAmountValid || !isAddressValid || !fee}
isLoading={isLoading || Boolean(isAmountValid && isAddressValid && !fee)}
/>
</Styled.Footer>
@@ -3,9 +3,9 @@ import { shallowEqual, useSelector } from 'react-redux';
import { ButtonAction, ButtonSize, ButtonType } from '@/constants/buttons';
import { STRING_KEYS } from '@/constants/localization';
import { NumberSign } from '@/constants/numbers';
import { DydxChainAsset } from '@/constants/wallets';
import { DYDX_CHAIN_ASSET_TAGS, DydxChainAsset } from '@/constants/wallets';
import { useAccountBalance, useTokenConfigs, useStringGetter } from '@/hooks';
import { useAccountBalance, useStringGetter } from '@/hooks';
import { Button } from '@/components/Button';
import { DiffOutput } from '@/components/DiffOutput';
@@ -37,7 +37,6 @@ export const TransferButtonAndReceipt = ({
const stringGetter = useStringGetter();
const canAccountTrade = useSelector(calculateCanAccountTrade, shallowEqual);
const { size } = useSelector(getTransferInputs, shallowEqual) || {};
const { tokensConfigs } = useTokenConfigs();
const { equity: equityInfo, leverage: leverageInfo } =
useSelector(getSubaccount, shallowEqual) || {};
@@ -61,7 +60,7 @@ export const TransferButtonAndReceipt = ({
key: 'fees',
label: (
<span>
{stringGetter({ key: STRING_KEYS.FEES })} <Tag>{tokensConfigs[selectedAsset].name}</Tag>
{stringGetter({ key: STRING_KEYS.FEES })} <Tag>{DYDX_CHAIN_ASSET_TAGS[selectedAsset]}</Tag>
</span>
),
value: <Output type={OutputType.Asset} value={fees} />,
@@ -70,7 +69,7 @@ export const TransferButtonAndReceipt = ({
key: 'balance',
label: (
<span>
{stringGetter({ key: STRING_KEYS.BALANCE })} <Tag>{tokensConfigs[selectedAsset].name}</Tag>
{stringGetter({ key: STRING_KEYS.BALANCE })} <Tag>{DYDX_CHAIN_ASSET_TAGS[selectedAsset]}</Tag>
</span>
),
value: (
+4 -17
View File
@@ -9,13 +9,7 @@ import { DialogTypes } from '@/constants/dialogs';
import { STRING_KEYS, TOOLTIP_STRING_KEYS } from '@/constants/localization';
import { DydxChainAsset, wallets } from '@/constants/wallets';
import {
useAccounts,
useBreakpoints,
useTokenConfigs,
useStringGetter,
useAccountBalance,
} from '@/hooks';
import { useAccounts, useBreakpoints, useStringGetter, useAccountBalance } from '@/hooks';
import { OnboardingTriggerButton } from '@/views/dialogs/OnboardingTriggerButton';
@@ -45,7 +39,6 @@ export const AccountMenu = () => {
const onboardingState = useSelector(getOnboardingState);
const { freeCollateral } = useSelector(getSubaccount, shallowEqual) || {};
const { nativeTokenBalance } = useAccountBalance();
const { usdcLabel, chainTokenLabel } = useTokenConfigs();
const { evmAddress, walletType, dydxAddress, hdKey } = useAccounts();
@@ -114,23 +107,17 @@ export const AccountMenu = () => {
<div>
<div>
<Styled.label>
{stringGetter({
key: STRING_KEYS.ASSET_BALANCE,
params: { ASSET: chainTokenLabel },
})}
{stringGetter({ key: STRING_KEYS.ASSET_BALANCE, params: { ASSET: 'Dv4TNT' } })}
{/* <AssetIcon symbol="DYDX" /> */}
</Styled.label>
<Styled.BalanceOutput type={OutputType.Asset} value={nativeTokenBalance} />
</div>
<AssetActions asset={DydxChainAsset.CHAINTOKEN} dispatch={dispatch} />
<AssetActions asset={DydxChainAsset.DYDX} dispatch={dispatch} />
</div>
<div>
<div>
<Styled.label>
{stringGetter({
key: STRING_KEYS.ASSET_BALANCE,
params: { ASSET: usdcLabel },
})}
{stringGetter({ key: STRING_KEYS.ASSET_BALANCE, params: { ASSET: 'USDC' } })}
<AssetIcon symbol="USDC" />
</Styled.label>
<Styled.BalanceOutput
+4 -5
View File
@@ -178,11 +178,10 @@ export const NotificationsMenu = ({
};
const $UnreadIndicator = styled.div`
width: 0.5rem;
height: 0.5rem;
width: 0.5em;
height: 0.5em;
border-radius: 50%;
background-color: var(--color-accent);
border: 1px solid var(--color-layer-2);
`;
const $TriggerContainer = styled.div`
@@ -193,8 +192,8 @@ const $TriggerUnreadIndicator = styled($UnreadIndicator)`
place-self: center;
position: relative;
right: -0.2rem;
top: -0.325rem;
right: -0.425em;
top: -0.425em;
`;
const $Output = styled(Output)`