Skip to content
This repository has been archived by the owner on Aug 1, 2023. It is now read-only.

SingerOrProvider invalid when following tutorial #39

Open
iguanaus opened this issue Feb 23, 2023 · 2 comments
Open

SingerOrProvider invalid when following tutorial #39

iguanaus opened this issue Feb 23, 2023 · 2 comments

Comments

@iguanaus
Copy link

Hey tried to run this script:

import { PairV2, RouteV2, TradeV2, LB_ROUTER_ADDRESS, LBRouterABI } from '@traderjoe-xyz/sdk-v2'
import { Token, ChainId, TokenAmount, JSBI, Percent, WAVAX} from '@traderjoe-xyz/sdk'

// WAVAX_ITEM: _WAVAX_ITEM,


import { Wallet } from 'ethers'
import { Contract } from '@ethersproject/contracts'
import { parseUnits } from '@ethersproject/units'
import { JsonRpcProvider } from '@ethersproject/providers'

const AVAX_URL = 'https://api.avax.network/ext/bc/C/rpc'
console.log(ChainId)
const CHAIN_ID = ChainId.AVALANCHE
const PROVIDER = new JsonRpcProvider(AVAX_URL)
const WALLET_PK = "<><><>"
const SIGNER = new Wallet(WALLET_PK, PROVIDER)
const ACCOUNT = await SIGNER.getAddress()
console.log("Addres is")
console.log(ACCOUNT)
// initialize tokens

console.log("WAVAX")
console.log(WAVAX)
console.log("CHain id")
console.log(CHAIN_ID)
const WAVAX_ITEM = WAVAX[CHAIN_ID] // Token instance of WAVAX_ITEM
const USDC = new Token(
    CHAIN_ID,
    '0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E',
    6,
    'USDC',
    'USD Coin'
)
const USDT = new Token(
    CHAIN_ID,
    '0x9702230A8Ea53601f5cD2dc00fDBc13d4dF4A8c7',
    6,
    'USDT',
    'Tether USD'
)

// declare bases used to generate trade routes
const BASES = [WAVAX_ITEM, USDC, USDT] 

// the input token in the trade
const inputToken = USDC

// the output token in the trade
const outputToken = WAVAX_ITEM

// specify whether user gave an exact inputToken or outputToken value for the trade
const isExactIn = true

// user string input; in this case representing 20 USDC
const typedValueIn = '20' 

// parse user input into inputToken's decimal precision, which is 6 for USDC
const typedValueInParsed = parseUnits( 
  typedValueIn, 
  inputToken.decimals
).toString() // returns 20000000

// wrap into TokenAmount
const amountIn = new TokenAmount(
  inputToken, 
  JSBI.BigInt(typedValueInParsed)
) 

console.log("Input")
console.log(inputToken)
console.log("Output")
console.log(outputToken)
console.log("Bases")
console.log(BASES)

// get all [Token, Token] combinations 
const allTokenPairs = PairV2.createAllTokenPairs(
  inputToken,
  outputToken,
  BASES
)

// init PairV2 instances for the [Token, Token] pairs
const allPairs = PairV2.initPairs(allTokenPairs) 

// generates all possible routes to consider
const allRoutes = RouteV2.createAllRoutes(
  allPairs,
  inputToken,
  outputToken,
  2 // maxHops 
) 

const isAvaxIn = false // set to 'true' if swapping from AVAX; otherwise, 'false'
const isAvaxOut = true // set to 'true' if swapping to AVAX; otherwise, 'false'

// generates all possible TradeV2 instances
const trades = await TradeV2.getTradesExactIn(
  allRoutes,
  amountIn,
  outputToken,
  isAvaxIn,
  isAvaxOut, 
  PROVIDER,
  CHAIN_ID
) 

// chooses the best trade 
const bestTrade = TradeV2.chooseBestTrade(trades, isExactIn)

// print useful information about the trade, such as the quote, executionPrice, fees, etc
console.log(bestTrade.toLog())

// get trade fee information
const { totalFeePct, feeAmountIn } = await bestTrade.getTradeFee(PROVIDER)
console.log('Total fees percentage', totalFeePct.toSignificant(6), '%')
console.log(`Fee: ${feeAmountIn.toSignificant(6)} ${feeAmountIn.token.symbol}`)

// set slippage tolerance
const userSlippageTolerance = new Percent(JSBI.BigInt(50), JSBI.BigInt(10000)) // 0.5%

// set deadline for the transaction
const currenTimeInSec =  Math.floor((new Date().getTime()) / 1000)
const deadline = currenTimeInSec + 3600

// set swap options
const swapOptions = {
  recipient: ACCOUNT, 
  allowedSlippage: userSlippageTolerance, 
  deadline,
  feeOnTransfer: false // or true
}

// generate swap method and parameters for contract call
const {
  methodName, // e.g. swapExactTokensForAVAX,
  args,       // e.g.[amountIn, amountOut, binSteps, path, to, deadline]
  value       // e.g. 0x0
} = bestTrade.swapCallParameters(swapOptions)

console.log("LB ROUTer address")
console.log(LB_ROUTER_ADDRESS)
console.log(LB_ROUTER_ADDRESS[CHAIN_ID])
console.log("LBRouter API")
console.log(LBRouterABI)
console.log("signer")
console.log(SIGNER)
console.log('signer done')
// init router contract
const router = new Contract(
  LB_ROUTER_ADDRESS[CHAIN_ID],
  LBRouterABI,
  SIGNER
)

// estimate gas
const gasOptions = value && !isZero(value) ? { value } : {} 
const gasEstimate = await router.estimateGas[methodName](...args, options)

// execute swap
const options = value && !isZero(value) 
  ? { value, from: ACCOUNT }
  : { from: ACCOUNT }
await router[methodName](...args, {
  gasLimit: calculateGasMargin(gasEstimate),
  ...options
})

and are getting this error. I don't think it is from my side. Any advice on them?

Error: invalid signer or provider (argument="signerOrProvider", value={"provider":{"_isProvider":true,"_events":[],"_emitted":{"block":-2},"disableCcipRead":false,"formatter":{"formats":{"transaction":{},"transactionRequest":{},"receiptLog":{},"receipt":{},"block":{},"blockWithTransactions":{},"filter":{},"filterLog":{}}},"anyNetwork":false,"_networkPromise":{},"_maxInternalBlockNumber":-1024,"_lastBlockNumber":-2,"_maxFilterBlockRange":10,"_pollingInterval":4000,"_fastQueryDate":0,"connection":{"url":"https://api.avax.network/ext/bc/C/rpc"},"_nextId":46,"_eventLoopCache":{"detectNetwork":null,"eth_chainId":null},"_network":{"chainId":43114,"name":"unknown"}},"address":"<>"}, code=INVALID_ARGUMENT, version=contracts/5.7.0)
    at Logger.makeError (/Users/johnpeurifoy/Documents/traderjoe/node_modules/@ethersproject/logger/lib/index.js:238:21)
    at Logger.throwError (/Users/johnpeurifoy/Documents/traderjoe/node_modules/@ethersproject/logger/lib/index.js:247:20)
    at Logger.throwArgumentError (/Users/johnpeurifoy/Documents/traderjoe/node_modules/@ethersproject/logger/lib/index.js:250:21)
    at Contract.BaseContract (/Users/johnpeurifoy/Documents/traderjoe/node_modules/@ethersproject/contracts/lib/index.js:630:20)
    at new Contract (/Users/johnpeurifoy/Documents/traderjoe/node_modules/@ethersproject/contracts/lib/index.js:1053:42)
    at file:///Users/johnpeurifoy/Documents/traderjoe/main.js:151:16
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
  reason: 'invalid signer or provider',
  code: 'INVALID_ARGUMENT',
  argument: 'signerOrProvider',
  value: Wallet {
    provider: JsonRpcProvider {
      _isProvider: true,
      _events: [],
      _emitted: { block: -2 },
      disableCcipRead: false,
      formatter: Formatter {
        formats: {
          transaction: {
            hash: [Function: bound ],
            type: [Function: bound ],
            accessList: [Function (anonymous)],
            blockHash: [Function (anonymous)],
            blockNumber: [Function (anonymous)],
            transactionIndex: [Function (anonymous)],
            confirmations: [Function (anonymous)],
            from: [Function: bound ],
            gasPrice: [Function (anonymous)],
            maxPriorityFeePerGas: [Function (anonymous)],
            maxFeePerGas: [Function (anonymous)],
            gasLimit: [Function: bound ],
            to: [Function (anonymous)],
            value: [Function: bound ],
            nonce: [Function: bound ],
            data: [Function: bound ],
            r: [Function (anonymous)],
            s: [Function (anonymous)],
            v: [Function (anonymous)],
            creates: [Function (anonymous)],
            raw: [Function (anonymous)]
          },
          transactionRequest: {
            from: [Function (anonymous)],
            nonce: [Function (anonymous)],
            gasLimit: [Function (anonymous)],
            gasPrice: [Function (anonymous)],
            maxPriorityFeePerGas: [Function (anonymous)],
            maxFeePerGas: [Function (anonymous)],
            to: [Function (anonymous)],
            value: [Function (anonymous)],
            data: [Function (anonymous)],
            type: [Function (anonymous)],
            accessList: [Function (anonymous)]
          },
          receiptLog: {
            transactionIndex: [Function: bound ],
            blockNumber: [Function: bound ],
            transactionHash: [Function: bound ],
            address: [Function: bound ],
            topics: [Function (anonymous)],
            data: [Function: bound ],
            logIndex: [Function: bound ],
            blockHash: [Function: bound ]
          },
          receipt: {
            to: [Function (anonymous)],
            from: [Function (anonymous)],
            contractAddress: [Function (anonymous)],
            transactionIndex: [Function: bound ],
            root: [Function (anonymous)],
            gasUsed: [Function: bound ],
            logsBloom: [Function (anonymous)],
            blockHash: [Function: bound ],
            transactionHash: [Function: bound ],
            logs: [Function (anonymous)],
            blockNumber: [Function: bound ],
            confirmations: [Function (anonymous)],
            cumulativeGasUsed: [Function: bound ],
            effectiveGasPrice: [Function (anonymous)],
            status: [Function (anonymous)],
            type: [Function: bound ]
          },
          block: {
            hash: [Function (anonymous)],
            parentHash: [Function: bound ],
            number: [Function: bound ],
            timestamp: [Function: bound ],
            nonce: [Function (anonymous)],
            difficulty: [Function: bound ],
            gasLimit: [Function: bound ],
            gasUsed: [Function: bound ],
            miner: [Function (anonymous)],
            extraData: [Function: bound ],
            transactions: [Function (anonymous)],
            baseFeePerGas: [Function (anonymous)]
          },
          blockWithTransactions: {
            hash: [Function (anonymous)],
            parentHash: [Function: bound ],
            number: [Function: bound ],
            timestamp: [Function: bound ],
            nonce: [Function (anonymous)],
            difficulty: [Function: bound ],
            gasLimit: [Function: bound ],
            gasUsed: [Function: bound ],
            miner: [Function (anonymous)],
            extraData: [Function: bound ],
            transactions: [Function (anonymous)],
            baseFeePerGas: [Function (anonymous)]
          },
          filter: {
            fromBlock: [Function (anonymous)],
            toBlock: [Function (anonymous)],
            blockHash: [Function (anonymous)],
            address: [Function (anonymous)],
            topics: [Function (anonymous)]
          },
          filterLog: {
            blockNumber: [Function (anonymous)],
            blockHash: [Function (anonymous)],
            transactionIndex: [Function: bound ],
            removed: [Function (anonymous)],
            address: [Function: bound ],
            data: [Function (anonymous)],
            topics: [Function (anonymous)],
            transactionHash: [Function: bound ],
            logIndex: [Function: bound ]
          }
        }
      },
      anyNetwork: false,
      _networkPromise: Promise { { chainId: 43114, name: 'unknown' } },
      _maxInternalBlockNumber: -1024,
      _lastBlockNumber: -2,
      _maxFilterBlockRange: 10,
      _pollingInterval: 4000,
      _fastQueryDate: 0,
      connection: { url: 'https://api.avax.network/ext/bc/C/rpc' },
      _nextId: 46,
      _eventLoopCache: { detectNetwork: null, eth_chainId: null },
      _network: { chainId: 43114, name: 'unknown' }
    },
    address: '<>'
  }
}
@iguanaus
Copy link
Author

Note that i had to fix several errors in the tutorial on: https://docs.traderjoexyz.com/SDK/trade

@Hovooo
Copy link

Hovooo commented May 30, 2023

Tutorial isn't working at all.
Besides primitive errors in naming (at one place variable is named "daedline", on the other "deadline"), there are more than 9 fatal errors.
Any suggestions on how can we use your sdk?

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants