Skip to content

refactor(connect,utils): replace web3 with viem [1/8]#766

Closed
pahor167 wants to merge 1 commit into
masterfrom
pahor/viem-A-connect-utils
Closed

refactor(connect,utils): replace web3 with viem [1/8]#766
pahor167 wants to merge 1 commit into
masterfrom
pahor/viem-A-connect-utils

Conversation

@pahor167

@pahor167 pahor167 commented Apr 1, 2026

Copy link
Copy Markdown
Contributor

Stack

A β†’ B β†’ C β†’ D1 β†’ D2 β†’ D3 β†’ D4 β†’ D5 (CI)

Changes

  • Delete rpc-caller.ts, celo-transaction-object.ts, tx-result.ts
  • Add contract-types.ts (CeloContract<TAbi>), viem-abi-coder.ts, wallet-adapter.ts
  • Replace web3 ABI types with viem-native equivalents
  • Rewrite connection.ts internals to use viem client
  • Remove BigNumber/bn.js from utils/ β€” native bigint in solidity.ts, signatureUtils.ts, ecies.ts
  • Remove @ethereumjs/* dependencies
  • Patch buffer-equal-constant-time for Node 25 compatibility
  • Drop web3 from yarn.lock

Part of the web3 β†’ viem migration. No CI requirement on this PR.


PR-Codex overview

This PR focuses on refactoring the codebase to improve type safety, remove deprecated features, and transition from web3 to viem for contract interactions. It also enhances logging and adjusts transaction handling for better performance and clarity.

Detailed summary

  • Removed several deprecated files and functions related to web3.
  • Introduced viem for contract interaction, replacing web3 methods.
  • Enhanced type safety across the codebase, eliminating any types.
  • Updated transaction parameters handling to use viem conventions.
  • Improved logging by replacing console.info with debug.
  • Added declarationMap to TypeScript configurations for better debugging.
  • Updated JSON files to reflect changes in transaction handling and dependencies.
  • Refactored tests to align with the new viem implementation and remove web3 dependencies.

The following files were skipped due to too many changes: packages/sdk/connect/src/types.ts, packages/sdk/connect/src/utils/formatter.ts, packages/sdk/utils/src/signatureUtils.ts, packages/sdk/connect/src/celo-provider.ts, specs/standardize-viem-clients.md, packages/sdk/connect/src/connection.ts, yarn.lock

✨ Ask PR-Codex anything about this PR by commenting with /codex {your question}

- Delete rpc-caller.ts, celo-transaction-object.ts, tx-result.ts, promi-event
- Add contract-types.ts (CeloContract<TAbi>), viem-abi-coder.ts, wallet-adapter.ts
- Replace web3 ABI types with viem-native equivalents in abi-types.ts
- Rewrite connection.ts internals to use viem client
- Remove BigNumber/bn.js from utils β€” use native bigint in solidity.ts, signatureUtils.ts, ecies.ts
- Remove @ethereumjs/* dependencies
- Patch buffer-equal-constant-time for Node 25 compatibility
- Drop web3 from yarn.lock
@pahor167 pahor167 requested a review from a team as a code owner April 1, 2026 09:07
@changeset-bot

changeset-bot Bot commented Apr 1, 2026

Copy link
Copy Markdown

πŸ¦‹ Changeset detected

Latest commit: 05fceb7

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 15 packages
Name Type
@celo/wallet-ledger Patch
@celo/celocli Major
@celo/connect Major
@celo/contractkit Major
@celo/dev-utils Minor
@celo/explorer Patch
@celo/governance Patch
@celo/transactions-uri Patch
@celo/wallet-base Patch
@celo/wallet-hsm-aws Patch
@celo/wallet-hsm-azure Patch
@celo/wallet-hsm-gcp Patch
@celo/wallet-local Patch
@celo/wallet-remote Patch
@celo/wallet-hsm Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

πŸ’‘ Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 05fceb7606

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with πŸ‘.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".


debugPayload('%O', payload)
request: EIP1193RequestFn = async ({ method, params }) => {
const safeParams: any[] = Array.isArray(params) ? params : params != null ? [params] : []

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Preserve object-form params when forwarding requests

The new request implementation always coerces non-array params into an array ({...} becomes [{...}]), but EIP-1193 allows object-form params and some RPC methods require that exact shape. In those cases (for example wallet-management methods), forwarding through CeloProvider will send malformed params and the upstream provider will reject the call, breaking consumers that call connection.currentProvider.request(...) with object params.

Useful? React with πŸ‘Β / πŸ‘Ž.

Comment on lines +39 to +40
const isOverrides =
lastArg != null && typeof lastArg === 'object' && !Array.isArray(lastArg)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Distinguish tuple args from tx overrides in write proxy

The proxy assumes any last argument that is an object is a transaction overrides object, but viem tuple/struct arguments are also plain objects. For contract write methods whose final ABI argument is a tuple, this path can incorrectly treat that tuple as overrides, injecting/removing fields like account/chain on user data and skipping proper overrides placement, which can cause write calls to fail or send with unintended account handling.

Useful? React with πŸ‘Β / πŸ‘Ž.

@palango

palango commented Apr 20, 2026

Copy link
Copy Markdown
Contributor

Code review

Found 1 issue:

  1. signedMessageToPublicKey (public export) no longer normalises v and will throw on v ∈ {0, 1}. The old implementation passed v to ecrecover, which accepted both the EIP-155 form (27/28) and the pre-EIP-155 recovery-id form (0/1). The new code does addRecoveryBit(v - 27) directly, so a caller passing v = 0 or v = 1 (a common convention for Ledger / modern signer libraries) now ends up invoking addRecoveryBit(-27) / addRecoveryBit(-26), which @noble/curves rejects. Internal callers are unaffected because parseSignatureAsRsv / parseSignatureAsVrs still do if (v < 27) v += 27, but external consumers of SignatureUtils.signedMessageToPublicKey lose behaviour that was previously supported.

export function signedMessageToPublicKey(message: string, v: number, r: string, s: string) {
const msgHash = hexToBytes(message as `0x${string}`)
const signature = new secp256k1.Signature(BigInt(r), BigInt(s)).addRecoveryBit(v - 27)
const pubKey = signature.recoverPublicKey(msgHash).toRawBytes(false)
// Return raw 64-byte key (without 04 prefix) for on-chain compatibility
return bytesToHex(pubKey.subarray(1))
}

πŸ€– Generated with Claude Code

- If this code review was useful, please react with πŸ‘. Otherwise, react with πŸ‘Ž.

pahor167 added a commit that referenced this pull request Jun 15, 2026
…es (#780)

## Summary

Combined branch containing the full web3 β†’ viem migration (the union of
the stacked PRs #766–#773) plus 24 commits of review fixes from a deep
multi-agent audit of the cumulative diff (~350 files).

### Migration (from the original stack)
- `@celo/connect`, `@celo/utils`: web3 replaced with viem-native
primitives (#766)
- `@celo/contractkit`: viem-native contract interaction across all
wrappers (#767)
- `@celo/explorer`, `@celo/governance`, wallets, dev-utils (#768)
- `@celo/celocli`: all command groups migrated (#769–#773)

### Review fixes on top (highlights, 38 findings fixed)

Funds/correctness critical:
- wallet-base: tx quantities above 2^53 were silently truncated when
hex-encoding (`1 CELO + 1 wei` signed as exactly 1 CELO); now
BigInt-backed with a regression test
- connect: `defaultFeeCurrency` was silently ignored for every
`contract.write`; dynamic chain now carries the Celo
serializers/formatters so CIP-64 serializes correctly
- contractkit: IPC provider hung forever (parsed only on socket `end`);
ws:// / wss:// node URLs fell through to the HTTP provider; HTTP error
statuses resolved `undefined`
- contractkit: `setAccount` without proof-of-possession always threw
(`'0x0'` as bytes32); `Attestations.getPendingWithdrawals` parameter
order restored to match the contract
- cli: `releasecelo:admin-revoke` lost the `{from: voteSigner}` override
β†’ revokes reverted with an authorized vote signer
- connect: fee-math radix bug inflated `maxFeePerGas` for string inputs

High:
- tuple-blind ABI signatures produced wrong selectors/topic hashes (ABI
enrichment, `methodIds`, log-explorer event matching)
- `BaseWrapper.getPastEvents` swallowed RPC errors as "no events";
unknown event names now throw (web3 parity)
- Election historical `blockNumber` queries were silently ignored (voter
rewards at past epochs)
- governance CLI commands no longer displayed on-chain event
confirmations (ProposalExecuted / HotfixExecuted / HotfixApproved /
Deposit) β€” restored, including the silently-dropped test snapshots
- `isValidChecksumAddress` accepted all-lowercase addresses; sourcify
proxy implementation address checksummed again
- BigInt-safe JSON-RPC serialization in production providers

Plus test-semantics restorations (weakened assertions,
mocked-method-under-test), test-infra robustness (receipt waits, strict
`evm_revert`), changeset corrections (contractkit correctly marked major
with full breaking-change list), and documentation of behavior changes.

Full audit trail (62 findings: 38 fixed, 12 refuted with evidence, the
rest classified pre-existing/wontfix) lives in
`.omc/ralph/pr-review-progress.md` on the working machine; findings are
also traceable through the individual commit messages.

## Test plan
- [x] Full workspace build green (all 23 packages)
- [x] Full test suite: all packages green locally except known env-flaky
timeouts under full parallel load (actions/keystores) and a pre-existing
`election:activate --wait` snapshot-order flake that reproduces on the
unmodified stack HEAD
- [x] Anvil-backed suites green: contractkit 258/258, celocli 337 passed
- [x] Live smoke tests: IPC provider against `anvil --ipc`, WebSocket
provider against `wss://forno.celo.org/ws`
- [ ] CI green on this PR

---------

Co-authored-by: Pavel Hornak <pavel.hornak@clabs.co>
Co-authored-by: Paul Lange <palango@gmx.de>
@pahor167 pahor167 closed this Jun 15, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants