Giter Site home page Giter Site logo

zksync-ethers's Introduction

๐Ÿš€ zksync-ethers JavaScript SDK ๐Ÿš€

License License: Apache 2.0 Contributor Covenant Contributions Welcome X (formerly Twitter) Follow Code Style: Google

Era Logo

In order to provide easy access to all the features of ZKsync Era, the zksync-ethers JavaScript SDK was created, which is made in a way that has an interface very similar to those of ethers. In fact, ethers is a peer dependency of our library and most of the objects exported by zksync-ethers ( e.g. Wallet, Provider etc.) inherit from the corresponding ethers objects and override only the fields that need to be changed.

While most of the existing SDKs should work out of the box, deploying smart contracts or using unique ZKsync Era features, like account abstraction, requires providing additional fields to those that Ethereum transactions have by default.

The library is made in such a way that after replacing ethers with zksync-ethers most client apps will work out of box.

๐Ÿ”— For a detailed walkthrough, refer to the official documentation.

๐Ÿ“Œ Overview

To begin, it is useful to have a basic understanding of the types of objects available and what they are responsible for, at a high level:

  • Provider provides connection to the ZKsync Era blockchain, which allows querying the blockchain state, such as account, block or transaction details, querying event logs or evaluating read-only code using call. Additionally, the client facilitates writing to the blockchain by sending transactions.
  • Wallet wraps all operations that interact with an account. An account generally has a private key, which can be used to sign a variety of types of payloads. It provides easy usage of the most common features.

๐Ÿ›  Prerequisites

๐Ÿ“ฅ Installation & Setup

yarn add zksync-ethers
yarn add ethers@6 # ethers is a peer dependency of zksync-ethers

๐Ÿ“ Examples

The complete examples with various use cases are available here.

Connect to the ZKsync Era network:

import { Provider, utils, types } from "zksync-ethers";
import { ethers } from "ethers";

const provider = Provider.getDefaultProvider(types.Network.Sepolia); // ZKsync Era testnet (L2)
const ethProvider = ethers.getDefaultProvider("sepolia"); // Sepolia testnet (L1)

Get the latest block number

const blockNumber = await provider.getBlockNumber();

Get the latest block

const block = await provider.getBlock("latest");

Create a wallet

const PRIVATE_KEY = process.env.PRIVATE_KEY;
const wallet = new Wallet(PRIVATE_KEY, provider, ethProvider);

Check account balances

const ethBalance = await wallet.getBalance(); // balance on ZKsync Era network

const ethBalanceL1 = await wallet.getBalanceL1(); // balance on Sepolia network

Transfer funds

Transfer funds among accounts on L2 network.

const receiver = Wallet.createRandom();

const transfer = await wallet.transfer({
    to: receiver,
    token: utils.ETH_ADDRESS,
    amount: ethers.parseEther("1.0"),
});

Deposit funds

Transfer funds from L1 to L2 network.

const deposit = await wallet.deposit({
    token: utils.ETH_ADDRESS,
    amount: ethers.parseEther("1.0"),
});

Withdraw funds

Transfer funds from L2 to L1 network.

const withdrawal = await wallet.withdraw({
    token: utils.ETH_ADDRESS,
    amount: ethers.parseEther("1.0"),
});

๐Ÿค– Running tests

In order to run test you need to run local-setup on your machine. For running tests, use:

yarn test:wait # waits for local-setup to be ready
yarn test:prepare # prepares the environment (deploys token on both layers, etc.)
yarn test

For running test coverage, use:

yarn test:coverage

๐Ÿค Contributing

We welcome contributions from the community! If you're interested in contributing to the zksync-ethers JavaScript SDK, please take a look at our CONTRIBUTING.md for guidelines and details on the process.

Thank you for making zksync-ethers JavaScript SDK better! ๐Ÿ™Œ

zksync-ethers's People

Contributors

coverlv avatar danijeltxfusion avatar dependabot[bot] avatar felixmohr avatar petartxfusion avatar popzxc avatar samzkback avatar semantic-release-bot avatar willxing avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

zksync-ethers's Issues

get UNSUPPORTED_OPERATION error

๐Ÿ› Bug Report for zksync2-js JavaScript SDK

๐Ÿ“ Description

Provide a clear and concise description of the bug.
When I tried to get list of prefetched transactions from the block, I get an error UNSUPPORTED_OPERATION

Error: transactions were not prefetched with block request (operation="transactionResponses()", code=UNSUPPORTED_OPERATION, version=6.11.1)
at ZkSyncEraService.listenTransactionsToMaster (/Users/macbookpro16/Desktop/Retrobridge/backend/src/modules/zk_sync_era/services/zk_sync_era.service.ts:209:13)
at processTicksAndRejections (node:internal/process/task_queues:95:5)

I tried to get list of prefetched txs via ethers but it didn't work, I had an error "missing r in transaction", some like missing r or v in one tx of list prefetched transactions

๐Ÿ”„ Reproduction Steps

  1. Call method provider.getBlock(block, true);
  2. And when you'll want to get prefetched txs, you will get an error

๐Ÿค” Expected Behavior

Describe what you expected to happen.

๐Ÿ˜ฏ Current Behavior

Describe what actually happened.

๐Ÿ–ฅ๏ธ Environment

  • Node version: [e.g., Node 18.16.1]
  • Operating System & Version: [e.g., Ubuntu 20.04]
  • Other relevant environment details:

๐Ÿ“‹ Additional Context

Add any other context about the problem here. If applicable, add screenshots to help explain.

๐Ÿ“Ž Log Output

Paste any relevant log output here.

Paymaster validation error

๐Ÿ› Bug Report for zksync2-js JavaScript SDK

๐Ÿ“ Description

Encountering errors when paying gas with Paymaster

๐Ÿ”„ Reproduction Steps

const paymasterAddress = "0xf2a173643ca958213714712ce195f6f6e9c686e7"
      paymasterParams = utils.getPaymasterParams(paymasterAddress, {
        type: "ApprovalBased",
        token: gasPayTokenAddress,
        minimalAllowance: ethers.constants.MaxUint256,
        innerInput: "0x0000000000000000000000000000000000000000000000000000000000000001",
      });
      let populatedTx = {
        from: wallet.address,
        data: swapDataHex,
        to: newRouteAddr,
        // gasPrice: gasPrice,
        gasLimit: 1000000,
        // type: EIP712_TX_TYPE;
        value:  ethers.BigNumber.from(0),
        customData: customData
      }
      const response =  await wallet.sendTransaction(populatedTx);
      result = await response.wait();

๐Ÿค” Expected Behavior

Paying gas with Paymaster

๐Ÿ˜ฏ Current Behavior

processing response error (body="{"jsonrpc":"2.0","error":{"code":3,"message":"failed to validate the transaction. reason: Validation revert: Paymaster validation error: Error function_selector = 0x, data = 0x","data":"0x"},"id":94}", error={"code":3,"data":"0x"}, requestBody="{"method":"eth_sendRawTransaction","params":[""],"id":94,"jsonrpc":"2.0"}", requestMethod="POST", url="", code=SERVER_ERROR, version=web/5.7.1),

๐Ÿ–ฅ๏ธ Environment

  • Node version: [v20.0]
  • Operating System & Version: [docker]
  • Other relevant environment details: [email protected]

๐Ÿ“‹ Additional Context

๐Ÿ“Ž Log Output

processing response error (body="{\"jsonrpc\":\"2.0\",\"error\":{\"code\":3,\"message\":\"failed to validate the transaction. reason: Validation revert: Paymaster validation error: Error function_selector = 0x, data = 0x\",\"data\":\"0x\"},\"id\":94}", error={"code":3,"data":"0x"}, requestBody="{\"method\":\"eth_sendRawTransaction\",\"params\":[\"\"],\"id\":94,\"jsonrpc\":\"2.0\"}", requestMethod="POST", url="", code=SERVER_ERROR, version=web/5.7.1),

Issue with zksync-ethers.js version 6: Blockage on Usage, Works with Version 5

๐Ÿ› Bug Report for zksync-ethers JavaScript SDK

๐Ÿ“ Description
I wanted to bring to your attention an issue I encountered while using zksync-ethers.js version 6. It appears that there is a compatibility issue or a bug with this version, as I experienced errors when trying to run my code. Specifically, I was unable to retrieve block information using zksync-ethers.js version 6, whereas the same code worked perfectly fine with version 5.

To resolve this issue, I downgraded to zksync-ethers.js version 5, and the problem was resolved. I was able to successfully retrieve the required block information without any errors.

There is an issue with the zksync-ethers JavaScript SDK version 6 where certain functionalities do not work as expected.

๐Ÿ”„ Reproduction Steps
Install zksync-ethers version 6.
Attempt to perform certain operations, such as retrieving latest block number

const { Provider, utils, types } = require("zksync-ethers");
const { ethers } = require("ethers");

async function main() {
    const provider = Provider.getDefaultProvider(types.Network.Sepolia);
    const ethProvider = ethers.getDefaultProvider("sepolia");

    // Get the network
    const network = await provider.getNetwork();
    console.log(`Network: ${JSON.stringify(network)}`);

    // Get the latest block number
    const blockNumber = await provider.getBlockNumber();
    console.log(`Block number: ${blockNumber}`);


}

main().catch(console.error);

Observe the error or unexpected behavior.

๐Ÿค” Expected Behavior
I expected the SDK to function without errors and provide accurate information regarding blocks.

๐Ÿ˜ฏ Current Behavior
The SDK throws errors and does not retrieve block information correctly.

๐Ÿ–ฅ๏ธ Environment
Node version: 18.16.1
Operating System & Version: macOS
Other relevant environment details:

๐Ÿ“‹ Additional Context
This issue was not present in zksync-ethers version 5, suggesting a regression in functionality with the latest version.

Add any other context about the problem here. If applicable, add screenshots to help explain.

๐Ÿ“Ž Log Output

node essai.js
/Users/michel/botcrevic/node_modules/zksync-ethers/build/types.js:58
class TransactionResponse extends ethers_1.ethers.TransactionResponse {
                                                  ^

TypeError: Class extends value undefined is not a constructor or null
    at Object.<anonymous> (/Users/michel/botcrevic/node_modules/zksync-ethers/build/types.js:58:51)
    at Module._compile (node:internal/modules/cjs/loader:1256:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1310:10)
    at Module.load (node:internal/modules/cjs/loader:1119:32)
    at Module._load (node:internal/modules/cjs/loader:960:12)
    at Module.require (node:internal/modules/cjs/loader:1143:19)
    at require (node:internal/modules/cjs/helpers:110:18)
    at Object.<anonymous> (/Users/michel/botcrevic/node_modules/zksync-ethers/build/utils.js:22:17)
    at Module._compile (node:internal/modules/cjs/loader:1256:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1310:10)

Node.js v18.16.1

ethers-v5-feat/bridgehub: wrong ETH address when using `estimateDefaultBridgeDepositL2Gas`

๐Ÿ› Bug Report for zksync-ethers JavaScript SDK

When using a non ETH token as base, the function estimateDefaultBridgeDepositL2Gas fails when the address of the token used is ETH_ADDRESS (0x0000000000000000000000000000000000000000).

๐Ÿ“ Description

Provide a clear and concise description of the bug.

  • SDK tries to call token.name() on ETH, causing the error.
  • This is because the previous if statement that prevents the name() function from being called when the token is ETH verifies that isAddressEq(l1TokenAddress, ETH_ADDRESS_IN_CONTRACTS)
  • ETH_ADDRESS != ETH_ADDRESS_IN_CONTRACTS.

๐Ÿ”„ Reproduction Steps

  1. Call the function like this, when using a non ETH based chain:
await zksync.utils.estimateDefaultBridgeDepositL2Gas(
            alice.providerL1!,
            alice.provider,
            ETH_ADDRESS,
            amount,
            alice.address,
            alice.address,
            gasPerPubdataByte,
            isBaseToken
        );

This is taken from ether.test.ts.

๐Ÿค” Expected Behavior

Correct fee estimation.

๐Ÿ˜ฏ Current Behavior

Following error:

call revert exception [ See: https://links.ethers.org/v5-errors-CALL_EXCEPTION ] (method="name()", data="0x", errorArgs=null, errorName=null, errorSignature=null, reason=null, code=CALL_EXCEPTION, version=abi/5.7.0)

Describe what actually happened.

๐Ÿ–ฅ๏ธ Environment

  • Node version: v18.18.0
  • Other relevant environment details: using zk server with base token impl.

Fixing this should just be adding:

if (token == ETH_ADDRESS) {
    token = ETH_ADDRESS_IN_CONTRACTS
}

Or, if we want to change the address only for non ETH based chains:

if (token == ETH_ADDRESS && !(await providerL2.isBaseToken(token))) {
    token = ETH_ADDRESS_IN_CONTRACTS
}

zksync ethers6 BrowserProvider cannot execute the paymaster properly

๐Ÿ› Bug Report for zksync-ethers JavaScript SDK

๐Ÿ“ Description

Provide a clear and concise description of the bug.
I used technology nextjs + web3modal + ethers6 + zksync-ethers6 to build, But I'm trying to will have a contract here, https://docs.zksync.io/build/tutorials/smart-contract-development/paymasters/custom-paymaster-tutorial.htm l When applying to the page, I found that I could not call normally, I made several attempts:

  1. ethers5 + zksync-ethers5 works properly
  2. Directly use the private key to build the wallet call, it can work normally
  3. ethers6 + zksync-ethers6 + window.ethereum, does not work properly

๐Ÿ”„ Reproduction Steps

  1. demo: https://github.com/chongqiangchen/zksync-nft-demo/blob/1bf9455add33f8e7e4b80aea99a8f13461d59741/hooks/use-token.ts#L19
  2. checkout v6 branch
  3. pnpm install && pnpm dev
  4. mint token and mint token again

๐Ÿค” Expected Behavior

Describe what you expected to happen.

๐Ÿ˜ฏ Current Behavior

Describe what actually happened.

๐Ÿ–ฅ๏ธ Environment

  • Node version: [e.g., Node 18.16.1]
  • Operating System & Version: [e.g., Ubuntu 20.04]
  • Other relevant environment details:
  • zkSync Sepolia Testnet
  • PAYMASTER_ADDRESS = 0xBC94cCE2637a72F888962A9Ba12E03B50a92470C
  • TOKEN_ADDRESS = 0x8Bb089cF2aaE59f7404391b8CE5Db6417E99066b
  • NFT_ADDRESS = 0xD7761373119F61135b1EfD5f421F0134135E1871

๐Ÿ“‹ Additional Context

Add any other context about the problem here. If applicable, add screenshots to help explain.

๐Ÿ“Ž Log Output

Paste any relevant log output here.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.