diff --git a/wallet/how-to/use-non-evm-networks/_category_.json b/wallet/how-to/use-non-evm-networks/_category_.json deleted file mode 100644 index 6a40514d41..0000000000 --- a/wallet/how-to/use-non-evm-networks/_category_.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "label": "Use non-EVM networks", - "position": 9, - "link": { - "type": "doc", - "id": "how-to/use-non-evm-networks/index" - } -} diff --git a/wallet/how-to/use-non-evm-networks/index.md b/wallet/how-to/use-non-evm-networks/index.md index 42165de095..88b818cfaf 100644 --- a/wallet/how-to/use-non-evm-networks/index.md +++ b/wallet/how-to/use-non-evm-networks/index.md @@ -1,5 +1,6 @@ --- -description: Interact with users' accounts on non-EVM networks +description: Interact with users' accounts on non-EVM networks. +sidebar_position: 9 --- import CardList from "@site/src/components/CardList" diff --git a/wallet/how-to/use-non-evm-networks/starknet/_category_.json b/wallet/how-to/use-non-evm-networks/starknet/_category_.json deleted file mode 100644 index 20f92141a9..0000000000 --- a/wallet/how-to/use-non-evm-networks/starknet/_category_.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "label": "Starknet", - "collapsible": true, - "collapsed": true, - "link": { - "type": "doc", - "id": "how-to/use-non-evm-networks/starknet/index" - } -} \ No newline at end of file diff --git a/wallet/how-to/use-non-evm-networks/starknet/connect-to-starknet.md b/wallet/how-to/use-non-evm-networks/starknet/connect-to-starknet.md index ebc0f632bf..9ab10feccc 100644 --- a/wallet/how-to/use-non-evm-networks/starknet/connect-to-starknet.md +++ b/wallet/how-to/use-non-evm-networks/starknet/connect-to-starknet.md @@ -22,6 +22,12 @@ This library simplifies the process of connecting to the Starknet Snap, allowing ## Connect using `get-starknet` +:::note + +We recommend using the `get-starknet method for most uses. + +::: + ### 1. Add `get-starknet` to your project Add the [`get-starknet`](https://github.com/starknet-io/get-starknet) `version 3.3.0` library and the version `6.11.0` of the `starknet.js` library to your project's dependencies: @@ -46,11 +52,10 @@ Add the [`get-starknet`](https://github.com/starknet-io/get-starknet) `version 3 ### 2. Connect to the Snap -Create a new file named `WalletConnectButton.js` in your project's `src/components` folder. Create this folder if it doesn't exist. Add the following code to the file:. - -```javascript -import React, { useState } from 'react'; -import { connect, disconnect } from 'get-starknet'; +Create a `src/components` directory, and add a new file named `WalletConnectButton.js` to the directory. Add the following code to the file: +```javascript title="WalletConnectButton.js" +import React, { useState } from "react"; +import { connect, disconnect } from "get-starknet"; import { encode } from "starknet"; function WalletConnectButton() { const [walletAddress, setWalletAddress] = useState(""); @@ -110,7 +115,7 @@ To connect to Starknet, the dapp user must ensure the [Starknet Snap](https://sn ### 3. Start the dapp -Start the dapp, which allow users to click **Connect Wallet** and interact with the Starknet network using MetaMask: +Start the dapp, which allows users to select **Connect Wallet** and interact with the Starknet network using MetaMask: @@ -142,14 +147,15 @@ Alternatively, you can manage the Snap invocation manually. Use the `wallet_invo ::: -In the `src/utils/snapHelper.js` file add the `connect` function and the `callSnap` helper function. This file handles the interactions with the Starknet Snap. +Create a `src/utils` directory, and add a new file named `snapHelper.js` to the directory. +In `snapHelper.js`, add a `connect` function and a `callSnap` helper function as follows. This file handles the interactions with the Starknet Snap: -```javascript title="src/utils/snapHelper.js" -const snapId = 'npm:starknet-snap'; +```javascript title="snapHelper.js" +const snapId = "npm:starknet-snap"; export async function connect() { await ethereum.request({ - method: 'wallet_requestSnaps', + method: "wallet_requestSnaps", params: { [snapId]: {}, }, @@ -159,7 +165,7 @@ export async function connect() { export async function callSnap(method, params) { try { const response = await ethereum.request({ - method: 'wallet_invokeSnap', + method: "wallet_invokeSnap", params: { snapId, request: { @@ -180,18 +186,20 @@ export async function callSnap(method, params) { ### 2. Call a specific Snap method -To call a specific Snap method, for example `createAccount` use the following: +Use the `callSnap` function to call a specific Snap method. +The following example calls `starkNet_createAccount`: ```javascript const deploy = false; // Set to true to deploy the actual account const addressIndex = 0; // Specify which address to derive -const chainId = "0x534e5f5345504f4c4941"; // Specify which chain to use (Sepolia testnet) -// For mainnet, use: "0x534e5f4d41494e" +const chainId = "0x534e5f5345504f4c4941"; // Specify which chain to use (in this instance the Sepolia testnet) const accountInfo = await callSnap('starkNet_createAccount', { addressIndex, deploy, chainId }); ``` -#### Example in HTML and JavaScript (Vanilla JS) +#### Example in HTML and Vanilla JS + +The following is a full example of a dapp with a button that, when clicked, connects to a Starknet wallet using a MetaMask Snap, creates a Starknet account, and displays the account address: ```html @@ -234,9 +242,9 @@ const accountInfo = await callSnap('starkNet_createAccount', { addressIndex, dep try { const snapId = 'npm:@consensys/starknet-snap'; // Snap ID await connect(snapId); - const deploy = false; // whether to deploy the actual account - const addressIndex = 0; // which address to derive - const chainId = "0x534e5f5345504f4c4941"; // which chain to use mainnet id "0x534e5f4d41494e", sepolia id "0x534e5f5345504f4c4941" + const deploy = false; // Whether to deploy the actual account. + const addressIndex = 0; // The address to derive. + const chainId = "0x534e5f5345504f4c4941"; // Chain ID of the network to use. const account = await callSnap(snapId, 'starkNet_createAccount', { addressIndex, deploy, chainId }); console.log(account) document.getElementById('accountInfo').innerText = `Connected Starknet Account: ${account.address}`; @@ -251,27 +259,29 @@ const accountInfo = await callSnap('starkNet_createAccount', { addressIndex, dep #### Example in a React component +The following is a full example of connecting to the Starknet Snap using `wallet_invokeSnap` in a React component: + ```javascript -import React, { useState } from 'react'; +import React, { useState } from "react"; const ConnectWallet = () => { const [accountInfo, setAccountInfo] = useState(''); const connect = async (snapId) => { try { await window.ethereum.request({ - method: 'wallet_requestSnaps', + method: "wallet_requestSnaps", params: { [snapId]: {}, }, }); } catch (err) { - console.error('Snap connection error:', err); + console.error("Snap connection error:", err); alert(`Error connecting to Snap: ${err.message || err}`); } }; const callSnap = async (snapId, method, params) => { try { const response = await window.ethereum.request({ - method: 'wallet_invokeSnap', + method: "wallet_invokeSnap", params: { snapId, request: { @@ -288,15 +298,15 @@ const ConnectWallet = () => { }; const handleConnectClick = async () => { try { - const snapId = 'npm:@consensys/starknet-snap'; // Snap ID + const snapId = "npm:@consensys/starknet-snap"; // Snap ID await connect(snapId); - const deploy = false; // whether to deploy the actual account - const addressIndex = 0; // which address to derive - const chainId = '0x534e5f5345504f4c4941'; // chain (sepolia) - const account = await callSnap(snapId, 'starkNet_createAccount', { addressIndex, deploy, chainId }); + const deploy = false; // Whether to deploy the actual account. + const addressIndex = 0; // The address to derive. + const chainId = "0x534e5f5345504f4c4941"; // Chain ID of the network to use. + const account = await callSnap(snapId, "starkNet_createAccount", { addressIndex, deploy, chainId }); setAccountInfo(`Connected Starknet Account: ${account.address}`); } catch (error) { - console.error('Error connecting to Starknet Snap:', error); + console.error("Error connecting to Starknet Snap:", error); } }; return ( diff --git a/wallet/how-to/use-non-evm-networks/starknet/index.md b/wallet/how-to/use-non-evm-networks/starknet/index.md index 037da298ed..8d9c8487e2 100644 --- a/wallet/how-to/use-non-evm-networks/starknet/index.md +++ b/wallet/how-to/use-non-evm-networks/starknet/index.md @@ -8,7 +8,7 @@ sidebar_position: 1 Starknet is a non-EVM Layer 2 network. To interact with Starknet accounts in MetaMask, you need to use the Starknet Snap. You can use the `get-starknet` library or the `wallet_invokeSnap` JSON-RPC method to connect to the Starknet Snap. -The choice depends on your specific use case and development preferences. + `get-starknet`: - Provides a high-level API that abstracts complex operations. @@ -27,7 +27,7 @@ The choice depends on your specific use case and development preferences. :::note -We recommend using the `get-starknet` library for a most use cases. +We recommend using the `get-starknet` library for most use cases. ::: @@ -59,7 +59,7 @@ sequenceDiagram participant get as get-starknet participant mm as MetaMask participant Snap as Starknet Snap - participant network as Starknet Network + participant network as Starknet network dapp->>get: Initialize connection get->>mm: Request connection @@ -87,11 +87,11 @@ sequenceDiagram get->>dapp: Notify change ``` -The `get-starknet` library offers several key features that improve how dapps interact with the StarkNet network through MetaMask." +The `get-starknet` library offers several key features that improve how dapps interact with the Starknet network through MetaMask: -- The `WalletAccount` uses a specified provider to access data from the StarkNet network. -- For transactions, `get-starknet` prepares the data and sends it to MetaMask for signing via StarkNet Snap. +- The `WalletAccount` uses a specified provider to access data from the Starknet network. +- For transactions, `get-starknet` prepares the data and sends it to MetaMask for signing through the Starknet Snap. - `get-starknet` enables the dapp to create contract instances connected to the `WalletAccount`, allowing smart contract functions to be invoked, with MetaMask handling the signatures. -- It sets up listeners for account and network changes in MetaMask, so the dapp can subscribe and update its state accordingly. -- `get-starknet` can request network changes through MetaMask, allowing users to switch between StarkNet networks, such as Mainnet or Sepolia testnet. -- It can also request MetaMask to display specific tokens, improving the user experience. \ No newline at end of file +- `get-starknet` sets up listeners for account and network changes in MetaMask, so the dapp can subscribe and update its state accordingly. +- `get-starknet` can request network changes through MetaMask, allowing users to switch between Starknet networks, such as Mainnet or Sepolia testnet. +- `get-starknet` can also request MetaMask to display specific tokens, improving the user experience. \ No newline at end of file diff --git a/wallet/how-to/use-non-evm-networks/starknet/manage-starknet-accounts.md b/wallet/how-to/use-non-evm-networks/starknet/manage-starknet-accounts.md index de0a8ca836..83852338ad 100644 --- a/wallet/how-to/use-non-evm-networks/starknet/manage-starknet-accounts.md +++ b/wallet/how-to/use-non-evm-networks/starknet/manage-starknet-accounts.md @@ -5,15 +5,7 @@ sidebar_position: 2 # Manage Starknet accounts -## Account creation - -Account creation in Starknet is handled by the wallet provider. As a dapp developer, you do not create accounts directly. Instead, you guide users to create an account with their preferred wallet provider. - -:::note - -Currently, multiple Starknet accounts are not supported in the Starknet Snap. - -::: +You can manage Starknet accounts to display account information, handle transactions, and respond to account changes in your dapp. ## View account information @@ -23,7 +15,7 @@ After a user connects, you can display the account details, such as the account const showAccountInfo = async () => { const account = await connectStarknetAccount(); if (account) { - document.getElementById('accountAddress').innerText = `Account Address: ${account}`; + document.getElementById("accountAddress").innerText = `Account Address: ${account}`; } }; ``` @@ -33,8 +25,8 @@ const showAccountInfo = async () => { To retrieve and display connected Starknet accounts, use the `get-starknet` library in combination with React hooks: ```javascript -import { useStarknet, useConnectors } from '@starknet-react/core'; -import { useState, useEffect } from 'react'; +import { useStarknet, useConnectors } from "@starknet-react/core"; +import { useState, useEffect } from "react"; function AccountDisplay() { const { account } = useStarknet(); @@ -67,6 +59,16 @@ function AccountDisplay() { This component displays the connected account address if available, and provides buttons to connect or disconnect accounts. +## Account creation + +Account creation in Starknet is handled by the wallet provider. As a dapp developer, you do not create accounts directly. Instead, you guide users to create an account with their preferred wallet provider. + +:::note + +Currently, multiple Starknet accounts are not supported in the Starknet Snap. + +::: + ## Manage account transactions You can manage transactions with `get-starknet`: @@ -78,8 +80,8 @@ const invokeStarknetContract = async () => { const starknet = getStarknet(); await starknet.enable(); // Make sure the wallet is enabled - const contractAddress = '0xYourContractAddress'; // Replace with your contract address - const entrypoint = 'function_name'; // The function you want to call + const contractAddress = "0xYourContractAddress"; // Replace with your contract address + const entrypoint = "function_name"; // The function you want to call const calldata = [/* your function arguments */]; // Replace with calldata const result = await starknet.invoke({ @@ -88,21 +90,22 @@ const invokeStarknetContract = async () => { calldata: calldata }); - console.log('Transaction result:', result); + console.log("Transaction result: ", result); } catch (error) { - console.error('Error invoking contract:', error); + console.error("Error invoking contract:", error); } }; ``` This invokes a specific function on a Starknet smart contract, handling wallet connection and transaction submission, and logs the result or any errors. + ## Handle account changes and disconnections To handle account changes and disconnections, you can use event listeners provided by `get-starknet`: ```javascript -import { getStarknet } from 'get-starknet'; -import { useEffect, useState } from 'react'; +import { getStarknet } from "get-starknet"; +import { useEffect, useState } from "react"; function AccountChangeHandler() { const [account, setAccount] = useState(null); @@ -111,20 +114,20 @@ function AccountChangeHandler() { const starknet = getStarknet(); const handleAccountsChanged = (accounts: string[]) => { - console.log('Accounts changed:', accounts); + console.log("Accounts changed:", accounts); setAccount(accounts[0] || null); - // Update your app's state here + // Update your app"s state here }; const handleDisconnect = () => { - console.log('Disconnected from wallet'); + console.log("Disconnected from wallet"); setAccount(null); // Handle disconnection (e.g., reset app state, show connect button) }; if (starknet) { - starknet.on('accountsChanged', handleAccountsChanged); - starknet.on('networkChanged', handleDisconnect); + starknet.on("accountsChanged", handleAccountsChanged); + starknet.on("networkChanged", handleDisconnect); // Initial account setup starknet.enable().then((accounts: string[]) => { @@ -132,8 +135,8 @@ function AccountChangeHandler() { }); return () => { - starknet.off('accountsChanged', handleAccountsChanged); - starknet.off('networkChanged', handleDisconnect); + starknet.off("accountsChanged", handleAccountsChanged); + starknet.off("networkChanged", handleDisconnect); }; } }, []); diff --git a/wallet/how-to/use-non-evm-networks/starknet/sign-starknet-data.md b/wallet/how-to/use-non-evm-networks/starknet/sign-starknet-data.md index 2515fc0d56..619ea2540d 100644 --- a/wallet/how-to/use-non-evm-networks/starknet/sign-starknet-data.md +++ b/wallet/how-to/use-non-evm-networks/starknet/sign-starknet-data.md @@ -1,6 +1,27 @@ --- -description: Sign Starknet data in MetaMask. +description: Sign Starknet transactions in MetaMask. sidebar_position: 5 --- -# Sign Starknet data \ No newline at end of file +# Sign Starknet transactions + +After the account is connected, you can sign a transaction using the `wallet.account.signer.signTransaction` function: +```typescript +const signStarknetTransaction = async (wallet, contractAddress, entrypoint, calldata) => { + try { + if(wallet?.isConnected !== true){ + throw('Wallet not connected'); + } + + // Send the transaction + const result = await wallet?.account?.signer.signTransaction({ + contractAddress: contractAddress, // The address of the contract + entrypoint: entrypoint, // The function to call in the contract + calldata: calldata // The parameters to pass to the function + }); + console.log('Transaction signed successfully:', result); + return result; + } catch (error) { + console.error('Error signing transaction:', error); + } +}; \ No newline at end of file diff --git a/wallet/how-to/use-non-evm-networks/starknet/tutorial.md b/wallet/how-to/use-non-evm-networks/starknet/tutorial.md index 0b2fa6d03e..dda9cf16e6 100644 --- a/wallet/how-to/use-non-evm-networks/starknet/tutorial.md +++ b/wallet/how-to/use-non-evm-networks/starknet/tutorial.md @@ -3,13 +3,13 @@ description: Starknet integration tutorial sidebar_position: 6 --- -# Build a Basic dApp with get-starknet and React TypeScript +# Create a basic dapp with `get-starknet` and React TypeScript -In this tutorial, you'll learn how to set up a basic dApp that uses get-starknet to connect to MetaMask and display the user's wallet address. +In this tutorial, you'll learn how to set up a basic dapp that uses get-starknet to connect to MetaMask and display the user's wallet address. ## 1. Project Setup -First, create a new React project with TypeScript and add the necessary dependencies: +Create a new React project with TypeScript and add the necessary dependencies ```bash # Create a new React project with TypeScript @@ -22,21 +22,17 @@ cd get-starknet-tutorial yarn add get-starknet starknet@next ``` -Note: We use the @next version of starknet to ensure compatibility with get-starknet. +## 2. -## 2. Key Elements to Understand Before Coding +### 2.1. Connecting to a wallet -Before we dive into the implementation, it's important to understand a few key concepts when using get-starknet to connect to a wallet in a React application. - -### 2.1. Connecting to a Wallet - -The `connect` function from get-starknet is the primary way to connect your dApp to a user's wallet. When called, it opens a connection to a wallet (like MetaMask) and returns an object containing important details about the wallet, such as: +The `connect` function from `get-starknet` is the primary way to connect your dapp to a user's wallet. When called, it opens a connection to the MetaMask wallet and returns an object containing important details about the wallet, such as following: - `name`: The name of the wallet. - `icon`: The wallet's icon, which can be used to display the wallet's logo. -- `account`: The account object from starknet.js, which contains the wallet's address and provides access to account-specific operations. +- `account`: The account object from `starknet.js`, which contains the wallet's address and provides access to account-specific operations. -Here's how you would import the necessary functions and connect to a wallet: +To import the necessary functions and connect to a wallet, add the following code: ```typescript import { connect, type ConnectOptions } from "get-starknet"; @@ -48,14 +44,14 @@ async function handleConnect(options?: ConnectOptions) { } ``` -### 2.2. Handling Connection Options +### 2.2. Configure connection options `connect` accepts an optional `ConnectOptions` object. This object can control how the connection process behaves, including: -- `modalMode`: Determines how the connection modal behaves (e.g., always ask, never ask). -- `modalTheme`: Allows setting the theme of the connection modal (e.g., dark, light). +- `modalMode`: Determines how the connection modal behaves. The options include "always ask" or "never ask". +- `modalTheme`: Allows setting the theme of the connection modal. The options includes dark or light theme. -Here's an example of how to pass these options: +The following code is an example of how to set these options: ```typescript handleConnect({ modalMode: "alwaysAsk", modalTheme: "dark" }); @@ -63,10 +59,10 @@ handleConnect({ modalMode: "alwaysAsk", modalTheme: "dark" }); ### 2.3. Create a `WalletAccount` -Once connected, you can create a new `WalletAccount` instance using the starknet.js library. This allows you to interact with the StarkNet network using the connected wallet, leveraging all the features of a standard Account object. +After it is connected, you can create a new `WalletAccount` instance using the `starknet.js` library. This allows interaction with the Starknet network using the connected wallet. ```typescript -import { WalletAccount } from 'starknet'; // v6.10.0 min +import { WalletAccount } from 'starknet'; async function handleConnect(options?: ConnectOptions) { const res = await connect(options); @@ -78,7 +74,7 @@ async function handleConnect(options?: ConnectOptions) { ### 2.4. Display wallet information -Once connected, the wallet's name, address, and icon can be displayed in your dApp. This provides visual feedback to the user, confirming which wallet they are using. +The wallet's name, address, and icon can be displayed in your dapp. This provides visual feedback to the user, confirming which wallet they are using. Here's a basic example of how to update the UI with the connected wallet's details: @@ -107,7 +103,7 @@ function App() { } ``` -### 2.5. The full code example +### 2.5. Example implementation Now that you understand the key elements and have seen snippets of the most important parts, here's the full implementation in `App.tsx`: @@ -316,7 +312,7 @@ The contract address for STRK (an ERC-20 token) on Sepolia testnet is `0x049D365 ## Next steps -In this section, we've shown how to extend your dApp by displaying the balance of an ERC-20 token like ETH and performing a token transfer. By creating a Contract instance with the WalletAccount, you can easily interact with smart contracts, fetch token balances, and execute transactions, enabling more complex functionality in your dApp. +In this section, we've shown how to extend your dapp by displaying the balance of an ERC-20 token like ETH and performing a token transfer. By creating a Contract instance with the WalletAccount, you can easily interact with smart contracts, fetch token balances, and execute transactions, enabling more complex functionality in your dapp. ## Additional resources