apibara / starknet-react

A collection of React providers and hooks for StarkNet
https://starknet-react.com
MIT License
369 stars 147 forks source link

Expected valid bigint: 0 < bigint < curve.n #510

Closed smakosh closed 3 weeks ago

smakosh commented 1 month ago

After upgrading to 3.0.1-beta.0 we started getting the following error: "Expected valid bigint: 0 < bigint < curve.n"

Here's the code responsible for that error:

const onSubmit = async ({ amount }: DepositFormData) => {
    try {
      if (!account || !assetContract) return
      setDisabled(true)

      const preAllowance = await assetContract.allowance(
        account.address,
        CONTROLLER
      )
      const txs = []

      if (
        uint256.uint256ToBN(
          preAllowance || {
            low: 0,
            high: 0,
          }
        ) < BigInt(parseUnits(amount.toString(), DECIMALS))
      ) {
        txs.push({
          contractAddress: asset,
          entrypoint: 'approve',
          calldata: [
            CONTROLLER,
            uint256.bnToUint256(parseUnits(amount.toString(), DECIMALS)).low,
            uint256.bnToUint256(parseUnits(amount.toString(), DECIMALS)).high,
          ],
        })
      }

      txs.push({
        contractAddress: CONTROLLER,
        entrypoint: 'deposit_collateral',
        calldata: [
          asset,
          uint256.bnToUint256(parseUnits(amount.toString(), DECIMALS)).low,
          uint256.bnToUint256(parseUnits(amount.toString(), DECIMALS)).high,
        ],
      })

      const depositTx = await account.execute(txs)

      setTxHash(depositTx.transaction_hash)
      setTxStatus({
        success: 'Collateral deposited',
        loading: 'Transaction pending',
        error: 'Failed to deposit collateral',
      })
    } catch (e: unknown) {
      toast.error((e as { toString: () => string }).toString())
    } finally {
      setDisabled(false)
    }
  }
fracek commented 1 month ago

Can you provide the following information:

Also try to console.log all bigint values and see if anything looks suspcious.

smakosh commented 1 month ago

Can you provide the following information:

  • a stack trace
  • which wallet you are using

Also try to console.log all bigint values and see if anything looks suspcious.

I'm using Argent X.

image

jancris100 commented 1 month ago

Can you assign this to me?

smakosh commented 1 month ago

for more details @fracek

Imports

import {
  useAccount,
  useConnect,
  useContract,
  useProvider,
  useTransactionReceipt,
} from '@starknet-react/core'
import { uint256 } from 'starknet'
import { useStarknetkitConnectModal } from 'starknetkit'
const { connect, connectors } = useConnect()
  const { starknetkitConnectModal } = useStarknetkitConnectModal({
    connectors: connectors as any,
  })

const connectWallet = async () => {
    const { connector } = await starknetkitConnectModal()
    if (connector) {
      connect({ connector })
    }
  }
'use client'

import { sepolia } from '@starknet-react/chains'
import { publicProvider, StarknetConfig, starkscan } from '@starknet-react/core'
import { constants } from 'starknet'
import {
ArgentMobileConnector,
isInArgentMobileAppBrowser,
} from 'starknetkit/argentMobile'
import { InjectedConnector } from 'starknetkit/injected'
import { WebWalletConnector } from 'starknetkit/webwallet'

const chains = [sepolia]

export const availableConnectors = isInArgentMobileAppBrowser()
? [
    ArgentMobileConnector.init({
      options: {
        url: typeof window !== 'undefined' ? window.location.href : '',
        dappName: 'Company name',
        chainId: constants.NetworkName.SN_SEPOLIA,
      },
    }),
  ]
: [
    new InjectedConnector({ options: { id: 'argentX' } }),
    new InjectedConnector({ options: { id: 'braavos' } }),
    ArgentMobileConnector.init({
      options: {
        url: typeof window !== 'undefined' ? window.location.href : '',
        dappName: 'Company name',
        chainId: constants.NetworkName.SN_SEPOLIA,
      },
    }),
    new WebWalletConnector({ url: process.env.NEXT_PUBLIC_WEB_WALLET_URL }),
  ]

export function StarknetProvider({ children }: { children: React.ReactNode }) {
return (
  <StarknetConfig
    chains={chains}
    provider={publicProvider()}
    connectors={availableConnectors}
    explorer={starkscan}
    autoConnect
  >
    {children}
  </StarknetConfig>
)
}
ScottyDavies commented 1 month ago

Hello @smakosh can i please be assigned this task?

smakosh commented 1 month ago

Hello @smakosh can i please be assigned this task?

I'm not the owner/maintainer of the repo, cannot assign issues here

RedBeardEth commented 1 month ago

image

@fracek This is the trace stack - and is only occurring when attempting to use account.execute() image Not sure if related - but the account signer pk is 0

fracek commented 1 month ago

Looks like the Signer object Which delegates to @scure/starknet (which in turn uses noble-curves) checks that the private key is in range (defined as [1, N)) and the key being 0 doesn't pass this check.

Can you check if the following demo works for you using ArgentX?

smakosh commented 1 month ago

following demo

Unable to connect the wallet, account address loads forever

Screenshot 2024-10-07 at 9 05 38 AM
fracek commented 1 month ago

Does it print any log? Can you download this repo and run the demo locally and try to see what's happening?

smakosh commented 1 month ago

Does it print any log? Can you download this repo and run the demo locally and try to see what's happening?

Ran it locally, here's what I get on the log

Uncaught TypeError: Cannot read properties of undefined (reading 'id')
smakosh commented 1 month ago

Also this demo doesn't use the account.execute() method

fracek commented 1 month ago

I noticed you're using starknetkit. Are you using the latest release (or prerelease) that is compatible with starknet react v3? V3 switches to the new wallet API to execute transactions.

RedBeardEth commented 1 month ago

This is using "starknetkit": "^2.3.2" (latest)

fracek commented 1 month ago

That's strange because it's the same version we use in the demo.

Last thing that could differ is the browser/OS you use and the argent version. Also did you test it with Braavos? Does it work with it?

smakosh commented 1 month ago

the demo doesn't use account.execute() which the initial issue is related to. This started occurring right after integrating starknetkit and upgrading it along with starknet-react

kseikyo commented 1 month ago

TLDR: Downgrade to "starknet-react: 3.0.0" and "starknetkit": "^2.3.0" for now.

Had the same error as op happen once after upgrading

- "starknet-react: 3.0.0",
+ "starknet-react: 3.0.1",
- "starknetkit": "^2.3.0",
+ "starknetkit": "^2.3.2",

Using starknet-react hooks to get the account and provider to use in the following code results in the error below:

const contract = new Contract(ABI, address, provider).typedv2(ABI);
console.log(contract); // logs correctly

const tx = contract.populateTransaction.fn(params);

return account.execute(tx); // will throw
LibraryError: RPC: starknet_getNonce with params {
  "contract_address": "0x68f5ed041a0fad85ad85d8f7b6653abd806ebe6e80b92faf501a883589347b7",
  "block_id": "pending"
}

        20: Contract not found: undefined
    at RpcChannel2.errorHandler (index.mjs:4134:13)
    at RpcChannel2.fetchEndpoint (index.mjs:4151:12)
    at async Account.execute (index.mjs:6464:45)
smakosh commented 1 month ago

I resolved my issue by moving away from account.execute() to useSendTransaction

Example:

const { sendAsync: doSomething } = useSendTransaction({
  calls: undefined,
})

const onSubmit = async () => {
  try {
    const { transaction_hash } = await doSomething([
      {
        contractAddress,
        entrypoint: 'some_function_name',
        calldata: [
          somedata,
          otherdata
        ],
      },
      {
        contractAddress,
        entrypoint: 'some_other_function_name',
        calldata: [
         somedata,
          otherdata
        ],
      },
    ])

    // Do something with `transaction_hash`
  } catch (e) {} 
}
fracek commented 1 month ago

Does account come from useAccount? Because that object is from starknet.js so it may be a bug in that library.

smakosh commented 1 month ago

Does account come from useAccount? Because that object is from starknet.js so it may be a bug in that library.

useAccount is imported from starknet-react

fracek commented 1 month ago

Yes, but the account object returned is WalletAccount from starknet.js.

smakosh commented 3 weeks ago

Closing this for now, see https://github.com/apibara/starknet-react/issues/510#issuecomment-2407675745 if you want to solve this