diff --git a/docs/.vuepress/config.js b/docs/.vuepress/config.js index 9a838bde21..0de727e328 100644 --- a/docs/.vuepress/config.js +++ b/docs/.vuepress/config.js @@ -42,15 +42,35 @@ module.exports = { auto: false, nav: [ { - title: "API", + title: "Getting Started", children: [ { - title: "Keplr API", + title: "Getting Started", + directory: true, + path: "/getting-started", + }, + ], + }, + { + title: "Keplr APIs", + children: [ + { + title: "Keplr APIs", directory: true, path: "/api", }, ], }, + { + title: "Using Cosmos Singing Libraries", + children: [ + { + title: "Using Cosmos Signing Libraries", + directory: true, + path: "/signing-lib", + }, + ], + } ], }, }, diff --git a/docs/README.md b/docs/README.md index a9d568f00f..5e0fcb7979 100644 --- a/docs/README.md +++ b/docs/README.md @@ -11,19 +11,23 @@ order: 1 ## Introduction -Keplr is a non-custodial blockchain wallets for webpages that allow users to interact with blockchain applications. +Keplr Wallet is an advanced, non-custodial web-based wallet tailored for the Cosmos ecosystem. Developers working with the Cosmos-based chains can utilize tools like cosmos-kit and CosmJS for seamless integration with the Keplr Wallet. Keplr stands out for its extensibility, security features, and intuitive interface, all of which enable fluid multi-chain operations for dApps desiring seamless multichain operations. ## Why Keplr? -- Private keys are stored locally. This removes the friction and risk of webpages having to manage user private keys safely and securely. -- As the user's private key is not managed by the website, users do not have to worry about the level of security of the website. The user only has to trust the security guarantees of Keplr, and freely interact with various web applications as they wish (and verify the contents of the transaction). -- Keplr can easily connect to libraries such as CosmJS, simplifying the process of connecting webpages to blockchains. +- **Frontend dApp Integration**: Keplr Wallet is expressly designed with frontend applications in mind, ensuring dApps can provide users with a seamless and intuitive blockchain interaction experience. -## Sections -[Integrate with Keplr](./api) describes how to integrate with Keplr in the webpage. +- **Enhanced Security & Extensibility**: Because the user's keys are stored locally, and only used to sign transactions requested by dApps, it allows dApps to provide a much more secure user path than storing private keys or mnemonics on the website. -[Use with cosmjs](./api/cosmjs.md) describes how to use cosmjs with Keplr. +- **User-Centric, multichain Design**: Keplr stands out with its user-focused interface for a multichain environment, simplifying asset management and transactions, which in turn enhances user adoption and trust in dApps integrated with it. -[Use with secretjs](./api/secretjs.md) describes how to use secretjs with Keplr if you need to use secret-wasm feature. - -[Suggest chain](./api/suggest-chain.md) describes how to suggest the chain to Keplr if the chain is not supported natively in Keplr. +Keplr's approach of allowing users to interact with multiple chains without setting an "active" chain contrasts with the traditional Ethereum wallet's model where users have to switch to a specific network to interact with it. + +1. **Seamless Cross-Chain Interactions**: + - By permitting interactions across multiple chains simultaneously, users can effortlessly perform cross-chain activities without needing to constantly switch their active chain. This is especially pertinent in the Cosmos ecosystem, where IBC (Inter-Blockchain Communication) enables tokens to move between chains. + +2. **User Experience**: + - The user doesn't have to be constantly aware of which chain they're interacting with, reducing cognitive load and improving the UX. It can be more intuitive, especially for newcomers who might not understand the concept of switching chains. + +3. **DApp Integration**: + - For dApps that span multiple chains, integration can be smoother, as there's no need to prompt users to switch networks. \ No newline at end of file diff --git a/docs/api/README.md b/docs/api/README.md deleted file mode 100644 index d10f3ccce4..0000000000 --- a/docs/api/README.md +++ /dev/null @@ -1,281 +0,0 @@ ---- -title: Basic API -order: 1 ---- - -## How to detect Keplr - -You can determine whether Keplr is installed on the user device by checking `window.keplr`. If `window.keplr` returns `undefined` after document.load, Keplr is not installed. There are several ways to wait for the load event to check the status. Refer to the examples below: - -You can register the function to `window.onload`: - -```javascript -window.onload = async () => { - if (!window.keplr) { - alert("Please install keplr extension"); - } else { - const chainId = "cosmoshub-4"; - - // Enabling before using the Keplr is recommended. - // This method will ask the user whether to allow access if they haven't visited this website. - // Also, it will request that the user unlock the wallet if the wallet is locked. - await window.keplr.enable(chainId); - - const offlineSigner = window.keplr.getOfflineSigner(chainId); - - // You can get the address/public keys by `getAccounts` method. - // It can return the array of address/public key. - // But, currently, Keplr extension manages only one address/public key pair. - // XXX: This line is needed to set the sender address for SigningCosmosClient. - const accounts = await offlineSigner.getAccounts(); - - // Initialize the gaia api with the offline signer that is injected by Keplr extension. - const cosmJS = new SigningCosmosClient( - "https://lcd-cosmoshub.keplr.app", - accounts[0].address, - offlineSigner, - ); - } -} -``` - -or track the document's ready state through the document event listener: - -```javascript -async getKeplr(): Promise { - if (window.keplr) { - return window.keplr; - } - - if (document.readyState === "complete") { - return window.keplr; - } - - return new Promise((resolve) => { - const documentStateChange = (event: Event) => { - if ( - event.target && - (event.target as Document).readyState === "complete" - ) { - resolve(window.keplr); - document.removeEventListener("readystatechange", documentStateChange); - } - }; - - document.addEventListener("readystatechange", documentStateChange); - }); -} -``` - -There may be multiple ways to achieve the same result, and no preferred method. - -## Keplr-specific features - -If you were able to connect Keplr with CosmJS, you may skip to the [Use Keplr with CosmJS](./cosmjs.md) section. - -While Keplr supports an easy way to connect to CosmJS, there are additional functions specific to Keplr which provide additional features. - -### Using with Typescript -**`window.d.ts`** -```javascript -import { Window as KeplrWindow } from "@keplr-wallet/types"; - -declare global { - // eslint-disable-next-line @typescript-eslint/no-empty-interface - interface Window extends KeplrWindow {} -} -``` - -The `@keplr-wallet/types` package has the type definition related to Keplr. -If you're using TypeScript, run `npm install --save-dev @keplr-wallet/types` or `yarn add -D @keplr-wallet/types` to install `@keplr-wallet/types`. -Then, you can add the `@keplr-wallet/types` window to a global window object and register the Keplr related types. - -> Usage of any other packages besides @keplr-wallet/types is not recommended. -> - Any other packages besides @keplr-wallet/types are actively being developed, backward compatibility is not in the scope of support. -> - Since there are active changes being made, documentation is not being updated to the most recent version of the package as of right now. Documentations would be updated as packages get stable. - -### Enable Connection - -```javascript -enable(chainIds: string | string[]): Promise -``` - -The `window.keplr.enable(chainIds)` method requests the extension to be unlocked if it's currently locked. If the user hasn't given permission to the webpage, it will ask the user to give permission for the webpage to access Keplr. - -`enable` method can receive one or more chain-id as an array. When the array of chain-id is passed, you can request permissions for all chains that have not yet been authorized at once. - -If the user cancels the unlock or rejects the permission, an error will be thrown. - -### Get Address / Public Key - -```javascript -getKey(chainId: string): Promise<{ - // Name of the selected key store. - name: string; - algo: string; - pubKey: Uint8Array; - address: Uint8Array; - bech32Address: string; -}> -``` - -If the webpage has permission and Keplr is unlocked, this function will return the address and public key in the following format: - -```javascript -{ - // Name of the selected key store. - name: string; - algo: string; - pubKey: Uint8Array; - address: Uint8Array; - bech32Address: string; - isNanoLedger: boolean; -} -``` - -It also returns the nickname for the key store currently selected, which should allow the webpage to display the current key store selected to the user in a more convenient mane. -`isNanoLedger` field in the return type is used to indicate whether the selected account is from the Ledger Nano. Because current Cosmos app in the Ledger Nano doesn't support the direct (protobuf) format msgs, this field can be used to select the amino or direct signer. [Ref](./cosmjs.md#types-of-offline-signers) - -### Sign Amino - -```javascript -signAmino(chainId: string, signer: string, signDoc: StdSignDoc): Promise -``` - -Similar to CosmJS `OfflineSigner`'s `signAmino`, but Keplr's `signAmino` takes the chain-id as a required parameter. Signs Amino-encoded `StdSignDoc`. - -### Sign Direct / Protobuf - -```javascript -signDirect(chainId:string, signer:string, signDoc: { - /** SignDoc bodyBytes */ - bodyBytes?: Uint8Array | null; - - /** SignDoc authInfoBytes */ - authInfoBytes?: Uint8Array | null; - - /** SignDoc chainId */ - chainId?: string | null; - - /** SignDoc accountNumber */ - accountNumber?: Long | null; - }): Promise -``` - -Similar to CosmJS `OfflineDirectSigner`'s `signDirect`, but Keplr's `signDirect` takes the chain-id as a required parameter. Signs Proto-encoded `StdSignDoc`. - -### Request Transaction Broadcasting - -```javascript -sendTx( - chainId: string, - tx: Uint8Array, - mode: BroadcastMode -): Promise; -``` - -This function requests Keplr to delegate the broadcasting of the transaction to Keplr's LCD endpoints (rather than the webpage broadcasting the transaction). -This method returns the transaction hash if it succeeds to broadcast, if else the method will throw an error. -When Keplr broadcasts the transaction, Keplr will send the notification on the transaction's progress. - -### Request Signature for Arbitrary Message - -```javascript -signArbitrary( - chainId: string, - signer: string, - data: string | Uint8Array -): Promise; -verifyArbitrary( - chainId: string, - signer: string, - data: string | Uint8Array, - signature: StdSignature -): Promise; -``` - -This is an experimental implementation of [ADR-36](https://github.com/cosmos/cosmos-sdk/blob/master/docs/architecture/adr-036-arbitrary-signature.md). Use this feature at your own risk. - -Its main usage is to prove ownership of an account off-chain, requesting ADR-36 signature using the `signArbitrary` API. - -If requested sign doc with the `signAnimo` API with the ADR-36 that Keplr requires instead of using the `signArbitary` API, it would function as `signArbitary` -- Only supports sign doc in the format of Amino. (in the case of protobuf, [ADR-36](https://github.com/cosmos/cosmos-sdk/blob/master/docs/architecture/adr-036-arbitrary-signature.md) requirements aren't fully specified for implementation) -- sign doc message should be single and the message type should be "sign/MsgSignData" -- sign doc "sign/MsgSignData" message should have "signer" and "data" as its value. "data" should be base64 encoded -- sign doc chain_id should be an empty string("") -- sign doc memo should be an empty string("") -- sign doc account_number should be "0" -- sign doc sequence should be "0" -- sign doc fee should be `{gas: "0", amount: []}` - -When using the `signArbitrary` API, if the `data` parameter type is `string`, the signature page displays as plain text. - -Using `verifyArbitrary`, you can verify the results requested by `signArbitrary` API or `signAmino` API that has been requested with the ADR-36 spec standards. - -`verifyArbitrary` has been only implemented for simple usage. `verifyArbitrary` returns the result of the verification of the current selected account's sign doc. If the account is not the currently selected account, it would throw an error. - -It is recommended to use `verifyADR36Amino` function in the `@keplr-wallet/cosmos` package or your own implementation instead of using `verifyArbitrary` API. - -### Request Ethereum Signature -```javascript -signEthereum( - chainId: string, - signer: string, // Bech32 address, not hex - data: string | Uint8Array, - type: 'message' | 'transaction' -) -``` - -This is an experimental implementation of native Ethereum signing in Keplr to be used by dApps on EVM-compatible chains such as Evmos. - -It supports signing either [Personal Messages](https://eips.ethereum.org/EIPS/eip-191) or [Transactions](https://ethereum.org/en/developers/docs/transactions/), with plans to support [Typed Data](https://eips.ethereum.org/EIPS/eip-712) in the future. - -Notes on Usage: -- The `signer` field must be a Bech32 address, not an Ethereum hex address -- The data should be either stringified JSON (for transactions) or a string message (for messages). Byte arrays are accepted as alternatives for either. - -### Interaction Options - -```javascript -export interface KeplrIntereactionOptions { - readonly sign?: KeplrSignOptions; -} - -export interface KeplrSignOptions { - readonly preferNoSetFee?: boolean; - readonly preferNoSetMemo?: boolean; -} -``` -Keplr v0.8.11+ offers additional options to customize interactions between the frontend website and Keplr extension. - -If `preferNoSetFee` is set to true, Keplr will prioritize the frontend-suggested fee rather than overriding the tx fee setting of the signing page. - -If `preferNoSetMemo` is set to true, Keplr will not override the memo and set fix memo as the front-end set memo. - -You can set the values as follows: -```javascript -window.keplr.defaultOptions = { - sign: { - preferNoSetFee: true, - preferNoSetMemo: true, - } -} -``` - -## Custom event - -### Change Key Store Event - -```javascript -keplr_keystorechange -``` - -When the user switches their key store/account after the webpage has received the information on the key store/account the key that the webpage is aware of may not match the selected key in Keplr which may cause issues in the interactions. - -To prevent this from happening, when the key store/account is changed, Keplr emits a `keplr_keystorechange` event to the webpage's window. You can request the new key/account based on this event listener. - -```javascript -window.addEventListener("keplr_keystorechange", () => { - console.log("Key store in Keplr is changed. You may need to refetch the account info.") -}) -``` diff --git a/docs/api/signing.md b/docs/api/signing.md new file mode 100644 index 0000000000..7dda73e1ea --- /dev/null +++ b/docs/api/signing.md @@ -0,0 +1,117 @@ +--- +title: Signing and Broadcasting +order: 4 +--- + +# Keplr Signature and Broadcasting API + +Keplr offers a rich set of functions that allow developers to sign various types of data and request broadcasting for transactions. This guide provides an overview of these functionalities. + +## Table of Contents + +- [Sign Amino](#sign-amino-signamino) +- [Sign Direct / Protobuf](#sign-direct-protobuf-signdirect) +- [Request Transaction Broadcasting](#request-transaction-broadcasting-sendtx) +- [Request Signature for Arbitrary Message](#request-signature-for-arbitrary-message-signarbitrary) +- [Verify offline messages](#verifying-offline-message-signatures-verifyarbitrary) +- [Request Ethereum Signature](#request-ethereum-signatures) + +## Sign Modes + +Cosmos SDK chains historically used Amino as the default encoding for transactions and communication. However, with the evolution of Cosmos SDK, Protobuf became the new encoding standard due to its efficiency and cross-language support (Cosmos SDK v0.40+). Most chains today use Protobuf. However, they also have compatibility for Amino signing, primarily due to the support needed for Ledger hardware wallet signing. + +#### When to use signAmino over signDirect? + +Ledger Hardware Wallets: Even if the chain supports Protobuf, if you are targeting users with Ledger hardware wallets within the Cosmos ecosystem, support for Amino signing might still be necessary. As of this writing, the Cosmos app on Ledger devices only supports Amino-encoded transactions. This means that Ledger users will need Amino signing support to interact with the chain. + +### Sign Amino (signAmino) + +```javascript +signAmino(chainId: string, signer: string, signDoc: StdSignDoc): Promise +``` + +- Keplr's `signAmino` is similar to CosmJS `OfflineSigner`'s `signAmino` but with the chain-id as a required parameter. +- It is used to sign Amino-encoded `StdSignDoc`. + +### Sign Direct / Protobuf (signDirect) + +```javascript +signDirect(chainId:string, signer:string, signDoc: { + /** SignDoc bodyBytes */ + bodyBytes?: Uint8Array | null; + /** SignDoc authInfoBytes */ + authInfoBytes?: Uint8Array | null; + /** SignDoc chainId */ + chainId?: string | null; + /** SignDoc accountNumber */ + accountNumber?: Long | null; + }): Promise +``` + +- Similar to CosmJS `OfflineDirectSigner`'s `signDirect` with chain-id as a required parameter. +- Used to sign Proto-encoded `StdSignDoc`. + +### Request Transaction Broadcasting (sendTx) + +```javascript +sendTx( + chainId: string, + tx: Uint8Array, + mode: BroadcastMode +): Promise; +``` + +- Delegates the broadcasting of the transaction to Keplr's LCD endpoints. +- Returns the transaction hash if successful; otherwise, throws an error. +- Keplr sends notifications on transaction progress. + +### Request Signature for Arbitrary Message (signArbitrary) + +```javascript +signArbitrary( + chainId: string, + signer: string, + data: string | Uint8Array +): Promise; +``` + +- Experimental implementation based on [ADR-36](https://github.com/cosmos/cosmos-sdk/blob/master/docs/architecture/adr-036-arbitrary-signature.md). +- Mainly used to prove ownership of an account off-chain. + +To use ADR-36 with the `signAmino` API, the following criteria must be met: + +- The signing document should be in the Amino format. (For Protobuf, ADR-36 requirements aren't fully specified for implementation yet.) +- The message in the sign doc should be singular, with the message type as "sign/MsgSignData". +- The "sign/MsgSignData" message should include "signer" and "data" as its value. The "data" should be base64 encoded. +- Specific fields in the sign doc, such as chain_id, memo, account_number, sequence, and fee, should be set as mentioned in your list above. +- If the `data` parameter type in the `signArbitrary` API is a `string`, the signature page will display as plain text. + +### Verifying offline message signatures (verifyArbitrary) + +Developers can use the `verifyArbitrary` API to validate results from both the `signArbitrary` and `signAmino` APIs, as long as they conform to the ADR-36 specification standards. + +However, a few key things to note: + +- The `verifyArbitrary` API is primarily designed for straightforward usage. +- It will return verification results only for the currently selected account's signing document. If the account isn't the one currently selected, an error will be thrown. +- For a more comprehensive experience, it's advisable to use the `verifyADR36Amino` function from the `@keplr-wallet/cosmos` package or implement a custom solution instead of solely relying on the `verifyArbitrary` API. + +### Request Ethereum Signatures + +```javascript +signEthereum( + chainId: string, + signer: string, // Bech32 address, not hex + data: string | Uint8Array, + type: 'message' | 'transaction' +) +``` + +This is an experimental implementation of native Ethereum signing in Keplr to be used by dApps on EVM-compatible chains such as Evmos. + +- Experimental implementation for native Ethereum signing in Keplr for EVM-compatible chains. +- Supports signing [Personal Messages](https://eips.ethereum.org/EIPS/eip-191) or [Transactions](https://ethereum.org/en/developers/docs/transactions/). + +Notes on Usage: +- The `signer` field must be a Bech32 address, not an Ethereum hex address +- The data should be either stringified JSON (for transactions) or a string message (for messages). Byte arrays are accepted as alternatives for either. \ No newline at end of file diff --git a/docs/api/suggest-chain.md b/docs/api/suggest-chain.md index 8d1dbb5682..5c698a552c 100644 --- a/docs/api/suggest-chain.md +++ b/docs/api/suggest-chain.md @@ -1,6 +1,6 @@ --- title: Suggest Chain -order: 4 +order: 6 --- ### Suggest Chain diff --git a/docs/getting-started/getting-started.md b/docs/getting-started/getting-started.md new file mode 100644 index 0000000000..3c3539cf6c --- /dev/null +++ b/docs/getting-started/getting-started.md @@ -0,0 +1,143 @@ +--- +title: Getting Started +order: 2 +--- + +## Detecting Keplr + +### 1. Detecting Keplr: + +Keplr can be detected on a user's device using the `window.keplr` object. If it returns `undefined` after the document loads, it indicates Keplr is not installed. + +There are two methods to detect Keplr: + +#### Using `window.onload`: +This method ensures that your code runs once the entire page (images or iframes), not just the DOM, is ready. + +```javascript +window.onload = async () => { + // Check if Keplr is installed + if (!window.keplr) { + alert("Please install Keplr extension"); + } else { + // If Keplr is detected, you can proceed with further operations + // ... more code + } +} +``` + +#### Using Document's Ready State: + +This method checks for Keplr once the DOM is completely loaded. It doesn't wait for other resources to finish, like images. + +```javascript +document.addEventListener("readystatechange", event => { + // Ensure the entire document is fully loaded + if (document.readyState === "complete") { + // Check if Keplr is installed + if (window.keplr) { + // If Keplr is detected, you can proceed with further operations + // ... more code + } + } +}); +``` + +While various methods can help in achieving this, there isn't one universally preferred method. Choose the one that best fits your application's architecture. + +#### 2. Enabling and Unlocking Keplr Wallet: + +Upon detecting Keplr, the next step is to enable it for the specific chain you are targeting. This process involves asking the user for permission if they haven't previously granted access to this website. Additionally, if the user's wallet is locked, Keplr will request the user to unlock it. Note that enabling/connection is done at a chain-by-chain basis. + +The code snippet below demonstrates this: + +```javascript +const chainId = "cosmoshub-4"; + +// Enabling Keplr before using it is recommended. +// This method will ask the user for permission to access the website. +// Also, it prompts the user to unlock their wallet if it's locked. +await window.keplr.enable(chainId); +``` + +Once enabled, you can initialize the offline signer which allows transactions to be signed offline for added security. Additionally, Keplr currently manages a single address/public key pair, which you can retrieve using the getAccounts method. This is necessary to set the sender's address for the SigningCosmosClient. + +```javascript +const offlineSigner = window.keplr.getOfflineSigner(chainId); + +// Retrieve the address/public key. +const accounts = await offlineSigner.getAccounts(); + +// Initialize the gaia API with the offline signer provided by Keplr. +const cosmJS = new SigningCosmosClient( + "https://rest.cosmos.directory/cosmoshub", + accounts[0].address, + offlineSigner +); +``` + +Note: Ensure that the necessary JavaScript libraries and dependencies (like `SigningCosmosClient`) are imported and available in your script. + +#### Initializing the Offline Signer: + +The offlineSigner is a software component designed to handle the signing of transactions without requiring an active internet connection. It's called "offline" because the actual signing process doesn't rely on being online, as the signing interaction between the transaction and the private key happens within the user's computer through the wallet. + +Once Keplr is enabled, you can get an instance of the offline signer associated with the specific chain. + +```javascript +const offlineSigner = window.keplr.getOfflineSigner(chainId); +``` + +#### Fetching Public Keys and Addresses: + +Keplr provides the getAccounts method to obtain the user's address and public keys. As of the current Keplr version, it manages only a single address/public key pair. This is crucial to note because the array returned will have only one element. + +```javascript +const accounts = await offlineSigner.getAccounts(); +``` + +#### Initializing the Cosmos Hub (Gaia) API with the Offline Signer: + +With the offline signer and the user's account information, you can initialize the Gaia API (or any other supported Cosmos API). This allows you to perform various operations on the chain, such as sending transactions. + +```javascript +const cosmJS = new SigningCosmosClient( + "https://lcd-cosmoshub.keplr.app", + accounts[0].address, + offlineSigner, +); +``` + +Note: This guide assumes that you're working with the cosmoshub-4 chain and the related Gaia API endpoint. Adjust the chain ID and endpoints based on your specific requirements. + +#### Integrating with TypeScript: Enhancing Keplr Type Support + +For developers leveraging TypeScript, Keplr offers a robust type definition through the @keplr-wallet/types package, ensuring accurate type checking and improved IDE support. This package is essential to facilitate better TypeScript integration. + +**Step-by-Step Integration:** + +1. Installing the Types Package: + +To get started, you first need to install the type definitions package. Depending on your package manager of choice, you can use: +```javascript +npm install --save-dev @keplr-wallet/types +``` +or +```javascript +yarn add -D @keplr-wallet/types +``` + +2. Extending the Global Window Object: +To use Keplr's types seamlessly, extend the global Window object. Create a window.d.ts declaration file and add the following: +```javascript +import { Window as KeplrWindow } from "@keplr-wallet/types"; + +declare global { + interface Window extends KeplrWindow {} +} +``` +This ensures that TypeScript recognizes the Keplr specific methods and properties attached to the window object, offering a more integrated development experience. + +Note: Rely exclusively on @keplr-wallet/types for Keplr's type definitions. This is the only official and recommended type package. + +Other packages related to Keplr is actively used within Keplr Wallet's core logic. However, active changes may be made, backward compatibility is not guaranteed, and we do not provide documentation due to lack of resources at this time. While it is a robust library, use it at your own discretion. \ No newline at end of file diff --git a/docs/getting-started/installation.md b/docs/getting-started/installation.md new file mode 100644 index 0000000000..0361cc419d --- /dev/null +++ b/docs/getting-started/installation.md @@ -0,0 +1,41 @@ +--- +title: Installation and Setup +order: 1 +--- + +## Installation & Setup of Keplr Wallet + +### 1. Browser Extension Download: + - Navigate to your browser's extension or add-on store (e.g., Chrome Web Store for Google Chrome, Firefox Add-ons for Mozilla Firefox). + - Search for "Keplr Wallet". + - Click on "Add to [Browser]" and confirm any prompts to install the extension. + +### 2. Launching the Wallet: + - After installation, locate the Keplr Wallet icon in your browser's toolbar and click on it to initiate the wallet interface. + +### 3. Initial Setup: + - Upon launch, you'll encounter a welcome screen. + - You'll have the option to either "Create New Wallet" or "Import Existing Wallet". + +### 4. Creating a New Wallet: + - If "Create New Wallet" is selected, you'll be prompted to generate a seed phrase. + - It's imperative to securely store this seed phrase as it's the main key to recover your wallet. + - Set a password for an added layer of security within your browser. + +### 5. Importing an Existing Wallet: + - For "Import Existing Wallet", you'll need to input your previously established seed phrase. + - You'll also have the opportunity to set (or reset) a password for the wallet within the browser. + +## Important Considerations + +### Backup Recommendations: + - Always ensure multiple copies of your seed phrase are stored in safe, offline locations (e.g., paper, offline storage devices). + - Never share your seed phrase with anyone, even if they claim to be from the Keplr support team. + +### Extension Authenticity: + - Be cautious of phishing attempts. Always double-check the extension's publisher and reviews before downloading. + - Bookmark the official Keplr or related web pages to avoid visiting malicious sites. + +### Further Learning & Resources: + - For detailed functionalities, troubleshooting, or advanced features, refer to the official Keplr documentation or community forums. + - Developers looking for integrations or API access can explore associated libraries and SDKs, if available, for enhanced dApp integration. diff --git a/docs/getting-started/keplr-basic-api.md b/docs/getting-started/keplr-basic-api.md new file mode 100644 index 0000000000..c9ae09ced8 --- /dev/null +++ b/docs/getting-started/keplr-basic-api.md @@ -0,0 +1,102 @@ +--- +title: Keplr API Usage +order: 3 +--- + +## Keplr API Documentation + +### Overview +While Keplr provides an effortless integration with CosmJS, it also has its exclusive features. This guide details those Keplr-specific methods and functionalities. + +### Enable Connection + +To connect and gain permission: +```javascript +enable(chainIds: string | string[]): Promise +``` + +- If Keplr is locked, this prompts the user to unlock. +- If the webpage hasn't been granted permission, the user will be asked to provide it. +- Accepts one or multiple chain-ids. +- Errors will be thrown if the user cancels the unlock or denies permission. + +### Retrieve Address & Public Key +Acquire the user's public key and address: + +```javascript +getKey(chainId: string): Promise<{ + name: string; + algo: string; + pubKey: Uint8Array; + address: Uint8Array; + bech32Address: string; + isNanoLedger: boolean; +}> +``` + +The function also returns the current key store's nickname, which useful for dApps to display to users. The `isNanoLedger` flag indicates if the account is linked to a Ledger Nano device. + +Note that the current Ledger Cosmos app doesn't support the signDirect and only signAmino. The value returned from this field can be used to select signDirect or signAmino. +### Interaction Options + +```javascript +export interface KeplrIntereactionOptions { + readonly sign?: KeplrSignOptions; +} + +export interface KeplrSignOptions { + readonly preferNoSetFee?: boolean; + readonly preferNoSetMemo?: boolean; +} +``` +Keplr v0.8.11+ offers additional options to customize interactions between the frontend website and Keplr extension. + +If `preferNoSetFee` is set to true, Keplr will prioritize the frontend-suggested fee rather than overriding the tx fee setting of the signing page. + +- **`preferNoSetFee`**: + When you set `preferNoSetFee` to `true`, it signals to Keplr that the frontend website or application has a preference for the fee it has suggested, and Keplr should prioritize this fee when initiating a transaction. Without this flag or when set to `false`, Keplr might override the fee specified by the frontend, potentially using its internal mechanisms to determine the optimal fee. + +- **Use case for `preferNoSetFee`**: + - **User-Centric Experience**: A dapp might want to subsidize the transaction fee for the user and thus set a specific fee, making sure the user doesn't have to pay. In such cases, they wouldn't want the wallet (Keplr, in this case) to modify that fee. + - **Optimal Fee Calculations**: A frontend might use its algorithms to calculate an optimal fee based on network congestion, aiming for a balance between fast confirmation times and cost. This calculated fee should not be overridden by the wallet. + + +If `preferNoSetMemo` is set to true, Keplr will not override the memo and set fix memo as the front-end set memo. + +- **`preferNoSetMemo`**: + The memo field in transactions is typically used for adding arbitrary comments or information. By setting `preferNoSetMemo` to `true`, you're instructing Keplr not to override the memo set by the frontend. This means whatever memo the frontend specifies will be retained in the transaction without Keplr attempting to modify it. + +- **Use case for `preferNoSetMemo`**: + - **Specific Instructions**: In some platforms, the memo could be used to relay specific instructions or identifiers. For instance, when sending tokens to an exchange, a memo might be used to specify which user account the tokens should be credited to. In such scenarios, it's crucial the memo isn't altered. + - **Traceability**: Dapps might add specific identifiers in memos for tracing transactions back to particular actions/events within the app. An overridden memo could disrupt this traceability. + + +You can set the values as follows: +```javascript +window.keplr.defaultOptions = { + sign: { + preferNoSetFee: true, // Indicating preference for frontend-specified fee + preferNoSetMemo: true, // Indicating preference for frontend-specified memo + } +} +``` + + +## Custom event + +### Change Key Store Event + +```javascript +keplr_keystorechange +``` + +When the user switches their key store/account after the webpage has received the information on the key store/account the key that the webpage is aware of may not match the selected key in Keplr which may cause issues in the interactions. + +To prevent this from happening, when the key store/account is changed, Keplr emits a `keplr_keystorechange` event to the webpage's window. You can request the new key/account based on this event listener. + +```javascript +window.addEventListener("keplr_keystorechange", () => { + console.log("Key store in Keplr is changed. You may need to refetch the account info.") +}) +``` + diff --git a/docs/api/cosmjs.md b/docs/signing-lib/cosmjs.md similarity index 99% rename from docs/api/cosmjs.md rename to docs/signing-lib/cosmjs.md index d4204900b6..07dcf56128 100644 --- a/docs/api/cosmjs.md +++ b/docs/signing-lib/cosmjs.md @@ -1,6 +1,6 @@ --- title: Use with CosmJs -order: 2 +order: 5 --- ## How to detect Keplr diff --git a/docs/api/secretjs.md b/docs/signing-lib/secretjs.md similarity index 100% rename from docs/api/secretjs.md rename to docs/signing-lib/secretjs.md