From 7942df61794b7f1c33049c54b6c34053c795258e Mon Sep 17 00:00:00 2001
From: petarTxFusion <130662325+petarTxFusion@users.noreply.github.com>
Date: Mon, 25 Mar 2024 01:46:36 +0100
Subject: [PATCH] feat(java-sdk): add missing docs (#979)
---
docs/build/sdks/java/accounts-l1-l2.md | 92 +-
docs/build/sdks/java/accounts.md | 653 ++++++++++----
docs/build/sdks/java/contracts.md | 21 +
docs/build/sdks/java/features.md | 25 +
docs/build/sdks/java/getting-started.md | 1051 +----------------------
docs/build/sdks/java/paymaster-utils.md | 69 ++
docs/build/sdks/java/providers.md | 483 ++++++++---
docs/build/sdks/java/types.md | 243 ++++++
docs/build/sdks/java/utils.md | 264 ++++++
9 files changed, 1466 insertions(+), 1435 deletions(-)
create mode 100644 docs/build/sdks/java/contracts.md
create mode 100644 docs/build/sdks/java/features.md
create mode 100644 docs/build/sdks/java/paymaster-utils.md
create mode 100644 docs/build/sdks/java/types.md
create mode 100644 docs/build/sdks/java/utils.md
diff --git a/docs/build/sdks/java/accounts-l1-l2.md b/docs/build/sdks/java/accounts-l1-l2.md
index 1f375bb1ef..8abeec3330 100644
--- a/docs/build/sdks/java/accounts-l1-l2.md
+++ b/docs/build/sdks/java/accounts-l1-l2.md
@@ -5,92 +5,30 @@ head:
content: Java SDK L1/L2 Transactions | zkSync Docs
---
-# Accounts: L1->L2 Transactions
+# Accounts: L1<->L2 Transactions
-This section explores the methods which allow the [account](./accounts.md) classes to send transactions from L1 to L2.
+This section explores the methods which allow the [account](./accounts.md) to send transactions among both L1 to L2 networks.
-If you want some background on how L1->L2 interaction works on zkSync Era, go through the [L1 / L2 interoperability doc](../../developer-reference/l1-l2-interop.md).
+If you want some background on how L1<->L2 interaction works on zkSync, go through the [introduction](../../developer-reference/l1-l2-interop.md).
-## EthereumProvider
+## Deposit
-### `approveDeposits`
+`Wallet` and `L1Signer` objects provide a deposit workflow. For more information, please refer to the method specification [`Deposit`](accounts.md#deposit).
-Send approve transaction to token contract.
+For a complete example of how to execute the deposit workflow, take a look at the following: [Deposit ETH and ERC20 token](https://github.com/zksync-sdk/zksync2-examples/blob/main/js/src/01_deposit.ts).
-Example:
+## Request execute
-```java
-TransactionReceipt approveReceipt = provider.approveDeposits(token, Optional.of(token.toBigInteger(10000000000L))).join();
-```
+`Wallet` and `L1Signer` objects provide an option to request execution of L2 transaction from L1. For more information, please refer
+to the method specification [`requestExecute`](accounts.md#requestexecute).
-| Name | Description |
-| ------ | ----------------------------------------------------- |
-| token | Token object supported by ZkSync Era. |
-| limit | Maximum amount to approve for ZkSync Era contract. |
-| return | `CompletableFuture` for waiting for transaction mine. |
+## Base cost
-### `deposit`
+`Wallet` and `L1Signer` objects provide an option to calculate base cost for L2 transaction. For more information, please refer to the
+method specification [`getBaseCost`](accounts.md#getbasecost).
-Send deposit transaction to ZkSync Era contract. For ERC20 token must be approved before. See [approveDeposits](#approvedeposits)
+## Withdrawal
-| Name | Description |
-| ------------ | ----------------------------------------------------- |
-| token | Token object supported by ZkSync Era. |
-| amount | Amount of tokens to transfer. |
-| operatorTips | Tips for operator that executes deposit on L2. |
-| userAddress | Address of L2 receiver of deposit in ZkSync Era. |
-| return | `CompletableFuture` for waiting for transaction mine. |
+`Wallet` and `Signer` objects provide a withdrawal workflow. For more information, please refer to the method specification [`Deposit`](accounts.md#deposit).
-Example:
-
-```java
- TransactionManager manager = new RawTransactionManager(web3j, credentials, chainId.longValue());
- BigInteger gasPrice = web3j.ethGasPrice().send().getGasPrice();
- ContractGasProvider gasProvider = new StaticGasProvider(gasPrice, BigInteger.valueOf(300_000L));
- TransactionReceipt receipt = EthereumProvider
- .load(wallet.getZksync(), web3j, manager, gasProvider).join()
- .deposit(Token.ETH, Convert.toWei("0.001", Convert.Unit.ETHER).toBigInteger(), BigInteger.ZERO, credentials.getAddress()).join();
-
- System.out.println(receipt);
-```
-
-### `getBaseCost`
-
-Get base cost for L2 transaction.
-
-Example:
-
-```java
-BigInteger baseCost = provider.getBaseCost(gasLimit, L1_TO_L2_GAS_PER_PUBDATA, gasPriceValue).join();
-```
-
-| Name | Description |
-| ----------------- | ----------------------------------------------------- |
-| gasLimit | Gas limit for L2 transaction. |
-| gasPerPubdataByte | Gas per pubdata byte. |
-| gasPrice | Gas price for L2 transaction. |
-| return | `CompletableFuture` for waiting for transaction mine. |
-
-### `transfer`
-
-Send transfer transaction. This is the regular transfer of ERC20 tokens.
-
-Example:
-
-```java
-TransactionManager manager = new RawTransactionManager(web3j, credentials, chainId.longValue());
-BigInteger gasPrice = web3j.ethGasPrice().send().getGasPrice();
-ContractGasProvider gasProvider = new StaticGasProvider(gasPrice, BigInteger.valueOf(300_000L));
-TransactionReceipt receipt = EthereumProvider
- .load(wallet.getZksync(), web3j, manager, gasProvider).join()
- .transfer(Token.ETH, Convert.toWei("0.117649", Convert.Unit.ETHER).toBigInteger(), credentials.getAddress()).join();
-
- System.out.println(receipt);
-```
-
-| Name | Description |
-| ------ | ----------------------------------------------------- |
-| token | Token object supported by ZkSync Era. |
-| amount | Amount of tokens to transfer. |
-| to | Address of token recipient. |
-| return | `CompletableFuture` for waiting for transaction mine. |
+For a complete example of how to execute the deposit workflow, take a look at the following: [Withdraw ETH and ERC20 token](https://github.com/zksync-sdk/zksync2-examples/blob/main/js/src/03_withdraw.ts).
diff --git a/docs/build/sdks/java/accounts.md b/docs/build/sdks/java/accounts.md
index 2b931bda55..28dc6106dc 100644
--- a/docs/build/sdks/java/accounts.md
+++ b/docs/build/sdks/java/accounts.md
@@ -7,306 +7,577 @@ head:
# Accounts
-## PrivateKeyEthSigner
+## Overview
-Used to get wallet address, generate signatures, and verify messages.
+`zksync2-java` uses following classes that can sign transactions on zkSync:
-### Create from credentials and chain id
+- `Wallet`
+- `EthSigner` class that is used to sign `EIP712`_-typed_ zkSync transactions.
-[Example](getting-started.md#ethsigner)
+## `Wallet`
-#### Inputs and outputs
+### `constructor`
-| Name | Description |
-| ----------- | ------------------------ |
-| credentials | Credentials object. |
-| chainId | Chain id of the network. |
-| returns | PrivateKeyEthSigner. |
+#### Inputs
-### `signTypedData`
+| Parameter | Type | Description |
+| ------------- | ----------- | ----------------------------------------------------------- |
+| `providerL1` | Web3j | Instance of Web3j class. |
+| `providerL2` | ZkSync | A zkSync node provider. Needed for interaction with zkSync. |
+| `credentials` | Credentials | An Ethereum node provider. Needed for interaction with L1. |
+
+### `getMainContract`
+
+Returns `Contract` wrapper of the zkSync smart contract.
+
+#### Example
```java
-String signature = signer.signTypedData(domain, message).join();
+IZkSync mainContract = testWallet.getMainContract()
```
-Signs typed-struct using Ethereum private key with the EIP-712 signature standard.
+### `getL1BridgeContracts`
+
+Returns L1 bridge contracts.
-#### Inputs and outputs
+:::note
-| Name | Description |
-| --------- | ---------------------------------------------- |
-| domain | EIP712 domain. |
-| typedData | Object implementing EIP712 structure standard. |
-| returns | Prepared gas estimate request. |
+There is no separate Ether bridge contract, [Main contract](./accounts.md#getMainContract) is used instead.
-### `verifyTypedData`
+:::
-Verify typed, EIP-712 struct standard.
+#### Example
```java
-boolean verified = signer.verifyTypedData(domain, message, signature).join();
+L1BridgeContracts l1BridgeContracts = wallet.getL1BridgeContracts();
```
-#### Inputs and outputs
+### `getAddress`
-| Name | Description |
-| --------- | ---------------------------------------------- |
-| domain | EIP712 domain. |
-| typedData | Object implementing EIP712 structure standard. |
-| returns | Prepared gas estimate request. |
+Returns the wallet address.
-### `signMessage`
+### Example
+
+```java
+String address = wallet.getAddress();
+```
-Sign raw message.
+### `getBalance`
+
+Returns the amount of the token the `Wallet` has.
```java
-signer.signMessage(Eip712Encoder.typedDataToSignedBytes(domain, typedData), false);
+BigInteger ethBalance = wallet.getBalance().sendAsync().join();
```
-#### Inputs and outputs
+#### Inputs
+
+| Parameter | Type | Description |
+| --------- | -------- | ---------------------------------------------------- |
+| `token` | `String` | The address of the token. ETH by default (optional). |
+
+#### Example
+
+```java
+String L1_DAI = "0x56E69Fa1BB0d1402c89E3A4E3417882DeA6B14Be"
+String l2DAI = wallet.l2TokenAddress(L1_DAI);
+
+BigInteger tokenBalance = wallet.getBalance(l2DAI).sendAsync().join();
+```
-| Name | Description |
-| --------- | ---------------------------------------------------------------------------------------------- |
-| message | Message to sign. |
-| addPrefix | If true then add secure prefix (EIP-712). |
-| returns | Signature object. |
+#### Inputs
-### `verifySignature`
+| Parameter | Type | Description |
+| ------------- | ------------- | ---------------------------------------------------------------------------------------------------------------- |
+| `address` | `String` | The address of the wallet. |
+| `token` | `String` | The address of the token. ETH by default. |
+| `blockNumber` | `BlockNumber` | In which block a balance should be checked on. `committed`, i.e. the latest processed one is the default option. |
-Verify signature with raw message.
+#### Example
```java
-signer.verifySignature(signature, Eip712Encoder.typedDataToSignedBytes(domain, typedData), false);
+String L1_DAI = "0x56E69Fa1BB0d1402c89E3A4E3417882DeA6B14Be"
+String l2DAI = wallet.l2TokenAddress(L1_DAI);
+
+BigInteger tokenBalance = wallet.getBalance(signer.getAddress(), l2DAI, ZkBlockParameterName.COMMITTED).sendAsync().join();
```
-#### Inputs and outputs
+### `balanceL1`
-| Name | Description |
-| --------- | ---------------------------------------------------------------------------------------------- |
-| signature | Signature string. |
-| message | Message to verify in bytes. |
-| prefixed | If true then add secure prefix (EIP-712). |
-| returns | true on verification success. |
+Returns the amount of the token the `Wallet` has on Ethereum.
-### `getAddress`
+```java
+BigInteger ethBalance = wallet.getBalance().sendAsync().join();
+```
+
+#### Inputs
+
+| Parameter | Type | Description |
+| --------- | -------- | ---------------------------------------------------- |
+| `token` | `String` | The address of the token. ETH by default (optional). |
+
+#### Example
+
+```java
+String L1_DAI = "0x56E69Fa1BB0d1402c89E3A4E3417882DeA6B14Be"
+String l2DAI = wallet.l2TokenAddress(L1_DAI);
+
+BigInteger tokenBalance = wallet.getBalance(l2DAI).sendAsync().join();
+```
+
+#### Inputs
-Get wallet address.
+| Parameter | Type | Description |
+| ------------- | ------------- | ---------------------------------------------------------------------------------------------------------------- |
+| `address` | `String` | The address of the wallet. |
+| `token` | `String` | The address of the token. ETH by default. |
+| `blockNumber` | `BlockNumber` | In which block a balance should be checked on. `committed`, i.e. the latest processed one is the default option. |
+
+#### Example
```java
-signer.getAddress();
+String L1_DAI = "0x56E69Fa1BB0d1402c89E3A4E3417882DeA6B14Be"
+String l2DAI = wallet.l2TokenAddress(L1_DAI);
+
+BigInteger tokenBalance = wallet.getBalance(signer.getAddress(), l2DAI, ZkBlockParameterName.COMMITTED).sendAsync().join();
```
-#### Inputs and outputs
+### `getAllBalances`
+
+Returns all balances for confirmed tokens given by an account address.
+
+#### Example
+
+```java
+ZksAccountBalances allBalances = wallet.getAddress().join();
+```
-| Name | Description |
-| ------- | ---------------------- |
-| returns | Address in hex string. |
+### `getNonce`
-## Wallet
+Returns account's nonce number.
-### Creating wallet from a private key
+#### Inputs
-The `Wallet` object from `zksync-ethers` can be created from an Ethereum private key.
-[Example](getting-started.md#zksync-era-wallet)
+| Parameter | Type | Description |
+| --------- | ----------------------- | --------------------------------------------------------------------------------------------------------------------------- |
+| `at` | `DefaultBlockParameter` | In which block a balance should be checked on. `committed`, i.e. the latest processed one is the default option (optional). |
-#### Inputs and outputs
+#### Example
-| Name | Description |
-| ------- | --------------------------------------------------------------------- |
-| zksync | A zkSync Era node provider. Needed for interaction with zkSync Era. |
-| signer | Used to get wallet address, generate signatures, and verify messages. |
-| token | Token object. |
-| returns | The new `Wallet` object. |
+```java
+BigInteger nonce = wallet.getNonce().sendAsync().join();
+```
+
+### `getDeploymentNonce`
+
+Returns account's deployment nonce number.
+
+#### Example
+
+```java
+BigInteger deploymentNonce = wallet.getDeploymentNonce().join()
+```
+
+### `estimateAndSend`
+
+Estimate and send the transaction to the network.
+
+#### Inputs
+
+| Parameter | Type | Description |
+| ---------------------- | ----------- | --------------------------------------------------------------------------- |
+| `transaction` | Transaction | Transaction request. |
+| `nonce` | BigInteger | Nonce to use in the transaction. |
+| `maxPriorityFeePerGas` | BigInteger | Max priority fee per gas to use in the transaction, default is 0.(optional) |
+
+#### Example
+
+```java
+Transaction tx = Transaction.createEthCallTransaction("", "", BigInteger(7_000_000_000L), signer.getAddress());
-[Example](getting-started.md#transfer-erc20-coins-via-zksyncwallet)
+TransactionReceipt receipt = wallet.transfer(transaction).sendAsync().join();
-| Name | Description |
-| ------- | ---------------------------------------------------------------- |
-| to | Recipient address. |
-| amount | Amount of funds to be transferred in minimum denomination (wei). |
-| token | Token object supported by ZkSync Era. |
-| returns | Prepared remote call of transaction. |
+wallet.getTransactionReceiptProcessor().waitForTransactionReceipt(receipt.getTransactionHash());
+```
-##### With specific token and custom nonce
+Transfer ETH using paymaster to facilitate fee payment with an ERC20 token.
-| Name | Description |
-| ------- | ---------------------------------------------------------------- |
-| to | Recipient address. |
-| amount | Amount of funds to be transferred in minimum denomination (wei). |
-| token | Token object supported by ZkSync Era. |
-| nonce | Custom nonce value of the wallet. |
-| returns | Prepared remote call of transaction. |
+```java
+PaymasterParams paymasterParams = new PaymasterParams(PAYMASTER, Numeric.hexStringToByteArray(FunctionEncoder.encode(Paymaster.encodeApprovalBased(TOKEN, BigInteger.ONE, new byte[] {}))));
+TransferTransaction transaction = new TransferTransaction("", BigInteger(7_000_000_000L), signer.getAddress(), paymasterParams);
-### `withdraw`
+TransactionReceipt receipt = wallet.transfer(transaction).sendAsync().join();
-Withdraw native coins or tokens from L1.
+wallet.getTransactionReceiptProcessor().waitForTransactionReceipt(receipt.getTransactionHash());
+```
-[Example](getting-started.md#withdraw-funds-via-zksyncwallet)
+### `l2TokenAddress`
-| Name | Description |
-| ------- | ------------------------------------------------------------ |
-| to | Address of the L1 wallet from which funds will be withdrawn. |
-| amount | Amount of funds to be withdrawn. |
-| returns | Prepared remote call of transaction. |
+Returns the L2 token address equivalent for a L1 token address as they are not equal. ETH's address is set to zero address.
-#### With specific token
+:::warning
+Only works for tokens bridged on default zkSync Era bridges.
+:::
-| Name | Description |
-| ------- | --------------------------------------------------------------- |
-| to | Address of the L1 wallet L1 from which funds will be withdrawn. |
-| amount | Amount of funds to be withdrawn. |
-| token | Token object supported by ZkSync Era. |
-| returns | Prepared remote call of transaction. |
+#### Inputs
-#### With specific token and custom nonce
+| Parameter | Type | Description |
+| ----------- | -------- | ------------------------------- |
+| `l1Address` | `String` | The address of the token on L1. |
-| Name | Description |
-| ------- | ------------------------------------------------------------ |
-| to | Address of the L1 wallet from which funds will be withdrawn. |
-| amount | Amount of funds to be withdrawn. |
-| token | Token object supported by ZkSync Era. |
-| nonce | Custom nonce value of the wallet. |
-| returns | Prepared remote call of transaction. |
+#### Example
-### `deploy`
+```java
+String L1_DAI = "0x56E69Fa1BB0d1402c89E3A4E3417882DeA6B14Be"
+
+String l2Address = wallet.l2TokenAddress(L1_DAI).sendAsync().join();
+```
+
+### `getAllowanceL1`
+
+Returns the amount of approved tokens for a specific L1 bridge.
-Deploy new smart contract onto chain (this method uses `create2`, see EIP-1014)
+#### Inputs
-[Example](getting-started.md#deploy-contract-via-zksyncwallet)
+| Parameter | Type | Description |
+| --------------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------- |
+| `token` | `String` | The Ethereum address of the token. |
+| `bridgeAddress` | `String` | The address of the bridge contract to be used. Defaults to the default zkSync bridge, either `L1EthBridge` or `L1Erc20Bridge` (optional). |
-| Name | Description |
-| -------- | ------------------------------------ |
-| bytecode | Compiled bytecode of the contract. |
-| returns | Prepared remote call of transaction. |
+#### Example
-#### With constructor
+```java
+String L1_DAI = "0x5C221E77624690fff6dd741493D735a17716c26B";
-[Example](getting-started.md#deploy-contract-with-constructor-via-zksyncwallet)
+BigInteger allowanceL1 = wallet.getAllowanceL1(L1_DAI).join();
+```
-| Name | Description |
-| -------- | --------------------------------------------- |
-| bytecode | Compiled bytecode of the contract. |
-| calldata | Encoded constructor parameter(s) of contract. |
-| returns | Prepared remote call of transaction. |
+### `approveERC20`
-#### With constructor and custom nonce
+Bridging ERC20 tokens from Ethereum requires approving the tokens to the zkSync Ethereum smart contract.
-| Name | Description |
-| -------- | --------------------------------------------- |
-| bytecode | Compiled bytecode of the contract. |
-| calldata | Encoded constructor parameter(s) of contract. |
-| nonce | Custom nonce value of the wallet. |
-| returns | Prepared remote call of transaction. |
+#### Inputs
-### `execute`
+| Parameter | Type | Description |
+| --------------- | ------------ | ----------------------------------------------------------------------------------------------------------------------------------------- |
+| `token` | `String` | The Ethereum address of the token. |
+| `amount` | `BigInteger` | The amount of the token to be approved. |
+| `bridgeAddress` | `String` | The address of the bridge contract to be used. Defaults to the default zkSync bridge, either `L1EthBridge` or `L1Erc20Bridge` (optional). |
-Execute function of deployed contract.
+#### Example
-[Example](getting-started.md#execute-contact-via-zksyncwallet)
+```java
+String L1_DAI = "0x5C221E77624690fff6dd741493D735a17716c26B";
-| Name | Description |
-| --------------- | -------------------------------------------------- |
-| contractAddress | Address of deployed contract. |
-| function | Prepared function call with or without parameters. |
-| returns | Prepared remote call of transaction. |
+TransactionReceipt tx = wallet.approveERC20(L1_DAI, BigInteger.valueOf(5)).join();
+```
-#### With custom nonce
+### `getBaseCost`
-| Name | Description |
-| --------------- | -------------------------------------------------- |
-| contractAddress | Address of deployed contract. |
-| function | Prepared function call with or without parameters. |
-| nonce | Custom nonce value of the wallet. |
-| returns | Prepared remote call of transaction. |
+Returns base cost for L2 transaction.
-### `getBalance`
+#### Inputs
-#### Get balance of wallet in native coin
+| Name | Type | Description |
+| ------------------- | ------------ | ------------------------------------------------------------------------------------------------- |
+| `gasLimit` | `BigInteger` | The `gasLimit` for the L2 contract call. |
+| `gasPerPubdataByte` | `BigInteger` | The L2 gas price for each published L1 calldata byte (optional). |
+| `gasPrice` | `BigInteger` | The L1 gas price of the L1 transaction that will send the request for an execute call (optional). |
+
+#### Example
```java
-BigInteger balance = wallet.getBalance().send();
+BigInteger baseCost = wallet.getBaseCost(BigInteger.valueOf(100_000));
```
-| Name | Description |
-| ------- | -------------------------- |
-| address | Wallet address. |
-| returns | Prepared get balance call. |
+### `deposit`
+
+Transfers the specified token from the associated account on the L1 network to the target account on the L2 network. The token can be either
+ETH or any ERC20 token. For ERC20 tokens, enough approved tokens must be associated with the specified L1 bridge (default one or the one
+defined in `transaction.bridgeAddress`). In this case, `transaction.approveERC20` can be enabled to perform token approval. If there are
+already enough approved tokens for the L1 bridge, token approval will be skipped. To check the amount of approved tokens for a specific bridge,
+use the [`allowanceL1`](#getallowancel1) method.
+
+#### Inputs
+
+| Parameter | Type | Description |
+| ------------- | -------------------- | ------------------------- |
+| `transaction` | `DepositTransaction` | DepositTransaction class. |
+
+#### Example
+
+Deposit ETH
+
+```java
+BigInteger amount = new BigInteger("7000000000");
+DepositTransaction transaction = new DepositTransaction(ZkSyncAddresses.ETH_ADDRESS, amount);
+
+EthSendTransaction hash = testWallet.deposit(transaction).send();
+// Wait for l1 receipt
+TransactionReceipt l1Receipt = processorL1.waitForTransactionReceipt(hash.getTransactionHash());
+// Get l2 hash from l1 receipt
+String l2Hash = zksync.getL2HashFromPriorityOp(l1Receipt, zksync.zksMainContract().sendAsync().join().getResult());
+// Wait for l2 receipt
+TransactionReceipt l2Receipt = wallet.getTransactionReceiptProcessor().waitForTransactionReceipt(l2Hash);
+```
-#### Get balance of wallet in token
+Deposit ERC20 token
```java
-Token token = new Token("L1_ADDRESS", "L2_ADDRESS", "SYMBOL", 18);
-BigInteger = wallet.getBalance(token).send();
+String L1_DAI = "0x56E69Fa1BB0d1402c89E3A4E3417882DeA6B14Be"
+String l2DAI = testWallet.l2TokenAddress(L1_DAI);
+
+DepositTransaction transaction = new DepositTransaction(L1_DAI, BigInteger.valueOf(5));
+
+EthSendTransaction hash = testWallet.deposit(transaction).send();
+// Wait for l1 receipt
+TransactionReceipt l1Receipt = processorL1.waitForTransactionReceipt(hash.getTransactionHash());
+// Get l2 hash from l1 receipt
+String l2Hash = zksync.getL2HashFromPriorityOp(l1Receipt, zksync.zksMainContract().sendAsync().join().getResult());
+// Wait for l2 receipt
+TransactionReceipt l2Receipt = wallet.getTransactionReceiptProcessor().waitForTransactionReceipt(l2Hash);
```
-| Name | Description |
-| ------- | ------------------------------------- |
-| token | Token object supported by ZkSync Era. |
-| returns | Prepared get balance call. |
+### `getDepositTransaction`
-#### Get balance of wallet by address of token
+Returns populated deposit transaction.
+
+#### Inputs
+
+| Parameter | Type | Description |
+| ------------- | -------------------- | ------------------------- |
+| `transaction` | `DepositTransaction` | DepositTransaction class. |
+
+#### Example
```java
-Token token = new Token("L1_ADDRESS", "L2_ADDRESS", "SYMBOL", 18);
-BigInteger = wallet.getBalance("ADDRESS" ,token).send();
+BigInteger amount = new BigInteger("7000000000");
+DepositTransaction transaction = new DepositTransaction(ZkSyncAddresses.ETH_ADDRESS, amount);
```
-| Name | Description |
-| ------- | ------------------------------------- |
-| address | Wallet address. |
-| token | Token object supported by ZkSync Era. |
-| returns | Prepared get balance call. |
+### `estimateGasDeposit`
+
+Estimates the amount of gas required for a deposit transaction on L1 network. Gas of approving ERC20 token is not included in estimation.
+
+#### Inputs
-#### Get balance of wallet by address of token at block `DefaultBlockParameter`
+| Parameter | Type | Description |
+| ------------- | -------------------- | ------------------------- |
+| `transaction` | `DepositTransaction` | DepositTransaction class. |
+
+#### Example
```java
-BigInteger = wallet.getBalance(address, token, ZkBlockParameterName.COMMITTED).send();
+BigInteger amount = new BigInteger("7000000000");
+DepositTransaction transaction = new DepositTransaction(ZkSyncAddresses.ETH_ADDRESS, amount);
+BigInteger result = testWallet.estimateGasDeposit(transaction);
```
-| Name | Description |
-| ------- | ------------------------------------- |
-| address | Wallet address. |
-| token | Token object supported by ZkSync Era. |
-| at | Block variant. |
-| returns | Prepared get balance call. |
+### `getFullRequiredDepositFee`
-### `getNonce`
+Retrieves the full needed ETH fee for the deposit. Returns the L1 fee and the L2 fee [`FullDepositFee`](./types.md#fulldepositfee).
+
+#### Inputs
+
+| Parameter | Type | Description |
+| ------------- | -------------------- | ------------------------- |
+| `transaction` | `DepositTransaction` | DepositTransaction class. |
+
+#### Example
+
+```java
+BigInteger amount = new BigInteger("7000000000");
+DepositTransaction transaction = new DepositTransaction(ZkSyncAddresses.ETH_ADDRESS, amount);
+BigInteger result = testWallet.getFullRequiredDepositFee(transaction);
+```
+
+### `withdraw`
+
+Initiates the withdrawal process which withdraws ETH or any ERC20 token from the associated account on L2 network to the target account on
+L1 network.
+
+#### Inputs
+
+| Parameter | Type | Description |
+| ------------- | -------------------- | ------------------------- |
+| `transaction` | `DepositTransaction` | DepositTransaction class. |
+
+#### Examples
+
+Withdraw ETH.
+
+```java
+BigInteger amount = new BigInteger("7000000000");
+WithdrawTransaction transaction = new WithdrawTransaction(ZkSyncAddresses.ETH_ADDRESS, amount, testWallet.getAddress());
+
+TransactionReceipt result = testWallet.withdraw(transaction).sendAsync().join();
+
+TransactionReceipt receipt = testWallet.getTransactionReceiptProcessor().waitForTransactionReceipt(result.getTransactionHash());
+```
+
+Withdraw ETH using paymaster to facilitate fee payment with an ERC20 token.
+
+```java
+BigInteger amount = new BigInteger("7000000000");
+String token = "0x927488F48ffbc32112F1fF721759649A89721F8F"; // Crown token which can be minted for free
+String paymaster = "0x13D0D8550769f59aa241a41897D4859c87f7Dd46"; // Paymaster for Crown token
+
+PaymasterParams paymasterParams = new PaymasterParams(paymaster, Numeric.hexStringToByteArray(FunctionEncoder.encode(Paymaster.encodeApprovalBased(token, BigInteger.ONE, new byte[]
+ {}))));
+WithdrawTransaction transaction = new WithdrawTransaction(ZkSyncAddresses.ETH_ADDRESS, amount, paymasterParams);
+
+TransactionReceipt result = testWallet.withdraw(transaction).sendAsync().join();
+
+TransactionReceipt receipt = testWallet.getTransactionReceiptProcessor().waitForTransactionReceipt(result.getTransactionHash());
+```
+
+Withdraw ERC20.
+
+```java
+BigInteger amount = BigInteger.valueOf(5);
+String tokenL1 = "0x56E69Fa1BB0d1402c89E3A4E3417882DeA6B14Be"
+String l2DAI = testWallet.l2TokenAddress(L1_DAI);
+
+WithdrawTransaction transaction = new WithdrawTransaction(l2DAI, amount, testWallet.getAddress());
+TransactionReceipt result = testWallet.withdraw(transaction).sendAsync().join();
+TransactionReceipt receipt = testWallet.getTransactionReceiptProcessor().waitForTransactionReceipt(result.getTransactionHash());
+```
+
+Withdraw ERC20 using paymaster to facilitate fee payment with an ERC20 token.
+
+```java
+BigInteger amount = BigInteger.valueOf(5);
+String tokenL1 = "0x56E69Fa1BB0d1402c89E3A4E3417882DeA6B14Be"
+String l2DAI = testWallet.l2TokenAddress(L1_DAI);
+
+String token = "0x927488F48ffbc32112F1fF721759649A89721F8F"; // Crown token which can be minted for free
+String paymaster = "0x13D0D8550769f59aa241a41897D4859c87f7Dd46"; // Paymaster for Crown token
+
+PaymasterParams paymasterParams = new PaymasterParams(paymaster, Numeric.hexStringToByteArray(FunctionEncoder.encode(Paymaster.encodeApprovalBased(token, BigInteger.ONE, new byte[]
+ {}))));
+
+WithdrawTransaction transaction = new WithdrawTransaction(l2DAI, amount, testWallet.getAddress(), paymasterParams);
+TransactionReceipt result = testWallet.withdraw(transaction).sendAsync().join();
+TransactionReceipt receipt = testWallet.getTransactionReceiptProcessor().waitForTransactionReceipt(result.getTransactionHash());
+```
+
+### `finalizeWithdraw`
+
+Proves the inclusion of the L2 -> L1 withdrawal message.
+
+#### Inputs
+
+| Name | Type | Description |
+| ---------------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------- |
+| `withdrawalHash` | `String` | Hash of the L2 transaction where the withdrawal was initiated. |
+| `index` | `Int` | In case there were multiple withdrawals in one transaction, you may pass an index of the withdrawal you want to finalize. Defaults to 0. |
+
+#### Example
-#### Get nonce for wallet at block `DefaultBlockParameter`
+```java
+WithdrawTransaction transaction = wallet.finalizeWithdraw("", 0).sendAsync().join();
+```
+
+### `requestExecute`
+
+Request execution of L2 transaction from L1.
+
+#### Inputs
+
+| Parameter | Type | Description |
+| ------------- | --------------------------- | --------------------------------- |
+| `transaction` | `RequestExecuteTransaction` | RequestExecuteTransaction struct. |
+
+#### Example
```java
-BigInteger = wallet.getNonce(ZkBlockParameterName.COMMITTED).send(); //ZkBlockParameterName.FINALIZED
+RequestExecuteTransaction transaction = new RequestExecuteTransaction(null, zksync.zksMainContract().send().getResult(), Numeric.hexStringToByteArray("0x"), BigInteger.valueOf(7000000), null, null, null, null, null);
+EthSendTransaction result = testWallet.requestExecute(transaction);
+// Wait for l1 receipt
+TransactionReceipt l1Receipt = processorL1.waitForTransactionReceipt(hash.getTransactionHash());
+// Get l2 hash from l1 receipt
+String l2Hash = zksync.getL2HashFromPriorityOp(l1Receipt, zksync.zksMainContract().sendAsync().join().getResult());
+// Wait for l2 receipt
+TransactionReceipt l2Receipt = wallet.getTransactionReceiptProcessor().waitForTransactionReceipt(l2Hash);
```
-| Name | Description |
-| ------- | ------------------------ |
-| at | Block variant. |
-| returns | Prepared get nonce call. |
+### `getRequestExecute`
+
+Returns populated RequestExecuteTransaction.
+
+#### Inputs
+
+| Parameter | Type | Description |
+| ------------- | --------------------------- | --------------------------------- |
+| `transaction` | `RequestExecuteTransaction` | RequestExecuteTransaction struct. |
-#### Get nonce for wallet at block `COMMITTED` `ZkBlockParameterName`
+#### Example
```java
-BigInteger = wallet.getNonce().send();
+RequestExecuteTransaction transaction = new RequestExecuteTransaction(null, zksync.zksMainContract().send().getResult(), Numeric.hexStringToByteArray("0x"), BigInteger.valueOf(7000000), null, null, null, null, null);
+RequestExecuteTransaction result = testWallet.getRequestExecute(transaction);
```
-| Name | Description |
-| ------- | ------------------------ |
-| returns | Prepared get nonce call. |
+### `estimateGasRequestExecute`
+
+Estimates the amount of gas required for a request execute transaction.
+
+#### Inputs
+
+| Parameter | Type | Description |
+| ------------- | --------------------------- | --------------------------------- |
+| `transaction` | `RequestExecuteTransaction` | RequestExecuteTransaction struct. |
+
+#### Example
+
+```java
+RequestExecuteTransaction transaction = new RequestExecuteTransaction(null, zksync.zksMainContract().send().getResult(), Numeric.hexStringToByteArray("0x"), BigInteger.valueOf(7000000), null, null, null, null, null);
+BigInteger baseGasLimit = estimateGasRequestExecute(transaction.toRequestExecute(mainContractAddress)).sendAsync().join().getAmountUsed();
+```
+
+## `ETHSigner`
+
+Provides support for an EIP712 transaction. The methods of this class are mostly used internally.
+
+### `getDomain`
+
+Returns the EIP712 domain.
+
+### `signTypedData`
+
+Signs typed struct using ethereum private key by EIP-712 signature standard.
+
+| Parameter | Type | Description |
+| ----------- | -------------- | ----------------- |
+| `domain` | `Eip712Domain` | EIP712 domain. |
+| `typedData` | `S` | EIP712 structure. |
+
+### `signMessage`
+
+Signs typed struct using ethereum private key by EIP-712 signature standard.
+
+| Parameter | Type | Description |
+| ----------- | --------- | ------------------------------- |
+| `message` | `byte[]` | Message to sign. |
+| `addPrefix` | `boolean` | If true then add secure prefix. |
diff --git a/docs/build/sdks/java/contracts.md b/docs/build/sdks/java/contracts.md
new file mode 100644
index 0000000000..b47755a925
--- /dev/null
+++ b/docs/build/sdks/java/contracts.md
@@ -0,0 +1,21 @@
+---
+head:
+ - - meta
+ - name: "twitter:title"
+ content: Java SDK Contracts | zkSync Docs
+---
+
+# Contracts
+
+`zksync2-java` implements contract wrappers. Created using [web3j CLI](https://docs.web3j.io/4.8.7/command_line_tools/#solidity-smart-contract-wrapper-generator)
+
+## `Generated wrappers`
+
+- `ERC20`
+- `IEthToken`
+- `IL1Bridge`
+- `IL1Messenger`
+- `IL2Bridge`
+- `INonceHolder`
+- `IZkSync`
+- `ZkSyncContract`
diff --git a/docs/build/sdks/java/features.md b/docs/build/sdks/java/features.md
new file mode 100644
index 0000000000..caa6fb4f48
--- /dev/null
+++ b/docs/build/sdks/java/features.md
@@ -0,0 +1,25 @@
+---
+head:
+ - - meta
+ - name: "twitter:title"
+ content: Java SDK Features | zkSync Docs
+---
+
+# zkSync Era Features
+
+While zkSync is mostly Web3-compatible, it has some differences compared to Ethereum. The major of those are:
+
+- Account abstraction support (accounts may have near-arbitrary validation logic, and also paymaster support is enabled).
+- Deployment transactions require the contracts' bytecode to be passed in a separate field.
+- The fee system is somewhat different.
+
+These require us to extend standard Ethereum transactions with new custom fields. Such extended transactions are called EIP712 transactions since
+[EIP712](https://eips.ethereum.org/EIPS/eip-712) is used to sign them. You can look at the internal structure of the EIP712 transactions [here](../../../zk-stack/concepts/transaction-lifecycle.md#eip-712-0x71).
+
+This document will focus solely on how to pass these arguments to the SDK.
+
+## Encoding paymaster params
+
+While the paymaster feature by itself does not impose any limitations on values of the `paymasterInput`, the Matter Labs team endorses certain types of [paymaster flows](../../developer-reference/account-abstraction.md#built-in-paymaster-flows) that are processable by EOAs.
+
+zkSync SDK provides a utility method that can be used to get the correctly formed `paymasterParams` object: [approvalBased](./paymaster-utils.md#encodeapprovalbased), [general](./paymaster-utils.md#encodegeneral).
diff --git a/docs/build/sdks/java/getting-started.md b/docs/build/sdks/java/getting-started.md
index ba9c67eb00..5662f85821 100644
--- a/docs/build/sdks/java/getting-started.md
+++ b/docs/build/sdks/java/getting-started.md
@@ -2,28 +2,19 @@
head:
- - meta
- name: "twitter:title"
- content: Java | zkSync Docs
+ content: Java SDK Getting Started | zkSync Docs
---
# Getting Started
-In this guide we will demonstrate how to:
+This is a short introduction to `zksync2-java` SDK, but covers many of the most common operations that developers require and provides a
+starting point for those newer to zkSync Era.
-1. Connect to the zkSync network.
-2. Deposit assets from Ethereum into zkSync.
-3. Check balances.
-4. Transfer and withdraw funds (native and ERC20 tokens).
-5. Deploy a smart contract.
-6. Deploy a smart contract with `create2`.
+## Getting zksync-ethers
-## Prerequisites
+### Dependency
-This guide assumes that you are familiar with the basics of [Java](https://docs.oracle.com/en/java/) programming language.
-
-## Dependency
-
-To install the ZkSync2 Java SDK, just add the following dependency to your build file:
-::: code-tabs
+For connecting ZkSync2 library just add the following dependency to your build file.
Maven `pom.xml`
@@ -34,12 +25,7 @@ Maven `pom.xml`
io.zksync
zksync2
- 0.1.1
-
-
- org.web3j
- core
- 4.9.7
+ v0.2.0
@@ -49,1038 +35,49 @@ Gradle `build.gradle`
```groovy
dependencies {
- implementation "io.zksync:zksync2:0.1.1"
+ implementation "io.zksync:zksync2:v0.2.0"
}
```
-## Examples
+## Overview
-### Instantiating the SDK
+While most of the existing SDKs should work out of the box, deploying smart contracts or using unique zkSync features, like account abstraction, requires providing additional
+fields to those that Ethereum transactions have by default.
-To start using this SDK, you just need to pass in a provider configuration.
+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:
-```java
-
-import io.zksync.protocol.ZkSync;
-import org.web3j.protocol.http.HttpService;
-
-public class Main {
- public static void main(String ...args) {
- ZkSync zksync = zksync.build(new HttpService(""));
- }
-}
-
-```
-
-### EthSigner
-
-```java
-import io.zksync.crypto.signer.EthSigner;
-import io.zksync.crypto.signer.PrivateKeyEthSigner;
-import org.web3j.crypto.Credentials;
-
-public class Main {
- public static void main(String ...args) {
- long chainId = 123L;// Chainid of the ZkSync Era network
-
- Credentials credentials = Credentials.create("0x");
-
- EthSigner signer = new PrivateKeyEthSigner(credentials, chainId);
- }
-}
-```
-
-:::tip
-Mainnet chain id: 324
-Sepolia testnet chain id: 300
-Local setup chain id: 270
-:::
-
-### ZkSync Era wallet
-
-You can connect the zkSync Era wallet for easier operations.
-
-```java
-import io.zksync.crypto.signer.EthSigner;
-import io.zksync.ZkSyncWallet;
-import io.zksync.protocol.ZkSync;
-import io.zksync.protocol.core.Token;
-
-public class Main {
- public static void main(String ...args) {
- ZkSync zksync; // Initialize client
- EthSigner signer; // Initialize signer
-
- ZkSyncWallet wallet = new ZkSyncWallet(zksync, signer, Token.ETH);
- }
-}
-```
+- `ZkSync` 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.
## Examples
-### Transactions
-
-ZkSync2 supports Ethereum's `Legacy` and `EIP-1155` transactions, except for deploying contracts.
-
-### Transfer
-
-#### Transfer ETH
-
-```java
-import io.zksync.abi.TransactionEncoder;
-import io.zksync.crypto.signer.EthSigner;
-import io.zksync.methods.request.Transaction;
-import io.zksync.protocol.ZkSync;
-import io.zksync.protocol.core.Token;
-import io.zksync.protocol.core.ZkBlockParameterName;
-import io.zksync.transaction.fee.DefaultTransactionFeeProvider;
-import io.zksync.transaction.fee.ZkTransactionFeeProvider;
-import io.zksync.transaction.type.Transaction712;
-import io.zksync.transaction.response.ZkSyncTransactionReceiptProcessor;
-
-import org.web3j.protocol.core.methods.response.TransactionReceipt;
-import org.web3j.protocol.core.methods.response.EthSendTransaction;
-import org.web3j.protocol.exceptions.TransactionException;
-import org.web3j.utils.Convert;
-import org.web3j.utils.Numeric;
-
-import java.io.IOException;
-import java.math.BigInteger;
-
-import static io.zksync.transaction.manager.ZkSyncTransactionManager.DEFAULT_POLLING_ATTEMPTS_PER_TX_HASH;
-import static io.zksync.transaction.manager.ZkSyncTransactionManager.DEFAULT_POLLING_FREQUENCY;
-
-public class Main {
- public static void main(String ...args) throws IOException, TransactionException {
- ZkSync zksync; // Initialize client
- EthSigner signer; // Initialize signer
- ZkSyncTransactionReceiptProcessor processor = new ZkSyncTransactionReceiptProcessor(zksync, DEFAULT_POLLING_FREQUENCY, DEFAULT_POLLING_ATTEMPTS_PER_TX_HASH);
- BigInteger chainId = zksync.ethChainId().send().getChainId();
-
- BigInteger amountInWei = Convert.toWei("1", Convert.Unit.ETHER).toBigInteger();
-
- BigInteger nonce = zksync
- .ethGetTransactionCount(signer.getAddress(), ZkBlockParameterName.COMMITTED).send()
- .getTransactionCount();
-
- Transaction estimate = Transaction.createFunctionCallTransaction(
- signer.getAddress(),
- "0x",
- BigInteger.ZERO,
- BigInteger.ZERO,
- amountInWei,
- "0x"
- );
-
- ZkTransactionFeeProvider feeProvider = new DefaultTransactionFeeProvider(zksync, Token.ETH);
-
- Transaction712 transaction = new Transaction712(
- chainId.longValue(),
- nonce,
- feeProvider.getGasLimit(estimate),
- estimate.getTo(),
- estimate.getValueNumber(),
- estimate.getData(),
- BigInteger.valueOf(100000000L),
- feeProvider.getGasPrice(),
- signer.getAddress(),
- estimate.getEip712Meta()
- );
-
- String signature = signer.getDomain().thenCompose(domain -> signer.signTypedData(domain, transaction)).join();
- byte[] message = TransactionEncoder.encode(transaction, TransactionEncoder.getSignatureData(signature));
-
- EthSendTransaction sent = zksync.ethSendRawTransaction(Numeric.toHexString(message)).send();
-
- TransactionReceipt receipt = processor.waitForTransactionReceipt(sent.getResult());
- }
-}
-```
-
-#### Transfer ERC20 tokens
-
-```java
-import io.zksync.abi.TransactionEncoder;
-import io.zksync.crypto.signer.EthSigner;
-import io.zksync.methods.request.Transaction;
-import io.zksync.protocol.ZkSync;
-import io.zksync.protocol.core.Token;
-import io.zksync.protocol.core.ZkBlockParameterName;
-import io.zksync.transaction.fee.DefaultTransactionFeeProvider;
-import io.zksync.transaction.fee.ZkTransactionFeeProvider;
-import io.zksync.transaction.response.ZkSyncTransactionReceiptProcessor;
-import io.zksync.transaction.type.Transaction712;
-import io.zksync.wrappers.ERC20;
-import org.web3j.abi.FunctionEncoder;
-import org.web3j.protocol.core.methods.response.EthSendTransaction;
-import org.web3j.protocol.core.methods.response.TransactionReceipt;
-import org.web3j.protocol.exceptions.TransactionException;
-import org.web3j.utils.Numeric;
-
-import java.io.IOException;
-import java.math.BigInteger;
-
-import static io.zksync.transaction.manager.ZkSyncTransactionManager.DEFAULT_POLLING_ATTEMPTS_PER_TX_HASH;
-import static io.zksync.transaction.manager.ZkSyncTransactionManager.DEFAULT_POLLING_FREQUENCY;
-
-public class Main {
- public static void main(String ...args) throws IOException, TransactionException {
- ZkSync zksync; // Initialize client
- EthSigner signer; // Initialize signer
- ZkSyncTransactionReceiptProcessor processor = new ZkSyncTransactionReceiptProcessor(zksync, DEFAULT_POLLING_FREQUENCY, DEFAULT_POLLING_ATTEMPTS_PER_TX_HASH);
- BigInteger chainId = zksync.ethChainId().send().getChainId();
-
- // Here we're getting tokens supported by ZkSync
- Token token = zksync.zksGetConfirmedTokens(0, (short) 100).send()
- .getResult().stream()
- .findAny().orElseThrow(IllegalArgumentException::new);
-
- BigInteger amount = token.toBigInteger(1.0);
-
- BigInteger nonce = zksync
- .ethGetTransactionCount(signer.getAddress(), ZkBlockParameterName.COMMITTED).send()
- .getTransactionCount();
- String calldata = FunctionEncoder.encode(ERC20.encodeTransfer("0x", amount));
-
- Transaction estimate = Transaction.createFunctionCallTransaction(
- signer.getAddress(),
- token.getL2Address(),
- BigInteger.ZERO,
- BigInteger.ZERO,
- calldata
- );
-
- ZkTransactionFeeProvider feeProvider = new DefaultTransactionFeeProvider(zksync, Token.ETH);
-
- Transaction712 transaction = new Transaction712(
- chainId.longValue(),
- nonce,
- feeProvider.getGasLimit(estimate),
- estimate.getTo(),
- estimate.getValueNumber(),
- estimate.getData(),
- BigInteger.valueOf(100000000L),
- feeProvider.getGasPrice(),
- signer.getAddress(),
- estimate.getEip712Meta()
- );
-
- String signature = signer.getDomain().thenCompose(domain -> signer.signTypedData(domain, transaction)).join();
- byte[] message = TransactionEncoder.encode(transaction, TransactionEncoder.getSignatureData(signature));
-
- EthSendTransaction sent = zksync.ethSendRawTransaction(Numeric.toHexString(message)).send();
-
- TransactionReceipt receipt = processor.waitForTransactionReceipt(sent.getResult());
- }
-}
-```
-
-#### Transfer native coins via ZkSyncWallet
-
-```java
-import io.zksync.ZkSyncWallet;
-import io.zksync.protocol.core.Token;
-import org.web3j.protocol.core.methods.response.TransactionReceipt;
-
-import java.math.BigDecimal;
-import java.math.BigInteger;
-
-public class Main {
- public static void main(String... args) throws Exception {
- ZkSyncWallet wallet; // Initialize wallet
-
- BigInteger amount = Token.ETH.toBigInteger(0.5);
-
- TransactionReceipt receipt = wallet.transfer("0x", amount).send();
-
- //You can check balance
- BigInteger balance = wallet.getBalance().send();
-
- //Also, you can convert amount number to decimal
- BigDecimal decimalBalance = Token.ETH.intoDecimal(balance);
- }
-}
-```
-
-#### Transfer ERC20 coins via ZkSyncWallet
-
-```java
-import io.zksync.ZkSyncWallet;
-import io.zksync.protocol.core.Token;
-import org.web3j.protocol.core.methods.response.TransactionReceipt;
-
-import java.math.BigDecimal;
-import java.math.BigInteger;
-
-public class Main {
- public static void main(String... args) throws Exception {
- ZkSyncWallet wallet; // Initialize wallet
-
- Token token = new Token("L1_ADDRESS", "L2_ADDRESS", "SYMBOL", 18);
-
- BigInteger amount = Token.ETH.toBigInteger(0.5);
-
- TransactionReceipt receipt = wallet.transfer("0x", amount, token).send();
-
- //You can check balance
- BigInteger balance = wallet.getBalance().send();
-
- //Also, you can convert amount number to decimal
- BigDecimal decimalBalance = Token.ETH.intoDecimal(balance);
- }
-}
-```
-
-### Deposit
-
-#### Deposit ETH
-
-```java
-import io.zksync.protocol.ZkSync;
-import org.web3j.crypto.Credentials;
-import org.web3j.tx.RawTransactionManager;
-import org.web3j.tx.TransactionManager;
-import org.web3j.tx.gas.ContractGasProvider;
-import org.web3j.protocol.core.methods.response.TransactionReceipt;
-import io.zksync.protocol.core.Token;
-import io.zksync.protocol.provider.EthereumProvider;
-import org.web3j.protocol.Web3j;
-import org.web3j.tx.gas.StaticGasProvider;
-import org.web3j.utils.Convert;
-
-import java.io.IOException;
-import java.math.BigInteger;
-
-public class Main {
- public static void main(String... args) throws IOException {
- ZkSync zksync; // Initialize client
- Web3j web3j; // Initialize web3j client
- Credentials credentials; // Initialize credentials
- BigInteger chainId; // Initialize chainId
-
- TransactionManager manager = new RawTransactionManager(web3j, credentials, chainId.longValue());
- BigInteger gasPrice = web3j.ethGasPrice().send().getGasPrice();
- ContractGasProvider gasProvider = new StaticGasProvider(gasPrice, BigInteger.valueOf(300_000L));
- TransactionReceipt receipt = EthereumProvider
- .load(zksync, web3j, manager, gasProvider).join()
- .deposit(Token.ETH, Convert.toWei("0.001", Convert.Unit.ETHER).toBigInteger(), BigInteger.ZERO, credentials.getAddress()).join();
-
- System.out.println(receipt);
- }
-}
-```
-
-#### Deposit ERC20 tokens
-
-```java
-import io.zksync.protocol.ZkSync;
-import org.web3j.crypto.Credentials;
-import org.web3j.tx.RawTransactionManager;
-import org.web3j.tx.TransactionManager;
-import org.web3j.tx.gas.ContractGasProvider;
-import org.web3j.protocol.core.methods.response.TransactionReceipt;
-import io.zksync.protocol.core.Token;
-import io.zksync.protocol.provider.EthereumProvider;
-import org.web3j.protocol.Web3j;
-import org.web3j.tx.gas.StaticGasProvider;
-import org.web3j.utils.Convert;
-
-import java.io.IOException;
-import java.math.BigInteger;
-
-public class Main {
- public static void main(String... args) throws IOException {
- ZkSync zksync; // Initialize client
- Web3j web3j; // Initialize web3j client
- Credentials credentials; // Initialize credentials
- BigInteger chainId; // Initialize chainId
- Token token = new Token("L1_ADDRESS", "L2_ADDRESS", "SYMBOL", 18);
-
- TransactionManager manager = new RawTransactionManager(web3j, credentials, chainId.longValue());
- BigInteger gasPrice = web3j.ethGasPrice().send().getGasPrice();
- ContractGasProvider gasProvider = new StaticGasProvider(gasPrice, BigInteger.valueOf(300_000L));
- TransactionReceipt receipt = EthereumProvider
- .load(zksync, web3j, manager, gasProvider).join()
- .deposit(token, Convert.toWei("0.001", Convert.Unit.ETHER).toBigInteger(), BigInteger.ZERO, credentials.getAddress()).join();
-
- System.out.println(receipt);
- }
-}
-```
-
-### Withdraw
-
-#### Withdraw ETH
-
-```java
-import io.zksync.abi.TransactionEncoder;
-import io.zksync.crypto.signer.EthSigner;
-import io.zksync.methods.request.Transaction;
-import io.zksync.protocol.ZkSync;
-import io.zksync.protocol.core.Token;
-import io.zksync.protocol.core.ZkBlockParameterName;
-import io.zksync.transaction.fee.DefaultTransactionFeeProvider;
-import io.zksync.transaction.fee.ZkTransactionFeeProvider;
-import io.zksync.transaction.type.Transaction712;
-import io.zksync.wrappers.IL2Bridge;
-import io.zksync.transaction.response.ZkSyncTransactionReceiptProcessor;
-
-import org.web3j.abi.FunctionEncoder;
-import org.web3j.abi.datatypes.Address;
-import org.web3j.abi.datatypes.Function;
-import org.web3j.protocol.core.methods.response.TransactionReceipt;
-import org.web3j.protocol.core.methods.response.EthSendTransaction;
-import org.web3j.protocol.exceptions.TransactionException;
-import org.web3j.utils.Numeric;
-
-import java.io.IOException;
-import java.math.BigInteger;
-import java.util.Arrays;
-import java.util.Collections;
-
-import static io.zksync.transaction.manager.ZkSyncTransactionManager.DEFAULT_POLLING_ATTEMPTS_PER_TX_HASH;
-import static io.zksync.transaction.manager.ZkSyncTransactionManager.DEFAULT_POLLING_FREQUENCY;
-import static io.zksync.utils.ZkSyncAddresses.L2_ETH_TOKEN_ADDRESS;
-
-public class Main {
- public static void main(String ...args) throws IOException, TransactionException {
- ZkSync zksync; // Initialize client
- EthSigner signer; // Initialize signer
- ZkSyncTransactionReceiptProcessor processor = new ZkSyncTransactionReceiptProcessor(zksync, DEFAULT_POLLING_FREQUENCY, DEFAULT_POLLING_ATTEMPTS_PER_TX_HASH);
-
- BigInteger chainId = zksync.ethChainId().send().getChainId();
-
- BigInteger nonce = zksync
- .ethGetTransactionCount(signer.getAddress(), ZkBlockParameterName.COMMITTED).send()
- .getTransactionCount();
-
- // Get address of the default bridge contract
- String l2EthBridge = L2_ETH_TOKEN_ADDRESS;
- final Function withdraw = new Function(
- IL2Bridge.FUNC_WITHDRAW,
- Arrays.asList(new Address("TO_ADDRESS")),
- Collections.emptyList());
-
- String calldata = FunctionEncoder.encode(withdraw);
-
- BigInteger amount; // Amount you want to withdraw
-
- Transaction estimate = Transaction.createFunctionCallTransaction(
- signer.getAddress(),
- l2EthBridge,
- BigInteger.ZERO,
- BigInteger.ZERO,
- amount,
- calldata
- );
-
- ZkTransactionFeeProvider feeProvider = new DefaultTransactionFeeProvider(zksync, Token.ETH);
-
- Transaction712 transaction = new Transaction712(
- chainId.longValue(),
- nonce,
- feeProvider.getGasLimit(estimate),
- estimate.getTo(),
- estimate.getValueNumber(),
- estimate.getData(),
- BigInteger.valueOf(100000000L),
- feeProvider.getGasPrice(),
- signer.getAddress(),
- estimate.getEip712Meta()
- );
-
- String signature = signer.getDomain().thenCompose(domain -> signer.signTypedData(domain, transaction)).join();
- byte[] message = TransactionEncoder.encode(transaction, TransactionEncoder.getSignatureData(signature));
-
- EthSendTransaction sent = zksync.ethSendRawTransaction(Numeric.toHexString(message)).send();
-
- TransactionReceipt receipt = processor.waitForTransactionReceipt(sent.getResult());
- }
-}
-```
-
-#### Withdraw ERC20 tokens
-
-```java
-import io.zksync.abi.TransactionEncoder;
-import io.zksync.crypto.signer.EthSigner;
-import io.zksync.methods.request.Transaction;
-import io.zksync.protocol.ZkSync;
-import io.zksync.protocol.core.Token;
-import io.zksync.protocol.core.ZkBlockParameterName;
-import io.zksync.transaction.fee.DefaultTransactionFeeProvider;
-import io.zksync.transaction.fee.ZkTransactionFeeProvider;
-import io.zksync.transaction.response.ZkSyncTransactionReceiptProcessor;
-import io.zksync.transaction.type.Transaction712;
-import io.zksync.wrappers.IL2Bridge;
-import org.web3j.abi.FunctionEncoder;
-import org.web3j.abi.datatypes.Address;
-import org.web3j.abi.datatypes.Function;
-import org.web3j.abi.datatypes.generated.Uint256;
-import org.web3j.protocol.core.methods.response.EthSendTransaction;
-import org.web3j.protocol.core.methods.response.TransactionReceipt;
-import org.web3j.protocol.exceptions.TransactionException;
-import org.web3j.utils.Numeric;
-
-import java.io.IOException;
-import java.math.BigInteger;
-import java.util.Arrays;
-import java.util.Collections;
-
-import static io.zksync.transaction.manager.ZkSyncTransactionManager.DEFAULT_POLLING_ATTEMPTS_PER_TX_HASH;
-import static io.zksync.transaction.manager.ZkSyncTransactionManager.DEFAULT_POLLING_FREQUENCY;
-
-public class Main {
- public static void main(String ...args) throws IOException, TransactionException {
- ZkSync zksync; // Initialize client
- EthSigner signer; // Initialize signer
-
- ZkSyncTransactionReceiptProcessor processor = new ZkSyncTransactionReceiptProcessor(zksync, DEFAULT_POLLING_FREQUENCY, DEFAULT_POLLING_ATTEMPTS_PER_TX_HASH);
-
- BigInteger chainId = zksync.ethChainId().send().getChainId();
-
- BigInteger nonce = zksync
- .ethGetTransactionCount(signer.getAddress(), ZkBlockParameterName.COMMITTED).send()
- .getTransactionCount();
-
- Token token = new Token("L1_ADDRESS", "L2_ADDRESS", "SYMBOL", 18);
-
- BigInteger amount;
-
- // Get address of the default bridge contract (ERC20)
- String l2Erc20Bridge = zksync.zksGetBridgeContracts().send().getResult().getL2Erc20DefaultBridge();
- final Function withdraw = new Function(
- IL2Bridge.FUNC_WITHDRAW,
- Arrays.asList(new Address("TO_ADDRESS"),
- new Address(token.getL2Address()),
- new Uint256(amount)),
- Collections.emptyList());
-
- String calldata = FunctionEncoder.encode(withdraw);
-
- Transaction estimate = Transaction.createFunctionCallTransaction(
- signer.getAddress(),
- l2Erc20Bridge,
- BigInteger.ZERO,
- BigInteger.ZERO,
- calldata
- );
-
- ZkTransactionFeeProvider feeProvider = new DefaultTransactionFeeProvider(zksync, Token.ETH);
-
- Transaction712 transaction = new Transaction712(
- chainId.longValue(),
- nonce,
- feeProvider.getGasLimit(estimate),
- estimate.getTo(),
- estimate.getValueNumber(),
- estimate.getData(),
- BigInteger.valueOf(100000000L),
- feeProvider.getGasPrice(),
- signer.getAddress(),
- estimate.getEip712Meta()
- );
-
- String signature = signer.getDomain().thenCompose(domain -> signer.signTypedData(domain, transaction)).join();
- byte[] message = TransactionEncoder.encode(transaction, TransactionEncoder.getSignatureData(signature));
-
- EthSendTransaction sent = zksync.ethSendRawTransaction(Numeric.toHexString(message)).send();
-
- TransactionReceipt receipt = processor.waitForTransactionReceipt(sent.getResult());
- }
-}
-```
-
-#### Withdraw funds via ZkSyncWallet
+Connect to the zkSync Era network:
```java
-import io.zksync.ZkSyncWallet;
-import io.zksync.protocol.core.Token;
-import org.web3j.protocol.core.methods.response.TransactionReceipt;
-
-import java.math.BigInteger;
-
-public class Main {
- public static void main(String... args) {
- ZkSyncWallet wallet; // Initialize wallet
-
- BigInteger amount = Token.ETH.toBigInteger(0.5);
-
- // ETH By default
- TransactionReceipt receipt = wallet.withdraw("0x", amount).send();
-
- // Also we can withdraw ERC20 token
- Token token;
-
- // ERC20 token
- TransactionReceipt receipt = wallet.withdraw("0x", amount, token).send();
- }
-}
-```
-
-#### Finalize Withdraw
-
-```java
-import io.zksync.protocol.ZkSync;
-import io.zksync.protocol.provider.EthereumProvider;
-import org.web3j.crypto.Credentials;
-import org.web3j.protocol.Web3j;
-import org.web3j.protocol.core.methods.response.TransactionReceipt;
-import org.web3j.tx.RawTransactionManager;
-import org.web3j.tx.TransactionManager;
-import org.web3j.tx.gas.ContractGasProvider;
-import org.web3j.tx.gas.StaticGasProvider;
-
-import java.math.BigInteger;
-
-public class Main {
- public static void main(String... args) {
- Web3j web3j; //Initialize web3j
- ZkSync zksync; //Initialize zksync
- Credentials credentials; //Initialize credentials
- BigInteger chainId; //Initialize chainId
-
- TransactionManager manager = new RawTransactionManager(web3j, credentials, chainId.longValue());
- BigInteger gasPrice = web3j.ethGasPrice().send().getGasPrice();
- ContractGasProvider gasProvider = new StaticGasProvider(gasPrice, BigInteger.valueOf(300_000L));
- TransactionReceipt receipt = EthereumProvider
- .load(zksync, web3j, manager, gasProvider).join()
- .finalizeWithdraw("TRANSACTION_HASH", 0);
- }
-}
-```
-
-### Deploy contract
-
-With zkSync Era, you can deploy a contract, using the `create` method, by transforming the contract into binary and deploying it to the zkSync Era network.
-
-Find below some smart contract examples:
-
-- [Storage](https://github.com/zksync-sdk/zksync2-python/blob/master/examples/solidity/storage/Storage.sol): Contract without constructor.
-- [Incrementer](https://github.com/zksync-sdk/zksync2-python/blob/master/examples/solidity/incrementer/Incrementer.sol): Contract with constructor.
-- [Demo](https://github.com/zksync-sdk/zksync2-python/blob/master/examples/solidity/demo/Demo.sol): Contract that has a dependency on
- [Foo](https://github.com/zksync-sdk/zksync2-python/blob/master/examples/solidity/demo/Foo.sol) contract.
-
-Follow [this guide to compile Solidity smart contracts using the `zksolc` compiler](https://github.com/zksync-sdk/zksync2-python/blob/master/examples/README.md).
-The compiler generates a `combined.json` file that contains the bytecode and ABI of a smart contract. Those files are used in the following examples.
-
-#### Deploy contract (create2) [EIP-1014](https://eips.ethereum.org/EIPS/eip-1014)
-
-Code:
-
-```java
-import io.zksync.abi.TransactionEncoder;
-import io.zksync.crypto.signer.EthSigner;
-import io.zksync.crypto.signer.PrivateKeyEthSigner;
-import io.zksync.methods.request.Transaction;
import io.zksync.protocol.ZkSync;
-import io.zksync.protocol.core.Token;
-import io.zksync.transaction.fee.DefaultTransactionFeeProvider;
-import io.zksync.transaction.fee.ZkTransactionFeeProvider;
-import io.zksync.transaction.type.Transaction712;
-import io.zksync.utils.ContractDeployer;
-import org.web3j.abi.datatypes.Address;
-import org.web3j.crypto.Credentials;
-import org.web3j.protocol.core.DefaultBlockParameterName;
-import org.web3j.protocol.core.methods.response.TransactionReceipt;
-import org.web3j.protocol.core.methods.response.EthSendTransaction;
-import io.zksync.transaction.response.ZkSyncTransactionReceiptProcessor;
-
-
-import org.web3j.protocol.exceptions.TransactionException;
import org.web3j.protocol.http.HttpService;
-import org.web3j.utils.Numeric;
-
-import java.io.IOException;
-import java.math.BigInteger;
-import java.security.SecureRandom;
-
-import static io.zksync.transaction.manager.ZkSyncTransactionManager.DEFAULT_POLLING_ATTEMPTS_PER_TX_HASH;
-import static io.zksync.transaction.manager.ZkSyncTransactionManager.DEFAULT_POLLING_FREQUENCY;
-
-public class Main {
- public static void main(String... args) throws TransactionException, IOException {
- ZkSync zksync = ZkSync.build(new HttpService(""));
- Credentials credentials = Credentials.create("PRIVATE_KEY"); // Initialize signer
- BigInteger chainId = zksync.ethChainId().send().getChainId();
- EthSigner signer = new PrivateKeyEthSigner(credentials, chainId.longValue());
- ZkSyncTransactionReceiptProcessor processor = new ZkSyncTransactionReceiptProcessor(zksync, DEFAULT_POLLING_FREQUENCY, DEFAULT_POLLING_ATTEMPTS_PER_TX_HASH);
-
- String binary = "0x";
-
- byte[] salt = SecureRandom.getSeed(32);
-
- // Here we can precompute contract address before its deploying
- String precomputedAddress = ContractDeployer.computeL2Create2Address(new Address(signer.getAddress()), Numeric.hexStringToByteArray(binary), new byte[]{}, salt).getValue();
-
- BigInteger nonce = zksync
- .ethGetTransactionCount(credentials.getAddress(), DefaultBlockParameterName.PENDING).send()
- .getTransactionCount();
-
- Transaction estimate = Transaction.create2ContractTransaction(
- credentials.getAddress(),
- BigInteger.ZERO,
- BigInteger.ZERO,
- binary,
- "0x",
- salt
- );
-
- ZkTransactionFeeProvider feeProvider = new DefaultTransactionFeeProvider(zksync, Token.ETH);
-
- Transaction712 transaction = new Transaction712(
- chainId.longValue(),
- nonce,
- feeProvider.getGasLimit(estimate),
- estimate.getTo(),
- estimate.getValueNumber(),
- estimate.getData(),
- BigInteger.valueOf(100000000L),
- feeProvider.getGasPrice(),
- credentials.getAddress(),
- estimate.getEip712Meta()
- );
-
- String signature = signer.getDomain().thenCompose(domain -> signer.signTypedData(domain, transaction)).join();
- byte[] message = TransactionEncoder.encode(transaction, TransactionEncoder.getSignatureData(signature));
-
- EthSendTransaction sent = zksync.ethSendRawTransaction(Numeric.toHexString(message)).send();
-
- TransactionReceipt receipt = processor.waitForTransactionReceipt(sent.getResult());
- }
-}
-```
-
-#### Deploy contract (create)
-
-Code:
-
-```java
-import io.zksync.abi.TransactionEncoder;
-import io.zksync.crypto.signer.EthSigner;
-import io.zksync.methods.request.Transaction;
-import io.zksync.protocol.ZkSync;
-import io.zksync.protocol.core.Token;
-import io.zksync.protocol.core.ZkBlockParameterName;
-import io.zksync.transaction.fee.DefaultTransactionFeeProvider;
-import io.zksync.transaction.fee.ZkTransactionFeeProvider;
-import io.zksync.transaction.type.Transaction712;
-import io.zksync.utils.ZkSyncAddresses;
-import io.zksync.wrappers.NonceHolder;
-import org.web3j.protocol.core.methods.response.TransactionReceipt;
-import org.web3j.protocol.core.methods.response.EthSendTransaction;
-import io.zksync.transaction.response.ZkSyncTransactionReceiptProcessor;
-
-import org.web3j.tx.ReadonlyTransactionManager;
-import org.web3j.tx.gas.DefaultGasProvider;
-import org.web3j.utils.Numeric;
-
-import java.math.BigInteger;
-
-import static io.zksync.transaction.manager.ZkSyncTransactionManager.DEFAULT_POLLING_ATTEMPTS_PER_TX_HASH;
-import static io.zksync.transaction.manager.ZkSyncTransactionManager.DEFAULT_POLLING_FREQUENCY;
-
-public class Main {
- public static void main(String... args) throws Exception {
- ZkSync zksync; // Initialize client
- EthSigner signer; // Initialize signer
- ZkSyncTransactionReceiptProcessor processor = new ZkSyncTransactionReceiptProcessor(zksync, DEFAULT_POLLING_FREQUENCY, DEFAULT_POLLING_ATTEMPTS_PER_TX_HASH);
-
- String binary = "0x";
-
- BigInteger chainId = zksync.ethChainId().send().getChainId();
-
- NonceHolder nonceHolder = NonceHolder.load(ZkSyncAddresses.NONCE_HOLDER_ADDRESS, zksync, new ReadonlyTransactionManager(zksync, signer.getAddress()), new DefaultGasProvider());
-
- BigInteger deploymentNonce = nonceHolder.getDeploymentNonce(signer.getAddress()).send();
-
- BigInteger nonce = zksync
- .ethGetTransactionCount(signer.getAddress(), ZkBlockParameterName.COMMITTED).send()
- .getTransactionCount();
-
- Transaction estimate = Transaction.createContractTransaction(
- signer.getAddress(),
- BigInteger.ZERO,
- BigInteger.ZERO,
- binary,
- "0x"
- );
-
- ZkTransactionFeeProvider feeProvider = new DefaultTransactionFeeProvider(zksync, Token.ETH);
-
- Transaction712 transaction = new Transaction712(
- chainId.longValue(),
- nonce,
- feeProvider.getGasLimit(estimate),
- estimate.getTo(),
- estimate.getValueNumber(),
- estimate.getData(),
- BigInteger.valueOf(100000000L),
- feeProvider.getGasPrice(),
- signer.getAddress(),
- estimate.getEip712Meta()
- );
-
- String signature = signer.getDomain().thenCompose(domain -> signer.signTypedData(domain, transaction)).join();
- byte[] message = TransactionEncoder.encode(transaction, TransactionEncoder.getSignatureData(signature));
-
- EthSendTransaction sent = zksync.ethSendRawTransaction(Numeric.toHexString(message)).send();
-
- // You can check transaction status as the same way as in Web3
- TransactionReceipt receipt = processor.waitForTransactionReceipt(sent.getResult());
- }
-}
-```
-
-#### Deploy contract via ZkSyncWallet
-
-Code:
-
-```java
-import io.zksync.ZkSyncWallet;
-import org.web3j.protocol.core.methods.response.TransactionReceipt;
-import org.web3j.utils.Numeric;
public class Main {
public static void main(String ...args) {
- ZkSyncWallet wallet; // Initialize wallet
-
- TransactionReceipt receipt = wallet.deploy(Numeric.hexStringToByteArray("0x")).send();
- }
-}
-```
-
-#### Deploy contract with constructor via ZkSyncWallet
-
-```java
-import io.zksync.ZkSyncWallet;
-import org.web3j.abi.FunctionEncoder;
-import org.web3j.abi.datatypes.Type;
-import org.web3j.abi.datatypes.Utf8String;
-import org.web3j.abi.datatypes.generated.Uint256;
-import org.web3j.protocol.core.methods.response.TransactionReceipt;
-import org.web3j.utils.Numeric;
-
-import java.math.BigInteger;
-import java.util.ArrayList;
-import java.util.List;
-
-public class Main {
- public static void main(String ...args) {
- ZkSyncWallet wallet; // Initialize wallet
-
- String name = "NAME";
- String symbol = "SYMBOL";
- BigInteger amount = new BigInteger("666234").multiply(new BigInteger("10").pow(18));
-
- List inputParameter = new ArrayList<>();
- inputParameter.add(new Utf8String(name));
- inputParameter.add(new Utf8String(symbol));
- inputParameter.add(new Uint256(amount));
-
- String bytecode = "0x";
- String calldata = FunctionEncoder.encodeConstructor(inputParameter);
- TransactionReceipt receipt = wallet.deploy(Numeric.hexStringToByteArray(bytecode), Numeric.hexStringToByteArray(calldata)).send();
- }
-}
-```
-
-### Contract interaction (execute)
-
-#### Execute contract
-
-```java
-import io.zksync.abi.TransactionEncoder;
-import io.zksync.crypto.signer.EthSigner;
-import io.zksync.methods.request.Transaction;
-import io.zksync.protocol.ZkSync;
-import io.zksync.protocol.core.Token;
-import io.zksync.protocol.core.ZkBlockParameterName;
-import io.zksync.transaction.fee.DefaultTransactionFeeProvider;
-import io.zksync.transaction.fee.ZkTransactionFeeProvider;
-import io.zksync.transaction.type.Transaction712;
-import io.zksync.transaction.response.ZkSyncTransactionReceiptProcessor;
-
-import org.web3j.abi.FunctionEncoder;
-import org.web3j.abi.datatypes.Function;
-import org.web3j.abi.datatypes.generated.Uint256;
-import org.web3j.protocol.core.methods.response.TransactionReceipt;
-import org.web3j.protocol.core.methods.response.EthSendTransaction;
-import org.web3j.protocol.exceptions.TransactionException;
-import org.web3j.utils.Numeric;
-
-import java.io.IOException;
-import java.math.BigInteger;
-import java.util.Collections;
-
-import static io.zksync.transaction.manager.ZkSyncTransactionManager.DEFAULT_POLLING_ATTEMPTS_PER_TX_HASH;
-import static io.zksync.transaction.manager.ZkSyncTransactionManager.DEFAULT_POLLING_FREQUENCY;
-
-public class Main {
- public static void main(String... args) throws IOException, TransactionException {
- ZkSync zksync; // Initialize client
- EthSigner signer; // Initialize signer
- ZkSyncTransactionReceiptProcessor processor = new ZkSyncTransactionReceiptProcessor(zksync, DEFAULT_POLLING_FREQUENCY, DEFAULT_POLLING_ATTEMPTS_PER_TX_HASH);
-
- BigInteger chainId = zksync.ethChainId().send().getChainId();
-
- BigInteger nonce = zksync
- .ethGetTransactionCount(signer.getAddress(), ZkBlockParameterName.COMMITTED).send()
- .getTransactionCount();
-
- String contractAddress = "0x";
-
- Function contractFunction = new Function(
- "increment",
- Collections.singletonList(new Uint256(BigInteger.ONE)),
- Collections.emptyList());
-
- String calldata = FunctionEncoder.encode(function);
-
- Transaction estimate = Transaction.createFunctionCallTransaction(
- signer.getAddress(),
- contractAddress,
- BigInteger.ZERO,
- BigInteger.ZERO,
- calldata
- );
-
- ZkTransactionFeeProvider feeProvider = new DefaultTransactionFeeProvider(zksync, Token.ETH);
-
- Transaction712 transaction = new Transaction712(
- chainId.longValue(),
- nonce,
- feeProvider.getGasLimit(estimate),
- estimate.getTo(),
- estimate.getValueNumber(),
- estimate.getData(),
- BigInteger.valueOf(100000000L),
- feeProvider.getGasPrice(),
- signer.getAddress(),
- estimate.getEip712Meta()
- );
-
- String signature = signer.getDomain().thenCompose(domain -> signer.signTypedData(domain, transaction)).join();
- byte[] message = TransactionEncoder.encode(transaction, TransactionEncoder.getSignatureData(signature));
-
- EthSendTransaction sent = zksync.ethSendRawTransaction(Numeric.toHexString(message)).send();
- TransactionReceipt receipt = processor.waitForTransactionReceipt(sent.getResult());
- }
-}
-```
-
-#### Execute contact via ZkSyncWallet
-
-```java
-import io.zksync.ZkSyncWallet;
-import org.web3j.abi.datatypes.Function;
-import org.web3j.abi.datatypes.generated.Uint256;
-import org.web3j.protocol.core.methods.response.TransactionReceipt;
-
-import java.math.BigInteger;
-import java.util.Collections;
-
-public class Main {
- public static void main(String... args) {
- ZkSyncWallet wallet; // Initialize wallet
-
- String contractAddress = "0x";
-
- // Example contract function
- Function contractFunction = new Function(
- "increment",
- Collections.singletonList(new Uint256(BigInteger.ONE)),
- Collections.emptyList());
-
- TransactionReceipt receipt = wallet.execute(contractAddress, contractFunction).send();
+ ZkSync zksync = ZkSync.build(new HttpService("http://127.0.0.1:3050"));
}
}
```
-#### Execute contract via Web3j generic contract
+Get the latest block number:
```java
-import io.zksync.crypto.signer.EthSigner;
-import io.zksync.protocol.ZkSync;
-import io.zksync.protocol.core.Token;
-import io.zksync.transaction.fee.DefaultTransactionFeeProvider;
-import io.zksync.transaction.fee.ZkTransactionFeeProvider;
-import io.zksync.transaction.manager.ZkSyncTransactionManager;
-import org.web3j.protocol.core.methods.response.TransactionReceipt;
-import org.web3j.tx.gas.DefaultGasProvider;
-
-import java.math.BigInteger;
-
-public class Main {
- public static void main(String... args) {
- ZkSync zksync; // Initialize client
- EthSigner signer; // Initialize signer
-
- ZkTransactionFeeProvider feeProvider = new DefaultTransactionFeeProvider(zksync, Token.ETH);
- ZkSyncTransactionManager transactionManager = new ZkSyncTransactionManager(zksync, signer, feeProvider);
-
- // Wrapper class of a contract generated by Web3j or Epirus ClI
- SomeContract contract = SomeContract.load("0x", zksync, transactionManager, new DefaultGasProvider()).send();
-
- // Generated method in wrapper
- TransactionReceipt receipt = contract.increment(BigInteger.ONE).send();
-
- //The same way you can call read function
-
- BigInteger result = contract.get().send();
- }
-}
+BigInteger blockNumber = zksync.ethBlockNumber().send().getBlockNumber();
+;
```
-### Estimate transaction fee
-
-#### Get fee via TransactionFeeProvider
-
```java
-import io.zksync.methods.request.Transaction;
-import io.zksync.protocol.ZkSync;
-import io.zksync.protocol.core.Token;
-import io.zksync.transaction.fee.DefaultTransactionFeeProvider;
-import io.zksync.transaction.fee.Fee;
-import io.zksync.transaction.fee.ZkTransactionFeeProvider;
-
-public class Main {
- public static void main(String ...args) {
- ZkSync zksync; // Initialize client
-
- ZkTransactionFeeProvider feeProvider = new DefaultTransactionFeeProvider(zksync, Token.ETH);
-
- Transaction forEstimate; // Create transaction as described above
-
- Fee fee = feeProvider.getFee(forEstimate);
- }
-}
+ZksBlock block = zksync.zksGetBlockByHash("0xb472c070c9e121ba42702f6c322b7b266e287a4d8b5fa426ed265b105430c397", true).send().getBlock();
```
-#### Get price of the transaction execution (currently not working properly)
-
-::: warning
-Feature currently unsupported. Under development
-:::
-
```java
-import io.zksync.methods.request.Transaction;
-import io.zksync.protocol.ZkSync;
-import io.zksync.transaction.fee.Fee;
-
-import java.io.IOException;
-import java.math.BigInteger;
-
-public class Main {
- public static void main(String... args) throws IOException {
- ZkSync zksync; // Initialize client
-
- Transaction forEstimate; // Create transaction as described above
-
- Fee fee = zksync.zksEstimateFee(forEstimate).send().getResult();
-
- // Also possible to use eth_estimateGas
- BigInteger gasUsed = zksync.ethEstimateGas(forEstimate).send().getAmountUsed();
- }
-}
+ZkTransaction transaction = zksync.zksGetTransactionByHash("0x9af27afed9a4dd018c0625ea1368afb8ba08e4cfb69b3e76dfb8521c8a87ecfc").send().getResult();
```
diff --git a/docs/build/sdks/java/paymaster-utils.md b/docs/build/sdks/java/paymaster-utils.md
new file mode 100644
index 0000000000..f02822fb7c
--- /dev/null
+++ b/docs/build/sdks/java/paymaster-utils.md
@@ -0,0 +1,69 @@
+---
+head:
+ - - meta
+ - name: "twitter:title"
+ content: Java SDK Paymaster Utilities | zkSync Docs
+---
+
+# Paymaster Utilities
+
+The [paymaster utilities](https://github.com/zksync-sdk/zksync2-java/blob/master/src/main/java/io/zksync/utils/Paymaster.java) contains essential utilities for using paymasters on zkSync Era.
+
+## Contract interfaces
+
+Constant ABI definition for
+the [Paymaster Flow Interface](https://github.com/matter-labs/era-contracts/blob/583cb674a2b942dda34e9f46edb5a9f5b696b90a/l2-contracts/contracts/interfaces/IPaymasterFlow.sol).
+
+## Functions
+
+### `encodeApprovalBased`
+
+Returns encoded input for an approval-based paymaster.
+
+#### Inputs
+
+| Parameter | Type | Description |
+| ------------------ | ------------ | --------------------------- |
+| `tokenAddress` | `String` | Address of paymaster token. |
+| `minimalAllowance` | `BigInteger` | Paymaster allowance. |
+| `input` | `byte[]` | |
+
+### `encodeGeneral`
+
+As above but for general-based paymaster.
+
+#### Inputs
+
+| Parameter | Type | Description |
+| --------- | -------- | ----------- |
+| `input` | `byte[]` | |
+
+#### Examples
+
+Creating `General` paymaster parameters.
+
+```java
+PaymasterParams paymasterParams = new PaymasterParams(
+ "0x0a67078A35745947A37A552174aFe724D8180c25",
+ Numeric.hexStringToByteArray(FunctionEncoder.encode(
+ Paymaster.encodeGeneral(
+ new byte[] {})
+ )
+ )
+ );
+```
+
+Creating `ApprovalBased` paymaster parameters.
+
+```java
+PaymasterParams paymasterParams = new PaymasterParams(
+ "0x0a67078A35745947A37A552174aFe724D8180c25",
+ Numeric.hexStringToByteArray(FunctionEncoder.encode(
+ Paymaster.encodeApprovalBased(
+ "0x65C899B5fb8Eb9ae4da51D67E1fc417c7CB7e964",
+ BigInteger.ONE,
+ new byte[] {})
+ )
+ )
+ );
+```
diff --git a/docs/build/sdks/java/providers.md b/docs/build/sdks/java/providers.md
index 4f8e00810f..8b90d82961 100644
--- a/docs/build/sdks/java/providers.md
+++ b/docs/build/sdks/java/providers.md
@@ -7,15 +7,32 @@ head:
# Providers
-Providers are objects that wrap interactions with the zkSync Era node. If you are new to the concept of providers in `web3`, check out the [Web3j docs](https://docs.web3j.io/4.9.8/getting_started/interacting_with_node/).
+A Web3 Provider object provides application-layer access to underlying blockchain networks.
-zkSync Era fully supports the Ethereum Web3 JSON-RPC API, so you can use the provider objects from `web3j`. However, zkSync API provides some additional JSON-RPC methods, which
-allow:
+The [`zksync2-java`](https://github.com/zksync-sdk/zksync2-java) library supports provider methods from the [`web3j`](https://docs.web3j.io/4.9.7/) library and
+supplies additional functionality.
-- Easy tracking of L1<->L2 transactions.
-- Different stages of finality for transactions. By default, the RPC returns information about the last state processed by the server, but some use cases may require tracking "finalized" transactions only.
+[`ZkSync`](#ZkSync): Supplies the same functionality as `Web3` and extends it with zkSync-specific methods.
-### `Initialize`
+## `ZkSync`
+
+:::info
+
+- This doc details zkSync Era specific methods.
+- Web3Swift implementations link to their [docs](https://docs.web3j.io/4.9.7/).
+ :::
+
+### `constructor`
+
+Returns a `ZkSyncClient` object.
+
+#### Inputs
+
+| Parameter | Type | Description |
+| ------------- | ----- | --------------------------- |
+| `providerURL` | `URL` | Network RPC URL (optional). |
+
+#### Example
```java
import io.zksync.protocol.ZkSync;
@@ -28,138 +45,221 @@ public class Main {
}
```
-#### Inputs and outputs
+### `estimateFee`
+
+Returns an estimated [`ZksEstimateFee`](./types.md#fee) for requested transaction.
+
+#### Inputs
+
+| Parameter | Type | Description |
+| ------------- | ------------- | -------------------- |
+| `transaction` | `Transaction` | Transaction request. |
+
+```java
+import io.zksync.protocol.ZkSync;
+import org.web3j.protocol.http.HttpService;
+import io.zksync.methods.response.ZkTransactionReceipt;
+
+public class Main {
+ public static void main(String ...args) {
+ io.zksync.methods.request.Transaction estimate = io.zksync.methods.request.Transaction.createFunctionCallTransaction(
+ "0x7e5f4552091a69125d5dfcb7b8c2659029395bdf",
+ "0x7e5f4552091a69125d5dfcb7b8c2659029395bdf",
+ BigInteger.ZERO,
+ BigInteger.ZERO,
+ "0x"
+ );
+
+ Fee fee = zksync.zksEstimateFee(estimate).send().getResult();
+ }
+```
+
+### `estimateGas`
-| Name | Description |
-| ------------ | ------------------------------------ |
-| web3jService | URL of the zkSync Era operator node. |
-| returns | `Provider` object. |
+Returns an estimate of the amount of gas required to submit a transaction to the network.
-### `zksGetAllAccountBalances`
+#### Inputs
-Get all known balances for a given account.
+| Parameter | Type | Description |
+| ------------- | ------------- | ------------------ |
+| `transaction` | `Transaction` | Transaction class. |
-Example:
+#### Example
```java
import io.zksync.protocol.ZkSync;
import org.web3j.protocol.http.HttpService;
+import io.zksync.methods.response.ZkTransactionReceipt;
public class Main {
public static void main(String ...args) {
- ZkSync zksync = ZkSync.build(new HttpService("https://sepolia.era.zksync.dev"));
- ZksAccountBalances response = zksync.zksGetAllAccountBalances("ADDRESS").send();
+ io.zksync.methods.request.Transaction estimate = io.zksync.methods.request.Transaction.createFunctionCallTransaction(
+ "0x7e5f4552091a69125d5dfcb7b8c2659029395bdf",
+ "0x7e5f4552091a69125d5dfcb7b8c2659029395bdf",
+ BigInteger.ZERO,
+ BigInteger.ZERO,
+ "0x"
+ );
+
+ BigInteger gasUsed = zksync.ethEstimateGas(estimate).send().getAmountUsed();
}
}
```
-#### Inputs and outputs
+### `estimateGasL1`
-| Name | Description |
-| ------- | ---------------------------------------------------------------------------- |
-| address | The user address with balances to check. |
-| returns | 'ZksAccountBalances': List of all balances where account has non-zero value. |
+Returns an estimate of the amount of gas required to submit a transaction from L1 to L2 as a `EthEstimateGas` object.
-### `zksGetConfirmedTokens`
+Calls the `zks_estimateL1ToL2` JSON-RPC method.
-Get list of the tokens supported by ZkSync Era. The tokens are returned in alphabetical order by their symbol. This means that the token id is its position in an alphabetically
-sorted array of tokens.
+#### Inputs
-Example:
+| Parameter | Type | Description |
+| ------------- | ------------- | ------------------ |
+| `transaction` | `Transaction` | Transaction class. |
+
+#### Example
```java
import io.zksync.protocol.ZkSync;
import org.web3j.protocol.http.HttpService;
+import io.zksync.methods.response.ZkTransactionReceipt;
public class Main {
public static void main(String ...args) {
- ZksTokens response = zksync.zksGetConfirmedTokens(offset, limit).send(); }
+ io.zksync.methods.request.Transaction estimate = io.zksync.methods.request.Transaction.createFunctionCallTransaction(
+ "0x7e5f4552091a69125d5dfcb7b8c2659029395bdf",
+ "0x7e5f4552091a69125d5dfcb7b8c2659029395bdf",
+ BigInteger.ZERO,
+ BigInteger.ZERO,
+ "0x"
+ );
+
+ BigInteger estimatedGas = zksync.estimateGasL1(estimate).send().getAmountUsed();
+ }
}
```
-#### Inputs and outputs
+### `estimateL1ToL2Execute`
-| Name | Description |
-| ------- | -------------------------------------- |
-| from | Offset of tokens. |
-| list | Limit of amount of tokens to return. |
-| returns | Prepared get confirmed tokens request. |
+Returns gas estimation for an L1 to L2 execute operation.
-### `zksGetBridgeContracts`
+#### Inputs
-Get default bridges addresses deployed on L1 and L2.
+| Parameter | Type | Description |
+| -------------------- | ------------ | ---------------------------------------------------------------- |
+| `contractAddress` | `String` | Address of contract. |
+| `calldata` | `byte[]` | The transaction call data. |
+| `caller` | `String` | Caller address. |
+| `l2GasLimit` | `BigInteger` | Current L2 gas value (optional). |
+| `l2Value` | `BigInteger` | L2 amount (optional). |
+| `factoryDeps` | `byte[][]` | Factory deps (optional). |
+| `operatorTip` | `BigInteger` | Operator tip (optional). |
+| `gasPerPubdataByte?` | `BigInteger` | Constant representing current amount of gas per byte (optional). |
+| `refoundRecepient` | `String` | Refound address. |
-Example:
+#### Example
```java
import io.zksync.protocol.ZkSync;
import org.web3j.protocol.http.HttpService;
-import io.zksync.protocol.core.BridgeAddresses;
+import io.zksync.methods.response.ZkTransactionReceipt;
public class Main {
public static void main(String ...args) {
- BridgeAddresses bridgeAddresses = zksync.zksGetBridgeContracts().sendAsync().join().getResult();
+ String mainContractAddress = zksync.zksMainContract().sendAsync().join()
+
+ BigInteger estimatedGas = zksync.estimateGasL1(mainContractAddress, Numeric.hexStringToByteArray("0x"), "0x36615Cf349d7F6344891B1e7CA7C72883F5dc049", null, BigInteger.
+ valueOf(7_000_000_000L), null, null, null, null).
+ send().
+ getAmountUsed();
+ }
}
```
-#### Inputs and outputs
+### `allAccountBalances`
-| Name | Description |
-| ------- | ------------------------------------- |
-| from | Offset of tokens. |
-| list | Limit of amount of tokens to return. |
-| returns | Prepared get bridge contract request. |
+Returns all balances for confirmed tokens given by an account address.
-### `zksMainContract`
+Calls the `zks_getAllAccountBalances` JSON-RPC method.
-Get address of main contract for current network chain.
+#### Inputs
-Example:
+| Parameter | Type | Description |
+| --------- | -------- | ---------------- |
+| `address` | `String` | Account address. |
+
+#### Example
```java
import io.zksync.protocol.ZkSync;
import org.web3j.protocol.http.HttpService;
+import io.zksync.methods.response.ZkTransactionReceipt;
public class Main {
public static void main(String ...args) {
- String mainContract = zksync.zksMainContract().sendAsync().join().getResult();
+ ZksAccountBalances allBalances = zkSync.zksGetAllAccountBalances("0x36615Cf349d7F6344891B1e7CA7C72883F5dc049").send();
+ }
}
```
-#### Inputs and outputs
+### `getBlockDetails`
-| Name | Description |
-| ------- | ------------------------------- |
-| returns | Prepared main contract request. |
+Returns additional zkSync-specific information about the L2 block.
-### `zksGetTestnetPaymaster`
+Calls the `zks_getBlockDetails` JSON-RPC method.
-Get the address of the testnet paymaster; i.e. the paymaster that is available on testnets and enables paying fees in ERC-20 compatible tokens.
+#### Inputs
-Example:
+| Parameter | Type | Description |
+| ------------- | ------------ | ------------- |
+| `blockNumber` | `BigInteger` | Block number. |
+
+#### Example
```java
import io.zksync.protocol.ZkSync;
import org.web3j.protocol.http.HttpService;
-import io.zksync.methods.response.ZksTestnetPaymasterAddress;
+import io.zksync.methods.response.ZkTransactionReceipt;
public class Main {
public static void main(String ...args) {
- ZksTestnetPaymasterAddress response = zksync.zksGetTestnetPaymaster().send();
+ ZksBlockDetails blockDetails = zkSync.getBlockDetails(BigInteger.valueOf(90_000)).send();
+ }
+}
+```
+
+### `zksGetBridgeContracts`
+
+Returns the addresses of the default zkSync Era bridge contracts on both L1 and L2.
+
+#### Example
+
+```java
+import io.zksync.protocol.ZkSync;
+import org.web3j.protocol.http.HttpService;
+import io.zksync.methods.response.ZkTransactionReceipt;
+
+public class Main {
+ public static void main(String ...args) {
+ ZksBlockDetails blockDetails = zkSync.zksGetBridgeContracts().send();
+ }
}
```
-#### Inputs and outputs
+### `getL1BatchBlockRange`
-| Name | Description |
-| ------- | ------------------------------- |
-| returns | Prepared get paymaster request. |
+Returns the range of blocks contained within a batch given by batch number.
-### `zksGetTransactionReceipt`
+Calls the `zks_getL1BatchBlockRange` JSON-RPC method.
-Get transaction receipt. The same as `eth_getTransactionReceipt` but with additional fields belong to L2toL1Log
+#### Inputs
-Example:
+| Parameter | Type | Description |
+| --------------- | ------------ | ---------------- |
+| `l1BatchNumber` | `BigInteger` | L1 batch number. |
+
+#### Example
```java
import io.zksync.protocol.ZkSync;
@@ -168,22 +268,25 @@ import io.zksync.methods.response.ZkTransactionReceipt;
public class Main {
public static void main(String ...args) {
- ZkTransactionReceipt zkReceipt = wallet.getZksync().zksGetTransactionReceipt("TRANSACTION_HASH").send().getTransactionReceipt().get();
+ BigInteger l1BatchNumber = zkSync.getL1BatchNumber().send().getL1BatchNumber();
+ BlockRange blockRange = zkSync.getL1BatchBlockRange(l1BatchNumber).send().getResult();
+ }
}
```
-#### Inputs and outputs
+### `getL1BatchDetails`
-| Name | Description |
-| --------------- | ----------------------------------------------------- |
-| transactionHash | Hash of the sent message's executed transaction hash. |
-| returns | Prepared get transaction receipt request. |
+Returns data pertaining to a given batch.
-### `zksGetTransactionDetails`
+Calls the `zks_getL1BatchDetails` JSON-RPC method.
+
+#### Inputs
-Get transaction details.
+| Parameter | Type | Description |
+| --------- | ------------ | ---------------- |
+| `number` | `BigInteger` | L1 batch number. |
-Example:
+#### Example
```java
import io.zksync.protocol.ZkSync;
@@ -192,22 +295,19 @@ import io.zksync.methods.response.ZkTransactionReceipt;
public class Main {
public static void main(String ...args) {
- ZksGetTransactionDetails response = zksync.zksGetTransactionDetails("TRANSACTION_HASH").send();
+ BigInteger l1BatchNumber = zkSync.getL1BatchNumber().send().getL1BatchNumber();
+ BatchDetails blockRange = zkSync.getL1BatchBlockRange(l1BatchNumber).send().getResult();
+ }
}
```
-#### Inputs and outputs
+### `getL1BatchNumber`
-| Name | Description |
-| --------------- | ----------------------------------------------------- |
-| transactionHash | Hash of the sent message's executed transaction hash. |
-| returns | Prepared get transaction details request. |
+Returns the latest L1 batch number.
-### `zksGetTransactionByHash`
+Calls the `zks_getL1BatchNumber` JSON-RPC method.
-Get transaction details.
-
-Example:
+#### Example
```java
import io.zksync.protocol.ZkSync;
@@ -216,22 +316,25 @@ import io.zksync.methods.response.ZkTransactionReceipt;
public class Main {
public static void main(String ...args) {
- ZksGetTransactionDetails response = zksync.zksGetTransactionDetails("TRANSACTION_HASH").send();
+ BigInteger l1BatchNumber = zkSync.getL1BatchNumber().send().getL1BatchNumber();
+ }
}
```
-#### Inputs and outputs
+### `getL2ToL1LogProof`
-| Name | Description |
-| --------------- | ----------------------------------------------------- |
-| transactionHash | Hash of the sent message's executed transaction hash. |
-| returns | Prepared get transaction details request. |
+Returns the proof for a transaction's L2 to L1 log sent via the L1Messenger system contract.
-### `zksEstimateFee`
+Calls the `zks_getL2ToL1LogProof` JSON-RPC method.
-Estimate fee for the given transaction at the latest committed block time.
+#### Inputs
-Example:
+| Parameter | Type | Description |
+| --------- | -------- | ---------------------------------------------------------------- |
+| `txHash` | `String` | Hash of the L2 transaction the L2 to L1 log was produced within. |
+| `index` | `int` | The index of the L2 to L1 log in the transaction (optional). |
+
+#### Example
```java
import io.zksync.protocol.ZkSync;
@@ -240,72 +343,91 @@ import io.zksync.methods.response.ZkTransactionReceipt;
public class Main {
public static void main(String ...args) {
- Transaction forEstimate;
-
- Fee fee = zksync.zksEstimateFee(forEstimate).send().getResult();
+ // Any L2 -> L1 transaction can be used.
+ // In this case, withdrawal transaction is used.
+ String tx = "0x2a1c6c74b184965c0cb015aae9ea134fd96215d2e4f4979cfec12563295f610e";
+ L2ToL1MessageProof result = zkSync.zksGetL2ToL1LogProof(tx, 0).sendAsync().join().getResult();
}
+}
```
-#### Inputs and outputs
+### `mainContract`
-| Name | Description |
-| ----------- | -------------------------------- |
-| transaction | Transaction data for estimation. |
-| returns | Prepared estimate fee request. |
+Returns the main zkSync Era smart contract address.
-### `zksL1ChainId`
+Calls the `zks_getMainContract` JSON-RPC method.
-Get chain identifier of the L1 chain.
+#### Example
-Example:
+```java
+import io.zksync.protocol.ZkSync;
+import org.web3j.protocol.http.HttpService;
+import io.zksync.methods.response.ZkTransactionReceipt;
+
+public class Main {
+ public static void main(String ...args) {
+ String result = zkSync.zksMainContract().sendAsync().join().getResult();
+ }
+}
+```
+
+### `zksGetTestnetPaymaster`
+
+Returns the testnet paymaster address if available, or null.
+
+#### Example
```java
import io.zksync.protocol.ZkSync;
import org.web3j.protocol.http.HttpService;
+import io.zksync.methods.response.ZkTransactionReceipt;
public class Main {
public static void main(String ...args) {
- ZksL1ChainId response = zksync.zksL1ChainId().send();
+ String result = zkSync.zksGetTestnetPaymaster().sendAsync().join().getResult();
}
+}
```
-#### Inputs and outputs
+### `zksGetTransactionDetails`
+
+Returns data from a specific transaction given by the transaction hash.
-| Name | Description |
-| ------- | ----------------------------- |
-| returns | Prepared L1 chain id request. |
+Calls the `getTransactionDetails` JSON-RPC method.
-### `zksGetL2ToL1MsgProof`
+#### Inputs
-Get the proof for the message sent via the L1Messenger system contract.
+| Parameter | Type | Description |
+| --------- | ----------- | ----------------- |
+| `txHash` | `BytesLike` | Transaction hash. |
-Example:
+#### Example
```java
import io.zksync.protocol.ZkSync;
import org.web3j.protocol.http.HttpService;
+import io.zksync.methods.response.ZkTransactionReceipt;
public class Main {
public static void main(String ...args) {
- ZksL1ChainId response = zksync.zksL1ChainId().send();
+ TransactionDetails result = zkSync.zksGetTransactionDetails("").sendAsync().join().getResult();
}
+}
```
-#### Inputs and outputs
+### `getTransferTransaction`
-| Name | Description |
-| ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| block | The number of the block where the message was emitted. |
-| sender | The sender of the message (i.e. the account that called the L1Messenger system contract). |
-| message | The keccak256 hash of the message that was sent. |
-| l2LogPosition | The index in the block of the event that was emitted by the L1Messenger when submitting this message. If it is omitted, the proof for the first message with such content will be returned. |
-| returns | Prepared L1 chain id request. |
+Returns the populated transfer transaction.
-### `ethEstimateGas`
+#### Inputs
-Generates and returns an estimate of how much gas is required to allow the transaction to complete. The transaction will not be added to the blockchain.
+| Parameter | Type | Description |
+| -------------------- | --------------------- | -------------------------- |
+| `tx` | `TransferTransaction` | TransferTransaction class. |
+| `transactionManager` | `TransactionManager` | L2 transaction manager. |
+| `gasProvider` | `ContractGasProvider` | L2 gas provider. |
-Example:
+#### Example
```java
import io.zksync.protocol.ZkSync;
@@ -314,40 +436,121 @@ import io.zksync.methods.response.ZkTransactionReceipt;
public class Main {
public static void main(String ...args) {
- Transaction forEstimate;
+ TransferTransaction transaction = new TransferTransaction(RECEIVER, amount, signer.getAddress());
+ Transaction result = zkSync.getTransferTransaction(transaction, transactionManager, gasProvider).sendAsync().join().getResult();
+ }
+}
+```
+
+Retrieve populated ETH transfer transaction using paymaster to facilitate fee payment with an ERC20 token.
+
+```java
+import io.zksync.protocol.ZkSync;
+import org.web3j.protocol.http.HttpService;
+import io.zksync.methods.response.ZkTransactionReceipt;
+
+public class Main {
+ public static void main(String ...args) {
+ BigInteger amount = BigInteger.valueOf(7_000_000_000L);
+ PaymasterParams paymasterParams = new PaymasterParams(PAYMASTER, Numeric.hexStringToByteArray(FunctionEncoder.encode(Paymaster.encodeApprovalBased(TOKEN, BigInteger.ONE, new byte[] {}))));
+
+ TransferTransaction transaction = new TransferTransaction(RECEIVER, amount, signer.getAddress(), paymasterParams);
+ Transaction result = zkSync.getTransferTransaction(transaction, transactionManager, gasProvider).sendAsync().join().getResult();
+ }
+}
+```
+
+### `getWithdrawTx`
+
+Returns the populated withdrawal transaction.
+
+#### Inputs
+
+| Parameter | Type | Description |
+| -------------------- | --------------------- | -------------------------- |
+| `tx` | `TransferTransaction` | TransferTransaction class. |
+| `transactionManager` | `TransactionManager` | L2 transaction manager. |
+| `gasProvider` | `ContractGasProvider` | L2 gas provider. |
+
+#### Examples
+
+Retrieve populated ETH withdrawal transactions.
+
+```java
+import io.zksync.protocol.ZkSync;
+import org.web3j.protocol.http.HttpService;
+import io.zksync.methods.response.ZkTransactionReceipt;
- BigInteger gasUsed = zksync.ethEstimateGas(forEstimate).send().getAmountUsed();
+public class Main {
+ public static void main(String ...args) {
+ WithdrawTransaction transaction = new WithdrawTransaction(RECEIVER, amount, signer.getAddress());
+ Transaction result = zkSync.getWithdrawTx(transaction, transactionManager, gasProvider).sendAsync().join().getResult();
}
+}
```
-#### Inputs and outputs
+Retrieve populated ETH withdrawal transaction using paymaster to facilitate fee payment with an ERC20 token.
+
+```java
+import io.zksync.protocol.ZkSync;
+import org.web3j.protocol.http.HttpService;
+import io.zksync.methods.response.ZkTransactionReceipt;
+
+public class Main {
+ public static void main(String ...args) {
+ BigInteger amount = BigInteger.valueOf(7_000_000_000L);
+ PaymasterParams paymasterParams = new PaymasterParams(PAYMASTER, Numeric.hexStringToByteArray(FunctionEncoder.encode(Paymaster.encodeApprovalBased(TOKEN, BigInteger.ONE, new byte[] {}))));
+
+ WithdrawTransaction transaction = new WithdrawTransaction(RECEIVER, amount, signer.getAddress(), paymasterParams);
+ Transaction result = zkSync.getWithdrawTx(transaction, transactionManager, gasProvider).sendAsync().join().getResult();
+ }
+}
+```
-| Name | Description |
-| ----------- | -------------------------------- |
-| transaction | Transaction data for estimation. |
-| returns | Prepared estimate gas request. |
+### `l1ChainId`
-### `zksGetBlockByHash`
+Returns the chain id of the underlying L1.
-Get block by hash.
+Calls the `zks_L1ChainId` JSON-RPC method.
-Example:
+#### Example
```java
import io.zksync.protocol.ZkSync;
import org.web3j.protocol.http.HttpService;
+import io.zksync.methods.response.ZkTransactionReceipt;
public class Main {
- public static void main(String... args) {
- ZksBlock response = zksync.zksGetBlockByHash("BLOCK_HASH", true).send();
+ public static void main(String ...args) {
+ BigInteger result = zkSync.l1ChainId().sendAsync().join().getResult();
}
}
```
-#### Inputs and outputs
+### `l1TokenAddress`
+
+Returns the L1 token address equivalent for a L2 token address as they are not equal. ETH's address is set to zero address.
+
+:::warning
+Only works for tokens bridged on default zkSync Era bridges.
+:::
+
+#### Inputs
-| Name | Description |
-| ---------------------------- | ---------------------------------------------------------------------------------------------- |
-| blockHash | Hash of a block. |
-| returnFullTransactionObjects | If true it returns the full transaction objects. If false only the hashes of the transactions. |
-| returns | Prepared get transaction receipt request. |
+| Parameter | Type | Description |
+| --------- | -------- | ------------------------------- |
+| `token` | `String` | The address of the token on L2. |
+
+#### Example
+
+```java
+import io.zksync.protocol.ZkSync;
+import org.web3j.protocol.http.HttpService;
+import io.zksync.methods.response.ZkTransactionReceipt;
+
+public class Main {
+ public static void main(String ...args) {
+ BigInteger result = zkSync.l1ChainId().sendAsync().join().getResult();
+ }
+}
+```
diff --git a/docs/build/sdks/java/types.md b/docs/build/sdks/java/types.md
new file mode 100644
index 0000000000..a7c59f0b31
--- /dev/null
+++ b/docs/build/sdks/java/types.md
@@ -0,0 +1,243 @@
+---
+head:
+ - - meta
+ - name: "twitter:title"
+ content: Java SDK Types | zkSync Docs
+---
+
+# Types and Interfaces
+
+## `AccountAbstractionVersion`
+
+Enumerated list of account abstraction versions.
+
+- None = `0` (Used for contracts that are not accounts.)
+- Version1 = `1`
+
+## `BatchDetails`
+
+Class representation of batch information containing various optional and mandatory fields.
+
+ private String commitTxHash;
+ private Date committedAt;
+ private String executeTxHash;
+ private Date executedAt;
+ private Uint l1TxCount;
+ private Uint l2TxCount;
+ private Uint number;
+ private String proveTxHash;
+ private Date provenAt;
+ private String rootHash;
+ private String status;
+ private Uint timestamp;
+
+## `Block`
+
+Class representation of a block.
+
+ private String l1BatchNumber;
+ private String l1BatchTimestamp;
+
+## `BlockDetails`
+
+Class representation of block information containing various optional and mandatory fields.
+
+ private String commitTxHash;
+ private Date committedAt;
+ private String executeTxHash;
+ private Date executedAt;
+ private Uint l1TxCount;
+ private Uint l2TxCount;
+ private Uint number;
+ private String proveTxHash;
+ private Date provenAt;
+ private String rootHash;
+ private String status;
+ private Uint timestamp;
+
+## `ZkBlockParameterName`
+
+Pipe-delimited list of block labels that includes block number in denary and hex plus block statuses.
+
+- `committed`
+- `finalized`
+- `latest`
+
+## `Eip712Meta`
+
+Type defining an EIP-712 transaction with optional parameters.
+
+ private BigInteger gasPerPubdata;
+ private byte[] customSignature;
+ private byte[][] factoryDeps;
+ private PaymasterParams paymasterParams;
+
+## `Fee`
+
+Class representation of transaction fee.
+
+ private Uint256 gasLimit;
+ private Uint256 maxFeePerGas;
+ private Uint256 maxPriorityFeePerGas;
+ private Uint256 gasPerPubdataLimit;
+
+## `FullDepositFee`
+
+Class representation of full deposit fee containing various mandatory and optional fields.
+
+ public BigInteger maxFeePerGas;
+ public BigInteger maxPriorityFeePerGas;
+ public BigInteger gasPrice;
+ public BigInteger baseCost;
+ public BigInteger l1GasLimit;
+ public BigInteger l2GasLimit;
+
+## `L2ToL1Log`
+
+Class representation of a layer 2 to layer 1 transaction log containing various fields.
+
+ public String BlockNumber;
+ public String BlockHash;
+ public String L1BatchNumber;
+ public String TransactionIndex;
+ public String ShardId;
+ public boolean IsService;
+ public Address Sender;
+ public String Key;
+ public String Value;
+ public String TxHash;
+ public int Index;
+
+## `ZkLog`
+
+Class representation of log that extends Ethers `Log` and supplies the layer 1 batch number.
+
+ private String l1BatchNumber;
+
+## `L2ToL1MessageProof`
+
+Class representation of message proof containing various fields.
+
+ private List proof;
+ private Integer id;
+ private String root;
+
+## `PaymasterParams`
+
+Type defining a paymaster by address and the bytestream input.
+
+ private String paymaster;
+ private byte[] paymasterInput;
+
+## `StorageProof`
+
+Interace representation of Merkle proofs for storage values.
+
+ private String address;
+ private StorageProofData storageProof;
+
+## `StorageProofData`
+
+ String key;
+ String value;
+ BigInteger index;
+ String[] proof;
+
+## `Token`
+
+Class representation of token containing various fields.
+
+ public static final Token ETH = createETH();
+ private String l1Address;
+ private String l2Address;
+ private String symbol;
+ private Integer decimals;
+
+## `TransactionDetails`
+
+Class representation of transaction details containing various mandatory and optional fields.
+
+ private boolean isL1Originated;
+ private TransactionStatus status;
+ private String fee;
+ private String initiatorAddress;
+ private Date receivedAt;
+ private String ethCommitTxHash;
+ private String ethProveTxHash;
+ private String ethExecuteTxHash;
+
+## `TransactionReceipt`
+
+Class representation of transaction receipt that extends from Web3j `TransactionReceipt` with additional fields.
+
+ private String l1BatchNumber;
+ private String l1BatchTxIndex;
+ private List l2ToL1Logs;
+
+## `TransactionStatus`
+
+Non-enumerated enum list of transaction statuses.
+
+ PROCESSING("processing"),
+ COMMITTED("committed"),
+ FINALIZED("finalized"),
+ NOT_FOUND("not-found");
+
+## `DepositTransaction`
+
+Used to call wallet.deposit, wallet.estimateGasdeposit, wallet.getDepositTransaction
+
+ public String tokenAddress;
+ public BigInteger amount;
+ public String to;
+ public BigInteger l2GasLimit;
+ public String bridgeAddress;
+ public byte[] customBridgeData;
+ public BigInteger gasPerPubdataByte;
+ public BigInteger operatorTip;
+ public String refoundRecepient;
+ public Boolean approveERC20;
+ public TransactionOptions options;
+
+## `RequestExecuteTransaction`
+
+ private BigInteger l2GasLimit;
+ private String contractAddress;
+ private byte[] calldata;
+ private BigInteger l2Value;
+ private byte[][] factoryDeps;
+ private BigInteger operatorTip;
+ private BigInteger gasPerPubDataByte;
+ private String refoundRecepient;
+ private TransactionOptions options;
+
+## `TransferTransaction`
+
+ public String to;
+ public BigInteger amount;
+ public String from;
+ public String tokenAddress;
+ public BigInteger gasPerPubData;
+ public PaymasterParams paymasterParams;
+ public TransactionOptions options;
+
+## `WithdrawTransaction`
+
+ public String tokenAddress;
+ public BigInteger amount;
+ public String to;
+ public String from;
+ public String bridgeAddress;
+ public byte[] customBridgeData;
+ public PaymasterParams paymasterParams;
+ public TransactionOptions options;
+
+## `TransactionOptions`
+
+ private BigInteger nonce;
+ private BigInteger value;
+ private BigInteger gasPrice;
+ private BigInteger maxFeePerGas;
+ private BigInteger maxPriorityFeePerGas;
+ private BigInteger gasLimit;
+ private BigInteger chainId;
diff --git a/docs/build/sdks/java/utils.md b/docs/build/sdks/java/utils.md
new file mode 100644
index 0000000000..fbe8c062a8
--- /dev/null
+++ b/docs/build/sdks/java/utils.md
@@ -0,0 +1,264 @@
+---
+head:
+ - - meta
+ - name: "twitter:title"
+ content: JS SDK Utilities | zkSync Docs
+---
+
+# Utilities
+
+The [utilities package](https://github.com/zksync-sdk/zksync2-java/tree/master/src/main/java/io/zksync/utils) contains essential utilities for building on zkSync Era.
+
+:::info
+
+- This document describes common functions and constants you may need.
+- Functions used internally are not necessarily described.
+- Check the code for the full list.
+ :::
+
+## Use the library
+
+Access the package by importing it into your scripts.
+
+```java
+import io.zksync.utils.*;
+```
+
+## Constants
+
+#### EIP712 structures
+
+Collection of EIP712 structures with their types.
+
+```ts
+export const EIP712_TYPES = {
+ Transaction: [
+ { name: "txType", type: "uint256" },
+ { name: "from", type: "uint256" },
+ { name: "to", type: "uint256" },
+ { name: "gasLimit", type: "uint256" },
+ { name: "gasPerPubdataByteLimit", type: "uint256" },
+ { name: "maxFeePerGas", type: "uint256" },
+ { name: "maxPriorityFeePerGas", type: "uint256" },
+ { name: "paymaster", type: "uint256" },
+ { name: "nonce", type: "uint256" },
+ { name: "value", type: "uint256" },
+ { name: "data", type: "bytes" },
+ { name: "factoryDeps", type: "bytes32[]" },
+ { name: "paymasterInput", type: "bytes" },
+ ],
+};
+```
+
+### ZkSyncAddresses
+
+#### ETH token layer 1
+
+```java
+public static final String ETH_ADDRESS = "0x0000000000000000000000000000000000000000";
+```
+
+#### ETH token alias on ZkSync Era
+
+```java
+public static final String L2_ETH_TOKEN_ADDRESS = "0x000000000000000000000000000000000000800a";
+```
+
+#### Contract deployer
+
+```java
+public static final String CONTRACT_DEPLOYER_ADDRESS = "0x0000000000000000000000000000000000008006";
+```
+
+#### L1 messenger
+
+```java
+public static final String MESSENGER_ADDRESS = "0x0000000000000000000000000000000000008008";
+```
+
+#### Nonce holder
+
+```java
+public static final String NONCE_HOLDER_ADDRESS = "0x0000000000000000000000000000000000008003";
+```
+
+## WalletUtils
+
+### `applyL1ToL2Alias`
+
+Converts the address that submitted a transaction to the inbox on L1 to the `msg.sender` viewed on L2.
+
+Returns the `msg.sender` of the L1->L2 transaction as the `address` of the contract that initiated the transaction.
+
+:::tip More info
+
+1. During a normal transaction, if contract A calls contract B, the `msg.sender` is A.
+2. During L1->L2 communication, if an EOA X calls contract B, the `msg.sender` is X.
+3. During L1->L2 communication, if a contract A calls contract B, the `msg.sender` is `applyL1ToL2Alias(A)`.
+ :::
+
+#### Inputs
+
+| Parameter | Type | Description |
+| --------- | ------ | ----------------- |
+| `address` | String | Contract address. |
+
+#### Example
+
+```ts
+String nonZeroPadded = WalletUtils.applyL1ToL2Alias("0x702942B8205E5dEdCD3374E5f4419843adA76Eeb");
+```
+
+### `undoL1ToL2Alias`
+
+Converts and returns the `msg.sender` viewed on L2 to the address that submitted a transaction to the inbox on L1.
+
+#### Inputs
+
+| Parameter | Type | Description |
+| --------- | ------ | --------------- |
+| `address` | String | Sender address. |
+
+#### Example
+
+```ts
+String nonZeroPadded = WalletUtils.undoL1ToL2Alias("0x813A42B8205E5DedCd3374e5f4419843ADa77FFC");
+```
+
+### `checkBaseCost`
+
+Checks if the transaction's base cost is greater than the provided value, which covers the transaction's cost. Throws an error if it is not.
+
+#### Inputs
+
+| Parameter | Type | Description |
+| ---------- | ------------ | ------------------------------------------ |
+| `baseCost` | `BigInteger` | transaction's base cost. |
+| `value` | `BigInteger` | value which covers the transaction's cost. |
+
+### Example
+
+```java
+BigInteger baseCost = BigInteger.valueOf(100);
+BigInteger value = BigInteger.valueOf(99);
+
+try {
+ WalletUtils.checkBaseCost(baseCost, value);
+} catch (Exception e) {
+ // e.message = `The base cost of performing the priority operation is higher than the provided value parameter for the transaction: baseCost: ${baseCost}, provided value: ${value}`,
+}
+```
+
+### `estimateDefaultBridgeDepositL2Gas`
+
+Returns an estimation of L2 gas required for token bridging via the default ERC20 bridge.
+
+#### Inputs
+
+| Parameter | Type | Description |
+| ------------------- | --------------------- | ------------------------------------------- |
+| `token` | `Address` | Token address. |
+| `amount` | `BigNumberish` | Deposit amount. |
+| `to` | `Address` | Recipient address. |
+| `providerL2` | `ZkSync` | zkSync provider. |
+| `bridgeContracts` | `L1BridgeContracts` | L1 bridge contract contracts. |
+| `providerL1` | `Web3j` | Ethers provider. |
+| `credentials` | `Credentials` | Sender credentials (optional). |
+| `gasProvider` | `ContractGasProvider` | Contract gas provider (optional). |
+| `from` | `Address` | Sender address (optional). |
+| `gasPerPubdataByte` | `BigNumberish` | Current gas per byte of pubdata (optional). |
+
+### `getERC20BridgeCalldata`
+
+Returns the calldata sent by an L1 ERC20 bridge to its L2 counterpart during token-bridging.
+
+#### Inputs
+
+| Parameter | Type | Description |
+| ---------------- | ------------ | ------------------------------------------- |
+| `l1TokenAddress` | `String` | Token address on L1. |
+| `l1Sender` | `String` | Sender address on L1. |
+| `l2Receiver` | `String` | Recipient address on L2. |
+| `amount` | `BigInteger` | Gas fee for the number of tokens to bridge. |
+| `bridgeData` | `byte[]` | Data |
+
+## ContractDeployer
+
+### `create2Address`
+
+Generates a future-proof contract address using salt plus bytecode which allows determination of an address before deployment.
+
+:::warning
+
+- The zkSync Era implementation is slightly different from Ethereum.
+ :::
+
+#### Inputs
+
+| Parameter | Type | Description |
+| ------------- | --------- | --------------------------------- |
+| `sender` | `Address` | Sender address. |
+| `bytecode` | `byte[]` | Output from zkSolc. |
+| `constructor` | `byte[]` | ABI encoded contrusctor arguments |
+| `salt` | `byte[]` | Randomization element. |
+
+#### Example
+
+```java
+Address result = ContractDeployer.computeL2Create2Address(new Address("0xa909312acfc0ed4370b8bd20dfe41c8ff6595194"), Numeric.hexStringToByteArray
+("0x010001cb6a6e8d5f6829522f19fa9568660e0a9cd53b2e8be4deb0a679452e41"), new byte[] {}, new byte[32]);
+```
+
+### `createAddress`
+
+Generates a contract address from deployer's account and nonce.
+
+#### Inputs
+
+| Parameter | Type | Description |
+| --------- | ------------ | --------------- |
+| `sender` | `Address` | Sender address. |
+| `nonce` | `BigInteger` | Sender nonce. |
+
+```ts
+export function createAddress(sender: Address, senderNonce: BigNumberish): string;
+```
+
+#### Example
+
+```java
+Address result = ContractDeployer.computeL2CreateAddress(new Address("0x7e5f4552091a69125d5dfcb7b8c2659029395bdf"), BigInteger.valueOf(1));
+```
+
+### `verifySignature`
+
+Called from [`verifyTypedData`](#verifyTypedData). Returns true if account abstraction EIP712
+signature is correct.
+
+#### Inputs
+
+| Parameter | Type | Description |
+| ----------- | --------- | ----------------- |
+| `signature` | `String` | Signature string. |
+| `message` | `byte[]` | Message bytes. |
+| `prefixed` | `boolean` | Is prefixed. |
+
+### `verifyTypedData`
+
+Returns true if account abstraction EIP712 signature is correct.
+
+#### Inputs
+
+| Parameter | Type | Description |
+| ----------- | -------------- | ------------------ |
+| `domain` | `Eip712Domain` | Domain data. |
+| `typedData` | `S` | Structurable data. |
+| `signature` | `String` | Signature. |
+
+#### Example
+
+```java
+final String signature = "0x4355c47d63924e8a72e509b65029052eb6c299d53a04e167c5775fd466751c9d07299936d304c153f6443dfa05f40ff007d72911b6f72307f996231605b915621c";
+
+boolean verified = key.verifyTypedData(domain, message, signature).join();
+```