From d05066db171f5b3249a337f49c625fd03524bdad Mon Sep 17 00:00:00 2001 From: wenty22 Date: Fri, 15 Nov 2024 10:03:02 +0800 Subject: [PATCH] refactor: Refactor sdk --- common/config/rush/pnpm-lock.yaml | 87 +++-- packages/canonical-bridge-sdk/package.json | 7 +- .../src/adapters/cBridge/index.ts | 137 +++++++- .../src/adapters/cBridge/types.ts | 20 +- .../src/adapters/layerZero/index.ts | 30 +- .../src/aggregator/index.ts | 237 ++++++++++++- .../src/constants/index.ts | 2 + .../src/shared/address.ts | 11 +- .../canonical-bridge-sdk/src/shared/string.ts | 5 + .../src/core/utils/address.ts | 3 +- .../canonical-bridge-widget/src/index.tsx | 4 + .../cBridge/hooks/useCBridgeSendMaxMin.ts | 2 +- .../cBridge/hooks/useCBridgeTransferParams.ts | 143 +------- .../aggregator/adapters/cBridge/types.ts | 121 ------- .../aggregator/adapters/deBridge/types.ts | 53 --- .../aggregator/adapters/layerZero/types.ts | 22 -- .../stargate/hooks/useStargateTransfer.ts | 133 ------- .../hooks/useStargateTransferParams.ts | 2 +- .../aggregator/adapters/stargate/types.ts | 10 - .../src/modules/aggregator/index.ts | 2 - .../src/modules/aggregator/reducer.ts | 3 +- .../components/Button/TransferButton.tsx | 326 ++++++++---------- .../RouteInfo/TokenInfoTooltip.tsx | 2 +- .../transfer/hooks/useLoadingBridgeFees.ts | 3 +- 24 files changed, 639 insertions(+), 726 deletions(-) create mode 100644 packages/canonical-bridge-sdk/src/shared/string.ts delete mode 100644 packages/canonical-bridge-widget/src/modules/aggregator/adapters/cBridge/types.ts delete mode 100644 packages/canonical-bridge-widget/src/modules/aggregator/adapters/layerZero/types.ts delete mode 100644 packages/canonical-bridge-widget/src/modules/aggregator/adapters/stargate/hooks/useStargateTransfer.ts diff --git a/common/config/rush/pnpm-lock.yaml b/common/config/rush/pnpm-lock.yaml index 52fc79bc..fd2b9ee2 100644 --- a/common/config/rush/pnpm-lock.yaml +++ b/common/config/rush/pnpm-lock.yaml @@ -233,6 +233,12 @@ importers: ../../packages/canonical-bridge-sdk: devDependencies: + '@solana/web3.js': + specifier: ~1.95.4 + version: 1.95.4(bufferutil@4.0.8)(encoding@0.1.13)(utf-8-validate@5.0.9) + '@types/node': + specifier: ~22.9.0 + version: 22.9.0 '@types/react': specifier: ^18 version: 18.3.8 @@ -241,7 +247,7 @@ importers: version: 18.3.0 '@vitejs/plugin-react': specifier: ^4.2.0 - version: 4.3.1(vite@4.5.3(@types/node@22.7.5)(terser@5.31.6)) + version: 4.3.1(vite@4.5.3(@types/node@22.9.0)(terser@5.31.6)) axios: specifier: ~0.27.2 version: 0.27.2 @@ -262,10 +268,10 @@ importers: version: 2.21.14(bufferutil@4.0.8)(typescript@5.5.4)(utf-8-validate@5.0.9)(zod@3.22.4) vite: specifier: ^4.5.0 - version: 4.5.3(@types/node@22.7.5)(terser@5.31.6) + version: 4.5.3(@types/node@22.9.0)(terser@5.31.6) vite-plugin-dts: specifier: ^3.6.3 - version: 3.9.1(@types/node@22.7.5)(rollup@3.29.4)(typescript@5.5.4)(vite@4.5.3(@types/node@22.7.5)(terser@5.31.6)) + version: 3.9.1(@types/node@22.9.0)(rollup@3.29.4)(typescript@5.5.4)(vite@4.5.3(@types/node@22.9.0)(terser@5.31.6)) ../../packages/canonical-bridge-widget: dependencies: @@ -304,8 +310,8 @@ importers: specifier: ~11.13.0 version: 11.13.0(@emotion/react@11.13.3(@types/react@18.3.8)(react@18.3.1)(supports-color@9.4.0))(@types/react@18.3.8)(react@18.3.1)(supports-color@9.4.0) '@node-real/walletkit': - specifier: 2.4.1-alpha.0 - version: 2.4.1-alpha.0(@babel/runtime@7.25.0)(@react-native-async-storage/async-storage@1.24.0)(@tanstack/react-query@5.50.1(react@18.3.1))(@types/react@18.3.8)(bs58@6.0.0)(bufferutil@4.0.8)(encoding@0.1.13)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(tslib@2.7.0)(typescript@5.5.4)(utf-8-validate@5.0.9)(viem@2.21.14(bufferutil@4.0.8)(typescript@5.5.4)(utf-8-validate@5.0.9)(zod@3.22.4))(wagmi@2.12.14(@react-native-async-storage/async-storage@1.24.0)(@tanstack/query-core@5.50.1)(@tanstack/react-query@5.50.1(react@18.3.1))(@types/react@18.3.8)(bufferutil@4.0.8)(encoding@0.1.13)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(rollup@3.29.4)(typescript@5.5.4)(utf-8-validate@5.0.9)(viem@2.21.14(bufferutil@4.0.8)(typescript@5.5.4)(utf-8-validate@5.0.9)(zod@3.22.4))(zod@3.22.4))(zod@3.22.4) + specifier: 2.4.1-alpha.2 + version: 2.4.1-alpha.2(@babel/core@7.24.9)(@babel/runtime@7.25.0)(@react-native-async-storage/async-storage@1.24.0)(@tanstack/react-query@5.50.1(react@18.3.1))(@types/react@18.3.8)(bs58@6.0.0)(bufferutil@4.0.8)(encoding@0.1.13)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(tslib@2.7.0)(typescript@5.5.4)(utf-8-validate@5.0.9)(viem@2.21.14(bufferutil@4.0.8)(typescript@5.5.4)(utf-8-validate@5.0.9)(zod@3.22.4))(wagmi@2.12.14(@react-native-async-storage/async-storage@1.24.0)(@tanstack/query-core@5.50.1)(@tanstack/react-query@5.50.1(react@18.3.1))(@types/react@18.3.8)(bufferutil@4.0.8)(encoding@0.1.13)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(rollup@3.29.4)(typescript@5.5.4)(utf-8-validate@5.0.9)(viem@2.21.14(bufferutil@4.0.8)(typescript@5.5.4)(utf-8-validate@5.0.9)(zod@3.22.4))(zod@3.22.4))(zod@3.22.4) '@tanstack/react-query': specifier: ~5.50.1 version: 5.50.1(react@18.3.1) @@ -2993,8 +2999,8 @@ packages: viem: ^2 wagmi: ^2 - '@node-real/walletkit@2.4.1-alpha.0': - resolution: {integrity: sha512-rl/uXrktICOROw4cGWXAmIdA9Hw8QlBW/GVYts2ucSJuwrST0EInM10Z7jwNCdJyn1ANDwzB5L/lA41BDJPafA==} + '@node-real/walletkit@2.4.1-alpha.2': + resolution: {integrity: sha512-0j3L7z8hWG26JyT6aUg6lEl9y2+rxRfpQHk61cQ68rL4UF58h4ZTkpNvENz6IW19adeLb4Yzcjzjf4wViS9aUA==} peerDependencies: '@tanstack/react-query': ^5 react: '>=17' @@ -4499,6 +4505,9 @@ packages: '@types/node@22.7.5': resolution: {integrity: sha512-jML7s2NAzMWc//QSJ1a3prpk78cOPchGvXJsC3C6R6PSMoooztvRVQEz89gmBTBY1SPMaqo5teB4uNHPdetShQ==} + '@types/node@22.9.0': + resolution: {integrity: sha512-vuyHg81vvWA1Z1ELfvLko2c8f34gyA0zaic0+Rllc5lbCnbSyuvb2Oxpm6TAUAC/2xZN3QGqxBNggD1nNR2AfQ==} + '@types/normalize-package-data@2.4.1': resolution: {integrity: sha512-Gj7cI7z+98M282Tqmp2K5EIsoouUEzbBJhQQzDE3jSIRk6r9gsz0oUokqIUR4u1R3dMHo0pDHM7sNOHyhulypw==} @@ -15590,11 +15599,11 @@ snapshots: transitivePeerDependencies: - '@types/node' - '@microsoft/api-extractor-model@7.28.13(@types/node@22.7.5)': + '@microsoft/api-extractor-model@7.28.13(@types/node@22.9.0)': dependencies: '@microsoft/tsdoc': 0.14.2 '@microsoft/tsdoc-config': 0.16.2 - '@rushstack/node-core-library': 4.0.2(@types/node@22.7.5) + '@rushstack/node-core-library': 4.0.2(@types/node@22.9.0) transitivePeerDependencies: - '@types/node' @@ -15616,15 +15625,15 @@ snapshots: transitivePeerDependencies: - '@types/node' - '@microsoft/api-extractor@7.43.0(@types/node@22.7.5)': + '@microsoft/api-extractor@7.43.0(@types/node@22.9.0)': dependencies: - '@microsoft/api-extractor-model': 7.28.13(@types/node@22.7.5) + '@microsoft/api-extractor-model': 7.28.13(@types/node@22.9.0) '@microsoft/tsdoc': 0.14.2 '@microsoft/tsdoc-config': 0.16.2 - '@rushstack/node-core-library': 4.0.2(@types/node@22.7.5) + '@rushstack/node-core-library': 4.0.2(@types/node@22.9.0) '@rushstack/rig-package': 0.5.2 - '@rushstack/terminal': 0.10.0(@types/node@22.7.5) - '@rushstack/ts-command-line': 4.19.1(@types/node@22.7.5) + '@rushstack/terminal': 0.10.0(@types/node@22.9.0) + '@rushstack/ts-command-line': 4.19.1(@types/node@22.9.0) lodash: 4.17.21 minimatch: 3.0.5 resolve: 1.22.8 @@ -15978,11 +15987,11 @@ snapshots: - utf-8-validate - zod - '@node-real/walletkit@2.4.1-alpha.0(@babel/runtime@7.25.0)(@react-native-async-storage/async-storage@1.24.0)(@tanstack/react-query@5.50.1(react@18.3.1))(@types/react@18.3.8)(bs58@6.0.0)(bufferutil@4.0.8)(encoding@0.1.13)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(tslib@2.7.0)(typescript@5.5.4)(utf-8-validate@5.0.9)(viem@2.21.14(bufferutil@4.0.8)(typescript@5.5.4)(utf-8-validate@5.0.9)(zod@3.22.4))(wagmi@2.12.14(@react-native-async-storage/async-storage@1.24.0)(@tanstack/query-core@5.50.1)(@tanstack/react-query@5.50.1(react@18.3.1))(@types/react@18.3.8)(bufferutil@4.0.8)(encoding@0.1.13)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(rollup@3.29.4)(typescript@5.5.4)(utf-8-validate@5.0.9)(viem@2.21.14(bufferutil@4.0.8)(typescript@5.5.4)(utf-8-validate@5.0.9)(zod@3.22.4))(zod@3.22.4))(zod@3.22.4)': + '@node-real/walletkit@2.4.1-alpha.2(@babel/core@7.24.9)(@babel/runtime@7.25.0)(@react-native-async-storage/async-storage@1.24.0)(@tanstack/react-query@5.50.1(react@18.3.1))(@types/react@18.3.8)(bs58@6.0.0)(bufferutil@4.0.8)(encoding@0.1.13)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(tslib@2.7.0)(typescript@5.5.4)(utf-8-validate@5.0.9)(viem@2.21.14(bufferutil@4.0.8)(typescript@5.5.4)(utf-8-validate@5.0.9)(zod@3.22.4))(wagmi@2.12.14(@react-native-async-storage/async-storage@1.24.0)(@tanstack/query-core@5.50.1)(@tanstack/react-query@5.50.1(react@18.3.1))(@types/react@18.3.8)(bufferutil@4.0.8)(encoding@0.1.13)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(rollup@3.29.4)(typescript@5.5.4)(utf-8-validate@5.0.9)(viem@2.21.14(bufferutil@4.0.8)(typescript@5.5.4)(utf-8-validate@5.0.9)(zod@3.22.4))(zod@3.22.4))(zod@3.22.4)': dependencies: '@metamask/jazzicon': 2.0.0 '@solana/wallet-adapter-react': 0.15.35(@solana/web3.js@1.95.4(bufferutil@4.0.8)(encoding@0.1.13)(utf-8-validate@5.0.9))(bs58@6.0.0)(react@18.3.1) - '@solana/wallet-adapter-wallets': 0.19.32(@babel/runtime@7.25.0)(@react-native-async-storage/async-storage@1.24.0)(@solana/web3.js@1.95.4(bufferutil@4.0.8)(encoding@0.1.13)(utf-8-validate@5.0.9))(bs58@6.0.0)(bufferutil@4.0.8)(encoding@0.1.13)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(tslib@2.7.0)(utf-8-validate@5.0.9) + '@solana/wallet-adapter-wallets': 0.19.32(@babel/core@7.24.9)(@babel/runtime@7.25.0)(@react-native-async-storage/async-storage@1.24.0)(@solana/web3.js@1.95.4(bufferutil@4.0.8)(encoding@0.1.13)(utf-8-validate@5.0.9))(bs58@6.0.0)(bufferutil@4.0.8)(encoding@0.1.13)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(tslib@2.7.0)(utf-8-validate@5.0.9) '@solana/web3.js': 1.95.4(bufferutil@4.0.8)(encoding@0.1.13)(utf-8-validate@5.0.9) '@tanstack/react-query': 5.50.1(react@18.3.1) '@tronweb3/tronwallet-abstract-adapter': 1.1.7 @@ -16260,7 +16269,7 @@ snapshots: optionalDependencies: '@types/node': 20.11.21 - '@rushstack/node-core-library@4.0.2(@types/node@22.7.5)': + '@rushstack/node-core-library@4.0.2(@types/node@22.9.0)': dependencies: fs-extra: 7.0.1 import-lazy: 4.0.0 @@ -16269,7 +16278,7 @@ snapshots: semver: 7.5.4 z-schema: 5.0.5 optionalDependencies: - '@types/node': 22.7.5 + '@types/node': 22.9.0 '@rushstack/rig-package@0.5.2': dependencies: @@ -16283,12 +16292,12 @@ snapshots: optionalDependencies: '@types/node': 20.11.21 - '@rushstack/terminal@0.10.0(@types/node@22.7.5)': + '@rushstack/terminal@0.10.0(@types/node@22.9.0)': dependencies: - '@rushstack/node-core-library': 4.0.2(@types/node@22.7.5) + '@rushstack/node-core-library': 4.0.2(@types/node@22.9.0) supports-color: 8.1.1 optionalDependencies: - '@types/node': 22.7.5 + '@types/node': 22.9.0 '@rushstack/ts-command-line@4.19.1(@types/node@20.11.21)': dependencies: @@ -16299,9 +16308,9 @@ snapshots: transitivePeerDependencies: - '@types/node' - '@rushstack/ts-command-line@4.19.1(@types/node@22.7.5)': + '@rushstack/ts-command-line@4.19.1(@types/node@22.9.0)': dependencies: - '@rushstack/terminal': 0.10.0(@types/node@22.7.5) + '@rushstack/terminal': 0.10.0(@types/node@22.9.0) '@types/argparse': 1.0.38 argparse: 1.0.10 string-argv: 0.3.1 @@ -16753,11 +16762,11 @@ snapshots: - tslib - utf-8-validate - '@solana/wallet-adapter-trezor@0.1.2(@solana/web3.js@1.95.4(bufferutil@4.0.8)(encoding@0.1.13)(utf-8-validate@5.0.9))(bufferutil@4.0.8)(encoding@0.1.13)(tslib@2.7.0)(utf-8-validate@5.0.9)': + '@solana/wallet-adapter-trezor@0.1.2(@babel/core@7.24.9)(@solana/web3.js@1.95.4(bufferutil@4.0.8)(encoding@0.1.13)(utf-8-validate@5.0.9))(bufferutil@4.0.8)(encoding@0.1.13)(tslib@2.7.0)(utf-8-validate@5.0.9)': dependencies: '@solana/wallet-adapter-base': 0.9.23(@solana/web3.js@1.95.4(bufferutil@4.0.8)(encoding@0.1.13)(utf-8-validate@5.0.9)) '@solana/web3.js': 1.95.4(bufferutil@4.0.8)(encoding@0.1.13)(utf-8-validate@5.0.9) - '@trezor/connect-web': 9.3.0(bufferutil@4.0.8)(encoding@0.1.13)(tslib@2.7.0)(utf-8-validate@5.0.9) + '@trezor/connect-web': 9.3.0(@babel/core@7.24.9)(bufferutil@4.0.8)(encoding@0.1.13)(tslib@2.7.0)(utf-8-validate@5.0.9) buffer: 6.0.3 transitivePeerDependencies: - '@babel/core' @@ -16873,7 +16882,7 @@ snapshots: - tslib - utf-8-validate - '@solana/wallet-adapter-wallets@0.19.32(@babel/runtime@7.25.0)(@react-native-async-storage/async-storage@1.24.0)(@solana/web3.js@1.95.4(bufferutil@4.0.8)(encoding@0.1.13)(utf-8-validate@5.0.9))(bs58@6.0.0)(bufferutil@4.0.8)(encoding@0.1.13)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(tslib@2.7.0)(utf-8-validate@5.0.9)': + '@solana/wallet-adapter-wallets@0.19.32(@babel/core@7.24.9)(@babel/runtime@7.25.0)(@react-native-async-storage/async-storage@1.24.0)(@solana/web3.js@1.95.4(bufferutil@4.0.8)(encoding@0.1.13)(utf-8-validate@5.0.9))(bs58@6.0.0)(bufferutil@4.0.8)(encoding@0.1.13)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(tslib@2.7.0)(utf-8-validate@5.0.9)': dependencies: '@solana/wallet-adapter-alpha': 0.1.10(@solana/web3.js@1.95.4(bufferutil@4.0.8)(encoding@0.1.13)(utf-8-validate@5.0.9)) '@solana/wallet-adapter-avana': 0.1.13(@solana/web3.js@1.95.4(bufferutil@4.0.8)(encoding@0.1.13)(utf-8-validate@5.0.9)) @@ -16906,7 +16915,7 @@ snapshots: '@solana/wallet-adapter-tokenary': 0.1.12(@solana/web3.js@1.95.4(bufferutil@4.0.8)(encoding@0.1.13)(utf-8-validate@5.0.9)) '@solana/wallet-adapter-tokenpocket': 0.4.19(@solana/web3.js@1.95.4(bufferutil@4.0.8)(encoding@0.1.13)(utf-8-validate@5.0.9)) '@solana/wallet-adapter-torus': 0.11.28(@babel/runtime@7.25.0)(@solana/web3.js@1.95.4(bufferutil@4.0.8)(encoding@0.1.13)(utf-8-validate@5.0.9))(bufferutil@4.0.8)(encoding@0.1.13)(supports-color@9.4.0)(utf-8-validate@5.0.9) - '@solana/wallet-adapter-trezor': 0.1.2(@solana/web3.js@1.95.4(bufferutil@4.0.8)(encoding@0.1.13)(utf-8-validate@5.0.9))(bufferutil@4.0.8)(encoding@0.1.13)(tslib@2.7.0)(utf-8-validate@5.0.9) + '@solana/wallet-adapter-trezor': 0.1.2(@babel/core@7.24.9)(@solana/web3.js@1.95.4(bufferutil@4.0.8)(encoding@0.1.13)(utf-8-validate@5.0.9))(bufferutil@4.0.8)(encoding@0.1.13)(tslib@2.7.0)(utf-8-validate@5.0.9) '@solana/wallet-adapter-trust': 0.1.13(@solana/web3.js@1.95.4(bufferutil@4.0.8)(encoding@0.1.13)(utf-8-validate@5.0.9)) '@solana/wallet-adapter-unsafe-burner': 0.1.7(@solana/web3.js@1.95.4(bufferutil@4.0.8)(encoding@0.1.13)(utf-8-validate@5.0.9)) '@solana/wallet-adapter-walletconnect': 0.1.16(@react-native-async-storage/async-storage@1.24.0)(@solana/web3.js@1.95.4(bufferutil@4.0.8)(encoding@0.1.13)(utf-8-validate@5.0.9))(bufferutil@4.0.8)(encoding@0.1.13)(supports-color@9.4.0)(utf-8-validate@5.0.9) @@ -18418,9 +18427,9 @@ snapshots: - supports-color - utf-8-validate - '@trezor/connect-web@9.3.0(bufferutil@4.0.8)(encoding@0.1.13)(tslib@2.7.0)(utf-8-validate@5.0.9)': + '@trezor/connect-web@9.3.0(@babel/core@7.24.9)(bufferutil@4.0.8)(encoding@0.1.13)(tslib@2.7.0)(utf-8-validate@5.0.9)': dependencies: - '@trezor/connect': 9.3.0(bufferutil@4.0.8)(encoding@0.1.13)(tslib@2.7.0)(utf-8-validate@5.0.9) + '@trezor/connect': 9.3.0(@babel/core@7.24.9)(bufferutil@4.0.8)(encoding@0.1.13)(tslib@2.7.0)(utf-8-validate@5.0.9) '@trezor/connect-common': 0.1.0(tslib@2.7.0) '@trezor/utils': 9.1.0(tslib@2.7.0) tslib: 2.7.0 @@ -18465,7 +18474,7 @@ snapshots: - supports-color - utf-8-validate - '@trezor/connect@9.3.0(bufferutil@4.0.8)(encoding@0.1.13)(tslib@2.7.0)(utf-8-validate@5.0.9)': + '@trezor/connect@9.3.0(@babel/core@7.24.9)(bufferutil@4.0.8)(encoding@0.1.13)(tslib@2.7.0)(utf-8-validate@5.0.9)': dependencies: '@babel/preset-typescript': 7.24.7(@babel/core@7.24.9) '@ethereumjs/common': 4.3.0 @@ -18873,6 +18882,10 @@ snapshots: dependencies: undici-types: 6.19.8 + '@types/node@22.9.0': + dependencies: + undici-types: 6.19.8 + '@types/normalize-package-data@2.4.1': {} '@types/npmlog@4.1.4': {} @@ -19279,14 +19292,14 @@ snapshots: transitivePeerDependencies: - supports-color - '@vitejs/plugin-react@4.3.1(vite@4.5.3(@types/node@22.7.5)(terser@5.31.6))': + '@vitejs/plugin-react@4.3.1(vite@4.5.3(@types/node@22.9.0)(terser@5.31.6))': dependencies: '@babel/core': 7.24.9 '@babel/plugin-transform-react-jsx-self': 7.24.7(@babel/core@7.24.9) '@babel/plugin-transform-react-jsx-source': 7.24.7(@babel/core@7.24.9) '@types/babel__core': 7.20.5 react-refresh: 0.14.2 - vite: 4.5.3(@types/node@22.7.5)(terser@5.31.6) + vite: 4.5.3(@types/node@22.9.0)(terser@5.31.6) transitivePeerDependencies: - supports-color @@ -28606,9 +28619,9 @@ snapshots: - rollup - supports-color - vite-plugin-dts@3.9.1(@types/node@22.7.5)(rollup@3.29.4)(typescript@5.5.4)(vite@4.5.3(@types/node@22.7.5)(terser@5.31.6)): + vite-plugin-dts@3.9.1(@types/node@22.9.0)(rollup@3.29.4)(typescript@5.5.4)(vite@4.5.3(@types/node@22.9.0)(terser@5.31.6)): dependencies: - '@microsoft/api-extractor': 7.43.0(@types/node@22.7.5) + '@microsoft/api-extractor': 7.43.0(@types/node@22.9.0) '@rollup/pluginutils': 5.1.0(rollup@3.29.4) '@vue/language-core': 1.8.27(typescript@5.5.4) debug: 4.3.4(supports-color@9.4.0) @@ -28617,7 +28630,7 @@ snapshots: typescript: 5.5.4 vue-tsc: 1.8.27(typescript@5.5.4) optionalDependencies: - vite: 4.5.3(@types/node@22.7.5)(terser@5.31.6) + vite: 4.5.3(@types/node@22.9.0)(terser@5.31.6) transitivePeerDependencies: - '@types/node' - rollup @@ -28633,13 +28646,13 @@ snapshots: fsevents: 2.3.3 terser: 5.31.6 - vite@4.5.3(@types/node@22.7.5)(terser@5.31.6): + vite@4.5.3(@types/node@22.9.0)(terser@5.31.6): dependencies: esbuild: 0.18.20 postcss: 8.4.31 rollup: 3.29.4 optionalDependencies: - '@types/node': 22.7.5 + '@types/node': 22.9.0 fsevents: 2.3.3 terser: 5.31.6 diff --git a/packages/canonical-bridge-sdk/package.json b/packages/canonical-bridge-sdk/package.json index cf4bb52a..b1520bf0 100644 --- a/packages/canonical-bridge-sdk/package.json +++ b/packages/canonical-bridge-sdk/package.json @@ -30,9 +30,11 @@ }, "peerDependencies": { "axios": "^0", - "viem": "^2" + "viem": "^2", + "@solana/web3.js": "^1" }, "devDependencies": { + "@solana/web3.js": "~1.95.4", "@types/react": "^18", "@types/react-dom": "^18", "@vitejs/plugin-react": "^4.2.0", @@ -43,6 +45,7 @@ "typescript": "^5", "viem": "~2.21.14", "vite": "^4.5.0", - "vite-plugin-dts": "^3.6.3" + "vite-plugin-dts": "^3.6.3", + "@types/node": "~22.9.0" } } diff --git a/packages/canonical-bridge-sdk/src/adapters/cBridge/index.ts b/packages/canonical-bridge-sdk/src/adapters/cBridge/index.ts index 1f21caeb..7e307258 100644 --- a/packages/canonical-bridge-sdk/src/adapters/cBridge/index.ts +++ b/packages/canonical-bridge-sdk/src/adapters/cBridge/index.ts @@ -1,4 +1,4 @@ -import { getContract, Hash, isAddress } from 'viem'; +import { getContract, Hash, isAddress, parseUnits } from 'viem'; import { BaseAdapter } from '@/adapters/base'; import { IInitialOptions, ITransferTokenPair } from '@/adapters/base/types'; import { @@ -18,7 +18,7 @@ import { IGetCBridgeTransferParamsInput, ISendCBridgeToken, } from '@/adapters/cBridge/types'; -import { BridgeType } from '@/aggregator/types'; +import { BridgeType, IBridgeChain, IBridgeToken } from '@/aggregator/types'; import axios, { AxiosInstance } from 'axios'; import { CLIENT_TIME_OUT, env } from '@/constants'; import { @@ -28,6 +28,7 @@ import { PEGGED_TOKEN_BRIDGE, PEGGED_TOKEN_BRIDGE_V2, } from '@/adapters/cBridge/exports'; +import { isNativeToken } from '@/shared/address'; export class CBridgeAdapter extends BaseAdapter< ICBridgeTransferConfig, @@ -392,6 +393,138 @@ export class CBridgeAdapter extends BaseAdapter< }; } + public getTransactionParams({ + userAddress, + fromChain, + toChain, + fromToken, + sendValue, + slippage, + }: { + userAddress: string; + fromChain: IBridgeChain; + toChain: IBridgeChain; + fromToken: IBridgeToken; + sendValue: string; + slippage: number; + }) { + const isPegged = !!fromToken.isPegged; + + const bridgeAddress = (() => { + try { + if ( + !fromChain || + (isPegged && !fromToken?.cBridge?.peggedConfig) || + (!isPegged && !fromChain?.cBridge?.raw) + ) { + return null; + } + return this.getTransferAddress({ + fromChainId: fromChain?.id as number, + isPegged, + peggedConfig: fromToken?.cBridge?.peggedConfig, + chainConfig: fromChain?.cBridge?.raw, + }); + } catch (e: any) { + // eslint-disable-next-line no-console + console.log(e); + } + })(); + + // Mint/deposit or burn/withdraw + const transferType = (() => { + if (fromToken?.cBridge?.peggedConfig?.org_chain_id === fromChain?.id) { + return 'deposit'; + } + if (fromToken?.cBridge?.peggedConfig?.pegged_chain_id === fromChain?.id) { + return 'withdraw'; + } + return ''; + })(); + + const argument = (() => { + if ( + !sendValue || + sendValue === '0' || + !toChain || + !fromToken || + !userAddress + ) { + return null; + } + const nonce = new Date().getTime(); + + let amount = 0n; + try { + if (fromToken.isPegged === false) { + amount = parseUnits( + sendValue, + fromToken?.cBridge?.raw?.token.decimal as number + ); // Convert to big number + } else if (transferType === 'deposit') { + amount = parseUnits( + sendValue, + fromToken?.cBridge?.peggedConfig?.org_token.token.decimal as number + ); + } else if (transferType === 'withdraw') { + amount = parseUnits( + sendValue, + fromToken?.cBridge?.peggedConfig?.pegged_token.token + .decimal as number + ); + } + } catch (e: any) { + // eslint-disable-next-line no-console + console.log(e); + } + + return this.getTransferParams({ + amount, + isPegged, + toChainId: toChain.id, + tokenAddress: fromToken?.address as `0x${string}`, + address: userAddress as `0x${string}`, + maxSlippage: slippage, + transferType: transferType ? transferType : undefined, + peggedConfig: fromToken.cBridge?.peggedConfig, + isNativeToken: isNativeToken(fromToken.address), + nonce, + }); + })(); + + // Arguments for bridge smart contract + const args = (() => { + const peggedConfig = fromToken?.cBridge?.peggedConfig; + if ( + !argument || + (isPegged && !transferType) || + !userAddress || + !bridgeAddress || + !fromToken + ) { + return null; + } + const abi = this.getABI({ + isPegged, + transferType: transferType || undefined, + peggedConfig, + }); + const functionName = this.getTransferFunction({ + isPegged, + isNativeToken: isNativeToken(fromToken?.address), + transferType: transferType || undefined, + }); + return { + address: bridgeAddress as `0x${string}`, + abi: abi, + functionName: functionName, + account: userAddress as `0x${string}`, + args: argument, + }; + })(); + return { args, bridgeAddress }; + } + public init(initialOptions?: IInitialOptions) { this.initOptions(initialOptions); diff --git a/packages/canonical-bridge-sdk/src/adapters/cBridge/types.ts b/packages/canonical-bridge-sdk/src/adapters/cBridge/types.ts index ed47b046..0ad79e4e 100644 --- a/packages/canonical-bridge-sdk/src/adapters/cBridge/types.ts +++ b/packages/canonical-bridge-sdk/src/adapters/cBridge/types.ts @@ -142,16 +142,6 @@ export interface ICBridgeTransactionResponse { error: null | unknown; } -export interface ICBridgeEstimateAmountRequest { - src_chain_id: number; - dst_chain_id: number; - token_symbol: string; - amt: string; - user_addr?: string; - slippage_tolerance: number; - is_pegged?: boolean; -} - export interface ICBridgeEstimateAmountResponse { err: object; eq_value_token_amt: string; @@ -222,3 +212,13 @@ export interface ICBridgeMaxMinSendAmt { max: string; min: string; } + +export interface ICBridgeEstimateAmountRequest { + src_chain_id: number; + dst_chain_id: number; + token_symbol: string; + amt: string; + user_addr?: string; + slippage_tolerance: number; + is_pegged?: boolean; +} diff --git a/packages/canonical-bridge-sdk/src/adapters/layerZero/index.ts b/packages/canonical-bridge-sdk/src/adapters/layerZero/index.ts index df239967..addbb696 100644 --- a/packages/canonical-bridge-sdk/src/adapters/layerZero/index.ts +++ b/packages/canonical-bridge-sdk/src/adapters/layerZero/index.ts @@ -41,13 +41,22 @@ export class LayerZeroAdapter extends BaseAdapter< walletClient, gasAmount = 200000n, version = 1, + airDropGas = 0n, + dstAddress = '0x', }: ISendCakeTokenInput): Promise { try { const address32Bytes = pad(userAddress, { size: 32 }); - const adapterParams = encodePacked( - ['uint16', 'uint256'], - [version, gasAmount] - ); + /* version 1 - send token + * version 2 - send token and air drop native gas on destination chain + * https://docs.layerzero.network/v1/developers/evm/evm-guides/advanced/relayer-adapter-parameters#airdrop + */ + const adapterParams = + version === 1 + ? encodePacked(['uint16', 'uint256'], [version, gasAmount]) + : encodePacked( + ['uint16', 'uint', 'uint', 'address'], + [2, gasAmount, airDropGas, dstAddress] + ); const fees = await publicClient.readContract({ address: bridgeAddress, abi: CAKE_PROXY_OFT_ABI, @@ -117,13 +126,18 @@ export class LayerZeroAdapter extends BaseAdapter< publicClient, gasAmount = 200000n, version = 1, + airDropGas = 0n, + dstAddress = '0x', }: IGetEstimateFeeInput) { try { const address32Bytes = pad(userAddress, { size: 32 }); - const adapterParams = encodePacked( - ['uint16', 'uint256'], - [version, gasAmount] - ); + const adapterParams = + version === 1 + ? encodePacked(['uint16', 'uint256'], [version, gasAmount]) + : encodePacked( + ['uint16', 'uint', 'uint', 'address'], + [2, gasAmount, airDropGas, dstAddress] + ); const fees = await publicClient.readContract({ address: bridgeAddress, abi: CAKE_PROXY_OFT_ABI, diff --git a/packages/canonical-bridge-sdk/src/aggregator/index.ts b/packages/canonical-bridge-sdk/src/aggregator/index.ts index 2eb993f6..28b4b78d 100644 --- a/packages/canonical-bridge-sdk/src/aggregator/index.ts +++ b/packages/canonical-bridge-sdk/src/aggregator/index.ts @@ -22,7 +22,15 @@ import { } from '@/aggregator/types'; import { sortChains } from '@/aggregator/utils/sortChains'; import { sortTokens } from '@/aggregator/utils/sortTokens'; -import { formatUnits, Hash, PublicClient } from 'viem'; +import { DEFAULT_SLIPPAGE } from '@/constants'; +import { isNativeToken } from '@/shared/address'; +import { utf8ToHex } from '@/shared/string'; +import { Hash, parseUnits, PublicClient, WalletClient } from 'viem'; +import { + VersionedTransaction, + Connection, + TransactionSignature, +} from '@solana/web3.js'; export interface CanonicalBridgeSDKOptions { chains: IChainConfig[]; @@ -223,8 +231,8 @@ export class CanonicalBridgeSDK { tokenAddress, userAddress, toUserAddress, - amount, - slippage = 10000, + sendValue, + slippage = DEFAULT_SLIPPAGE, }: { publicClient: PublicClient; fromChainId: number; @@ -232,7 +240,7 @@ export class CanonicalBridgeSDK { tokenAddress: string; userAddress: string; toUserAddress?: string; - amount: bigint; + sendValue: string; slippage?: number; }) { const { fromChain, toChain, fromToken, toToken } = this.getParamDetails({ @@ -246,6 +254,7 @@ export class CanonicalBridgeSDK { throw new Error('Missing parameters'); } + const amount = parseUnits(sendValue, fromToken.decimals); const promiseArr: Array<{ bridgeType: BridgeType; apiCall: Promise }> = []; @@ -351,11 +360,10 @@ export class CanonicalBridgeSDK { // meson if (this.meson && fromToken?.meson?.raw?.id && toToken?.meson?.raw?.id) { - const mesonAmount = formatUnits(amount, fromToken.meson.raw.decimals); const mesonFeeAPICall = this.meson.getEstimatedFees({ fromToken: `${fromChain?.meson?.raw?.id}:${fromToken?.meson?.raw?.id}`, toToken: `${toChain?.meson?.raw?.id}:${toToken?.meson?.raw?.id}`, - amount: mesonAmount, + amount: sendValue, fromAddr: userAddress, }); promiseArr.push({ @@ -377,6 +385,223 @@ export class CanonicalBridgeSDK { ) as Record>; } + async sendToken({ + bridgeType, + publicClient, + walletClient, + fromChainId, + toChainId, + tokenAddress, + userAddress, + toUserAddress, + sendValue, + slippage = DEFAULT_SLIPPAGE, + solanaOpts, + mesonOpts, + }: { + bridgeType: BridgeType; + publicClient: PublicClient; + walletClient: WalletClient; + fromChainId: number; + toChainId: number; + tokenAddress: string; + userAddress: string; + toUserAddress?: string; + sendValue: string; + slippage?: number; + solanaOpts?: { + connection: Connection; + sendTransaction: ( + transaction: VersionedTransaction, + connection: Connection + ) => Promise; + }; + mesonOpts?: { + signMessage: (message: string) => Promise; + signTransaction: (message: string) => Promise; + }; + }) { + const { fromChain, toChain, fromToken, toToken } = this.getParamDetails({ + fromChainId, + toChainId, + tokenAddress, + }); + + if (!fromChain || !toChain || !fromToken || !toToken) { + console.log(fromChain, toChain, fromToken, toToken); + throw new Error('Missing parameters'); + } + + const amount = parseUnits(sendValue, fromToken.decimals); + + if (bridgeType === 'cBridge' && this.cBridge) { + const { args, bridgeAddress } = this.cBridge.getTransactionParams({ + fromChain, + toChain, + fromToken, + userAddress, + sendValue, + slippage, + }); + + const hash = await this.cBridge.sendToken({ + walletClient, + publicClient, + bridgeAddress: bridgeAddress as string, + fromChainId, + isPegged: fromToken.isPegged, + isNativeToken: isNativeToken(fromToken.address), + address: userAddress as `0x${string}`, + peggedConfig: fromToken.cBridge?.peggedConfig, + args, + }); + + await publicClient.waitForTransactionReceipt({ + hash, + }); + + return { + hash, + }; + } + + if (bridgeType === 'deBridge' && this.deBridge) { + const txQuote = await this.deBridge.getEstimatedFees({ + fromChainId, + toChainId, + fromTokenAddress: fromToken.deBridge?.raw?.address as `0x${string}`, + toTokenAddress: toToken.deBridge?.raw?.address as `0x${string}`, + amount, + userAddress, + toUserAddress: toUserAddress || userAddress, + }); + + if (fromChain.chainType === 'evm') { + const hash = await this.deBridge?.sendToken({ + walletClient, + bridgeAddress: txQuote.tx.to as string, + data: txQuote.tx.data as `0x${string}`, + amount: BigInt(txQuote.tx.value), + address: userAddress as `0x${string}`, + }); + + await publicClient.waitForTransactionReceipt({ + hash, + }); + + return { + hash, + }; + } + + if (fromChain?.chainType === 'solana') { + if (solanaOpts) { + const { connection, sendTransaction } = solanaOpts; + + const { blockhash } = await connection.getLatestBlockhash(); + const data = (txQuote.tx.data as string)?.slice(2); + const tx = VersionedTransaction.deserialize(Buffer.from(data, 'hex')); + + tx.message.recentBlockhash = blockhash; + const hash = await sendTransaction(tx, connection); + + return { + hash, + }; + } else { + throw Error('Parameter [solanaOpts] is required'); + } + } + } + + if (bridgeType === 'stargate' && this.stargate) { + const hash = await this.stargate?.sendToken({ + walletClient, + publicClient, + bridgeAddress: fromToken.stargate?.raw?.bridgeAddress as `0x${string}`, + tokenAddress: fromToken.stargate?.raw?.address as `0x${string}`, + endPointId: toToken.stargate?.raw?.endpointID as number, + receiver: userAddress as `0x${string}`, + amount, + }); + + return { + hash, + }; + } + + if (bridgeType === 'layerZero' && this.layerZero) { + const hash = await this.layerZero?.sendToken({ + walletClient, + publicClient, + bridgeAddress: fromToken.layerZero?.raw?.bridgeAddress as `0x${string}`, + dstEndpoint: toToken.layerZero?.raw?.endpointID as number, + userAddress: userAddress as `0x${string}`, + amount, + }); + + return { + hash, + }; + } + + if (bridgeType === 'meson' && this.meson) { + if (mesonOpts) { + const { signMessage, signTransaction } = mesonOpts; + + let message = ''; + let signature = ''; + + // get unsigned message + const unsignedMessage = await this.meson.getUnsignedMessage({ + fromToken: `${fromChain?.meson?.raw?.id}:${fromToken?.meson?.raw?.id}`, + toToken: `${toChain?.meson?.raw?.id}:${toToken?.meson?.raw?.id}`, + amount: sendValue, + fromAddress: userAddress, + recipient: toUserAddress || userAddress, + }); + + if (unsignedMessage?.result) { + const result = unsignedMessage.result; + const encodedData = result.encoded; + const signingMessage = result.signingRequest.message; + + if (fromChain?.chainType === 'tron') { + const hexTronHeader = utf8ToHex('\x19TRON Signed Message:\n32'); + message = signingMessage.replace(hexTronHeader, ''); + } else { + const hexEthHeader = utf8ToHex('\x19Ethereum Signed Message:\n52'); + message = signingMessage.replace(hexEthHeader, ''); + } + + if (fromChain?.chainType != 'tron') { + signature = await signMessage(message); + } else { + // TODO + signature = await signTransaction(message); + } + + const swapId = await this.meson?.sendToken({ + fromAddress: userAddress, + recipient: toUserAddress || userAddress, + signature: signature, + encodedData: encodedData, + }); + + return { + swapId, + }; + } else { + throw new Error(unsignedMessage?.error.message); + } + } else { + throw Error('Parameter [mesonOpts] is required'); + } + } + + return {}; + } + public getFromChains() { const chainMap = new Map(); diff --git a/packages/canonical-bridge-sdk/src/constants/index.ts b/packages/canonical-bridge-sdk/src/constants/index.ts index c6a9f5a5..45646b2b 100644 --- a/packages/canonical-bridge-sdk/src/constants/index.ts +++ b/packages/canonical-bridge-sdk/src/constants/index.ts @@ -16,3 +16,5 @@ export const EXPLORER_URL: Record<(typeof ExplorerList)[number], string> = { cBridge: 'https://celerscan.com/tx/', deBridge: 'https://app.debridge.finance/orders?s=', }; + +export const DEFAULT_SLIPPAGE = 10000; diff --git a/packages/canonical-bridge-sdk/src/shared/address.ts b/packages/canonical-bridge-sdk/src/shared/address.ts index 570e7b0a..c76bfbc8 100644 --- a/packages/canonical-bridge-sdk/src/shared/address.ts +++ b/packages/canonical-bridge-sdk/src/shared/address.ts @@ -1,3 +1,5 @@ +import { ChainType } from '@/aggregator/types'; + export function isSameAddress(A?: string, B?: string) { if (!A || !B) return false; @@ -12,7 +14,14 @@ export function isEvmAddress(address?: string) { return !!address && /^0x[a-f0-9]{40}$/i.test(address); } -export function isNativeToken(tokenAddress: string) { +export function isNativeToken( + tokenAddress: string, + chainType: ChainType = 'evm' +) { + if (chainType === 'solana') { + return tokenAddress === '11111111111111111111111111111111'; + } + return tokenAddress === '0x0000000000000000000000000000000000000000'; } diff --git a/packages/canonical-bridge-sdk/src/shared/string.ts b/packages/canonical-bridge-sdk/src/shared/string.ts new file mode 100644 index 00000000..ea7f7492 --- /dev/null +++ b/packages/canonical-bridge-sdk/src/shared/string.ts @@ -0,0 +1,5 @@ +export function utf8ToHex(utf8Str: any) { + return Array.from(utf8Str) + .map((char: any) => char.charCodeAt(0).toString(16).padStart(2, '0')) + .join(''); +} diff --git a/packages/canonical-bridge-widget/src/core/utils/address.ts b/packages/canonical-bridge-widget/src/core/utils/address.ts index 89bf1b60..3a5cfa7c 100644 --- a/packages/canonical-bridge-widget/src/core/utils/address.ts +++ b/packages/canonical-bridge-widget/src/core/utils/address.ts @@ -1,5 +1,6 @@ +import { ChainType } from '@bnb-chain/canonical-bridge-sdk'; + import { truncateHash } from '@/core/utils/string'; -import { ChainType } from '@/modules/aggregator'; export function formatAppAddress(params: { address?: string; diff --git a/packages/canonical-bridge-widget/src/index.tsx b/packages/canonical-bridge-widget/src/index.tsx index 8406f0f8..1f2f8edc 100644 --- a/packages/canonical-bridge-widget/src/index.tsx +++ b/packages/canonical-bridge-widget/src/index.tsx @@ -8,3 +8,7 @@ export * from '@/core/utils/gtm'; // locales export * from '@/core/locales'; + +// TODO +// sdk +export * from '@bnb-chain/canonical-bridge-sdk'; diff --git a/packages/canonical-bridge-widget/src/modules/aggregator/adapters/cBridge/hooks/useCBridgeSendMaxMin.ts b/packages/canonical-bridge-widget/src/modules/aggregator/adapters/cBridge/hooks/useCBridgeSendMaxMin.ts index 23ea7029..0ec086fe 100644 --- a/packages/canonical-bridge-widget/src/modules/aggregator/adapters/cBridge/hooks/useCBridgeSendMaxMin.ts +++ b/packages/canonical-bridge-widget/src/modules/aggregator/adapters/cBridge/hooks/useCBridgeSendMaxMin.ts @@ -1,10 +1,10 @@ import { useEffect, useState } from 'react'; import { usePublicClient } from 'wagmi'; import { formatUnits } from 'viem'; +import { ICBridgeMaxMinSendAmt } from '@bnb-chain/canonical-bridge-sdk'; import { useAppSelector } from '@/modules/store/StoreProvider'; import { useCBridgeTransferParams } from '@/modules/aggregator/adapters/cBridge/hooks/useCBridgeTransferParams'; -import { ICBridgeMaxMinSendAmt } from '@/modules/aggregator/adapters/cBridge/types'; import { useBridgeSDK } from '@/core/hooks/useBridgeSDK'; export const useCBridgeSendMaxMin = (isDisabled = false) => { diff --git a/packages/canonical-bridge-widget/src/modules/aggregator/adapters/cBridge/hooks/useCBridgeTransferParams.ts b/packages/canonical-bridge-widget/src/modules/aggregator/adapters/cBridge/hooks/useCBridgeTransferParams.ts index 210b8389..4cddbe22 100644 --- a/packages/canonical-bridge-widget/src/modules/aggregator/adapters/cBridge/hooks/useCBridgeTransferParams.ts +++ b/packages/canonical-bridge-widget/src/modules/aggregator/adapters/cBridge/hooks/useCBridgeTransferParams.ts @@ -1,143 +1,36 @@ import { useMemo } from 'react'; -import { parseUnits } from 'viem'; import { useAccount } from 'wagmi'; import { useAppSelector } from '@/modules/store/StoreProvider'; import { useBridgeSDK } from '@/core/hooks/useBridgeSDK'; -import { isNativeToken } from '@/core/utils/address'; export const useCBridgeTransferParams = () => { - const { address } = useAccount(); const bridgeSDK = useBridgeSDK(); - const selectedToken = useAppSelector((state) => state.transfer.selectedToken); + const { address } = useAccount(); + const fromChain = useAppSelector((state) => state.transfer.fromChain); const toChain = useAppSelector((state) => state.transfer.toChain); + const selectedToken = useAppSelector((state) => state.transfer.selectedToken); const sendValue = useAppSelector((state) => state.transfer.sendValue); - const max_slippage = useAppSelector((state) => state.transfer.slippage); - const isPegged = useMemo(() => selectedToken?.isPegged || false, [selectedToken]); - const bridgeAddress = useMemo(() => { - try { - if ( - !fromChain || - (isPegged && !selectedToken?.cBridge?.peggedConfig) || - (!isPegged && !fromChain?.cBridge?.raw) || - !bridgeSDK?.cBridge - ) { - return null; - } - return bridgeSDK.cBridge.getTransferAddress({ - fromChainId: fromChain?.id as number, - isPegged, - peggedConfig: selectedToken?.cBridge?.peggedConfig, - chainConfig: fromChain?.cBridge?.raw, + const slippage = useAppSelector((state) => state.transfer.slippage); + + return useMemo(() => { + if (fromChain && toChain && selectedToken && address && bridgeSDK.cBridge) { + const { args, bridgeAddress } = bridgeSDK.cBridge.getTransactionParams({ + fromChain, + toChain, + fromToken: selectedToken, + userAddress: address, + sendValue, + slippage, }); - } catch (e: any) { - // eslint-disable-next-line no-console - console.log(e); - } - }, [selectedToken, fromChain, isPegged, bridgeSDK?.cBridge]); - - // Mint/deposit or burn/withdraw - const transferType = useMemo(() => { - if (selectedToken?.cBridge?.peggedConfig?.org_chain_id === fromChain?.id) { - return 'deposit'; + return { args, bridgeAddress }; } - if (selectedToken?.cBridge?.peggedConfig?.pegged_chain_id === fromChain?.id) { - return 'withdraw'; - } - return ''; - }, [selectedToken, fromChain?.id]); - - const argument = useMemo(() => { - if ( - !sendValue || - sendValue === '0' || - !toChain || - !selectedToken || - !address || - !bridgeSDK?.cBridge - ) { - return null; - } - const nonce = new Date().getTime(); - let amount = 0n; - try { - if (selectedToken.isPegged === false) { - amount = parseUnits( - String(sendValue), - selectedToken?.cBridge?.raw?.token.decimal as number, - ); // Convert to big number - } else if (transferType === 'deposit') { - amount = parseUnits( - String(sendValue), - selectedToken?.cBridge?.peggedConfig?.org_token.token.decimal as number, - ); - } else if (transferType === 'withdraw') { - amount = parseUnits( - String(sendValue), - selectedToken?.cBridge?.peggedConfig?.pegged_token.token.decimal as number, - ); - } - } catch (e: any) { - // eslint-disable-next-line no-console - console.log(e); - } - - return bridgeSDK.cBridge.getTransferParams({ - amount, - isPegged, - toChainId: toChain.id, - tokenAddress: selectedToken?.address as `0x${string}`, - address: address as `0x${string}`, - maxSlippage: max_slippage, - transferType: transferType ? transferType : undefined, - peggedConfig: selectedToken.cBridge?.peggedConfig, - isNativeToken: isNativeToken(selectedToken.address), - nonce, - }); - }, [ - sendValue, - toChain, - selectedToken, - address, - isPegged, - transferType, - max_slippage, - bridgeSDK?.cBridge, - ]); - - // Arguments for bridge smart contract - const args = useMemo(() => { - const peggedConfig = selectedToken?.cBridge?.peggedConfig; - if ( - !argument || - (isPegged && !transferType) || - !address || - !bridgeAddress || - !bridgeSDK?.cBridge || - !selectedToken - ) { - return null; - } - const abi = bridgeSDK.cBridge.getABI({ - isPegged, - transferType: transferType || undefined, - peggedConfig, - }); - const functionName = bridgeSDK.cBridge.getTransferFunction({ - isPegged, - isNativeToken: isNativeToken(selectedToken?.address), - transferType: transferType || undefined, - }); return { - address: bridgeAddress as `0x${string}`, - abi: abi, - functionName: functionName, - account: address as `0x${string}`, - args: argument, + args: null, + bridgeAddress: null, }; - }, [bridgeAddress, transferType, selectedToken, isPegged, address, argument, bridgeSDK?.cBridge]); - return { args, bridgeAddress }; + }, [address, bridgeSDK.cBridge, fromChain, selectedToken, sendValue, slippage, toChain]); }; diff --git a/packages/canonical-bridge-widget/src/modules/aggregator/adapters/cBridge/types.ts b/packages/canonical-bridge-widget/src/modules/aggregator/adapters/cBridge/types.ts deleted file mode 100644 index 1d75c6d0..00000000 --- a/packages/canonical-bridge-widget/src/modules/aggregator/adapters/cBridge/types.ts +++ /dev/null @@ -1,121 +0,0 @@ -import { ICBridgeChain, ICBridgePeggedPairConfig } from '@bnb-chain/canonical-bridge-sdk'; -import { type PublicClient, type WalletClient } from 'viem'; - -export interface ICBridgeTransferInfo { - chain: any; - token: any; - amount: string; -} - -export interface ICBridgeTransferHistory { - transfer_id: string; - src_send_info: ICBridgeTransferInfo; - dst_received_info: ICBridgeTransferInfo; - ts: number; - src_block_tx_link: string; - dst_block_tx_link: string; - status: string; - refund_reason: string; -} - -export interface ICBridgeTransferHistoryResponse { - err: object; - history: ICBridgeTransferHistory[]; - next_page_token: string; - current_size: string; -} - -export interface ICBridgeTransferEstimatedTime { - err: object; - median_transfer_latency_in_second: number; -} - -export interface ICBridgeTransactionResponse { - data: null | { - gasFee: bigint; - gasPrice: bigint; - transferId: string; - send: () => Promise<`0x${string}`>; - }; - isLoading: boolean; - isError: boolean; - error: null | unknown; -} - -export interface ICBridgeEstimateAmountRequest { - src_chain_id: number; - dst_chain_id: number; - token_symbol: string; - amt: string; - user_addr?: string; - slippage_tolerance: number; - is_pegged?: boolean; -} - -export interface ICBridgeEstimateAmountResponse { - err: object; - eq_value_token_amt: string; - bridge_rate: number; - perc_fee: string; - base_fee: string; - slippage_tolerance: number; - max_slippage: number; - estimated_receive_amt: string; - drop_gas_amt: string; - op_fee_rebate: number; - op_fee_rebate_portion: number; - op_fee_rebate_end_time: string; -} - -export interface ICBridgeSendRangeInput { - bridgeAddress: `0x${string}`; - tokenAddress: `0x${string}`; - isPegged?: boolean; - client: PublicClient; -} - -export interface ISendCBridgeToken { - walletClient: WalletClient; - publicClient: PublicClient; - bridgeAddress: string; - fromChainId: number; - address: `0x${string}`; - peggedConfig?: ICBridgePeggedPairConfig; - isPegged: boolean; - args: any; -} - -export interface IGetCBridgeTransferAddressInput { - fromChainId: number; - isPegged: boolean; - peggedConfig?: ICBridgePeggedPairConfig; - chainConfig?: ICBridgeChain; -} - -export interface IGetCBridgeTransferParamsInput { - amount: bigint; - isPegged: boolean; - toChainId: number; - address: `0x${string}`; - tokenAddress: `0x${string}`; - maxSlippage: number; - transferType?: 'deposit' | 'withdraw'; - peggedConfig?: ICBridgePeggedPairConfig; - nonce: number; -} - -export interface IGetCBridgeABI { - isPegged: boolean; - transferType?: 'deposit' | 'withdraw'; - peggedConfig?: ICBridgePeggedPairConfig; -} - -export interface IGetCBridgeTransferFunction { - isPegged: boolean; - transferType?: 'deposit' | 'withdraw'; -} - -export interface ICBridgeMaxMinSendAmt { - max: string; - min: string; -} diff --git a/packages/canonical-bridge-widget/src/modules/aggregator/adapters/deBridge/types.ts b/packages/canonical-bridge-widget/src/modules/aggregator/adapters/deBridge/types.ts index dde03ecc..46d384e9 100644 --- a/packages/canonical-bridge-widget/src/modules/aggregator/adapters/deBridge/types.ts +++ b/packages/canonical-bridge-widget/src/modules/aggregator/adapters/deBridge/types.ts @@ -1,56 +1,3 @@ -// https://deswap.debridge.finance/v1.0/#/DLN -export type IQuoteResponse = { - estimation: { - srcChainTokenIn: { - address: `0x${string}`; - name: string; - symbol: string; - chainId: number; - decimals: number; - amount: string; - approximateOperatingExpense: string; - mutatedWithOperatingExpense: boolean; - }; - srcChainTokenOut: { - address: `0x${string}`; - name: string; - symbol: string; - decimals: number; - amount: string; - chainId: number; - maxRefundAmount: string; - }; - dstChainTokenOut: { - address: `0x${string}`; - name: string; - symbol: string; - decimals: number; - amount: string; - recommendedAmount: string; - withoutAdditionalTakerRewardsAmount: string; - maxTheoreticalAmount: string; - chainId: number; - }; - costsDetails: any[]; - recommendedSlippage: number; - }; - tx: { - allowanceTarget: `0x${string}`; - allowanceValue: string; - data: `0x${string}`; - to: `0x${string}`; // Bridge address - value: string; - }; - prependedOperatingExpenseCost: string; - order: { - approximateFulfillmentDelay: number; - }; - fixFee: string; - userPoints: number; - integratorPoints: number; - orderId: string; -}; - export interface TokenQueryParams { chainId: number; address: string; diff --git a/packages/canonical-bridge-widget/src/modules/aggregator/adapters/layerZero/types.ts b/packages/canonical-bridge-widget/src/modules/aggregator/adapters/layerZero/types.ts deleted file mode 100644 index b2216f1a..00000000 --- a/packages/canonical-bridge-widget/src/modules/aggregator/adapters/layerZero/types.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { type PublicClient, type WalletClient } from 'viem'; - -export interface ISendCakeTokenInput { - userAddress: `0x${string}`; - bridgeAddress: `0x${string}`; - amount: bigint; - dstEndpoint: number; - gasAmount?: bigint; - version?: number; - publicClient: PublicClient; - walletClient: WalletClient; -} - -export interface IGetEstimateFeeInput { - userAddress: `0x${string}`; - bridgeAddress: `0x${string}`; - amount: bigint; - dstEndpoint: number; - gasAmount?: bigint; - version?: number; - publicClient: PublicClient; -} diff --git a/packages/canonical-bridge-widget/src/modules/aggregator/adapters/stargate/hooks/useStargateTransfer.ts b/packages/canonical-bridge-widget/src/modules/aggregator/adapters/stargate/hooks/useStargateTransfer.ts deleted file mode 100644 index eb783dd5..00000000 --- a/packages/canonical-bridge-widget/src/modules/aggregator/adapters/stargate/hooks/useStargateTransfer.ts +++ /dev/null @@ -1,133 +0,0 @@ -import { useAccount, usePublicClient, useWalletClient } from 'wagmi'; -import { useCallback } from 'react'; -import { parseUnits } from 'viem'; - -import { useAppDispatch, useAppSelector } from '@/modules/store/StoreProvider'; -import { setEstimatedAmount } from '@/modules/transfer/action'; -import { toObject } from '@/core/utils/string'; -import { useDebounce } from '@/core/hooks/useDebounce'; -import { DEBOUNCE_DELAY, DEFAULT_ADDRESS } from '@/core/constants'; -import { useToTokenInfo } from '@/modules/transfer/hooks/useToTokenInfo'; -import { useStargateTransferParams } from '@/modules/aggregator/adapters/stargate/hooks/useStargateTransferParams'; -import { useBridgeSDK } from '@/core/hooks/useBridgeSDK'; - -export const useStargateTransfer = () => { - const { data: walletClient } = useWalletClient(); - const { address } = useAccount(); - const dispatch = useAppDispatch(); - const bridgeSDK = useBridgeSDK(); - - const selectedToken = useAppSelector((state) => state.transfer.selectedToken); - const sendValue = useAppSelector((state) => state.transfer.sendValue); - const estimatedAmount = useAppSelector((state) => state.transfer.estimatedAmount); - const fromChain = useAppSelector((state) => state.transfer.fromChain); - const toChain = useAppSelector((state) => state.transfer.toChain); - const { toTokenInfo } = useToTokenInfo(); - - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const publicClient = usePublicClient({ chainId: fromChain?.id }) as any; - const debouncedSendValue = useDebounce(sendValue, DEBOUNCE_DELAY); - const { args } = useStargateTransferParams(); - - const getQuoteOFT = useCallback(async () => { - if ( - !args || - !fromChain || - !toChain || - !selectedToken || - !debouncedSendValue || - !Number(debouncedSendValue) || - !toTokenInfo || - !publicClient || - !bridgeSDK - ) { - return; - } - try { - const bridgeAddress = selectedToken.stargate?.raw?.bridgeAddress as `0x${string}`; - - const quoteOFTResponse = await bridgeSDK.stargate?.getQuoteOFT({ - publicClient: publicClient, - bridgeAddress, - endPointId: args.dstEid, - receiver: address || DEFAULT_ADDRESS, - amount: parseUnits(debouncedSendValue, selectedToken.decimals), - }); - - dispatch(setEstimatedAmount({ stargate: toObject(quoteOFTResponse) })); - return { quoteOFT: quoteOFTResponse }; - // eslint-disable-next-line - } catch (error: any) { - // eslint-disable-next-line no-console - console.log(error, error.message); - dispatch(setEstimatedAmount({ stargate: undefined })); - } - }, [ - args, - fromChain, - toChain, - selectedToken, - debouncedSendValue, - toTokenInfo, - dispatch, - publicClient, - address, - bridgeSDK, - ]); - - const sendToken = useCallback( - async ({ onOpenFailedModal }: { onOpenFailedModal: () => void }) => { - if ( - !address || - !estimatedAmount?.stargate || - !args || - !selectedToken || - !publicClient || - !walletClient - ) - return; - try { - const bridgeAddress = selectedToken.stargate?.raw?.bridgeAddress as `0x${string}`; - const amountReceivedLD = estimatedAmount?.stargate[2].amountReceivedLD; - const sendParams = { ...args }; - if (amountReceivedLD) { - sendParams.minAmountLD = BigInt(amountReceivedLD); - } - const hash = await bridgeSDK.stargate?.sendToken({ - walletClient: walletClient as any, - publicClient: publicClient, - bridgeAddress, - tokenAddress: selectedToken.address as `0x${string}`, - endPointId: args.dstEid, - receiver: address, - amount: parseUnits(sendValue, selectedToken.decimals), - }); - const tx = await publicClient.waitForTransactionReceipt({ - hash: hash as `0x${string}`, - }); - // eslint-disable-next-line no-console - console.log('send token response', tx); - return hash; - } catch (e: any) { - // eslint-disable-next-line no-console - console.log(e, e.message); - onOpenFailedModal(); - } - }, - [ - address, - args, - estimatedAmount, - publicClient, - selectedToken, - walletClient, - sendValue, - bridgeSDK?.stargate, - ], - ); - - return { - getQuoteOFT, - sendToken, - }; -}; diff --git a/packages/canonical-bridge-widget/src/modules/aggregator/adapters/stargate/hooks/useStargateTransferParams.ts b/packages/canonical-bridge-widget/src/modules/aggregator/adapters/stargate/hooks/useStargateTransferParams.ts index 9d22653e..a5e33370 100644 --- a/packages/canonical-bridge-widget/src/modules/aggregator/adapters/stargate/hooks/useStargateTransferParams.ts +++ b/packages/canonical-bridge-widget/src/modules/aggregator/adapters/stargate/hooks/useStargateTransferParams.ts @@ -2,12 +2,12 @@ import { useAccount } from 'wagmi'; import { useMemo } from 'react'; import { parseUnits } from 'viem'; import { ethers } from 'ethers'; +import { IStargateParams } from '@bnb-chain/canonical-bridge-sdk'; import { useAppSelector } from '@/modules/store/StoreProvider'; import { useDebounce } from '@/core/hooks/useDebounce'; import { DEBOUNCE_DELAY, DEFAULT_ADDRESS } from '@/core/constants'; import { useToTokenInfo } from '@/modules/transfer/hooks/useToTokenInfo'; -import { IStargateParams } from '@/modules/aggregator/adapters/stargate/types'; export const useStargateTransferParams = (): { args: IStargateParams | null } => { const { address } = useAccount(); diff --git a/packages/canonical-bridge-widget/src/modules/aggregator/adapters/stargate/types.ts b/packages/canonical-bridge-widget/src/modules/aggregator/adapters/stargate/types.ts index de4e54d4..101322bf 100644 --- a/packages/canonical-bridge-widget/src/modules/aggregator/adapters/stargate/types.ts +++ b/packages/canonical-bridge-widget/src/modules/aggregator/adapters/stargate/types.ts @@ -1,13 +1,3 @@ -export interface IStargateParams { - dstEid: number; - to: `0x${string}`; - amountLD: bigint; - minAmountLD: bigint; - extraOptions: `0x${string}`; - composeMsg: `0x${string}`; - oftCmd: `0x${string}`; -} - export interface IStargateQuoteSend { nativeFee: bigint; lzTokenFee: bigint; diff --git a/packages/canonical-bridge-widget/src/modules/aggregator/index.ts b/packages/canonical-bridge-widget/src/modules/aggregator/index.ts index 8541ef67..de689ef7 100644 --- a/packages/canonical-bridge-widget/src/modules/aggregator/index.ts +++ b/packages/canonical-bridge-widget/src/modules/aggregator/index.ts @@ -1,5 +1,3 @@ export * from '@/modules/aggregator/types'; -export * from '@/modules/aggregator/adapters/cBridge/types'; export * from '@/modules/aggregator/adapters/deBridge/types'; -export * from '@/modules/aggregator/adapters/layerZero/types'; export * from '@/modules/aggregator/adapters/stargate/types'; diff --git a/packages/canonical-bridge-widget/src/modules/aggregator/reducer.ts b/packages/canonical-bridge-widget/src/modules/aggregator/reducer.ts index b267d1ea..93160bf8 100644 --- a/packages/canonical-bridge-widget/src/modules/aggregator/reducer.ts +++ b/packages/canonical-bridge-widget/src/modules/aggregator/reducer.ts @@ -1,6 +1,7 @@ +import { ICBridgeMaxMinSendAmt } from '@bnb-chain/canonical-bridge-sdk'; + import { createReducer } from '@/modules/store/createReducer'; import * as actions from '@/modules/aggregator/action'; -import { ICBridgeMaxMinSendAmt } from '@/modules/aggregator/adapters/cBridge/types'; export interface IAggregatorState { tokenPrices: { cmcPrices: Record; diff --git a/packages/canonical-bridge-widget/src/modules/transfer/components/Button/TransferButton.tsx b/packages/canonical-bridge-widget/src/modules/transfer/components/Button/TransferButton.tsx index a81a3a8d..f84fa603 100644 --- a/packages/canonical-bridge-widget/src/modules/transfer/components/Button/TransferButton.tsx +++ b/packages/canonical-bridge-widget/src/modules/transfer/components/Button/TransferButton.tsx @@ -1,11 +1,10 @@ import { Button, Flex, useColorMode, useIntl, useTheme } from '@bnb-chain/space'; import { useCallback, useState } from 'react'; import { useAccount, useBytecode, usePublicClient, useSignMessage, useWalletClient } from 'wagmi'; -import { formatUnits, parseUnits } from 'viem'; +import { formatUnits } from 'viem'; import { useTronWallet } from '@node-real/walletkit/tron'; import { useConnection } from '@solana/wallet-adapter-react'; import { useSolanaWallet } from '@node-real/walletkit/solana'; -import { VersionedTransaction } from '@solana/web3.js'; import { useAppSelector } from '@/modules/store/StoreProvider'; import { useGetAllowance } from '@/core/contract/hooks/useGetAllowance'; @@ -15,10 +14,9 @@ import { reportEvent } from '@/core/utils/gtm'; import { useGetTronAllowance } from '@/modules/aggregator/adapters/meson/hooks/useGetTronAllowance'; import { useCurrentWallet } from '@/modules/wallet/CurrentWalletProvider'; import { useTronTransferInfo } from '@/modules/transfer/hooks/tron/useTronTransferInfo'; -import { utf8ToHex } from '@/core/utils/string'; import { useTronContract } from '@/modules/aggregator/adapters/meson/hooks/useTronContract'; -import { isNativeToken } from '@/core/utils/address'; import { useSolanaTransferInfo } from '@/modules/transfer/hooks/solana/useSolanaTransferInfo'; +import { useSolanaAccount } from '@/modules/wallet/hooks/useSolanaAccount'; export function TransferButton({ onOpenSubmittedModal, @@ -52,13 +50,13 @@ export function TransferButton({ const { isSolanaTransfer, isSolanaAvailableToAccount } = useSolanaTransferInfo(); const { connection } = useConnection(); const { sendTransaction: sendSolanaTransaction } = useSolanaWallet(); + const { address: solanaAddress } = useSolanaAccount(); const sendValue = useAppSelector((state) => state.transfer.sendValue); const transferActionInfo = useAppSelector((state) => state.transfer.transferActionInfo); const selectedToken = useAppSelector((state) => state.transfer.selectedToken); const isGlobalFeeLoading = useAppSelector((state) => state.transfer.isGlobalFeeLoading); const isTransferable = useAppSelector((state) => state.transfer.isTransferable); - const toToken = useAppSelector((state) => state.transfer.toToken); const fromChain = useAppSelector((state) => state.transfer.fromChain); const toChain = useAppSelector((state) => state.transfer.toChain); const toAccount = useAppSelector((state) => state.transfer.toAccount); @@ -167,104 +165,85 @@ export function TransferButton({ }); if (transferActionInfo.bridgeType === 'cBridge' && cBridgeArgs && fromChain && address) { - try { - const cBridgeHash = await bridgeSDK.cBridge?.sendToken({ - // eslint-disable-next-line @typescript-eslint/no-explicit-any - walletClient: walletClient as any, - publicClient, - bridgeAddress: transferActionInfo.bridgeAddress as string, - fromChainId: fromChain?.id, - isPegged: selectedToken.isPegged, - isNativeToken: isNativeToken(selectedToken.address), - address, - peggedConfig: selectedToken?.cBridge?.peggedConfig, - args: cBridgeArgs.args, - }); - await publicClient.waitForTransactionReceipt({ - hash: cBridgeHash, + const { hash: cBridgeHash } = await bridgeSDK.sendToken({ + bridgeType: 'cBridge', + publicClient, + walletClient: walletClient as any, + fromChainId: fromChain.id, + toChainId: toChain!.id, + tokenAddress: selectedToken.address, + userAddress: address, + sendValue, + }); + if (cBridgeHash) { + reportEvent({ + id: 'transaction_bridge_success', + params: { + item_category: fromChain?.name, + item_category2: toChain?.name, + token: selectedToken.displaySymbol, + value: sendValue, + item_variant: 'cBridge', + }, }); - if (cBridgeHash) { - reportEvent({ - id: 'transaction_bridge_success', - params: { - item_category: fromChain?.name, - item_category2: toChain?.name, - token: selectedToken.displaySymbol, - value: sendValue, - item_variant: 'cBridge', - }, - }); - onCloseConfirmingModal(); - setHash(cBridgeHash); - setChosenBridge('cBridge'); - onOpenSubmittedModal(); - } - // eslint-disable-next-line no-console - console.log('cBridge tx', cBridgeHash); - } catch (e) { - // eslint-disable-next-line no-console - console.log(e); - handleFailure(e); + onCloseConfirmingModal(); + setHash(cBridgeHash); + setChosenBridge('cBridge'); + onOpenSubmittedModal(); } + // eslint-disable-next-line no-console + console.log('cBridge tx', cBridgeHash); } else if (transferActionInfo.bridgeType === 'deBridge') { - try { - let deBridgeHash: string | undefined; - - if (fromChain?.chainType === 'evm' && transferActionInfo.value && address) { - deBridgeHash = await bridgeSDK.deBridge?.sendToken({ - // eslint-disable-next-line @typescript-eslint/no-explicit-any - walletClient: walletClient as any, - bridgeAddress: transferActionInfo.bridgeAddress as string, - data: transferActionInfo.data as `0x${string}`, - amount: BigInt(transferActionInfo.value), - address, - }); - await publicClient.waitForTransactionReceipt({ - hash: deBridgeHash, - }); - } + const userAddress = (fromChain?.chainType === 'solana' ? solanaAddress : address) as string; + const toUserAddress = + fromChain?.chainType === 'solana' || toChain?.chainType === 'solana' + ? toAccount?.address + : undefined; - if (fromChain?.chainType === 'solana') { - const { blockhash } = await connection.getLatestBlockhash(); - const data = (transferActionInfo.data as string)?.slice(2); - const tx = VersionedTransaction.deserialize(Buffer.from(data, 'hex')); - - tx.message.recentBlockhash = blockhash; - deBridgeHash = await sendSolanaTransaction(tx, connection); - } + const { hash: deBridgeHash } = await bridgeSDK.sendToken({ + bridgeType: 'deBridge', + publicClient, + walletClient: walletClient as any, + fromChainId: fromChain!.id, + toChainId: toChain!.id, + tokenAddress: selectedToken.address, + userAddress, + toUserAddress, + sendValue, + solanaOpts: { + connection, + sendTransaction: sendSolanaTransaction, + }, + }); - if (deBridgeHash) { - reportEvent({ - id: 'transaction_bridge_success', - params: { - item_category: fromChain?.name, - item_category2: toChain?.name, - token: selectedToken.displaySymbol, - value: sendValue, - item_variant: 'deBridge', - }, - }); - onCloseConfirmingModal(); - setChosenBridge('deBridge'); - setHash(deBridgeHash); - onOpenSubmittedModal(); - } - } catch (e) { - // eslint-disable-next-line no-console - console.log(e); - handleFailure(e); + if (deBridgeHash) { + reportEvent({ + id: 'transaction_bridge_success', + params: { + item_category: fromChain?.name, + item_category2: toChain?.name, + token: selectedToken.displaySymbol, + value: sendValue, + item_variant: 'deBridge', + }, + }); + onCloseConfirmingModal(); + setChosenBridge('deBridge'); + setHash(deBridgeHash); + onOpenSubmittedModal(); } } else if (transferActionInfo.bridgeType === 'stargate' && address) { - const stargateHash = await bridgeSDK.stargate?.sendToken({ - // eslint-disable-next-line @typescript-eslint/no-explicit-any - walletClient: walletClient as any, + const { hash: stargateHash } = await bridgeSDK.sendToken({ + bridgeType: 'stargate', publicClient, - bridgeAddress: transferActionInfo.bridgeAddress as `0x${string}`, - tokenAddress: selectedToken.address as `0x${string}`, - endPointId: toToken?.stargate?.raw?.endpointID as number, - receiver: address, - amount: parseUnits(sendValue, selectedToken.decimals), + walletClient: walletClient as any, + fromChainId: fromChain!.id, + toChainId: toChain!.id, + tokenAddress: selectedToken.address, + userAddress: address as string, + sendValue, }); + if (stargateHash) { reportEvent({ id: 'transaction_bridge_success', @@ -282,14 +261,15 @@ export function TransferButton({ onOpenSubmittedModal(); } } else if (transferActionInfo.bridgeType === 'layerZero' && address) { - const layerZeroHash = await bridgeSDK.layerZero?.sendToken({ - bridgeAddress: transferActionInfo.bridgeAddress as `0x${string}`, - dstEndpoint: toToken?.layerZero?.raw?.endpointID as number, - userAddress: address, - amount: parseUnits(sendValue, selectedToken.decimals), - // eslint-disable-next-line @typescript-eslint/no-explicit-any - walletClient: walletClient as any, + const { hash: layerZeroHash } = await bridgeSDK.sendToken({ + bridgeType: 'layerZero', publicClient, + walletClient: walletClient as any, + fromChainId: fromChain!.id, + toChainId: toChain!.id, + tokenAddress: selectedToken.address, + userAddress: address as string, + sendValue, }); if (layerZeroHash) { reportEvent({ @@ -308,90 +288,68 @@ export function TransferButton({ onOpenSubmittedModal(); } } else if (transferActionInfo.bridgeType === 'meson') { - let fromAddress = ''; - let toAddress = ''; - let msg = ''; - let signature = ''; + let userAddress = ''; + let toUserAddress = ''; if (fromChain?.chainType === 'tron' && tronAddress) { - fromAddress = tronAddress; + userAddress = tronAddress; } else if (fromChain?.chainType !== 'tron' && address) { - fromAddress = address; + userAddress = address; } if (isTronTransfer && isTronAvailableToAccount && toAccount?.address) { - toAddress = toAccount.address; + toUserAddress = toAccount.address; } else if (address) { - toAddress = address; + toUserAddress = address; } - // get unsigned message - const unsignedMessage = await bridgeSDK.meson?.getUnsignedMessage({ - fromToken: `${fromChain?.meson?.raw?.id}:${selectedToken?.meson?.raw?.id}`, - toToken: `${toChain?.meson?.raw?.id}:${toToken?.meson?.raw?.id}`, - amount: sendValue, - fromAddress: fromAddress, - recipient: toAddress, + const { swapId } = await bridgeSDK.sendToken({ + bridgeType: 'meson', + publicClient, + walletClient: walletClient as any, + fromChainId: fromChain!.id, + toChainId: toChain!.id, + tokenAddress: selectedToken.address, + userAddress, + toUserAddress, + sendValue, + mesonOpts: { + signTransaction: async (message) => { + return String(await signTransaction(message as any)); + }, + signMessage: async (message) => { + return await signMessageAsync({ + account: userAddress as `0x${string}`, + message: { + raw: message as `0x${string}`, + }, + }); + }, + }, }); + // eslint-disable-next-line no-console + console.log(swapId); + if (swapId?.result?.swapId) { + setChosenBridge('meson'); + setHash(swapId?.result?.swapId); + } + if (swapId?.error) { + throw new Error(swapId?.error.message); + } - if (unsignedMessage?.result) { - const result = unsignedMessage.result; - const encodedData = result.encoded; - const message = result.signingRequest.message; - - if (fromChain?.chainType === 'tron') { - const hexTronHeader = utf8ToHex('\x19TRON Signed Message:\n32'); - msg = message.replace(hexTronHeader, ''); - } else { - const hexEthHeader = utf8ToHex('\x19Ethereum Signed Message:\n52'); - msg = message.replace(hexEthHeader, ''); - } - - if (fromChain?.chainType != 'tron') { - signature = await signMessageAsync({ - account: address, - message: { - raw: msg as `0x${string}`, - }, - }); - } else { - // TODO - signature = String(await signTransaction(msg as any)); - } - - const swapId = await bridgeSDK.meson?.sendToken({ - fromAddress: fromAddress, - recipient: toAddress, - signature: signature, - encodedData: encodedData, - }); - - // eslint-disable-next-line no-console - console.log(swapId); - if (swapId?.result?.swapId) { - setChosenBridge('meson'); - setHash(swapId?.result?.swapId); - } - if (swapId?.error) { - throw new Error(swapId?.error.message); - } - - reportEvent({ - id: 'transaction_bridge_success', - params: { - item_category: fromChain?.name, - item_category2: toChain?.name, - token: selectedToken.displaySymbol, - value: sendValue, - item_variant: 'meson', - }, - }); + reportEvent({ + id: 'transaction_bridge_success', + params: { + item_category: fromChain?.name, + item_category2: toChain?.name, + token: selectedToken.displaySymbol, + value: sendValue, + item_variant: 'meson', + }, + }); - onCloseConfirmingModal(); - onOpenSubmittedModal(); - } else { - throw new Error(unsignedMessage?.error.message); - } + onCloseConfirmingModal(); + onOpenSubmittedModal(); } } catch (e: any) { // eslint-disable-next-line no-console @@ -403,18 +361,18 @@ export function TransferButton({ } }, [ selectedToken, - transferActionInfo, + transferActionInfo?.bridgeType, + transferActionInfo?.bridgeAddress, + fromChain, walletClient, publicClient, address, allowance, isEvmConnected, - fromChain, isTronConnected, tronAddress, tronAllowance, - toChain?.name, - toChain?.meson?.raw?.id, + toChain, sendValue, onOpenFailedModal, setHash, @@ -423,23 +381,17 @@ export function TransferButton({ onOpenConfirmingModal, cBridgeArgs, onOpenApproveModal, - bridgeSDK.cBridge, - bridgeSDK.deBridge, - bridgeSDK.stargate, - bridgeSDK.layerZero, - bridgeSDK.meson, + bridgeSDK, onCloseConfirmingModal, onOpenSubmittedModal, + solanaAddress, + toAccount.address, connection, sendSolanaTransaction, - toToken?.stargate?.raw?.endpointID, - toToken?.layerZero?.raw?.endpointID, - toToken?.meson?.raw?.id, isTronTransfer, isTronAvailableToAccount, - toAccount.address, - signMessageAsync, signTransaction, + signMessageAsync, ]); return ( diff --git a/packages/canonical-bridge-widget/src/modules/transfer/components/TransferOverview/RouteInfo/TokenInfoTooltip.tsx b/packages/canonical-bridge-widget/src/modules/transfer/components/TransferOverview/RouteInfo/TokenInfoTooltip.tsx index fc1e6183..e9ed57b7 100644 --- a/packages/canonical-bridge-widget/src/modules/transfer/components/TransferOverview/RouteInfo/TokenInfoTooltip.tsx +++ b/packages/canonical-bridge-widget/src/modules/transfer/components/TransferOverview/RouteInfo/TokenInfoTooltip.tsx @@ -12,9 +12,9 @@ import { Portal, } from '@bnb-chain/space'; import { useMemo } from 'react'; +import { ChainType } from '@bnb-chain/canonical-bridge-sdk'; import { isNativeToken } from '@/core/utils/address.ts'; -import { ChainType } from '@/modules/aggregator'; interface TokenTooltipProps { tokenLinkUrl: string; diff --git a/packages/canonical-bridge-widget/src/modules/transfer/hooks/useLoadingBridgeFees.ts b/packages/canonical-bridge-widget/src/modules/transfer/hooks/useLoadingBridgeFees.ts index c25fd0d4..1c61e843 100644 --- a/packages/canonical-bridge-widget/src/modules/transfer/hooks/useLoadingBridgeFees.ts +++ b/packages/canonical-bridge-widget/src/modules/transfer/hooks/useLoadingBridgeFees.ts @@ -113,7 +113,6 @@ export const useLoadingBridgeFees = () => { const valueArr = []; try { - const amount = parseUnits(debouncedSendValue, selectedToken.decimals); const now = Date.now(); lastTime = now; @@ -122,7 +121,7 @@ export const useLoadingBridgeFees = () => { fromChainId: fromChain.id, toChainId: toChain?.id, tokenAddress: selectedToken.address, - amount, + sendValue: debouncedSendValue, slippage: max_slippage, userAddress: fromChain?.chainType === 'solana'