├── .babelrc ├── .gitignore ├── LICENSE ├── LICENSE-MIT ├── README.md ├── babel-polyfill.js ├── example ├── .eslintrc.json ├── .gitignore ├── config.ts ├── next-env.d.ts ├── next.config.js ├── package.json ├── pages │ ├── _app.tsx │ └── index.tsx ├── postcss.config.js ├── public │ ├── atom.svg │ ├── cosmodal.png │ ├── favicon.ico │ ├── keplr-wallet-extension.png │ ├── logo.png │ └── walletconnect-keplr.png ├── styles │ └── globals.css ├── tailwind.config.js ├── tsconfig.json ├── window.d.ts └── yarn.lock ├── package.json ├── preview.png ├── src ├── components │ ├── BaseModal.tsx │ ├── CloseIcon.tsx │ ├── SelectWalletModal.tsx │ ├── WalletConnectQRCodeModal.tsx │ ├── WalletManagerContext.tsx │ └── index.ts ├── index.ts └── providers │ ├── connectors │ ├── index.ts │ └── walletconnect-keplr.ts │ ├── index.ts │ └── logos │ ├── keplr-wallet-extension.png │ └── walletconnect-keplr.png ├── tsconfig.json ├── webpack.config.js └── yarn.lock /.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "presets": [ 3 | [ 4 | "@babel/preset-env", 5 | { 6 | "useBuiltIns": "usage" 7 | } 8 | ], 9 | "@babel/typescript" 10 | ] 11 | } 12 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. 2 | 3 | # dependencies 4 | /dist 5 | /node_modules 6 | /.pnp 7 | .pnp.js 8 | 9 | # testing 10 | /coverage 11 | 12 | # production 13 | /build 14 | 15 | # misc 16 | .DS_Store 17 | .env.local 18 | .env.development.local 19 | .env.test.local 20 | .env.production.local 21 | 22 | npm-debug.log* 23 | yarn-debug.log* 24 | yarn-error.log* 25 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2022 The COSMODAL AUTHORS 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright 2022 The COSMODAL AUTHORS 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | # Cosmodal is now CosmosKit 3 | 4 | CosmosKit: A wallet connector for the Cosmos ⚛️ 5 | 6 | https://github.com/cosmology-tech/cosmos-kit 7 | 8 | Cosmos Kit is a wallet adapter for developers to build apps that quickly and easily interact with Cosmos blockchains and wallets. 9 | 10 | # use Create Cosmos App to get started with CosmosKit 11 | 12 | Create Cosmos App: Set up a modern Cosmos app by running one command ⚛️ 13 | 14 | https://github.com/cosmology-tech/create-cosmos-app 15 | 16 | Everything is preconfigured, ready-to-go, so you can focus on your code! 17 | 18 | * ⚡️ Connect easily to keplr + keplr mobile via wallet connect 19 | * ⚛️ Sign and broadcast with [cosmjs](https://github.com/cosmos/cosmjs) stargate + cosmwasm signers 20 | * 🛠 Render pages with [next.js](https://nextjs.org/) hybrid static & server rendering 21 | * 🎨 Build awesome UI with [Cosmos Kit](https://github.com/cosmology-tech/cosmos-kit) and [Chakra UI](https://chakra-ui.com/docs/components) 22 | * 📝 Leverage [chain-registry](https://github.com/cosmology-tech/chain-registry) for Chain and Asset info for all Cosmos chains 23 | 24 | # Cosmodal 25 | 26 | Connecting web applications to the Cosmos ecosystem. 27 | 28 | ## Preview 29 | 30 | You can test the library on https://cosmodal.vercel.app/ 31 | 32 | ![preview](./preview.png) 33 | 34 | ## Running example locally 35 | 36 | ``` 37 | yarn && yarn start 38 | 39 | # OR 40 | 41 | npm install && npm run start 42 | ``` 43 | 44 | ## Usage 45 | 46 | **Now It supports React application only.** 47 | 48 | 1. Install Cosmodal npm package 49 | 50 | ``` 51 | yarn add cosmodal 52 | 53 | # OR 54 | 55 | npm install --save cosmodal 56 | ``` 57 | 58 | 2. Import `WalletManagerProvider` and render it around your whole app. 59 | 60 | ```tsx 61 | import { getKeplrFromWindow } from "@keplr-wallet/stores"; 62 | import WalletConnect from "@walletconnect/client"; 63 | import { 64 | KeplrWalletConnectV1, 65 | WalletInfo, 66 | WalletManagerProvider, 67 | } from "cosmodal"; 68 | import type { AppProps } from "next/app"; 69 | import Head from "next/head"; 70 | import { EmbedChainInfos } from "../config"; 71 | 72 | const walletInfoList: WalletInfo[] = [ 73 | { 74 | id: "keplr-wallet-extension", 75 | name: "Keplr Wallet", 76 | description: "Keplr Browser Extension", 77 | logoImgUrl: "/keplr-wallet-extension.png", 78 | getWallet: () => getKeplrFromWindow(), 79 | }, 80 | { 81 | id: "walletconnect-keplr", 82 | name: "WalletConnect", 83 | description: "Keplr Mobile", 84 | logoImgUrl: "/walletconnect-keplr.png", 85 | getWallet: (connector?: WalletConnect) => 86 | Promise.resolve( 87 | connector 88 | ? new KeplrWalletConnectV1(connector, EmbedChainInfos) 89 | : undefined 90 | ), 91 | }, 92 | ]; 93 | 94 | function MyApp({ Component, pageProps }: AppProps) { 95 | return ( 96 | 97 | 98 | 99 | ); 100 | } 101 | 102 | export default MyApp; 103 | ``` 104 | 105 | 3. Manage and Use wallet using `useWalletManager` in your component 106 | 107 | ```tsx 108 | import { Keplr } from "@keplr-wallet/types"; 109 | import { KeplrWalletConnectV1, useWalletManager } from "cosmodal"; 110 | import type { NextPage } from "next"; 111 | import { useState } from "react"; 112 | 113 | const Home: NextPage = () => { 114 | const [address, setAddress] = useState(""); 115 | const { getWallet } = useWalletManager(); 116 | 117 | const connectWallet = async () => { 118 | const wallet: Keplr | KeplrWalletConnectV1 = await getWallet(); 119 | await wallet.enable(["cosmoshub-4"]); 120 | 121 | const key = await wallet.getKey("cosmoshub-4"); 122 | setAddress(key.bech32Address); 123 | }; 124 | 125 | return
Your address: {address}
; 126 | }; 127 | 128 | export default Home; 129 | ``` 130 | 131 | ## Learn More 132 | 133 | To learn more about Cosmodal API, please check [our example code](https://github.com/chainapsis/cosmodal/tree/main/example) 134 | 135 | To learn more about how to use Keplr-specific API, please check the following resources: 136 | 137 | - [Keplr Example](https://github.com/chainapsis/keplr-example) 138 | - [Keplr Documentation](https://docs.keplr.app) 139 | 140 | To learn more about JavaScript client library for Cosmos check out [CosmJS](https://github.com/chainapsis/keplr-example) 141 | -------------------------------------------------------------------------------- /babel-polyfill.js: -------------------------------------------------------------------------------- 1 | require("@babel/register")({ 2 | extensions: [".ts", ".js", ".tsx", ".jsx"], 3 | }); 4 | -------------------------------------------------------------------------------- /example/.eslintrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "next/core-web-vitals" 3 | } 4 | -------------------------------------------------------------------------------- /example/.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. 2 | 3 | # dependencies 4 | /node_modules 5 | /.pnp 6 | .pnp.js 7 | 8 | # testing 9 | /coverage 10 | 11 | # next.js 12 | /.next/ 13 | /out/ 14 | 15 | # production 16 | /build 17 | 18 | # misc 19 | .DS_Store 20 | *.pem 21 | 22 | # debug 23 | npm-debug.log* 24 | yarn-debug.log* 25 | yarn-error.log* 26 | 27 | # local env files 28 | .env.local 29 | .env.development.local 30 | .env.test.local 31 | .env.production.local 32 | 33 | # vercel 34 | .vercel 35 | 36 | # typescript 37 | *.tsbuildinfo 38 | -------------------------------------------------------------------------------- /example/config.ts: -------------------------------------------------------------------------------- 1 | import { Bech32Address } from "@keplr-wallet/cosmos"; 2 | import { ChainInfo } from "@keplr-wallet/types"; 3 | 4 | export const EmbedChainInfos: ChainInfo[] = [ 5 | { 6 | rpc: "https://rpc-cosmoshub.blockapsis.com", 7 | rest: "https://lcd-cosmoshub.blockapsis.com", 8 | chainId: "cosmoshub-4", 9 | chainName: "Cosmos Hub", 10 | stakeCurrency: { 11 | coinDenom: "ATOM", 12 | coinMinimalDenom: "uatom", 13 | coinDecimals: 6, 14 | coinGeckoId: "cosmos", 15 | coinImageUrl: "/tokens/cosmos.svg", 16 | }, 17 | bip44: { 18 | coinType: 118, 19 | }, 20 | bech32Config: Bech32Address.defaultBech32Config("cosmos"), 21 | currencies: [ 22 | { 23 | coinDenom: "ATOM", 24 | coinMinimalDenom: "uatom", 25 | coinDecimals: 6, 26 | coinGeckoId: "cosmos", 27 | coinImageUrl: "/tokens/cosmos.svg", 28 | }, 29 | ], 30 | feeCurrencies: [ 31 | { 32 | coinDenom: "ATOM", 33 | coinMinimalDenom: "uatom", 34 | coinDecimals: 6, 35 | coinGeckoId: "cosmos", 36 | coinImageUrl: "/tokens/cosmos.svg", 37 | }, 38 | ], 39 | coinType: 118, 40 | features: ["ibc-transfer", "ibc-go"], 41 | }, 42 | ]; 43 | -------------------------------------------------------------------------------- /example/next-env.d.ts: -------------------------------------------------------------------------------- 1 | /// 2 | /// 3 | 4 | // NOTE: This file should not be edited 5 | // see https://nextjs.org/docs/basic-features/typescript for more information. 6 | -------------------------------------------------------------------------------- /example/next.config.js: -------------------------------------------------------------------------------- 1 | /** @type {import('next').NextConfig} */ 2 | module.exports = { 3 | reactStrictMode: true, 4 | }; 5 | -------------------------------------------------------------------------------- /example/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "example", 3 | "author": "chainapsis", 4 | "license": "ISC", 5 | "scripts": { 6 | "clean": "rm -rf node_modules .next dist", 7 | "dev": "next dev", 8 | "bootstrap": "yarn clean && yarn install && yarn dev", 9 | "build": "next build", 10 | "start": "next start", 11 | "lint": "next lint" 12 | }, 13 | "dependencies": { 14 | "cosmodal": "^0.3.1", 15 | "@cosmjs/stargate": "^0.28.4", 16 | "next": "12.1.5", 17 | "react": "^18.0.0", 18 | "react-dom": "^18.0.0" 19 | }, 20 | "devDependencies": { 21 | "@types/node": "17.0.23", 22 | "@types/react": "^18.0.5", 23 | "@types/react-dom": "^18.0.0", 24 | "autoprefixer": "^10.4.4", 25 | "eslint": "8.13.0", 26 | "eslint-config-next": "12.1.4", 27 | "postcss": "^8.4.12", 28 | "tailwindcss": "^3.0.23", 29 | "typescript": "4.6.3" 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /example/pages/_app.tsx: -------------------------------------------------------------------------------- 1 | import { getKeplrFromWindow } from "@keplr-wallet/stores"; 2 | import WalletConnect from "@walletconnect/client"; 3 | import { 4 | KeplrWalletConnectV1, 5 | WalletInfo, 6 | WalletManagerProvider, 7 | } from "cosmodal"; 8 | import type { AppProps } from "next/app"; 9 | import Head from "next/head"; 10 | import { EmbedChainInfos } from "../config"; 11 | import "../styles/globals.css"; 12 | 13 | const walletInfoList: WalletInfo[] = [ 14 | { 15 | id: "keplr-wallet-extension", 16 | name: "Keplr Wallet", 17 | description: "Keplr Browser Extension", 18 | logoImgUrl: "/keplr-wallet-extension.png", 19 | getWallet: () => getKeplrFromWindow(), 20 | }, 21 | { 22 | id: "walletconnect-keplr", 23 | name: "WalletConnect", 24 | description: "Keplr Mobile", 25 | logoImgUrl: "/walletconnect-keplr.png", 26 | getWallet: (connector?: WalletConnect) => 27 | Promise.resolve( 28 | connector 29 | ? new KeplrWalletConnectV1(connector, EmbedChainInfos) 30 | : undefined 31 | ), 32 | }, 33 | ]; 34 | 35 | function MyApp({ Component, pageProps }: AppProps) { 36 | return ( 37 | 38 | 39 | Cosmodal 40 | 41 | 45 | 46 | 47 | 48 | ); 49 | } 50 | 51 | export default MyApp; 52 | -------------------------------------------------------------------------------- /example/pages/index.tsx: -------------------------------------------------------------------------------- 1 | import { SigningStargateClient } from "@cosmjs/stargate"; 2 | import { Bech32Address } from "@keplr-wallet/cosmos"; 3 | import { Keplr } from "@keplr-wallet/types"; 4 | import { KeplrWalletConnectV1, useWalletManager } from "cosmodal"; 5 | import type { NextPage } from "next"; 6 | import { useEffect, useState } from "react"; 7 | import { EmbedChainInfos } from "../config"; 8 | 9 | const AUTO_CONNECT_WALLET_KEY = "auto_connect_wallet"; 10 | 11 | const Home: NextPage = () => { 12 | const [address, setAddress] = useState(""); 13 | const [stakeCurrencyAmount, setStakeCurrencyAmount] = useState(0); 14 | const { 15 | getWallet, 16 | clearLastUsedWallet, 17 | connectionType, 18 | setDefaultConnectionType, 19 | } = useWalletManager(); 20 | 21 | const currentChain = EmbedChainInfos[0]; 22 | 23 | const connectWallet = async () => { 24 | const wallet: Keplr | KeplrWalletConnectV1 = await getWallet(); 25 | await wallet.enable([currentChain.chainId]); 26 | const key = await wallet.getKey(currentChain.chainId); 27 | setAddress(key.bech32Address); 28 | 29 | const offlineSigner = wallet.getOfflineSigner(currentChain.chainId); 30 | const client = await SigningStargateClient.connectWithSigner( 31 | currentChain.rpc, 32 | offlineSigner 33 | ); 34 | const stakeCurrencyBalance = await client.getBalance( 35 | key.bech32Address, 36 | currentChain.stakeCurrency.coinMinimalDenom 37 | ); 38 | setStakeCurrencyAmount(parseFloat(stakeCurrencyBalance.amount) / 1000000); 39 | }; 40 | 41 | const signOut = () => { 42 | setAddress(""); 43 | clearLastUsedWallet(); 44 | setDefaultConnectionType(undefined); 45 | localStorage.removeItem(AUTO_CONNECT_WALLET_KEY); 46 | // For removing cached WalletConnect info 47 | localStorage.removeItem("walletconnect"); 48 | }; 49 | 50 | // Store connected wallet type 51 | useEffect(() => { 52 | if (connectionType) { 53 | localStorage.setItem(AUTO_CONNECT_WALLET_KEY, connectionType); 54 | } 55 | }, [connectionType]); 56 | 57 | // Automatically connect wallet as stored type, even if page refreshed, 58 | useEffect(() => { 59 | const autoConnectionType = localStorage.getItem(AUTO_CONNECT_WALLET_KEY); 60 | if (autoConnectionType) { 61 | setDefaultConnectionType(autoConnectionType); 62 | connectWallet(); 63 | } 64 | }, []); 65 | 66 | return ( 67 |
68 |
69 |
70 | logo 71 | cosmodal 72 |
73 |
74 | 75 | {Bech32Address.shortenAddress(address, 22)} 76 | 77 | 83 |
84 |
85 | {address && ( 86 |
87 |
88 |
Connected Network
89 |
{currentChain.chainName}
90 |
91 |
92 |
93 |
Balances
94 |
95 |
96 | 97 | 98 | {currentChain.stakeCurrency.coinDenom} 99 | 100 |
101 |
{stakeCurrencyAmount}
102 |
103 |
104 |
105 |
106 | )} 107 |
108 | ); 109 | }; 110 | 111 | export default Home; 112 | -------------------------------------------------------------------------------- /example/postcss.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | plugins: { 3 | tailwindcss: {}, 4 | autoprefixer: {}, 5 | }, 6 | } 7 | -------------------------------------------------------------------------------- /example/public/atom.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /example/public/cosmodal.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hyperweb-io/cosmodal/69c8b87bfd2d89817da19509219f1c16050390c5/example/public/cosmodal.png -------------------------------------------------------------------------------- /example/public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hyperweb-io/cosmodal/69c8b87bfd2d89817da19509219f1c16050390c5/example/public/favicon.ico -------------------------------------------------------------------------------- /example/public/keplr-wallet-extension.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hyperweb-io/cosmodal/69c8b87bfd2d89817da19509219f1c16050390c5/example/public/keplr-wallet-extension.png -------------------------------------------------------------------------------- /example/public/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hyperweb-io/cosmodal/69c8b87bfd2d89817da19509219f1c16050390c5/example/public/logo.png -------------------------------------------------------------------------------- /example/public/walletconnect-keplr.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hyperweb-io/cosmodal/69c8b87bfd2d89817da19509219f1c16050390c5/example/public/walletconnect-keplr.png -------------------------------------------------------------------------------- /example/styles/globals.css: -------------------------------------------------------------------------------- 1 | @tailwind base; 2 | @tailwind components; 3 | @tailwind utilities; 4 | 5 | html, 6 | body { 7 | padding: 0; 8 | margin: 0; 9 | font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Oxygen, 10 | Ubuntu, Cantarell, Fira Sans, Droid Sans, Helvetica Neue, sans-serif; 11 | } 12 | 13 | a { 14 | color: inherit; 15 | text-decoration: none; 16 | } 17 | 18 | * { 19 | box-sizing: border-box; 20 | } 21 | -------------------------------------------------------------------------------- /example/tailwind.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | content: [ 3 | "./pages/**/*.{js,ts,jsx,tsx}", 4 | "./components/**/*.{js,ts,jsx,tsx}", 5 | ], 6 | theme: { 7 | extend: {}, 8 | }, 9 | plugins: [], 10 | }; 11 | -------------------------------------------------------------------------------- /example/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "es5", 4 | "lib": ["dom", "dom.iterable", "esnext"], 5 | "allowJs": true, 6 | "skipLibCheck": true, 7 | "strict": true, 8 | "forceConsistentCasingInFileNames": true, 9 | "noEmit": true, 10 | "esModuleInterop": true, 11 | "module": "esnext", 12 | "moduleResolution": "node", 13 | "resolveJsonModule": true, 14 | "isolatedModules": true, 15 | "jsx": "preserve", 16 | "incremental": true 17 | }, 18 | "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"], 19 | "exclude": ["node_modules"] 20 | } 21 | -------------------------------------------------------------------------------- /example/window.d.ts: -------------------------------------------------------------------------------- 1 | import { Window as KeplrWindow } from "@keplr-wallet/types"; 2 | 3 | declare global { 4 | // eslint-disable-next-line @typescript-eslint/no-empty-interface 5 | interface Window extends KeplrWindow {} 6 | } 7 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "cosmodal", 3 | "version": "0.3.1", 4 | "repository": { 5 | "type": "git", 6 | "url": "git+https://github.com/chainapsis/cosmodal.git" 7 | }, 8 | "author": "chainapsis", 9 | "license": "SEE LICENSE IN LICENSE", 10 | "bugs": { 11 | "url": "https://github.com/chainapsis/cosmodal/issues" 12 | }, 13 | "homepage": "https://github.com/chainapsis/cosmodal#readme", 14 | "main": "dist/index.js", 15 | "module": "dist/index.js", 16 | "unpkg": "dist/index.js", 17 | "types": "dist/index.d.ts", 18 | "typings": "dist/index.d.ts", 19 | "files": [ 20 | "/dist" 21 | ], 22 | "scripts": { 23 | "clean": "rm -rf node_modules dist", 24 | "build": "webpack", 25 | "start": "yarn build && cd example && yarn bootstrap" 26 | }, 27 | "dependencies": { 28 | "@cosmjs/launchpad": "^0.27.1", 29 | "@cosmjs/proto-signing": "^0.28.0", 30 | "@keplr-wallet/common": "^0.9.10", 31 | "@keplr-wallet/cosmos": "^0.9.16", 32 | "@keplr-wallet/provider": "^0.9.12", 33 | "@keplr-wallet/stores": "^0.9.18", 34 | "@keplr-wallet/types": "^0.9.12", 35 | "@walletconnect/client": "^1.7.7", 36 | "@walletconnect/types": "^1.7.7", 37 | "@walletconnect/utils": "^1.7.7", 38 | "qrcode.react": "^3.0.0", 39 | "react-modal": "^3.14.4", 40 | "secretjs": "^0.17.5", 41 | "styled-components": "^5.3.5" 42 | }, 43 | "devDependencies": { 44 | "@babel/cli": "^7.17.6", 45 | "@babel/core": "^7.16.0", 46 | "@babel/node": "^7.16.8", 47 | "@babel/polyfill": "^7.12.1", 48 | "@babel/preset-env": "^7.16.11", 49 | "@babel/preset-typescript": "^7.16.7", 50 | "@babel/register": "^7.17.7", 51 | "@types/node": "^16.7.13", 52 | "@types/react": "^16.9.0", 53 | "@types/react-dom": "^16.9.0", 54 | "@types/react-modal": "^3.13.1", 55 | "@types/styled-components": "^5.1.25", 56 | "autoprefixer": "^10.4.4", 57 | "buffer": "^6.0.3", 58 | "crypto-browserify": "^3.12.0", 59 | "path-browserify": "^1.0.1", 60 | "postcss": "^8.4.12", 61 | "process": "^0.11.10", 62 | "stream-browserify": "^3.0.0", 63 | "ts-loader": "^9.2.8", 64 | "typescript": "^4.4.2", 65 | "url-loader": "^4.1.1", 66 | "webpack": "^5.64.4", 67 | "webpack-cli": "^4.9.2" 68 | }, 69 | "peerDependencies": { 70 | "react": "^18.0.0", 71 | "react-dom": "^18.0.0" 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /preview.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hyperweb-io/cosmodal/69c8b87bfd2d89817da19509219f1c16050390c5/preview.png -------------------------------------------------------------------------------- /src/components/BaseModal.tsx: -------------------------------------------------------------------------------- 1 | import React, { FunctionComponent, ReactElement } from "react"; 2 | import ReactModal from "react-modal"; 3 | import styled from "styled-components"; 4 | import { CloseIcon } from "./CloseIcon"; 5 | 6 | export interface BaseModalProps { 7 | isOpen: boolean; 8 | onRequestClose: () => void; 9 | 10 | title?: ReactElement | string; 11 | maxWidth?: string; 12 | } 13 | 14 | export const BaseModal: FunctionComponent = ({ 15 | isOpen, 16 | onRequestClose, 17 | title, 18 | maxWidth = "36rem", 19 | children, 20 | }) => { 21 | return ( 22 | { 25 | e.preventDefault(); 26 | onRequestClose(); 27 | }} 28 | className="_" 29 | overlayClassName="_" 30 | contentElement={(props, children) => ( 31 | 32 | {children} 33 | 34 | )} 35 | overlayElement={(props, children) => ( 36 | {children} 37 | )} 38 | > 39 | {typeof title === "string" ? {title} : title} 40 | onRequestClose()}> 41 | 42 | 43 | {children} 44 | 45 | ); 46 | }; 47 | 48 | const ModalContent = styled.div<{ maxWidth: string }>` 49 | position: absolute; 50 | left: 50%; 51 | transform: translateX(-50%); 52 | padding: 1.25rem; 53 | border-radius: 1rem; 54 | display: flex; 55 | flex-direction: column; 56 | background: white; 57 | width: 100%; 58 | max-width: ${(props) => props.maxWidth}; 59 | outline: none; 60 | 61 | @media (max-width: 768px) { 62 | width: calc(100% - 40px); 63 | } 64 | `; 65 | 66 | const ModalOverlay = styled.div` 67 | position: fixed; 68 | top: 0; 69 | left: 0; 70 | right: 0; 71 | bottom: 0; 72 | width: 100vw; 73 | height: 100vh; 74 | z-index: 50; 75 | background-color: rgba(0, 0, 0, 0.3); 76 | display: flex; 77 | align-items: center; 78 | justify-content: cetner; 79 | `; 80 | 81 | const ModalHeader = styled.div` 82 | color: rgb(31, 41, 55); 83 | font-size: 1.25rem; 84 | font-weight: bold; 85 | line-height: 1.75rem; 86 | margin-bottom: 1rem; 87 | `; 88 | 89 | const ModalCloseButton = styled.div` 90 | position: absolute; 91 | top: 1.25rem; 92 | right: 1.25rem; 93 | cursor: pointer; 94 | `; 95 | -------------------------------------------------------------------------------- /src/components/CloseIcon.tsx: -------------------------------------------------------------------------------- 1 | import React, { SVGProps } from "react"; 2 | 3 | export const CloseIcon = (props: SVGProps) => ( 4 | 12 | 19 | 20 | ); 21 | -------------------------------------------------------------------------------- /src/components/SelectWalletModal.tsx: -------------------------------------------------------------------------------- 1 | import React, { FunctionComponent } from "react"; 2 | import styled from "styled-components"; 3 | import { BaseModal, BaseModalProps } from "./BaseModal"; 4 | 5 | export interface Wallet { 6 | id: string; 7 | name: string; 8 | description: string; 9 | logoImgUrl: string; 10 | } 11 | 12 | export const SelectWalletModal: FunctionComponent< 13 | BaseModalProps & { 14 | wallets: Wallet[]; 15 | selectWallet: (walletId: string) => void; 16 | } 17 | > = ({ isOpen, onRequestClose, wallets, selectWallet }) => { 18 | return ( 19 | 24 | 25 | {wallets.map((wallet) => ( 26 | { 29 | e.preventDefault(); 30 | selectWallet(wallet.id); 31 | }} 32 | > 33 | 34 | 35 | {wallet.name} 36 | {wallet.description} 37 | 38 | 39 | ))} 40 | 41 | 42 | ); 43 | }; 44 | 45 | const WalletList = styled.div` 46 | display: flex; 47 | flex-direction: column; 48 | gap: 1rem; 49 | `; 50 | 51 | const Wallet = styled.div` 52 | border-radius: 1rem; 53 | padding: 1.25rem; 54 | display: flex; 55 | align-items: center; 56 | background-color: rgb(229 231 235); 57 | box-shadow: inset 0 0 0 1px rgb(156 163 175); 58 | 59 | &:hover { 60 | cursor: pointer; 61 | } 62 | `; 63 | 64 | const WalletIconImg = styled.img` 65 | width: 4rem; 66 | height: 4rem; 67 | `; 68 | 69 | const WalletInfo = styled.div` 70 | display: flex; 71 | flex-direction: column; 72 | margin-left: 1.25rem; 73 | `; 74 | 75 | const WalletName = styled.div` 76 | color: black; 77 | font-size: 1.125rem; 78 | font-weight: 600; 79 | line-height: 1.75rem; 80 | `; 81 | 82 | const WalletDescription = styled.div` 83 | margin-top: 0.25rem; 84 | color: rgb(75 85 99); 85 | `; 86 | -------------------------------------------------------------------------------- /src/components/WalletConnectQRCodeModal.tsx: -------------------------------------------------------------------------------- 1 | import QRCode from "qrcode.react"; 2 | import React, { FunctionComponent } from "react"; 3 | import { BaseModal, BaseModalProps } from "./BaseModal"; 4 | 5 | export const WalletConnectQRCodeModal: FunctionComponent< 6 | BaseModalProps & { 7 | uri: string; 8 | } 9 | > = ({ isOpen, onRequestClose, uri }) => { 10 | return ( 11 | 17 | {uri ? ( 18 | 23 | ) : undefined} 24 | 25 | ); 26 | }; 27 | -------------------------------------------------------------------------------- /src/components/WalletManagerContext.tsx: -------------------------------------------------------------------------------- 1 | import WalletConnect from "@walletconnect/client"; 2 | import EventEmitter from "eventemitter3"; 3 | import React, { 4 | createContext, 5 | FunctionComponent, 6 | ReactNode, 7 | useCallback, 8 | useContext, 9 | useRef, 10 | useState, 11 | } from "react"; 12 | import { SelectWalletModal, WalletConnectQRCodeModal } from "."; 13 | 14 | export interface WalletInfo { 15 | id: string; 16 | name: string; 17 | description: string; 18 | logoImgUrl: string; 19 | getWallet: (connector?: WalletConnect) => Promise; 20 | } 21 | 22 | export const WalletManagerContext = createContext<{ 23 | getWallet: () => Promise; 24 | clearLastUsedWallet: () => void; 25 | setDefaultConnectionType: (type: string | undefined) => void; 26 | connectionType?: string | undefined; 27 | } | null>(null); 28 | 29 | export const WalletManagerProvider: FunctionComponent<{ 30 | walletInfoList: WalletInfo[]; 31 | children: ReactNode; 32 | }> = ({ walletInfoList, children }) => { 33 | const [isModalOpen, setIsModalOpen] = useState(false); 34 | const [wcUri, setWCUri] = useState(""); 35 | 36 | const lastUsedWalletRef = useRef(); 37 | const defaultConnectionTypeRef = useRef(); 38 | const [connectionType, setConnectionType] = useState(); 39 | const [eventListener] = useState(() => new EventEmitter()); 40 | 41 | const [getWallet] = useState(() => (): Promise => { 42 | if (typeof window === "undefined") { 43 | return Promise.resolve(undefined); 44 | } 45 | 46 | if (lastUsedWalletRef.current) { 47 | return Promise.resolve(lastUsedWalletRef.current); 48 | } 49 | 50 | const cleanUp = () => { 51 | eventListener.off("modal_close"); 52 | eventListener.off("wc_qr_modal_close"); 53 | walletInfoList.forEach((walletInfo) => { 54 | eventListener.off(walletInfo.id); 55 | }); 56 | }; 57 | 58 | let callbackClosed: (() => void) | undefined; 59 | 60 | const wcConnector = new WalletConnect({ 61 | bridge: "https://bridge.walletconnect.org", 62 | signingMethods: [ 63 | "keplr_enable_wallet_connect_v1", 64 | "keplr_sign_amino_wallet_connect_v1", 65 | ], 66 | qrcodeModal: { 67 | open: (uri: string, cb: any) => { 68 | setWCUri(uri); 69 | callbackClosed = cb; 70 | }, 71 | close: () => setWCUri(""), 72 | }, 73 | }); 74 | 75 | const resolveWallet = async ( 76 | walletInfo: WalletInfo, 77 | resolver?: (value: any) => void 78 | ) => { 79 | const wallet = await walletInfo.getWallet(wcConnector); 80 | lastUsedWalletRef.current = wallet; 81 | setConnectionType(walletInfo.id); 82 | eventListener.off("modal_close"); 83 | eventListener.off("wc_qr_modal_close"); 84 | return resolver ? resolver(wallet) : Promise.resolve(wallet); 85 | }; 86 | 87 | const defaultConnectionWalletInfo = walletInfoList.find( 88 | (walletInfo) => defaultConnectionTypeRef.current === walletInfo.id 89 | ); 90 | if (defaultConnectionWalletInfo) { 91 | return resolveWallet(defaultConnectionWalletInfo); 92 | } 93 | 94 | return new Promise((resolve, reject) => { 95 | setIsModalOpen(true); 96 | 97 | eventListener.on("modal_close", () => { 98 | setIsModalOpen(false); 99 | reject(); 100 | cleanUp(); 101 | }); 102 | 103 | eventListener.on("wc_qr_modal_close", () => { 104 | setWCUri(""); 105 | if (callbackClosed) { 106 | callbackClosed(); 107 | } 108 | }); 109 | 110 | walletInfoList.forEach((walletInfo) => { 111 | eventListener.on(walletInfo.id, async () => { 112 | setIsModalOpen(false); 113 | 114 | if (walletInfo.id.startsWith("walletconnect")) { 115 | if (!wcConnector.connected) { 116 | wcConnector.createSession(); 117 | 118 | wcConnector.on("connect", (error: any) => { 119 | if (error) { 120 | reject(error); 121 | } else { 122 | resolveWallet(walletInfo, resolve); 123 | } 124 | }); 125 | } else { 126 | resolveWallet(walletInfo, resolve); 127 | } 128 | } else { 129 | resolveWallet(walletInfo, resolve); 130 | } 131 | }); 132 | }); 133 | }); 134 | }); 135 | 136 | return ( 137 | { 141 | lastUsedWalletRef.current = undefined; 142 | setConnectionType(undefined); 143 | }, []), 144 | setDefaultConnectionType: useCallback((type: string | undefined) => { 145 | defaultConnectionTypeRef.current = type; 146 | }, []), 147 | connectionType, 148 | }} 149 | > 150 | { 153 | eventListener.emit("modal_close"); 154 | }} 155 | wallets={walletInfoList} 156 | selectWallet={(walletId: string) => { 157 | eventListener.emit(walletId); 158 | }} 159 | /> 160 | 0} 162 | onRequestClose={() => eventListener.emit("wc_qr_modal_close")} 163 | uri={wcUri} 164 | /> 165 | {children} 166 | 167 | ); 168 | }; 169 | 170 | export const useWalletManager = () => { 171 | const context = useContext(WalletManagerContext); 172 | if (!context) { 173 | throw new Error("You forgot to use WalletManagerProvider"); 174 | } 175 | 176 | return context; 177 | }; 178 | -------------------------------------------------------------------------------- /src/components/index.ts: -------------------------------------------------------------------------------- 1 | export * from "./BaseModal"; 2 | export * from "./SelectWalletModal"; 3 | export * from "./WalletConnectQRCodeModal"; 4 | 5 | export * from "./WalletManagerContext"; 6 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | export * from "./components"; 2 | export * from "./providers"; 3 | -------------------------------------------------------------------------------- /src/providers/connectors/index.ts: -------------------------------------------------------------------------------- 1 | export * from "./walletconnect-keplr"; 2 | -------------------------------------------------------------------------------- /src/providers/connectors/walletconnect-keplr.ts: -------------------------------------------------------------------------------- 1 | import { 2 | AminoSignResponse, 3 | BroadcastMode, 4 | OfflineSigner, 5 | StdSignature, 6 | StdSignDoc, 7 | StdTx, 8 | } from "@cosmjs/launchpad"; 9 | import { DirectSignResponse, OfflineDirectSigner } from "@cosmjs/proto-signing"; 10 | import { IndexedDBKVStore, KVStore } from "@keplr-wallet/common"; 11 | import { 12 | CosmJSOfflineSigner, 13 | CosmJSOfflineSignerOnlyAmino, 14 | } from "@keplr-wallet/provider"; 15 | import { 16 | ChainInfo, 17 | Keplr, 18 | KeplrIntereactionOptions, 19 | KeplrMode, 20 | KeplrSignOptions, 21 | Key, 22 | } from "@keplr-wallet/types"; 23 | import { 24 | IConnector, 25 | IJsonRpcRequest, 26 | IRequestOptions, 27 | } from "@walletconnect/types"; 28 | import { payloadId } from "@walletconnect/utils"; 29 | import Axios from "axios"; 30 | import { Buffer } from "buffer/"; 31 | import deepmerge from "deepmerge"; 32 | import { SecretUtils } from "secretjs/types/enigmautils"; 33 | 34 | // VersionFormatRegExp checks if a chainID is in the format required for parsing versions 35 | // The chainID should be in the form: `{identifier}-{version}` 36 | const ChainVersionFormatRegExp = /(.+)-([\d]+)/; 37 | 38 | function parseChainId(chainId: string): { 39 | identifier: string; 40 | version: number; 41 | } { 42 | const split = chainId.split(ChainVersionFormatRegExp).filter(Boolean); 43 | if (split.length !== 2) { 44 | return { 45 | identifier: chainId, 46 | version: 0, 47 | }; 48 | } else { 49 | return { identifier: split[0], version: parseInt(split[1]) }; 50 | } 51 | } 52 | 53 | export type KeplrGetKeyWalletCoonectV1Response = { 54 | address: string; 55 | algo: string; 56 | bech32Address: string; 57 | isNanoLedger: boolean; 58 | name: string; 59 | pubKey: string; 60 | }; 61 | 62 | export type KeplrKeystoreMayChangedEventParam = { 63 | algo: string; 64 | name: string; 65 | isNanoLedger: boolean; 66 | keys: { 67 | chainIdentifier: string; 68 | address: string; 69 | bech32Address: string; 70 | pubKey: string; 71 | }[]; 72 | }; 73 | 74 | export class KeplrWalletConnectV1 implements Keplr { 75 | constructor( 76 | public readonly connector: IConnector, 77 | public readonly chainInfos: ChainInfo[], 78 | public readonly options: { 79 | kvStore?: KVStore; 80 | onBeforeSendRequest?: ( 81 | request: Partial, 82 | options?: IRequestOptions 83 | ) => Promise | void; 84 | onAfterSendRequest?: ( 85 | response: any, 86 | request: Partial, 87 | options?: IRequestOptions 88 | ) => Promise | void; 89 | } = {} 90 | ) { 91 | if (!options.kvStore) { 92 | options.kvStore = new IndexedDBKVStore("keplr_wallet_connect"); 93 | } 94 | 95 | connector.on("disconnect", () => { 96 | this.clearSaved(); 97 | }); 98 | 99 | connector.on("call_request", this.onCallReqeust); 100 | } 101 | 102 | readonly version: string = "0.9.0"; 103 | readonly mode: KeplrMode = "walletconnect"; 104 | 105 | defaultOptions: KeplrIntereactionOptions = {}; 106 | 107 | protected readonly onCallReqeust = async ( 108 | error: Error | null, 109 | payload: any | null 110 | ) => { 111 | if (error) { 112 | console.log(error); 113 | return; 114 | } 115 | 116 | if (!payload) { 117 | return; 118 | } 119 | 120 | if ( 121 | payload.method === "keplr_keystore_may_changed_event_wallet_connect_v1" 122 | ) { 123 | const param = payload.params[0] as 124 | | KeplrKeystoreMayChangedEventParam 125 | | undefined; 126 | if (!param) { 127 | return; 128 | } 129 | 130 | const lastSeenKeys = await this.getAllLastSeenKey(); 131 | if (!lastSeenKeys) { 132 | return; 133 | } 134 | 135 | const mayChangedKeyMap: Record< 136 | string, 137 | KeplrGetKeyWalletCoonectV1Response 138 | > = {}; 139 | for (const mayChangedKey of param.keys) { 140 | mayChangedKeyMap[mayChangedKey.chainIdentifier] = { 141 | address: mayChangedKey.address, 142 | algo: param.algo, 143 | bech32Address: mayChangedKey.bech32Address, 144 | isNanoLedger: param.isNanoLedger, 145 | name: param.name, 146 | pubKey: mayChangedKey.pubKey, 147 | }; 148 | } 149 | 150 | let hasChanged = false; 151 | 152 | for (const chainId of Object.keys(lastSeenKeys)) { 153 | const savedKey = lastSeenKeys[chainId]; 154 | if (savedKey) { 155 | const { identifier } = parseChainId(chainId); 156 | const mayChangedKey = mayChangedKeyMap[identifier]; 157 | if (mayChangedKey) { 158 | if ( 159 | mayChangedKey.algo !== savedKey.algo || 160 | mayChangedKey.name !== savedKey.name || 161 | mayChangedKey.isNanoLedger !== savedKey.isNanoLedger || 162 | mayChangedKey.address !== savedKey.address || 163 | mayChangedKey.bech32Address !== savedKey.bech32Address || 164 | mayChangedKey.pubKey !== savedKey.pubKey 165 | ) { 166 | hasChanged = true; 167 | 168 | lastSeenKeys[chainId] = mayChangedKey; 169 | } 170 | } 171 | } 172 | } 173 | 174 | if (hasChanged) { 175 | await this.saveAllLastSeenKey(lastSeenKeys); 176 | window.dispatchEvent(new Event("keplr_keystorechange")); 177 | } 178 | } 179 | }; 180 | 181 | protected async clearSaved(): Promise { 182 | const kvStore = this.options.kvStore!; 183 | 184 | await Promise.all([ 185 | kvStore.set(this.getKeyHasEnabled(), null), 186 | kvStore.set(this.getKeyLastSeenKey(), null), 187 | ]); 188 | } 189 | 190 | protected async sendCustomRequest( 191 | request: Partial, 192 | options?: IRequestOptions 193 | ): Promise { 194 | if (this.options.onBeforeSendRequest) { 195 | await this.options.onBeforeSendRequest(request, options); 196 | } 197 | 198 | try { 199 | const res = await this.connector.sendCustomRequest(request, options); 200 | 201 | if (this.options.onAfterSendRequest) { 202 | await this.options.onAfterSendRequest(res, request, options); 203 | } 204 | 205 | return res; 206 | } catch (e) { 207 | console.log(e); 208 | } 209 | } 210 | 211 | async enable(chainIds: string | string[]): Promise { 212 | if (typeof chainIds === "string") { 213 | chainIds = [chainIds]; 214 | } 215 | 216 | const hasEnabledChainIds = await this.getHasEnabledChainIds(); 217 | let allEnabled = true; 218 | for (const chainId of chainIds) { 219 | if (hasEnabledChainIds.indexOf(chainId) < 0) { 220 | allEnabled = false; 221 | break; 222 | } 223 | } 224 | 225 | if (allEnabled) { 226 | return; 227 | } 228 | 229 | await this.sendCustomRequest({ 230 | id: payloadId(), 231 | jsonrpc: "2.0", 232 | method: "keplr_enable_wallet_connect_v1", 233 | params: chainIds, 234 | }); 235 | 236 | await this.saveHasEnabledChainIds(chainIds); 237 | } 238 | 239 | protected getKeyHasEnabled() { 240 | return `${this.connector.session.handshakeTopic}-enabled`; 241 | } 242 | 243 | protected async getHasEnabledChainIds(): Promise { 244 | return ( 245 | (await this.options.kvStore!.get(this.getKeyHasEnabled())) ?? [] 246 | ); 247 | } 248 | 249 | protected async saveHasEnabledChainIds(chainIds: string[]) { 250 | const hasEnabledChainIds = await this.getHasEnabledChainIds(); 251 | for (const chainId of chainIds) { 252 | if (hasEnabledChainIds.indexOf(chainId) < 0) { 253 | hasEnabledChainIds.push(chainId); 254 | } 255 | } 256 | await this.options.kvStore!.set( 257 | this.getKeyHasEnabled(), 258 | hasEnabledChainIds 259 | ); 260 | } 261 | 262 | enigmaDecrypt( 263 | _chainId: string, 264 | _ciphertext: Uint8Array, 265 | _nonce: Uint8Array 266 | ): Promise { 267 | throw new Error("Not yet implemented"); 268 | } 269 | 270 | enigmaEncrypt( 271 | _chainId: string, 272 | _contractCodeHash: string, 273 | // eslint-disable-next-line @typescript-eslint/ban-types 274 | _msg: object 275 | ): Promise { 276 | throw new Error("Not yet implemented"); 277 | } 278 | 279 | experimentalSuggestChain(_chainInfo: ChainInfo): Promise { 280 | throw new Error("Not yet implemented"); 281 | } 282 | 283 | getEnigmaPubKey(_chainId: string): Promise { 284 | throw new Error("Not yet implemented"); 285 | } 286 | 287 | getEnigmaTxEncryptionKey( 288 | _chainId: string, 289 | _nonce: Uint8Array 290 | ): Promise { 291 | throw new Error("Not yet implemented"); 292 | } 293 | 294 | getEnigmaUtils(_chainId: string): SecretUtils { 295 | throw new Error("Not yet implemented"); 296 | } 297 | 298 | async getKey(chainId: string): Promise { 299 | const lastSeenKey = await this.getLastSeenKey(chainId); 300 | if (lastSeenKey) { 301 | return { 302 | address: Buffer.from(lastSeenKey.address, "hex"), 303 | algo: lastSeenKey.algo, 304 | bech32Address: lastSeenKey.bech32Address, 305 | isNanoLedger: lastSeenKey.isNanoLedger, 306 | name: lastSeenKey.name, 307 | pubKey: Buffer.from(lastSeenKey.pubKey, "hex"), 308 | }; 309 | } 310 | 311 | const response = ( 312 | await this.sendCustomRequest({ 313 | id: payloadId(), 314 | jsonrpc: "2.0", 315 | method: "keplr_get_key_wallet_connect_v1", 316 | params: [chainId], 317 | }) 318 | )[0] as KeplrGetKeyWalletCoonectV1Response; 319 | 320 | await this.saveLastSeenKey(chainId, response); 321 | 322 | return { 323 | address: Buffer.from(response.address, "hex"), 324 | algo: response.algo, 325 | bech32Address: response.bech32Address, 326 | isNanoLedger: response.isNanoLedger, 327 | name: response.name, 328 | pubKey: Buffer.from(response.pubKey, "hex"), 329 | }; 330 | } 331 | 332 | protected getKeyLastSeenKey() { 333 | return `${this.connector.session.handshakeTopic}-key`; 334 | } 335 | 336 | protected async getLastSeenKey( 337 | chainId: string 338 | ): Promise { 339 | const saved = await this.getAllLastSeenKey(); 340 | 341 | if (!saved) { 342 | return undefined; 343 | } 344 | 345 | return saved[chainId]; 346 | } 347 | 348 | protected async getAllLastSeenKey() { 349 | return await this.options.kvStore!.get<{ 350 | [chainId: string]: KeplrGetKeyWalletCoonectV1Response | undefined; 351 | }>(this.getKeyLastSeenKey()); 352 | } 353 | 354 | protected async saveAllLastSeenKey(data: { 355 | [chainId: string]: KeplrGetKeyWalletCoonectV1Response | undefined; 356 | }) { 357 | await this.options.kvStore!.set(this.getKeyLastSeenKey(), data); 358 | } 359 | 360 | protected async saveLastSeenKey( 361 | chainId: string, 362 | response: KeplrGetKeyWalletCoonectV1Response 363 | ) { 364 | let saved = await this.getAllLastSeenKey(); 365 | 366 | if (!saved) { 367 | saved = {}; 368 | } 369 | 370 | saved[chainId] = response; 371 | 372 | await this.saveAllLastSeenKey(saved); 373 | } 374 | 375 | signArbitrary( 376 | _chainId: string, 377 | _signer: string, 378 | _data: string | Uint8Array 379 | ): Promise { 380 | throw new Error("Not yet implemented"); 381 | } 382 | 383 | verifyArbitrary( 384 | _chainId: string, 385 | _signer: string, 386 | _data: string | Uint8Array, 387 | _signature: StdSignature 388 | ): Promise { 389 | throw new Error("Not yet implemented"); 390 | } 391 | 392 | getOfflineSigner(chainId: string): OfflineSigner & OfflineDirectSigner { 393 | return new CosmJSOfflineSigner(chainId, this); 394 | } 395 | 396 | async getOfflineSignerAuto( 397 | chainId: string 398 | ): Promise { 399 | const key = await this.getKey(chainId); 400 | if (key.isNanoLedger) { 401 | return new CosmJSOfflineSignerOnlyAmino(chainId, this); 402 | } 403 | return new CosmJSOfflineSigner(chainId, this); 404 | } 405 | 406 | getOfflineSignerOnlyAmino(chainId: string): OfflineSigner { 407 | return new CosmJSOfflineSignerOnlyAmino(chainId, this); 408 | } 409 | 410 | getSecret20ViewingKey( 411 | _chainId: string, 412 | _contractAddress: string 413 | ): Promise { 414 | throw new Error("Not yet implemented"); 415 | } 416 | 417 | async sendTx( 418 | chainId: string, 419 | tx: StdTx | Uint8Array, 420 | mode: BroadcastMode 421 | ): Promise { 422 | const restInstance = Axios.create({ 423 | baseURL: this.chainInfos.find( 424 | (chainInfo) => chainInfo.chainId === chainId 425 | )!.rest, 426 | }); 427 | 428 | const isProtoTx = Buffer.isBuffer(tx) || tx instanceof Uint8Array; 429 | 430 | const params = isProtoTx 431 | ? { 432 | tx_bytes: Buffer.from(tx as any).toString("base64"), 433 | mode: (() => { 434 | switch (mode) { 435 | case "async": 436 | return "BROADCAST_MODE_ASYNC"; 437 | case "block": 438 | return "BROADCAST_MODE_BLOCK"; 439 | case "sync": 440 | return "BROADCAST_MODE_SYNC"; 441 | default: 442 | return "BROADCAST_MODE_UNSPECIFIED"; 443 | } 444 | })(), 445 | } 446 | : { 447 | tx, 448 | mode: mode, 449 | }; 450 | 451 | const result = await restInstance.post( 452 | isProtoTx ? "/cosmos/tx/v1beta1/txs" : "/txs", 453 | params 454 | ); 455 | 456 | const txResponse = isProtoTx ? result.data["tx_response"] : result.data; 457 | 458 | if (txResponse.code != null && txResponse.code !== 0) { 459 | throw new Error(txResponse["raw_log"]); 460 | } 461 | 462 | return Buffer.from(txResponse.txhash, "hex"); 463 | } 464 | 465 | async signAmino( 466 | chainId: string, 467 | signer: string, 468 | signDoc: StdSignDoc, 469 | signOptions: KeplrSignOptions = {} 470 | ): Promise { 471 | return ( 472 | await this.sendCustomRequest({ 473 | id: payloadId(), 474 | jsonrpc: "2.0", 475 | method: "keplr_sign_amino_wallet_connect_v1", 476 | params: [ 477 | chainId, 478 | signer, 479 | signDoc, 480 | deepmerge(this.defaultOptions.sign ?? {}, signOptions), 481 | ], 482 | }) 483 | )[0]; 484 | } 485 | 486 | signDirect( 487 | _chainId: string, 488 | _signer: string, 489 | _signDoc: { 490 | bodyBytes?: Uint8Array | null; 491 | authInfoBytes?: Uint8Array | null; 492 | chainId?: string | null; 493 | accountNumber?: Long | null; 494 | }, 495 | _signOptions: KeplrSignOptions = {} 496 | ): Promise { 497 | throw new Error("Not yet implemented"); 498 | } 499 | 500 | suggestToken( 501 | _chainId: string, 502 | _contractAddress: string, 503 | _viewingKey?: string 504 | ): Promise { 505 | throw new Error("Not yet implemented"); 506 | } 507 | } 508 | -------------------------------------------------------------------------------- /src/providers/index.ts: -------------------------------------------------------------------------------- 1 | export * from "./connectors"; 2 | -------------------------------------------------------------------------------- /src/providers/logos/keplr-wallet-extension.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hyperweb-io/cosmodal/69c8b87bfd2d89817da19509219f1c16050390c5/src/providers/logos/keplr-wallet-extension.png -------------------------------------------------------------------------------- /src/providers/logos/walletconnect-keplr.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hyperweb-io/cosmodal/69c8b87bfd2d89817da19509219f1c16050390c5/src/providers/logos/walletconnect-keplr.png -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "outDir": "dist", 4 | "rootDir": "src", 5 | "baseUrl": ".", 6 | "module": "commonjs", 7 | "target": "es5", 8 | "lib": ["es7", "dom"], 9 | "jsx": "react", 10 | "allowSyntheticDefaultImports": true, 11 | "composite": true, 12 | "declaration": true, 13 | "declarationMap": true, 14 | "downlevelIteration": true, 15 | "esModuleInterop": true, 16 | "forceConsistentCasingInFileNames": true, 17 | "importHelpers": true, 18 | "noImplicitAny": true, 19 | "noImplicitReturns": true, 20 | "noImplicitThis": true, 21 | "noUnusedLocals": true, 22 | "preserveSymlinks": true, 23 | "resolveJsonModule": true, 24 | "skipLibCheck": true, 25 | "sourceMap": true, 26 | "strict": true, 27 | "strictNullChecks": true, 28 | "suppressImplicitAnyIndexErrors": true 29 | }, 30 | "include": ["./src/**/*"] 31 | } 32 | -------------------------------------------------------------------------------- /webpack.config.js: -------------------------------------------------------------------------------- 1 | const path = require("path"); 2 | const webpack = require("webpack"); 3 | 4 | module.exports = { 5 | mode: "production", 6 | entry: { 7 | index: "./src/index.ts", 8 | }, 9 | output: { 10 | path: path.resolve(__dirname, "dist"), 11 | filename: "[name].js", 12 | libraryTarget: "umd", 13 | library: "cosmodal", 14 | umdNamedDefine: true, 15 | globalObject: "this", 16 | }, 17 | devtool: "source-map", 18 | module: { 19 | rules: [ 20 | { test: /\.tsx?$/, loader: "ts-loader" }, 21 | { 22 | test: /\.(png|svg|jpg|gif)$/, 23 | use: [ 24 | { 25 | loader: "url-loader", 26 | options: { 27 | limit: 65535, 28 | name: "static/media/[name].[hash:8].[ext]", 29 | }, 30 | }, 31 | ], 32 | }, 33 | ], 34 | }, 35 | plugins: [ 36 | new webpack.ProvidePlugin({ 37 | process: "process/browser", 38 | Buffer: ["buffer", "Buffer"], 39 | }), 40 | ], 41 | resolve: { 42 | extensions: [".ts", ".tsx", ".js"], 43 | alias: { 44 | react: path.resolve(__dirname, "./node_modules/react"), 45 | "react-dom": path.resolve(__dirname, "./node_modules/react-dom"), 46 | }, 47 | fallback: { 48 | buffer: require.resolve("buffer"), 49 | crypto: require.resolve("crypto-browserify"), 50 | path: require.resolve("path-browserify"), 51 | stream: require.resolve("stream-browserify"), 52 | }, 53 | }, 54 | externals: { 55 | react: { 56 | commonjs: "react", 57 | commonjs2: "react", 58 | amd: "React", 59 | root: "React", 60 | }, 61 | "react-dom": { 62 | commonjs: "react-dom", 63 | commonjs2: "react-dom", 64 | amd: "ReactDOM", 65 | root: "ReactDOM", 66 | }, 67 | }, 68 | }; 69 | --------------------------------------------------------------------------------