Skip to content

refactor: migrate from Web3.js to Ethers.js#24

Open
yogeshkumawat2027 wants to merge 1 commit intoDjedAlliance:mainfrom
yogeshkumawat2027:refactor/web3-to-ethers
Open

refactor: migrate from Web3.js to Ethers.js#24
yogeshkumawat2027 wants to merge 1 commit intoDjedAlliance:mainfrom
yogeshkumawat2027:refactor/web3-to-ethers

Conversation

@yogeshkumawat2027
Copy link

@yogeshkumawat2027 yogeshkumawat2027 commented Dec 13, 2025

Overview

This PR migrates the SDK from Web3.js to Ethers.js, providing a more modern, lightweight, and feature-rich blockchain interaction library.

Changes

djed-sdk

  • Imports: Replaced all Web3.js imports with ethers.js across all modules

  • Provider Setup (src/web3.js):

    • Changed from new Web3() to ethers.BrowserProvider(window.ethereum)
    • Maintains backward compatibility with getWeb3() function
  • Contract Interactions:

    • Replaced new web3.eth.Contract() with ethers.Contract
    • Updated all contract method calls from .methods[fn]().call() to contract[fn]()
    • Changed method encoding from .methods.fn().encodeABI() to .interface.encodeFunctionData()
  • Core Files Updated:

    • src/djed/djed.js: Contract instantiation with ethers
    • src/djed/system.js: Balance queries using provider.getBalance()
    • src/djed/stableCoin.js: Transaction encoding with ethers interface
    • src/djed/reserveCoin.js: Transaction encoding with ethers interface
    • src/djed/tradeUtils.js: TX receipt verification with provider.getTransactionReceipt()
    • src/oracle/oracle.js: Oracle contract setup with ethers

stablepay-sdk

  • Integration (src/core/Transaction.js):
    • Updated to use ethers provider instead of Web3 instance
    • Changed contract address properties from ._address to .target
    • Updated initialization to work with new parameter names

Migration Guide for Consumers

Function Signature Changes

Only parameter names have changed; all public API remains the same:

// Before
const djed = getDjedContract(web3, DJED_ADDRESS);
const { stableCoin, reserveCoin } = await getCoinContracts(djed, web3);
const { scDecimals, rcDecimals } = await getDecimals(stableCoin, reserveCoin);
const accountDetails = await getAccountDetails(web3, account, stableCoin, reserveCoin, scDecimals, rcDecimals);

// After
const djed = getDjedContract(provider, DJED_ADDRESS);
const { stableCoin, reserveCoin } = await getCoinContracts(djed, provider);
const { scDecimals, rcDecimals } = await getDecimals(stableCoin, reserveCoin);
const accountDetails = await getAccountDetails(provider, account, stableCoin, reserveCoin, scDecimals, rcDecimals);

<!-- This is an auto-generated comment: release notes by coderabbit.ai -->

## Summary by CodeRabbit

* **Refactor**
  * Updated SDK to align blockchain provider handling with modern standards. Function signatures now accept provider parameter for contract interactions instead of previous approach.

<sub>✏️ Tip: You can customize this high-level summary in your review settings.</sub>

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

@coderabbitai
Copy link

coderabbitai bot commented Dec 13, 2025

Walkthrough

This pull request migrates the SDK from web3.js to ethers.js across multiple modules, replacing web3-based contract instantiation with ethers-based providers, updating contract call encoding mechanisms, and adjusting parameter signatures while maintaining overall API compatibility.

Changes

Cohort / File(s) Summary
Provider & Contract Instantiation
djed-sdk/src/djed/djed.js, djed-sdk/src/oracle/oracle.js, djed-sdk/src/web3.js
Updated getDjedContract, getCoinContracts, and getOracleContract to accept ethers providers instead of web3 instances; getWeb3 now returns ethers.BrowserProvider from window.ethereum; removed msgSender parameter from oracle contract factory.
Contract Encoding Migration
djed-sdk/src/djed/reserveCoin.js, djed-sdk/src/djed/stableCoin.js
Replaced web3-style contract.methods[...].encodeABI() with ethers-style contract.interface.encodeFunctionData(...) for buyReserveCoins, sellReserveCoins, buyStableCoins, and sellStableCoins.
Provider Parameter Updates
djed-sdk/src/djed/system.js, djed-sdk/src/djed/tradeUtils.js
Renamed first parameter from web3 to provider in getAccountDetails and verifyTx; updated internal method calls to use provider equivalents (getBalance, getTransactionReceipt).
Helper & Transaction Support
djed-sdk/src/helpers.js, stablepay-sdk/src/core/Transaction.js
Updated contract call dispatch pattern; changed transaction value and gasLimit to use BigInt (500000n); integrated ethers provider throughout Transaction initialization and contract lookups; updated oracle address extraction from ._address to .target.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

  • Verify all provider parameter replacements are consistent across call sites
  • Confirm encodeFunctionData arguments match the original encodeABI payloads exactly
  • Validate BigInt handling in transaction construction (value/gasLimit conversions)
  • Check that .target property access on ethers contracts works as expected for address extraction
  • Ensure contract instantiation patterns align with ethers.js API and maintain compatibility with signer expectations

Possibly related PRs

  • StablePay#12: Updates stablepay-sdk/src/core/Transaction.js to wire djed-sdk's buyScTx and migrate provider usage, directly affected by this migration.

Poem

🐰 From Web3's Web we've hopped along,
To ethers bright, our new swan song!
Providers dance, encodings glow,
BigInts and contracts steal the show! ✨

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The pull request title accurately and specifically describes the main objective of the changeset: migrating from Web3.js to Ethers.js across the SDK codebase.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
djed-sdk/src/web3.js (1)

1-17: Remove the unused BLOCKCHAIN_URI parameter or document its deprecation.

The function accepts BLOCKCHAIN_URI but never uses it; the provider is determined solely by window.ethereum. Callers in stablepay-sdk pass this.networkUri but the function ignores it. Either:

  1. Remove the parameter (cleaner API, but breaking)
  2. Document that it's ignored for backward compatibility

Regarding the return type change: getWeb3 now returns ethers.BrowserProvider instead of a Web3 instance. While technically different, this is not a breaking change in practice since callers treat the returned provider generically (passing it to helper functions like getDjedContract, getCoinContracts, etc.) rather than invoking Web3-specific methods.

♻️ Duplicate comments (1)
djed-sdk/src/djed/djed.js (1)

30-36: Same web3Promise compatibility concern applies here.

The ethers-based stableCoin and reserveCoin contracts are passed to web3Promise (lines 32-33). This should be verified along with the usage in getCoinContracts.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 2a125cf and e848624.

📒 Files selected for processing (9)
  • djed-sdk/src/djed/djed.js (1 hunks)
  • djed-sdk/src/djed/reserveCoin.js (1 hunks)
  • djed-sdk/src/djed/stableCoin.js (1 hunks)
  • djed-sdk/src/djed/system.js (2 hunks)
  • djed-sdk/src/djed/tradeUtils.js (1 hunks)
  • djed-sdk/src/helpers.js (1 hunks)
  • djed-sdk/src/oracle/oracle.js (1 hunks)
  • djed-sdk/src/web3.js (1 hunks)
  • stablepay-sdk/src/core/Transaction.js (5 hunks)
🧰 Additional context used
🧬 Code graph analysis (6)
djed-sdk/src/djed/stableCoin.js (3)
djed-sdk/dist/esm/index.js (12)
  • data (356-361)
  • data (382-387)
  • data (409-411)
  • data (416-418)
  • data (431-436)
  • data (464-469)
  • data (491-491)
  • data (498-500)
  • djed (1615-1615)
  • FEE_UI_UNSCALED (157-160)
  • value (390-394)
  • value (471-475)
djed-sdk/dist/umd/index.js (12)
  • data (360-365)
  • data (386-391)
  • data (413-415)
  • data (420-422)
  • data (435-440)
  • data (468-473)
  • data (495-495)
  • data (502-504)
  • djed (1619-1619)
  • FEE_UI_UNSCALED (161-164)
  • value (394-398)
  • value (475-479)
djed-sdk/src/helpers.js (1)
  • buildTx (8-19)
djed-sdk/src/djed/tradeUtils.js (2)
djed-sdk/dist/esm/index.js (1)
  • verifyTx (272-280)
djed-sdk/dist/umd/index.js (1)
  • verifyTx (276-284)
djed-sdk/src/helpers.js (2)
djed-sdk/dist/esm/index.js (1)
  • tx (23-28)
djed-sdk/dist/umd/index.js (1)
  • tx (27-32)
djed-sdk/src/web3.js (2)
djed-sdk/dist/esm/index.js (1)
  • getWeb3 (3-15)
djed-sdk/dist/umd/index.js (1)
  • getWeb3 (7-19)
djed-sdk/src/djed/system.js (3)
djed-sdk/src/helpers.js (1)
  • scaledUnscaledPromise (86-91)
djed-sdk/dist/esm/index.js (1)
  • BC_DECIMALS (149-149)
djed-sdk/dist/umd/index.js (1)
  • BC_DECIMALS (153-153)
djed-sdk/src/oracle/oracle.js (3)
djed-sdk/dist/esm/index.js (3)
  • getOracleAddress (2258-2260)
  • getOracleContract (2262-2267)
  • oracle (2263-2265)
djed-sdk/dist/umd/index.js (3)
  • getOracleAddress (2262-2264)
  • getOracleContract (2266-2271)
  • oracle (2267-2269)
djed-sdk/src/helpers.js (1)
  • web3Promise (2-4)
🔇 Additional comments (10)
stablepay-sdk/src/core/Transaction.js (1)

15-37: LGTM! Migration to ethers provider is implemented correctly.

The initialization flow properly obtains the ethers provider via getWeb3, passes it to contract getters, and updates oracle contract initialization to use the provider-based signature. The use of .target for contract addresses is correct for ethers v6.

djed-sdk/src/djed/tradeUtils.js (1)

131-139: LGTM! Correctly migrated to ethers provider API.

The function signature update and the call to provider.getTransactionReceipt(hash) align with ethers.js patterns.

djed-sdk/src/djed/reserveCoin.js (1)

73-90: LGTM! Encoding migration follows ethers.js patterns correctly.

Both buyRcTx and sellRcTx correctly use djed.interface.encodeFunctionData() with the appropriate parameters for ethers v6 contract interaction.

djed-sdk/src/helpers.js (1)

1-4: LGTM! Direct contract method invocation is correct for ethers.

The simplified pattern contract[method](...args) is the proper way to call contract methods in ethers.js for read operations.

djed-sdk/src/djed/stableCoin.js (2)

79-89: LGTM! Transaction encoding correctly migrated to ethers.

The buyScTx function properly uses djed.interface.encodeFunctionData("buyStableCoins", [...]) for ethers v6 contract interaction.


91-99: LGTM! Transaction encoding correctly migrated to ethers.

The sellScTx function properly uses djed.interface.encodeFunctionData("sellStableCoins", [...]) for ethers v6 contract interaction.

djed-sdk/src/djed/system.js (1)

117-149: LGTM! Balance retrieval correctly migrated to ethers provider.

The signature update to accept provider instead of web3 and the call to provider.getBalance(account) are correct for ethers.js. The remaining contract calls via web3Promise continue to work as that helper now supports ethers contracts.

djed-sdk/src/oracle/oracle.js (1)

9-16: The oracle contract correctly uses a read-only provider.

The function signature change from getOracleContract(web3, oracleAddress, msgSender) to getOracleContract(provider, oracleAddress) is appropriate. The oracle contract is only used for read operations—specifically calling readData() to retrieve price information. Creating the contract with just a provider is correct; a signer is not needed.

djed-sdk/src/djed/djed.js (2)

6-10: LGTM! Clean migration to ethers provider pattern.

The function correctly instantiates an ethers read-only contract using the provider. The updated parameter name from web3 to provider accurately reflects the migration.


12-28: No issue found with web3Promise usage.

The web3Promise helper is a generic function that calls contract methods via contract[method](...args). It works with both web3.js and ethers.js contracts, making it fully compatible with the ethers contract instances used here. The function name is misleading but the implementation is not web3-specific.

@@ -1,25 +1,32 @@
import { ethers } from "ethers";
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical

🧩 Analysis chain

🏁 Script executed:

find . -name "package.json" -type f | head -20

Repository: DjedAlliance/StablePay

Length of output: 118


🏁 Script executed:

cat package.json | grep -A 5 -B 5 "ethers"

Repository: DjedAlliance/StablePay

Length of output: 110


🏁 Script executed:

cat djed-sdk/package.json | jq '.dependencies.ethers, .devDependencies.ethers'

Repository: DjedAlliance/StablePay

Length of output: 75


🏁 Script executed:

grep -r "web3Promise" djed-sdk/src/ -A 5 -B 2

Repository: DjedAlliance/StablePay

Length of output: 8867


🏁 Script executed:

cat djed-sdk/package.json

Repository: DjedAlliance/StablePay

Length of output: 608


🏁 Script executed:

cat djed-sdk/src/djed/djed.js | head -20

Repository: DjedAlliance/StablePay

Length of output: 814


Add ethers as a dependency in package.json.

The file imports ethers but the package is not listed in djed-sdk/package.json. Specify the ethers version in dependencies (or devDependencies) to resolve the missing module error at runtime. Confirm the version aligns with the API patterns used (e.g., new ethers.Contract(address, abi, provider)).

🤖 Prompt for AI Agents
In djed-sdk/src/djed/djed.js around line 1, the file imports "ethers" but
djed-sdk/package.json does not list ethers as a dependency; add ethers to
package.json dependencies with a concrete version (for example "ethers":
"^6.8.0") so the module is installed at runtime, ensure the chosen version is
compatible with the code's API usage (e.g., new ethers.Contract(address, abi,
provider)), then run npm/yarn install and update lockfile.

Comment on lines 8 to 18
export function buildTx(from_, to_, value_, data_, setGasLimit = true) {
const tx = {
to: to_,
from: from_,
value: "0x" + BigInt(value_).toString(16), // Use BigInt instead of BN
value: value_ ? BigInt(value_) : 0n,
data: data_,
};
if (setGasLimit) {
tx.gasLimit = 500_000;
tx.gasLimit = 500_000n;
}
return tx;
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Check if dist files contain outdated BigInt hex conversion patterns

echo "=== Checking dist/esm/index.js ==="
rg -n "0x.*BigInt.*toString\(16\)" djed-sdk/dist/esm/index.js || echo "Pattern not found"

echo ""
echo "=== Checking dist/umd/index.js ==="
rg -n "0x.*BigInt.*toString\(16\)" djed-sdk/dist/umd/index.js || echo "Pattern not found"

echo ""
echo "=== Checking if source uses direct BigInt ==="
rg -n "value_.*BigInt.*:" djed-sdk/src/helpers.js

Repository: DjedAlliance/StablePay

Length of output: 385


Rebuild dist files to reflect the updated source code.

The source code uses direct BigInt values (value_ ? BigInt(value_) : 0n at line 12 and 500_000n at line 16), which ethers v6 accepts directly. However, the dist files contain outdated hex string conversion patterns ("0x" + BigInt(value_).toString(16) at djed-sdk/dist/esm/index.js:26 and djed-sdk/dist/umd/index.js:30), indicating the dist files need to be rebuilt.

🤖 Prompt for AI Agents
In djed-sdk/src/helpers.js around lines 8 to 18, the source now uses BigInt
literals and BigInt(value_) but the distributed builds still contain old
hex-string conversions; rebuild the dist artifacts so they reflect the updated
source (replace occurrences like '"0x" + BigInt(value_).toString(16)' with the
new BigInt usage), run the project build step (e.g., npm run build or the
repository's build command) to regenerate djed-sdk/dist/esm and
djed-sdk/dist/umd, and verify the generated files contain the direct BigInt
values instead of manual hex conversions.

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.

1 participant