Code Monkey home page Code Monkey logo

starknet.js's People

Contributors

0xs34n avatar 1swaraj avatar arcticae avatar avimak avatar badurinantun avatar cfal avatar corbt avatar delaaxe avatar dhruvkelawala avatar diegodelrieu avatar edisontim avatar haroune-mohammedi avatar ikrcatov avatar irisdv avatar ivpavici avatar janek26 avatar kongtaoxing avatar lazarmitic avatar lukasaric avatar milgard91 avatar notv4l avatar nuelose avatar penovicp avatar philipper26 avatar semantic-release-bot avatar tabaktoni avatar ugur-eren avatar web-flow avatar yoga-braavos avatar yohantz 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

starknet.js's Issues

Typo in testnet name

The Görli testnet is spelled goerli not georli.

I can send a PR to fix it, just nott sure how you want to handle it since this might be a breaking change.

Deploying contracts returns error

data: {
  code: 'StarknetErrorCode.SECURITY_ERROR',
  message: 'Invalid value for field prime:  
    3618502788666131106986593281521497120414687020801267626233049500247285301248. Expected: 
    3.618502788666131e+75.  
    3618502788666131213697322783095070105623107215331596699973092056135872020481.'
}

Getting the following error when deploying the AMM compiled code here

However, it works when you use the starknet deploy command

change `waitForTx` to use `setInterval()` rather than `setTimeout()`

My suggestion:

function waitForTxV2(
  txHash: utils.number.BigNumberish,
  retryInterval: number = 1000,
  func: Function
) {
  console.log("=== WAIT FOR TX V2 STARTED ===");
  const interval = setInterval(async () => {
    const transactionResponse = await getTransactionStatus(txHash);
    console.log("=== TRANSACTION STATUS ===", transactionResponse.tx_status);

    func(transactionResponse.tx_status);

    if (
      transactionResponse.tx_status === "PENDING" || // Success State
      transactionResponse.tx_status === "ACCEPTED_ONCHAIN" || // Success State
      transactionResponse.tx_status === "REJECTED" // Failure State
    ) {
      clearInterval(interval);
    }
  }, retryInterval);

  // clear interval after 90 seconds
  setTimeout(() => {
    console.log("=== 90 seconds are up... clearing interval ===");
    clearInterval(interval);
  }, 90000);
}

Implement verifyMessage() on signer

Signer should get an additional method verifyMessage(typedData: TypedData, signature: Signature): Promise<boolean>, which allows the signer to check if the given signature signs the given message using the signers pub key.
There should also be a verifyMessageHash(typedDataHash: BigNumberish, signature: Signature): Promise<boolean>, which allows the signer to check if the given signature is valid for the account by calling is_valid_signature on the account contract.

`invokeFunction()` on starknet.ts

Something like this:

export function invokeFunction(contractAddress, signature, callData, entrypointSelector) {
  return addTransaction({
    type: 'INVOKE_FUNCTION',
    contract_address: contractAddress,
    signature,
    calldata: callData,
    entry_point_selector: entrypointSelector,
  });
}

Usage with Create React App

I made an example using this library with react, everything is working fine in development, but in production it looks like starknet.js is throwing a type error. You can open this page to see the error more in detail.

To reproduce locally:

  • Clone my example repo
  • Build with yarn run build
  • Serve production build with yarn run serve

Add Utilities for Felt Array Conversion

Hey team,

I was wondering if the following utilities would be a good place for this repo:

/**
 * Converts a string into an array of numerical characters in utf-8 encoding
 * @param {string} str - The string to convert
 * @returns {bigint[]} - The string converted as an array of numerical characters
 */
 export function stringToFeltArray(str: string): bigint[] {
  const strArr = str.split('');
  return strArr.map(char => BigInt(Buffer.from(char)[0].toString(10)));
}

/**
 * Converts an array of utf-8 numerical characters into a readable string
 * @param {bigint[]} felts - The array of numerical characters
 * @returns {string} - The readable string
 */
export function feltArrayToString(felts: bigint[]): string {
  return felts.reduce((memo, felt) => memo + Buffer.from(felt.toString(16), 'hex').toString(), '');
}

I found these utilities useful for the scenario:
to convert a string -> [felt] so that it can be passed as an argument to a function with parameters: arg_len: felt, arg: felt*:

I can create the PR if that works for everyone!

Introduce abstractions

The API we want to expose with this package has rapidly expanded.
I think it'd be good timing to discuss the exposed methods and objects, to prevent future surprises.

I really like the simplicity introduced by @seanjameshan initially, by exposing the api endpoints as is. But with introducing more complex types like contracts and accounts we need to find a middle ground.
I'd like to introduce a simple yet extensible api for developers to use.

Simple and extensible api:
Lets assume defaults, but also expose the building blocks used onto of those defaults.
ie: Starknet Goerli Alphanet is the only one accessible right now. This won't stay this way, with main net approaching quick. Lets always expose a simple (opinionated) export to get the developer started right away, aswell as a class contructor where you can pass your own arguments.

// Beginner
import { api } from "starknet.js"

// assuming goerli alpha and subject to change
const { Starknet, GpsStatementVerifier } = await api.getContractAddresses()

// Advanced
import { Api } from "starknet.js"

const localApi = new Api({ endpoint: "http://localhost:3002" })
const { Starknet, GpsStatementVerifier } = await localApi.getContractAddresses()

Classes:
On top of that I think it makes sense to introduce some Classes, to leave the choice of if a develop wants to use OOP or a more functional style. ie:

// functional
import { wallet } from "starknet.js"

const { getKeyPair, sign, getStarkKey } = wallet

const kp = getKeyPair("Private Key")
const address = getStarkKey(kp)
const sig = sign(kp, "hello")

// object oriented
import { Wallet } from "starknet.js"

const wallet = Wallet("Private Key")

const address = wallet.getStarkKey()
const sig = wallet.sign(kp, "hello")

Reimplement json-bigint

One of our dependencies https://github.com/sidorares/json-bigint has seen it's best days.
It uses bignumber.js as a dependency, while this library uses bn.js. It also supports native BigInt which breaks support for older browsers and browserslists (see #37 ).

Lets reimplement this package in TS.
As a starting point we can use the test suites provided at the original repo and write an implementation against it.

We can ether make this repo a monorepo or start a new repo.

Acceptance Criteria

  • no use of native BigInt
  • use BN.js as only dependency
  • passes all test from the original repo

move `getSelectorFromName()` to `starknet`from `utils/starknet`

getSelectorFromName() is used very frequently with dapps. Every time I make a smart contract call I would have to import like the following:

const {
  starknet: { getSelectorFromName },
} = utils;

Would prefer this import instead:

import { getSelectorFromName, addTransaction } from "starknet";

I am not using Provider / Signer at the moment so this could possibly be outdated

The automated release is failing 🚨

🚨 The automated release from the main branch failed. 🚨

I recommend you give this issue a high priority, so other packages depending on you can benefit from your bug fixes and new features again.

You can find below the list of errors reported by semantic-release. Each one of them has to be resolved in order to automatically publish your package. I’m sure you can fix this 💪.

Errors are usually caused by a misconfiguration or an authentication problem. With each error reported below you will find explanation and guidance to help you to resolve it.

Once all the errors are resolved, semantic-release will release your package the next time you push a commit to the main branch. You can also manually restart the failed CI job that runs semantic-release.

If you are not sure how to resolve this, here are some links that can help you:

If those don’t help, or if this issue is reporting something you think isn’t right, you can always ask the humans behind semantic-release.


The release 1.5.3 on branch main cannot be published as it is out of range.

Based on the releases published on other branches, only versions within the range >=1.5.2 <1.5.3 can be published from branch main.

The following commits are responsible for the invalid release:

  • Merge pull request #44 from seanjameshan/develop (3022ae6)
  • Merge pull request #43 from seanjameshan/fix/export-needed-types (3901b84)
  • fix: more types (e816a3b)
  • Merge pull request #42 from seanjameshan/develop (fe35d29)
  • Merge pull request #35 from seanjameshan/develop (a302ac9)
  • Merge pull request #24 from seanjameshan/develop (07135f5)
  • Merge pull request #20 from seanjameshan/develop (ce4bdca)
  • Merge pull request #15 from seanjameshan/develop (8074e3a)

Those commits should be moved to a valid branch with git merge or git cherry-pick and removed from branch main with git revert or git reset.

A valid branch could be develop.

See the workflow configuration documentation for more details.


Good luck with your project ✨

Your semantic-release bot 📦🚀

use develop as default branch

Hey Sean!

can we maybe change the default branch to develop ?

It'd improve DX as PRs would be created against develop and also improve release automation, as issues do not get closed if a PR fixing it isn't targeting the default branch.

As the documentation lives on a webpage by now, it would still be valid for the main rpm package :-)

Support Type transformations for Contracts

Calling contract’s function transforms python types to Cairo types based on ABI:
int -> felt
tuple -> tuple
iterable -> array
dict -> struct
Function result is transformed from Cairo types to Python types.

replace axios by fetch

Should we replace axios by some isomorphic fetch implementation to have less dependencies in case the used environment already has fetch available? :) It would not introduce any extra complexity as we can't use most of axis advantages anyways when handling biting json data.

Would love to hear your thoughts @seanjameshan

I'd suggest https://github.com/lquixada/cross-fetch

Better way to parse Uint256 result of `Args` to BN

Currently,

export type Args = { [inputName: string]: string | string[] | { type: 'struct'; [k: string]: BigNumberish }; };

The type of Args does not include a type Uint256 which is a normal JS object with low and high properties. How should it be parsed on frontend?

For example,

Example ABI:
{ "inputs": [ { "name": "account", "type": "felt" } ], "name": "balanceOf", "outputs": [ { "name": "balance", "type": "Uint256" } ], "stateMutability": "view", "type": "function" }

The output of balanceOf call will be of type Args

const result = contract.call(balanceOf, { account: address }) // returns result = { balance: Object }

Here, the type of balance is neither string, string[] or struct.

Type string | string[] | { type: 'struct'; [k: string]: BigNumberish is also not compatible with arguement of uint256ToBN().

Currently, I am passing result as any in uint256ToBN which is not a good way to do this.

Add `tx_failure_reason` to the Error from `waitForTx`

Currently, we can't display to users any details about failure transactions. We only have a status code. But get_transaction_status also sends us the tx_failure_reason, and I think we should be able to read this reason

invoke function to contract

Create a nice interface for developers to sent invokeFunction transactions through the addTransaction method using the ABI

  • pack call data as described by ABI (ref)
  • sent tx using addTransaction
  • tests

Guides

End-to-end and comprehensive guides on how to use StarkNet.js

Sending Uint256 Fail: AssertionError: normalize_address() cannot be used with the current constants

version 2.5
More context: https://discordapp.com/channels/793094838509764618/927918707613786162/930855057568727141

Sending Uint256 end up with a REJECT transaction
Same values send from starknet cli wor
Screenshot from 2022-01-12 15-57-08
k

Error


/home/filip/.local/lib/python3.8/site-packages/starkware/starknet/common/storage.cairo:22:5: Error at pc=0:91:
    if is_small != 0:
    ^^
Got an exception while executing a hint.
Cairo traceback (most recent call last):
/path/to/my-project/contracts/utils/token/ERC20.cairo:19:6
func constructor{
     ^*********^
/path/to/my-project/contracts/utils/token/ERC20.cairo:29:5
    ERC20_initializer(name, symbol, initial_supply, recipient)
    ^********************************************************^
/path/to/my-project/contracts/utils/token/ERC20_base.cairo:54:5
    ERC20_mint(recipient, initial_supply)
    ^***********************************^
/path/to/my-project/contracts/utils/token/ERC20_base.cairo:135:30
    let (balance: Uint256) = ERC20_balances.read(account=recipient)
                             ^************************************^
autogen/starknet/storage_var/ERC20_balances/impl.cairo:16:30
        let (storage_addr) = addr(account)
                             ^***********^
autogen/starknet/storage_var/ERC20_balances/impl.cairo:10:21
        let (res) = normalize_address(addr=res)
                    ^*************************^

Traceback (most recent call last):
  File "<hint5>", line 5, in <module>
AssertionError: normalize_address() cannot be used with the current constants.

deployContract deploys a faulty contract

I was receiving the error AssertionError: normalize_address() cannot be used with the current constants when calling a contract I deployed with provider.deployContract. After investigating the issue with Tom (starknet) on discord he has suggested that it is possibly something to do with the way starknet JS is handling ints from the compile_contract.json file that is passed in as the first argument to deployContract

This is the code I am using to deploy my contract:

const calldata = compileCalldata({
    name: nameFelt,
    symbol: symbolFelt,
    owner: account,
});

const resp = await provider.deployContract(compiledERC721, calldata);

This is the JSON file:

https://github.com/GeraldHost/fractor/blob/master/packages/fractor-web/src/constants/contracts/erc721.json

And here is a script that shows the error when calling a contract deployed with the starknet CLI that works and then that same contract deployed with starknet.js that doesn't work:

https://github.com/GeraldHost/fractor/blob/master/packages/fractor-contracts/scripts/starknet_js_test.js

Appreciate the time and help

Support array-return values in contract

Contract::ParseResponse does not support array-return types (X_len:felt, X: felt*). Instead the current method returns two variables with the length & the first value.

I am not clear whether Cairo intends to support struct return values, which also would entail changes to this function.

Method inputs (Human Readable Api)

Instance methods like invokeFunction should do more preprocessing and not expect results from helper functions like getSelectorFromName or compileCalldata.

This will allow other actors in the ecosystem to implement their own Provider or Signer, with the ability to show human readable data to the user. This is very important for wallets, but also Hardware wallets like Ledger, so we don't just approve hashes and hex values like we do in Ethereum today.

entry_point_selector

It should always be the human readable string, like "mint" or "transfer". It should not be a pre-computed address like the result of getSelectorFromName or any other hex value.

calldata

This one is a little bit more complicated. Basically there are 2 difference appearances of calldata. In Providers and Signers the calldata normally isn't aware of any ABI or context. In these cases, like addTransaction there should be a 2nd parameter which accepts an ABI. This way signers like Argent X, Ledger or whatever, can show relevant information to the user approving. This parameter should be optional, and wallets can handle it differently if it's not provided (deny signing, display warning etc).

signature

Signatures should not assume that there's just one signing party. Signature is always a flat array of BigNumberish with variable length n.

Starknet.js v3 - human readable interfaces

Discussed in #102

Originally posted by janek26 January 12, 2022
Hey all,
today I'll propose new interfaces for Provider, Signer and especially Contract.

Provider and Signer

A Provider should stay similar to an ethers.js Provider, allowing for interactions with the blockchain without signing. Traditionally these are reading states from the blockchain, but due to how StarkNet is build you can do a little more with it in starknet.js, like sending contract deployment transactions etc.

A Signer extends a Provider and inherits/implements all of its methods. It also introduces some methods which are just possible with a Signer, eg creating/verifying signatures. It's primarily interacting with an account contract on starknet.

Signer

Signer should get an additional method verifyMessage(typedData: TypedData, signature: Signature): Promise<boolean>, which allows the signer to check if the given signature signs the given message using the signers pub key.
There should also be a verifyMessageHash(typedDataHash: BigNumberish, signature: Signature): Promise<boolean>, which allows the signer to check if the given signature is valid for the account by calling is_valid_signature on the account contract.

Method inputs

Instance methods like invokeFunction should do more preprocessing and not expect results from helper functions like getSelectorFromName or compileCalldata.
This will allow other actors in the ecosystem to implement their own Provider or Signer, with the ability to show human readable data to the user. This is very important for wallets, but also Hardware wallets like Ledger, so we don't just approve hashes and hex values like we do in Ethereum today.

entry_point_selector

It should always be the human readable string, like "mint" or "transfer". It should not be a pre-computed address like the result of getSelectorFromName or any other hex value.

calldata

This one is a little bit more complicated. Basically there are 2 difference appearances of calldata. In Providers and Signers the calldata normally isn't aware of any ABI or context. In these cases, like addTransaction there should be a 2nd parameter which accepts an ABI. This way signers like Argent X, Ledger or whatever, can show relevant information to the user approving. This parameter should be optional, and wallets can handle it differently if it's not provided (deny signing, display warning etc).

signature

Signatures should not assume that there's just one signing party. Signature is always a flat array of BigNumberish with variable length n.

Contract

Contracts can do data transforming in JS based on an ABI. They can also call and invoke to starknet through a provided Signer.
We should split between Contract and ContractFactory (which is also able to deploy contracts) like they do with ethers.js

Contracts should be able to transform most common Cairo values, like Uint256, to JS objects like BigNumber. It could also allow the user to pass there own transformers, similar to how JSON.parse does it.

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.