Approve contract using viem

307 Views Asked by At

I'm trying to learn how to work/develop with blockchain, specifically using viem and Avalanche. I'm trying to follow this example for Trade Joe

https://docs.traderjoexyz.com/SDK/trade

I am able to follow through almost all the document but I have a big trouble with the step

  1. Execute trade using Viem

I can not find how to accomplish this: "Remember to approve spending ERC20 tokens by router before execution" using viem.

The documentation from viem is kind of clear to be honest

https://viem.sh/docs/contract/simulateContract#state-overrides

very simple, but I can't find the way how to implement it.

The main issue is this:

"reason": "ERC20: transfer amount exceeds allowance", "shortMessage": "The contract function "swapExactTokensForNATIVE" reverted with the following reason: ERC20: transfer amount exceeds allowance",

I can fully grass the reason, the router haven't had the necessary approval to spend the token in my wallet but I've have a hard time trying to fix that.

If someone can read this, and can help me to solved or at least point me out in the direction to do it I will be appreciate it.

I did try to read all the documents and I'm expecting this message find someone that could help me to fix it.

1

There are 1 best solutions below

1
Juan On

The solution to this basically come in two parts.

  1. "Remember to approve spending ERC20 tokens by router before execution"

This really means to do that on the MM, as normal. Nothing really special on this one. My mistake was thinking that I needed it to do it in the code. KISS apply here for sure!

  1. "ERC20: transfer amount exceeds allowance"

I guess this where everything started to go south for me. Searching around I found some post where they said that error might be come from the no approval on the token, and since this approval is not in the code, well...

That message what it really means is this (which I copied from someone else code):

console.log("YOU CAN'T SEND WHAT YOU DON'T HAVE!")

I want to thanks to all of the 38 people (to this point in time) that took sometime to read this (dumb) question and I hope this answer could help any other person.