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

Useless deepEqual check in structuralSharing? #4310

Closed
1 task done
Rubilmax opened this issue Oct 2, 2024 · 3 comments
Closed
1 task done

Useless deepEqual check in structuralSharing? #4310

Rubilmax opened this issue Oct 2, 2024 · 3 comments

Comments

@Rubilmax
Copy link

Rubilmax commented Oct 2, 2024

Check existing issues

Describe the bug

I see this check in wagmi's default structuralSharing function:

if (deepEqual(oldData, newData)) return oldData as data

And I'm wondering if it's not useless, knowing that tanstack query's replaceEqualDeep already merge recursively merge objects the most referentially stable possible

In other words, replaceEqualDeep({ test: {}, k: 1 }, { test: {}, k: 2 }).test has the same reference as the first object's test property, thanks to this line

So what is the purpose of deepEqual in structuralSharing in this case?

I suppose it is a "performance" optimization check because deepEqual is faster than replaceEqualDeep, but is there any benchmark for this?
It seems to potentially be an additional non trivial deep equality check that is not worth the cost (because replaceEqualDeep will only replace references that are not deep equal)

Link to Minimal Reproducible Example

No response

Steps To Reproduce

const src = { test: {}, k: 1 };

expect(replaceEqualDeep(src, { test: {}, k: 2 }).test).toBe(src.test);

What Wagmi package(s) are you using?

@wagmi/core

Wagmi Package(s) Version(s)

2.12.16

Viem Version

2.21.8

TypeScript Version

5.6.2

Anything else?

No response

@Rubilmax
Copy link
Author

Rubilmax commented Oct 2, 2024

So I just realized that it does not work with classes as the following test fails:

import { replaceEqualDeep } from "@tanstack/query-core";
import { describe, expect, test } from "vitest";

class Test {
  public readonly test = 1;
}

describe("structuralSharing", () => {
  test("should share the same object", () => {
    const prevTest = new Test();

    const newTest = new Test();

    expect(replaceEqualDeep(prevTest, newTest)).toBe(prevTest);
  });
});

Due to the isPlainObject check in tanstack query

But then, would we want wagmi to cover this edge case with a custom mergeDeepEqual function used in structuralSharing?

EDIT:

In the end, here is what I came up with to handle classes:

import { Market, MarketConfig } from "@morpho-org/blue-sdk";
import { replaceEqualDeep } from "@tanstack/query-core";
import { describe, expect, test } from "vitest";

export function isPlainArray(value: unknown) {
  return Array.isArray(value) && value.length === Object.keys(value).length;
}

/**
 * This function returns `a` if `b` is deeply equal.
 * If not, it will replace any deeply equal children of `b` with those of `a`.
 * This can be used for structural sharing between JSON values for example.
 * It may be unsafe to use with JS classes or other non-plain objects because it will not preserve the prototype chain.
 */
export function mergeDeepEqual<T>(a: unknown, b: T): T;
export function mergeDeepEqual(a: any, b: any): any {
  if (a === b) return a;

  if (
    a == null ||
    typeof a === "number" ||
    typeof a === "string" ||
    typeof a === "boolean" ||
    typeof a === "bigint" ||
    typeof a === "symbol"
  )
    return b;

  const array = isPlainArray(a) && isPlainArray(b);

  const aItems = array ? a : Object.keys(a);
  const aSize = aItems.length;
  const bItems = array ? b : Object.keys(b);
  const bSize = bItems.length;
  const copy = Object.create(
    Object.getPrototypeOf(a),
    Object.getOwnPropertyDescriptors(a),
  );

  let equalItems = 0;

  for (let i = 0; i < bSize; i++) {
    const key = array ? i : bItems[i];
    if (
      ((!array && aItems.includes(key)) || array) &&
      a[key] === undefined &&
      b[key] === undefined
    ) {
      copy[key] = undefined;
      equalItems++;
    } else {
      copy[key] = mergeDeepEqual(a[key], b[key]);
      if (copy[key] === a[key] && a[key] !== undefined) {
        equalItems++;
      }
    }
  }

  return aSize === bSize && equalItems === aSize ? a : copy;
}

const market = new Market({
  config: new MarketConfig({
    collateralToken: "0x7f39C581F595B53c5cb19bD0b3f8dA6c935E2Ca0",
    irm: "0x870aC11D48B15DB9a138Cf899d20F13F79Ba00BC",
    lltv: 860000000000000000n,
    loanToken: "0xdAC17F958D2ee523a2206206994597C13D831ec7",
    oracle: "0x95DB30fAb9A3754e42423000DF27732CB2396992",
  }),
  fee: 0n,
  lastUpdate: 1727795543n,
  price: 2942555708084216647826084922n,
  rateAtTarget: 584469632n,
  totalBorrowAssets: 2977356497368n,
  totalBorrowShares: 2835315603261918002n,
  totalSupplyAssets: 3161520661952n,
  totalSupplyShares: 3030791088453168045n,
});

describe("structuralSharing", () => {
  test("tanstack query should not be optimal with classes", () => {
    const newMarket = new Market(market);

    expect(replaceEqualDeep(market, newMarket)).not.toBe(market);
  });

  test("mergeDeepEqual should be optimal with classes", () => {
    const newMarket = new Market(market);

    expect(mergeDeepEqual(market, newMarket)).toBe(market);
  });

  test("mergeDeepEqual should update reference if at least one reference changed", () => {
    const newMarket = new Market(market);

    newMarket.fee = 1n;

    const merged = mergeDeepEqual(market, newMarket);

    expect(merged).not.toBe(market);
    expect(merged.config).toBe(market.config);
  });
});

This may not be tanstack query friendly, but it handles classes as I want so far.

Still this issue's main topic remains: I believe deepEqual usage in structuralSharing is sub-optimal

@1997roylee
Copy link
Contributor

I do think Wagmi is using tanquery as a default.

return useQuery({
    ...query,
    ...options,
    enabled,
    structuralSharing: query.structuralSharing ?? structuralSharing,
  })

@tmm tmm closed this as completed in cb7dd2e Nov 6, 2024
Nichebiche added a commit to Nichebiche/wagmi that referenced this issue Nov 8, 2024
* fix: wevm#4140

* chore: update mipd

* chore: version packages (wevm#4141)

Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>

* feat: `useWatchAsset` hook (wevm#4128)

* feat: `useWatchAsset` hook

* test: add tests

* docs: add docs

* nit: use `getConnectorClient`

* fix: types

* test: fix

* test: fix

* test: fix

* chore: tweaks

* chore: changeset

---------

Co-authored-by: Tom Meagher <[email protected]>

* feat(vue): useBytecode (wevm#4145)

* feat: useBytecode

* docs: tweak the composable example for vue

* docs: use missing code highlighting for the TSQ Vue examples

* chore: fix tests

* chore: changeset

---------

Co-authored-by: Skas Merkushin <[email protected]>

* chore: version packages (wevm#4144)

* chore: version packages

* chore: correct version

---------

Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
Co-authored-by: Tom Meagher <[email protected]>

* chore: update `@safe-global/safe-apps-sdk` (wevm#4146)

chore: update safe

* chore: version packages (wevm#4147)

Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>

* docs: update write-to-contract.md (wevm#4148)

This section talk about minting using tokenId input name but the example code switch to using address as input name

* fix: wevm#4118

* fix: wevm#4150

* chore: format

* close: wevm#4151

* chore: types

* chore: version packages (wevm#4152)

Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>

* FIX: useConnectorClient to be enabled only when connected or reconnecting (wevm#4124)

* update enabled param for useConnectorClient and add a test

* bring updated hook

* change set

* apply review

* chore: version packages (wevm#4155)

Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>

* Update useEstimateGas.md (wevm#4156)

* feat: propagate transport rpc urls to connectors (wevm#4162)

* feat: propagate transport rpc urls to connectors

* tests: update snaps

* chore: tweak changeset

* chore: version packages (wevm#4163)

* chore: version packages

* Update package.json

* Update CHANGELOG.md

* Update version.ts

---------

Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
Co-authored-by: jxom <[email protected]>

* chore: add sponsor

* fix: wevm#4169

* chore: format

* test: chore

* chore: format

* chore: version packages (wevm#4170)

Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>

* test: createConfig restore unconfigured chainId

* chore: bump deps

* chore: bump deps

* chore: version packages (wevm#4182)

Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>

* Update AppKit guide link (wevm#4190)

* fix: wevm#4097

* chore: version packages (wevm#4191)

Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>

* feat: validate internal state for persisted chainId

* chore: version packages (wevm#4192)

Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>

* chore: gg21

* chore: format

* chore: add sponsor

* docs: tweak

* fix: wevm#4196

* chore: version packages (wevm#4197)

Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>

* Fixed the wrong input boxes. (wevm#4199)

Removed input boxes with input of Address and Value.
Added input boxes with input of tokenId.

* docs: tweaks

* chore: update ethereum provider to 2.15.0 (wevm#4208)

* chore: update ethereum provider to 2.15.0

* chore: add changeset file

* Update .changeset/neat-pants-care.md

---------

Co-authored-by: awkweb <[email protected]>

* fix: metaMask dappMetadata add default value (wevm#4203)

* fix: add name for mm connector (wevm#4211)

* fix: metaMask dappMetadata add default value

* chore: changeset

---------

Co-authored-by: rich.eth <[email protected]>

* chore: version packages (wevm#4212)

* Update @walletconnect/ethereum-provider to 2.15.1 (wevm#4213)

* chore: update @walletconnect/ethereum-provider to 2.15.1

* chore: ammend changeset to match convention

* chore: version packages (wevm#4214)

Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>

* chore: remove gc banner

* chore: sponsors

* chore: sponsor

* chore(connectors): bump wc provider

* chore: version packages (wevm#4232)

Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>

* docs: up

* chore: update @walletconnect/ethehreum-provider to version 2.15.3 (wevm#4243)

* chore: updates @walletconnect/ethehreum-provider to version 2.15.3

* Update .changeset/slow-moose-unite.md

---------

Co-authored-by: awkweb <[email protected]>

* test: setup connector

* test: remove

* chore: bump mm sdk (wevm#4251)

* feat: update sdk

* chore: format

* chore: tweaks

* chore: changeset

---------

Co-authored-by: abretonc7s <[email protected]>
Co-authored-by: abretonc7s <[email protected]>
Co-authored-by: abretonc7s <[email protected]>

* chore: version packages (wevm#4250)

Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>

* feat(vue): useWatchContractEvent (wevm#4252)

* feat(vue): useWatchContractEvent

* chore: snaps

* test: boost

* chore: format

* chore: tweaks

* chore: version packages (wevm#4253)

Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>

* fix: guard (get|use)ConnectorClient when reconnecting (wevm#4259)

* feat: connector client reconnection

* chore: changeset

* chore: snaps

* fix(react,vue): useReadContract deployless reads (wevm#4260)

* fix(react,vue): deployless reads

* chore: changeset

* chore: Update ethereum-provider to version 2.16.1 (wevm#4255)

* chore: update @walletconnect/ethereum-provider to 2.16.1

* chore: add changeset

* Update .changeset/empty-falcons-approve.md

---------

Co-authored-by: awkweb <[email protected]>

* chore: version packages (wevm#4261)

Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>

* Add experimental actions export to react package (wevm#4262)

* Add experimental actions export to react package

* chore: add vue entrypoint

* chore: changeset

---------

Co-authored-by: Tom Meagher <[email protected]>

* chore: fix exports

* chore: version packages (wevm#4263)

Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>

* docs: fix typos (wevm#4264)

* fix typo

* fix typos

* fix typos

* fix typo

* fix typo

* feat: update the 'metamask-sdk' package to version '0.28.4' (wevm#4271)

* feat: update metamask-sdk package to version 0.28.4

* chore: changeset

---------

Co-authored-by: Tom Meagher <[email protected]>

* fix: allow detection of hardhat when using bun (wevm#4224)

* fix: allow detection of hardhat when using bun

- added the user agent check now that bun supports it when finding the package manager
- since bun does not have an ls command similar to the others, we check all installed packaged (--all is needed in monorepos) and check it it contains hardhat

* chore: tweaks

---------

Co-authored-by: Tom Meagher <[email protected]>

* Fix the switchChain error encountered when using the "metaMask" connector (wevm#4227)

* fix: metaMask switchChain

* chore: changeset

---------

Co-authored-by: Tom Meagher <[email protected]>

* chore: version packages (wevm#4278)

Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>

* chore: remove duplicate extend in getWalletClient (wevm#4286)

* chore: remove duplicate extend

* chore: changeset

---------

Co-authored-by: Tom Meagher <[email protected]>

* chore: version packages (wevm#4289)

Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>

* fix: guard against missing provider.on

* chore: version packages (wevm#4294)

Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>

* fix: prevent component re-rendering with the same account snapshot (wevm#4229)

* fix: prevent component re-rendering with the same account snapshot

* test: check component re-rendering caused by useSyncExternalStoreWithTracked

* test: update

* chore: changeset

---------

Co-authored-by: Tom Meagher <[email protected]>

* test: boost coverage

* chore: version packages (wevm#4299)

Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>

* Fix race condition in injected.ts (wevm#4207)

* Fix race condition in injected.ts

It can hangs if "once" catches an event with unexpected chainId

* chore: tweaks

---------

Co-authored-by: Tom Meagher <[email protected]>

* chore: version packages (wevm#4300)

Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>

* chore: bump dev deps (wevm#4302)

* chore: bump dev deps

* chore: bump vitest

* chore: format

* chore: bump

* chore: tweaks

---------

Co-authored-by: tmm <[email protected]>

* test: up

* test: cov

* chore: format

* test: skip

* chore: bump deps

* chore: snaps

* chore: fix script

* chore: version packages (wevm#4315)

* docs: tweaks

* feat: bump mm sdk (wevm#4337)

* feat: update metamask sdk and implement connectSign

* feat: cleanup

* feat: cleanup

* sdk 0.29.1

* feat: cleanup

* feat: url default

* feat: prevent breaking changes

* feat: cleanup

* chore: tweaks

* chore: tweaks

* chore: format

* chore: changeset

---------

Co-authored-by: abretonc7s <[email protected]>
Co-authored-by: tmm <[email protected]>

* test: snaps

* chore: version packages (wevm#4342)

Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>

* chore: bump mm (wevm#4345)

* chore: bump mm sdk

* chore: changeset

* chore: version packages (wevm#4346)

Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>

* fix: uniswap wallet trying to make itself look like MetaMask (wevm#4336)

* fix: uniswap wallet trying to make itself look like MetaMask

* chore: changeset

---------

Co-authored-by: Tom Meagher <[email protected]>

* test: mock reconnect

* chore: format

* chore: viem tweaks

* chore: up viem

* chore: up snaps

* fix: MetaMask disconnecting during the connection process. (wevm#4347)

* fix: disconnection during the connection process.

* fix: disconnection during the connection process.

* chore: tweaks

* chore: changeset

* chore: comment

---------

Co-authored-by: Tom Meagher <[email protected]>

* chore: add codeowners

* feat: bump metamask 0.30.0 (wevm#4350)

* feat: bump metamask 0.30.0

* feat: add changeset

* Update .changeset/tasty-clouds-kiss.md

Co-authored-by: awkweb <[email protected]>

* Update .changeset/tasty-clouds-kiss.md

---------

Co-authored-by: awkweb <[email protected]>

* chore: version packages (wevm#4348)

* feat(connectors): filter mipd by connector rdns (wevm#4343)

* feat(connectors): filter mipd by connector rdns

* feat: add connect listeners

* test: boost coverage

* test(core): eip 6963 announce

* test: tweaks

* chore: format

* chore: changeset

* feat: works with ssr flag

* chore: changeset

* chore: tweaks

---------

Co-authored-by: tmm <[email protected]>

* chore: skip

* chore: version packages (wevm#4354)

* chore: version packages

* chore: fix version

---------

Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
Co-authored-by: Tom Meagher <[email protected]>

* chore: up version

* chore(core): bump internal deps (wevm#4349)

chore: bump deps

* feat(core): mock defaultConnected

* chore: version packages (wevm#4355)

Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>

* test: tweak

* chore: clean up deps (wevm#4357)

* chore: clean up deps

* chore: types

* chore: changeset

* chore: bump deps

* chore: version packages (wevm#4359)

Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>

* chore: boost coverage

* ci: protected push

* feat: export type

* chore: version packages (wevm#4361)

Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>

* fix: MetaMask readonlyRPCMap type (wevm#4362)

* fix: MetaMask readonlyRPCMap type

* chore: tweaks

* chore: changeset

---------

Co-authored-by: Tom Meagher <[email protected]>

* chore: version packages (wevm#4363)

Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>

* test: up

* chore: add sponsor

* docs: bump deps

* chore(cli): bump chokidar (wevm#4370)

* chore: bump chokidar

* chore: fmt

* chore: changeset

---------

Co-authored-by: Tom Meagher <[email protected]>

* chore: version packages (wevm#4378)

Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>

* chore: add sponsor

* fix: Safe connector not working in some Vite apps (wevm#4371)

* Fix Safe connector not working in some Vite apps

* Fix Safe connector not working in some Vite apps

* chore: tweaks

---------

Co-authored-by: Tom Meagher <[email protected]>

* fix: waitForTransactionReceipt proper eth_call usage (wevm#4339)

* fix: waitForTransactionReceipt proper eth_call usage

* chore: tweaks

---------

Co-authored-by: Tom Meagher <[email protected]>

* docs(cli/create-wagmi): template selection (wevm#4356)

* docs(cli/create-wagmi): template selection

Explain how to select the template when you don't specify `--template` or `-t`, and what each option means.

* docs: up

---------

Co-authored-by: Tom Meagher <[email protected]>

* chore: snaps

* fix: wevm#4353

* docs: close wevm#4344

* chore: snaps

* chore: version packages (wevm#4380)

Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>

* docs: rpc

* fix: wevm#4310

* fix: wevm#4367

* chore: version packages (wevm#4383)

Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>

* chore: pnpm catalogs

* chore: tweaks

* chore: bump dependencies (wevm#4385)

* chore: bump dependencies

* Update .changeset/four-pens-collect.md

---------

Co-authored-by: Jake <=>
Co-authored-by: awkweb <[email protected]>

* chore: fix types

* chore: version packages (wevm#4387)

Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>

* chore: snaps

* fix: injected connector throws error after switching to a chain that was just added via `'wallet_addEthereumChain'`. (wevm#4311)

* fix: injected connector throwing error after switching to a chain that was just added via `'wallet_addEthereumChain'`.

* chore: changeset

* chore: tweaks

---------

Co-authored-by: Tom Meagher <[email protected]>

* test: tweaks

* chore: version packages (wevm#4388)

Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>

---------

Co-authored-by: Tom Meagher <[email protected]>
Co-authored-by: jxom <[email protected]>
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
Co-authored-by: Vladyslav Dalechyn <[email protected]>
Co-authored-by: Skas Merkushin <[email protected]>
Co-authored-by: Samson Adesanoye <[email protected]>
Co-authored-by: tmm <[email protected]>
Co-authored-by: t0rbik <[email protected]>
Co-authored-by: wy <[email protected]>
Co-authored-by: Radek Sienkiewicz <[email protected]>
Co-authored-by: Vedant-asati <[email protected]>
Co-authored-by: tomiir <[email protected]>
Co-authored-by: rich.eth <[email protected]>
Co-authored-by: rich.eth <[email protected]>
Co-authored-by: abretonc7s <[email protected]>
Co-authored-by: abretonc7s <[email protected]>
Co-authored-by: abretonc7s <[email protected]>
Co-authored-by: Łukasz Stankiewicz <[email protected]>
Co-authored-by: omahs <[email protected]>
Co-authored-by: Omri Dan <[email protected]>
Co-authored-by: Roderik van der Veer <[email protected]>
Co-authored-by: 闲尘 <[email protected]>
Co-authored-by: Kevin Ingersoll <[email protected]>
Co-authored-by: Weil Liao <[email protected]>
Co-authored-by: Dmitry Blues <[email protected]>
Co-authored-by: Edouard Bougon <[email protected]>
Co-authored-by: v1rtl <[email protected]>
Co-authored-by: Ice and dust <[email protected]>
Co-authored-by: insomnia.exe <[email protected]>
Co-authored-by: Ori Pomerantz <[email protected]>
Co-authored-by: cb-jake <[email protected]>
Co-authored-by: Eugene Chybisov <[email protected]>
Copy link
Contributor

This issue has been locked since it has been closed for more than 14 days.

If you found a concrete bug or regression related to it, please open a new bug report with a reproduction against the latest Wagmi version. If you have any questions or comments you can create a new discussion thread.

@github-actions github-actions bot locked as resolved and limited conversation to collaborators Nov 21, 2024
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants
@Rubilmax @1997roylee and others