Skip to content

Replace web3 with viem 2#761

Open
pahor167 wants to merge 166 commits intomasterfrom
pahor/removeViem
Open

Replace web3 with viem 2#761
pahor167 wants to merge 166 commits intomasterfrom
pahor/removeViem

Conversation

@pahor167
Copy link
Contributor

Removal of web3 and replacing with viem

Pavel Hornak and others added 30 commits February 8, 2026 00:23
Use block timestamp instead of Date.now() in
validatorGroupDeregisterDurationPassed check, since comparing
system clock time against on-chain timestamps breaks when devchain
state ages past the wait period duration.

Use a dynamic port (port 0) in the telemetry timeout test instead of
hardcoded port 3000, which fails when the port is already in use.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
…n tool replacing the VS Code extensions recommendations). It's not from my work. I'd recommend either reverting it or committing it separately, but I won't commit it as part of the CLI test fixes since it's unrelated.

Would you like me to revert this file, or leave it as-is?
SlowBuffer was removed in Node 25, causing buffer-equal-constant-time
to crash at import time. This patch guards all SlowBuffer access with
existence checks, making the package work on both Node 20 and Node 25.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
…llel execution

The @viem/anvil library defaults to a 10s startTimeout, which is
insufficient when many Anvil instances start concurrently (e.g. when
running yarn test from the repo root). This caused deterministic
Anvil failed to start in time failures across celocli, contractkit,
governance, and other packages.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Phase 1 - @celo/utils:
- Replace web3-utils imports with viem equivalents
- Replace web3-eth-abi with viem encodeAbiParameters
- Remove web3-utils and web3-eth-abi deps, add viem

Phase 2 - @celo/connect:
- Replace Web3 constructor with Provider interface
- Define standalone types for CeloTx, CeloTxReceipt, etc.
- Replace web3.eth.* calls with direct RPC calls
- Implement viemAbiCoder to replace web3.eth.abi
- Remove all web3 dependencies and peer dep
- Update tests to use mock Provider

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Add a web3-compatible shim layer on Connection class so that existing
code using connection.web3.eth.Contract, connection.web3.utils, etc.
continues to work after web3 was removed from @celo/connect. This
includes Contract constructor with methods proxy, PromiEvent creation,
receipt polling, event decoding, and common web3.utils functions.

Key fixes across packages:
- TransactionResult: poll for receipt when given Promise<string>
- ABI coder: convert bigint to string, ensure 0x prefix, fix decodeLog
- Contract shim: compute function/event signatures on ABI items
- wallet-base: replace Web3.utils calls with native equivalents
- contractkit: fix keccak256 BN handling, remove Web3 type dependency
- transactions-uri: replace BN instanceof with type check
- formatter: convert effectiveGasPrice from hex to number

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Remove web3/web3-*/web3-eth-abi/web3-core-helpers from contractkit,
cli, dev-utils, transactions-uri, explorer, and all wallet packages.

Production code changes:
- contractkit/setupForKits.ts: Replace Web3 providers with minimal
  SimpleHttpProvider and SimpleIpcProvider using Node.js http/https/net
- contractkit/kit.ts, mini-kit.ts, proxy.ts: Remove Web3 type imports
- cli/base.ts: Use getWeb3ForKit instead of new Web3(), return
  kit.web3 (shim) from getWeb3() for full API compatibility
- cli/utils/safe.ts, commands/governance/approve.ts: Remove Web3 types
- dev-utils/test-utils.ts: Inline SimpleHttpProvider, use Connection
- dev-utils/anvil-test.ts, chain-setup.ts, contracts.ts: Remove Web3
- transactions-uri/tx-uri.ts: Use viemAbiCoder from @celo/connect

Web3 shim enhancements (connection.ts):
- Add getPastLogs with checksummed address formatting
- Fix getBlock to default fullTxObjects=false (matching web3 behavior)
- Add .host property to SimpleHttpProvider for backward compat

Test file changes (~100 files):
- Remove all `import Web3 from 'web3'` statements
- Replace `web3: Web3` type annotations with `web3: any`
- Replace Web3.utils.toWei with parseEther or inlined values
- Replace Web3.utils.toBN with BigInt
- Replace new Web3() with Connection or kit helpers

Package.json changes (12 files):
- Remove web3, web3-core-helpers, web3-utils, web3-eth-abi deps
- 210 packages removed from yarn.lock

All 98 CLI test suites pass (337 tests), all 57 connect tests pass.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Remove web3 and web3-utils version pinning from resolutions since
no package in the monorepo depends on web3 anymore.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
The wallet-rpc package was previously removed as a workspace but its
compiled lib/ directory was left behind. It has no package.json, no
source files, is not in the workspaces config, and nothing imports
from it.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Remove only the compiled test files (rpc-wallet.test.js and
test-utils/ganache.*) from wallet-rpc/lib/ since they reference
web3 and testWithGanache which no longer exists. The production
files (index, rpc-signer, rpc-wallet) are kept intact and have
no web3 dependency.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Replace untyped `web3: any` parameters with strongly-typed `Web3` interface
from @celo/connect and rename the parameter from `web3` to `client` across
all test files and utility functions for clarity.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Conflicts resolved:
- approve.test.ts/approve.ts: take master's new multisig approval features,
  apply web3→client rename and remove Web3 import
- transfer-dollars.test.ts: take master's cUSD→USDm rename, keep client param
- checks.ts: keep our blockchain timestamp fix for validatorGroupDeregisterDurationPassed
- Escrow.test.ts: take master's cUSD→USDm rename, keep client param
- SortedOracles.test.ts: take master's cUSD→USDm/cEUR→EURm/cREAL→BRLm, keep client param
- yarn.lock: regenerated from master's lockfile
- contracts.ts: apply web3→client rename (missed in prior commit)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
- Fix deploy().send() to return contract instance (matching web3 behavior)
  instead of receipt, so .options.address works for contract deployment
- Add eth.accounts.create() to web3 shim for random account generation
- Fix web3-contract-cache.test.ts import path (was incorrectly renamed)
- Fix SortedOracles.test.ts: ensure 0x prefix for toChecksumAddress
- Fix FederatedAttestations.test.ts: cast eth.accounts access

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
- Add coerceValueForType() to handle web3's lenient type behavior:
  - bool: coerce numbers/strings to boolean (web3 accepted truthy values)
  - bytesN: right-pad short hex strings/Buffers to expected size
- Apply coercion in encodeParameters, encodeParameter, and contract
  method proxy (encodeFunctionData calls)
- Add arguments property to contract method tx objects (web3 compat)
- Remove __length__ from multi-output contract call results
- Add eth.accounts.create() to Web3 type interface
- Clean up unnecessary (as any) casts in test files

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
- Add eth.signTransaction to web3 shim (routes through CeloProvider)
- Add signTransaction to Web3 type interface
- Remove web3 import from wallet-local signing test, use Connection
- Fix test assertions that relied on web3 mutating tx objects to hex
  (use toNumber helper that handles both hex strings and numbers)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Fixes biome lint/complexity/useLiteralKeys errors.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
- Remove @celo/abis/web3/ICeloVersionedContract import from BaseWrapper.ts
  (the .d.ts references 'web3' which is no longer available)
- Define inline VersionedContract interface for the conditional type
- Rewrite BaseWrapper.test.ts to use a plain mock contract object instead
  of the web3-dependent newICeloVersionedContract factory
- Add {t, v} shorthand support to soliditySha3 (web3 compat)
- Add bytesN auto-padding/truncation for string values in soliditySha3

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
…Transaction

- hashMessage was using viem's toBytes() which decodes hex strings as bytes,
  but web3's soliditySha3({type:'string'}) always treated input as UTF-8.
  Use stringToBytes() instead to match the original behavior.
- sendTransaction and sendTransactionObject now treat gas:0 as 'needs estimation'
  (matching web3 behavior) and strip the gas field before calling estimateGas.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
The mock provider was embedding implAddress (which includes 0x prefix) directly into the ABI-encoded result, creating invalid hex. Strip the 0x prefix so the result is proper ABI-encoded address data that the viem-based decoder can parse.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Replace ~80+ instances of any with proper types across 35 files. Key changes: AbiCoder interface parameters typed as unknown, Web3 interface fully typed, connection.ts typed SolidityValue/AbiInput/Provider unions, types.ts typed CeloTx.common/EventLog.raw.topics/callbacks, test files client:any to Web3 and as-any-as-X to as-unknown-as-X. Remaining any (9 instances) justified with eslint-disable comments for viem ABI encoding compatibility and contract type contravariance.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Pavel Hornak and others added 30 commits February 27, 2026 11:17
…/connect)

Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-opencode)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-opencode)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
…emoval

- Add WeakMap in BaseWrapper to track contract-to-connection mapping for proxyCallGenericImpl
- Update kit.test.ts to mock sendTransactionViaProvider instead of txo.send()
- Fix GoldToken, Governance, Reserve, SortedOracles test mocks for viem-native APIs
- Update CLI governance test snapshots (removed decodeReceiptEvents output)
- Fix contracts.test.ts to mock viemClient getter
… with viem decodeFunctionResult

Replace viemAbiCoder.decodeParameters with viem native decodeFunctionResult in
viem-tx-object.ts, constrain proxyCall PreParsedOutput to ContractFunctionReturnType,
and replace all (res: any) output parsers across 24 wrapper files with ABI-derived types.
Update CLI test snapshots for bigint return values.
…i>, add coercion helpers and .read type tests
…s (Freezer, ScoreManager, OdisPayments, FeeCurrencyDirectory, EpochRewards, Escrow, FederatedAttestations, Reserve)
…s (Accounts, Attestations, Election, EpochManager, LockedGold, MultiSig, SortedOracles)
…s (Governance, Validators, ReleaseGold, StableToken, FeeHandler)
Enable VS Code cmd+click to navigate to .ts source files instead of
.d.ts declaration files across inter-package imports by generating
.d.ts.map source map files alongside declarations.
Ultraworked with Sisyphus

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
Ultraworked with Sisyphus

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
Ultraworked with Sisyphus

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
Ultraworked with Sisyphus

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
…unctionData to BaseWrapper

- Add sendTx(), sendTxUnchecked(), encodeFunctionData() to BaseWrapper as viem-native replacements for buildTx/buildTxUnchecked
- Add connection.callContract() for read operations (replaces createViemTxObject().call() pattern)
- Migrate proxyCallGenericImpl to use connection.callContract()
- Migrate AbstractFeeCurrencyWrapper reads to connection.callContract()
- Migrate address-registry.ts and sourcify.ts reads to connection.callContract()
…eturn tx hash)

Replace buildTx/CeloTransactionObject with sendTx returning Promise<`0x${string}`>
across all contractkit wrappers. Methods now send transactions eagerly and return
the tx hash directly, matching viem's writeContract pattern.

- 20 wrapper files: return types changed from CeloTransactionObject to Promise<`0x${string}`>
- Private helpers accept (args[], txParams?) pattern for txParams passthrough
- Array-returning methods (Election.activate/revoke, LockedGold.relock) send sequentially
- test-utils/utils.ts updated to match new eager-send API
…ata in ProposalBuilder and chain-setup

- ProposalBuilder: fromWeb3tx→fromEncodedTx, addWeb3Tx→addEncodedTx, removed addTx
- buildCallToCoreContract uses viem encodeFunctionData + coerceArgsForAbi
- proxy.ts setImplementationOnProxy returns encoded calldata string
- dev-utils chain-setup.ts uses encodeFunctionData + connection.sendTransaction
- Removed CeloTxObject, CeloTransactionObject, createViemTxObject imports
…I commands

Migrate ~57 CLI command files from displaySendTx (CeloTransactionObject-based)
to displayViemTx (viem-native, takes Promise<Address> + PublicCeloClient).

- All command files now use this.getPublicClient() + displayViemTx
- txParams (from, value) moved to wrapper method last arg
- Array-returning methods (relock, activate, revoke) handled with Promise.resolve
- safe.ts updated to use encodeFunctionData
- governance/approve.ts and propose.ts updated for new API
- displaySendTx and innerDisplaySendTx removed from cli.ts
- CLI test-utils partially updated (chain-setup.ts wrapper calls)
…, and network/contracts

Replace all remaining createViemTxObject usages in CLI with viem-native patterns:
- DKG commands: encodeFunctionData + connection.sendTransaction for sends,
  encodeFunctionData + viemClient.call + decodeFunctionResult for reads
- test-utils (chain-setup, multisigUtils, release-gold): same patterns
- network/contracts.ts: viem-native read calls
- Test files: updated to match new patterns
- Zero createViemTxObject remaining in packages/cli/
…ject, createViemTxObject

Delete celo-transaction-object.ts and viem-tx-object.ts entirely.
Remove CeloTxObject interface from types.ts, sendTransactionObject from
connection.ts and kit.ts. Remove buildTx, buildTxUnchecked,
proxyCallGeneric, proxyCallGenericImpl from BaseWrapper.ts. Replace
proxyCallGeneric in CeloTokenWrapper and Erc20Wrapper with
connection.callContract. Update all contractkit test files to use
wrapper methods directly instead of .txo/.sendAndWaitForReceipt.
Remove dead requireCall from CLI require.ts. Add viem dependency to
governance package.json for encodeFunctionData imports.
…x sendTx waitReceipt

- Update 15 contractkit test files to remove .sendAndWaitForReceipt()/.send()/.txo
- Update 3 CLI governance test files (show, approve, propose) to new patterns
- Fix sendTx/sendTxUnchecked in BaseWrapper to await result.waitReceipt() before returning hash
- Clean up JSDoc references to CeloTransactionObject in Accounts.ts and ReleaseGold.ts
- Remove unused variables in SortedOracles.test.ts
- Fix type casts in propose.test.ts for viem encodeFunctionData
…oinbase, getBlockHeader, sendSignedTransaction)
…r, @ethereumjs/util, deprecated aliases

- Remove bn.js/@types/bn.js from contractkit, transactions-uri, utils, cryptographic-utils
- Replace BN type with string in Accounts.ts keccak256 method
- Remove deprecated CeloProvider methods (addAccount, removeAccount, getAccounts)
- Remove deprecated ViemContract type alias
- Remove tslint:disable comment and stale web3 references
- Replace BigNumber with native BigInt in formatter.ts and tx-params-normalizer.ts
- Remove bignumber.js dependency from @celo/connect
- Replace bufferToHex from @ethereumjs/util with viem toHex
- Remove @ethereumjs/util dependency from @celo/connect
- Modernize BaseWrapper.getPastEvents to use viem client.getLogs
…act to .read, remove deprecated exports

- Remove dead Connection methods: keccak256, hexToAscii, isListening, isSyncing, nonce
- Update callers: Accounts uses viem keccak256, Reserve uses viem hexToString, tx-params-normalizer uses getTransactionCount
- Remove kit.isListening() and kit.isSyncing() pass-throughs
- Migrate callContract() to .read pattern in Erc20Wrapper, CeloTokenWrapper, AbstractFeeCurrencyWrapper
- Remove deprecated: gasPriceSuggestionMultiplier, authorizeValidatorSignerAndBls (Accounts+ReleaseGold), getCurrentValidatorSigners, getValidatorSigners (Election)
…on, and fix CLI getHash/waitReceipt

- Remove callContract() from Connection: migrate 3 remaining callers (address-registry, sourcify, EpochManager.test) to .read pattern
- Remove AbiCoder interface from abi-types.ts
- Remove viemAbiCoder singleton from viem-abi-coder.ts (keep utility functions)
- Remove getAbiCoder() from Connection class
- Migrate all 13+ abiCoder callers to direct viem imports:
  - encodeFunctionSignature → toFunctionSelector/toFunctionHash
  - encodeFunctionCall → encodeFunctionData
  - encodeParameters → encodeAbiParameters
  - decodeParameters → decodeParametersToObject (new helper in abi-utils)
  - decodeLog → decodeEventLog
  - decodeParameter → decodeAbiParameters
- Add decodeParametersToObject helper for callers needing DecodedParamsObject shape
- Refactor decodeStringParameter to use viem directly (no AbiCoder param)
- Fix pre-existing CLI build errors: replace .getHash()/.waitReceipt() with direct hash usage and waitForTransactionReceipt
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.

3 participants