Skip to content

Commit

Permalink
apply suggestions
Browse files Browse the repository at this point in the history
  • Loading branch information
joaniefromtheblock committed Sep 19, 2024
1 parent b915696 commit 5b6e1cf
Show file tree
Hide file tree
Showing 8 changed files with 117 additions and 103 deletions.
8 changes: 0 additions & 8 deletions wallet/how-to/use-non-evm-networks/_category_.json

This file was deleted.

3 changes: 2 additions & 1 deletion wallet/how-to/use-non-evm-networks/index.md
Original file line number Diff line number Diff line change
@@ -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"
Expand Down
9 changes: 0 additions & 9 deletions wallet/how-to/use-non-evm-networks/starknet/_category_.json

This file was deleted.

66 changes: 38 additions & 28 deletions wallet/how-to/use-non-evm-networks/starknet/connect-to-starknet.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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("");
Expand Down Expand Up @@ -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:
<Tabs>
<TabItem value="yarn" label="Yarn" default>
Expand Down Expand Up @@ -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]: {},
},
Expand All @@ -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: {
Expand All @@ -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
<html lang="en">
Expand Down Expand Up @@ -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}`;
Expand All @@ -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: {
Expand All @@ -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 (
Expand Down
18 changes: 9 additions & 9 deletions wallet/how-to/use-non-evm-networks/starknet/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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.

:::

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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.
- `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.
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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}`;
}
};
```
Expand All @@ -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();
Expand Down Expand Up @@ -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`:
Expand All @@ -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({
Expand All @@ -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<string | null>(null);
Expand All @@ -111,29 +114,29 @@ 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[]) => {
setAccount(accounts[0] || null);
});

return () => {
starknet.off('accountsChanged', handleAccountsChanged);
starknet.off('networkChanged', handleDisconnect);
starknet.off("accountsChanged", handleAccountsChanged);
starknet.off("networkChanged", handleDisconnect);
};
}
}, []);
Expand Down
25 changes: 23 additions & 2 deletions wallet/how-to/use-non-evm-networks/starknet/sign-starknet-data.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,27 @@
---
description: Sign Starknet data in MetaMask.
description: Sign Starknet transactions in MetaMask.
sidebar_position: 5
---

# Sign Starknet data
# 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);
}
};
Loading

0 comments on commit 5b6e1cf

Please sign in to comment.