Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement local Katana integration #181

Closed
3 tasks done
stranger80 opened this issue Oct 30, 2023 · 3 comments
Closed
3 tasks done

Implement local Katana integration #181

stranger80 opened this issue Oct 30, 2023 · 3 comments
Assignees
Labels
Milestone

Comments

@stranger80
Copy link
Contributor

stranger80 commented Oct 30, 2023

Ensure that user can connect to a local Katana instance
(instead of is_alive use "version" endpoint)

Checklist
  • Modify plugin/src/components/DevnetAccountSelector/index.tsx7296dc8
  • Check plugin/src/components/DevnetAccountSelector/index.tsxd92ee01
  • Modify plugin/src/components/EnvironmentSelector/index.tsx ! No changes made

Flowchart

Copy link

sweep-ai bot commented Nov 1, 2023

Here's the PR! #190.

Sweep Basic Tier: I'm using GPT-4. You have 5 GPT-4 tickets left for the month and 3 for the day.

For more GPT-4 tickets, visit our payment portal. For a one week free trial, try Sweep Pro (unlimited GPT-4 tickets).

Actions (click)

  • ↻ Restart Sweep
Install Sweep Configs: Pull Request

Step 1: 🔎 Searching

I found the following snippets in your repository. I will now analyze these snippets and come up with a plan.

Some code snippets I looked at (click to expand). If some file is missing from here, you can mention the path in the ticket description.

[![Discord](https://img.shields.io/discord/629004402170134531?label=Discord)](https://discord.com/invite/PaCMRFdvWT)
[![Static Badge](https://img.shields.io/badge/Telegram-2AABEE)](https://t.me/StarknetRemixPlugin)
Welcome to the **Starknet Remix Plugin** repository! 🎉
This powerful tool seamlessly integrates with the Remix IDE, enabling developers to effortlessly deploy and interact with Starknet contracts! Whether you're a Cairo and Starknet wizard 🧙‍♂️ or taking your very first steps, this plugin supercharges your journey by providing an effortless way to deploy and interact with Starknet contracts. Happy coding! 🚀
<details>
<summary>Table of Contents</summary>
- [Starknet Remix Plugin](#Starknet-remix-plugin)
- [For Users](#for-users)
- [Getting Started](#getting-started)
- Installation
- Usage
- Feedback
- [For Developers](#for-developers)
- [Installation](#installation)
- [API](#api)
- [Plugin](#plugin)
- [Running the Development Environment](#running-the-development-environment)
- [Connecting the Plugin](#connecting-the-plugin)
- [Support and Contributions](#support-and-contributions)
</details>
## For users
If you're looking to utilize the capabilities of Starknet contracts within the Remix IDE, you've come to the right place. This section provides you with a straightforward guide to get started.
### Getting Started
1. **Installation**: Get excited, folks, no complicated installations needed here! If you're a user, all you have to do is head over to the Remix IDE and locate the Starknet Remix Plugin in the plugins section. Want to make it even simpler? Click right through to Remix using [this direct link](https://remix.ethereum.org/#activate=Starknet) and you're good to go! 🎉
2. **Usage**: Once the plugin is activated, you'll find a user-friendly interface that allows you to deploy and interact with Starknet contracts. Follow the on-screen prompts and tooltips for an effortlessly smooth experience!
3. **Feedback**: Your feedback is invaluable to us 🌟! If you encounter any issues or have game-changing suggestions, don't hesitate to reach out through our [Discord](https://discord.com/invite/PaCMRFdvWT) or our [Community Forum](https://community.nethermind.io/). Let's make something awesome together! 🤝
### Troubleshooting
Most issues with Starknet plugin or Remix itself are caused by connectivity problems (also resulting from restricted networks, web-proxies blocking certain content, etc.) or browser plugin interference.
- A user should first attempt to disable any browser components & addons which may impact the connectivity or Javascript execution.
- Some networks may restrict connectivity to certain sites or domains. Using a VPN connection may resolve problems observed on restricted networks.
More specific potential error causes are also described in detail below.
<details>
<summary><strong>1. Problems when searching plugins in Remix UI</strong></summary>
<br/>
Searching for online plugins in Remix IDE may return blank or otherwise incorrect content, such as on screenshot below:
![Plugin search not working](docs/images/plugin-search-error.png)
Ensure that the following URL is accessible from a web browser, and that a JSON metadata code is returned -
https://raw.githubusercontent.com/ethereum/remix-plugins-directory/master/build/metadata.json :
![Correct plugin metadata](docs/images/plugin-metadata-connectivity.png)
</details>
<details>
<summary><strong>2. Problems when launching Starknet plugin in Remix UI</strong></summary>
<br/>
Starknet plugin launch issues may be caused by connectivity errors or plugin components being unavailable. This can be tested from web browser, as indicated below:
- https://cairo-remix-test.nethermind.io should respond with blank page (advanced: viewing page source will reveal a React component entry HTML markup) - no errors should be reported by the browser
- https://cairo-compile-remix-test.nethermind.io/health should respond with `OK`
- https://starknet-devnet-dev.nethermind.io/predeployed_accounts should respond with JSON text describing predeployed Starknet accounts
</details>
<details>
<summary><strong>3. `localStorage` access errors</strong></summary>
<br/>
The following error indicates that the browser is blocking access to `localStorage` element of the webpage:
![localStorage access error](docs/images/plugin-localStorage-error.png)
Possible causes:
- Chrome is launched in incognito mode
- Chrome setting "Block third-party cookies" is activated (see [chrome://settings/cookies](chrome://settings/cookies)):
![Chrome cookies settings](docs/images/plugin-chrome-cookies-settings.png)
Note: even with "Block third-party cookies" activate, exceptions can be added to a whitelist - the whitelist must include:
- https://remix.ethereum.org
- https://cairo-remix-test.nethermind.io
- ...also see this [link](https://stackoverflow.com/questions/30481516/iframe-in-chrome-error-failed-to-read-localstorage-from-window-access-deni) for potential hints.
</details>
## For Developers
### Installation
#### API
Our API is built with [Rocket](https://rocket.rs/), a web framework for Rust. So, you'll need to get Rust and Cargo on your machine to get started. 🛠️
The easiest way to install Rust and Cargo is by using [rustup](https://rustup.rs/). It's the [recommended tool](https://www.rust-lang.org/tools/install) for managing Rust versions and associated tools for your project.
Then:
```bash
cd api;
git submodule update --init;
cargo build;
```
#### Plugin
The plugin it self is a React project, you'll need to install [pnpm](https://pnpm.io/installation#using-npm).
```bash
cd plugin;
pnpm install;
```
#### Running the development environment
You need to be running both the server and the plugin in order to have a working environment.
For your dev environment:
```bash
cd plugin;
pnpm run start;
```
For an optimized build (will not listen to changes):
```
pnpm run deploy;
pnpm run serve;
```
```bash
cd api;
cargo run;
```
or alternatively, you can run the server in watch mode (with `cargo watch`):
```bash
cargo install cargo-watch;
cargo watch -x run;
```
For devnet interactions, you'll need to use [Starknet Devnet](https://github.com/Shard-Labs/Starknet-devnet).
##### Connecting the plugin
In [Remix](http://remix-alpha.ethereum.org/), go to the `Plugin Manager` at the bottom of the left panel, and click on `Connect to a Local Plugin`.
Then, chose a name for the plugin, and in the `URL` field, enter `http://localhost:3000`, the `Type of Connection` should `iframe` and the `Location in remix` `Side Panel` and click on `Ok`, see the image below.
![Plugin Manager](./docs/images/plugin-import.png)
You should be all set to see the magic happen! Activate the plugin and it should now be visible and ready to be hacked with! 🚀
## Support and Contributions
Feel free to contribute! Spotted any [issues](https://github.com/NethermindEth/Starknet-remix-plugin/issues)? Head on over to our [good first issues](https://github.com/NethermindEth/Starknet-remix-plugin/issues?q=is%3Aissue+is%3Aopen+label%3A%22good+first+issue%22) or read through our [Contribution Guidelines](/docs/CONTRIBUTING.md) to get started. 📝
Jump into our [Discord channel](https://discord.com/invite/PaCMRFdvWT) and join our thriving [community](https://community.nethermind.io/)! Connect with other users, share insights, and get all your questions answered. Our community is always eager to help newcomers! 🤝
We're thrilled for you to experience the Starknet Remix Plugin, and we can't wait to see the inventive ways you'll engage with Starknet contracts! Happy coding! 💡

import {
getRoundedNumber,
getShortenedHash,
weiToEth
} from '../../utils/utils'
import { getAccounts } from '../../utils/network'
import React, { useEffect, useState } from 'react'
import { Account, Provider } from 'starknet'
import { MdCopyAll, MdRefresh } from 'react-icons/md'
import './devnetAccountSelector.css'
import copy from 'copy-to-clipboard'
import { useAtom, useAtomValue } from 'jotai'
import { availableDevnetAccountsAtom, devnetAtom, envAtom, isDevnetAliveAtom, selectedDevnetAccountAtom } from '../../atoms/environment'
import useAccount from '../../hooks/useAccount'
import useProvider from '../../hooks/useProvider'
import useRemixClient from '../../hooks/useRemixClient'
import * as D from '../../components/ui_components/Dropdown'
import { BsCheck, BsChevronDown } from 'react-icons/bs'
const DevnetAccountSelector: React.FC = () => {
const { account, setAccount } = useAccount()
const { provider, setProvider } = useProvider()
const { remixClient } = useRemixClient()
const env = useAtomValue(envAtom)
const devnet = useAtomValue(devnetAtom)
const [isDevnetAlive, setIsDevnetAlive] = useAtom(isDevnetAliveAtom)
const [selectedDevnetAccount, setSelectedDevnetAccount] = useAtom(selectedDevnetAccountAtom)
const [availableDevnetAccounts, setAvailableDevnetAccounts] = useAtom(availableDevnetAccountsAtom)
const checkDevnetUrl = async (): Promise<void> => {
try {
const response = await fetch(`${devnet.url}/is_alive`, {
method: 'GET',
redirect: 'follow',
headers: {
'Content-Type': 'application/json'
}
})
const status = await response.text()
if (status !== 'Alive!!!' || response.status !== 200) {
setIsDevnetAlive(false)
} else {
setIsDevnetAlive(true)
}
} catch (error) {
setIsDevnetAlive(false)
}
}
// devnet live status
useEffect(() => {
const interval = setInterval(() => {
checkDevnetUrl().catch(e => {
console.error(e)
})
}, 3000)
return () => {
clearInterval(interval)
}
}, [devnet])
const notifyDevnetStatus = async (): Promise<void> => {
try {
await remixClient.call(
'notification' as any,
'toast',
`❗️ Server ${devnet.name} - ${devnet.url} is not healthy or not reachable at the moment`
)
} catch (e) {
console.error(e)
}
}
useEffect(() => {
if (!isDevnetAlive) {
notifyDevnetStatus().catch((e) => {
console.error(e)
})
}
}, [isDevnetAlive])
const refreshDevnetAccounts = async (): Promise<void> => {
setAccountRefreshing(true)
try {
const accounts = await getAccounts(devnet.url)
if (
JSON.stringify(accounts) !== JSON.stringify(availableDevnetAccounts)
) {
setAvailableDevnetAccounts(accounts)
}
} catch (e) {
await remixClient.terminal.log({
type: 'error',
value: `Failed to get accounts information from ${devnet.url}`
})
}
setAccountRefreshing(false)
}
useEffect(() => {
setTimeout(() => {
if (!isDevnetAlive) {
return
}
refreshDevnetAccounts().catch(e => {
console.error(e)
})
}, 1)
}, [devnet, isDevnetAlive])
useEffect(() => {
if (
!(
selectedDevnetAccount !== null &&
availableDevnetAccounts.includes(selectedDevnetAccount)
) &&
availableDevnetAccounts.length > 0
) {
setSelectedDevnetAccount(availableDevnetAccounts[0])
}
}, [availableDevnetAccounts, devnet])
useEffect(() => {
const newProvider = new Provider({
sequencer: {
baseUrl: devnet.url
}
})
if (selectedDevnetAccount != null) {
setAccount(
new Account(
newProvider,
selectedDevnetAccount.address,
selectedDevnetAccount.private_key
)
)
}
setProvider(newProvider)
}, [devnet, selectedDevnetAccount])
function handleAccountChange (value: number): void {
if (value === -1) {
return
}
setAccountIdx(value)
setSelectedDevnetAccount(availableDevnetAccounts[value])
const newProvider = new Provider({

import React, { useState } from 'react'
import { devnets } from '../../utils/network'
import './styles.css'
import { devnetAtom, envAtom } from '../../atoms/environment'
import { useAtom, useSetAtom } from 'jotai'
import useStarknetWindow from '../../hooks/starknetWindow'
import useProvider from '../../hooks/useProvider'
import * as D from '../../components/ui_components/Dropdown'
import { BsChevronDown } from 'react-icons/bs'
const EnvironmentSelector: React.FC = () => {
const { setProvider } = useProvider()
const [env, setEnv] = useAtom(envAtom)
const setDevnet = useSetAtom(devnetAtom)
const { starknetWindowObject, connectWalletHandler } = useStarknetWindow()
const handleEnvironmentChange = (ipValue: string): void => {
const value = parseInt(ipValue)
if (!isNaN(value) && value > 0) {
setDevnet(devnets[value - 1])
if (value === 2) setEnv('remoteDevnet')
else setEnv('localDevnet')
setProvider(null)
return
}
setEnv('wallet')
if (starknetWindowObject === null) {
connectWalletHandler()
.catch(
e => {
console.error(e)
})
}
}
const getActiveEnv = (lEnv: typeof env): string => {
switch (lEnv) {
case 'manual': return 'Manual'
case 'localDevnet': return 'Local Devnet'
case 'remoteDevnet': return 'Remote Devnet'
case 'wallet': return 'Wallet'
}
}
const [dropdownControl, setDropdownControl] = useState(false)
return (
<div className="environment-selector-wrapper">
<D.Root open={dropdownControl} onOpenChange={(e) => { setDropdownControl(e) }}>
<D.Trigger>
<div className="flex flex-row justify-content-space-between align-items-center p-2 br-1 devnet-trigger-wrapper">
<label className='text-light text-sm m-0'>{getActiveEnv(env)}</label>
<BsChevronDown style={{
transform: dropdownControl ? 'rotate(180deg)' : 'none',
transition: 'all 0.3s ease'
}} />
</div>
</D.Trigger>
<D.Portal>
<D.Content>
<D.Item
key={'0wallet'}
onClick={() => {
handleEnvironmentChange('0')
}}
>
Wallet
</D.Item>
{devnets.map((devnet, i) => {
return (
<D.Item


Step 2: ⌨️ Coding

  • Modify plugin/src/components/DevnetAccountSelector/index.tsx7296dc8
Modify plugin/src/components/DevnetAccountSelector/index.tsx with contents:
• Replace the `is_alive` endpoint with the `version` endpoint in the `checkDevnetUrl` function. This involves changing the URL in the fetch request from `${devnet.url}/is_alive` to `${devnet.url}/version`.
• Update the condition in the if statement that checks the status of the response. Instead of checking if `status !== 'Alive!!!'`, it should check if the response does not contain a version number. This can be done by parsing the response as JSON and checking if the `version` property exists.
  • Check plugin/src/components/DevnetAccountSelector/index.tsxd92ee01
Sandbox logs for https://github.com/NethermindEth/starknet-remix-plugin/commit/d92ee01c60d708844bc7a7aae5e62e972b9c20ee
trunk fmt plugin/src/components/DevnetAccountSelector/index.tsx || exit 0 1/2 ✓
 ✔ Formatted plugin/src/components/DevnetAccountSelector/index.tsx
Re-checking autofixed files...


Checked 1 file
✔ No issues
Run trunk upgrade to upgrade 2 linters
trunk check --fix --print-failures plugin/src/components/DevnetAccountSelector/index.tsx 2/2 ✓
Checked 1 file
✔ No issues
  • Modify plugin/src/components/EnvironmentSelector/index.tsx ! No changes made
Modify plugin/src/components/EnvironmentSelector/index.tsx with contents:
• Replace the `is_alive` endpoint with the `version` endpoint in the `handleEnvironmentChange` function. This involves changing the URL in the fetch request from `${devnet.url}/is_alive` to `${devnet.url}/version`.
• Update the condition in the if statement that checks the status of the response. Instead of checking if `status !== 'Alive!!!'`, it should check if the response does not contain a version number. This can be done by parsing the response as JSON and checking if the `version` property exists.
  • Check plugin/src/components/EnvironmentSelector/index.tsx
Run plugin/src/components/EnvironmentSelector/index.tsx through the sandbox.

Step 3: 🔁 Code Review

Here are my self-reviews of my changes at sweep/local-katana-integration.

Here is the 1st review

The changes made in the file "plugin/src/components/DevnetAccountSelector/index.tsx" are correct and well implemented. Good job on that!

However, the changes for the file "plugin/src/components/EnvironmentSelector/index.tsx" were not provided in the diff. Please ensure that similar changes are made in this file as well, specifically:

  • Replace the is_alive endpoint with the version endpoint in the handleEnvironmentChange function. This involves changing the URL in the fetch request from ${devnet.url}/is_alive to ${devnet.url}/version.
  • Update the condition in the if statement that checks the status of the response. Instead of checking if status !== 'Alive!!!', it should check if the response does not contain a version number. This can be done by parsing the response as JSON and checking if the version property exists.

Once these changes are made and provided, we can proceed with the review.

I finished incorporating these changes.


🎉 Latest improvements to Sweep:

  • Sweep can now passively improve your repository! Check out Rules to learn more.

💡 To recreate the pull request edit the issue title or description. To tweak the pull request, leave a comment on the pull request.
Join Our Discord

@JorikSchellekens
Copy link
Contributor

@rjnrohit Does the pr this bot created look correct?

@stranger80 stranger80 modified the milestones: v0.2.6, v0.2.7 Nov 14, 2023
@stranger80 stranger80 moved this from To Do to In Progress in [Nubia] Starknet Remix Plugin Nov 20, 2023
@stranger80
Copy link
Contributor Author

The Katana project is managed from here: https://github.com/dojoengine/dojo/blob/main/crates/katana/README.md

@stranger80 stranger80 moved this from In Progress to Done in [Nubia] Starknet Remix Plugin Nov 23, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
Status: Done
Development

Successfully merging a pull request may close this issue.

3 participants