Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Error on Events triggering #3767

Closed
marsniper27 opened this issue Feb 12, 2023 · 28 comments
Closed

Error on Events triggering #3767

marsniper27 opened this issue Feb 12, 2023 · 28 comments
Assignees
Labels
bug Verified to be an issue. fixed/complete This Bug is fixed or Enhancement is complete and published. v6 Issues regarding v6

Comments

@marsniper27
Copy link

Ethers Version

6.02

Search Terms

events, event

Describe the Problem

While creating event listeners upon receipt of event an error occurs. Simplified example provided.
This is occurring for multiple contracts and events. Switching to v5.7.2 the events work fine.

Code Snippet

const { ethers } =  require(`ethers`);

const newEthersClient = new ethers.providers.JsonRpcProvider('https://rpc.ankr.com/polygon/486f6d938d85e35aeacf83a59afd95c4fab739093c8f919adb258799d81d51bf');

abi = [
    "event Transfer(address indexed from, address indexed to, uint amount)"
  ]
  
  contract = new ethers.Contract("0x8f3Cf7ad23Cd3CaDbD9735AFf958023239c6A063", abi, newEthersClient)
  
  // Begin listening for any Transfer event
  contract.on("Transfer", (from, to, _amount, event) => {
    const amount = ethers.formatEther(_amount, 18)
    console.log(`${ from } => ${ to }: ${ amount }`);
  
    // The `event.log` has the entire EventLog
  
    // Optionally, convenience method to stop listening
    event.removeListener();
  });

Contract ABI

[
    "event Transfer(address indexed from, address indexed to, uint amount)"
  ]

Errors

Uncaught TypeError TypeError: unknown ProviderEvent (argument="event", value="{\"topics\":[\"0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef\"],\"address\":[\"0x8f3cf7ad23cd3cadbd9735aff958023239c6a063\"]}", code=INVALID_ARGUMENT, version=6.0.2)

Environment

node.js (v12 or newer)

Environment (Other)

No response

@marsniper27 marsniper27 added the investigate Under investigation and may be a bug. label Feb 12, 2023
@marsniper27 marsniper27 changed the title Event Error on Events triggering Feb 12, 2023
@ricmoo ricmoo added the v6 Issues regarding v6 label Feb 13, 2023
@ricmoo
Copy link
Member

ricmoo commented Feb 13, 2023

The problem seems to be that the specified backend does not support the eth_newFilter method.

In v5, polling was always used, which is why it continues to work.

In v6, it is supposed to detect this and fallback onto polling, so I'm looking into why it isn't. I think it has to do with detection. When Geth doesn't support filters, it returns a null filter ID, while it looks like Polygon throws an error instead.

@samuelmonday699
Copy link

samuelmonday699 commented Feb 13, 2023 via email

@ricmoo ricmoo added bug Verified to be an issue. on-deck This Enhancement or Bug is currently being worked on. and removed investigate Under investigation and may be a bug. labels Feb 13, 2023
@ricmoo
Copy link
Member

ricmoo commented Feb 13, 2023

This should be fixed now. Let me know if you have any more issues.

Thanks! :)

@ricmoo ricmoo added fixed/complete This Bug is fixed or Enhancement is complete and published. and removed on-deck This Enhancement or Bug is currently being worked on. labels Feb 13, 2023
@ricmoo ricmoo closed this as completed Feb 13, 2023
@marsniper27
Copy link
Author

Just tested and seems to be working on JsonRPC but still same error if i try with a websocket.

@ricmoo
Copy link
Member

ricmoo commented Feb 13, 2023

Thanks! I’ll look into it shortly.

@ricmoo ricmoo reopened this Feb 13, 2023
@ricmoo
Copy link
Member

ricmoo commented Feb 13, 2023

I think it might be a little more difficult to support a connection-based provider. It seems strange to me that something that supports long-lived connections doesn’t support filters. Do you have a websocket url I can test against?

@FancyLobster
Copy link

Hello @ricmoo , I am having almost the exact same issue while listening for the "PairCreated" event from the Uniswap v2 Factory with the new 6.0.5 version.

Here is the error message:

error = new TypeError(message);
                    ^
TypeError: unknown ProviderEvent (argument="event", value="{\"topics\":[\"0x0d3648bd0f6ba80134a33ba9275ac585d9d315f0ad8355cddefde31afa28d0e9\"],\"address\":[\"0x5c69bee701ef814a2b6a3edd4b1652cb9cc5aa6f\"]}", code=INVALID_ARGUMENT, version=6.0.5)

And here is some of my code:

const account = wallet.connect(provider); 
const factory = new ethers.Contract(
   addresses.factory,
   [
   "event PairCreated(address indexed token0, address indexed token1, address pair, uint)", 
   ],
   account
   );
        
factory.on("PairCreated", async (token0, token1, pair_address) => {
  // Handle Incoming Parameters Here
}

@ricmoo
Copy link
Member

ricmoo commented Feb 20, 2023

@FancyLobster what network and provider are you using?

@FancyLobster
Copy link

FancyLobster commented Feb 20, 2023 via email

@saccura
Copy link

saccura commented Feb 22, 2023

hello @ricmoo. Have the same issue while listening from websocket connection

CONTRACT_DEAL.on(
  'Sold',
  onSellOrBought
);

The error:

uncaughtException: unknown ProviderEvent (argument="event", value="{"topics":["0xb7cfccdb200d3b32433aeb5d2b829c5191534e3602213c2fbb1d2de273a91f20"],"address":["0x1aeca9d86feba74b2c10ff6ed859f11375df87db"]}", code=INVALID_ARGUMENT, version=6.0.5)

V5 working without any problems, please assist here

@ricmoo
Copy link
Member

ricmoo commented Feb 22, 2023

@saccura which network and provider are you using? I’ll look into this asap.

@ricmoo ricmoo added investigate Under investigation and may be a bug. and removed fixed/complete This Bug is fixed or Enhancement is complete and published. labels Feb 22, 2023
@saccura
Copy link

saccura commented Feb 22, 2023

It is private Geth clone, custom contracts.

@ricmoo
Copy link
Member

ricmoo commented Feb 22, 2023

@saccura WebSocketProvider? IpcProvider? JsonRpcProvider? Any additional details are helpful tracking issues down.

@saccura
Copy link

saccura commented Feb 22, 2023

WebSocketProvider

@saccura
Copy link

saccura commented Feb 22, 2023

Here is my factory provider:

import { JsonRpcProvider, WebSocketProvider } from 'ethers';
import { logger } from '../../common/logger.js';

const ENDPOINTS = {
  'eth': process.env.ENDPOINT_ETH,
  'bnb': process.env.ENDPOINT_BNB,
};

class ETHProviderFactoryClass {
  constructor() {
    this.instances = {};
    this.stateChangeListeners = {};
  }

  async getInstance({ networkId }) {
    const endpoint = ENDPOINTS[networkId];
    if (!endpoint) {
      console.error(`[ETHProviderFactoryClass].getInstance no endpoint for [${networkId}]`);
      return;
    }
    if (this.instances[networkId]) return this.instances[networkId];
    if (ENDPOINTS[networkId].startsWith('http')) {
      this.instances[networkId] = await new JsonRpcProvider(endpoint);
      this.sendCallbacks(networkId, true);
    } else {
      try {
        this.instances[networkId] = await this.connectWS(endpoint, networkId);
      } catch (error) {
        console.error('[ETHProviderFactoryClass].WebSocketProvider', error);
      }
    }
    return this.instances[networkId];
  }

  reConnectWS(endpoint, networkId) {
    setTimeout(async () => {
      try {
        this.instances[networkId] = await this.connectWS(endpoint, networkId);
      } catch (error) {
        //
      }
    }, 1000);
  }

  sendCallbacks(networkId, value) {
    this.stateChangeListeners && this.stateChangeListeners[networkId] && this.stateChangeListeners[networkId].forEach(fn => fn(value));
  }

  onStateChange(fn, networkId) {
    if (!this.stateChangeListeners[networkId]) {
      this.stateChangeListeners[networkId] = [];
    }
    this.stateChangeListeners[networkId].push(fn);

    return () => {
      this.stateChangeListeners[networkId] = this.stateChangeListeners[networkId].filter(l => l !== fn);
    };
  }

  async connectWS(endpoint, networkId) {
    if (this.instances[networkId]) return this.instances[networkId];
    return new Promise(async (resolve, reject) => {
      try {
        const provider = await new WebSocketProvider(endpoint);
        const onClose = provider.websocket.onclose;
        const onOpen = provider.websocket.onopen;
        logger.data(`[connectWS] trying websocket ${endpoint}`);
        provider.websocket.onopen = async event => {
          console.log(`[connectWS].onopen endpoint: [${endpoint}] networkId: [${networkId}] connnected`, provider.ID);
          this.sendCallbacks(networkId, true);
          onOpen && onOpen(event);
          resolve(provider);
          // reject(event);
        };
        provider.websocket.onclose = event => {
          logger.error(`[connectWS].onclose networkId: [${networkId}], code: ${event.code}`);
          reject(event);
          this.instances[networkId] = null;
          this.sendCallbacks(networkId, false);
          onClose && onClose(event);
          this.reConnectWS(endpoint, networkId);
        };
        provider.endpoint = endpoint;
        provider.ID = Math.floor(Math.random() * 10000);
      } catch (ex) {
        logger.exception(`[connectWS] ${ex.message}`, { stack: ex.stack });
        reject();
      }
    });
  }

  free({ networkId }) {
    if (!this.instances[networkId]) return false;
    this.sendCallbacks(networkId, false);
    this.instances[networkId].removeAllListeners();
    delete this.instances[networkId];
  }

  isConnected({ networkId }) {
    return !!this.instances[networkId];
  }
}

export const FabricProviderETH = new ETHProviderFactoryClass();

May be provider.websocket works differently in v6?

@hussamsh
Copy link

I am having the exact same issue the others are having with WebSocketProvider. [network=BSC][provider=getblock]

@comunidadio
Copy link

Have the same issue as well with QuickNode WebSocket on 6.0.8.
Getting events fine when using QuickNode https provider, but getting the following with wss:

error: Uncaught TypeError: unknown ProviderEvent (argument="event", value="{\"topics\":[\"0x0559884fd3a460db3073b7fc896cc77986f16e378210ded43186175bf646fc5f\"],\"address\":[\"0x4dd6655ad5ed7c06c882f496e3f42ace5766cb89\"]}", code=INVALID_ARGUMENT, version=6.0.8)
    at makeError (file:///Users/XXX/Library/Caches/deno/npm/registry.npmjs.org/ethers/6.0.8/lib.esm/utils/errors.js:109:21)
    at assert (file:///Users/XXX/Library/Caches/deno/npm/registry.npmjs.org/ethers/6.0.8/lib.esm/utils/errors.js:132:15)
    at assertArgument (file:///Users/XXX/Library/Caches/deno/npm/registry.npmjs.org/ethers/6.0.8/lib.esm/utils/errors.js:143:5)
    at getSubscription (file:///Users/XXX/Library/Caches/deno/npm/registry.npmjs.org/ethers/6.0.8/lib.esm/providers/abstract-provider.js:135:5)
    at WebSocketProvider.#hasSub (file:///Users/XXX/Library/Caches/deno/npm/registry.npmjs.org/ethers/6.0.8/lib.esm/providers/abstract-provider.js:866:25)
    at WebSocketProvider.emit (file:///Users/XXX/Library/Caches/deno/npm/registry.npmjs.org/ethers/6.0.8/lib.esm/providers/abstract-provider.js:913:39)
    at SocketEventSubscriber._emit (file:///Users/XXX/Library/Caches/deno/npm/registry.npmjs.org/ethers/6.0.8/lib.esm/providers/provider-socket.js:99:18)
    at SocketEventSubscriber._handleMessage (file:///Users/XXX/Library/Caches/deno/npm/registry.npmjs.org/ethers/6.0.8/lib.esm/providers/provider-socket.js:57:36)
    at WebSocketProvider._processMessage (file:///Users/XXX/Library/Caches/deno/npm/registry.npmjs.org/ethers/6.0.8/lib.esm/providers/provider-socket.js:213:28)
    at WebSocketProvider.websocket.onmessage (file:///Users/XXX/Library/Caches/deno/npm/registry.npmjs.org/ethers/6.0.8/lib.esm/providers/provider-websocket.js:37:18)

@mktcode
Copy link

mktcode commented Mar 12, 2023

I'm testing something on sepolia and I'm missing the event object in the callback. :(

contract.on("Transfer", async (from, to, tokenId, event) => {
  console.log(event) // undefined :(

@WorkDarwin
Copy link

@saccura WebSocketProvider? IpcProvider? JsonRpcProvider? Any additional details are helpful tracking issues down.

In version 6.1, the problem remains, the same error. It does not depend on the provider, in HTTP listening works correctly, and in WSS there is an error on the event: "TypeError: unknown ProviderEvent (argument="event", value="{"topics":["0x..."],"address":["0x..."]}", code=INVALID_ARGUMENT, version=6.1.0)" . Please fix it

@jsaorin
Copy link

jsaorin commented Mar 20, 2023

I also have that problem in version 6.1.0.
With version 5.7.2 it works.

@WorkDarwin
Copy link

I also have that problem in version 6.1.0. With version 5.7.2 it works.

Yes, thanks for the information, I know about it. But currently I have migrated a large amount of code to version 6, so there is no way to go back to 5.7.2. Unfortunately, I had to use another library for now. But I believe in developers and I'm waiting for updates!

@shirotech
Copy link

shirotech commented Mar 21, 2023

This is still happening in 6.2.0, IPC Provider, here is the error message:

TypeError: unknown ProviderEvent (argument="event", value="{\"topics\":[\"0x9902e12af946c468918984c5760caf02072c36782c79c6a797a77665e9c512c3\"],\"address\":[\"xyz>
    at makeError (file:///home/<user>/app/node_modules/ethers/lib.esm/utils/errors.js:109:21)
    at assert (file:///home/<user>/app/node_modules/ethers/lib.esm/utils/errors.js:132:15)
    at assertArgument (file:///home/<user>/app/node_modules/ethers/lib.esm/utils/errors.js:143:5)
    at getSubscription (file:///home/<user>/app/node_modules/ethers/lib.esm/providers/abstract-provider.js:136:5)
    at #hasSub (file:///home/<user>/app/node_modules/ethers/lib.esm/providers/abstract-provider.js:871:25)
    at IpcSocketProvider.emit (file:///home/<user>/app/node_modules/ethers/lib.esm/providers/abstract-provider.js:918:39)
    at SocketEventSubscriber._emit (file:///home/<user>/app/node_modules/ethers/lib.esm/providers/provider-socket.js:109:18)
    at SocketEventSubscriber._handleMessage (file:///home/<user>/app/node_modules/ethers/lib.esm/providers/provider-socket.js:59:36)
    at IpcSocketProvider._processMessage (file:///home/<user>/app/node_modules/ethers/lib.esm/providers/provider-socket.js:225:28)
    at file:///home/<user>/app/node_modules/ethers/lib.esm/providers/provider-ipcsocket.js:38:22 {
  code: 'INVALID_ARGUMENT',
  argument: 'event',
  value: '{"topics":["0x9902e12af946c468918984c5760caf02072c36782c79c6a797a77665e9c512c3"],"address":["xyz"]}'
}

Also it's not a critical error, why even cause an exception that is impossible to try catch, app just crashes for no reason when it can recover if otherwise.

shirotech added a commit to shirotech/ethers.js that referenced this issue Mar 22, 2023
@shirotech
Copy link

@ricmoo I have a suggested fix for this in a PR #3922 The issue is that the _event arg was expected to be an object, but it was a string that wasn't parsed or was stringify from somewhere.

@ricmoo
Copy link
Member

ricmoo commented Mar 26, 2023

Sorry. Lost track of this. I will look into it today.

@ricmoo ricmoo added the on-deck This Enhancement or Bug is currently being worked on. label Mar 27, 2023
@ricmoo
Copy link
Member

ricmoo commented Mar 28, 2023

Found the single-character bug causing this in the SocketEventSubscriber. I'll get this out shortly. :)

@ricmoo
Copy link
Member

ricmoo commented Mar 28, 2023

This should now be fixed for WebSocketProvider in v6.2.3.

Please try it out and let me know if there are further issues.

Thanks! :)

@ricmoo ricmoo added fixed/complete This Bug is fixed or Enhancement is complete and published. and removed investigate Under investigation and may be a bug. on-deck This Enhancement or Bug is currently being worked on. labels Mar 28, 2023
@ricmoo
Copy link
Member

ricmoo commented Mar 30, 2023

Closing as fixed. But if any further problems occur, let me know.

Thanks! :)

@ricmoo ricmoo closed this as completed Mar 30, 2023
@ArminSm98
Copy link

ArminSm98 commented Sep 18, 2023

@ricmoo I have issue while listening to PairCreated event in pancakeswap v2 factory, i use JsonRpcProvider, my network is BSC and my ethers version is 5.7.0 ,when i run code nothing happens , i don't get any errors but i don't get new pairs which are created. could you please help me?!
this is my code:
const provider= new ethers.providers.JsonRpcProvider('https://bsc-dataseed.binance.org');
const factoryInterface = ['event PairCreated(address indexed token0, address indexed token1, address pair, uint)',];
const factory = new ethers.Contract(config.addresses.factory, factoryInterface, provider);
async function updateCollections() {
factory.on('PairCreated', async (token0, token1, pairAddress) => {
try {
//handle parameters
} catch (error){
throw new Error(Error updating collections: ${error});
}
});
}

updateCollections();

Woodpile37 pushed a commit to Woodpile37/ethers.js that referenced this issue Jan 14, 2024
Woodpile37 pushed a commit to Woodpile37/ethers.js that referenced this issue Jan 14, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Verified to be an issue. fixed/complete This Bug is fixed or Enhancement is complete and published. v6 Issues regarding v6
Projects
None yet
Development

No branches or pull requests