Unexpected error could not estimate gas for the approve

Суть такова: пробую совершить обмен определенного токена на BUSD, а обмен не проходит и вылазит ошибка на скрине ниже. В чем может быть проблема и как ее решить?

Рекомендуемые сообщения

bakalavr

Пользователь

    • Поделиться

Суть такова: пробую совершить обмен определенного токена на BUSD, а обмен не проходит и вылазит ошибка на скрине ниже. В чем может быть проблема и как ее решить? 

pps.jpg


Изменено 17 Dec 2021, 05:49 пользователем Helber

Ссылка на комментарий
Поделиться на другие сайты

  • 16 Dec 2021, 14:55

    rammendo изменил название на pancaceswap

Helber

Продвинутый пользователь

    • Поделиться

@bakalavr , хеш транзакции покажите.

Судя по написанному, там не хватает газа — возможно, при обмене смарт-контракт неправильно ставит вам газлимит? Тогда нужно найти там настройки и поставить газлимит вручную, побольше. Потратится все равно сколько потребуется, а остаток вернется.

+Вы хоть кошелек (название) соизвольте указать.

Ссылка на комментарий
Поделиться на другие сайты

bakalavr

Пользователь

  • Автор
    • Поделиться

15 минут назад, Helber сказал:

@bakalavr , хеш транзакции покажите.

Судя по написанному, там не хватает газа — возможно, при обмене смарт-контракт неправильно ставит вам газлимит? Тогда нужно найти там настройки и поставить газлимит вручную, побольше. Потратится все равно сколько потребуется, а остаток вернется.

+Вы хоть кошелек (название) соизвольте указать.

Кошелек трастваллет, но там стандартные настройки по газу стоят, даже не знаю, можно ли больше поставить. А в панкакесвапе есть настройки по газу или всё в кошельке? 

Гугл переводчик говорит что этот алерт о том, что невозможно определить стоимость газа, вообще не пойму ничего, кто ж его может определить как не биржа или кошелёк

Ссылка на комментарий
Поделиться на другие сайты

vernichter

Продвинутый пользователь

    • Поделиться

22 минуты назад, bakalavr сказал:

А в панкакесвапе есть настройки по газу или всё в кошельке?

Вот какие-то такие

pancake.jpg

Ссылка на комментарий
Поделиться на другие сайты

Helber

Продвинутый пользователь

    • Поделиться

24 минуты назад, bakalavr сказал:

Кошелек трастваллет, но там стандартные настройки по газу стоят, даже не знаю, можно ли больше поставить.

Можно. В момент оформления самой транзакции, там есть малозаметная шестеренка (у меня так)

25 минут назад, bakalavr сказал:

А в панкакесвапе есть настройки по газу

Вряд ли..

25 минут назад, bakalavr сказал:

Гугл переводчик говорит что этот алерт о том, что невозможно определить стоимость газа, вообще не пойму ничего

Как и я

43 минуты назад, Helber сказал:

хеш транзакции покажите.

Большой секрет? На лям покупаете/продаете?

Ссылка на комментарий
Поделиться на другие сайты

bakalavr

Пользователь

  • Автор
    • Поделиться

1 час назад, Helber сказал:

Можно. В момент оформления самой транзакции, там есть малозаметная шестеренка (у меня так)

Вряд ли..

Как и я

Большой секрет? На лям покупаете/продаете?

Секрета никакого нет, через пару часов попробую найти этот хеш, хотя как его искать, если транзакция не свершилась, то есть я так не совершил обмен

Ссылка на комментарий
Поделиться на другие сайты

Helber

Продвинутый пользователь

    • Поделиться

Только что, bakalavr сказал:

Секрета никакого нет, через пару часов попробую найти этот хеш, хотя как его искать, если транзакция не свершилась, то есть я так не совершил обмен

По идее, если выбило ошибку, транзакция была в блокчейне и зафейлилась

Попробуйте искать, отталкиваясь от адреса своего кошелька(т.е.просматривая исходящие транзакции)

Ссылка на комментарий
Поделиться на другие сайты

bakalavr

Пользователь

  • Автор
    • Поделиться

@Helber Хеша не обнаружил, вот скрин того что свопаю

pps2.jpg

Ссылка на комментарий
Поделиться на другие сайты

Helber

Продвинутый пользователь

    • Поделиться

1 час назад, bakalavr сказал:

вот скрин того что свопаю

:facepalm:
 

Адрес для пополнения вашего кошелька напишите. 
 

5 часов назад, Helber сказал:

искать, отталкиваясь от адреса своего кошелька(т.е.просматривая исходящие транзакции)

Ссылка на комментарий
Поделиться на другие сайты

bakalavr

Пользователь

  • Автор
    • Поделиться

@Helber 0x0B69b2F02CB36c105bfdE0d635Cb7D7890EBa40A если я правильно понял. Это трастваллет

Ссылка на комментарий
Поделиться на другие сайты

Helber

Продвинутый пользователь

    • Поделиться

3 часа назад, bakalavr сказал:

0x0B69b2F02CB36c105bfdE0d635Cb7D7890EBa40A если я правильно понял. Это трастваллет

Да, оно

https://bscscan.com/address/0x0B69b2F02CB36c105bfdE0d635Cb7D7890EBa40A#tokentxns

Токены MTK на месте. Никаких зафейленных транзакций нет. BNB для оплаты комиссий — явно хватает.

Шестеренка для настройки газа у меня видна на этом шаге

2B15187B-7DFB-42ED-99F2-68542BE33370.jpeg

Можете зайти в эти настройки и посмотреть там, как система поставила вам газлимит, как цену газа. Можно увеличить то или это

Ссылка на комментарий
Поделиться на другие сайты

  • 17 Dec 2021, 05:49

    Helber изменил название на Pancaceswap + Trust wallet, ошибка the transaction cannot succeed due to error cannot estimate gas

bakalavr

Пользователь

  • Автор
    • Поделиться

Извиняюсь за долгий ответ. 

Вот поскринил настройки с панкакесвапа, пробовал разные варианты, не подходит ни одинpps4.thumb.jpg.9a2a5d9d8a63a5f9016ee3e343fd7175.jpg  

pps3.thumb.jpg.8a2697490f563d23bc15730e18e0ee76.jpg 

Никак не могу это обьяснить, но это факт. Предполагаю, что панкакесвап не умеет для разного рода шиткоинов определять стоимость газа. Буду рад конструктивным советам и предположениям

pps7.jpg

pps6.jpg

pps5.jpg

Ссылка на комментарий
Поделиться на другие сайты

Helber

Продвинутый пользователь

    • Поделиться

@bakalavr , на следуюшем шаге после этого

44 минуты назад, bakalavr сказал:

pps4.thumb.jpg.9a2a5d9d8a63a5f9016ee3e343fd7175.jpg  

Уже это?

В 16.12.2021 в 17:21, bakalavr сказал:

pps.jpg


Ну другой декс попробуйте…

Ссылка на комментарий
Поделиться на другие сайты

bakalavr

Пользователь

  • Автор
    • Поделиться

11 часов назад, Helber сказал:

@bakalavr , на следуюшем шаге после этого

Уже это?

Ну там следующий шаг подтверждениеpps8.thumb.jpg.4ba65ce59dc4348b934a5249879c6141.jpg

но в нем нет никаких настроек, просто кнопку нажать.

Потом иногда появляется pps6.thumb.jpg.2706b64d20b211762c140d5de9fd3b2b.jpg

но тут вообще ничего не кликабельно

11 часов назад, Helber сказал:


Ну другой декс попробуйте…

Этот шиток я так понял только на панкакесвапе торгуется

Ссылка на комментарий
Поделиться на другие сайты

Helber

Продвинутый пользователь

    • Поделиться

6 часов назад, bakalavr сказал:

но тут вообще ничего не кликабельно

Попробуйте запустить трастваллет на другом устройстве. Или вообще запустить метамаск в браузере  и восстановиться в нем по сиду

Что-то похоже на глюк

6 часов назад, bakalavr сказал:

Этот шиток я так понял только на панкакесвапе торгуется

https://coinmarketcap.com/rankings/exchanges/dex/ ?

Ссылка на комментарий
Поделиться на другие сайты

  • 4 недели спустя…

Tarapeyeva

Новичок

    • Поделиться

У меня сейчас выходит такая же ошибка… у вас получилось в итоге обменять? 

Ссылка на комментарий
Поделиться на другие сайты

Для публикации сообщений создайте учётную запись или авторизуйтесь

Вы должны быть пользователем, чтобы оставить комментарий

Войти

Уже есть аккаунт? Войти в систему.

Войти

Are you getting a “cannot estimate gas” error on PancakeSwap?

Here’s the full error message, “The transaction cannot succeed due to error: cannot estimate gas”.

Followed by, “transaction may fail or may require manual gas limit. This is probably an issue with one of the tokens you are swapping”.

The error message prevents you from buying or selling the token.

It can be caused when you’re swapping a token such as Safemoon, Bonfire, or others.

Errors like these are very common on PancakeSwap, so you’re not the only one experiencing it.

In this guide, you’ll learn what does “cannot estimate gas” mean on PancakeSwap and how to fix it.

  • What does “cannot estimate gas” mean on PancakeSwap?
  • How to fix “cannot estimate gas” on PancakeSwap

What does “cannot estimate gas” mean on PancakeSwap?

Cannot estimate gas PancakeSwap

“cannot estimate gas” on PancakeSwap means that the exchange cannot estimate the fee of the transaction.

It usually happens when there are too many decimal places in the number of tokens.

When there are too many decimal places in the number of tokens, the “cannot estimate gas” error may occur.

For example, if you’re swapping BNB for 155.968325 ANKR, you may get the error message.

This is because the token has too many decimal places.

Another reason why you got the “cannot estimate gas” error is because the token might be a scam.

However, this is usually not the case.

To check whether the token is a scam, you need to view its recent transactions.

If there are people buying and selling the token recently, then it’s most likely not a scam and the error message is caused by PancakeSwap.

The error message can be easily fixed by using the steps below.

To fix “cannot estimate gas” on PancakeSwap, change your slippage tolerance to 12%.

Then, you need to change the number of tokens that you’re trying to swap.

After you’ve changed the number of tokens that you’re trying to swap, the error message will be fixed.

For example, if you’re trying to swap BNB for Safemoon, the number of Safemoon may have a lot of decimal places.

Or, the last numbers of Safemoon might be very randomized (e.g. 5123859).

When this happens, PancakeSwap may have trouble estimating the fee of the transaction.

As a result, the transaction will fail and you’ll get the “cannot estimate gas” error.

In addition, a low slippage tolerance might cause your transaction to fail as well.

This is due to the fee of the token.

You can mitigate this by increasing your slippage tolerance in increments to find out the lowest slippage tolerance for the transaction to succeed.

Here’s how you can fix “cannot estimate gas” on PancakeSwap:

Step #1: Change your slippage tolerance to 12%

To begin with, you need to open PancakeSwap.

Once you’re on PancakeSwap, choose the tokens that you want to swap.

You can do so by selecting the token that you want to buy in the “To” field.

Then, select the token that you want to use to swap for it in the “From” field.

Next, you need to change your slippage tolerance.

To do so, tap on the Settings icon.

After you’ve tapped on the Settings icon, the Settings pop-up will open.

On the Settings pop-up, you’ll see a “Slippage tolerance” field.

In the field, input “12” as your slippage tolerance.

Then, close the Settings pop-up by tapping on the “x” icon.

Alternatively, you can increase your slippage tolerance in increments.

Start with a 2% slippage tolerance, then work your way up to 4%, 6%. 8%, and more.

This will allow you to find the lowest slippage tolerance for the transaction to succeed.

However, if you’re trying to buy a token like Safemoon, you’ll need to set a slippage tolerance of 12%.

This is due to the token’s fees.

Step #2: Change the last numbers to zero

Next, you need to change the last numbers of the token to zero.

Firstly, select the token that you want to buy in the “To” field.

Then, select the token that you want to use to swap it with (e.g., BNB, Ethereum).

Next, enter the amount of BNB or Ethereum that you want to swap for the token.

For example, if you want to swap 0.04515 BNB, input “0.04515” in the “From” field.

This will make the “To” field estimated.

However, the “To” field cannot be estimated if you’re buying a token.

If the “To” field is estimated, you may receive an error message like the “cannot estimate gas” error when you tap on “Swap”.

Instead, you need the “From” field to be estimated.

How to fix "cannot estimate gas" on PancakeSwap

When you’re buying a token, you need the “From” field to be estimated.

To do so, change the last numbers of the token that you’re trying to buy to zeroes.

For example, if you’re trying to buy 155.958 ANKR, change it to 155.000.

In most cases, this will fix the “cannot estimate gas” error.

However, if the last numbers of the token that you’re trying to buy are already all zeroes, try changing it to random numbers.

For example, if you’re trying to buy 155.000 ANKR, change it to 155.958.

If you’re still getting the “cannot estimate gas” error, try changing the numbers in the “To” and “From” fields to random ones until the transaction succeeds.

This is because the error message is usually caused by the number of tokens that you’re trying to swap.

Conclusion

Here are some general rules to follow whenever you’re buying a selling a token:

If you’re buying a token, make sure that the “From” field is estimated.

To do so, change the last numbers of the token in the “To” field.

On the other hand, if you’re selling a token, make sure that the “To” field is estimated.

To do so, change the last numbers of the token in the “From” field.

This will mitigate any transaction errors from happening such as the “cannot estimate gas” error.

Further reading

Best International Trading Brokers in 2021

How to Buy Dogelon Mars (ELON)

How to Buy HODL Coin (HODL)

Coming Across “Cannot Estimate Gas” on PancakeSwap? Well, many Crypto Lovers find it difficult when these type of problem arises during swapping of New Coins. These kind of issues are mostly faced while buying or selling new cryptocurrencies on PancakeSwap with connecting Trust Wallet or Metamask Wallet. Today, we will discuss why the error message “the transaction cannot succeed due to error cannot estimate gas” is displayed on pancakeswap and what are the solutions to overcome the error.

Read – Baby DogeCoin: Price Prediction – 20X?

“Cannot Estimate Gas Fees” – Where does this error come from?

The error message can be shown by Pancakeswap in multiple ways, such as –

(i) “Transaction may fail or may require manual gas limit”

(ii) “Error cannot estimate gas

(iii) “Cannot Estimate Fees”

(iv) “the transaction cannot succeed due to error can’t estimate gas“.

Here is a pictorial view of the error which is being displayed on PancakeSwap on PC. If you are using your Android or iOS devices, same error can be seen.

how to fix The error transaction cannot succeed due to error: cannot estimate gas on Pancakeswap on ios apple iphone and android

How to Solve “The transaction cannot succeed due to error: cannot estimate gas” on Pancakeswap?

Step 1: To fix the Gas Fee Estimate Error in Pancakeswap, first open your PancakeSwap from Trustwallet DAPP or any other supported browser / apps and connect your wallet.

Step 2: After connecting your wallet, click on Trade > Exchange.

the transaction cannot succeed due to error cannot estimate gas error solution

Step 3: Now, choose your desired coin pair which you want to swap.

Step 4: After that, click on the Settings menu icon.

Step 5: Enter 12 in the Slippage tolerance area. If your transaction fails, then you will have to enter 18%. But, first try with 12%.

Step 6: Then, close the window and click on Swap as shown in the image below.

pancake swap error Transaction may fail or may require manual gas limit

By increasing this slippage tolerance to 12%, you will not face the Gas Price Error on pancakeswap. If you face same error even if by changing the slippage tolerance to 12%, then you may need to increase it to 18%.

How to Solve Error “Transaction may fail or may require manual gas limit” on iOS / Android?

If you are using any DAPP in Android or iOS, then you need to open the PancakeSwap.finance V2 website on that app. After that, change your slippage tolerance to 12% or 18% depending on the crypto you are swapping.

For Trust wallet users on iOS and Android, there is a separate DAPP option where you can directly visit the PancakeSwap DEX without switching or minimizing the app. From the app itself, you will be able to connect your wallet to pancakeswap. Change the slippage tolerance on that app. Now, try to swap the currency.

Hope this article has helped you to fix the error. For any doubts, please comment below.

FAQ

Why the transaction fail message appears for manual gas limit?

The Transaction fail message appears if you have set your slippage tolerance is too low.

Is my crypto safe if the warning shows in pancakeswap?

Yes, your crypto will be completely safe despite of the error warning.

What should be my slippage tolerance to avoid the Cannot Estimate gas error warning?

That depends on the crypto you are exchanging. Most of the times, 12% slippage tolerance works.

Does this method still works in May 2023?

Yes, we have got feedback from several users that the same method resolves the PancakeSwap Gas Estimate error in May 2023.

Вы получаете сообщение об ошибке «Не могу оценить газ» на PancakeSwap?

Вот полное сообщение об ошибке : «Транзакция не может быть выполнена из-за ошибки: невозможно оценить газ».

Затем следует «The transcation cannot succeed due to erro: vannot estimate gas: transactiob may fail or may require manual gasl limit».

Сообщение об ошибке не позволяет вам купить или продать токен.

Это может быть вызвано обменом токена, например Safemoon, Bonfire или других.

Подобные ошибки очень распространены в PancakeSwap, поэтому не только вы сталкиваетесь с ними.

В этом руководстве вы узнаете, что означает «невозможно оценить газ» на PancakeSwap и как это исправить.

Что означает «gas: transactiob may fail or may require manual gasl limit» на PancakeSwap?

.

«Не может оценить газ» на PancakeSwap означает, что биржа не может оценить комиссию за транзакцию.

Обычно это происходит, когда в количестве токенов слишком много десятичных знаков.

Когда в количестве жетонов слишком много десятичных знаков, может возникнуть ошибка «Невозможно оценить газ».

Например, если вы меняете BNB на 155.968325 ANKR, вы можете получить сообщение об ошибке.

Это связано с тем, что в токене слишком много десятичных знаков.

Еще одна причина, по которой вы получили ошибку «Не могу оценить газ», заключается в том, что токен может быть мошенничеством.

Как на примере с Orlov Analytics с токеном CDX coin

Чтобы проверить, является ли токен мошенничеством, вам необходимо просмотреть его последние транзакции.

сли в последнее время есть люди, покупающие и продающие токен, то, скорее всего, это не афера, а сообщение об ошибке вызвано PancakeSwap.

Сообщение об ошибке можно легко исправить, выполнив следующие действия.

Как исправить «не могу оценить газ» на PancakeSwap

Чтобы исправить ошибку «не могу оценить газ» на PancakeSwap, измените допуск по проскальзыванию на 12%.

Затем вам нужно изменить количество токенов, которые вы пытаетесь обменять.

После того как вы измените количество токенов, которые вы пытаетесь поменять местами, сообщение об ошибке будет исправлено.

Например, если вы пытаетесь поменять BNB на Safemoon, количество Safemoon может содержать много десятичных знаков.

Или последние числа Safemoon могут быть очень рандомизированы (например, 5123859).

Когда это происходит, у PancakeSwap могут возникнуть проблемы с оценкой комиссии за транзакцию.

В результате транзакция не состоится, и вы получите ошибку «Не могу оценить газ».

Кроме того, низкий допуск к проскальзыванию также может привести к сбою вашей транзакции.

Это связано с комиссией токена.

Вы можете смягчить это, постепенно увеличивая допуск по проскальзыванию, чтобы определить минимальный допуск проскальзывания для успешной транзакции

Шаг №1: Измените допуск по проскальзыванию на 12%

Для начала нужно открыть PancakeSwap.

Как только вы перейдете на PancakeSwap, выберите токены, которые вы хотите обменять.

Вы можете сделать это, выбрав токен, который хотите купить, в поле «Кому».

Затем выберите токен, который вы хотите использовать для обмена, в поле «От».

Затем вам нужно изменить допуск по проскальзыванию.

Для этого коснитесь значка «Настройки».


После того, как вы нажмете на значок «Настройки», откроется всплывающее окно «Настройки».

Во всплывающем окне «Настройки» вы увидите поле «Допуск по проскальзыванию».

В поле введите «12» в качестве допуска по проскальзыванию.

Затем закройте всплывающее окно «Настройки», нажав значок «x».

В качестве альтернативы вы можете постепенно увеличивать допуск по проскальзыванию .

Начните с 2% допуска на проскальзывание, затем увеличивайте его до 4%, 6%. 8% и более.

Это позволит вам найти минимальный допуск проскальзывания для успешной транзакции.

Однако, если вы пытаетесь купить токен, такой как Safemoon, вам необходимо установить допуск по проскальзыванию в 12%.

Это связано с комиссией за токен.

Шаг № 2: замените последние цифры на ноль

.Далее нужно поменять последние цифры токена на ноль.

Сначала выберите токен, который вы хотите купить, в поле «Кому».

Затем выберите токен, который вы хотите использовать для обмена (например, BNB, Ethereum).

Затем введите количество BNB или Ethereum, которое вы хотите обменять на токен.

Например, если вы хотите обменять 0,04515 BNB, введите «0,04515» в поле «От».

Это сделает оценочное поле «Кому».

Однако значение поля «Кому» невозможно оценить, если вы покупаете токен.

Если поле «До» оценено, вы можете получить сообщение об ошибке, например, «невозможно оценить газ», когда вы нажмете «Поменять местами».

Вместо этого вам нужно поле «От» для оценки.

Когда вы покупаете токен, вам нужно, чтобы поле «От» оценивалось.

Для этого измените последние числа токена, который вы пытаетесь купить, на ноль.

Например, если вы пытаетесь купить 155,958 ANKR, измените его на 155,000.

В большинстве случаев это устранит ошибку «невозможно оценить газ».

Однако, если все последние числа токена, который вы пытаетесь купить, уже равны нулю, попробуйте изменить его на случайные числа.

Например, если вы пытаетесь купить 155 000 ANKR, измените его на 155 958.

Если вы по-прежнему получаете сообщение об ошибке «Не могу оценить газ», попробуйте изменить числа в полях «Кому» и «От» на случайные, пока транзакция не будет успешной.

Это связано с тем, что сообщение об ошибке обычно вызвано количеством токенов, которые вы пытаетесь поменять местами.

Заключение

Вот несколько общих правил, которым нужно следовать, когда вы покупаете токен для продажи:

Если вы покупаете токен , убедитесь, что поле «От» оценено.

Для этого измените последние цифры токена в поле «Кому».

С другой стороны, если вы продаете токен , убедитесь, что поле «Кому» оценено.

Для этого измените последние цифры токена в поле «От».

Это снизит вероятность возникновения любых ошибок транзакций, таких как ошибка «невозможно оценить газ».

Description

I frequently get errors like the following:

     Error: cannot estimate gas; transaction may fail or may require manual gas limit [ See: https://links.ethers.org/v5-errors-UNPREDICTABLE_GAS_LIMIT ] 
(reason="VM Exception while processing transaction: reverted with reason string ''", method="estimateGas", transaction=
{"from":"0x3C44CdDdB6a900fa2b585dd299e03d12FA4293BC","gasPrice":
{"type":"BigNumber","hex":"0x00"},"to":"0x663F3ad617193148711d28f5334eE4Ed07016602","value":
{"type":"BigNumber","hex":"0x65"},"data":"0x3e58c58c00000000000000000000000071c95911e9a5d330f4d621842ec243ee1343292e",
"accessList":null}, error={"stackTrace":[{"type":4,"sourceReference":
{"function":"send","contract":"SendFunction","sourceName":"contracts/test/SendFunction.sol","sourceContent":
"// SPDX-License-Identifier: MITnnpragma solidity ^0.8.14;nncontract SendFunction {n    
function send(address to) external payable {n        (bool success, bytes memory data) = to.call{value: msg.value}("x");n        
if (!success) {n            revert(string(data));n        }n    }n}n","line":9,"range":[244,264]},"message":{"value":
{"type":"Buffer","data":
[8,195,121,160,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,32,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0]},"_selector":"08c379a0"},"isInvalidOpcodeError":false}],"data":"0x08c379a000000000000000000000000000000000
000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000000"}, 
code=UNPREDICTABLE_GAS_LIMIT, version=providers/5.6.8)
      at Logger.makeError (node_modules/@ethersproject/logger/src.ts/index.ts:261:28)
      at Logger.throwError (node_modules/@ethersproject/logger/src.ts/index.ts:273:20)
      at checkError (node_modules/@ethersproject/providers/src.ts/json-rpc-provider.ts:78:20)
      at EthersProviderWrapper.<anonymous> (node_modules/@ethersproject/providers/src.ts/json-rpc-provider.ts:603:20)
      at step (node_modules/@ethersproject/providers/lib/json-rpc-provider.js:48:23)
      at Object.throw (node_modules/@ethersproject/providers/lib/json-rpc-provider.js:29:53)
      at rejected (node_modules/@ethersproject/providers/lib/json-rpc-provider.js:21:65)

This only happens occasionally (I’ll include a testcase below), and it’s always hard to fix. The only solution is to set {gasLimit: 3e7} in each contract function call.

One thing that can trigger this problem is when the contract size approaches the maximum possible size. (Hopefully the testcase triggers this as a standalone program — other contracts in my build environment raise the total size close to the limit.)

Environment

  • Compiler version: 0.8.14
  • Target EVM version (as per compiler settings): unknown
  • Framework/IDE (e.g. Truffle or Remix): Hardhat
  • EVM execution environment / backend / blockchain client: Hardhat network
  • Operating system: Linux

Steps to Reproduce

Contracts.sol:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.14;

contract HasReceiveFunction {
    uint256 public receivedETH;
    receive() external payable {
        receivedETH += msg.value;
    }
}

contract SendFunction {
    function send(address to) external payable {
        (bool success,) = to.call{value: msg.value}("");
        if (!success) {
            revert("Failed to send ETH");
        }
    }
}

index.js:

const { expect } = require("chai");
const { ethers } = require("hardhat");
const SendFunction = require("../artifacts/contracts/Contracts.sol/SendFunction.json");
const HasReceiveFunction = require("../artifacts/contracts/Contracts.sol/HasReceiveFunction.json");

async function deployContract(wallet, contract, constructorArgs) {
    const contractInstance = await ethers.ContractFactory.fromSolidity(contract, wallet).deploy(...constructorArgs);
    await contractInstance.deployed();
    return contractInstance;
}

describe("TestSendReceiveFunction", () => {
  let wallet;

  beforeEach(async () => {
    wallet = await ethers.getSigners();
  });

  it("send ETH", async () => {
    const send = await deployContract(wallet[2], SendFunction, []);
    const hasReceive = await deployContract(wallet[1], HasReceiveFunction, []);
    await send.send(hasReceive.address, {value: 101, gasLimit: 3e7});
    expect(await hasReceive.receivedETH({gasLimit:3e7})).to.equal(101);
  });
)};

To trigger the error, you need to do two things:

  1. Remove the gasLimit: 3e7 args.
  2. Change (bool success,) = to.call{value: msg.value}(""); into (bool success,) = to.call{value: msg.value}("x"); — this should revert the call, because receive functions require that msg.data.length == 0. It’s when this call tries to revert that the «cannot estimate gas» error seems to be triggered.

Понравилась статья? Поделить с друзьями:
  • Unexpected error как убрать
  • Unexpected error while running link что это
  • Unexpected error assetto corsa что делать
  • Unexpected error another launcher is already running что делать
  • Unexpected error while getting the method or property getfilebyid on object driveapp