Coder Social home page Coder Social logo

0xspaceshard / starknet-hardhat-plugin Goto Github PK

View Code? Open in Web Editor NEW
199.0 12.0 35.0 3.49 MB

A plugin for integrating Starknet tools into Hardhat projects

Home Page: https://0xspaceshard.github.io/starknet-hardhat-plugin/

License: MIT License

TypeScript 89.49% Shell 4.56% Python 1.36% Cairo 0.91% JavaScript 2.96% CSS 0.71%
hardhat starknet blockchain

starknet-hardhat-plugin's Introduction

Hardhat Plugin

Starknet Hardhat Plugin

npm package

If you've used Hardhat ๐Ÿ‘ทโ€โ™€๏ธ๐Ÿ‘ทโ€โ™‚๏ธ and want to develop for Starknet starknet, this plugin might come in hand. If you've never set up a Hardhat project, check out this guide.

๐ŸŒ Docs

On the following links you can find the documentation of:

โœ๏ธ Contributing

We โค๏ธ and encourage all contributions!

Click here for the development guide.

Special thanks ๐Ÿ™Œ to all the contributors!

starknet-hardhat-plugin's People

Contributors

amanusk avatar augustbleeds avatar badurinantun avatar cfal avatar charlietilt avatar dribeiro-shardlabs avatar fabijanc avatar ivpavici avatar lucaslvy avatar mikiw avatar mrostamii avatar nathan-sl avatar notv4l avatar omahs avatar penovicp avatar qperrot avatar remiroyc avatar shramee avatar solimander avatar taco-paco avatar tsbauer avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

starknet-hardhat-plugin's Issues

Error with account.call

Summary

I am getting an error when trying to call a contract @view method. I get the same issue locally (shardlabs/starknet-devnet:0.2.2-arm) as I do on alpha.

I have attached the test contract and test spec file:

Here is the error I received when running on alpha:

HardhatPluginError: Could not perform call on __execute__:
Got BadRequest while trying to access https://alpha4.starknet.io/feeder_gateway/call_contract?blockNumber=pending. Status code: 500; text: {"code": "StarknetErrorCode.TRANSACTION_FAILED", "message": "Error at pc=0:134:\nSignature (1673925406664288395194014266915634121255994698743581988859762645609544057099, 3267185712093669269158180303132515657399762799212131849029619600604002588995), is invalid, with respect to the public key 2001874741716233317693150946109625889536559338446422799470279717300847451737, and the message hash 513841997411178000137272081953651204656394336317085175571681275522893698968.\nCairo traceback (most recent call last):\nUnknown location (pc=0:921)\nUnknown location (pc=0:865)\nUnknown location (pc=0:477)\nUnknown location (pc=0:394)"}.
Traceback (most recent call last):
  File "/usr/local/lib/python3.7/site-packages/services/external_api/base_client.py", line 120, in _send_request
    raise BadRequest(status_code=response.status, text=text)
services.external_api.base_client.BadRequest: HTTP error ocurred. Status: 500. Text: {"code": "StarknetErrorCode.TRANSACTION_FAILED", "message": "Error at pc=0:134:\nSignature (1673925406664288395194014266915634121255994698743581988859762645609544057099, 3267185712093669269158180303132515657399762799212131849029619600604002588995), is invalid, with respect to the public key 2001874741716233317693150946109625889536559338446422799470279717300847451737, and the message hash 513841997411178000137272081953651204656394336317085175571681275522893698968.\nCairo traceback (most recent call last):\nUnknown location (pc=0:921)\nUnknown location (pc=0:865)\nUnknown location (pc=0:477)\nUnknown location (pc=0:394)"}
Error: BadRequest: HTTP error ocurred. Status: 500. Text: {"code": "StarknetErrorCode.TRANSACTION_FAILED", "message": "Error at pc=0:134:\nSignature (1673925406664288395194014266915634121255994698743581988859762645609544057099, 3267185712093669269158180303132515657399762799212131849029619600604002588995), is invalid, with respect to the public key 2001874741716233317693150946109625889536559338446422799470279717300847451737, and the message hash 513841997411178000137272081953651204656394336317085175571681275522893698968.\nCairo traceback (most recent call last):\nUnknown location (pc=0:921)\nUnknown location (pc=0:865)\nUnknown location (pc=0:477)\nUnknown location (pc=0:394)"}

      at StarknetContract.<anonymous> (node_modules/@shardlabs/starknet-hardhat-plugin/src/types.ts:520:19)
      at Generator.next (<anonymous>)
      at fulfilled (node_modules/@shardlabs/starknet-hardhat-plugin/dist/src/types.js:28:58)
      at processTicksAndRejections (node:internal/process/task_queues:96:5)

How to understand all the dependency files for starknet-verify

Hello team!
I was trying the new verify feature in the the fresh 0.4.3 release. But it seems I am not able to verify it correctly. I think the issue is that I am not including all the files I should.

Is there a way to list all the files that I should include as a dependency? Do you plan to automate the process?

โฏ yarn hardhat starknet-verify \                    
  --starknet-network alpha \
  --address 0x0623f78e25377c359d335b3c3de0e808135a365aed916b9a868108e090bf8a83 \
  --path ./contracts/token/ERC721/ERC721_pokianimals.cairo \
  ./contracts/token/ERC721/ERC721_base.cairo ./contracts/token/ERC721/ERC165_base.cairo ./contracts/token/ERC721/IERC721_Receiver.cairo ./contracts/token/ERC20/IERC20.cairo
yarn run v1.22.17
$ /Users/claudio/Dev/web3/starknet-erc721-homeworks/node_modules/.bin/hardhat starknet-verify --starknet-network alpha --address 0x0623f78e25377c359d335b3c3de0e808135a365aed916b9a868108e090bf8a83 --path ./contracts/token/ERC721/ERC721_pokianimals.cairo ./contracts/token/ERC721/ERC721_base.cairo ./contracts/token/ERC721/ERC165_base.cairo ./contracts/token/ERC721/IERC721_Receiver.cairo ./contracts/token/ERC20/IERC20.cairo
Starknet plugin using the active environment.
Error in plugin Starknet: Contract at address 0x0623f78e25377c359d335b3c3de0e808135a365aed916b9a868108e090bf8a83 does not match the provided code

This is the header section of ERC721_pokianimals.cairo:

%lang starknet
%builtins pedersen range_check ecdsa

from starkware.cairo.common.cairo_builtins import HashBuiltin, SignatureBuiltin
from starkware.cairo.common.uint256 import (
    Uint256, uint256_add, uint256_sub
)
from starkware.cairo.common.math import (
    assert_not_zero, assert_not_equal, assert_lt
)
from starkware.starknet.common.syscalls import get_caller_address

from contracts.token.ERC721.ERC721_base import (
    ERC721_name, ERC721_symbol, ERC721_balanceOf, ERC721_ownerOf, ERC721_getApproved,
    ERC721_isApprovedForAll, ERC721_mint, ERC721_burn, ERC721_initializer, ERC721_approve,
    ERC721_setApprovalForAll, ERC721_transferFrom, ERC721_safeTransferFrom, _exists
)
from contracts.token.ERC20.IERC20 import IERC20
...

So I included ERC721_base and IERC20.

Then going inside ERC721_base, the header is:

%lang starknet

from starkware.cairo.common.cairo_builtins import HashBuiltin, SignatureBuiltin
from starkware.cairo.common.math import assert_not_zero, assert_not_equal
from starkware.cairo.common.alloc import alloc
from starkware.starknet.common.syscalls import get_caller_address
from starkware.cairo.common.uint256 import (
    Uint256, uint256_add, uint256_sub
)

from contracts.token.ERC721.ERC165_base import (
    ERC165_register_interface
)

from contracts.token.ERC721.IERC721_Receiver import IERC721_Receiver
...

So I included ERC165_base and IERC721_Receiver.

Am I doing it wrong?

CI/CD workflow fails because of invalid nonce

E.g. this CircleCI job.

When testing on alpha-goerli, we are using a funded account (whose private key and address are stored in the CircleCI Shardlabs context).

I believe the nonce error results from the parallel execution of tests while using the same account (simultaneous transactions altering the nonce value). Either that, or someone somewhere is using the account at the same time, and it ain't me.

Possible solutions:

  • allow only one test at a time to access the account
  • have one account per each parallel job
  • have alpha-goerli tests only in one job

Any suggestions?

Allow loading contracts with only ABI

starknet.getContractFactory could be modified to not require both contract.json and contract_abi.json artifacts. This way using contractFactory.getContractAt would only be supported, contractFactory.deploy wouldn't.

Export all flag

Hey! Thanks for creating this package. It has really helped me a lot!

Quick question:
Is there an --export-all ../react-app/src/contracts/hardhat_contracts.json" flag like the ethereum hardhat package has?
Or is there a way to output a json file with an array of all deployed contracts with their respective addresses and ABI's?

Cannot deploy account

Hello team.

I am trying to simply deploy a new account wallet. But I get a dependency issue error:

> yarn hardhat starknet-deploy-account --starknet-network devnet --wallet Deployer
yarn run v1.22.17
$ /Users/claudio/Dev/web3/starknet-erc721-homeworks/node_modules/.bin/hardhat starknet-deploy-account --starknet-network devnet --wallet Deployer
Starknet plugin using the active environment.
Traceback (most recent call last):
  File "<string>", line 1, in <module>
ImportError: No module named asyncio

        Failed

Error in plugin Starknet: Could not deploy account contract:
Traceback (most recent call last):
  File "<string>", line 1, in <module>
ImportError: No module named asyncio


For more info run Hardhat with --show-stack-traces
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

This is a working installation (I can compile and deploy contracts). And Deployer is a correct wallet defined in the hardhat.config.ts.

Add hardhat task that returns currently installed plugin version

Something that would be used like this:

npx hardhat starknet-plugin-version

and return

0.6.1

or whichever is the current version.

This would be useful when debugging with users (so that they don't have to interpret their package.json, package-lock.json or yarn.lock files when asked about the plugin version they are using).

I cannot connect to Devnet on macOS

Hello team!
I cannot connect to devnet, I followed instructions on other tickets but nothing.

Here some details about my setup:

  • macOS 12.2.1 Monterey
  • MacBook Pro M1 Max (not intel)
  • hardhat 2.8.4
  • plugin 0.4.0

Here my hardhat.config.ts:

const config: HardhatUserConfig = {
  starknet: {
    venv: "active",
    network: "devnet",
  },
  networks: {
    devnet: {
      url: "http://localhost:5000/"
    }
  },
};

When I run yarn hardhat test:

yarn run v1.22.17
$ /Users/claudio/Dev/web3/starknet-hardhat-example-alt/node_modules/.bin/hardhat test
Starknet plugin using the active environment.


  Starknet
Started deployment
    1) should work for a fresh deployment


  0 passing (746ms)
  1 failing

  1) Starknet
       should work for a fresh deployment:
     HardhatPluginError: Could not deploy contract. Check the network url in config. Is it responsive?
      at StarknetContractFactory.<anonymous> (node_modules/@shardlabs/starknet-hardhat-plugin/src/types.ts:259:19)
      at Generator.next (<anonymous>)
      at fulfilled (node_modules/@shardlabs/starknet-hardhat-plugin/dist/types.js:24:58)



An unexpected error occurred:

Error: error:0308010C:digital envelope routines::unsupported
    at new Hash (node:internal/crypto/hash:67:19)
    at Object.createHash (node:crypto:130:10)
    at hash160 (/Users/claudio/Dev/web3/starknet-hardhat-example-alt/node_modules/ethereum-cryptography/vendor/hdkey-without-crypto.js:249:21)
    at HDKey.set (/Users/claudio/Dev/web3/starknet-hardhat-example-alt/node_modules/ethereum-cryptography/vendor/hdkey-without-crypto.js:50:24)
    at Function.HDKey.fromMasterSeed (/Users/claudio/Dev/web3/starknet-hardhat-example-alt/node_modules/ethereum-cryptography/vendor/hdkey-without-crypto.js:194:20)
    at deriveKeyFromMnemonicAndPath (/Users/claudio/Dev/web3/starknet-hardhat-example-alt/node_modules/hardhat/src/internal/util/keys-derivation.ts:21:27)
    at derivePrivateKeys (/Users/claudio/Dev/web3/starknet-hardhat-example-alt/node_modules/hardhat/src/internal/core/providers/util.ts:29:52)
    at normalizeHardhatNetworkAccountsConfig (/Users/claudio/Dev/web3/starknet-hardhat-example-alt/node_modules/hardhat/src/internal/core/providers/util.ts:56:10)
    at createProvider (/Users/claudio/Dev/web3/starknet-hardhat-example-alt/node_modules/hardhat/src/internal/core/providers/construction.ts:78:59)
    at /Users/claudio/Dev/web3/starknet-hardhat-example-alt/node_modules/hardhat/src/internal/core/runtime-environment.ts:80:28 {
  opensslErrorStack: [ 'error:03000086:digital envelope routines::initialization error' ],
  library: 'digital envelope routines',
  reason: 'unsupported',
  code: 'ERR_OSSL_EVP_UNSUPPORTED'
}
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

Any idea why?

OpenZeppeling 0.2.0 account contract have an issue with signature verification.

I have tried running the oz-account-test.ts test of starknet-plugin-exaple and ran into the following issue:


  2) OpenZeppelin account
       should handle multiple invokes through an account:
     Error: Transaction rejected. Error message:

Error at pc=0:133:
Got an exception while executing a hint.
Cairo traceback (most recent call last):
Unknown location (pc=0:746)
Unknown location (pc=0:682)
Error message: Account: invalid signature
Unknown location (pc=0:347)
Unknown location (pc=0:321)

Traceback (most recent call last):
  File "<hint14>", line 1, in <module>
  File "/app/src/starkware/starknet/services/batcher/starknet_batcher_venv-site/starkware/cairo/lang/builtins/signature/signature_builtin_runner.py", line 94, in add_signature
    ), f"Signature hint must point to the signature builtin segment, not {addr}."
AssertionError: Signature hint must point to the signature builtin segment, not 14:0.

The cause is probably this issue #378 of OpenZeppelin with contracts of version 0.2.0 on Goerli testnet.

Refactor flattenStringMap approach

Should just count number of nested elements instead of creating a flattened structure and just using its length. Also, splicing should be replaced with an index-tracking approach to have linear instead of quadratic time complexity.

Issue when trying to use Python virtual environment

Hello,

When trying to use the pluging with Python virtual env, I have an issue: it seems that the plugin still tries to use dockerized setting:
when executing starknet-compile, the compilation fails:

An unexpected error occurred:

DockerNotInstalledError
    at Function.create (/Users/jerome.caporossi/Documents/starknet-hardhat/node_modules/@nomiclabs/hardhat-docker/src/hardhat-docker.ts:23:13) {
  parent: undefined
}

With --verbose flag:

npx hardhat --verbose starknet-compile
  hardhat:core:config Loading Hardhat config from /Users/jerome.caporossi/Documents/starknet-hardhat/hardhat.config.ts +0ms
  hardhat:core:global-dir Looking up Client Id at /Users/jerome.caporossi/Library/Application Support/hardhat-nodejs/analytics.json +0ms
  hardhat:core:global-dir Client Id found: 007f1aec-7b74-41e6-89b1-90b344705eca +1ms
  hardhat:core:analytics Sending hit for /task/custom +0ms
  hardhat:core:analytics Hit payload: {"v":"1","t":"pageview","tid":"UA-117668706-3","cid":"007f1aec-7b74-41e6-89b1-90b344705eca","dp":"/task/custom","dh":"cli.hardhat.org","ua":"Node/v17.3.1 (Macintosh; Intel Mac OS X 10_13_6)","cs":"Developer","cm":"User Type","cd1":"hardhat-project","cd2":"Developer","cd3":"Hardhat 2.8.4"} +1ms
  hardhat:core:hre Creating HardhatRuntimeEnvironment +0ms
Starknet plugin using dockerized environment (shardlabs/cairo-cli:0.7.0)
  hardhat:core:hre Running task starknet-compile +0ms
Compiling /Users/jerome.caporossi/Documents/starknet-hardhat/contracts/user_auth.cairo
An unexpected error occurred:

DockerNotInstalledError
    at Function.create (/Users/jerome.caporossi/Documents/starknet-hardhat/node_modules/@nomiclabs/hardhat-docker/src/hardhat-docker.ts:23:13) {
  parent: undefined
}

For information, here is the content of hardhat.config.ts:

import { HardhatUserConfig } from "hardhat/types";
import "@shardlabs/starknet-hardhat-plugin";

//const config: HardhatUserConfig = {
module.exports = {
  starknet: {
    venv: "active",
    network: "devnet",
    wallets: {
      OpenZeppelin: {
        accountName: "OpenZeppelin",
        modulePath: "starkware.starknet.wallets.open_zeppelin.OpenZeppelinAccount",
        accountPath: "~/.starknet_accounts",
      }
    }
   },
  networks: {
    devnet: {
      url: "http://localhost:5001"
    }
  }
};

//export default config;

Another issue is when using config: HardhatUserConfig, the TS compiler raised an error saying that starknet field cannot be used in HardhatUserConfig.

Thanks for your support,
KR,
Jerome

Implicitly calculate maxFee

Currently users have to manually run account.estimateFee before doing account.invoke and explicitly set maxFee as an option of the invoke. Ideally this would be done implicitly, by internally calling fee estimation, and multiplying it with a factor (see which factor others use).

This would be a breaking change since currently the maxFee is implicitly 0 by default.

Introduce --starknet-network CLI param to hardhat run

Looks like recent versions of hardhat support overriding the hardhat run command with optional CLI parameters. This should enable introducing the --starknet-network parameter.

Existing hardhat-run test should be updated to use this CLI parameter instead of reading the network from hardhat.config.ts.

The docs on hardhat run should also be updated to probably looks the same as for hardhat test.

Argent Account not working in js

deploying an Argent account and invoking a function works well
but when reading an existing account and invoking a function in a contract there this issue :

var msgSignature = keyPair.sign(fixMessage(msgHash));
^
TypeError: Cannot read properties of null (reading 'sign')

using the private key exported from argent google extension

Screen Shot 2022-06-06 at 7 02 37 PM

Module '"hardhat"' has no exported member 'starknet'

When including import { starknet } from "hardhat" at the top of my index.tsx file I get the error:

Module '"hardhat"' has no exported member 'starknet'

The module is not importing correctly as I get a bunch of messages saying the modules cannot be resolved. The code runs fine with Node.js just not with React for some reason. Anyone know why?

Here are my hardhat.config.ts settings:

const { HardhatUserConfig } = require("hardhat/types")
require("@shardlabs/starknet-hardhat-plugin")
require("@nomiclabs/hardhat-ethers")

/**
 * @type import('hardhat/config').HardhatUserConfig
 */
module.exports = {
    solidity: "0.8.9",
    starknet: {
        venv: "cairo_venv",
        network: "devnet",
        wallets: {
            OpenZeppelin: {
                accountName: "OpenZeppelin",
                modulePath: "starkware.starknet.wallets.open_zeppelin.OpenZeppelinAccount",
                accountPath: "~/.starknet_accounts",
            },
        },
    },
    networks: {
        devnet: {
            url: "http://127.0.0.1:5050",
        },
    },
}

Create a starknet.js wrapper

Similar to how there are venv wrapper and docker wrapper, there should be a starknet.js wrapper and we should be moving toward relying on starknet.js instead of Starknet CLI

Remove double logging

Somewhere we are probably doing log and throw, so errors get printed twice. If this is the case, only throw, don't also log. If this is not the case and we cannot do anything about it, report here.

DockerNotInstalledError when using local devnet

I have setup a local devnet using starknet-devnet in a local venv, and am trying to get starknet-hardhat-plugin to work with it.

When running npx hardhat starknet-compile (or other commands) I get the following error:

An unexpected error occurred:

DockerNotInstalledError: 
    at Function.create (<dir>/node_modules/@nomiclabs/hardhat-docker/src/hardhat-docker.ts:23:13)
    at processTicksAndRejections (node:internal/process/task_queues:96:5) {
  parent: undefined
}

Here are my hardhat.config.js settings:

require("@shardlabs/starknet-hardhat-plugin")

module.exports = {
    solidity: "0.8.9",
    starknet: {
        network: "myNetwork",
    },
    networks: {
        myNetwork: {
            url: "http://127.0.0.1:5050",
        },
    },
}

Does anyone have an idea what is causing this error? From what I understand if running a local devnet, Docker should not be needed at all.

Example tests when using OpenZeppelin Proxy contracts

I have created my VNCollection smart contract, then I refactored to use OpenZeppelin Proxy upgrade contract.
Now the setup of my tests is not intuitive any more. It would be useful to have some documentation showing how to do it.

Since, I ended figuring it out for my self, here is my setup that can be shared as an example:

const collectionContractFactory = async () => getContractFactory('VNCollection')
const proxyContractFactory = async () => getContractFactory('Proxy')

describe('VNCollection', async () => {
  let collectionClassHash: string
  let collectionContract: StarknetContract
  let proxyClassHash: string
  let proxyContract: StarknetContract

  before(async () => {
    const collectionFactory = await collectionContractFactory()
    collectionClassHash = await collectionFactory.declare()
    const proxyFactory = await proxyContractFactory()
    proxyClassHash = await proxyFactory.declare()
  })

  beforeEach(async () => {
    const collectionFactory = await collectionContractFactory()
    collectionContract = await collectionFactory.deploy()

    const proxyFactory = await proxyContractFactory()
    proxyContract = await proxyFactory.deploy({ implementation_hash: collectionContract.address })

    await collectionContract.invoke('initializer', {
      name: shortStringToBigInt('Items'),
      symbol: shortStringToBigInt('ITEMS'),
      owner: 1n,
      proxy_admin: proxyContract.address,
    })
  })

  describe('mint', () => {
    it('mints correctly a new channel', async () => {
      // Given
      await collectionContract.invoke('mint', { to: EXAMPLE_ACCOUNT_ADDRESS, tokenURI: EXAMPLE_TOKEN_URI_FELT_ARRAY, parentTokenId: PARENT_ALPHA_TOKEN_ID })
      // When
      const { totalSupply } = await collectionContract.call('totalSupply')
      const { owner } = await collectionContract.call('ownerOf', { tokenId: ZERO })
      const { tokenURI } = await collectionContract.call('tokenURI', { tokenId: ZERO })
      const { parentTokenId } = await collectionContract.call('parentTokenId', { tokenId: ZERO })
      // Then
      expect(totalSupply).to.be.deep.equal(ONE)
      expect(owner).to.be.deep.equal(EXAMPLE_ACCOUNT_ADDRESS)
      expect(tokenURI).to.be.deep.equal(EXAMPLE_TOKEN_URI_FELT_ARRAY)
      expect(feltArrayToString(tokenURI)).to.be.deep.equal(EXAMPLE_TOKEN_URI)
      expect(parentTokenId).to.be.deep.equal(PARENT_ALPHA_TOKEN_ID)
    }).timeout(TIMEOUT)
  })
})

`starknet-deploy` should support `salt` parameter

Python CLI deploy command supports salt parameter:

(cairo_venv) maciejka@X1$ starknet deploy
usage: starknet [-h] [--salt SALT] [--inputs [INPUTS [INPUTS ...]]] --contract
                CONTRACT [--token TOKEN]
starknet: error: the following arguments are required: --contract

hardhat plug in does not seem to do it: https://github.com/Shard-Labs/starknet-hardhat-plugin/blob/1bd7c2a34198155e95137849fcf36536c296d4e6/src/starknet-wrappers.ts#L17

Deploy method of StarknetContractFactory (https://github.com/Shard-Labs/starknet-hardhat-plugin/blob/1bd7c2a34198155e95137849fcf36536c296d4e6/src/types.ts#L163) should also support this parameter.

Use existing Python virtual environment?

Could it be possible to configure this plugin to use an existing virtualenv?

This would avoid having to use a heavy container in places where it isn't needed, and also keeps the Python environment accessible for projects that need it (like VSCode plugins)? Starkware is also closely tied to Python and its standard lib and it may prove cumbersome to have it all in a container

Fix return type of `StarknetContract.decodeEvents`

Currently it's Promise<DecodedEvent[]>, but could be DecodedEvent[].

This would be a breaking change since users are currently expecting a different type.

Marking this as enhancement since it's not really a bug in the sense that something's not working as expected.

Not working with Windows

The plugin is not usable with Windows. Under the surface it tries to utilize Docker with const DOCKER_SOCKET_PATH = "/var/run/docker.sock" but that obviously won't work with Windows.

Maybe extend the documentation to mention that Windows is not supported?
WSL (version 2) seems to work, so Windows users could be pointed to use that.

Not able to use a wallet in a function call

Hello again and sorry for writing all the time.

I have previously deployed on devnet a wallet on called Deployer with success:

Contract address: 0x0227353702c3b2f0058f537095ae90b77ecef173ba6f4199dce78b792fc97652
Public key: 0x02f56dc23f579d14801c645c48d28d39352ac47cd7dea3d0a1f8967a61dc2dd7

I deployed a contract with success:

yarn hardhat starknet-deploy ERC721_pokianimals \
  --starknet-network devnet \
  --inputs "1349479273 1347373897 0x02f56dc23f579d14801c645c48d28d39352ac47cd7dea3d0a1f8967a61dc2dd7"

Deploy transaction was sent.
Contract address: 0x01d3e84687fd354e2e6c615c816f319188a7fb2bb91553f2f2f5bd2c1eaea57f
Transaction hash: 0x01b9b825267180fadf3f0b4b164622ad3058a32d1fbed1be4f9ffa139e3e6cc6

When I call a function which does not require wallet, I get a success (123 0):

โฏ yarn hardhat starknet-call \
  --starknet-network devnet \
  --contract ERC721_pokianimals \
  --address 0x01d3e84687fd354e2e6c615c816f319188a7fb2bb91553f2f2f5bd2c1eaea57f \
  --function registration_price  

123 0

        Succeeded
โœจ  Done in 3.10s.

When I try to call the same function which requires a wallet, or for the sake of example even the same one, I get a 500 error:

โฏ yarn hardhat starknet-call \
  --starknet-network devnet \
  --contract ERC721_pokianimals \
  --address 0x01d3e84687fd354e2e6c615c816f319188a7fb2bb91553f2f2f5bd2c1eaea57f \
  --function registration_price \
  --wallet Deployer

Starknet plugin using the active environment.
Got BadRequest
Traceback (most recent call last):
  File "/Users/claudio/cairo_venv/lib/python3.9/site-packages/services/external_api/base_client.py", line 116, in _send_request
    raise BadRequest(status_code=response.status, text=text)
services.external_api.base_client.BadRequest: HTTP error ocurred. Status: 500. Text: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>500 Internal Server Error</title>
<h1>Internal Server Error</h1>
<p>The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.</p>

Error: BadRequest: HTTP error ocurred. Status: 500. Text: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>500 Internal Server Error</title>
<h1>Internal Server Error</h1>
<p>The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.</p>

        Failed

Happens the same when invoking a function.

I think that the issue is with this plugin or starknet-devnet. I have deployed the same contract on alpha-goerli and it works correctly.

Ideas?

Thanks a lot for the support! ๐Ÿ™Œ

Refactor adapt functions

Refactor adaptInputUtil and adaptComplexInput
Same for adaptOutputUtil and adaptComplexOutput

The functions in each of the pairs are very similar, and common logic could be extracted, or one could use the other or something to reduce code duplication

Could not find module error when import module from same repo

Can't compile the contracts using hardhat starknet-compile if I have contract imported from my local repo
Error:

$ hh starknet-compile 
Compiling /home/my-user/path/to/my-project/contracts/MyContract.cairo
/home/my-user/path/to/my-project/contracts/MyContract.cairo:18:6: Could not find module 'contracts.utils.IOwnable'. Searched in the following paths:
/app/contracts/utils/IOwnable.cairo
/usr/local/lib/python3.7/site-packages/contracts/utils/IOwnable.cairo
from contracts.utils.IOwnable import IOwnable
     ^**********************^
        Failed

Allow users to see integrated-devnet stdout

Perhaps in the hardhat config file it could be specified where the user wants this output to go. So an optional property would have to be introduced to the integrated-devnet network config entry.

PS: What about stderr?

Support for Type Alias

Cairo-lang 0.8.0 added Type Aliases but it looks like this plugin does not allow one to actually use them :(

Here's a code example that uses it. Try running it, you should have

HardhatPluginError: Expected address to be a tuple

https://gist.github.com/pscott/5ac165dd35cd0a4ef55cddf77dda4d05

The way I would expect to call a type alias is this way:

// Assuming we have `using Foo = (bar: felt, zoro: felt)`, then in ts I would expect
[{bar: 1}, {zoro: 2}]

But this is just an idea, might not be the best way to call use it :)

Cannot deploy Argent Account

const starknetAccount = await starknet.deployAccount("OpenZeppelin");

This fails with error:

HardhatPluginError: Could not perform invoke on initialize:
Got BadRequest while trying to access https://alpha4.starknet.io/gateway/add_transaction. Status code: 500; text: {"code": "StarknetErrorCode.OUT_OF_RANGE_FEE", "message": "max_fee must be bigger than 0.\n0 >= 0"}.

I believe it's because a fee is required to initialize the Argent Account, but I can't set a fee using await starknet.deployAccount("OpenZeppelin");

This is mentioned here: #117 (comment)
But should be trakced imo

dockerizedVersion: "0.8.1" NOT WORKING

Hi,

I am trying to update to (dockerizedVersion: "0.8.1") but its not working. This is necessary in order for "starknet.getTransaction" to work.

If I stay on 0.8.0 then "getTransaction" doesn't work but if I move to 0.8.1 then calling contracts from accounts doesn't work.

please help!

Thank you

Add timeout to starknet.devnet requests

starknet.devnet.load and starknet.devnet.dump are reported to hang forever due to the lack of timeout.

Since this would require adding the same timeout config to all the requests, devnet-utils.ts could use a refactor to extract the commonalities.

EDIT: devnet-utils.ts is not the only place where the changes should be applied - also in integrated-devnet classes.

[feature] Support `getContractAt`

Hi, is it possible that the plugin supports accessing a deployed Cairo contract similar to how ethers.getContractAt works?

Also, I would get Property 'address' is private and only accessible within class 'StarknetContract' error if write the code in typescript. Wonder if that can be fixed.

Add plugin support for default entrypoints

Some users would like to use the plugin as the proxy for default entrypoints in other contracts. it should be doable if when checking the function in the abi, if it doesn't exist, return __default__ instead of an error

HardhatPluginError: Could not deploy contract. Check the network url in config. Is it responsive?

Hello team.
I updated to the latest 0.5.2 and tried to run the tests.

I have one test passing but one not.
I get this error HardhatPluginError: Could not deploy contract. Check the network url in config. Is it responsive?

My current configuration has been for a while:

  networks: {
    devnet: {
      url: 'http://127.0.0.1:5000/',
    },
  },

This is the output:

yarn hardhat test
yarn run v1.22.18
$ /Users/claudio/Dev/web3/starknet-video-network-poc/hardhat/node_modules/.bin/hardhat test
Starknet plugin using the active environment.
Using network devnet at http://127.0.0.1:5000/
...
  1) VNChannel
       constructor
         should have stored correctly the name and symbol:
     HardhatPluginError: Could not deploy contract. Check the network url in config. Is it responsive?
      at StarknetContractFactory.<anonymous> (node_modules/@shardlabs/starknet-hardhat-plugin/src/types.ts:354:19)
      at Generator.next (<anonymous>)
      at fulfilled (node_modules/@shardlabs/starknet-hardhat-plugin/dist/types.js:24:58)

This is the test failing:

import { expect } from 'chai'
import { starknet } from 'hardhat'
import { StarknetContract, StarknetContractFactory } from 'hardhat/types/runtime'

const { getContractFactory, shortStringToBigInt } = starknet

describe('VNChannel', () => {
  let contract: StarknetContract

  const setupContract = async () => {
    const contractFactory: StarknetContractFactory = await getContractFactory('VNChannel')
    contract = await contractFactory.deploy({
      name: shortStringToBigInt('VNChannel'),
      symbol: shortStringToBigInt('VNChannel'),
      owner: 1n,
    })
  }

  describe('constructor', () => {
    it('should have stored correctly the name and symbol', async () => {
      // Given
      await setupContract()
      // When
      const { name } = await contract.call('name')
      const { symbol } = await contract.call('symbol')
      // Then
      expect(name).to.be.deep.equal(shortStringToBigInt('VNChannel'))
      expect(symbol).to.be.deep.equal(shortStringToBigInt('VNChannel'))
    })
  })
})

Ideas why?

Integrate the Abi-Wan library

First some typechain (type generating tool) needs to be implemented, then we'd see how it can be integrated into plugin.

Invalid signature error for account invoke outside of test env

Summary

When trying to execute an account.invoke outside of the test scripts (Ex: node file.js) I am getting the following invalid signature error. When running the same code inside of a test (npx hardhat test) it works no problem.

Invoke transaction 0x4879f2e799c3f582947033d71f7aaaef212df254b92671cbe783ee0c229411f is REJECTED.
Transaction rejected. Error message:

/home/badurina/projects/cairo-contracts/env/lib/python3.8/site-packages/starkware/cairo/common/signature.cairo:12:5: Error at pc=0:134:
Signature (938829697521780319332146409030067216646503173912283525226354363451947159347, 539935339141187093863590712174480503359402253748499857344377649991277935741), is invalid, with respect to the public key 2749374374727211637233520590806508110892759908750735217418460050042256624526, and the message hash 2048874378711897586683480876739342048796352607406708712693589312404693008671.
Cairo traceback (most recent call last):
src/openzeppelin/account/Account.cairo:94:6: (pc=0:719)
src/openzeppelin/account/Account.cairo:106:36: (pc=0:663)
/home/badurina/projects/cairo-contracts/src/openzeppelin/account/library.cairo:179:26: (pc=0:368)
/home/badurina/projects/cairo-contracts/src/openzeppelin/account/library.cairo:135:9: (pc=0:321)

Environment Details

  • dockerized version of devnet shardlabs/starknet-devnet:0.2.4-arm
  • virtual environment(tried both): venv: 'active' and dockerizedVersion: 'shardlabs/cairo-cli:0.9.0-arm'

Hardhat config

require('@shardlabs/starknet-hardhat-plugin');


module.exports = {
  mocha: {
    bail: true,
    timeout: 600_000
  },
  networks: {
    dockerStark: {
      url: 'http://localhost:9000'
    }
  },
  paths: {
    cairoPaths: [ './lib' ]
  },
  starknet: {
    network: 'dockerStark',
    // venv: 'active',
    dockerizedVersion: 'shardlabs/cairo-cli:0.9.0-arm',
    wallets: {
      MyWallet: {
        accountName: 'OpenZeppelin',
        modulePath: 'starkware.starknet.wallets.open_zeppelin.OpenZeppelinAccount',
        accountPath: '~/.starknet_accounts'
      }
    }
  }
};

Script code

const { starknet } = require('hardhat');
const { stark: { randomAddress } } = require('starknet');

const done = function (error) {
  if (error) console.error(error);
  console.info('done');
  process.exit();
}

const main = async function () {
  const account = await starknet.deployAccount('OpenZeppelin');
  const contractFactory = await starknet.getContractFactory('Proxy');
  const contract = await contractFactory.deploy({ proxy_admin: account.address });
  const class_hash = randomAddress();
  await account.invoke(contract, 'setClassHash', { class_hash });
};


main()
.then(() => done())
.catch(done);

Test Code

const { expect } = require('chai');
const { starknet } = require('hardhat');
const { stark: { randomAddress } } = require('starknet');

describe('Proxy contract', function () {
  this.timeout(600_000);
  let account;
  let accountAddress;
  let contract;

  before(async function () {
    account = await starknet.deployAccount('OpenZeppelin');
    accountAddress = BigInt(account.address);
  });

  beforeEach(async function () {
    console.info('deploying proxy contract...');
    const contractFactory = await starknet.getContractFactory('Proxy');
    contract = await contractFactory.deploy({ proxy_admin: account.address });
  });

  describe('setClassHash', function () {
    it('should set the class hash', async function () {
      const newClassHash = randomAddress();
      await account.invoke(contract, 'setClassHash', { class_hash: newClassHash });

      const { class_hash } = await contract.call('getClassHash');
      expect(BigInt(class_hash).toString()).to.eql(BigInt(newClassHash).toString());
    });

    it('should fail if not called by the admin', async function () {
      const newClassHash = randomAddress();
      try {
        await contract.invoke('setClassHash', { class_hash: newClassHash });
        expect.fail('setClassHash by non admin should fail');
      } catch (error) {
        expect(error.message).to.deep.contain('Proxy: caller is not admin');
      }
    });
  });
});

Issues connecting to local devnet

Hi,

When trying to run mocha tests on a local devnet (i.e. http://localhost:5000), Hardhat cannot connect to the network

yarn run v1.22.10
$ hardhat test
Starknet plugin using the active environment.


  Account
    1) should deploy the Account contract


  0 passing (3s)
  1 failing

  1) Account
       should deploy the Account contract:
     HardhatPluginError: Could not deploy contract. Check the network url in config. Is it responsive?
      at StarknetContractFactory.<anonymous> (node_modules/@shardlabs/starknet-hardhat-plugin/src/types.ts:223:19)
      at Generator.next (<anonymous>)
      at fulfilled (node_modules/@shardlabs/starknet-hardhat-plugin/dist/types.js:24:58)

You can see my hardhat.config.ts file here

import "@shardlabs/starknet-hardhat-plugin";
import { HardhatUserConfig } from "hardhat/config";

const config: HardhatUserConfig = {
  cairo: {
    venv: 'active',
  },
  defaultNetwork: 'devnet',
  networks: {
    devnet: {
      url: 'http://localhost:5000',
    }
  },
  mocha: {
    starknetNetwork: 'devnet',
  }
};

export default config;

I tried using both nile node and starknet-devnet and both fail.

I really like the ability to use Hardhat for Cairo development as well and keep Cairo and Solidity in the same project. Fixing this issue would really help in a major Cairo/StarkNet integration.

Setup:
macOS 12.0.1
python 3.8.9
cairo-lang 0.6.1

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.