diff --git a/.github/workflows/manual_release.yml b/.github/workflows/manual_publish.yml similarity index 100% rename from .github/workflows/manual_release.yml rename to .github/workflows/manual_publish.yml diff --git a/.github/workflows/release.yaml b/.github/workflows/publish.yaml similarity index 100% rename from .github/workflows/release.yaml rename to .github/workflows/publish.yaml diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..8df760c --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,35 @@ +name: Release +on: + workflow_dispatch: + +permissions: + contents: read # for checkout + +jobs: + release: + name: Release + runs-on: ubuntu-latest + permissions: + contents: write # to be able to publish a GitHub release + issues: write # to be able to comment on released issues + pull-requests: write # to be able to comment on released pull requests + steps: + - name: Checkout + uses: actions/checkout@v3 + with: + fetch-depth: 0 + - name: Setup Node.js + uses: actions/setup-node@v3 + with: + node-version: "lts/*" + - name: Install dependencies + run: | + npm install -g "semantic-release@21.0.7" \ + "@semantic-release/commit-analyzer@11.1.0" \ + "@semantic-release/changelog@6.0.3" \ + "@semantic-release/git@10.0.1" \ + "@semantic-release/github@9.0.4" + - name: Release + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: npx semantic-release \ No newline at end of file diff --git a/.github/workflows/test.yaml b/.github/workflows/test.yaml index efe4204..9f87e49 100755 --- a/.github/workflows/test.yaml +++ b/.github/workflows/test.yaml @@ -1,12 +1,10 @@ name: Test Java SDK library on: + workflow_dispatch: pull_request: - branches: - - master - push: - branches: - - develop + branches: [master] + types: [ opened, reopened, synchronize ] jobs: test: @@ -14,9 +12,9 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - - name: Set up JDK 8 + - name: Set up JDK uses: actions/setup-java@v1 with: - java-version: 1.8 + java-version: 11 - name: Test with Gradle run: gradle clean test diff --git a/.github/workflows/validate.yml b/.github/workflows/validate.yml new file mode 100644 index 0000000..69b300d --- /dev/null +++ b/.github/workflows/validate.yml @@ -0,0 +1,71 @@ +name: Validate +on: + pull_request: + branches: [master] + types: [ opened, reopened, synchronize ] + +permissions: + contents: read # for checkout + +jobs: + lint: + name: Check code format + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v3 + with: + fetch-depth: 0 + - name: Set up JDK + uses: actions/setup-java@v1 + with: + java-version: 11 + - name: Test with Gradle + run: gradle spotlessCheck + commits: + name: Check commits + runs-on: ubuntu-latest + if: github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository + steps: + - name: Checkout + uses: actions/checkout@v3 + - name: Setup Node.js + uses: actions/setup-node@v3 + with: + node-version: "lts/*" + - name: Install dependencies + run: npm install -g @commitlint/cli @commitlint/config-conventional + - name: Configure + run: | + echo 'module.exports = {"extends": ["@commitlint/config-conventional"]}' > commitlint.config.js + - name: Validate + run: | + git fetch + npx commitlint \ + --from ${{ github.event.pull_request.head.sha }}~${{ github.event.pull_request.commits }} \ + --to ${{ github.event.pull_request.head.sha }} \ + --verbose + commits-fork: + name: Check commits from forks + runs-on: ubuntu-latest + if: github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name != github.repository + steps: + - name: Checkout + uses: actions/checkout@v3 + - name: Setup Node.js + uses: actions/setup-node@v3 + with: + node-version: "lts/*" + - name: Install dependencies + run: npm install -g @commitlint/cli @commitlint/config-conventional + - name: Configure + run: | + echo 'module.exports = {"extends": ["@commitlint/config-conventional"]}' > commitlint.config.js + - name: Validate + run: | + git fetch origin "+refs/pull/${{ github.event.pull_request.number }}/head:refs/pull/${{ github.event.pull_request.number }}/head" + git checkout "refs/pull/${{ github.event.pull_request.number }}/head" + npx commitlint \ + --from HEAD~${{ github.event.pull_request.commits }} \ + --to HEAD \ + --verbose \ No newline at end of file diff --git a/.releaserc b/.releaserc new file mode 100644 index 0000000..3a36f58 --- /dev/null +++ b/.releaserc @@ -0,0 +1,25 @@ +{ + "repositoryUrl": "https://github.com/zksync-sdk/zksync2-java.git", + "branches": "main", + "debug": true, + "addReleases": "top", + "preset": "angular", + "plugins": [ + "@semantic-release/commit-analyzer", + "@semantic-release/release-notes-generator", + [ + "@semantic-release/changelog", + { + "changelogFile": "CHANGELOG.md" + } + ], + [ + "@semantic-release/git", + { + "assets": ["CHANGELOG.md"], + "message": "${nextRelease.version} version bump [skip ci]\n\n${nextRelease.notes}" + } + ], + "@semantic-release/github" + ] +} \ No newline at end of file diff --git a/build.gradle b/build.gradle index 47556c6..f7fe960 100755 --- a/build.gradle +++ b/build.gradle @@ -3,6 +3,7 @@ plugins { id 'maven-publish' id 'signing' id 'io.github.gradle-nexus.publish-plugin' version '1.3.0' + id "com.diffplug.spotless" version "6.23.3" } group = 'io.zksync' @@ -126,3 +127,10 @@ test { events "passed", "skipped", "failed" } } + +spotless { + java { + googleJavaFormat() + target '**/*.java' // Targeting all Java files + } +} diff --git a/src/main/java/io/zksync/ZkSyncWallet.java b/src/main/java/io/zksync/ZkSyncWallet.java index 5c6f916..429f112 100644 --- a/src/main/java/io/zksync/ZkSyncWallet.java +++ b/src/main/java/io/zksync/ZkSyncWallet.java @@ -1,14 +1,20 @@ package io.zksync; -import java.io.IOException; -import java.math.BigInteger; -import java.security.SecureRandom; -import java.util.*; -import java.util.concurrent.CompletableFuture; +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; +import io.zksync.abi.TransactionEncoder; import io.zksync.abi.ZkFunctionEncoder; +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.protocol.core.ZkBlockParameterName; import io.zksync.protocol.exceptions.JsonRpcResponseException; +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.utils.AccountAbstractionVersion; @@ -17,18 +23,21 @@ import io.zksync.wrappers.ERC20; import io.zksync.wrappers.IL2Bridge; import io.zksync.wrappers.IL2Messenger; +import java.io.IOException; +import java.math.BigInteger; +import java.security.SecureRandom; +import java.util.*; +import java.util.concurrent.CompletableFuture; +import lombok.Getter; import org.jetbrains.annotations.Nullable; import org.web3j.abi.FunctionEncoder; -import org.web3j.abi.TypeEncoder; import org.web3j.abi.datatypes.Address; import org.web3j.abi.datatypes.Function; import org.web3j.abi.datatypes.generated.Uint256; import org.web3j.crypto.Credentials; -import org.web3j.crypto.Hash; import org.web3j.protocol.core.DefaultBlockParameter; import org.web3j.protocol.core.RemoteCall; import org.web3j.protocol.core.methods.response.EthSendTransaction; -import org.web3j.protocol.core.methods.response.Log; import org.web3j.protocol.core.methods.response.TransactionReceipt; import org.web3j.protocol.exceptions.TransactionException; import org.web3j.tx.ReadonlyTransactionManager; @@ -36,483 +45,514 @@ import org.web3j.tx.response.TransactionReceiptProcessor; import org.web3j.utils.Numeric; -import io.zksync.abi.TransactionEncoder; -import io.zksync.crypto.signer.EthSigner; -import io.zksync.crypto.signer.PrivateKeyEthSigner; -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 lombok.Getter; - -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; - @Getter public class ZkSyncWallet { - private final ZkSync zksync; - private final EthSigner signer; - private final TransactionReceiptProcessor transactionReceiptProcessor; - private final ZkTransactionFeeProvider feeProvider; - - public ZkSyncWallet(ZkSync zksync, EthSigner signer, TransactionReceiptProcessor transactionReceiptProcessor, - ZkTransactionFeeProvider feeProvider) { - this.zksync = zksync; - this.signer = signer; - this.transactionReceiptProcessor = transactionReceiptProcessor; - this.feeProvider = feeProvider; - } - - public ZkSyncWallet(ZkSync zksync, EthSigner signer) { - this(zksync, signer, new ZkSyncTransactionReceiptProcessor(zksync, DEFAULT_POLLING_FREQUENCY, DEFAULT_POLLING_ATTEMPTS_PER_TX_HASH), - new DefaultTransactionFeeProvider(zksync, Token.ETH)); - } - - public ZkSyncWallet(ZkSync zksync, EthSigner signer, Token feeToken) { - this(zksync, signer, new ZkSyncTransactionReceiptProcessor(zksync, DEFAULT_POLLING_FREQUENCY, DEFAULT_POLLING_ATTEMPTS_PER_TX_HASH), - new DefaultTransactionFeeProvider(zksync, feeToken)); - } - - public ZkSyncWallet(ZkSync zksync, Credentials credentials, Long chainId) { - this(zksync, new PrivateKeyEthSigner(credentials, chainId)); - } - - /** - * Transfer coins - * - * @param to Receiver address - * @param amount Amount of funds to be transferred in minimal denomination (in Wei) - * @return Prepared remote call of transaction - */ - public RemoteCall transfer(String to, BigInteger amount) { - return transfer(to, amount, null, null); + private final ZkSync zksync; + private final EthSigner signer; + private final TransactionReceiptProcessor transactionReceiptProcessor; + private final ZkTransactionFeeProvider feeProvider; + + public ZkSyncWallet( + ZkSync zksync, + EthSigner signer, + TransactionReceiptProcessor transactionReceiptProcessor, + ZkTransactionFeeProvider feeProvider) { + this.zksync = zksync; + this.signer = signer; + this.transactionReceiptProcessor = transactionReceiptProcessor; + this.feeProvider = feeProvider; + } + + public ZkSyncWallet(ZkSync zksync, EthSigner signer) { + this( + zksync, + signer, + new ZkSyncTransactionReceiptProcessor( + zksync, DEFAULT_POLLING_FREQUENCY, DEFAULT_POLLING_ATTEMPTS_PER_TX_HASH), + new DefaultTransactionFeeProvider(zksync, Token.ETH)); + } + + public ZkSyncWallet(ZkSync zksync, EthSigner signer, Token feeToken) { + this( + zksync, + signer, + new ZkSyncTransactionReceiptProcessor( + zksync, DEFAULT_POLLING_FREQUENCY, DEFAULT_POLLING_ATTEMPTS_PER_TX_HASH), + new DefaultTransactionFeeProvider(zksync, feeToken)); + } + + public ZkSyncWallet(ZkSync zksync, Credentials credentials, Long chainId) { + this(zksync, new PrivateKeyEthSigner(credentials, chainId)); + } + + /** + * Transfer coins + * + * @param to Receiver address + * @param amount Amount of funds to be transferred in minimal denomination (in Wei) + * @return Prepared remote call of transaction + */ + public RemoteCall transfer(String to, BigInteger amount) { + return transfer(to, amount, null, null); + } + + /** + * Transfer coins or tokens + * + * @param to Receiver address + * @param amount Amount of funds to be transferred in minimal denomination + * @param token Token object supported by ZkSync + * @return Prepared remote call of transaction + */ + public RemoteCall transfer(String to, BigInteger amount, Token token) { + return transfer(to, amount, token, null); + } + + /** + * Transfer coins or tokens + * + * @param to Receiver address + * @param amount Amount of funds to be transferred in minimal denomination + * @param token Token object supported by ZkSync + * @param nonce Custom nonce value of the wallet + * @return Prepared remote call of transaction + */ + public RemoteCall transfer( + String to, BigInteger amount, @Nullable Token token, @Nullable BigInteger nonce) { + Token tokenToUse = token == null ? Token.ETH : token; + String calldata; + String txTo; + BigInteger txAmount; + + if (tokenToUse.isETH()) { + calldata = "0x"; + txTo = to; + txAmount = amount; + } else { + Function function = ERC20.encodeTransfer(to, amount); + calldata = FunctionEncoder.encode(function); + txTo = tokenToUse.getL2Address(); + txAmount = null; } + return new RemoteCall<>( + () -> { + BigInteger nonceToUse = nonce != null ? nonce : getNonce().send(); + + Transaction estimate = + Transaction.createFunctionCallTransaction( + signer.getAddress(), txTo, BigInteger.ZERO, BigInteger.ZERO, txAmount, calldata); + + EthSendTransaction sent = estimateAndSend(estimate, nonceToUse).join(); + + try { + return this.transactionReceiptProcessor.waitForTransactionReceipt( + sent.getTransactionHash()); + } catch (IOException | TransactionException e) { + throw new RuntimeException(e); + } + }); + } + + /** + * Withdraw native coins to L1 chain + * + * @param to Address of the wallet in L1 to that funds will be withdrawn + * @param amount Amount of the funds to be withdrawn + * @return Prepared remote call of transaction + */ + public RemoteCall withdraw(String to, BigInteger amount) { + return withdraw(to, amount, null, null); + } + + /** + * Withdraw native coins or tokens to L1 chain + * + * @param to Address of the wallet in L1 to that funds will be withdrawn + * @param amount Amount of the funds to be withdrawn + * @param token Token object supported by ZkSync + * @return Prepared remote call of transaction + */ + public RemoteCall withdraw(String to, BigInteger amount, Token token) { + return withdraw(to, amount, token, null); + } + + /** + * Withdraw native coins to L1 chain + * + * @param to Address of the wallet in L1 to that funds will be withdrawn + * @param amount Amount of the funds to be withdrawn + * @param token Token object supported by ZkSync + * @param nonce Custom nonce value of the wallet + * @return Prepared remote call of transaction + */ + public RemoteCall withdraw( + String to, BigInteger amount, @Nullable Token token, @Nullable BigInteger nonce) { + Token tokenToUse = token == null ? Token.ETH : token; + + return new RemoteCall<>( + () -> { + BigInteger nonceToUse = nonce != null ? nonce : getNonce().send(); + String l2Bridge; + ArrayList parameters = new ArrayList(); + parameters.add(new Address(to)); + Transaction estimate; + if (tokenToUse.isETH()) { + Function function = + new Function( + IL2Bridge.FUNC_WITHDRAW, + Arrays.asList(new Address(to)), + Collections.emptyList()); - /** - * Transfer coins or tokens - * - * @param to Receiver address - * @param amount Amount of funds to be transferred in minimal denomination - * @param token Token object supported by ZkSync - * @return Prepared remote call of transaction - */ - public RemoteCall transfer(String to, BigInteger amount, Token token) { - return transfer(to, amount, token, null); - } + String calldata = FunctionEncoder.encode(function); + l2Bridge = L2_ETH_TOKEN_ADDRESS; - /** - * Transfer coins or tokens - * - * @param to Receiver address - * @param amount Amount of funds to be transferred in minimal denomination - * @param token Token object supported by ZkSync - * @param nonce Custom nonce value of the wallet - * @return Prepared remote call of transaction - */ - public RemoteCall transfer(String to, BigInteger amount, @Nullable Token token, @Nullable BigInteger nonce) { - Token tokenToUse = token == null ? Token.ETH : token; - String calldata; - String txTo; - BigInteger txAmount; - - if (tokenToUse.isETH()) { - calldata = "0x"; - txTo = to; - txAmount = amount; - } else { - Function function = ERC20.encodeTransfer(to, amount); - calldata = FunctionEncoder.encode(function); - txTo = tokenToUse.getL2Address(); - txAmount = null; - } - return new RemoteCall<>(() -> { - BigInteger nonceToUse = nonce != null ? nonce : getNonce().send(); - - Transaction estimate = Transaction.createFunctionCallTransaction( + estimate = + Transaction.createFunctionCallTransaction( signer.getAddress(), - txTo, + l2Bridge, BigInteger.ZERO, BigInteger.ZERO, - txAmount, - calldata - ); - - EthSendTransaction sent = estimateAndSend(estimate, nonceToUse).join(); + amount, + calldata); + } else { + Function function = + new Function( + IL2Bridge.FUNC_WITHDRAW, + Arrays.asList( + new Address(to), + new Address(tokenToUse.getL2Address()), + new Uint256(amount)), + Collections.emptyList()); - try { - return this.transactionReceiptProcessor.waitForTransactionReceipt(sent.getTransactionHash()); - } catch (IOException | TransactionException e) { - throw new RuntimeException(e); - } - }); - } + String calldata = FunctionEncoder.encode(function); + l2Bridge = zksync.zksGetBridgeContracts().send().getResult().getL2Erc20DefaultBridge(); - /** - * Withdraw native coins to L1 chain - * - * @param to Address of the wallet in L1 to that funds will be withdrawn - * @param amount Amount of the funds to be withdrawn - * @return Prepared remote call of transaction - */ - public RemoteCall withdraw(String to, BigInteger amount) { - return withdraw(to, amount, null, null); - } + estimate = + Transaction.createFunctionCallTransaction( + signer.getAddress(), l2Bridge, BigInteger.ZERO, BigInteger.ZERO, calldata); + } - /** - * Withdraw native coins or tokens to L1 chain - * - * @param to Address of the wallet in L1 to that funds will be withdrawn - * @param amount Amount of the funds to be withdrawn - * @param token Token object supported by ZkSync - * @return Prepared remote call of transaction - */ - public RemoteCall withdraw(String to, BigInteger amount, Token token) { - return withdraw(to, amount, token, null); - } + EthSendTransaction sent = estimateAndSend(estimate, nonceToUse).join(); - /** - * Withdraw native coins to L1 chain - * - * @param to Address of the wallet in L1 to that funds will be withdrawn - * @param amount Amount of the funds to be withdrawn - * @param token Token object supported by ZkSync - * @param nonce Custom nonce value of the wallet - * @return Prepared remote call of transaction - */ - public RemoteCall withdraw(String to, BigInteger amount, @Nullable Token token, @Nullable BigInteger nonce) { - Token tokenToUse = token == null ? Token.ETH : token; - - return new RemoteCall<>(() -> { - BigInteger nonceToUse = nonce != null ? nonce : getNonce().send(); - String l2Bridge; - ArrayList parameters = new ArrayList(); - parameters.add(new Address(to)); - Transaction estimate; - if (tokenToUse.isETH()) { - Function function = new Function( - IL2Bridge.FUNC_WITHDRAW, - Arrays.asList(new Address(to)), - Collections.emptyList()); - - String calldata = FunctionEncoder.encode(function); - l2Bridge = L2_ETH_TOKEN_ADDRESS; - - estimate = Transaction.createFunctionCallTransaction( - signer.getAddress(), - l2Bridge, - BigInteger.ZERO, - BigInteger.ZERO, - amount, - calldata - ); - } else { - Function function = new Function( - IL2Bridge.FUNC_WITHDRAW, - Arrays.asList(new Address(to), - new Address(tokenToUse.getL2Address()), - new Uint256(amount)), - Collections.emptyList()); - - String calldata = FunctionEncoder.encode(function); - l2Bridge = zksync.zksGetBridgeContracts().send().getResult().getL2Erc20DefaultBridge(); - - estimate = Transaction.createFunctionCallTransaction( - signer.getAddress(), - l2Bridge, - BigInteger.ZERO, - BigInteger.ZERO, - calldata - ); - } - - EthSendTransaction sent = estimateAndSend(estimate, nonceToUse).join(); - - try { - return this.transactionReceiptProcessor.waitForTransactionReceipt(sent.getTransactionHash()); - } catch (IOException | TransactionException e) { - throw new RuntimeException(e); - } + try { + return this.transactionReceiptProcessor.waitForTransactionReceipt( + sent.getTransactionHash()); + } catch (IOException | TransactionException e) { + throw new RuntimeException(e); + } }); - } - - /** - * Deploy new smart-contract into chain (this method uses create2, see EIP-1014) - * - * @param bytecode Compiled bytecode of the contract - * @return Prepared remote call of transaction - */ - public RemoteCall deploy(byte[] bytecode) { - return deploy(bytecode, null, null); - } - - /** - * Deploy new smart-contract into chain (this method uses create2, see EIP-1014) - * - * @param bytecode Compiled bytecode of the contract - * @param calldata Encoded constructor parameter of contract - * @return Prepared remote call of transaction - */ - public RemoteCall deploy(byte[] bytecode, byte[] calldata) { - return deploy(bytecode, calldata, null); - } - - /** - * Deploy new smart-contract into chain (this method uses create2, see EIP-1014) - * - * @param bytecode Compiled bytecode of the contract - * @param calldata Encoded constructor parameter of contract - * @param nonce Custom nonce value of the wallet - * @return Prepared remote call of transaction - */ - public RemoteCall deploy(byte[] bytecode, @Nullable byte[] calldata, - @Nullable BigInteger nonce) { - return new RemoteCall<>(() -> { - BigInteger nonceToUse = nonce != null ? nonce : getNonce().send(); - - Transaction estimate = Transaction.createContractTransaction( - signer.getAddress(), - BigInteger.ZERO, - BigInteger.ZERO, - Numeric.toHexString(bytecode), - calldata != null ? Numeric.toHexString(calldata) : "0x" - ); - - EthSendTransaction sent = estimateAndSend(estimate, nonceToUse).join(); - - try { - return this.transactionReceiptProcessor.waitForTransactionReceipt(sent.getTransactionHash()); - } catch (IOException | TransactionException e) { - throw new RuntimeException(e); - } + } + + /** + * Deploy new smart-contract into chain (this method uses create2, see EIP-1014) + * + * @param bytecode Compiled bytecode of the contract + * @return Prepared remote call of transaction + */ + public RemoteCall deploy(byte[] bytecode) { + return deploy(bytecode, null, null); + } + + /** + * Deploy new smart-contract into chain (this method uses create2, see EIP-1014) + * + * @param bytecode Compiled bytecode of the contract + * @param calldata Encoded constructor parameter of contract + * @return Prepared remote call of transaction + */ + public RemoteCall deploy(byte[] bytecode, byte[] calldata) { + return deploy(bytecode, calldata, null); + } + + /** + * Deploy new smart-contract into chain (this method uses create2, see EIP-1014) + * + * @param bytecode Compiled bytecode of the contract + * @param calldata Encoded constructor parameter of contract + * @param nonce Custom nonce value of the wallet + * @return Prepared remote call of transaction + */ + public RemoteCall deploy( + byte[] bytecode, @Nullable byte[] calldata, @Nullable BigInteger nonce) { + return new RemoteCall<>( + () -> { + BigInteger nonceToUse = nonce != null ? nonce : getNonce().send(); + + Transaction estimate = + Transaction.createContractTransaction( + signer.getAddress(), + BigInteger.ZERO, + BigInteger.ZERO, + Numeric.toHexString(bytecode), + calldata != null ? Numeric.toHexString(calldata) : "0x"); + + EthSendTransaction sent = estimateAndSend(estimate, nonceToUse).join(); + + try { + return this.transactionReceiptProcessor.waitForTransactionReceipt( + sent.getTransactionHash()); + } catch (IOException | TransactionException e) { + throw new RuntimeException(e); + } }); - } - public RemoteCall deployAccount(byte[] bytecode, - byte[] calldata){ - return deployAccount(bytecode, calldata, null, null); - } - public RemoteCall deployAccount(byte[] bytecode, - byte[] calldata, - BigInteger nonce){ - return deployAccount(bytecode, calldata, null, nonce); - } - public RemoteCall deployAccount(byte[] bytecode, - byte[] calldata, - byte[] salt) { - return deployAccount(bytecode, calldata, salt, null); - } - public RemoteCall deployAccount(byte[] bytecode, - byte[] calldata, - @Nullable byte[] salt, - @Nullable BigInteger nonce) { - return new RemoteCall<>(() -> { - BigInteger nonceToUse = nonce != null ? nonce : getNonce().send(); - - byte[] saltToUse = salt == null ? SecureRandom.getSeed(32) : salt; - Function function = ContractDeployer.encodeCreate2Account(bytecode, calldata, saltToUse, AccountAbstractionVersion.Version1); - ZkFunctionEncoder encoder = new ZkFunctionEncoder(); - String data = encoder.encodeFunction(function); - Transaction estimate = Transaction.create2ContractTransaction( - signer.getAddress(), - BigInteger.ZERO, - BigInteger.ZERO, - Numeric.toHexString(bytecode), - data, - Collections.singletonList(Numeric.toHexString(bytecode)) - ); - - EthSendTransaction sent = estimateAndSend(estimate, nonceToUse).join(); - - try { - return this.transactionReceiptProcessor.waitForTransactionReceipt(sent.getTransactionHash()); - } catch (IOException | TransactionException e) { - throw new RuntimeException(e); - } + } + + public RemoteCall deployAccount(byte[] bytecode, byte[] calldata) { + return deployAccount(bytecode, calldata, null, null); + } + + public RemoteCall deployAccount( + byte[] bytecode, byte[] calldata, BigInteger nonce) { + return deployAccount(bytecode, calldata, null, nonce); + } + + public RemoteCall deployAccount( + byte[] bytecode, byte[] calldata, byte[] salt) { + return deployAccount(bytecode, calldata, salt, null); + } + + public RemoteCall deployAccount( + byte[] bytecode, byte[] calldata, @Nullable byte[] salt, @Nullable BigInteger nonce) { + return new RemoteCall<>( + () -> { + BigInteger nonceToUse = nonce != null ? nonce : getNonce().send(); + + byte[] saltToUse = salt == null ? SecureRandom.getSeed(32) : salt; + Function function = + ContractDeployer.encodeCreate2Account( + bytecode, calldata, saltToUse, AccountAbstractionVersion.Version1); + ZkFunctionEncoder encoder = new ZkFunctionEncoder(); + String data = encoder.encodeFunction(function); + Transaction estimate = + Transaction.create2ContractTransaction( + signer.getAddress(), + BigInteger.ZERO, + BigInteger.ZERO, + Numeric.toHexString(bytecode), + data, + Collections.singletonList(Numeric.toHexString(bytecode))); + + EthSendTransaction sent = estimateAndSend(estimate, nonceToUse).join(); + + try { + return this.transactionReceiptProcessor.waitForTransactionReceipt( + sent.getTransactionHash()); + } catch (IOException | TransactionException e) { + throw new RuntimeException(e); + } }); - } - /** - * Execute function of deployed contract - * - * @param contractAddress Address of deployed contract - * @param function Prepared function call with or without parameters - * @return Prepared remote call of transaction - */ - public RemoteCall execute(String contractAddress, Function function) { - return execute(contractAddress, function, null); - } - - /** - * Execute function of deployed contract - * - * @param contractAddress Address of deployed contract - * @param function Prepared function call with or without parameters - * @param nonce Custom nonce value of the wallet - * @return Prepared remote call of transaction - */ - public RemoteCall execute(String contractAddress, Function function, @Nullable BigInteger nonce) { - return new RemoteCall<>(() -> { - BigInteger nonceToUse = nonce != null ? nonce : getNonce().send(); - String calldata = FunctionEncoder.encode(function); - - Transaction estimate = Transaction.createFunctionCallTransaction( - signer.getAddress(), - contractAddress, - BigInteger.ZERO, - BigInteger.ZERO, - calldata - ); - - EthSendTransaction sent = estimateAndSend(estimate, nonceToUse).join(); - - try { - return this.transactionReceiptProcessor.waitForTransactionReceipt(sent.getTransactionHash()); - } catch (IOException | TransactionException e) { - throw new RuntimeException(e); - } + } + + /** + * Execute function of deployed contract + * + * @param contractAddress Address of deployed contract + * @param function Prepared function call with or without parameters + * @return Prepared remote call of transaction + */ + public RemoteCall execute(String contractAddress, Function function) { + return execute(contractAddress, function, null); + } + + /** + * Execute function of deployed contract + * + * @param contractAddress Address of deployed contract + * @param function Prepared function call with or without parameters + * @param nonce Custom nonce value of the wallet + * @return Prepared remote call of transaction + */ + public RemoteCall execute( + String contractAddress, Function function, @Nullable BigInteger nonce) { + return new RemoteCall<>( + () -> { + BigInteger nonceToUse = nonce != null ? nonce : getNonce().send(); + String calldata = FunctionEncoder.encode(function); + + Transaction estimate = + Transaction.createFunctionCallTransaction( + signer.getAddress(), contractAddress, BigInteger.ZERO, BigInteger.ZERO, calldata); + + EthSendTransaction sent = estimateAndSend(estimate, nonceToUse).join(); + + try { + return this.transactionReceiptProcessor.waitForTransactionReceipt( + sent.getTransactionHash()); + } catch (IOException | TransactionException e) { + throw new RuntimeException(e); + } }); + } + + /** + * Get balance of wallet in native coin (wallet address gets from {@link EthSigner}) + * + * @return Prepared get balance call + */ + public RemoteCall getBalance() { + return getBalance(signer.getAddress(), Token.ETH, ZkBlockParameterName.COMMITTED); + } + + /** + * Get balance of wallet in {@link Token} (wallet address gets from {@link EthSigner}) + * + * @param token Token object supported by ZkSync + * @return Prepared get balance call + */ + public RemoteCall getBalance(Token token) { + return getBalance(signer.getAddress(), token, ZkBlockParameterName.COMMITTED); + } + + /** + * Get balance of wallet in native coin + * + * @param address Address of the wallet + * @return Prepared get balance call + */ + public RemoteCall getBalance(String address) { + return getBalance(address, Token.ETH, ZkBlockParameterName.COMMITTED); + } + + /** + * Get balance of wallet in {@link Token} + * + * @param address Address of the wallet + * @param token Token object supported by ZkSync + * @return Prepared get balance call + */ + public RemoteCall getBalance(String address, Token token) { + return getBalance(address, token, ZkBlockParameterName.COMMITTED); + } + + /** + * Get balance of wallet by address in {@link Token} at block {@link DefaultBlockParameter} also + * see {@link org.web3j.protocol.core.DefaultBlockParameterName}, {@link + * org.web3j.protocol.core.DefaultBlockParameterNumber}, {@link ZkBlockParameterName} + * + * @param address Wallet address + * @param token Token object supported by ZkSync + * @param at Block variant + * @return Prepared get balance call + */ + public RemoteCall getBalance(String address, Token token, DefaultBlockParameter at) { + if (token.isETH()) { + return new RemoteCall<>( + () -> this.zksync.ethGetBalance(address, at).sendAsync().join().getBalance()); + } else { + ERC20 erc20 = + ERC20.load( + token.getL2Address(), + this.zksync, + new ReadonlyTransactionManager(this.zksync, getSigner().getAddress()), + new DefaultGasProvider()); + return erc20.balanceOf(address); } - - /** - * Get balance of wallet in native coin (wallet address gets from {@link EthSigner}) - * - * @return Prepared get balance call - */ - public RemoteCall getBalance() { - return getBalance(signer.getAddress(), Token.ETH, ZkBlockParameterName.COMMITTED); - } - - /** - * Get balance of wallet in {@link Token} (wallet address gets from {@link EthSigner}) - * - * @param token Token object supported by ZkSync - * @return Prepared get balance call - */ - public RemoteCall getBalance(Token token) { - return getBalance(signer.getAddress(), token, ZkBlockParameterName.COMMITTED); - } - - /** - * Get balance of wallet in native coin - * - * @param address Address of the wallet - * @return Prepared get balance call - */ - public RemoteCall getBalance(String address) { - return getBalance(address, Token.ETH, ZkBlockParameterName.COMMITTED); - } - - /** - * Get balance of wallet in {@link Token} - * - * @param address Address of the wallet - * @param token Token object supported by ZkSync - * @return Prepared get balance call - */ - public RemoteCall getBalance(String address, Token token) { - return getBalance(address, token, ZkBlockParameterName.COMMITTED); - } - - /** - * Get balance of wallet by address in {@link Token} at block {@link DefaultBlockParameter} - * also see {@link org.web3j.protocol.core.DefaultBlockParameterName}, {@link org.web3j.protocol.core.DefaultBlockParameterNumber}, {@link ZkBlockParameterName} - * - * @param address Wallet address - * @param token Token object supported by ZkSync - * @param at Block variant - * @return Prepared get balance call - */ - public RemoteCall getBalance(String address, Token token, DefaultBlockParameter at) { - if (token.isETH()) { - return new RemoteCall<>(() -> - this.zksync.ethGetBalance(address, at).sendAsync().join().getBalance()); - } else { - ERC20 erc20 = ERC20.load(token.getL2Address(), this.zksync, new ReadonlyTransactionManager(this.zksync, getSigner().getAddress()), new DefaultGasProvider()); - return erc20.balanceOf(address); - } - } - - /** - * Get nonce for wallet at block {@link DefaultBlockParameter} (wallet address gets from {@link EthSigner}) - * also see {@link org.web3j.protocol.core.DefaultBlockParameterName}, {@link org.web3j.protocol.core.DefaultBlockParameterNumber}, {@link ZkBlockParameterName} - * @param at Block variant - * @return Prepared get nonce call - */ - public RemoteCall getNonce(DefaultBlockParameter at) { - return new RemoteCall<>(() -> this.zksync - .ethGetTransactionCount(signer.getAddress(), at).sendAsync().join() + } + + /** + * Get nonce for wallet at block {@link DefaultBlockParameter} (wallet address gets from {@link + * EthSigner}) also see {@link org.web3j.protocol.core.DefaultBlockParameterName}, {@link + * org.web3j.protocol.core.DefaultBlockParameterNumber}, {@link ZkBlockParameterName} + * + * @param at Block variant + * @return Prepared get nonce call + */ + public RemoteCall getNonce(DefaultBlockParameter at) { + return new RemoteCall<>( + () -> + this.zksync + .ethGetTransactionCount(signer.getAddress(), at) + .sendAsync() + .join() .getTransactionCount()); - } - - /** - * Get nonce for wallet at block `COMMITTED` {@link ZkBlockParameterName} (wallet address gets from {@link EthSigner}) - * @return Prepared get nonce call - */ - public RemoteCall getNonce() { - return getNonce(ZkBlockParameterName.COMMITTED); - } - - public RemoteCall sendMessageToL1(byte[] message) { - return sendMessageToL1(message, null); - } - - public RemoteCall sendMessageToL1(byte[] message, @Nullable BigInteger nonce) { - return new RemoteCall<>(() -> { - BigInteger nonceToUse = nonce != null ? nonce : getNonce().send(); - String calldata = FunctionEncoder.encode(IL2Messenger.encodeSendToL1(message)); - - Transaction estimate = Transaction.createFunctionCallTransaction( - signer.getAddress(), - ZkSyncAddresses.MESSENGER_ADDRESS, - BigInteger.ZERO, - BigInteger.ZERO, - calldata - ); - - EthSendTransaction sent = estimateAndSend(estimate, nonceToUse).join(); - - try { - return this.transactionReceiptProcessor.waitForTransactionReceipt(sent.getTransactionHash()); - } catch (IOException | TransactionException e) { - throw new RuntimeException(e); - } + } + + /** + * Get nonce for wallet at block `COMMITTED` {@link ZkBlockParameterName} (wallet address gets + * from {@link EthSigner}) + * + * @return Prepared get nonce call + */ + public RemoteCall getNonce() { + return getNonce(ZkBlockParameterName.COMMITTED); + } + + public RemoteCall sendMessageToL1(byte[] message) { + return sendMessageToL1(message, null); + } + + public RemoteCall sendMessageToL1( + byte[] message, @Nullable BigInteger nonce) { + return new RemoteCall<>( + () -> { + BigInteger nonceToUse = nonce != null ? nonce : getNonce().send(); + String calldata = FunctionEncoder.encode(IL2Messenger.encodeSendToL1(message)); + + Transaction estimate = + Transaction.createFunctionCallTransaction( + signer.getAddress(), + ZkSyncAddresses.MESSENGER_ADDRESS, + BigInteger.ZERO, + BigInteger.ZERO, + calldata); + + EthSendTransaction sent = estimateAndSend(estimate, nonceToUse).join(); + + try { + return this.transactionReceiptProcessor.waitForTransactionReceipt( + sent.getTransactionHash()); + } catch (IOException | TransactionException e) { + throw new RuntimeException(e); + } }); - } - - private CompletableFuture estimateAndSend(Transaction transaction, BigInteger nonce) { - return CompletableFuture - .supplyAsync(() -> { - long chainId = signer.getDomain().join().getChainId().getValue().longValue(); - BigInteger gas = getFeeProvider().getGasLimit(transaction); - BigInteger gasPrice = getFeeProvider().getGasPrice(); - - Transaction712 prepared = new Transaction712( - chainId, - nonce, - gas, - transaction.getTo(), - transaction.getValueNumber(), - transaction.getData(), - BigInteger.valueOf(100000000L), // TODO: Estimate correct one - gasPrice, - transaction.getFrom(), - transaction.getEip712Meta() - ); - - String signature = signer.getDomain().thenCompose(domain -> signer.signTypedData(domain, prepared)).join(); - byte[] signed = TransactionEncoder.encode(prepared, TransactionEncoder.getSignatureData(signature)); - - return this.zksync.ethSendRawTransaction(Numeric.toHexString(signed)) - .sendAsync().join(); - }) - .thenApply(response -> { - if (response.hasError()) { - throw new JsonRpcResponseException(response); - } else { - return response; - } - }); - } - + } + + private CompletableFuture estimateAndSend( + Transaction transaction, BigInteger nonce) { + return CompletableFuture.supplyAsync( + () -> { + long chainId = signer.getDomain().join().getChainId().getValue().longValue(); + BigInteger gas = getFeeProvider().getGasLimit(transaction); + BigInteger gasPrice = getFeeProvider().getGasPrice(); + + Transaction712 prepared = + new Transaction712( + chainId, + nonce, + gas, + transaction.getTo(), + transaction.getValueNumber(), + transaction.getData(), + BigInteger.valueOf(100000000L), // TODO: Estimate correct one + gasPrice, + transaction.getFrom(), + transaction.getEip712Meta()); + + String signature = + signer + .getDomain() + .thenCompose(domain -> signer.signTypedData(domain, prepared)) + .join(); + byte[] signed = + TransactionEncoder.encode( + prepared, TransactionEncoder.getSignatureData(signature)); + + return this.zksync + .ethSendRawTransaction(Numeric.toHexString(signed)) + .sendAsync() + .join(); + }) + .thenApply( + response -> { + if (response.hasError()) { + throw new JsonRpcResponseException(response); + } else { + return response; + } + }); + } } diff --git a/src/main/java/io/zksync/abi/TransactionEncoder.java b/src/main/java/io/zksync/abi/TransactionEncoder.java index cf38aaa..7d84347 100755 --- a/src/main/java/io/zksync/abi/TransactionEncoder.java +++ b/src/main/java/io/zksync/abi/TransactionEncoder.java @@ -1,13 +1,12 @@ package io.zksync.abi; -import java.nio.ByteBuffer; -import java.util.Arrays; -import java.util.List; - import io.zksync.crypto.eip712.Eip712Domain; import io.zksync.crypto.signer.EthSigner; import io.zksync.crypto.signer.PrivateKeyEthSigner; import io.zksync.transaction.type.Transaction712; +import java.nio.ByteBuffer; +import java.util.Arrays; +import java.util.List; import org.web3j.crypto.Credentials; import org.web3j.crypto.Sign; import org.web3j.crypto.transaction.type.ITransaction; @@ -19,38 +18,37 @@ public class TransactionEncoder extends org.web3j.crypto.TransactionEncoder { - public static Sign.SignatureData getSignatureData(String signature) { - byte[] signatureRaw = Numeric.hexStringToByteArray(signature); + public static Sign.SignatureData getSignatureData(String signature) { + byte[] signatureRaw = Numeric.hexStringToByteArray(signature); - return new Sign.SignatureData( - Arrays.copyOfRange(signatureRaw, 64, signatureRaw.length), - Arrays.copyOfRange(signatureRaw, 0, 32), - Arrays.copyOfRange(signatureRaw, 32, 64) - ); - } + return new Sign.SignatureData( + Arrays.copyOfRange(signatureRaw, 64, signatureRaw.length), + Arrays.copyOfRange(signatureRaw, 0, 32), + Arrays.copyOfRange(signatureRaw, 32, 64)); + } - public static Sign.SignatureData signMessage(Transaction712 transactionRequest, Eip712Domain domain, Credentials credentials) { - EthSigner signer = new PrivateKeyEthSigner(credentials, domain); - String signature = signer.signTypedData(domain, transactionRequest).join(); - return getSignatureData(signature); - } + public static Sign.SignatureData signMessage( + Transaction712 transactionRequest, Eip712Domain domain, Credentials credentials) { + EthSigner signer = new PrivateKeyEthSigner(credentials, domain); + String signature = signer.signTypedData(domain, transactionRequest).join(); + return getSignatureData(signature); + } - public static byte[] encode(ITransaction rawTransaction, Sign.SignatureData signatureData) { - List values = rawTransaction.asRlpValues(signatureData); - RlpList rlpList = new RlpList(values); - byte[] encoded = RlpEncoder.encode(rlpList); - if (!rawTransaction.getType().equals(TransactionType.LEGACY)) { - return ByteBuffer.allocate(encoded.length + 1) - .put(rawTransaction.getType().getRlpType()) - .put(encoded) - .array(); - } else if (rawTransaction instanceof Transaction712) { - return ByteBuffer.allocate(encoded.length + 1) - .put(Transaction712.EIP_712_TX_TYPE) - .put(encoded) - .array(); - } - return encoded; + public static byte[] encode(ITransaction rawTransaction, Sign.SignatureData signatureData) { + List values = rawTransaction.asRlpValues(signatureData); + RlpList rlpList = new RlpList(values); + byte[] encoded = RlpEncoder.encode(rlpList); + if (!rawTransaction.getType().equals(TransactionType.LEGACY)) { + return ByteBuffer.allocate(encoded.length + 1) + .put(rawTransaction.getType().getRlpType()) + .put(encoded) + .array(); + } else if (rawTransaction instanceof Transaction712) { + return ByteBuffer.allocate(encoded.length + 1) + .put(Transaction712.EIP_712_TX_TYPE) + .put(encoded) + .array(); } - + return encoded; + } } diff --git a/src/main/java/io/zksync/abi/ZkFunctionEncoder.java b/src/main/java/io/zksync/abi/ZkFunctionEncoder.java index 7effcb5..8054f4c 100644 --- a/src/main/java/io/zksync/abi/ZkFunctionEncoder.java +++ b/src/main/java/io/zksync/abi/ZkFunctionEncoder.java @@ -1,190 +1,183 @@ package io.zksync.abi; -import org.apache.commons.lang3.ArrayUtils; -import org.web3j.abi.FunctionEncoder; -import org.web3j.abi.TypeEncoder; -import org.web3j.abi.datatypes.*; -import org.web3j.utils.Numeric; +import static org.web3j.abi.Utils.staticStructNestedPublicFieldsFlatList; import java.math.BigInteger; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.Arrays; import java.util.List; - -import static org.web3j.abi.Utils.staticStructNestedPublicFieldsFlatList; +import org.apache.commons.lang3.ArrayUtils; +import org.web3j.abi.FunctionEncoder; +import org.web3j.abi.TypeEncoder; +import org.web3j.abi.datatypes.*; +import org.web3j.utils.Numeric; public class ZkFunctionEncoder extends FunctionEncoder { - private static final int ABI_OFFSET_CALL_RETURN_DATA = 8; - private static final int ABI_OFFSET_RETURN_DATA_SIZE = 1; - private static final int ABI_OFFSET_CALLDATA_SIZE = 0; + private static final int ABI_OFFSET_CALL_RETURN_DATA = 8; + private static final int ABI_OFFSET_RETURN_DATA_SIZE = 1; + private static final int ABI_OFFSET_CALLDATA_SIZE = 0; - private static final int ABI_MEMORY_DATA_OFFSET = 1; - private static final int ABI_MEMORY_HEADER_OFFSET = 0; - private static final int ABI_OFFSET_ENTRY_HASH = 7; - private static final int FIELD_SIZE = 32; - - @Override - @SuppressWarnings("rawtypes") - public String encodeFunction(final Function function) { - final List parameters = function.getInputParameters(); + private static final int ABI_MEMORY_DATA_OFFSET = 1; + private static final int ABI_MEMORY_HEADER_OFFSET = 0; + private static final int ABI_OFFSET_ENTRY_HASH = 7; + private static final int FIELD_SIZE = 32; - final String methodSignature = buildMethodSignature(function.getName(), parameters); - final String methodId = buildMethodId(methodSignature); + @Override + @SuppressWarnings("rawtypes") + public String encodeFunction(final Function function) { + final List parameters = function.getInputParameters(); - final StringBuilder result = new StringBuilder(); - result.append(methodId); + final String methodSignature = buildMethodSignature(function.getName(), parameters); + final String methodId = buildMethodId(methodSignature); - return encodeParameters(parameters, result); - } + final StringBuilder result = new StringBuilder(); + result.append(methodId); - @Override - @SuppressWarnings("rawtypes") - public String encodeParameters(final List parameters) { - return encodeParameters(parameters, new StringBuilder()); - } + return encodeParameters(parameters, result); + } - @Override - protected String encodeWithSelector(String methodId, List parameters) { - final StringBuilder result = new StringBuilder(methodId); + @Override + @SuppressWarnings("rawtypes") + public String encodeParameters(final List parameters) { + return encodeParameters(parameters, new StringBuilder()); + } - return encodeParameters(parameters, result); - } + @Override + protected String encodeWithSelector(String methodId, List parameters) { + final StringBuilder result = new StringBuilder(methodId); + + return encodeParameters(parameters, result); + } - @Override - protected String encodePackedParameters(List parameters) { - final StringBuilder result = new StringBuilder(); - for (Type parameter : parameters) { - result.append(TypeEncoder.encodePacked(parameter)); - } - return result.toString(); + @Override + protected String encodePackedParameters(List parameters) { + final StringBuilder result = new StringBuilder(); + for (Type parameter : parameters) { + result.append(TypeEncoder.encodePacked(parameter)); } + return result.toString(); + } - public static byte[] encodeConstructor(byte[] calldata) { - int size = calldata.length; + public static byte[] encodeConstructor(byte[] calldata) { + int size = calldata.length; - if (size % 32 != 0) { - int offset = 32 - size % 32; - int newLength = size + offset; - calldata = Arrays.copyOf(calldata, newLength); - } + if (size % 32 != 0) { + int offset = 32 - size % 32; + int newLength = size + offset; + calldata = Arrays.copyOf(calldata, newLength); + } - byte[] result = new byte[ABI_MEMORY_DATA_OFFSET * FIELD_SIZE + calldata.length]; + byte[] result = new byte[ABI_MEMORY_DATA_OFFSET * FIELD_SIZE + calldata.length]; - int calldataOffset = ABI_MEMORY_HEADER_OFFSET * FIELD_SIZE; - byte[] calldataSize = ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN).putInt(size).array(); + int calldataOffset = ABI_MEMORY_HEADER_OFFSET * FIELD_SIZE; + byte[] calldataSize = + ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN).putInt(size).array(); - System.arraycopy(calldataSize, 0, result, calldataOffset, 4); + System.arraycopy(calldataSize, 0, result, calldataOffset, 4); - int constructorDataOffset = 8; - result[constructorDataOffset] |= 0b00000001; + int constructorDataOffset = 8; + result[constructorDataOffset] |= 0b00000001; - for (int i = 0; i < calldata.length; i += FIELD_SIZE) { - ArrayUtils.reverse(calldata, i, Math.min(calldata.length, i + FIELD_SIZE)); - } - System.arraycopy(calldata, 0, result, FIELD_SIZE, calldata.length); + for (int i = 0; i < calldata.length; i += FIELD_SIZE) { + ArrayUtils.reverse(calldata, i, Math.min(calldata.length, i + FIELD_SIZE)); + } + System.arraycopy(calldata, 0, result, FIELD_SIZE, calldata.length); + + return result; + } + + public static byte[] encodeCalldata(Function function) { + final byte[] calldata = Numeric.hexStringToByteArray(FunctionEncoder.encode(function)); + final int calldataSize = function.getInputParameters().size(); + final int returndataSize = function.getOutputParameters().size(); + final int size = (ABI_OFFSET_CALL_RETURN_DATA + calldataSize) * FIELD_SIZE; + final int calldataSizeOffset = ABI_OFFSET_CALLDATA_SIZE * FIELD_SIZE; + final ByteBuffer buffer = ByteBuffer.allocate(size); + buffer.order(ByteOrder.LITTLE_ENDIAN); + buffer.putInt(calldataSizeOffset, calldataSize); + + final int returndataSizeOffset = ABI_OFFSET_RETURN_DATA_SIZE * FIELD_SIZE; + buffer.putInt(returndataSizeOffset, returndataSize); + + final int constructorCalllOffset = ABI_OFFSET_ENTRY_HASH * FIELD_SIZE; + buffer.put(constructorCalllOffset, (byte) 0); + + final int entryHashOffset = (ABI_OFFSET_ENTRY_HASH + 1) * FIELD_SIZE - 4; + final byte[] selector = ArrayUtils.subarray(calldata, 0, 4); + ArrayUtils.reverse(selector); + for (int i = 0; i < 4; i++) { + buffer.put(entryHashOffset + i, selector[i]); + } - return result; + int calldataOffset = ABI_OFFSET_CALL_RETURN_DATA * FIELD_SIZE; + for (Type value : function.getInputParameters()) { + final String result = TypeEncoder.encode(value); + final byte[] encoded = Numeric.hexStringToByteArray(result); + ArrayUtils.reverse(encoded); + for (int i = 0; i < encoded.length; i++) { + buffer.put(calldataOffset + i, encoded[i]); + } + calldataOffset += FIELD_SIZE; } - public static byte[] encodeCalldata(Function function) { - final byte[] calldata = Numeric.hexStringToByteArray(FunctionEncoder.encode(function)); - final int calldataSize = function.getInputParameters().size(); - final int returndataSize = function.getOutputParameters().size(); - final int size = (ABI_OFFSET_CALL_RETURN_DATA + calldataSize) * FIELD_SIZE; - final int calldataSizeOffset = ABI_OFFSET_CALLDATA_SIZE * FIELD_SIZE; - final ByteBuffer buffer = ByteBuffer.allocate(size); - buffer.order(ByteOrder.LITTLE_ENDIAN); - buffer.putInt(calldataSizeOffset, calldataSize); - - final int returndataSizeOffset = ABI_OFFSET_RETURN_DATA_SIZE * FIELD_SIZE; - buffer.putInt(returndataSizeOffset, returndataSize); - - final int constructorCalllOffset = ABI_OFFSET_ENTRY_HASH * FIELD_SIZE; - buffer.put(constructorCalllOffset, (byte) 0); - - final int entryHashOffset = (ABI_OFFSET_ENTRY_HASH + 1) * FIELD_SIZE - 4; - final byte[] selector = ArrayUtils.subarray(calldata, 0, 4); - ArrayUtils.reverse(selector); - for (int i = 0; i < 4; i++) { - buffer.put(entryHashOffset + i, selector[i]); - } - - int calldataOffset = ABI_OFFSET_CALL_RETURN_DATA * FIELD_SIZE; - for (Type value : function.getInputParameters()) { - final String result = TypeEncoder.encode(value); - final byte[] encoded = Numeric.hexStringToByteArray(result); - ArrayUtils.reverse(encoded); - for (int i = 0; i < encoded.length; i++) { - buffer.put(calldataOffset + i, encoded[i]); - } - calldataOffset += FIELD_SIZE; - } - - return buffer.array(); + return buffer.array(); + } - } + @SuppressWarnings("rawtypes") + private static String encodeParameters(final List parameters, final StringBuilder result) { - @SuppressWarnings("rawtypes") - private static String encodeParameters( - final List parameters, final StringBuilder result) { - - int dynamicDataOffset = getLength(parameters) * Type.MAX_BYTE_LENGTH; - final StringBuilder dynamicData = new StringBuilder(); - - for (Type parameter : parameters) { - final String encodedValue = ZkTypeEncoder.encode(parameter); - - if (isDynamic(parameter)) { - final String encodedDataOffset = - TypeEncoder.encode(new Uint(BigInteger.valueOf(dynamicDataOffset))); - result.append(encodedDataOffset); - dynamicData.append(encodedValue); - dynamicDataOffset += encodedValue.length() >> 1; - } else { - result.append(encodedValue); - } - } - result.append(dynamicData); - - return result.toString(); - } + int dynamicDataOffset = getLength(parameters) * Type.MAX_BYTE_LENGTH; + final StringBuilder dynamicData = new StringBuilder(); - @SuppressWarnings({"unchecked", "rawtypes"}) - private static int getLength(final List parameters) { - int count = 0; - for (final Type type : parameters) { - if (type instanceof StaticArray - && StaticStruct.class.isAssignableFrom( - ((StaticArray) type).getComponentType())) { - count += - staticStructNestedPublicFieldsFlatList( - ((StaticArray) type).getComponentType()) - .size() - * ((StaticArray) type).getValue().size(); - } else if (type instanceof StaticArray - && DynamicStruct.class.isAssignableFrom( - ((StaticArray) type).getComponentType())) { - count++; - } else if(type instanceof StaticStruct) { - count += getLength(((StaticStruct) type).getValue()); - } else if (type instanceof StaticArray) { - count += ((StaticArray) type).getValue().size(); - } else { - count++; - } - } - return count; - } + for (Type parameter : parameters) { + final String encodedValue = ZkTypeEncoder.encode(parameter); - @SuppressWarnings("rawtypes") - static boolean isDynamic(Type parameter) { - return parameter instanceof DynamicBytes - || parameter instanceof Utf8String - || parameter instanceof DynamicArray - || (parameter instanceof StaticArray - && DynamicStruct.class.isAssignableFrom( - ((StaticArray) parameter).getComponentType())); + if (isDynamic(parameter)) { + final String encodedDataOffset = + TypeEncoder.encode(new Uint(BigInteger.valueOf(dynamicDataOffset))); + result.append(encodedDataOffset); + dynamicData.append(encodedValue); + dynamicDataOffset += encodedValue.length() >> 1; + } else { + result.append(encodedValue); + } + } + result.append(dynamicData); + + return result.toString(); + } + + @SuppressWarnings({"unchecked", "rawtypes"}) + private static int getLength(final List parameters) { + int count = 0; + for (final Type type : parameters) { + if (type instanceof StaticArray + && StaticStruct.class.isAssignableFrom(((StaticArray) type).getComponentType())) { + count += + staticStructNestedPublicFieldsFlatList(((StaticArray) type).getComponentType()).size() + * ((StaticArray) type).getValue().size(); + } else if (type instanceof StaticArray + && DynamicStruct.class.isAssignableFrom(((StaticArray) type).getComponentType())) { + count++; + } else if (type instanceof StaticStruct) { + count += getLength(((StaticStruct) type).getValue()); + } else if (type instanceof StaticArray) { + count += ((StaticArray) type).getValue().size(); + } else { + count++; + } } + return count; + } + + @SuppressWarnings("rawtypes") + static boolean isDynamic(Type parameter) { + return parameter instanceof DynamicBytes + || parameter instanceof Utf8String + || parameter instanceof DynamicArray + || (parameter instanceof StaticArray + && DynamicStruct.class.isAssignableFrom(((StaticArray) parameter).getComponentType())); + } } diff --git a/src/main/java/io/zksync/abi/ZkFunctionEncoderProvider.java b/src/main/java/io/zksync/abi/ZkFunctionEncoderProvider.java index e96ac16..d97621d 100644 --- a/src/main/java/io/zksync/abi/ZkFunctionEncoderProvider.java +++ b/src/main/java/io/zksync/abi/ZkFunctionEncoderProvider.java @@ -5,9 +5,8 @@ public class ZkFunctionEncoderProvider implements FunctionEncoderProvider { - @Override - public FunctionEncoder get() { - return new ZkFunctionEncoder(); - } - + @Override + public FunctionEncoder get() { + return new ZkFunctionEncoder(); + } } diff --git a/src/main/java/io/zksync/abi/ZkTypeEncoder.java b/src/main/java/io/zksync/abi/ZkTypeEncoder.java index 3362f81..0883556 100644 --- a/src/main/java/io/zksync/abi/ZkTypeEncoder.java +++ b/src/main/java/io/zksync/abi/ZkTypeEncoder.java @@ -1,392 +1,381 @@ package io.zksync.abi; -import org.web3j.abi.TypeEncoder; -import org.web3j.abi.datatypes.*; -import org.web3j.abi.datatypes.primitive.PrimitiveType; -import org.web3j.utils.Numeric; +import static org.web3j.abi.datatypes.Type.MAX_BIT_LENGTH; +import static org.web3j.abi.datatypes.Type.MAX_BYTE_LENGTH; import java.math.BigInteger; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; - -import static org.web3j.abi.datatypes.Type.MAX_BIT_LENGTH; -import static org.web3j.abi.datatypes.Type.MAX_BYTE_LENGTH; +import org.web3j.abi.TypeEncoder; +import org.web3j.abi.datatypes.*; +import org.web3j.abi.datatypes.primitive.PrimitiveType; +import org.web3j.utils.Numeric; public class ZkTypeEncoder { - private ZkTypeEncoder() {} + private ZkTypeEncoder() {} - static boolean isDynamic(Type parameter) { - return parameter instanceof DynamicBytes - || parameter instanceof Utf8String - || parameter instanceof DynamicArray - || (parameter instanceof StaticArray - && DynamicStruct.class.isAssignableFrom( - ((StaticArray) parameter).getComponentType())); - } + static boolean isDynamic(Type parameter) { + return parameter instanceof DynamicBytes + || parameter instanceof Utf8String + || parameter instanceof DynamicArray + || (parameter instanceof StaticArray + && DynamicStruct.class.isAssignableFrom(((StaticArray) parameter).getComponentType())); + } - @SuppressWarnings("unchecked") - public static String encode(Type parameter) { - if (parameter instanceof NumericType) { - return encodeNumeric(((NumericType) parameter)); - } else if (parameter instanceof Address) { - return encodeAddress((Address) parameter); - } else if (parameter instanceof Bool) { - return encodeBool((Bool) parameter); - } else if (parameter instanceof Bytes) { - return encodeBytes((Bytes) parameter); - } else if (parameter instanceof DynamicBytes) { - return encodeDynamicBytes((DynamicBytes) parameter); - } else if (parameter instanceof Utf8String) { - return encodeString((Utf8String) parameter); - } else if (parameter instanceof StaticArray) { - if (DynamicStruct.class.isAssignableFrom( - ((StaticArray) parameter).getComponentType())) { - return encodeStaticArrayWithDynamicStruct((StaticArray) parameter); - } else { - return encodeArrayValues((StaticArray) parameter); - } - } else if (parameter instanceof DynamicStruct) { - return encodeDynamicStruct((DynamicStruct) parameter); - } else if (parameter instanceof DynamicArray) { - return encodeDynamicArray((DynamicArray) parameter); - } else if (parameter instanceof PrimitiveType) { - return encode(((PrimitiveType) parameter).toSolidityType()); - } else { - throw new UnsupportedOperationException( - "Type cannot be encoded: " + parameter.getClass()); - } + @SuppressWarnings("unchecked") + public static String encode(Type parameter) { + if (parameter instanceof NumericType) { + return encodeNumeric(((NumericType) parameter)); + } else if (parameter instanceof Address) { + return encodeAddress((Address) parameter); + } else if (parameter instanceof Bool) { + return encodeBool((Bool) parameter); + } else if (parameter instanceof Bytes) { + return encodeBytes((Bytes) parameter); + } else if (parameter instanceof DynamicBytes) { + return encodeDynamicBytes((DynamicBytes) parameter); + } else if (parameter instanceof Utf8String) { + return encodeString((Utf8String) parameter); + } else if (parameter instanceof StaticArray) { + if (DynamicStruct.class.isAssignableFrom(((StaticArray) parameter).getComponentType())) { + return encodeStaticArrayWithDynamicStruct((StaticArray) parameter); + } else { + return encodeArrayValues((StaticArray) parameter); + } + } else if (parameter instanceof DynamicStruct) { + return encodeDynamicStruct((DynamicStruct) parameter); + } else if (parameter instanceof DynamicArray) { + return encodeDynamicArray((DynamicArray) parameter); + } else if (parameter instanceof PrimitiveType) { + return encode(((PrimitiveType) parameter).toSolidityType()); + } else { + throw new UnsupportedOperationException("Type cannot be encoded: " + parameter.getClass()); } + } - /** - * Returns abi.encodePacked hex value for the supported types. First the value is encoded and - * after the padding or length, in arrays cases, is removed resulting the packed encode hex - * value - * - * @param parameter Value to be encoded - * @return - */ - public static String encodePacked(Type parameter) { - if (parameter instanceof Utf8String) { - return removePadding(encode(parameter), parameter); - } else if (parameter instanceof DynamicBytes) { - return encode(parameter).substring(64); - } else if (parameter instanceof DynamicArray) { - return arrayEncodePacked((DynamicArray) parameter); - } else if (parameter instanceof StaticArray) { - return arrayEncodePacked((StaticArray) parameter); - } else if (parameter instanceof PrimitiveType) { - return encodePacked(((PrimitiveType) parameter).toSolidityType()); - } else { - return removePadding(encode(parameter), parameter); - } + /** + * Returns abi.encodePacked hex value for the supported types. First the value is encoded and + * after the padding or length, in arrays cases, is removed resulting the packed encode hex value + * + * @param parameter Value to be encoded + * @return + */ + public static String encodePacked(Type parameter) { + if (parameter instanceof Utf8String) { + return removePadding(encode(parameter), parameter); + } else if (parameter instanceof DynamicBytes) { + return encode(parameter).substring(64); + } else if (parameter instanceof DynamicArray) { + return arrayEncodePacked((DynamicArray) parameter); + } else if (parameter instanceof StaticArray) { + return arrayEncodePacked((StaticArray) parameter); + } else if (parameter instanceof PrimitiveType) { + return encodePacked(((PrimitiveType) parameter).toSolidityType()); + } else { + return removePadding(encode(parameter), parameter); } + } - /** - * Remove padding from the static types and {@link Utf8String} after the encode was applied - * - * @param encodedValue Encoded value of the parameter - * @param parameter Value which was encoded - * @return The encoded value without padding - */ - static String removePadding(String encodedValue, Type parameter) { - if (parameter instanceof NumericType) { - if (parameter instanceof Ufixed || parameter instanceof Fixed) { - return encodedValue; - } - return encodedValue.substring(64 - ((NumericType) parameter).getBitSize() / 4, 64); - } else if (parameter instanceof Address) { - return encodedValue.substring(64 - ((Address) parameter).toUint().getBitSize() / 4, 64); - } else if (parameter instanceof Bool) { - return encodedValue.substring(62, 64); - } - if (parameter instanceof Bytes) { - return encodedValue.substring(0, ((BytesType) parameter).getValue().length * 2); - } - if (parameter instanceof Utf8String) { - int length = - ((Utf8String) parameter).getValue().getBytes(StandardCharsets.UTF_8).length; - return encodedValue.substring(64, 64 + length * 2); - } else { - throw new UnsupportedOperationException( - "Type cannot be encoded: " + parameter.getClass()); - } + /** + * Remove padding from the static types and {@link Utf8String} after the encode was applied + * + * @param encodedValue Encoded value of the parameter + * @param parameter Value which was encoded + * @return The encoded value without padding + */ + static String removePadding(String encodedValue, Type parameter) { + if (parameter instanceof NumericType) { + if (parameter instanceof Ufixed || parameter instanceof Fixed) { + return encodedValue; + } + return encodedValue.substring(64 - ((NumericType) parameter).getBitSize() / 4, 64); + } else if (parameter instanceof Address) { + return encodedValue.substring(64 - ((Address) parameter).toUint().getBitSize() / 4, 64); + } else if (parameter instanceof Bool) { + return encodedValue.substring(62, 64); + } + if (parameter instanceof Bytes) { + return encodedValue.substring(0, ((BytesType) parameter).getValue().length * 2); } + if (parameter instanceof Utf8String) { + int length = ((Utf8String) parameter).getValue().getBytes(StandardCharsets.UTF_8).length; + return encodedValue.substring(64, 64 + length * 2); + } else { + throw new UnsupportedOperationException("Type cannot be encoded: " + parameter.getClass()); + } + } - /** - * Encodes a static array containing a dynamic struct type. In this case, the array items are - * decoded as dynamic values and have their offsets at the beginning of the encoding. Example: - * For the following static array containing three elements: StaticArray3 - * enc([struct1, struct2, struct2]) = offset(enc(struct1)) offset(enc(struct2)) - * offset(enc(struct3)) enc(struct1) enc(struct2) enc(struct3) - * - * @param - * @return - */ - private static String encodeStaticArrayWithDynamicStruct(Array value) { - String valuesOffsets = encodeStructsArraysOffsets(value); - String encodedValues = encodeArrayValues(value); + /** + * Encodes a static array containing a dynamic struct type. In this case, the array items are + * decoded as dynamic values and have their offsets at the beginning of the encoding. Example: For + * the following static array containing three elements: StaticArray3 enc([struct1, + * struct2, struct2]) = offset(enc(struct1)) offset(enc(struct2)) offset(enc(struct3)) + * enc(struct1) enc(struct2) enc(struct3) + * + * @param + * @return + */ + private static String encodeStaticArrayWithDynamicStruct(Array value) { + String valuesOffsets = encodeStructsArraysOffsets(value); + String encodedValues = encodeArrayValues(value); - StringBuilder result = new StringBuilder(); - result.append(valuesOffsets); - result.append(encodedValues); - return result.toString(); - } + StringBuilder result = new StringBuilder(); + result.append(valuesOffsets); + result.append(encodedValues); + return result.toString(); + } + + static String encodeAddress(Address address) { + return encodeNumeric(address.toUint()); + } - static String encodeAddress(Address address) { - return encodeNumeric(address.toUint()); + static String encodeNumeric(NumericType numericType) { + byte[] rawValue = toByteArray(numericType); + byte paddingValue = getPaddingValue(numericType); + byte[] paddedRawValue = new byte[MAX_BYTE_LENGTH]; + if (paddingValue != 0) { + for (int i = 0; i < paddedRawValue.length; i++) { + paddedRawValue[i] = paddingValue; + } } - static String encodeNumeric(NumericType numericType) { - byte[] rawValue = toByteArray(numericType); - byte paddingValue = getPaddingValue(numericType); - byte[] paddedRawValue = new byte[MAX_BYTE_LENGTH]; - if (paddingValue != 0) { - for (int i = 0; i < paddedRawValue.length; i++) { - paddedRawValue[i] = paddingValue; - } - } + System.arraycopy( + rawValue, 0, paddedRawValue, MAX_BYTE_LENGTH - rawValue.length, rawValue.length); + return Numeric.toHexStringNoPrefix(paddedRawValue); + } - System.arraycopy( - rawValue, 0, paddedRawValue, MAX_BYTE_LENGTH - rawValue.length, rawValue.length); - return Numeric.toHexStringNoPrefix(paddedRawValue); + private static byte getPaddingValue(NumericType numericType) { + if (numericType.getValue().signum() == -1) { + return (byte) 0xff; + } else { + return 0; } + } - private static byte getPaddingValue(NumericType numericType) { - if (numericType.getValue().signum() == -1) { - return (byte) 0xff; - } else { - return 0; - } + private static byte[] toByteArray(NumericType numericType) { + BigInteger value = numericType.getValue(); + if (numericType instanceof Ufixed || numericType instanceof Uint) { + if (value.bitLength() == MAX_BIT_LENGTH) { + // As BigInteger is signed, if we have a 256 bit value, the resultant byte array + // will contain a sign byte in it's MSB, which we should ignore for this unsigned + // integer type. + byte[] byteArray = new byte[MAX_BYTE_LENGTH]; + System.arraycopy(value.toByteArray(), 1, byteArray, 0, MAX_BYTE_LENGTH); + return byteArray; + } } + return value.toByteArray(); + } - private static byte[] toByteArray(NumericType numericType) { - BigInteger value = numericType.getValue(); - if (numericType instanceof Ufixed || numericType instanceof Uint) { - if (value.bitLength() == MAX_BIT_LENGTH) { - // As BigInteger is signed, if we have a 256 bit value, the resultant byte array - // will contain a sign byte in it's MSB, which we should ignore for this unsigned - // integer type. - byte[] byteArray = new byte[MAX_BYTE_LENGTH]; - System.arraycopy(value.toByteArray(), 1, byteArray, 0, MAX_BYTE_LENGTH); - return byteArray; - } - } - return value.toByteArray(); + static String encodeBool(Bool value) { + byte[] rawValue = new byte[MAX_BYTE_LENGTH]; + if (value.getValue()) { + rawValue[rawValue.length - 1] = 1; } + return Numeric.toHexStringNoPrefix(rawValue); + } - static String encodeBool(Bool value) { - byte[] rawValue = new byte[MAX_BYTE_LENGTH]; - if (value.getValue()) { - rawValue[rawValue.length - 1] = 1; - } - return Numeric.toHexStringNoPrefix(rawValue); + static String encodeBytes(BytesType bytesType) { + byte[] value = bytesType.getValue(); + int length = value.length; + int mod = length % MAX_BYTE_LENGTH; + String val = Numeric.toHexString(value); + byte[] dest; + if (mod != 0) { + int padding = MAX_BYTE_LENGTH - mod; + dest = new byte[padding]; + return Numeric.toHexStringNoPrefix(dest) + Numeric.toHexStringNoPrefix(value); + } else { + dest = value; } - static String encodeBytes(BytesType bytesType) { - byte[] value = bytesType.getValue(); - int length = value.length; - int mod = length % MAX_BYTE_LENGTH; - String val = Numeric.toHexString(value); - byte[] dest; - if (mod != 0) { - int padding = MAX_BYTE_LENGTH - mod; - dest = new byte[padding]; - return Numeric.toHexStringNoPrefix(dest) + Numeric.toHexStringNoPrefix(value); - } else { - dest = value; - } + String x = Numeric.toHexString(value); + return Numeric.toHexStringNoPrefix(dest); + } - String x = Numeric.toHexString(value); - return Numeric.toHexStringNoPrefix(dest); - } + static String encodeDynamicBytes(DynamicBytes dynamicBytes) { + int size = dynamicBytes.getValue().length; + String encodedLength = encode(new Uint(BigInteger.valueOf(size))); + String encodedValue = encodeBytes(dynamicBytes); - static String encodeDynamicBytes(DynamicBytes dynamicBytes) { - int size = dynamicBytes.getValue().length; - String encodedLength = encode(new Uint(BigInteger.valueOf(size))); - String encodedValue = encodeBytes(dynamicBytes); + StringBuilder result = new StringBuilder(); + result.append(encodedLength); + result.append(encodedValue); + return result.toString(); + } - StringBuilder result = new StringBuilder(); - result.append(encodedLength); - result.append(encodedValue); - return result.toString(); - } + static String encodeString(Utf8String string) { + byte[] utfEncoded = string.getValue().getBytes(StandardCharsets.UTF_8); + return encodeDynamicBytes(new DynamicBytes(utfEncoded)); + } - static String encodeString(Utf8String string) { - byte[] utfEncoded = string.getValue().getBytes(StandardCharsets.UTF_8); - return encodeDynamicBytes(new DynamicBytes(utfEncoded)); + static String encodeArrayValues(Array value) { + StringBuilder result = new StringBuilder(); + for (Type type : value.getValue()) { + result.append(encode(type)); } + return result.toString(); + } - static String encodeArrayValues(Array value) { - StringBuilder result = new StringBuilder(); - for (Type type : value.getValue()) { - result.append(encode(type)); - } - return result.toString(); - } + static String encodeDynamicStruct(final DynamicStruct value) { + String encodedValues = encodeDynamicStructValues(value); - static String encodeDynamicStruct(final DynamicStruct value) { - String encodedValues = encodeDynamicStructValues(value); + StringBuilder result = new StringBuilder(); + result.append(encodedValues); + return result.toString(); + } - StringBuilder result = new StringBuilder(); - result.append(encodedValues); - return result.toString(); + private static String encodeDynamicStructValues(final DynamicStruct value) { + int staticSize = 0; + for (int i = 0; i < value.getValue().size(); ++i) { + final Type type = value.getValue().get(i); + if (isDynamic(type)) { + staticSize += 32; + } else { + staticSize += type.bytes32PaddedLength(); + } } - - private static String encodeDynamicStructValues(final DynamicStruct value) { - int staticSize = 0; - for (int i = 0; i < value.getValue().size(); ++i) { - final Type type = value.getValue().get(i); - if (isDynamic(type)) { - staticSize += 32; - } else { - staticSize += type.bytes32PaddedLength(); - } - } - int dynamicOffset = staticSize; - final List offsetsAndStaticValues = new ArrayList<>(); - final List dynamicValues = new ArrayList<>(); - for (int i = 0; i < value.getValue().size(); ++i) { - final Type type = value.getValue().get(i); - if (isDynamic(type)) { - offsetsAndStaticValues.add( - Numeric.toHexStringNoPrefix( - Numeric.toBytesPadded( - new BigInteger(Long.toString(dynamicOffset)), - MAX_BYTE_LENGTH))); - String encodedValue = encode(type); - dynamicValues.add(encodedValue); - dynamicOffset += encodedValue.length() >> 1; - } else { - offsetsAndStaticValues.add(encode(value.getValue().get(i))); - } - } - final List data = new ArrayList<>(); - data.addAll(offsetsAndStaticValues); - data.addAll(dynamicValues); - return String.join("", data); + int dynamicOffset = staticSize; + final List offsetsAndStaticValues = new ArrayList<>(); + final List dynamicValues = new ArrayList<>(); + for (int i = 0; i < value.getValue().size(); ++i) { + final Type type = value.getValue().get(i); + if (isDynamic(type)) { + offsetsAndStaticValues.add( + Numeric.toHexStringNoPrefix( + Numeric.toBytesPadded( + new BigInteger(Long.toString(dynamicOffset)), MAX_BYTE_LENGTH))); + String encodedValue = encode(type); + dynamicValues.add(encodedValue); + dynamicOffset += encodedValue.length() >> 1; + } else { + offsetsAndStaticValues.add(encode(value.getValue().get(i))); + } } + final List data = new ArrayList<>(); + data.addAll(offsetsAndStaticValues); + data.addAll(dynamicValues); + return String.join("", data); + } - static String encodeDynamicArray(DynamicArray value) { - int size = value.getValue().size(); - String encodedLength = encode(new Uint(BigInteger.valueOf(size))); - String valuesOffsets = encodeArrayValuesOffsets(value); - String encodedValues = encodeArrayValues(value); + static String encodeDynamicArray(DynamicArray value) { + int size = value.getValue().size(); + String encodedLength = encode(new Uint(BigInteger.valueOf(size))); + String valuesOffsets = encodeArrayValuesOffsets(value); + String encodedValues = encodeArrayValues(value); - StringBuilder result = new StringBuilder(); - result.append(encodedLength); - result.append(valuesOffsets); - result.append(encodedValues); - return result.toString(); - } + StringBuilder result = new StringBuilder(); + result.append(encodedLength); + result.append(valuesOffsets); + result.append(encodedValues); + return result.toString(); + } - /** - * Encodes the array values offsets of the to be encrypted dynamic array, which are in our case - * the heads of the encryption. Refer to - * - * @see encoding - * formal specification - *

Dynamic structs array encryption

- *

An array of dynamic structs (ie, structs containing dynamic datatypes) is encoded in - * the following way: Considering X = [struct1, struct2] for example enc(X) = head(struct1) - * head(struct2) tail(struct1) tail(struct2) with: - tail(struct1) = enc(struct1) - - * tail(struct2) = enc(struct2) - head(struct1) = enc(len( head(struct1) head(struct2))) = - * enc(64), because the heads are 256bits - head(struct2) = enc(len( head(struct1) - * head(struct2) tail(struct1))) - */ - private static String encodeArrayValuesOffsets(DynamicArray value) { - StringBuilder result = new StringBuilder(); - boolean arrayOfBytes = - !value.getValue().isEmpty() && value.getValue().get(0) instanceof DynamicBytes; - boolean arrayOfString = - !value.getValue().isEmpty() && value.getValue().get(0) instanceof Utf8String; - boolean arrayOfDynamicStructs = - !value.getValue().isEmpty() && value.getValue().get(0) instanceof DynamicStruct; - if (arrayOfBytes || arrayOfString) { - long offset = 0; - for (int i = 0; i < value.getValue().size(); i++) { - if (i == 0) { - offset = value.getValue().size() * MAX_BYTE_LENGTH; - } else { - int bytesLength = - arrayOfBytes - ? ((byte[]) value.getValue().get(i - 1).getValue()).length - : ((String) value.getValue().get(i - 1).getValue()).length(); - int numberOfWords = (bytesLength + MAX_BYTE_LENGTH - 1) / MAX_BYTE_LENGTH; - int totalBytesLength = numberOfWords * MAX_BYTE_LENGTH; - offset += totalBytesLength + MAX_BYTE_LENGTH; - } - result.append( - Numeric.toHexStringNoPrefix( - Numeric.toBytesPadded( - new BigInteger(Long.toString(offset)), MAX_BYTE_LENGTH))); - } - } else if (arrayOfDynamicStructs) { - result.append(encodeStructsArraysOffsets(value)); + /** + * Encodes the array values offsets of the to be encrypted dynamic array, which are in our case + * the heads of the encryption. Refer to + * + * @see encoding + * formal specification + *

Dynamic structs array encryption

+ *

An array of dynamic structs (ie, structs containing dynamic datatypes) is encoded in the + * following way: Considering X = [struct1, struct2] for example enc(X) = head(struct1) + * head(struct2) tail(struct1) tail(struct2) with: - tail(struct1) = enc(struct1) - + * tail(struct2) = enc(struct2) - head(struct1) = enc(len( head(struct1) head(struct2))) = + * enc(64), because the heads are 256bits - head(struct2) = enc(len( head(struct1) + * head(struct2) tail(struct1))) + */ + private static String encodeArrayValuesOffsets(DynamicArray value) { + StringBuilder result = new StringBuilder(); + boolean arrayOfBytes = + !value.getValue().isEmpty() && value.getValue().get(0) instanceof DynamicBytes; + boolean arrayOfString = + !value.getValue().isEmpty() && value.getValue().get(0) instanceof Utf8String; + boolean arrayOfDynamicStructs = + !value.getValue().isEmpty() && value.getValue().get(0) instanceof DynamicStruct; + if (arrayOfBytes || arrayOfString) { + long offset = 0; + for (int i = 0; i < value.getValue().size(); i++) { + if (i == 0) { + offset = value.getValue().size() * MAX_BYTE_LENGTH; + } else { + int bytesLength = + arrayOfBytes + ? ((byte[]) value.getValue().get(i - 1).getValue()).length + : ((String) value.getValue().get(i - 1).getValue()).length(); + int numberOfWords = (bytesLength + MAX_BYTE_LENGTH - 1) / MAX_BYTE_LENGTH; + int totalBytesLength = numberOfWords * MAX_BYTE_LENGTH; + offset += totalBytesLength + MAX_BYTE_LENGTH; } - return result.toString(); + result.append( + Numeric.toHexStringNoPrefix( + Numeric.toBytesPadded(new BigInteger(Long.toString(offset)), MAX_BYTE_LENGTH))); + } + } else if (arrayOfDynamicStructs) { + result.append(encodeStructsArraysOffsets(value)); } + return result.toString(); + } - /** - * Encodes arrays of structs elements offsets. To be used when encoding a dynamic array or a - * static array containing dynamic structs, - * - * @param value DynamicArray or StaticArray containing dynamic structs - * @return encoded array offset - */ - private static String encodeStructsArraysOffsets(Array value) { - StringBuilder result = new StringBuilder(); - long offset = value.getValue().size(); - List tailsEncoding = - value.getValue().stream().map(TypeEncoder::encode).collect(Collectors.toList()); - for (int i = 0; i < value.getValue().size(); i++) { - if (i == 0) { - offset = offset * MAX_BYTE_LENGTH; - } else { - offset += tailsEncoding.get(i - 1).length() / 2; - } - result.append( - Numeric.toHexStringNoPrefix( - Numeric.toBytesPadded( - new BigInteger(Long.toString(offset)), MAX_BYTE_LENGTH))); - } - return result.toString(); + /** + * Encodes arrays of structs elements offsets. To be used when encoding a dynamic array or a + * static array containing dynamic structs, + * + * @param value DynamicArray or StaticArray containing dynamic structs + * @return encoded array offset + */ + private static String encodeStructsArraysOffsets(Array value) { + StringBuilder result = new StringBuilder(); + long offset = value.getValue().size(); + List tailsEncoding = + value.getValue().stream().map(TypeEncoder::encode).collect(Collectors.toList()); + for (int i = 0; i < value.getValue().size(); i++) { + if (i == 0) { + offset = offset * MAX_BYTE_LENGTH; + } else { + offset += tailsEncoding.get(i - 1).length() / 2; + } + result.append( + Numeric.toHexStringNoPrefix( + Numeric.toBytesPadded(new BigInteger(Long.toString(offset)), MAX_BYTE_LENGTH))); } + return result.toString(); + } - /** - * Checks if the received array doesn't contain any element that can make the array unsupported - * for abi.encodePacked - * - * @param value Array to which the abi.encodePacked should be applied - * @param Types of elements from the array - * @return if the encodePacked is supported for the given array - */ - private static boolean isSupportingEncodedPacked(Array value) { - if (Utf8String.class.isAssignableFrom(value.getComponentType()) - || DynamicStruct.class.isAssignableFrom(value.getComponentType()) - || DynamicArray.class.isAssignableFrom(value.getComponentType()) - || StaticStruct.class.isAssignableFrom(value.getComponentType()) - || FixedPointType.class.isAssignableFrom(value.getComponentType()) - || DynamicBytes.class.isAssignableFrom(value.getComponentType())) { - return false; - } - return true; + /** + * Checks if the received array doesn't contain any element that can make the array unsupported + * for abi.encodePacked + * + * @param value Array to which the abi.encodePacked should be applied + * @param Types of elements from the array + * @return if the encodePacked is supported for the given array + */ + private static boolean isSupportingEncodedPacked(Array value) { + if (Utf8String.class.isAssignableFrom(value.getComponentType()) + || DynamicStruct.class.isAssignableFrom(value.getComponentType()) + || DynamicArray.class.isAssignableFrom(value.getComponentType()) + || StaticStruct.class.isAssignableFrom(value.getComponentType()) + || FixedPointType.class.isAssignableFrom(value.getComponentType()) + || DynamicBytes.class.isAssignableFrom(value.getComponentType())) { + return false; } + return true; + } - private static String arrayEncodePacked(Array values) { - if (isSupportingEncodedPacked(values)) { - if (values.getValue().isEmpty()) { - return ""; - } - if (values instanceof DynamicArray) { - return encode(values).substring(64); - } else if (values instanceof StaticArray) { - return encode(values); - } - } - throw new UnsupportedOperationException( - "Type cannot be packed encoded: " + values.getClass()); + private static String arrayEncodePacked(Array values) { + if (isSupportingEncodedPacked(values)) { + if (values.getValue().isEmpty()) { + return ""; + } + if (values instanceof DynamicArray) { + return encode(values).substring(64); + } else if (values instanceof StaticArray) { + return encode(values); + } } + throw new UnsupportedOperationException("Type cannot be packed encoded: " + values.getClass()); + } } diff --git a/src/main/java/io/zksync/crypto/eip712/Eip712Domain.java b/src/main/java/io/zksync/crypto/eip712/Eip712Domain.java index 1aab38b..42c639d 100755 --- a/src/main/java/io/zksync/crypto/eip712/Eip712Domain.java +++ b/src/main/java/io/zksync/crypto/eip712/Eip712Domain.java @@ -1,66 +1,71 @@ package io.zksync.crypto.eip712; +import io.zksync.protocol.core.ZkSyncNetwork; import java.util.ArrayList; import java.util.List; - +import lombok.AllArgsConstructor; +import lombok.Data; import org.apache.commons.lang3.tuple.Pair; import org.web3j.abi.datatypes.Address; import org.web3j.abi.datatypes.Type; import org.web3j.abi.datatypes.Utf8String; import org.web3j.abi.datatypes.generated.Uint256; -import io.zksync.protocol.core.ZkSyncNetwork; -import lombok.AllArgsConstructor; -import lombok.Data; - @Data @AllArgsConstructor public class Eip712Domain implements Structurable { - public static final String NAME = "zkSync"; - public static final String VERSION = "2"; - - public static Eip712Domain defaultDomain(ZkSyncNetwork chainId) { - return new Eip712Domain(new Utf8String(NAME), new Utf8String(VERSION), new Uint256(chainId.getChainId()), null); - } - - public static Eip712Domain defaultDomain(Long chainId) { - return new Eip712Domain(new Utf8String(NAME), new Utf8String(VERSION), new Uint256(chainId), null); - } - - public Eip712Domain(String name, String version, Long chainId) { - this(new Utf8String(name), new Utf8String(version), new Uint256(chainId), null); - } - - public Eip712Domain(String name, String version, ZkSyncNetwork chainId, String address) { - this(new Utf8String(name), new Utf8String(version), new Uint256(chainId.getChainId()), new Address(address)); - } - - public Eip712Domain(String name, String version, Long chainId, String address) { - this(new Utf8String(name), new Utf8String(version), new Uint256(chainId), new Address(address)); - } - - private Utf8String name; - - private Utf8String version; - - private Uint256 chainId; - - private Address verifyingContract; - - @Override - public String getTypeName() { - return "EIP712Domain"; - } - - @Override - public List>> eip712types() { - return new ArrayList>>() {{ - add(Pair.of("name", name)); - add(Pair.of("version", version)); - add(Pair.of("chainId", chainId)); - if (verifyingContract != null) add(Pair.of("verifyingContract", verifyingContract)); - }}; - } - + public static final String NAME = "zkSync"; + public static final String VERSION = "2"; + + public static Eip712Domain defaultDomain(ZkSyncNetwork chainId) { + return new Eip712Domain( + new Utf8String(NAME), new Utf8String(VERSION), new Uint256(chainId.getChainId()), null); + } + + public static Eip712Domain defaultDomain(Long chainId) { + return new Eip712Domain( + new Utf8String(NAME), new Utf8String(VERSION), new Uint256(chainId), null); + } + + public Eip712Domain(String name, String version, Long chainId) { + this(new Utf8String(name), new Utf8String(version), new Uint256(chainId), null); + } + + public Eip712Domain(String name, String version, ZkSyncNetwork chainId, String address) { + this( + new Utf8String(name), + new Utf8String(version), + new Uint256(chainId.getChainId()), + new Address(address)); + } + + public Eip712Domain(String name, String version, Long chainId, String address) { + this(new Utf8String(name), new Utf8String(version), new Uint256(chainId), new Address(address)); + } + + private Utf8String name; + + private Utf8String version; + + private Uint256 chainId; + + private Address verifyingContract; + + @Override + public String getTypeName() { + return "EIP712Domain"; + } + + @Override + public List>> eip712types() { + return new ArrayList>>() { + { + add(Pair.of("name", name)); + add(Pair.of("version", version)); + add(Pair.of("chainId", chainId)); + if (verifyingContract != null) add(Pair.of("verifyingContract", verifyingContract)); + } + }; + } } diff --git a/src/main/java/io/zksync/crypto/eip712/Eip712Encoder.java b/src/main/java/io/zksync/crypto/eip712/Eip712Encoder.java index 2b9a48c..51241b2 100755 --- a/src/main/java/io/zksync/crypto/eip712/Eip712Encoder.java +++ b/src/main/java/io/zksync/crypto/eip712/Eip712Encoder.java @@ -1,95 +1,96 @@ package io.zksync.crypto.eip712; +import io.zksync.crypto.signer.EthSigner; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.util.List; import java.util.Set; import java.util.TreeSet; - import org.apache.commons.lang3.tuple.Pair; import org.web3j.abi.datatypes.*; import org.web3j.abi.datatypes.generated.Bytes32; import org.web3j.crypto.Hash; import org.web3j.utils.Numeric; -import io.zksync.crypto.signer.EthSigner; - public class Eip712Encoder { - public static Bytes32 encodeValue(Type value) { - if (value instanceof Utf8String) { - Utf8String s = (Utf8String) value; - return new Bytes32(Hash.sha3(s.getValue().getBytes())); - } else if (value instanceof Bytes32) { - return (Bytes32) value; - } else if (value instanceof NumericType) { - NumericType nt = (NumericType) value; - return new Bytes32(Numeric.toBytesPadded(nt.getValue(), 32)); - } else if (value instanceof DynamicArray) { - List> members = ((DynamicArray>) value).getValue(); - ByteBuffer bytes = ByteBuffer.allocate(members.size() * 32); - members.stream().map(Eip712Encoder::encodeValue).forEach(bytes32 -> bytes.put(bytes32.getValue())); - return new Bytes32(Hash.sha3(bytes.array())); - } else if (value instanceof BytesType) { - BytesType bt = (BytesType) value; - byte[] bytes = Hash.sha3(bt.getValue()); - return new Bytes32(bytes); - } else if (value instanceof Address) { - Address address = (Address) value; - byte[] bytes = Numeric.hexStringToByteArray(address.getValue()); - byte[] result = new byte[32]; - System.arraycopy(bytes, 0, result, 12, 20); - return new Bytes32(result); - } else if (value instanceof Eip712Struct) { - Eip712Struct struct = (Eip712Struct) value; - byte[] typeHash = typeHash(struct); - List>> members = struct.getValue().eip712types(); - ByteBuffer bytes = ByteBuffer.allocate((members.size() + 1) * 32); - bytes.put(typeHash); - for (Pair> member : members) { - Bytes32 result = encodeValue(member.getValue()); - bytes.put(result.getValue()); - } - return new Bytes32(Hash.sha3(bytes.array())); - } else { - throw new IllegalArgumentException(String.format("Unsupported ethereum type: \"%s\"", value.getTypeAsString())); - } + public static Bytes32 encodeValue(Type value) { + if (value instanceof Utf8String) { + Utf8String s = (Utf8String) value; + return new Bytes32(Hash.sha3(s.getValue().getBytes())); + } else if (value instanceof Bytes32) { + return (Bytes32) value; + } else if (value instanceof NumericType) { + NumericType nt = (NumericType) value; + return new Bytes32(Numeric.toBytesPadded(nt.getValue(), 32)); + } else if (value instanceof DynamicArray) { + List> members = ((DynamicArray>) value).getValue(); + ByteBuffer bytes = ByteBuffer.allocate(members.size() * 32); + members.stream() + .map(Eip712Encoder::encodeValue) + .forEach(bytes32 -> bytes.put(bytes32.getValue())); + return new Bytes32(Hash.sha3(bytes.array())); + } else if (value instanceof BytesType) { + BytesType bt = (BytesType) value; + byte[] bytes = Hash.sha3(bt.getValue()); + return new Bytes32(bytes); + } else if (value instanceof Address) { + Address address = (Address) value; + byte[] bytes = Numeric.hexStringToByteArray(address.getValue()); + byte[] result = new byte[32]; + System.arraycopy(bytes, 0, result, 12, 20); + return new Bytes32(result); + } else if (value instanceof Eip712Struct) { + Eip712Struct struct = (Eip712Struct) value; + byte[] typeHash = typeHash(struct); + List>> members = struct.getValue().eip712types(); + ByteBuffer bytes = ByteBuffer.allocate((members.size() + 1) * 32); + bytes.put(typeHash); + for (Pair> member : members) { + Bytes32 result = encodeValue(member.getValue()); + bytes.put(result.getValue()); + } + return new Bytes32(Hash.sha3(bytes.array())); + } else { + throw new IllegalArgumentException( + String.format("Unsupported ethereum type: \"%s\"", value.getTypeAsString())); } + } - public static String encodeType(Eip712Struct structure) { - StringBuilder sb = new StringBuilder(structure.encodeType()); - dependencies(structure).forEach(value -> sb.append(value.encodeType())); + public static String encodeType(Eip712Struct structure) { + StringBuilder sb = new StringBuilder(structure.encodeType()); + dependencies(structure).forEach(value -> sb.append(value.encodeType())); - return sb.toString(); - } + return sb.toString(); + } - public static byte[] typeHash(Eip712Struct structure) { - return Hash.sha3(encodeType(structure).getBytes()); - } + public static byte[] typeHash(Eip712Struct structure) { + return Hash.sha3(encodeType(structure).getBytes()); + } - public static Set dependencies(Eip712Struct structure) { - final TreeSet result = new TreeSet<>(); - for (Pair> value : structure.getValue().eip712types()) { - if (value.getValue() instanceof Eip712Struct) { - result.add((Eip712Struct) value.getValue()); - } - } - - return result; + public static Set dependencies(Eip712Struct structure) { + final TreeSet result = new TreeSet<>(); + for (Pair> value : structure.getValue().eip712types()) { + if (value.getValue() instanceof Eip712Struct) { + result.add((Eip712Struct) value.getValue()); + } } - public static byte[] typedDataToSignedBytes(Eip712Domain domain, S typedData) { - final ByteArrayOutputStream output = new ByteArrayOutputStream(); + return result; + } - try { - output.write(EthSigner.MESSAGE_EIP712_PREFIX.getBytes()); - output.write(Eip712Encoder.encodeValue(domain.intoEip712Struct()).getValue()); - output.write(Eip712Encoder.encodeValue(typedData.intoEip712Struct()).getValue()); - } catch (IOException e) { - throw new IllegalStateException("Error when creating ETH signature", e); - } + public static byte[] typedDataToSignedBytes( + Eip712Domain domain, S typedData) { + final ByteArrayOutputStream output = new ByteArrayOutputStream(); - return Hash.sha3(output.toByteArray()); + try { + output.write(EthSigner.MESSAGE_EIP712_PREFIX.getBytes()); + output.write(Eip712Encoder.encodeValue(domain.intoEip712Struct()).getValue()); + output.write(Eip712Encoder.encodeValue(typedData.intoEip712Struct()).getValue()); + } catch (IOException e) { + throw new IllegalStateException("Error when creating ETH signature", e); } + return Hash.sha3(output.toByteArray()); + } } diff --git a/src/main/java/io/zksync/crypto/eip712/Eip712Struct.java b/src/main/java/io/zksync/crypto/eip712/Eip712Struct.java index 6a2e174..5a59a1b 100755 --- a/src/main/java/io/zksync/crypto/eip712/Eip712Struct.java +++ b/src/main/java/io/zksync/crypto/eip712/Eip712Struct.java @@ -1,36 +1,35 @@ package io.zksync.crypto.eip712; import java.util.stream.Collectors; - -import org.web3j.abi.datatypes.Type; - import lombok.AllArgsConstructor; +import org.web3j.abi.datatypes.Type; @AllArgsConstructor public class Eip712Struct implements Type, Comparable { - private Structurable structure; - - @Override - public Structurable getValue() { - return structure; - } - - @Override - public String getTypeAsString() { - return structure.getTypeName(); - } - - @Override - public int compareTo(Eip712Struct o) { - return this.getTypeAsString().compareTo(o.getTypeAsString()); - } - - public String encodeType() { - return structure.getTypeName() + - "(" + - structure.eip712types().stream().map((entry) -> entry.getValue().getTypeAsString() + " " + entry.getKey()).collect(Collectors.joining(",")) + - ")"; - } - + private Structurable structure; + + @Override + public Structurable getValue() { + return structure; + } + + @Override + public String getTypeAsString() { + return structure.getTypeName(); + } + + @Override + public int compareTo(Eip712Struct o) { + return this.getTypeAsString().compareTo(o.getTypeAsString()); + } + + public String encodeType() { + return structure.getTypeName() + + "(" + + structure.eip712types().stream() + .map((entry) -> entry.getValue().getTypeAsString() + " " + entry.getKey()) + .collect(Collectors.joining(",")) + + ")"; + } } diff --git a/src/main/java/io/zksync/crypto/eip712/Structurable.java b/src/main/java/io/zksync/crypto/eip712/Structurable.java index 8cf6c02..0bb4c3d 100755 --- a/src/main/java/io/zksync/crypto/eip712/Structurable.java +++ b/src/main/java/io/zksync/crypto/eip712/Structurable.java @@ -1,18 +1,16 @@ package io.zksync.crypto.eip712; import java.util.List; - import org.apache.commons.lang3.tuple.Pair; import org.web3j.abi.datatypes.Type; public interface Structurable { - - String getTypeName(); - List>> eip712types(); + String getTypeName(); - default Eip712Struct intoEip712Struct() { - return new Eip712Struct(this); - } + List>> eip712types(); + default Eip712Struct intoEip712Struct() { + return new Eip712Struct(this); + } } diff --git a/src/main/java/io/zksync/crypto/signer/EthSigner.java b/src/main/java/io/zksync/crypto/signer/EthSigner.java index 46207bf..6c8f02d 100755 --- a/src/main/java/io/zksync/crypto/signer/EthSigner.java +++ b/src/main/java/io/zksync/crypto/signer/EthSigner.java @@ -1,102 +1,103 @@ package io.zksync.crypto.signer; +import io.zksync.crypto.eip712.Eip712Domain; +import io.zksync.crypto.eip712.Structurable; import java.util.concurrent.CompletableFuture; - import org.web3j.crypto.Hash; import org.web3j.utils.Numeric; -import io.zksync.crypto.eip712.Eip712Domain; -import io.zksync.crypto.eip712.Structurable; - public interface EthSigner { - String MESSAGE_PREFIX = "\u0019Ethereum Signed Message:\n"; - String MESSAGE_EIP712_PREFIX = "\u0019\u0001"; - byte[] EIP1271_SUCCESS_VALUE = Numeric.hexStringToByteArray("0x1626ba7e"); - - /** - * Get wallet address - * - * @return Address in hex string - */ - String getAddress(); - - /** - * Get EIP712 domain - * - * @return Eip712 domain - */ - CompletableFuture getDomain(); - - /** - * Signs typed struct using ethereum private key by EIP-712 signature standard. - * - * @param - EIP712 structure - * @param domain - EIP712 domain - * @param typedData - Object implementing EIP712 structure standard - * @return Signature object - */ - CompletableFuture signTypedData(Eip712Domain domain, S typedData); - - /** - * Verify typed EIP-712 struct standard. - * - * @param - EIP712 structure - * @param domain - EIP712 domain - * @param typedData - Object implementing EIP712 structure standard - * @param signature - Signature of the EIP-712 structures - * @return true on verification success - */ - CompletableFuture verifyTypedData(Eip712Domain domain, S typedData, String signature); - - /** - * Sign raw message - * - * @param message - Message to sign - * @return Signature object - */ - CompletableFuture signMessage(byte[] message); - - /** - * Sign raw message - * - * @param message - Message to sign - * @param addPrefix - If true then add secure prefix (EIP-712) - * @return Signature object - */ - CompletableFuture signMessage(byte[] message, boolean addPrefix); - - /** - * Verify signature with raw message - * - * @param signature - Signature object - * @param message - Message to verify - * @return true on verification success - */ - CompletableFuture verifySignature(String signature, byte[] message); - - /** - * Verify signature with raw message - * - * @param signature - Signature object - * @param message - Message to verify - * @param prefixed - If true then add secure prefix (EIP-712) - * @return true on verification success - */ - CompletableFuture verifySignature(String signature, byte[] message, boolean prefixed); - - static byte[] getEthereumMessagePrefix(int messageLength) { - return MESSAGE_PREFIX.concat(String.valueOf(messageLength)).getBytes(); - } - - static byte[] getEthereumMessageHash(byte[] message) { - byte[] prefix = getEthereumMessagePrefix(message.length); - - byte[] result = new byte[prefix.length + message.length]; - System.arraycopy(prefix, 0, result, 0, prefix.length); - System.arraycopy(message, 0, result, prefix.length, message.length); - - return Hash.sha3(result); - } - + String MESSAGE_PREFIX = "\u0019Ethereum Signed Message:\n"; + String MESSAGE_EIP712_PREFIX = "\u0019\u0001"; + byte[] EIP1271_SUCCESS_VALUE = Numeric.hexStringToByteArray("0x1626ba7e"); + + /** + * Get wallet address + * + * @return Address in hex string + */ + String getAddress(); + + /** + * Get EIP712 domain + * + * @return Eip712 domain + */ + CompletableFuture getDomain(); + + /** + * Signs typed struct using ethereum private key by EIP-712 signature standard. + * + * @param - EIP712 structure + * @param domain - EIP712 domain + * @param typedData - Object implementing EIP712 structure standard + * @return Signature object + */ + CompletableFuture signTypedData( + Eip712Domain domain, S typedData); + + /** + * Verify typed EIP-712 struct standard. + * + * @param - EIP712 structure + * @param domain - EIP712 domain + * @param typedData - Object implementing EIP712 structure standard + * @param signature - Signature of the EIP-712 structures + * @return true on verification success + */ + CompletableFuture verifyTypedData( + Eip712Domain domain, S typedData, String signature); + + /** + * Sign raw message + * + * @param message - Message to sign + * @return Signature object + */ + CompletableFuture signMessage(byte[] message); + + /** + * Sign raw message + * + * @param message - Message to sign + * @param addPrefix - If true then add secure prefix (EIP-712) + * @return Signature object + */ + CompletableFuture signMessage(byte[] message, boolean addPrefix); + + /** + * Verify signature with raw message + * + * @param signature - Signature object + * @param message - Message to verify + * @return true on verification success + */ + CompletableFuture verifySignature(String signature, byte[] message); + + /** + * Verify signature with raw message + * + * @param signature - Signature object + * @param message - Message to verify + * @param prefixed - If true then add secure prefix (EIP-712) + * @return true on verification success + */ + CompletableFuture verifySignature(String signature, byte[] message, boolean prefixed); + + static byte[] getEthereumMessagePrefix(int messageLength) { + return MESSAGE_PREFIX.concat(String.valueOf(messageLength)).getBytes(); + } + + static byte[] getEthereumMessageHash(byte[] message) { + byte[] prefix = getEthereumMessagePrefix(message.length); + + byte[] result = new byte[prefix.length + message.length]; + System.arraycopy(prefix, 0, result, 0, prefix.length); + System.arraycopy(message, 0, result, prefix.length, message.length); + + return Hash.sha3(result); + } } diff --git a/src/main/java/io/zksync/crypto/signer/PrivateKeyEthSigner.java b/src/main/java/io/zksync/crypto/signer/PrivateKeyEthSigner.java index 534dca3..396446b 100755 --- a/src/main/java/io/zksync/crypto/signer/PrivateKeyEthSigner.java +++ b/src/main/java/io/zksync/crypto/signer/PrivateKeyEthSigner.java @@ -1,11 +1,14 @@ package io.zksync.crypto.signer; +import io.zksync.crypto.eip712.Eip712Domain; +import io.zksync.crypto.eip712.Eip712Encoder; +import io.zksync.crypto.eip712.Structurable; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.math.BigInteger; import java.util.Arrays; import java.util.concurrent.CompletableFuture; - +import lombok.AllArgsConstructor; import org.web3j.crypto.Bip32ECKeyPair; import org.web3j.crypto.Credentials; import org.web3j.crypto.ECDSASignature; @@ -14,125 +17,129 @@ import org.web3j.crypto.Sign; import org.web3j.utils.Numeric; -import io.zksync.crypto.eip712.Eip712Domain; -import io.zksync.crypto.eip712.Eip712Encoder; -import io.zksync.crypto.eip712.Structurable; - -import lombok.AllArgsConstructor; - @AllArgsConstructor public class PrivateKeyEthSigner implements EthSigner { - private Credentials credentials; - private Eip712Domain domain; - - public PrivateKeyEthSigner(Credentials credentials, long chainId) { - this.credentials = credentials; - this.domain = Eip712Domain.defaultDomain(chainId); - } - - public static PrivateKeyEthSigner fromMnemonic(String mnemonic, long chainId) { - Credentials credentials = generateCredentialsFromMnemonic(mnemonic, 0); - return new PrivateKeyEthSigner(credentials, chainId); - } - - public static PrivateKeyEthSigner fromMnemonic(String mnemonic, int accountIndex, long chainId) { - Credentials credentials = generateCredentialsFromMnemonic(mnemonic, accountIndex); - return new PrivateKeyEthSigner(credentials, chainId); - } - - @Override - public String getAddress() { - return credentials.getAddress(); - } - - @Override - public CompletableFuture getDomain() { - return CompletableFuture.completedFuture(domain); - } - - @Override - public CompletableFuture signTypedData(Eip712Domain domain, S typedData) { - return this.signMessage(Eip712Encoder.typedDataToSignedBytes(domain, typedData), false); - } - - @Override - public CompletableFuture verifyTypedData(Eip712Domain domain, S typedData, - String signature) { - return this.verifySignature(signature, Eip712Encoder.typedDataToSignedBytes(domain, typedData), false); + private Credentials credentials; + private Eip712Domain domain; + + public PrivateKeyEthSigner(Credentials credentials, long chainId) { + this.credentials = credentials; + this.domain = Eip712Domain.defaultDomain(chainId); + } + + public static PrivateKeyEthSigner fromMnemonic(String mnemonic, long chainId) { + Credentials credentials = generateCredentialsFromMnemonic(mnemonic, 0); + return new PrivateKeyEthSigner(credentials, chainId); + } + + public static PrivateKeyEthSigner fromMnemonic(String mnemonic, int accountIndex, long chainId) { + Credentials credentials = generateCredentialsFromMnemonic(mnemonic, accountIndex); + return new PrivateKeyEthSigner(credentials, chainId); + } + + @Override + public String getAddress() { + return credentials.getAddress(); + } + + @Override + public CompletableFuture getDomain() { + return CompletableFuture.completedFuture(domain); + } + + @Override + public CompletableFuture signTypedData( + Eip712Domain domain, S typedData) { + return this.signMessage(Eip712Encoder.typedDataToSignedBytes(domain, typedData), false); + } + + @Override + public CompletableFuture verifyTypedData( + Eip712Domain domain, S typedData, String signature) { + return this.verifySignature( + signature, Eip712Encoder.typedDataToSignedBytes(domain, typedData), false); + } + + @Override + public CompletableFuture signMessage(byte[] message) { + return this.signMessage(message, true); + } + + @Override + public CompletableFuture signMessage(byte[] message, boolean addPrefix) { + Sign.SignatureData sig = + addPrefix + ? Sign.signPrefixedMessage(message, credentials.getEcKeyPair()) + : Sign.signMessage(message, credentials.getEcKeyPair(), false); + + final ByteArrayOutputStream output = new ByteArrayOutputStream(); + + try { + output.write(sig.getR()); + output.write(sig.getS()); + output.write(sig.getV()); + } catch (IOException e) { + throw new IllegalStateException("Error when creating ETH signature", e); } - @Override - public CompletableFuture signMessage(byte[] message) { - return this.signMessage(message, true); - } - - @Override - public CompletableFuture signMessage(byte[] message, boolean addPrefix) { - Sign.SignatureData sig = addPrefix ? Sign.signPrefixedMessage(message, credentials.getEcKeyPair()) - : Sign.signMessage(message, credentials.getEcKeyPair(), false); + final String signature = Numeric.toHexString(output.toByteArray()); - final ByteArrayOutputStream output = new ByteArrayOutputStream(); + return CompletableFuture.completedFuture(signature); + } - try { - output.write(sig.getR()); - output.write(sig.getS()); - output.write(sig.getV()); - } catch (IOException e) { - throw new IllegalStateException("Error when creating ETH signature", e); - } + @Override + public CompletableFuture verifySignature(String signature, byte[] message) { + return this.verifySignature(signature, message, true); + } - final String signature = Numeric.toHexString(output.toByteArray()); + @Override + public CompletableFuture verifySignature( + String signature, byte[] message, boolean prefixed) { + byte[] messageHash = prefixed ? EthSigner.getEthereumMessageHash(message) : message; - return CompletableFuture.completedFuture(signature); - } - - @Override - public CompletableFuture verifySignature(String signature, byte[] message) { - return this.verifySignature(signature, message, true); - } - - @Override - public CompletableFuture verifySignature(String signature, byte[] message, boolean prefixed) { - byte[] messageHash = prefixed ? EthSigner.getEthereumMessageHash(message) : message; - - String address = ecrecover(Numeric.hexStringToByteArray(signature), messageHash); - - return CompletableFuture.completedFuture(address.equalsIgnoreCase(this.getAddress())); - } - - private static String ecrecover(byte[] signature, byte[] hash) { - ECDSASignature sig = new ECDSASignature( - Numeric.toBigInt(Arrays.copyOfRange(signature, 0, 32)), - Numeric.toBigInt(Arrays.copyOfRange(signature, 32, 64))); - - byte v = signature[64]; - - int recId; - if (v >= 3) { - recId = v - 27; - } else { - recId = v; - } - - BigInteger recovered = Sign.recoverFromSignature(recId, sig, hash); - return "0x" + Keys.getAddress(recovered); - } + String address = ecrecover(Numeric.hexStringToByteArray(signature), messageHash); - private static Credentials generateCredentialsFromMnemonic(String mnemonic, int accountIndex) { - // m/44'/60'/0'/0 derivation path - int[] derivationPath = { 44 | Bip32ECKeyPair.HARDENED_BIT, 60 | Bip32ECKeyPair.HARDENED_BIT, - 0 | Bip32ECKeyPair.HARDENED_BIT, 0, accountIndex }; + return CompletableFuture.completedFuture(address.equalsIgnoreCase(this.getAddress())); + } - // Generate a BIP32 master keypair from the mnemonic phrase - Bip32ECKeyPair masterKeypair = Bip32ECKeyPair.generateKeyPair( - MnemonicUtils.generateSeed(mnemonic, "")); + private static String ecrecover(byte[] signature, byte[] hash) { + ECDSASignature sig = + new ECDSASignature( + Numeric.toBigInt(Arrays.copyOfRange(signature, 0, 32)), + Numeric.toBigInt(Arrays.copyOfRange(signature, 32, 64))); - // Derive the keypair using the derivation path - Bip32ECKeyPair derivedKeyPair = Bip32ECKeyPair.deriveKeyPair(masterKeypair, derivationPath); + byte v = signature[64]; - // Load the wallet for the derived keypair - return Credentials.create(derivedKeyPair); + int recId; + if (v >= 3) { + recId = v - 27; + } else { + recId = v; } + BigInteger recovered = Sign.recoverFromSignature(recId, sig, hash); + return "0x" + Keys.getAddress(recovered); + } + + private static Credentials generateCredentialsFromMnemonic(String mnemonic, int accountIndex) { + // m/44'/60'/0'/0 derivation path + int[] derivationPath = { + 44 | Bip32ECKeyPair.HARDENED_BIT, + 60 | Bip32ECKeyPair.HARDENED_BIT, + 0 | Bip32ECKeyPair.HARDENED_BIT, + 0, + accountIndex + }; + + // Generate a BIP32 master keypair from the mnemonic phrase + Bip32ECKeyPair masterKeypair = + Bip32ECKeyPair.generateKeyPair(MnemonicUtils.generateSeed(mnemonic, "")); + + // Derive the keypair using the derivation path + Bip32ECKeyPair derivedKeyPair = Bip32ECKeyPair.deriveKeyPair(masterKeypair, derivationPath); + + // Load the wallet for the derived keypair + return Credentials.create(derivedKeyPair); + } } diff --git a/src/main/java/io/zksync/methods/request/Eip712Meta.java b/src/main/java/io/zksync/methods/request/Eip712Meta.java index 1279078..0019010 100644 --- a/src/main/java/io/zksync/methods/request/Eip712Meta.java +++ b/src/main/java/io/zksync/methods/request/Eip712Meta.java @@ -4,56 +4,53 @@ import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import io.zksync.utils.ByteArraySerializer; +import java.math.BigInteger; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.NoArgsConstructor; import lombok.Setter; import org.web3j.utils.Numeric; -import java.math.BigInteger; - @NoArgsConstructor @AllArgsConstructor @JsonInclude(JsonInclude.Include.NON_NULL) @Setter @Builder public class Eip712Meta { - private BigInteger gasPerPubdata; - private byte[] customSignature; - private byte[][] factoryDeps; - - private PaymasterParams paymasterParams; - - - public String getGasPerPubdata() { - return convert(gasPerPubdata); - } - - @JsonIgnore - public BigInteger getGasPerPubdataNumber() { - return gasPerPubdata; + private BigInteger gasPerPubdata; + private byte[] customSignature; + private byte[][] factoryDeps; + + private PaymasterParams paymasterParams; + + public String getGasPerPubdata() { + return convert(gasPerPubdata); + } + + @JsonIgnore + public BigInteger getGasPerPubdataNumber() { + return gasPerPubdata; + } + + @JsonSerialize(using = ByteArraySerializer.class) + public byte[] getCustomSignature() { + return customSignature; + } + + @JsonSerialize(using = io.zksync.utils.ByteArray2Serializer.class) + public byte[][] getFactoryDeps() { + return factoryDeps; + } + + public PaymasterParams getPaymasterParams() { + return paymasterParams; + } + + private static String convert(BigInteger value) { + if (value != null) { + return Numeric.encodeQuantity(value); + } else { + return null; // we don't want the field to be encoded if not present } - - @JsonSerialize(using = ByteArraySerializer.class) - public byte[] getCustomSignature() { - return customSignature; - } - - @JsonSerialize(using = io.zksync.utils.ByteArray2Serializer.class) - public byte[][] getFactoryDeps() { - return factoryDeps; - } - - public PaymasterParams getPaymasterParams() { - return paymasterParams; - } - - private static String convert(BigInteger value) { - if (value != null) { - return Numeric.encodeQuantity(value); - } else { - return null; // we don't want the field to be encoded if not present - } - } - + } } diff --git a/src/main/java/io/zksync/methods/request/PaymasterParams.java b/src/main/java/io/zksync/methods/request/PaymasterParams.java index 05a1254..b471e1a 100644 --- a/src/main/java/io/zksync/methods/request/PaymasterParams.java +++ b/src/main/java/io/zksync/methods/request/PaymasterParams.java @@ -12,15 +12,15 @@ @Setter @JsonInclude(JsonInclude.Include.NON_NULL) public class PaymasterParams { - private String paymaster; - private byte[] paymasterInput; + private String paymaster; + private byte[] paymasterInput; - public String getPaymaster() { - return paymaster; - } + public String getPaymaster() { + return paymaster; + } - @JsonSerialize(using = ByteArraySerializer.class) - public byte[] getPaymasterInput() { - return paymasterInput; - } + @JsonSerialize(using = ByteArraySerializer.class) + public byte[] getPaymasterInput() { + return paymasterInput; + } } diff --git a/src/main/java/io/zksync/methods/request/Transaction.java b/src/main/java/io/zksync/methods/request/Transaction.java index 669d491..707f67b 100644 --- a/src/main/java/io/zksync/methods/request/Transaction.java +++ b/src/main/java/io/zksync/methods/request/Transaction.java @@ -6,14 +6,13 @@ import io.zksync.utils.AccountAbstractionVersion; import io.zksync.utils.ContractDeployer; import io.zksync.utils.ZkSyncAddresses; +import java.math.BigInteger; +import java.util.List; import lombok.AllArgsConstructor; import org.web3j.abi.FunctionEncoder; import org.web3j.protocol.core.methods.response.AccessListObject; import org.web3j.utils.Numeric; -import java.math.BigInteger; -import java.util.List; - /** * Transaction request object used the below methods. * @@ -27,361 +26,414 @@ @JsonInclude(JsonInclude.Include.NON_NULL) public class Transaction { - private String from; - private String to; - private BigInteger gas; - private BigInteger gasPrice; - private BigInteger value; - private String data; - - private Long transactionType; - private AccessListObject accessList; - private Eip712Meta eip712Meta; - - public Transaction(String from, String to, BigInteger gas, BigInteger gasPrice, BigInteger value, String data, Eip712Meta eip712Meta) { - this.from = from; - this.to = to; - this.gas = gas; - this.gasPrice = gasPrice; - this.value = value; - this.data = data; - this.eip712Meta = eip712Meta; - - this.transactionType = (long) Transaction712.EIP_712_TX_TYPE; - } - - public static Transaction createEtherTransaction( - String from, - BigInteger gasPrice, - BigInteger gasLimit, - String to, - BigInteger value) { - - Eip712Meta meta = new Eip712Meta(BigInteger.valueOf(160000L), null, null, null); - return new Transaction(from, to, gasPrice, gasLimit, value, "0x", meta); - } - - public static Transaction create2ContractTransaction( - String from, - BigInteger gasPrice, - BigInteger gasLimit, - BigInteger value, - String bytecode - ) { - byte[] bytecodeBytes = Numeric.hexStringToByteArray(bytecode); - String calldata = FunctionEncoder.encode(ContractDeployer.encodeCreate2(bytecodeBytes)); - Eip712Meta meta = new Eip712Meta(BigInteger.valueOf(160000L), null, new byte[][] {bytecodeBytes}, null); - return new Transaction(from, ZkSyncAddresses.CONTRACT_DEPLOYER_ADDRESS, gasPrice, gasLimit, value, calldata, meta); - } - - public static Transaction create2ContractTransaction( - String from, - BigInteger gasPrice, - BigInteger gasLimit, - String bytecode - ) { - byte[] bytecodeBytes = Numeric.hexStringToByteArray(bytecode); - String calldata = FunctionEncoder.encode(ContractDeployer.encodeCreate2(bytecodeBytes)); - Eip712Meta meta = new Eip712Meta(BigInteger.valueOf(160000L), null, new byte[][] {bytecodeBytes}, null); - return new Transaction(from, ZkSyncAddresses.CONTRACT_DEPLOYER_ADDRESS, gasPrice, gasLimit, null, calldata, meta); - } - - public static Transaction create2ContractTransaction( - String from, - BigInteger gasPrice, - BigInteger gasLimit, - String bytecode, - String calldata - ) { - byte[] bytecodeBytes = Numeric.hexStringToByteArray(bytecode); - byte[] calldataBytes = Numeric.hexStringToByteArray(calldata); - String calldataCreate = FunctionEncoder.encode(ContractDeployer.encodeCreate2(bytecodeBytes, calldataBytes)); - Eip712Meta meta = new Eip712Meta(BigInteger.valueOf(160000L), null, new byte[][] {bytecodeBytes}, null); - return new Transaction(from, ZkSyncAddresses.CONTRACT_DEPLOYER_ADDRESS, gasPrice, gasLimit, null, calldataCreate, meta); - } - - public static Transaction create2ContractTransaction( - String from, - BigInteger gasPrice, - BigInteger gasLimit, - String bytecode, - String calldata, - byte[] salt - ) { - byte[] bytecodeBytes = Numeric.hexStringToByteArray(bytecode); - byte[] calldataBytes = Numeric.hexStringToByteArray(calldata); - String calldataCreate = FunctionEncoder.encode(ContractDeployer.encodeCreate2(bytecodeBytes, calldataBytes, salt)); - Eip712Meta meta = new Eip712Meta(BigInteger.valueOf(160000L), null, new byte[][] {bytecodeBytes}, null); - return new Transaction(from, ZkSyncAddresses.CONTRACT_DEPLOYER_ADDRESS, gasPrice, gasLimit, null, calldataCreate, meta); - } - - public static Transaction create2ContractTransaction( - String from, - BigInteger gasPrice, - BigInteger gasLimit, - String bytecode, - String calldata, - List deps - ) { - byte[] bytecodeBytes = Numeric.hexStringToByteArray(bytecode); - byte[][] factoryDeps = new byte[deps.size() + 1][]; - for (int i = 0; i < deps.size(); i ++) { - factoryDeps[i] = Numeric.hexStringToByteArray(deps.get(i)); - } - factoryDeps[deps.size()] = bytecodeBytes; - Eip712Meta meta = new Eip712Meta(BigInteger.valueOf(160000L), null, factoryDeps, null); - return new Transaction(from, ZkSyncAddresses.CONTRACT_DEPLOYER_ADDRESS, gasPrice, gasLimit, null, calldata, meta); - } - - public static Transaction create2ContractTransaction( - String from, - BigInteger gasPrice, - BigInteger gasLimit, - String bytecode, - List deps, - String calldata, - byte[] salt - ) { - byte[] bytecodeBytes = Numeric.hexStringToByteArray(bytecode); - byte[] calldataBytes = Numeric.hexStringToByteArray(calldata); - byte[][] factoryDeps = new byte[deps.size() + 1][]; - for (int i = 0; i < deps.size(); i ++) { - factoryDeps[i] = Numeric.hexStringToByteArray(deps.get(i)); - } - factoryDeps[deps.size()] = bytecodeBytes; - String calldataCreate = FunctionEncoder.encode(ContractDeployer.encodeCreate2(bytecodeBytes, calldataBytes, salt)); - Eip712Meta meta = new Eip712Meta(BigInteger.valueOf(160000L), null, factoryDeps, null); - return new Transaction(from, ZkSyncAddresses.CONTRACT_DEPLOYER_ADDRESS, gasPrice, gasLimit, null, calldataCreate, meta); - } - - public static Transaction create2ContractTransaction( - String from, - BigInteger gasPrice, - BigInteger gasLimit, - String bytecode, - String calldata, - String customSignature - ) { - byte[] bytecodeBytes = Numeric.hexStringToByteArray(bytecode); - byte[] calldataBytes = Numeric.hexStringToByteArray(calldata); - byte[] customSignatureBytes = Numeric.hexStringToByteArray(customSignature); - String calldataCreate = FunctionEncoder.encode(ContractDeployer.encodeCreate2(bytecodeBytes, calldataBytes)); - Eip712Meta meta = new Eip712Meta(BigInteger.valueOf(160000L), customSignatureBytes, new byte[][] {bytecodeBytes}, null); - return new Transaction(from, ZkSyncAddresses.CONTRACT_DEPLOYER_ADDRESS, gasPrice, gasLimit, null, calldataCreate, meta); - } - - public static Transaction create2ContractTransaction( - String from, - BigInteger gasPrice, - BigInteger gasLimit, - String bytecode, - String calldata, - String customSignature, - PaymasterParams paymasterParams - ) { - byte[] bytecodeBytes = Numeric.hexStringToByteArray(bytecode); - byte[] calldataBytes = Numeric.hexStringToByteArray(calldata); - byte[] customSignatureBytes = Numeric.hexStringToByteArray(customSignature); - String calldataCreate = FunctionEncoder.encode(ContractDeployer.encodeCreate2(bytecodeBytes, calldataBytes)); - Eip712Meta meta = new Eip712Meta(BigInteger.valueOf(160000L), customSignatureBytes, new byte[][] {bytecodeBytes}, paymasterParams); - return new Transaction(from, ZkSyncAddresses.CONTRACT_DEPLOYER_ADDRESS, gasPrice, gasLimit, null, calldataCreate, meta); - } - - public static Transaction create2AccountTransaction( - String from, - BigInteger gasPrice, - BigInteger gasLimit, - String bytecode - ) { - byte[] bytecodeBytes = Numeric.hexStringToByteArray(bytecode); - String calldata = FunctionEncoder.encode(ContractDeployer.encodeCreate2Account(bytecodeBytes)); - Eip712Meta meta = new Eip712Meta(BigInteger.valueOf(160000L), null, new byte[][] {bytecodeBytes}, null); - return new Transaction(from, ZkSyncAddresses.CONTRACT_DEPLOYER_ADDRESS, gasPrice, gasLimit, null, calldata, meta); - } - - public static Transaction create2AccountTransaction( - String from, - BigInteger gasPrice, - BigInteger gasLimit, - String bytecode, - String calldata - ) { - byte[] bytecodeBytes = Numeric.hexStringToByteArray(bytecode); - byte[] calldataBytes = Numeric.hexStringToByteArray(calldata); - String calldataCreate = FunctionEncoder.encode(ContractDeployer.encodeCreate2Account(bytecodeBytes, calldataBytes)); - Eip712Meta meta = new Eip712Meta(BigInteger.valueOf(160000L), null, new byte[][] {bytecodeBytes}, null); - return new Transaction(from, ZkSyncAddresses.CONTRACT_DEPLOYER_ADDRESS, gasPrice, gasLimit, null, calldataCreate, meta); - } - public static Transaction create2AccountTransaction( - String from, - BigInteger gasPrice, - BigInteger gasLimit, - String bytecode, - String calldata, - byte[] salt - ) { - byte[] bytecodeBytes = Numeric.hexStringToByteArray(bytecode); - byte[] calldataBytes = Numeric.hexStringToByteArray(calldata); - String calldataCreate = FunctionEncoder.encode(ContractDeployer.encodeCreate2Account(bytecodeBytes, calldataBytes, salt, AccountAbstractionVersion.Version1)); - Eip712Meta meta = new Eip712Meta(BigInteger.valueOf(160000L), null, new byte[][] {bytecodeBytes}, null); - return new Transaction(from, ZkSyncAddresses.CONTRACT_DEPLOYER_ADDRESS, gasPrice, gasLimit, null, calldataCreate, meta); - } - - - public static Transaction createContractTransaction( - String from, - BigInteger gasPrice, - BigInteger gasLimit, - BigInteger value, - String bytecode - ) { - byte[] bytecodeBytes = Numeric.hexStringToByteArray(bytecode); - String calldata = FunctionEncoder.encode(ContractDeployer.encodeCreate(bytecodeBytes)); - Eip712Meta meta = new Eip712Meta(BigInteger.valueOf(160000L), null, new byte[][] {bytecodeBytes}, null); - return new Transaction(from, ZkSyncAddresses.CONTRACT_DEPLOYER_ADDRESS, gasPrice, gasLimit, value, calldata, meta); - } - - public static Transaction createContractTransaction( - String from, - BigInteger gasPrice, - BigInteger gasLimit, - String bytecode - ) { - byte[] bytecodeBytes = Numeric.hexStringToByteArray(bytecode); - String calldata = FunctionEncoder.encode(ContractDeployer.encodeCreate(bytecodeBytes)); - Eip712Meta meta = new Eip712Meta(BigInteger.valueOf(160000L), null, new byte[][] {bytecodeBytes}, null); - return new Transaction(from, ZkSyncAddresses.CONTRACT_DEPLOYER_ADDRESS, gasPrice, gasLimit, null, calldata, meta); - } - - public static Transaction createContractTransaction( - String from, - BigInteger gasPrice, - BigInteger gasLimit, - String bytecode, - String calldata - ) { - byte[] bytecodeBytes = Numeric.hexStringToByteArray(bytecode); - byte[] calldataBytes = Numeric.hexStringToByteArray(calldata); - String calldataCreate = FunctionEncoder.encode(ContractDeployer.encodeCreate(bytecodeBytes, calldataBytes)); - Eip712Meta meta = new Eip712Meta(BigInteger.valueOf(160000L), null, new byte[][] {bytecodeBytes}, null); - return new Transaction(from, ZkSyncAddresses.CONTRACT_DEPLOYER_ADDRESS, gasPrice, gasLimit, null, calldataCreate, meta); - } - - public static Transaction createContractTransaction( - String from, - BigInteger gasPrice, - BigInteger gasLimit, - String bytecode, - List deps, - String calldata - ) { - byte[] bytecodeBytes = Numeric.hexStringToByteArray(bytecode); - byte[] calldataBytes = Numeric.hexStringToByteArray(calldata); - byte[][] factoryDeps = new byte[deps.size() + 1][]; - for (int i = 0; i < deps.size(); i ++) { - factoryDeps[i] = Numeric.hexStringToByteArray(deps.get(i)); - } - factoryDeps[deps.size()] = bytecodeBytes; - String calldataCreate = FunctionEncoder.encode(ContractDeployer.encodeCreate(bytecodeBytes, calldataBytes)); - Eip712Meta meta = new Eip712Meta(BigInteger.valueOf(160000L), null, factoryDeps, null); - return new Transaction(from, ZkSyncAddresses.CONTRACT_DEPLOYER_ADDRESS, gasPrice, gasLimit, null, calldataCreate, meta); - } - - public static Transaction createFunctionCallTransaction( - String from, - String to, - BigInteger gasPrice, - BigInteger gasLimit, - BigInteger value, - String data - ) { - Eip712Meta meta = new Eip712Meta(BigInteger.valueOf(160000L), null, null, null); - return new Transaction(from, to, gasPrice, gasLimit, value, data, meta); - } - - public static Transaction createFunctionCallTransaction( - String from, - String to, - BigInteger gasPrice, - BigInteger gasLimit, - String data - ) { - - Eip712Meta meta = new Eip712Meta(BigInteger.valueOf(160000L), null, null, null); - return new Transaction(from, to, gasPrice, gasLimit, null, data, meta); - } - - public static Transaction createFunctionCallTransaction( - String from, - String to, - BigInteger gasPrice, - BigInteger gasLimit, - BigInteger value, - String data, - String customSignature, - PaymasterParams paymasterParams - ) { - Eip712Meta meta = new Eip712Meta(BigInteger.valueOf(160000L), Numeric.hexStringToByteArray(customSignature), null, paymasterParams); - return new Transaction(from, to, gasPrice, gasLimit, value, data, meta); - } - - public String getFrom() { - return from; - } - - public String getTo() { - return to; - } - - public String getGas() { - return convert(gas); - } - - public String getGasPrice() { - return convert(gasPrice); - } - - public String getValue() { - return convert(value); - } - - @JsonIgnore - public BigInteger getGasNumber() { - return gas; - } - - @JsonIgnore - public BigInteger getGasPriceNumber() { - return gasPrice; - } - - @JsonIgnore - public BigInteger getValueNumber() { - return value; - } - - public String getData() { - return data; - } - - public String getTransactionType() { - return convert(BigInteger.valueOf(transactionType)); - } - - public AccessListObject getAccessList() { - return accessList; - } - - public Eip712Meta getEip712Meta() { - return eip712Meta; - } - - private static String convert(BigInteger value) { - if (value != null) { - return Numeric.encodeQuantity(value); - } else { - return null; // we don't want the field to be encoded if not present - } - } - + private String from; + private String to; + private BigInteger gas; + private BigInteger gasPrice; + private BigInteger value; + private String data; + + private Long transactionType; + private AccessListObject accessList; + private Eip712Meta eip712Meta; + + public Transaction( + String from, + String to, + BigInteger gas, + BigInteger gasPrice, + BigInteger value, + String data, + Eip712Meta eip712Meta) { + this.from = from; + this.to = to; + this.gas = gas; + this.gasPrice = gasPrice; + this.value = value; + this.data = data; + this.eip712Meta = eip712Meta; + + this.transactionType = (long) Transaction712.EIP_712_TX_TYPE; + } + + public static Transaction createEtherTransaction( + String from, BigInteger gasPrice, BigInteger gasLimit, String to, BigInteger value) { + + Eip712Meta meta = new Eip712Meta(BigInteger.valueOf(160000L), null, null, null); + return new Transaction(from, to, gasPrice, gasLimit, value, "0x", meta); + } + + public static Transaction create2ContractTransaction( + String from, BigInteger gasPrice, BigInteger gasLimit, BigInteger value, String bytecode) { + byte[] bytecodeBytes = Numeric.hexStringToByteArray(bytecode); + String calldata = FunctionEncoder.encode(ContractDeployer.encodeCreate2(bytecodeBytes)); + Eip712Meta meta = + new Eip712Meta(BigInteger.valueOf(160000L), null, new byte[][] {bytecodeBytes}, null); + return new Transaction( + from, ZkSyncAddresses.CONTRACT_DEPLOYER_ADDRESS, gasPrice, gasLimit, value, calldata, meta); + } + + public static Transaction create2ContractTransaction( + String from, BigInteger gasPrice, BigInteger gasLimit, String bytecode) { + byte[] bytecodeBytes = Numeric.hexStringToByteArray(bytecode); + String calldata = FunctionEncoder.encode(ContractDeployer.encodeCreate2(bytecodeBytes)); + Eip712Meta meta = + new Eip712Meta(BigInteger.valueOf(160000L), null, new byte[][] {bytecodeBytes}, null); + return new Transaction( + from, ZkSyncAddresses.CONTRACT_DEPLOYER_ADDRESS, gasPrice, gasLimit, null, calldata, meta); + } + + public static Transaction create2ContractTransaction( + String from, BigInteger gasPrice, BigInteger gasLimit, String bytecode, String calldata) { + byte[] bytecodeBytes = Numeric.hexStringToByteArray(bytecode); + byte[] calldataBytes = Numeric.hexStringToByteArray(calldata); + String calldataCreate = + FunctionEncoder.encode(ContractDeployer.encodeCreate2(bytecodeBytes, calldataBytes)); + Eip712Meta meta = + new Eip712Meta(BigInteger.valueOf(160000L), null, new byte[][] {bytecodeBytes}, null); + return new Transaction( + from, + ZkSyncAddresses.CONTRACT_DEPLOYER_ADDRESS, + gasPrice, + gasLimit, + null, + calldataCreate, + meta); + } + + public static Transaction create2ContractTransaction( + String from, + BigInteger gasPrice, + BigInteger gasLimit, + String bytecode, + String calldata, + byte[] salt) { + byte[] bytecodeBytes = Numeric.hexStringToByteArray(bytecode); + byte[] calldataBytes = Numeric.hexStringToByteArray(calldata); + String calldataCreate = + FunctionEncoder.encode(ContractDeployer.encodeCreate2(bytecodeBytes, calldataBytes, salt)); + Eip712Meta meta = + new Eip712Meta(BigInteger.valueOf(160000L), null, new byte[][] {bytecodeBytes}, null); + return new Transaction( + from, + ZkSyncAddresses.CONTRACT_DEPLOYER_ADDRESS, + gasPrice, + gasLimit, + null, + calldataCreate, + meta); + } + + public static Transaction create2ContractTransaction( + String from, + BigInteger gasPrice, + BigInteger gasLimit, + String bytecode, + String calldata, + List deps) { + byte[] bytecodeBytes = Numeric.hexStringToByteArray(bytecode); + byte[][] factoryDeps = new byte[deps.size() + 1][]; + for (int i = 0; i < deps.size(); i++) { + factoryDeps[i] = Numeric.hexStringToByteArray(deps.get(i)); + } + factoryDeps[deps.size()] = bytecodeBytes; + Eip712Meta meta = new Eip712Meta(BigInteger.valueOf(160000L), null, factoryDeps, null); + return new Transaction( + from, ZkSyncAddresses.CONTRACT_DEPLOYER_ADDRESS, gasPrice, gasLimit, null, calldata, meta); + } + + public static Transaction create2ContractTransaction( + String from, + BigInteger gasPrice, + BigInteger gasLimit, + String bytecode, + List deps, + String calldata, + byte[] salt) { + byte[] bytecodeBytes = Numeric.hexStringToByteArray(bytecode); + byte[] calldataBytes = Numeric.hexStringToByteArray(calldata); + byte[][] factoryDeps = new byte[deps.size() + 1][]; + for (int i = 0; i < deps.size(); i++) { + factoryDeps[i] = Numeric.hexStringToByteArray(deps.get(i)); + } + factoryDeps[deps.size()] = bytecodeBytes; + String calldataCreate = + FunctionEncoder.encode(ContractDeployer.encodeCreate2(bytecodeBytes, calldataBytes, salt)); + Eip712Meta meta = new Eip712Meta(BigInteger.valueOf(160000L), null, factoryDeps, null); + return new Transaction( + from, + ZkSyncAddresses.CONTRACT_DEPLOYER_ADDRESS, + gasPrice, + gasLimit, + null, + calldataCreate, + meta); + } + + public static Transaction create2ContractTransaction( + String from, + BigInteger gasPrice, + BigInteger gasLimit, + String bytecode, + String calldata, + String customSignature) { + byte[] bytecodeBytes = Numeric.hexStringToByteArray(bytecode); + byte[] calldataBytes = Numeric.hexStringToByteArray(calldata); + byte[] customSignatureBytes = Numeric.hexStringToByteArray(customSignature); + String calldataCreate = + FunctionEncoder.encode(ContractDeployer.encodeCreate2(bytecodeBytes, calldataBytes)); + Eip712Meta meta = + new Eip712Meta( + BigInteger.valueOf(160000L), customSignatureBytes, new byte[][] {bytecodeBytes}, null); + return new Transaction( + from, + ZkSyncAddresses.CONTRACT_DEPLOYER_ADDRESS, + gasPrice, + gasLimit, + null, + calldataCreate, + meta); + } + + public static Transaction create2ContractTransaction( + String from, + BigInteger gasPrice, + BigInteger gasLimit, + String bytecode, + String calldata, + String customSignature, + PaymasterParams paymasterParams) { + byte[] bytecodeBytes = Numeric.hexStringToByteArray(bytecode); + byte[] calldataBytes = Numeric.hexStringToByteArray(calldata); + byte[] customSignatureBytes = Numeric.hexStringToByteArray(customSignature); + String calldataCreate = + FunctionEncoder.encode(ContractDeployer.encodeCreate2(bytecodeBytes, calldataBytes)); + Eip712Meta meta = + new Eip712Meta( + BigInteger.valueOf(160000L), + customSignatureBytes, + new byte[][] {bytecodeBytes}, + paymasterParams); + return new Transaction( + from, + ZkSyncAddresses.CONTRACT_DEPLOYER_ADDRESS, + gasPrice, + gasLimit, + null, + calldataCreate, + meta); + } + + public static Transaction create2AccountTransaction( + String from, BigInteger gasPrice, BigInteger gasLimit, String bytecode) { + byte[] bytecodeBytes = Numeric.hexStringToByteArray(bytecode); + String calldata = FunctionEncoder.encode(ContractDeployer.encodeCreate2Account(bytecodeBytes)); + Eip712Meta meta = + new Eip712Meta(BigInteger.valueOf(160000L), null, new byte[][] {bytecodeBytes}, null); + return new Transaction( + from, ZkSyncAddresses.CONTRACT_DEPLOYER_ADDRESS, gasPrice, gasLimit, null, calldata, meta); + } + + public static Transaction create2AccountTransaction( + String from, BigInteger gasPrice, BigInteger gasLimit, String bytecode, String calldata) { + byte[] bytecodeBytes = Numeric.hexStringToByteArray(bytecode); + byte[] calldataBytes = Numeric.hexStringToByteArray(calldata); + String calldataCreate = + FunctionEncoder.encode(ContractDeployer.encodeCreate2Account(bytecodeBytes, calldataBytes)); + Eip712Meta meta = + new Eip712Meta(BigInteger.valueOf(160000L), null, new byte[][] {bytecodeBytes}, null); + return new Transaction( + from, + ZkSyncAddresses.CONTRACT_DEPLOYER_ADDRESS, + gasPrice, + gasLimit, + null, + calldataCreate, + meta); + } + + public static Transaction create2AccountTransaction( + String from, + BigInteger gasPrice, + BigInteger gasLimit, + String bytecode, + String calldata, + byte[] salt) { + byte[] bytecodeBytes = Numeric.hexStringToByteArray(bytecode); + byte[] calldataBytes = Numeric.hexStringToByteArray(calldata); + String calldataCreate = + FunctionEncoder.encode( + ContractDeployer.encodeCreate2Account( + bytecodeBytes, calldataBytes, salt, AccountAbstractionVersion.Version1)); + Eip712Meta meta = + new Eip712Meta(BigInteger.valueOf(160000L), null, new byte[][] {bytecodeBytes}, null); + return new Transaction( + from, + ZkSyncAddresses.CONTRACT_DEPLOYER_ADDRESS, + gasPrice, + gasLimit, + null, + calldataCreate, + meta); + } + + public static Transaction createContractTransaction( + String from, BigInteger gasPrice, BigInteger gasLimit, BigInteger value, String bytecode) { + byte[] bytecodeBytes = Numeric.hexStringToByteArray(bytecode); + String calldata = FunctionEncoder.encode(ContractDeployer.encodeCreate(bytecodeBytes)); + Eip712Meta meta = + new Eip712Meta(BigInteger.valueOf(160000L), null, new byte[][] {bytecodeBytes}, null); + return new Transaction( + from, ZkSyncAddresses.CONTRACT_DEPLOYER_ADDRESS, gasPrice, gasLimit, value, calldata, meta); + } + + public static Transaction createContractTransaction( + String from, BigInteger gasPrice, BigInteger gasLimit, String bytecode) { + byte[] bytecodeBytes = Numeric.hexStringToByteArray(bytecode); + String calldata = FunctionEncoder.encode(ContractDeployer.encodeCreate(bytecodeBytes)); + Eip712Meta meta = + new Eip712Meta(BigInteger.valueOf(160000L), null, new byte[][] {bytecodeBytes}, null); + return new Transaction( + from, ZkSyncAddresses.CONTRACT_DEPLOYER_ADDRESS, gasPrice, gasLimit, null, calldata, meta); + } + + public static Transaction createContractTransaction( + String from, BigInteger gasPrice, BigInteger gasLimit, String bytecode, String calldata) { + byte[] bytecodeBytes = Numeric.hexStringToByteArray(bytecode); + byte[] calldataBytes = Numeric.hexStringToByteArray(calldata); + String calldataCreate = + FunctionEncoder.encode(ContractDeployer.encodeCreate(bytecodeBytes, calldataBytes)); + Eip712Meta meta = + new Eip712Meta(BigInteger.valueOf(160000L), null, new byte[][] {bytecodeBytes}, null); + return new Transaction( + from, + ZkSyncAddresses.CONTRACT_DEPLOYER_ADDRESS, + gasPrice, + gasLimit, + null, + calldataCreate, + meta); + } + + public static Transaction createContractTransaction( + String from, + BigInteger gasPrice, + BigInteger gasLimit, + String bytecode, + List deps, + String calldata) { + byte[] bytecodeBytes = Numeric.hexStringToByteArray(bytecode); + byte[] calldataBytes = Numeric.hexStringToByteArray(calldata); + byte[][] factoryDeps = new byte[deps.size() + 1][]; + for (int i = 0; i < deps.size(); i++) { + factoryDeps[i] = Numeric.hexStringToByteArray(deps.get(i)); + } + factoryDeps[deps.size()] = bytecodeBytes; + String calldataCreate = + FunctionEncoder.encode(ContractDeployer.encodeCreate(bytecodeBytes, calldataBytes)); + Eip712Meta meta = new Eip712Meta(BigInteger.valueOf(160000L), null, factoryDeps, null); + return new Transaction( + from, + ZkSyncAddresses.CONTRACT_DEPLOYER_ADDRESS, + gasPrice, + gasLimit, + null, + calldataCreate, + meta); + } + + public static Transaction createFunctionCallTransaction( + String from, + String to, + BigInteger gasPrice, + BigInteger gasLimit, + BigInteger value, + String data) { + Eip712Meta meta = new Eip712Meta(BigInteger.valueOf(160000L), null, null, null); + return new Transaction(from, to, gasPrice, gasLimit, value, data, meta); + } + + public static Transaction createFunctionCallTransaction( + String from, String to, BigInteger gasPrice, BigInteger gasLimit, String data) { + + Eip712Meta meta = new Eip712Meta(BigInteger.valueOf(160000L), null, null, null); + return new Transaction(from, to, gasPrice, gasLimit, null, data, meta); + } + + public static Transaction createFunctionCallTransaction( + String from, + String to, + BigInteger gasPrice, + BigInteger gasLimit, + BigInteger value, + String data, + String customSignature, + PaymasterParams paymasterParams) { + Eip712Meta meta = + new Eip712Meta( + BigInteger.valueOf(160000L), + Numeric.hexStringToByteArray(customSignature), + null, + paymasterParams); + return new Transaction(from, to, gasPrice, gasLimit, value, data, meta); + } + + public String getFrom() { + return from; + } + + public String getTo() { + return to; + } + + public String getGas() { + return convert(gas); + } + + public String getGasPrice() { + return convert(gasPrice); + } + + public String getValue() { + return convert(value); + } + + @JsonIgnore + public BigInteger getGasNumber() { + return gas; + } + + @JsonIgnore + public BigInteger getGasPriceNumber() { + return gasPrice; + } + + @JsonIgnore + public BigInteger getValueNumber() { + return value; + } + + public String getData() { + return data; + } + + public String getTransactionType() { + return convert(BigInteger.valueOf(transactionType)); + } + + public AccessListObject getAccessList() { + return accessList; + } + + public Eip712Meta getEip712Meta() { + return eip712Meta; + } + + private static String convert(BigInteger value) { + if (value != null) { + return Numeric.encodeQuantity(value); + } else { + return null; // we don't want the field to be encoded if not present + } + } } diff --git a/src/main/java/io/zksync/methods/response/L2toL1Log.java b/src/main/java/io/zksync/methods/response/L2toL1Log.java index ca33a6f..821d8b3 100644 --- a/src/main/java/io/zksync/methods/response/L2toL1Log.java +++ b/src/main/java/io/zksync/methods/response/L2toL1Log.java @@ -2,106 +2,104 @@ import org.web3j.abi.datatypes.Address; -import java.math.BigInteger; - public class L2toL1Log { - 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; - - public String getBlockNumber() { - return BlockNumber; - } - - public void setBlockNumber(String blockNumber) { - BlockNumber = blockNumber; - } - - public String getBlockHash() { - return BlockHash; - } - - public void setBlockHash(String blockHash) { - BlockHash = blockHash; - } - - public String getL1BatchNumber() { - return L1BatchNumber; - } - - public void setL1BatchNumber(String l1BatchNumber) { - L1BatchNumber = l1BatchNumber; - } - - public String getTransactionIndex() { - return TransactionIndex; - } - - public void setTransactionIndex(String transactionIndex) { - TransactionIndex = transactionIndex; - } - - public String getShardId() { - return ShardId; - } - - public void setShardId(String shardId) { - ShardId = shardId; - } - - public boolean isService() { - return IsService; - } - - public void setService(boolean service) { - IsService = service; - } - - public Address getSender() { - return Sender; - } - - public void setSender(Address sender) { - Sender = sender; - } - - public String getKey() { - return Key; - } - - public void setKey(String key) { - Key = key; - } - - public String getValue() { - return Value; - } - - public void setValue(String value) { - Value = value; - } - - public String getTxHash() { - return TxHash; - } - - public void setTxHash(String txHash) { - TxHash = txHash; - } - - public int getIndex() { - return Index; - } - - public void setIndex(int index) { - Index = index; - } + 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; + + public String getBlockNumber() { + return BlockNumber; + } + + public void setBlockNumber(String blockNumber) { + BlockNumber = blockNumber; + } + + public String getBlockHash() { + return BlockHash; + } + + public void setBlockHash(String blockHash) { + BlockHash = blockHash; + } + + public String getL1BatchNumber() { + return L1BatchNumber; + } + + public void setL1BatchNumber(String l1BatchNumber) { + L1BatchNumber = l1BatchNumber; + } + + public String getTransactionIndex() { + return TransactionIndex; + } + + public void setTransactionIndex(String transactionIndex) { + TransactionIndex = transactionIndex; + } + + public String getShardId() { + return ShardId; + } + + public void setShardId(String shardId) { + ShardId = shardId; + } + + public boolean isService() { + return IsService; + } + + public void setService(boolean service) { + IsService = service; + } + + public Address getSender() { + return Sender; + } + + public void setSender(Address sender) { + Sender = sender; + } + + public String getKey() { + return Key; + } + + public void setKey(String key) { + Key = key; + } + + public String getValue() { + return Value; + } + + public void setValue(String value) { + Value = value; + } + + public String getTxHash() { + return TxHash; + } + + public void setTxHash(String txHash) { + TxHash = txHash; + } + + public int getIndex() { + return Index; + } + + public void setIndex(int index) { + Index = index; + } } diff --git a/src/main/java/io/zksync/methods/response/ZkLog.java b/src/main/java/io/zksync/methods/response/ZkLog.java index 68cc8f8..8c87068 100644 --- a/src/main/java/io/zksync/methods/response/ZkLog.java +++ b/src/main/java/io/zksync/methods/response/ZkLog.java @@ -1,42 +1,62 @@ package io.zksync.methods.response; -import org.web3j.protocol.core.methods.response.Log; - import java.util.List; import java.util.Objects; +import org.web3j.protocol.core.methods.response.Log; public class ZkLog extends Log { - private String l1BatchNumber; - private String transactionLogIndex; - - public String getL1BatchNumber() { - return l1BatchNumber; - } - - public void setL1BatchNumber(String l1BatchNumber) { - this.l1BatchNumber = l1BatchNumber; - } - - public ZkLog(String l1BatchNumber) { - this.l1BatchNumber = l1BatchNumber; - } - - public ZkLog(boolean removed, String logIndex, String transactionIndex, String transactionHash, String blockHash, String blockNumber, String address, String data, String type, List topics, String l1BatchNumber) { - super(removed, logIndex, transactionIndex, transactionHash, blockHash, blockNumber, address, data, type, topics); - this.l1BatchNumber = l1BatchNumber; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof ZkLog)) return false; - if (!super.equals(o)) return false; - ZkLog zkLog = (ZkLog) o; - return l1BatchNumber.equals(zkLog.l1BatchNumber); - } - - @Override - public int hashCode() { - return Objects.hash(super.hashCode(), l1BatchNumber); - } + private String l1BatchNumber; + private String transactionLogIndex; + + public String getL1BatchNumber() { + return l1BatchNumber; + } + + public void setL1BatchNumber(String l1BatchNumber) { + this.l1BatchNumber = l1BatchNumber; + } + + public ZkLog(String l1BatchNumber) { + this.l1BatchNumber = l1BatchNumber; + } + + public ZkLog( + boolean removed, + String logIndex, + String transactionIndex, + String transactionHash, + String blockHash, + String blockNumber, + String address, + String data, + String type, + List topics, + String l1BatchNumber) { + super( + removed, + logIndex, + transactionIndex, + transactionHash, + blockHash, + blockNumber, + address, + data, + type, + topics); + this.l1BatchNumber = l1BatchNumber; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (!(o instanceof ZkLog)) return false; + if (!super.equals(o)) return false; + ZkLog zkLog = (ZkLog) o; + return l1BatchNumber.equals(zkLog.l1BatchNumber); + } + + @Override + public int hashCode() { + return Objects.hash(super.hashCode(), l1BatchNumber); + } } diff --git a/src/main/java/io/zksync/methods/response/ZkTransaction.java b/src/main/java/io/zksync/methods/response/ZkTransaction.java index a7ad6d6..a08f4f2 100644 --- a/src/main/java/io/zksync/methods/response/ZkTransaction.java +++ b/src/main/java/io/zksync/methods/response/ZkTransaction.java @@ -1,85 +1,103 @@ package io.zksync.methods.response; -import org.web3j.protocol.core.methods.response.Transaction; -import org.web3j.utils.Numeric; - import java.math.BigInteger; import java.util.List; import java.util.Objects; +import org.web3j.protocol.core.methods.response.Transaction; +import org.web3j.utils.Numeric; public class ZkTransaction extends Transaction { - private String l1BatchNumber; - private String l1BatchTxIndex; - - public ZkTransaction(String hash, - String nonce, - String blockHash, - String blockNumber, - String chainId, - String transactionIndex, - String from, - String to, - String value, - String gas, - String gasPrice, - String input, - String creates, - String publicKey, - String raw, - String r, - String s, - long v, - String type, - String maxFeePerGas, - String maxPriorityFeePerGas, - List accessList, - String l1BatchNumber, - String l1BatchTxIndex) { - super(hash, nonce, blockHash, blockNumber, chainId, transactionIndex, from, to, value, gas, gasPrice, input, - creates, publicKey, raw, r, s, v, type, maxFeePerGas, maxPriorityFeePerGas, accessList); - this.l1BatchNumber = l1BatchNumber; - this.l1BatchTxIndex = l1BatchTxIndex; - } - - public String getL1BatchNumberRaw() { - return l1BatchNumber; - } - - public BigInteger getL1BatchNumber() { - return Numeric.decodeQuantity(l1BatchNumber); - } - - - public void setL1BatchNumber(String l1BatchNumber) { - this.l1BatchNumber = l1BatchNumber; - } - - public String getL1BatchTxIndexRaw() { - return l1BatchTxIndex; - } - - public BigInteger getL1BatchTxIndex() { - return Numeric.decodeQuantity(l1BatchTxIndex); - } - - public void setL1BatchTxIndex(String l1BatchTxIndex) { - this.l1BatchTxIndex = l1BatchTxIndex; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof ZkTransaction)) return false; - if (!super.equals(o)) return false; - ZkTransaction that = (ZkTransaction) o; - return l1BatchNumber.equals(that.l1BatchNumber) && l1BatchTxIndex.equals(that.l1BatchTxIndex); - } - - @Override - public int hashCode() { - return Objects.hash(super.hashCode(), l1BatchNumber, l1BatchTxIndex); - } - - + private String l1BatchNumber; + private String l1BatchTxIndex; + + public ZkTransaction( + String hash, + String nonce, + String blockHash, + String blockNumber, + String chainId, + String transactionIndex, + String from, + String to, + String value, + String gas, + String gasPrice, + String input, + String creates, + String publicKey, + String raw, + String r, + String s, + long v, + String type, + String maxFeePerGas, + String maxPriorityFeePerGas, + List accessList, + String l1BatchNumber, + String l1BatchTxIndex) { + super( + hash, + nonce, + blockHash, + blockNumber, + chainId, + transactionIndex, + from, + to, + value, + gas, + gasPrice, + input, + creates, + publicKey, + raw, + r, + s, + v, + type, + maxFeePerGas, + maxPriorityFeePerGas, + accessList); + this.l1BatchNumber = l1BatchNumber; + this.l1BatchTxIndex = l1BatchTxIndex; + } + + public String getL1BatchNumberRaw() { + return l1BatchNumber; + } + + public BigInteger getL1BatchNumber() { + return Numeric.decodeQuantity(l1BatchNumber); + } + + public void setL1BatchNumber(String l1BatchNumber) { + this.l1BatchNumber = l1BatchNumber; + } + + public String getL1BatchTxIndexRaw() { + return l1BatchTxIndex; + } + + public BigInteger getL1BatchTxIndex() { + return Numeric.decodeQuantity(l1BatchTxIndex); + } + + public void setL1BatchTxIndex(String l1BatchTxIndex) { + this.l1BatchTxIndex = l1BatchTxIndex; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (!(o instanceof ZkTransaction)) return false; + if (!super.equals(o)) return false; + ZkTransaction that = (ZkTransaction) o; + return l1BatchNumber.equals(that.l1BatchNumber) && l1BatchTxIndex.equals(that.l1BatchTxIndex); + } + + @Override + public int hashCode() { + return Objects.hash(super.hashCode(), l1BatchNumber, l1BatchTxIndex); + } } diff --git a/src/main/java/io/zksync/methods/response/ZkTransactionReceipt.java b/src/main/java/io/zksync/methods/response/ZkTransactionReceipt.java index eb77efb..ccd8c6f 100644 --- a/src/main/java/io/zksync/methods/response/ZkTransactionReceipt.java +++ b/src/main/java/io/zksync/methods/response/ZkTransactionReceipt.java @@ -1,82 +1,118 @@ package io.zksync.methods.response; -import kotlin.OverloadResolutionByLambdaReturnType; -import kotlin.jvm.JvmOverloads; -import org.web3j.protocol.core.methods.response.Log; -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; import java.util.Objects; +import org.web3j.protocol.core.methods.response.Log; +import org.web3j.protocol.core.methods.response.TransactionReceipt; +import org.web3j.utils.Numeric; public class ZkTransactionReceipt extends TransactionReceipt { - private String l1BatchNumber; - private String l1BatchTxIndex; - private List l2ToL1Logs; - - public ZkTransactionReceipt() { - } - public ZkTransactionReceipt(String transactionHash, String transactionIndex, String blockHash, String blockNumber, String cumulativeGasUsed, String gasUsed, String contractAddress, String root, String status, String from, String to, List logs, String logsBloom, String revertReason, String type, String effectiveGasPrice, String l1BatchNumber, String l1BatchTxIndex, List l2ToL1Logs) { - super(transactionHash, transactionIndex, blockHash, blockNumber, cumulativeGasUsed, gasUsed, contractAddress, root, status, from, to, logs, logsBloom, revertReason, type, effectiveGasPrice); - this.l1BatchNumber = l1BatchNumber; - this.l1BatchTxIndex = l1BatchTxIndex; - this.l2ToL1Logs = l2ToL1Logs; - } - - public String getL1BatchNumberRaw() { - return l1BatchNumber; - } - - public BigInteger getL1BatchNumber() { - return Numeric.decodeQuantity(l1BatchNumber); - } - - public void setL1BatchNumber(String l1BatchNumber) { - this.l1BatchNumber = l1BatchNumber; - } - - public String getL1BatchTxIndexRaw() { - return l1BatchTxIndex; - } - - public BigInteger getL1BatchTxIndex() { - return Numeric.decodeQuantity(l1BatchTxIndex); - } - - public void setL1BatchTxIndex(String l1BatchTxIndex) { - this.l1BatchTxIndex = l1BatchTxIndex; - } - - public void setL2ToL1Logs(List l2ToL1Logs) { - this.l2ToL1Logs = l2ToL1Logs; - } - - public List getl2ToL1Logs() { - return l2ToL1Logs; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof ZkTransactionReceipt)) return false; - if (!super.equals(o)) return false; - ZkTransactionReceipt that = (ZkTransactionReceipt) o; - return l1BatchNumber.equals(that.l1BatchNumber) && l1BatchTxIndex.equals(that.l1BatchTxIndex); - } - - @Override - public int hashCode() { - return Objects.hash(super.hashCode(), l1BatchNumber, l1BatchTxIndex); - } - - @Override - public String toString() { - return "ZkTransactionReceipt{" + - "l1BatchNumber='" + l1BatchNumber + '\'' + - ", l1BatchTxIndex='" + l1BatchTxIndex + '\'' + - "} " + super.toString(); - } + private String l1BatchNumber; + private String l1BatchTxIndex; + private List l2ToL1Logs; + + public ZkTransactionReceipt() {} + + public ZkTransactionReceipt( + String transactionHash, + String transactionIndex, + String blockHash, + String blockNumber, + String cumulativeGasUsed, + String gasUsed, + String contractAddress, + String root, + String status, + String from, + String to, + List logs, + String logsBloom, + String revertReason, + String type, + String effectiveGasPrice, + String l1BatchNumber, + String l1BatchTxIndex, + List l2ToL1Logs) { + super( + transactionHash, + transactionIndex, + blockHash, + blockNumber, + cumulativeGasUsed, + gasUsed, + contractAddress, + root, + status, + from, + to, + logs, + logsBloom, + revertReason, + type, + effectiveGasPrice); + this.l1BatchNumber = l1BatchNumber; + this.l1BatchTxIndex = l1BatchTxIndex; + this.l2ToL1Logs = l2ToL1Logs; + } + + public String getL1BatchNumberRaw() { + return l1BatchNumber; + } + + public BigInteger getL1BatchNumber() { + return Numeric.decodeQuantity(l1BatchNumber); + } + + public void setL1BatchNumber(String l1BatchNumber) { + this.l1BatchNumber = l1BatchNumber; + } + + public String getL1BatchTxIndexRaw() { + return l1BatchTxIndex; + } + + public BigInteger getL1BatchTxIndex() { + return Numeric.decodeQuantity(l1BatchTxIndex); + } + + public void setL1BatchTxIndex(String l1BatchTxIndex) { + this.l1BatchTxIndex = l1BatchTxIndex; + } + + public void setL2ToL1Logs(List l2ToL1Logs) { + this.l2ToL1Logs = l2ToL1Logs; + } + + public List getl2ToL1Logs() { + return l2ToL1Logs; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (!(o instanceof ZkTransactionReceipt)) return false; + if (!super.equals(o)) return false; + ZkTransactionReceipt that = (ZkTransactionReceipt) o; + return l1BatchNumber.equals(that.l1BatchNumber) && l1BatchTxIndex.equals(that.l1BatchTxIndex); + } + + @Override + public int hashCode() { + return Objects.hash(super.hashCode(), l1BatchNumber, l1BatchTxIndex); + } + + @Override + public String toString() { + return "ZkTransactionReceipt{" + + "l1BatchNumber='" + + l1BatchNumber + + '\'' + + ", l1BatchTxIndex='" + + l1BatchTxIndex + + '\'' + + "} " + + super.toString(); + } } diff --git a/src/main/java/io/zksync/methods/response/ZksAccountBalances.java b/src/main/java/io/zksync/methods/response/ZksAccountBalances.java index 63605bd..436a4a4 100644 --- a/src/main/java/io/zksync/methods/response/ZksAccountBalances.java +++ b/src/main/java/io/zksync/methods/response/ZksAccountBalances.java @@ -1,15 +1,15 @@ package io.zksync.methods.response; -import org.web3j.protocol.core.Response; -import org.web3j.utils.Numeric; - import java.math.BigInteger; import java.util.Map; import java.util.stream.Collectors; +import org.web3j.protocol.core.Response; +import org.web3j.utils.Numeric; public class ZksAccountBalances extends Response> { - public Map getBalances() { - return getResult().entrySet().stream() - .collect(Collectors.toMap(Map.Entry::getKey, entry -> Numeric.decodeQuantity(entry.getValue()))); - } + public Map getBalances() { + return getResult().entrySet().stream() + .collect( + Collectors.toMap(Map.Entry::getKey, entry -> Numeric.decodeQuantity(entry.getValue()))); + } } diff --git a/src/main/java/io/zksync/methods/response/ZksBlock.java b/src/main/java/io/zksync/methods/response/ZksBlock.java index 2f034af..cdae72c 100644 --- a/src/main/java/io/zksync/methods/response/ZksBlock.java +++ b/src/main/java/io/zksync/methods/response/ZksBlock.java @@ -6,251 +6,288 @@ import com.fasterxml.jackson.databind.JsonDeserializer; import com.fasterxml.jackson.databind.ObjectReader; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import org.web3j.protocol.ObjectMapperFactory; -import org.web3j.protocol.core.Response; -import org.web3j.protocol.core.methods.response.AccessListObject; -import org.web3j.protocol.core.methods.response.EthBlock; -import org.web3j.utils.Numeric; - import java.io.IOException; import java.math.BigInteger; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Objects; +import org.web3j.protocol.ObjectMapperFactory; +import org.web3j.protocol.core.Response; +import org.web3j.protocol.core.methods.response.AccessListObject; +import org.web3j.protocol.core.methods.response.EthBlock; +import org.web3j.utils.Numeric; public class ZksBlock extends Response { - @Override - @JsonDeserialize(using = ZksBlock.ResponseDeserialiser.class) - public void setResult(ZksBlock.Block result) { - super.setResult(result); + @Override + @JsonDeserialize(using = ZksBlock.ResponseDeserialiser.class) + public void setResult(ZksBlock.Block result) { + super.setResult(result); + } + + public ZksBlock.Block getBlock() { + return getResult(); + } + + public static class Block extends EthBlock.Block { + private String l1BatchNumber; + private String l1BatchTimestamp; + + public Block() {} + + public Block( + String number, + String hash, + String parentHash, + String nonce, + String sha3Uncles, + String logsBloom, + String transactionsRoot, + String stateRoot, + String receiptsRoot, + String author, + String miner, + String mixHash, + String difficulty, + String totalDifficulty, + String extraData, + String size, + String gasLimit, + String gasUsed, + String timestamp, + List transactions, + List uncles, + List sealFields, + String baseFeePerGas, + String l1BatchNumber, + String l1BatchTimestamp) { + super( + number, + hash, + parentHash, + nonce, + sha3Uncles, + logsBloom, + transactionsRoot, + stateRoot, + receiptsRoot, + author, + miner, + mixHash, + difficulty, + totalDifficulty, + extraData, + size, + gasLimit, + gasUsed, + timestamp, + transactions, + uncles, + sealFields, + baseFeePerGas); + this.l1BatchNumber = l1BatchNumber; + this.l1BatchTimestamp = l1BatchTimestamp; } - public ZksBlock.Block getBlock() { - return getResult(); + public BigInteger getL1BatchNumber() { + return Numeric.decodeQuantity(l1BatchNumber); } - public static class Block extends EthBlock.Block { - private String l1BatchNumber; - private String l1BatchTimestamp; - - public Block() {} - - public Block(String number, String hash, String parentHash, String nonce, String sha3Uncles, String logsBloom, - String transactionsRoot, String stateRoot, String receiptsRoot, String author, String miner, - String mixHash, String difficulty, String totalDifficulty, String extraData, String size, - String gasLimit, String gasUsed, String timestamp, List transactions, - List uncles, List sealFields, String baseFeePerGas, String l1BatchNumber, - String l1BatchTimestamp) { - super(number, hash, parentHash, nonce, sha3Uncles, logsBloom, transactionsRoot, stateRoot, receiptsRoot, - author, miner, mixHash, difficulty, totalDifficulty, extraData, size, gasLimit, gasUsed, timestamp, - transactions, uncles, sealFields, baseFeePerGas); - this.l1BatchNumber = l1BatchNumber; - this.l1BatchTimestamp = l1BatchTimestamp; - } - - public BigInteger getL1BatchNumber() { - return Numeric.decodeQuantity(l1BatchNumber); - } - - public void setL1BatchNumber(String l1BatchNumber) { - this.l1BatchNumber = l1BatchNumber; - } - - public BigInteger getL1BatchTimestamp() { - return Numeric.decodeQuantity(l1BatchTimestamp); - } - - public void setL1BatchTimestamp(String l1BatchTimestamp) { - this.l1BatchTimestamp = l1BatchTimestamp; - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - - if (!(o instanceof Block)) { - return false; - } - - if (!super.equals(o)) { - return false; - } - - Block block = (Block) o; + public void setL1BatchNumber(String l1BatchNumber) { + this.l1BatchNumber = l1BatchNumber; + } - if (getL1BatchNumber() != null - ? !getL1BatchNumber().equals(block.getL1BatchNumber()) - : block.getL1BatchNumber() != null) { - return false; - } + public BigInteger getL1BatchTimestamp() { + return Numeric.decodeQuantity(l1BatchTimestamp); + } - return getL1BatchTimestamp() != null - ? getL1BatchTimestamp().equals(block.getL1BatchTimestamp()) - : block.getL1BatchTimestamp() == null; - } + public void setL1BatchTimestamp(String l1BatchTimestamp) { + this.l1BatchTimestamp = l1BatchTimestamp; + } - @Override - public int hashCode() { - int result = super.hashCode(); - result = 31 * result + (getL1BatchTimestamp() != null ? getL1BatchTimestamp().hashCode() : 0); - result = 31 * result + (getL1BatchNumber() != null ? getL1BatchNumber().hashCode() : 0); - return result; - } + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + + if (!(o instanceof Block)) { + return false; + } + + if (!super.equals(o)) { + return false; + } + + Block block = (Block) o; + + if (getL1BatchNumber() != null + ? !getL1BatchNumber().equals(block.getL1BatchNumber()) + : block.getL1BatchNumber() != null) { + return false; + } + + return getL1BatchTimestamp() != null + ? getL1BatchTimestamp().equals(block.getL1BatchTimestamp()) + : block.getL1BatchTimestamp() == null; } - public interface TransactionResult { - T get(); + @Override + public int hashCode() { + int result = super.hashCode(); + result = 31 * result + (getL1BatchTimestamp() != null ? getL1BatchTimestamp().hashCode() : 0); + result = 31 * result + (getL1BatchNumber() != null ? getL1BatchNumber().hashCode() : 0); + return result; } + } - public static class TransactionHash implements ZksBlock.TransactionResult { - private String value; + public interface TransactionResult { + T get(); + } - public TransactionHash() {} + public static class TransactionHash implements ZksBlock.TransactionResult { + private String value; - public TransactionHash(String value) { - this.value = value; - } + public TransactionHash() {} - @Override - public String get() { - return value; - } + public TransactionHash(String value) { + this.value = value; + } - public void setValue(String value) { - this.value = value; - } + @Override + public String get() { + return value; + } - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (!(o instanceof ZksBlock.TransactionHash)) { - return false; - } + public void setValue(String value) { + this.value = value; + } - ZksBlock.TransactionHash that = (ZksBlock.TransactionHash) o; + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (!(o instanceof ZksBlock.TransactionHash)) { + return false; + } - return Objects.equals(value, that.value); - } + ZksBlock.TransactionHash that = (ZksBlock.TransactionHash) o; - @Override - public int hashCode() { - return value != null ? value.hashCode() : 0; - } + return Objects.equals(value, that.value); } - - public static class TransactionObject extends ZkTransaction - implements ZksBlock.TransactionResult { - public TransactionObject( - String hash, - String nonce, - String blockHash, - String blockNumber, - String chainId, - String transactionIndex, - String from, - String to, - String value, - String gasPrice, - String gas, - String input, - String creates, - String publicKey, - String raw, - String r, - String s, - long v, - String type, - String maxFeePerGas, - String maxPriorityFeePerGas, - List accessList, - String l1BatchNumber, - String l1BatchTxIndex) { - super( - hash, - nonce, - blockHash, - blockNumber, - chainId, - transactionIndex, - from, - to, - value, - gas, - gasPrice, - input, - creates, - publicKey, - raw, - r, - s, - v, - type, - maxFeePerGas, - maxPriorityFeePerGas, - accessList, - l1BatchNumber, - l1BatchTxIndex); - } - - @Override - public ZkTransaction get() { - return this; - } + @Override + public int hashCode() { + return value != null ? value.hashCode() : 0; + } + } + + public static class TransactionObject extends ZkTransaction + implements ZksBlock.TransactionResult { + public TransactionObject( + String hash, + String nonce, + String blockHash, + String blockNumber, + String chainId, + String transactionIndex, + String from, + String to, + String value, + String gasPrice, + String gas, + String input, + String creates, + String publicKey, + String raw, + String r, + String s, + long v, + String type, + String maxFeePerGas, + String maxPriorityFeePerGas, + List accessList, + String l1BatchNumber, + String l1BatchTxIndex) { + super( + hash, + nonce, + blockHash, + blockNumber, + chainId, + transactionIndex, + from, + to, + value, + gas, + gasPrice, + input, + creates, + publicKey, + raw, + r, + s, + v, + type, + maxFeePerGas, + maxPriorityFeePerGas, + accessList, + l1BatchNumber, + l1BatchTxIndex); } - public static class ResultTransactionDeserialiser - extends JsonDeserializer> { + @Override + public ZkTransaction get() { + return this; + } + } - private ObjectReader objectReader = ObjectMapperFactory.getObjectReader(); + public static class ResultTransactionDeserialiser + extends JsonDeserializer> { - @Override - public List deserialize( - JsonParser jsonParser, DeserializationContext deserializationContext) - throws IOException { + private ObjectReader objectReader = ObjectMapperFactory.getObjectReader(); - List transactionResults = new ArrayList<>(); - JsonToken nextToken = jsonParser.nextToken(); + @Override + public List deserialize( + JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException { - if (nextToken == JsonToken.START_OBJECT) { - Iterator transactionObjectIterator = - objectReader.readValues(jsonParser, ZksBlock.TransactionObject.class); - while (transactionObjectIterator.hasNext()) { - transactionResults.add(transactionObjectIterator.next()); - } - } else if (nextToken == JsonToken.VALUE_STRING) { - jsonParser.getValueAsString(); + List transactionResults = new ArrayList<>(); + JsonToken nextToken = jsonParser.nextToken(); - Iterator transactionHashIterator = - objectReader.readValues(jsonParser, ZksBlock.TransactionHash.class); - while (transactionHashIterator.hasNext()) { - transactionResults.add(transactionHashIterator.next()); - } - } + if (nextToken == JsonToken.START_OBJECT) { + Iterator transactionObjectIterator = + objectReader.readValues(jsonParser, ZksBlock.TransactionObject.class); + while (transactionObjectIterator.hasNext()) { + transactionResults.add(transactionObjectIterator.next()); + } + } else if (nextToken == JsonToken.VALUE_STRING) { + jsonParser.getValueAsString(); - return transactionResults; + Iterator transactionHashIterator = + objectReader.readValues(jsonParser, ZksBlock.TransactionHash.class); + while (transactionHashIterator.hasNext()) { + transactionResults.add(transactionHashIterator.next()); } + } + + return transactionResults; } + } - public static class ResponseDeserialiser extends JsonDeserializer { + public static class ResponseDeserialiser extends JsonDeserializer { - private ObjectReader objectReader = ObjectMapperFactory.getObjectReader(); + private ObjectReader objectReader = ObjectMapperFactory.getObjectReader(); - @Override - public ZksBlock.Block deserialize( - JsonParser jsonParser, DeserializationContext deserializationContext) - throws IOException { - if (jsonParser.getCurrentToken() != JsonToken.VALUE_NULL) { - return objectReader.readValue(jsonParser, ZksBlock.Block.class); - } else { - return null; // null is wrapped by Optional in above getter - } - } + @Override + public ZksBlock.Block deserialize( + JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException { + if (jsonParser.getCurrentToken() != JsonToken.VALUE_NULL) { + return objectReader.readValue(jsonParser, ZksBlock.Block.class); + } else { + return null; // null is wrapped by Optional in above getter + } } -} \ No newline at end of file + } +} diff --git a/src/main/java/io/zksync/methods/response/ZksContractDebugInfo.java b/src/main/java/io/zksync/methods/response/ZksContractDebugInfo.java index c02ea98..7c63b6d 100644 --- a/src/main/java/io/zksync/methods/response/ZksContractDebugInfo.java +++ b/src/main/java/io/zksync/methods/response/ZksContractDebugInfo.java @@ -1,9 +1,6 @@ package io.zksync.methods.response; -import org.web3j.protocol.core.Response; - import io.zksync.protocol.core.debug.ContractSourceDebugInfo; +import org.web3j.protocol.core.Response; -public class ZksContractDebugInfo extends Response { - -} +public class ZksContractDebugInfo extends Response {} diff --git a/src/main/java/io/zksync/methods/response/ZksEstimateFee.java b/src/main/java/io/zksync/methods/response/ZksEstimateFee.java index 0c10132..1de20bc 100755 --- a/src/main/java/io/zksync/methods/response/ZksEstimateFee.java +++ b/src/main/java/io/zksync/methods/response/ZksEstimateFee.java @@ -3,6 +3,4 @@ import io.zksync.transaction.fee.Fee; import org.web3j.protocol.core.Response; -public class ZksEstimateFee extends Response { - -} +public class ZksEstimateFee extends Response {} diff --git a/src/main/java/io/zksync/methods/response/ZksGetLogs.java b/src/main/java/io/zksync/methods/response/ZksGetLogs.java index d87b3a8..a4aa43b 100644 --- a/src/main/java/io/zksync/methods/response/ZksGetLogs.java +++ b/src/main/java/io/zksync/methods/response/ZksGetLogs.java @@ -1,7 +1,5 @@ package io.zksync.methods.response; - import org.web3j.protocol.core.Response; -public class ZksGetLogs extends Response { -} +public class ZksGetLogs extends Response {} diff --git a/src/main/java/io/zksync/methods/response/ZksGetTransactionByHash.java b/src/main/java/io/zksync/methods/response/ZksGetTransactionByHash.java index 84ca42b..f5a117f 100644 --- a/src/main/java/io/zksync/methods/response/ZksGetTransactionByHash.java +++ b/src/main/java/io/zksync/methods/response/ZksGetTransactionByHash.java @@ -2,6 +2,4 @@ import org.web3j.protocol.core.Response; - -public class ZksGetTransactionByHash extends Response { -} \ No newline at end of file +public class ZksGetTransactionByHash extends Response {} diff --git a/src/main/java/io/zksync/methods/response/ZksGetTransactionDetails.java b/src/main/java/io/zksync/methods/response/ZksGetTransactionDetails.java index e7e5755..2e245d5 100644 --- a/src/main/java/io/zksync/methods/response/ZksGetTransactionDetails.java +++ b/src/main/java/io/zksync/methods/response/ZksGetTransactionDetails.java @@ -3,6 +3,4 @@ import io.zksync.transaction.TransactionDetails; import org.web3j.protocol.core.Response; -public class ZksGetTransactionDetails extends Response { - -} +public class ZksGetTransactionDetails extends Response {} diff --git a/src/main/java/io/zksync/methods/response/ZksGetTransactionReceipt.java b/src/main/java/io/zksync/methods/response/ZksGetTransactionReceipt.java index f7667b8..18c9a85 100644 --- a/src/main/java/io/zksync/methods/response/ZksGetTransactionReceipt.java +++ b/src/main/java/io/zksync/methods/response/ZksGetTransactionReceipt.java @@ -1,13 +1,11 @@ package io.zksync.methods.response; -import org.web3j.protocol.core.Response; - import java.util.Optional; +import org.web3j.protocol.core.Response; public class ZksGetTransactionReceipt extends Response { - public Optional getTransactionReceipt() { - return Optional.ofNullable(getResult()); - } - + public Optional getTransactionReceipt() { + return Optional.ofNullable(getResult()); + } } diff --git a/src/main/java/io/zksync/methods/response/ZksL1ChainId.java b/src/main/java/io/zksync/methods/response/ZksL1ChainId.java index 091e9ad..b200d05 100644 --- a/src/main/java/io/zksync/methods/response/ZksL1ChainId.java +++ b/src/main/java/io/zksync/methods/response/ZksL1ChainId.java @@ -1,12 +1,11 @@ package io.zksync.methods.response; +import java.math.BigInteger; import org.web3j.protocol.core.Response; import org.web3j.utils.Numeric; -import java.math.BigInteger; - public class ZksL1ChainId extends Response { - public BigInteger getChainId() { - return Numeric.decodeQuantity(getResult()); - } + public BigInteger getChainId() { + return Numeric.decodeQuantity(getResult()); + } } diff --git a/src/main/java/io/zksync/methods/response/ZksMainContract.java b/src/main/java/io/zksync/methods/response/ZksMainContract.java index 2c5fc8c..9d6e31b 100644 --- a/src/main/java/io/zksync/methods/response/ZksMainContract.java +++ b/src/main/java/io/zksync/methods/response/ZksMainContract.java @@ -2,6 +2,4 @@ import org.web3j.protocol.core.Response; -public class ZksMainContract extends Response { - -} +public class ZksMainContract extends Response {} diff --git a/src/main/java/io/zksync/methods/response/ZksMessageProof.java b/src/main/java/io/zksync/methods/response/ZksMessageProof.java index 7610677..a02f874 100644 --- a/src/main/java/io/zksync/methods/response/ZksMessageProof.java +++ b/src/main/java/io/zksync/methods/response/ZksMessageProof.java @@ -3,5 +3,4 @@ import io.zksync.protocol.core.L2ToL1MessageProof; import org.web3j.protocol.core.Response; -public class ZksMessageProof extends Response { -} +public class ZksMessageProof extends Response {} diff --git a/src/main/java/io/zksync/methods/response/ZksTestnetPaymasterAddress.java b/src/main/java/io/zksync/methods/response/ZksTestnetPaymasterAddress.java index 25d68b2..a60b514 100644 --- a/src/main/java/io/zksync/methods/response/ZksTestnetPaymasterAddress.java +++ b/src/main/java/io/zksync/methods/response/ZksTestnetPaymasterAddress.java @@ -2,5 +2,4 @@ import org.web3j.protocol.core.Response; -public class ZksTestnetPaymasterAddress extends Response { -} +public class ZksTestnetPaymasterAddress extends Response {} diff --git a/src/main/java/io/zksync/methods/response/ZksTokenPrice.java b/src/main/java/io/zksync/methods/response/ZksTokenPrice.java index 9a2593d..086b8a1 100644 --- a/src/main/java/io/zksync/methods/response/ZksTokenPrice.java +++ b/src/main/java/io/zksync/methods/response/ZksTokenPrice.java @@ -1,9 +1,6 @@ package io.zksync.methods.response; import java.math.BigDecimal; - import org.web3j.protocol.core.Response; -public class ZksTokenPrice extends Response { - -} +public class ZksTokenPrice extends Response {} diff --git a/src/main/java/io/zksync/methods/response/ZksTokens.java b/src/main/java/io/zksync/methods/response/ZksTokens.java index 54f3092..1f394dd 100755 --- a/src/main/java/io/zksync/methods/response/ZksTokens.java +++ b/src/main/java/io/zksync/methods/response/ZksTokens.java @@ -1,9 +1,7 @@ package io.zksync.methods.response; +import io.zksync.protocol.core.Token; import java.util.List; - import org.web3j.protocol.core.Response; -import io.zksync.protocol.core.Token; - public class ZksTokens extends Response> {} diff --git a/src/main/java/io/zksync/methods/response/ZksTransactionTrace.java b/src/main/java/io/zksync/methods/response/ZksTransactionTrace.java index e720484..507e0db 100644 --- a/src/main/java/io/zksync/methods/response/ZksTransactionTrace.java +++ b/src/main/java/io/zksync/methods/response/ZksTransactionTrace.java @@ -1,9 +1,6 @@ package io.zksync.methods.response; -import org.web3j.protocol.core.Response; - import io.zksync.protocol.core.debug.VmDebugTrace; +import org.web3j.protocol.core.Response; -public class ZksTransactionTrace extends Response { - -} +public class ZksTransactionTrace extends Response {} diff --git a/src/main/java/io/zksync/methods/response/ZksTransactions.java b/src/main/java/io/zksync/methods/response/ZksTransactions.java index fc3768b..31eb4e3 100644 --- a/src/main/java/io/zksync/methods/response/ZksTransactions.java +++ b/src/main/java/io/zksync/methods/response/ZksTransactions.java @@ -1,10 +1,7 @@ package io.zksync.methods.response; import java.util.List; - import org.web3j.protocol.core.Response; import org.web3j.protocol.core.methods.response.Transaction; -public class ZksTransactions extends Response> { - -} +public class ZksTransactions extends Response> {} diff --git a/src/main/java/io/zksync/protocol/JsonRpc2_0ZkSync.java b/src/main/java/io/zksync/protocol/JsonRpc2_0ZkSync.java index 7a508af..db9c275 100755 --- a/src/main/java/io/zksync/protocol/JsonRpc2_0ZkSync.java +++ b/src/main/java/io/zksync/protocol/JsonRpc2_0ZkSync.java @@ -1,10 +1,9 @@ package io.zksync.protocol; -import java.util.Arrays; -import java.util.Collections; - import io.zksync.methods.request.Transaction; import io.zksync.methods.response.*; +import java.util.Arrays; +import java.util.Collections; import org.jetbrains.annotations.Nullable; import org.web3j.protocol.Web3jService; import org.web3j.protocol.core.DefaultBlockParameter; @@ -15,124 +14,165 @@ public class JsonRpc2_0ZkSync extends JsonRpc2_0Web3j implements ZkSync { - public static final int DEFAULT_BLOCK_COMMIT_TIME = 800; - - public JsonRpc2_0ZkSync(Web3jService web3jService) { - super(web3jService); - } - - @Override - public Request zksEstimateFee(Transaction transaction) { - return new Request<>( - "zks_estimateFee", Collections.singletonList(transaction), web3jService, ZksEstimateFee.class); - } - - @Override - public Request zksMainContract() { - return new Request<>("zks_getMainContract", Collections.emptyList(), web3jService, ZksMainContract.class); - } - - @Override - public Request zksGetConfirmedTokens(Integer from, Short limit) { - return new Request<>( - "zks_getConfirmedTokens", Arrays.asList(from, limit), web3jService, ZksTokens.class); - } - - @Override - public Request zksGetTokenPrice(String tokenAddress) { - return new Request<>( - "zks_getTokenPrice", Collections.singletonList(tokenAddress), web3jService, ZksTokenPrice.class); - } - - @Override - public Request zksL1ChainId() { - return new Request<>("zks_L1ChainId", Collections.emptyList(), web3jService, ZksL1ChainId.class); - } - - @Override - public Request zksGetContractDebugInfo(String contractAddress) { - return new Request<>( - "zks_getContractDebugInfo", Collections.singletonList(contractAddress), web3jService, ZksContractDebugInfo.class); - } - - @Override - public Request zksGetTransactionTrace(String transactionHash) { - return new Request<>( - "zks_getTransactionTrace", Collections.singletonList(transactionHash), web3jService, ZksTransactionTrace.class); - } - - @Override - public Request zksGetAllAccountBalances(String address) { - return new Request<>("zks_getAllAccountBalances", Collections.singletonList(address), web3jService, ZksAccountBalances.class); - } - - @Override - public Request zksGetBridgeContracts() { - return new Request<>("zks_getBridgeContracts", Collections.emptyList(), web3jService, ZksBridgeAddresses.class); - } - - @Override - public Request zksGetL2ToL1MsgProof(Integer block, String sender, String message, @Nullable Long l2LogPosition) { - return new Request<>("zks_getL2ToL1MsgProof", Arrays.asList(block, sender, message), web3jService, ZksMessageProof.class); - } - - @Override - public Request zksGetL2ToL1LogProof(String txHash, int index) { - return new Request<>("zks_getL2ToL1LogProof", Arrays.asList(txHash, index), web3jService, ZksMessageProof.class); - } - - @Override - public Request ethEstimateGas(Transaction transaction) { - return new Request<>( - "eth_estimateGas", Collections.singletonList(transaction), web3jService, EthEstimateGas.class); - } - - @Override - public Request zksGetTestnetPaymaster() { - return new Request<>("zks_getTestnetPaymaster", Collections.emptyList(), web3jService, ZksTestnetPaymasterAddress.class); - } - - @Override - public Request zksGetTransactionReceipt(String transactionHash) { - return new Request<>( - "eth_getTransactionReceipt", Collections.singletonList(transactionHash), web3jService, ZksGetTransactionReceipt.class); - } - - @Override - public Request zksGetTransactionDetails(String transactionHash) { - return new Request<>( - "zks_getTransactionDetails", Collections.singletonList(transactionHash), web3jService, ZksGetTransactionDetails.class); - } - - @Override - public Request zksGetTransactionByHash(String transactionHash) { - return new Request<>( - "eth_getTransactionByHash", Collections.singletonList(transactionHash), web3jService, ZksGetTransactionByHash.class); - } - - @Override - public Request zksGetLogs(EthFilter ethFilter) { - return new Request<>( - "eth_getLogs", Collections.singletonList(ethFilter), web3jService, ZksGetLogs.class); - } - - @Override - public Request zksGetBlockByHash( - String blockHash, boolean returnFullTransactionObjects) { - return new Request<>( - "eth_getBlockByHash", - Arrays.asList(blockHash, returnFullTransactionObjects), - web3jService, - ZksBlock.class); - } - - @Override - public Request zksGetBlockByNumber( - DefaultBlockParameter defaultBlockParameter, boolean returnFullTransactionObjects) { - return new Request<>( - "eth_getBlockByNumber", - Arrays.asList(defaultBlockParameter.getValue(), returnFullTransactionObjects), - web3jService, - ZksBlock.class); - } + public static final int DEFAULT_BLOCK_COMMIT_TIME = 800; + + public JsonRpc2_0ZkSync(Web3jService web3jService) { + super(web3jService); + } + + @Override + public Request zksEstimateFee(Transaction transaction) { + return new Request<>( + "zks_estimateFee", + Collections.singletonList(transaction), + web3jService, + ZksEstimateFee.class); + } + + @Override + public Request zksMainContract() { + return new Request<>( + "zks_getMainContract", Collections.emptyList(), web3jService, ZksMainContract.class); + } + + @Override + public Request zksGetConfirmedTokens(Integer from, Short limit) { + return new Request<>( + "zks_getConfirmedTokens", Arrays.asList(from, limit), web3jService, ZksTokens.class); + } + + @Override + public Request zksGetTokenPrice(String tokenAddress) { + return new Request<>( + "zks_getTokenPrice", + Collections.singletonList(tokenAddress), + web3jService, + ZksTokenPrice.class); + } + + @Override + public Request zksL1ChainId() { + return new Request<>( + "zks_L1ChainId", Collections.emptyList(), web3jService, ZksL1ChainId.class); + } + + @Override + public Request zksGetContractDebugInfo(String contractAddress) { + return new Request<>( + "zks_getContractDebugInfo", + Collections.singletonList(contractAddress), + web3jService, + ZksContractDebugInfo.class); + } + + @Override + public Request zksGetTransactionTrace(String transactionHash) { + return new Request<>( + "zks_getTransactionTrace", + Collections.singletonList(transactionHash), + web3jService, + ZksTransactionTrace.class); + } + + @Override + public Request zksGetAllAccountBalances(String address) { + return new Request<>( + "zks_getAllAccountBalances", + Collections.singletonList(address), + web3jService, + ZksAccountBalances.class); + } + + @Override + public Request zksGetBridgeContracts() { + return new Request<>( + "zks_getBridgeContracts", Collections.emptyList(), web3jService, ZksBridgeAddresses.class); + } + + @Override + public Request zksGetL2ToL1MsgProof( + Integer block, String sender, String message, @Nullable Long l2LogPosition) { + return new Request<>( + "zks_getL2ToL1MsgProof", + Arrays.asList(block, sender, message), + web3jService, + ZksMessageProof.class); + } + + @Override + public Request zksGetL2ToL1LogProof(String txHash, int index) { + return new Request<>( + "zks_getL2ToL1LogProof", Arrays.asList(txHash, index), web3jService, ZksMessageProof.class); + } + + @Override + public Request ethEstimateGas(Transaction transaction) { + return new Request<>( + "eth_estimateGas", + Collections.singletonList(transaction), + web3jService, + EthEstimateGas.class); + } + + @Override + public Request zksGetTestnetPaymaster() { + return new Request<>( + "zks_getTestnetPaymaster", + Collections.emptyList(), + web3jService, + ZksTestnetPaymasterAddress.class); + } + + @Override + public Request zksGetTransactionReceipt(String transactionHash) { + return new Request<>( + "eth_getTransactionReceipt", + Collections.singletonList(transactionHash), + web3jService, + ZksGetTransactionReceipt.class); + } + + @Override + public Request zksGetTransactionDetails(String transactionHash) { + return new Request<>( + "zks_getTransactionDetails", + Collections.singletonList(transactionHash), + web3jService, + ZksGetTransactionDetails.class); + } + + @Override + public Request zksGetTransactionByHash(String transactionHash) { + return new Request<>( + "eth_getTransactionByHash", + Collections.singletonList(transactionHash), + web3jService, + ZksGetTransactionByHash.class); + } + + @Override + public Request zksGetLogs(EthFilter ethFilter) { + return new Request<>( + "eth_getLogs", Collections.singletonList(ethFilter), web3jService, ZksGetLogs.class); + } + + @Override + public Request zksGetBlockByHash( + String blockHash, boolean returnFullTransactionObjects) { + return new Request<>( + "eth_getBlockByHash", + Arrays.asList(blockHash, returnFullTransactionObjects), + web3jService, + ZksBlock.class); + } + + @Override + public Request zksGetBlockByNumber( + DefaultBlockParameter defaultBlockParameter, boolean returnFullTransactionObjects) { + return new Request<>( + "eth_getBlockByNumber", + Arrays.asList(defaultBlockParameter.getValue(), returnFullTransactionObjects), + web3jService, + ZksBlock.class); + } } diff --git a/src/main/java/io/zksync/protocol/ZkSync.java b/src/main/java/io/zksync/protocol/ZkSync.java index 0480d23..57540ac 100755 --- a/src/main/java/io/zksync/protocol/ZkSync.java +++ b/src/main/java/io/zksync/protocol/ZkSync.java @@ -11,151 +11,156 @@ import org.web3j.protocol.core.methods.response.EthEstimateGas; public interface ZkSync extends Web3j { - static ZkSync build(Web3jService web3jService) { - return new JsonRpc2_0ZkSync(web3jService); - } - - /** - * Estimate fee for the given transaction at the moment of the latest committed - * block. - * - * @param transaction Transaction data for estimation - * @return Prepared estimate fee request - */ - Request zksEstimateFee(Transaction transaction); - - /** - * Get address of main contract for current network chain. - * - * @return Prepared main contract request - */ - Request zksMainContract(); - - /** - * Get list of the tokens supported by ZkSync. - * The tokens are returned in alphabetical order by their symbol, so basically, the token id is its position in an alphabetically sorted array of tokens. - * - * @param from Offset of tokens - * @param limit Limit of amount of tokens to return - * @return Prepared get confirmed tokens request - */ - Request zksGetConfirmedTokens(Integer from, Short limit); - - /** - * Get price of the token in USD. - * - * @param tokenAddress Address of the token in hex format - * @return Prepared get token price request - */ - Request zksGetTokenPrice(String tokenAddress); - - /** - * Get chain identifier of the L1 chain. - * - * @return Prepared l1 chainid request - */ - Request zksL1ChainId(); - - Request zksGetContractDebugInfo(String contractAddress); - - Request zksGetTransactionTrace(String transactionHash); - - /** - * Get all known balances for the given account. - * - * @param address Wallet address - * @return List of all balances where account has non-zero value - */ - Request zksGetAllAccountBalances(String address); - - /** - * Get default bridges addresses deployed on L1 and L2. - * - * @return Prepared get bridge contract request - */ - Request zksGetBridgeContracts(); - - /** - * Get the proof for the message sent via the L1Messenger system contract. - * - * @param block The number of the block where the message was emitted - * @param sender The sender of the message (i.e. the account that called the L1Messenger system contract) - * @param message The keccak256 hash of the message that was sent - * @param 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 - * @return Prepared get proof for message request - */ - Request zksGetL2ToL1MsgProof(Integer block, String sender, String message, @Nullable Long l2LogPosition); - - Request zksGetL2ToL1LogProof(String txHash, int index); - /** - * Generates and returns an estimate of how much gas is necessary to allow the transaction to complete. The transaction will not be added to the blockchain. - * - * @param transaction Transaction data for estimation - * @return Prepared estimate gas request - */ - Request ethEstimateGas(Transaction transaction); - - /** - * Get the address of the testnet paymaster: the paymaster that is available on testnets and enables paying fees in ERC-20 compatible tokens. - * - * @return Prepared get paymaster request - */ - Request zksGetTestnetPaymaster(); - - /** - * Get transaction receipt. - * The same as eth_getTransactionReceipt but with additional fields belong to L2ToL1 messenger - * See {@link io.zksync.utils.Messenger} - * - * @param transactionHash Hash of the executed transaction hash with sent message - * @return Prepared get transaction receipt request - */ - Request zksGetTransactionReceipt(String transactionHash); - - /** - * Get transaction details. - * - * @param transactionHash Hash of the executed transaction hash with sent message - * @return Prepared get transaction details request - */ - Request zksGetTransactionDetails(String transactionHash); - - /** - * Get transaction. - * - * @param transactionHash Hash of the executed transaction hash with sent message - * @return Prepared get transaction request - */ - Request zksGetTransactionByHash(String transactionHash); - - /** - * Get logs. - * - * @param ethFilter the filter options - * @return Prepared get transaction request - */ - Request zksGetLogs(EthFilter ethFilter); - - /** - * Get block by hash. - * - * @param blockHash Hash of a block - * @param returnFullTransactionObjects If true it returns the full transaction objects, - * if false only the hashes of the transactions - * @return Prepared get transaction receipt request - */ - Request zksGetBlockByHash( - String blockHash, boolean returnFullTransactionObjects); - - /** - * Get block by number. - * - * @param defaultBlockParameter integer of a block number, or the string "earliest", - * "latest" or "pending", as in the default block parameter. - * @param returnFullTransactionObjects If true it returns the full transaction objects, - * if false only the hashes of the transactions. - * @return Prepared get transaction receipt request - */ - Request zksGetBlockByNumber( - DefaultBlockParameter defaultBlockParameter, boolean returnFullTransactionObjects); -} \ No newline at end of file + static ZkSync build(Web3jService web3jService) { + return new JsonRpc2_0ZkSync(web3jService); + } + + /** + * Estimate fee for the given transaction at the moment of the latest committed block. + * + * @param transaction Transaction data for estimation + * @return Prepared estimate fee request + */ + Request zksEstimateFee(Transaction transaction); + + /** + * Get address of main contract for current network chain. + * + * @return Prepared main contract request + */ + Request zksMainContract(); + + /** + * Get list of the tokens supported by ZkSync. The tokens are returned in alphabetical order by + * their symbol, so basically, the token id is its position in an alphabetically sorted array of + * tokens. + * + * @param from Offset of tokens + * @param limit Limit of amount of tokens to return + * @return Prepared get confirmed tokens request + */ + Request zksGetConfirmedTokens(Integer from, Short limit); + + /** + * Get price of the token in USD. + * + * @param tokenAddress Address of the token in hex format + * @return Prepared get token price request + */ + Request zksGetTokenPrice(String tokenAddress); + + /** + * Get chain identifier of the L1 chain. + * + * @return Prepared l1 chainid request + */ + Request zksL1ChainId(); + + Request zksGetContractDebugInfo(String contractAddress); + + Request zksGetTransactionTrace(String transactionHash); + + /** + * Get all known balances for the given account. + * + * @param address Wallet address + * @return List of all balances where account has non-zero value + */ + Request zksGetAllAccountBalances(String address); + + /** + * Get default bridges addresses deployed on L1 and L2. + * + * @return Prepared get bridge contract request + */ + Request zksGetBridgeContracts(); + + /** + * Get the proof for the message sent via the L1Messenger system contract. + * + * @param block The number of the block where the message was emitted + * @param sender The sender of the message (i.e. the account that called the L1Messenger system + * contract) + * @param message The keccak256 hash of the message that was sent + * @param 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 + * @return Prepared get proof for message request + */ + Request zksGetL2ToL1MsgProof( + Integer block, String sender, String message, @Nullable Long l2LogPosition); + + Request zksGetL2ToL1LogProof(String txHash, int index); + + /** + * Generates and returns an estimate of how much gas is necessary to allow the transaction to + * complete. The transaction will not be added to the blockchain. + * + * @param transaction Transaction data for estimation + * @return Prepared estimate gas request + */ + Request ethEstimateGas(Transaction transaction); + + /** + * Get the address of the testnet paymaster: the paymaster that is available on testnets and + * enables paying fees in ERC-20 compatible tokens. + * + * @return Prepared get paymaster request + */ + Request zksGetTestnetPaymaster(); + + /** + * Get transaction receipt. The same as eth_getTransactionReceipt but with additional fields + * belong to L2ToL1 messenger See {@link io.zksync.utils.Messenger} + * + * @param transactionHash Hash of the executed transaction hash with sent message + * @return Prepared get transaction receipt request + */ + Request zksGetTransactionReceipt(String transactionHash); + + /** + * Get transaction details. + * + * @param transactionHash Hash of the executed transaction hash with sent message + * @return Prepared get transaction details request + */ + Request zksGetTransactionDetails(String transactionHash); + + /** + * Get transaction. + * + * @param transactionHash Hash of the executed transaction hash with sent message + * @return Prepared get transaction request + */ + Request zksGetTransactionByHash(String transactionHash); + + /** + * Get logs. + * + * @param ethFilter the filter options + * @return Prepared get transaction request + */ + Request zksGetLogs(EthFilter ethFilter); + + /** + * Get block by hash. + * + * @param blockHash Hash of a block + * @param returnFullTransactionObjects If true it returns the full transaction objects, if false + * only the hashes of the transactions + * @return Prepared get transaction receipt request + */ + Request zksGetBlockByHash(String blockHash, boolean returnFullTransactionObjects); + + /** + * Get block by number. + * + * @param defaultBlockParameter integer of a block number, or the string "earliest", "latest" or + * "pending", as in the default block parameter. + * @param returnFullTransactionObjects If true it returns the full transaction objects, if false + * only the hashes of the transactions. + * @return Prepared get transaction receipt request + */ + Request zksGetBlockByNumber( + DefaultBlockParameter defaultBlockParameter, boolean returnFullTransactionObjects); +} diff --git a/src/main/java/io/zksync/protocol/core/BridgeAddresses.java b/src/main/java/io/zksync/protocol/core/BridgeAddresses.java index b104664..cc01061 100644 --- a/src/main/java/io/zksync/protocol/core/BridgeAddresses.java +++ b/src/main/java/io/zksync/protocol/core/BridgeAddresses.java @@ -8,6 +8,6 @@ @NoArgsConstructor @Data public class BridgeAddresses { - private String l1Erc20DefaultBridge; - private String l2Erc20DefaultBridge; + private String l1Erc20DefaultBridge; + private String l2Erc20DefaultBridge; } diff --git a/src/main/java/io/zksync/protocol/core/L2ToL1MessageProof.java b/src/main/java/io/zksync/protocol/core/L2ToL1MessageProof.java index 4c14318..4864a3e 100644 --- a/src/main/java/io/zksync/protocol/core/L2ToL1MessageProof.java +++ b/src/main/java/io/zksync/protocol/core/L2ToL1MessageProof.java @@ -1,16 +1,15 @@ package io.zksync.protocol.core; +import java.util.List; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; -import java.util.List; - @AllArgsConstructor @NoArgsConstructor @Data public class L2ToL1MessageProof { - private List proof; - private Integer id; - private String root; + private List proof; + private Integer id; + private String root; } diff --git a/src/main/java/io/zksync/protocol/core/Token.java b/src/main/java/io/zksync/protocol/core/Token.java index 5655306..9490f9a 100755 --- a/src/main/java/io/zksync/protocol/core/Token.java +++ b/src/main/java/io/zksync/protocol/core/Token.java @@ -1,15 +1,13 @@ package io.zksync.protocol.core; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; - import io.zksync.utils.ZkSyncAddresses; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; - import java.math.BigDecimal; import java.math.BigInteger; import java.math.RoundingMode; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; @Data @NoArgsConstructor @@ -17,43 +15,39 @@ @JsonIgnoreProperties(ignoreUnknown = true) public class Token implements TokenId { - public static final Token ETH = createETH(); + public static final Token ETH = createETH(); - private String l1Address; + private String l1Address; - private String l2Address; + private String l2Address; - private String symbol; + private String symbol; - private Integer decimals; + private Integer decimals; - public String formatToken(BigInteger amount) { - return new BigDecimal(amount).divide(BigDecimal.TEN.pow(decimals)).toString(); - } + public String formatToken(BigInteger amount) { + return new BigDecimal(amount).divide(BigDecimal.TEN.pow(decimals)).toString(); + } - public boolean isETH() { - return l2Address.equals(ZkSyncAddresses.ETH_ADDRESS) && symbol.equals("ETH"); - } + public boolean isETH() { + return l2Address.equals(ZkSyncAddresses.ETH_ADDRESS) && symbol.equals("ETH"); + } - public BigDecimal intoDecimal(BigInteger amount) { - return new BigDecimal(amount) - .setScale(decimals) - .divide(BigDecimal.TEN.pow(decimals), RoundingMode.DOWN); - } + public BigDecimal intoDecimal(BigInteger amount) { + return new BigDecimal(amount) + .setScale(decimals) + .divide(BigDecimal.TEN.pow(decimals), RoundingMode.DOWN); + } - public BigInteger toBigInteger(BigDecimal amount) { - return amount.multiply(BigDecimal.TEN.pow(decimals)).toBigInteger(); - } + public BigInteger toBigInteger(BigDecimal amount) { + return amount.multiply(BigDecimal.TEN.pow(decimals)).toBigInteger(); + } - public BigInteger toBigInteger(double amount) { - return BigDecimal.valueOf(amount).multiply(BigDecimal.TEN.pow(decimals)).toBigInteger(); - } + public BigInteger toBigInteger(double amount) { + return BigDecimal.valueOf(amount).multiply(BigDecimal.TEN.pow(decimals)).toBigInteger(); + } - public static Token createETH() { - return new Token( - ZkSyncAddresses.ETH_ADDRESS, - ZkSyncAddresses.ETH_ADDRESS, - "ETH", - 18); - } + public static Token createETH() { + return new Token(ZkSyncAddresses.ETH_ADDRESS, ZkSyncAddresses.ETH_ADDRESS, "ETH", 18); + } } diff --git a/src/main/java/io/zksync/protocol/core/TokenId.java b/src/main/java/io/zksync/protocol/core/TokenId.java index 8e686fd..021282b 100755 --- a/src/main/java/io/zksync/protocol/core/TokenId.java +++ b/src/main/java/io/zksync/protocol/core/TokenId.java @@ -5,8 +5,7 @@ public interface TokenId { - String getSymbol(); + String getSymbol(); - BigDecimal intoDecimal(BigInteger amount); - + BigDecimal intoDecimal(BigInteger amount); } diff --git a/src/main/java/io/zksync/protocol/core/ZkBlockParameterName.java b/src/main/java/io/zksync/protocol/core/ZkBlockParameterName.java index d1aab5b..cf86b6e 100644 --- a/src/main/java/io/zksync/protocol/core/ZkBlockParameterName.java +++ b/src/main/java/io/zksync/protocol/core/ZkBlockParameterName.java @@ -1,42 +1,35 @@ package io.zksync.protocol.core; import com.fasterxml.jackson.annotation.JsonValue; - import org.web3j.protocol.core.DefaultBlockParameter; public enum ZkBlockParameterName implements DefaultBlockParameter { - /** - * Alias for BlockNumber::Latest - */ - COMMITTED("committed"), + /** Alias for BlockNumber::Latest */ + COMMITTED("committed"), - /** - * Last block that was finalized on L1 - */ - FINALIZED("finalized"); + /** Last block that was finalized on L1 */ + FINALIZED("finalized"); - private final String name; + private final String name; - ZkBlockParameterName(String name) { - this.name = name; - } + ZkBlockParameterName(String name) { + this.name = name; + } - @JsonValue - @Override - public String getValue() { - return name; - } + @JsonValue + @Override + public String getValue() { + return name; + } - public static ZkBlockParameterName fromString(String name) { - if (name != null) { - for (ZkBlockParameterName defaultBlockParameterName : - ZkBlockParameterName.values()) { - if (name.equalsIgnoreCase(defaultBlockParameterName.name)) { - return defaultBlockParameterName; - } - } + public static ZkBlockParameterName fromString(String name) { + if (name != null) { + for (ZkBlockParameterName defaultBlockParameterName : ZkBlockParameterName.values()) { + if (name.equalsIgnoreCase(defaultBlockParameterName.name)) { + return defaultBlockParameterName; } - return valueOf(name); + } } - + return valueOf(name); + } } diff --git a/src/main/java/io/zksync/protocol/core/ZkSyncNetwork.java b/src/main/java/io/zksync/protocol/core/ZkSyncNetwork.java index d14991f..fe811be 100755 --- a/src/main/java/io/zksync/protocol/core/ZkSyncNetwork.java +++ b/src/main/java/io/zksync/protocol/core/ZkSyncNetwork.java @@ -1,15 +1,18 @@ package io.zksync.protocol.core; public enum ZkSyncNetwork { - Mainnet, - Localhost, - Unknown; + Mainnet, + Localhost, + Unknown; - public long getChainId() { - switch (this) { - case Mainnet: return 1; - case Localhost: return 42; - default: throw new IllegalArgumentException("Unknown chain ID"); - } + public long getChainId() { + switch (this) { + case Mainnet: + return 1; + case Localhost: + return 42; + default: + throw new IllegalArgumentException("Unknown chain ID"); } + } } diff --git a/src/main/java/io/zksync/protocol/core/debug/ContractSourceDebugInfo.java b/src/main/java/io/zksync/protocol/core/debug/ContractSourceDebugInfo.java index da23866..d97dd12 100644 --- a/src/main/java/io/zksync/protocol/core/debug/ContractSourceDebugInfo.java +++ b/src/main/java/io/zksync/protocol/core/debug/ContractSourceDebugInfo.java @@ -1,13 +1,12 @@ package io.zksync.protocol.core.debug; import java.util.Map; - import lombok.*; @AllArgsConstructor @NoArgsConstructor @Data public class ContractSourceDebugInfo { - private String assemblyCode; - private Map pcLineMapping; + private String assemblyCode; + private Map pcLineMapping; } diff --git a/src/main/java/io/zksync/protocol/core/debug/MemoryDirection.java b/src/main/java/io/zksync/protocol/core/debug/MemoryDirection.java index f353cc7..5d9ccf0 100644 --- a/src/main/java/io/zksync/protocol/core/debug/MemoryDirection.java +++ b/src/main/java/io/zksync/protocol/core/debug/MemoryDirection.java @@ -1,6 +1,6 @@ package io.zksync.protocol.core.debug; public enum MemoryDirection { - Read, - Write + Read, + Write } diff --git a/src/main/java/io/zksync/protocol/core/debug/MemoryInteraction.java b/src/main/java/io/zksync/protocol/core/debug/MemoryInteraction.java index d059bc5..ca0e7d8 100644 --- a/src/main/java/io/zksync/protocol/core/debug/MemoryInteraction.java +++ b/src/main/java/io/zksync/protocol/core/debug/MemoryInteraction.java @@ -1,16 +1,15 @@ package io.zksync.protocol.core.debug; import java.math.BigInteger; - import lombok.*; @AllArgsConstructor @NoArgsConstructor @Data public class MemoryInteraction { - private String memoryType; - private Long page; - private Short address; - private BigInteger value; - private MemoryDirection direction; + private String memoryType; + private Long page; + private Short address; + private BigInteger value; + private MemoryDirection direction; } diff --git a/src/main/java/io/zksync/protocol/core/debug/VmDebugTrace.java b/src/main/java/io/zksync/protocol/core/debug/VmDebugTrace.java index 5644000..bc8251b 100644 --- a/src/main/java/io/zksync/protocol/core/debug/VmDebugTrace.java +++ b/src/main/java/io/zksync/protocol/core/debug/VmDebugTrace.java @@ -2,13 +2,12 @@ import java.util.List; import java.util.Map; - import lombok.*; @AllArgsConstructor @NoArgsConstructor @Data public class VmDebugTrace { - private List steps; - private Map sources; + private List steps; + private Map sources; } diff --git a/src/main/java/io/zksync/protocol/core/debug/VmExecutionStep.java b/src/main/java/io/zksync/protocol/core/debug/VmExecutionStep.java index 544c493..8bc1f6f 100644 --- a/src/main/java/io/zksync/protocol/core/debug/VmExecutionStep.java +++ b/src/main/java/io/zksync/protocol/core/debug/VmExecutionStep.java @@ -3,21 +3,20 @@ import java.math.BigInteger; import java.util.List; import java.util.Map; - import lombok.*; @AllArgsConstructor @NoArgsConstructor @Data public class VmExecutionStep { - private String contractAddress; - private Long memoryPageIndex; - private Long childMemoryIndex; - private Short pc; - private List setFlags; - private List registers; - private Map registerInteractions; - private Short sp; - private List memoryInteractions; - private String error; + private String contractAddress; + private Long memoryPageIndex; + private Long childMemoryIndex; + private Short pc; + private List setFlags; + private List registers; + private Map registerInteractions; + private Short sp; + private List memoryInteractions; + private String error; } diff --git a/src/main/java/io/zksync/protocol/exceptions/JsonRpcResponseException.java b/src/main/java/io/zksync/protocol/exceptions/JsonRpcResponseException.java index 1dc9ea6..d4bfbb0 100644 --- a/src/main/java/io/zksync/protocol/exceptions/JsonRpcResponseException.java +++ b/src/main/java/io/zksync/protocol/exceptions/JsonRpcResponseException.java @@ -2,90 +2,90 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; -import org.web3j.protocol.core.Response; - import java.util.Optional; +import org.web3j.protocol.core.Response; public class JsonRpcResponseException extends RuntimeException { - private final Optional error; - private final Optional data; - - private JsonRpcResponseException(Response response, Data data) { - super(String.format("%s: %s", - response.hasError() ? response.getError().getMessage() : "", - data != null ? data.getMessage() : "")); - - this.error = Optional.ofNullable(response.getError()); - this.data = Optional.ofNullable(data); - } - - public JsonRpcResponseException(String message) { - super(message); - this.error = Optional.empty(); - this.data = Optional.empty(); + private final Optional error; + private final Optional data; + + private JsonRpcResponseException(Response response, Data data) { + super( + String.format( + "%s: %s", + response.hasError() ? response.getError().getMessage() : "", + data != null ? data.getMessage() : "")); + + this.error = Optional.ofNullable(response.getError()); + this.data = Optional.ofNullable(data); + } + + public JsonRpcResponseException(String message) { + super(message); + this.error = Optional.empty(); + this.data = Optional.empty(); + } + + public JsonRpcResponseException(String message, Throwable cause) { + super(message, cause); + this.error = Optional.empty(); + this.data = Optional.empty(); + } + + public JsonRpcResponseException(Throwable cause) { + super(cause); + this.error = Optional.empty(); + this.data = Optional.empty(); + } + + public JsonRpcResponseException(Response response) { + this(response, response.hasError() ? parseData(response.getError().getData()) : null); + } + + public Optional getCode() { + return error.map(Response.Error::getCode); + } + + public Optional getData() { + return data; + } + + private static Data parseData(String data) { + ObjectMapper objectMapper = new ObjectMapper(); + + try { + return data != null ? objectMapper.readValue(data, Data.class) : null; + } catch (JsonProcessingException e) { + return null; } + } - public JsonRpcResponseException(String message, Throwable cause) { - super(message, cause); - this.error = Optional.empty(); - this.data = Optional.empty(); - } + public static class Data { + private int code; + private String message; - public JsonRpcResponseException(Throwable cause) { - super(cause); - this.error = Optional.empty(); - this.data = Optional.empty(); - } + public Data() {} - public JsonRpcResponseException(Response response) { - this(response, response.hasError() ? parseData(response.getError().getData()) : null); + public Data(int code, String message) { + this.code = code; + this.message = message; } - public Optional getCode() { - return error.map(Response.Error::getCode); + public int getCode() { + return code; } - public Optional getData() { - return data; + public void setCode(int code) { + this.code = code; } - private static Data parseData(String data) { - ObjectMapper objectMapper = new ObjectMapper(); - - try { - return data != null ? objectMapper.readValue(data, Data.class) : null; - } catch (JsonProcessingException e) { - return null; - } + public String getMessage() { + return message; } - public static class Data { - private int code; - private String message; - - public Data() { - } - - public Data(int code, String message) { - this.code = code; - this.message = message; - } - - public int getCode() { - return code; - } - - public void setCode(int code) { - this.code = code; - } - - public String getMessage() { - return message; - } - - public void setMessage(String message) { - this.message = message; - } + public void setMessage(String message) { + this.message = message; } + } } diff --git a/src/main/java/io/zksync/protocol/provider/DefaultEthereumProvider.java b/src/main/java/io/zksync/protocol/provider/DefaultEthereumProvider.java index a9d7795..626d5d0 100755 --- a/src/main/java/io/zksync/protocol/provider/DefaultEthereumProvider.java +++ b/src/main/java/io/zksync/protocol/provider/DefaultEthereumProvider.java @@ -1,5 +1,9 @@ package io.zksync.protocol.provider; +import static io.zksync.utils.ZkSyncAddresses.L2_ETH_TOKEN_ADDRESS; +import static io.zksync.utils.ZkSyncAddresses.MESSENGER_ADDRESS; +import static io.zksync.wrappers.L1Messenger.L1MESSAGESENT_EVENT; + import io.zksync.methods.response.L2toL1Log; import io.zksync.methods.response.ZkTransactionReceipt; import io.zksync.protocol.ZkSync; @@ -9,6 +13,10 @@ import io.zksync.wrappers.IL1Bridge; import io.zksync.wrappers.IL2Bridge; import io.zksync.wrappers.ZkSyncContract; +import java.math.BigDecimal; +import java.math.BigInteger; +import java.util.*; +import java.util.concurrent.CompletableFuture; import lombok.RequiredArgsConstructor; import org.jetbrains.annotations.Nullable; import org.web3j.abi.EventValues; @@ -26,218 +34,284 @@ import org.web3j.utils.Convert.Unit; import org.web3j.utils.Numeric; -import java.math.BigDecimal; -import java.math.BigInteger; -import java.util.*; -import java.util.concurrent.CompletableFuture; - -import static io.zksync.utils.ZkSyncAddresses.L2_ETH_TOKEN_ADDRESS; -import static io.zksync.utils.ZkSyncAddresses.MESSENGER_ADDRESS; -import static io.zksync.wrappers.L1Messenger.L1MESSAGESENT_EVENT; - @RequiredArgsConstructor public class DefaultEthereumProvider implements EthereumProvider { - private static final HashMap GAS_LIMITS; + private static final HashMap GAS_LIMITS; - private static final BigInteger MAX_APPROVE_AMOUNT = BigInteger.valueOf(2).pow(256).subtract(BigInteger.ONE); - private static final BigInteger DEFAULT_THRESHOLD = BigInteger.valueOf(2).pow(255); - private static final ContractGasProvider DEFAULT_GAS_PROVIDER = new StaticGasProvider(BigInteger.ZERO, - BigInteger.ZERO); + private static final BigInteger MAX_APPROVE_AMOUNT = + BigInteger.valueOf(2).pow(256).subtract(BigInteger.ONE); + private static final BigInteger DEFAULT_THRESHOLD = BigInteger.valueOf(2).pow(255); + private static final ContractGasProvider DEFAULT_GAS_PROVIDER = + new StaticGasProvider(BigInteger.ZERO, BigInteger.ZERO); - private static final BigInteger L1_TO_L2_GAS_PER_PUBDATA = BigInteger.valueOf(800); + private static final BigInteger L1_TO_L2_GAS_PER_PUBDATA = BigInteger.valueOf(800); - private final Web3j web3j; - private final ZkSync zkSync; - private final TransactionManager transactionManager; - private final ContractGasProvider gasProvider; - private final ZkSyncContract contract; - private final IL1Bridge l1ERC20Bridge; + private final Web3j web3j; + private final ZkSync zkSync; + private final TransactionManager transactionManager; + private final ContractGasProvider gasProvider; + private final ZkSyncContract contract; + private final IL1Bridge l1ERC20Bridge; - public CompletableFuture getGasPrice() { - return web3j.ethGasPrice() - .sendAsync() - .thenApply(EthGasPrice::getGasPrice); - } + public CompletableFuture getGasPrice() { + return web3j.ethGasPrice().sendAsync().thenApply(EthGasPrice::getGasPrice); + } - @Override - public CompletableFuture approveDeposits(Token token, Optional limit) { - ERC20 tokenContract = ERC20.load(token.getL1Address(), web3j, transactionManager, - gasProvider); - return tokenContract.approve(l1ERC20BridgeAddress(), limit.orElse(MAX_APPROVE_AMOUNT)).sendAsync(); - } + @Override + public CompletableFuture approveDeposits( + Token token, Optional limit) { + ERC20 tokenContract = ERC20.load(token.getL1Address(), web3j, transactionManager, gasProvider); + return tokenContract + .approve(l1ERC20BridgeAddress(), limit.orElse(MAX_APPROVE_AMOUNT)) + .sendAsync(); + } - @Override - public CompletableFuture transfer(Token token, BigInteger amount, String to) { - if (token.isETH()) { - Transfer transfer = new Transfer(web3j, transactionManager); - return transfer.sendFunds(to, new BigDecimal(amount), Unit.WEI).sendAsync(); - } else { - ERC20 tokenContract = ERC20.load(token.getL1Address(), web3j, transactionManager, - gasProvider); - return tokenContract.transfer(to, amount).sendAsync(); - } + @Override + public CompletableFuture transfer(Token token, BigInteger amount, String to) { + if (token.isETH()) { + Transfer transfer = new Transfer(web3j, transactionManager); + return transfer.sendFunds(to, new BigDecimal(amount), Unit.WEI).sendAsync(); + } else { + ERC20 tokenContract = + ERC20.load(token.getL1Address(), web3j, transactionManager, gasProvider); + return tokenContract.transfer(to, amount).sendAsync(); } + } - @Override - public CompletableFuture getBaseCost(BigInteger gasLimit, BigInteger gasPerPubdataByte, @Nullable BigInteger gasPrice) { - if (gasPrice != null) { - return contract.l2TransactionBaseCost(gasPrice, gasLimit, gasPerPubdataByte).sendAsync(); - } else { - return getGasPrice() - .thenCompose(g -> contract.l2TransactionBaseCost(g, gasLimit, gasPerPubdataByte).sendAsync()); - } + @Override + public CompletableFuture getBaseCost( + BigInteger gasLimit, BigInteger gasPerPubdataByte, @Nullable BigInteger gasPrice) { + if (gasPrice != null) { + return contract.l2TransactionBaseCost(gasPrice, gasLimit, gasPerPubdataByte).sendAsync(); + } else { + return getGasPrice() + .thenCompose( + g -> contract.l2TransactionBaseCost(g, gasLimit, gasPerPubdataByte).sendAsync()); } + } - @Override - public CompletableFuture requestExecute(String contractAddress, BigInteger l2Value, byte[] calldata, BigInteger gasLimit, @Nullable byte[][] factoryDeps, @Nullable BigInteger operatorTips, @Nullable BigInteger gasPrice, String refundRecipient) { - return CompletableFuture.supplyAsync(() -> { - BigInteger gasPriceValue = gasPrice == null ? getGasPrice().join() : gasPrice; - List factoryDepsList = factoryDeps == null ? Collections.emptyList() : Arrays.asList(factoryDeps); - BigInteger operatorTipsValue = operatorTips == null ? BigInteger.ZERO : operatorTips; - BigInteger baseCost = getBaseCost(gasLimit, L1_TO_L2_GAS_PER_PUBDATA, gasPriceValue).join(); - BigInteger totalValue = l2Value.add(baseCost).add(operatorTipsValue); - return contract.requestL2Transaction(contractAddress, l2Value, calldata, gasLimit, L1_TO_L2_GAS_PER_PUBDATA, factoryDepsList, refundRecipient, totalValue).sendAsync().join(); + @Override + public CompletableFuture requestExecute( + String contractAddress, + BigInteger l2Value, + byte[] calldata, + BigInteger gasLimit, + @Nullable byte[][] factoryDeps, + @Nullable BigInteger operatorTips, + @Nullable BigInteger gasPrice, + String refundRecipient) { + return CompletableFuture.supplyAsync( + () -> { + BigInteger gasPriceValue = gasPrice == null ? getGasPrice().join() : gasPrice; + List factoryDepsList = + factoryDeps == null ? Collections.emptyList() : Arrays.asList(factoryDeps); + BigInteger operatorTipsValue = operatorTips == null ? BigInteger.ZERO : operatorTips; + BigInteger baseCost = + getBaseCost(gasLimit, L1_TO_L2_GAS_PER_PUBDATA, gasPriceValue).join(); + BigInteger totalValue = l2Value.add(baseCost).add(operatorTipsValue); + return contract + .requestL2Transaction( + contractAddress, + l2Value, + calldata, + gasLimit, + L1_TO_L2_GAS_PER_PUBDATA, + factoryDepsList, + refundRecipient, + totalValue) + .sendAsync() + .join(); }); - } + } - @Override - public CompletableFuture deposit(Token token, BigInteger amount, BigInteger operatorTips, String userAddress) { - return CompletableFuture.supplyAsync(() -> { - BigInteger baseCost = BigInteger.ZERO; - if (token.isETH()) { - BigInteger gasLimit = BigInteger.valueOf(10000000); - return requestExecute(userAddress, amount, DynamicBytes.DEFAULT.getValue(), gasLimit, null, operatorTips, null, userAddress).join(); - } else { - BigInteger gasLimit = GAS_LIMITS.getOrDefault(token.getL1Address(), BigInteger.valueOf(300000)); - BigInteger totalAmount = operatorTips.add(baseCost); - return l1ERC20Bridge.deposit(userAddress, token.getL1Address(), gasLimit, L1_TO_L2_GAS_PER_PUBDATA, amount, totalAmount).sendAsync().join(); - } + @Override + public CompletableFuture deposit( + Token token, BigInteger amount, BigInteger operatorTips, String userAddress) { + return CompletableFuture.supplyAsync( + () -> { + BigInteger baseCost = BigInteger.ZERO; + if (token.isETH()) { + BigInteger gasLimit = BigInteger.valueOf(10000000); + return requestExecute( + userAddress, + amount, + DynamicBytes.DEFAULT.getValue(), + gasLimit, + null, + operatorTips, + null, + userAddress) + .join(); + } else { + BigInteger gasLimit = + GAS_LIMITS.getOrDefault(token.getL1Address(), BigInteger.valueOf(300000)); + BigInteger totalAmount = operatorTips.add(baseCost); + return l1ERC20Bridge + .deposit( + userAddress, + token.getL1Address(), + gasLimit, + L1_TO_L2_GAS_PER_PUBDATA, + amount, + totalAmount) + .sendAsync() + .join(); + } }); - } - - @Override - public CompletableFuture withdraw(Token token, BigInteger amount, String userAddress) { -// return contract.requestWithdraw(token.getAddress(), amount, userAddress, PriorityQueueType.Deque.getValue(), PriorityOpTree.Full.getValue()).sendAsync(); - throw new UnsupportedOperationException(); - } + } - @Override - public TransactionReceipt finalizeWithdraw(String txHash, int index) throws Exception { - try { - Thread.sleep(10000); - } catch (InterruptedException e) { - throw new RuntimeException(e); - } - ZkTransactionReceipt receipt = zkSync.zksGetTransactionReceipt(txHash).sendAsync().join().getResult(); + @Override + public CompletableFuture withdraw( + Token token, BigInteger amount, String userAddress) { + // return contract.requestWithdraw(token.getAddress(), amount, userAddress, + // PriorityQueueType.Deque.getValue(), PriorityOpTree.Full.getValue()).sendAsync(); + throw new UnsupportedOperationException(); + } - int logIndex = getWithdrawalLogIndex(receipt.getLogs(), index); - Log log = receipt.getLogs().get(logIndex); + @Override + public TransactionReceipt finalizeWithdraw(String txHash, int index) throws Exception { + try { + Thread.sleep(10000); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } + ZkTransactionReceipt receipt = + zkSync.zksGetTransactionReceipt(txHash).sendAsync().join().getResult(); - int l2ToL1LogIndex = getWithdrawalL2ToL1LogIndex(receipt.getl2ToL1Logs(), index); - L2ToL1MessageProof l2ToL1MessageProof = zkSync.zksGetL2ToL1LogProof(txHash, l2ToL1LogIndex).sendAsync().join().getResult(); + int logIndex = getWithdrawalLogIndex(receipt.getLogs(), index); + Log log = receipt.getLogs().get(logIndex); - EventValues eventValues = Contract.staticExtractEventParameters(L1MESSAGESENT_EVENT, log); - byte[] bytes_data = (byte[]) eventValues.getNonIndexedValues().get(0).getValue(); + int l2ToL1LogIndex = getWithdrawalL2ToL1LogIndex(receipt.getl2ToL1Logs(), index); + L2ToL1MessageProof l2ToL1MessageProof = + zkSync.zksGetL2ToL1LogProof(txHash, l2ToL1LogIndex).sendAsync().join().getResult(); - BigInteger l1BatchNumber = receipt.getL1BatchNumber(); + EventValues eventValues = Contract.staticExtractEventParameters(L1MESSAGESENT_EVENT, log); + byte[] bytes_data = (byte[]) eventValues.getNonIndexedValues().get(0).getValue(); - List merkle_proof = new ArrayList<>(); - for (int i = 0 ; i < l2ToL1MessageProof.getProof().size() ; i++){ - merkle_proof.add(Numeric.hexStringToByteArray(l2ToL1MessageProof.getProof().get(i))); - } - String sender = log.getTopics().get(1); + BigInteger l1BatchNumber = receipt.getL1BatchNumber(); - if (sender.equals(L2_ETH_TOKEN_ADDRESS)){ - return contract.finalizeEthWithdrawal(l1BatchNumber, BigInteger.valueOf(l2ToL1MessageProof.getId()), receipt.getL1BatchTxIndex(), bytes_data, merkle_proof).sendAsync().join(); - } - IL2Bridge il2Bridge = IL2Bridge.load(sender, web3j, transactionManager, gasProvider); - IL1Bridge il1Bridge = IL1Bridge.load(il2Bridge.l1Bridge().send(), web3j, transactionManager, gasProvider); + List merkle_proof = new ArrayList<>(); + for (int i = 0; i < l2ToL1MessageProof.getProof().size(); i++) { + merkle_proof.add(Numeric.hexStringToByteArray(l2ToL1MessageProof.getProof().get(i))); + } + String sender = log.getTopics().get(1); - return il1Bridge.finalizeWithdrawal(l1BatchNumber, BigInteger.valueOf(l2ToL1MessageProof.getId()), receipt.getL1BatchTxIndex(), bytes_data, merkle_proof).sendAsync().join(); + if (sender.equals(L2_ETH_TOKEN_ADDRESS)) { + return contract + .finalizeEthWithdrawal( + l1BatchNumber, + BigInteger.valueOf(l2ToL1MessageProof.getId()), + receipt.getL1BatchTxIndex(), + bytes_data, + merkle_proof) + .sendAsync() + .join(); } + IL2Bridge il2Bridge = IL2Bridge.load(sender, web3j, transactionManager, gasProvider); + IL1Bridge il1Bridge = + IL1Bridge.load(il2Bridge.l1Bridge().send(), web3j, transactionManager, gasProvider); - public int getWithdrawalLogIndex(List logs, int index){ - String topic = "L1MessageSent(address,bytes32,bytes)"; - List logIndex = new ArrayList<>(); + return il1Bridge + .finalizeWithdrawal( + l1BatchNumber, + BigInteger.valueOf(l2ToL1MessageProof.getId()), + receipt.getL1BatchTxIndex(), + bytes_data, + merkle_proof) + .sendAsync() + .join(); + } - for (int i = 0 ; i < logs.size() ; i++){ - if (logs.get(i).getAddress().equals(MESSENGER_ADDRESS) && Arrays.equals(logs.get(i).getTopics().get(0).getBytes(), Hash.sha3String(topic).getBytes())){ - logIndex.add(i); - } - } + public int getWithdrawalLogIndex(List logs, int index) { + String topic = "L1MessageSent(address,bytes32,bytes)"; + List logIndex = new ArrayList<>(); - return logIndex.get(index); + for (int i = 0; i < logs.size(); i++) { + if (logs.get(i).getAddress().equals(MESSENGER_ADDRESS) + && Arrays.equals( + logs.get(i).getTopics().get(0).getBytes(), Hash.sha3String(topic).getBytes())) { + logIndex.add(i); + } } - public int getWithdrawalL2ToL1LogIndex(List logs, int index){ - List logIndex = new ArrayList<>(); + return logIndex.get(index); + } - for (int i = 0 ; i < logs.size() ; i++){ - if (logs.get(i).getSender().getValue().equals(MESSENGER_ADDRESS)){ - logIndex.add(i); - } - } + public int getWithdrawalL2ToL1LogIndex(List logs, int index) { + List logIndex = new ArrayList<>(); - return logIndex.get(index); - } - @Override - public CompletableFuture isDepositApproved(Token token, String to, Optional threshold) { - ERC20 tokenContract = ERC20.load(token.getL1Address(), web3j, transactionManager, - DEFAULT_GAS_PROVIDER); - return tokenContract.allowance(to, l1ERC20BridgeAddress()).sendAsync() - .thenApply(allowance -> allowance.compareTo(threshold.orElse(DEFAULT_THRESHOLD)) >= 0); + for (int i = 0; i < logs.size(); i++) { + if (logs.get(i).getSender().getValue().equals(MESSENGER_ADDRESS)) { + logIndex.add(i); + } } - @Override - public String l1ERC20BridgeAddress() { - return l1ERC20Bridge.getContractAddress(); - } + return logIndex.get(index); + } + + @Override + public CompletableFuture isDepositApproved( + Token token, String to, Optional threshold) { + ERC20 tokenContract = + ERC20.load(token.getL1Address(), web3j, transactionManager, DEFAULT_GAS_PROVIDER); + return tokenContract + .allowance(to, l1ERC20BridgeAddress()) + .sendAsync() + .thenApply(allowance -> allowance.compareTo(threshold.orElse(DEFAULT_THRESHOLD)) >= 0); + } - static { - //{ - // "0x0000000000095413afc295d19edeb1ad7b71c952": 140000, - // "0xeb4c2781e4eba804ce9a9803c67d0893436bb27d": 160000, - // "0xbbbbca6a901c926f240b89eacb641d8aec7aeafd": 140000, - // "0xb64ef51c888972c908cfacf59b47c1afbc0ab8ac": 140000, - // "0x1f9840a85d5af5bf1d1762f925bdaddc4201f984": 150000, - // "0x9ba00d6856a4edf4665bca2c2309936572473b7e": 270000, - // "0x8daebade922df735c38c80c7ebd708af50815faa": 140000, - // "0x0d8775f648430679a709e98d2b0cb6250d2887ef": 140000, - // "0xdac17f958d2ee523a2206206994597c13d831ec7": 140000, - // "0x6de037ef9ad2725eb40118bb1702ebb27e4aeb24": 150000, - // "0x056fd409e1d7a124bd7017459dfea2f387b6d5cd": 180000, - // "0x0f5d2fb29fb7d3cfee444a200298f468908cc942": 140000, - // "0x514910771af9ca656af840dff83e8264ecf986ca": 140000, - // "0x1985365e9f78359a9b6ad760e32412f4a445e862": 180000, - // "0x2260fac5e5542a773aa44fbcfedf7c193bc2c599": 140000, - // "0xe41d2489571d322189246dafa5ebde1f4699f498": 140000, - // "0x6b175474e89094c44da98b954eedeac495271d0f": 140000, - // "0xaaaebe6fe48e54f431b0c390cfaf0b017d09d42d": 150000, - // "0x2b591e99afe9f32eaa6214f7b7629768c40eeb39": 140000, - // "0x65ece136b89ebaa72a7f7aa815674946e44ca3f9": 140000, - // "0x0000000000085d4780b73119b644ae5ecd22b376": 150000, - // "0xdb25f211ab05b1c97d595516f45794528a807ad8": 180000, - // "0x408e41876cccdc0f92210600ef50372656052a38": 140000, - // "0x15a2b3cfafd696e1c783fe99eed168b78a3a371e": 160000, - // "0x38e4adb44ef08f22f5b5b76a8f0c2d0dcbe7dca1": 160000, - // "0x3108ccfd96816f9e663baa0e8c5951d229e8c6da": 140000, - // "0x56d811088235f11c8920698a204a5010a788f4b3": 240000, - // "0x57ab1ec28d129707052df4df418d58a2d46d5f51": 220000, - // "0x9f8f72aa9304c8b593d555f12ef6589cc3a579a2": 140000, - // "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48": 150000, - // "0xc011a73ee8576fb46f5e1c5751ca3b9fe0af2a6f": 200000, - // "0x744d70fdbe2ba4cf95131626614a1763df805b9e": 230000, - // "0x0bc529c00c6401aef6d220be8c6ea1667f6ad93e": 140000, - // "0x4c7065bca76fe44afb0d16c2441b1e6e163354e2": 250000, - // "0xdd974d5c2e2928dea5f71b9825b8b646686bd200": 140000, - // "0x80fb784b7ed66730e8b1dbd9820afd29931aab03": 140000, - // "0xd56dac73a4d6766464b38ec6d91eb45ce7457c44": 140000, - // "0x4fabb145d64652a948d72533023f6e7a623c7c53": 150000, - // "0x38a2fdc11f526ddd5a607c1f251c065f40fbf2f7": 140000, - // "0x7dd9c5cba05e151c895fde1cf355c9a1d5da6429": 140000 - //} - GAS_LIMITS = new HashMap() {{ + @Override + public String l1ERC20BridgeAddress() { + return l1ERC20Bridge.getContractAddress(); + } + + static { + // { + // "0x0000000000095413afc295d19edeb1ad7b71c952": 140000, + // "0xeb4c2781e4eba804ce9a9803c67d0893436bb27d": 160000, + // "0xbbbbca6a901c926f240b89eacb641d8aec7aeafd": 140000, + // "0xb64ef51c888972c908cfacf59b47c1afbc0ab8ac": 140000, + // "0x1f9840a85d5af5bf1d1762f925bdaddc4201f984": 150000, + // "0x9ba00d6856a4edf4665bca2c2309936572473b7e": 270000, + // "0x8daebade922df735c38c80c7ebd708af50815faa": 140000, + // "0x0d8775f648430679a709e98d2b0cb6250d2887ef": 140000, + // "0xdac17f958d2ee523a2206206994597c13d831ec7": 140000, + // "0x6de037ef9ad2725eb40118bb1702ebb27e4aeb24": 150000, + // "0x056fd409e1d7a124bd7017459dfea2f387b6d5cd": 180000, + // "0x0f5d2fb29fb7d3cfee444a200298f468908cc942": 140000, + // "0x514910771af9ca656af840dff83e8264ecf986ca": 140000, + // "0x1985365e9f78359a9b6ad760e32412f4a445e862": 180000, + // "0x2260fac5e5542a773aa44fbcfedf7c193bc2c599": 140000, + // "0xe41d2489571d322189246dafa5ebde1f4699f498": 140000, + // "0x6b175474e89094c44da98b954eedeac495271d0f": 140000, + // "0xaaaebe6fe48e54f431b0c390cfaf0b017d09d42d": 150000, + // "0x2b591e99afe9f32eaa6214f7b7629768c40eeb39": 140000, + // "0x65ece136b89ebaa72a7f7aa815674946e44ca3f9": 140000, + // "0x0000000000085d4780b73119b644ae5ecd22b376": 150000, + // "0xdb25f211ab05b1c97d595516f45794528a807ad8": 180000, + // "0x408e41876cccdc0f92210600ef50372656052a38": 140000, + // "0x15a2b3cfafd696e1c783fe99eed168b78a3a371e": 160000, + // "0x38e4adb44ef08f22f5b5b76a8f0c2d0dcbe7dca1": 160000, + // "0x3108ccfd96816f9e663baa0e8c5951d229e8c6da": 140000, + // "0x56d811088235f11c8920698a204a5010a788f4b3": 240000, + // "0x57ab1ec28d129707052df4df418d58a2d46d5f51": 220000, + // "0x9f8f72aa9304c8b593d555f12ef6589cc3a579a2": 140000, + // "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48": 150000, + // "0xc011a73ee8576fb46f5e1c5751ca3b9fe0af2a6f": 200000, + // "0x744d70fdbe2ba4cf95131626614a1763df805b9e": 230000, + // "0x0bc529c00c6401aef6d220be8c6ea1667f6ad93e": 140000, + // "0x4c7065bca76fe44afb0d16c2441b1e6e163354e2": 250000, + // "0xdd974d5c2e2928dea5f71b9825b8b646686bd200": 140000, + // "0x80fb784b7ed66730e8b1dbd9820afd29931aab03": 140000, + // "0xd56dac73a4d6766464b38ec6d91eb45ce7457c44": 140000, + // "0x4fabb145d64652a948d72533023f6e7a623c7c53": 150000, + // "0x38a2fdc11f526ddd5a607c1f251c065f40fbf2f7": 140000, + // "0x7dd9c5cba05e151c895fde1cf355c9a1d5da6429": 140000 + // } + GAS_LIMITS = + new HashMap() { + { put("0x0000000000095413afc295d19edeb1ad7b71c952", BigInteger.valueOf(140000)); put("0xeb4c2781e4eba804ce9a9803c67d0893436bb27d", BigInteger.valueOf(160000)); put("0xbbbbca6a901c926f240b89eacb641d8aec7aeafd", BigInteger.valueOf(140000)); @@ -278,6 +352,7 @@ public String l1ERC20BridgeAddress() { put("0x4fabb145d64652a948d72533023f6e7a623c7c53", BigInteger.valueOf(150000)); put("0x38a2fdc11f526ddd5a607c1f251c065f40fbf2f7", BigInteger.valueOf(140000)); put("0x7dd9c5cba05e151c895fde1cf355c9a1d5da6429", BigInteger.valueOf(140000)); - }}; - } + } + }; + } } diff --git a/src/main/java/io/zksync/protocol/provider/EthereumProvider.java b/src/main/java/io/zksync/protocol/provider/EthereumProvider.java index 1875cac..a20da20 100755 --- a/src/main/java/io/zksync/protocol/provider/EthereumProvider.java +++ b/src/main/java/io/zksync/protocol/provider/EthereumProvider.java @@ -1,117 +1,138 @@ package io.zksync.protocol.provider; -import java.math.BigInteger; -import java.util.Optional; -import java.util.concurrent.CompletableFuture; - -import io.zksync.methods.response.ZksMainContract; +import io.zksync.protocol.ZkSync; import io.zksync.protocol.core.BridgeAddresses; -import io.zksync.protocol.exceptions.JsonRpcResponseException; +import io.zksync.protocol.core.Token; import io.zksync.wrappers.IL1Bridge; import io.zksync.wrappers.ZkSyncContract; +import java.math.BigInteger; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; import org.jetbrains.annotations.Nullable; import org.web3j.protocol.Web3j; import org.web3j.protocol.core.methods.response.TransactionReceipt; import org.web3j.tx.TransactionManager; import org.web3j.tx.gas.ContractGasProvider; -import io.zksync.protocol.ZkSync; -import io.zksync.protocol.core.Token; - - public interface EthereumProvider { - /** - * Send approve transaction to token contract. - * - * @param token - Token object supported by ZkSync - * @param limit - Maximum amount to approve for ZkSync contract - * @return CompletableFuture for waiting for transaction mine - */ - CompletableFuture approveDeposits(Token token, Optional limit); - - /** - * Send transfer transaction. This is the regular transfer of ERC20 token - * - * @param token - Token object supported by ZkSync - * @param amount - Amount tokens to transfer - * @param to - Address of receiver tokens - * @return CompletableFuture for waiting for transaction mine - */ - CompletableFuture transfer(Token token, BigInteger amount, String to); - - /** - * Get base cost for L2 transaction. - * @param gasLimit - Gas limit for L2 transaction - * @param gasPerPubdataByte - Gas per pubdata byte - * @param gasPrice - Gas price for L2 transaction - * @return CompletableFuture for waiting for transaction mine - */ - CompletableFuture getBaseCost(BigInteger gasLimit, BigInteger gasPerPubdataByte, @Nullable BigInteger gasPrice); - -/** - * Send request execute transaction to ZkSync contract. - * - * @param contractAddress - Address of contract to call - * @param l2Value - Value to send to contract - * @param calldata - Calldata to send to contract - * @param gasLimit - Gas limit for L2 transaction - * @param factoryDeps - Factory dependencies - * @param operatorTips - Tips for operator on L2 that executes deposit - * @param gasPrice - Gas price for L2 transaction - * @param refundRecipient - Address of L2 receiver refund in ZkSync - * @return CompletableFuture for waiting for transaction mine - */ - CompletableFuture requestExecute(String contractAddress, BigInteger l2Value, byte[] calldata, BigInteger gasLimit, @Nullable byte[][] factoryDeps, @Nullable BigInteger operatorTips, @Nullable BigInteger gasPrice, String refundRecipient); - - /** - * Send deposit transaction to ZkSync contract. For ERC20 token must be approved before. @see EthereumProvider.approveDepodits - * - * @param token - Token object supported by ZkSync - * @param amount - Amount tokens to transfer - * @param operatorTips - Tips for operator on L2 that executes deposit - * @param userAddress - Address of L2 receiver deposit in ZkSync - * @return CompletableFuture for waiting for transaction mine - */ - - CompletableFuture deposit(Token token, BigInteger amount, BigInteger operatorTips, String userAddress); - - /** - * Send withdraw transaction to ZkSync contract. - * - * @param token - Token object supported by ZkSync - * @param amount - Amount tokens to transfer - * @param userAddress - Address of L1 receiver withdraw in ZkSync - * @return CompletableFuture for waiting for transaction mine - */ - CompletableFuture withdraw(Token token, BigInteger amount, String userAddress); - TransactionReceipt finalizeWithdraw(String txHash, int index) throws Exception; - - /** - * Check if deposit is approved in enough amount - * - * @param token - Token object supported by ZkSync - * @param to - Address of the account who can deposit tokens from yours - * @param threshold - Minimum threshold of approved tokens - * @return CompletableFuture of blockchain smart-contract call - */ - CompletableFuture isDepositApproved(Token token, String to, Optional threshold); - - /** - * Get ZkSync Bridge for ERC20 smart-contract address in Ethereum blockchain - * - * @return Contract address in hex string - */ - String l1ERC20BridgeAddress(); - - static CompletableFuture load(ZkSync zksync, Web3j ethereum, TransactionManager transactionManager, ContractGasProvider gasProvider) { - return CompletableFuture.supplyAsync(() -> { - BridgeAddresses bridgeAddresses = zksync.zksGetBridgeContracts().sendAsync().join().getResult(); - String mainContract = zksync.zksMainContract().sendAsync().join().getResult(); - IL1Bridge erc20Bridge = IL1Bridge.load(bridgeAddresses.getL1Erc20DefaultBridge(), ethereum, transactionManager, gasProvider); - ZkSyncContract zkSyncContract = ZkSyncContract.load(mainContract, ethereum, transactionManager, gasProvider); - return new DefaultEthereumProvider(ethereum,zksync, transactionManager, gasProvider, zkSyncContract, erc20Bridge); + /** + * Send approve transaction to token contract. + * + * @param token - Token object supported by ZkSync + * @param limit - Maximum amount to approve for ZkSync contract + * @return CompletableFuture for waiting for transaction mine + */ + CompletableFuture approveDeposits(Token token, Optional limit); + + /** + * Send transfer transaction. This is the regular transfer of ERC20 token + * + * @param token - Token object supported by ZkSync + * @param amount - Amount tokens to transfer + * @param to - Address of receiver tokens + * @return CompletableFuture for waiting for transaction mine + */ + CompletableFuture transfer(Token token, BigInteger amount, String to); + + /** + * Get base cost for L2 transaction. + * + * @param gasLimit - Gas limit for L2 transaction + * @param gasPerPubdataByte - Gas per pubdata byte + * @param gasPrice - Gas price for L2 transaction + * @return CompletableFuture for waiting for transaction mine + */ + CompletableFuture getBaseCost( + BigInteger gasLimit, BigInteger gasPerPubdataByte, @Nullable BigInteger gasPrice); + + /** + * Send request execute transaction to ZkSync contract. + * + * @param contractAddress - Address of contract to call + * @param l2Value - Value to send to contract + * @param calldata - Calldata to send to contract + * @param gasLimit - Gas limit for L2 transaction + * @param factoryDeps - Factory dependencies + * @param operatorTips - Tips for operator on L2 that executes deposit + * @param gasPrice - Gas price for L2 transaction + * @param refundRecipient - Address of L2 receiver refund in ZkSync + * @return CompletableFuture for waiting for transaction mine + */ + CompletableFuture requestExecute( + String contractAddress, + BigInteger l2Value, + byte[] calldata, + BigInteger gasLimit, + @Nullable byte[][] factoryDeps, + @Nullable BigInteger operatorTips, + @Nullable BigInteger gasPrice, + String refundRecipient); + + /** + * Send deposit transaction to ZkSync contract. For ERC20 token must be approved before. @see + * EthereumProvider.approveDepodits + * + * @param token - Token object supported by ZkSync + * @param amount - Amount tokens to transfer + * @param operatorTips - Tips for operator on L2 that executes deposit + * @param userAddress - Address of L2 receiver deposit in ZkSync + * @return CompletableFuture for waiting for transaction mine + */ + CompletableFuture deposit( + Token token, BigInteger amount, BigInteger operatorTips, String userAddress); + + /** + * Send withdraw transaction to ZkSync contract. + * + * @param token - Token object supported by ZkSync + * @param amount - Amount tokens to transfer + * @param userAddress - Address of L1 receiver withdraw in ZkSync + * @return CompletableFuture for waiting for transaction mine + */ + CompletableFuture withdraw( + Token token, BigInteger amount, String userAddress); + + TransactionReceipt finalizeWithdraw(String txHash, int index) throws Exception; + + /** + * Check if deposit is approved in enough amount + * + * @param token - Token object supported by ZkSync + * @param to - Address of the account who can deposit tokens from yours + * @param threshold - Minimum threshold of approved tokens + * @return CompletableFuture of blockchain smart-contract call + */ + CompletableFuture isDepositApproved( + Token token, String to, Optional threshold); + + /** + * Get ZkSync Bridge for ERC20 smart-contract address in Ethereum blockchain + * + * @return Contract address in hex string + */ + String l1ERC20BridgeAddress(); + + static CompletableFuture load( + ZkSync zksync, + Web3j ethereum, + TransactionManager transactionManager, + ContractGasProvider gasProvider) { + return CompletableFuture.supplyAsync( + () -> { + BridgeAddresses bridgeAddresses = + zksync.zksGetBridgeContracts().sendAsync().join().getResult(); + String mainContract = zksync.zksMainContract().sendAsync().join().getResult(); + IL1Bridge erc20Bridge = + IL1Bridge.load( + bridgeAddresses.getL1Erc20DefaultBridge(), + ethereum, + transactionManager, + gasProvider); + ZkSyncContract zkSyncContract = + ZkSyncContract.load(mainContract, ethereum, transactionManager, gasProvider); + return new DefaultEthereumProvider( + ethereum, zksync, transactionManager, gasProvider, zkSyncContract, erc20Bridge); }); - } - + } } diff --git a/src/main/java/io/zksync/transaction/TransactionDetails.java b/src/main/java/io/zksync/transaction/TransactionDetails.java index b050557..05a7fdb 100644 --- a/src/main/java/io/zksync/transaction/TransactionDetails.java +++ b/src/main/java/io/zksync/transaction/TransactionDetails.java @@ -1,95 +1,107 @@ package io.zksync.transaction; -import org.web3j.utils.Numeric; - import java.math.BigInteger; import java.util.Date; +import org.web3j.utils.Numeric; public class TransactionDetails { - private boolean isL1Originated; - private TransactionStatus status; - private String fee; - private String initiatorAddress; - private Date receivedAt; - private String ethCommitTxHash; - private String ethProveTxHash; - private String ethExecuteTxHash; - - public boolean isL1Originated() { - return isL1Originated; - } - - public void setL1Originated(boolean l1Originated) { - isL1Originated = l1Originated; - } - - public TransactionStatus getStatus() { - return status; - } - - public void setStatus(TransactionStatus status) { - this.status = status; - } - - public BigInteger getFee() { - return Numeric.decodeQuantity(fee); - } - - public void setFee(String fee) { - this.fee = fee; - } - - public String getInitiatorAddress() { - return initiatorAddress; - } - - public void setInitiatorAddress(String initiatorAddress) { - this.initiatorAddress = initiatorAddress; - } - - public Date getReceivedAt() { - return receivedAt; - } - - public void setReceivedAt(Date receivedAt) { - this.receivedAt = receivedAt; - } - - public String getEthCommitTxHash() { - return ethCommitTxHash; - } - - public void setEthCommitTxHash(String ethCommitTxHash) { - this.ethCommitTxHash = ethCommitTxHash; - } - - public String getEthProveTxHash() { - return ethProveTxHash; - } - - public void setEthProveTxHash(String ethProveTxHash) { - this.ethProveTxHash = ethProveTxHash; - } - - public String getEthExecuteTxHash() { - return ethExecuteTxHash; - } - - public void setEthExecuteTxHash(String ethExecuteTxHash) { - this.ethExecuteTxHash = ethExecuteTxHash; - } - - @Override - public String toString() { - return "TransactionDetails{" + - "isL1Originated=" + isL1Originated + - ", status=" + status + - ", fee='" + fee + '\'' + - ", initiatorAddress='" + initiatorAddress + '\'' + - ", receivedAt=" + receivedAt + - ", ethCommitTxHash='" + ethCommitTxHash + '\'' + - ", ethProveTxHash='" + ethProveTxHash + '\'' + - ", ethExecuteTxHash='" + ethExecuteTxHash + '\'' + - '}'; - } + private boolean isL1Originated; + private TransactionStatus status; + private String fee; + private String initiatorAddress; + private Date receivedAt; + private String ethCommitTxHash; + private String ethProveTxHash; + private String ethExecuteTxHash; + + public boolean isL1Originated() { + return isL1Originated; + } + + public void setL1Originated(boolean l1Originated) { + isL1Originated = l1Originated; + } + + public TransactionStatus getStatus() { + return status; + } + + public void setStatus(TransactionStatus status) { + this.status = status; + } + + public BigInteger getFee() { + return Numeric.decodeQuantity(fee); + } + + public void setFee(String fee) { + this.fee = fee; + } + + public String getInitiatorAddress() { + return initiatorAddress; + } + + public void setInitiatorAddress(String initiatorAddress) { + this.initiatorAddress = initiatorAddress; + } + + public Date getReceivedAt() { + return receivedAt; + } + + public void setReceivedAt(Date receivedAt) { + this.receivedAt = receivedAt; + } + + public String getEthCommitTxHash() { + return ethCommitTxHash; + } + + public void setEthCommitTxHash(String ethCommitTxHash) { + this.ethCommitTxHash = ethCommitTxHash; + } + + public String getEthProveTxHash() { + return ethProveTxHash; + } + + public void setEthProveTxHash(String ethProveTxHash) { + this.ethProveTxHash = ethProveTxHash; + } + + public String getEthExecuteTxHash() { + return ethExecuteTxHash; + } + + public void setEthExecuteTxHash(String ethExecuteTxHash) { + this.ethExecuteTxHash = ethExecuteTxHash; + } + + @Override + public String toString() { + return "TransactionDetails{" + + "isL1Originated=" + + isL1Originated + + ", status=" + + status + + ", fee='" + + fee + + '\'' + + ", initiatorAddress='" + + initiatorAddress + + '\'' + + ", receivedAt=" + + receivedAt + + ", ethCommitTxHash='" + + ethCommitTxHash + + '\'' + + ", ethProveTxHash='" + + ethProveTxHash + + '\'' + + ", ethExecuteTxHash='" + + ethExecuteTxHash + + '\'' + + '}'; + } } diff --git a/src/main/java/io/zksync/transaction/TransactionStatus.java b/src/main/java/io/zksync/transaction/TransactionStatus.java index ac0d8ca..2cd492b 100644 --- a/src/main/java/io/zksync/transaction/TransactionStatus.java +++ b/src/main/java/io/zksync/transaction/TransactionStatus.java @@ -3,12 +3,12 @@ import com.fasterxml.jackson.annotation.JsonProperty; public enum TransactionStatus { - @JsonProperty("pending") - PENDING, - @JsonProperty("included") - INCLUDED, - @JsonProperty("verified") - VERIFIED, - @JsonProperty("failed") - FAILED + @JsonProperty("pending") + PENDING, + @JsonProperty("included") + INCLUDED, + @JsonProperty("verified") + VERIFIED, + @JsonProperty("failed") + FAILED } diff --git a/src/main/java/io/zksync/transaction/fee/DefaultTransactionFeeProvider.java b/src/main/java/io/zksync/transaction/fee/DefaultTransactionFeeProvider.java index 6d40aa1..073f958 100644 --- a/src/main/java/io/zksync/transaction/fee/DefaultTransactionFeeProvider.java +++ b/src/main/java/io/zksync/transaction/fee/DefaultTransactionFeeProvider.java @@ -5,56 +5,55 @@ import io.zksync.protocol.ZkSync; import io.zksync.protocol.core.Token; import io.zksync.protocol.exceptions.JsonRpcResponseException; +import java.math.BigInteger; import lombok.AllArgsConstructor; import lombok.SneakyThrows; -import java.math.BigInteger; - @AllArgsConstructor public class DefaultTransactionFeeProvider implements ZkTransactionFeeProvider { - private ZkSync zksync; - private Token feeToken; - - @SneakyThrows - @Override - public Fee getFee(Transaction transaction) { - ZksEstimateFee estimateFee = this.zksync.zksEstimateFee(transaction).send(); + private ZkSync zksync; + private Token feeToken; - if (estimateFee.hasError()) { - throw new JsonRpcResponseException(estimateFee); - } - - return estimateFee.getResult(); - } - - @Override - public Token getFeeToken() { - return this.feeToken; - } + @SneakyThrows + @Override + public Fee getFee(Transaction transaction) { + ZksEstimateFee estimateFee = this.zksync.zksEstimateFee(transaction).send(); - @Override - public BigInteger getGasPrice(String contractFunc) { - return zksync.ethGasPrice().sendAsync().join().getGasPrice(); + if (estimateFee.hasError()) { + throw new JsonRpcResponseException(estimateFee); } - @Override - public BigInteger getGasPrice() { - return zksync.ethGasPrice().sendAsync().join().getGasPrice(); - } - - @Override - public BigInteger getGasLimit(String contractFunc) { - return null; - } - - @Override - public BigInteger getGasLimit() { - return null; - } - - @Override - public BigInteger getGasLimit(Transaction transaction) { - return zksync.ethEstimateGas(transaction).sendAsync().join().getAmountUsed(); - } + return estimateFee.getResult(); + } + + @Override + public Token getFeeToken() { + return this.feeToken; + } + + @Override + public BigInteger getGasPrice(String contractFunc) { + return zksync.ethGasPrice().sendAsync().join().getGasPrice(); + } + + @Override + public BigInteger getGasPrice() { + return zksync.ethGasPrice().sendAsync().join().getGasPrice(); + } + + @Override + public BigInteger getGasLimit(String contractFunc) { + return null; + } + + @Override + public BigInteger getGasLimit() { + return null; + } + + @Override + public BigInteger getGasLimit(Transaction transaction) { + return zksync.ethEstimateGas(transaction).sendAsync().join().getAmountUsed(); + } } diff --git a/src/main/java/io/zksync/transaction/fee/Fee.java b/src/main/java/io/zksync/transaction/fee/Fee.java index a14577a..341acd5 100644 --- a/src/main/java/io/zksync/transaction/fee/Fee.java +++ b/src/main/java/io/zksync/transaction/fee/Fee.java @@ -2,92 +2,91 @@ import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonSetter; +import java.math.BigInteger; import lombok.AllArgsConstructor; import lombok.Data; import org.web3j.abi.datatypes.generated.Uint256; import org.web3j.utils.Numeric; -import java.math.BigInteger; - @Data @AllArgsConstructor public class Fee { - @JsonIgnore - private Uint256 gasLimit; - - @JsonIgnore - private Uint256 maxFeePerGas; - - @JsonIgnore - private Uint256 maxPriorityFeePerGas; - - @JsonIgnore - private Uint256 gasPerPubdataLimit; - - public Fee() { - this.gasLimit = Uint256.DEFAULT; - this.maxFeePerGas = Uint256.DEFAULT; - this.maxPriorityFeePerGas = Uint256.DEFAULT; - this.gasPerPubdataLimit = Uint256.DEFAULT; - } - - public Fee(BigInteger gqsLimit, BigInteger maxFeePerGas, BigInteger maxPriorityFeePerGas, BigInteger gasPerPubdataLimit) { - this.gasLimit = new Uint256(gqsLimit); - this.maxFeePerGas = new Uint256(maxFeePerGas); - this.maxPriorityFeePerGas = new Uint256(maxPriorityFeePerGas); - this.gasPerPubdataLimit = new Uint256(gasPerPubdataLimit); - } - - public BigInteger getGasLimitNumber() { - return gasLimit.getValue(); - } - - public void setGasLimit(BigInteger gasLimit) { - this.gasLimit = new Uint256(gasLimit); - } - - @JsonSetter("gas_limit") - public void setGasLimit(String gasLimit) { - this.gasLimit = new Uint256(Numeric.toBigInt(gasLimit)); - } - - public BigInteger getGasPriceLimitNumber() { - return maxFeePerGas.getValue(); - } - - public void setMaxFeePerGas(BigInteger maxFeePerGas) { - this.maxFeePerGas = new Uint256(maxFeePerGas); - } - - @JsonSetter("max_fee_per_gas") - public void setMaxFeePerGas(String gasPriceLimit) { - this.maxFeePerGas = new Uint256(Numeric.toBigInt(gasPriceLimit)); - } - - public BigInteger getMaxPriorityFeePerErgNumber() { - return maxPriorityFeePerGas.getValue(); - } - - public void setMaxPriorityFeePerGas(BigInteger maxPriorityFeePerGas) { - this.maxPriorityFeePerGas = new Uint256(maxPriorityFeePerGas); - } - - @JsonSetter("max_priority_fee_per_erg") - public void setMaxPriorityFeePerGas(String maxPriorityFeePerErg) { - this.maxPriorityFeePerGas = new Uint256(Numeric.toBigInt(maxPriorityFeePerErg)); - } - - public BigInteger getGasPerPubdataLimitNumber() { - return gasPerPubdataLimit.getValue(); - } - - public void setGasPerPubdataLimit(BigInteger gasPerPubdataLimit) { - this.gasPerPubdataLimit = new Uint256(gasPerPubdataLimit); - } - - @JsonSetter("gas_per_pubdata_limit") - public void setGasPerPubdataLimit(String gasPerPubdataLimit) { - this.gasPerPubdataLimit = new Uint256(Numeric.toBigInt(gasPerPubdataLimit)); - } + @JsonIgnore private Uint256 gasLimit; + + @JsonIgnore private Uint256 maxFeePerGas; + + @JsonIgnore private Uint256 maxPriorityFeePerGas; + + @JsonIgnore private Uint256 gasPerPubdataLimit; + + public Fee() { + this.gasLimit = Uint256.DEFAULT; + this.maxFeePerGas = Uint256.DEFAULT; + this.maxPriorityFeePerGas = Uint256.DEFAULT; + this.gasPerPubdataLimit = Uint256.DEFAULT; + } + + public Fee( + BigInteger gqsLimit, + BigInteger maxFeePerGas, + BigInteger maxPriorityFeePerGas, + BigInteger gasPerPubdataLimit) { + this.gasLimit = new Uint256(gqsLimit); + this.maxFeePerGas = new Uint256(maxFeePerGas); + this.maxPriorityFeePerGas = new Uint256(maxPriorityFeePerGas); + this.gasPerPubdataLimit = new Uint256(gasPerPubdataLimit); + } + + public BigInteger getGasLimitNumber() { + return gasLimit.getValue(); + } + + public void setGasLimit(BigInteger gasLimit) { + this.gasLimit = new Uint256(gasLimit); + } + + @JsonSetter("gas_limit") + public void setGasLimit(String gasLimit) { + this.gasLimit = new Uint256(Numeric.toBigInt(gasLimit)); + } + + public BigInteger getGasPriceLimitNumber() { + return maxFeePerGas.getValue(); + } + + public void setMaxFeePerGas(BigInteger maxFeePerGas) { + this.maxFeePerGas = new Uint256(maxFeePerGas); + } + + @JsonSetter("max_fee_per_gas") + public void setMaxFeePerGas(String gasPriceLimit) { + this.maxFeePerGas = new Uint256(Numeric.toBigInt(gasPriceLimit)); + } + + public BigInteger getMaxPriorityFeePerErgNumber() { + return maxPriorityFeePerGas.getValue(); + } + + public void setMaxPriorityFeePerGas(BigInteger maxPriorityFeePerGas) { + this.maxPriorityFeePerGas = new Uint256(maxPriorityFeePerGas); + } + + @JsonSetter("max_priority_fee_per_erg") + public void setMaxPriorityFeePerGas(String maxPriorityFeePerErg) { + this.maxPriorityFeePerGas = new Uint256(Numeric.toBigInt(maxPriorityFeePerErg)); + } + + public BigInteger getGasPerPubdataLimitNumber() { + return gasPerPubdataLimit.getValue(); + } + + public void setGasPerPubdataLimit(BigInteger gasPerPubdataLimit) { + this.gasPerPubdataLimit = new Uint256(gasPerPubdataLimit); + } + + @JsonSetter("gas_per_pubdata_limit") + public void setGasPerPubdataLimit(String gasPerPubdataLimit) { + this.gasPerPubdataLimit = new Uint256(Numeric.toBigInt(gasPerPubdataLimit)); + } } diff --git a/src/main/java/io/zksync/transaction/fee/ZkTransactionFeeProvider.java b/src/main/java/io/zksync/transaction/fee/ZkTransactionFeeProvider.java index 17702c1..a73d754 100644 --- a/src/main/java/io/zksync/transaction/fee/ZkTransactionFeeProvider.java +++ b/src/main/java/io/zksync/transaction/fee/ZkTransactionFeeProvider.java @@ -2,16 +2,14 @@ import io.zksync.methods.request.Transaction; import io.zksync.protocol.core.Token; -import org.web3j.tx.gas.ContractGasProvider; - import java.math.BigInteger; +import org.web3j.tx.gas.ContractGasProvider; public interface ZkTransactionFeeProvider extends ContractGasProvider { - Fee getFee(Transaction transaction); + Fee getFee(Transaction transaction); - BigInteger getGasLimit(Transaction transaction); + BigInteger getGasLimit(Transaction transaction); - Token getFeeToken(); - + Token getFeeToken(); } diff --git a/src/main/java/io/zksync/transaction/manager/ZkSyncTransactionManager.java b/src/main/java/io/zksync/transaction/manager/ZkSyncTransactionManager.java index 887f68d..63cc544 100644 --- a/src/main/java/io/zksync/transaction/manager/ZkSyncTransactionManager.java +++ b/src/main/java/io/zksync/transaction/manager/ZkSyncTransactionManager.java @@ -1,15 +1,19 @@ package io.zksync.transaction.manager; +import static io.zksync.protocol.JsonRpc2_0ZkSync.DEFAULT_BLOCK_COMMIT_TIME; + import io.zksync.abi.TransactionEncoder; import io.zksync.crypto.signer.EthSigner; import io.zksync.methods.request.Eip712Meta; import io.zksync.methods.request.Transaction; -import io.zksync.protocol.exceptions.JsonRpcResponseException; -import io.zksync.transaction.response.ZkSyncTransactionReceiptProcessor; -import io.zksync.transaction.type.Transaction712; import io.zksync.protocol.ZkSync; import io.zksync.protocol.core.ZkBlockParameterName; +import io.zksync.protocol.exceptions.JsonRpcResponseException; import io.zksync.transaction.fee.ZkTransactionFeeProvider; +import io.zksync.transaction.response.ZkSyncTransactionReceiptProcessor; +import io.zksync.transaction.type.Transaction712; +import java.io.IOException; +import java.math.BigInteger; import org.web3j.protocol.core.DefaultBlockParameter; import org.web3j.protocol.core.methods.response.EthCall; import org.web3j.protocol.core.methods.response.EthGetCode; @@ -18,124 +22,139 @@ import org.web3j.tx.TransactionManager; import org.web3j.utils.Numeric; -import java.io.IOException; -import java.math.BigInteger; - -import static io.zksync.protocol.JsonRpc2_0ZkSync.DEFAULT_BLOCK_COMMIT_TIME; - public class ZkSyncTransactionManager extends TransactionManager { - public static final int DEFAULT_POLLING_ATTEMPTS_PER_TX_HASH = 40; - public static final long DEFAULT_POLLING_FREQUENCY = DEFAULT_BLOCK_COMMIT_TIME; - - private final ZkSync zkSync; - private final EthSigner signer; - - private final ZkTransactionFeeProvider feeProvider; - - public ZkSyncTransactionManager(ZkSync zkSync, EthSigner signer, ZkTransactionFeeProvider feeProvider) { - super(new ZkSyncTransactionReceiptProcessor(zkSync, DEFAULT_POLLING_FREQUENCY, DEFAULT_POLLING_ATTEMPTS_PER_TX_HASH), signer.getAddress()); - - this.zkSync = zkSync; - this.signer = signer; - this.feeProvider = feeProvider; + public static final int DEFAULT_POLLING_ATTEMPTS_PER_TX_HASH = 40; + public static final long DEFAULT_POLLING_FREQUENCY = DEFAULT_BLOCK_COMMIT_TIME; + + private final ZkSync zkSync; + private final EthSigner signer; + + private final ZkTransactionFeeProvider feeProvider; + + public ZkSyncTransactionManager( + ZkSync zkSync, EthSigner signer, ZkTransactionFeeProvider feeProvider) { + super( + new ZkSyncTransactionReceiptProcessor( + zkSync, DEFAULT_POLLING_FREQUENCY, DEFAULT_POLLING_ATTEMPTS_PER_TX_HASH), + signer.getAddress()); + + this.zkSync = zkSync; + this.signer = signer; + this.feeProvider = feeProvider; + } + + @Override + public EthSendTransaction sendTransaction( + BigInteger gasPrice, + BigInteger gasLimit, + String to, + String data, + BigInteger value, + boolean constructor) + throws IOException { + final Transaction712 transaction; + long chainId = getSigner().getDomain().join().getChainId().getValue().longValue(); + if (gasPrice == null) { + gasPrice = getFeeProvider().getGasPrice(); } - - @Override - public EthSendTransaction sendTransaction(BigInteger gasPrice, BigInteger gasLimit, String to, String data, BigInteger value, boolean constructor) throws IOException { - final Transaction712 transaction; - long chainId = getSigner().getDomain().join().getChainId().getValue().longValue(); - if (gasPrice == null) { - gasPrice = getFeeProvider().getGasPrice(); - } - Eip712Meta meta = new Eip712Meta( - BigInteger.valueOf(160000L), - null, - null, - null - ); - if (constructor) { - throw new UnsupportedOperationException("Not supported deploying with Contract wrapper"); - } else { - if (gasLimit == null) { - Transaction estimate = Transaction.createFunctionCallTransaction( - getFromAddress(), - to, - BigInteger.ZERO, - BigInteger.ZERO, - data - ); - gasLimit = getFeeProvider().getGasLimit(estimate); - } - transaction = new Transaction712( - chainId, - getNonce(), - gasLimit, - to, - value, - data, - BigInteger.valueOf(100000000L), - gasPrice, - getFromAddress(), - meta - ); - } - - String signature = getSigner().getDomain().thenCompose(domain -> getSigner().signTypedData(domain, transaction)).join(); - byte[] signed = TransactionEncoder.encode(transaction, TransactionEncoder.getSignatureData(signature)); - - EthSendTransaction response = zkSync.ethSendRawTransaction(Numeric.toHexString(signed)).send(); - - if (response.hasError()) { - throw new JsonRpcResponseException(response); - } else { - return response; - } - } - - @Override - public EthSendTransaction sendEIP1559Transaction(long chainId, BigInteger maxPriorityFeePerGas, BigInteger maxFeePerGas, BigInteger gasLimit, String to, String data, BigInteger value, boolean constructor) throws IOException { - return sendTransaction(maxPriorityFeePerGas, gasLimit, to, data, value, constructor); + Eip712Meta meta = new Eip712Meta(BigInteger.valueOf(160000L), null, null, null); + if (constructor) { + throw new UnsupportedOperationException("Not supported deploying with Contract wrapper"); + } else { + if (gasLimit == null) { + Transaction estimate = + Transaction.createFunctionCallTransaction( + getFromAddress(), to, BigInteger.ZERO, BigInteger.ZERO, data); + gasLimit = getFeeProvider().getGasLimit(estimate); + } + transaction = + new Transaction712( + chainId, + getNonce(), + gasLimit, + to, + value, + data, + BigInteger.valueOf(100000000L), + gasPrice, + getFromAddress(), + meta); } - @Override - public String sendCall(String to, String data, DefaultBlockParameter defaultBlockParameter) throws IOException { - EthCall ethCall = - zkSync.ethCall( - org.web3j.protocol.core.methods.request.Transaction.createEthCallTransaction(getFromAddress(), to, data), - defaultBlockParameter) - .send(); + String signature = + getSigner() + .getDomain() + .thenCompose(domain -> getSigner().signTypedData(domain, transaction)) + .join(); + byte[] signed = + TransactionEncoder.encode(transaction, TransactionEncoder.getSignatureData(signature)); - if (ethCall.hasError()) { - throw new JsonRpcResponseException(ethCall); - } + EthSendTransaction response = zkSync.ethSendRawTransaction(Numeric.toHexString(signed)).send(); - return ethCall.getValue(); + if (response.hasError()) { + throw new JsonRpcResponseException(response); + } else { + return response; } - - @Override - public EthGetCode getCode(String contractAddress, DefaultBlockParameter defaultBlockParameter) throws IOException { - return zkSync.ethGetCode(contractAddress, defaultBlockParameter).send(); + } + + @Override + public EthSendTransaction sendEIP1559Transaction( + long chainId, + BigInteger maxPriorityFeePerGas, + BigInteger maxFeePerGas, + BigInteger gasLimit, + String to, + String data, + BigInteger value, + boolean constructor) + throws IOException { + return sendTransaction(maxPriorityFeePerGas, gasLimit, to, data, value, constructor); + } + + @Override + public String sendCall(String to, String data, DefaultBlockParameter defaultBlockParameter) + throws IOException { + EthCall ethCall = + zkSync + .ethCall( + org.web3j.protocol.core.methods.request.Transaction.createEthCallTransaction( + getFromAddress(), to, data), + defaultBlockParameter) + .send(); + + if (ethCall.hasError()) { + throw new JsonRpcResponseException(ethCall); } - public ZkTransactionFeeProvider getFeeProvider() { - return feeProvider; - } + return ethCall.getValue(); + } - public EthSigner getSigner() { - return signer; - } + @Override + public EthGetCode getCode(String contractAddress, DefaultBlockParameter defaultBlockParameter) + throws IOException { + return zkSync.ethGetCode(contractAddress, defaultBlockParameter).send(); + } - protected BigInteger getNonce() throws IOException { - EthGetTransactionCount ethGetTransactionCount = - zkSync.ethGetTransactionCount( - getSigner().getAddress(), ZkBlockParameterName.COMMITTED) - .send(); + public ZkTransactionFeeProvider getFeeProvider() { + return feeProvider; + } - return ethGetTransactionCount.getTransactionCount(); - } + public EthSigner getSigner() { + return signer; + } - private boolean isVanillaEVMByteCode(String bytecodeHex) { - return bytecodeHex.startsWith("0x60"); - } + protected BigInteger getNonce() throws IOException { + EthGetTransactionCount ethGetTransactionCount = + zkSync + .ethGetTransactionCount(getSigner().getAddress(), ZkBlockParameterName.COMMITTED) + .send(); + + return ethGetTransactionCount.getTransactionCount(); + } + + private boolean isVanillaEVMByteCode(String bytecodeHex) { + return bytecodeHex.startsWith("0x60"); + } } diff --git a/src/main/java/io/zksync/transaction/response/ZkSyncTransactionReceiptProcessor.java b/src/main/java/io/zksync/transaction/response/ZkSyncTransactionReceiptProcessor.java index b9a37a9..ce31648 100644 --- a/src/main/java/io/zksync/transaction/response/ZkSyncTransactionReceiptProcessor.java +++ b/src/main/java/io/zksync/transaction/response/ZkSyncTransactionReceiptProcessor.java @@ -1,72 +1,69 @@ package io.zksync.transaction.response; import io.zksync.protocol.ZkSync; +import java.io.IOException; +import java.util.Optional; import org.web3j.protocol.core.methods.response.EthGetTransactionReceipt; import org.web3j.protocol.core.methods.response.TransactionReceipt; import org.web3j.protocol.exceptions.TransactionException; import org.web3j.tx.response.TransactionReceiptProcessor; -import java.io.IOException; -import java.util.Optional; - public class ZkSyncTransactionReceiptProcessor extends TransactionReceiptProcessor { - private final ZkSync zkSync; + private final ZkSync zkSync; - protected final long sleepDuration; - protected final int attempts; + protected final long sleepDuration; + protected final int attempts; - public ZkSyncTransactionReceiptProcessor(ZkSync zkSync, long sleepDuration, int attempts) { - super(zkSync); - this.zkSync = zkSync; - this.attempts = attempts; - this.sleepDuration = sleepDuration; - } - - @Override - public TransactionReceipt waitForTransactionReceipt(String transactionHash) - throws IOException, TransactionException { + public ZkSyncTransactionReceiptProcessor(ZkSync zkSync, long sleepDuration, int attempts) { + super(zkSync); + this.zkSync = zkSync; + this.attempts = attempts; + this.sleepDuration = sleepDuration; + } - return getTransactionReceipt(transactionHash, sleepDuration, attempts); - } + @Override + public TransactionReceipt waitForTransactionReceipt(String transactionHash) + throws IOException, TransactionException { - private TransactionReceipt getTransactionReceipt( - String transactionHash, long sleepDuration, int attempts) - throws IOException, TransactionException { + return getTransactionReceipt(transactionHash, sleepDuration, attempts); + } - Optional receiptOptional = - sendTransactionReceiptRequest(transactionHash); - for (int i = 0; i < attempts; i++) { - if (!receiptOptional.isPresent() || receiptOptional.get().getBlockHash() == null) { - try { - Thread.sleep(sleepDuration); - } catch (InterruptedException e) { - throw new TransactionException(e); - } + private TransactionReceipt getTransactionReceipt( + String transactionHash, long sleepDuration, int attempts) + throws IOException, TransactionException { - receiptOptional = sendTransactionReceiptRequest(transactionHash); - } else { - return receiptOptional.get(); - } + Optional receiptOptional = + sendTransactionReceiptRequest(transactionHash); + for (int i = 0; i < attempts; i++) { + if (!receiptOptional.isPresent() || receiptOptional.get().getBlockHash() == null) { + try { + Thread.sleep(sleepDuration); + } catch (InterruptedException e) { + throw new TransactionException(e); } - throw new TransactionException( - "Transaction receipt was not generated after " - + ((sleepDuration * attempts) / 1000 - + " seconds for transaction: " - + transactionHash), - transactionHash); + receiptOptional = sendTransactionReceiptRequest(transactionHash); + } else { + return receiptOptional.get(); + } } - Optional sendTransactionReceiptRequest(String transactionHash) - throws IOException, TransactionException { - EthGetTransactionReceipt transactionReceipt = - zkSync.ethGetTransactionReceipt(transactionHash).send(); - if (transactionReceipt.hasError()) { - throw new TransactionException( - "Error processing request: " + transactionReceipt.getError().getMessage()); - } + throw new TransactionException( + "Transaction receipt was not generated after " + + ((sleepDuration * attempts) / 1000 + " seconds for transaction: " + transactionHash), + transactionHash); + } - return transactionReceipt.getTransactionReceipt(); + Optional sendTransactionReceiptRequest(String transactionHash) + throws IOException, TransactionException { + EthGetTransactionReceipt transactionReceipt = + zkSync.ethGetTransactionReceipt(transactionHash).send(); + if (transactionReceipt.hasError()) { + throw new TransactionException( + "Error processing request: " + transactionReceipt.getError().getMessage()); } + + return transactionReceipt.getTransactionReceipt(); + } } diff --git a/src/main/java/io/zksync/transaction/type/Transaction712.java b/src/main/java/io/zksync/transaction/type/Transaction712.java index 81c1b9c..ad07b3f 100644 --- a/src/main/java/io/zksync/transaction/type/Transaction712.java +++ b/src/main/java/io/zksync/transaction/type/Transaction712.java @@ -3,6 +3,14 @@ import io.zksync.crypto.eip712.Structurable; import io.zksync.methods.request.Eip712Meta; import io.zksync.utils.ContractDeployer; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.stream.Collectors; import org.apache.commons.lang3.tuple.Pair; import org.web3j.abi.datatypes.DynamicArray; import org.web3j.abi.datatypes.DynamicBytes; @@ -18,178 +26,204 @@ import org.web3j.utils.Assertions; import org.web3j.utils.Numeric; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.math.BigInteger; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.stream.Collectors; - public class Transaction712 extends Transaction1559 implements Structurable { - static final String TRANSACTION_TYPE = "Transaction"; - public static final byte EIP_712_TX_TYPE = (byte) 0x71; - private final String from; - private final Eip712Meta meta; - - public Transaction712(long chainId, BigInteger nonce, BigInteger gasLimit, String to, BigInteger value, String data, BigInteger maxPriorityFeePerGas, BigInteger maxFeePerGas, String from, Eip712Meta meta) { - super(chainId, nonce, gasLimit, to, value, data, maxPriorityFeePerGas, maxFeePerGas); - this.from = from; - this.meta = meta; + static final String TRANSACTION_TYPE = "Transaction"; + public static final byte EIP_712_TX_TYPE = (byte) 0x71; + private final String from; + private final Eip712Meta meta; + + public Transaction712( + long chainId, + BigInteger nonce, + BigInteger gasLimit, + String to, + BigInteger value, + String data, + BigInteger maxPriorityFeePerGas, + BigInteger maxFeePerGas, + String from, + Eip712Meta meta) { + super(chainId, nonce, gasLimit, to, value, data, maxPriorityFeePerGas, maxFeePerGas); + this.from = from; + this.meta = meta; + } + + @Override + public List asRlpValues(Sign.SignatureData signatureData) { + Assertions.verifyPrecondition( + signatureData != null || getMeta().getCustomSignature() != null, + "One of `signatureData` and `meta.customSignature` MUST be set"); + List result = new ArrayList<>(); + + result.add(RlpString.create(getNonce())); // 0 + + // add maxPriorityFeePerGas and maxFeePerGas if this is an EIP-1559 transaction + result.add(RlpString.create(getMaxPriorityFeePerGas())); // 1 + result.add(RlpString.create(getMaxFeePerGas())); // GasPrice // 2 + + result.add(RlpString.create(getGasLimit())); // 3 + + // an empty to address (contract creation) should not be encoded as a numeric 0 value + String to = getTo(); + if (to != null && to.length() > 0) { + // addresses that start with zeros should be encoded with the zeros included, not + // as numeric values + result.add(RlpString.create(Numeric.hexStringToByteArray(to))); // 4 + } else { + result.add(RlpString.create("")); // 4 } + result.add(RlpString.create(getValue())); // 5 - @Override - public List asRlpValues(Sign.SignatureData signatureData) { - Assertions.verifyPrecondition(signatureData != null || getMeta().getCustomSignature() != null, "One of `signatureData` and `meta.customSignature` MUST be set"); - List result = new ArrayList<>(); - - result.add(RlpString.create(getNonce())); // 0 - - // add maxPriorityFeePerGas and maxFeePerGas if this is an EIP-1559 transaction - result.add(RlpString.create(getMaxPriorityFeePerGas())); // 1 - result.add(RlpString.create(getMaxFeePerGas()));// GasPrice // 2 - - result.add(RlpString.create(getGasLimit())); // 3 - - // an empty to address (contract creation) should not be encoded as a numeric 0 value - String to = getTo(); - if (to != null && to.length() > 0) { - // addresses that start with zeros should be encoded with the zeros included, not - // as numeric values - result.add(RlpString.create(Numeric.hexStringToByteArray(to))); // 4 - } else { - result.add(RlpString.create("")); // 4 - } - - result.add(RlpString.create(getValue())); // 5 + // value field will already be hex encoded, so we need to convert into binary first + byte[] data = Numeric.hexStringToByteArray(getData()); + result.add(RlpString.create(data)); // 6 - // value field will already be hex encoded, so we need to convert into binary first - byte[] data = Numeric.hexStringToByteArray(getData()); - result.add(RlpString.create(data)); // 6 + // ZkSync part - // ZkSync part + result.add(RlpString.create(getChainId())); // 7 + result.add(RlpString.create("")); // 8 + result.add(RlpString.create("")); // 9 - result.add(RlpString.create(getChainId())); //7 - result.add(RlpString.create("")); // 8 - result.add(RlpString.create("")); // 9 + result.add(RlpString.create(getChainId())); // 10 - result.add(RlpString.create(getChainId())); // 10 + result.add(RlpString.create(Numeric.hexStringToByteArray(getFrom()))); // 11 - result.add(RlpString.create(Numeric.hexStringToByteArray(getFrom()))); // 11 + BigInteger gasPerPubdata = getGasPerPubdata(); + result.add(RlpString.create(gasPerPubdata)); // 12 - BigInteger gasPerPubdata = getGasPerPubdata(); - result.add(RlpString.create(gasPerPubdata)); //12 - - List factoryDeps; - - if (getFactoryDeps() != null) { - factoryDeps = Arrays.stream(getFactoryDeps()) - .map(RlpString::create) - .collect(Collectors.toList()); - } else { - factoryDeps = Collections.emptyList(); - } - - result.add(new RlpList(factoryDeps)); // 13 - - if (getMeta().getCustomSignature() != null) { - result.add(RlpString.create(getMeta().getCustomSignature())); // 14 - } else { - final ByteArrayOutputStream output = new ByteArrayOutputStream(); - - try { - output.write(signatureData.getR()); - output.write(signatureData.getS()); - output.write(signatureData.getV()); - } catch (IOException e) { - throw new IllegalStateException("Error when creating ETH signature", e); - } - result.add(RlpString.create(output.toByteArray())); // 14 - } - - List paymasterParams; - - if (getMeta().getPaymasterParams() != null && getPaymaster() != null && getPaymasterInput() != null) { - paymasterParams = Arrays.asList( - RlpString.create(Numeric.hexStringToByteArray(getMeta().getPaymasterParams().getPaymaster())), - RlpString.create(getMeta().getPaymasterParams().getPaymasterInput()) - ); - } else { - paymasterParams = Collections.emptyList(); - } - - result.add(new RlpList(paymasterParams)); // 15 - - return result; - } - - public String getFrom() { - return from; - } - - public BigInteger getGasPerPubdata() { - return meta.getGasPerPubdataNumber(); - } - - public byte[][] getFactoryDeps() { - return meta.getFactoryDeps(); - } - - public Eip712Meta getMeta() { - return meta; - } - - public String getPaymaster() { - return getMeta() != null && getMeta().getPaymasterParams() != null ? getMeta().getPaymasterParams().getPaymaster() : null; - } - - public byte[] getPaymasterInput() { - return getMeta() != null && getMeta().getPaymasterParams() != null ? getMeta().getPaymasterParams().getPaymasterInput() : null; - } + List factoryDeps; - @Override - public TransactionType getType() { - // NOTE: Transaction type encoded manually in `asRlpValues` - return TransactionType.LEGACY; + if (getFactoryDeps() != null) { + factoryDeps = + Arrays.stream(getFactoryDeps()).map(RlpString::create).collect(Collectors.toList()); + } else { + factoryDeps = Collections.emptyList(); } - @Override - public String getTypeName() { - return TRANSACTION_TYPE; + result.add(new RlpList(factoryDeps)); // 13 + + if (getMeta().getCustomSignature() != null) { + result.add(RlpString.create(getMeta().getCustomSignature())); // 14 + } else { + final ByteArrayOutputStream output = new ByteArrayOutputStream(); + + try { + output.write(signatureData.getR()); + output.write(signatureData.getS()); + output.write(signatureData.getV()); + } catch (IOException e) { + throw new IllegalStateException("Error when creating ETH signature", e); + } + result.add(RlpString.create(output.toByteArray())); // 14 } - @Override - public List>> eip712types() { - List>> result = new ArrayList<>(13); - - result.add(Pair.of("txType", new Uint256(Transaction712.EIP_712_TX_TYPE))); - result.add(Pair.of("from", new Uint256(Numeric.toBigInt(getFrom())))); - result.add(Pair.of("to", getTo() != null ? new Uint256(Numeric.toBigInt(getTo())) : Uint256.DEFAULT)); - result.add(Pair.of("gasLimit", new Uint256(getGasLimit()))); - - result.add(Pair.of("gasPerPubdataByteLimit", new Uint256(getGasPerPubdata()))); - result.add(Pair.of("maxFeePerGas", new Uint256(getMaxFeePerGas()))); - result.add(Pair.of("maxPriorityFeePerGas", new Uint256(getMaxPriorityFeePerGas()))); - result.add(Pair.of("paymaster", getPaymaster() != null ? new Uint256(Numeric.toBigInt(getPaymaster())) : Uint256.DEFAULT)); - result.add(Pair.of("nonce", new Uint256(getNonce()))); - result.add(Pair.of("value", getValue() != null ? new Uint256(getValue()) : Uint256.DEFAULT)); - result.add(Pair.of("data", getData() != null ? new DynamicBytes(Numeric.hexStringToByteArray(getData())) : DynamicBytes.DEFAULT)); - result.add(Pair.of("factoryDeps", getFactoryDepsHashes())); - result.add(Pair.of("paymasterInput", getPaymasterInput() != null ? new DynamicBytes(getPaymasterInput()) : DynamicBytes.DEFAULT)); - - return result; + List paymasterParams; + + if (getMeta().getPaymasterParams() != null + && getPaymaster() != null + && getPaymasterInput() != null) { + paymasterParams = + Arrays.asList( + RlpString.create( + Numeric.hexStringToByteArray(getMeta().getPaymasterParams().getPaymaster())), + RlpString.create(getMeta().getPaymasterParams().getPaymasterInput())); + } else { + paymasterParams = Collections.emptyList(); } - private DynamicArray getFactoryDepsHashes() { - if (getFactoryDeps() != null) { - return new DynamicArray<>(Bytes32.class, Arrays.stream(getFactoryDeps()) - .map(ContractDeployer::hashBytecode) - .map(Bytes32::new) - .collect(Collectors.toList())); - } else { - return new DynamicArray<>(Bytes32.class, Collections.emptyList()); - } + result.add(new RlpList(paymasterParams)); // 15 + + return result; + } + + public String getFrom() { + return from; + } + + public BigInteger getGasPerPubdata() { + return meta.getGasPerPubdataNumber(); + } + + public byte[][] getFactoryDeps() { + return meta.getFactoryDeps(); + } + + public Eip712Meta getMeta() { + return meta; + } + + public String getPaymaster() { + return getMeta() != null && getMeta().getPaymasterParams() != null + ? getMeta().getPaymasterParams().getPaymaster() + : null; + } + + public byte[] getPaymasterInput() { + return getMeta() != null && getMeta().getPaymasterParams() != null + ? getMeta().getPaymasterParams().getPaymasterInput() + : null; + } + + @Override + public TransactionType getType() { + // NOTE: Transaction type encoded manually in `asRlpValues` + return TransactionType.LEGACY; + } + + @Override + public String getTypeName() { + return TRANSACTION_TYPE; + } + + @Override + public List>> eip712types() { + List>> result = new ArrayList<>(13); + + result.add(Pair.of("txType", new Uint256(Transaction712.EIP_712_TX_TYPE))); + result.add(Pair.of("from", new Uint256(Numeric.toBigInt(getFrom())))); + result.add( + Pair.of("to", getTo() != null ? new Uint256(Numeric.toBigInt(getTo())) : Uint256.DEFAULT)); + result.add(Pair.of("gasLimit", new Uint256(getGasLimit()))); + + result.add(Pair.of("gasPerPubdataByteLimit", new Uint256(getGasPerPubdata()))); + result.add(Pair.of("maxFeePerGas", new Uint256(getMaxFeePerGas()))); + result.add(Pair.of("maxPriorityFeePerGas", new Uint256(getMaxPriorityFeePerGas()))); + result.add( + Pair.of( + "paymaster", + getPaymaster() != null + ? new Uint256(Numeric.toBigInt(getPaymaster())) + : Uint256.DEFAULT)); + result.add(Pair.of("nonce", new Uint256(getNonce()))); + result.add(Pair.of("value", getValue() != null ? new Uint256(getValue()) : Uint256.DEFAULT)); + result.add( + Pair.of( + "data", + getData() != null + ? new DynamicBytes(Numeric.hexStringToByteArray(getData())) + : DynamicBytes.DEFAULT)); + result.add(Pair.of("factoryDeps", getFactoryDepsHashes())); + result.add( + Pair.of( + "paymasterInput", + getPaymasterInput() != null + ? new DynamicBytes(getPaymasterInput()) + : DynamicBytes.DEFAULT)); + + return result; + } + + private DynamicArray getFactoryDepsHashes() { + if (getFactoryDeps() != null) { + return new DynamicArray<>( + Bytes32.class, + Arrays.stream(getFactoryDeps()) + .map(ContractDeployer::hashBytecode) + .map(Bytes32::new) + .collect(Collectors.toList())); + } else { + return new DynamicArray<>(Bytes32.class, Collections.emptyList()); } + } } diff --git a/src/main/java/io/zksync/utils/AccountAbstractionVersion.java b/src/main/java/io/zksync/utils/AccountAbstractionVersion.java index bce84a5..0422561 100644 --- a/src/main/java/io/zksync/utils/AccountAbstractionVersion.java +++ b/src/main/java/io/zksync/utils/AccountAbstractionVersion.java @@ -1,15 +1,16 @@ package io.zksync.utils; public enum AccountAbstractionVersion { - NONE(0), - Version1(1); + NONE(0), + Version1(1); - private final int value; - AccountAbstractionVersion(int value) { - this.value = value; - } + private final int value; - public int getRawValue(){ - return this.value; - } + AccountAbstractionVersion(int value) { + this.value = value; + } + + public int getRawValue() { + return this.value; + } } diff --git a/src/main/java/io/zksync/utils/ByteArray2Serializer.java b/src/main/java/io/zksync/utils/ByteArray2Serializer.java index a499448..0383359 100644 --- a/src/main/java/io/zksync/utils/ByteArray2Serializer.java +++ b/src/main/java/io/zksync/utils/ByteArray2Serializer.java @@ -3,29 +3,27 @@ import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.SerializerProvider; - import java.io.IOException; public class ByteArray2Serializer extends JsonSerializer { - @Override - public void serialize(byte[][] bytes, JsonGenerator generator, SerializerProvider provider) throws IOException { - generator.writeStartArray(); - - for (byte[] inner : bytes) { - generator.writeStartArray(); - for (byte b : inner) { - generator.writeNumber(unsigned(b)); - } - generator.writeEndArray(); - } - - generator.writeEndArray(); - + @Override + public void serialize(byte[][] bytes, JsonGenerator generator, SerializerProvider provider) + throws IOException { + generator.writeStartArray(); + + for (byte[] inner : bytes) { + generator.writeStartArray(); + for (byte b : inner) { + generator.writeNumber(unsigned(b)); + } + generator.writeEndArray(); } - private static int unsigned(byte b) { - return b & 0xFF; - } + generator.writeEndArray(); + } -} \ No newline at end of file + private static int unsigned(byte b) { + return b & 0xFF; + } +} diff --git a/src/main/java/io/zksync/utils/ByteArraySerializer.java b/src/main/java/io/zksync/utils/ByteArraySerializer.java index f9502b5..77b33ed 100644 --- a/src/main/java/io/zksync/utils/ByteArraySerializer.java +++ b/src/main/java/io/zksync/utils/ByteArraySerializer.java @@ -3,25 +3,23 @@ import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.SerializerProvider; - import java.io.IOException; public class ByteArraySerializer extends JsonSerializer { - @Override - public void serialize(byte[] bytes, JsonGenerator generator, SerializerProvider provider) throws IOException { - generator.writeStartArray(); - - for (byte b : bytes) { - generator.writeNumber(unsigned(b)); - } - - generator.writeEndArray(); + @Override + public void serialize(byte[] bytes, JsonGenerator generator, SerializerProvider provider) + throws IOException { + generator.writeStartArray(); + for (byte b : bytes) { + generator.writeNumber(unsigned(b)); } - private static int unsigned(byte b) { - return b & 0xFF; - } + generator.writeEndArray(); + } -} \ No newline at end of file + private static int unsigned(byte b) { + return b & 0xFF; + } +} diff --git a/src/main/java/io/zksync/utils/ContractDeployer.java b/src/main/java/io/zksync/utils/ContractDeployer.java index 472d432..3984d3a 100644 --- a/src/main/java/io/zksync/utils/ContractDeployer.java +++ b/src/main/java/io/zksync/utils/ContractDeployer.java @@ -1,5 +1,11 @@ package io.zksync.utils; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.math.BigInteger; +import java.util.Arrays; +import java.util.Collections; +import java.util.Objects; import org.apache.commons.lang3.ArrayUtils; import org.web3j.abi.EventValues; import org.web3j.abi.TypeReference; @@ -15,248 +21,266 @@ import org.web3j.utils.Assertions; import org.web3j.utils.Numeric; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.math.BigInteger; -import java.util.Arrays; -import java.util.Collections; -import java.util.Objects; - public class ContractDeployer { - private static final BigInteger MAX_BYTECODE_SIZE = BigInteger.valueOf(2).pow(16); - public static final String CREATE_PREFIX = Hash.sha3String("zksyncCreate"); - public static final String CREATE2_PREFIX = Hash.sha3String("zksyncCreate2"); - - /** - * Compute contract address according EIP-1014 - * - * @param sender Address of a source of a transaction - * @param bytecode Compiled bytecode of the contract - * @param constructor Encoded constructor parameters - * @param salt 32 bytes salt - * @return Computed address of a contract - */ - public static Address computeL2Create2Address(Address sender, byte[] bytecode, byte[] constructor, byte[] salt) { - Assertions.verifyPrecondition(salt.length == 32, "Salt length must be 32 bytes"); - byte[] senderBytes = Numeric.toBytesPadded(sender.toUint().getValue(), 32); - byte[] bytecodeHash = hashBytecode(bytecode); - byte[] constructorHash = Hash.sha3(constructor); - - try (final ByteArrayOutputStream output = new ByteArrayOutputStream()) { - output.write(Numeric.hexStringToByteArray(CREATE2_PREFIX)); - output.write(senderBytes); - output.write(salt); - output.write(bytecodeHash); - output.write(constructorHash); - - byte[] result = Hash.sha3(output.toByteArray()); - - return new Address(Numeric.toBigInt(ArrayUtils.subarray(result, 12, result.length))); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - - /** - * Compute contract address - * - * @param sender Address of a source of a transaction - * @param nonce Deployment nonce (see {@link io.zksync.wrappers.NonceHolder}) - * @return Computed address of a contract - */ - public static Address computeL2CreateAddress(Address sender, BigInteger nonce) { - byte[] senderBytes = Numeric.toBytesPadded(sender.toUint().getValue(), 32); - byte[] nonceBytes = Numeric.toBytesPadded(nonce, 32); - - try (final ByteArrayOutputStream output = new ByteArrayOutputStream()) { - output.write(Numeric.hexStringToByteArray(CREATE_PREFIX)); - output.write(senderBytes); - output.write(nonceBytes); - - byte[] result = Hash.sha3(output.toByteArray()); - - return new Address(Numeric.toBigInt(ArrayUtils.subarray(result, 12, result.length))); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - - /** - * Extract correct deployed contract address from transaction receipt - * - * @param receipt Transaction receipt - * @return Address of the deployed contract - */ - public static Address extractContractAddress(TransactionReceipt receipt) { - Event contractDeployed = new Event("ContractDeployed", Arrays.asList(new TypeReference

(true) {}, new TypeReference(true) {}, new TypeReference
(true) {})); - - EventValues deployedEvent = receipt.getLogs().stream() - .map(log -> Contract.staticExtractEventParameters(contractDeployed, log)) - .filter(Objects::nonNull) - .reduce((ignore, last) -> last).orElseThrow(() -> new IllegalArgumentException("Receipt does not have any `ContractDeployed` event")); - - return (Address) deployedEvent.getIndexedValues().get(2); - } - - /** - * Generates SHA-256 digest for the given bytecode. - * - * @param bytecode Compiled bytecode of the contract - * @return The hash value for the given input - */ - public static byte[] hashBytecode(byte[] bytecode) { - byte[] bytecodeHash = Hash.sha256(bytecode); - - if (bytecode.length % 32 != 0) { - throw new IllegalArgumentException("The bytecode length in bytes must be divisible by 32"); - } - - BigInteger length = BigInteger.valueOf(bytecode.length / 32); - if (length.compareTo(MAX_BYTECODE_SIZE) > 0) { - throw new IllegalArgumentException("Bytecode length must be less than 2^16 bytes"); - } - - byte[] codeHashVersion = new byte[] { 1, 0 }; - byte[] bytecodeLength = Numeric.toBytesPadded(length, 2); - - System.arraycopy(codeHashVersion, 0, bytecodeHash, 0, codeHashVersion.length); - System.arraycopy(bytecodeLength, 0, bytecodeHash, 2, bytecodeLength.length); - - return bytecodeHash; - } - - /** - * Encode `create2` deployment function of default factory contract - * - * @param bytecode Compiled bytecode of the contract - * @return Encoded contract function - */ - public static Function encodeCreate2(byte[] bytecode) { - return encodeCreate2(bytecode, new byte[] {}, new byte[32]); - } - - /** - * Encode `create2` deployment function of default factory contract - * - * @param bytecode Compiled bytecode of the contract - * @param calldata Encoded constructor parameters - * @return Encoded contract function - */ - public static Function encodeCreate2(byte[] bytecode, byte[] calldata) { - return encodeCreate2(bytecode, calldata, new byte[32]); - } - - /** - * Encode `create2` deployment function of default factory contract - * - * @param bytecode Compiled bytecode of the contract - * @param calldata Encoded constructor parameters - * @param salt 32 bytes salt - * @return Encoded contract function - */ - public static Function encodeCreate2(byte[] bytecode, byte[] calldata, byte[] salt) { - Assertions.verifyPrecondition(salt.length == 32, "Salt length must be 32 bytes"); - byte[] bytecodeHash = hashBytecode(bytecode); - - return new Function( - "create2", - Arrays.asList(new Bytes32(salt), new Bytes32(bytecodeHash), new DynamicBytes(calldata)), - Collections.emptyList() - ); + private static final BigInteger MAX_BYTECODE_SIZE = BigInteger.valueOf(2).pow(16); + public static final String CREATE_PREFIX = Hash.sha3String("zksyncCreate"); + public static final String CREATE2_PREFIX = Hash.sha3String("zksyncCreate2"); + + /** + * Compute contract address according EIP-1014 + * + * @param sender Address of a source of a transaction + * @param bytecode Compiled bytecode of the contract + * @param constructor Encoded constructor parameters + * @param salt 32 bytes salt + * @return Computed address of a contract + */ + public static Address computeL2Create2Address( + Address sender, byte[] bytecode, byte[] constructor, byte[] salt) { + Assertions.verifyPrecondition(salt.length == 32, "Salt length must be 32 bytes"); + byte[] senderBytes = Numeric.toBytesPadded(sender.toUint().getValue(), 32); + byte[] bytecodeHash = hashBytecode(bytecode); + byte[] constructorHash = Hash.sha3(constructor); + + try (final ByteArrayOutputStream output = new ByteArrayOutputStream()) { + output.write(Numeric.hexStringToByteArray(CREATE2_PREFIX)); + output.write(senderBytes); + output.write(salt); + output.write(bytecodeHash); + output.write(constructorHash); + + byte[] result = Hash.sha3(output.toByteArray()); + + return new Address(Numeric.toBigInt(ArrayUtils.subarray(result, 12, result.length))); + } catch (IOException e) { + throw new RuntimeException(e); } - - /** - * Encode `create` deployment function of default factory contract - * - * @param bytecode Compiled bytecode of the contract - * @return Encoded contract function - */ - public static Function encodeCreate(byte[] bytecode) { - return encodeCreate(bytecode, new byte[] {}); - } - - /** - * Encode `create` deployment function of default factory contract - * - * @param bytecode Compiled bytecode of the contract - * @param calldata Encoded constructor parameters - * @return Encoded contract function - */ - public static Function encodeCreate(byte[] bytecode, byte[] calldata) { - byte[] bytecodeHash = hashBytecode(bytecode); - - return new Function( - "create", - Arrays.asList(new Bytes32(new byte[32]), new Bytes32(bytecodeHash), new DynamicBytes(calldata)), - Collections.emptyList() - ); - } - - /** - * Encode `create2` deployment custom account function of default factory contract (see EIP-4337) - * - * @param bytecode Compiled bytecode of the Custom Account contract - * @return Encoded contract function - */ - public static Function encodeCreate2Account(byte[] bytecode) { - return encodeCreate2Account(bytecode, new byte[] {}, new byte[32], AccountAbstractionVersion.Version1); + } + + /** + * Compute contract address + * + * @param sender Address of a source of a transaction + * @param nonce Deployment nonce (see {@link io.zksync.wrappers.NonceHolder}) + * @return Computed address of a contract + */ + public static Address computeL2CreateAddress(Address sender, BigInteger nonce) { + byte[] senderBytes = Numeric.toBytesPadded(sender.toUint().getValue(), 32); + byte[] nonceBytes = Numeric.toBytesPadded(nonce, 32); + + try (final ByteArrayOutputStream output = new ByteArrayOutputStream()) { + output.write(Numeric.hexStringToByteArray(CREATE_PREFIX)); + output.write(senderBytes); + output.write(nonceBytes); + + byte[] result = Hash.sha3(output.toByteArray()); + + return new Address(Numeric.toBigInt(ArrayUtils.subarray(result, 12, result.length))); + } catch (IOException e) { + throw new RuntimeException(e); } - - /** - * Encode `create2` deployment custom account function of default factory contract (see EIP-4337) - * - * @param bytecode Compiled bytecode of the Custom Account contract - * @param calldata Encoded constructor parameters - * @return Encoded contract function - */ - public static Function encodeCreate2Account(byte[] bytecode, byte[] calldata) { - return encodeCreate2Account(bytecode, calldata, new byte[32], AccountAbstractionVersion.Version1); - } - - /** - * Encode `create2` deployment custom account function of default factory contract (see EIP-4337) - * - * @param bytecode Compiled bytecode of the Custom Account contract - * @param calldata Encoded constructor parameters - * @param salt 32 bytes salt - * @return Encoded contract function - */ - public static Function encodeCreate2Account(byte[] bytecode, byte[] calldata, byte[] salt, AccountAbstractionVersion accountAbstractionVersion) { - Assertions.verifyPrecondition(salt.length == 32, "Salt length must be 32 bytes"); - byte[] bytecodeHash = hashBytecode(bytecode); - return new Function( - "create2Account", - Arrays.asList(new Bytes32(salt), new Bytes32(bytecodeHash), new DynamicBytes(calldata), new Uint8(accountAbstractionVersion.getRawValue())), - Collections.emptyList() - ); - } - - /** - * Encode `create` deployment custom account function of default factory contract (see EIP-4337) - * - * @param bytecode Compiled bytecode of the Custom Account contract - * @return Encoded contract function - */ - public static Function encodeCreateAccount(byte[] bytecode) { - return encodeCreateAccount(bytecode, new byte[] {}); + } + + /** + * Extract correct deployed contract address from transaction receipt + * + * @param receipt Transaction receipt + * @return Address of the deployed contract + */ + public static Address extractContractAddress(TransactionReceipt receipt) { + Event contractDeployed = + new Event( + "ContractDeployed", + Arrays.asList( + new TypeReference
(true) {}, + new TypeReference(true) {}, + new TypeReference
(true) {})); + + EventValues deployedEvent = + receipt.getLogs().stream() + .map(log -> Contract.staticExtractEventParameters(contractDeployed, log)) + .filter(Objects::nonNull) + .reduce((ignore, last) -> last) + .orElseThrow( + () -> + new IllegalArgumentException( + "Receipt does not have any `ContractDeployed` event")); + + return (Address) deployedEvent.getIndexedValues().get(2); + } + + /** + * Generates SHA-256 digest for the given bytecode. + * + * @param bytecode Compiled bytecode of the contract + * @return The hash value for the given input + */ + public static byte[] hashBytecode(byte[] bytecode) { + byte[] bytecodeHash = Hash.sha256(bytecode); + + if (bytecode.length % 32 != 0) { + throw new IllegalArgumentException("The bytecode length in bytes must be divisible by 32"); } - /** - * Encode `create` deployment custom account function of default factory contract (see EIP-4337) - * - * @param bytecode Compiled bytecode of the Custom Account contract - * @param calldata Encoded constructor parameters - * @return Encoded contract function - */ - public static Function encodeCreateAccount(byte[] bytecode, byte[] calldata) { - byte[] bytecodeHash = hashBytecode(bytecode); - - return new Function( - "createAccount", - Arrays.asList(new Bytes32(new byte[32]), new Bytes32(bytecodeHash), new DynamicBytes(calldata)), - Collections.emptyList() - ); + BigInteger length = BigInteger.valueOf(bytecode.length / 32); + if (length.compareTo(MAX_BYTECODE_SIZE) > 0) { + throw new IllegalArgumentException("Bytecode length must be less than 2^16 bytes"); } + byte[] codeHashVersion = new byte[] {1, 0}; + byte[] bytecodeLength = Numeric.toBytesPadded(length, 2); + + System.arraycopy(codeHashVersion, 0, bytecodeHash, 0, codeHashVersion.length); + System.arraycopy(bytecodeLength, 0, bytecodeHash, 2, bytecodeLength.length); + + return bytecodeHash; + } + + /** + * Encode `create2` deployment function of default factory contract + * + * @param bytecode Compiled bytecode of the contract + * @return Encoded contract function + */ + public static Function encodeCreate2(byte[] bytecode) { + return encodeCreate2(bytecode, new byte[] {}, new byte[32]); + } + + /** + * Encode `create2` deployment function of default factory contract + * + * @param bytecode Compiled bytecode of the contract + * @param calldata Encoded constructor parameters + * @return Encoded contract function + */ + public static Function encodeCreate2(byte[] bytecode, byte[] calldata) { + return encodeCreate2(bytecode, calldata, new byte[32]); + } + + /** + * Encode `create2` deployment function of default factory contract + * + * @param bytecode Compiled bytecode of the contract + * @param calldata Encoded constructor parameters + * @param salt 32 bytes salt + * @return Encoded contract function + */ + public static Function encodeCreate2(byte[] bytecode, byte[] calldata, byte[] salt) { + Assertions.verifyPrecondition(salt.length == 32, "Salt length must be 32 bytes"); + byte[] bytecodeHash = hashBytecode(bytecode); + + return new Function( + "create2", + Arrays.asList(new Bytes32(salt), new Bytes32(bytecodeHash), new DynamicBytes(calldata)), + Collections.emptyList()); + } + + /** + * Encode `create` deployment function of default factory contract + * + * @param bytecode Compiled bytecode of the contract + * @return Encoded contract function + */ + public static Function encodeCreate(byte[] bytecode) { + return encodeCreate(bytecode, new byte[] {}); + } + + /** + * Encode `create` deployment function of default factory contract + * + * @param bytecode Compiled bytecode of the contract + * @param calldata Encoded constructor parameters + * @return Encoded contract function + */ + public static Function encodeCreate(byte[] bytecode, byte[] calldata) { + byte[] bytecodeHash = hashBytecode(bytecode); + + return new Function( + "create", + Arrays.asList( + new Bytes32(new byte[32]), new Bytes32(bytecodeHash), new DynamicBytes(calldata)), + Collections.emptyList()); + } + + /** + * Encode `create2` deployment custom account function of default factory contract (see EIP-4337) + * + * @param bytecode Compiled bytecode of the Custom Account contract + * @return Encoded contract function + */ + public static Function encodeCreate2Account(byte[] bytecode) { + return encodeCreate2Account( + bytecode, new byte[] {}, new byte[32], AccountAbstractionVersion.Version1); + } + + /** + * Encode `create2` deployment custom account function of default factory contract (see EIP-4337) + * + * @param bytecode Compiled bytecode of the Custom Account contract + * @param calldata Encoded constructor parameters + * @return Encoded contract function + */ + public static Function encodeCreate2Account(byte[] bytecode, byte[] calldata) { + return encodeCreate2Account( + bytecode, calldata, new byte[32], AccountAbstractionVersion.Version1); + } + + /** + * Encode `create2` deployment custom account function of default factory contract (see EIP-4337) + * + * @param bytecode Compiled bytecode of the Custom Account contract + * @param calldata Encoded constructor parameters + * @param salt 32 bytes salt + * @return Encoded contract function + */ + public static Function encodeCreate2Account( + byte[] bytecode, + byte[] calldata, + byte[] salt, + AccountAbstractionVersion accountAbstractionVersion) { + Assertions.verifyPrecondition(salt.length == 32, "Salt length must be 32 bytes"); + byte[] bytecodeHash = hashBytecode(bytecode); + return new Function( + "create2Account", + Arrays.asList( + new Bytes32(salt), + new Bytes32(bytecodeHash), + new DynamicBytes(calldata), + new Uint8(accountAbstractionVersion.getRawValue())), + Collections.emptyList()); + } + + /** + * Encode `create` deployment custom account function of default factory contract (see EIP-4337) + * + * @param bytecode Compiled bytecode of the Custom Account contract + * @return Encoded contract function + */ + public static Function encodeCreateAccount(byte[] bytecode) { + return encodeCreateAccount(bytecode, new byte[] {}); + } + + /** + * Encode `create` deployment custom account function of default factory contract (see EIP-4337) + * + * @param bytecode Compiled bytecode of the Custom Account contract + * @param calldata Encoded constructor parameters + * @return Encoded contract function + */ + public static Function encodeCreateAccount(byte[] bytecode, byte[] calldata) { + byte[] bytecodeHash = hashBytecode(bytecode); + + return new Function( + "createAccount", + Arrays.asList( + new Bytes32(new byte[32]), new Bytes32(bytecodeHash), new DynamicBytes(calldata)), + Collections.emptyList()); + } } diff --git a/src/main/java/io/zksync/utils/Messenger.java b/src/main/java/io/zksync/utils/Messenger.java index cb13aa9..250691d 100644 --- a/src/main/java/io/zksync/utils/Messenger.java +++ b/src/main/java/io/zksync/utils/Messenger.java @@ -1,48 +1,48 @@ package io.zksync.utils; import io.zksync.protocol.core.L2ToL1MessageProof; -import org.apache.commons.lang3.ArrayUtils; -import org.web3j.abi.datatypes.Address; -import org.web3j.crypto.Hash; -import org.web3j.utils.Numeric; - import java.io.ByteArrayOutputStream; import java.io.IOException; import java.math.BigInteger; import java.util.Arrays; +import org.apache.commons.lang3.ArrayUtils; +import org.web3j.abi.datatypes.Address; +import org.web3j.crypto.Hash; +import org.web3j.utils.Numeric; public class Messenger { - public static byte[] getHashedMessage(Address sender, byte[] message, BigInteger txNumberInBlock) { - byte[] messageHash = Hash.sha3(message); - try (final ByteArrayOutputStream output = new ByteArrayOutputStream()) { - output.write(0); - output.write(1); - output.write(Numeric.toBytesPadded(txNumberInBlock, 2)); - output.write(Numeric.hexStringToByteArray(ZkSyncAddresses.MESSENGER_ADDRESS)); - output.write(Numeric.toBytesPadded(sender.toUint().getValue(), 32)); - output.write(messageHash); - - return Hash.sha3(output.toByteArray()); - } catch (IOException e) { - throw new RuntimeException(e); - } + public static byte[] getHashedMessage( + Address sender, byte[] message, BigInteger txNumberInBlock) { + byte[] messageHash = Hash.sha3(message); + try (final ByteArrayOutputStream output = new ByteArrayOutputStream()) { + output.write(0); + output.write(1); + output.write(Numeric.toBytesPadded(txNumberInBlock, 2)); + output.write(Numeric.hexStringToByteArray(ZkSyncAddresses.MESSENGER_ADDRESS)); + output.write(Numeric.toBytesPadded(sender.toUint().getValue(), 32)); + output.write(messageHash); + + return Hash.sha3(output.toByteArray()); + } catch (IOException e) { + throw new RuntimeException(e); } + } - public static boolean verifyMessage(L2ToL1MessageProof proof, byte[] messageHash) { - int id = proof.getId(); - - byte[] result = messageHash; - for (String e : proof.getProof()) { - byte[] bytes = (id & 1) == 0 ? - ArrayUtils.addAll(result, Numeric.hexStringToByteArray(e)) : - ArrayUtils.addAll(Numeric.hexStringToByteArray(e), result); + public static boolean verifyMessage(L2ToL1MessageProof proof, byte[] messageHash) { + int id = proof.getId(); - result = Hash.sha3(bytes); - id /= 2; - } + byte[] result = messageHash; + for (String e : proof.getProof()) { + byte[] bytes = + (id & 1) == 0 + ? ArrayUtils.addAll(result, Numeric.hexStringToByteArray(e)) + : ArrayUtils.addAll(Numeric.hexStringToByteArray(e), result); - return Arrays.equals(result, Numeric.hexStringToByteArray(proof.getRoot())); + result = Hash.sha3(bytes); + id /= 2; } + return Arrays.equals(result, Numeric.hexStringToByteArray(proof.getRoot())); + } } diff --git a/src/main/java/io/zksync/utils/Paymaster.java b/src/main/java/io/zksync/utils/Paymaster.java index 9ad2ce5..abe7281 100644 --- a/src/main/java/io/zksync/utils/Paymaster.java +++ b/src/main/java/io/zksync/utils/Paymaster.java @@ -1,23 +1,30 @@ package io.zksync.utils; +import java.math.BigInteger; +import java.util.Arrays; +import java.util.Collections; import org.web3j.abi.datatypes.Address; import org.web3j.abi.datatypes.DynamicBytes; import org.web3j.abi.datatypes.Function; import org.web3j.abi.datatypes.generated.Uint256; -import java.math.BigInteger; -import java.util.Arrays; -import java.util.Collections; - public class Paymaster { - private final static String GENERAL_FUNCTION = "general"; - private final static String APPROVAL_BASED_FUNCTION = "approvalBased"; + private static final String GENERAL_FUNCTION = "general"; + private static final String APPROVAL_BASED_FUNCTION = "approvalBased"; - public static Function encodeGeneral(byte[] input) { - return new Function(GENERAL_FUNCTION, Collections.singletonList(new DynamicBytes(input)), Collections.emptyList()); - } + public static Function encodeGeneral(byte[] input) { + return new Function( + GENERAL_FUNCTION, + Collections.singletonList(new DynamicBytes(input)), + Collections.emptyList()); + } - public static Function encodeApprovalBased(String tokenAddress, BigInteger minimalAllowance, byte[] input) { - return new Function(APPROVAL_BASED_FUNCTION, Arrays.asList(new Address(tokenAddress), new Uint256(minimalAllowance), new DynamicBytes(input)), Collections.emptyList()); - } + public static Function encodeApprovalBased( + String tokenAddress, BigInteger minimalAllowance, byte[] input) { + return new Function( + APPROVAL_BASED_FUNCTION, + Arrays.asList( + new Address(tokenAddress), new Uint256(minimalAllowance), new DynamicBytes(input)), + Collections.emptyList()); + } } diff --git a/src/main/java/io/zksync/utils/ZkSyncAddresses.java b/src/main/java/io/zksync/utils/ZkSyncAddresses.java index 9c5d4b3..0328e95 100644 --- a/src/main/java/io/zksync/utils/ZkSyncAddresses.java +++ b/src/main/java/io/zksync/utils/ZkSyncAddresses.java @@ -2,10 +2,10 @@ public final class ZkSyncAddresses { - public static final String ETH_ADDRESS = "0x0000000000000000000000000000000000000000"; - public static final String CONTRACT_DEPLOYER_ADDRESS = "0x0000000000000000000000000000000000008006"; - public static final String NONCE_HOLDER_ADDRESS = "0x0000000000000000000000000000000000008003"; - public static final String MESSENGER_ADDRESS = "0x0000000000000000000000000000000000008008"; - public static final String L2_ETH_TOKEN_ADDRESS = "0x000000000000000000000000000000000000800a"; - + public static final String ETH_ADDRESS = "0x0000000000000000000000000000000000000000"; + public static final String CONTRACT_DEPLOYER_ADDRESS = + "0x0000000000000000000000000000000000008006"; + public static final String NONCE_HOLDER_ADDRESS = "0x0000000000000000000000000000000000008003"; + public static final String MESSENGER_ADDRESS = "0x0000000000000000000000000000000000008008"; + public static final String L2_ETH_TOKEN_ADDRESS = "0x000000000000000000000000000000000000800a"; } diff --git a/src/main/java/io/zksync/wrappers/ERC20.java b/src/main/java/io/zksync/wrappers/ERC20.java index 43d7520..87ba9dd 100644 --- a/src/main/java/io/zksync/wrappers/ERC20.java +++ b/src/main/java/io/zksync/wrappers/ERC20.java @@ -27,262 +27,348 @@ import org.web3j.tx.gas.ContractGasProvider; /** - *

Auto generated code. + * Auto generated code. + * *

Do not modify! + * *

Please use the web3j command line tools, - * or the org.web3j.codegen.SolidityFunctionWrapperGenerator in the - * codegen module to update. + * or the org.web3j.codegen.SolidityFunctionWrapperGenerator in the codegen module to update. * *

Generated with web3j version 4.1.1. */ public class ERC20 extends Contract { - private static final String BINARY = "Bin file was not provided"; - - public static final String FUNC_NAME = "name"; - - public static final String FUNC_APPROVE = "approve"; - - public static final String FUNC_TOTALSUPPLY = "totalSupply"; - - public static final String FUNC_TRANSFERFROM = "transferFrom"; - - public static final String FUNC_DECIMALS = "decimals"; - - public static final String FUNC_BALANCEOF = "balanceOf"; - - public static final String FUNC_SYMBOL = "symbol"; - - public static final String FUNC_TRANSFER = "transfer"; - - public static final String FUNC_ALLOWANCE = "allowance"; - - public static final Event TRANSFER_EVENT = new Event("Transfer", - Arrays.>asList(new TypeReference

(true) {}, new TypeReference
(true) {}, new TypeReference() {})); - ; - - public static final Event APPROVAL_EVENT = new Event("Approval", - Arrays.>asList(new TypeReference
(true) {}, new TypeReference
(true) {}, new TypeReference() {})); - ; - - @Deprecated - protected ERC20(String contractAddress, Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) { - super(BINARY, contractAddress, web3j, credentials, gasPrice, gasLimit); - } - - protected ERC20(String contractAddress, Web3j web3j, Credentials credentials, ContractGasProvider contractGasProvider) { - super(BINARY, contractAddress, web3j, credentials, contractGasProvider); - } - - @Deprecated - protected ERC20(String contractAddress, Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit) { - super(BINARY, contractAddress, web3j, transactionManager, gasPrice, gasLimit); - } - - protected ERC20(String contractAddress, Web3j web3j, TransactionManager transactionManager, ContractGasProvider contractGasProvider) { - super(BINARY, contractAddress, web3j, transactionManager, contractGasProvider); - } - - public RemoteCall name() { - final Function function = new Function(FUNC_NAME, - Arrays.asList(), - Arrays.>asList(new TypeReference() {})); - return executeRemoteCallSingleValueReturn(function, String.class); - } - - public RemoteCall approve(String _spender, BigInteger _value) { - final Function function = new Function( - FUNC_APPROVE, - Arrays.asList(new org.web3j.abi.datatypes.Address(_spender), - new org.web3j.abi.datatypes.generated.Uint256(_value)), - Collections.>emptyList()); - return executeRemoteCallTransaction(function); - } - - public RemoteCall totalSupply() { - final Function function = new Function(FUNC_TOTALSUPPLY, - Arrays.asList(), - Arrays.>asList(new TypeReference() {})); - return executeRemoteCallSingleValueReturn(function, BigInteger.class); - } - - public RemoteCall transferFrom(String _from, String _to, BigInteger _value) { - final Function function = new Function( - FUNC_TRANSFERFROM, - Arrays.asList(new org.web3j.abi.datatypes.Address(_from), - new org.web3j.abi.datatypes.Address(_to), - new org.web3j.abi.datatypes.generated.Uint256(_value)), - Collections.>emptyList()); - return executeRemoteCallTransaction(function); - } - - public RemoteCall decimals() { - final Function function = new Function(FUNC_DECIMALS, - Arrays.asList(), - Arrays.>asList(new TypeReference() {})); - return executeRemoteCallSingleValueReturn(function, BigInteger.class); - } - - public RemoteCall balanceOf(String _owner) { - final Function function = new Function(FUNC_BALANCEOF, - Arrays.asList(new org.web3j.abi.datatypes.Address(_owner)), - Arrays.>asList(new TypeReference() {})); - return executeRemoteCallSingleValueReturn(function, BigInteger.class); - } - - public RemoteCall symbol() { - final Function function = new Function(FUNC_SYMBOL, - Arrays.asList(), - Arrays.>asList(new TypeReference() {})); - return executeRemoteCallSingleValueReturn(function, String.class); - } - - public RemoteCall transfer(String _to, BigInteger _value) { - final Function function = new Function( - FUNC_TRANSFER, - Arrays.asList(new org.web3j.abi.datatypes.Address(_to), - new org.web3j.abi.datatypes.generated.Uint256(_value)), - Collections.>emptyList()); - return executeRemoteCallTransaction(function); - } - - public RemoteCall allowance(String _owner, String _spender) { - final Function function = new Function(FUNC_ALLOWANCE, - Arrays.asList(new org.web3j.abi.datatypes.Address(_owner), - new org.web3j.abi.datatypes.Address(_spender)), - Arrays.>asList(new TypeReference() {})); - return executeRemoteCallSingleValueReturn(function, BigInteger.class); - } - - public static Function encodeTransfer(String _to, BigInteger _value) { - return new Function( - FUNC_TRANSFER, - Arrays.asList(new org.web3j.abi.datatypes.Address(_to), - new org.web3j.abi.datatypes.generated.Uint256(_value)), + private static final String BINARY = "Bin file was not provided"; + + public static final String FUNC_NAME = "name"; + + public static final String FUNC_APPROVE = "approve"; + + public static final String FUNC_TOTALSUPPLY = "totalSupply"; + + public static final String FUNC_TRANSFERFROM = "transferFrom"; + + public static final String FUNC_DECIMALS = "decimals"; + + public static final String FUNC_BALANCEOF = "balanceOf"; + + public static final String FUNC_SYMBOL = "symbol"; + + public static final String FUNC_TRANSFER = "transfer"; + + public static final String FUNC_ALLOWANCE = "allowance"; + + public static final Event TRANSFER_EVENT = + new Event( + "Transfer", + Arrays.>asList( + new TypeReference
(true) {}, + new TypeReference
(true) {}, + new TypeReference() {})); + ; + + public static final Event APPROVAL_EVENT = + new Event( + "Approval", + Arrays.>asList( + new TypeReference
(true) {}, + new TypeReference
(true) {}, + new TypeReference() {})); + ; + + @Deprecated + protected ERC20( + String contractAddress, + Web3j web3j, + Credentials credentials, + BigInteger gasPrice, + BigInteger gasLimit) { + super(BINARY, contractAddress, web3j, credentials, gasPrice, gasLimit); + } + + protected ERC20( + String contractAddress, + Web3j web3j, + Credentials credentials, + ContractGasProvider contractGasProvider) { + super(BINARY, contractAddress, web3j, credentials, contractGasProvider); + } + + @Deprecated + protected ERC20( + String contractAddress, + Web3j web3j, + TransactionManager transactionManager, + BigInteger gasPrice, + BigInteger gasLimit) { + super(BINARY, contractAddress, web3j, transactionManager, gasPrice, gasLimit); + } + + protected ERC20( + String contractAddress, + Web3j web3j, + TransactionManager transactionManager, + ContractGasProvider contractGasProvider) { + super(BINARY, contractAddress, web3j, transactionManager, contractGasProvider); + } + + public RemoteCall name() { + final Function function = + new Function( + FUNC_NAME, + Arrays.asList(), + Arrays.>asList(new TypeReference() {})); + return executeRemoteCallSingleValueReturn(function, String.class); + } + + public RemoteCall approve(String _spender, BigInteger _value) { + final Function function = + new Function( + FUNC_APPROVE, + Arrays.asList( + new org.web3j.abi.datatypes.Address(_spender), + new org.web3j.abi.datatypes.generated.Uint256(_value)), Collections.>emptyList()); - } - - public static Function encodeTransferFrom(String _from, String _to, BigInteger _value) { - return new Function( - FUNC_TRANSFERFROM, - Arrays.asList(new org.web3j.abi.datatypes.Address(_from), - new org.web3j.abi.datatypes.Address(_to), - new org.web3j.abi.datatypes.generated.Uint256(_value)), + return executeRemoteCallTransaction(function); + } + + public RemoteCall totalSupply() { + final Function function = + new Function( + FUNC_TOTALSUPPLY, + Arrays.asList(), + Arrays.>asList(new TypeReference() {})); + return executeRemoteCallSingleValueReturn(function, BigInteger.class); + } + + public RemoteCall transferFrom(String _from, String _to, BigInteger _value) { + final Function function = + new Function( + FUNC_TRANSFERFROM, + Arrays.asList( + new org.web3j.abi.datatypes.Address(_from), + new org.web3j.abi.datatypes.Address(_to), + new org.web3j.abi.datatypes.generated.Uint256(_value)), Collections.>emptyList()); - } - - public static Function encodeApprove(String _spender, BigInteger _value) { - return new Function( - FUNC_APPROVE, - Arrays.asList(new org.web3j.abi.datatypes.Address(_spender), - new org.web3j.abi.datatypes.generated.Uint256(_value)), + return executeRemoteCallTransaction(function); + } + + public RemoteCall decimals() { + final Function function = + new Function( + FUNC_DECIMALS, + Arrays.asList(), + Arrays.>asList(new TypeReference() {})); + return executeRemoteCallSingleValueReturn(function, BigInteger.class); + } + + public RemoteCall balanceOf(String _owner) { + final Function function = + new Function( + FUNC_BALANCEOF, + Arrays.asList(new org.web3j.abi.datatypes.Address(_owner)), + Arrays.>asList(new TypeReference() {})); + return executeRemoteCallSingleValueReturn(function, BigInteger.class); + } + + public RemoteCall symbol() { + final Function function = + new Function( + FUNC_SYMBOL, + Arrays.asList(), + Arrays.>asList(new TypeReference() {})); + return executeRemoteCallSingleValueReturn(function, String.class); + } + + public RemoteCall transfer(String _to, BigInteger _value) { + final Function function = + new Function( + FUNC_TRANSFER, + Arrays.asList( + new org.web3j.abi.datatypes.Address(_to), + new org.web3j.abi.datatypes.generated.Uint256(_value)), Collections.>emptyList()); + return executeRemoteCallTransaction(function); + } + + public RemoteCall allowance(String _owner, String _spender) { + final Function function = + new Function( + FUNC_ALLOWANCE, + Arrays.asList( + new org.web3j.abi.datatypes.Address(_owner), + new org.web3j.abi.datatypes.Address(_spender)), + Arrays.>asList(new TypeReference() {})); + return executeRemoteCallSingleValueReturn(function, BigInteger.class); + } + + public static Function encodeTransfer(String _to, BigInteger _value) { + return new Function( + FUNC_TRANSFER, + Arrays.asList( + new org.web3j.abi.datatypes.Address(_to), + new org.web3j.abi.datatypes.generated.Uint256(_value)), + Collections.>emptyList()); + } + + public static Function encodeTransferFrom(String _from, String _to, BigInteger _value) { + return new Function( + FUNC_TRANSFERFROM, + Arrays.asList( + new org.web3j.abi.datatypes.Address(_from), + new org.web3j.abi.datatypes.Address(_to), + new org.web3j.abi.datatypes.generated.Uint256(_value)), + Collections.>emptyList()); + } + + public static Function encodeApprove(String _spender, BigInteger _value) { + return new Function( + FUNC_APPROVE, + Arrays.asList( + new org.web3j.abi.datatypes.Address(_spender), + new org.web3j.abi.datatypes.generated.Uint256(_value)), + Collections.>emptyList()); + } + + public List getTransferEvents(TransactionReceipt transactionReceipt) { + List valueList = + extractEventParametersWithLog(TRANSFER_EVENT, transactionReceipt); + ArrayList responses = + new ArrayList(valueList.size()); + for (Contract.EventValuesWithLog eventValues : valueList) { + TransferEventResponse typedResponse = new TransferEventResponse(); + typedResponse.log = eventValues.getLog(); + typedResponse._from = (String) eventValues.getIndexedValues().get(0).getValue(); + typedResponse._to = (String) eventValues.getIndexedValues().get(1).getValue(); + typedResponse._value = (BigInteger) eventValues.getNonIndexedValues().get(0).getValue(); + responses.add(typedResponse); } - - public List getTransferEvents(TransactionReceipt transactionReceipt) { - List valueList = extractEventParametersWithLog(TRANSFER_EVENT, transactionReceipt); - ArrayList responses = new ArrayList(valueList.size()); - for (Contract.EventValuesWithLog eventValues : valueList) { - TransferEventResponse typedResponse = new TransferEventResponse(); - typedResponse.log = eventValues.getLog(); - typedResponse._from = (String) eventValues.getIndexedValues().get(0).getValue(); - typedResponse._to = (String) eventValues.getIndexedValues().get(1).getValue(); - typedResponse._value = (BigInteger) eventValues.getNonIndexedValues().get(0).getValue(); - responses.add(typedResponse); - } - return responses; - } - - public Flowable transferEventFlowable(EthFilter filter) { - return web3j.ethLogFlowable(filter).map(new io.reactivex.functions.Function() { - @Override - public TransferEventResponse apply(Log log) { - Contract.EventValuesWithLog eventValues = extractEventParametersWithLog(TRANSFER_EVENT, log); + return responses; + } + + public Flowable transferEventFlowable(EthFilter filter) { + return web3j + .ethLogFlowable(filter) + .map( + new io.reactivex.functions.Function() { + @Override + public TransferEventResponse apply(Log log) { + Contract.EventValuesWithLog eventValues = + extractEventParametersWithLog(TRANSFER_EVENT, log); TransferEventResponse typedResponse = new TransferEventResponse(); typedResponse.log = log; typedResponse._from = (String) eventValues.getIndexedValues().get(0).getValue(); typedResponse._to = (String) eventValues.getIndexedValues().get(1).getValue(); - typedResponse._value = (BigInteger) eventValues.getNonIndexedValues().get(0).getValue(); + typedResponse._value = + (BigInteger) eventValues.getNonIndexedValues().get(0).getValue(); return typedResponse; - } - }); - } - - public Flowable transferEventFlowable(DefaultBlockParameter startBlock, DefaultBlockParameter endBlock) { - EthFilter filter = new EthFilter(startBlock, endBlock, getContractAddress()); - filter.addSingleTopic(EventEncoder.encode(TRANSFER_EVENT)); - return transferEventFlowable(filter); - } - - public List getApprovalEvents(TransactionReceipt transactionReceipt) { - List valueList = extractEventParametersWithLog(APPROVAL_EVENT, transactionReceipt); - ArrayList responses = new ArrayList(valueList.size()); - for (Contract.EventValuesWithLog eventValues : valueList) { - ApprovalEventResponse typedResponse = new ApprovalEventResponse(); - typedResponse.log = eventValues.getLog(); - typedResponse._owner = (String) eventValues.getIndexedValues().get(0).getValue(); - typedResponse._spender = (String) eventValues.getIndexedValues().get(1).getValue(); - typedResponse._value = (BigInteger) eventValues.getNonIndexedValues().get(0).getValue(); - responses.add(typedResponse); - } - return responses; + } + }); + } + + public Flowable transferEventFlowable( + DefaultBlockParameter startBlock, DefaultBlockParameter endBlock) { + EthFilter filter = new EthFilter(startBlock, endBlock, getContractAddress()); + filter.addSingleTopic(EventEncoder.encode(TRANSFER_EVENT)); + return transferEventFlowable(filter); + } + + public List getApprovalEvents(TransactionReceipt transactionReceipt) { + List valueList = + extractEventParametersWithLog(APPROVAL_EVENT, transactionReceipt); + ArrayList responses = + new ArrayList(valueList.size()); + for (Contract.EventValuesWithLog eventValues : valueList) { + ApprovalEventResponse typedResponse = new ApprovalEventResponse(); + typedResponse.log = eventValues.getLog(); + typedResponse._owner = (String) eventValues.getIndexedValues().get(0).getValue(); + typedResponse._spender = (String) eventValues.getIndexedValues().get(1).getValue(); + typedResponse._value = (BigInteger) eventValues.getNonIndexedValues().get(0).getValue(); + responses.add(typedResponse); } - - public Flowable approvalEventFlowable(EthFilter filter) { - return web3j.ethLogFlowable(filter).map(new io.reactivex.functions.Function() { - @Override - public ApprovalEventResponse apply(Log log) { - Contract.EventValuesWithLog eventValues = extractEventParametersWithLog(APPROVAL_EVENT, log); + return responses; + } + + public Flowable approvalEventFlowable(EthFilter filter) { + return web3j + .ethLogFlowable(filter) + .map( + new io.reactivex.functions.Function() { + @Override + public ApprovalEventResponse apply(Log log) { + Contract.EventValuesWithLog eventValues = + extractEventParametersWithLog(APPROVAL_EVENT, log); ApprovalEventResponse typedResponse = new ApprovalEventResponse(); typedResponse.log = log; typedResponse._owner = (String) eventValues.getIndexedValues().get(0).getValue(); typedResponse._spender = (String) eventValues.getIndexedValues().get(1).getValue(); - typedResponse._value = (BigInteger) eventValues.getNonIndexedValues().get(0).getValue(); + typedResponse._value = + (BigInteger) eventValues.getNonIndexedValues().get(0).getValue(); return typedResponse; - } - }); - } - - public Flowable approvalEventFlowable(DefaultBlockParameter startBlock, DefaultBlockParameter endBlock) { - EthFilter filter = new EthFilter(startBlock, endBlock, getContractAddress()); - filter.addSingleTopic(EventEncoder.encode(APPROVAL_EVENT)); - return approvalEventFlowable(filter); - } - - @Deprecated - public static ERC20 load(String contractAddress, Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) { - return new ERC20(contractAddress, web3j, credentials, gasPrice, gasLimit); - } - - @Deprecated - public static ERC20 load(String contractAddress, Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit) { - return new ERC20(contractAddress, web3j, transactionManager, gasPrice, gasLimit); - } - - public static ERC20 load(String contractAddress, Web3j web3j, Credentials credentials, ContractGasProvider contractGasProvider) { - return new ERC20(contractAddress, web3j, credentials, contractGasProvider); - } - - public static ERC20 load(String contractAddress, Web3j web3j, TransactionManager transactionManager, ContractGasProvider contractGasProvider) { - return new ERC20(contractAddress, web3j, transactionManager, contractGasProvider); - } - - public static class TransferEventResponse { - public Log log; - - public String _from; - - public String _to; - - public BigInteger _value; - } - - public static class ApprovalEventResponse { - public Log log; - - public String _owner; - - public String _spender; - - public BigInteger _value; - } + } + }); + } + + public Flowable approvalEventFlowable( + DefaultBlockParameter startBlock, DefaultBlockParameter endBlock) { + EthFilter filter = new EthFilter(startBlock, endBlock, getContractAddress()); + filter.addSingleTopic(EventEncoder.encode(APPROVAL_EVENT)); + return approvalEventFlowable(filter); + } + + @Deprecated + public static ERC20 load( + String contractAddress, + Web3j web3j, + Credentials credentials, + BigInteger gasPrice, + BigInteger gasLimit) { + return new ERC20(contractAddress, web3j, credentials, gasPrice, gasLimit); + } + + @Deprecated + public static ERC20 load( + String contractAddress, + Web3j web3j, + TransactionManager transactionManager, + BigInteger gasPrice, + BigInteger gasLimit) { + return new ERC20(contractAddress, web3j, transactionManager, gasPrice, gasLimit); + } + + public static ERC20 load( + String contractAddress, + Web3j web3j, + Credentials credentials, + ContractGasProvider contractGasProvider) { + return new ERC20(contractAddress, web3j, credentials, contractGasProvider); + } + + public static ERC20 load( + String contractAddress, + Web3j web3j, + TransactionManager transactionManager, + ContractGasProvider contractGasProvider) { + return new ERC20(contractAddress, web3j, transactionManager, contractGasProvider); + } + + public static class TransferEventResponse { + public Log log; + + public String _from; + + public String _to; + + public BigInteger _value; + } + + public static class ApprovalEventResponse { + public Log log; + + public String _owner; + + public String _spender; + + public BigInteger _value; + } } diff --git a/src/main/java/io/zksync/wrappers/IL1Bridge.java b/src/main/java/io/zksync/wrappers/IL1Bridge.java index 3d190cf..5ddc338 100644 --- a/src/main/java/io/zksync/wrappers/IL1Bridge.java +++ b/src/main/java/io/zksync/wrappers/IL1Bridge.java @@ -29,295 +29,421 @@ import org.web3j.tx.gas.ContractGasProvider; /** - *

Auto generated code. + * Auto generated code. + * *

Do not modify! + * *

Please use the web3j command line tools, - * or the org.web3j.codegen.SolidityFunctionWrapperGenerator in the - * codegen module to update. + * or the org.web3j.codegen.SolidityFunctionWrapperGenerator in the codegen module to update. * *

Generated with web3j version 1.4.2. */ @SuppressWarnings("rawtypes") public class IL1Bridge extends Contract { - public static final String BINARY = "0x"; - - public static final String FUNC_CLAIMFAILEDDEPOSIT = "claimFailedDeposit"; - - public static final String FUNC_DEPOSIT = "deposit"; - - public static final String FUNC_FINALIZEWITHDRAWAL = "finalizeWithdrawal"; - - public static final String FUNC_ISWITHDRAWALFINALIZED = "isWithdrawalFinalized"; - - public static final String FUNC_L2TOKENADDRESS = "l2TokenAddress"; - - public static final Event CLAIMEDFAILEDDEPOSIT_EVENT = new Event("ClaimedFailedDeposit", - Arrays.>asList(new TypeReference

(true) {}, new TypeReference
(true) {}, new TypeReference() {})); - ; - - public static final Event DEPOSITINITIATED_EVENT = new Event("DepositInitiated", - Arrays.>asList(new TypeReference
(true) {}, new TypeReference
(true) {}, new TypeReference
(true) {}, new TypeReference() {})); - ; - - public static final Event WITHDRAWALFINALIZED_EVENT = new Event("WithdrawalFinalized", - Arrays.>asList(new TypeReference
(true) {}, new TypeReference
(true) {}, new TypeReference() {})); - ; - - protected static final HashMap _addresses; - - static { - _addresses = new HashMap(); - } - - @Deprecated - protected IL1Bridge(String contractAddress, Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) { - super(BINARY, contractAddress, web3j, credentials, gasPrice, gasLimit); - } - - protected IL1Bridge(String contractAddress, Web3j web3j, Credentials credentials, ContractGasProvider contractGasProvider) { - super(BINARY, contractAddress, web3j, credentials, contractGasProvider); - } - - @Deprecated - protected IL1Bridge(String contractAddress, Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit) { - super(BINARY, contractAddress, web3j, transactionManager, gasPrice, gasLimit); - } - - protected IL1Bridge(String contractAddress, Web3j web3j, TransactionManager transactionManager, ContractGasProvider contractGasProvider) { - super(BINARY, contractAddress, web3j, transactionManager, contractGasProvider); - } - - public static List getClaimedFailedDepositEvents(TransactionReceipt transactionReceipt) { - List valueList = staticExtractEventParametersWithLog(CLAIMEDFAILEDDEPOSIT_EVENT, transactionReceipt); - ArrayList responses = new ArrayList(valueList.size()); - for (Contract.EventValuesWithLog eventValues : valueList) { - ClaimedFailedDepositEventResponse typedResponse = new ClaimedFailedDepositEventResponse(); - typedResponse.log = eventValues.getLog(); - typedResponse.to = (String) eventValues.getIndexedValues().get(0).getValue(); - typedResponse.l1Token = (String) eventValues.getIndexedValues().get(1).getValue(); - typedResponse.amount = (BigInteger) eventValues.getNonIndexedValues().get(0).getValue(); - responses.add(typedResponse); - } - return responses; - } - - public Flowable claimedFailedDepositEventFlowable(EthFilter filter) { - return web3j.ethLogFlowable(filter).map(new Function() { - @Override - public ClaimedFailedDepositEventResponse apply(Log log) { - Contract.EventValuesWithLog eventValues = extractEventParametersWithLog(CLAIMEDFAILEDDEPOSIT_EVENT, log); - ClaimedFailedDepositEventResponse typedResponse = new ClaimedFailedDepositEventResponse(); + public static final String BINARY = "0x"; + + public static final String FUNC_CLAIMFAILEDDEPOSIT = "claimFailedDeposit"; + + public static final String FUNC_DEPOSIT = "deposit"; + + public static final String FUNC_FINALIZEWITHDRAWAL = "finalizeWithdrawal"; + + public static final String FUNC_ISWITHDRAWALFINALIZED = "isWithdrawalFinalized"; + + public static final String FUNC_L2TOKENADDRESS = "l2TokenAddress"; + + public static final Event CLAIMEDFAILEDDEPOSIT_EVENT = + new Event( + "ClaimedFailedDeposit", + Arrays.>asList( + new TypeReference
(true) {}, + new TypeReference
(true) {}, + new TypeReference() {})); + ; + + public static final Event DEPOSITINITIATED_EVENT = + new Event( + "DepositInitiated", + Arrays.>asList( + new TypeReference
(true) {}, + new TypeReference
(true) {}, + new TypeReference
(true) {}, + new TypeReference() {})); + ; + + public static final Event WITHDRAWALFINALIZED_EVENT = + new Event( + "WithdrawalFinalized", + Arrays.>asList( + new TypeReference
(true) {}, + new TypeReference
(true) {}, + new TypeReference() {})); + ; + + protected static final HashMap _addresses; + + static { + _addresses = new HashMap(); + } + + @Deprecated + protected IL1Bridge( + String contractAddress, + Web3j web3j, + Credentials credentials, + BigInteger gasPrice, + BigInteger gasLimit) { + super(BINARY, contractAddress, web3j, credentials, gasPrice, gasLimit); + } + + protected IL1Bridge( + String contractAddress, + Web3j web3j, + Credentials credentials, + ContractGasProvider contractGasProvider) { + super(BINARY, contractAddress, web3j, credentials, contractGasProvider); + } + + @Deprecated + protected IL1Bridge( + String contractAddress, + Web3j web3j, + TransactionManager transactionManager, + BigInteger gasPrice, + BigInteger gasLimit) { + super(BINARY, contractAddress, web3j, transactionManager, gasPrice, gasLimit); + } + + protected IL1Bridge( + String contractAddress, + Web3j web3j, + TransactionManager transactionManager, + ContractGasProvider contractGasProvider) { + super(BINARY, contractAddress, web3j, transactionManager, contractGasProvider); + } + + public static List getClaimedFailedDepositEvents( + TransactionReceipt transactionReceipt) { + List valueList = + staticExtractEventParametersWithLog(CLAIMEDFAILEDDEPOSIT_EVENT, transactionReceipt); + ArrayList responses = + new ArrayList(valueList.size()); + for (Contract.EventValuesWithLog eventValues : valueList) { + ClaimedFailedDepositEventResponse typedResponse = new ClaimedFailedDepositEventResponse(); + typedResponse.log = eventValues.getLog(); + typedResponse.to = (String) eventValues.getIndexedValues().get(0).getValue(); + typedResponse.l1Token = (String) eventValues.getIndexedValues().get(1).getValue(); + typedResponse.amount = (BigInteger) eventValues.getNonIndexedValues().get(0).getValue(); + responses.add(typedResponse); + } + return responses; + } + + public Flowable claimedFailedDepositEventFlowable( + EthFilter filter) { + return web3j + .ethLogFlowable(filter) + .map( + new Function() { + @Override + public ClaimedFailedDepositEventResponse apply(Log log) { + Contract.EventValuesWithLog eventValues = + extractEventParametersWithLog(CLAIMEDFAILEDDEPOSIT_EVENT, log); + ClaimedFailedDepositEventResponse typedResponse = + new ClaimedFailedDepositEventResponse(); typedResponse.log = log; typedResponse.to = (String) eventValues.getIndexedValues().get(0).getValue(); typedResponse.l1Token = (String) eventValues.getIndexedValues().get(1).getValue(); - typedResponse.amount = (BigInteger) eventValues.getNonIndexedValues().get(0).getValue(); + typedResponse.amount = + (BigInteger) eventValues.getNonIndexedValues().get(0).getValue(); return typedResponse; - } - }); - } - - public Flowable claimedFailedDepositEventFlowable(DefaultBlockParameter startBlock, DefaultBlockParameter endBlock) { - EthFilter filter = new EthFilter(startBlock, endBlock, getContractAddress()); - filter.addSingleTopic(EventEncoder.encode(CLAIMEDFAILEDDEPOSIT_EVENT)); - return claimedFailedDepositEventFlowable(filter); - } - - public static List getDepositInitiatedEvents(TransactionReceipt transactionReceipt) { - List valueList = staticExtractEventParametersWithLog(DEPOSITINITIATED_EVENT, transactionReceipt); - ArrayList responses = new ArrayList(valueList.size()); - for (Contract.EventValuesWithLog eventValues : valueList) { - DepositInitiatedEventResponse typedResponse = new DepositInitiatedEventResponse(); - typedResponse.log = eventValues.getLog(); - typedResponse.from = (String) eventValues.getIndexedValues().get(0).getValue(); - typedResponse.to = (String) eventValues.getIndexedValues().get(1).getValue(); - typedResponse.l1Token = (String) eventValues.getIndexedValues().get(2).getValue(); - typedResponse.amount = (BigInteger) eventValues.getNonIndexedValues().get(0).getValue(); - responses.add(typedResponse); - } - return responses; - } - - public Flowable depositInitiatedEventFlowable(EthFilter filter) { - return web3j.ethLogFlowable(filter).map(new Function() { - @Override - public DepositInitiatedEventResponse apply(Log log) { - Contract.EventValuesWithLog eventValues = extractEventParametersWithLog(DEPOSITINITIATED_EVENT, log); + } + }); + } + + public Flowable claimedFailedDepositEventFlowable( + DefaultBlockParameter startBlock, DefaultBlockParameter endBlock) { + EthFilter filter = new EthFilter(startBlock, endBlock, getContractAddress()); + filter.addSingleTopic(EventEncoder.encode(CLAIMEDFAILEDDEPOSIT_EVENT)); + return claimedFailedDepositEventFlowable(filter); + } + + public static List getDepositInitiatedEvents( + TransactionReceipt transactionReceipt) { + List valueList = + staticExtractEventParametersWithLog(DEPOSITINITIATED_EVENT, transactionReceipt); + ArrayList responses = + new ArrayList(valueList.size()); + for (Contract.EventValuesWithLog eventValues : valueList) { + DepositInitiatedEventResponse typedResponse = new DepositInitiatedEventResponse(); + typedResponse.log = eventValues.getLog(); + typedResponse.from = (String) eventValues.getIndexedValues().get(0).getValue(); + typedResponse.to = (String) eventValues.getIndexedValues().get(1).getValue(); + typedResponse.l1Token = (String) eventValues.getIndexedValues().get(2).getValue(); + typedResponse.amount = (BigInteger) eventValues.getNonIndexedValues().get(0).getValue(); + responses.add(typedResponse); + } + return responses; + } + + public Flowable depositInitiatedEventFlowable(EthFilter filter) { + return web3j + .ethLogFlowable(filter) + .map( + new Function() { + @Override + public DepositInitiatedEventResponse apply(Log log) { + Contract.EventValuesWithLog eventValues = + extractEventParametersWithLog(DEPOSITINITIATED_EVENT, log); DepositInitiatedEventResponse typedResponse = new DepositInitiatedEventResponse(); typedResponse.log = log; typedResponse.from = (String) eventValues.getIndexedValues().get(0).getValue(); typedResponse.to = (String) eventValues.getIndexedValues().get(1).getValue(); typedResponse.l1Token = (String) eventValues.getIndexedValues().get(2).getValue(); - typedResponse.amount = (BigInteger) eventValues.getNonIndexedValues().get(0).getValue(); + typedResponse.amount = + (BigInteger) eventValues.getNonIndexedValues().get(0).getValue(); return typedResponse; - } - }); - } - - public Flowable depositInitiatedEventFlowable(DefaultBlockParameter startBlock, DefaultBlockParameter endBlock) { - EthFilter filter = new EthFilter(startBlock, endBlock, getContractAddress()); - filter.addSingleTopic(EventEncoder.encode(DEPOSITINITIATED_EVENT)); - return depositInitiatedEventFlowable(filter); - } - - public static List getWithdrawalFinalizedEvents(TransactionReceipt transactionReceipt) { - List valueList = staticExtractEventParametersWithLog(WITHDRAWALFINALIZED_EVENT, transactionReceipt); - ArrayList responses = new ArrayList(valueList.size()); - for (Contract.EventValuesWithLog eventValues : valueList) { - WithdrawalFinalizedEventResponse typedResponse = new WithdrawalFinalizedEventResponse(); - typedResponse.log = eventValues.getLog(); - typedResponse.to = (String) eventValues.getIndexedValues().get(0).getValue(); - typedResponse.l1Token = (String) eventValues.getIndexedValues().get(1).getValue(); - typedResponse.amount = (BigInteger) eventValues.getNonIndexedValues().get(0).getValue(); - responses.add(typedResponse); - } - return responses; - } - - public Flowable withdrawalFinalizedEventFlowable(EthFilter filter) { - return web3j.ethLogFlowable(filter).map(new Function() { - @Override - public WithdrawalFinalizedEventResponse apply(Log log) { - Contract.EventValuesWithLog eventValues = extractEventParametersWithLog(WITHDRAWALFINALIZED_EVENT, log); - WithdrawalFinalizedEventResponse typedResponse = new WithdrawalFinalizedEventResponse(); + } + }); + } + + public Flowable depositInitiatedEventFlowable( + DefaultBlockParameter startBlock, DefaultBlockParameter endBlock) { + EthFilter filter = new EthFilter(startBlock, endBlock, getContractAddress()); + filter.addSingleTopic(EventEncoder.encode(DEPOSITINITIATED_EVENT)); + return depositInitiatedEventFlowable(filter); + } + + public static List getWithdrawalFinalizedEvents( + TransactionReceipt transactionReceipt) { + List valueList = + staticExtractEventParametersWithLog(WITHDRAWALFINALIZED_EVENT, transactionReceipt); + ArrayList responses = + new ArrayList(valueList.size()); + for (Contract.EventValuesWithLog eventValues : valueList) { + WithdrawalFinalizedEventResponse typedResponse = new WithdrawalFinalizedEventResponse(); + typedResponse.log = eventValues.getLog(); + typedResponse.to = (String) eventValues.getIndexedValues().get(0).getValue(); + typedResponse.l1Token = (String) eventValues.getIndexedValues().get(1).getValue(); + typedResponse.amount = (BigInteger) eventValues.getNonIndexedValues().get(0).getValue(); + responses.add(typedResponse); + } + return responses; + } + + public Flowable withdrawalFinalizedEventFlowable( + EthFilter filter) { + return web3j + .ethLogFlowable(filter) + .map( + new Function() { + @Override + public WithdrawalFinalizedEventResponse apply(Log log) { + Contract.EventValuesWithLog eventValues = + extractEventParametersWithLog(WITHDRAWALFINALIZED_EVENT, log); + WithdrawalFinalizedEventResponse typedResponse = + new WithdrawalFinalizedEventResponse(); typedResponse.log = log; typedResponse.to = (String) eventValues.getIndexedValues().get(0).getValue(); typedResponse.l1Token = (String) eventValues.getIndexedValues().get(1).getValue(); - typedResponse.amount = (BigInteger) eventValues.getNonIndexedValues().get(0).getValue(); + typedResponse.amount = + (BigInteger) eventValues.getNonIndexedValues().get(0).getValue(); return typedResponse; - } - }); - } - - public Flowable withdrawalFinalizedEventFlowable(DefaultBlockParameter startBlock, DefaultBlockParameter endBlock) { - EthFilter filter = new EthFilter(startBlock, endBlock, getContractAddress()); - filter.addSingleTopic(EventEncoder.encode(WITHDRAWALFINALIZED_EVENT)); - return withdrawalFinalizedEventFlowable(filter); - } - - public RemoteFunctionCall claimFailedDeposit(String _depositSender, String _l1Token, byte[] _l2TxHash, BigInteger _l2BlockNumber, BigInteger _l2MessageIndex, BigInteger _l2TxNumberInBlock, List _merkleProof) { - final org.web3j.abi.datatypes.Function function = new org.web3j.abi.datatypes.Function( - FUNC_CLAIMFAILEDDEPOSIT, - Arrays.asList(new org.web3j.abi.datatypes.Address(_depositSender), - new org.web3j.abi.datatypes.Address(_l1Token), - new org.web3j.abi.datatypes.generated.Bytes32(_l2TxHash), - new org.web3j.abi.datatypes.generated.Uint256(_l2BlockNumber), - new org.web3j.abi.datatypes.generated.Uint256(_l2MessageIndex), - new org.web3j.abi.datatypes.generated.Uint16(_l2TxNumberInBlock), + } + }); + } + + public Flowable withdrawalFinalizedEventFlowable( + DefaultBlockParameter startBlock, DefaultBlockParameter endBlock) { + EthFilter filter = new EthFilter(startBlock, endBlock, getContractAddress()); + filter.addSingleTopic(EventEncoder.encode(WITHDRAWALFINALIZED_EVENT)); + return withdrawalFinalizedEventFlowable(filter); + } + + public RemoteFunctionCall claimFailedDeposit( + String _depositSender, + String _l1Token, + byte[] _l2TxHash, + BigInteger _l2BlockNumber, + BigInteger _l2MessageIndex, + BigInteger _l2TxNumberInBlock, + List _merkleProof) { + final org.web3j.abi.datatypes.Function function = + new org.web3j.abi.datatypes.Function( + FUNC_CLAIMFAILEDDEPOSIT, + Arrays.asList( + new org.web3j.abi.datatypes.Address(_depositSender), + new org.web3j.abi.datatypes.Address(_l1Token), + new org.web3j.abi.datatypes.generated.Bytes32(_l2TxHash), + new org.web3j.abi.datatypes.generated.Uint256(_l2BlockNumber), + new org.web3j.abi.datatypes.generated.Uint256(_l2MessageIndex), + new org.web3j.abi.datatypes.generated.Uint16(_l2TxNumberInBlock), new org.web3j.abi.datatypes.DynamicArray( - org.web3j.abi.datatypes.generated.Bytes32.class, - org.web3j.abi.Utils.typeMap(_merkleProof, org.web3j.abi.datatypes.generated.Bytes32.class))), - Collections.>emptyList()); - return executeRemoteCallTransaction(function); - } - - public RemoteFunctionCall deposit(String _l2Receiver, String _l1Token, BigInteger _amount, BigInteger _l2TxGasLimit, BigInteger _l2TxGasPerPubdataByte, BigInteger weiValue) { - final org.web3j.abi.datatypes.Function function = new org.web3j.abi.datatypes.Function( - FUNC_DEPOSIT, - Arrays.asList(new org.web3j.abi.datatypes.Address(_l2Receiver), - new org.web3j.abi.datatypes.Address(_l1Token), - new org.web3j.abi.datatypes.generated.Uint256(_amount), - new org.web3j.abi.datatypes.generated.Uint256(_l2TxGasLimit), - new org.web3j.abi.datatypes.generated.Uint256(_l2TxGasPerPubdataByte)), - Collections.>emptyList()); - return executeRemoteCallTransaction(function, weiValue); - } - - public RemoteFunctionCall finalizeWithdrawal(BigInteger _l2BlockNumber, BigInteger _l2MessageIndex, BigInteger _l2TxNumberInBlock, byte[] _message, List _merkleProof) { - final org.web3j.abi.datatypes.Function function = new org.web3j.abi.datatypes.Function( - FUNC_FINALIZEWITHDRAWAL, - Arrays.asList(new org.web3j.abi.datatypes.generated.Uint256(_l2BlockNumber), - new org.web3j.abi.datatypes.generated.Uint256(_l2MessageIndex), - new org.web3j.abi.datatypes.generated.Uint16(_l2TxNumberInBlock), - new org.web3j.abi.datatypes.DynamicBytes(_message), + org.web3j.abi.datatypes.generated.Bytes32.class, + org.web3j.abi.Utils.typeMap( + _merkleProof, org.web3j.abi.datatypes.generated.Bytes32.class))), + Collections.>emptyList()); + return executeRemoteCallTransaction(function); + } + + public RemoteFunctionCall deposit( + String _l2Receiver, + String _l1Token, + BigInteger _amount, + BigInteger _l2TxGasLimit, + BigInteger _l2TxGasPerPubdataByte, + BigInteger weiValue) { + final org.web3j.abi.datatypes.Function function = + new org.web3j.abi.datatypes.Function( + FUNC_DEPOSIT, + Arrays.asList( + new org.web3j.abi.datatypes.Address(_l2Receiver), + new org.web3j.abi.datatypes.Address(_l1Token), + new org.web3j.abi.datatypes.generated.Uint256(_amount), + new org.web3j.abi.datatypes.generated.Uint256(_l2TxGasLimit), + new org.web3j.abi.datatypes.generated.Uint256(_l2TxGasPerPubdataByte)), + Collections.>emptyList()); + return executeRemoteCallTransaction(function, weiValue); + } + + public RemoteFunctionCall finalizeWithdrawal( + BigInteger _l2BlockNumber, + BigInteger _l2MessageIndex, + BigInteger _l2TxNumberInBlock, + byte[] _message, + List _merkleProof) { + final org.web3j.abi.datatypes.Function function = + new org.web3j.abi.datatypes.Function( + FUNC_FINALIZEWITHDRAWAL, + Arrays.asList( + new org.web3j.abi.datatypes.generated.Uint256(_l2BlockNumber), + new org.web3j.abi.datatypes.generated.Uint256(_l2MessageIndex), + new org.web3j.abi.datatypes.generated.Uint16(_l2TxNumberInBlock), + new org.web3j.abi.datatypes.DynamicBytes(_message), new org.web3j.abi.datatypes.DynamicArray( - org.web3j.abi.datatypes.generated.Bytes32.class, - org.web3j.abi.Utils.typeMap(_merkleProof, org.web3j.abi.datatypes.generated.Bytes32.class))), - Collections.>emptyList()); - return executeRemoteCallTransaction(function); - } - - public RemoteFunctionCall isWithdrawalFinalized(BigInteger _l2BlockNumber, BigInteger _l2MessageIndex) { - final org.web3j.abi.datatypes.Function function = new org.web3j.abi.datatypes.Function(FUNC_ISWITHDRAWALFINALIZED, - Arrays.asList(new org.web3j.abi.datatypes.generated.Uint256(_l2BlockNumber), - new org.web3j.abi.datatypes.generated.Uint256(_l2MessageIndex)), - Arrays.>asList(new TypeReference() {})); - return executeRemoteCallSingleValueReturn(function, Boolean.class); - } - - public RemoteFunctionCall l2TokenAddress(String _l1Token) { - final org.web3j.abi.datatypes.Function function = new org.web3j.abi.datatypes.Function(FUNC_L2TOKENADDRESS, - Arrays.asList(new org.web3j.abi.datatypes.Address(_l1Token)), - Arrays.>asList(new TypeReference
() {})); - return executeRemoteCallSingleValueReturn(function, String.class); - } - - @Deprecated - public static IL1Bridge load(String contractAddress, Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) { - return new IL1Bridge(contractAddress, web3j, credentials, gasPrice, gasLimit); - } - - @Deprecated - public static IL1Bridge load(String contractAddress, Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit) { - return new IL1Bridge(contractAddress, web3j, transactionManager, gasPrice, gasLimit); - } - - public static IL1Bridge load(String contractAddress, Web3j web3j, Credentials credentials, ContractGasProvider contractGasProvider) { - return new IL1Bridge(contractAddress, web3j, credentials, contractGasProvider); - } - - public static IL1Bridge load(String contractAddress, Web3j web3j, TransactionManager transactionManager, ContractGasProvider contractGasProvider) { - return new IL1Bridge(contractAddress, web3j, transactionManager, contractGasProvider); - } - - public static RemoteCall deploy(Web3j web3j, Credentials credentials, ContractGasProvider contractGasProvider) { - return deployRemoteCall(IL1Bridge.class, web3j, credentials, contractGasProvider, BINARY, ""); - } - - @Deprecated - public static RemoteCall deploy(Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) { - return deployRemoteCall(IL1Bridge.class, web3j, credentials, gasPrice, gasLimit, BINARY, ""); - } - - public static RemoteCall deploy(Web3j web3j, TransactionManager transactionManager, ContractGasProvider contractGasProvider) { - return deployRemoteCall(IL1Bridge.class, web3j, transactionManager, contractGasProvider, BINARY, ""); - } - - @Deprecated - public static RemoteCall deploy(Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit) { - return deployRemoteCall(IL1Bridge.class, web3j, transactionManager, gasPrice, gasLimit, BINARY, ""); - } - - protected String getStaticDeployedAddress(String networkId) { - return _addresses.get(networkId); - } - - public static String getPreviouslyDeployedAddress(String networkId) { - return _addresses.get(networkId); - } - - public static class ClaimedFailedDepositEventResponse extends BaseEventResponse { - public String to; - - public String l1Token; - - public BigInteger amount; - } - - public static class DepositInitiatedEventResponse extends BaseEventResponse { - public String from; - - public String to; - - public String l1Token; - - public BigInteger amount; - } - - public static class WithdrawalFinalizedEventResponse extends BaseEventResponse { - public String to; - - public String l1Token; - - public BigInteger amount; - } + org.web3j.abi.datatypes.generated.Bytes32.class, + org.web3j.abi.Utils.typeMap( + _merkleProof, org.web3j.abi.datatypes.generated.Bytes32.class))), + Collections.>emptyList()); + return executeRemoteCallTransaction(function); + } + + public RemoteFunctionCall isWithdrawalFinalized( + BigInteger _l2BlockNumber, BigInteger _l2MessageIndex) { + final org.web3j.abi.datatypes.Function function = + new org.web3j.abi.datatypes.Function( + FUNC_ISWITHDRAWALFINALIZED, + Arrays.asList( + new org.web3j.abi.datatypes.generated.Uint256(_l2BlockNumber), + new org.web3j.abi.datatypes.generated.Uint256(_l2MessageIndex)), + Arrays.>asList(new TypeReference() {})); + return executeRemoteCallSingleValueReturn(function, Boolean.class); + } + + public RemoteFunctionCall l2TokenAddress(String _l1Token) { + final org.web3j.abi.datatypes.Function function = + new org.web3j.abi.datatypes.Function( + FUNC_L2TOKENADDRESS, + Arrays.asList(new org.web3j.abi.datatypes.Address(_l1Token)), + Arrays.>asList(new TypeReference
() {})); + return executeRemoteCallSingleValueReturn(function, String.class); + } + + @Deprecated + public static IL1Bridge load( + String contractAddress, + Web3j web3j, + Credentials credentials, + BigInteger gasPrice, + BigInteger gasLimit) { + return new IL1Bridge(contractAddress, web3j, credentials, gasPrice, gasLimit); + } + + @Deprecated + public static IL1Bridge load( + String contractAddress, + Web3j web3j, + TransactionManager transactionManager, + BigInteger gasPrice, + BigInteger gasLimit) { + return new IL1Bridge(contractAddress, web3j, transactionManager, gasPrice, gasLimit); + } + + public static IL1Bridge load( + String contractAddress, + Web3j web3j, + Credentials credentials, + ContractGasProvider contractGasProvider) { + return new IL1Bridge(contractAddress, web3j, credentials, contractGasProvider); + } + + public static IL1Bridge load( + String contractAddress, + Web3j web3j, + TransactionManager transactionManager, + ContractGasProvider contractGasProvider) { + return new IL1Bridge(contractAddress, web3j, transactionManager, contractGasProvider); + } + + public static RemoteCall deploy( + Web3j web3j, Credentials credentials, ContractGasProvider contractGasProvider) { + return deployRemoteCall(IL1Bridge.class, web3j, credentials, contractGasProvider, BINARY, ""); + } + + @Deprecated + public static RemoteCall deploy( + Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) { + return deployRemoteCall(IL1Bridge.class, web3j, credentials, gasPrice, gasLimit, BINARY, ""); + } + + public static RemoteCall deploy( + Web3j web3j, TransactionManager transactionManager, ContractGasProvider contractGasProvider) { + return deployRemoteCall( + IL1Bridge.class, web3j, transactionManager, contractGasProvider, BINARY, ""); + } + + @Deprecated + public static RemoteCall deploy( + Web3j web3j, + TransactionManager transactionManager, + BigInteger gasPrice, + BigInteger gasLimit) { + return deployRemoteCall( + IL1Bridge.class, web3j, transactionManager, gasPrice, gasLimit, BINARY, ""); + } + + protected String getStaticDeployedAddress(String networkId) { + return _addresses.get(networkId); + } + + public static String getPreviouslyDeployedAddress(String networkId) { + return _addresses.get(networkId); + } + + public static class ClaimedFailedDepositEventResponse extends BaseEventResponse { + public String to; + + public String l1Token; + + public BigInteger amount; + } + + public static class DepositInitiatedEventResponse extends BaseEventResponse { + public String from; + + public String to; + + public String l1Token; + + public BigInteger amount; + } + + public static class WithdrawalFinalizedEventResponse extends BaseEventResponse { + public String to; + + public String l1Token; + + public BigInteger amount; + } } diff --git a/src/main/java/io/zksync/wrappers/IL2Bridge.java b/src/main/java/io/zksync/wrappers/IL2Bridge.java index 7383f10..3427393 100644 --- a/src/main/java/io/zksync/wrappers/IL2Bridge.java +++ b/src/main/java/io/zksync/wrappers/IL2Bridge.java @@ -18,148 +18,210 @@ import org.web3j.tx.gas.ContractGasProvider; /** - *

Auto generated code. + * Auto generated code. + * *

Do not modify! + * *

Please use the web3j command line tools, - * or the org.web3j.codegen.SolidityFunctionWrapperGenerator in the - * codegen module to update. + * or the org.web3j.codegen.SolidityFunctionWrapperGenerator in the codegen module to update. * *

Generated with web3j version 1.4.2. */ @SuppressWarnings("rawtypes") public class IL2Bridge extends Contract { - public static final String BINARY = "0x"; - - public static final String FUNC_FINALIZEDEPOSIT = "finalizeDeposit"; - - public static final String FUNC_INITIALIZE = "initialize"; - - public static final String FUNC_L1BRIDGE = "l1Bridge"; - - public static final String FUNC_L1TOKENADDRESS = "l1TokenAddress"; - - public static final String FUNC_L2TOKENADDRESS = "l2TokenAddress"; - - public static final String FUNC_WITHDRAW = "withdraw"; - - protected static final HashMap _addresses; - - static { - _addresses = new HashMap(); - } - - @Deprecated - protected IL2Bridge(String contractAddress, Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) { - super(BINARY, contractAddress, web3j, credentials, gasPrice, gasLimit); - } - - protected IL2Bridge(String contractAddress, Web3j web3j, Credentials credentials, ContractGasProvider contractGasProvider) { - super(BINARY, contractAddress, web3j, credentials, contractGasProvider); - } - - @Deprecated - protected IL2Bridge(String contractAddress, Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit) { - super(BINARY, contractAddress, web3j, transactionManager, gasPrice, gasLimit); - } - - protected IL2Bridge(String contractAddress, Web3j web3j, TransactionManager transactionManager, ContractGasProvider contractGasProvider) { - super(BINARY, contractAddress, web3j, transactionManager, contractGasProvider); - } - - public RemoteFunctionCall finalizeDeposit(String _l1Sender, String _l2Receiver, String _l1Token, BigInteger _amount, byte[] _data) { - final Function function = new Function( - FUNC_FINALIZEDEPOSIT, - Arrays.asList(new org.web3j.abi.datatypes.Address(_l1Sender), - new org.web3j.abi.datatypes.Address(_l2Receiver), - new org.web3j.abi.datatypes.Address(_l1Token), - new org.web3j.abi.datatypes.generated.Uint256(_amount), - new org.web3j.abi.datatypes.DynamicBytes(_data)), - Collections.>emptyList()); - return executeRemoteCallTransaction(function); - } - - public RemoteFunctionCall initialize(String _l1Bridge, byte[] _l2TokenProxyBytecodeHash, String _governor) { - final Function function = new Function( - FUNC_INITIALIZE, - Arrays.asList(new org.web3j.abi.datatypes.Address(_l1Bridge), - new org.web3j.abi.datatypes.generated.Bytes32(_l2TokenProxyBytecodeHash), - new org.web3j.abi.datatypes.Address(_governor)), - Collections.>emptyList()); - return executeRemoteCallTransaction(function); - } - - public RemoteFunctionCall l1Bridge() { - final Function function = new Function(FUNC_L1BRIDGE, - Arrays.asList(), - Arrays.>asList(new TypeReference

() {})); - return executeRemoteCallSingleValueReturn(function, String.class); - } - - public RemoteFunctionCall l1TokenAddress(String _l2Token) { - final Function function = new Function(FUNC_L1TOKENADDRESS, - Arrays.asList(new org.web3j.abi.datatypes.Address(_l2Token)), - Arrays.>asList(new TypeReference
() {})); - return executeRemoteCallSingleValueReturn(function, String.class); - } - - public RemoteFunctionCall l2TokenAddress(String _l1Token) { - final Function function = new Function(FUNC_L2TOKENADDRESS, - Arrays.asList(new org.web3j.abi.datatypes.Address(_l1Token)), - Arrays.>asList(new TypeReference
() {})); - return executeRemoteCallSingleValueReturn(function, String.class); - } - - public RemoteFunctionCall withdraw(String _l1Receiver, String _l2Token, BigInteger _amount) { - final Function function = new Function( - FUNC_WITHDRAW, - Arrays.asList(new org.web3j.abi.datatypes.Address(_l1Receiver), - new org.web3j.abi.datatypes.Address(_l2Token), - new org.web3j.abi.datatypes.generated.Uint256(_amount)), - Collections.>emptyList()); - return executeRemoteCallTransaction(function); - } - - @Deprecated - public static IL2Bridge load(String contractAddress, Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) { - return new IL2Bridge(contractAddress, web3j, credentials, gasPrice, gasLimit); - } - - @Deprecated - public static IL2Bridge load(String contractAddress, Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit) { - return new IL2Bridge(contractAddress, web3j, transactionManager, gasPrice, gasLimit); - } - - public static IL2Bridge load(String contractAddress, Web3j web3j, Credentials credentials, ContractGasProvider contractGasProvider) { - return new IL2Bridge(contractAddress, web3j, credentials, contractGasProvider); - } - - public static IL2Bridge load(String contractAddress, Web3j web3j, TransactionManager transactionManager, ContractGasProvider contractGasProvider) { - return new IL2Bridge(contractAddress, web3j, transactionManager, contractGasProvider); - } - - public static RemoteCall deploy(Web3j web3j, Credentials credentials, ContractGasProvider contractGasProvider) { - return deployRemoteCall(IL2Bridge.class, web3j, credentials, contractGasProvider, BINARY, ""); - } - - @Deprecated - public static RemoteCall deploy(Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) { - return deployRemoteCall(IL2Bridge.class, web3j, credentials, gasPrice, gasLimit, BINARY, ""); - } - - public static RemoteCall deploy(Web3j web3j, TransactionManager transactionManager, ContractGasProvider contractGasProvider) { - return deployRemoteCall(IL2Bridge.class, web3j, transactionManager, contractGasProvider, BINARY, ""); - } - - @Deprecated - public static RemoteCall deploy(Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit) { - return deployRemoteCall(IL2Bridge.class, web3j, transactionManager, gasPrice, gasLimit, BINARY, ""); - } - - protected String getStaticDeployedAddress(String networkId) { - return _addresses.get(networkId); - } - - public static String getPreviouslyDeployedAddress(String networkId) { - return _addresses.get(networkId); - } + public static final String BINARY = "0x"; + + public static final String FUNC_FINALIZEDEPOSIT = "finalizeDeposit"; + + public static final String FUNC_INITIALIZE = "initialize"; + + public static final String FUNC_L1BRIDGE = "l1Bridge"; + + public static final String FUNC_L1TOKENADDRESS = "l1TokenAddress"; + + public static final String FUNC_L2TOKENADDRESS = "l2TokenAddress"; + + public static final String FUNC_WITHDRAW = "withdraw"; + + protected static final HashMap _addresses; + + static { + _addresses = new HashMap(); + } + + @Deprecated + protected IL2Bridge( + String contractAddress, + Web3j web3j, + Credentials credentials, + BigInteger gasPrice, + BigInteger gasLimit) { + super(BINARY, contractAddress, web3j, credentials, gasPrice, gasLimit); + } + + protected IL2Bridge( + String contractAddress, + Web3j web3j, + Credentials credentials, + ContractGasProvider contractGasProvider) { + super(BINARY, contractAddress, web3j, credentials, contractGasProvider); + } + + @Deprecated + protected IL2Bridge( + String contractAddress, + Web3j web3j, + TransactionManager transactionManager, + BigInteger gasPrice, + BigInteger gasLimit) { + super(BINARY, contractAddress, web3j, transactionManager, gasPrice, gasLimit); + } + + protected IL2Bridge( + String contractAddress, + Web3j web3j, + TransactionManager transactionManager, + ContractGasProvider contractGasProvider) { + super(BINARY, contractAddress, web3j, transactionManager, contractGasProvider); + } + + public RemoteFunctionCall finalizeDeposit( + String _l1Sender, String _l2Receiver, String _l1Token, BigInteger _amount, byte[] _data) { + final Function function = + new Function( + FUNC_FINALIZEDEPOSIT, + Arrays.asList( + new org.web3j.abi.datatypes.Address(_l1Sender), + new org.web3j.abi.datatypes.Address(_l2Receiver), + new org.web3j.abi.datatypes.Address(_l1Token), + new org.web3j.abi.datatypes.generated.Uint256(_amount), + new org.web3j.abi.datatypes.DynamicBytes(_data)), + Collections.>emptyList()); + return executeRemoteCallTransaction(function); + } + + public RemoteFunctionCall initialize( + String _l1Bridge, byte[] _l2TokenProxyBytecodeHash, String _governor) { + final Function function = + new Function( + FUNC_INITIALIZE, + Arrays.asList( + new org.web3j.abi.datatypes.Address(_l1Bridge), + new org.web3j.abi.datatypes.generated.Bytes32(_l2TokenProxyBytecodeHash), + new org.web3j.abi.datatypes.Address(_governor)), + Collections.>emptyList()); + return executeRemoteCallTransaction(function); + } + + public RemoteFunctionCall l1Bridge() { + final Function function = + new Function( + FUNC_L1BRIDGE, + Arrays.asList(), + Arrays.>asList(new TypeReference
() {})); + return executeRemoteCallSingleValueReturn(function, String.class); + } + + public RemoteFunctionCall l1TokenAddress(String _l2Token) { + final Function function = + new Function( + FUNC_L1TOKENADDRESS, + Arrays.asList(new org.web3j.abi.datatypes.Address(_l2Token)), + Arrays.>asList(new TypeReference
() {})); + return executeRemoteCallSingleValueReturn(function, String.class); + } + + public RemoteFunctionCall l2TokenAddress(String _l1Token) { + final Function function = + new Function( + FUNC_L2TOKENADDRESS, + Arrays.asList(new org.web3j.abi.datatypes.Address(_l1Token)), + Arrays.>asList(new TypeReference
() {})); + return executeRemoteCallSingleValueReturn(function, String.class); + } + + public RemoteFunctionCall withdraw( + String _l1Receiver, String _l2Token, BigInteger _amount) { + final Function function = + new Function( + FUNC_WITHDRAW, + Arrays.asList( + new org.web3j.abi.datatypes.Address(_l1Receiver), + new org.web3j.abi.datatypes.Address(_l2Token), + new org.web3j.abi.datatypes.generated.Uint256(_amount)), + Collections.>emptyList()); + return executeRemoteCallTransaction(function); + } + + @Deprecated + public static IL2Bridge load( + String contractAddress, + Web3j web3j, + Credentials credentials, + BigInteger gasPrice, + BigInteger gasLimit) { + return new IL2Bridge(contractAddress, web3j, credentials, gasPrice, gasLimit); + } + + @Deprecated + public static IL2Bridge load( + String contractAddress, + Web3j web3j, + TransactionManager transactionManager, + BigInteger gasPrice, + BigInteger gasLimit) { + return new IL2Bridge(contractAddress, web3j, transactionManager, gasPrice, gasLimit); + } + + public static IL2Bridge load( + String contractAddress, + Web3j web3j, + Credentials credentials, + ContractGasProvider contractGasProvider) { + return new IL2Bridge(contractAddress, web3j, credentials, contractGasProvider); + } + + public static IL2Bridge load( + String contractAddress, + Web3j web3j, + TransactionManager transactionManager, + ContractGasProvider contractGasProvider) { + return new IL2Bridge(contractAddress, web3j, transactionManager, contractGasProvider); + } + + public static RemoteCall deploy( + Web3j web3j, Credentials credentials, ContractGasProvider contractGasProvider) { + return deployRemoteCall(IL2Bridge.class, web3j, credentials, contractGasProvider, BINARY, ""); + } + + @Deprecated + public static RemoteCall deploy( + Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) { + return deployRemoteCall(IL2Bridge.class, web3j, credentials, gasPrice, gasLimit, BINARY, ""); + } + + public static RemoteCall deploy( + Web3j web3j, TransactionManager transactionManager, ContractGasProvider contractGasProvider) { + return deployRemoteCall( + IL2Bridge.class, web3j, transactionManager, contractGasProvider, BINARY, ""); + } + + @Deprecated + public static RemoteCall deploy( + Web3j web3j, + TransactionManager transactionManager, + BigInteger gasPrice, + BigInteger gasLimit) { + return deployRemoteCall( + IL2Bridge.class, web3j, transactionManager, gasPrice, gasLimit, BINARY, ""); + } + + protected String getStaticDeployedAddress(String networkId) { + return _addresses.get(networkId); + } + + public static String getPreviouslyDeployedAddress(String networkId) { + return _addresses.get(networkId); + } } diff --git a/src/main/java/io/zksync/wrappers/IL2Messenger.java b/src/main/java/io/zksync/wrappers/IL2Messenger.java index 49569f6..7aca11d 100644 --- a/src/main/java/io/zksync/wrappers/IL2Messenger.java +++ b/src/main/java/io/zksync/wrappers/IL2Messenger.java @@ -1,13 +1,10 @@ package io.zksync.wrappers; import java.math.BigInteger; -import java.util.Arrays; import java.util.Collections; import java.util.HashMap; -import org.web3j.abi.TypeReference; import org.web3j.abi.datatypes.DynamicBytes; import org.web3j.abi.datatypes.Function; -import org.web3j.abi.datatypes.Type; import org.web3j.crypto.Credentials; import org.web3j.protocol.Web3j; import org.web3j.protocol.core.RemoteCall; @@ -18,100 +15,149 @@ import org.web3j.tx.gas.ContractGasProvider; /** - *

Auto generated code. + * Auto generated code. + * *

Do not modify! + * *

Please use the web3j command line tools, - * or the org.web3j.codegen.SolidityFunctionWrapperGenerator in the - * codegen module to update. + * or the org.web3j.codegen.SolidityFunctionWrapperGenerator in the codegen module to update. * *

Generated with web3j version 1.4.1. */ @SuppressWarnings("rawtypes") public class IL2Messenger extends Contract { - public static final String BINARY = "0x"; - - public static final String FUNC_SENDTOL1 = "sendToL1"; - - protected static final HashMap _addresses; - - static { - _addresses = new HashMap(); - } - - @Deprecated - protected IL2Messenger(String contractAddress, Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) { - super(BINARY, contractAddress, web3j, credentials, gasPrice, gasLimit); - } - - protected IL2Messenger(String contractAddress, Web3j web3j, Credentials credentials, ContractGasProvider contractGasProvider) { - super(BINARY, contractAddress, web3j, credentials, contractGasProvider); - } - - @Deprecated - protected IL2Messenger(String contractAddress, Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit) { - super(BINARY, contractAddress, web3j, transactionManager, gasPrice, gasLimit); - } - - protected IL2Messenger(String contractAddress, Web3j web3j, TransactionManager transactionManager, ContractGasProvider contractGasProvider) { - super(BINARY, contractAddress, web3j, transactionManager, contractGasProvider); - } - - public RemoteFunctionCall sendToL1(byte[] _message) { - final Function function = new Function( - FUNC_SENDTOL1, - Collections.singletonList(new DynamicBytes(_message)), - Collections.emptyList()); - return executeRemoteCallTransaction(function); - } - - public static Function encodeSendToL1(byte[] message) { - return new Function( - FUNC_SENDTOL1, - Collections.singletonList(new DynamicBytes(message)), - Collections.emptyList()); - } - - @Deprecated - public static IL2Messenger load(String contractAddress, Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) { - return new IL2Messenger(contractAddress, web3j, credentials, gasPrice, gasLimit); - } - - @Deprecated - public static IL2Messenger load(String contractAddress, Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit) { - return new IL2Messenger(contractAddress, web3j, transactionManager, gasPrice, gasLimit); - } - - public static IL2Messenger load(String contractAddress, Web3j web3j, Credentials credentials, ContractGasProvider contractGasProvider) { - return new IL2Messenger(contractAddress, web3j, credentials, contractGasProvider); - } - - public static IL2Messenger load(String contractAddress, Web3j web3j, TransactionManager transactionManager, ContractGasProvider contractGasProvider) { - return new IL2Messenger(contractAddress, web3j, transactionManager, contractGasProvider); - } - - public static RemoteCall deploy(Web3j web3j, Credentials credentials, ContractGasProvider contractGasProvider) { - return deployRemoteCall(IL2Messenger.class, web3j, credentials, contractGasProvider, BINARY, ""); - } - - @Deprecated - public static RemoteCall deploy(Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) { - return deployRemoteCall(IL2Messenger.class, web3j, credentials, gasPrice, gasLimit, BINARY, ""); - } - - public static RemoteCall deploy(Web3j web3j, TransactionManager transactionManager, ContractGasProvider contractGasProvider) { - return deployRemoteCall(IL2Messenger.class, web3j, transactionManager, contractGasProvider, BINARY, ""); - } - - @Deprecated - public static RemoteCall deploy(Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit) { - return deployRemoteCall(IL2Messenger.class, web3j, transactionManager, gasPrice, gasLimit, BINARY, ""); - } - - protected String getStaticDeployedAddress(String networkId) { - return _addresses.get(networkId); - } - - public static String getPreviouslyDeployedAddress(String networkId) { - return _addresses.get(networkId); - } + public static final String BINARY = "0x"; + + public static final String FUNC_SENDTOL1 = "sendToL1"; + + protected static final HashMap _addresses; + + static { + _addresses = new HashMap(); + } + + @Deprecated + protected IL2Messenger( + String contractAddress, + Web3j web3j, + Credentials credentials, + BigInteger gasPrice, + BigInteger gasLimit) { + super(BINARY, contractAddress, web3j, credentials, gasPrice, gasLimit); + } + + protected IL2Messenger( + String contractAddress, + Web3j web3j, + Credentials credentials, + ContractGasProvider contractGasProvider) { + super(BINARY, contractAddress, web3j, credentials, contractGasProvider); + } + + @Deprecated + protected IL2Messenger( + String contractAddress, + Web3j web3j, + TransactionManager transactionManager, + BigInteger gasPrice, + BigInteger gasLimit) { + super(BINARY, contractAddress, web3j, transactionManager, gasPrice, gasLimit); + } + + protected IL2Messenger( + String contractAddress, + Web3j web3j, + TransactionManager transactionManager, + ContractGasProvider contractGasProvider) { + super(BINARY, contractAddress, web3j, transactionManager, contractGasProvider); + } + + public RemoteFunctionCall sendToL1(byte[] _message) { + final Function function = + new Function( + FUNC_SENDTOL1, + Collections.singletonList(new DynamicBytes(_message)), + Collections.emptyList()); + return executeRemoteCallTransaction(function); + } + + public static Function encodeSendToL1(byte[] message) { + return new Function( + FUNC_SENDTOL1, + Collections.singletonList(new DynamicBytes(message)), + Collections.emptyList()); + } + + @Deprecated + public static IL2Messenger load( + String contractAddress, + Web3j web3j, + Credentials credentials, + BigInteger gasPrice, + BigInteger gasLimit) { + return new IL2Messenger(contractAddress, web3j, credentials, gasPrice, gasLimit); + } + + @Deprecated + public static IL2Messenger load( + String contractAddress, + Web3j web3j, + TransactionManager transactionManager, + BigInteger gasPrice, + BigInteger gasLimit) { + return new IL2Messenger(contractAddress, web3j, transactionManager, gasPrice, gasLimit); + } + + public static IL2Messenger load( + String contractAddress, + Web3j web3j, + Credentials credentials, + ContractGasProvider contractGasProvider) { + return new IL2Messenger(contractAddress, web3j, credentials, contractGasProvider); + } + + public static IL2Messenger load( + String contractAddress, + Web3j web3j, + TransactionManager transactionManager, + ContractGasProvider contractGasProvider) { + return new IL2Messenger(contractAddress, web3j, transactionManager, contractGasProvider); + } + + public static RemoteCall deploy( + Web3j web3j, Credentials credentials, ContractGasProvider contractGasProvider) { + return deployRemoteCall( + IL2Messenger.class, web3j, credentials, contractGasProvider, BINARY, ""); + } + + @Deprecated + public static RemoteCall deploy( + Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) { + return deployRemoteCall(IL2Messenger.class, web3j, credentials, gasPrice, gasLimit, BINARY, ""); + } + + public static RemoteCall deploy( + Web3j web3j, TransactionManager transactionManager, ContractGasProvider contractGasProvider) { + return deployRemoteCall( + IL2Messenger.class, web3j, transactionManager, contractGasProvider, BINARY, ""); + } + + @Deprecated + public static RemoteCall deploy( + Web3j web3j, + TransactionManager transactionManager, + BigInteger gasPrice, + BigInteger gasLimit) { + return deployRemoteCall( + IL2Messenger.class, web3j, transactionManager, gasPrice, gasLimit, BINARY, ""); + } + + protected String getStaticDeployedAddress(String networkId) { + return _addresses.get(networkId); + } + + public static String getPreviouslyDeployedAddress(String networkId) { + return _addresses.get(networkId); + } } diff --git a/src/main/java/io/zksync/wrappers/L1Messenger.java b/src/main/java/io/zksync/wrappers/L1Messenger.java index 0e40523..eb2b699 100644 --- a/src/main/java/io/zksync/wrappers/L1Messenger.java +++ b/src/main/java/io/zksync/wrappers/L1Messenger.java @@ -27,108 +27,161 @@ import org.web3j.tx.gas.ContractGasProvider; /** - *

Auto generated code. + * Auto generated code. + * *

Do not modify! + * *

Please use the web3j command line tools, - * or the org.web3j.codegen.SolidityFunctionWrapperGenerator in the - * codegen module to update. + * or the org.web3j.codegen.SolidityFunctionWrapperGenerator in the codegen module to update. * *

Generated with web3j version 1.4.2. */ @SuppressWarnings("rawtypes") public class L1Messenger extends Contract { - public static final String BINARY = "Bin file was not provided"; - - public static final String FUNC_SENDTOL1 = "sendToL1"; - - public static final Event L1MESSAGESENT_EVENT = new Event("L1MessageSent", - Arrays.>asList(new TypeReference

(true) {}, new TypeReference(true) {}, new TypeReference() {})); - ; - - @Deprecated - protected L1Messenger(String contractAddress, Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) { - super(BINARY, contractAddress, web3j, credentials, gasPrice, gasLimit); - } - - protected L1Messenger(String contractAddress, Web3j web3j, Credentials credentials, ContractGasProvider contractGasProvider) { - super(BINARY, contractAddress, web3j, credentials, contractGasProvider); - } - - @Deprecated - protected L1Messenger(String contractAddress, Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit) { - super(BINARY, contractAddress, web3j, transactionManager, gasPrice, gasLimit); - } - - protected L1Messenger(String contractAddress, Web3j web3j, TransactionManager transactionManager, ContractGasProvider contractGasProvider) { - super(BINARY, contractAddress, web3j, transactionManager, contractGasProvider); - } - - public static List getL1MessageSentEvents(TransactionReceipt transactionReceipt) { - List valueList = staticExtractEventParametersWithLog(L1MESSAGESENT_EVENT, transactionReceipt); - ArrayList responses = new ArrayList(valueList.size()); - for (Contract.EventValuesWithLog eventValues : valueList) { - L1MessageSentEventResponse typedResponse = new L1MessageSentEventResponse(); - typedResponse.log = eventValues.getLog(); - typedResponse._sender = (String) eventValues.getIndexedValues().get(0).getValue(); - typedResponse._hash = (byte[]) eventValues.getIndexedValues().get(1).getValue(); - typedResponse._message = (byte[]) eventValues.getNonIndexedValues().get(0).getValue(); - responses.add(typedResponse); - } - return responses; + public static final String BINARY = "Bin file was not provided"; + + public static final String FUNC_SENDTOL1 = "sendToL1"; + + public static final Event L1MESSAGESENT_EVENT = + new Event( + "L1MessageSent", + Arrays.>asList( + new TypeReference
(true) {}, + new TypeReference(true) {}, + new TypeReference() {})); + ; + + @Deprecated + protected L1Messenger( + String contractAddress, + Web3j web3j, + Credentials credentials, + BigInteger gasPrice, + BigInteger gasLimit) { + super(BINARY, contractAddress, web3j, credentials, gasPrice, gasLimit); + } + + protected L1Messenger( + String contractAddress, + Web3j web3j, + Credentials credentials, + ContractGasProvider contractGasProvider) { + super(BINARY, contractAddress, web3j, credentials, contractGasProvider); + } + + @Deprecated + protected L1Messenger( + String contractAddress, + Web3j web3j, + TransactionManager transactionManager, + BigInteger gasPrice, + BigInteger gasLimit) { + super(BINARY, contractAddress, web3j, transactionManager, gasPrice, gasLimit); + } + + protected L1Messenger( + String contractAddress, + Web3j web3j, + TransactionManager transactionManager, + ContractGasProvider contractGasProvider) { + super(BINARY, contractAddress, web3j, transactionManager, contractGasProvider); + } + + public static List getL1MessageSentEvents( + TransactionReceipt transactionReceipt) { + List valueList = + staticExtractEventParametersWithLog(L1MESSAGESENT_EVENT, transactionReceipt); + ArrayList responses = + new ArrayList(valueList.size()); + for (Contract.EventValuesWithLog eventValues : valueList) { + L1MessageSentEventResponse typedResponse = new L1MessageSentEventResponse(); + typedResponse.log = eventValues.getLog(); + typedResponse._sender = (String) eventValues.getIndexedValues().get(0).getValue(); + typedResponse._hash = (byte[]) eventValues.getIndexedValues().get(1).getValue(); + typedResponse._message = (byte[]) eventValues.getNonIndexedValues().get(0).getValue(); + responses.add(typedResponse); } - - public Flowable l1MessageSentEventFlowable(EthFilter filter) { - return web3j.ethLogFlowable(filter).map(new Function() { - @Override - public L1MessageSentEventResponse apply(Log log) { - Contract.EventValuesWithLog eventValues = extractEventParametersWithLog(L1MESSAGESENT_EVENT, log); + return responses; + } + + public Flowable l1MessageSentEventFlowable(EthFilter filter) { + return web3j + .ethLogFlowable(filter) + .map( + new Function() { + @Override + public L1MessageSentEventResponse apply(Log log) { + Contract.EventValuesWithLog eventValues = + extractEventParametersWithLog(L1MESSAGESENT_EVENT, log); L1MessageSentEventResponse typedResponse = new L1MessageSentEventResponse(); typedResponse.log = log; typedResponse._sender = (String) eventValues.getIndexedValues().get(0).getValue(); typedResponse._hash = (byte[]) eventValues.getIndexedValues().get(1).getValue(); - typedResponse._message = (byte[]) eventValues.getNonIndexedValues().get(0).getValue(); + typedResponse._message = + (byte[]) eventValues.getNonIndexedValues().get(0).getValue(); return typedResponse; - } - }); - } - - public Flowable l1MessageSentEventFlowable(DefaultBlockParameter startBlock, DefaultBlockParameter endBlock) { - EthFilter filter = new EthFilter(startBlock, endBlock, getContractAddress()); - filter.addSingleTopic(EventEncoder.encode(L1MESSAGESENT_EVENT)); - return l1MessageSentEventFlowable(filter); - } - - public RemoteFunctionCall sendToL1(byte[] _message) { - final org.web3j.abi.datatypes.Function function = new org.web3j.abi.datatypes.Function( - FUNC_SENDTOL1, - Arrays.asList(new org.web3j.abi.datatypes.DynamicBytes(_message)), - Collections.>emptyList()); - return executeRemoteCallTransaction(function); - } - - @Deprecated - public static L1Messenger load(String contractAddress, Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) { - return new L1Messenger(contractAddress, web3j, credentials, gasPrice, gasLimit); - } - - @Deprecated - public static L1Messenger load(String contractAddress, Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit) { - return new L1Messenger(contractAddress, web3j, transactionManager, gasPrice, gasLimit); - } - - public static L1Messenger load(String contractAddress, Web3j web3j, Credentials credentials, ContractGasProvider contractGasProvider) { - return new L1Messenger(contractAddress, web3j, credentials, contractGasProvider); - } - - public static L1Messenger load(String contractAddress, Web3j web3j, TransactionManager transactionManager, ContractGasProvider contractGasProvider) { - return new L1Messenger(contractAddress, web3j, transactionManager, contractGasProvider); - } - - public static class L1MessageSentEventResponse extends BaseEventResponse { - public String _sender; - - public byte[] _hash; - - public byte[] _message; - } + } + }); + } + + public Flowable l1MessageSentEventFlowable( + DefaultBlockParameter startBlock, DefaultBlockParameter endBlock) { + EthFilter filter = new EthFilter(startBlock, endBlock, getContractAddress()); + filter.addSingleTopic(EventEncoder.encode(L1MESSAGESENT_EVENT)); + return l1MessageSentEventFlowable(filter); + } + + public RemoteFunctionCall sendToL1(byte[] _message) { + final org.web3j.abi.datatypes.Function function = + new org.web3j.abi.datatypes.Function( + FUNC_SENDTOL1, + Arrays.asList(new org.web3j.abi.datatypes.DynamicBytes(_message)), + Collections.>emptyList()); + return executeRemoteCallTransaction(function); + } + + @Deprecated + public static L1Messenger load( + String contractAddress, + Web3j web3j, + Credentials credentials, + BigInteger gasPrice, + BigInteger gasLimit) { + return new L1Messenger(contractAddress, web3j, credentials, gasPrice, gasLimit); + } + + @Deprecated + public static L1Messenger load( + String contractAddress, + Web3j web3j, + TransactionManager transactionManager, + BigInteger gasPrice, + BigInteger gasLimit) { + return new L1Messenger(contractAddress, web3j, transactionManager, gasPrice, gasLimit); + } + + public static L1Messenger load( + String contractAddress, + Web3j web3j, + Credentials credentials, + ContractGasProvider contractGasProvider) { + return new L1Messenger(contractAddress, web3j, credentials, contractGasProvider); + } + + public static L1Messenger load( + String contractAddress, + Web3j web3j, + TransactionManager transactionManager, + ContractGasProvider contractGasProvider) { + return new L1Messenger(contractAddress, web3j, transactionManager, contractGasProvider); + } + + public static class L1MessageSentEventResponse extends BaseEventResponse { + public String _sender; + + public byte[] _hash; + + public byte[] _message; + } } diff --git a/src/main/java/io/zksync/wrappers/NonceHolder.java b/src/main/java/io/zksync/wrappers/NonceHolder.java index 5947dd4..2af6ffd 100644 --- a/src/main/java/io/zksync/wrappers/NonceHolder.java +++ b/src/main/java/io/zksync/wrappers/NonceHolder.java @@ -16,108 +16,153 @@ import org.web3j.tx.gas.ContractGasProvider; /** - *

Auto generated code. + * Auto generated code. + * *

Do not modify! + * *

Please use the web3j command line tools, - * or the org.web3j.codegen.SolidityFunctionWrapperGenerator in the - * codegen module to update. + * or the org.web3j.codegen.SolidityFunctionWrapperGenerator in the codegen module to update. * *

Generated with web3j version 4.7.0. */ @SuppressWarnings("rawtypes") public class NonceHolder extends Contract { - public static final String BINARY = "Bin file was not provided"; - - public static final String FUNC_GETACCOUNTNONCE = "getAccountNonce"; - - public static final String FUNC_GETDEPLOYMENTNONCE = "getDeploymentNonce"; - - public static final String FUNC_GETRAWNONCE = "getRawNonce"; - - public static final String FUNC_INCREMENTDEPLOYMENTNONCE = "incrementDeploymentNonce"; - - public static final String FUNC_INCREMENTNONCE = "incrementNonce"; - - public static final String FUNC_INCREMENTNONCEIFEQUALS = "incrementNonceIfEquals"; - - @Deprecated - protected NonceHolder(String contractAddress, Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) { - super(BINARY, contractAddress, web3j, credentials, gasPrice, gasLimit); - } - - protected NonceHolder(String contractAddress, Web3j web3j, Credentials credentials, ContractGasProvider contractGasProvider) { - super(BINARY, contractAddress, web3j, credentials, contractGasProvider); - } - - @Deprecated - protected NonceHolder(String contractAddress, Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit) { - super(BINARY, contractAddress, web3j, transactionManager, gasPrice, gasLimit); - } - - protected NonceHolder(String contractAddress, Web3j web3j, TransactionManager transactionManager, ContractGasProvider contractGasProvider) { - super(BINARY, contractAddress, web3j, transactionManager, contractGasProvider); - } - - public RemoteFunctionCall getAccountNonce() { - final Function function = new Function(FUNC_GETACCOUNTNONCE, - Arrays.asList(), - Arrays.>asList(new TypeReference() {})); - return executeRemoteCallSingleValueReturn(function, BigInteger.class); - } - - public RemoteFunctionCall getDeploymentNonce(String _address) { - final Function function = new Function(FUNC_GETDEPLOYMENTNONCE, - Arrays.asList(new org.web3j.abi.datatypes.Address(160, _address)), - Arrays.>asList(new TypeReference() {})); - return executeRemoteCallSingleValueReturn(function, BigInteger.class); - } - - public RemoteFunctionCall getRawNonce(String _address) { - final Function function = new Function(FUNC_GETRAWNONCE, - Arrays.asList(new org.web3j.abi.datatypes.Address(160, _address)), - Arrays.>asList(new TypeReference() {})); - return executeRemoteCallSingleValueReturn(function, BigInteger.class); - } - - public RemoteFunctionCall incrementDeploymentNonce(String _address) { - final Function function = new Function( - FUNC_INCREMENTDEPLOYMENTNONCE, - Arrays.asList(new org.web3j.abi.datatypes.Address(160, _address)), - Collections.>emptyList()); - return executeRemoteCallTransaction(function); - } - - public RemoteFunctionCall incrementNonce() { - final Function function = new Function( - FUNC_INCREMENTNONCE, - Arrays.asList(), - Collections.>emptyList()); - return executeRemoteCallTransaction(function); - } - - public RemoteFunctionCall incrementNonceIfEquals(BigInteger _expectedNonce) { - final Function function = new Function( - FUNC_INCREMENTNONCEIFEQUALS, - Arrays.asList(new org.web3j.abi.datatypes.generated.Uint256(_expectedNonce)), - Collections.>emptyList()); - return executeRemoteCallTransaction(function); - } - - @Deprecated - public static NonceHolder load(String contractAddress, Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) { - return new NonceHolder(contractAddress, web3j, credentials, gasPrice, gasLimit); - } - - @Deprecated - public static NonceHolder load(String contractAddress, Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit) { - return new NonceHolder(contractAddress, web3j, transactionManager, gasPrice, gasLimit); - } - - public static NonceHolder load(String contractAddress, Web3j web3j, Credentials credentials, ContractGasProvider contractGasProvider) { - return new NonceHolder(contractAddress, web3j, credentials, contractGasProvider); - } - - public static NonceHolder load(String contractAddress, Web3j web3j, TransactionManager transactionManager, ContractGasProvider contractGasProvider) { - return new NonceHolder(contractAddress, web3j, transactionManager, contractGasProvider); - } + public static final String BINARY = "Bin file was not provided"; + + public static final String FUNC_GETACCOUNTNONCE = "getAccountNonce"; + + public static final String FUNC_GETDEPLOYMENTNONCE = "getDeploymentNonce"; + + public static final String FUNC_GETRAWNONCE = "getRawNonce"; + + public static final String FUNC_INCREMENTDEPLOYMENTNONCE = "incrementDeploymentNonce"; + + public static final String FUNC_INCREMENTNONCE = "incrementNonce"; + + public static final String FUNC_INCREMENTNONCEIFEQUALS = "incrementNonceIfEquals"; + + @Deprecated + protected NonceHolder( + String contractAddress, + Web3j web3j, + Credentials credentials, + BigInteger gasPrice, + BigInteger gasLimit) { + super(BINARY, contractAddress, web3j, credentials, gasPrice, gasLimit); + } + + protected NonceHolder( + String contractAddress, + Web3j web3j, + Credentials credentials, + ContractGasProvider contractGasProvider) { + super(BINARY, contractAddress, web3j, credentials, contractGasProvider); + } + + @Deprecated + protected NonceHolder( + String contractAddress, + Web3j web3j, + TransactionManager transactionManager, + BigInteger gasPrice, + BigInteger gasLimit) { + super(BINARY, contractAddress, web3j, transactionManager, gasPrice, gasLimit); + } + + protected NonceHolder( + String contractAddress, + Web3j web3j, + TransactionManager transactionManager, + ContractGasProvider contractGasProvider) { + super(BINARY, contractAddress, web3j, transactionManager, contractGasProvider); + } + + public RemoteFunctionCall getAccountNonce() { + final Function function = + new Function( + FUNC_GETACCOUNTNONCE, + Arrays.asList(), + Arrays.>asList(new TypeReference() {})); + return executeRemoteCallSingleValueReturn(function, BigInteger.class); + } + + public RemoteFunctionCall getDeploymentNonce(String _address) { + final Function function = + new Function( + FUNC_GETDEPLOYMENTNONCE, + Arrays.asList(new org.web3j.abi.datatypes.Address(160, _address)), + Arrays.>asList(new TypeReference() {})); + return executeRemoteCallSingleValueReturn(function, BigInteger.class); + } + + public RemoteFunctionCall getRawNonce(String _address) { + final Function function = + new Function( + FUNC_GETRAWNONCE, + Arrays.asList(new org.web3j.abi.datatypes.Address(160, _address)), + Arrays.>asList(new TypeReference() {})); + return executeRemoteCallSingleValueReturn(function, BigInteger.class); + } + + public RemoteFunctionCall incrementDeploymentNonce(String _address) { + final Function function = + new Function( + FUNC_INCREMENTDEPLOYMENTNONCE, + Arrays.asList(new org.web3j.abi.datatypes.Address(160, _address)), + Collections.>emptyList()); + return executeRemoteCallTransaction(function); + } + + public RemoteFunctionCall incrementNonce() { + final Function function = + new Function( + FUNC_INCREMENTNONCE, Arrays.asList(), Collections.>emptyList()); + return executeRemoteCallTransaction(function); + } + + public RemoteFunctionCall incrementNonceIfEquals(BigInteger _expectedNonce) { + final Function function = + new Function( + FUNC_INCREMENTNONCEIFEQUALS, + Arrays.asList(new org.web3j.abi.datatypes.generated.Uint256(_expectedNonce)), + Collections.>emptyList()); + return executeRemoteCallTransaction(function); + } + + @Deprecated + public static NonceHolder load( + String contractAddress, + Web3j web3j, + Credentials credentials, + BigInteger gasPrice, + BigInteger gasLimit) { + return new NonceHolder(contractAddress, web3j, credentials, gasPrice, gasLimit); + } + + @Deprecated + public static NonceHolder load( + String contractAddress, + Web3j web3j, + TransactionManager transactionManager, + BigInteger gasPrice, + BigInteger gasLimit) { + return new NonceHolder(contractAddress, web3j, transactionManager, gasPrice, gasLimit); + } + + public static NonceHolder load( + String contractAddress, + Web3j web3j, + Credentials credentials, + ContractGasProvider contractGasProvider) { + return new NonceHolder(contractAddress, web3j, credentials, contractGasProvider); + } + + public static NonceHolder load( + String contractAddress, + Web3j web3j, + TransactionManager transactionManager, + ContractGasProvider contractGasProvider) { + return new NonceHolder(contractAddress, web3j, transactionManager, contractGasProvider); + } } diff --git a/src/main/java/io/zksync/wrappers/PriorityOpTree.java b/src/main/java/io/zksync/wrappers/PriorityOpTree.java index 8d8f1e8..d023822 100644 --- a/src/main/java/io/zksync/wrappers/PriorityOpTree.java +++ b/src/main/java/io/zksync/wrappers/PriorityOpTree.java @@ -3,16 +3,16 @@ import java.math.BigInteger; public enum PriorityOpTree { - Full(0), - Rollup(1); + Full(0), + Rollup(1); - private final long type; + private final long type; - PriorityOpTree(long type) { - this.type = type; - } + PriorityOpTree(long type) { + this.type = type; + } - public BigInteger getValue() { - return BigInteger.valueOf(type); - } + public BigInteger getValue() { + return BigInteger.valueOf(type); + } } diff --git a/src/main/java/io/zksync/wrappers/PriorityQueueType.java b/src/main/java/io/zksync/wrappers/PriorityQueueType.java index 9a15482..ad1e18f 100644 --- a/src/main/java/io/zksync/wrappers/PriorityQueueType.java +++ b/src/main/java/io/zksync/wrappers/PriorityQueueType.java @@ -3,17 +3,17 @@ import java.math.BigInteger; public enum PriorityQueueType { - Deque(0), - HeapBuffer(1), - Heap(2); + Deque(0), + HeapBuffer(1), + Heap(2); - private final long type; + private final long type; - PriorityQueueType(long type) { - this.type = type; - } + PriorityQueueType(long type) { + this.type = type; + } - public BigInteger getValue() { - return BigInteger.valueOf(type); - } + public BigInteger getValue() { + return BigInteger.valueOf(type); + } } diff --git a/src/main/java/io/zksync/wrappers/ZkSyncContract.java b/src/main/java/io/zksync/wrappers/ZkSyncContract.java index 40293b7..a35ca34 100644 --- a/src/main/java/io/zksync/wrappers/ZkSyncContract.java +++ b/src/main/java/io/zksync/wrappers/ZkSyncContract.java @@ -44,2077 +44,2702 @@ import org.web3j.tx.gas.ContractGasProvider; /** - *

Auto generated code. + * Auto generated code. + * *

Do not modify! + * *

Please use the web3j command line tools, - * or the org.web3j.codegen.SolidityFunctionWrapperGenerator in the - * codegen module to update. + * or the org.web3j.codegen.SolidityFunctionWrapperGenerator in the codegen module to update. * *

Generated with web3j version 4.9.7. */ @SuppressWarnings("rawtypes") public class ZkSyncContract extends Contract { - public static final String BINARY = "0x"; - - public static final String FUNC_ACCEPTGOVERNOR = "acceptGovernor"; - - public static final String FUNC_CANCELUPGRADEPROPOSAL = "cancelUpgradeProposal"; + public static final String BINARY = "0x"; - public static final String FUNC_COMMITBLOCKS = "commitBlocks"; + public static final String FUNC_ACCEPTGOVERNOR = "acceptGovernor"; - public static final String FUNC_EXECUTEBLOCKS = "executeBlocks"; + public static final String FUNC_CANCELUPGRADEPROPOSAL = "cancelUpgradeProposal"; - public static final String FUNC_EXECUTEUPGRADE = "executeUpgrade"; + public static final String FUNC_COMMITBLOCKS = "commitBlocks"; - public static final String FUNC_FACETADDRESS = "facetAddress"; + public static final String FUNC_EXECUTEBLOCKS = "executeBlocks"; - public static final String FUNC_FACETADDRESSES = "facetAddresses"; + public static final String FUNC_EXECUTEUPGRADE = "executeUpgrade"; - public static final String FUNC_FACETFUNCTIONSELECTORS = "facetFunctionSelectors"; + public static final String FUNC_FACETADDRESS = "facetAddress"; - public static final String FUNC_FACETS = "facets"; + public static final String FUNC_FACETADDRESSES = "facetAddresses"; - public static final String FUNC_FINALIZEETHWITHDRAWAL = "finalizeEthWithdrawal"; + public static final String FUNC_FACETFUNCTIONSELECTORS = "facetFunctionSelectors"; - public static final String FUNC_FREEZEDIAMOND = "freezeDiamond"; + public static final String FUNC_FACETS = "facets"; - public static final String FUNC_GETCURRENTPROPOSALID = "getCurrentProposalId"; + public static final String FUNC_FINALIZEETHWITHDRAWAL = "finalizeEthWithdrawal"; - public static final String FUNC_GETFIRSTUNPROCESSEDPRIORITYTX = "getFirstUnprocessedPriorityTx"; + public static final String FUNC_FREEZEDIAMOND = "freezeDiamond"; - public static final String FUNC_GETGOVERNOR = "getGovernor"; + public static final String FUNC_GETCURRENTPROPOSALID = "getCurrentProposalId"; - public static final String FUNC_GETL2BOOTLOADERBYTECODEHASH = "getL2BootloaderBytecodeHash"; + public static final String FUNC_GETFIRSTUNPROCESSEDPRIORITYTX = "getFirstUnprocessedPriorityTx"; - public static final String FUNC_GETL2DEFAULTACCOUNTBYTECODEHASH = "getL2DefaultAccountBytecodeHash"; + public static final String FUNC_GETGOVERNOR = "getGovernor"; - public static final String FUNC_GETPENDINGGOVERNOR = "getPendingGovernor"; + public static final String FUNC_GETL2BOOTLOADERBYTECODEHASH = "getL2BootloaderBytecodeHash"; - public static final String FUNC_GETPRIORITYQUEUESIZE = "getPriorityQueueSize"; + public static final String FUNC_GETL2DEFAULTACCOUNTBYTECODEHASH = + "getL2DefaultAccountBytecodeHash"; - public static final String FUNC_GETPROPOSEDUPGRADEHASH = "getProposedUpgradeHash"; + public static final String FUNC_GETPENDINGGOVERNOR = "getPendingGovernor"; - public static final String FUNC_GETPROPOSEDUPGRADETIMESTAMP = "getProposedUpgradeTimestamp"; + public static final String FUNC_GETPRIORITYQUEUESIZE = "getPriorityQueueSize"; - public static final String FUNC_GETSECURITYCOUNCIL = "getSecurityCouncil"; + public static final String FUNC_GETPROPOSEDUPGRADEHASH = "getProposedUpgradeHash"; - public static final String FUNC_GETTOTALBLOCKSCOMMITTED = "getTotalBlocksCommitted"; + public static final String FUNC_GETPROPOSEDUPGRADETIMESTAMP = "getProposedUpgradeTimestamp"; - public static final String FUNC_GETTOTALBLOCKSEXECUTED = "getTotalBlocksExecuted"; + public static final String FUNC_GETSECURITYCOUNCIL = "getSecurityCouncil"; - public static final String FUNC_GETTOTALBLOCKSVERIFIED = "getTotalBlocksVerified"; + public static final String FUNC_GETTOTALBLOCKSCOMMITTED = "getTotalBlocksCommitted"; - public static final String FUNC_GETTOTALPRIORITYTXS = "getTotalPriorityTxs"; + public static final String FUNC_GETTOTALBLOCKSEXECUTED = "getTotalBlocksExecuted"; - public static final String FUNC_GETUPGRADEPROPOSALSTATE = "getUpgradeProposalState"; + public static final String FUNC_GETTOTALBLOCKSVERIFIED = "getTotalBlocksVerified"; - public static final String FUNC_GETVERIFIER = "getVerifier"; + public static final String FUNC_GETTOTALPRIORITYTXS = "getTotalPriorityTxs"; - public static final String FUNC_GETVERIFIERPARAMS = "getVerifierParams"; + public static final String FUNC_GETUPGRADEPROPOSALSTATE = "getUpgradeProposalState"; - public static final String FUNC_GETPRIORITYTXMAXGASLIMIT = "getpriorityTxMaxGasLimit"; + public static final String FUNC_GETVERIFIER = "getVerifier"; - public static final String FUNC_ISAPPROVEDBYSECURITYCOUNCIL = "isApprovedBySecurityCouncil"; + public static final String FUNC_GETVERIFIERPARAMS = "getVerifierParams"; - public static final String FUNC_ISDIAMONDSTORAGEFROZEN = "isDiamondStorageFrozen"; + public static final String FUNC_GETPRIORITYTXMAXGASLIMIT = "getpriorityTxMaxGasLimit"; - public static final String FUNC_ISETHWITHDRAWALFINALIZED = "isEthWithdrawalFinalized"; + public static final String FUNC_ISAPPROVEDBYSECURITYCOUNCIL = "isApprovedBySecurityCouncil"; - public static final String FUNC_ISFACETFREEZABLE = "isFacetFreezable"; + public static final String FUNC_ISDIAMONDSTORAGEFROZEN = "isDiamondStorageFrozen"; - public static final String FUNC_ISFUNCTIONFREEZABLE = "isFunctionFreezable"; + public static final String FUNC_ISETHWITHDRAWALFINALIZED = "isEthWithdrawalFinalized"; - public static final String FUNC_ISVALIDATOR = "isValidator"; + public static final String FUNC_ISFACETFREEZABLE = "isFacetFreezable"; - public static final String FUNC_L2LOGSROOTHASH = "l2LogsRootHash"; + public static final String FUNC_ISFUNCTIONFREEZABLE = "isFunctionFreezable"; - public static final String FUNC_L2TRANSACTIONBASECOST = "l2TransactionBaseCost"; + public static final String FUNC_ISVALIDATOR = "isValidator"; - public static final String FUNC_PRIORITYQUEUEFRONTOPERATION = "priorityQueueFrontOperation"; + public static final String FUNC_L2LOGSROOTHASH = "l2LogsRootHash"; - public static final String FUNC_PROPOSESHADOWUPGRADE = "proposeShadowUpgrade"; + public static final String FUNC_L2TRANSACTIONBASECOST = "l2TransactionBaseCost"; - public static final String FUNC_PROPOSETRANSPARENTUPGRADE = "proposeTransparentUpgrade"; + public static final String FUNC_PRIORITYQUEUEFRONTOPERATION = "priorityQueueFrontOperation"; - public static final String FUNC_PROVEBLOCKS = "proveBlocks"; + public static final String FUNC_PROPOSESHADOWUPGRADE = "proposeShadowUpgrade"; - public static final String FUNC_PROVEL1TOL2TRANSACTIONSTATUS = "proveL1ToL2TransactionStatus"; + public static final String FUNC_PROPOSETRANSPARENTUPGRADE = "proposeTransparentUpgrade"; - public static final String FUNC_PROVEL2LOGINCLUSION = "proveL2LogInclusion"; + public static final String FUNC_PROVEBLOCKS = "proveBlocks"; - public static final String FUNC_PROVEL2MESSAGEINCLUSION = "proveL2MessageInclusion"; + public static final String FUNC_PROVEL1TOL2TRANSACTIONSTATUS = "proveL1ToL2TransactionStatus"; - public static final String FUNC_REQUESTL2TRANSACTION = "requestL2Transaction"; + public static final String FUNC_PROVEL2LOGINCLUSION = "proveL2LogInclusion"; - public static final String FUNC_REVERTBLOCKS = "revertBlocks"; + public static final String FUNC_PROVEL2MESSAGEINCLUSION = "proveL2MessageInclusion"; - public static final String FUNC_SECURITYCOUNCILUPGRADEAPPROVE = "securityCouncilUpgradeApprove"; + public static final String FUNC_REQUESTL2TRANSACTION = "requestL2Transaction"; - public static final String FUNC_SERIALIZEL2TRANSACTION = "serializeL2Transaction"; + public static final String FUNC_REVERTBLOCKS = "revertBlocks"; - public static final String FUNC_SETL2BOOTLOADERBYTECODEHASH = "setL2BootloaderBytecodeHash"; + public static final String FUNC_SECURITYCOUNCILUPGRADEAPPROVE = "securityCouncilUpgradeApprove"; - public static final String FUNC_SETL2DEFAULTACCOUNTBYTECODEHASH = "setL2DefaultAccountBytecodeHash"; + public static final String FUNC_SERIALIZEL2TRANSACTION = "serializeL2Transaction"; - public static final String FUNC_SETPENDINGGOVERNOR = "setPendingGovernor"; + public static final String FUNC_SETL2BOOTLOADERBYTECODEHASH = "setL2BootloaderBytecodeHash"; - public static final String FUNC_SETPORTERAVAILABILITY = "setPorterAvailability"; + public static final String FUNC_SETL2DEFAULTACCOUNTBYTECODEHASH = + "setL2DefaultAccountBytecodeHash"; - public static final String FUNC_SETPRIORITYTXMAXGASLIMIT = "setPriorityTxMaxGasLimit"; + public static final String FUNC_SETPENDINGGOVERNOR = "setPendingGovernor"; - public static final String FUNC_SETVALIDATOR = "setValidator"; + public static final String FUNC_SETPORTERAVAILABILITY = "setPorterAvailability"; - public static final String FUNC_SETVERIFIER = "setVerifier"; + public static final String FUNC_SETPRIORITYTXMAXGASLIMIT = "setPriorityTxMaxGasLimit"; - public static final String FUNC_SETVERIFIERPARAMS = "setVerifierParams"; + public static final String FUNC_SETVALIDATOR = "setValidator"; - public static final String FUNC_STOREDBLOCKHASH = "storedBlockHash"; + public static final String FUNC_SETVERIFIER = "setVerifier"; - public static final String FUNC_UNFREEZEDIAMOND = "unfreezeDiamond"; + public static final String FUNC_SETVERIFIERPARAMS = "setVerifierParams"; - public static final String FUNC_UPGRADEPROPOSALHASH = "upgradeProposalHash"; + public static final String FUNC_STOREDBLOCKHASH = "storedBlockHash"; - public static final Event BLOCKCOMMIT_EVENT = new Event("BlockCommit", - Arrays.>asList(new TypeReference(true) {}, new TypeReference(true) {}, new TypeReference(true) {})); - ; + public static final String FUNC_UNFREEZEDIAMOND = "unfreezeDiamond"; - public static final Event BLOCKEXECUTION_EVENT = new Event("BlockExecution", - Arrays.>asList(new TypeReference(true) {}, new TypeReference(true) {}, new TypeReference(true) {})); - ; + public static final String FUNC_UPGRADEPROPOSALHASH = "upgradeProposalHash"; - public static final Event BLOCKSREVERT_EVENT = new Event("BlocksRevert", - Arrays.>asList(new TypeReference() {}, new TypeReference() {}, new TypeReference() {})); - ; + public static final Event BLOCKCOMMIT_EVENT = + new Event( + "BlockCommit", + Arrays.>asList( + new TypeReference(true) {}, + new TypeReference(true) {}, + new TypeReference(true) {})); + ; - public static final Event BLOCKSVERIFICATION_EVENT = new Event("BlocksVerification", - Arrays.>asList(new TypeReference(true) {}, new TypeReference(true) {})); - ; + public static final Event BLOCKEXECUTION_EVENT = + new Event( + "BlockExecution", + Arrays.>asList( + new TypeReference(true) {}, + new TypeReference(true) {}, + new TypeReference(true) {})); + ; - public static final Event CANCELUPGRADEPROPOSAL_EVENT = new Event("CancelUpgradeProposal", - Arrays.>asList(new TypeReference(true) {}, new TypeReference(true) {})); - ; + public static final Event BLOCKSREVERT_EVENT = + new Event( + "BlocksRevert", + Arrays.>asList( + new TypeReference() {}, + new TypeReference() {}, + new TypeReference() {})); + ; - public static final Event ETHWITHDRAWALFINALIZED_EVENT = new Event("EthWithdrawalFinalized", - Arrays.>asList(new TypeReference

(true) {}, new TypeReference() {})); - ; + public static final Event BLOCKSVERIFICATION_EVENT = + new Event( + "BlocksVerification", + Arrays.>asList( + new TypeReference(true) {}, new TypeReference(true) {})); + ; - public static final Event EXECUTEUPGRADE_EVENT = new Event("ExecuteUpgrade", - Arrays.>asList(new TypeReference(true) {}, new TypeReference(true) {}, new TypeReference() {})); - ; - - public static final Event FREEZE_EVENT = new Event("Freeze", - Arrays.>asList()); - ; - - public static final Event ISPORTERAVAILABLESTATUSUPDATE_EVENT = new Event("IsPorterAvailableStatusUpdate", + public static final Event CANCELUPGRADEPROPOSAL_EVENT = + new Event( + "CancelUpgradeProposal", + Arrays.>asList( + new TypeReference(true) {}, new TypeReference(true) {})); + ; + + public static final Event ETHWITHDRAWALFINALIZED_EVENT = + new Event( + "EthWithdrawalFinalized", + Arrays.>asList( + new TypeReference
(true) {}, new TypeReference() {})); + ; + + public static final Event EXECUTEUPGRADE_EVENT = + new Event( + "ExecuteUpgrade", + Arrays.>asList( + new TypeReference(true) {}, + new TypeReference(true) {}, + new TypeReference() {})); + ; + + public static final Event FREEZE_EVENT = new Event("Freeze", Arrays.>asList()); + ; + + public static final Event ISPORTERAVAILABLESTATUSUPDATE_EVENT = + new Event( + "IsPorterAvailableStatusUpdate", + Arrays.>asList(new TypeReference() {})); + ; + + public static final Event NEWGOVERNOR_EVENT = + new Event( + "NewGovernor", + Arrays.>asList( + new TypeReference
(true) {}, new TypeReference
(true) {})); + ; + + public static final Event NEWL2BOOTLOADERBYTECODEHASH_EVENT = + new Event( + "NewL2BootloaderBytecodeHash", + Arrays.>asList( + new TypeReference(true) {}, new TypeReference(true) {})); + ; + + public static final Event NEWL2DEFAULTACCOUNTBYTECODEHASH_EVENT = + new Event( + "NewL2DefaultAccountBytecodeHash", + Arrays.>asList( + new TypeReference(true) {}, new TypeReference(true) {})); + ; + + public static final Event NEWPENDINGGOVERNOR_EVENT = + new Event( + "NewPendingGovernor", + Arrays.>asList( + new TypeReference
(true) {}, new TypeReference
(true) {})); + ; + + public static final Event NEWPRIORITYREQUEST_EVENT = + new Event( + "NewPriorityRequest", + Arrays.>asList( + new TypeReference() {}, + new TypeReference() {}, + new TypeReference() {}, + new TypeReference() {}, + new TypeReference>() {})); + ; + + public static final Event NEWPRIORITYTXMAXGASLIMIT_EVENT = + new Event( + "NewPriorityTxMaxGasLimit", + Arrays.>asList( + new TypeReference() {}, new TypeReference() {})); + ; + + public static final Event NEWVERIFIER_EVENT = + new Event( + "NewVerifier", + Arrays.>asList( + new TypeReference
(true) {}, new TypeReference
(true) {})); + ; + + public static final Event NEWVERIFIERPARAMS_EVENT = + new Event( + "NewVerifierParams", + Arrays.>asList( + new TypeReference() {}, new TypeReference() {})); + ; + + public static final Event PROPOSESHADOWUPGRADE_EVENT = + new Event( + "ProposeShadowUpgrade", + Arrays.>asList( + new TypeReference(true) {}, new TypeReference(true) {})); + ; + + public static final Event PROPOSETRANSPARENTUPGRADE_EVENT = + new Event( + "ProposeTransparentUpgrade", + Arrays.>asList( + new TypeReference() {}, + new TypeReference(true) {}, + new TypeReference() {})); + ; + + public static final Event SECURITYCOUNCILUPGRADEAPPROVE_EVENT = + new Event( + "SecurityCouncilUpgradeApprove", + Arrays.>asList( + new TypeReference(true) {}, new TypeReference(true) {})); + ; + + public static final Event UNFREEZE_EVENT = + new Event("Unfreeze", Arrays.>asList()); + ; + + public static final Event VALIDATORSTATUSUPDATE_EVENT = + new Event( + "ValidatorStatusUpdate", + Arrays.>asList( + new TypeReference
(true) {}, new TypeReference() {})); + ; + + protected static final HashMap _addresses; + + static { + _addresses = new HashMap(); + } + + @Deprecated + protected ZkSyncContract( + String contractAddress, + Web3j web3j, + Credentials credentials, + BigInteger gasPrice, + BigInteger gasLimit) { + super(BINARY, contractAddress, web3j, credentials, gasPrice, gasLimit); + } + + protected ZkSyncContract( + String contractAddress, + Web3j web3j, + Credentials credentials, + ContractGasProvider contractGasProvider) { + super(BINARY, contractAddress, web3j, credentials, contractGasProvider); + } + + @Deprecated + protected ZkSyncContract( + String contractAddress, + Web3j web3j, + TransactionManager transactionManager, + BigInteger gasPrice, + BigInteger gasLimit) { + super(BINARY, contractAddress, web3j, transactionManager, gasPrice, gasLimit); + } + + protected ZkSyncContract( + String contractAddress, + Web3j web3j, + TransactionManager transactionManager, + ContractGasProvider contractGasProvider) { + super(BINARY, contractAddress, web3j, transactionManager, contractGasProvider); + } + + public static List getBlockCommitEvents( + TransactionReceipt transactionReceipt) { + List valueList = + staticExtractEventParametersWithLog(BLOCKCOMMIT_EVENT, transactionReceipt); + ArrayList responses = + new ArrayList(valueList.size()); + for (Contract.EventValuesWithLog eventValues : valueList) { + BlockCommitEventResponse typedResponse = new BlockCommitEventResponse(); + typedResponse.log = eventValues.getLog(); + typedResponse.blockNumber = (BigInteger) eventValues.getIndexedValues().get(0).getValue(); + typedResponse.blockHash = (byte[]) eventValues.getIndexedValues().get(1).getValue(); + typedResponse.commitment = (byte[]) eventValues.getIndexedValues().get(2).getValue(); + responses.add(typedResponse); + } + return responses; + } + + public static BlockCommitEventResponse getBlockCommitEventFromLog(Log log) { + Contract.EventValuesWithLog eventValues = + staticExtractEventParametersWithLog(BLOCKCOMMIT_EVENT, log); + BlockCommitEventResponse typedResponse = new BlockCommitEventResponse(); + typedResponse.log = log; + typedResponse.blockNumber = (BigInteger) eventValues.getIndexedValues().get(0).getValue(); + typedResponse.blockHash = (byte[]) eventValues.getIndexedValues().get(1).getValue(); + typedResponse.commitment = (byte[]) eventValues.getIndexedValues().get(2).getValue(); + return typedResponse; + } + + public Flowable blockCommitEventFlowable(EthFilter filter) { + return web3j.ethLogFlowable(filter).map(log -> getBlockCommitEventFromLog(log)); + } + + public Flowable blockCommitEventFlowable( + DefaultBlockParameter startBlock, DefaultBlockParameter endBlock) { + EthFilter filter = new EthFilter(startBlock, endBlock, getContractAddress()); + filter.addSingleTopic(EventEncoder.encode(BLOCKCOMMIT_EVENT)); + return blockCommitEventFlowable(filter); + } + + public static List getBlockExecutionEvents( + TransactionReceipt transactionReceipt) { + List valueList = + staticExtractEventParametersWithLog(BLOCKEXECUTION_EVENT, transactionReceipt); + ArrayList responses = + new ArrayList(valueList.size()); + for (Contract.EventValuesWithLog eventValues : valueList) { + BlockExecutionEventResponse typedResponse = new BlockExecutionEventResponse(); + typedResponse.log = eventValues.getLog(); + typedResponse.blockNumber = (BigInteger) eventValues.getIndexedValues().get(0).getValue(); + typedResponse.blockHash = (byte[]) eventValues.getIndexedValues().get(1).getValue(); + typedResponse.commitment = (byte[]) eventValues.getIndexedValues().get(2).getValue(); + responses.add(typedResponse); + } + return responses; + } + + public static BlockExecutionEventResponse getBlockExecutionEventFromLog(Log log) { + Contract.EventValuesWithLog eventValues = + staticExtractEventParametersWithLog(BLOCKEXECUTION_EVENT, log); + BlockExecutionEventResponse typedResponse = new BlockExecutionEventResponse(); + typedResponse.log = log; + typedResponse.blockNumber = (BigInteger) eventValues.getIndexedValues().get(0).getValue(); + typedResponse.blockHash = (byte[]) eventValues.getIndexedValues().get(1).getValue(); + typedResponse.commitment = (byte[]) eventValues.getIndexedValues().get(2).getValue(); + return typedResponse; + } + + public Flowable blockExecutionEventFlowable(EthFilter filter) { + return web3j.ethLogFlowable(filter).map(log -> getBlockExecutionEventFromLog(log)); + } + + public Flowable blockExecutionEventFlowable( + DefaultBlockParameter startBlock, DefaultBlockParameter endBlock) { + EthFilter filter = new EthFilter(startBlock, endBlock, getContractAddress()); + filter.addSingleTopic(EventEncoder.encode(BLOCKEXECUTION_EVENT)); + return blockExecutionEventFlowable(filter); + } + + public static List getBlocksRevertEvents( + TransactionReceipt transactionReceipt) { + List valueList = + staticExtractEventParametersWithLog(BLOCKSREVERT_EVENT, transactionReceipt); + ArrayList responses = + new ArrayList(valueList.size()); + for (Contract.EventValuesWithLog eventValues : valueList) { + BlocksRevertEventResponse typedResponse = new BlocksRevertEventResponse(); + typedResponse.log = eventValues.getLog(); + typedResponse.totalBlocksCommitted = + (BigInteger) eventValues.getNonIndexedValues().get(0).getValue(); + typedResponse.totalBlocksVerified = + (BigInteger) eventValues.getNonIndexedValues().get(1).getValue(); + typedResponse.totalBlocksExecuted = + (BigInteger) eventValues.getNonIndexedValues().get(2).getValue(); + responses.add(typedResponse); + } + return responses; + } + + public static BlocksRevertEventResponse getBlocksRevertEventFromLog(Log log) { + Contract.EventValuesWithLog eventValues = + staticExtractEventParametersWithLog(BLOCKSREVERT_EVENT, log); + BlocksRevertEventResponse typedResponse = new BlocksRevertEventResponse(); + typedResponse.log = log; + typedResponse.totalBlocksCommitted = + (BigInteger) eventValues.getNonIndexedValues().get(0).getValue(); + typedResponse.totalBlocksVerified = + (BigInteger) eventValues.getNonIndexedValues().get(1).getValue(); + typedResponse.totalBlocksExecuted = + (BigInteger) eventValues.getNonIndexedValues().get(2).getValue(); + return typedResponse; + } + + public Flowable blocksRevertEventFlowable(EthFilter filter) { + return web3j.ethLogFlowable(filter).map(log -> getBlocksRevertEventFromLog(log)); + } + + public Flowable blocksRevertEventFlowable( + DefaultBlockParameter startBlock, DefaultBlockParameter endBlock) { + EthFilter filter = new EthFilter(startBlock, endBlock, getContractAddress()); + filter.addSingleTopic(EventEncoder.encode(BLOCKSREVERT_EVENT)); + return blocksRevertEventFlowable(filter); + } + + public static List getBlocksVerificationEvents( + TransactionReceipt transactionReceipt) { + List valueList = + staticExtractEventParametersWithLog(BLOCKSVERIFICATION_EVENT, transactionReceipt); + ArrayList responses = + new ArrayList(valueList.size()); + for (Contract.EventValuesWithLog eventValues : valueList) { + BlocksVerificationEventResponse typedResponse = new BlocksVerificationEventResponse(); + typedResponse.log = eventValues.getLog(); + typedResponse.previousLastVerifiedBlock = + (BigInteger) eventValues.getIndexedValues().get(0).getValue(); + typedResponse.currentLastVerifiedBlock = + (BigInteger) eventValues.getIndexedValues().get(1).getValue(); + responses.add(typedResponse); + } + return responses; + } + + public static BlocksVerificationEventResponse getBlocksVerificationEventFromLog(Log log) { + Contract.EventValuesWithLog eventValues = + staticExtractEventParametersWithLog(BLOCKSVERIFICATION_EVENT, log); + BlocksVerificationEventResponse typedResponse = new BlocksVerificationEventResponse(); + typedResponse.log = log; + typedResponse.previousLastVerifiedBlock = + (BigInteger) eventValues.getIndexedValues().get(0).getValue(); + typedResponse.currentLastVerifiedBlock = + (BigInteger) eventValues.getIndexedValues().get(1).getValue(); + return typedResponse; + } + + public Flowable blocksVerificationEventFlowable( + EthFilter filter) { + return web3j.ethLogFlowable(filter).map(log -> getBlocksVerificationEventFromLog(log)); + } + + public Flowable blocksVerificationEventFlowable( + DefaultBlockParameter startBlock, DefaultBlockParameter endBlock) { + EthFilter filter = new EthFilter(startBlock, endBlock, getContractAddress()); + filter.addSingleTopic(EventEncoder.encode(BLOCKSVERIFICATION_EVENT)); + return blocksVerificationEventFlowable(filter); + } + + public static List getCancelUpgradeProposalEvents( + TransactionReceipt transactionReceipt) { + List valueList = + staticExtractEventParametersWithLog(CANCELUPGRADEPROPOSAL_EVENT, transactionReceipt); + ArrayList responses = + new ArrayList(valueList.size()); + for (Contract.EventValuesWithLog eventValues : valueList) { + CancelUpgradeProposalEventResponse typedResponse = new CancelUpgradeProposalEventResponse(); + typedResponse.log = eventValues.getLog(); + typedResponse.proposalId = (BigInteger) eventValues.getIndexedValues().get(0).getValue(); + typedResponse.proposalHash = (byte[]) eventValues.getIndexedValues().get(1).getValue(); + responses.add(typedResponse); + } + return responses; + } + + public static CancelUpgradeProposalEventResponse getCancelUpgradeProposalEventFromLog(Log log) { + Contract.EventValuesWithLog eventValues = + staticExtractEventParametersWithLog(CANCELUPGRADEPROPOSAL_EVENT, log); + CancelUpgradeProposalEventResponse typedResponse = new CancelUpgradeProposalEventResponse(); + typedResponse.log = log; + typedResponse.proposalId = (BigInteger) eventValues.getIndexedValues().get(0).getValue(); + typedResponse.proposalHash = (byte[]) eventValues.getIndexedValues().get(1).getValue(); + return typedResponse; + } + + public Flowable cancelUpgradeProposalEventFlowable( + EthFilter filter) { + return web3j.ethLogFlowable(filter).map(log -> getCancelUpgradeProposalEventFromLog(log)); + } + + public Flowable cancelUpgradeProposalEventFlowable( + DefaultBlockParameter startBlock, DefaultBlockParameter endBlock) { + EthFilter filter = new EthFilter(startBlock, endBlock, getContractAddress()); + filter.addSingleTopic(EventEncoder.encode(CANCELUPGRADEPROPOSAL_EVENT)); + return cancelUpgradeProposalEventFlowable(filter); + } + + public static List getEthWithdrawalFinalizedEvents( + TransactionReceipt transactionReceipt) { + List valueList = + staticExtractEventParametersWithLog(ETHWITHDRAWALFINALIZED_EVENT, transactionReceipt); + ArrayList responses = + new ArrayList(valueList.size()); + for (Contract.EventValuesWithLog eventValues : valueList) { + EthWithdrawalFinalizedEventResponse typedResponse = new EthWithdrawalFinalizedEventResponse(); + typedResponse.log = eventValues.getLog(); + typedResponse.to = (String) eventValues.getIndexedValues().get(0).getValue(); + typedResponse.amount = (BigInteger) eventValues.getNonIndexedValues().get(0).getValue(); + responses.add(typedResponse); + } + return responses; + } + + public static EthWithdrawalFinalizedEventResponse getEthWithdrawalFinalizedEventFromLog(Log log) { + Contract.EventValuesWithLog eventValues = + staticExtractEventParametersWithLog(ETHWITHDRAWALFINALIZED_EVENT, log); + EthWithdrawalFinalizedEventResponse typedResponse = new EthWithdrawalFinalizedEventResponse(); + typedResponse.log = log; + typedResponse.to = (String) eventValues.getIndexedValues().get(0).getValue(); + typedResponse.amount = (BigInteger) eventValues.getNonIndexedValues().get(0).getValue(); + return typedResponse; + } + + public Flowable ethWithdrawalFinalizedEventFlowable( + EthFilter filter) { + return web3j.ethLogFlowable(filter).map(log -> getEthWithdrawalFinalizedEventFromLog(log)); + } + + public Flowable ethWithdrawalFinalizedEventFlowable( + DefaultBlockParameter startBlock, DefaultBlockParameter endBlock) { + EthFilter filter = new EthFilter(startBlock, endBlock, getContractAddress()); + filter.addSingleTopic(EventEncoder.encode(ETHWITHDRAWALFINALIZED_EVENT)); + return ethWithdrawalFinalizedEventFlowable(filter); + } + + public static List getExecuteUpgradeEvents( + TransactionReceipt transactionReceipt) { + List valueList = + staticExtractEventParametersWithLog(EXECUTEUPGRADE_EVENT, transactionReceipt); + ArrayList responses = + new ArrayList(valueList.size()); + for (Contract.EventValuesWithLog eventValues : valueList) { + ExecuteUpgradeEventResponse typedResponse = new ExecuteUpgradeEventResponse(); + typedResponse.log = eventValues.getLog(); + typedResponse.proposalId = (BigInteger) eventValues.getIndexedValues().get(0).getValue(); + typedResponse.proposalHash = (byte[]) eventValues.getIndexedValues().get(1).getValue(); + typedResponse.proposalSalt = (byte[]) eventValues.getNonIndexedValues().get(0).getValue(); + responses.add(typedResponse); + } + return responses; + } + + public static ExecuteUpgradeEventResponse getExecuteUpgradeEventFromLog(Log log) { + Contract.EventValuesWithLog eventValues = + staticExtractEventParametersWithLog(EXECUTEUPGRADE_EVENT, log); + ExecuteUpgradeEventResponse typedResponse = new ExecuteUpgradeEventResponse(); + typedResponse.log = log; + typedResponse.proposalId = (BigInteger) eventValues.getIndexedValues().get(0).getValue(); + typedResponse.proposalHash = (byte[]) eventValues.getIndexedValues().get(1).getValue(); + typedResponse.proposalSalt = (byte[]) eventValues.getNonIndexedValues().get(0).getValue(); + return typedResponse; + } + + public Flowable executeUpgradeEventFlowable(EthFilter filter) { + return web3j.ethLogFlowable(filter).map(log -> getExecuteUpgradeEventFromLog(log)); + } + + public Flowable executeUpgradeEventFlowable( + DefaultBlockParameter startBlock, DefaultBlockParameter endBlock) { + EthFilter filter = new EthFilter(startBlock, endBlock, getContractAddress()); + filter.addSingleTopic(EventEncoder.encode(EXECUTEUPGRADE_EVENT)); + return executeUpgradeEventFlowable(filter); + } + + public static List getFreezeEvents(TransactionReceipt transactionReceipt) { + List valueList = + staticExtractEventParametersWithLog(FREEZE_EVENT, transactionReceipt); + ArrayList responses = new ArrayList(valueList.size()); + for (Contract.EventValuesWithLog eventValues : valueList) { + FreezeEventResponse typedResponse = new FreezeEventResponse(); + typedResponse.log = eventValues.getLog(); + responses.add(typedResponse); + } + return responses; + } + + public static FreezeEventResponse getFreezeEventFromLog(Log log) { + Contract.EventValuesWithLog eventValues = + staticExtractEventParametersWithLog(FREEZE_EVENT, log); + FreezeEventResponse typedResponse = new FreezeEventResponse(); + typedResponse.log = log; + return typedResponse; + } + + public Flowable freezeEventFlowable(EthFilter filter) { + return web3j.ethLogFlowable(filter).map(log -> getFreezeEventFromLog(log)); + } + + public Flowable freezeEventFlowable( + DefaultBlockParameter startBlock, DefaultBlockParameter endBlock) { + EthFilter filter = new EthFilter(startBlock, endBlock, getContractAddress()); + filter.addSingleTopic(EventEncoder.encode(FREEZE_EVENT)); + return freezeEventFlowable(filter); + } + + public static List + getIsPorterAvailableStatusUpdateEvents(TransactionReceipt transactionReceipt) { + List valueList = + staticExtractEventParametersWithLog( + ISPORTERAVAILABLESTATUSUPDATE_EVENT, transactionReceipt); + ArrayList responses = + new ArrayList(valueList.size()); + for (Contract.EventValuesWithLog eventValues : valueList) { + IsPorterAvailableStatusUpdateEventResponse typedResponse = + new IsPorterAvailableStatusUpdateEventResponse(); + typedResponse.log = eventValues.getLog(); + typedResponse.isPorterAvailable = + (Boolean) eventValues.getNonIndexedValues().get(0).getValue(); + responses.add(typedResponse); + } + return responses; + } + + public static IsPorterAvailableStatusUpdateEventResponse + getIsPorterAvailableStatusUpdateEventFromLog(Log log) { + Contract.EventValuesWithLog eventValues = + staticExtractEventParametersWithLog(ISPORTERAVAILABLESTATUSUPDATE_EVENT, log); + IsPorterAvailableStatusUpdateEventResponse typedResponse = + new IsPorterAvailableStatusUpdateEventResponse(); + typedResponse.log = log; + typedResponse.isPorterAvailable = (Boolean) eventValues.getNonIndexedValues().get(0).getValue(); + return typedResponse; + } + + public Flowable + isPorterAvailableStatusUpdateEventFlowable(EthFilter filter) { + return web3j + .ethLogFlowable(filter) + .map(log -> getIsPorterAvailableStatusUpdateEventFromLog(log)); + } + + public Flowable + isPorterAvailableStatusUpdateEventFlowable( + DefaultBlockParameter startBlock, DefaultBlockParameter endBlock) { + EthFilter filter = new EthFilter(startBlock, endBlock, getContractAddress()); + filter.addSingleTopic(EventEncoder.encode(ISPORTERAVAILABLESTATUSUPDATE_EVENT)); + return isPorterAvailableStatusUpdateEventFlowable(filter); + } + + public static List getNewGovernorEvents( + TransactionReceipt transactionReceipt) { + List valueList = + staticExtractEventParametersWithLog(NEWGOVERNOR_EVENT, transactionReceipt); + ArrayList responses = + new ArrayList(valueList.size()); + for (Contract.EventValuesWithLog eventValues : valueList) { + NewGovernorEventResponse typedResponse = new NewGovernorEventResponse(); + typedResponse.log = eventValues.getLog(); + typedResponse.oldGovernor = (String) eventValues.getIndexedValues().get(0).getValue(); + typedResponse.newGovernor = (String) eventValues.getIndexedValues().get(1).getValue(); + responses.add(typedResponse); + } + return responses; + } + + public static NewGovernorEventResponse getNewGovernorEventFromLog(Log log) { + Contract.EventValuesWithLog eventValues = + staticExtractEventParametersWithLog(NEWGOVERNOR_EVENT, log); + NewGovernorEventResponse typedResponse = new NewGovernorEventResponse(); + typedResponse.log = log; + typedResponse.oldGovernor = (String) eventValues.getIndexedValues().get(0).getValue(); + typedResponse.newGovernor = (String) eventValues.getIndexedValues().get(1).getValue(); + return typedResponse; + } + + public Flowable newGovernorEventFlowable(EthFilter filter) { + return web3j.ethLogFlowable(filter).map(log -> getNewGovernorEventFromLog(log)); + } + + public Flowable newGovernorEventFlowable( + DefaultBlockParameter startBlock, DefaultBlockParameter endBlock) { + EthFilter filter = new EthFilter(startBlock, endBlock, getContractAddress()); + filter.addSingleTopic(EventEncoder.encode(NEWGOVERNOR_EVENT)); + return newGovernorEventFlowable(filter); + } + + public static List getNewL2BootloaderBytecodeHashEvents( + TransactionReceipt transactionReceipt) { + List valueList = + staticExtractEventParametersWithLog(NEWL2BOOTLOADERBYTECODEHASH_EVENT, transactionReceipt); + ArrayList responses = + new ArrayList(valueList.size()); + for (Contract.EventValuesWithLog eventValues : valueList) { + NewL2BootloaderBytecodeHashEventResponse typedResponse = + new NewL2BootloaderBytecodeHashEventResponse(); + typedResponse.log = eventValues.getLog(); + typedResponse.previousBytecodeHash = + (byte[]) eventValues.getIndexedValues().get(0).getValue(); + typedResponse.newBytecodeHash = (byte[]) eventValues.getIndexedValues().get(1).getValue(); + responses.add(typedResponse); + } + return responses; + } + + public static NewL2BootloaderBytecodeHashEventResponse getNewL2BootloaderBytecodeHashEventFromLog( + Log log) { + Contract.EventValuesWithLog eventValues = + staticExtractEventParametersWithLog(NEWL2BOOTLOADERBYTECODEHASH_EVENT, log); + NewL2BootloaderBytecodeHashEventResponse typedResponse = + new NewL2BootloaderBytecodeHashEventResponse(); + typedResponse.log = log; + typedResponse.previousBytecodeHash = (byte[]) eventValues.getIndexedValues().get(0).getValue(); + typedResponse.newBytecodeHash = (byte[]) eventValues.getIndexedValues().get(1).getValue(); + return typedResponse; + } + + public Flowable + newL2BootloaderBytecodeHashEventFlowable(EthFilter filter) { + return web3j.ethLogFlowable(filter).map(log -> getNewL2BootloaderBytecodeHashEventFromLog(log)); + } + + public Flowable + newL2BootloaderBytecodeHashEventFlowable( + DefaultBlockParameter startBlock, DefaultBlockParameter endBlock) { + EthFilter filter = new EthFilter(startBlock, endBlock, getContractAddress()); + filter.addSingleTopic(EventEncoder.encode(NEWL2BOOTLOADERBYTECODEHASH_EVENT)); + return newL2BootloaderBytecodeHashEventFlowable(filter); + } + + public static List + getNewL2DefaultAccountBytecodeHashEvents(TransactionReceipt transactionReceipt) { + List valueList = + staticExtractEventParametersWithLog( + NEWL2DEFAULTACCOUNTBYTECODEHASH_EVENT, transactionReceipt); + ArrayList responses = + new ArrayList(valueList.size()); + for (Contract.EventValuesWithLog eventValues : valueList) { + NewL2DefaultAccountBytecodeHashEventResponse typedResponse = + new NewL2DefaultAccountBytecodeHashEventResponse(); + typedResponse.log = eventValues.getLog(); + typedResponse.previousBytecodeHash = + (byte[]) eventValues.getIndexedValues().get(0).getValue(); + typedResponse.newBytecodeHash = (byte[]) eventValues.getIndexedValues().get(1).getValue(); + responses.add(typedResponse); + } + return responses; + } + + public static NewL2DefaultAccountBytecodeHashEventResponse + getNewL2DefaultAccountBytecodeHashEventFromLog(Log log) { + Contract.EventValuesWithLog eventValues = + staticExtractEventParametersWithLog(NEWL2DEFAULTACCOUNTBYTECODEHASH_EVENT, log); + NewL2DefaultAccountBytecodeHashEventResponse typedResponse = + new NewL2DefaultAccountBytecodeHashEventResponse(); + typedResponse.log = log; + typedResponse.previousBytecodeHash = (byte[]) eventValues.getIndexedValues().get(0).getValue(); + typedResponse.newBytecodeHash = (byte[]) eventValues.getIndexedValues().get(1).getValue(); + return typedResponse; + } + + public Flowable + newL2DefaultAccountBytecodeHashEventFlowable(EthFilter filter) { + return web3j + .ethLogFlowable(filter) + .map(log -> getNewL2DefaultAccountBytecodeHashEventFromLog(log)); + } + + public Flowable + newL2DefaultAccountBytecodeHashEventFlowable( + DefaultBlockParameter startBlock, DefaultBlockParameter endBlock) { + EthFilter filter = new EthFilter(startBlock, endBlock, getContractAddress()); + filter.addSingleTopic(EventEncoder.encode(NEWL2DEFAULTACCOUNTBYTECODEHASH_EVENT)); + return newL2DefaultAccountBytecodeHashEventFlowable(filter); + } + + public static List getNewPendingGovernorEvents( + TransactionReceipt transactionReceipt) { + List valueList = + staticExtractEventParametersWithLog(NEWPENDINGGOVERNOR_EVENT, transactionReceipt); + ArrayList responses = + new ArrayList(valueList.size()); + for (Contract.EventValuesWithLog eventValues : valueList) { + NewPendingGovernorEventResponse typedResponse = new NewPendingGovernorEventResponse(); + typedResponse.log = eventValues.getLog(); + typedResponse.oldPendingGovernor = (String) eventValues.getIndexedValues().get(0).getValue(); + typedResponse.newPendingGovernor = (String) eventValues.getIndexedValues().get(1).getValue(); + responses.add(typedResponse); + } + return responses; + } + + public static NewPendingGovernorEventResponse getNewPendingGovernorEventFromLog(Log log) { + Contract.EventValuesWithLog eventValues = + staticExtractEventParametersWithLog(NEWPENDINGGOVERNOR_EVENT, log); + NewPendingGovernorEventResponse typedResponse = new NewPendingGovernorEventResponse(); + typedResponse.log = log; + typedResponse.oldPendingGovernor = (String) eventValues.getIndexedValues().get(0).getValue(); + typedResponse.newPendingGovernor = (String) eventValues.getIndexedValues().get(1).getValue(); + return typedResponse; + } + + public Flowable newPendingGovernorEventFlowable( + EthFilter filter) { + return web3j.ethLogFlowable(filter).map(log -> getNewPendingGovernorEventFromLog(log)); + } + + public Flowable newPendingGovernorEventFlowable( + DefaultBlockParameter startBlock, DefaultBlockParameter endBlock) { + EthFilter filter = new EthFilter(startBlock, endBlock, getContractAddress()); + filter.addSingleTopic(EventEncoder.encode(NEWPENDINGGOVERNOR_EVENT)); + return newPendingGovernorEventFlowable(filter); + } + + public static List getNewPriorityRequestEvents( + TransactionReceipt transactionReceipt) { + List valueList = + staticExtractEventParametersWithLog(NEWPRIORITYREQUEST_EVENT, transactionReceipt); + ArrayList responses = + new ArrayList(valueList.size()); + for (Contract.EventValuesWithLog eventValues : valueList) { + NewPriorityRequestEventResponse typedResponse = new NewPriorityRequestEventResponse(); + typedResponse.log = eventValues.getLog(); + typedResponse.txId = (BigInteger) eventValues.getNonIndexedValues().get(0).getValue(); + typedResponse.txHash = (byte[]) eventValues.getNonIndexedValues().get(1).getValue(); + typedResponse.expirationTimestamp = + (BigInteger) eventValues.getNonIndexedValues().get(2).getValue(); + typedResponse.transaction = (L2CanonicalTransaction) eventValues.getNonIndexedValues().get(3); + typedResponse.factoryDeps = + (List) ((Array) eventValues.getNonIndexedValues().get(4)).getNativeValueCopy(); + responses.add(typedResponse); + } + return responses; + } + + public static NewPriorityRequestEventResponse getNewPriorityRequestEventFromLog(Log log) { + Contract.EventValuesWithLog eventValues = + staticExtractEventParametersWithLog(NEWPRIORITYREQUEST_EVENT, log); + NewPriorityRequestEventResponse typedResponse = new NewPriorityRequestEventResponse(); + typedResponse.log = log; + typedResponse.txId = (BigInteger) eventValues.getNonIndexedValues().get(0).getValue(); + typedResponse.txHash = (byte[]) eventValues.getNonIndexedValues().get(1).getValue(); + typedResponse.expirationTimestamp = + (BigInteger) eventValues.getNonIndexedValues().get(2).getValue(); + typedResponse.transaction = (L2CanonicalTransaction) eventValues.getNonIndexedValues().get(3); + typedResponse.factoryDeps = + (List) ((Array) eventValues.getNonIndexedValues().get(4)).getNativeValueCopy(); + return typedResponse; + } + + public Flowable newPriorityRequestEventFlowable( + EthFilter filter) { + return web3j.ethLogFlowable(filter).map(log -> getNewPriorityRequestEventFromLog(log)); + } + + public Flowable newPriorityRequestEventFlowable( + DefaultBlockParameter startBlock, DefaultBlockParameter endBlock) { + EthFilter filter = new EthFilter(startBlock, endBlock, getContractAddress()); + filter.addSingleTopic(EventEncoder.encode(NEWPRIORITYREQUEST_EVENT)); + return newPriorityRequestEventFlowable(filter); + } + + public static List getNewPriorityTxMaxGasLimitEvents( + TransactionReceipt transactionReceipt) { + List valueList = + staticExtractEventParametersWithLog(NEWPRIORITYTXMAXGASLIMIT_EVENT, transactionReceipt); + ArrayList responses = + new ArrayList(valueList.size()); + for (Contract.EventValuesWithLog eventValues : valueList) { + NewPriorityTxMaxGasLimitEventResponse typedResponse = + new NewPriorityTxMaxGasLimitEventResponse(); + typedResponse.log = eventValues.getLog(); + typedResponse.oldPriorityTxMaxGasLimit = + (BigInteger) eventValues.getNonIndexedValues().get(0).getValue(); + typedResponse.newPriorityTxMaxGasLimit = + (BigInteger) eventValues.getNonIndexedValues().get(1).getValue(); + responses.add(typedResponse); + } + return responses; + } + + public static NewPriorityTxMaxGasLimitEventResponse getNewPriorityTxMaxGasLimitEventFromLog( + Log log) { + Contract.EventValuesWithLog eventValues = + staticExtractEventParametersWithLog(NEWPRIORITYTXMAXGASLIMIT_EVENT, log); + NewPriorityTxMaxGasLimitEventResponse typedResponse = + new NewPriorityTxMaxGasLimitEventResponse(); + typedResponse.log = log; + typedResponse.oldPriorityTxMaxGasLimit = + (BigInteger) eventValues.getNonIndexedValues().get(0).getValue(); + typedResponse.newPriorityTxMaxGasLimit = + (BigInteger) eventValues.getNonIndexedValues().get(1).getValue(); + return typedResponse; + } + + public Flowable newPriorityTxMaxGasLimitEventFlowable( + EthFilter filter) { + return web3j.ethLogFlowable(filter).map(log -> getNewPriorityTxMaxGasLimitEventFromLog(log)); + } + + public Flowable newPriorityTxMaxGasLimitEventFlowable( + DefaultBlockParameter startBlock, DefaultBlockParameter endBlock) { + EthFilter filter = new EthFilter(startBlock, endBlock, getContractAddress()); + filter.addSingleTopic(EventEncoder.encode(NEWPRIORITYTXMAXGASLIMIT_EVENT)); + return newPriorityTxMaxGasLimitEventFlowable(filter); + } + + public static List getNewVerifierEvents( + TransactionReceipt transactionReceipt) { + List valueList = + staticExtractEventParametersWithLog(NEWVERIFIER_EVENT, transactionReceipt); + ArrayList responses = + new ArrayList(valueList.size()); + for (Contract.EventValuesWithLog eventValues : valueList) { + NewVerifierEventResponse typedResponse = new NewVerifierEventResponse(); + typedResponse.log = eventValues.getLog(); + typedResponse.oldVerifier = (String) eventValues.getIndexedValues().get(0).getValue(); + typedResponse.newVerifier = (String) eventValues.getIndexedValues().get(1).getValue(); + responses.add(typedResponse); + } + return responses; + } + + public static NewVerifierEventResponse getNewVerifierEventFromLog(Log log) { + Contract.EventValuesWithLog eventValues = + staticExtractEventParametersWithLog(NEWVERIFIER_EVENT, log); + NewVerifierEventResponse typedResponse = new NewVerifierEventResponse(); + typedResponse.log = log; + typedResponse.oldVerifier = (String) eventValues.getIndexedValues().get(0).getValue(); + typedResponse.newVerifier = (String) eventValues.getIndexedValues().get(1).getValue(); + return typedResponse; + } + + public Flowable newVerifierEventFlowable(EthFilter filter) { + return web3j.ethLogFlowable(filter).map(log -> getNewVerifierEventFromLog(log)); + } + + public Flowable newVerifierEventFlowable( + DefaultBlockParameter startBlock, DefaultBlockParameter endBlock) { + EthFilter filter = new EthFilter(startBlock, endBlock, getContractAddress()); + filter.addSingleTopic(EventEncoder.encode(NEWVERIFIER_EVENT)); + return newVerifierEventFlowable(filter); + } + + public static List getNewVerifierParamsEvents( + TransactionReceipt transactionReceipt) { + List valueList = + staticExtractEventParametersWithLog(NEWVERIFIERPARAMS_EVENT, transactionReceipt); + ArrayList responses = + new ArrayList(valueList.size()); + for (Contract.EventValuesWithLog eventValues : valueList) { + NewVerifierParamsEventResponse typedResponse = new NewVerifierParamsEventResponse(); + typedResponse.log = eventValues.getLog(); + typedResponse.oldVerifierParams = (VerifierParams) eventValues.getNonIndexedValues().get(0); + typedResponse.newVerifierParams = (VerifierParams) eventValues.getNonIndexedValues().get(1); + responses.add(typedResponse); + } + return responses; + } + + public static NewVerifierParamsEventResponse getNewVerifierParamsEventFromLog(Log log) { + Contract.EventValuesWithLog eventValues = + staticExtractEventParametersWithLog(NEWVERIFIERPARAMS_EVENT, log); + NewVerifierParamsEventResponse typedResponse = new NewVerifierParamsEventResponse(); + typedResponse.log = log; + typedResponse.oldVerifierParams = (VerifierParams) eventValues.getNonIndexedValues().get(0); + typedResponse.newVerifierParams = (VerifierParams) eventValues.getNonIndexedValues().get(1); + return typedResponse; + } + + public Flowable newVerifierParamsEventFlowable(EthFilter filter) { + return web3j.ethLogFlowable(filter).map(log -> getNewVerifierParamsEventFromLog(log)); + } + + public Flowable newVerifierParamsEventFlowable( + DefaultBlockParameter startBlock, DefaultBlockParameter endBlock) { + EthFilter filter = new EthFilter(startBlock, endBlock, getContractAddress()); + filter.addSingleTopic(EventEncoder.encode(NEWVERIFIERPARAMS_EVENT)); + return newVerifierParamsEventFlowable(filter); + } + + public static List getProposeShadowUpgradeEvents( + TransactionReceipt transactionReceipt) { + List valueList = + staticExtractEventParametersWithLog(PROPOSESHADOWUPGRADE_EVENT, transactionReceipt); + ArrayList responses = + new ArrayList(valueList.size()); + for (Contract.EventValuesWithLog eventValues : valueList) { + ProposeShadowUpgradeEventResponse typedResponse = new ProposeShadowUpgradeEventResponse(); + typedResponse.log = eventValues.getLog(); + typedResponse.proposalId = (BigInteger) eventValues.getIndexedValues().get(0).getValue(); + typedResponse.proposalHash = (byte[]) eventValues.getIndexedValues().get(1).getValue(); + responses.add(typedResponse); + } + return responses; + } + + public static ProposeShadowUpgradeEventResponse getProposeShadowUpgradeEventFromLog(Log log) { + Contract.EventValuesWithLog eventValues = + staticExtractEventParametersWithLog(PROPOSESHADOWUPGRADE_EVENT, log); + ProposeShadowUpgradeEventResponse typedResponse = new ProposeShadowUpgradeEventResponse(); + typedResponse.log = log; + typedResponse.proposalId = (BigInteger) eventValues.getIndexedValues().get(0).getValue(); + typedResponse.proposalHash = (byte[]) eventValues.getIndexedValues().get(1).getValue(); + return typedResponse; + } + + public Flowable proposeShadowUpgradeEventFlowable( + EthFilter filter) { + return web3j.ethLogFlowable(filter).map(log -> getProposeShadowUpgradeEventFromLog(log)); + } + + public Flowable proposeShadowUpgradeEventFlowable( + DefaultBlockParameter startBlock, DefaultBlockParameter endBlock) { + EthFilter filter = new EthFilter(startBlock, endBlock, getContractAddress()); + filter.addSingleTopic(EventEncoder.encode(PROPOSESHADOWUPGRADE_EVENT)); + return proposeShadowUpgradeEventFlowable(filter); + } + + public static List getProposeTransparentUpgradeEvents( + TransactionReceipt transactionReceipt) { + List valueList = + staticExtractEventParametersWithLog(PROPOSETRANSPARENTUPGRADE_EVENT, transactionReceipt); + ArrayList responses = + new ArrayList(valueList.size()); + for (Contract.EventValuesWithLog eventValues : valueList) { + ProposeTransparentUpgradeEventResponse typedResponse = + new ProposeTransparentUpgradeEventResponse(); + typedResponse.log = eventValues.getLog(); + typedResponse.proposalId = (BigInteger) eventValues.getIndexedValues().get(0).getValue(); + typedResponse.diamondCut = (DiamondCutData) eventValues.getNonIndexedValues().get(0); + typedResponse.proposalSalt = (byte[]) eventValues.getNonIndexedValues().get(1).getValue(); + responses.add(typedResponse); + } + return responses; + } + + public static ProposeTransparentUpgradeEventResponse getProposeTransparentUpgradeEventFromLog( + Log log) { + Contract.EventValuesWithLog eventValues = + staticExtractEventParametersWithLog(PROPOSETRANSPARENTUPGRADE_EVENT, log); + ProposeTransparentUpgradeEventResponse typedResponse = + new ProposeTransparentUpgradeEventResponse(); + typedResponse.log = log; + typedResponse.proposalId = (BigInteger) eventValues.getIndexedValues().get(0).getValue(); + typedResponse.diamondCut = (DiamondCutData) eventValues.getNonIndexedValues().get(0); + typedResponse.proposalSalt = (byte[]) eventValues.getNonIndexedValues().get(1).getValue(); + return typedResponse; + } + + public Flowable proposeTransparentUpgradeEventFlowable( + EthFilter filter) { + return web3j.ethLogFlowable(filter).map(log -> getProposeTransparentUpgradeEventFromLog(log)); + } + + public Flowable proposeTransparentUpgradeEventFlowable( + DefaultBlockParameter startBlock, DefaultBlockParameter endBlock) { + EthFilter filter = new EthFilter(startBlock, endBlock, getContractAddress()); + filter.addSingleTopic(EventEncoder.encode(PROPOSETRANSPARENTUPGRADE_EVENT)); + return proposeTransparentUpgradeEventFlowable(filter); + } + + public static List + getSecurityCouncilUpgradeApproveEvents(TransactionReceipt transactionReceipt) { + List valueList = + staticExtractEventParametersWithLog( + SECURITYCOUNCILUPGRADEAPPROVE_EVENT, transactionReceipt); + ArrayList responses = + new ArrayList(valueList.size()); + for (Contract.EventValuesWithLog eventValues : valueList) { + SecurityCouncilUpgradeApproveEventResponse typedResponse = + new SecurityCouncilUpgradeApproveEventResponse(); + typedResponse.log = eventValues.getLog(); + typedResponse.proposalId = (BigInteger) eventValues.getIndexedValues().get(0).getValue(); + typedResponse.proposalHash = (byte[]) eventValues.getIndexedValues().get(1).getValue(); + responses.add(typedResponse); + } + return responses; + } + + public static SecurityCouncilUpgradeApproveEventResponse + getSecurityCouncilUpgradeApproveEventFromLog(Log log) { + Contract.EventValuesWithLog eventValues = + staticExtractEventParametersWithLog(SECURITYCOUNCILUPGRADEAPPROVE_EVENT, log); + SecurityCouncilUpgradeApproveEventResponse typedResponse = + new SecurityCouncilUpgradeApproveEventResponse(); + typedResponse.log = log; + typedResponse.proposalId = (BigInteger) eventValues.getIndexedValues().get(0).getValue(); + typedResponse.proposalHash = (byte[]) eventValues.getIndexedValues().get(1).getValue(); + return typedResponse; + } + + public Flowable + securityCouncilUpgradeApproveEventFlowable(EthFilter filter) { + return web3j + .ethLogFlowable(filter) + .map(log -> getSecurityCouncilUpgradeApproveEventFromLog(log)); + } + + public Flowable + securityCouncilUpgradeApproveEventFlowable( + DefaultBlockParameter startBlock, DefaultBlockParameter endBlock) { + EthFilter filter = new EthFilter(startBlock, endBlock, getContractAddress()); + filter.addSingleTopic(EventEncoder.encode(SECURITYCOUNCILUPGRADEAPPROVE_EVENT)); + return securityCouncilUpgradeApproveEventFlowable(filter); + } + + public static List getUnfreezeEvents( + TransactionReceipt transactionReceipt) { + List valueList = + staticExtractEventParametersWithLog(UNFREEZE_EVENT, transactionReceipt); + ArrayList responses = + new ArrayList(valueList.size()); + for (Contract.EventValuesWithLog eventValues : valueList) { + UnfreezeEventResponse typedResponse = new UnfreezeEventResponse(); + typedResponse.log = eventValues.getLog(); + responses.add(typedResponse); + } + return responses; + } + + public static UnfreezeEventResponse getUnfreezeEventFromLog(Log log) { + Contract.EventValuesWithLog eventValues = + staticExtractEventParametersWithLog(UNFREEZE_EVENT, log); + UnfreezeEventResponse typedResponse = new UnfreezeEventResponse(); + typedResponse.log = log; + return typedResponse; + } + + public Flowable unfreezeEventFlowable(EthFilter filter) { + return web3j.ethLogFlowable(filter).map(log -> getUnfreezeEventFromLog(log)); + } + + public Flowable unfreezeEventFlowable( + DefaultBlockParameter startBlock, DefaultBlockParameter endBlock) { + EthFilter filter = new EthFilter(startBlock, endBlock, getContractAddress()); + filter.addSingleTopic(EventEncoder.encode(UNFREEZE_EVENT)); + return unfreezeEventFlowable(filter); + } + + public static List getValidatorStatusUpdateEvents( + TransactionReceipt transactionReceipt) { + List valueList = + staticExtractEventParametersWithLog(VALIDATORSTATUSUPDATE_EVENT, transactionReceipt); + ArrayList responses = + new ArrayList(valueList.size()); + for (Contract.EventValuesWithLog eventValues : valueList) { + ValidatorStatusUpdateEventResponse typedResponse = new ValidatorStatusUpdateEventResponse(); + typedResponse.log = eventValues.getLog(); + typedResponse.validatorAddress = (String) eventValues.getIndexedValues().get(0).getValue(); + typedResponse.isActive = (Boolean) eventValues.getNonIndexedValues().get(0).getValue(); + responses.add(typedResponse); + } + return responses; + } + + public static ValidatorStatusUpdateEventResponse getValidatorStatusUpdateEventFromLog(Log log) { + Contract.EventValuesWithLog eventValues = + staticExtractEventParametersWithLog(VALIDATORSTATUSUPDATE_EVENT, log); + ValidatorStatusUpdateEventResponse typedResponse = new ValidatorStatusUpdateEventResponse(); + typedResponse.log = log; + typedResponse.validatorAddress = (String) eventValues.getIndexedValues().get(0).getValue(); + typedResponse.isActive = (Boolean) eventValues.getNonIndexedValues().get(0).getValue(); + return typedResponse; + } + + public Flowable validatorStatusUpdateEventFlowable( + EthFilter filter) { + return web3j.ethLogFlowable(filter).map(log -> getValidatorStatusUpdateEventFromLog(log)); + } + + public Flowable validatorStatusUpdateEventFlowable( + DefaultBlockParameter startBlock, DefaultBlockParameter endBlock) { + EthFilter filter = new EthFilter(startBlock, endBlock, getContractAddress()); + filter.addSingleTopic(EventEncoder.encode(VALIDATORSTATUSUPDATE_EVENT)); + return validatorStatusUpdateEventFlowable(filter); + } + + public RemoteFunctionCall acceptGovernor() { + final Function function = + new Function( + FUNC_ACCEPTGOVERNOR, Arrays.asList(), Collections.>emptyList()); + return executeRemoteCallTransaction(function); + } + + public RemoteFunctionCall cancelUpgradeProposal(byte[] _proposedUpgradeHash) { + final Function function = + new Function( + FUNC_CANCELUPGRADEPROPOSAL, + Arrays.asList( + new org.web3j.abi.datatypes.generated.Bytes32(_proposedUpgradeHash)), + Collections.>emptyList()); + return executeRemoteCallTransaction(function); + } + + public RemoteFunctionCall commitBlocks( + StoredBlockInfo _lastCommittedBlockData, List _newBlocksData) { + final Function function = + new Function( + FUNC_COMMITBLOCKS, + Arrays.asList( + _lastCommittedBlockData, + new org.web3j.abi.datatypes.DynamicArray( + CommitBlockInfo.class, _newBlocksData)), + Collections.>emptyList()); + return executeRemoteCallTransaction(function); + } + + public RemoteFunctionCall executeBlocks(List _blocksData) { + final Function function = + new Function( + FUNC_EXECUTEBLOCKS, + Arrays.asList( + new org.web3j.abi.datatypes.DynamicArray( + StoredBlockInfo.class, _blocksData)), + Collections.>emptyList()); + return executeRemoteCallTransaction(function); + } + + public RemoteFunctionCall executeUpgrade( + DiamondCutData _diamondCut, byte[] _proposalSalt) { + final Function function = + new Function( + FUNC_EXECUTEUPGRADE, + Arrays.asList( + _diamondCut, new org.web3j.abi.datatypes.generated.Bytes32(_proposalSalt)), + Collections.>emptyList()); + return executeRemoteCallTransaction(function); + } + + public RemoteFunctionCall facetAddress(byte[] _selector) { + final Function function = + new Function( + FUNC_FACETADDRESS, + Arrays.asList(new org.web3j.abi.datatypes.generated.Bytes4(_selector)), + Arrays.>asList(new TypeReference
() {})); + return executeRemoteCallSingleValueReturn(function, String.class); + } + + public RemoteFunctionCall facetAddresses() { + final Function function = + new Function( + FUNC_FACETADDRESSES, + Arrays.asList(), + Arrays.>asList(new TypeReference>() {})); + return new RemoteFunctionCall( + function, + new Callable() { + @Override + @SuppressWarnings("unchecked") + public List call() throws Exception { + List result = (List) executeCallSingleValueReturn(function, List.class); + return convertToNative(result); + } + }); + } + + public RemoteFunctionCall facetFunctionSelectors(String _facet) { + final Function function = + new Function( + FUNC_FACETFUNCTIONSELECTORS, + Arrays.asList(new org.web3j.abi.datatypes.Address(_facet)), + Arrays.>asList(new TypeReference>() {})); + return new RemoteFunctionCall( + function, + new Callable() { + @Override + @SuppressWarnings("unchecked") + public List call() throws Exception { + List result = (List) executeCallSingleValueReturn(function, List.class); + return convertToNative(result); + } + }); + } + + public RemoteFunctionCall facets() { + final Function function = + new Function( + FUNC_FACETS, + Arrays.asList(), + Arrays.>asList(new TypeReference>() {})); + return new RemoteFunctionCall( + function, + new Callable() { + @Override + @SuppressWarnings("unchecked") + public List call() throws Exception { + List result = (List) executeCallSingleValueReturn(function, List.class); + return convertToNative(result); + } + }); + } + + public RemoteFunctionCall finalizeEthWithdrawal( + BigInteger _l2BlockNumber, + BigInteger _l2MessageIndex, + BigInteger _l2TxNumberInBlock, + byte[] _message, + List _merkleProof) { + final Function function = + new Function( + FUNC_FINALIZEETHWITHDRAWAL, + Arrays.asList( + new org.web3j.abi.datatypes.generated.Uint256(_l2BlockNumber), + new org.web3j.abi.datatypes.generated.Uint256(_l2MessageIndex), + new org.web3j.abi.datatypes.generated.Uint16(_l2TxNumberInBlock), + new org.web3j.abi.datatypes.DynamicBytes(_message), + new org.web3j.abi.datatypes.DynamicArray( + org.web3j.abi.datatypes.generated.Bytes32.class, + org.web3j.abi.Utils.typeMap( + _merkleProof, org.web3j.abi.datatypes.generated.Bytes32.class))), + Collections.>emptyList()); + return executeRemoteCallTransaction(function); + } + + public RemoteFunctionCall freezeDiamond() { + final Function function = + new Function( + FUNC_FREEZEDIAMOND, Arrays.asList(), Collections.>emptyList()); + return executeRemoteCallTransaction(function); + } + + public RemoteFunctionCall getCurrentProposalId() { + final Function function = + new Function( + FUNC_GETCURRENTPROPOSALID, + Arrays.asList(), + Arrays.>asList(new TypeReference() {})); + return executeRemoteCallSingleValueReturn(function, BigInteger.class); + } + + public RemoteFunctionCall getFirstUnprocessedPriorityTx() { + final Function function = + new Function( + FUNC_GETFIRSTUNPROCESSEDPRIORITYTX, + Arrays.asList(), + Arrays.>asList(new TypeReference() {})); + return executeRemoteCallSingleValueReturn(function, BigInteger.class); + } + + public RemoteFunctionCall getGovernor() { + final Function function = + new Function( + FUNC_GETGOVERNOR, + Arrays.asList(), + Arrays.>asList(new TypeReference
() {})); + return executeRemoteCallSingleValueReturn(function, String.class); + } + + public RemoteFunctionCall getL2BootloaderBytecodeHash() { + final Function function = + new Function( + FUNC_GETL2BOOTLOADERBYTECODEHASH, + Arrays.asList(), + Arrays.>asList(new TypeReference() {})); + return executeRemoteCallSingleValueReturn(function, byte[].class); + } + + public RemoteFunctionCall getL2DefaultAccountBytecodeHash() { + final Function function = + new Function( + FUNC_GETL2DEFAULTACCOUNTBYTECODEHASH, + Arrays.asList(), + Arrays.>asList(new TypeReference() {})); + return executeRemoteCallSingleValueReturn(function, byte[].class); + } + + public RemoteFunctionCall getPendingGovernor() { + final Function function = + new Function( + FUNC_GETPENDINGGOVERNOR, + Arrays.asList(), + Arrays.>asList(new TypeReference
() {})); + return executeRemoteCallSingleValueReturn(function, String.class); + } + + public RemoteFunctionCall getPriorityQueueSize() { + final Function function = + new Function( + FUNC_GETPRIORITYQUEUESIZE, + Arrays.asList(), + Arrays.>asList(new TypeReference() {})); + return executeRemoteCallSingleValueReturn(function, BigInteger.class); + } + + public RemoteFunctionCall getProposedUpgradeHash() { + final Function function = + new Function( + FUNC_GETPROPOSEDUPGRADEHASH, + Arrays.asList(), + Arrays.>asList(new TypeReference() {})); + return executeRemoteCallSingleValueReturn(function, byte[].class); + } + + public RemoteFunctionCall getProposedUpgradeTimestamp() { + final Function function = + new Function( + FUNC_GETPROPOSEDUPGRADETIMESTAMP, + Arrays.asList(), + Arrays.>asList(new TypeReference() {})); + return executeRemoteCallSingleValueReturn(function, BigInteger.class); + } + + public RemoteFunctionCall getSecurityCouncil() { + final Function function = + new Function( + FUNC_GETSECURITYCOUNCIL, + Arrays.asList(), + Arrays.>asList(new TypeReference
() {})); + return executeRemoteCallSingleValueReturn(function, String.class); + } + + public RemoteFunctionCall getTotalBlocksCommitted() { + final Function function = + new Function( + FUNC_GETTOTALBLOCKSCOMMITTED, + Arrays.asList(), + Arrays.>asList(new TypeReference() {})); + return executeRemoteCallSingleValueReturn(function, BigInteger.class); + } + + public RemoteFunctionCall getTotalBlocksExecuted() { + final Function function = + new Function( + FUNC_GETTOTALBLOCKSEXECUTED, + Arrays.asList(), + Arrays.>asList(new TypeReference() {})); + return executeRemoteCallSingleValueReturn(function, BigInteger.class); + } + + public RemoteFunctionCall getTotalBlocksVerified() { + final Function function = + new Function( + FUNC_GETTOTALBLOCKSVERIFIED, + Arrays.asList(), + Arrays.>asList(new TypeReference() {})); + return executeRemoteCallSingleValueReturn(function, BigInteger.class); + } + + public RemoteFunctionCall getTotalPriorityTxs() { + final Function function = + new Function( + FUNC_GETTOTALPRIORITYTXS, + Arrays.asList(), + Arrays.>asList(new TypeReference() {})); + return executeRemoteCallSingleValueReturn(function, BigInteger.class); + } + + public RemoteFunctionCall getUpgradeProposalState() { + final Function function = + new Function( + FUNC_GETUPGRADEPROPOSALSTATE, + Arrays.asList(), + Arrays.>asList(new TypeReference() {})); + return executeRemoteCallSingleValueReturn(function, BigInteger.class); + } + + public RemoteFunctionCall getVerifier() { + final Function function = + new Function( + FUNC_GETVERIFIER, + Arrays.asList(), + Arrays.>asList(new TypeReference
() {})); + return executeRemoteCallSingleValueReturn(function, String.class); + } + + public RemoteFunctionCall getVerifierParams() { + final Function function = + new Function( + FUNC_GETVERIFIERPARAMS, + Arrays.asList(), + Arrays.>asList(new TypeReference() {})); + return executeRemoteCallSingleValueReturn(function, VerifierParams.class); + } + + public RemoteFunctionCall getpriorityTxMaxGasLimit() { + final Function function = + new Function( + FUNC_GETPRIORITYTXMAXGASLIMIT, + Arrays.asList(), + Arrays.>asList(new TypeReference() {})); + return executeRemoteCallSingleValueReturn(function, BigInteger.class); + } + + public RemoteFunctionCall isApprovedBySecurityCouncil() { + final Function function = + new Function( + FUNC_ISAPPROVEDBYSECURITYCOUNCIL, + Arrays.asList(), Arrays.>asList(new TypeReference() {})); - ; - - public static final Event NEWGOVERNOR_EVENT = new Event("NewGovernor", - Arrays.>asList(new TypeReference
(true) {}, new TypeReference
(true) {})); - ; - - public static final Event NEWL2BOOTLOADERBYTECODEHASH_EVENT = new Event("NewL2BootloaderBytecodeHash", - Arrays.>asList(new TypeReference(true) {}, new TypeReference(true) {})); - ; - - public static final Event NEWL2DEFAULTACCOUNTBYTECODEHASH_EVENT = new Event("NewL2DefaultAccountBytecodeHash", - Arrays.>asList(new TypeReference(true) {}, new TypeReference(true) {})); - ; - - public static final Event NEWPENDINGGOVERNOR_EVENT = new Event("NewPendingGovernor", - Arrays.>asList(new TypeReference
(true) {}, new TypeReference
(true) {})); - ; - - public static final Event NEWPRIORITYREQUEST_EVENT = new Event("NewPriorityRequest", - Arrays.>asList(new TypeReference() {}, new TypeReference() {}, new TypeReference() {}, new TypeReference() {}, new TypeReference>() {})); - ; - - public static final Event NEWPRIORITYTXMAXGASLIMIT_EVENT = new Event("NewPriorityTxMaxGasLimit", - Arrays.>asList(new TypeReference() {}, new TypeReference() {})); - ; - - public static final Event NEWVERIFIER_EVENT = new Event("NewVerifier", - Arrays.>asList(new TypeReference
(true) {}, new TypeReference
(true) {})); - ; - - public static final Event NEWVERIFIERPARAMS_EVENT = new Event("NewVerifierParams", - Arrays.>asList(new TypeReference() {}, new TypeReference() {})); - ; - - public static final Event PROPOSESHADOWUPGRADE_EVENT = new Event("ProposeShadowUpgrade", - Arrays.>asList(new TypeReference(true) {}, new TypeReference(true) {})); - ; - - public static final Event PROPOSETRANSPARENTUPGRADE_EVENT = new Event("ProposeTransparentUpgrade", - Arrays.>asList(new TypeReference() {}, new TypeReference(true) {}, new TypeReference() {})); - ; - - public static final Event SECURITYCOUNCILUPGRADEAPPROVE_EVENT = new Event("SecurityCouncilUpgradeApprove", - Arrays.>asList(new TypeReference(true) {}, new TypeReference(true) {})); - ; - - public static final Event UNFREEZE_EVENT = new Event("Unfreeze", - Arrays.>asList()); - ; - - public static final Event VALIDATORSTATUSUPDATE_EVENT = new Event("ValidatorStatusUpdate", - Arrays.>asList(new TypeReference
(true) {}, new TypeReference() {})); - ; - - protected static final HashMap _addresses; - - static { - _addresses = new HashMap(); - } - - @Deprecated - protected ZkSyncContract(String contractAddress, Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) { - super(BINARY, contractAddress, web3j, credentials, gasPrice, gasLimit); - } - - protected ZkSyncContract(String contractAddress, Web3j web3j, Credentials credentials, ContractGasProvider contractGasProvider) { - super(BINARY, contractAddress, web3j, credentials, contractGasProvider); - } - - @Deprecated - protected ZkSyncContract(String contractAddress, Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit) { - super(BINARY, contractAddress, web3j, transactionManager, gasPrice, gasLimit); - } - - protected ZkSyncContract(String contractAddress, Web3j web3j, TransactionManager transactionManager, ContractGasProvider contractGasProvider) { - super(BINARY, contractAddress, web3j, transactionManager, contractGasProvider); - } - - public static List getBlockCommitEvents(TransactionReceipt transactionReceipt) { - List valueList = staticExtractEventParametersWithLog(BLOCKCOMMIT_EVENT, transactionReceipt); - ArrayList responses = new ArrayList(valueList.size()); - for (Contract.EventValuesWithLog eventValues : valueList) { - BlockCommitEventResponse typedResponse = new BlockCommitEventResponse(); - typedResponse.log = eventValues.getLog(); - typedResponse.blockNumber = (BigInteger) eventValues.getIndexedValues().get(0).getValue(); - typedResponse.blockHash = (byte[]) eventValues.getIndexedValues().get(1).getValue(); - typedResponse.commitment = (byte[]) eventValues.getIndexedValues().get(2).getValue(); - responses.add(typedResponse); - } - return responses; - } - - public static BlockCommitEventResponse getBlockCommitEventFromLog(Log log) { - Contract.EventValuesWithLog eventValues = staticExtractEventParametersWithLog(BLOCKCOMMIT_EVENT, log); - BlockCommitEventResponse typedResponse = new BlockCommitEventResponse(); - typedResponse.log = log; - typedResponse.blockNumber = (BigInteger) eventValues.getIndexedValues().get(0).getValue(); - typedResponse.blockHash = (byte[]) eventValues.getIndexedValues().get(1).getValue(); - typedResponse.commitment = (byte[]) eventValues.getIndexedValues().get(2).getValue(); - return typedResponse; - } - - public Flowable blockCommitEventFlowable(EthFilter filter) { - return web3j.ethLogFlowable(filter).map(log -> getBlockCommitEventFromLog(log)); - } - - public Flowable blockCommitEventFlowable(DefaultBlockParameter startBlock, DefaultBlockParameter endBlock) { - EthFilter filter = new EthFilter(startBlock, endBlock, getContractAddress()); - filter.addSingleTopic(EventEncoder.encode(BLOCKCOMMIT_EVENT)); - return blockCommitEventFlowable(filter); - } - - public static List getBlockExecutionEvents(TransactionReceipt transactionReceipt) { - List valueList = staticExtractEventParametersWithLog(BLOCKEXECUTION_EVENT, transactionReceipt); - ArrayList responses = new ArrayList(valueList.size()); - for (Contract.EventValuesWithLog eventValues : valueList) { - BlockExecutionEventResponse typedResponse = new BlockExecutionEventResponse(); - typedResponse.log = eventValues.getLog(); - typedResponse.blockNumber = (BigInteger) eventValues.getIndexedValues().get(0).getValue(); - typedResponse.blockHash = (byte[]) eventValues.getIndexedValues().get(1).getValue(); - typedResponse.commitment = (byte[]) eventValues.getIndexedValues().get(2).getValue(); - responses.add(typedResponse); - } - return responses; - } - - public static BlockExecutionEventResponse getBlockExecutionEventFromLog(Log log) { - Contract.EventValuesWithLog eventValues = staticExtractEventParametersWithLog(BLOCKEXECUTION_EVENT, log); - BlockExecutionEventResponse typedResponse = new BlockExecutionEventResponse(); - typedResponse.log = log; - typedResponse.blockNumber = (BigInteger) eventValues.getIndexedValues().get(0).getValue(); - typedResponse.blockHash = (byte[]) eventValues.getIndexedValues().get(1).getValue(); - typedResponse.commitment = (byte[]) eventValues.getIndexedValues().get(2).getValue(); - return typedResponse; - } - - public Flowable blockExecutionEventFlowable(EthFilter filter) { - return web3j.ethLogFlowable(filter).map(log -> getBlockExecutionEventFromLog(log)); - } - - public Flowable blockExecutionEventFlowable(DefaultBlockParameter startBlock, DefaultBlockParameter endBlock) { - EthFilter filter = new EthFilter(startBlock, endBlock, getContractAddress()); - filter.addSingleTopic(EventEncoder.encode(BLOCKEXECUTION_EVENT)); - return blockExecutionEventFlowable(filter); - } - - public static List getBlocksRevertEvents(TransactionReceipt transactionReceipt) { - List valueList = staticExtractEventParametersWithLog(BLOCKSREVERT_EVENT, transactionReceipt); - ArrayList responses = new ArrayList(valueList.size()); - for (Contract.EventValuesWithLog eventValues : valueList) { - BlocksRevertEventResponse typedResponse = new BlocksRevertEventResponse(); - typedResponse.log = eventValues.getLog(); - typedResponse.totalBlocksCommitted = (BigInteger) eventValues.getNonIndexedValues().get(0).getValue(); - typedResponse.totalBlocksVerified = (BigInteger) eventValues.getNonIndexedValues().get(1).getValue(); - typedResponse.totalBlocksExecuted = (BigInteger) eventValues.getNonIndexedValues().get(2).getValue(); - responses.add(typedResponse); - } - return responses; - } - - public static BlocksRevertEventResponse getBlocksRevertEventFromLog(Log log) { - Contract.EventValuesWithLog eventValues = staticExtractEventParametersWithLog(BLOCKSREVERT_EVENT, log); - BlocksRevertEventResponse typedResponse = new BlocksRevertEventResponse(); - typedResponse.log = log; - typedResponse.totalBlocksCommitted = (BigInteger) eventValues.getNonIndexedValues().get(0).getValue(); - typedResponse.totalBlocksVerified = (BigInteger) eventValues.getNonIndexedValues().get(1).getValue(); - typedResponse.totalBlocksExecuted = (BigInteger) eventValues.getNonIndexedValues().get(2).getValue(); - return typedResponse; - } - - public Flowable blocksRevertEventFlowable(EthFilter filter) { - return web3j.ethLogFlowable(filter).map(log -> getBlocksRevertEventFromLog(log)); - } - - public Flowable blocksRevertEventFlowable(DefaultBlockParameter startBlock, DefaultBlockParameter endBlock) { - EthFilter filter = new EthFilter(startBlock, endBlock, getContractAddress()); - filter.addSingleTopic(EventEncoder.encode(BLOCKSREVERT_EVENT)); - return blocksRevertEventFlowable(filter); - } - - public static List getBlocksVerificationEvents(TransactionReceipt transactionReceipt) { - List valueList = staticExtractEventParametersWithLog(BLOCKSVERIFICATION_EVENT, transactionReceipt); - ArrayList responses = new ArrayList(valueList.size()); - for (Contract.EventValuesWithLog eventValues : valueList) { - BlocksVerificationEventResponse typedResponse = new BlocksVerificationEventResponse(); - typedResponse.log = eventValues.getLog(); - typedResponse.previousLastVerifiedBlock = (BigInteger) eventValues.getIndexedValues().get(0).getValue(); - typedResponse.currentLastVerifiedBlock = (BigInteger) eventValues.getIndexedValues().get(1).getValue(); - responses.add(typedResponse); - } - return responses; - } - - public static BlocksVerificationEventResponse getBlocksVerificationEventFromLog(Log log) { - Contract.EventValuesWithLog eventValues = staticExtractEventParametersWithLog(BLOCKSVERIFICATION_EVENT, log); - BlocksVerificationEventResponse typedResponse = new BlocksVerificationEventResponse(); - typedResponse.log = log; - typedResponse.previousLastVerifiedBlock = (BigInteger) eventValues.getIndexedValues().get(0).getValue(); - typedResponse.currentLastVerifiedBlock = (BigInteger) eventValues.getIndexedValues().get(1).getValue(); - return typedResponse; - } - - public Flowable blocksVerificationEventFlowable(EthFilter filter) { - return web3j.ethLogFlowable(filter).map(log -> getBlocksVerificationEventFromLog(log)); - } - - public Flowable blocksVerificationEventFlowable(DefaultBlockParameter startBlock, DefaultBlockParameter endBlock) { - EthFilter filter = new EthFilter(startBlock, endBlock, getContractAddress()); - filter.addSingleTopic(EventEncoder.encode(BLOCKSVERIFICATION_EVENT)); - return blocksVerificationEventFlowable(filter); - } - - public static List getCancelUpgradeProposalEvents(TransactionReceipt transactionReceipt) { - List valueList = staticExtractEventParametersWithLog(CANCELUPGRADEPROPOSAL_EVENT, transactionReceipt); - ArrayList responses = new ArrayList(valueList.size()); - for (Contract.EventValuesWithLog eventValues : valueList) { - CancelUpgradeProposalEventResponse typedResponse = new CancelUpgradeProposalEventResponse(); - typedResponse.log = eventValues.getLog(); - typedResponse.proposalId = (BigInteger) eventValues.getIndexedValues().get(0).getValue(); - typedResponse.proposalHash = (byte[]) eventValues.getIndexedValues().get(1).getValue(); - responses.add(typedResponse); - } - return responses; - } - - public static CancelUpgradeProposalEventResponse getCancelUpgradeProposalEventFromLog(Log log) { - Contract.EventValuesWithLog eventValues = staticExtractEventParametersWithLog(CANCELUPGRADEPROPOSAL_EVENT, log); - CancelUpgradeProposalEventResponse typedResponse = new CancelUpgradeProposalEventResponse(); - typedResponse.log = log; - typedResponse.proposalId = (BigInteger) eventValues.getIndexedValues().get(0).getValue(); - typedResponse.proposalHash = (byte[]) eventValues.getIndexedValues().get(1).getValue(); - return typedResponse; - } - - public Flowable cancelUpgradeProposalEventFlowable(EthFilter filter) { - return web3j.ethLogFlowable(filter).map(log -> getCancelUpgradeProposalEventFromLog(log)); - } - - public Flowable cancelUpgradeProposalEventFlowable(DefaultBlockParameter startBlock, DefaultBlockParameter endBlock) { - EthFilter filter = new EthFilter(startBlock, endBlock, getContractAddress()); - filter.addSingleTopic(EventEncoder.encode(CANCELUPGRADEPROPOSAL_EVENT)); - return cancelUpgradeProposalEventFlowable(filter); - } - - public static List getEthWithdrawalFinalizedEvents(TransactionReceipt transactionReceipt) { - List valueList = staticExtractEventParametersWithLog(ETHWITHDRAWALFINALIZED_EVENT, transactionReceipt); - ArrayList responses = new ArrayList(valueList.size()); - for (Contract.EventValuesWithLog eventValues : valueList) { - EthWithdrawalFinalizedEventResponse typedResponse = new EthWithdrawalFinalizedEventResponse(); - typedResponse.log = eventValues.getLog(); - typedResponse.to = (String) eventValues.getIndexedValues().get(0).getValue(); - typedResponse.amount = (BigInteger) eventValues.getNonIndexedValues().get(0).getValue(); - responses.add(typedResponse); - } - return responses; - } - - public static EthWithdrawalFinalizedEventResponse getEthWithdrawalFinalizedEventFromLog(Log log) { - Contract.EventValuesWithLog eventValues = staticExtractEventParametersWithLog(ETHWITHDRAWALFINALIZED_EVENT, log); - EthWithdrawalFinalizedEventResponse typedResponse = new EthWithdrawalFinalizedEventResponse(); - typedResponse.log = log; - typedResponse.to = (String) eventValues.getIndexedValues().get(0).getValue(); - typedResponse.amount = (BigInteger) eventValues.getNonIndexedValues().get(0).getValue(); - return typedResponse; - } - - public Flowable ethWithdrawalFinalizedEventFlowable(EthFilter filter) { - return web3j.ethLogFlowable(filter).map(log -> getEthWithdrawalFinalizedEventFromLog(log)); - } - - public Flowable ethWithdrawalFinalizedEventFlowable(DefaultBlockParameter startBlock, DefaultBlockParameter endBlock) { - EthFilter filter = new EthFilter(startBlock, endBlock, getContractAddress()); - filter.addSingleTopic(EventEncoder.encode(ETHWITHDRAWALFINALIZED_EVENT)); - return ethWithdrawalFinalizedEventFlowable(filter); - } - - public static List getExecuteUpgradeEvents(TransactionReceipt transactionReceipt) { - List valueList = staticExtractEventParametersWithLog(EXECUTEUPGRADE_EVENT, transactionReceipt); - ArrayList responses = new ArrayList(valueList.size()); - for (Contract.EventValuesWithLog eventValues : valueList) { - ExecuteUpgradeEventResponse typedResponse = new ExecuteUpgradeEventResponse(); - typedResponse.log = eventValues.getLog(); - typedResponse.proposalId = (BigInteger) eventValues.getIndexedValues().get(0).getValue(); - typedResponse.proposalHash = (byte[]) eventValues.getIndexedValues().get(1).getValue(); - typedResponse.proposalSalt = (byte[]) eventValues.getNonIndexedValues().get(0).getValue(); - responses.add(typedResponse); - } - return responses; - } - - public static ExecuteUpgradeEventResponse getExecuteUpgradeEventFromLog(Log log) { - Contract.EventValuesWithLog eventValues = staticExtractEventParametersWithLog(EXECUTEUPGRADE_EVENT, log); - ExecuteUpgradeEventResponse typedResponse = new ExecuteUpgradeEventResponse(); - typedResponse.log = log; - typedResponse.proposalId = (BigInteger) eventValues.getIndexedValues().get(0).getValue(); - typedResponse.proposalHash = (byte[]) eventValues.getIndexedValues().get(1).getValue(); - typedResponse.proposalSalt = (byte[]) eventValues.getNonIndexedValues().get(0).getValue(); - return typedResponse; - } - - public Flowable executeUpgradeEventFlowable(EthFilter filter) { - return web3j.ethLogFlowable(filter).map(log -> getExecuteUpgradeEventFromLog(log)); - } - - public Flowable executeUpgradeEventFlowable(DefaultBlockParameter startBlock, DefaultBlockParameter endBlock) { - EthFilter filter = new EthFilter(startBlock, endBlock, getContractAddress()); - filter.addSingleTopic(EventEncoder.encode(EXECUTEUPGRADE_EVENT)); - return executeUpgradeEventFlowable(filter); - } - - public static List getFreezeEvents(TransactionReceipt transactionReceipt) { - List valueList = staticExtractEventParametersWithLog(FREEZE_EVENT, transactionReceipt); - ArrayList responses = new ArrayList(valueList.size()); - for (Contract.EventValuesWithLog eventValues : valueList) { - FreezeEventResponse typedResponse = new FreezeEventResponse(); - typedResponse.log = eventValues.getLog(); - responses.add(typedResponse); - } - return responses; - } - - public static FreezeEventResponse getFreezeEventFromLog(Log log) { - Contract.EventValuesWithLog eventValues = staticExtractEventParametersWithLog(FREEZE_EVENT, log); - FreezeEventResponse typedResponse = new FreezeEventResponse(); - typedResponse.log = log; - return typedResponse; - } - - public Flowable freezeEventFlowable(EthFilter filter) { - return web3j.ethLogFlowable(filter).map(log -> getFreezeEventFromLog(log)); - } - - public Flowable freezeEventFlowable(DefaultBlockParameter startBlock, DefaultBlockParameter endBlock) { - EthFilter filter = new EthFilter(startBlock, endBlock, getContractAddress()); - filter.addSingleTopic(EventEncoder.encode(FREEZE_EVENT)); - return freezeEventFlowable(filter); - } - - public static List getIsPorterAvailableStatusUpdateEvents(TransactionReceipt transactionReceipt) { - List valueList = staticExtractEventParametersWithLog(ISPORTERAVAILABLESTATUSUPDATE_EVENT, transactionReceipt); - ArrayList responses = new ArrayList(valueList.size()); - for (Contract.EventValuesWithLog eventValues : valueList) { - IsPorterAvailableStatusUpdateEventResponse typedResponse = new IsPorterAvailableStatusUpdateEventResponse(); - typedResponse.log = eventValues.getLog(); - typedResponse.isPorterAvailable = (Boolean) eventValues.getNonIndexedValues().get(0).getValue(); - responses.add(typedResponse); - } - return responses; - } - - public static IsPorterAvailableStatusUpdateEventResponse getIsPorterAvailableStatusUpdateEventFromLog(Log log) { - Contract.EventValuesWithLog eventValues = staticExtractEventParametersWithLog(ISPORTERAVAILABLESTATUSUPDATE_EVENT, log); - IsPorterAvailableStatusUpdateEventResponse typedResponse = new IsPorterAvailableStatusUpdateEventResponse(); - typedResponse.log = log; - typedResponse.isPorterAvailable = (Boolean) eventValues.getNonIndexedValues().get(0).getValue(); - return typedResponse; - } - - public Flowable isPorterAvailableStatusUpdateEventFlowable(EthFilter filter) { - return web3j.ethLogFlowable(filter).map(log -> getIsPorterAvailableStatusUpdateEventFromLog(log)); - } - - public Flowable isPorterAvailableStatusUpdateEventFlowable(DefaultBlockParameter startBlock, DefaultBlockParameter endBlock) { - EthFilter filter = new EthFilter(startBlock, endBlock, getContractAddress()); - filter.addSingleTopic(EventEncoder.encode(ISPORTERAVAILABLESTATUSUPDATE_EVENT)); - return isPorterAvailableStatusUpdateEventFlowable(filter); - } - - public static List getNewGovernorEvents(TransactionReceipt transactionReceipt) { - List valueList = staticExtractEventParametersWithLog(NEWGOVERNOR_EVENT, transactionReceipt); - ArrayList responses = new ArrayList(valueList.size()); - for (Contract.EventValuesWithLog eventValues : valueList) { - NewGovernorEventResponse typedResponse = new NewGovernorEventResponse(); - typedResponse.log = eventValues.getLog(); - typedResponse.oldGovernor = (String) eventValues.getIndexedValues().get(0).getValue(); - typedResponse.newGovernor = (String) eventValues.getIndexedValues().get(1).getValue(); - responses.add(typedResponse); - } - return responses; - } - - public static NewGovernorEventResponse getNewGovernorEventFromLog(Log log) { - Contract.EventValuesWithLog eventValues = staticExtractEventParametersWithLog(NEWGOVERNOR_EVENT, log); - NewGovernorEventResponse typedResponse = new NewGovernorEventResponse(); - typedResponse.log = log; - typedResponse.oldGovernor = (String) eventValues.getIndexedValues().get(0).getValue(); - typedResponse.newGovernor = (String) eventValues.getIndexedValues().get(1).getValue(); - return typedResponse; - } - - public Flowable newGovernorEventFlowable(EthFilter filter) { - return web3j.ethLogFlowable(filter).map(log -> getNewGovernorEventFromLog(log)); - } - - public Flowable newGovernorEventFlowable(DefaultBlockParameter startBlock, DefaultBlockParameter endBlock) { - EthFilter filter = new EthFilter(startBlock, endBlock, getContractAddress()); - filter.addSingleTopic(EventEncoder.encode(NEWGOVERNOR_EVENT)); - return newGovernorEventFlowable(filter); - } - - public static List getNewL2BootloaderBytecodeHashEvents(TransactionReceipt transactionReceipt) { - List valueList = staticExtractEventParametersWithLog(NEWL2BOOTLOADERBYTECODEHASH_EVENT, transactionReceipt); - ArrayList responses = new ArrayList(valueList.size()); - for (Contract.EventValuesWithLog eventValues : valueList) { - NewL2BootloaderBytecodeHashEventResponse typedResponse = new NewL2BootloaderBytecodeHashEventResponse(); - typedResponse.log = eventValues.getLog(); - typedResponse.previousBytecodeHash = (byte[]) eventValues.getIndexedValues().get(0).getValue(); - typedResponse.newBytecodeHash = (byte[]) eventValues.getIndexedValues().get(1).getValue(); - responses.add(typedResponse); - } - return responses; - } - - public static NewL2BootloaderBytecodeHashEventResponse getNewL2BootloaderBytecodeHashEventFromLog(Log log) { - Contract.EventValuesWithLog eventValues = staticExtractEventParametersWithLog(NEWL2BOOTLOADERBYTECODEHASH_EVENT, log); - NewL2BootloaderBytecodeHashEventResponse typedResponse = new NewL2BootloaderBytecodeHashEventResponse(); - typedResponse.log = log; - typedResponse.previousBytecodeHash = (byte[]) eventValues.getIndexedValues().get(0).getValue(); - typedResponse.newBytecodeHash = (byte[]) eventValues.getIndexedValues().get(1).getValue(); - return typedResponse; - } - - public Flowable newL2BootloaderBytecodeHashEventFlowable(EthFilter filter) { - return web3j.ethLogFlowable(filter).map(log -> getNewL2BootloaderBytecodeHashEventFromLog(log)); - } - - public Flowable newL2BootloaderBytecodeHashEventFlowable(DefaultBlockParameter startBlock, DefaultBlockParameter endBlock) { - EthFilter filter = new EthFilter(startBlock, endBlock, getContractAddress()); - filter.addSingleTopic(EventEncoder.encode(NEWL2BOOTLOADERBYTECODEHASH_EVENT)); - return newL2BootloaderBytecodeHashEventFlowable(filter); - } - - public static List getNewL2DefaultAccountBytecodeHashEvents(TransactionReceipt transactionReceipt) { - List valueList = staticExtractEventParametersWithLog(NEWL2DEFAULTACCOUNTBYTECODEHASH_EVENT, transactionReceipt); - ArrayList responses = new ArrayList(valueList.size()); - for (Contract.EventValuesWithLog eventValues : valueList) { - NewL2DefaultAccountBytecodeHashEventResponse typedResponse = new NewL2DefaultAccountBytecodeHashEventResponse(); - typedResponse.log = eventValues.getLog(); - typedResponse.previousBytecodeHash = (byte[]) eventValues.getIndexedValues().get(0).getValue(); - typedResponse.newBytecodeHash = (byte[]) eventValues.getIndexedValues().get(1).getValue(); - responses.add(typedResponse); - } - return responses; - } - - public static NewL2DefaultAccountBytecodeHashEventResponse getNewL2DefaultAccountBytecodeHashEventFromLog(Log log) { - Contract.EventValuesWithLog eventValues = staticExtractEventParametersWithLog(NEWL2DEFAULTACCOUNTBYTECODEHASH_EVENT, log); - NewL2DefaultAccountBytecodeHashEventResponse typedResponse = new NewL2DefaultAccountBytecodeHashEventResponse(); - typedResponse.log = log; - typedResponse.previousBytecodeHash = (byte[]) eventValues.getIndexedValues().get(0).getValue(); - typedResponse.newBytecodeHash = (byte[]) eventValues.getIndexedValues().get(1).getValue(); - return typedResponse; - } - - public Flowable newL2DefaultAccountBytecodeHashEventFlowable(EthFilter filter) { - return web3j.ethLogFlowable(filter).map(log -> getNewL2DefaultAccountBytecodeHashEventFromLog(log)); - } - - public Flowable newL2DefaultAccountBytecodeHashEventFlowable(DefaultBlockParameter startBlock, DefaultBlockParameter endBlock) { - EthFilter filter = new EthFilter(startBlock, endBlock, getContractAddress()); - filter.addSingleTopic(EventEncoder.encode(NEWL2DEFAULTACCOUNTBYTECODEHASH_EVENT)); - return newL2DefaultAccountBytecodeHashEventFlowable(filter); - } - - public static List getNewPendingGovernorEvents(TransactionReceipt transactionReceipt) { - List valueList = staticExtractEventParametersWithLog(NEWPENDINGGOVERNOR_EVENT, transactionReceipt); - ArrayList responses = new ArrayList(valueList.size()); - for (Contract.EventValuesWithLog eventValues : valueList) { - NewPendingGovernorEventResponse typedResponse = new NewPendingGovernorEventResponse(); - typedResponse.log = eventValues.getLog(); - typedResponse.oldPendingGovernor = (String) eventValues.getIndexedValues().get(0).getValue(); - typedResponse.newPendingGovernor = (String) eventValues.getIndexedValues().get(1).getValue(); - responses.add(typedResponse); - } - return responses; - } - - public static NewPendingGovernorEventResponse getNewPendingGovernorEventFromLog(Log log) { - Contract.EventValuesWithLog eventValues = staticExtractEventParametersWithLog(NEWPENDINGGOVERNOR_EVENT, log); - NewPendingGovernorEventResponse typedResponse = new NewPendingGovernorEventResponse(); - typedResponse.log = log; - typedResponse.oldPendingGovernor = (String) eventValues.getIndexedValues().get(0).getValue(); - typedResponse.newPendingGovernor = (String) eventValues.getIndexedValues().get(1).getValue(); - return typedResponse; - } - - public Flowable newPendingGovernorEventFlowable(EthFilter filter) { - return web3j.ethLogFlowable(filter).map(log -> getNewPendingGovernorEventFromLog(log)); - } - - public Flowable newPendingGovernorEventFlowable(DefaultBlockParameter startBlock, DefaultBlockParameter endBlock) { - EthFilter filter = new EthFilter(startBlock, endBlock, getContractAddress()); - filter.addSingleTopic(EventEncoder.encode(NEWPENDINGGOVERNOR_EVENT)); - return newPendingGovernorEventFlowable(filter); - } - - public static List getNewPriorityRequestEvents(TransactionReceipt transactionReceipt) { - List valueList = staticExtractEventParametersWithLog(NEWPRIORITYREQUEST_EVENT, transactionReceipt); - ArrayList responses = new ArrayList(valueList.size()); - for (Contract.EventValuesWithLog eventValues : valueList) { - NewPriorityRequestEventResponse typedResponse = new NewPriorityRequestEventResponse(); - typedResponse.log = eventValues.getLog(); - typedResponse.txId = (BigInteger) eventValues.getNonIndexedValues().get(0).getValue(); - typedResponse.txHash = (byte[]) eventValues.getNonIndexedValues().get(1).getValue(); - typedResponse.expirationTimestamp = (BigInteger) eventValues.getNonIndexedValues().get(2).getValue(); - typedResponse.transaction = (L2CanonicalTransaction) eventValues.getNonIndexedValues().get(3); - typedResponse.factoryDeps = (List) ((Array) eventValues.getNonIndexedValues().get(4)).getNativeValueCopy(); - responses.add(typedResponse); - } - return responses; - } - - public static NewPriorityRequestEventResponse getNewPriorityRequestEventFromLog(Log log) { - Contract.EventValuesWithLog eventValues = staticExtractEventParametersWithLog(NEWPRIORITYREQUEST_EVENT, log); - NewPriorityRequestEventResponse typedResponse = new NewPriorityRequestEventResponse(); - typedResponse.log = log; - typedResponse.txId = (BigInteger) eventValues.getNonIndexedValues().get(0).getValue(); - typedResponse.txHash = (byte[]) eventValues.getNonIndexedValues().get(1).getValue(); - typedResponse.expirationTimestamp = (BigInteger) eventValues.getNonIndexedValues().get(2).getValue(); - typedResponse.transaction = (L2CanonicalTransaction) eventValues.getNonIndexedValues().get(3); - typedResponse.factoryDeps = (List) ((Array) eventValues.getNonIndexedValues().get(4)).getNativeValueCopy(); - return typedResponse; - } - - public Flowable newPriorityRequestEventFlowable(EthFilter filter) { - return web3j.ethLogFlowable(filter).map(log -> getNewPriorityRequestEventFromLog(log)); - } - - public Flowable newPriorityRequestEventFlowable(DefaultBlockParameter startBlock, DefaultBlockParameter endBlock) { - EthFilter filter = new EthFilter(startBlock, endBlock, getContractAddress()); - filter.addSingleTopic(EventEncoder.encode(NEWPRIORITYREQUEST_EVENT)); - return newPriorityRequestEventFlowable(filter); - } - - public static List getNewPriorityTxMaxGasLimitEvents(TransactionReceipt transactionReceipt) { - List valueList = staticExtractEventParametersWithLog(NEWPRIORITYTXMAXGASLIMIT_EVENT, transactionReceipt); - ArrayList responses = new ArrayList(valueList.size()); - for (Contract.EventValuesWithLog eventValues : valueList) { - NewPriorityTxMaxGasLimitEventResponse typedResponse = new NewPriorityTxMaxGasLimitEventResponse(); - typedResponse.log = eventValues.getLog(); - typedResponse.oldPriorityTxMaxGasLimit = (BigInteger) eventValues.getNonIndexedValues().get(0).getValue(); - typedResponse.newPriorityTxMaxGasLimit = (BigInteger) eventValues.getNonIndexedValues().get(1).getValue(); - responses.add(typedResponse); - } - return responses; - } - - public static NewPriorityTxMaxGasLimitEventResponse getNewPriorityTxMaxGasLimitEventFromLog(Log log) { - Contract.EventValuesWithLog eventValues = staticExtractEventParametersWithLog(NEWPRIORITYTXMAXGASLIMIT_EVENT, log); - NewPriorityTxMaxGasLimitEventResponse typedResponse = new NewPriorityTxMaxGasLimitEventResponse(); - typedResponse.log = log; - typedResponse.oldPriorityTxMaxGasLimit = (BigInteger) eventValues.getNonIndexedValues().get(0).getValue(); - typedResponse.newPriorityTxMaxGasLimit = (BigInteger) eventValues.getNonIndexedValues().get(1).getValue(); - return typedResponse; - } - - public Flowable newPriorityTxMaxGasLimitEventFlowable(EthFilter filter) { - return web3j.ethLogFlowable(filter).map(log -> getNewPriorityTxMaxGasLimitEventFromLog(log)); - } - - public Flowable newPriorityTxMaxGasLimitEventFlowable(DefaultBlockParameter startBlock, DefaultBlockParameter endBlock) { - EthFilter filter = new EthFilter(startBlock, endBlock, getContractAddress()); - filter.addSingleTopic(EventEncoder.encode(NEWPRIORITYTXMAXGASLIMIT_EVENT)); - return newPriorityTxMaxGasLimitEventFlowable(filter); - } - - public static List getNewVerifierEvents(TransactionReceipt transactionReceipt) { - List valueList = staticExtractEventParametersWithLog(NEWVERIFIER_EVENT, transactionReceipt); - ArrayList responses = new ArrayList(valueList.size()); - for (Contract.EventValuesWithLog eventValues : valueList) { - NewVerifierEventResponse typedResponse = new NewVerifierEventResponse(); - typedResponse.log = eventValues.getLog(); - typedResponse.oldVerifier = (String) eventValues.getIndexedValues().get(0).getValue(); - typedResponse.newVerifier = (String) eventValues.getIndexedValues().get(1).getValue(); - responses.add(typedResponse); - } - return responses; - } - - public static NewVerifierEventResponse getNewVerifierEventFromLog(Log log) { - Contract.EventValuesWithLog eventValues = staticExtractEventParametersWithLog(NEWVERIFIER_EVENT, log); - NewVerifierEventResponse typedResponse = new NewVerifierEventResponse(); - typedResponse.log = log; - typedResponse.oldVerifier = (String) eventValues.getIndexedValues().get(0).getValue(); - typedResponse.newVerifier = (String) eventValues.getIndexedValues().get(1).getValue(); - return typedResponse; - } - - public Flowable newVerifierEventFlowable(EthFilter filter) { - return web3j.ethLogFlowable(filter).map(log -> getNewVerifierEventFromLog(log)); - } - - public Flowable newVerifierEventFlowable(DefaultBlockParameter startBlock, DefaultBlockParameter endBlock) { - EthFilter filter = new EthFilter(startBlock, endBlock, getContractAddress()); - filter.addSingleTopic(EventEncoder.encode(NEWVERIFIER_EVENT)); - return newVerifierEventFlowable(filter); - } - - public static List getNewVerifierParamsEvents(TransactionReceipt transactionReceipt) { - List valueList = staticExtractEventParametersWithLog(NEWVERIFIERPARAMS_EVENT, transactionReceipt); - ArrayList responses = new ArrayList(valueList.size()); - for (Contract.EventValuesWithLog eventValues : valueList) { - NewVerifierParamsEventResponse typedResponse = new NewVerifierParamsEventResponse(); - typedResponse.log = eventValues.getLog(); - typedResponse.oldVerifierParams = (VerifierParams) eventValues.getNonIndexedValues().get(0); - typedResponse.newVerifierParams = (VerifierParams) eventValues.getNonIndexedValues().get(1); - responses.add(typedResponse); - } - return responses; - } - - public static NewVerifierParamsEventResponse getNewVerifierParamsEventFromLog(Log log) { - Contract.EventValuesWithLog eventValues = staticExtractEventParametersWithLog(NEWVERIFIERPARAMS_EVENT, log); - NewVerifierParamsEventResponse typedResponse = new NewVerifierParamsEventResponse(); - typedResponse.log = log; - typedResponse.oldVerifierParams = (VerifierParams) eventValues.getNonIndexedValues().get(0); - typedResponse.newVerifierParams = (VerifierParams) eventValues.getNonIndexedValues().get(1); - return typedResponse; - } - - public Flowable newVerifierParamsEventFlowable(EthFilter filter) { - return web3j.ethLogFlowable(filter).map(log -> getNewVerifierParamsEventFromLog(log)); - } - - public Flowable newVerifierParamsEventFlowable(DefaultBlockParameter startBlock, DefaultBlockParameter endBlock) { - EthFilter filter = new EthFilter(startBlock, endBlock, getContractAddress()); - filter.addSingleTopic(EventEncoder.encode(NEWVERIFIERPARAMS_EVENT)); - return newVerifierParamsEventFlowable(filter); - } - - public static List getProposeShadowUpgradeEvents(TransactionReceipt transactionReceipt) { - List valueList = staticExtractEventParametersWithLog(PROPOSESHADOWUPGRADE_EVENT, transactionReceipt); - ArrayList responses = new ArrayList(valueList.size()); - for (Contract.EventValuesWithLog eventValues : valueList) { - ProposeShadowUpgradeEventResponse typedResponse = new ProposeShadowUpgradeEventResponse(); - typedResponse.log = eventValues.getLog(); - typedResponse.proposalId = (BigInteger) eventValues.getIndexedValues().get(0).getValue(); - typedResponse.proposalHash = (byte[]) eventValues.getIndexedValues().get(1).getValue(); - responses.add(typedResponse); - } - return responses; - } - - public static ProposeShadowUpgradeEventResponse getProposeShadowUpgradeEventFromLog(Log log) { - Contract.EventValuesWithLog eventValues = staticExtractEventParametersWithLog(PROPOSESHADOWUPGRADE_EVENT, log); - ProposeShadowUpgradeEventResponse typedResponse = new ProposeShadowUpgradeEventResponse(); - typedResponse.log = log; - typedResponse.proposalId = (BigInteger) eventValues.getIndexedValues().get(0).getValue(); - typedResponse.proposalHash = (byte[]) eventValues.getIndexedValues().get(1).getValue(); - return typedResponse; - } - - public Flowable proposeShadowUpgradeEventFlowable(EthFilter filter) { - return web3j.ethLogFlowable(filter).map(log -> getProposeShadowUpgradeEventFromLog(log)); - } - - public Flowable proposeShadowUpgradeEventFlowable(DefaultBlockParameter startBlock, DefaultBlockParameter endBlock) { - EthFilter filter = new EthFilter(startBlock, endBlock, getContractAddress()); - filter.addSingleTopic(EventEncoder.encode(PROPOSESHADOWUPGRADE_EVENT)); - return proposeShadowUpgradeEventFlowable(filter); - } - - public static List getProposeTransparentUpgradeEvents(TransactionReceipt transactionReceipt) { - List valueList = staticExtractEventParametersWithLog(PROPOSETRANSPARENTUPGRADE_EVENT, transactionReceipt); - ArrayList responses = new ArrayList(valueList.size()); - for (Contract.EventValuesWithLog eventValues : valueList) { - ProposeTransparentUpgradeEventResponse typedResponse = new ProposeTransparentUpgradeEventResponse(); - typedResponse.log = eventValues.getLog(); - typedResponse.proposalId = (BigInteger) eventValues.getIndexedValues().get(0).getValue(); - typedResponse.diamondCut = (DiamondCutData) eventValues.getNonIndexedValues().get(0); - typedResponse.proposalSalt = (byte[]) eventValues.getNonIndexedValues().get(1).getValue(); - responses.add(typedResponse); - } - return responses; - } - - public static ProposeTransparentUpgradeEventResponse getProposeTransparentUpgradeEventFromLog(Log log) { - Contract.EventValuesWithLog eventValues = staticExtractEventParametersWithLog(PROPOSETRANSPARENTUPGRADE_EVENT, log); - ProposeTransparentUpgradeEventResponse typedResponse = new ProposeTransparentUpgradeEventResponse(); - typedResponse.log = log; - typedResponse.proposalId = (BigInteger) eventValues.getIndexedValues().get(0).getValue(); - typedResponse.diamondCut = (DiamondCutData) eventValues.getNonIndexedValues().get(0); - typedResponse.proposalSalt = (byte[]) eventValues.getNonIndexedValues().get(1).getValue(); - return typedResponse; - } - - public Flowable proposeTransparentUpgradeEventFlowable(EthFilter filter) { - return web3j.ethLogFlowable(filter).map(log -> getProposeTransparentUpgradeEventFromLog(log)); - } - - public Flowable proposeTransparentUpgradeEventFlowable(DefaultBlockParameter startBlock, DefaultBlockParameter endBlock) { - EthFilter filter = new EthFilter(startBlock, endBlock, getContractAddress()); - filter.addSingleTopic(EventEncoder.encode(PROPOSETRANSPARENTUPGRADE_EVENT)); - return proposeTransparentUpgradeEventFlowable(filter); - } - - public static List getSecurityCouncilUpgradeApproveEvents(TransactionReceipt transactionReceipt) { - List valueList = staticExtractEventParametersWithLog(SECURITYCOUNCILUPGRADEAPPROVE_EVENT, transactionReceipt); - ArrayList responses = new ArrayList(valueList.size()); - for (Contract.EventValuesWithLog eventValues : valueList) { - SecurityCouncilUpgradeApproveEventResponse typedResponse = new SecurityCouncilUpgradeApproveEventResponse(); - typedResponse.log = eventValues.getLog(); - typedResponse.proposalId = (BigInteger) eventValues.getIndexedValues().get(0).getValue(); - typedResponse.proposalHash = (byte[]) eventValues.getIndexedValues().get(1).getValue(); - responses.add(typedResponse); - } - return responses; - } - - public static SecurityCouncilUpgradeApproveEventResponse getSecurityCouncilUpgradeApproveEventFromLog(Log log) { - Contract.EventValuesWithLog eventValues = staticExtractEventParametersWithLog(SECURITYCOUNCILUPGRADEAPPROVE_EVENT, log); - SecurityCouncilUpgradeApproveEventResponse typedResponse = new SecurityCouncilUpgradeApproveEventResponse(); - typedResponse.log = log; - typedResponse.proposalId = (BigInteger) eventValues.getIndexedValues().get(0).getValue(); - typedResponse.proposalHash = (byte[]) eventValues.getIndexedValues().get(1).getValue(); - return typedResponse; - } - - public Flowable securityCouncilUpgradeApproveEventFlowable(EthFilter filter) { - return web3j.ethLogFlowable(filter).map(log -> getSecurityCouncilUpgradeApproveEventFromLog(log)); - } - - public Flowable securityCouncilUpgradeApproveEventFlowable(DefaultBlockParameter startBlock, DefaultBlockParameter endBlock) { - EthFilter filter = new EthFilter(startBlock, endBlock, getContractAddress()); - filter.addSingleTopic(EventEncoder.encode(SECURITYCOUNCILUPGRADEAPPROVE_EVENT)); - return securityCouncilUpgradeApproveEventFlowable(filter); - } - - public static List getUnfreezeEvents(TransactionReceipt transactionReceipt) { - List valueList = staticExtractEventParametersWithLog(UNFREEZE_EVENT, transactionReceipt); - ArrayList responses = new ArrayList(valueList.size()); - for (Contract.EventValuesWithLog eventValues : valueList) { - UnfreezeEventResponse typedResponse = new UnfreezeEventResponse(); - typedResponse.log = eventValues.getLog(); - responses.add(typedResponse); - } - return responses; - } - - public static UnfreezeEventResponse getUnfreezeEventFromLog(Log log) { - Contract.EventValuesWithLog eventValues = staticExtractEventParametersWithLog(UNFREEZE_EVENT, log); - UnfreezeEventResponse typedResponse = new UnfreezeEventResponse(); - typedResponse.log = log; - return typedResponse; - } - - public Flowable unfreezeEventFlowable(EthFilter filter) { - return web3j.ethLogFlowable(filter).map(log -> getUnfreezeEventFromLog(log)); - } - - public Flowable unfreezeEventFlowable(DefaultBlockParameter startBlock, DefaultBlockParameter endBlock) { - EthFilter filter = new EthFilter(startBlock, endBlock, getContractAddress()); - filter.addSingleTopic(EventEncoder.encode(UNFREEZE_EVENT)); - return unfreezeEventFlowable(filter); - } - - public static List getValidatorStatusUpdateEvents(TransactionReceipt transactionReceipt) { - List valueList = staticExtractEventParametersWithLog(VALIDATORSTATUSUPDATE_EVENT, transactionReceipt); - ArrayList responses = new ArrayList(valueList.size()); - for (Contract.EventValuesWithLog eventValues : valueList) { - ValidatorStatusUpdateEventResponse typedResponse = new ValidatorStatusUpdateEventResponse(); - typedResponse.log = eventValues.getLog(); - typedResponse.validatorAddress = (String) eventValues.getIndexedValues().get(0).getValue(); - typedResponse.isActive = (Boolean) eventValues.getNonIndexedValues().get(0).getValue(); - responses.add(typedResponse); - } - return responses; - } - - public static ValidatorStatusUpdateEventResponse getValidatorStatusUpdateEventFromLog(Log log) { - Contract.EventValuesWithLog eventValues = staticExtractEventParametersWithLog(VALIDATORSTATUSUPDATE_EVENT, log); - ValidatorStatusUpdateEventResponse typedResponse = new ValidatorStatusUpdateEventResponse(); - typedResponse.log = log; - typedResponse.validatorAddress = (String) eventValues.getIndexedValues().get(0).getValue(); - typedResponse.isActive = (Boolean) eventValues.getNonIndexedValues().get(0).getValue(); - return typedResponse; - } - - public Flowable validatorStatusUpdateEventFlowable(EthFilter filter) { - return web3j.ethLogFlowable(filter).map(log -> getValidatorStatusUpdateEventFromLog(log)); - } - - public Flowable validatorStatusUpdateEventFlowable(DefaultBlockParameter startBlock, DefaultBlockParameter endBlock) { - EthFilter filter = new EthFilter(startBlock, endBlock, getContractAddress()); - filter.addSingleTopic(EventEncoder.encode(VALIDATORSTATUSUPDATE_EVENT)); - return validatorStatusUpdateEventFlowable(filter); - } - - public RemoteFunctionCall acceptGovernor() { - final Function function = new Function( - FUNC_ACCEPTGOVERNOR, - Arrays.asList(), - Collections.>emptyList()); - return executeRemoteCallTransaction(function); - } - - public RemoteFunctionCall cancelUpgradeProposal(byte[] _proposedUpgradeHash) { - final Function function = new Function( - FUNC_CANCELUPGRADEPROPOSAL, - Arrays.asList(new org.web3j.abi.datatypes.generated.Bytes32(_proposedUpgradeHash)), - Collections.>emptyList()); - return executeRemoteCallTransaction(function); - } - - public RemoteFunctionCall commitBlocks(StoredBlockInfo _lastCommittedBlockData, List _newBlocksData) { - final Function function = new Function( - FUNC_COMMITBLOCKS, - Arrays.asList(_lastCommittedBlockData, - new org.web3j.abi.datatypes.DynamicArray(CommitBlockInfo.class, _newBlocksData)), - Collections.>emptyList()); - return executeRemoteCallTransaction(function); - } - - public RemoteFunctionCall executeBlocks(List _blocksData) { - final Function function = new Function( - FUNC_EXECUTEBLOCKS, - Arrays.asList(new org.web3j.abi.datatypes.DynamicArray(StoredBlockInfo.class, _blocksData)), - Collections.>emptyList()); - return executeRemoteCallTransaction(function); - } - - public RemoteFunctionCall executeUpgrade(DiamondCutData _diamondCut, byte[] _proposalSalt) { - final Function function = new Function( - FUNC_EXECUTEUPGRADE, - Arrays.asList(_diamondCut, - new org.web3j.abi.datatypes.generated.Bytes32(_proposalSalt)), - Collections.>emptyList()); - return executeRemoteCallTransaction(function); - } - - public RemoteFunctionCall facetAddress(byte[] _selector) { - final Function function = new Function(FUNC_FACETADDRESS, - Arrays.asList(new org.web3j.abi.datatypes.generated.Bytes4(_selector)), - Arrays.>asList(new TypeReference
() {})); - return executeRemoteCallSingleValueReturn(function, String.class); - } - - public RemoteFunctionCall facetAddresses() { - final Function function = new Function(FUNC_FACETADDRESSES, - Arrays.asList(), - Arrays.>asList(new TypeReference>() {})); - return new RemoteFunctionCall(function, - new Callable() { - @Override - @SuppressWarnings("unchecked") - public List call() throws Exception { - List result = (List) executeCallSingleValueReturn(function, List.class); - return convertToNative(result); - } - }); - } - - public RemoteFunctionCall facetFunctionSelectors(String _facet) { - final Function function = new Function(FUNC_FACETFUNCTIONSELECTORS, - Arrays.asList(new org.web3j.abi.datatypes.Address(_facet)), - Arrays.>asList(new TypeReference>() {})); - return new RemoteFunctionCall(function, - new Callable() { - @Override - @SuppressWarnings("unchecked") - public List call() throws Exception { - List result = (List) executeCallSingleValueReturn(function, List.class); - return convertToNative(result); - } - }); - } - - public RemoteFunctionCall facets() { - final Function function = new Function(FUNC_FACETS, - Arrays.asList(), - Arrays.>asList(new TypeReference>() {})); - return new RemoteFunctionCall(function, - new Callable() { - @Override - @SuppressWarnings("unchecked") - public List call() throws Exception { - List result = (List) executeCallSingleValueReturn(function, List.class); - return convertToNative(result); - } - }); - } - - public RemoteFunctionCall finalizeEthWithdrawal(BigInteger _l2BlockNumber, BigInteger _l2MessageIndex, BigInteger _l2TxNumberInBlock, byte[] _message, List _merkleProof) { - final Function function = new Function( - FUNC_FINALIZEETHWITHDRAWAL, - Arrays.asList(new org.web3j.abi.datatypes.generated.Uint256(_l2BlockNumber), - new org.web3j.abi.datatypes.generated.Uint256(_l2MessageIndex), - new org.web3j.abi.datatypes.generated.Uint16(_l2TxNumberInBlock), - new org.web3j.abi.datatypes.DynamicBytes(_message), - new org.web3j.abi.datatypes.DynamicArray( - org.web3j.abi.datatypes.generated.Bytes32.class, - org.web3j.abi.Utils.typeMap(_merkleProof, org.web3j.abi.datatypes.generated.Bytes32.class))), - Collections.>emptyList()); - return executeRemoteCallTransaction(function); - } - - public RemoteFunctionCall freezeDiamond() { - final Function function = new Function( - FUNC_FREEZEDIAMOND, - Arrays.asList(), - Collections.>emptyList()); - return executeRemoteCallTransaction(function); - } - - public RemoteFunctionCall getCurrentProposalId() { - final Function function = new Function(FUNC_GETCURRENTPROPOSALID, - Arrays.asList(), - Arrays.>asList(new TypeReference() {})); - return executeRemoteCallSingleValueReturn(function, BigInteger.class); - } - - public RemoteFunctionCall getFirstUnprocessedPriorityTx() { - final Function function = new Function(FUNC_GETFIRSTUNPROCESSEDPRIORITYTX, - Arrays.asList(), - Arrays.>asList(new TypeReference() {})); - return executeRemoteCallSingleValueReturn(function, BigInteger.class); - } - - public RemoteFunctionCall getGovernor() { - final Function function = new Function(FUNC_GETGOVERNOR, - Arrays.asList(), - Arrays.>asList(new TypeReference
() {})); - return executeRemoteCallSingleValueReturn(function, String.class); - } - - public RemoteFunctionCall getL2BootloaderBytecodeHash() { - final Function function = new Function(FUNC_GETL2BOOTLOADERBYTECODEHASH, - Arrays.asList(), - Arrays.>asList(new TypeReference() {})); - return executeRemoteCallSingleValueReturn(function, byte[].class); - } - - public RemoteFunctionCall getL2DefaultAccountBytecodeHash() { - final Function function = new Function(FUNC_GETL2DEFAULTACCOUNTBYTECODEHASH, - Arrays.asList(), - Arrays.>asList(new TypeReference() {})); - return executeRemoteCallSingleValueReturn(function, byte[].class); - } - - public RemoteFunctionCall getPendingGovernor() { - final Function function = new Function(FUNC_GETPENDINGGOVERNOR, - Arrays.asList(), - Arrays.>asList(new TypeReference
() {})); - return executeRemoteCallSingleValueReturn(function, String.class); - } - - public RemoteFunctionCall getPriorityQueueSize() { - final Function function = new Function(FUNC_GETPRIORITYQUEUESIZE, - Arrays.asList(), - Arrays.>asList(new TypeReference() {})); - return executeRemoteCallSingleValueReturn(function, BigInteger.class); - } - - public RemoteFunctionCall getProposedUpgradeHash() { - final Function function = new Function(FUNC_GETPROPOSEDUPGRADEHASH, - Arrays.asList(), - Arrays.>asList(new TypeReference() {})); - return executeRemoteCallSingleValueReturn(function, byte[].class); - } - - public RemoteFunctionCall getProposedUpgradeTimestamp() { - final Function function = new Function(FUNC_GETPROPOSEDUPGRADETIMESTAMP, - Arrays.asList(), - Arrays.>asList(new TypeReference() {})); - return executeRemoteCallSingleValueReturn(function, BigInteger.class); - } - - public RemoteFunctionCall getSecurityCouncil() { - final Function function = new Function(FUNC_GETSECURITYCOUNCIL, - Arrays.asList(), - Arrays.>asList(new TypeReference
() {})); - return executeRemoteCallSingleValueReturn(function, String.class); - } - - public RemoteFunctionCall getTotalBlocksCommitted() { - final Function function = new Function(FUNC_GETTOTALBLOCKSCOMMITTED, - Arrays.asList(), - Arrays.>asList(new TypeReference() {})); - return executeRemoteCallSingleValueReturn(function, BigInteger.class); - } - - public RemoteFunctionCall getTotalBlocksExecuted() { - final Function function = new Function(FUNC_GETTOTALBLOCKSEXECUTED, - Arrays.asList(), - Arrays.>asList(new TypeReference() {})); - return executeRemoteCallSingleValueReturn(function, BigInteger.class); - } - - public RemoteFunctionCall getTotalBlocksVerified() { - final Function function = new Function(FUNC_GETTOTALBLOCKSVERIFIED, - Arrays.asList(), - Arrays.>asList(new TypeReference() {})); - return executeRemoteCallSingleValueReturn(function, BigInteger.class); - } - - public RemoteFunctionCall getTotalPriorityTxs() { - final Function function = new Function(FUNC_GETTOTALPRIORITYTXS, - Arrays.asList(), - Arrays.>asList(new TypeReference() {})); - return executeRemoteCallSingleValueReturn(function, BigInteger.class); - } - - public RemoteFunctionCall getUpgradeProposalState() { - final Function function = new Function(FUNC_GETUPGRADEPROPOSALSTATE, - Arrays.asList(), - Arrays.>asList(new TypeReference() {})); - return executeRemoteCallSingleValueReturn(function, BigInteger.class); - } - - public RemoteFunctionCall getVerifier() { - final Function function = new Function(FUNC_GETVERIFIER, - Arrays.asList(), - Arrays.>asList(new TypeReference
() {})); - return executeRemoteCallSingleValueReturn(function, String.class); - } - - public RemoteFunctionCall getVerifierParams() { - final Function function = new Function(FUNC_GETVERIFIERPARAMS, - Arrays.asList(), - Arrays.>asList(new TypeReference() {})); - return executeRemoteCallSingleValueReturn(function, VerifierParams.class); - } - - public RemoteFunctionCall getpriorityTxMaxGasLimit() { - final Function function = new Function(FUNC_GETPRIORITYTXMAXGASLIMIT, - Arrays.asList(), - Arrays.>asList(new TypeReference() {})); - return executeRemoteCallSingleValueReturn(function, BigInteger.class); - } - - public RemoteFunctionCall isApprovedBySecurityCouncil() { - final Function function = new Function(FUNC_ISAPPROVEDBYSECURITYCOUNCIL, - Arrays.asList(), - Arrays.>asList(new TypeReference() {})); - return executeRemoteCallSingleValueReturn(function, Boolean.class); - } - - public RemoteFunctionCall isDiamondStorageFrozen() { - final Function function = new Function(FUNC_ISDIAMONDSTORAGEFROZEN, - Arrays.asList(), - Arrays.>asList(new TypeReference() {})); - return executeRemoteCallSingleValueReturn(function, Boolean.class); - } - - public RemoteFunctionCall isEthWithdrawalFinalized(BigInteger _l2BlockNumber, BigInteger _l2MessageIndex) { - final Function function = new Function(FUNC_ISETHWITHDRAWALFINALIZED, - Arrays.asList(new org.web3j.abi.datatypes.generated.Uint256(_l2BlockNumber), - new org.web3j.abi.datatypes.generated.Uint256(_l2MessageIndex)), - Arrays.>asList(new TypeReference() {})); - return executeRemoteCallSingleValueReturn(function, Boolean.class); - } - - public RemoteFunctionCall isFacetFreezable(String _facet) { - final Function function = new Function(FUNC_ISFACETFREEZABLE, - Arrays.asList(new org.web3j.abi.datatypes.Address(_facet)), - Arrays.>asList(new TypeReference() {})); - return executeRemoteCallSingleValueReturn(function, Boolean.class); - } - - public RemoteFunctionCall isFunctionFreezable(byte[] _selector) { - final Function function = new Function(FUNC_ISFUNCTIONFREEZABLE, - Arrays.asList(new org.web3j.abi.datatypes.generated.Bytes4(_selector)), - Arrays.>asList(new TypeReference() {})); - return executeRemoteCallSingleValueReturn(function, Boolean.class); - } - - public RemoteFunctionCall isValidator(String _address) { - final Function function = new Function(FUNC_ISVALIDATOR, - Arrays.asList(new org.web3j.abi.datatypes.Address(_address)), - Arrays.>asList(new TypeReference() {})); - return executeRemoteCallSingleValueReturn(function, Boolean.class); - } - - public RemoteFunctionCall l2LogsRootHash(BigInteger _blockNumber) { - final Function function = new Function(FUNC_L2LOGSROOTHASH, - Arrays.asList(new org.web3j.abi.datatypes.generated.Uint256(_blockNumber)), - Arrays.>asList(new TypeReference() {})); - return executeRemoteCallSingleValueReturn(function, byte[].class); - } - - public RemoteFunctionCall l2TransactionBaseCost(BigInteger _gasPrice, BigInteger _l2GasLimit, BigInteger _l2GasPerPubdataByteLimit) { - final Function function = new Function(FUNC_L2TRANSACTIONBASECOST, - Arrays.asList(new org.web3j.abi.datatypes.generated.Uint256(_gasPrice), - new org.web3j.abi.datatypes.generated.Uint256(_l2GasLimit), - new org.web3j.abi.datatypes.generated.Uint256(_l2GasPerPubdataByteLimit)), - Arrays.>asList(new TypeReference() {})); - return executeRemoteCallSingleValueReturn(function, BigInteger.class); - } - - public RemoteFunctionCall priorityQueueFrontOperation() { - final Function function = new Function(FUNC_PRIORITYQUEUEFRONTOPERATION, - Arrays.asList(), - Arrays.>asList(new TypeReference() {})); - return executeRemoteCallSingleValueReturn(function, PriorityOperation.class); - } - - public RemoteFunctionCall proposeShadowUpgrade(byte[] _proposalHash, BigInteger _proposalId) { - final Function function = new Function( - FUNC_PROPOSESHADOWUPGRADE, - Arrays.asList(new org.web3j.abi.datatypes.generated.Bytes32(_proposalHash), - new org.web3j.abi.datatypes.generated.Uint40(_proposalId)), - Collections.>emptyList()); - return executeRemoteCallTransaction(function); - } - - public RemoteFunctionCall proposeTransparentUpgrade(DiamondCutData _diamondCut, BigInteger _proposalId) { - final Function function = new Function( - FUNC_PROPOSETRANSPARENTUPGRADE, - Arrays.asList(_diamondCut, - new org.web3j.abi.datatypes.generated.Uint40(_proposalId)), - Collections.>emptyList()); - return executeRemoteCallTransaction(function); - } - - public RemoteFunctionCall proveBlocks(StoredBlockInfo _prevBlock, List _committedBlocks, ProofInput _proof) { - final Function function = new Function( - FUNC_PROVEBLOCKS, - Arrays.asList(_prevBlock, - new org.web3j.abi.datatypes.DynamicArray(StoredBlockInfo.class, _committedBlocks), - _proof), - Collections.>emptyList()); - return executeRemoteCallTransaction(function); - } - - public RemoteFunctionCall proveL1ToL2TransactionStatus(byte[] _l2TxHash, BigInteger _l2BlockNumber, BigInteger _l2MessageIndex, BigInteger _l2TxNumberInBlock, List _merkleProof, BigInteger _status) { - final Function function = new Function(FUNC_PROVEL1TOL2TRANSACTIONSTATUS, - Arrays.asList(new org.web3j.abi.datatypes.generated.Bytes32(_l2TxHash), - new org.web3j.abi.datatypes.generated.Uint256(_l2BlockNumber), - new org.web3j.abi.datatypes.generated.Uint256(_l2MessageIndex), - new org.web3j.abi.datatypes.generated.Uint16(_l2TxNumberInBlock), - new org.web3j.abi.datatypes.DynamicArray( - org.web3j.abi.datatypes.generated.Bytes32.class, - org.web3j.abi.Utils.typeMap(_merkleProof, org.web3j.abi.datatypes.generated.Bytes32.class)), - new org.web3j.abi.datatypes.generated.Uint8(_status)), - Arrays.>asList(new TypeReference() {})); - return executeRemoteCallSingleValueReturn(function, Boolean.class); - } - - public RemoteFunctionCall proveL2LogInclusion(BigInteger _blockNumber, BigInteger _index, L2Log _log, List _proof) { - final Function function = new Function(FUNC_PROVEL2LOGINCLUSION, - Arrays.asList(new org.web3j.abi.datatypes.generated.Uint256(_blockNumber), - new org.web3j.abi.datatypes.generated.Uint256(_index), - _log, - new org.web3j.abi.datatypes.DynamicArray( - org.web3j.abi.datatypes.generated.Bytes32.class, - org.web3j.abi.Utils.typeMap(_proof, org.web3j.abi.datatypes.generated.Bytes32.class))), - Arrays.>asList(new TypeReference() {})); - return executeRemoteCallSingleValueReturn(function, Boolean.class); - } - - public RemoteFunctionCall proveL2MessageInclusion(BigInteger _blockNumber, BigInteger _index, L2Message _message, List _proof) { - final Function function = new Function(FUNC_PROVEL2MESSAGEINCLUSION, - Arrays.asList(new org.web3j.abi.datatypes.generated.Uint256(_blockNumber), - new org.web3j.abi.datatypes.generated.Uint256(_index), - _message, - new org.web3j.abi.datatypes.DynamicArray( - org.web3j.abi.datatypes.generated.Bytes32.class, - org.web3j.abi.Utils.typeMap(_proof, org.web3j.abi.datatypes.generated.Bytes32.class))), - Arrays.>asList(new TypeReference() {})); - return executeRemoteCallSingleValueReturn(function, Boolean.class); - } - - public RemoteFunctionCall requestL2Transaction(String _contractL2, BigInteger _l2Value, byte[] _calldata, BigInteger _l2GasLimit, BigInteger _l2GasPerPubdataByteLimit, List _factoryDeps, String _refundRecipient, BigInteger weiValue) { - final Function function = new Function( - FUNC_REQUESTL2TRANSACTION, - Arrays.asList(new org.web3j.abi.datatypes.Address(_contractL2), - new org.web3j.abi.datatypes.generated.Uint256(_l2Value), - new org.web3j.abi.datatypes.DynamicBytes(_calldata), - new org.web3j.abi.datatypes.generated.Uint256(_l2GasLimit), - new org.web3j.abi.datatypes.generated.Uint256(_l2GasPerPubdataByteLimit), - new org.web3j.abi.datatypes.DynamicArray( - org.web3j.abi.datatypes.DynamicBytes.class, - org.web3j.abi.Utils.typeMap(_factoryDeps, org.web3j.abi.datatypes.DynamicBytes.class)), - new org.web3j.abi.datatypes.Address(_refundRecipient)), - Collections.>emptyList()); - return executeRemoteCallTransaction(function, weiValue); - } - - public RemoteFunctionCall revertBlocks(BigInteger _newLastBlock) { - final Function function = new Function( - FUNC_REVERTBLOCKS, - Arrays.asList(new org.web3j.abi.datatypes.generated.Uint256(_newLastBlock)), - Collections.>emptyList()); - return executeRemoteCallTransaction(function); - } - - public RemoteFunctionCall securityCouncilUpgradeApprove(byte[] _upgradeProposalHash) { - final Function function = new Function( - FUNC_SECURITYCOUNCILUPGRADEAPPROVE, - Arrays.asList(new org.web3j.abi.datatypes.generated.Bytes32(_upgradeProposalHash)), - Collections.>emptyList()); - return executeRemoteCallTransaction(function); - } - - public RemoteFunctionCall serializeL2Transaction(BigInteger _txId, BigInteger _l2Value, String _sender, String _contractAddressL2, byte[] _calldata, BigInteger _l2GasLimit, BigInteger _l2GasPerPubdataByteLimit, List _factoryDeps, BigInteger _toMint, String _refundRecipient) { - final Function function = new Function(FUNC_SERIALIZEL2TRANSACTION, - Arrays.asList(new org.web3j.abi.datatypes.generated.Uint256(_txId), - new org.web3j.abi.datatypes.generated.Uint256(_l2Value), - new org.web3j.abi.datatypes.Address(_sender), - new org.web3j.abi.datatypes.Address(_contractAddressL2), - new org.web3j.abi.datatypes.DynamicBytes(_calldata), - new org.web3j.abi.datatypes.generated.Uint256(_l2GasLimit), - new org.web3j.abi.datatypes.generated.Uint256(_l2GasPerPubdataByteLimit), - new org.web3j.abi.datatypes.DynamicArray( - org.web3j.abi.datatypes.DynamicBytes.class, - org.web3j.abi.Utils.typeMap(_factoryDeps, org.web3j.abi.datatypes.DynamicBytes.class)), - new org.web3j.abi.datatypes.generated.Uint256(_toMint), - new org.web3j.abi.datatypes.Address(_refundRecipient)), - Arrays.>asList(new TypeReference() {})); - return executeRemoteCallSingleValueReturn(function, L2CanonicalTransaction.class); - } - - public RemoteFunctionCall setL2BootloaderBytecodeHash(byte[] _l2BootloaderBytecodeHash) { - final Function function = new Function( - FUNC_SETL2BOOTLOADERBYTECODEHASH, - Arrays.asList(new org.web3j.abi.datatypes.generated.Bytes32(_l2BootloaderBytecodeHash)), - Collections.>emptyList()); - return executeRemoteCallTransaction(function); - } - - public RemoteFunctionCall setL2DefaultAccountBytecodeHash(byte[] _l2DefaultAccountBytecodeHash) { - final Function function = new Function( - FUNC_SETL2DEFAULTACCOUNTBYTECODEHASH, - Arrays.asList(new org.web3j.abi.datatypes.generated.Bytes32(_l2DefaultAccountBytecodeHash)), - Collections.>emptyList()); - return executeRemoteCallTransaction(function); - } - - public RemoteFunctionCall setPendingGovernor(String _newPendingGovernor) { - final Function function = new Function( - FUNC_SETPENDINGGOVERNOR, - Arrays.asList(new org.web3j.abi.datatypes.Address(_newPendingGovernor)), - Collections.>emptyList()); - return executeRemoteCallTransaction(function); - } - - public RemoteFunctionCall setPorterAvailability(Boolean _zkPorterIsAvailable) { - final Function function = new Function( - FUNC_SETPORTERAVAILABILITY, - Arrays.asList(new org.web3j.abi.datatypes.Bool(_zkPorterIsAvailable)), - Collections.>emptyList()); - return executeRemoteCallTransaction(function); - } - - public RemoteFunctionCall setPriorityTxMaxGasLimit(BigInteger _newPriorityTxMaxGasLimit) { - final Function function = new Function( - FUNC_SETPRIORITYTXMAXGASLIMIT, - Arrays.asList(new org.web3j.abi.datatypes.generated.Uint256(_newPriorityTxMaxGasLimit)), - Collections.>emptyList()); - return executeRemoteCallTransaction(function); - } - - public RemoteFunctionCall setValidator(String _validator, Boolean _active) { - final Function function = new Function( - FUNC_SETVALIDATOR, - Arrays.asList(new org.web3j.abi.datatypes.Address(_validator), - new org.web3j.abi.datatypes.Bool(_active)), - Collections.>emptyList()); - return executeRemoteCallTransaction(function); - } - - public RemoteFunctionCall setVerifier(String _newVerifier) { - final Function function = new Function( - FUNC_SETVERIFIER, - Arrays.asList(new org.web3j.abi.datatypes.Address(_newVerifier)), - Collections.>emptyList()); - return executeRemoteCallTransaction(function); - } - - public RemoteFunctionCall setVerifierParams(VerifierParams _newVerifierParams) { - final Function function = new Function( - FUNC_SETVERIFIERPARAMS, - Arrays.asList(_newVerifierParams), - Collections.>emptyList()); - return executeRemoteCallTransaction(function); - } - - public RemoteFunctionCall storedBlockHash(BigInteger _blockNumber) { - final Function function = new Function(FUNC_STOREDBLOCKHASH, - Arrays.asList(new org.web3j.abi.datatypes.generated.Uint256(_blockNumber)), - Arrays.>asList(new TypeReference() {})); - return executeRemoteCallSingleValueReturn(function, byte[].class); - } - - public RemoteFunctionCall unfreezeDiamond() { - final Function function = new Function( - FUNC_UNFREEZEDIAMOND, - Arrays.asList(), - Collections.>emptyList()); - return executeRemoteCallTransaction(function); - } - - public RemoteFunctionCall upgradeProposalHash(DiamondCutData _diamondCut, BigInteger _proposalId, byte[] _salt) { - final Function function = new Function(FUNC_UPGRADEPROPOSALHASH, - Arrays.asList(_diamondCut, - new org.web3j.abi.datatypes.generated.Uint256(_proposalId), - new org.web3j.abi.datatypes.generated.Bytes32(_salt)), - Arrays.>asList(new TypeReference() {})); - return executeRemoteCallSingleValueReturn(function, byte[].class); - } - - @Deprecated - public static ZkSyncContract load(String contractAddress, Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) { - return new ZkSyncContract(contractAddress, web3j, credentials, gasPrice, gasLimit); - } - - @Deprecated - public static ZkSyncContract load(String contractAddress, Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit) { - return new ZkSyncContract(contractAddress, web3j, transactionManager, gasPrice, gasLimit); - } - - public static ZkSyncContract load(String contractAddress, Web3j web3j, Credentials credentials, ContractGasProvider contractGasProvider) { - return new ZkSyncContract(contractAddress, web3j, credentials, contractGasProvider); - } - - public static ZkSyncContract load(String contractAddress, Web3j web3j, TransactionManager transactionManager, ContractGasProvider contractGasProvider) { - return new ZkSyncContract(contractAddress, web3j, transactionManager, contractGasProvider); - } - - public static RemoteCall deploy(Web3j web3j, Credentials credentials, ContractGasProvider contractGasProvider) { - return deployRemoteCall(ZkSyncContract.class, web3j, credentials, contractGasProvider, BINARY, ""); - } - - @Deprecated - public static RemoteCall deploy(Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) { - return deployRemoteCall(ZkSyncContract.class, web3j, credentials, gasPrice, gasLimit, BINARY, ""); - } - - public static RemoteCall deploy(Web3j web3j, TransactionManager transactionManager, ContractGasProvider contractGasProvider) { - return deployRemoteCall(ZkSyncContract.class, web3j, transactionManager, contractGasProvider, BINARY, ""); - } - - @Deprecated - public static RemoteCall deploy(Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit) { - return deployRemoteCall(ZkSyncContract.class, web3j, transactionManager, gasPrice, gasLimit, BINARY, ""); - } - - protected String getStaticDeployedAddress(String networkId) { - return _addresses.get(networkId); - } - - public static String getPreviouslyDeployedAddress(String networkId) { - return _addresses.get(networkId); - } - - public static class L2CanonicalTransaction extends DynamicStruct { - public BigInteger txType; - - public BigInteger from; - - public BigInteger to; - - public BigInteger gasLimit; - - public BigInteger gasPerPubdataByteLimit; - - public BigInteger maxFeePerGas; - - public BigInteger maxPriorityFeePerGas; - - public BigInteger paymaster; - - public BigInteger nonce; - - public BigInteger value; - - public List reserved; - - public byte[] data; - - public byte[] signature; - - public List factoryDeps; - - public byte[] paymasterInput; - - public byte[] reservedDynamic; - - public L2CanonicalTransaction(BigInteger txType, BigInteger from, BigInteger to, BigInteger gasLimit, BigInteger gasPerPubdataByteLimit, BigInteger maxFeePerGas, BigInteger maxPriorityFeePerGas, BigInteger paymaster, BigInteger nonce, BigInteger value, List reserved, byte[] data, byte[] signature, List factoryDeps, byte[] paymasterInput, byte[] reservedDynamic) { - super(new org.web3j.abi.datatypes.generated.Uint256(txType), - new org.web3j.abi.datatypes.generated.Uint256(from), - new org.web3j.abi.datatypes.generated.Uint256(to), - new org.web3j.abi.datatypes.generated.Uint256(gasLimit), - new org.web3j.abi.datatypes.generated.Uint256(gasPerPubdataByteLimit), - new org.web3j.abi.datatypes.generated.Uint256(maxFeePerGas), - new org.web3j.abi.datatypes.generated.Uint256(maxPriorityFeePerGas), - new org.web3j.abi.datatypes.generated.Uint256(paymaster), - new org.web3j.abi.datatypes.generated.Uint256(nonce), - new org.web3j.abi.datatypes.generated.Uint256(value), - new org.web3j.abi.datatypes.generated.StaticArray4( - org.web3j.abi.datatypes.generated.Uint256.class, - org.web3j.abi.Utils.typeMap(reserved, org.web3j.abi.datatypes.generated.Uint256.class)), - new org.web3j.abi.datatypes.DynamicBytes(data), - new org.web3j.abi.datatypes.DynamicBytes(signature), - new org.web3j.abi.datatypes.DynamicArray( - org.web3j.abi.datatypes.generated.Uint256.class, - org.web3j.abi.Utils.typeMap(factoryDeps, org.web3j.abi.datatypes.generated.Uint256.class)), - new org.web3j.abi.datatypes.DynamicBytes(paymasterInput), - new org.web3j.abi.datatypes.DynamicBytes(reservedDynamic)); - this.txType = txType; - this.from = from; - this.to = to; - this.gasLimit = gasLimit; - this.gasPerPubdataByteLimit = gasPerPubdataByteLimit; - this.maxFeePerGas = maxFeePerGas; - this.maxPriorityFeePerGas = maxPriorityFeePerGas; - this.paymaster = paymaster; - this.nonce = nonce; - this.value = value; - this.reserved = reserved; - this.data = data; - this.signature = signature; - this.factoryDeps = factoryDeps; - this.paymasterInput = paymasterInput; - this.reservedDynamic = reservedDynamic; - } - - public L2CanonicalTransaction(Uint256 txType, Uint256 from, Uint256 to, Uint256 gasLimit, Uint256 gasPerPubdataByteLimit, Uint256 maxFeePerGas, Uint256 maxPriorityFeePerGas, Uint256 paymaster, Uint256 nonce, Uint256 value, StaticArray4 reserved, DynamicBytes data, DynamicBytes signature, DynamicArray factoryDeps, DynamicBytes paymasterInput, DynamicBytes reservedDynamic) { - super(txType, from, to, gasLimit, gasPerPubdataByteLimit, maxFeePerGas, maxPriorityFeePerGas, paymaster, nonce, value, reserved, data, signature, factoryDeps, paymasterInput, reservedDynamic); - this.txType = txType.getValue(); - this.from = from.getValue(); - this.to = to.getValue(); - this.gasLimit = gasLimit.getValue(); - this.gasPerPubdataByteLimit = gasPerPubdataByteLimit.getValue(); - this.maxFeePerGas = maxFeePerGas.getValue(); - this.maxPriorityFeePerGas = maxPriorityFeePerGas.getValue(); - this.paymaster = paymaster.getValue(); - this.nonce = nonce.getValue(); - this.value = value.getValue(); - this.reserved = reserved.getValue().stream().map(v -> v.getValue()).collect(Collectors.toList()); - this.data = data.getValue(); - this.signature = signature.getValue(); - this.factoryDeps = factoryDeps.getValue().stream().map(v -> v.getValue()).collect(Collectors.toList()); - this.paymasterInput = paymasterInput.getValue(); - this.reservedDynamic = reservedDynamic.getValue(); - } - } - - public static class VerifierParams extends StaticStruct { - public byte[] recursionNodeLevelVkHash; - - public byte[] recursionLeafLevelVkHash; - - public byte[] recursionCircuitsSetVksHash; - - public VerifierParams(byte[] recursionNodeLevelVkHash, byte[] recursionLeafLevelVkHash, byte[] recursionCircuitsSetVksHash) { - super(new org.web3j.abi.datatypes.generated.Bytes32(recursionNodeLevelVkHash), - new org.web3j.abi.datatypes.generated.Bytes32(recursionLeafLevelVkHash), - new org.web3j.abi.datatypes.generated.Bytes32(recursionCircuitsSetVksHash)); - this.recursionNodeLevelVkHash = recursionNodeLevelVkHash; - this.recursionLeafLevelVkHash = recursionLeafLevelVkHash; - this.recursionCircuitsSetVksHash = recursionCircuitsSetVksHash; - } - - public VerifierParams(Bytes32 recursionNodeLevelVkHash, Bytes32 recursionLeafLevelVkHash, Bytes32 recursionCircuitsSetVksHash) { - super(recursionNodeLevelVkHash, recursionLeafLevelVkHash, recursionCircuitsSetVksHash); - this.recursionNodeLevelVkHash = recursionNodeLevelVkHash.getValue(); - this.recursionLeafLevelVkHash = recursionLeafLevelVkHash.getValue(); - this.recursionCircuitsSetVksHash = recursionCircuitsSetVksHash.getValue(); - } - } - - public static class FacetCut extends DynamicStruct { - public String facet; - - public BigInteger action; - - public Boolean isFreezable; - - public List selectors; - - public FacetCut(String facet, BigInteger action, Boolean isFreezable, List selectors) { - super(new org.web3j.abi.datatypes.Address(facet), - new org.web3j.abi.datatypes.generated.Uint8(action), - new org.web3j.abi.datatypes.Bool(isFreezable), - new org.web3j.abi.datatypes.DynamicArray( - org.web3j.abi.datatypes.generated.Bytes4.class, - org.web3j.abi.Utils.typeMap(selectors, org.web3j.abi.datatypes.generated.Bytes4.class))); - this.facet = facet; - this.action = action; - this.isFreezable = isFreezable; - this.selectors = selectors; - } - - public FacetCut(Address facet, Uint8 action, Bool isFreezable, DynamicArray selectors) { - super(facet, action, isFreezable, selectors); - this.facet = facet.getValue(); - this.action = action.getValue(); - this.isFreezable = isFreezable.getValue(); - this.selectors = selectors.getValue().stream().map(v -> v.getValue()).collect(Collectors.toList()); - } - } - - public static class StoredBlockInfo extends StaticStruct { - public BigInteger blockNumber; - - public byte[] blockHash; - - public BigInteger indexRepeatedStorageChanges; - - public BigInteger numberOfLayer1Txs; - - public byte[] priorityOperationsHash; - - public byte[] l2LogsTreeRoot; - - public BigInteger timestamp; - - public byte[] commitment; - - public StoredBlockInfo(BigInteger blockNumber, byte[] blockHash, BigInteger indexRepeatedStorageChanges, BigInteger numberOfLayer1Txs, byte[] priorityOperationsHash, byte[] l2LogsTreeRoot, BigInteger timestamp, byte[] commitment) { - super(new org.web3j.abi.datatypes.generated.Uint64(blockNumber), - new org.web3j.abi.datatypes.generated.Bytes32(blockHash), - new org.web3j.abi.datatypes.generated.Uint64(indexRepeatedStorageChanges), - new org.web3j.abi.datatypes.generated.Uint256(numberOfLayer1Txs), - new org.web3j.abi.datatypes.generated.Bytes32(priorityOperationsHash), - new org.web3j.abi.datatypes.generated.Bytes32(l2LogsTreeRoot), - new org.web3j.abi.datatypes.generated.Uint256(timestamp), - new org.web3j.abi.datatypes.generated.Bytes32(commitment)); - this.blockNumber = blockNumber; - this.blockHash = blockHash; - this.indexRepeatedStorageChanges = indexRepeatedStorageChanges; - this.numberOfLayer1Txs = numberOfLayer1Txs; - this.priorityOperationsHash = priorityOperationsHash; - this.l2LogsTreeRoot = l2LogsTreeRoot; - this.timestamp = timestamp; - this.commitment = commitment; - } - - public StoredBlockInfo(Uint64 blockNumber, Bytes32 blockHash, Uint64 indexRepeatedStorageChanges, Uint256 numberOfLayer1Txs, Bytes32 priorityOperationsHash, Bytes32 l2LogsTreeRoot, Uint256 timestamp, Bytes32 commitment) { - super(blockNumber, blockHash, indexRepeatedStorageChanges, numberOfLayer1Txs, priorityOperationsHash, l2LogsTreeRoot, timestamp, commitment); - this.blockNumber = blockNumber.getValue(); - this.blockHash = blockHash.getValue(); - this.indexRepeatedStorageChanges = indexRepeatedStorageChanges.getValue(); - this.numberOfLayer1Txs = numberOfLayer1Txs.getValue(); - this.priorityOperationsHash = priorityOperationsHash.getValue(); - this.l2LogsTreeRoot = l2LogsTreeRoot.getValue(); - this.timestamp = timestamp.getValue(); - this.commitment = commitment.getValue(); - } - } - - public static class CommitBlockInfo extends DynamicStruct { - public BigInteger blockNumber; - - public BigInteger timestamp; - - public BigInteger indexRepeatedStorageChanges; - - public byte[] newStateRoot; - - public BigInteger numberOfLayer1Txs; - - public byte[] l2LogsTreeRoot; - - public byte[] priorityOperationsHash; - - public byte[] initialStorageChanges; - - public byte[] repeatedStorageChanges; - - public byte[] l2Logs; - - public List l2ArbitraryLengthMessages; - - public List factoryDeps; - - public CommitBlockInfo(BigInteger blockNumber, BigInteger timestamp, BigInteger indexRepeatedStorageChanges, byte[] newStateRoot, BigInteger numberOfLayer1Txs, byte[] l2LogsTreeRoot, byte[] priorityOperationsHash, byte[] initialStorageChanges, byte[] repeatedStorageChanges, byte[] l2Logs, List l2ArbitraryLengthMessages, List factoryDeps) { - super(new org.web3j.abi.datatypes.generated.Uint64(blockNumber), - new org.web3j.abi.datatypes.generated.Uint64(timestamp), - new org.web3j.abi.datatypes.generated.Uint64(indexRepeatedStorageChanges), - new org.web3j.abi.datatypes.generated.Bytes32(newStateRoot), - new org.web3j.abi.datatypes.generated.Uint256(numberOfLayer1Txs), - new org.web3j.abi.datatypes.generated.Bytes32(l2LogsTreeRoot), - new org.web3j.abi.datatypes.generated.Bytes32(priorityOperationsHash), - new org.web3j.abi.datatypes.DynamicBytes(initialStorageChanges), - new org.web3j.abi.datatypes.DynamicBytes(repeatedStorageChanges), - new org.web3j.abi.datatypes.DynamicBytes(l2Logs), - new org.web3j.abi.datatypes.DynamicArray( - org.web3j.abi.datatypes.DynamicBytes.class, - org.web3j.abi.Utils.typeMap(l2ArbitraryLengthMessages, org.web3j.abi.datatypes.DynamicBytes.class)), - new org.web3j.abi.datatypes.DynamicArray( - org.web3j.abi.datatypes.DynamicBytes.class, - org.web3j.abi.Utils.typeMap(factoryDeps, org.web3j.abi.datatypes.DynamicBytes.class))); - this.blockNumber = blockNumber; - this.timestamp = timestamp; - this.indexRepeatedStorageChanges = indexRepeatedStorageChanges; - this.newStateRoot = newStateRoot; - this.numberOfLayer1Txs = numberOfLayer1Txs; - this.l2LogsTreeRoot = l2LogsTreeRoot; - this.priorityOperationsHash = priorityOperationsHash; - this.initialStorageChanges = initialStorageChanges; - this.repeatedStorageChanges = repeatedStorageChanges; - this.l2Logs = l2Logs; - this.l2ArbitraryLengthMessages = l2ArbitraryLengthMessages; - this.factoryDeps = factoryDeps; - } - - public CommitBlockInfo(Uint64 blockNumber, Uint64 timestamp, Uint64 indexRepeatedStorageChanges, Bytes32 newStateRoot, Uint256 numberOfLayer1Txs, Bytes32 l2LogsTreeRoot, Bytes32 priorityOperationsHash, DynamicBytes initialStorageChanges, DynamicBytes repeatedStorageChanges, DynamicBytes l2Logs, DynamicArray l2ArbitraryLengthMessages, DynamicArray factoryDeps) { - super(blockNumber, timestamp, indexRepeatedStorageChanges, newStateRoot, numberOfLayer1Txs, l2LogsTreeRoot, priorityOperationsHash, initialStorageChanges, repeatedStorageChanges, l2Logs, l2ArbitraryLengthMessages, factoryDeps); - this.blockNumber = blockNumber.getValue(); - this.timestamp = timestamp.getValue(); - this.indexRepeatedStorageChanges = indexRepeatedStorageChanges.getValue(); - this.newStateRoot = newStateRoot.getValue(); - this.numberOfLayer1Txs = numberOfLayer1Txs.getValue(); - this.l2LogsTreeRoot = l2LogsTreeRoot.getValue(); - this.priorityOperationsHash = priorityOperationsHash.getValue(); - this.initialStorageChanges = initialStorageChanges.getValue(); - this.repeatedStorageChanges = repeatedStorageChanges.getValue(); - this.l2Logs = l2Logs.getValue(); - this.l2ArbitraryLengthMessages = l2ArbitraryLengthMessages.getValue().stream().map(v -> v.getValue()).collect(Collectors.toList()); - this.factoryDeps = factoryDeps.getValue().stream().map(v -> v.getValue()).collect(Collectors.toList()); - } - } + return executeRemoteCallSingleValueReturn(function, Boolean.class); + } + + public RemoteFunctionCall isDiamondStorageFrozen() { + final Function function = + new Function( + FUNC_ISDIAMONDSTORAGEFROZEN, + Arrays.asList(), + Arrays.>asList(new TypeReference() {})); + return executeRemoteCallSingleValueReturn(function, Boolean.class); + } + + public RemoteFunctionCall isEthWithdrawalFinalized( + BigInteger _l2BlockNumber, BigInteger _l2MessageIndex) { + final Function function = + new Function( + FUNC_ISETHWITHDRAWALFINALIZED, + Arrays.asList( + new org.web3j.abi.datatypes.generated.Uint256(_l2BlockNumber), + new org.web3j.abi.datatypes.generated.Uint256(_l2MessageIndex)), + Arrays.>asList(new TypeReference() {})); + return executeRemoteCallSingleValueReturn(function, Boolean.class); + } + + public RemoteFunctionCall isFacetFreezable(String _facet) { + final Function function = + new Function( + FUNC_ISFACETFREEZABLE, + Arrays.asList(new org.web3j.abi.datatypes.Address(_facet)), + Arrays.>asList(new TypeReference() {})); + return executeRemoteCallSingleValueReturn(function, Boolean.class); + } + + public RemoteFunctionCall isFunctionFreezable(byte[] _selector) { + final Function function = + new Function( + FUNC_ISFUNCTIONFREEZABLE, + Arrays.asList(new org.web3j.abi.datatypes.generated.Bytes4(_selector)), + Arrays.>asList(new TypeReference() {})); + return executeRemoteCallSingleValueReturn(function, Boolean.class); + } + + public RemoteFunctionCall isValidator(String _address) { + final Function function = + new Function( + FUNC_ISVALIDATOR, + Arrays.asList(new org.web3j.abi.datatypes.Address(_address)), + Arrays.>asList(new TypeReference() {})); + return executeRemoteCallSingleValueReturn(function, Boolean.class); + } + + public RemoteFunctionCall l2LogsRootHash(BigInteger _blockNumber) { + final Function function = + new Function( + FUNC_L2LOGSROOTHASH, + Arrays.asList(new org.web3j.abi.datatypes.generated.Uint256(_blockNumber)), + Arrays.>asList(new TypeReference() {})); + return executeRemoteCallSingleValueReturn(function, byte[].class); + } + + public RemoteFunctionCall l2TransactionBaseCost( + BigInteger _gasPrice, BigInteger _l2GasLimit, BigInteger _l2GasPerPubdataByteLimit) { + final Function function = + new Function( + FUNC_L2TRANSACTIONBASECOST, + Arrays.asList( + new org.web3j.abi.datatypes.generated.Uint256(_gasPrice), + new org.web3j.abi.datatypes.generated.Uint256(_l2GasLimit), + new org.web3j.abi.datatypes.generated.Uint256(_l2GasPerPubdataByteLimit)), + Arrays.>asList(new TypeReference() {})); + return executeRemoteCallSingleValueReturn(function, BigInteger.class); + } + + public RemoteFunctionCall priorityQueueFrontOperation() { + final Function function = + new Function( + FUNC_PRIORITYQUEUEFRONTOPERATION, + Arrays.asList(), + Arrays.>asList(new TypeReference() {})); + return executeRemoteCallSingleValueReturn(function, PriorityOperation.class); + } + + public RemoteFunctionCall proposeShadowUpgrade( + byte[] _proposalHash, BigInteger _proposalId) { + final Function function = + new Function( + FUNC_PROPOSESHADOWUPGRADE, + Arrays.asList( + new org.web3j.abi.datatypes.generated.Bytes32(_proposalHash), + new org.web3j.abi.datatypes.generated.Uint40(_proposalId)), + Collections.>emptyList()); + return executeRemoteCallTransaction(function); + } + + public RemoteFunctionCall proposeTransparentUpgrade( + DiamondCutData _diamondCut, BigInteger _proposalId) { + final Function function = + new Function( + FUNC_PROPOSETRANSPARENTUPGRADE, + Arrays.asList( + _diamondCut, new org.web3j.abi.datatypes.generated.Uint40(_proposalId)), + Collections.>emptyList()); + return executeRemoteCallTransaction(function); + } + + public RemoteFunctionCall proveBlocks( + StoredBlockInfo _prevBlock, List _committedBlocks, ProofInput _proof) { + final Function function = + new Function( + FUNC_PROVEBLOCKS, + Arrays.asList( + _prevBlock, + new org.web3j.abi.datatypes.DynamicArray( + StoredBlockInfo.class, _committedBlocks), + _proof), + Collections.>emptyList()); + return executeRemoteCallTransaction(function); + } + + public RemoteFunctionCall proveL1ToL2TransactionStatus( + byte[] _l2TxHash, + BigInteger _l2BlockNumber, + BigInteger _l2MessageIndex, + BigInteger _l2TxNumberInBlock, + List _merkleProof, + BigInteger _status) { + final Function function = + new Function( + FUNC_PROVEL1TOL2TRANSACTIONSTATUS, + Arrays.asList( + new org.web3j.abi.datatypes.generated.Bytes32(_l2TxHash), + new org.web3j.abi.datatypes.generated.Uint256(_l2BlockNumber), + new org.web3j.abi.datatypes.generated.Uint256(_l2MessageIndex), + new org.web3j.abi.datatypes.generated.Uint16(_l2TxNumberInBlock), + new org.web3j.abi.datatypes.DynamicArray( + org.web3j.abi.datatypes.generated.Bytes32.class, + org.web3j.abi.Utils.typeMap( + _merkleProof, org.web3j.abi.datatypes.generated.Bytes32.class)), + new org.web3j.abi.datatypes.generated.Uint8(_status)), + Arrays.>asList(new TypeReference() {})); + return executeRemoteCallSingleValueReturn(function, Boolean.class); + } + + public RemoteFunctionCall proveL2LogInclusion( + BigInteger _blockNumber, BigInteger _index, L2Log _log, List _proof) { + final Function function = + new Function( + FUNC_PROVEL2LOGINCLUSION, + Arrays.asList( + new org.web3j.abi.datatypes.generated.Uint256(_blockNumber), + new org.web3j.abi.datatypes.generated.Uint256(_index), + _log, + new org.web3j.abi.datatypes.DynamicArray( + org.web3j.abi.datatypes.generated.Bytes32.class, + org.web3j.abi.Utils.typeMap( + _proof, org.web3j.abi.datatypes.generated.Bytes32.class))), + Arrays.>asList(new TypeReference() {})); + return executeRemoteCallSingleValueReturn(function, Boolean.class); + } + + public RemoteFunctionCall proveL2MessageInclusion( + BigInteger _blockNumber, BigInteger _index, L2Message _message, List _proof) { + final Function function = + new Function( + FUNC_PROVEL2MESSAGEINCLUSION, + Arrays.asList( + new org.web3j.abi.datatypes.generated.Uint256(_blockNumber), + new org.web3j.abi.datatypes.generated.Uint256(_index), + _message, + new org.web3j.abi.datatypes.DynamicArray( + org.web3j.abi.datatypes.generated.Bytes32.class, + org.web3j.abi.Utils.typeMap( + _proof, org.web3j.abi.datatypes.generated.Bytes32.class))), + Arrays.>asList(new TypeReference() {})); + return executeRemoteCallSingleValueReturn(function, Boolean.class); + } + + public RemoteFunctionCall requestL2Transaction( + String _contractL2, + BigInteger _l2Value, + byte[] _calldata, + BigInteger _l2GasLimit, + BigInteger _l2GasPerPubdataByteLimit, + List _factoryDeps, + String _refundRecipient, + BigInteger weiValue) { + final Function function = + new Function( + FUNC_REQUESTL2TRANSACTION, + Arrays.asList( + new org.web3j.abi.datatypes.Address(_contractL2), + new org.web3j.abi.datatypes.generated.Uint256(_l2Value), + new org.web3j.abi.datatypes.DynamicBytes(_calldata), + new org.web3j.abi.datatypes.generated.Uint256(_l2GasLimit), + new org.web3j.abi.datatypes.generated.Uint256(_l2GasPerPubdataByteLimit), + new org.web3j.abi.datatypes.DynamicArray( + org.web3j.abi.datatypes.DynamicBytes.class, + org.web3j.abi.Utils.typeMap( + _factoryDeps, org.web3j.abi.datatypes.DynamicBytes.class)), + new org.web3j.abi.datatypes.Address(_refundRecipient)), + Collections.>emptyList()); + return executeRemoteCallTransaction(function, weiValue); + } + + public RemoteFunctionCall revertBlocks(BigInteger _newLastBlock) { + final Function function = + new Function( + FUNC_REVERTBLOCKS, + Arrays.asList(new org.web3j.abi.datatypes.generated.Uint256(_newLastBlock)), + Collections.>emptyList()); + return executeRemoteCallTransaction(function); + } + + public RemoteFunctionCall securityCouncilUpgradeApprove( + byte[] _upgradeProposalHash) { + final Function function = + new Function( + FUNC_SECURITYCOUNCILUPGRADEAPPROVE, + Arrays.asList( + new org.web3j.abi.datatypes.generated.Bytes32(_upgradeProposalHash)), + Collections.>emptyList()); + return executeRemoteCallTransaction(function); + } + + public RemoteFunctionCall serializeL2Transaction( + BigInteger _txId, + BigInteger _l2Value, + String _sender, + String _contractAddressL2, + byte[] _calldata, + BigInteger _l2GasLimit, + BigInteger _l2GasPerPubdataByteLimit, + List _factoryDeps, + BigInteger _toMint, + String _refundRecipient) { + final Function function = + new Function( + FUNC_SERIALIZEL2TRANSACTION, + Arrays.asList( + new org.web3j.abi.datatypes.generated.Uint256(_txId), + new org.web3j.abi.datatypes.generated.Uint256(_l2Value), + new org.web3j.abi.datatypes.Address(_sender), + new org.web3j.abi.datatypes.Address(_contractAddressL2), + new org.web3j.abi.datatypes.DynamicBytes(_calldata), + new org.web3j.abi.datatypes.generated.Uint256(_l2GasLimit), + new org.web3j.abi.datatypes.generated.Uint256(_l2GasPerPubdataByteLimit), + new org.web3j.abi.datatypes.DynamicArray( + org.web3j.abi.datatypes.DynamicBytes.class, + org.web3j.abi.Utils.typeMap( + _factoryDeps, org.web3j.abi.datatypes.DynamicBytes.class)), + new org.web3j.abi.datatypes.generated.Uint256(_toMint), + new org.web3j.abi.datatypes.Address(_refundRecipient)), + Arrays.>asList(new TypeReference() {})); + return executeRemoteCallSingleValueReturn(function, L2CanonicalTransaction.class); + } + + public RemoteFunctionCall setL2BootloaderBytecodeHash( + byte[] _l2BootloaderBytecodeHash) { + final Function function = + new Function( + FUNC_SETL2BOOTLOADERBYTECODEHASH, + Arrays.asList( + new org.web3j.abi.datatypes.generated.Bytes32(_l2BootloaderBytecodeHash)), + Collections.>emptyList()); + return executeRemoteCallTransaction(function); + } + + public RemoteFunctionCall setL2DefaultAccountBytecodeHash( + byte[] _l2DefaultAccountBytecodeHash) { + final Function function = + new Function( + FUNC_SETL2DEFAULTACCOUNTBYTECODEHASH, + Arrays.asList( + new org.web3j.abi.datatypes.generated.Bytes32(_l2DefaultAccountBytecodeHash)), + Collections.>emptyList()); + return executeRemoteCallTransaction(function); + } + + public RemoteFunctionCall setPendingGovernor(String _newPendingGovernor) { + final Function function = + new Function( + FUNC_SETPENDINGGOVERNOR, + Arrays.asList(new org.web3j.abi.datatypes.Address(_newPendingGovernor)), + Collections.>emptyList()); + return executeRemoteCallTransaction(function); + } + + public RemoteFunctionCall setPorterAvailability( + Boolean _zkPorterIsAvailable) { + final Function function = + new Function( + FUNC_SETPORTERAVAILABILITY, + Arrays.asList(new org.web3j.abi.datatypes.Bool(_zkPorterIsAvailable)), + Collections.>emptyList()); + return executeRemoteCallTransaction(function); + } + + public RemoteFunctionCall setPriorityTxMaxGasLimit( + BigInteger _newPriorityTxMaxGasLimit) { + final Function function = + new Function( + FUNC_SETPRIORITYTXMAXGASLIMIT, + Arrays.asList( + new org.web3j.abi.datatypes.generated.Uint256(_newPriorityTxMaxGasLimit)), + Collections.>emptyList()); + return executeRemoteCallTransaction(function); + } + + public RemoteFunctionCall setValidator(String _validator, Boolean _active) { + final Function function = + new Function( + FUNC_SETVALIDATOR, + Arrays.asList( + new org.web3j.abi.datatypes.Address(_validator), + new org.web3j.abi.datatypes.Bool(_active)), + Collections.>emptyList()); + return executeRemoteCallTransaction(function); + } + + public RemoteFunctionCall setVerifier(String _newVerifier) { + final Function function = + new Function( + FUNC_SETVERIFIER, + Arrays.asList(new org.web3j.abi.datatypes.Address(_newVerifier)), + Collections.>emptyList()); + return executeRemoteCallTransaction(function); + } + + public RemoteFunctionCall setVerifierParams( + VerifierParams _newVerifierParams) { + final Function function = + new Function( + FUNC_SETVERIFIERPARAMS, + Arrays.asList(_newVerifierParams), + Collections.>emptyList()); + return executeRemoteCallTransaction(function); + } + + public RemoteFunctionCall storedBlockHash(BigInteger _blockNumber) { + final Function function = + new Function( + FUNC_STOREDBLOCKHASH, + Arrays.asList(new org.web3j.abi.datatypes.generated.Uint256(_blockNumber)), + Arrays.>asList(new TypeReference() {})); + return executeRemoteCallSingleValueReturn(function, byte[].class); + } + + public RemoteFunctionCall unfreezeDiamond() { + final Function function = + new Function( + FUNC_UNFREEZEDIAMOND, Arrays.asList(), Collections.>emptyList()); + return executeRemoteCallTransaction(function); + } + + public RemoteFunctionCall upgradeProposalHash( + DiamondCutData _diamondCut, BigInteger _proposalId, byte[] _salt) { + final Function function = + new Function( + FUNC_UPGRADEPROPOSALHASH, + Arrays.asList( + _diamondCut, + new org.web3j.abi.datatypes.generated.Uint256(_proposalId), + new org.web3j.abi.datatypes.generated.Bytes32(_salt)), + Arrays.>asList(new TypeReference() {})); + return executeRemoteCallSingleValueReturn(function, byte[].class); + } + + @Deprecated + public static ZkSyncContract load( + String contractAddress, + Web3j web3j, + Credentials credentials, + BigInteger gasPrice, + BigInteger gasLimit) { + return new ZkSyncContract(contractAddress, web3j, credentials, gasPrice, gasLimit); + } + + @Deprecated + public static ZkSyncContract load( + String contractAddress, + Web3j web3j, + TransactionManager transactionManager, + BigInteger gasPrice, + BigInteger gasLimit) { + return new ZkSyncContract(contractAddress, web3j, transactionManager, gasPrice, gasLimit); + } + + public static ZkSyncContract load( + String contractAddress, + Web3j web3j, + Credentials credentials, + ContractGasProvider contractGasProvider) { + return new ZkSyncContract(contractAddress, web3j, credentials, contractGasProvider); + } + + public static ZkSyncContract load( + String contractAddress, + Web3j web3j, + TransactionManager transactionManager, + ContractGasProvider contractGasProvider) { + return new ZkSyncContract(contractAddress, web3j, transactionManager, contractGasProvider); + } + + public static RemoteCall deploy( + Web3j web3j, Credentials credentials, ContractGasProvider contractGasProvider) { + return deployRemoteCall( + ZkSyncContract.class, web3j, credentials, contractGasProvider, BINARY, ""); + } + + @Deprecated + public static RemoteCall deploy( + Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) { + return deployRemoteCall( + ZkSyncContract.class, web3j, credentials, gasPrice, gasLimit, BINARY, ""); + } + + public static RemoteCall deploy( + Web3j web3j, TransactionManager transactionManager, ContractGasProvider contractGasProvider) { + return deployRemoteCall( + ZkSyncContract.class, web3j, transactionManager, contractGasProvider, BINARY, ""); + } + + @Deprecated + public static RemoteCall deploy( + Web3j web3j, + TransactionManager transactionManager, + BigInteger gasPrice, + BigInteger gasLimit) { + return deployRemoteCall( + ZkSyncContract.class, web3j, transactionManager, gasPrice, gasLimit, BINARY, ""); + } + + protected String getStaticDeployedAddress(String networkId) { + return _addresses.get(networkId); + } + + public static String getPreviouslyDeployedAddress(String networkId) { + return _addresses.get(networkId); + } + + public static class L2CanonicalTransaction extends DynamicStruct { + public BigInteger txType; + + public BigInteger from; + + public BigInteger to; + + public BigInteger gasLimit; + + public BigInteger gasPerPubdataByteLimit; + + public BigInteger maxFeePerGas; + + public BigInteger maxPriorityFeePerGas; + + public BigInteger paymaster; + + public BigInteger nonce; + + public BigInteger value; + + public List reserved; + + public byte[] data; + + public byte[] signature; + + public List factoryDeps; + + public byte[] paymasterInput; + + public byte[] reservedDynamic; + + public L2CanonicalTransaction( + BigInteger txType, + BigInteger from, + BigInteger to, + BigInteger gasLimit, + BigInteger gasPerPubdataByteLimit, + BigInteger maxFeePerGas, + BigInteger maxPriorityFeePerGas, + BigInteger paymaster, + BigInteger nonce, + BigInteger value, + List reserved, + byte[] data, + byte[] signature, + List factoryDeps, + byte[] paymasterInput, + byte[] reservedDynamic) { + super( + new org.web3j.abi.datatypes.generated.Uint256(txType), + new org.web3j.abi.datatypes.generated.Uint256(from), + new org.web3j.abi.datatypes.generated.Uint256(to), + new org.web3j.abi.datatypes.generated.Uint256(gasLimit), + new org.web3j.abi.datatypes.generated.Uint256(gasPerPubdataByteLimit), + new org.web3j.abi.datatypes.generated.Uint256(maxFeePerGas), + new org.web3j.abi.datatypes.generated.Uint256(maxPriorityFeePerGas), + new org.web3j.abi.datatypes.generated.Uint256(paymaster), + new org.web3j.abi.datatypes.generated.Uint256(nonce), + new org.web3j.abi.datatypes.generated.Uint256(value), + new org.web3j.abi.datatypes.generated.StaticArray4< + org.web3j.abi.datatypes.generated.Uint256>( + org.web3j.abi.datatypes.generated.Uint256.class, + org.web3j.abi.Utils.typeMap( + reserved, org.web3j.abi.datatypes.generated.Uint256.class)), + new org.web3j.abi.datatypes.DynamicBytes(data), + new org.web3j.abi.datatypes.DynamicBytes(signature), + new org.web3j.abi.datatypes.DynamicArray( + org.web3j.abi.datatypes.generated.Uint256.class, + org.web3j.abi.Utils.typeMap( + factoryDeps, org.web3j.abi.datatypes.generated.Uint256.class)), + new org.web3j.abi.datatypes.DynamicBytes(paymasterInput), + new org.web3j.abi.datatypes.DynamicBytes(reservedDynamic)); + this.txType = txType; + this.from = from; + this.to = to; + this.gasLimit = gasLimit; + this.gasPerPubdataByteLimit = gasPerPubdataByteLimit; + this.maxFeePerGas = maxFeePerGas; + this.maxPriorityFeePerGas = maxPriorityFeePerGas; + this.paymaster = paymaster; + this.nonce = nonce; + this.value = value; + this.reserved = reserved; + this.data = data; + this.signature = signature; + this.factoryDeps = factoryDeps; + this.paymasterInput = paymasterInput; + this.reservedDynamic = reservedDynamic; + } + + public L2CanonicalTransaction( + Uint256 txType, + Uint256 from, + Uint256 to, + Uint256 gasLimit, + Uint256 gasPerPubdataByteLimit, + Uint256 maxFeePerGas, + Uint256 maxPriorityFeePerGas, + Uint256 paymaster, + Uint256 nonce, + Uint256 value, + StaticArray4 reserved, + DynamicBytes data, + DynamicBytes signature, + DynamicArray factoryDeps, + DynamicBytes paymasterInput, + DynamicBytes reservedDynamic) { + super( + txType, + from, + to, + gasLimit, + gasPerPubdataByteLimit, + maxFeePerGas, + maxPriorityFeePerGas, + paymaster, + nonce, + value, + reserved, + data, + signature, + factoryDeps, + paymasterInput, + reservedDynamic); + this.txType = txType.getValue(); + this.from = from.getValue(); + this.to = to.getValue(); + this.gasLimit = gasLimit.getValue(); + this.gasPerPubdataByteLimit = gasPerPubdataByteLimit.getValue(); + this.maxFeePerGas = maxFeePerGas.getValue(); + this.maxPriorityFeePerGas = maxPriorityFeePerGas.getValue(); + this.paymaster = paymaster.getValue(); + this.nonce = nonce.getValue(); + this.value = value.getValue(); + this.reserved = + reserved.getValue().stream().map(v -> v.getValue()).collect(Collectors.toList()); + this.data = data.getValue(); + this.signature = signature.getValue(); + this.factoryDeps = + factoryDeps.getValue().stream().map(v -> v.getValue()).collect(Collectors.toList()); + this.paymasterInput = paymasterInput.getValue(); + this.reservedDynamic = reservedDynamic.getValue(); + } + } + + public static class VerifierParams extends StaticStruct { + public byte[] recursionNodeLevelVkHash; + + public byte[] recursionLeafLevelVkHash; + + public byte[] recursionCircuitsSetVksHash; + + public VerifierParams( + byte[] recursionNodeLevelVkHash, + byte[] recursionLeafLevelVkHash, + byte[] recursionCircuitsSetVksHash) { + super( + new org.web3j.abi.datatypes.generated.Bytes32(recursionNodeLevelVkHash), + new org.web3j.abi.datatypes.generated.Bytes32(recursionLeafLevelVkHash), + new org.web3j.abi.datatypes.generated.Bytes32(recursionCircuitsSetVksHash)); + this.recursionNodeLevelVkHash = recursionNodeLevelVkHash; + this.recursionLeafLevelVkHash = recursionLeafLevelVkHash; + this.recursionCircuitsSetVksHash = recursionCircuitsSetVksHash; + } + + public VerifierParams( + Bytes32 recursionNodeLevelVkHash, + Bytes32 recursionLeafLevelVkHash, + Bytes32 recursionCircuitsSetVksHash) { + super(recursionNodeLevelVkHash, recursionLeafLevelVkHash, recursionCircuitsSetVksHash); + this.recursionNodeLevelVkHash = recursionNodeLevelVkHash.getValue(); + this.recursionLeafLevelVkHash = recursionLeafLevelVkHash.getValue(); + this.recursionCircuitsSetVksHash = recursionCircuitsSetVksHash.getValue(); + } + } + + public static class FacetCut extends DynamicStruct { + public String facet; + + public BigInteger action; + + public Boolean isFreezable; + + public List selectors; + + public FacetCut(String facet, BigInteger action, Boolean isFreezable, List selectors) { + super( + new org.web3j.abi.datatypes.Address(facet), + new org.web3j.abi.datatypes.generated.Uint8(action), + new org.web3j.abi.datatypes.Bool(isFreezable), + new org.web3j.abi.datatypes.DynamicArray( + org.web3j.abi.datatypes.generated.Bytes4.class, + org.web3j.abi.Utils.typeMap( + selectors, org.web3j.abi.datatypes.generated.Bytes4.class))); + this.facet = facet; + this.action = action; + this.isFreezable = isFreezable; + this.selectors = selectors; + } + + public FacetCut(Address facet, Uint8 action, Bool isFreezable, DynamicArray selectors) { + super(facet, action, isFreezable, selectors); + this.facet = facet.getValue(); + this.action = action.getValue(); + this.isFreezable = isFreezable.getValue(); + this.selectors = + selectors.getValue().stream().map(v -> v.getValue()).collect(Collectors.toList()); + } + } + + public static class StoredBlockInfo extends StaticStruct { + public BigInteger blockNumber; + + public byte[] blockHash; + + public BigInteger indexRepeatedStorageChanges; + + public BigInteger numberOfLayer1Txs; + + public byte[] priorityOperationsHash; + + public byte[] l2LogsTreeRoot; + + public BigInteger timestamp; + + public byte[] commitment; + + public StoredBlockInfo( + BigInteger blockNumber, + byte[] blockHash, + BigInteger indexRepeatedStorageChanges, + BigInteger numberOfLayer1Txs, + byte[] priorityOperationsHash, + byte[] l2LogsTreeRoot, + BigInteger timestamp, + byte[] commitment) { + super( + new org.web3j.abi.datatypes.generated.Uint64(blockNumber), + new org.web3j.abi.datatypes.generated.Bytes32(blockHash), + new org.web3j.abi.datatypes.generated.Uint64(indexRepeatedStorageChanges), + new org.web3j.abi.datatypes.generated.Uint256(numberOfLayer1Txs), + new org.web3j.abi.datatypes.generated.Bytes32(priorityOperationsHash), + new org.web3j.abi.datatypes.generated.Bytes32(l2LogsTreeRoot), + new org.web3j.abi.datatypes.generated.Uint256(timestamp), + new org.web3j.abi.datatypes.generated.Bytes32(commitment)); + this.blockNumber = blockNumber; + this.blockHash = blockHash; + this.indexRepeatedStorageChanges = indexRepeatedStorageChanges; + this.numberOfLayer1Txs = numberOfLayer1Txs; + this.priorityOperationsHash = priorityOperationsHash; + this.l2LogsTreeRoot = l2LogsTreeRoot; + this.timestamp = timestamp; + this.commitment = commitment; + } + + public StoredBlockInfo( + Uint64 blockNumber, + Bytes32 blockHash, + Uint64 indexRepeatedStorageChanges, + Uint256 numberOfLayer1Txs, + Bytes32 priorityOperationsHash, + Bytes32 l2LogsTreeRoot, + Uint256 timestamp, + Bytes32 commitment) { + super( + blockNumber, + blockHash, + indexRepeatedStorageChanges, + numberOfLayer1Txs, + priorityOperationsHash, + l2LogsTreeRoot, + timestamp, + commitment); + this.blockNumber = blockNumber.getValue(); + this.blockHash = blockHash.getValue(); + this.indexRepeatedStorageChanges = indexRepeatedStorageChanges.getValue(); + this.numberOfLayer1Txs = numberOfLayer1Txs.getValue(); + this.priorityOperationsHash = priorityOperationsHash.getValue(); + this.l2LogsTreeRoot = l2LogsTreeRoot.getValue(); + this.timestamp = timestamp.getValue(); + this.commitment = commitment.getValue(); + } + } + + public static class CommitBlockInfo extends DynamicStruct { + public BigInteger blockNumber; + + public BigInteger timestamp; + + public BigInteger indexRepeatedStorageChanges; + + public byte[] newStateRoot; + + public BigInteger numberOfLayer1Txs; + + public byte[] l2LogsTreeRoot; + + public byte[] priorityOperationsHash; + + public byte[] initialStorageChanges; + + public byte[] repeatedStorageChanges; + + public byte[] l2Logs; + + public List l2ArbitraryLengthMessages; + + public List factoryDeps; + + public CommitBlockInfo( + BigInteger blockNumber, + BigInteger timestamp, + BigInteger indexRepeatedStorageChanges, + byte[] newStateRoot, + BigInteger numberOfLayer1Txs, + byte[] l2LogsTreeRoot, + byte[] priorityOperationsHash, + byte[] initialStorageChanges, + byte[] repeatedStorageChanges, + byte[] l2Logs, + List l2ArbitraryLengthMessages, + List factoryDeps) { + super( + new org.web3j.abi.datatypes.generated.Uint64(blockNumber), + new org.web3j.abi.datatypes.generated.Uint64(timestamp), + new org.web3j.abi.datatypes.generated.Uint64(indexRepeatedStorageChanges), + new org.web3j.abi.datatypes.generated.Bytes32(newStateRoot), + new org.web3j.abi.datatypes.generated.Uint256(numberOfLayer1Txs), + new org.web3j.abi.datatypes.generated.Bytes32(l2LogsTreeRoot), + new org.web3j.abi.datatypes.generated.Bytes32(priorityOperationsHash), + new org.web3j.abi.datatypes.DynamicBytes(initialStorageChanges), + new org.web3j.abi.datatypes.DynamicBytes(repeatedStorageChanges), + new org.web3j.abi.datatypes.DynamicBytes(l2Logs), + new org.web3j.abi.datatypes.DynamicArray( + org.web3j.abi.datatypes.DynamicBytes.class, + org.web3j.abi.Utils.typeMap( + l2ArbitraryLengthMessages, org.web3j.abi.datatypes.DynamicBytes.class)), + new org.web3j.abi.datatypes.DynamicArray( + org.web3j.abi.datatypes.DynamicBytes.class, + org.web3j.abi.Utils.typeMap( + factoryDeps, org.web3j.abi.datatypes.DynamicBytes.class))); + this.blockNumber = blockNumber; + this.timestamp = timestamp; + this.indexRepeatedStorageChanges = indexRepeatedStorageChanges; + this.newStateRoot = newStateRoot; + this.numberOfLayer1Txs = numberOfLayer1Txs; + this.l2LogsTreeRoot = l2LogsTreeRoot; + this.priorityOperationsHash = priorityOperationsHash; + this.initialStorageChanges = initialStorageChanges; + this.repeatedStorageChanges = repeatedStorageChanges; + this.l2Logs = l2Logs; + this.l2ArbitraryLengthMessages = l2ArbitraryLengthMessages; + this.factoryDeps = factoryDeps; + } + + public CommitBlockInfo( + Uint64 blockNumber, + Uint64 timestamp, + Uint64 indexRepeatedStorageChanges, + Bytes32 newStateRoot, + Uint256 numberOfLayer1Txs, + Bytes32 l2LogsTreeRoot, + Bytes32 priorityOperationsHash, + DynamicBytes initialStorageChanges, + DynamicBytes repeatedStorageChanges, + DynamicBytes l2Logs, + DynamicArray l2ArbitraryLengthMessages, + DynamicArray factoryDeps) { + super( + blockNumber, + timestamp, + indexRepeatedStorageChanges, + newStateRoot, + numberOfLayer1Txs, + l2LogsTreeRoot, + priorityOperationsHash, + initialStorageChanges, + repeatedStorageChanges, + l2Logs, + l2ArbitraryLengthMessages, + factoryDeps); + this.blockNumber = blockNumber.getValue(); + this.timestamp = timestamp.getValue(); + this.indexRepeatedStorageChanges = indexRepeatedStorageChanges.getValue(); + this.newStateRoot = newStateRoot.getValue(); + this.numberOfLayer1Txs = numberOfLayer1Txs.getValue(); + this.l2LogsTreeRoot = l2LogsTreeRoot.getValue(); + this.priorityOperationsHash = priorityOperationsHash.getValue(); + this.initialStorageChanges = initialStorageChanges.getValue(); + this.repeatedStorageChanges = repeatedStorageChanges.getValue(); + this.l2Logs = l2Logs.getValue(); + this.l2ArbitraryLengthMessages = + l2ArbitraryLengthMessages.getValue().stream() + .map(v -> v.getValue()) + .collect(Collectors.toList()); + this.factoryDeps = + factoryDeps.getValue().stream().map(v -> v.getValue()).collect(Collectors.toList()); + } + } + + public static class Facet extends DynamicStruct { + public String addr; + + public List selectors; + + public Facet(String addr, List selectors) { + super( + new org.web3j.abi.datatypes.Address(addr), + new org.web3j.abi.datatypes.DynamicArray( + org.web3j.abi.datatypes.generated.Bytes4.class, + org.web3j.abi.Utils.typeMap( + selectors, org.web3j.abi.datatypes.generated.Bytes4.class))); + this.addr = addr; + this.selectors = selectors; + } + + public Facet(Address addr, DynamicArray selectors) { + super(addr, selectors); + this.addr = addr.getValue(); + this.selectors = + selectors.getValue().stream().map(v -> v.getValue()).collect(Collectors.toList()); + } + } + + public static class PriorityOperation extends StaticStruct { + public byte[] canonicalTxHash; + + public BigInteger expirationTimestamp; + + public BigInteger layer2Tip; + + public PriorityOperation( + byte[] canonicalTxHash, BigInteger expirationTimestamp, BigInteger layer2Tip) { + super( + new org.web3j.abi.datatypes.generated.Bytes32(canonicalTxHash), + new org.web3j.abi.datatypes.generated.Uint64(expirationTimestamp), + new org.web3j.abi.datatypes.generated.Uint192(layer2Tip)); + this.canonicalTxHash = canonicalTxHash; + this.expirationTimestamp = expirationTimestamp; + this.layer2Tip = layer2Tip; + } + + public PriorityOperation( + Bytes32 canonicalTxHash, Uint64 expirationTimestamp, Uint192 layer2Tip) { + super(canonicalTxHash, expirationTimestamp, layer2Tip); + this.canonicalTxHash = canonicalTxHash.getValue(); + this.expirationTimestamp = expirationTimestamp.getValue(); + this.layer2Tip = layer2Tip.getValue(); + } + } + + public static class ProofInput extends DynamicStruct { + public List recursiveAggregationInput; + + public List serializedProof; + + public ProofInput( + List recursiveAggregationInput, List serializedProof) { + super( + new org.web3j.abi.datatypes.DynamicArray( + org.web3j.abi.datatypes.generated.Uint256.class, + org.web3j.abi.Utils.typeMap( + recursiveAggregationInput, org.web3j.abi.datatypes.generated.Uint256.class)), + new org.web3j.abi.datatypes.DynamicArray( + org.web3j.abi.datatypes.generated.Uint256.class, + org.web3j.abi.Utils.typeMap( + serializedProof, org.web3j.abi.datatypes.generated.Uint256.class))); + this.recursiveAggregationInput = recursiveAggregationInput; + this.serializedProof = serializedProof; + } + + public ProofInput( + DynamicArray recursiveAggregationInput, DynamicArray serializedProof) { + super(recursiveAggregationInput, serializedProof); + this.recursiveAggregationInput = + recursiveAggregationInput.getValue().stream() + .map(v -> v.getValue()) + .collect(Collectors.toList()); + this.serializedProof = + serializedProof.getValue().stream().map(v -> v.getValue()).collect(Collectors.toList()); + } + } + + public static class L2Log extends StaticStruct { + public BigInteger l2ShardId; + + public Boolean isService; + + public BigInteger txNumberInBlock; + + public String sender; + + public byte[] key; + + public byte[] value; + + public L2Log( + BigInteger l2ShardId, + Boolean isService, + BigInteger txNumberInBlock, + String sender, + byte[] key, + byte[] value) { + super( + new org.web3j.abi.datatypes.generated.Uint8(l2ShardId), + new org.web3j.abi.datatypes.Bool(isService), + new org.web3j.abi.datatypes.generated.Uint16(txNumberInBlock), + new org.web3j.abi.datatypes.Address(sender), + new org.web3j.abi.datatypes.generated.Bytes32(key), + new org.web3j.abi.datatypes.generated.Bytes32(value)); + this.l2ShardId = l2ShardId; + this.isService = isService; + this.txNumberInBlock = txNumberInBlock; + this.sender = sender; + this.key = key; + this.value = value; + } - public static class Facet extends DynamicStruct { - public String addr; - - public List selectors; - - public Facet(String addr, List selectors) { - super(new org.web3j.abi.datatypes.Address(addr), - new org.web3j.abi.datatypes.DynamicArray( - org.web3j.abi.datatypes.generated.Bytes4.class, - org.web3j.abi.Utils.typeMap(selectors, org.web3j.abi.datatypes.generated.Bytes4.class))); - this.addr = addr; - this.selectors = selectors; - } - - public Facet(Address addr, DynamicArray selectors) { - super(addr, selectors); - this.addr = addr.getValue(); - this.selectors = selectors.getValue().stream().map(v -> v.getValue()).collect(Collectors.toList()); - } + public L2Log( + Uint8 l2ShardId, + Bool isService, + Uint16 txNumberInBlock, + Address sender, + Bytes32 key, + Bytes32 value) { + super(l2ShardId, isService, txNumberInBlock, sender, key, value); + this.l2ShardId = l2ShardId.getValue(); + this.isService = isService.getValue(); + this.txNumberInBlock = txNumberInBlock.getValue(); + this.sender = sender.getValue(); + this.key = key.getValue(); + this.value = value.getValue(); } + } - public static class PriorityOperation extends StaticStruct { - public byte[] canonicalTxHash; + public static class L2Message extends DynamicStruct { + public BigInteger txNumberInBlock; - public BigInteger expirationTimestamp; + public String sender; - public BigInteger layer2Tip; + public byte[] data; - public PriorityOperation(byte[] canonicalTxHash, BigInteger expirationTimestamp, BigInteger layer2Tip) { - super(new org.web3j.abi.datatypes.generated.Bytes32(canonicalTxHash), - new org.web3j.abi.datatypes.generated.Uint64(expirationTimestamp), - new org.web3j.abi.datatypes.generated.Uint192(layer2Tip)); - this.canonicalTxHash = canonicalTxHash; - this.expirationTimestamp = expirationTimestamp; - this.layer2Tip = layer2Tip; - } - - public PriorityOperation(Bytes32 canonicalTxHash, Uint64 expirationTimestamp, Uint192 layer2Tip) { - super(canonicalTxHash, expirationTimestamp, layer2Tip); - this.canonicalTxHash = canonicalTxHash.getValue(); - this.expirationTimestamp = expirationTimestamp.getValue(); - this.layer2Tip = layer2Tip.getValue(); - } - } - - public static class ProofInput extends DynamicStruct { - public List recursiveAggregationInput; - - public List serializedProof; - - public ProofInput(List recursiveAggregationInput, List serializedProof) { - super(new org.web3j.abi.datatypes.DynamicArray( - org.web3j.abi.datatypes.generated.Uint256.class, - org.web3j.abi.Utils.typeMap(recursiveAggregationInput, org.web3j.abi.datatypes.generated.Uint256.class)), - new org.web3j.abi.datatypes.DynamicArray( - org.web3j.abi.datatypes.generated.Uint256.class, - org.web3j.abi.Utils.typeMap(serializedProof, org.web3j.abi.datatypes.generated.Uint256.class))); - this.recursiveAggregationInput = recursiveAggregationInput; - this.serializedProof = serializedProof; - } - - public ProofInput(DynamicArray recursiveAggregationInput, DynamicArray serializedProof) { - super(recursiveAggregationInput, serializedProof); - this.recursiveAggregationInput = recursiveAggregationInput.getValue().stream().map(v -> v.getValue()).collect(Collectors.toList()); - this.serializedProof = serializedProof.getValue().stream().map(v -> v.getValue()).collect(Collectors.toList()); - } + public L2Message(BigInteger txNumberInBlock, String sender, byte[] data) { + super( + new org.web3j.abi.datatypes.generated.Uint16(txNumberInBlock), + new org.web3j.abi.datatypes.Address(sender), + new org.web3j.abi.datatypes.DynamicBytes(data)); + this.txNumberInBlock = txNumberInBlock; + this.sender = sender; + this.data = data; } - public static class L2Log extends StaticStruct { - public BigInteger l2ShardId; - - public Boolean isService; - - public BigInteger txNumberInBlock; - - public String sender; - - public byte[] key; - - public byte[] value; - - public L2Log(BigInteger l2ShardId, Boolean isService, BigInteger txNumberInBlock, String sender, byte[] key, byte[] value) { - super(new org.web3j.abi.datatypes.generated.Uint8(l2ShardId), - new org.web3j.abi.datatypes.Bool(isService), - new org.web3j.abi.datatypes.generated.Uint16(txNumberInBlock), - new org.web3j.abi.datatypes.Address(sender), - new org.web3j.abi.datatypes.generated.Bytes32(key), - new org.web3j.abi.datatypes.generated.Bytes32(value)); - this.l2ShardId = l2ShardId; - this.isService = isService; - this.txNumberInBlock = txNumberInBlock; - this.sender = sender; - this.key = key; - this.value = value; - } - - public L2Log(Uint8 l2ShardId, Bool isService, Uint16 txNumberInBlock, Address sender, Bytes32 key, Bytes32 value) { - super(l2ShardId, isService, txNumberInBlock, sender, key, value); - this.l2ShardId = l2ShardId.getValue(); - this.isService = isService.getValue(); - this.txNumberInBlock = txNumberInBlock.getValue(); - this.sender = sender.getValue(); - this.key = key.getValue(); - this.value = value.getValue(); - } + public L2Message(Uint16 txNumberInBlock, Address sender, DynamicBytes data) { + super(txNumberInBlock, sender, data); + this.txNumberInBlock = txNumberInBlock.getValue(); + this.sender = sender.getValue(); + this.data = data.getValue(); } + } - public static class L2Message extends DynamicStruct { - public BigInteger txNumberInBlock; + public static class DiamondCutData extends DynamicStruct { + public List facetCuts; - public String sender; + public String initAddress; - public byte[] data; + public byte[] initCalldata; - public L2Message(BigInteger txNumberInBlock, String sender, byte[] data) { - super(new org.web3j.abi.datatypes.generated.Uint16(txNumberInBlock), - new org.web3j.abi.datatypes.Address(sender), - new org.web3j.abi.datatypes.DynamicBytes(data)); - this.txNumberInBlock = txNumberInBlock; - this.sender = sender; - this.data = data; - } - - public L2Message(Uint16 txNumberInBlock, Address sender, DynamicBytes data) { - super(txNumberInBlock, sender, data); - this.txNumberInBlock = txNumberInBlock.getValue(); - this.sender = sender.getValue(); - this.data = data.getValue(); - } + public DiamondCutData(List facetCuts, String initAddress, byte[] initCalldata) { + super( + new org.web3j.abi.datatypes.DynamicArray(FacetCut.class, facetCuts), + new org.web3j.abi.datatypes.Address(initAddress), + new org.web3j.abi.datatypes.DynamicBytes(initCalldata)); + this.facetCuts = facetCuts; + this.initAddress = initAddress; + this.initCalldata = initCalldata; } - public static class DiamondCutData extends DynamicStruct { - public List facetCuts; - - public String initAddress; - - public byte[] initCalldata; - - public DiamondCutData(List facetCuts, String initAddress, byte[] initCalldata) { - super(new org.web3j.abi.datatypes.DynamicArray(FacetCut.class, facetCuts), - new org.web3j.abi.datatypes.Address(initAddress), - new org.web3j.abi.datatypes.DynamicBytes(initCalldata)); - this.facetCuts = facetCuts; - this.initAddress = initAddress; - this.initCalldata = initCalldata; - } - - public DiamondCutData(@Parameterized(type = FacetCut.class) DynamicArray facetCuts, Address initAddress, DynamicBytes initCalldata) { - super(facetCuts, initAddress, initCalldata); - this.facetCuts = facetCuts.getValue(); - this.initAddress = initAddress.getValue(); - this.initCalldata = initCalldata.getValue(); - } + public DiamondCutData( + @Parameterized(type = FacetCut.class) DynamicArray facetCuts, + Address initAddress, + DynamicBytes initCalldata) { + super(facetCuts, initAddress, initCalldata); + this.facetCuts = facetCuts.getValue(); + this.initAddress = initAddress.getValue(); + this.initCalldata = initCalldata.getValue(); } + } - public static class BlockCommitEventResponse extends BaseEventResponse { - public BigInteger blockNumber; + public static class BlockCommitEventResponse extends BaseEventResponse { + public BigInteger blockNumber; - public byte[] blockHash; + public byte[] blockHash; - public byte[] commitment; - } + public byte[] commitment; + } - public static class BlockExecutionEventResponse extends BaseEventResponse { - public BigInteger blockNumber; + public static class BlockExecutionEventResponse extends BaseEventResponse { + public BigInteger blockNumber; - public byte[] blockHash; + public byte[] blockHash; - public byte[] commitment; - } + public byte[] commitment; + } - public static class BlocksRevertEventResponse extends BaseEventResponse { - public BigInteger totalBlocksCommitted; + public static class BlocksRevertEventResponse extends BaseEventResponse { + public BigInteger totalBlocksCommitted; - public BigInteger totalBlocksVerified; + public BigInteger totalBlocksVerified; - public BigInteger totalBlocksExecuted; - } + public BigInteger totalBlocksExecuted; + } - public static class BlocksVerificationEventResponse extends BaseEventResponse { - public BigInteger previousLastVerifiedBlock; + public static class BlocksVerificationEventResponse extends BaseEventResponse { + public BigInteger previousLastVerifiedBlock; - public BigInteger currentLastVerifiedBlock; - } + public BigInteger currentLastVerifiedBlock; + } - public static class CancelUpgradeProposalEventResponse extends BaseEventResponse { - public BigInteger proposalId; + public static class CancelUpgradeProposalEventResponse extends BaseEventResponse { + public BigInteger proposalId; - public byte[] proposalHash; - } + public byte[] proposalHash; + } - public static class EthWithdrawalFinalizedEventResponse extends BaseEventResponse { - public String to; + public static class EthWithdrawalFinalizedEventResponse extends BaseEventResponse { + public String to; - public BigInteger amount; - } + public BigInteger amount; + } - public static class ExecuteUpgradeEventResponse extends BaseEventResponse { - public BigInteger proposalId; + public static class ExecuteUpgradeEventResponse extends BaseEventResponse { + public BigInteger proposalId; - public byte[] proposalHash; + public byte[] proposalHash; - public byte[] proposalSalt; - } + public byte[] proposalSalt; + } - public static class FreezeEventResponse extends BaseEventResponse { - } + public static class FreezeEventResponse extends BaseEventResponse {} - public static class IsPorterAvailableStatusUpdateEventResponse extends BaseEventResponse { - public Boolean isPorterAvailable; - } + public static class IsPorterAvailableStatusUpdateEventResponse extends BaseEventResponse { + public Boolean isPorterAvailable; + } - public static class NewGovernorEventResponse extends BaseEventResponse { - public String oldGovernor; + public static class NewGovernorEventResponse extends BaseEventResponse { + public String oldGovernor; - public String newGovernor; - } + public String newGovernor; + } - public static class NewL2BootloaderBytecodeHashEventResponse extends BaseEventResponse { - public byte[] previousBytecodeHash; + public static class NewL2BootloaderBytecodeHashEventResponse extends BaseEventResponse { + public byte[] previousBytecodeHash; - public byte[] newBytecodeHash; - } + public byte[] newBytecodeHash; + } - public static class NewL2DefaultAccountBytecodeHashEventResponse extends BaseEventResponse { - public byte[] previousBytecodeHash; + public static class NewL2DefaultAccountBytecodeHashEventResponse extends BaseEventResponse { + public byte[] previousBytecodeHash; - public byte[] newBytecodeHash; - } + public byte[] newBytecodeHash; + } - public static class NewPendingGovernorEventResponse extends BaseEventResponse { - public String oldPendingGovernor; + public static class NewPendingGovernorEventResponse extends BaseEventResponse { + public String oldPendingGovernor; - public String newPendingGovernor; - } + public String newPendingGovernor; + } - public static class NewPriorityRequestEventResponse extends BaseEventResponse { - public BigInteger txId; + public static class NewPriorityRequestEventResponse extends BaseEventResponse { + public BigInteger txId; - public byte[] txHash; + public byte[] txHash; - public BigInteger expirationTimestamp; + public BigInteger expirationTimestamp; - public L2CanonicalTransaction transaction; + public L2CanonicalTransaction transaction; - public List factoryDeps; - } + public List factoryDeps; + } - public static class NewPriorityTxMaxGasLimitEventResponse extends BaseEventResponse { - public BigInteger oldPriorityTxMaxGasLimit; + public static class NewPriorityTxMaxGasLimitEventResponse extends BaseEventResponse { + public BigInteger oldPriorityTxMaxGasLimit; - public BigInteger newPriorityTxMaxGasLimit; - } + public BigInteger newPriorityTxMaxGasLimit; + } - public static class NewVerifierEventResponse extends BaseEventResponse { - public String oldVerifier; + public static class NewVerifierEventResponse extends BaseEventResponse { + public String oldVerifier; - public String newVerifier; - } + public String newVerifier; + } - public static class NewVerifierParamsEventResponse extends BaseEventResponse { - public VerifierParams oldVerifierParams; + public static class NewVerifierParamsEventResponse extends BaseEventResponse { + public VerifierParams oldVerifierParams; - public VerifierParams newVerifierParams; - } + public VerifierParams newVerifierParams; + } - public static class ProposeShadowUpgradeEventResponse extends BaseEventResponse { - public BigInteger proposalId; + public static class ProposeShadowUpgradeEventResponse extends BaseEventResponse { + public BigInteger proposalId; - public byte[] proposalHash; - } + public byte[] proposalHash; + } - public static class ProposeTransparentUpgradeEventResponse extends BaseEventResponse { - public BigInteger proposalId; + public static class ProposeTransparentUpgradeEventResponse extends BaseEventResponse { + public BigInteger proposalId; - public DiamondCutData diamondCut; + public DiamondCutData diamondCut; - public byte[] proposalSalt; - } + public byte[] proposalSalt; + } - public static class SecurityCouncilUpgradeApproveEventResponse extends BaseEventResponse { - public BigInteger proposalId; + public static class SecurityCouncilUpgradeApproveEventResponse extends BaseEventResponse { + public BigInteger proposalId; - public byte[] proposalHash; - } + public byte[] proposalHash; + } - public static class UnfreezeEventResponse extends BaseEventResponse { - } + public static class UnfreezeEventResponse extends BaseEventResponse {} - public static class ValidatorStatusUpdateEventResponse extends BaseEventResponse { - public String validatorAddress; + public static class ValidatorStatusUpdateEventResponse extends BaseEventResponse { + public String validatorAddress; - public Boolean isActive; - } + public Boolean isActive; + } } diff --git a/src/test/java/io/zksync/abi/ZkTransactionEncoderTest.java b/src/test/java/io/zksync/abi/ZkTransactionEncoderTest.java index d22db5c..58ecfa8 100644 --- a/src/test/java/io/zksync/abi/ZkTransactionEncoderTest.java +++ b/src/test/java/io/zksync/abi/ZkTransactionEncoderTest.java @@ -2,16 +2,16 @@ import static org.junit.jupiter.api.Assertions.*; -import java.math.BigInteger; -import java.util.Arrays; -import java.util.Collections; - import io.zksync.helper.CounterContract; import io.zksync.methods.request.Eip712Meta; +import io.zksync.protocol.core.Token; import io.zksync.transaction.type.Transaction712; import io.zksync.utils.ContractDeployer; import io.zksync.utils.ZkSyncAddresses; import io.zksync.wrappers.IL2Bridge; +import java.math.BigInteger; +import java.util.Arrays; +import java.util.Collections; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.web3j.abi.FunctionEncoder; @@ -20,112 +20,100 @@ import org.web3j.abi.datatypes.generated.Uint256; import org.web3j.crypto.Credentials; import org.web3j.crypto.ECKeyPair; - -import io.zksync.protocol.core.Token; import org.web3j.utils.Numeric; public class ZkTransactionEncoderTest { - private static final Token ETH = Token.createETH(); - private static final String BRIDGE_ADDRESS = "0x8c98381FfE6229Ee9E53B6aAb784E86863f61885"; - private static final BigInteger GAS_LIMIT = BigInteger.valueOf(42); - private static final BigInteger GAS_PRICE = BigInteger.valueOf(43); - private static final Long CHAIN_ID = 270L; - - Credentials credentials; - - @BeforeEach - public void setUp() { - this.credentials = Credentials.create(ECKeyPair.create(BigInteger.ONE)); - } - - @Test - public void testEncodeWithdraw() { - final Function withdraw = new Function( - IL2Bridge.FUNC_WITHDRAW, - Arrays.asList(new Address(credentials.getAddress()), - new Address(ETH.getL2Address()), - new Uint256(ETH.toBigInteger(1))), - Collections.emptyList()); - - String calldata = FunctionEncoder.encode(withdraw); - - Transaction712 transaction = new Transaction712( - CHAIN_ID, - BigInteger.ZERO, - GAS_LIMIT, - BRIDGE_ADDRESS, - BigInteger.ZERO, - calldata, - GAS_PRICE, - GAS_PRICE, - credentials.getAddress(), - new Eip712Meta( - BigInteger.ZERO, - new byte[] {}, - null, - null - ) - ); - - String expected = "0x71f8a1802b2b2a948c98381ffe6229ee9e53b6aab784e86863f6188580b864d9caed120000000000000000000000007e5f4552091a69125d5dfcb7b8c2659029395bdf00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000de0b6b3a764000082010e808082010e947e5f4552091a69125d5dfcb7b8c2659029395bdf80c080c0"; - - assertEquals(expected, Numeric.toHexString(TransactionEncoder.encode(transaction, null))); - } - - @Test - public void testEncodeDeploy() { - byte[] bytecodeBytes = Numeric.hexStringToByteArray(CounterContract.BINARY); - String calldata = FunctionEncoder.encode(ContractDeployer.encodeCreate2(bytecodeBytes)); - - Transaction712 transaction = new Transaction712( - CHAIN_ID, - BigInteger.ZERO, - GAS_LIMIT, - ZkSyncAddresses.CONTRACT_DEPLOYER_ADDRESS, - BigInteger.ZERO, - calldata, - GAS_PRICE, - GAS_PRICE, - credentials.getAddress(), - new Eip712Meta( - BigInteger.ZERO, - new byte[] {}, - new byte[][]{bytecodeBytes}, - null - ) - ); - - String expected = "0x71f90ae6802b2b2a94000000000000000000000000000000000000800680b8843cda33510000000000000000000000000000000000000000000000000000000000000000010000517112c421df08d7b49e4dc1312f4ee62268ee4f5683b11d9e2d33525a0000000000000000000000000000000000000000000000000000000000000060000000000000000000000000000000000000000000000000000000000000000082010e808082010e947e5f4552091a69125d5dfcb7b8c2659029395bdf80f90a23b90a20000200000000000200010000000103550000006001100270000000410010019d000000010120018f000000000110004c000000080000c13d00fd00180000040f00fd00090000040f0000008001000039000000400200003900000000001204350000000001000416000000000110004c000000160000c13d000000200100003900000100020000390000000000120439000001200100003900000000000104390000004201000041000000fe0001042e0000000001000019000000ff0001043000040000000000020000000001000410000080020210008c000000330000613d0000000002000411000080010220008c000000330000613d0000004302000041000000000020043900000004020000390000000000120439000000440100004100008002020000390000000003000415000000040330008a00000020033000c900fd00e00000040f000000ff01000039000000030110024f000000000110004c000000560000613d000000040100035f000000000101043b000000000110004c000000330000c13d0000000001000019000000fe0001042e0000008001000039000000400600003900000000001604350000000001000031000000030210008c000000540000a13d0000000102000367000000000302043b000000e003300270000000450430009c0000006c0000613d000000460230009c000000580000613d000000470230009c000000540000c13d0000000002000416000000000220004c000000800000c13d000000040110008a00000048020000410000001f0310008c000000000300001900000000030220190000004801100197000000000410004c0000000002008019000000480110009c00000000010300190000000001026019000000000110004c0000008e0000c13d0000000001000019000000ff000104300000000001000019000000ff000104300000000001000019000000ff000104300000000002000416000000000220004c0000007e0000c13d000000040110008a000000010200008a0000004803000041000000000221004b000000000200001900000000020320190000004801100197000000480410009c00000000030080190000004801100167000000480110009c00000000010200190000000001036019000000000110004c000000840000c13d0000000001000019000000ff000104300000000003000416000000000330004c000000820000c13d000000040110008a00000048030000410000003f0410008c000000000400001900000000040320190000004801100197000000000510004c0000000003008019000000480110009c00000000010400190000000001036019000000000110004c000000a20000c13d0000000001000019000000ff000104300000000001000019000000ff000104300000000001000019000000ff000104300000000001000019000000ff000104300000000001000019000200000006001d00fd00fb0000040f000000020200002900000000020204330000000000120435000000400120021000000049011001970000004c011001c7000000fe0001042e000200000006001d000000000100001900fd00fb0000040f00000001020003670000000402200370000000000202043b0000000001120019000000000221004b00000000020000190000000102004039000000010220018f000000000220004c000000be0000613d0000004a0100004100000000001004350000001101000039000000040200003900000000001204350000004b01000041000000ff000104300000002401200370000000000201043b000000000120004c0000000001000019000000010100c039000000000112004b000000c50000c13d000100000002001d000200000006001d000000000100001900fd00fb0000040f00000001020003670000000402200370000000000202043b0000000001120019000000000221004b00000000020000190000000102004039000000010220018f000000000220004c000000c70000613d0000004a0100004100000000001004350000001101000039000000040200003900000000001204350000004b01000041000000ff00010430000000000200001900fd00f90000040f0000000201000029000000000101043300000040011002100000004901100197000000fe0001042e0000000001000019000000ff00010430000000000200001900fd00f90000040f000000020100002900000000010104330000000102000029000000000220004c000000d10000c13d00000040011002100000004901100197000000fe0001042e00000044021000390000004d03000041000000000032043500000024021000390000001a0300003900000000003204350000004e020000410000000000210435000000040210003900000020030000390000000000320435000000400110021000000049011001970000004f011001c7000000ff000104300002000000000002000200000003001d0000002003300039000100000003001d000000ef002104230000000203000029000000200230011a000000000201035500000048010000410000000102000029000000200220011a00000000021201bd00000000010300190000000200000005000000000001042d0000000203000029000000200230011a000000000201035500000050010000410000000102000029000000200220011a000000000212018d00000000010300190000000200000005000000000001042d000000000012041b000000000001042d000000000101041a000000000001042d000000fd00000432000000fe0001042e000000ff00010430000000000000000100000000000000010000000000000001000000000000000100000000000000000000000000000000000000000000000000000000ffffffff00000002000000000000000000000000000000400000010000000000000000001806aa1896bbf26568e884a7374b41e002500962caba6a15023a8d90e8508b830200020000000000000000000000000000000024000000000000000000000000000000000000000000000000000000000000000000000000000000000436dad6000000000000000000000000000000000000000000000000000000006d4ce63c000000000000000000000000000000000000000000000000000000007cf5dab080000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000ffffffff00000000000000004e487b71000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000024000000000000000000000000000000000000000000000000000000000000002000000000000000000000000054686973206d6574686f6420616c77617973207265766572747300000000000008c379a00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000640000000000000000000000007fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff80c0"; - - assertEquals(expected, Numeric.toHexString(TransactionEncoder.encode(transaction, null))); - } - - @Test - public void testEncodeExecute() { - String calldata = FunctionEncoder.encode(CounterContract.encodeIncrement(BigInteger.valueOf(42L))); - - Transaction712 transaction = new Transaction712( - CHAIN_ID, - BigInteger.ZERO, - GAS_LIMIT, - "0xe1fab3efd74a77c23b426c302d96372140ff7d0c", - BigInteger.ZERO, - calldata, - GAS_PRICE, - GAS_PRICE, - credentials.getAddress(), - new Eip712Meta( - BigInteger.ZERO, - new byte[] {}, - null, - null - ) - ); - - String expected = "0x71f860802b2b2a94e1fab3efd74a77c23b426c302d96372140ff7d0c80a47cf5dab0000000000000000000000000000000000000000000000000000000000000002a82010e808082010e947e5f4552091a69125d5dfcb7b8c2659029395bdf80c080c0"; - - assertEquals(expected, Numeric.toHexString(TransactionEncoder.encode(transaction, null))); - } - + private static final Token ETH = Token.createETH(); + private static final String BRIDGE_ADDRESS = "0x8c98381FfE6229Ee9E53B6aAb784E86863f61885"; + private static final BigInteger GAS_LIMIT = BigInteger.valueOf(42); + private static final BigInteger GAS_PRICE = BigInteger.valueOf(43); + private static final Long CHAIN_ID = 270L; + + Credentials credentials; + + @BeforeEach + public void setUp() { + this.credentials = Credentials.create(ECKeyPair.create(BigInteger.ONE)); + } + + @Test + public void testEncodeWithdraw() { + final Function withdraw = + new Function( + IL2Bridge.FUNC_WITHDRAW, + Arrays.asList( + new Address(credentials.getAddress()), + new Address(ETH.getL2Address()), + new Uint256(ETH.toBigInteger(1))), + Collections.emptyList()); + + String calldata = FunctionEncoder.encode(withdraw); + + Transaction712 transaction = + new Transaction712( + CHAIN_ID, + BigInteger.ZERO, + GAS_LIMIT, + BRIDGE_ADDRESS, + BigInteger.ZERO, + calldata, + GAS_PRICE, + GAS_PRICE, + credentials.getAddress(), + new Eip712Meta(BigInteger.ZERO, new byte[] {}, null, null)); + + String expected = + "0x71f8a1802b2b2a948c98381ffe6229ee9e53b6aab784e86863f6188580b864d9caed120000000000000000000000007e5f4552091a69125d5dfcb7b8c2659029395bdf00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000de0b6b3a764000082010e808082010e947e5f4552091a69125d5dfcb7b8c2659029395bdf80c080c0"; + + assertEquals(expected, Numeric.toHexString(TransactionEncoder.encode(transaction, null))); + } + + @Test + public void testEncodeDeploy() { + byte[] bytecodeBytes = Numeric.hexStringToByteArray(CounterContract.BINARY); + String calldata = FunctionEncoder.encode(ContractDeployer.encodeCreate2(bytecodeBytes)); + + Transaction712 transaction = + new Transaction712( + CHAIN_ID, + BigInteger.ZERO, + GAS_LIMIT, + ZkSyncAddresses.CONTRACT_DEPLOYER_ADDRESS, + BigInteger.ZERO, + calldata, + GAS_PRICE, + GAS_PRICE, + credentials.getAddress(), + new Eip712Meta(BigInteger.ZERO, new byte[] {}, new byte[][] {bytecodeBytes}, null)); + + String expected = + "0x71f90ae6802b2b2a94000000000000000000000000000000000000800680b8843cda33510000000000000000000000000000000000000000000000000000000000000000010000517112c421df08d7b49e4dc1312f4ee62268ee4f5683b11d9e2d33525a0000000000000000000000000000000000000000000000000000000000000060000000000000000000000000000000000000000000000000000000000000000082010e808082010e947e5f4552091a69125d5dfcb7b8c2659029395bdf80f90a23b90a20000200000000000200010000000103550000006001100270000000410010019d000000010120018f000000000110004c000000080000c13d00fd00180000040f00fd00090000040f0000008001000039000000400200003900000000001204350000000001000416000000000110004c000000160000c13d000000200100003900000100020000390000000000120439000001200100003900000000000104390000004201000041000000fe0001042e0000000001000019000000ff0001043000040000000000020000000001000410000080020210008c000000330000613d0000000002000411000080010220008c000000330000613d0000004302000041000000000020043900000004020000390000000000120439000000440100004100008002020000390000000003000415000000040330008a00000020033000c900fd00e00000040f000000ff01000039000000030110024f000000000110004c000000560000613d000000040100035f000000000101043b000000000110004c000000330000c13d0000000001000019000000fe0001042e0000008001000039000000400600003900000000001604350000000001000031000000030210008c000000540000a13d0000000102000367000000000302043b000000e003300270000000450430009c0000006c0000613d000000460230009c000000580000613d000000470230009c000000540000c13d0000000002000416000000000220004c000000800000c13d000000040110008a00000048020000410000001f0310008c000000000300001900000000030220190000004801100197000000000410004c0000000002008019000000480110009c00000000010300190000000001026019000000000110004c0000008e0000c13d0000000001000019000000ff000104300000000001000019000000ff000104300000000001000019000000ff000104300000000002000416000000000220004c0000007e0000c13d000000040110008a000000010200008a0000004803000041000000000221004b000000000200001900000000020320190000004801100197000000480410009c00000000030080190000004801100167000000480110009c00000000010200190000000001036019000000000110004c000000840000c13d0000000001000019000000ff000104300000000003000416000000000330004c000000820000c13d000000040110008a00000048030000410000003f0410008c000000000400001900000000040320190000004801100197000000000510004c0000000003008019000000480110009c00000000010400190000000001036019000000000110004c000000a20000c13d0000000001000019000000ff000104300000000001000019000000ff000104300000000001000019000000ff000104300000000001000019000000ff000104300000000001000019000200000006001d00fd00fb0000040f000000020200002900000000020204330000000000120435000000400120021000000049011001970000004c011001c7000000fe0001042e000200000006001d000000000100001900fd00fb0000040f00000001020003670000000402200370000000000202043b0000000001120019000000000221004b00000000020000190000000102004039000000010220018f000000000220004c000000be0000613d0000004a0100004100000000001004350000001101000039000000040200003900000000001204350000004b01000041000000ff000104300000002401200370000000000201043b000000000120004c0000000001000019000000010100c039000000000112004b000000c50000c13d000100000002001d000200000006001d000000000100001900fd00fb0000040f00000001020003670000000402200370000000000202043b0000000001120019000000000221004b00000000020000190000000102004039000000010220018f000000000220004c000000c70000613d0000004a0100004100000000001004350000001101000039000000040200003900000000001204350000004b01000041000000ff00010430000000000200001900fd00f90000040f0000000201000029000000000101043300000040011002100000004901100197000000fe0001042e0000000001000019000000ff00010430000000000200001900fd00f90000040f000000020100002900000000010104330000000102000029000000000220004c000000d10000c13d00000040011002100000004901100197000000fe0001042e00000044021000390000004d03000041000000000032043500000024021000390000001a0300003900000000003204350000004e020000410000000000210435000000040210003900000020030000390000000000320435000000400110021000000049011001970000004f011001c7000000ff000104300002000000000002000200000003001d0000002003300039000100000003001d000000ef002104230000000203000029000000200230011a000000000201035500000048010000410000000102000029000000200220011a00000000021201bd00000000010300190000000200000005000000000001042d0000000203000029000000200230011a000000000201035500000050010000410000000102000029000000200220011a000000000212018d00000000010300190000000200000005000000000001042d000000000012041b000000000001042d000000000101041a000000000001042d000000fd00000432000000fe0001042e000000ff00010430000000000000000100000000000000010000000000000001000000000000000100000000000000000000000000000000000000000000000000000000ffffffff00000002000000000000000000000000000000400000010000000000000000001806aa1896bbf26568e884a7374b41e002500962caba6a15023a8d90e8508b830200020000000000000000000000000000000024000000000000000000000000000000000000000000000000000000000000000000000000000000000436dad6000000000000000000000000000000000000000000000000000000006d4ce63c000000000000000000000000000000000000000000000000000000007cf5dab080000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000ffffffff00000000000000004e487b71000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000024000000000000000000000000000000000000000000000000000000000000002000000000000000000000000054686973206d6574686f6420616c77617973207265766572747300000000000008c379a00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000640000000000000000000000007fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff80c0"; + + assertEquals(expected, Numeric.toHexString(TransactionEncoder.encode(transaction, null))); + } + + @Test + public void testEncodeExecute() { + String calldata = + FunctionEncoder.encode(CounterContract.encodeIncrement(BigInteger.valueOf(42L))); + + Transaction712 transaction = + new Transaction712( + CHAIN_ID, + BigInteger.ZERO, + GAS_LIMIT, + "0xe1fab3efd74a77c23b426c302d96372140ff7d0c", + BigInteger.ZERO, + calldata, + GAS_PRICE, + GAS_PRICE, + credentials.getAddress(), + new Eip712Meta(BigInteger.ZERO, new byte[] {}, null, null)); + + String expected = + "0x71f860802b2b2a94e1fab3efd74a77c23b426c302d96372140ff7d0c80a47cf5dab0000000000000000000000000000000000000000000000000000000000000002a82010e808082010e947e5f4552091a69125d5dfcb7b8c2659029395bdf80c080c0"; + + assertEquals(expected, Numeric.toHexString(TransactionEncoder.encode(transaction, null))); + } } diff --git a/src/test/java/io/zksync/crypto/eip712/Eip712EncoderTest.java b/src/test/java/io/zksync/crypto/eip712/Eip712EncoderTest.java index 59a57c7..7fe7315 100755 --- a/src/test/java/io/zksync/crypto/eip712/Eip712EncoderTest.java +++ b/src/test/java/io/zksync/crypto/eip712/Eip712EncoderTest.java @@ -2,148 +2,174 @@ import static org.junit.jupiter.api.Assertions.*; +import io.zksync.helper.eip712.Mail; +import io.zksync.protocol.core.ZkSyncNetwork; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.web3j.abi.datatypes.Address; import org.web3j.abi.datatypes.generated.Uint128; import org.web3j.utils.Numeric; -import io.zksync.protocol.core.ZkSyncNetwork; -import io.zksync.helper.eip712.Mail; - public class Eip712EncoderTest { - private static Eip712Domain domain; - private static Mail message; - - @BeforeAll - public static void setUp() { - message = new Mail(); - - domain = new Eip712Domain( - "Ether Mail", - "1", - ZkSyncNetwork.Mainnet, - "0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC" - ); + private static Eip712Domain domain; + private static Mail message; + + @BeforeAll + public static void setUp() { + message = new Mail(); + + domain = + new Eip712Domain( + "Ether Mail", "1", ZkSyncNetwork.Mainnet, "0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC"); + } + + @Test + public void testEncodeType() { + final String result = Eip712Encoder.encodeType(message.intoEip712Struct()); + + assertEquals( + "Mail(Person from,Person to,string contents)Person(string name,address wallet)", result); + } + + @Test + public void testHashEncodedType() { + final byte[] hash = Eip712Encoder.typeHash(message.intoEip712Struct()); + + assertEquals( + "0xa0cedeb2dc280ba39b857546d74f5549c3a1d7bdc2dd96bf881f76108e23dac2", + Numeric.toHexString(hash)); + } + + @Test + public void testEncodeContentsValue() { + final byte[] hash = Eip712Encoder.encodeValue(message.contents).getValue(); + + assertEquals( + "0xb5aadf3154a261abdd9086fc627b61efca26ae5702701d05cd2305f7c52a2fc8", + Numeric.toHexString(hash)); + } + + @Test + public void testEncodePersonData() { + final byte[] fromHash = Eip712Encoder.encodeValue(message.from.intoEip712Struct()).getValue(); + final byte[] toHash = Eip712Encoder.encodeValue(message.to.intoEip712Struct()).getValue(); + + assertEquals( + "0xfc71e5fa27ff56c350aa531bc129ebdf613b772b6604664f5d8dbe21b85eb0c8", + Numeric.toHexString(fromHash)); + assertEquals( + "0xcd54f074a4af31b4411ff6a60c9719dbd559c221c8ac3492d9d872b041d703d1", + Numeric.toHexString(toHash)); + } + + @Test + public void testEncodeMailData() { + final byte[] data = Eip712Encoder.encodeValue(message.intoEip712Struct()).getValue(); + + assertEquals( + "0xc52c0ee5d84264471806290a3f2c4cecfc5490626bf912d01f240d7a274b371e", + Numeric.toHexString(data)); + } + + @Test + public void testEncodeDomainType() { + final String result = Eip712Encoder.encodeType(domain.intoEip712Struct()); + + assertEquals( + "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)", + result); + } + + @Test + public void testEncodeDomainMemberValues() { + { + final byte[] data = Eip712Encoder.encodeValue(domain.getName()).getValue(); + + assertEquals( + "0xc70ef06638535b4881fafcac8287e210e3769ff1a8e91f1b95d6246e61e4d3c6", + Numeric.toHexString(data)); } + { + final byte[] data = Eip712Encoder.encodeValue(domain.getVersion()).getValue(); - @Test - public void testEncodeType() { - final String result = Eip712Encoder.encodeType(message.intoEip712Struct()); - - assertEquals("Mail(Person from,Person to,string contents)Person(string name,address wallet)", result); + assertEquals( + "0xc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6", + Numeric.toHexString(data)); } + { + final byte[] data = Eip712Encoder.encodeValue(domain.getChainId()).getValue(); - @Test - public void testHashEncodedType() { - final byte[] hash = Eip712Encoder.typeHash(message.intoEip712Struct()); - - assertEquals("0xa0cedeb2dc280ba39b857546d74f5549c3a1d7bdc2dd96bf881f76108e23dac2", Numeric.toHexString(hash)); + assertEquals( + "0x0000000000000000000000000000000000000000000000000000000000000001", + Numeric.toHexString(data)); } + { + final byte[] data = Eip712Encoder.encodeValue(domain.getVerifyingContract()).getValue(); - @Test - public void testEncodeContentsValue() { - final byte[] hash = Eip712Encoder.encodeValue(message.contents).getValue(); - - assertEquals("0xb5aadf3154a261abdd9086fc627b61efca26ae5702701d05cd2305f7c52a2fc8", Numeric.toHexString(hash)); + assertEquals( + "0x000000000000000000000000cccccccccccccccccccccccccccccccccccccccc", + Numeric.toHexString(data)); } + } - @Test - public void testEncodePersonData() { - final byte[] fromHash = Eip712Encoder.encodeValue(message.from.intoEip712Struct()).getValue(); - final byte[] toHash = Eip712Encoder.encodeValue(message.to.intoEip712Struct()).getValue(); + @Test + public void testEncodeDomainData() { + final byte[] data = Eip712Encoder.encodeValue(domain.intoEip712Struct()).getValue(); - assertEquals("0xfc71e5fa27ff56c350aa531bc129ebdf613b772b6604664f5d8dbe21b85eb0c8", Numeric.toHexString(fromHash)); - assertEquals("0xcd54f074a4af31b4411ff6a60c9719dbd559c221c8ac3492d9d872b041d703d1", Numeric.toHexString(toHash)); - } + assertEquals( + "0xf2cee375fa42b42143804025fc449deafd50cc031ca257e0b194a650a912090f", + Numeric.toHexString(data)); + } - @Test - public void testEncodeMailData() { - final byte[] data = Eip712Encoder.encodeValue(message.intoEip712Struct()).getValue(); + @Test + public void testTypedDataToSignedBytes() { + final byte[] data = Eip712Encoder.typedDataToSignedBytes(domain, message); - assertEquals("0xc52c0ee5d84264471806290a3f2c4cecfc5490626bf912d01f240d7a274b371e", Numeric.toHexString(data)); - } - - @Test - public void testEncodeDomainType() { - final String result = Eip712Encoder.encodeType(domain.intoEip712Struct()); + assertEquals( + "0xbe609aee343fb3c4b28e1df9e632fca64fcfaede20f02e86244efddf30957bd2", + Numeric.toHexString(data)); + } - assertEquals("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)", result); - } + @Test + public void testEncodeTypes() { + { + Address address = new Address("0xe1fab3efd74a77c23b426c302d96372140ff7d0c"); - @Test - public void testEncodeDomainMemberValues() { - { - final byte[] data = Eip712Encoder.encodeValue(domain.getName()).getValue(); + byte[] result = Eip712Encoder.encodeValue(address).getValue(); - assertEquals("0xc70ef06638535b4881fafcac8287e210e3769ff1a8e91f1b95d6246e61e4d3c6", Numeric.toHexString(data)); - } - { - final byte[] data = Eip712Encoder.encodeValue(domain.getVersion()).getValue(); - - assertEquals("0xc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6", Numeric.toHexString(data)); - } - { - final byte[] data = Eip712Encoder.encodeValue(domain.getChainId()).getValue(); - - assertEquals("0x0000000000000000000000000000000000000000000000000000000000000001", Numeric.toHexString(data)); - } - { - final byte[] data = Eip712Encoder.encodeValue(domain.getVerifyingContract()).getValue(); - - assertEquals("0x000000000000000000000000cccccccccccccccccccccccccccccccccccccccc", Numeric.toHexString(data)); - } + assertEquals( + "0x000000000000000000000000e1fab3efd74a77c23b426c302d96372140ff7d0c", + Numeric.toHexString(result)); } - @Test - public void testEncodeDomainData() { - final byte[] data = Eip712Encoder.encodeValue(domain.intoEip712Struct()).getValue(); + { + Uint128 number = new Uint128(123); - assertEquals("0xf2cee375fa42b42143804025fc449deafd50cc031ca257e0b194a650a912090f", Numeric.toHexString(data)); - } + byte[] result = Eip712Encoder.encodeValue(number).getValue(); - @Test - public void testTypedDataToSignedBytes() { - final byte[] data = Eip712Encoder.typedDataToSignedBytes(domain, message); - - assertEquals("0xbe609aee343fb3c4b28e1df9e632fca64fcfaede20f02e86244efddf30957bd2", Numeric.toHexString(data)); + assertEquals( + "0x000000000000000000000000000000000000000000000000000000000000007b", + Numeric.toHexString(result)); } - - @Test - public void testEncodeTypes() { - { - Address address = new Address("0xe1fab3efd74a77c23b426c302d96372140ff7d0c"); - - byte[] result = Eip712Encoder.encodeValue(address).getValue(); - - assertEquals("0x000000000000000000000000e1fab3efd74a77c23b426c302d96372140ff7d0c", Numeric.toHexString(result)); - } - - { - Uint128 number = new Uint128(123); - - byte[] result = Eip712Encoder.encodeValue(number).getValue(); - - assertEquals("0x000000000000000000000000000000000000000000000000000000000000007b", Numeric.toHexString(result)); - } - } - -// @Test -// public void testEncodeTransfer() { -// Transfer zkTransfer = new Transfer( -// ETH.getAddress(), -// this.credentials.getAddress(), -// Convert.toWei("1", Unit.ETHER).toBigInteger(), -// this.credentials.getAddress(), -// ETH.getAddress(), -// BigInteger.ZERO, -// 1, -// new TimeRange() -// ); -// -// byte[] result = Eip712Encoder.encodeValue(zkTransfer.intoEip712Struct()).getValue(); -// -// assertEquals("0x997cbce617f1c5aca3616ddc2122db218d726e220fa040451d893430d7382ce5", Numeric.toHexString(result)); -// } + } + + // @Test + // public void testEncodeTransfer() { + // Transfer zkTransfer = new Transfer( + // ETH.getAddress(), + // this.credentials.getAddress(), + // Convert.toWei("1", Unit.ETHER).toBigInteger(), + // this.credentials.getAddress(), + // ETH.getAddress(), + // BigInteger.ZERO, + // 1, + // new TimeRange() + // ); + // + // byte[] result = Eip712Encoder.encodeValue(zkTransfer.intoEip712Struct()).getValue(); + // + // assertEquals("0x997cbce617f1c5aca3616ddc2122db218d726e220fa040451d893430d7382ce5", + // Numeric.toHexString(result)); + // } } diff --git a/src/test/java/io/zksync/crypto/signer/PrivateKeyEthSignerTest.java b/src/test/java/io/zksync/crypto/signer/PrivateKeyEthSignerTest.java index 1d5a93c..a50b56c 100755 --- a/src/test/java/io/zksync/crypto/signer/PrivateKeyEthSignerTest.java +++ b/src/test/java/io/zksync/crypto/signer/PrivateKeyEthSignerTest.java @@ -2,55 +2,52 @@ import static org.junit.jupiter.api.Assertions.*; +import io.zksync.crypto.eip712.Eip712Domain; +import io.zksync.helper.eip712.Mail; +import io.zksync.protocol.core.ZkSyncNetwork; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.web3j.crypto.Credentials; import org.web3j.crypto.Hash; import org.web3j.tx.ChainIdLong; -import io.zksync.protocol.core.ZkSyncNetwork; -import io.zksync.crypto.eip712.Eip712Domain; - -import io.zksync.helper.eip712.Mail; - public class PrivateKeyEthSignerTest { - - private static Credentials credentials; - private static PrivateKeyEthSigner key; - private static Eip712Domain domain; - private static Mail message; - @BeforeAll - public static void setUp() { - final String privateKey = Hash.sha3String("cow"); + private static Credentials credentials; + private static PrivateKeyEthSigner key; + private static Eip712Domain domain; + private static Mail message; - credentials = Credentials.create(privateKey); - key = new PrivateKeyEthSigner(credentials, ChainIdLong.MAINNET); + @BeforeAll + public static void setUp() { + final String privateKey = Hash.sha3String("cow"); - domain = new Eip712Domain( - "Ether Mail", - "1", - ZkSyncNetwork.Mainnet, - "0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC" - ); + credentials = Credentials.create(privateKey); + key = new PrivateKeyEthSigner(credentials, ChainIdLong.MAINNET); - message = new Mail(); - } + domain = + new Eip712Domain( + "Ether Mail", "1", ZkSyncNetwork.Mainnet, "0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC"); - @Test - public void testSignTypedData() { - final String signature = key.signTypedData(domain, message).join(); + message = new Mail(); + } - assertEquals("0x4355c47d63924e8a72e509b65029052eb6c299d53a04e167c5775fd466751c9d07299936d304c153f6443dfa05f40ff007d72911b6f72307f996231605b915621c", signature); - } + @Test + public void testSignTypedData() { + final String signature = key.signTypedData(domain, message).join(); - @Test - public void testVerifySignedTypedData() { - final String signature = "0x4355c47d63924e8a72e509b65029052eb6c299d53a04e167c5775fd466751c9d07299936d304c153f6443dfa05f40ff007d72911b6f72307f996231605b915621c"; + assertEquals( + "0x4355c47d63924e8a72e509b65029052eb6c299d53a04e167c5775fd466751c9d07299936d304c153f6443dfa05f40ff007d72911b6f72307f996231605b915621c", + signature); + } - boolean verified = key.verifyTypedData(domain, message, signature).join(); + @Test + public void testVerifySignedTypedData() { + final String signature = + "0x4355c47d63924e8a72e509b65029052eb6c299d53a04e167c5775fd466751c9d07299936d304c153f6443dfa05f40ff007d72911b6f72307f996231605b915621c"; - assertTrue(verified); - } + boolean verified = key.verifyTypedData(domain, message, signature).join(); + assertTrue(verified); + } } diff --git a/src/test/java/io/zksync/crypto/signer/SelfTransferTest.java b/src/test/java/io/zksync/crypto/signer/SelfTransferTest.java index 6fa1892..c978fc5 100644 --- a/src/test/java/io/zksync/crypto/signer/SelfTransferTest.java +++ b/src/test/java/io/zksync/crypto/signer/SelfTransferTest.java @@ -7,6 +7,12 @@ import io.zksync.protocol.core.ZkBlockParameterName; import io.zksync.protocol.provider.EthereumProvider; import io.zksync.transaction.type.Transaction712; +import java.io.IOException; +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; @@ -27,132 +33,140 @@ import org.web3j.utils.Convert; import org.web3j.utils.Numeric; -import java.io.IOException; -import java.math.BigInteger; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - @Disabled public class SelfTransferTest { - private static Credentials credentials; - private static PrivateKeyEthSigner key; - private static Eip712Domain domain; - private static Transaction712 message; - private static ZkSync zksync; - private static Web3j web3j; - private static ZkSyncWallet wallet; - private static BigInteger chainId; - - - @BeforeAll - public static void setUp() throws IOException { - - final String privateKey = "PRIVATE_KEY"; - zksync = ZkSync.build(new HttpService("https://zksync2-testnet.zksync.dev")); - credentials = Credentials.create(privateKey); - key = new PrivateKeyEthSigner(credentials, 280L); - wallet = new ZkSyncWallet(zksync, key, Token.ETH); - web3j = Web3j.build(new HttpService("https://goerli.infura.io/v3/API_KEY")); - chainId = web3j.ethChainId().send().getChainId(); - domain = Eip712Domain.defaultDomain(280L); - } - - @Test - public void SelfTransfer() throws IOException { - 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); - - } - - - @Test - public void withdrawTest() throws Exception { - TransactionReceipt receipt = wallet.withdraw(credentials.getAddress(), Convert.toWei("0.117649", Convert.Unit.ETHER).toBigInteger()).send(); - System.out.println(receipt); - } - - - @Test - public void deployTestContract() throws Exception { - String bytecode = "BYTE_CODE"; - TransactionReceipt receipt = wallet.deploy(Numeric.hexStringToByteArray(bytecode)).send(); - System.out.println(receipt); - - } - - @Test - public void deployTestContractWithConstructor() throws Exception { - String name = "Test"; - String symbol = "COIN"; - 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 = "CONTRACT_BYTECODE"; - String calldata = FunctionEncoder.encodeConstructor(inputParameter); - TransactionReceipt receipt = wallet.deploy(Numeric.hexStringToByteArray(bytecode), Numeric.hexStringToByteArray(calldata)).send(); - - System.out.println(receipt); - } - - - @Test - public void executeContract() throws Exception { - String contractAddress = "CONTRACT_ADDRESS"; - Uint256 amount = new Uint256(new BigInteger("1234").multiply(new BigInteger(String.valueOf(10)).pow(18))); - String address = credentials.getAddress(); - Function contractFunction = new Function("mint", Arrays.asList(new Address(address), amount), Collections.emptyList()); - - TransactionReceipt receipt = wallet.execute("0x2da10A1e27bF85cEdD8FFb1AbBe97e53391C0295", contractFunction, null).send(); - System.out.println(receipt); - } - - - @Test - public void callTest() throws Exception { - String contractAddress = "0x0d7a0d1097072c9fddb6f934159cfa8479e0d1b1"; - - Function contractFunction = new Function("testCallString", - Collections.emptyList(), - Collections.singletonList(new TypeReference() { - })); - - org.web3j.protocol.core.methods.request.Transaction call = org.web3j.protocol.core.methods.request.Transaction.createEthCallTransaction( - null, - contractAddress, - FunctionEncoder.encode(contractFunction) - ); - - EthCall ethCall = wallet.getZksync().ethCall(call, ZkBlockParameterName.COMMITTED).send(); - String fooName = (String) FunctionReturnDecoder.decode(ethCall.getValue(), contractFunction.getOutputParameters()).get(0).getValue(); - System.out.println(fooName); - System.out.println(ethCall.getValue()); - } - - - @Test - public void testDeposit() throws IOException { - 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); - } - - -} \ No newline at end of file + private static Credentials credentials; + private static PrivateKeyEthSigner key; + private static Eip712Domain domain; + private static Transaction712 message; + private static ZkSync zksync; + private static Web3j web3j; + private static ZkSyncWallet wallet; + private static BigInteger chainId; + + @BeforeAll + public static void setUp() throws IOException { + + final String privateKey = "PRIVATE_KEY"; + zksync = ZkSync.build(new HttpService("https://zksync2-testnet.zksync.dev")); + credentials = Credentials.create(privateKey); + key = new PrivateKeyEthSigner(credentials, 280L); + wallet = new ZkSyncWallet(zksync, key, Token.ETH); + web3j = Web3j.build(new HttpService("https://goerli.infura.io/v3/API_KEY")); + chainId = web3j.ethChainId().send().getChainId(); + domain = Eip712Domain.defaultDomain(280L); + } + + @Test + public void SelfTransfer() throws IOException { + 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); + } + + @Test + public void withdrawTest() throws Exception { + TransactionReceipt receipt = + wallet + .withdraw( + credentials.getAddress(), + Convert.toWei("0.117649", Convert.Unit.ETHER).toBigInteger()) + .send(); + System.out.println(receipt); + } + + @Test + public void deployTestContract() throws Exception { + String bytecode = "BYTE_CODE"; + TransactionReceipt receipt = wallet.deploy(Numeric.hexStringToByteArray(bytecode)).send(); + System.out.println(receipt); + } + + @Test + public void deployTestContractWithConstructor() throws Exception { + String name = "Test"; + String symbol = "COIN"; + 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 = "CONTRACT_BYTECODE"; + String calldata = FunctionEncoder.encodeConstructor(inputParameter); + TransactionReceipt receipt = + wallet + .deploy(Numeric.hexStringToByteArray(bytecode), Numeric.hexStringToByteArray(calldata)) + .send(); + + System.out.println(receipt); + } + + @Test + public void executeContract() throws Exception { + String contractAddress = "CONTRACT_ADDRESS"; + Uint256 amount = + new Uint256(new BigInteger("1234").multiply(new BigInteger(String.valueOf(10)).pow(18))); + String address = credentials.getAddress(); + Function contractFunction = + new Function("mint", Arrays.asList(new Address(address), amount), Collections.emptyList()); + + TransactionReceipt receipt = + wallet.execute("0x2da10A1e27bF85cEdD8FFb1AbBe97e53391C0295", contractFunction, null).send(); + System.out.println(receipt); + } + + @Test + public void callTest() throws Exception { + String contractAddress = "0x0d7a0d1097072c9fddb6f934159cfa8479e0d1b1"; + + Function contractFunction = + new Function( + "testCallString", + Collections.emptyList(), + Collections.singletonList(new TypeReference() {})); + + org.web3j.protocol.core.methods.request.Transaction call = + org.web3j.protocol.core.methods.request.Transaction.createEthCallTransaction( + null, contractAddress, FunctionEncoder.encode(contractFunction)); + + EthCall ethCall = wallet.getZksync().ethCall(call, ZkBlockParameterName.COMMITTED).send(); + String fooName = + (String) + FunctionReturnDecoder.decode(ethCall.getValue(), contractFunction.getOutputParameters()) + .get(0) + .getValue(); + System.out.println(fooName); + System.out.println(ethCall.getValue()); + } + + @Test + public void testDeposit() throws IOException { + 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); + } +} diff --git a/src/test/java/io/zksync/crypto/signer/Transaction712SignTest.java b/src/test/java/io/zksync/crypto/signer/Transaction712SignTest.java index 521ad4b..1418662 100644 --- a/src/test/java/io/zksync/crypto/signer/Transaction712SignTest.java +++ b/src/test/java/io/zksync/crypto/signer/Transaction712SignTest.java @@ -2,90 +2,78 @@ import static org.junit.jupiter.api.Assertions.*; +import io.zksync.crypto.eip712.Eip712Domain; import io.zksync.methods.request.Eip712Meta; import io.zksync.methods.request.PaymasterParams; import io.zksync.transaction.type.Transaction712; +import java.math.BigInteger; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.web3j.crypto.Credentials; -import io.zksync.crypto.eip712.Eip712Domain; - import org.web3j.utils.Numeric; -import java.math.BigInteger; - public class Transaction712SignTest { - private static Credentials credentials; - private static PrivateKeyEthSigner key; - private static Eip712Domain domain; - private static Transaction712 message; - - @BeforeAll - public static void setUp() { - final String privateKey = "0x0000000000000000000000000000000000000000000000000000000000000001"; - - credentials = Credentials.create(privateKey); - key = new PrivateKeyEthSigner(credentials, 280L); - - domain = Eip712Domain.defaultDomain(280L); - - message = buildTransferTransaction(); - } - - @Test - public void testSignTypedTransferData() { - final String signature = key.signTypedData(domain, message).join(); - - assertEquals("0x4a9ff9c2a31be0ef25954a4906865953edab960ed7f509a00c86db9f70df01a904f73dbac053f119f6d90878f95c5da1f666e1dc987355fa666e82d50a56cdce1b", signature); - } - - @Test - public void testSignTypedExecuteData() { - message = buildExecuteTransaction(); - final String signature = key.signTypedData(domain, message).join(); - assertEquals("0x07c9e373dba52a79d4c5d539aa73ad6f3dcd362702788fa5177f045af6f63ef638f04c295e9469249cb960146d3d9d101a13a5d1e6795f439a3cf6f222200a761b", signature); - } - - - private static Transaction712 buildTransferTransaction() { - return new Transaction712( - 280, - BigInteger.valueOf(0), - Numeric.toBigInt("0x30a108"), - "0x000102030405060708090a0b0c0d0e0f10111213", - Numeric.toBigInt("0x1"), - "", - BigInteger.ZERO, - Numeric.toBigInt("0xee6b280"), - "0x7e5f4552091a69125d5dfcb7b8c2659029395bdf", - new Eip712Meta( - Numeric.toBigInt("0x3d0e"), - null, - null, - new PaymasterParams() - ) - ); - } - - - private static Transaction712 buildExecuteTransaction() { - return new Transaction712( - 280, - Numeric.toBigInt("0x0"), - Numeric.toBigInt("0x3dbb95"), - "0x0000000000000000000000000000000000000000", - Numeric.toBigInt("0x0"), - "0xa9059cbb000000000000000000000000b06b15bc1818971cbfd1b181c345a5db1ecda00d00000000000000000000000000000000000000000000000000000000312c8040", - BigInteger.ZERO, - Numeric.toBigInt("0xee6b280"), - "0x7e5f4552091a69125d5dfcb7b8c2659029395bdf", - new Eip712Meta( - Numeric.toBigInt("0x4e20"), - null, - null, - new PaymasterParams() - ) - ); - } -} \ No newline at end of file + private static Credentials credentials; + private static PrivateKeyEthSigner key; + private static Eip712Domain domain; + private static Transaction712 message; + + @BeforeAll + public static void setUp() { + final String privateKey = "0x0000000000000000000000000000000000000000000000000000000000000001"; + + credentials = Credentials.create(privateKey); + key = new PrivateKeyEthSigner(credentials, 280L); + + domain = Eip712Domain.defaultDomain(280L); + + message = buildTransferTransaction(); + } + + @Test + public void testSignTypedTransferData() { + final String signature = key.signTypedData(domain, message).join(); + + assertEquals( + "0x4a9ff9c2a31be0ef25954a4906865953edab960ed7f509a00c86db9f70df01a904f73dbac053f119f6d90878f95c5da1f666e1dc987355fa666e82d50a56cdce1b", + signature); + } + + @Test + public void testSignTypedExecuteData() { + message = buildExecuteTransaction(); + final String signature = key.signTypedData(domain, message).join(); + assertEquals( + "0x07c9e373dba52a79d4c5d539aa73ad6f3dcd362702788fa5177f045af6f63ef638f04c295e9469249cb960146d3d9d101a13a5d1e6795f439a3cf6f222200a761b", + signature); + } + + private static Transaction712 buildTransferTransaction() { + return new Transaction712( + 280, + BigInteger.valueOf(0), + Numeric.toBigInt("0x30a108"), + "0x000102030405060708090a0b0c0d0e0f10111213", + Numeric.toBigInt("0x1"), + "", + BigInteger.ZERO, + Numeric.toBigInt("0xee6b280"), + "0x7e5f4552091a69125d5dfcb7b8c2659029395bdf", + new Eip712Meta(Numeric.toBigInt("0x3d0e"), null, null, new PaymasterParams())); + } + + private static Transaction712 buildExecuteTransaction() { + return new Transaction712( + 280, + Numeric.toBigInt("0x0"), + Numeric.toBigInt("0x3dbb95"), + "0x0000000000000000000000000000000000000000", + Numeric.toBigInt("0x0"), + "0xa9059cbb000000000000000000000000b06b15bc1818971cbfd1b181c345a5db1ecda00d00000000000000000000000000000000000000000000000000000000312c8040", + BigInteger.ZERO, + Numeric.toBigInt("0xee6b280"), + "0x7e5f4552091a69125d5dfcb7b8c2659029395bdf", + new Eip712Meta(Numeric.toBigInt("0x4e20"), null, null, new PaymasterParams())); + } +} diff --git a/src/test/java/io/zksync/helper/ConstructorContract.java b/src/test/java/io/zksync/helper/ConstructorContract.java index 847da3e..1426449 100644 --- a/src/test/java/io/zksync/helper/ConstructorContract.java +++ b/src/test/java/io/zksync/helper/ConstructorContract.java @@ -6,8 +6,6 @@ import java.math.BigInteger; import java.util.Arrays; import java.util.Collections; - -import io.zksync.abi.ZkFunctionEncoder; import org.web3j.abi.FunctionEncoder; import org.web3j.abi.TypeReference; import org.web3j.abi.datatypes.Function; @@ -20,121 +18,227 @@ import org.web3j.tx.Contract; import org.web3j.tx.TransactionManager; import org.web3j.tx.gas.ContractGasProvider; -import org.web3j.utils.Numeric; /** - *

Auto generated code. + * Auto generated code. + * *

Do not modify! + * *

Please use the web3j command line tools, - * or the org.web3j.codegen.SolidityFunctionWrapperGenerator in the - * codegen module to update. + * or the org.web3j.codegen.SolidityFunctionWrapperGenerator in the codegen module to update. * *

Generated with web3j version 1.4.1. */ @SuppressWarnings("rawtypes") public class ConstructorContract extends Contract { - public static final String BINARY; - - static { - try (FileInputStream fis = new FileInputStream("src/test/resources/constructorContractBinary.hex")) { - ByteArrayOutputStream buffer = new ByteArrayOutputStream(); - - int count; - byte[] bytes = new byte[16536]; - while ((count = fis.read(bytes)) != -1) { - buffer.write(bytes, 0, count); - } - BINARY = buffer.toString("UTF-8"); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - - public static final String FUNC_GET = "get"; - - @Deprecated - protected ConstructorContract(String contractAddress, Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) { - super(BINARY, contractAddress, web3j, credentials, gasPrice, gasLimit); - } - - protected ConstructorContract(String contractAddress, Web3j web3j, Credentials credentials, ContractGasProvider contractGasProvider) { - super(BINARY, contractAddress, web3j, credentials, contractGasProvider); - } - - @Deprecated - protected ConstructorContract(String contractAddress, Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit) { - super(BINARY, contractAddress, web3j, transactionManager, gasPrice, gasLimit); - } - - protected ConstructorContract(String contractAddress, Web3j web3j, TransactionManager transactionManager, ContractGasProvider contractGasProvider) { - super(BINARY, contractAddress, web3j, transactionManager, contractGasProvider); - } - - public RemoteFunctionCall get() { - final Function function = new Function(FUNC_GET, - Arrays.asList(), - Arrays.>asList(new TypeReference() {})); - return executeRemoteCallSingleValueReturn(function, BigInteger.class); - } - - public static Function encodeGet() { - return new Function(FUNC_GET, - Collections.emptyList(), - Collections.singletonList(new TypeReference() { - })); - } - - public static String encodeConstructor(BigInteger a, BigInteger b, Boolean shouldRevert) { - return FunctionEncoder.encodeConstructor(Arrays.asList(new org.web3j.abi.datatypes.generated.Uint256(a), + public static final String BINARY; + + static { + try (FileInputStream fis = + new FileInputStream("src/test/resources/constructorContractBinary.hex")) { + ByteArrayOutputStream buffer = new ByteArrayOutputStream(); + + int count; + byte[] bytes = new byte[16536]; + while ((count = fis.read(bytes)) != -1) { + buffer.write(bytes, 0, count); + } + BINARY = buffer.toString("UTF-8"); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + public static final String FUNC_GET = "get"; + + @Deprecated + protected ConstructorContract( + String contractAddress, + Web3j web3j, + Credentials credentials, + BigInteger gasPrice, + BigInteger gasLimit) { + super(BINARY, contractAddress, web3j, credentials, gasPrice, gasLimit); + } + + protected ConstructorContract( + String contractAddress, + Web3j web3j, + Credentials credentials, + ContractGasProvider contractGasProvider) { + super(BINARY, contractAddress, web3j, credentials, contractGasProvider); + } + + @Deprecated + protected ConstructorContract( + String contractAddress, + Web3j web3j, + TransactionManager transactionManager, + BigInteger gasPrice, + BigInteger gasLimit) { + super(BINARY, contractAddress, web3j, transactionManager, gasPrice, gasLimit); + } + + protected ConstructorContract( + String contractAddress, + Web3j web3j, + TransactionManager transactionManager, + ContractGasProvider contractGasProvider) { + super(BINARY, contractAddress, web3j, transactionManager, contractGasProvider); + } + + public RemoteFunctionCall get() { + final Function function = + new Function( + FUNC_GET, + Arrays.asList(), + Arrays.>asList(new TypeReference() {})); + return executeRemoteCallSingleValueReturn(function, BigInteger.class); + } + + public static Function encodeGet() { + return new Function( + FUNC_GET, + Collections.emptyList(), + Collections.singletonList(new TypeReference() {})); + } + + public static String encodeConstructor(BigInteger a, BigInteger b, Boolean shouldRevert) { + return FunctionEncoder.encodeConstructor( + Arrays.asList( + new org.web3j.abi.datatypes.generated.Uint256(a), + new org.web3j.abi.datatypes.generated.Uint256(b), + new org.web3j.abi.datatypes.Bool(shouldRevert))); + } + + @Deprecated + public static ConstructorContract load( + String contractAddress, + Web3j web3j, + Credentials credentials, + BigInteger gasPrice, + BigInteger gasLimit) { + return new ConstructorContract(contractAddress, web3j, credentials, gasPrice, gasLimit); + } + + @Deprecated + public static ConstructorContract load( + String contractAddress, + Web3j web3j, + TransactionManager transactionManager, + BigInteger gasPrice, + BigInteger gasLimit) { + return new ConstructorContract(contractAddress, web3j, transactionManager, gasPrice, gasLimit); + } + + public static ConstructorContract load( + String contractAddress, + Web3j web3j, + Credentials credentials, + ContractGasProvider contractGasProvider) { + return new ConstructorContract(contractAddress, web3j, credentials, contractGasProvider); + } + + public static ConstructorContract load( + String contractAddress, + Web3j web3j, + TransactionManager transactionManager, + ContractGasProvider contractGasProvider) { + return new ConstructorContract(contractAddress, web3j, transactionManager, contractGasProvider); + } + + public static RemoteCall deploy( + Web3j web3j, + Credentials credentials, + ContractGasProvider contractGasProvider, + BigInteger a, + BigInteger b, + Boolean shouldRevert) { + String encodedConstructor = + FunctionEncoder.encodeConstructor( + Arrays.asList( + new org.web3j.abi.datatypes.generated.Uint256(a), new org.web3j.abi.datatypes.generated.Uint256(b), new org.web3j.abi.datatypes.Bool(shouldRevert))); - } - - @Deprecated - public static ConstructorContract load(String contractAddress, Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) { - return new ConstructorContract(contractAddress, web3j, credentials, gasPrice, gasLimit); - } - - @Deprecated - public static ConstructorContract load(String contractAddress, Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit) { - return new ConstructorContract(contractAddress, web3j, transactionManager, gasPrice, gasLimit); - } - - public static ConstructorContract load(String contractAddress, Web3j web3j, Credentials credentials, ContractGasProvider contractGasProvider) { - return new ConstructorContract(contractAddress, web3j, credentials, contractGasProvider); - } - - public static ConstructorContract load(String contractAddress, Web3j web3j, TransactionManager transactionManager, ContractGasProvider contractGasProvider) { - return new ConstructorContract(contractAddress, web3j, transactionManager, contractGasProvider); - } - - public static RemoteCall deploy(Web3j web3j, Credentials credentials, ContractGasProvider contractGasProvider, BigInteger a, BigInteger b, Boolean shouldRevert) { - String encodedConstructor = FunctionEncoder.encodeConstructor(Arrays.asList(new org.web3j.abi.datatypes.generated.Uint256(a), - new org.web3j.abi.datatypes.generated.Uint256(b), - new org.web3j.abi.datatypes.Bool(shouldRevert))); - return deployRemoteCall(ConstructorContract.class, web3j, credentials, contractGasProvider, BINARY, encodedConstructor); - } - - public static RemoteCall deploy(Web3j web3j, TransactionManager transactionManager, ContractGasProvider contractGasProvider, BigInteger a, BigInteger b, Boolean shouldRevert) { - String encodedConstructor = FunctionEncoder.encodeConstructor(Arrays.asList(new org.web3j.abi.datatypes.generated.Uint256(a), - new org.web3j.abi.datatypes.generated.Uint256(b), + return deployRemoteCall( + ConstructorContract.class, + web3j, + credentials, + contractGasProvider, + BINARY, + encodedConstructor); + } + + public static RemoteCall deploy( + Web3j web3j, + TransactionManager transactionManager, + ContractGasProvider contractGasProvider, + BigInteger a, + BigInteger b, + Boolean shouldRevert) { + String encodedConstructor = + FunctionEncoder.encodeConstructor( + Arrays.asList( + new org.web3j.abi.datatypes.generated.Uint256(a), + new org.web3j.abi.datatypes.generated.Uint256(b), new org.web3j.abi.datatypes.Bool(shouldRevert))); - return deployRemoteCall(ConstructorContract.class, web3j, transactionManager, contractGasProvider, BINARY, encodedConstructor); - } - - @Deprecated - public static RemoteCall deploy(Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit, BigInteger a, BigInteger b, Boolean shouldRevert) { - String encodedConstructor = FunctionEncoder.encodeConstructor(Arrays.asList(new org.web3j.abi.datatypes.generated.Uint256(a), - new org.web3j.abi.datatypes.generated.Uint256(b), + return deployRemoteCall( + ConstructorContract.class, + web3j, + transactionManager, + contractGasProvider, + BINARY, + encodedConstructor); + } + + @Deprecated + public static RemoteCall deploy( + Web3j web3j, + Credentials credentials, + BigInteger gasPrice, + BigInteger gasLimit, + BigInteger a, + BigInteger b, + Boolean shouldRevert) { + String encodedConstructor = + FunctionEncoder.encodeConstructor( + Arrays.asList( + new org.web3j.abi.datatypes.generated.Uint256(a), + new org.web3j.abi.datatypes.generated.Uint256(b), new org.web3j.abi.datatypes.Bool(shouldRevert))); - return deployRemoteCall(ConstructorContract.class, web3j, credentials, gasPrice, gasLimit, BINARY, encodedConstructor); - } - - @Deprecated - public static RemoteCall deploy(Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit, BigInteger a, BigInteger b, Boolean shouldRevert) { - String encodedConstructor = FunctionEncoder.encodeConstructor(Arrays.asList(new org.web3j.abi.datatypes.generated.Uint256(a), - new org.web3j.abi.datatypes.generated.Uint256(b), + return deployRemoteCall( + ConstructorContract.class, + web3j, + credentials, + gasPrice, + gasLimit, + BINARY, + encodedConstructor); + } + + @Deprecated + public static RemoteCall deploy( + Web3j web3j, + TransactionManager transactionManager, + BigInteger gasPrice, + BigInteger gasLimit, + BigInteger a, + BigInteger b, + Boolean shouldRevert) { + String encodedConstructor = + FunctionEncoder.encodeConstructor( + Arrays.asList( + new org.web3j.abi.datatypes.generated.Uint256(a), + new org.web3j.abi.datatypes.generated.Uint256(b), new org.web3j.abi.datatypes.Bool(shouldRevert))); - return deployRemoteCall(ConstructorContract.class, web3j, transactionManager, gasPrice, gasLimit, BINARY, encodedConstructor); - } + return deployRemoteCall( + ConstructorContract.class, + web3j, + transactionManager, + gasPrice, + gasLimit, + BINARY, + encodedConstructor); + } } diff --git a/src/test/java/io/zksync/helper/CounterContract.java b/src/test/java/io/zksync/helper/CounterContract.java index c5e85bc..7161200 100644 --- a/src/test/java/io/zksync/helper/CounterContract.java +++ b/src/test/java/io/zksync/helper/CounterContract.java @@ -17,100 +17,154 @@ import org.web3j.tx.gas.ContractGasProvider; /** - *

Auto generated code. + * Auto generated code. + * *

Do not modify! + * *

Please use the web3j command line tools, - * or the org.web3j.codegen.SolidityFunctionWrapperGenerator in the - * codegen module to update. + * or the org.web3j.codegen.SolidityFunctionWrapperGenerator in the codegen module to update. * *

Generated with web3j version 1.4.1. */ @SuppressWarnings("rawtypes") public class CounterContract extends Contract { - public static final String BINARY = "0x000200000000000200010000000103550000006001100270000000410010019d000000010120018f000000000110004c000000080000c13d00fd00180000040f00fd00090000040f0000008001000039000000400200003900000000001204350000000001000416000000000110004c000000160000c13d000000200100003900000100020000390000000000120439000001200100003900000000000104390000004201000041000000fe0001042e0000000001000019000000ff0001043000040000000000020000000001000410000080020210008c000000330000613d0000000002000411000080010220008c000000330000613d0000004302000041000000000020043900000004020000390000000000120439000000440100004100008002020000390000000003000415000000040330008a00000020033000c900fd00e00000040f000000ff01000039000000030110024f000000000110004c000000560000613d000000040100035f000000000101043b000000000110004c000000330000c13d0000000001000019000000fe0001042e0000008001000039000000400600003900000000001604350000000001000031000000030210008c000000540000a13d0000000102000367000000000302043b000000e003300270000000450430009c0000006c0000613d000000460230009c000000580000613d000000470230009c000000540000c13d0000000002000416000000000220004c000000800000c13d000000040110008a00000048020000410000001f0310008c000000000300001900000000030220190000004801100197000000000410004c0000000002008019000000480110009c00000000010300190000000001026019000000000110004c0000008e0000c13d0000000001000019000000ff000104300000000001000019000000ff000104300000000001000019000000ff000104300000000002000416000000000220004c0000007e0000c13d000000040110008a000000010200008a0000004803000041000000000221004b000000000200001900000000020320190000004801100197000000480410009c00000000030080190000004801100167000000480110009c00000000010200190000000001036019000000000110004c000000840000c13d0000000001000019000000ff000104300000000003000416000000000330004c000000820000c13d000000040110008a00000048030000410000003f0410008c000000000400001900000000040320190000004801100197000000000510004c0000000003008019000000480110009c00000000010400190000000001036019000000000110004c000000a20000c13d0000000001000019000000ff000104300000000001000019000000ff000104300000000001000019000000ff000104300000000001000019000000ff000104300000000001000019000200000006001d00fd00fb0000040f000000020200002900000000020204330000000000120435000000400120021000000049011001970000004c011001c7000000fe0001042e000200000006001d000000000100001900fd00fb0000040f00000001020003670000000402200370000000000202043b0000000001120019000000000221004b00000000020000190000000102004039000000010220018f000000000220004c000000be0000613d0000004a0100004100000000001004350000001101000039000000040200003900000000001204350000004b01000041000000ff000104300000002401200370000000000201043b000000000120004c0000000001000019000000010100c039000000000112004b000000c50000c13d000100000002001d000200000006001d000000000100001900fd00fb0000040f00000001020003670000000402200370000000000202043b0000000001120019000000000221004b00000000020000190000000102004039000000010220018f000000000220004c000000c70000613d0000004a0100004100000000001004350000001101000039000000040200003900000000001204350000004b01000041000000ff00010430000000000200001900fd00f90000040f0000000201000029000000000101043300000040011002100000004901100197000000fe0001042e0000000001000019000000ff00010430000000000200001900fd00f90000040f000000020100002900000000010104330000000102000029000000000220004c000000d10000c13d00000040011002100000004901100197000000fe0001042e00000044021000390000004d03000041000000000032043500000024021000390000001a0300003900000000003204350000004e020000410000000000210435000000040210003900000020030000390000000000320435000000400110021000000049011001970000004f011001c7000000ff000104300002000000000002000200000003001d0000002003300039000100000003001d000000ef002104230000000203000029000000200230011a000000000201035500000048010000410000000102000029000000200220011a00000000021201bd00000000010300190000000200000005000000000001042d0000000203000029000000200230011a000000000201035500000050010000410000000102000029000000200220011a000000000212018d00000000010300190000000200000005000000000001042d000000000012041b000000000001042d000000000101041a000000000001042d000000fd00000432000000fe0001042e000000ff00010430000000000000000100000000000000010000000000000001000000000000000100000000000000000000000000000000000000000000000000000000ffffffff00000002000000000000000000000000000000400000010000000000000000001806aa1896bbf26568e884a7374b41e002500962caba6a15023a8d90e8508b830200020000000000000000000000000000000024000000000000000000000000000000000000000000000000000000000000000000000000000000000436dad6000000000000000000000000000000000000000000000000000000006d4ce63c000000000000000000000000000000000000000000000000000000007cf5dab080000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000ffffffff00000000000000004e487b71000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000024000000000000000000000000000000000000000000000000000000000000002000000000000000000000000054686973206d6574686f6420616c77617973207265766572747300000000000008c379a00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000640000000000000000000000007fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"; - public static final String FUNC_GET = "get"; - - public static final String FUNC_INCREMENT = "increment"; - - @Deprecated - protected CounterContract(String contractAddress, Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) { - super(BINARY, contractAddress, web3j, credentials, gasPrice, gasLimit); - } - - protected CounterContract(String contractAddress, Web3j web3j, Credentials credentials, ContractGasProvider contractGasProvider) { - super(BINARY, contractAddress, web3j, credentials, contractGasProvider); - } - - @Deprecated - protected CounterContract(String contractAddress, Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit) { - super(BINARY, contractAddress, web3j, transactionManager, gasPrice, gasLimit); - } - - protected CounterContract(String contractAddress, Web3j web3j, TransactionManager transactionManager, ContractGasProvider contractGasProvider) { - super(BINARY, contractAddress, web3j, transactionManager, contractGasProvider); - } - - public RemoteFunctionCall get() { - final Function function = new Function(FUNC_GET, - Arrays.asList(), - Arrays.>asList(new TypeReference() {})); - return executeRemoteCallSingleValueReturn(function, BigInteger.class); - } - - public RemoteFunctionCall increment(BigInteger x) { - final Function function = new Function( - FUNC_INCREMENT, - Arrays.asList(new org.web3j.abi.datatypes.generated.Uint256(x)), - Collections.>emptyList()); - return executeRemoteCallTransaction(function); - } - - public static Function encodeIncrement(BigInteger _value) { - return new Function( - FUNC_INCREMENT, - Arrays.asList(new org.web3j.abi.datatypes.generated.Uint256(_value)), - Collections.>emptyList()); - } - - public static Function encodeGet() { - return new Function(FUNC_GET, - Arrays.asList(), - Arrays.>asList(new TypeReference() {})); - } - - @Deprecated - public static CounterContract load(String contractAddress, Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) { - return new CounterContract(contractAddress, web3j, credentials, gasPrice, gasLimit); - } - - @Deprecated - public static CounterContract load(String contractAddress, Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit) { - return new CounterContract(contractAddress, web3j, transactionManager, gasPrice, gasLimit); - } - - public static CounterContract load(String contractAddress, Web3j web3j, Credentials credentials, ContractGasProvider contractGasProvider) { - return new CounterContract(contractAddress, web3j, credentials, contractGasProvider); - } - - public static CounterContract load(String contractAddress, Web3j web3j, TransactionManager transactionManager, ContractGasProvider contractGasProvider) { - return new CounterContract(contractAddress, web3j, transactionManager, contractGasProvider); - } - - public static RemoteCall deploy(Web3j web3j, Credentials credentials, ContractGasProvider contractGasProvider) { - return deployRemoteCall(CounterContract.class, web3j, credentials, contractGasProvider, BINARY, ""); - } - - @Deprecated - public static RemoteCall deploy(Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) { - return deployRemoteCall(CounterContract.class, web3j, credentials, gasPrice, gasLimit, BINARY, ""); - } - - public static RemoteCall deploy(Web3j web3j, TransactionManager transactionManager, ContractGasProvider contractGasProvider) { - return deployRemoteCall(CounterContract.class, web3j, transactionManager, contractGasProvider, BINARY, ""); - } - - @Deprecated - public static RemoteCall deploy(Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit) { - return deployRemoteCall(CounterContract.class, web3j, transactionManager, gasPrice, gasLimit, BINARY, ""); - } + public static final String BINARY = + "0x000200000000000200010000000103550000006001100270000000410010019d000000010120018f000000000110004c000000080000c13d00fd00180000040f00fd00090000040f0000008001000039000000400200003900000000001204350000000001000416000000000110004c000000160000c13d000000200100003900000100020000390000000000120439000001200100003900000000000104390000004201000041000000fe0001042e0000000001000019000000ff0001043000040000000000020000000001000410000080020210008c000000330000613d0000000002000411000080010220008c000000330000613d0000004302000041000000000020043900000004020000390000000000120439000000440100004100008002020000390000000003000415000000040330008a00000020033000c900fd00e00000040f000000ff01000039000000030110024f000000000110004c000000560000613d000000040100035f000000000101043b000000000110004c000000330000c13d0000000001000019000000fe0001042e0000008001000039000000400600003900000000001604350000000001000031000000030210008c000000540000a13d0000000102000367000000000302043b000000e003300270000000450430009c0000006c0000613d000000460230009c000000580000613d000000470230009c000000540000c13d0000000002000416000000000220004c000000800000c13d000000040110008a00000048020000410000001f0310008c000000000300001900000000030220190000004801100197000000000410004c0000000002008019000000480110009c00000000010300190000000001026019000000000110004c0000008e0000c13d0000000001000019000000ff000104300000000001000019000000ff000104300000000001000019000000ff000104300000000002000416000000000220004c0000007e0000c13d000000040110008a000000010200008a0000004803000041000000000221004b000000000200001900000000020320190000004801100197000000480410009c00000000030080190000004801100167000000480110009c00000000010200190000000001036019000000000110004c000000840000c13d0000000001000019000000ff000104300000000003000416000000000330004c000000820000c13d000000040110008a00000048030000410000003f0410008c000000000400001900000000040320190000004801100197000000000510004c0000000003008019000000480110009c00000000010400190000000001036019000000000110004c000000a20000c13d0000000001000019000000ff000104300000000001000019000000ff000104300000000001000019000000ff000104300000000001000019000000ff000104300000000001000019000200000006001d00fd00fb0000040f000000020200002900000000020204330000000000120435000000400120021000000049011001970000004c011001c7000000fe0001042e000200000006001d000000000100001900fd00fb0000040f00000001020003670000000402200370000000000202043b0000000001120019000000000221004b00000000020000190000000102004039000000010220018f000000000220004c000000be0000613d0000004a0100004100000000001004350000001101000039000000040200003900000000001204350000004b01000041000000ff000104300000002401200370000000000201043b000000000120004c0000000001000019000000010100c039000000000112004b000000c50000c13d000100000002001d000200000006001d000000000100001900fd00fb0000040f00000001020003670000000402200370000000000202043b0000000001120019000000000221004b00000000020000190000000102004039000000010220018f000000000220004c000000c70000613d0000004a0100004100000000001004350000001101000039000000040200003900000000001204350000004b01000041000000ff00010430000000000200001900fd00f90000040f0000000201000029000000000101043300000040011002100000004901100197000000fe0001042e0000000001000019000000ff00010430000000000200001900fd00f90000040f000000020100002900000000010104330000000102000029000000000220004c000000d10000c13d00000040011002100000004901100197000000fe0001042e00000044021000390000004d03000041000000000032043500000024021000390000001a0300003900000000003204350000004e020000410000000000210435000000040210003900000020030000390000000000320435000000400110021000000049011001970000004f011001c7000000ff000104300002000000000002000200000003001d0000002003300039000100000003001d000000ef002104230000000203000029000000200230011a000000000201035500000048010000410000000102000029000000200220011a00000000021201bd00000000010300190000000200000005000000000001042d0000000203000029000000200230011a000000000201035500000050010000410000000102000029000000200220011a000000000212018d00000000010300190000000200000005000000000001042d000000000012041b000000000001042d000000000101041a000000000001042d000000fd00000432000000fe0001042e000000ff00010430000000000000000100000000000000010000000000000001000000000000000100000000000000000000000000000000000000000000000000000000ffffffff00000002000000000000000000000000000000400000010000000000000000001806aa1896bbf26568e884a7374b41e002500962caba6a15023a8d90e8508b830200020000000000000000000000000000000024000000000000000000000000000000000000000000000000000000000000000000000000000000000436dad6000000000000000000000000000000000000000000000000000000006d4ce63c000000000000000000000000000000000000000000000000000000007cf5dab080000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000ffffffff00000000000000004e487b71000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000024000000000000000000000000000000000000000000000000000000000000002000000000000000000000000054686973206d6574686f6420616c77617973207265766572747300000000000008c379a00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000640000000000000000000000007fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"; + public static final String FUNC_GET = "get"; + + public static final String FUNC_INCREMENT = "increment"; + + @Deprecated + protected CounterContract( + String contractAddress, + Web3j web3j, + Credentials credentials, + BigInteger gasPrice, + BigInteger gasLimit) { + super(BINARY, contractAddress, web3j, credentials, gasPrice, gasLimit); + } + + protected CounterContract( + String contractAddress, + Web3j web3j, + Credentials credentials, + ContractGasProvider contractGasProvider) { + super(BINARY, contractAddress, web3j, credentials, contractGasProvider); + } + + @Deprecated + protected CounterContract( + String contractAddress, + Web3j web3j, + TransactionManager transactionManager, + BigInteger gasPrice, + BigInteger gasLimit) { + super(BINARY, contractAddress, web3j, transactionManager, gasPrice, gasLimit); + } + + protected CounterContract( + String contractAddress, + Web3j web3j, + TransactionManager transactionManager, + ContractGasProvider contractGasProvider) { + super(BINARY, contractAddress, web3j, transactionManager, contractGasProvider); + } + + public RemoteFunctionCall get() { + final Function function = + new Function( + FUNC_GET, + Arrays.asList(), + Arrays.>asList(new TypeReference() {})); + return executeRemoteCallSingleValueReturn(function, BigInteger.class); + } + + public RemoteFunctionCall increment(BigInteger x) { + final Function function = + new Function( + FUNC_INCREMENT, + Arrays.asList(new org.web3j.abi.datatypes.generated.Uint256(x)), + Collections.>emptyList()); + return executeRemoteCallTransaction(function); + } + + public static Function encodeIncrement(BigInteger _value) { + return new Function( + FUNC_INCREMENT, + Arrays.asList(new org.web3j.abi.datatypes.generated.Uint256(_value)), + Collections.>emptyList()); + } + + public static Function encodeGet() { + return new Function( + FUNC_GET, + Arrays.asList(), + Arrays.>asList(new TypeReference() {})); + } + + @Deprecated + public static CounterContract load( + String contractAddress, + Web3j web3j, + Credentials credentials, + BigInteger gasPrice, + BigInteger gasLimit) { + return new CounterContract(contractAddress, web3j, credentials, gasPrice, gasLimit); + } + + @Deprecated + public static CounterContract load( + String contractAddress, + Web3j web3j, + TransactionManager transactionManager, + BigInteger gasPrice, + BigInteger gasLimit) { + return new CounterContract(contractAddress, web3j, transactionManager, gasPrice, gasLimit); + } + + public static CounterContract load( + String contractAddress, + Web3j web3j, + Credentials credentials, + ContractGasProvider contractGasProvider) { + return new CounterContract(contractAddress, web3j, credentials, contractGasProvider); + } + + public static CounterContract load( + String contractAddress, + Web3j web3j, + TransactionManager transactionManager, + ContractGasProvider contractGasProvider) { + return new CounterContract(contractAddress, web3j, transactionManager, contractGasProvider); + } + + public static RemoteCall deploy( + Web3j web3j, Credentials credentials, ContractGasProvider contractGasProvider) { + return deployRemoteCall( + CounterContract.class, web3j, credentials, contractGasProvider, BINARY, ""); + } + + @Deprecated + public static RemoteCall deploy( + Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) { + return deployRemoteCall( + CounterContract.class, web3j, credentials, gasPrice, gasLimit, BINARY, ""); + } + + public static RemoteCall deploy( + Web3j web3j, TransactionManager transactionManager, ContractGasProvider contractGasProvider) { + return deployRemoteCall( + CounterContract.class, web3j, transactionManager, contractGasProvider, BINARY, ""); + } + + @Deprecated + public static RemoteCall deploy( + Web3j web3j, + TransactionManager transactionManager, + BigInteger gasPrice, + BigInteger gasLimit) { + return deployRemoteCall( + CounterContract.class, web3j, transactionManager, gasPrice, gasLimit, BINARY, ""); + } } diff --git a/src/test/java/io/zksync/helper/CustomAccountContract.java b/src/test/java/io/zksync/helper/CustomAccountContract.java index c2f7e24..d326e57 100644 --- a/src/test/java/io/zksync/helper/CustomAccountContract.java +++ b/src/test/java/io/zksync/helper/CustomAccountContract.java @@ -8,7 +8,6 @@ import java.util.Collections; import java.util.List; import java.util.stream.Collectors; - import org.web3j.abi.TypeReference; import org.web3j.abi.datatypes.DynamicArray; import org.web3j.abi.datatypes.DynamicBytes; @@ -29,223 +28,321 @@ import org.web3j.tx.gas.ContractGasProvider; /** - *

Auto generated code. + * Auto generated code. + * *

Do not modify! + * *

Please use the web3j command line tools, - * or the org.web3j.codegen.SolidityFunctionWrapperGenerator in the - * codegen module to update. + * or the org.web3j.codegen.SolidityFunctionWrapperGenerator in the codegen module to update. * *

Generated with web3j version 4.7.0. */ @SuppressWarnings("rawtypes") public class CustomAccountContract extends Contract { - public static final String BINARY; - - static { - try (FileInputStream fis = new FileInputStream("src/test/resources/customAccountBinary.hex")) { - ByteArrayOutputStream buffer = new ByteArrayOutputStream(); - - int count; - byte[] bytes = new byte[16536]; - while ((count = fis.read(bytes)) != -1) { - buffer.write(bytes, 0, count); - } - BINARY = buffer.toString("UTF-8"); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - public static final String FUNC_EXECUTETRANSACTION = "executeTransaction"; - - public static final String FUNC_EXECUTETRANSACTIONFROMOUTSIDE = "executeTransactionFromOutside"; - - public static final String FUNC_PAYFORTRANSACTION = "payForTransaction"; - - public static final String FUNC_PREPAYMASTER = "prePaymaster"; - - public static final String FUNC_VALIDATETRANSACTION = "validateTransaction"; - - @Deprecated - protected CustomAccountContract(String contractAddress, Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) { - super(BINARY, contractAddress, web3j, credentials, gasPrice, gasLimit); - } - - protected CustomAccountContract(String contractAddress, Web3j web3j, Credentials credentials, ContractGasProvider contractGasProvider) { - super(BINARY, contractAddress, web3j, credentials, contractGasProvider); - } - - @Deprecated - protected CustomAccountContract(String contractAddress, Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit) { - super(BINARY, contractAddress, web3j, transactionManager, gasPrice, gasLimit); - } - - protected CustomAccountContract(String contractAddress, Web3j web3j, TransactionManager transactionManager, ContractGasProvider contractGasProvider) { - super(BINARY, contractAddress, web3j, transactionManager, contractGasProvider); - } - - public RemoteFunctionCall executeTransaction(Transaction _transaction) { - final Function function = new Function( - FUNC_EXECUTETRANSACTION, - Arrays.asList(_transaction), - Collections.>emptyList()); - return executeRemoteCallTransaction(function); - } - - public RemoteFunctionCall executeTransactionFromOutside(Transaction _transaction) { - final Function function = new Function( - FUNC_EXECUTETRANSACTIONFROMOUTSIDE, - Arrays.asList(_transaction), - Collections.>emptyList()); - return executeRemoteCallTransaction(function); - } - - public RemoteFunctionCall payForTransaction(Transaction _transaction) { - final Function function = new Function( - FUNC_PAYFORTRANSACTION, - Arrays.asList(_transaction), - Collections.>emptyList()); - return executeRemoteCallTransaction(function); - } - - public RemoteFunctionCall prePaymaster(Transaction _transaction) { - final Function function = new Function( - FUNC_PREPAYMASTER, - Arrays.asList(_transaction), - Collections.>emptyList()); - return executeRemoteCallTransaction(function); - } - - public RemoteFunctionCall validateTransaction(Transaction _transaction) { - final Function function = new Function( - FUNC_VALIDATETRANSACTION, - Arrays.asList(_transaction), - Collections.>emptyList()); - return executeRemoteCallTransaction(function); - } - - @Deprecated - public static CustomAccountContract load(String contractAddress, Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) { - return new CustomAccountContract(contractAddress, web3j, credentials, gasPrice, gasLimit); - } - - @Deprecated - public static CustomAccountContract load(String contractAddress, Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit) { - return new CustomAccountContract(contractAddress, web3j, transactionManager, gasPrice, gasLimit); - } - - public static CustomAccountContract load(String contractAddress, Web3j web3j, Credentials credentials, ContractGasProvider contractGasProvider) { - return new CustomAccountContract(contractAddress, web3j, credentials, contractGasProvider); - } - - public static CustomAccountContract load(String contractAddress, Web3j web3j, TransactionManager transactionManager, ContractGasProvider contractGasProvider) { - return new CustomAccountContract(contractAddress, web3j, transactionManager, contractGasProvider); - } - - public static RemoteCall deploy(Web3j web3j, Credentials credentials, ContractGasProvider contractGasProvider) { - return deployRemoteCall(CustomAccountContract.class, web3j, credentials, contractGasProvider, BINARY, ""); + public static final String BINARY; + + static { + try (FileInputStream fis = new FileInputStream("src/test/resources/customAccountBinary.hex")) { + ByteArrayOutputStream buffer = new ByteArrayOutputStream(); + + int count; + byte[] bytes = new byte[16536]; + while ((count = fis.read(bytes)) != -1) { + buffer.write(bytes, 0, count); + } + BINARY = buffer.toString("UTF-8"); + } catch (IOException e) { + throw new RuntimeException(e); } - - @Deprecated - public static RemoteCall deploy(Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) { - return deployRemoteCall(CustomAccountContract.class, web3j, credentials, gasPrice, gasLimit, BINARY, ""); - } - - public static RemoteCall deploy(Web3j web3j, TransactionManager transactionManager, ContractGasProvider contractGasProvider) { - return deployRemoteCall(CustomAccountContract.class, web3j, transactionManager, contractGasProvider, BINARY, ""); - } - - @Deprecated - public static RemoteCall deploy(Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit) { - return deployRemoteCall(CustomAccountContract.class, web3j, transactionManager, gasPrice, gasLimit, BINARY, ""); + } + + public static final String FUNC_EXECUTETRANSACTION = "executeTransaction"; + + public static final String FUNC_EXECUTETRANSACTIONFROMOUTSIDE = "executeTransactionFromOutside"; + + public static final String FUNC_PAYFORTRANSACTION = "payForTransaction"; + + public static final String FUNC_PREPAYMASTER = "prePaymaster"; + + public static final String FUNC_VALIDATETRANSACTION = "validateTransaction"; + + @Deprecated + protected CustomAccountContract( + String contractAddress, + Web3j web3j, + Credentials credentials, + BigInteger gasPrice, + BigInteger gasLimit) { + super(BINARY, contractAddress, web3j, credentials, gasPrice, gasLimit); + } + + protected CustomAccountContract( + String contractAddress, + Web3j web3j, + Credentials credentials, + ContractGasProvider contractGasProvider) { + super(BINARY, contractAddress, web3j, credentials, contractGasProvider); + } + + @Deprecated + protected CustomAccountContract( + String contractAddress, + Web3j web3j, + TransactionManager transactionManager, + BigInteger gasPrice, + BigInteger gasLimit) { + super(BINARY, contractAddress, web3j, transactionManager, gasPrice, gasLimit); + } + + protected CustomAccountContract( + String contractAddress, + Web3j web3j, + TransactionManager transactionManager, + ContractGasProvider contractGasProvider) { + super(BINARY, contractAddress, web3j, transactionManager, contractGasProvider); + } + + public RemoteFunctionCall executeTransaction(Transaction _transaction) { + final Function function = + new Function( + FUNC_EXECUTETRANSACTION, + Arrays.asList(_transaction), + Collections.>emptyList()); + return executeRemoteCallTransaction(function); + } + + public RemoteFunctionCall executeTransactionFromOutside( + Transaction _transaction) { + final Function function = + new Function( + FUNC_EXECUTETRANSACTIONFROMOUTSIDE, + Arrays.asList(_transaction), + Collections.>emptyList()); + return executeRemoteCallTransaction(function); + } + + public RemoteFunctionCall payForTransaction(Transaction _transaction) { + final Function function = + new Function( + FUNC_PAYFORTRANSACTION, + Arrays.asList(_transaction), + Collections.>emptyList()); + return executeRemoteCallTransaction(function); + } + + public RemoteFunctionCall prePaymaster(Transaction _transaction) { + final Function function = + new Function( + FUNC_PREPAYMASTER, + Arrays.asList(_transaction), + Collections.>emptyList()); + return executeRemoteCallTransaction(function); + } + + public RemoteFunctionCall validateTransaction(Transaction _transaction) { + final Function function = + new Function( + FUNC_VALIDATETRANSACTION, + Arrays.asList(_transaction), + Collections.>emptyList()); + return executeRemoteCallTransaction(function); + } + + @Deprecated + public static CustomAccountContract load( + String contractAddress, + Web3j web3j, + Credentials credentials, + BigInteger gasPrice, + BigInteger gasLimit) { + return new CustomAccountContract(contractAddress, web3j, credentials, gasPrice, gasLimit); + } + + @Deprecated + public static CustomAccountContract load( + String contractAddress, + Web3j web3j, + TransactionManager transactionManager, + BigInteger gasPrice, + BigInteger gasLimit) { + return new CustomAccountContract( + contractAddress, web3j, transactionManager, gasPrice, gasLimit); + } + + public static CustomAccountContract load( + String contractAddress, + Web3j web3j, + Credentials credentials, + ContractGasProvider contractGasProvider) { + return new CustomAccountContract(contractAddress, web3j, credentials, contractGasProvider); + } + + public static CustomAccountContract load( + String contractAddress, + Web3j web3j, + TransactionManager transactionManager, + ContractGasProvider contractGasProvider) { + return new CustomAccountContract( + contractAddress, web3j, transactionManager, contractGasProvider); + } + + public static RemoteCall deploy( + Web3j web3j, Credentials credentials, ContractGasProvider contractGasProvider) { + return deployRemoteCall( + CustomAccountContract.class, web3j, credentials, contractGasProvider, BINARY, ""); + } + + @Deprecated + public static RemoteCall deploy( + Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) { + return deployRemoteCall( + CustomAccountContract.class, web3j, credentials, gasPrice, gasLimit, BINARY, ""); + } + + public static RemoteCall deploy( + Web3j web3j, TransactionManager transactionManager, ContractGasProvider contractGasProvider) { + return deployRemoteCall( + CustomAccountContract.class, web3j, transactionManager, contractGasProvider, BINARY, ""); + } + + @Deprecated + public static RemoteCall deploy( + Web3j web3j, + TransactionManager transactionManager, + BigInteger gasPrice, + BigInteger gasLimit) { + return deployRemoteCall( + CustomAccountContract.class, web3j, transactionManager, gasPrice, gasLimit, BINARY, ""); + } + + /** + * struct Transaction { uint8 txType; uint256 from; uint256 to; uint256 ergsLimit; uint256 + * ergsPerPubdataByteLimit; uint256 ergsPrice; uint256 paymaster; // In the future, we might want + * to add some // new fields to the struct. The `txData` struct // is to be passed to account and + * any changes to its structure // would mean a breaking change to these accounts. In order to + * prevent this, // we should keep some fields as "reserved". // It is also recommneded that their + * length is fixed, since // it would allow easier proof integration (in case we will need // some + * special circuit for preprocessing transactions). uint256[6] reserved; bytes data; bytes + * signature; bytes32[] factoryDeps; bytes paymasterInput; // Reserved dynamic type for the future + * use-case. Using it should be avoided, // But it is still here, just in case we want to enable + * some additional functionality. bytes reservedDynamic; } + */ + public static class Transaction extends DynamicStruct { + public BigInteger txType; + + public BigInteger from; + + public BigInteger to; + + public BigInteger ergsLimit; + + public BigInteger ergsPerPubdataByteLimit; + + public BigInteger ergsPrice; + + public BigInteger paymaster; + + public List reserved; + + public byte[] data; + + public byte[] signature; + + public List factoryDeps; + + public byte[] paymasterInput; + + public byte[] reservedDynamic; + + public Transaction( + BigInteger txType, + BigInteger from, + BigInteger to, + BigInteger ergsLimit, + BigInteger ergsPerPubdataByteLimit, + BigInteger ergsPrice, + BigInteger paymaster, + List reserved, + byte[] data, + byte[] signature, + List factoryDeps, + byte[] paymasterInput, + byte[] reservedDynamic) { + super( + new org.web3j.abi.datatypes.generated.Uint8(txType), + new org.web3j.abi.datatypes.generated.Uint256(from), + new org.web3j.abi.datatypes.generated.Uint256(to), + new org.web3j.abi.datatypes.generated.Uint256(ergsLimit), + new org.web3j.abi.datatypes.generated.Uint256(ergsPerPubdataByteLimit), + new org.web3j.abi.datatypes.generated.Uint256(ergsPrice), + new org.web3j.abi.datatypes.generated.Uint256(paymaster), + new org.web3j.abi.datatypes.generated.StaticArray6<>( + Uint256.class, reserved.stream().map(Uint256::new).collect(Collectors.toList())), + new org.web3j.abi.datatypes.DynamicBytes(data), + new org.web3j.abi.datatypes.DynamicBytes(signature), + new org.web3j.abi.datatypes.DynamicArray<>( + Bytes32.class, factoryDeps.stream().map(Bytes32::new).collect(Collectors.toList())), + new org.web3j.abi.datatypes.DynamicBytes(paymasterInput), + new org.web3j.abi.datatypes.DynamicBytes(reservedDynamic)); + this.txType = txType; + this.from = from; + this.to = to; + this.ergsLimit = ergsLimit; + this.ergsPerPubdataByteLimit = ergsPerPubdataByteLimit; + this.ergsPrice = ergsPrice; + this.paymaster = paymaster; + this.reserved = reserved; + this.data = data; + this.signature = signature; + this.factoryDeps = factoryDeps; + this.paymasterInput = paymasterInput; + this.reservedDynamic = reservedDynamic; } - /** - * struct Transaction { - * uint8 txType; - * uint256 from; - * uint256 to; - * uint256 ergsLimit; - * uint256 ergsPerPubdataByteLimit; - * uint256 ergsPrice; - * uint256 paymaster; - * // In the future, we might want to add some - * // new fields to the struct. The `txData` struct - * // is to be passed to account and any changes to its structure - * // would mean a breaking change to these accounts. In order to prevent this, - * // we should keep some fields as "reserved". - * // It is also recommneded that their length is fixed, since - * // it would allow easier proof integration (in case we will need - * // some special circuit for preprocessing transactions). - * uint256[6] reserved; - * bytes data; - * bytes signature; - * bytes32[] factoryDeps; - * bytes paymasterInput; - * // Reserved dynamic type for the future use-case. Using it should be avoided, - * // But it is still here, just in case we want to enable some additional functionality. - * bytes reservedDynamic; - * } - */ - - public static class Transaction extends DynamicStruct { - public BigInteger txType; - - public BigInteger from; - - public BigInteger to; - - public BigInteger ergsLimit; - - public BigInteger ergsPerPubdataByteLimit; - - public BigInteger ergsPrice; - - public BigInteger paymaster; - - public List reserved; - - public byte[] data; - - public byte[] signature; - - public List factoryDeps; - - public byte[] paymasterInput; - - public byte[] reservedDynamic; - - public Transaction(BigInteger txType, BigInteger from, BigInteger to, BigInteger ergsLimit, BigInteger ergsPerPubdataByteLimit, BigInteger ergsPrice, BigInteger paymaster, List reserved, byte[] data, byte[] signature, List factoryDeps, byte[] paymasterInput, byte[] reservedDynamic) { - super(new org.web3j.abi.datatypes.generated.Uint8(txType),new org.web3j.abi.datatypes.generated.Uint256(from),new org.web3j.abi.datatypes.generated.Uint256(to),new org.web3j.abi.datatypes.generated.Uint256(ergsLimit),new org.web3j.abi.datatypes.generated.Uint256(ergsPerPubdataByteLimit),new org.web3j.abi.datatypes.generated.Uint256(ergsPrice),new org.web3j.abi.datatypes.generated.Uint256(paymaster),new org.web3j.abi.datatypes.generated.StaticArray6<>(Uint256.class, reserved.stream().map(Uint256::new).collect(Collectors.toList())),new org.web3j.abi.datatypes.DynamicBytes(data),new org.web3j.abi.datatypes.DynamicBytes(signature),new org.web3j.abi.datatypes.DynamicArray<>(Bytes32.class, factoryDeps.stream().map(Bytes32::new).collect(Collectors.toList())),new org.web3j.abi.datatypes.DynamicBytes(paymasterInput),new org.web3j.abi.datatypes.DynamicBytes(reservedDynamic)); - this.txType = txType; - this.from = from; - this.to = to; - this.ergsLimit = ergsLimit; - this.ergsPerPubdataByteLimit = ergsPerPubdataByteLimit; - this.ergsPrice = ergsPrice; - this.paymaster = paymaster; - this.reserved = reserved; - this.data = data; - this.signature = signature; - this.factoryDeps = factoryDeps; - this.paymasterInput = paymasterInput; - this.reservedDynamic = reservedDynamic; - } - - public Transaction(Uint8 txType, Uint256 from, Uint256 to, Uint256 ergsLimit, Uint256 ergsPerPubdataByteLimit, Uint256 ergsPrice, Uint256 paymaster, StaticArray6 reserved, DynamicBytes data, DynamicBytes signature, DynamicArray factoryDeps, DynamicBytes paymasterInput, DynamicBytes reservedDynamic) { - super(txType,from,to,ergsLimit,ergsPerPubdataByteLimit,ergsPrice,paymaster,reserved,data,signature,factoryDeps,paymasterInput,reservedDynamic); - this.txType = txType.getValue(); - this.from = from.getValue(); - this.to = to.getValue(); - this.ergsLimit = ergsLimit.getValue(); - this.ergsPerPubdataByteLimit = ergsPerPubdataByteLimit.getValue(); - this.ergsPrice = ergsPrice.getValue(); - this.paymaster = paymaster.getValue(); - this.reserved = reserved.getValue().stream().map(Uint256::getValue).collect(Collectors.toList()); - this.data = data.getValue(); - this.signature = signature.getValue(); - this.factoryDeps = factoryDeps.getValue().stream().map(Bytes32::getValue).collect(Collectors.toList()); - this.paymasterInput = paymasterInput.getValue(); - this.reservedDynamic = reservedDynamic.getValue(); - } + public Transaction( + Uint8 txType, + Uint256 from, + Uint256 to, + Uint256 ergsLimit, + Uint256 ergsPerPubdataByteLimit, + Uint256 ergsPrice, + Uint256 paymaster, + StaticArray6 reserved, + DynamicBytes data, + DynamicBytes signature, + DynamicArray factoryDeps, + DynamicBytes paymasterInput, + DynamicBytes reservedDynamic) { + super( + txType, + from, + to, + ergsLimit, + ergsPerPubdataByteLimit, + ergsPrice, + paymaster, + reserved, + data, + signature, + factoryDeps, + paymasterInput, + reservedDynamic); + this.txType = txType.getValue(); + this.from = from.getValue(); + this.to = to.getValue(); + this.ergsLimit = ergsLimit.getValue(); + this.ergsPerPubdataByteLimit = ergsPerPubdataByteLimit.getValue(); + this.ergsPrice = ergsPrice.getValue(); + this.paymaster = paymaster.getValue(); + this.reserved = + reserved.getValue().stream().map(Uint256::getValue).collect(Collectors.toList()); + this.data = data.getValue(); + this.signature = signature.getValue(); + this.factoryDeps = + factoryDeps.getValue().stream().map(Bytes32::getValue).collect(Collectors.toList()); + this.paymasterInput = paymasterInput.getValue(); + this.reservedDynamic = reservedDynamic.getValue(); } + } } diff --git a/src/test/java/io/zksync/helper/CustomPaymasterContract.java b/src/test/java/io/zksync/helper/CustomPaymasterContract.java index e8d242d..290266e 100644 --- a/src/test/java/io/zksync/helper/CustomPaymasterContract.java +++ b/src/test/java/io/zksync/helper/CustomPaymasterContract.java @@ -8,7 +8,6 @@ import java.util.Collections; import java.util.List; import java.util.stream.Collectors; - import org.web3j.abi.TypeReference; import org.web3j.abi.datatypes.DynamicArray; import org.web3j.abi.datatypes.DynamicBytes; @@ -29,184 +28,279 @@ import org.web3j.tx.gas.ContractGasProvider; /** - *

Auto generated code. + * Auto generated code. + * *

Do not modify! + * *

Please use the web3j command line tools, - * or the org.web3j.codegen.SolidityFunctionWrapperGenerator in the - * codegen module to update. + * or the org.web3j.codegen.SolidityFunctionWrapperGenerator in the codegen module to update. * *

Generated with web3j version 4.7.0. */ @SuppressWarnings("rawtypes") public class CustomPaymasterContract extends Contract { - public static final String BINARY; - - static { - try (FileInputStream fis = new FileInputStream("src/test/resources/customPaymasterBinary.hex")) { - ByteArrayOutputStream buffer = new ByteArrayOutputStream(); - - int count; - byte[] bytes = new byte[16536]; - while ((count = fis.read(bytes)) != -1) { - buffer.write(bytes, 0, count); - } - BINARY = buffer.toString("UTF-8"); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - - public static final String FUNC_VALIDATEANDPAYFORPAYMASTERTRANSACTION = "validateAndPayForPaymasterTransaction"; - - @Deprecated - protected CustomPaymasterContract(String contractAddress, Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) { - super(BINARY, contractAddress, web3j, credentials, gasPrice, gasLimit); - } - - protected CustomPaymasterContract(String contractAddress, Web3j web3j, Credentials credentials, ContractGasProvider contractGasProvider) { - super(BINARY, contractAddress, web3j, credentials, contractGasProvider); + public static final String BINARY; + + static { + try (FileInputStream fis = + new FileInputStream("src/test/resources/customPaymasterBinary.hex")) { + ByteArrayOutputStream buffer = new ByteArrayOutputStream(); + + int count; + byte[] bytes = new byte[16536]; + while ((count = fis.read(bytes)) != -1) { + buffer.write(bytes, 0, count); + } + BINARY = buffer.toString("UTF-8"); + } catch (IOException e) { + throw new RuntimeException(e); } - - @Deprecated - protected CustomPaymasterContract(String contractAddress, Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit) { - super(BINARY, contractAddress, web3j, transactionManager, gasPrice, gasLimit); - } - - protected CustomPaymasterContract(String contractAddress, Web3j web3j, TransactionManager transactionManager, ContractGasProvider contractGasProvider) { - super(BINARY, contractAddress, web3j, transactionManager, contractGasProvider); - } - - public RemoteFunctionCall validateAndPayForPaymasterTransaction(Transaction _transaction) { - final Function function = new Function( - FUNC_VALIDATEANDPAYFORPAYMASTERTRANSACTION, - Arrays.asList(_transaction), - Collections.>emptyList()); - return executeRemoteCallTransaction(function); - } - - @Deprecated - public static CustomPaymasterContract load(String contractAddress, Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) { - return new CustomPaymasterContract(contractAddress, web3j, credentials, gasPrice, gasLimit); - } - - @Deprecated - public static CustomPaymasterContract load(String contractAddress, Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit) { - return new CustomPaymasterContract(contractAddress, web3j, transactionManager, gasPrice, gasLimit); - } - - public static CustomPaymasterContract load(String contractAddress, Web3j web3j, Credentials credentials, ContractGasProvider contractGasProvider) { - return new CustomPaymasterContract(contractAddress, web3j, credentials, contractGasProvider); - } - - public static CustomPaymasterContract load(String contractAddress, Web3j web3j, TransactionManager transactionManager, ContractGasProvider contractGasProvider) { - return new CustomPaymasterContract(contractAddress, web3j, transactionManager, contractGasProvider); - } - - public static RemoteCall deploy(Web3j web3j, Credentials credentials, ContractGasProvider contractGasProvider) { - return deployRemoteCall(CustomPaymasterContract.class, web3j, credentials, contractGasProvider, BINARY, ""); - } - - @Deprecated - public static RemoteCall deploy(Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) { - return deployRemoteCall(CustomPaymasterContract.class, web3j, credentials, gasPrice, gasLimit, BINARY, ""); - } - - public static RemoteCall deploy(Web3j web3j, TransactionManager transactionManager, ContractGasProvider contractGasProvider) { - return deployRemoteCall(CustomPaymasterContract.class, web3j, transactionManager, contractGasProvider, BINARY, ""); - } - - @Deprecated - public static RemoteCall deploy(Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit) { - return deployRemoteCall(CustomPaymasterContract.class, web3j, transactionManager, gasPrice, gasLimit, BINARY, ""); + } + + public static final String FUNC_VALIDATEANDPAYFORPAYMASTERTRANSACTION = + "validateAndPayForPaymasterTransaction"; + + @Deprecated + protected CustomPaymasterContract( + String contractAddress, + Web3j web3j, + Credentials credentials, + BigInteger gasPrice, + BigInteger gasLimit) { + super(BINARY, contractAddress, web3j, credentials, gasPrice, gasLimit); + } + + protected CustomPaymasterContract( + String contractAddress, + Web3j web3j, + Credentials credentials, + ContractGasProvider contractGasProvider) { + super(BINARY, contractAddress, web3j, credentials, contractGasProvider); + } + + @Deprecated + protected CustomPaymasterContract( + String contractAddress, + Web3j web3j, + TransactionManager transactionManager, + BigInteger gasPrice, + BigInteger gasLimit) { + super(BINARY, contractAddress, web3j, transactionManager, gasPrice, gasLimit); + } + + protected CustomPaymasterContract( + String contractAddress, + Web3j web3j, + TransactionManager transactionManager, + ContractGasProvider contractGasProvider) { + super(BINARY, contractAddress, web3j, transactionManager, contractGasProvider); + } + + public RemoteFunctionCall validateAndPayForPaymasterTransaction( + Transaction _transaction) { + final Function function = + new Function( + FUNC_VALIDATEANDPAYFORPAYMASTERTRANSACTION, + Arrays.asList(_transaction), + Collections.>emptyList()); + return executeRemoteCallTransaction(function); + } + + @Deprecated + public static CustomPaymasterContract load( + String contractAddress, + Web3j web3j, + Credentials credentials, + BigInteger gasPrice, + BigInteger gasLimit) { + return new CustomPaymasterContract(contractAddress, web3j, credentials, gasPrice, gasLimit); + } + + @Deprecated + public static CustomPaymasterContract load( + String contractAddress, + Web3j web3j, + TransactionManager transactionManager, + BigInteger gasPrice, + BigInteger gasLimit) { + return new CustomPaymasterContract( + contractAddress, web3j, transactionManager, gasPrice, gasLimit); + } + + public static CustomPaymasterContract load( + String contractAddress, + Web3j web3j, + Credentials credentials, + ContractGasProvider contractGasProvider) { + return new CustomPaymasterContract(contractAddress, web3j, credentials, contractGasProvider); + } + + public static CustomPaymasterContract load( + String contractAddress, + Web3j web3j, + TransactionManager transactionManager, + ContractGasProvider contractGasProvider) { + return new CustomPaymasterContract( + contractAddress, web3j, transactionManager, contractGasProvider); + } + + public static RemoteCall deploy( + Web3j web3j, Credentials credentials, ContractGasProvider contractGasProvider) { + return deployRemoteCall( + CustomPaymasterContract.class, web3j, credentials, contractGasProvider, BINARY, ""); + } + + @Deprecated + public static RemoteCall deploy( + Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) { + return deployRemoteCall( + CustomPaymasterContract.class, web3j, credentials, gasPrice, gasLimit, BINARY, ""); + } + + public static RemoteCall deploy( + Web3j web3j, TransactionManager transactionManager, ContractGasProvider contractGasProvider) { + return deployRemoteCall( + CustomPaymasterContract.class, web3j, transactionManager, contractGasProvider, BINARY, ""); + } + + @Deprecated + public static RemoteCall deploy( + Web3j web3j, + TransactionManager transactionManager, + BigInteger gasPrice, + BigInteger gasLimit) { + return deployRemoteCall( + CustomPaymasterContract.class, web3j, transactionManager, gasPrice, gasLimit, BINARY, ""); + } + + /** + * struct Transaction { uint8 txType; uint256 from; uint256 to; uint256 ergsLimit; uint256 + * ergsPerPubdataByteLimit; uint256 ergsPrice; uint256 paymaster; // In the future, we might want + * to add some // new fields to the struct. The `txData` struct // is to be passed to account and + * any changes to its structure // would mean a breaking change to these accounts. In order to + * prevent this, // we should keep some fields as "reserved". // It is also recommneded that their + * length is fixed, since // it would allow easier proof integration (in case we will need // some + * special circuit for preprocessing transactions). uint256[6] reserved; bytes data; bytes + * signature; bytes32[] factoryDeps; bytes paymasterInput; // Reserved dynamic type for the future + * use-case. Using it should be avoided, // But it is still here, just in case we want to enable + * some additional functionality. bytes reservedDynamic; } + */ + public static class Transaction extends DynamicStruct { + public BigInteger txType; + + public BigInteger from; + + public BigInteger to; + + public BigInteger ergsLimit; + + public BigInteger ergsPerPubdataByteLimit; + + public BigInteger ergsPrice; + + public BigInteger paymaster; + + public List reserved; + + public byte[] data; + + public byte[] signature; + + public List factoryDeps; + + public byte[] paymasterInput; + + public byte[] reservedDynamic; + + public Transaction( + BigInteger txType, + BigInteger from, + BigInteger to, + BigInteger ergsLimit, + BigInteger ergsPerPubdataByteLimit, + BigInteger ergsPrice, + BigInteger paymaster, + List reserved, + byte[] data, + byte[] signature, + List factoryDeps, + byte[] paymasterInput, + byte[] reservedDynamic) { + super( + new org.web3j.abi.datatypes.generated.Uint8(txType), + new org.web3j.abi.datatypes.generated.Uint256(from), + new org.web3j.abi.datatypes.generated.Uint256(to), + new org.web3j.abi.datatypes.generated.Uint256(ergsLimit), + new org.web3j.abi.datatypes.generated.Uint256(ergsPerPubdataByteLimit), + new org.web3j.abi.datatypes.generated.Uint256(ergsPrice), + new org.web3j.abi.datatypes.generated.Uint256(paymaster), + new org.web3j.abi.datatypes.generated.StaticArray6<>( + Uint256.class, reserved.stream().map(Uint256::new).collect(Collectors.toList())), + new org.web3j.abi.datatypes.DynamicBytes(data), + new org.web3j.abi.datatypes.DynamicBytes(signature), + new org.web3j.abi.datatypes.DynamicArray<>( + Bytes32.class, factoryDeps.stream().map(Bytes32::new).collect(Collectors.toList())), + new org.web3j.abi.datatypes.DynamicBytes(paymasterInput), + new org.web3j.abi.datatypes.DynamicBytes(reservedDynamic)); + this.txType = txType; + this.from = from; + this.to = to; + this.ergsLimit = ergsLimit; + this.ergsPerPubdataByteLimit = ergsPerPubdataByteLimit; + this.ergsPrice = ergsPrice; + this.paymaster = paymaster; + this.reserved = reserved; + this.data = data; + this.signature = signature; + this.factoryDeps = factoryDeps; + this.paymasterInput = paymasterInput; + this.reservedDynamic = reservedDynamic; } - /** - * struct Transaction { - * uint8 txType; - * uint256 from; - * uint256 to; - * uint256 ergsLimit; - * uint256 ergsPerPubdataByteLimit; - * uint256 ergsPrice; - * uint256 paymaster; - * // In the future, we might want to add some - * // new fields to the struct. The `txData` struct - * // is to be passed to account and any changes to its structure - * // would mean a breaking change to these accounts. In order to prevent this, - * // we should keep some fields as "reserved". - * // It is also recommneded that their length is fixed, since - * // it would allow easier proof integration (in case we will need - * // some special circuit for preprocessing transactions). - * uint256[6] reserved; - * bytes data; - * bytes signature; - * bytes32[] factoryDeps; - * bytes paymasterInput; - * // Reserved dynamic type for the future use-case. Using it should be avoided, - * // But it is still here, just in case we want to enable some additional functionality. - * bytes reservedDynamic; - * } - */ - - public static class Transaction extends DynamicStruct { - public BigInteger txType; - - public BigInteger from; - - public BigInteger to; - - public BigInteger ergsLimit; - - public BigInteger ergsPerPubdataByteLimit; - - public BigInteger ergsPrice; - - public BigInteger paymaster; - - public List reserved; - - public byte[] data; - - public byte[] signature; - - public List factoryDeps; - - public byte[] paymasterInput; - - public byte[] reservedDynamic; - - public Transaction(BigInteger txType, BigInteger from, BigInteger to, BigInteger ergsLimit, BigInteger ergsPerPubdataByteLimit, BigInteger ergsPrice, BigInteger paymaster, List reserved, byte[] data, byte[] signature, List factoryDeps, byte[] paymasterInput, byte[] reservedDynamic) { - super(new org.web3j.abi.datatypes.generated.Uint8(txType),new org.web3j.abi.datatypes.generated.Uint256(from),new org.web3j.abi.datatypes.generated.Uint256(to),new org.web3j.abi.datatypes.generated.Uint256(ergsLimit),new org.web3j.abi.datatypes.generated.Uint256(ergsPerPubdataByteLimit),new org.web3j.abi.datatypes.generated.Uint256(ergsPrice),new org.web3j.abi.datatypes.generated.Uint256(paymaster),new org.web3j.abi.datatypes.generated.StaticArray6<>(Uint256.class, reserved.stream().map(Uint256::new).collect(Collectors.toList())),new org.web3j.abi.datatypes.DynamicBytes(data),new org.web3j.abi.datatypes.DynamicBytes(signature),new org.web3j.abi.datatypes.DynamicArray<>(Bytes32.class, factoryDeps.stream().map(Bytes32::new).collect(Collectors.toList())),new org.web3j.abi.datatypes.DynamicBytes(paymasterInput),new org.web3j.abi.datatypes.DynamicBytes(reservedDynamic)); - this.txType = txType; - this.from = from; - this.to = to; - this.ergsLimit = ergsLimit; - this.ergsPerPubdataByteLimit = ergsPerPubdataByteLimit; - this.ergsPrice = ergsPrice; - this.paymaster = paymaster; - this.reserved = reserved; - this.data = data; - this.signature = signature; - this.factoryDeps = factoryDeps; - this.paymasterInput = paymasterInput; - this.reservedDynamic = reservedDynamic; - } - - public Transaction(Uint8 txType, Uint256 from, Uint256 to, Uint256 ergsLimit, Uint256 ergsPerPubdataByteLimit, Uint256 ergsPrice, Uint256 paymaster, StaticArray6 reserved, DynamicBytes data, DynamicBytes signature, DynamicArray factoryDeps, DynamicBytes paymasterInput, DynamicBytes reservedDynamic) { - super(txType,from,to,ergsLimit,ergsPerPubdataByteLimit,ergsPrice,paymaster,reserved,data,signature,factoryDeps,paymasterInput,reservedDynamic); - this.txType = txType.getValue(); - this.from = from.getValue(); - this.to = to.getValue(); - this.ergsLimit = ergsLimit.getValue(); - this.ergsPerPubdataByteLimit = ergsPerPubdataByteLimit.getValue(); - this.ergsPrice = ergsPrice.getValue(); - this.paymaster = paymaster.getValue(); - this.reserved = reserved.getValue().stream().map(Uint256::getValue).collect(Collectors.toList()); - this.data = data.getValue(); - this.signature = signature.getValue(); - this.factoryDeps = factoryDeps.getValue().stream().map(Bytes32::getValue).collect(Collectors.toList()); - this.paymasterInput = paymasterInput.getValue(); - this.reservedDynamic = reservedDynamic.getValue(); - } + public Transaction( + Uint8 txType, + Uint256 from, + Uint256 to, + Uint256 ergsLimit, + Uint256 ergsPerPubdataByteLimit, + Uint256 ergsPrice, + Uint256 paymaster, + StaticArray6 reserved, + DynamicBytes data, + DynamicBytes signature, + DynamicArray factoryDeps, + DynamicBytes paymasterInput, + DynamicBytes reservedDynamic) { + super( + txType, + from, + to, + ergsLimit, + ergsPerPubdataByteLimit, + ergsPrice, + paymaster, + reserved, + data, + signature, + factoryDeps, + paymasterInput, + reservedDynamic); + this.txType = txType.getValue(); + this.from = from.getValue(); + this.to = to.getValue(); + this.ergsLimit = ergsLimit.getValue(); + this.ergsPerPubdataByteLimit = ergsPerPubdataByteLimit.getValue(); + this.ergsPrice = ergsPrice.getValue(); + this.paymaster = paymaster.getValue(); + this.reserved = + reserved.getValue().stream().map(Uint256::getValue).collect(Collectors.toList()); + this.data = data.getValue(); + this.signature = signature.getValue(); + this.factoryDeps = + factoryDeps.getValue().stream().map(Bytes32::getValue).collect(Collectors.toList()); + this.paymasterInput = paymasterInput.getValue(); + this.reservedDynamic = reservedDynamic.getValue(); } + } } diff --git a/src/test/java/io/zksync/helper/Import.java b/src/test/java/io/zksync/helper/Import.java index 65e70df..cd5f381 100644 --- a/src/test/java/io/zksync/helper/Import.java +++ b/src/test/java/io/zksync/helper/Import.java @@ -16,93 +16,147 @@ import org.web3j.tx.gas.ContractGasProvider; /** - *

Auto generated code. + * Auto generated code. + * *

Do not modify! + * *

Please use the web3j command line tools, - * or the org.web3j.codegen.SolidityFunctionWrapperGenerator in the - * codegen module to update. + * or the org.web3j.codegen.SolidityFunctionWrapperGenerator in the codegen module to update. * *

Generated with web3j version 1.4.1. */ @SuppressWarnings("rawtypes") public class Import extends Contract { - public static final String BINARY = "0x0004000000000002000200000001035500000060031002700000007d0030019d0000007d03300197000000000131034f000300000001035500000060011002700001007d0010019d000000010120018f000000000110004c0000000d0000c13d01ed006d0000040f01ed000e0000040f00040000000000020000008001000039000000400300003900000000001304350000000002000416000000000220004c000000410000c13d000100000003001d0000007e02000041000000a40300003900000000002304350000007f020000410000000000210435000000840100003900000000000104350000006002000039000000c401000039000200000002001d0000000000210435000000e4010000390000000000010435000000800100004100008006020000390000000003000415000000040330008a00000020033000c901ed01b70000040f000000040100035f000000ff02000039000000030220024f000000010220008c000000430000c13d000000000301043b000000000230004c000000430000613d0000000001000019000200000003001d01ed01eb0000040f000000020200002900000083022001970000008401100197000000000121019f000000000200001901ed01e90000040f000000200100003900000100020000390000000000120439000001200100003900000000000104390000008501000041000001ee0001042e0000000001000019000001ef000104300000004002100370000000000402043b000000600210037000030000000203550000001f0340018f000100000004001f000000010100002900000000010104330000000504400270000000000540004c000000570000613d000000000500001900000005065002100000000007610019000000000662034f000000000606043b00000000006704350000000105500039000000000645004b0000004f0000413d000000000530004c000000660000613d0000000504400210000000000242034f00000000044100190000000303300210000000000504043300000000053501cf000000000535022f000000000202043b0000010003300089000000000232022f00000000023201cf000000000252019f000000000024043500000040011002100000008101100197000000020200002900000001022001ff0000008202200197000000000112019f000001ef0001043000060000000000020000000001000410000080020210008c000000880000613d0000000002000411000080010220008c000000880000613d0000008602000041000000000020043900000004020000390000000000120439000000870100004100008002020000390000000003000415000000060330008a00000020033000c901ed01d00000040f000000ff01000039000000050110024f000000000110004c000000ab0000613d000000060100035f000000000101043b000000000110004c000000880000c13d0000000001000019000001ee0001042e0000008006000039000000400500003900000000006504350000000001000031000000030210008c000000a90000a13d0000000202000367000000000202043b000000e002200270000000880320009c000000ad0000613d000000890220009c000000a90000c13d0000000002000416000000000220004c000000c10000c13d000000040110008a000000010200008a0000008a03000041000000000221004b000000000200001900000000020320190000008a011001970000008a0410009c00000000030080190000008a011001670000008a0110009c00000000010200190000000001036019000000000110004c000000c50000c13d0000000001000019000001ef000104300000000001000019000001ef000104300000000001000019000001ef000104300000000002000416000000000220004c000000c30000c13d000000040110008a000000010200008a0000008a03000041000000000221004b000000000200001900000000020320190000008a011001970000008a0410009c00000000030080190000008a011001670000008a0110009c00000000010200190000000001036019000000000110004c000000d30000c13d0000000001000019000001ef000104300000000001000019000001ef000104300000000001000019000001ef000104300000000001000019000200000005001d01ed01eb0000040f000000020a00002900000000080a04330000008b02000041000000000028043500000000030004140000008302100197000000040120008c000000db0000c13d00000003020003670000000101000031000000f10000013d0000000001000019000200000006001d01ed01eb0000040f0000008301100197000000020200002900000000001204350000009501000041000001ee0001042e000000c0013002100000008c0110019700000040038002100000008103300197000000000113019f0000008d011001c70000000003000415000000040330008a00000020033000c9000100000008001d01ed01d00000040f0000000108000029000000020a000029000000040200035f000300000002035500000060012002700001007d0010019d0000007d01100197000000ff03000039000000030330024f000000000330004c0000012e0000613d0000001f0310018f0000000504100270000000000540004c000000fe0000613d000000000500001900000005065002100000000007680019000000000662034f000000000606043b00000000006704350000000105500039000000000645004b000000f60000413d000000000530004c0000010d0000613d0000000504400210000000000242034f00000000044800190000000303300210000000000504043300000000053501cf000000000535022f000000000202043b0000010003300089000000000232022f00000000023201cf000000000252019f00000000002404350000001f02100039000000200300008a000000000432016f0000000002840019000000000442004b000000000400001900000001040040390000008e0520009c000001270000213d000000010440018f000000000440004c000001270000c13d00000000002a04350000008a04000041000000200510008c000000000500001900000000050440190000008a06100197000000000760004c000000000400a0190000008a0660009c000000000405c019000000000440004c000001520000613d0000000001000019000001ef00010430000000930100004100000000001004350000004101000039000000040200003900000000001204350000009401000041000001ef000104300000001f0410018f00000000030a04330000000501100270000000000510004c0000013c0000613d000000000500001900000005065002100000000007630019000000000662034f000000000606043b00000000006704350000000105500039000000000615004b000001340000413d000000000540004c0000014b0000613d0000000501100210000000000212034f00000000011300190000000304400210000000000501043300000000054501cf000000000545022f000000000202043b0000010004400089000000000242022f00000000024201cf000000000252019f000000000021043500000040013002100000008101100197000000600200003900000001022001ff0000008202200197000000000112019f000001ef0001043000000000040804330000008f0540009c000001570000413d0000000001000019000001ef00010430000000000181001900000000058400190000001f045000390000008a06000041000000000714004b000000000700001900000000070640190000008a044001970000008a08100197000000000984004b000000000600a019000000000484013f0000008a0440009c00000000040700190000000004066019000000000440004c000001720000613d00000000040504330000008f0640009c000001740000413d000000930100004100000000001004350000004101000039000000040200003900000000001204350000009401000041000001ef000104300000000001000019000001ef000104300000003f06400039000000000336016f00000000032300190000008f0630009c000001800000413d000000930100004100000000001004350000004101000039000000040200003900000000001204350000009401000041000001ef0001043000000000003a0435000000000042043500000020035000390000000005430019000000000115004b000001880000a13d0000000001000019000001ef000104300000002001200039000000000540004c000001930000613d000000000500001900000000061500190000000007530019000000000707043300000000007604350000002005500039000000000645004b0000018c0000413d0000000003140019000000000003043500000000040a0433000200000004001d000000200300003900000000003404350000000003020433000100000003001d00000020024000390000000000320435000000400240003901ed01aa0000040f000000020100002900000040011002100000008101100197000000010200002900000060022002100000009002200041000000910220019700000092022000410000009102200197000000000112019f000001ee0001042e000000000430004c000001b40000613d000000000400001900000000052400190000000006140019000000000606043300000000006504350000002004400039000000000534004b000001ad0000413d00000000012300190000000000010435000000000001042d0002000000000002000200000003001d0000002003300039000100000003001d000001c6002104210000000203000029000000200230011a00000000020103550000008a010000410000000102000029000000200220011a00000000021201bd00000000010300190000000200000005000000000001042d0000000203000029000000200230011a000000000201035500000096010000410000000102000029000000200220011a000000000212018d00000000010300190000000200000005000000000001042d0002000000000002000200000003001d0000002003300039000100000003001d000001df002104230000000203000029000000200230011a00000000020103550000008a010000410000000102000029000000200220011a00000000021201bd00000000010300190000000200000005000000000001042d0000000203000029000000200230011a000000000201035500000096010000410000000102000029000000200220011a000000000212018d00000000010300190000000200000005000000000001042d000000000012041b000000000001042d000000000101041a000000000001042d000001ed00000432000001ee0001042e000001ef00010430000000000000000100000000000000010000000000000001000000000000000100000000000000000000000000000000000000000000000000000000ffffffff01000061ed3851b8c5ecd6c9a112682425918e9bca825b159b17cb55fe7342ff9c4d535bdea7cd8a978f128b93471df48c7dbab89d703809115bdc118c235bfd02000000000000000000000000000000000000840000008000000000000000000000000000000000000000000000000000000000ffffffff000000000000000000000000000000000000000000000000ffffffff000000000000000000000000000000000000000000000000ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff000000000000000000000000000000000000000000000002000000000000000000000000000000400000010000000000000000001806aa1896bbf26568e884a7374b41e002500962caba6a15023a8d90e8508b83020002000000000000000000000000000000002400000000000000000000000000000000000000000000000000000000000000000000000000000000c298557800000000000000000000000000000000000000000000000000000000c6261261800000000000000000000000000000000000000000000000000000000000000006fdde030000000000000000000000000000000000000000000000000000000000000000ffffffff0000000000000000000000000000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000000000000ffffffffffffffff0000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000001f00000000000000000000000000000000000000000000000000000000ffffffe000000000000000000000000000000000000000000000000000000000000000400000000000000000000000004e487b7100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002400000000000000000000000000000000000000000000000000000000000000200000008000000000000000007fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"; - public static final String FOO_BINARY = "0x0002000000000002000100000001035500000060011002700000004e0010019d000000010120018f000000000110004c000000080000c13d013100720000040f013100090000040f00040000000000020000008001000039000000400200003900000000001204350000000001000416000000000110004c000000280000c13d00000000010000190131012f0000040f000000010210018f00000001011002700000007f0310018f000000000420004c000000000301c0190000001f0130008c00000000010000190000000101002039000000010110018f000000000220004c0000000002000019000000010200c039000000010220018f000000000112004b0000002a0000613d000000540100004100000000001004350000002201000039000000040200003900000000001204350000005501000041000001330001043000000000010000190000013300010430000000200130008c0000004a0000413d000200000003001d00000000000004350000004f0100004100008010020000390000000003000415000000040330008a00000020033000c9013101140000040f000000040100035f000000ff02000039000000030220024f000000000220004c000000540000613d000000000201043b00000002010000290000001f0110003900000005011002700000000003120019000000000132004b0000004a0000813d000100000003001d000200000002001d000000000100001900000002020000290131012d0000040f000000010300002900000002020000290000000102200039000000000132004b000000410000413d000000520100004100000000020000190131012d0000040f000000200100003900000100020000390000000000120439000001200100003900000000000104390000005301000041000001320001042e00000060021002700000001f0220018f00000065031002700000005003300197000000000430004c000000620000613d00000000040000190000000505400210000000000651034f000000000606043b00000000006504350000000104400039000000000534004b0000005b0000413d000000000420004c000000700000613d00000003022002100000000503300210000000000403043300000000042401cf000000000424022f000000000531034f000000000505043b0000010002200089000000000525022f00000000022501cf000000000242019f00000000002304350000005101100197000001330001043000060000000000020000000001000410000080020210008c0000008d0000613d0000000002000411000080010220008c0000008d0000613d0000005602000041000000000020043900000004020000390000000000120439000000570100004100008002020000390000000003000415000000060330008a00000020033000c9013101140000040f000000ff01000039000000050110024f000000000110004c000000ab0000613d000000060100035f000000000101043b000000000110004c0000008d0000c13d0000000001000019000001320001042e0000000001000031000000030210008c000000a90000a13d0000000102000367000000000202043b0000005802200197000000590220009c000000a90000c13d0000000002000416000000000220004c000000ad0000c13d000000040110008a000000010200008a0000005a03000041000000000221004b000000000200001900000000020320190000005a011001970000005a0410009c00000000030080190000005a011001670000005a0110009c00000000010200190000000001036019000000000110004c000000af0000c13d0000000001000019000001330001043000000000010000190000013300010430000000000100001900000133000104300000000001000019000001330001043000000000010000190131012f0000040f000000010210018f00000001031002700000007f0430018f000000000520004c000000000503001900000000050460190000001f0350008c00000000030000190000000103002039000000010330018f000000000420004c0000000004000019000000010400c039000000010440018f000000000334004b000000c80000613d000000540100004100000000001004350000002201000039000000040200003900000000001204350000005501000041000001330001043000000080040000390000000000540435000000000220004c000000d40000c13d000001000200008a000000000121016f000000a0020000390000000000120435000000000150004c000000c001000039000000a001006039000000ec0000013d000000bf01000039000000a0030000390000000000000435000000000250004c000000f90000613d000100000004001d0000005b030000410000000001000019000200000005001d000400000003001d000300000001001d00000000010300190131012f0000040f000000030400002900000004030000290000000205000029000000a002400039000000000012043500000001033000390000002001400039000000000251004b000000dd0000413d000000c00140003900000001040000290000001f01100039000000200200008a000000000321016f000000800230008a0000005c0220009c000000f90000a13d000000540100004100000000001004350000004101000039000000040200003900000000001204350000005501000041000001330001043000000040020000390000000000320435000000200200003900000000002304350000000002040433000000200430003900000000002404350000004003300039000000000420004c0000010b0000613d00000000040000190000000005430019000000a006400039000000000606043300000000006504350000002004400039000000000524004b000001040000413d0000000003230019000000000003043500000040011002100000005d0110019700000060022002100000005e022000410000005f02200197000000000112019f000001320001042e0002000000000002000200000003001d0000002003300039000100000003001d00000123002104230000000203000029000000200230011a00000000020103550000005a010000410000000102000029000000200220011a00000000021201bd00000000010300190000000200000005000000000001042d0000000203000029000000200230011a000000000201035500000060010000410000000102000029000000200220011a000000000212018d00000000010300190000000200000005000000000001042d000000000012041b000000000001042d000000000101041a000000000001042d0000013100000432000001320001042e0000013300010430000000000000000100000000000000010000000000000001000000000000000100000000000000000000000000000000000000000000000000000000ffffffff020000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000000000000007ffffffffffffff00000000000000000000000000000000ffffffff000000000000000000000000466f6f000000000000000000000000000000000000000000000000000000000600000002000000000000000000000000000000400000010000000000000000004e487b710000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000240000000000000000000000001806aa1896bbf26568e884a7374b41e002500962caba6a15023a8d90e8508b830200020000000000000000000000000000000024000000000000000000000000ffffffff0000000000000000000000000000000000000000000000000000000006fdde03000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000000000290decd9548b62a8d60345a988386fc84ba6bc95484008f6362f93160ef3e563000000000000000000000000000000000000000000000000ffffffffffffff7f0000000000000000000000000000000000000000ffffffe00000000000000000000000000000000000000000000000000000005f00000000000000000000000000000000000000000000000000000000ffffffe00000000000000000000000007fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"; - public static final String FUNC_FOO = "foo"; - - public static final String FUNC_GETFOONAME = "getFooName"; - - @Deprecated - protected Import(String contractAddress, Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) { - super(BINARY, contractAddress, web3j, credentials, gasPrice, gasLimit); - } - - protected Import(String contractAddress, Web3j web3j, Credentials credentials, ContractGasProvider contractGasProvider) { - super(BINARY, contractAddress, web3j, credentials, contractGasProvider); - } - - @Deprecated - protected Import(String contractAddress, Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit) { - super(BINARY, contractAddress, web3j, transactionManager, gasPrice, gasLimit); - } - - protected Import(String contractAddress, Web3j web3j, TransactionManager transactionManager, ContractGasProvider contractGasProvider) { - super(BINARY, contractAddress, web3j, transactionManager, contractGasProvider); - } - - public RemoteFunctionCall foo() { - final Function function = new Function(FUNC_FOO, - Arrays.asList(), - Arrays.>asList(new TypeReference

() {})); - return executeRemoteCallSingleValueReturn(function, String.class); - } - - public RemoteFunctionCall getFooName() { - final Function function = new Function(FUNC_GETFOONAME, - Arrays.asList(), - Arrays.>asList(new TypeReference() {})); - return executeRemoteCallSingleValueReturn(function, String.class); - } - - public static Function encodeGetFooName() { - return new Function(FUNC_GETFOONAME, - Arrays.asList(), - Arrays.>asList(new TypeReference() {})); - } - - @Deprecated - public static Import load(String contractAddress, Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) { - return new Import(contractAddress, web3j, credentials, gasPrice, gasLimit); - } - - @Deprecated - public static Import load(String contractAddress, Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit) { - return new Import(contractAddress, web3j, transactionManager, gasPrice, gasLimit); - } - - public static Import load(String contractAddress, Web3j web3j, Credentials credentials, ContractGasProvider contractGasProvider) { - return new Import(contractAddress, web3j, credentials, contractGasProvider); - } - - public static Import load(String contractAddress, Web3j web3j, TransactionManager transactionManager, ContractGasProvider contractGasProvider) { - return new Import(contractAddress, web3j, transactionManager, contractGasProvider); - } - - public static RemoteCall deploy(Web3j web3j, Credentials credentials, ContractGasProvider contractGasProvider) { - return deployRemoteCall(Import.class, web3j, credentials, contractGasProvider, BINARY, ""); - } - - @Deprecated - public static RemoteCall deploy(Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) { - return deployRemoteCall(Import.class, web3j, credentials, gasPrice, gasLimit, BINARY, ""); - } - - public static RemoteCall deploy(Web3j web3j, TransactionManager transactionManager, ContractGasProvider contractGasProvider) { - return deployRemoteCall(Import.class, web3j, transactionManager, contractGasProvider, BINARY, ""); - } - - @Deprecated - public static RemoteCall deploy(Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit) { - return deployRemoteCall(Import.class, web3j, transactionManager, gasPrice, gasLimit, BINARY, ""); - } + public static final String BINARY = + "0x0004000000000002000200000001035500000060031002700000007d0030019d0000007d03300197000000000131034f000300000001035500000060011002700001007d0010019d000000010120018f000000000110004c0000000d0000c13d01ed006d0000040f01ed000e0000040f00040000000000020000008001000039000000400300003900000000001304350000000002000416000000000220004c000000410000c13d000100000003001d0000007e02000041000000a40300003900000000002304350000007f020000410000000000210435000000840100003900000000000104350000006002000039000000c401000039000200000002001d0000000000210435000000e4010000390000000000010435000000800100004100008006020000390000000003000415000000040330008a00000020033000c901ed01b70000040f000000040100035f000000ff02000039000000030220024f000000010220008c000000430000c13d000000000301043b000000000230004c000000430000613d0000000001000019000200000003001d01ed01eb0000040f000000020200002900000083022001970000008401100197000000000121019f000000000200001901ed01e90000040f000000200100003900000100020000390000000000120439000001200100003900000000000104390000008501000041000001ee0001042e0000000001000019000001ef000104300000004002100370000000000402043b000000600210037000030000000203550000001f0340018f000100000004001f000000010100002900000000010104330000000504400270000000000540004c000000570000613d000000000500001900000005065002100000000007610019000000000662034f000000000606043b00000000006704350000000105500039000000000645004b0000004f0000413d000000000530004c000000660000613d0000000504400210000000000242034f00000000044100190000000303300210000000000504043300000000053501cf000000000535022f000000000202043b0000010003300089000000000232022f00000000023201cf000000000252019f000000000024043500000040011002100000008101100197000000020200002900000001022001ff0000008202200197000000000112019f000001ef0001043000060000000000020000000001000410000080020210008c000000880000613d0000000002000411000080010220008c000000880000613d0000008602000041000000000020043900000004020000390000000000120439000000870100004100008002020000390000000003000415000000060330008a00000020033000c901ed01d00000040f000000ff01000039000000050110024f000000000110004c000000ab0000613d000000060100035f000000000101043b000000000110004c000000880000c13d0000000001000019000001ee0001042e0000008006000039000000400500003900000000006504350000000001000031000000030210008c000000a90000a13d0000000202000367000000000202043b000000e002200270000000880320009c000000ad0000613d000000890220009c000000a90000c13d0000000002000416000000000220004c000000c10000c13d000000040110008a000000010200008a0000008a03000041000000000221004b000000000200001900000000020320190000008a011001970000008a0410009c00000000030080190000008a011001670000008a0110009c00000000010200190000000001036019000000000110004c000000c50000c13d0000000001000019000001ef000104300000000001000019000001ef000104300000000001000019000001ef000104300000000002000416000000000220004c000000c30000c13d000000040110008a000000010200008a0000008a03000041000000000221004b000000000200001900000000020320190000008a011001970000008a0410009c00000000030080190000008a011001670000008a0110009c00000000010200190000000001036019000000000110004c000000d30000c13d0000000001000019000001ef000104300000000001000019000001ef000104300000000001000019000001ef000104300000000001000019000200000005001d01ed01eb0000040f000000020a00002900000000080a04330000008b02000041000000000028043500000000030004140000008302100197000000040120008c000000db0000c13d00000003020003670000000101000031000000f10000013d0000000001000019000200000006001d01ed01eb0000040f0000008301100197000000020200002900000000001204350000009501000041000001ee0001042e000000c0013002100000008c0110019700000040038002100000008103300197000000000113019f0000008d011001c70000000003000415000000040330008a00000020033000c9000100000008001d01ed01d00000040f0000000108000029000000020a000029000000040200035f000300000002035500000060012002700001007d0010019d0000007d01100197000000ff03000039000000030330024f000000000330004c0000012e0000613d0000001f0310018f0000000504100270000000000540004c000000fe0000613d000000000500001900000005065002100000000007680019000000000662034f000000000606043b00000000006704350000000105500039000000000645004b000000f60000413d000000000530004c0000010d0000613d0000000504400210000000000242034f00000000044800190000000303300210000000000504043300000000053501cf000000000535022f000000000202043b0000010003300089000000000232022f00000000023201cf000000000252019f00000000002404350000001f02100039000000200300008a000000000432016f0000000002840019000000000442004b000000000400001900000001040040390000008e0520009c000001270000213d000000010440018f000000000440004c000001270000c13d00000000002a04350000008a04000041000000200510008c000000000500001900000000050440190000008a06100197000000000760004c000000000400a0190000008a0660009c000000000405c019000000000440004c000001520000613d0000000001000019000001ef00010430000000930100004100000000001004350000004101000039000000040200003900000000001204350000009401000041000001ef000104300000001f0410018f00000000030a04330000000501100270000000000510004c0000013c0000613d000000000500001900000005065002100000000007630019000000000662034f000000000606043b00000000006704350000000105500039000000000615004b000001340000413d000000000540004c0000014b0000613d0000000501100210000000000212034f00000000011300190000000304400210000000000501043300000000054501cf000000000545022f000000000202043b0000010004400089000000000242022f00000000024201cf000000000252019f000000000021043500000040013002100000008101100197000000600200003900000001022001ff0000008202200197000000000112019f000001ef0001043000000000040804330000008f0540009c000001570000413d0000000001000019000001ef00010430000000000181001900000000058400190000001f045000390000008a06000041000000000714004b000000000700001900000000070640190000008a044001970000008a08100197000000000984004b000000000600a019000000000484013f0000008a0440009c00000000040700190000000004066019000000000440004c000001720000613d00000000040504330000008f0640009c000001740000413d000000930100004100000000001004350000004101000039000000040200003900000000001204350000009401000041000001ef000104300000000001000019000001ef000104300000003f06400039000000000336016f00000000032300190000008f0630009c000001800000413d000000930100004100000000001004350000004101000039000000040200003900000000001204350000009401000041000001ef0001043000000000003a0435000000000042043500000020035000390000000005430019000000000115004b000001880000a13d0000000001000019000001ef000104300000002001200039000000000540004c000001930000613d000000000500001900000000061500190000000007530019000000000707043300000000007604350000002005500039000000000645004b0000018c0000413d0000000003140019000000000003043500000000040a0433000200000004001d000000200300003900000000003404350000000003020433000100000003001d00000020024000390000000000320435000000400240003901ed01aa0000040f000000020100002900000040011002100000008101100197000000010200002900000060022002100000009002200041000000910220019700000092022000410000009102200197000000000112019f000001ee0001042e000000000430004c000001b40000613d000000000400001900000000052400190000000006140019000000000606043300000000006504350000002004400039000000000534004b000001ad0000413d00000000012300190000000000010435000000000001042d0002000000000002000200000003001d0000002003300039000100000003001d000001c6002104210000000203000029000000200230011a00000000020103550000008a010000410000000102000029000000200220011a00000000021201bd00000000010300190000000200000005000000000001042d0000000203000029000000200230011a000000000201035500000096010000410000000102000029000000200220011a000000000212018d00000000010300190000000200000005000000000001042d0002000000000002000200000003001d0000002003300039000100000003001d000001df002104230000000203000029000000200230011a00000000020103550000008a010000410000000102000029000000200220011a00000000021201bd00000000010300190000000200000005000000000001042d0000000203000029000000200230011a000000000201035500000096010000410000000102000029000000200220011a000000000212018d00000000010300190000000200000005000000000001042d000000000012041b000000000001042d000000000101041a000000000001042d000001ed00000432000001ee0001042e000001ef00010430000000000000000100000000000000010000000000000001000000000000000100000000000000000000000000000000000000000000000000000000ffffffff01000061ed3851b8c5ecd6c9a112682425918e9bca825b159b17cb55fe7342ff9c4d535bdea7cd8a978f128b93471df48c7dbab89d703809115bdc118c235bfd02000000000000000000000000000000000000840000008000000000000000000000000000000000000000000000000000000000ffffffff000000000000000000000000000000000000000000000000ffffffff000000000000000000000000000000000000000000000000ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff000000000000000000000000000000000000000000000002000000000000000000000000000000400000010000000000000000001806aa1896bbf26568e884a7374b41e002500962caba6a15023a8d90e8508b83020002000000000000000000000000000000002400000000000000000000000000000000000000000000000000000000000000000000000000000000c298557800000000000000000000000000000000000000000000000000000000c6261261800000000000000000000000000000000000000000000000000000000000000006fdde030000000000000000000000000000000000000000000000000000000000000000ffffffff0000000000000000000000000000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000000000000ffffffffffffffff0000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000001f00000000000000000000000000000000000000000000000000000000ffffffe000000000000000000000000000000000000000000000000000000000000000400000000000000000000000004e487b7100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002400000000000000000000000000000000000000000000000000000000000000200000008000000000000000007fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"; + public static final String FOO_BINARY = + "0x0002000000000002000100000001035500000060011002700000004e0010019d000000010120018f000000000110004c000000080000c13d013100720000040f013100090000040f00040000000000020000008001000039000000400200003900000000001204350000000001000416000000000110004c000000280000c13d00000000010000190131012f0000040f000000010210018f00000001011002700000007f0310018f000000000420004c000000000301c0190000001f0130008c00000000010000190000000101002039000000010110018f000000000220004c0000000002000019000000010200c039000000010220018f000000000112004b0000002a0000613d000000540100004100000000001004350000002201000039000000040200003900000000001204350000005501000041000001330001043000000000010000190000013300010430000000200130008c0000004a0000413d000200000003001d00000000000004350000004f0100004100008010020000390000000003000415000000040330008a00000020033000c9013101140000040f000000040100035f000000ff02000039000000030220024f000000000220004c000000540000613d000000000201043b00000002010000290000001f0110003900000005011002700000000003120019000000000132004b0000004a0000813d000100000003001d000200000002001d000000000100001900000002020000290131012d0000040f000000010300002900000002020000290000000102200039000000000132004b000000410000413d000000520100004100000000020000190131012d0000040f000000200100003900000100020000390000000000120439000001200100003900000000000104390000005301000041000001320001042e00000060021002700000001f0220018f00000065031002700000005003300197000000000430004c000000620000613d00000000040000190000000505400210000000000651034f000000000606043b00000000006504350000000104400039000000000534004b0000005b0000413d000000000420004c000000700000613d00000003022002100000000503300210000000000403043300000000042401cf000000000424022f000000000531034f000000000505043b0000010002200089000000000525022f00000000022501cf000000000242019f00000000002304350000005101100197000001330001043000060000000000020000000001000410000080020210008c0000008d0000613d0000000002000411000080010220008c0000008d0000613d0000005602000041000000000020043900000004020000390000000000120439000000570100004100008002020000390000000003000415000000060330008a00000020033000c9013101140000040f000000ff01000039000000050110024f000000000110004c000000ab0000613d000000060100035f000000000101043b000000000110004c0000008d0000c13d0000000001000019000001320001042e0000000001000031000000030210008c000000a90000a13d0000000102000367000000000202043b0000005802200197000000590220009c000000a90000c13d0000000002000416000000000220004c000000ad0000c13d000000040110008a000000010200008a0000005a03000041000000000221004b000000000200001900000000020320190000005a011001970000005a0410009c00000000030080190000005a011001670000005a0110009c00000000010200190000000001036019000000000110004c000000af0000c13d0000000001000019000001330001043000000000010000190000013300010430000000000100001900000133000104300000000001000019000001330001043000000000010000190131012f0000040f000000010210018f00000001031002700000007f0430018f000000000520004c000000000503001900000000050460190000001f0350008c00000000030000190000000103002039000000010330018f000000000420004c0000000004000019000000010400c039000000010440018f000000000334004b000000c80000613d000000540100004100000000001004350000002201000039000000040200003900000000001204350000005501000041000001330001043000000080040000390000000000540435000000000220004c000000d40000c13d000001000200008a000000000121016f000000a0020000390000000000120435000000000150004c000000c001000039000000a001006039000000ec0000013d000000bf01000039000000a0030000390000000000000435000000000250004c000000f90000613d000100000004001d0000005b030000410000000001000019000200000005001d000400000003001d000300000001001d00000000010300190131012f0000040f000000030400002900000004030000290000000205000029000000a002400039000000000012043500000001033000390000002001400039000000000251004b000000dd0000413d000000c00140003900000001040000290000001f01100039000000200200008a000000000321016f000000800230008a0000005c0220009c000000f90000a13d000000540100004100000000001004350000004101000039000000040200003900000000001204350000005501000041000001330001043000000040020000390000000000320435000000200200003900000000002304350000000002040433000000200430003900000000002404350000004003300039000000000420004c0000010b0000613d00000000040000190000000005430019000000a006400039000000000606043300000000006504350000002004400039000000000524004b000001040000413d0000000003230019000000000003043500000040011002100000005d0110019700000060022002100000005e022000410000005f02200197000000000112019f000001320001042e0002000000000002000200000003001d0000002003300039000100000003001d00000123002104230000000203000029000000200230011a00000000020103550000005a010000410000000102000029000000200220011a00000000021201bd00000000010300190000000200000005000000000001042d0000000203000029000000200230011a000000000201035500000060010000410000000102000029000000200220011a000000000212018d00000000010300190000000200000005000000000001042d000000000012041b000000000001042d000000000101041a000000000001042d0000013100000432000001320001042e0000013300010430000000000000000100000000000000010000000000000001000000000000000100000000000000000000000000000000000000000000000000000000ffffffff020000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000000000000007ffffffffffffff00000000000000000000000000000000ffffffff000000000000000000000000466f6f000000000000000000000000000000000000000000000000000000000600000002000000000000000000000000000000400000010000000000000000004e487b710000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000240000000000000000000000001806aa1896bbf26568e884a7374b41e002500962caba6a15023a8d90e8508b830200020000000000000000000000000000000024000000000000000000000000ffffffff0000000000000000000000000000000000000000000000000000000006fdde03000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000000000290decd9548b62a8d60345a988386fc84ba6bc95484008f6362f93160ef3e563000000000000000000000000000000000000000000000000ffffffffffffff7f0000000000000000000000000000000000000000ffffffe00000000000000000000000000000000000000000000000000000005f00000000000000000000000000000000000000000000000000000000ffffffe00000000000000000000000007fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"; + public static final String FUNC_FOO = "foo"; + + public static final String FUNC_GETFOONAME = "getFooName"; + + @Deprecated + protected Import( + String contractAddress, + Web3j web3j, + Credentials credentials, + BigInteger gasPrice, + BigInteger gasLimit) { + super(BINARY, contractAddress, web3j, credentials, gasPrice, gasLimit); + } + + protected Import( + String contractAddress, + Web3j web3j, + Credentials credentials, + ContractGasProvider contractGasProvider) { + super(BINARY, contractAddress, web3j, credentials, contractGasProvider); + } + + @Deprecated + protected Import( + String contractAddress, + Web3j web3j, + TransactionManager transactionManager, + BigInteger gasPrice, + BigInteger gasLimit) { + super(BINARY, contractAddress, web3j, transactionManager, gasPrice, gasLimit); + } + + protected Import( + String contractAddress, + Web3j web3j, + TransactionManager transactionManager, + ContractGasProvider contractGasProvider) { + super(BINARY, contractAddress, web3j, transactionManager, contractGasProvider); + } + + public RemoteFunctionCall foo() { + final Function function = + new Function( + FUNC_FOO, + Arrays.asList(), + Arrays.>asList(new TypeReference
() {})); + return executeRemoteCallSingleValueReturn(function, String.class); + } + + public RemoteFunctionCall getFooName() { + final Function function = + new Function( + FUNC_GETFOONAME, + Arrays.asList(), + Arrays.>asList(new TypeReference() {})); + return executeRemoteCallSingleValueReturn(function, String.class); + } + + public static Function encodeGetFooName() { + return new Function( + FUNC_GETFOONAME, + Arrays.asList(), + Arrays.>asList(new TypeReference() {})); + } + + @Deprecated + public static Import load( + String contractAddress, + Web3j web3j, + Credentials credentials, + BigInteger gasPrice, + BigInteger gasLimit) { + return new Import(contractAddress, web3j, credentials, gasPrice, gasLimit); + } + + @Deprecated + public static Import load( + String contractAddress, + Web3j web3j, + TransactionManager transactionManager, + BigInteger gasPrice, + BigInteger gasLimit) { + return new Import(contractAddress, web3j, transactionManager, gasPrice, gasLimit); + } + + public static Import load( + String contractAddress, + Web3j web3j, + Credentials credentials, + ContractGasProvider contractGasProvider) { + return new Import(contractAddress, web3j, credentials, contractGasProvider); + } + + public static Import load( + String contractAddress, + Web3j web3j, + TransactionManager transactionManager, + ContractGasProvider contractGasProvider) { + return new Import(contractAddress, web3j, transactionManager, contractGasProvider); + } + + public static RemoteCall deploy( + Web3j web3j, Credentials credentials, ContractGasProvider contractGasProvider) { + return deployRemoteCall(Import.class, web3j, credentials, contractGasProvider, BINARY, ""); + } + + @Deprecated + public static RemoteCall deploy( + Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) { + return deployRemoteCall(Import.class, web3j, credentials, gasPrice, gasLimit, BINARY, ""); + } + + public static RemoteCall deploy( + Web3j web3j, TransactionManager transactionManager, ContractGasProvider contractGasProvider) { + return deployRemoteCall( + Import.class, web3j, transactionManager, contractGasProvider, BINARY, ""); + } + + @Deprecated + public static RemoteCall deploy( + Web3j web3j, + TransactionManager transactionManager, + BigInteger gasPrice, + BigInteger gasLimit) { + return deployRemoteCall( + Import.class, web3j, transactionManager, gasPrice, gasLimit, BINARY, ""); + } } diff --git a/src/test/java/io/zksync/helper/RequestTester.java b/src/test/java/io/zksync/helper/RequestTester.java index 759d608..d96e8fd 100644 --- a/src/test/java/io/zksync/helper/RequestTester.java +++ b/src/test/java/io/zksync/helper/RequestTester.java @@ -12,8 +12,10 @@ */ package io.zksync.helper; -import java.io.IOException; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import java.io.IOException; import okhttp3.Interceptor; import okhttp3.MediaType; import okhttp3.OkHttpClient; @@ -23,71 +25,66 @@ import okhttp3.ResponseBody; import okio.Buffer; import org.junit.jupiter.api.BeforeEach; - import org.web3j.protocol.http.HttpService; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; - public abstract class RequestTester { - private OkHttpClient httpClient; - private HttpService httpService; - public static final MediaType JSON_MEDIA_TYPE = - MediaType.parse("application/json; charset=utf-8"); - private RequestInterceptor requestInterceptor; - - @BeforeEach - public void setUp() { - requestInterceptor = new RequestInterceptor(); - httpClient = new OkHttpClient.Builder().addInterceptor(requestInterceptor).build(); - httpService = new HttpService(httpClient); - initWeb3Client(httpService); - } - - protected abstract void initWeb3Client(HttpService httpService); - - protected void verifyResult(String expected) throws Exception { - RequestBody requestBody = requestInterceptor.getRequestBody(); - assertNotNull(requestBody); - assertEquals(requestBody.contentType(), (HttpService.JSON_MEDIA_TYPE)); - - Buffer buffer = new Buffer(); - requestBody.writeTo(buffer); - assertEquals((replaceRequestId(expected)), replaceRequestId(buffer.readUtf8())); - } - - private String replaceRequestId(String json) { - return json.replaceAll("\"id\":\\d*}$", "\"id\":}"); + private OkHttpClient httpClient; + private HttpService httpService; + public static final MediaType JSON_MEDIA_TYPE = + MediaType.parse("application/json; charset=utf-8"); + private RequestInterceptor requestInterceptor; + + @BeforeEach + public void setUp() { + requestInterceptor = new RequestInterceptor(); + httpClient = new OkHttpClient.Builder().addInterceptor(requestInterceptor).build(); + httpService = new HttpService(httpClient); + initWeb3Client(httpService); + } + + protected abstract void initWeb3Client(HttpService httpService); + + protected void verifyResult(String expected) throws Exception { + RequestBody requestBody = requestInterceptor.getRequestBody(); + assertNotNull(requestBody); + assertEquals(requestBody.contentType(), (HttpService.JSON_MEDIA_TYPE)); + + Buffer buffer = new Buffer(); + requestBody.writeTo(buffer); + assertEquals((replaceRequestId(expected)), replaceRequestId(buffer.readUtf8())); + } + + private String replaceRequestId(String json) { + return json.replaceAll("\"id\":\\d*}$", "\"id\":}"); + } + + private class RequestInterceptor implements Interceptor { + + private RequestBody requestBody; + + @Override + public okhttp3.Response intercept(Chain chain) throws IOException { + + Request request = chain.request(); + this.requestBody = request.body(); + okhttp3.Response response = + new okhttp3.Response.Builder() + .request(chain.request()) + .protocol(Protocol.HTTP_2) + .code(200) + .body( + ResponseBody.create( + "{\"jsonrpc\":\"2.0\",\"method\":\"\"," + "\"params\":[],\"id\":1}", + JSON_MEDIA_TYPE)) + .message("") + .build(); + + return response; } - private class RequestInterceptor implements Interceptor { - - private RequestBody requestBody; - - @Override - public okhttp3.Response intercept(Chain chain) throws IOException { - - Request request = chain.request(); - this.requestBody = request.body(); - okhttp3.Response response = - new okhttp3.Response.Builder() - .request(chain.request()) - .protocol(Protocol.HTTP_2) - .code(200) - .body( - ResponseBody.create( - "{\"jsonrpc\":\"2.0\",\"method\":\"\"," - + "\"params\":[],\"id\":1}", - JSON_MEDIA_TYPE)) - .message("") - .build(); - - return response; - } - - public RequestBody getRequestBody() { - return requestBody; - } + public RequestBody getRequestBody() { + return requestBody; } -} \ No newline at end of file + } +} diff --git a/src/test/java/io/zksync/helper/ResponseTester.java b/src/test/java/io/zksync/helper/ResponseTester.java index 70a14da..a69d564 100644 --- a/src/test/java/io/zksync/helper/ResponseTester.java +++ b/src/test/java/io/zksync/helper/ResponseTester.java @@ -12,78 +12,76 @@ */ package io.zksync.helper; -import java.io.IOException; +import static org.junit.jupiter.api.Assertions.fail; +import static org.web3j.protocol.http.HttpService.JSON_MEDIA_TYPE; +import java.io.IOException; import okhttp3.Interceptor; import okhttp3.OkHttpClient; import okhttp3.Protocol; import okhttp3.ResponseBody; import org.junit.jupiter.api.BeforeEach; - import org.web3j.protocol.core.Request; import org.web3j.protocol.core.Response; import org.web3j.protocol.http.HttpService; -import static org.junit.jupiter.api.Assertions.fail; -import static org.web3j.protocol.http.HttpService.JSON_MEDIA_TYPE; - /** Protocol Response tests. */ public abstract class ResponseTester { - private HttpService web3jService; - private OkHttpClient okHttpClient; - private ResponseInterceptor responseInterceptor; - - @BeforeEach - public void setUp() { - responseInterceptor = new ResponseInterceptor(); - okHttpClient = new OkHttpClient.Builder().addInterceptor(responseInterceptor).build(); - configureWeb3Service(false); + private HttpService web3jService; + private OkHttpClient okHttpClient; + private ResponseInterceptor responseInterceptor; + + @BeforeEach + public void setUp() { + responseInterceptor = new ResponseInterceptor(); + okHttpClient = new OkHttpClient.Builder().addInterceptor(responseInterceptor).build(); + configureWeb3Service(false); + } + + protected void buildResponse(String data) { + responseInterceptor.setJsonResponse(data); + } + + protected void configureWeb3Service(boolean includeRawResponses) { + web3jService = new HttpService(okHttpClient, includeRawResponses); + } + + protected T deserialiseResponse(Class type) { + T response = null; + try { + response = web3jService.send(new Request(), type); + } catch (IOException e) { + fail(e.getMessage()); } + return response; + } - protected void buildResponse(String data) { - responseInterceptor.setJsonResponse(data); - } + private class ResponseInterceptor implements Interceptor { - protected void configureWeb3Service(boolean includeRawResponses) { - web3jService = new HttpService(okHttpClient, includeRawResponses); - } + private String jsonResponse; - protected T deserialiseResponse(Class type) { - T response = null; - try { - response = web3jService.send(new Request(), type); - } catch (IOException e) { - fail(e.getMessage()); - } - return response; + public void setJsonResponse(String jsonResponse) { + this.jsonResponse = jsonResponse; } - private class ResponseInterceptor implements Interceptor { - - private String jsonResponse; - - public void setJsonResponse(String jsonResponse) { - this.jsonResponse = jsonResponse; - } - - @Override - public okhttp3.Response intercept(Chain chain) throws IOException { + @Override + public okhttp3.Response intercept(Chain chain) throws IOException { - if (jsonResponse == null) { - throw new UnsupportedOperationException("Response has not been configured"); - } + if (jsonResponse == null) { + throw new UnsupportedOperationException("Response has not been configured"); + } - okhttp3.Response response = - new okhttp3.Response.Builder() - .body(ResponseBody.create(jsonResponse, JSON_MEDIA_TYPE)) - .request(chain.request()) - .protocol(Protocol.HTTP_2) - .code(200) - .message("") - .build(); + okhttp3.Response response = + new okhttp3.Response.Builder() + .body(ResponseBody.create(jsonResponse, JSON_MEDIA_TYPE)) + .request(chain.request()) + .protocol(Protocol.HTTP_2) + .code(200) + .message("") + .build(); - return response; - } + return response; } -} \ No newline at end of file + } +} diff --git a/src/test/java/io/zksync/helper/ZkSyncERC20.java b/src/test/java/io/zksync/helper/ZkSyncERC20.java index 4a1fbca..c6bc125 100644 --- a/src/test/java/io/zksync/helper/ZkSyncERC20.java +++ b/src/test/java/io/zksync/helper/ZkSyncERC20.java @@ -2,7 +2,6 @@ import io.reactivex.Flowable; import io.reactivex.functions.Function; - import java.io.ByteArrayOutputStream; import java.io.FileInputStream; import java.io.IOException; @@ -34,370 +33,531 @@ import org.web3j.tx.gas.ContractGasProvider; /** - *

Auto generated code. + * Auto generated code. + * *

Do not modify! + * *

Please use the web3j command line tools, - * or the org.web3j.codegen.SolidityFunctionWrapperGenerator in the - * codegen module to update. + * or the org.web3j.codegen.SolidityFunctionWrapperGenerator in the codegen module to update. * *

Generated with web3j version 1.4.1. */ @SuppressWarnings("rawtypes") public class ZkSyncERC20 extends Contract { - public static final String BINARY; - - static { - try (FileInputStream fis = new FileInputStream("src/test/resources/customERC20TokenBinary.hex")) { - ByteArrayOutputStream buffer = new ByteArrayOutputStream(); - - int count; - byte[] bytes = new byte[16536]; - while ((count = fis.read(bytes)) != -1) { - buffer.write(bytes, 0, count); - } - BINARY = buffer.toString("UTF-8"); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - public static final String FUNC__AFTERTOKENTRANSFER = "_afterTokenTransfer"; - - public static final String FUNC__APPROVE = "_approve"; - - public static final String FUNC__BEFORETOKENTRANSFER = "_beforeTokenTransfer"; - - public static final String FUNC__BURN = "_burn"; - - public static final String FUNC__MINT = "_mint"; - - public static final String FUNC__TRANSFER = "_transfer"; - - public static final String FUNC_ALLOWANCE = "allowance"; - - public static final String FUNC_APPROVE = "approve"; - - public static final String FUNC_BALANCEOF = "balanceOf"; - - public static final String FUNC_DECIMALS = "decimals"; - - public static final String FUNC_DECREASEALLOWANCE = "decreaseAllowance"; - - public static final String FUNC_INCREASEALLOWANCE = "increaseAllowance"; - - public static final String FUNC_NAME = "name"; - - public static final String FUNC_SYMBOL = "symbol"; - - public static final String FUNC_TOTALSUPPLY = "totalSupply"; - - public static final String FUNC_TRANSFER = "transfer"; - - public static final String FUNC_TRANSFERFROM = "transferFrom"; - - public static final Event APPROVAL_EVENT = new Event("Approval", - Arrays.>asList(new TypeReference

(true) {}, new TypeReference
(true) {}, new TypeReference() {})); - ; - - public static final Event TRANSFER_EVENT = new Event("Transfer", - Arrays.>asList(new TypeReference
(true) {}, new TypeReference
(true) {}, new TypeReference() {})); - ; - - @Deprecated - protected ZkSyncERC20(String contractAddress, Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) { - super(BINARY, contractAddress, web3j, credentials, gasPrice, gasLimit); - } - - protected ZkSyncERC20(String contractAddress, Web3j web3j, Credentials credentials, ContractGasProvider contractGasProvider) { - super(BINARY, contractAddress, web3j, credentials, contractGasProvider); - } - - @Deprecated - protected ZkSyncERC20(String contractAddress, Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit) { - super(BINARY, contractAddress, web3j, transactionManager, gasPrice, gasLimit); - } - - protected ZkSyncERC20(String contractAddress, Web3j web3j, TransactionManager transactionManager, ContractGasProvider contractGasProvider) { - super(BINARY, contractAddress, web3j, transactionManager, contractGasProvider); - } + public static final String BINARY; - public List getApprovalEvents(TransactionReceipt transactionReceipt) { - List valueList = extractEventParametersWithLog(APPROVAL_EVENT, transactionReceipt); - ArrayList responses = new ArrayList(valueList.size()); - for (Contract.EventValuesWithLog eventValues : valueList) { - ApprovalEventResponse typedResponse = new ApprovalEventResponse(); - typedResponse.log = eventValues.getLog(); - typedResponse.owner = (String) eventValues.getIndexedValues().get(0).getValue(); - typedResponse.spender = (String) eventValues.getIndexedValues().get(1).getValue(); - typedResponse.value = (BigInteger) eventValues.getNonIndexedValues().get(0).getValue(); - responses.add(typedResponse); - } - return responses; - } + static { + try (FileInputStream fis = + new FileInputStream("src/test/resources/customERC20TokenBinary.hex")) { + ByteArrayOutputStream buffer = new ByteArrayOutputStream(); - public Flowable approvalEventFlowable(EthFilter filter) { - return web3j.ethLogFlowable(filter).map(new Function() { - @Override - public ApprovalEventResponse apply(Log log) { - Contract.EventValuesWithLog eventValues = extractEventParametersWithLog(APPROVAL_EVENT, log); + int count; + byte[] bytes = new byte[16536]; + while ((count = fis.read(bytes)) != -1) { + buffer.write(bytes, 0, count); + } + BINARY = buffer.toString("UTF-8"); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + public static final String FUNC__AFTERTOKENTRANSFER = "_afterTokenTransfer"; + + public static final String FUNC__APPROVE = "_approve"; + + public static final String FUNC__BEFORETOKENTRANSFER = "_beforeTokenTransfer"; + + public static final String FUNC__BURN = "_burn"; + + public static final String FUNC__MINT = "_mint"; + + public static final String FUNC__TRANSFER = "_transfer"; + + public static final String FUNC_ALLOWANCE = "allowance"; + + public static final String FUNC_APPROVE = "approve"; + + public static final String FUNC_BALANCEOF = "balanceOf"; + + public static final String FUNC_DECIMALS = "decimals"; + + public static final String FUNC_DECREASEALLOWANCE = "decreaseAllowance"; + + public static final String FUNC_INCREASEALLOWANCE = "increaseAllowance"; + + public static final String FUNC_NAME = "name"; + + public static final String FUNC_SYMBOL = "symbol"; + + public static final String FUNC_TOTALSUPPLY = "totalSupply"; + + public static final String FUNC_TRANSFER = "transfer"; + + public static final String FUNC_TRANSFERFROM = "transferFrom"; + + public static final Event APPROVAL_EVENT = + new Event( + "Approval", + Arrays.>asList( + new TypeReference
(true) {}, + new TypeReference
(true) {}, + new TypeReference() {})); + ; + + public static final Event TRANSFER_EVENT = + new Event( + "Transfer", + Arrays.>asList( + new TypeReference
(true) {}, + new TypeReference
(true) {}, + new TypeReference() {})); + ; + + @Deprecated + protected ZkSyncERC20( + String contractAddress, + Web3j web3j, + Credentials credentials, + BigInteger gasPrice, + BigInteger gasLimit) { + super(BINARY, contractAddress, web3j, credentials, gasPrice, gasLimit); + } + + protected ZkSyncERC20( + String contractAddress, + Web3j web3j, + Credentials credentials, + ContractGasProvider contractGasProvider) { + super(BINARY, contractAddress, web3j, credentials, contractGasProvider); + } + + @Deprecated + protected ZkSyncERC20( + String contractAddress, + Web3j web3j, + TransactionManager transactionManager, + BigInteger gasPrice, + BigInteger gasLimit) { + super(BINARY, contractAddress, web3j, transactionManager, gasPrice, gasLimit); + } + + protected ZkSyncERC20( + String contractAddress, + Web3j web3j, + TransactionManager transactionManager, + ContractGasProvider contractGasProvider) { + super(BINARY, contractAddress, web3j, transactionManager, contractGasProvider); + } + + public List getApprovalEvents(TransactionReceipt transactionReceipt) { + List valueList = + extractEventParametersWithLog(APPROVAL_EVENT, transactionReceipt); + ArrayList responses = + new ArrayList(valueList.size()); + for (Contract.EventValuesWithLog eventValues : valueList) { + ApprovalEventResponse typedResponse = new ApprovalEventResponse(); + typedResponse.log = eventValues.getLog(); + typedResponse.owner = (String) eventValues.getIndexedValues().get(0).getValue(); + typedResponse.spender = (String) eventValues.getIndexedValues().get(1).getValue(); + typedResponse.value = (BigInteger) eventValues.getNonIndexedValues().get(0).getValue(); + responses.add(typedResponse); + } + return responses; + } + + public Flowable approvalEventFlowable(EthFilter filter) { + return web3j + .ethLogFlowable(filter) + .map( + new Function() { + @Override + public ApprovalEventResponse apply(Log log) { + Contract.EventValuesWithLog eventValues = + extractEventParametersWithLog(APPROVAL_EVENT, log); ApprovalEventResponse typedResponse = new ApprovalEventResponse(); typedResponse.log = log; typedResponse.owner = (String) eventValues.getIndexedValues().get(0).getValue(); typedResponse.spender = (String) eventValues.getIndexedValues().get(1).getValue(); - typedResponse.value = (BigInteger) eventValues.getNonIndexedValues().get(0).getValue(); + typedResponse.value = + (BigInteger) eventValues.getNonIndexedValues().get(0).getValue(); return typedResponse; - } - }); - } - - public Flowable approvalEventFlowable(DefaultBlockParameter startBlock, DefaultBlockParameter endBlock) { - EthFilter filter = new EthFilter(startBlock, endBlock, getContractAddress()); - filter.addSingleTopic(EventEncoder.encode(APPROVAL_EVENT)); - return approvalEventFlowable(filter); - } - - public List getTransferEvents(TransactionReceipt transactionReceipt) { - List valueList = extractEventParametersWithLog(TRANSFER_EVENT, transactionReceipt); - ArrayList responses = new ArrayList(valueList.size()); - for (Contract.EventValuesWithLog eventValues : valueList) { - TransferEventResponse typedResponse = new TransferEventResponse(); - typedResponse.log = eventValues.getLog(); - typedResponse.from = (String) eventValues.getIndexedValues().get(0).getValue(); - typedResponse.to = (String) eventValues.getIndexedValues().get(1).getValue(); - typedResponse.value = (BigInteger) eventValues.getNonIndexedValues().get(0).getValue(); - responses.add(typedResponse); - } - return responses; - } - - public Flowable transferEventFlowable(EthFilter filter) { - return web3j.ethLogFlowable(filter).map(new Function() { - @Override - public TransferEventResponse apply(Log log) { - Contract.EventValuesWithLog eventValues = extractEventParametersWithLog(TRANSFER_EVENT, log); + } + }); + } + + public Flowable approvalEventFlowable( + DefaultBlockParameter startBlock, DefaultBlockParameter endBlock) { + EthFilter filter = new EthFilter(startBlock, endBlock, getContractAddress()); + filter.addSingleTopic(EventEncoder.encode(APPROVAL_EVENT)); + return approvalEventFlowable(filter); + } + + public List getTransferEvents(TransactionReceipt transactionReceipt) { + List valueList = + extractEventParametersWithLog(TRANSFER_EVENT, transactionReceipt); + ArrayList responses = + new ArrayList(valueList.size()); + for (Contract.EventValuesWithLog eventValues : valueList) { + TransferEventResponse typedResponse = new TransferEventResponse(); + typedResponse.log = eventValues.getLog(); + typedResponse.from = (String) eventValues.getIndexedValues().get(0).getValue(); + typedResponse.to = (String) eventValues.getIndexedValues().get(1).getValue(); + typedResponse.value = (BigInteger) eventValues.getNonIndexedValues().get(0).getValue(); + responses.add(typedResponse); + } + return responses; + } + + public Flowable transferEventFlowable(EthFilter filter) { + return web3j + .ethLogFlowable(filter) + .map( + new Function() { + @Override + public TransferEventResponse apply(Log log) { + Contract.EventValuesWithLog eventValues = + extractEventParametersWithLog(TRANSFER_EVENT, log); TransferEventResponse typedResponse = new TransferEventResponse(); typedResponse.log = log; typedResponse.from = (String) eventValues.getIndexedValues().get(0).getValue(); typedResponse.to = (String) eventValues.getIndexedValues().get(1).getValue(); - typedResponse.value = (BigInteger) eventValues.getNonIndexedValues().get(0).getValue(); + typedResponse.value = + (BigInteger) eventValues.getNonIndexedValues().get(0).getValue(); return typedResponse; - } - }); - } - - public Flowable transferEventFlowable(DefaultBlockParameter startBlock, DefaultBlockParameter endBlock) { - EthFilter filter = new EthFilter(startBlock, endBlock, getContractAddress()); - filter.addSingleTopic(EventEncoder.encode(TRANSFER_EVENT)); - return transferEventFlowable(filter); - } - - public RemoteFunctionCall _afterTokenTransfer(String from, String to, BigInteger amount) { - final org.web3j.abi.datatypes.Function function = new org.web3j.abi.datatypes.Function( - FUNC__AFTERTOKENTRANSFER, - Arrays.asList(new org.web3j.abi.datatypes.Address(160, from), - new org.web3j.abi.datatypes.Address(160, to), - new org.web3j.abi.datatypes.generated.Uint256(amount)), - Collections.>emptyList()); - return executeRemoteCallTransaction(function); - } - - public RemoteFunctionCall _approve(String owner, String spender, BigInteger amount) { - final org.web3j.abi.datatypes.Function function = new org.web3j.abi.datatypes.Function( - FUNC__APPROVE, - Arrays.asList(new org.web3j.abi.datatypes.Address(160, owner), - new org.web3j.abi.datatypes.Address(160, spender), - new org.web3j.abi.datatypes.generated.Uint256(amount)), - Collections.>emptyList()); - return executeRemoteCallTransaction(function); - } - - public RemoteFunctionCall _beforeTokenTransfer(String from, String to, BigInteger amount) { - final org.web3j.abi.datatypes.Function function = new org.web3j.abi.datatypes.Function( - FUNC__BEFORETOKENTRANSFER, - Arrays.asList(new org.web3j.abi.datatypes.Address(160, from), - new org.web3j.abi.datatypes.Address(160, to), - new org.web3j.abi.datatypes.generated.Uint256(amount)), - Collections.>emptyList()); - return executeRemoteCallTransaction(function); - } - - public RemoteFunctionCall _burn(String account, BigInteger amount) { - final org.web3j.abi.datatypes.Function function = new org.web3j.abi.datatypes.Function( - FUNC__BURN, - Arrays.asList(new org.web3j.abi.datatypes.Address(160, account), - new org.web3j.abi.datatypes.generated.Uint256(amount)), - Collections.>emptyList()); - return executeRemoteCallTransaction(function); - } - - public RemoteFunctionCall _mint(String account, BigInteger amount) { - final org.web3j.abi.datatypes.Function function = new org.web3j.abi.datatypes.Function( - FUNC__MINT, - Arrays.asList(new org.web3j.abi.datatypes.Address(160, account), - new org.web3j.abi.datatypes.generated.Uint256(amount)), - Collections.>emptyList()); - return executeRemoteCallTransaction(function); - } - - public RemoteFunctionCall _transfer(String sender, String recipient, BigInteger amount) { - final org.web3j.abi.datatypes.Function function = new org.web3j.abi.datatypes.Function( - FUNC__TRANSFER, - Arrays.asList(new org.web3j.abi.datatypes.Address(160, sender), - new org.web3j.abi.datatypes.Address(160, recipient), - new org.web3j.abi.datatypes.generated.Uint256(amount)), - Collections.>emptyList()); - return executeRemoteCallTransaction(function); - } - - public RemoteFunctionCall allowance(String owner, String spender) { - final org.web3j.abi.datatypes.Function function = new org.web3j.abi.datatypes.Function(FUNC_ALLOWANCE, - Arrays.asList(new org.web3j.abi.datatypes.Address(160, owner), - new org.web3j.abi.datatypes.Address(160, spender)), - Arrays.>asList(new TypeReference() {})); - return executeRemoteCallSingleValueReturn(function, BigInteger.class); - } - - public RemoteFunctionCall approve(String spender, BigInteger amount) { - final org.web3j.abi.datatypes.Function function = new org.web3j.abi.datatypes.Function( - FUNC_APPROVE, - Arrays.asList(new org.web3j.abi.datatypes.Address(160, spender), - new org.web3j.abi.datatypes.generated.Uint256(amount)), - Collections.>emptyList()); - return executeRemoteCallTransaction(function); - } - - public RemoteFunctionCall balanceOf(String account) { - final org.web3j.abi.datatypes.Function function = new org.web3j.abi.datatypes.Function(FUNC_BALANCEOF, - Arrays.asList(new org.web3j.abi.datatypes.Address(160, account)), - Arrays.>asList(new TypeReference() {})); - return executeRemoteCallSingleValueReturn(function, BigInteger.class); - } - - public RemoteFunctionCall decimals() { - final org.web3j.abi.datatypes.Function function = new org.web3j.abi.datatypes.Function(FUNC_DECIMALS, - Arrays.asList(), - Arrays.>asList(new TypeReference() {})); - return executeRemoteCallSingleValueReturn(function, BigInteger.class); - } - - public RemoteFunctionCall decreaseAllowance(String spender, BigInteger subtractedValue) { - final org.web3j.abi.datatypes.Function function = new org.web3j.abi.datatypes.Function( - FUNC_DECREASEALLOWANCE, - Arrays.asList(new org.web3j.abi.datatypes.Address(160, spender), - new org.web3j.abi.datatypes.generated.Uint256(subtractedValue)), - Collections.>emptyList()); - return executeRemoteCallTransaction(function); - } - - public RemoteFunctionCall increaseAllowance(String spender, BigInteger addedValue) { - final org.web3j.abi.datatypes.Function function = new org.web3j.abi.datatypes.Function( - FUNC_INCREASEALLOWANCE, - Arrays.asList(new org.web3j.abi.datatypes.Address(160, spender), - new org.web3j.abi.datatypes.generated.Uint256(addedValue)), - Collections.>emptyList()); - return executeRemoteCallTransaction(function); - } - - public RemoteFunctionCall name() { - final org.web3j.abi.datatypes.Function function = new org.web3j.abi.datatypes.Function(FUNC_NAME, - Arrays.asList(), - Arrays.>asList(new TypeReference() {})); - return executeRemoteCallSingleValueReturn(function, String.class); - } - - public RemoteFunctionCall symbol() { - final org.web3j.abi.datatypes.Function function = new org.web3j.abi.datatypes.Function(FUNC_SYMBOL, - Arrays.asList(), - Arrays.>asList(new TypeReference() {})); - return executeRemoteCallSingleValueReturn(function, String.class); - } - - public RemoteFunctionCall totalSupply() { - final org.web3j.abi.datatypes.Function function = new org.web3j.abi.datatypes.Function(FUNC_TOTALSUPPLY, - Arrays.asList(), - Arrays.>asList(new TypeReference() {})); - return executeRemoteCallSingleValueReturn(function, BigInteger.class); - } - - public RemoteFunctionCall transfer(String recipient, BigInteger amount) { - final org.web3j.abi.datatypes.Function function = new org.web3j.abi.datatypes.Function( - FUNC_TRANSFER, - Arrays.asList(new org.web3j.abi.datatypes.Address(160, recipient), - new org.web3j.abi.datatypes.generated.Uint256(amount)), - Collections.>emptyList()); - return executeRemoteCallTransaction(function); - } - - public RemoteFunctionCall transferFrom(String sender, String recipient, BigInteger amount) { - final org.web3j.abi.datatypes.Function function = new org.web3j.abi.datatypes.Function( - FUNC_TRANSFERFROM, - Arrays.asList(new org.web3j.abi.datatypes.Address(160, sender), - new org.web3j.abi.datatypes.Address(160, recipient), - new org.web3j.abi.datatypes.generated.Uint256(amount)), - Collections.>emptyList()); - return executeRemoteCallTransaction(function); - } - - @Deprecated - public static ZkSyncERC20 load(String contractAddress, Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) { - return new ZkSyncERC20(contractAddress, web3j, credentials, gasPrice, gasLimit); - } - - @Deprecated - public static ZkSyncERC20 load(String contractAddress, Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit) { - return new ZkSyncERC20(contractAddress, web3j, transactionManager, gasPrice, gasLimit); - } - - public static ZkSyncERC20 load(String contractAddress, Web3j web3j, Credentials credentials, ContractGasProvider contractGasProvider) { - return new ZkSyncERC20(contractAddress, web3j, credentials, contractGasProvider); - } - - public static ZkSyncERC20 load(String contractAddress, Web3j web3j, TransactionManager transactionManager, ContractGasProvider contractGasProvider) { - return new ZkSyncERC20(contractAddress, web3j, transactionManager, contractGasProvider); - } - - public static RemoteCall deploy(Web3j web3j, Credentials credentials, ContractGasProvider contractGasProvider, String name, String symbol, BigInteger decimals) { - String encodedConstructor = FunctionEncoder.encodeConstructor(Arrays.asList(new org.web3j.abi.datatypes.Utf8String(name), - new org.web3j.abi.datatypes.Utf8String(symbol), + } + }); + } + + public Flowable transferEventFlowable( + DefaultBlockParameter startBlock, DefaultBlockParameter endBlock) { + EthFilter filter = new EthFilter(startBlock, endBlock, getContractAddress()); + filter.addSingleTopic(EventEncoder.encode(TRANSFER_EVENT)); + return transferEventFlowable(filter); + } + + public RemoteFunctionCall _afterTokenTransfer( + String from, String to, BigInteger amount) { + final org.web3j.abi.datatypes.Function function = + new org.web3j.abi.datatypes.Function( + FUNC__AFTERTOKENTRANSFER, + Arrays.asList( + new org.web3j.abi.datatypes.Address(160, from), + new org.web3j.abi.datatypes.Address(160, to), + new org.web3j.abi.datatypes.generated.Uint256(amount)), + Collections.>emptyList()); + return executeRemoteCallTransaction(function); + } + + public RemoteFunctionCall _approve( + String owner, String spender, BigInteger amount) { + final org.web3j.abi.datatypes.Function function = + new org.web3j.abi.datatypes.Function( + FUNC__APPROVE, + Arrays.asList( + new org.web3j.abi.datatypes.Address(160, owner), + new org.web3j.abi.datatypes.Address(160, spender), + new org.web3j.abi.datatypes.generated.Uint256(amount)), + Collections.>emptyList()); + return executeRemoteCallTransaction(function); + } + + public RemoteFunctionCall _beforeTokenTransfer( + String from, String to, BigInteger amount) { + final org.web3j.abi.datatypes.Function function = + new org.web3j.abi.datatypes.Function( + FUNC__BEFORETOKENTRANSFER, + Arrays.asList( + new org.web3j.abi.datatypes.Address(160, from), + new org.web3j.abi.datatypes.Address(160, to), + new org.web3j.abi.datatypes.generated.Uint256(amount)), + Collections.>emptyList()); + return executeRemoteCallTransaction(function); + } + + public RemoteFunctionCall _burn(String account, BigInteger amount) { + final org.web3j.abi.datatypes.Function function = + new org.web3j.abi.datatypes.Function( + FUNC__BURN, + Arrays.asList( + new org.web3j.abi.datatypes.Address(160, account), + new org.web3j.abi.datatypes.generated.Uint256(amount)), + Collections.>emptyList()); + return executeRemoteCallTransaction(function); + } + + public RemoteFunctionCall _mint(String account, BigInteger amount) { + final org.web3j.abi.datatypes.Function function = + new org.web3j.abi.datatypes.Function( + FUNC__MINT, + Arrays.asList( + new org.web3j.abi.datatypes.Address(160, account), + new org.web3j.abi.datatypes.generated.Uint256(amount)), + Collections.>emptyList()); + return executeRemoteCallTransaction(function); + } + + public RemoteFunctionCall _transfer( + String sender, String recipient, BigInteger amount) { + final org.web3j.abi.datatypes.Function function = + new org.web3j.abi.datatypes.Function( + FUNC__TRANSFER, + Arrays.asList( + new org.web3j.abi.datatypes.Address(160, sender), + new org.web3j.abi.datatypes.Address(160, recipient), + new org.web3j.abi.datatypes.generated.Uint256(amount)), + Collections.>emptyList()); + return executeRemoteCallTransaction(function); + } + + public RemoteFunctionCall allowance(String owner, String spender) { + final org.web3j.abi.datatypes.Function function = + new org.web3j.abi.datatypes.Function( + FUNC_ALLOWANCE, + Arrays.asList( + new org.web3j.abi.datatypes.Address(160, owner), + new org.web3j.abi.datatypes.Address(160, spender)), + Arrays.>asList(new TypeReference() {})); + return executeRemoteCallSingleValueReturn(function, BigInteger.class); + } + + public RemoteFunctionCall approve(String spender, BigInteger amount) { + final org.web3j.abi.datatypes.Function function = + new org.web3j.abi.datatypes.Function( + FUNC_APPROVE, + Arrays.asList( + new org.web3j.abi.datatypes.Address(160, spender), + new org.web3j.abi.datatypes.generated.Uint256(amount)), + Collections.>emptyList()); + return executeRemoteCallTransaction(function); + } + + public RemoteFunctionCall balanceOf(String account) { + final org.web3j.abi.datatypes.Function function = + new org.web3j.abi.datatypes.Function( + FUNC_BALANCEOF, + Arrays.asList(new org.web3j.abi.datatypes.Address(160, account)), + Arrays.>asList(new TypeReference() {})); + return executeRemoteCallSingleValueReturn(function, BigInteger.class); + } + + public RemoteFunctionCall decimals() { + final org.web3j.abi.datatypes.Function function = + new org.web3j.abi.datatypes.Function( + FUNC_DECIMALS, + Arrays.asList(), + Arrays.>asList(new TypeReference() {})); + return executeRemoteCallSingleValueReturn(function, BigInteger.class); + } + + public RemoteFunctionCall decreaseAllowance( + String spender, BigInteger subtractedValue) { + final org.web3j.abi.datatypes.Function function = + new org.web3j.abi.datatypes.Function( + FUNC_DECREASEALLOWANCE, + Arrays.asList( + new org.web3j.abi.datatypes.Address(160, spender), + new org.web3j.abi.datatypes.generated.Uint256(subtractedValue)), + Collections.>emptyList()); + return executeRemoteCallTransaction(function); + } + + public RemoteFunctionCall increaseAllowance( + String spender, BigInteger addedValue) { + final org.web3j.abi.datatypes.Function function = + new org.web3j.abi.datatypes.Function( + FUNC_INCREASEALLOWANCE, + Arrays.asList( + new org.web3j.abi.datatypes.Address(160, spender), + new org.web3j.abi.datatypes.generated.Uint256(addedValue)), + Collections.>emptyList()); + return executeRemoteCallTransaction(function); + } + + public RemoteFunctionCall name() { + final org.web3j.abi.datatypes.Function function = + new org.web3j.abi.datatypes.Function( + FUNC_NAME, + Arrays.asList(), + Arrays.>asList(new TypeReference() {})); + return executeRemoteCallSingleValueReturn(function, String.class); + } + + public RemoteFunctionCall symbol() { + final org.web3j.abi.datatypes.Function function = + new org.web3j.abi.datatypes.Function( + FUNC_SYMBOL, + Arrays.asList(), + Arrays.>asList(new TypeReference() {})); + return executeRemoteCallSingleValueReturn(function, String.class); + } + + public RemoteFunctionCall totalSupply() { + final org.web3j.abi.datatypes.Function function = + new org.web3j.abi.datatypes.Function( + FUNC_TOTALSUPPLY, + Arrays.asList(), + Arrays.>asList(new TypeReference() {})); + return executeRemoteCallSingleValueReturn(function, BigInteger.class); + } + + public RemoteFunctionCall transfer(String recipient, BigInteger amount) { + final org.web3j.abi.datatypes.Function function = + new org.web3j.abi.datatypes.Function( + FUNC_TRANSFER, + Arrays.asList( + new org.web3j.abi.datatypes.Address(160, recipient), + new org.web3j.abi.datatypes.generated.Uint256(amount)), + Collections.>emptyList()); + return executeRemoteCallTransaction(function); + } + + public RemoteFunctionCall transferFrom( + String sender, String recipient, BigInteger amount) { + final org.web3j.abi.datatypes.Function function = + new org.web3j.abi.datatypes.Function( + FUNC_TRANSFERFROM, + Arrays.asList( + new org.web3j.abi.datatypes.Address(160, sender), + new org.web3j.abi.datatypes.Address(160, recipient), + new org.web3j.abi.datatypes.generated.Uint256(amount)), + Collections.>emptyList()); + return executeRemoteCallTransaction(function); + } + + @Deprecated + public static ZkSyncERC20 load( + String contractAddress, + Web3j web3j, + Credentials credentials, + BigInteger gasPrice, + BigInteger gasLimit) { + return new ZkSyncERC20(contractAddress, web3j, credentials, gasPrice, gasLimit); + } + + @Deprecated + public static ZkSyncERC20 load( + String contractAddress, + Web3j web3j, + TransactionManager transactionManager, + BigInteger gasPrice, + BigInteger gasLimit) { + return new ZkSyncERC20(contractAddress, web3j, transactionManager, gasPrice, gasLimit); + } + + public static ZkSyncERC20 load( + String contractAddress, + Web3j web3j, + Credentials credentials, + ContractGasProvider contractGasProvider) { + return new ZkSyncERC20(contractAddress, web3j, credentials, contractGasProvider); + } + + public static ZkSyncERC20 load( + String contractAddress, + Web3j web3j, + TransactionManager transactionManager, + ContractGasProvider contractGasProvider) { + return new ZkSyncERC20(contractAddress, web3j, transactionManager, contractGasProvider); + } + + public static RemoteCall deploy( + Web3j web3j, + Credentials credentials, + ContractGasProvider contractGasProvider, + String name, + String symbol, + BigInteger decimals) { + String encodedConstructor = + FunctionEncoder.encodeConstructor( + Arrays.asList( + new org.web3j.abi.datatypes.Utf8String(name), + new org.web3j.abi.datatypes.Utf8String(symbol), new org.web3j.abi.datatypes.generated.Uint8(decimals))); - return deployRemoteCall(ZkSyncERC20.class, web3j, credentials, contractGasProvider, BINARY, encodedConstructor); - } - - public static RemoteCall deploy(Web3j web3j, TransactionManager transactionManager, ContractGasProvider contractGasProvider, String name, String symbol, BigInteger decimals) { - String encodedConstructor = FunctionEncoder.encodeConstructor(Arrays.asList(new org.web3j.abi.datatypes.Utf8String(name), - new org.web3j.abi.datatypes.Utf8String(symbol), + return deployRemoteCall( + ZkSyncERC20.class, web3j, credentials, contractGasProvider, BINARY, encodedConstructor); + } + + public static RemoteCall deploy( + Web3j web3j, + TransactionManager transactionManager, + ContractGasProvider contractGasProvider, + String name, + String symbol, + BigInteger decimals) { + String encodedConstructor = + FunctionEncoder.encodeConstructor( + Arrays.asList( + new org.web3j.abi.datatypes.Utf8String(name), + new org.web3j.abi.datatypes.Utf8String(symbol), new org.web3j.abi.datatypes.generated.Uint8(decimals))); - return deployRemoteCall(ZkSyncERC20.class, web3j, transactionManager, contractGasProvider, BINARY, encodedConstructor); - } - - @Deprecated - public static RemoteCall deploy(Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit, String name, String symbol, BigInteger decimals) { - String encodedConstructor = FunctionEncoder.encodeConstructor(Arrays.asList(new org.web3j.abi.datatypes.Utf8String(name), - new org.web3j.abi.datatypes.Utf8String(symbol), + return deployRemoteCall( + ZkSyncERC20.class, + web3j, + transactionManager, + contractGasProvider, + BINARY, + encodedConstructor); + } + + @Deprecated + public static RemoteCall deploy( + Web3j web3j, + Credentials credentials, + BigInteger gasPrice, + BigInteger gasLimit, + String name, + String symbol, + BigInteger decimals) { + String encodedConstructor = + FunctionEncoder.encodeConstructor( + Arrays.asList( + new org.web3j.abi.datatypes.Utf8String(name), + new org.web3j.abi.datatypes.Utf8String(symbol), new org.web3j.abi.datatypes.generated.Uint8(decimals))); - return deployRemoteCall(ZkSyncERC20.class, web3j, credentials, gasPrice, gasLimit, BINARY, encodedConstructor); - } - - @Deprecated - public static RemoteCall deploy(Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit, String name, String symbol, BigInteger decimals) { - String encodedConstructor = FunctionEncoder.encodeConstructor(Arrays.asList(new org.web3j.abi.datatypes.Utf8String(name), - new org.web3j.abi.datatypes.Utf8String(symbol), + return deployRemoteCall( + ZkSyncERC20.class, web3j, credentials, gasPrice, gasLimit, BINARY, encodedConstructor); + } + + @Deprecated + public static RemoteCall deploy( + Web3j web3j, + TransactionManager transactionManager, + BigInteger gasPrice, + BigInteger gasLimit, + String name, + String symbol, + BigInteger decimals) { + String encodedConstructor = + FunctionEncoder.encodeConstructor( + Arrays.asList( + new org.web3j.abi.datatypes.Utf8String(name), + new org.web3j.abi.datatypes.Utf8String(symbol), new org.web3j.abi.datatypes.generated.Uint8(decimals))); - return deployRemoteCall(ZkSyncERC20.class, web3j, transactionManager, gasPrice, gasLimit, BINARY, encodedConstructor); - } + return deployRemoteCall( + ZkSyncERC20.class, + web3j, + transactionManager, + gasPrice, + gasLimit, + BINARY, + encodedConstructor); + } - public static class ApprovalEventResponse extends BaseEventResponse { - public String owner; + public static class ApprovalEventResponse extends BaseEventResponse { + public String owner; - public String spender; + public String spender; - public BigInteger value; - } + public BigInteger value; + } - public static class TransferEventResponse extends BaseEventResponse { - public String from; + public static class TransferEventResponse extends BaseEventResponse { + public String from; - public String to; + public String to; - public BigInteger value; - } + public BigInteger value; + } } diff --git a/src/test/java/io/zksync/helper/eip712/Mail.java b/src/test/java/io/zksync/helper/eip712/Mail.java index d72da73..55626c7 100755 --- a/src/test/java/io/zksync/helper/eip712/Mail.java +++ b/src/test/java/io/zksync/helper/eip712/Mail.java @@ -1,43 +1,42 @@ package io.zksync.helper.eip712; +import io.zksync.crypto.eip712.Structurable; import java.util.ArrayList; import java.util.List; - -import org.web3j.abi.datatypes.*; import org.apache.commons.lang3.tuple.Pair; - -import io.zksync.crypto.eip712.Structurable; +import org.web3j.abi.datatypes.*; public class Mail implements Structurable { - public Person from; - public Person to; - public Utf8String contents; - - public Mail() { - this( - new Person("Cow", "0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826"), - new Person("Bob", "0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB"), - "Hello, Bob!" - ); - } - - public Mail(Person from, Person to, String contents) { - this.from = from; - this.to = to; - this.contents = new Utf8String(contents); - } - - @Override - public String getTypeName() { - return "Mail"; - } - - @Override - public List>> eip712types() { - return new ArrayList>>() {{ - add(Pair.of("from", from.intoEip712Struct())); - add(Pair.of("to", to.intoEip712Struct())); - add(Pair.of("contents", contents)); - }}; - } + public Person from; + public Person to; + public Utf8String contents; + + public Mail() { + this( + new Person("Cow", "0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826"), + new Person("Bob", "0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB"), + "Hello, Bob!"); + } + + public Mail(Person from, Person to, String contents) { + this.from = from; + this.to = to; + this.contents = new Utf8String(contents); + } + + @Override + public String getTypeName() { + return "Mail"; + } + + @Override + public List>> eip712types() { + return new ArrayList>>() { + { + add(Pair.of("from", from.intoEip712Struct())); + add(Pair.of("to", to.intoEip712Struct())); + add(Pair.of("contents", contents)); + } + }; + } } diff --git a/src/test/java/io/zksync/helper/eip712/Person.java b/src/test/java/io/zksync/helper/eip712/Person.java index f0e1522..7bc65a8 100755 --- a/src/test/java/io/zksync/helper/eip712/Person.java +++ b/src/test/java/io/zksync/helper/eip712/Person.java @@ -1,32 +1,32 @@ package io.zksync.helper.eip712; +import io.zksync.crypto.eip712.Structurable; import java.util.ArrayList; import java.util.List; - -import org.web3j.abi.datatypes.*; import org.apache.commons.lang3.tuple.Pair; - -import io.zksync.crypto.eip712.Structurable; +import org.web3j.abi.datatypes.*; public class Person implements Structurable { - public Utf8String name; - public Address wallet; + public Utf8String name; + public Address wallet; - public Person(String name, String wallet) { - this.name = new Utf8String(name); - this.wallet = new Address(wallet); - } + public Person(String name, String wallet) { + this.name = new Utf8String(name); + this.wallet = new Address(wallet); + } - @Override - public String getTypeName() { - return "Person"; - } + @Override + public String getTypeName() { + return "Person"; + } - @Override - public List>> eip712types() { - return new ArrayList>>() {{ - add(Pair.of("name", name)); - add(Pair.of("wallet", wallet)); - }}; - } + @Override + public List>> eip712types() { + return new ArrayList>>() { + { + add(Pair.of("name", name)); + add(Pair.of("wallet", wallet)); + } + }; + } } diff --git a/src/test/java/io/zksync/integration/BaseIntegrationEnv.java b/src/test/java/io/zksync/integration/BaseIntegrationEnv.java index 6f35ca3..7e1aba8 100644 --- a/src/test/java/io/zksync/integration/BaseIntegrationEnv.java +++ b/src/test/java/io/zksync/integration/BaseIntegrationEnv.java @@ -1,5 +1,7 @@ package io.zksync.integration; +import static org.junit.jupiter.api.Assertions.*; + import io.zksync.ZkSyncWallet; import io.zksync.abi.TransactionEncoder; import io.zksync.crypto.signer.EthSigner; @@ -15,6 +17,8 @@ import io.zksync.transaction.response.ZkSyncTransactionReceiptProcessor; import io.zksync.transaction.type.Transaction712; import io.zksync.utils.ContractDeployer; +import java.io.IOException; +import java.math.BigInteger; import org.web3j.crypto.Credentials; import org.web3j.crypto.ECKeyPair; import org.web3j.protocol.Web3j; @@ -33,134 +37,154 @@ import org.web3j.utils.Convert; import org.web3j.utils.Numeric; -import java.io.IOException; -import java.math.BigInteger; - -import static org.junit.jupiter.api.Assertions.*; - public class BaseIntegrationEnv { - public static final Token ETH = Token.ETH; - - private final String L1_NODE; - private final String L2_NODE; - - protected final Web3j l1Web3; - protected final ZkSync zksync; - protected final Credentials credentials; - protected final EthSigner signer; - - protected final ZkSyncTransactionReceiptProcessor processor; - - protected final ZkTransactionFeeProvider feeProvider; - - protected final BigInteger chainId; - - protected final ZkSyncWallet wallet; - - protected BaseIntegrationEnv() { - L1_NODE = System.getenv("ZKSYNC2_JAVA_CI_L1_NODE_URL"); - L2_NODE = System.getenv("ZKSYNC2_JAVA_CI_L2_NODE_URL"); - - final String privateKey = System.getenv("ZKSYNC2_JAVA_CI_PRIVATE_KEY"); - - this.l1Web3 = Web3j.build(new HttpService(L1_NODE)); - this.zksync = ZkSync.build(new HttpService(L2_NODE)); - this.credentials = privateKey != null ? Credentials.create(privateKey) : Credentials.create(ECKeyPair.create(BigInteger.ONE)); - - chainId = this.zksync.ethChainId().sendAsync().join().getChainId(); - - this.signer = new PrivateKeyEthSigner(credentials, chainId.longValue()); - - this.processor = new ZkSyncTransactionReceiptProcessor(this.zksync, 200, 100); - - this.feeProvider = new DefaultTransactionFeeProvider(zksync, ETH); - - this.wallet = new ZkSyncWallet(zksync, signer, ETH); + public static final Token ETH = Token.ETH; + + private final String L1_NODE; + private final String L2_NODE; + + protected final Web3j l1Web3; + protected final ZkSync zksync; + protected final Credentials credentials; + protected final EthSigner signer; + + protected final ZkSyncTransactionReceiptProcessor processor; + + protected final ZkTransactionFeeProvider feeProvider; + + protected final BigInteger chainId; + + protected final ZkSyncWallet wallet; + + protected BaseIntegrationEnv() { + L1_NODE = System.getenv("ZKSYNC2_JAVA_CI_L1_NODE_URL"); + L2_NODE = System.getenv("ZKSYNC2_JAVA_CI_L2_NODE_URL"); + + final String privateKey = System.getenv("ZKSYNC2_JAVA_CI_PRIVATE_KEY"); + + this.l1Web3 = Web3j.build(new HttpService(L1_NODE)); + this.zksync = ZkSync.build(new HttpService(L2_NODE)); + this.credentials = + privateKey != null + ? Credentials.create(privateKey) + : Credentials.create(ECKeyPair.create(BigInteger.ONE)); + + chainId = this.zksync.ethChainId().sendAsync().join().getChainId(); + + this.signer = new PrivateKeyEthSigner(credentials, chainId.longValue()); + + this.processor = new ZkSyncTransactionReceiptProcessor(this.zksync, 200, 100); + + this.feeProvider = new DefaultTransactionFeeProvider(zksync, ETH); + + this.wallet = new ZkSyncWallet(zksync, signer, ETH); + } + + protected void sendTestMoney() { + String account = l1Web3.ethAccounts().sendAsync().join().getAccounts().get(0); + + EthSendTransaction sent = + l1Web3 + .ethSendTransaction( + Transaction.createEtherTransaction( + account, + null, + Convert.toWei("1", Convert.Unit.GWEI).toBigInteger(), + BigInteger.valueOf(21_000L), + this.credentials.getAddress(), + Convert.toWei("100", Convert.Unit.ETHER).toBigInteger())) + .sendAsync() + .join(); + + assertResponse(sent); + } + + protected void deposit() throws IOException { + BigInteger chainId = l1Web3.ethChainId().send().getChainId(); + TransactionManager manager = + new RawTransactionManager(l1Web3, credentials, chainId.longValue()); + ContractGasProvider gasProvider = + new StaticGasProvider( + Convert.toWei("1", Convert.Unit.GWEI).toBigInteger(), BigInteger.valueOf(555_000L)); + TransactionReceipt receipt = + EthereumProvider.load(zksync, l1Web3, manager, gasProvider) + .join() + .deposit( + ETH, + Convert.toWei("100", Convert.Unit.ETHER).toBigInteger(), + BigInteger.ZERO, + credentials.getAddress()) + .join(); + + System.out.println(receipt); + } + + protected void assertResponse(Response response) { + if (response.hasError()) { + System.out.println(response.getError().getMessage()); + System.out.println(response.getError().getData()); + } else { + System.out.println(response.getResult()); } - protected void sendTestMoney() { - String account = l1Web3.ethAccounts().sendAsync().join().getAccounts().get(0); + assertFalse(response::hasError); + } - EthSendTransaction sent = l1Web3.ethSendTransaction( - Transaction.createEtherTransaction(account, null, Convert.toWei("1", Convert.Unit.GWEI).toBigInteger(), BigInteger.valueOf(21_000L), - this.credentials.getAddress(), Convert.toWei("100", Convert.Unit.ETHER).toBigInteger())) - .sendAsync().join(); + protected void assertContractDeployResponse(TransactionReceipt response) { + assertNotNull(response.getContractAddress()); + } - assertResponse(sent); - } + protected void assertContractDeployResponse(TransactionReceipt response, String expected) { + assertContractDeployResponse(response); + String correctContractAddress = ContractDeployer.extractContractAddress(response).getValue(); + assertEquals(correctContractAddress, expected); + } - protected void deposit() throws IOException { - BigInteger chainId = l1Web3.ethChainId().send().getChainId(); - TransactionManager manager = new RawTransactionManager(l1Web3, credentials, chainId.longValue()); - ContractGasProvider gasProvider = new StaticGasProvider(Convert.toWei("1", Convert.Unit.GWEI).toBigInteger(), BigInteger.valueOf(555_000L)); - TransactionReceipt receipt = EthereumProvider - .load(zksync, l1Web3, manager, gasProvider).join() - .deposit(ETH, Convert.toWei("100", Convert.Unit.ETHER).toBigInteger(), BigInteger.ZERO, credentials.getAddress()).join(); + protected TransactionReceipt submitTransaction(io.zksync.methods.request.Transaction estimate) + throws IOException, TransactionException { + BigInteger nonce = + zksync + .ethGetTransactionCount(credentials.getAddress(), DefaultBlockParameterName.PENDING) + .send() + .getTransactionCount(); + ZksEstimateFee estimateFee = zksync.zksEstimateFee(estimate).send(); - System.out.println(receipt); - } + EthGasPrice gasPrice = zksync.ethGasPrice().send(); - protected void assertResponse(Response response) { - if (response.hasError()) { - System.out.println(response.getError().getMessage()); - System.out.println(response.getError().getData()); - } else { - System.out.println(response.getResult()); - } + assertResponse(estimateFee); + assertResponse(gasPrice); - assertFalse(response::hasError); - } + Fee fee = estimateFee.getResult(); - protected void assertContractDeployResponse(TransactionReceipt response) { - assertNotNull(response.getContractAddress()); - } + Eip712Meta meta = estimate.getEip712Meta(); + meta.setGasPerPubdata(fee.getGasPerPubdataLimitNumber()); - protected void assertContractDeployResponse(TransactionReceipt response, String expected) { - assertContractDeployResponse(response); - String correctContractAddress = ContractDeployer.extractContractAddress(response).getValue(); - assertEquals(correctContractAddress, expected); - } - - protected TransactionReceipt submitTransaction(io.zksync.methods.request.Transaction estimate) throws IOException, TransactionException { - BigInteger nonce = zksync - .ethGetTransactionCount(credentials.getAddress(), DefaultBlockParameterName.PENDING).send() - .getTransactionCount(); - ZksEstimateFee estimateFee = zksync.zksEstimateFee(estimate).send(); - - EthGasPrice gasPrice = zksync.ethGasPrice().send(); - - assertResponse(estimateFee); - assertResponse(gasPrice); + Transaction712 transaction = + new Transaction712( + chainId.longValue(), + nonce, + fee.getGasLimitNumber(), + estimate.getTo(), + estimate.getValueNumber(), + estimate.getData(), + fee.getMaxPriorityFeePerErgNumber(), + fee.getGasPriceLimitNumber(), + credentials.getAddress(), + meta); - Fee fee = estimateFee.getResult(); + String signature = + signer.getDomain().thenCompose(domain -> signer.signTypedData(domain, transaction)).join(); + byte[] message = + TransactionEncoder.encode(transaction, TransactionEncoder.getSignatureData(signature)); - Eip712Meta meta = estimate.getEip712Meta(); - meta.setGasPerPubdata(fee.getGasPerPubdataLimitNumber()); + EthSendTransaction sent = zksync.ethSendRawTransaction(Numeric.toHexString(message)).send(); - Transaction712 transaction = new Transaction712( - chainId.longValue(), - nonce, - fee.getGasLimitNumber(), - estimate.getTo(), - estimate.getValueNumber(), - estimate.getData(), - fee.getMaxPriorityFeePerErgNumber(), - fee.getGasPriceLimitNumber(), - credentials.getAddress(), - meta - ); + assertResponse(sent); - String signature = signer.getDomain().thenCompose(domain -> signer.signTypedData(domain, transaction)).join(); - byte[] message = TransactionEncoder.encode(transaction, TransactionEncoder.getSignatureData(signature)); + TransactionReceipt receipt = processor.waitForTransactionReceipt(sent.getResult()); - EthSendTransaction sent = zksync.ethSendRawTransaction(Numeric.toHexString(message)).send(); + assertTrue(receipt::isStatusOK); - assertResponse(sent); - - TransactionReceipt receipt = processor.waitForTransactionReceipt(sent.getResult()); - - assertTrue(receipt::isStatusOK); - - return receipt; - } + return receipt; + } } diff --git a/src/test/java/io/zksync/integration/IntegrationZkSyncWalletTest.java b/src/test/java/io/zksync/integration/IntegrationZkSyncWalletTest.java index c5cf299..d2d9732 100644 --- a/src/test/java/io/zksync/integration/IntegrationZkSyncWalletTest.java +++ b/src/test/java/io/zksync/integration/IntegrationZkSyncWalletTest.java @@ -1,5 +1,7 @@ package io.zksync.integration; +import static org.junit.jupiter.api.Assertions.*; + import io.zksync.ZkSyncWallet; import io.zksync.crypto.signer.EthSigner; import io.zksync.crypto.signer.PrivateKeyEthSigner; @@ -13,6 +15,10 @@ import io.zksync.protocol.provider.EthereumProvider; import io.zksync.transaction.manager.ZkSyncTransactionManager; import io.zksync.utils.Messenger; +import java.io.IOException; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.util.concurrent.TimeUnit; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Disabled; @@ -39,203 +45,263 @@ import org.web3j.utils.Convert; import org.web3j.utils.Numeric; -import java.io.IOException; -import java.math.BigInteger; -import java.nio.charset.StandardCharsets; -import java.util.concurrent.TimeUnit; - -import static org.junit.jupiter.api.Assertions.*; - @Disabled public class IntegrationZkSyncWalletTest { - private static final String L1_NODE = "http://127.0.0.1:8545"; - private static final String L2_NODE = "http://127.0.0.1:3050"; - - private static ZkSyncWallet wallet; - private static Credentials credentials; - - @BeforeAll - public static void setUp() { - ZkSync zksync = ZkSync.build(new HttpService(L2_NODE)); - credentials = Credentials.create(ECKeyPair.create(BigInteger.ONE)); - - BigInteger chainId = zksync.ethChainId().sendAsync().join().getChainId(); - - EthSigner signer = new PrivateKeyEthSigner(credentials, chainId.longValue()); - - wallet = new ZkSyncWallet(zksync, signer, Token.ETH); - } - - @Test - public void sendTestMoney() { - Web3j web3j = Web3j.build(new HttpService(L1_NODE)); - - String account = web3j.ethAccounts().sendAsync().join().getAccounts().get(0); - - EthSendTransaction sent = web3j.ethSendTransaction( - Transaction.createEtherTransaction(account, null, BigInteger.ZERO, BigInteger.valueOf(21_000L), - credentials.getAddress(), Convert.toWei("1000", Convert.Unit.ETHER).toBigInteger())) - .sendAsync().join(); - - assertResponse(sent); - } - - @Test - public void testDeposit() throws IOException { - Web3j web3j = Web3j.build(new HttpService(L1_NODE)); - BigInteger chainId = web3j.ethChainId().send().getChainId(); - TransactionManager manager = new RawTransactionManager(web3j, credentials, chainId.longValue()); - - ContractGasProvider gasProvider = new DefaultGasProvider(); - TransactionReceipt receipt = EthereumProvider - .load(wallet.getZksync(), web3j, manager, gasProvider).join() - .deposit(Token.ETH, Convert.toWei("1", Convert.Unit.GWEI).toBigInteger(), BigInteger.ZERO, credentials.getAddress()).join(); - - System.out.println(receipt); - } - - @Test - public void testTransfer() throws Exception { - BigInteger amount = Token.ETH.toBigInteger(0.5); - BigInteger desiredFee = BigInteger.valueOf(10560L).multiply(BigInteger.valueOf(28572L)); // Only for test - EthGetBalance balance = wallet.getZksync() - .ethGetBalance(credentials.getAddress(), ZkBlockParameterName.COMMITTED) - .send(); - - assertResponse(balance); - - TransactionReceipt receipt = wallet.transfer(credentials.getAddress(), amount).send(); - - assertTrue(receipt.isStatusOK()); - - EthGetBalance balanceNew = wallet.getZksync() - .ethGetBalance(credentials.getAddress(), ZkBlockParameterName.COMMITTED) - .send(); - - assertResponse(balanceNew); + private static final String L1_NODE = "http://127.0.0.1:8545"; + private static final String L2_NODE = "http://127.0.0.1:3050"; + + private static ZkSyncWallet wallet; + private static Credentials credentials; + + @BeforeAll + public static void setUp() { + ZkSync zksync = ZkSync.build(new HttpService(L2_NODE)); + credentials = Credentials.create(ECKeyPair.create(BigInteger.ONE)); + + BigInteger chainId = zksync.ethChainId().sendAsync().join().getChainId(); + + EthSigner signer = new PrivateKeyEthSigner(credentials, chainId.longValue()); + + wallet = new ZkSyncWallet(zksync, signer, Token.ETH); + } + + @Test + public void sendTestMoney() { + Web3j web3j = Web3j.build(new HttpService(L1_NODE)); + + String account = web3j.ethAccounts().sendAsync().join().getAccounts().get(0); + + EthSendTransaction sent = + web3j + .ethSendTransaction( + Transaction.createEtherTransaction( + account, + null, + BigInteger.ZERO, + BigInteger.valueOf(21_000L), + credentials.getAddress(), + Convert.toWei("1000", Convert.Unit.ETHER).toBigInteger())) + .sendAsync() + .join(); - assertEquals(balance.getBalance().subtract(amount).subtract(desiredFee), balanceNew.getBalance()); - } - - @Test - public void testWithdraw() throws Exception { - BigInteger amount = Token.ETH.toBigInteger(0.5); - BigInteger desiredFee = BigInteger.valueOf(10560L).multiply(BigInteger.valueOf(28572L)); // Only for test - EthGetBalance balance = wallet.getZksync() - .ethGetBalance(credentials.getAddress(), ZkBlockParameterName.COMMITTED) - .send(); - - assertResponse(balance); - - TransactionReceipt receipt = wallet.withdraw(credentials.getAddress(), amount).send(); - - assertTrue(receipt.isStatusOK()); - - EthGetBalance balanceNew = wallet.getZksync() - .ethGetBalance(credentials.getAddress(), ZkBlockParameterName.COMMITTED) - .send(); - - assertResponse(balanceNew); - - assertEquals(balanceNew.getBalance(), balance.getBalance().subtract(amount).subtract(desiredFee)); - } - - @Test - public void testDeploy() throws Exception { - - BigInteger nonce = wallet.getNonce().send(); - String contractAddress = ContractUtils.generateContractAddress(credentials.getAddress(), nonce); - - EthGetCode code = wallet.getZksync().ethGetCode(contractAddress, DefaultBlockParameterName.PENDING).send(); - - assertResponse(code); - assertEquals("0x", code.getCode()); - - TransactionReceipt receipt = wallet.deploy(Numeric.hexStringToByteArray(CounterContract.BINARY)).send(); - - assertTrue(receipt.isStatusOK()); - - EthGetCode codeDeployed = wallet.getZksync().ethGetCode(contractAddress, DefaultBlockParameterName.PENDING).send(); - - assertResponse(codeDeployed); - assertNotEquals("0x", codeDeployed.getCode()); - } - - @Test - public void testDeployWithConstructor() throws Exception { - - BigInteger nonce = wallet.getNonce().send(); - String contractAddress = ContractUtils.generateContractAddress(credentials.getAddress(), nonce); + assertResponse(sent); + } - EthGetCode code = wallet.getZksync().ethGetCode(contractAddress, DefaultBlockParameterName.PENDING).send(); + @Test + public void testDeposit() throws IOException { + Web3j web3j = Web3j.build(new HttpService(L1_NODE)); + BigInteger chainId = web3j.ethChainId().send().getChainId(); + TransactionManager manager = new RawTransactionManager(web3j, credentials, chainId.longValue()); - assertResponse(code); - assertEquals("0x", code.getCode()); + ContractGasProvider gasProvider = new DefaultGasProvider(); + TransactionReceipt receipt = + EthereumProvider.load(wallet.getZksync(), web3j, manager, gasProvider) + .join() + .deposit( + Token.ETH, + Convert.toWei("1", Convert.Unit.GWEI).toBigInteger(), + BigInteger.ZERO, + credentials.getAddress()) + .join(); - String constructor = ConstructorContract.encodeConstructor(BigInteger.valueOf(42), BigInteger.valueOf(43), false); - TransactionReceipt receipt = wallet.deploy(Numeric.hexStringToByteArray(ConstructorContract.BINARY), Numeric.hexStringToByteArray(constructor)).send(); + System.out.println(receipt); + } - assertTrue(receipt.isStatusOK()); + @Test + public void testTransfer() throws Exception { + BigInteger amount = Token.ETH.toBigInteger(0.5); + BigInteger desiredFee = + BigInteger.valueOf(10560L).multiply(BigInteger.valueOf(28572L)); // Only for test + EthGetBalance balance = + wallet + .getZksync() + .ethGetBalance(credentials.getAddress(), ZkBlockParameterName.COMMITTED) + .send(); - EthGetCode codeDeployed = wallet.getZksync().ethGetCode(contractAddress, DefaultBlockParameterName.PENDING).send(); + assertResponse(balance); - assertResponse(codeDeployed); - assertNotEquals("0x", codeDeployed.getCode()); + TransactionReceipt receipt = wallet.transfer(credentials.getAddress(), amount).send(); - ConstructorContract contract = ConstructorContract.load(contractAddress, wallet.getZksync(), new ReadonlyTransactionManager(wallet.getZksync(), wallet.getSigner().getAddress()), new DefaultGasProvider()); - - BigInteger after = contract.get().send(); - assertEquals(BigInteger.valueOf(42).multiply(BigInteger.valueOf(43)), after); - } + assertTrue(receipt.isStatusOK()); - @Test - public void testExecute() throws Exception { - TransactionReceipt deployed = wallet.deploy(Numeric.hexStringToByteArray(CounterContract.BINARY)).send(); + EthGetBalance balanceNew = + wallet + .getZksync() + .ethGetBalance(credentials.getAddress(), ZkBlockParameterName.COMMITTED) + .send(); - assertTrue(deployed.isStatusOK()); - String contractAddress = deployed.getContractAddress(); + assertResponse(balanceNew); - TransactionManager transactionManager = new ZkSyncTransactionManager(wallet.getZksync(), wallet.getSigner(), wallet.getFeeProvider()); - CounterContract contract = CounterContract.load(contractAddress, wallet.getZksync(), transactionManager, new DefaultGasProvider()); - - BigInteger before = contract.get().send(); - assertEquals(BigInteger.ZERO, before); - - TransactionReceipt receipt = wallet.execute(contractAddress, CounterContract.encodeIncrement(BigInteger.TEN)).send(); - assertTrue(receipt.isStatusOK()); - - BigInteger after = contract.get().send(); - assertEquals(BigInteger.TEN, after); - } - - @Test - public void testSendMessageL2ToL1() throws Exception { - String someMessage = "Some message from ZkSync2j client"; - byte[] messageBytes = someMessage.getBytes(StandardCharsets.UTF_8); - - TransactionReceipt receipt = wallet.sendMessageToL1(messageBytes).send(); - - TimeUnit.SECONDS.sleep(5); - - ZkTransactionReceipt zkReceipt = wallet.getZksync().zksGetTransactionReceipt(receipt.getTransactionHash()).send().getTransactionReceipt().get(); - - L2ToL1MessageProof proof = wallet.getZksync().zksGetL2ToL1MsgProof(zkReceipt.getBlockNumber().intValue(), wallet.getSigner().getAddress(), Numeric.toHexString(Hash.sha3(messageBytes)), null).send().getResult(); - - byte[] messageHash = Messenger.getHashedMessage(new Address(wallet.getSigner().getAddress()), messageBytes, zkReceipt.getL1BatchTxIndex()); - - Assertions.assertTrue(Messenger.verifyMessage(proof, messageHash)); - } + assertEquals( + balance.getBalance().subtract(amount).subtract(desiredFee), balanceNew.getBalance()); + } - private void assertResponse(Response response) { - if (response.hasError()) { - System.out.println(response.getError().getMessage()); - System.out.println(response.getError().getData()); - } else { - System.out.println(response.getResult()); - } + @Test + public void testWithdraw() throws Exception { + BigInteger amount = Token.ETH.toBigInteger(0.5); + BigInteger desiredFee = + BigInteger.valueOf(10560L).multiply(BigInteger.valueOf(28572L)); // Only for test + EthGetBalance balance = + wallet + .getZksync() + .ethGetBalance(credentials.getAddress(), ZkBlockParameterName.COMMITTED) + .send(); + + assertResponse(balance); + + TransactionReceipt receipt = wallet.withdraw(credentials.getAddress(), amount).send(); + + assertTrue(receipt.isStatusOK()); + + EthGetBalance balanceNew = + wallet + .getZksync() + .ethGetBalance(credentials.getAddress(), ZkBlockParameterName.COMMITTED) + .send(); + + assertResponse(balanceNew); + + assertEquals( + balanceNew.getBalance(), balance.getBalance().subtract(amount).subtract(desiredFee)); + } + + @Test + public void testDeploy() throws Exception { + + BigInteger nonce = wallet.getNonce().send(); + String contractAddress = ContractUtils.generateContractAddress(credentials.getAddress(), nonce); + + EthGetCode code = + wallet.getZksync().ethGetCode(contractAddress, DefaultBlockParameterName.PENDING).send(); + + assertResponse(code); + assertEquals("0x", code.getCode()); + + TransactionReceipt receipt = + wallet.deploy(Numeric.hexStringToByteArray(CounterContract.BINARY)).send(); + + assertTrue(receipt.isStatusOK()); + + EthGetCode codeDeployed = + wallet.getZksync().ethGetCode(contractAddress, DefaultBlockParameterName.PENDING).send(); + + assertResponse(codeDeployed); + assertNotEquals("0x", codeDeployed.getCode()); + } + + @Test + public void testDeployWithConstructor() throws Exception { + + BigInteger nonce = wallet.getNonce().send(); + String contractAddress = ContractUtils.generateContractAddress(credentials.getAddress(), nonce); + + EthGetCode code = + wallet.getZksync().ethGetCode(contractAddress, DefaultBlockParameterName.PENDING).send(); + + assertResponse(code); + assertEquals("0x", code.getCode()); + + String constructor = + ConstructorContract.encodeConstructor( + BigInteger.valueOf(42), BigInteger.valueOf(43), false); + TransactionReceipt receipt = + wallet + .deploy( + Numeric.hexStringToByteArray(ConstructorContract.BINARY), + Numeric.hexStringToByteArray(constructor)) + .send(); + + assertTrue(receipt.isStatusOK()); + + EthGetCode codeDeployed = + wallet.getZksync().ethGetCode(contractAddress, DefaultBlockParameterName.PENDING).send(); + + assertResponse(codeDeployed); + assertNotEquals("0x", codeDeployed.getCode()); + + ConstructorContract contract = + ConstructorContract.load( + contractAddress, + wallet.getZksync(), + new ReadonlyTransactionManager(wallet.getZksync(), wallet.getSigner().getAddress()), + new DefaultGasProvider()); + + BigInteger after = contract.get().send(); + assertEquals(BigInteger.valueOf(42).multiply(BigInteger.valueOf(43)), after); + } + + @Test + public void testExecute() throws Exception { + TransactionReceipt deployed = + wallet.deploy(Numeric.hexStringToByteArray(CounterContract.BINARY)).send(); + + assertTrue(deployed.isStatusOK()); + String contractAddress = deployed.getContractAddress(); + + TransactionManager transactionManager = + new ZkSyncTransactionManager( + wallet.getZksync(), wallet.getSigner(), wallet.getFeeProvider()); + CounterContract contract = + CounterContract.load( + contractAddress, wallet.getZksync(), transactionManager, new DefaultGasProvider()); - assertFalse(response::hasError); + BigInteger before = contract.get().send(); + assertEquals(BigInteger.ZERO, before); + + TransactionReceipt receipt = + wallet.execute(contractAddress, CounterContract.encodeIncrement(BigInteger.TEN)).send(); + assertTrue(receipt.isStatusOK()); + + BigInteger after = contract.get().send(); + assertEquals(BigInteger.TEN, after); + } + + @Test + public void testSendMessageL2ToL1() throws Exception { + String someMessage = "Some message from ZkSync2j client"; + byte[] messageBytes = someMessage.getBytes(StandardCharsets.UTF_8); + + TransactionReceipt receipt = wallet.sendMessageToL1(messageBytes).send(); + + TimeUnit.SECONDS.sleep(5); + + ZkTransactionReceipt zkReceipt = + wallet + .getZksync() + .zksGetTransactionReceipt(receipt.getTransactionHash()) + .send() + .getTransactionReceipt() + .get(); + + L2ToL1MessageProof proof = + wallet + .getZksync() + .zksGetL2ToL1MsgProof( + zkReceipt.getBlockNumber().intValue(), + wallet.getSigner().getAddress(), + Numeric.toHexString(Hash.sha3(messageBytes)), + null) + .send() + .getResult(); + + byte[] messageHash = + Messenger.getHashedMessage( + new Address(wallet.getSigner().getAddress()), + messageBytes, + zkReceipt.getL1BatchTxIndex()); + + Assertions.assertTrue(Messenger.verifyMessage(proof, messageHash)); + } + + private void assertResponse(Response response) { + if (response.hasError()) { + System.out.println(response.getError().getMessage()); + System.out.println(response.getError().getData()); + } else { + System.out.println(response.getResult()); } + assertFalse(response::hasError); + } } diff --git a/src/test/java/io/zksync/integration/IntegrationZkSyncWeb3RpcTest.java b/src/test/java/io/zksync/integration/IntegrationZkSyncWeb3RpcTest.java index 536c739..8752bae 100755 --- a/src/test/java/io/zksync/integration/IntegrationZkSyncWeb3RpcTest.java +++ b/src/test/java/io/zksync/integration/IntegrationZkSyncWeb3RpcTest.java @@ -1,5 +1,8 @@ package io.zksync.integration; +import static io.zksync.utils.ZkSyncAddresses.L2_ETH_TOKEN_ADDRESS; +import static org.junit.jupiter.api.Assertions.*; + import io.zksync.abi.TransactionEncoder; import io.zksync.helper.ConstructorContract; import io.zksync.helper.CounterContract; @@ -17,6 +20,11 @@ import io.zksync.wrappers.ERC20; import io.zksync.wrappers.IL2Bridge; import io.zksync.wrappers.NonceHolder; +import java.io.IOException; +import java.math.BigDecimal; +import java.math.BigInteger; +import java.security.SecureRandom; +import java.util.*; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable; @@ -40,1053 +48,1181 @@ import org.web3j.utils.Convert.Unit; import org.web3j.utils.Numeric; -import java.io.IOException; -import java.math.BigDecimal; -import java.math.BigInteger; -import java.security.SecureRandom; -import java.util.*; - -import static io.zksync.utils.ZkSyncAddresses.L2_ETH_TOKEN_ADDRESS; -import static org.junit.jupiter.api.Assertions.*; - @EnabledIfEnvironmentVariables({ - @EnabledIfEnvironmentVariable(named = "ZKSYNC2_JAVA_CI_L1_NODE_URL", matches = "^https://*"), - @EnabledIfEnvironmentVariable(named = "ZKSYNC2_JAVA_CI_L2_NODE_URL", matches = "^https://*"), + @EnabledIfEnvironmentVariable(named = "ZKSYNC2_JAVA_CI_L1_NODE_URL", matches = "^https://*"), + @EnabledIfEnvironmentVariable(named = "ZKSYNC2_JAVA_CI_L2_NODE_URL", matches = "^https://*"), }) public class IntegrationZkSyncWeb3RpcTest extends BaseIntegrationEnv { - @Test - public void printChainId() { - System.out.println(chainId); - System.out.println(credentials.getAddress()); - } - - @Test - @Disabled - @Deprecated - public void sendTestMoney() { - String account = l1Web3.ethAccounts().sendAsync().join().getAccounts().get(0); - - EthSendTransaction sent = l1Web3.ethSendTransaction( - Transaction.createEtherTransaction(account, null, Convert.toWei("1", Unit.GWEI).toBigInteger(), BigInteger.valueOf(21_000L), - credentials.getAddress(), Convert.toWei("1000000", Unit.ETHER).toBigInteger())) - .sendAsync().join(); - - assertResponse(sent); - } - - @Test - @Disabled - public void testGetBalanceOfNativeL1() throws IOException { - EthGetBalance getBalance = l1Web3 - .ethGetBalance(credentials.getAddress(), DefaultBlockParameterName.LATEST) - .send(); - - assertResponse(getBalance); - System.out.printf("%s: %d\n", credentials.getAddress(), Numeric.toBigInt(getBalance.getResult())); - assertTrue(getBalance.getBalance().compareTo(Convert.toWei("0.2", Unit.ETHER).toBigInteger()) >= 0); - } - - @Test - @Disabled - public void testDeposit() throws IOException { - BigInteger chainId = l1Web3.ethChainId().send().getChainId(); - TransactionManager manager = new RawTransactionManager(l1Web3, credentials, chainId.longValue()); - BigInteger gasPrice = l1Web3.ethGasPrice().send().getGasPrice(); - ContractGasProvider gasProvider = new StaticGasProvider(gasPrice, BigInteger.valueOf(170_000L)); - TransactionReceipt receipt = EthereumProvider - .load(zksync, l1Web3, manager, gasProvider).join() - .deposit(ETH, Convert.toWei("0.001", Unit.ETHER).toBigInteger(), BigInteger.ZERO, credentials.getAddress()).join(); - - System.out.println(receipt); - } - - @Test - @Disabled - public void testDepositToken() throws IOException { - Token token = zksync.zksGetConfirmedTokens(0, (short) 100).send() - .getResult().stream() - .filter(t -> t.getSymbol().equalsIgnoreCase("USDC")) - .findFirst().orElseThrow(IllegalArgumentException::new); - BigInteger chainId = l1Web3.ethChainId().send().getChainId(); - BigInteger gasPrice = l1Web3.ethGasPrice().send().getGasPrice(); - TransactionManager manager = new RawTransactionManager(l1Web3, credentials, chainId.longValue()); - ContractGasProvider gasProvider = new StaticGasProvider(gasPrice, BigInteger.valueOf(200_000L)); - EthereumProvider provider = EthereumProvider.load(zksync, l1Web3, manager, gasProvider).join(); - TransactionReceipt approveReceipt = provider.approveDeposits(token, Optional.of(token.toBigInteger(10000000000L))).join(); - System.out.println(approveReceipt); - - TransactionReceipt receipt = provider.deposit(token, token.toBigInteger(10000000000L), BigInteger.ZERO, credentials.getAddress()).join(); - - System.out.println(receipt); - } - - @Test - public void testGetBalanceOfNative() throws IOException { - EthGetBalance getBalance = zksync - .ethGetBalance(credentials.getAddress(), DefaultBlockParameterName.LATEST) - .send(); - - System.out.printf("%s: %d\n", credentials.getAddress(), Numeric.toBigInt(getBalance.getResult())); - } - - @Test - public void testGetNonce() throws IOException { - EthGetTransactionCount getTransactionCount = zksync - .ethGetTransactionCount(credentials.getAddress(), DefaultBlockParameterName.LATEST) - .send(); - - System.out.printf("%s: %d\n", credentials.getAddress(), Numeric.toBigInt(getTransactionCount.getResult())); - } - - @Test - public void testGetDeploymentNonce() throws Exception { - NonceHolder nonceHolder = NonceHolder.load(ZkSyncAddresses.NONCE_HOLDER_ADDRESS, zksync, new ReadonlyTransactionManager(zksync, credentials.getAddress()), new DefaultGasProvider()); - - BigInteger nonce = nonceHolder.getDeploymentNonce(credentials.getAddress()).send(); - - System.out.printf("%s: %d\n", credentials.getAddress(), nonce); - } - - @Test - public void testGetTransactionReceipt() throws IOException { - TransactionReceipt receipt = zksync - .ethGetTransactionReceipt("0xea87f073bbb8826edf51abbbc77b5812848c92bfb8a825f82a74586ad3553309").send() - .getResult(); - - System.out.println(receipt); - } - - @Test - public void testGetTransaction() throws IOException { - org.web3j.protocol.core.methods.response.Transaction receipt = zksync - .ethGetTransactionByHash("0x60c05fffdfca5ffb5884f8dd0a80268f16ef768c71f6e173ed1fb58a50790e29").send() - .getResult(); - - System.out.println(receipt); - } - - @Test - public void testTransferNativeToSelf() throws IOException, TransactionException { - final BigInteger value = Convert.toWei(BigDecimal.valueOf(0.01), Unit.ETHER).toBigInteger(); - - BigInteger nonce = zksync - .ethGetTransactionCount(credentials.getAddress(), ZkBlockParameterName.COMMITTED).send() - .getTransactionCount(); - - io.zksync.methods.request.Transaction estimate = io.zksync.methods.request.Transaction.createEtherTransaction( - credentials.getAddress(), - BigInteger.ZERO, - BigInteger.ZERO, - credentials.getAddress(), - value - ); - - ZksEstimateFee estimateFee = zksync.zksEstimateFee(estimate).send(); - - EthGasPrice gasPrice = zksync.ethGasPrice().send(); - - assertResponse(gasPrice); - assertResponse(estimateFee); - - Fee fee = estimateFee.getResult(); - - Eip712Meta meta = estimate.getEip712Meta(); - meta.setGasPerPubdata(fee.getGasPerPubdataLimitNumber()); - - Transaction712 transaction = new Transaction712( - chainId.longValue(), - nonce, - fee.getGasLimitNumber(), - estimate.getTo(), - value, - estimate.getData(), - fee.getMaxPriorityFeePerErgNumber(), - fee.getGasPriceLimitNumber(), - credentials.getAddress(), - meta - ); - - 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(); - - assertResponse(sent); - - TransactionReceipt receipt = processor.waitForTransactionReceipt(sent.getResult()); - - assertTrue(receipt::isStatusOK); - } - - @Test - public void testTransferTokenToSelf() throws IOException, TransactionException { - BigInteger nonce = zksync - .ethGetTransactionCount(credentials.getAddress(), ZkBlockParameterName.COMMITTED).send() - .getTransactionCount(); - - Token token = zksync.zksGetConfirmedTokens(0, (short) 100).send() - .getResult().stream() - .filter(t -> t.getSymbol().equalsIgnoreCase("USDC")) - .findFirst().orElseThrow(IllegalArgumentException::new); - String tokenAddress = token.getL2Address(); - Function transfer = ERC20.encodeTransfer(credentials.getAddress(), token.toBigInteger(10)); - String calldata = FunctionEncoder.encode(transfer); - - io.zksync.methods.request.Transaction estimate = io.zksync.methods.request.Transaction.createFunctionCallTransaction( - credentials.getAddress(), - tokenAddress, - BigInteger.ZERO, - BigInteger.ZERO, - calldata - ); - - ZksEstimateFee estimateFee = zksync.zksEstimateFee(estimate).send(); - - EthGasPrice gasPrice = zksync.ethGasPrice().send(); - - assertResponse(gasPrice); - assertResponse(estimateFee); - - Fee fee = estimateFee.getResult(); - - Eip712Meta meta = estimate.getEip712Meta(); - meta.setGasPerPubdata(fee.getGasPerPubdataLimitNumber()); - - Transaction712 transaction = new Transaction712( - chainId.longValue(), - nonce, - fee.getGasLimitNumber(), - estimate.getTo(), - estimate.getValueNumber(), - estimate.getData(), - fee.getMaxPriorityFeePerErgNumber(), - fee.getGasPriceLimitNumber(), - credentials.getAddress(), - meta - ); - - 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(); - - assertResponse(sent); - - TransactionReceipt receipt = processor.waitForTransactionReceipt(sent.getResult()); - - assertTrue(receipt::isStatusOK); - } - - @Test - public void testTransferTokenToSelfWeb3jContract() throws Exception { - Token token = zksync.zksGetConfirmedTokens(0, (short) 100).send() - .getResult().stream() - .filter(t -> t.getSymbol().equalsIgnoreCase("USDC")) - .findFirst().orElseThrow(IllegalArgumentException::new); - - ERC20 erc20 = ERC20.load(token.getL2Address(), zksync, - new ZkSyncTransactionManager(zksync, signer, feeProvider), - feeProvider); - - TransactionReceipt receipt = erc20.transfer(credentials.getAddress(), token.toBigInteger(10)).send(); - - assertTrue(receipt::isStatusOK); - } - - @Test - public void testWithdraw() throws IOException, TransactionException { - final Token token = ETH; - final double amount = 0.01; - - BigInteger nonce = zksync - .ethGetTransactionCount(credentials.getAddress(), ZkBlockParameterName.COMMITTED).send() - .getTransactionCount(); - - String l2EthBridge = L2_ETH_TOKEN_ADDRESS; - - final Function withdraw = new Function( - IL2Bridge.FUNC_WITHDRAW, - Arrays.asList(new Address(credentials.getAddress()), - new Address(token.getL2Address()), - new Uint256(token.toBigInteger(amount))), - Collections.emptyList()); - - String calldata = FunctionEncoder.encode(withdraw); - - io.zksync.methods.request.Transaction estimate = io.zksync.methods.request.Transaction.createFunctionCallTransaction( - credentials.getAddress(), - l2EthBridge, - BigInteger.ZERO, - BigInteger.ZERO, - calldata - ); - - ZksEstimateFee estimateFee = zksync.zksEstimateFee(estimate).send(); - - EthGasPrice gasPrice = zksync.ethGasPrice().send(); - - assertResponse(estimateFee); - assertResponse(gasPrice); - - Fee fee = estimateFee.getResult(); - - Eip712Meta meta = estimate.getEip712Meta(); - meta.setGasPerPubdata(fee.getGasPerPubdataLimitNumber()); - - Transaction712 transaction = new Transaction712( - chainId.longValue(), - nonce, - fee.getGasLimitNumber(), - estimate.getTo(), - estimate.getValueNumber(), - estimate.getData(), - fee.getMaxPriorityFeePerErgNumber(), - fee.getGasPriceLimitNumber(), - credentials.getAddress(), - meta - ); - - 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(); - - assertResponse(sent); - - TransactionReceipt receipt = processor.waitForTransactionReceipt(sent.getResult()); - - assertTrue(receipt::isStatusOK); - } - - @Test - public void testWithdrawToken() throws IOException, TransactionException { - Token token = zksync.zksGetConfirmedTokens(0, (short) 100).send() - .getResult().stream() - .filter(t -> t.getSymbol().equalsIgnoreCase("USDC")) - .findFirst().orElseThrow(IllegalArgumentException::new); - final double amount = 10; - - BigInteger nonce = zksync - .ethGetTransactionCount(credentials.getAddress(), ZkBlockParameterName.COMMITTED).send() - .getTransactionCount(); - - String l2Erc20Bridge = zksync.zksGetBridgeContracts().send().getResult().getL2Erc20DefaultBridge(); - - final Function withdraw = new Function( - IL2Bridge.FUNC_WITHDRAW, - Arrays.asList(new Address(credentials.getAddress()), - new Address(token.getL2Address()), - new Uint256(token.toBigInteger(amount))), - Collections.emptyList()); - - String calldata = FunctionEncoder.encode(withdraw); - - io.zksync.methods.request.Transaction estimate = io.zksync.methods.request.Transaction.createFunctionCallTransaction( - credentials.getAddress(), - l2Erc20Bridge, - BigInteger.ZERO, - BigInteger.ZERO, - calldata - ); - - ZksEstimateFee estimateFee = zksync.zksEstimateFee(estimate).send(); - - EthGasPrice gasPrice = zksync.ethGasPrice().send(); - - assertResponse(estimateFee); - assertResponse(gasPrice); - - Fee fee = estimateFee.getResult(); - - Eip712Meta meta = estimate.getEip712Meta(); - meta.setGasPerPubdata(fee.getGasPerPubdataLimitNumber()); - - Transaction712 transaction = new Transaction712( - chainId.longValue(), - nonce, - fee.getGasLimitNumber(), - estimate.getTo(), - estimate.getValueNumber(), - estimate.getData(), - fee.getMaxPriorityFeePerErgNumber(), - fee.getGasPriceLimitNumber(), - credentials.getAddress(), - meta - ); - - 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(); - - assertResponse(sent); - - TransactionReceipt receipt = processor.waitForTransactionReceipt(sent.getResult()); - - assertTrue(receipt::isStatusOK); - } - - @Test - @Disabled - public void testEstimateGas_Withdraw() throws IOException { - String l2EthBridge = L2_ETH_TOKEN_ADDRESS; - final Function withdraw = new Function( - IL2Bridge.FUNC_WITHDRAW, - Arrays.asList(new Address(credentials.getAddress()), - new Address(ETH.getL2Address()), - new Uint256(ETH.toBigInteger(1))), - Collections.emptyList()); - - String calldata = FunctionEncoder.encode(withdraw); - - EthEstimateGas estimateGas = zksync.ethEstimateGas(io.zksync.methods.request.Transaction.createFunctionCallTransaction( - credentials.getAddress(), - l2EthBridge, - BigInteger.ZERO, - BigInteger.ZERO, - calldata - )).send(); - - assertResponse(estimateGas); - } - - @Test - @Disabled - public void testEstimateGas_TransferNative() throws IOException { - io.zksync.methods.request.Transaction estimate = io.zksync.methods.request.Transaction.createFunctionCallTransaction( - credentials.getAddress(), - credentials.getAddress(), - BigInteger.ZERO, - BigInteger.ZERO, - "0x" - ); - - EthEstimateGas estimateGas = zksync.ethEstimateGas(estimate).send(); - - assertResponse(estimateGas); - } - - @Test - @Disabled - public void testEstimateFee_TransferNative() throws IOException { - io.zksync.methods.request.Transaction estimate = io.zksync.methods.request.Transaction.createFunctionCallTransaction( - credentials.getAddress(), - credentials.getAddress(), - BigInteger.ZERO, - BigInteger.ZERO, - "0x" - ); - - - ZksEstimateFee estimateFee = zksync.zksEstimateFee(estimate).send(); - - assertResponse(estimateFee); - System.out.println(estimateFee.getRawResponse()); - } - - @Test - @Disabled - public void testEstimateGas_Execute() throws IOException { - Function transfer = ERC20.encodeTransfer("0xe1fab3efd74a77c23b426c302d96372140ff7d0c", BigInteger.valueOf(1L)); - String calldata = FunctionEncoder.encode(transfer); - - EthEstimateGas estimateGas = zksync.ethEstimateGas(io.zksync.methods.request.Transaction.createFunctionCallTransaction( - credentials.getAddress(), - "0x79f73588fa338e685e9bbd7181b410f60895d2a3", - BigInteger.ZERO, - BigInteger.ZERO, - calldata - )).send(); - - assertResponse(estimateGas); - } - - @Test - @Disabled - public void testEstimateGas_DeployContract() throws IOException { - EthEstimateGas estimateGas = zksync.ethEstimateGas(io.zksync.methods.request.Transaction.create2ContractTransaction( - credentials.getAddress(), - BigInteger.ZERO, - BigInteger.ZERO, - CounterContract.BINARY - )).send(); - - assertResponse(estimateGas); - } - - @Test - @Disabled - public void testEstimateFee_DeployContract() throws IOException { - ZksEstimateFee estimateFee = zksync.zksEstimateFee(io.zksync.methods.request.Transaction.create2ContractTransaction( - credentials.getAddress(), - BigInteger.ZERO, + @Test + public void printChainId() { + System.out.println(chainId); + System.out.println(credentials.getAddress()); + } + + @Test + @Disabled + @Deprecated + public void sendTestMoney() { + String account = l1Web3.ethAccounts().sendAsync().join().getAccounts().get(0); + + EthSendTransaction sent = + l1Web3 + .ethSendTransaction( + Transaction.createEtherTransaction( + account, + null, + Convert.toWei("1", Unit.GWEI).toBigInteger(), + BigInteger.valueOf(21_000L), + credentials.getAddress(), + Convert.toWei("1000000", Unit.ETHER).toBigInteger())) + .sendAsync() + .join(); + + assertResponse(sent); + } + + @Test + @Disabled + public void testGetBalanceOfNativeL1() throws IOException { + EthGetBalance getBalance = + l1Web3.ethGetBalance(credentials.getAddress(), DefaultBlockParameterName.LATEST).send(); + + assertResponse(getBalance); + System.out.printf( + "%s: %d\n", credentials.getAddress(), Numeric.toBigInt(getBalance.getResult())); + assertTrue( + getBalance.getBalance().compareTo(Convert.toWei("0.2", Unit.ETHER).toBigInteger()) >= 0); + } + + @Test + @Disabled + public void testDeposit() throws IOException { + BigInteger chainId = l1Web3.ethChainId().send().getChainId(); + TransactionManager manager = + new RawTransactionManager(l1Web3, credentials, chainId.longValue()); + BigInteger gasPrice = l1Web3.ethGasPrice().send().getGasPrice(); + ContractGasProvider gasProvider = new StaticGasProvider(gasPrice, BigInteger.valueOf(170_000L)); + TransactionReceipt receipt = + EthereumProvider.load(zksync, l1Web3, manager, gasProvider) + .join() + .deposit( + ETH, + Convert.toWei("0.001", Unit.ETHER).toBigInteger(), BigInteger.ZERO, - CounterContract.BINARY - )).send(); - - assertResponse(estimateFee); - } + credentials.getAddress()) + .join(); + + System.out.println(receipt); + } + + @Test + @Disabled + public void testDepositToken() throws IOException { + Token token = + zksync.zksGetConfirmedTokens(0, (short) 100).send().getResult().stream() + .filter(t -> t.getSymbol().equalsIgnoreCase("USDC")) + .findFirst() + .orElseThrow(IllegalArgumentException::new); + BigInteger chainId = l1Web3.ethChainId().send().getChainId(); + BigInteger gasPrice = l1Web3.ethGasPrice().send().getGasPrice(); + TransactionManager manager = + new RawTransactionManager(l1Web3, credentials, chainId.longValue()); + ContractGasProvider gasProvider = new StaticGasProvider(gasPrice, BigInteger.valueOf(200_000L)); + EthereumProvider provider = EthereumProvider.load(zksync, l1Web3, manager, gasProvider).join(); + TransactionReceipt approveReceipt = + provider.approveDeposits(token, Optional.of(token.toBigInteger(10000000000L))).join(); + System.out.println(approveReceipt); + + TransactionReceipt receipt = + provider + .deposit( + token, token.toBigInteger(10000000000L), BigInteger.ZERO, credentials.getAddress()) + .join(); + + System.out.println(receipt); + } + + @Test + public void testGetBalanceOfNative() throws IOException { + EthGetBalance getBalance = + zksync.ethGetBalance(credentials.getAddress(), DefaultBlockParameterName.LATEST).send(); + + System.out.printf( + "%s: %d\n", credentials.getAddress(), Numeric.toBigInt(getBalance.getResult())); + } + + @Test + public void testGetNonce() throws IOException { + EthGetTransactionCount getTransactionCount = + zksync + .ethGetTransactionCount(credentials.getAddress(), DefaultBlockParameterName.LATEST) + .send(); + + System.out.printf( + "%s: %d\n", credentials.getAddress(), Numeric.toBigInt(getTransactionCount.getResult())); + } + + @Test + public void testGetDeploymentNonce() throws Exception { + NonceHolder nonceHolder = + NonceHolder.load( + ZkSyncAddresses.NONCE_HOLDER_ADDRESS, + zksync, + new ReadonlyTransactionManager(zksync, credentials.getAddress()), + new DefaultGasProvider()); + + BigInteger nonce = nonceHolder.getDeploymentNonce(credentials.getAddress()).send(); + + System.out.printf("%s: %d\n", credentials.getAddress(), nonce); + } + + @Test + public void testGetTransactionReceipt() throws IOException { + TransactionReceipt receipt = + zksync + .ethGetTransactionReceipt( + "0xea87f073bbb8826edf51abbbc77b5812848c92bfb8a825f82a74586ad3553309") + .send() + .getResult(); + + System.out.println(receipt); + } + + @Test + public void testGetTransaction() throws IOException { + org.web3j.protocol.core.methods.response.Transaction receipt = + zksync + .ethGetTransactionByHash( + "0x60c05fffdfca5ffb5884f8dd0a80268f16ef768c71f6e173ed1fb58a50790e29") + .send() + .getResult(); + + System.out.println(receipt); + } + + @Test + public void testTransferNativeToSelf() throws IOException, TransactionException { + final BigInteger value = Convert.toWei(BigDecimal.valueOf(0.01), Unit.ETHER).toBigInteger(); + + BigInteger nonce = + zksync + .ethGetTransactionCount(credentials.getAddress(), ZkBlockParameterName.COMMITTED) + .send() + .getTransactionCount(); + + io.zksync.methods.request.Transaction estimate = + io.zksync.methods.request.Transaction.createEtherTransaction( + credentials.getAddress(), + BigInteger.ZERO, + BigInteger.ZERO, + credentials.getAddress(), + value); + + ZksEstimateFee estimateFee = zksync.zksEstimateFee(estimate).send(); + + EthGasPrice gasPrice = zksync.ethGasPrice().send(); + + assertResponse(gasPrice); + assertResponse(estimateFee); + + Fee fee = estimateFee.getResult(); + + Eip712Meta meta = estimate.getEip712Meta(); + meta.setGasPerPubdata(fee.getGasPerPubdataLimitNumber()); + + Transaction712 transaction = + new Transaction712( + chainId.longValue(), + nonce, + fee.getGasLimitNumber(), + estimate.getTo(), + value, + estimate.getData(), + fee.getMaxPriorityFeePerErgNumber(), + fee.getGasPriceLimitNumber(), + credentials.getAddress(), + meta); + + 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(); + + assertResponse(sent); + + TransactionReceipt receipt = processor.waitForTransactionReceipt(sent.getResult()); + + assertTrue(receipt::isStatusOK); + } + + @Test + public void testTransferTokenToSelf() throws IOException, TransactionException { + BigInteger nonce = + zksync + .ethGetTransactionCount(credentials.getAddress(), ZkBlockParameterName.COMMITTED) + .send() + .getTransactionCount(); + + Token token = + zksync.zksGetConfirmedTokens(0, (short) 100).send().getResult().stream() + .filter(t -> t.getSymbol().equalsIgnoreCase("USDC")) + .findFirst() + .orElseThrow(IllegalArgumentException::new); + String tokenAddress = token.getL2Address(); + Function transfer = ERC20.encodeTransfer(credentials.getAddress(), token.toBigInteger(10)); + String calldata = FunctionEncoder.encode(transfer); + + io.zksync.methods.request.Transaction estimate = + io.zksync.methods.request.Transaction.createFunctionCallTransaction( + credentials.getAddress(), tokenAddress, BigInteger.ZERO, BigInteger.ZERO, calldata); + + ZksEstimateFee estimateFee = zksync.zksEstimateFee(estimate).send(); + + EthGasPrice gasPrice = zksync.ethGasPrice().send(); + + assertResponse(gasPrice); + assertResponse(estimateFee); + + Fee fee = estimateFee.getResult(); + + Eip712Meta meta = estimate.getEip712Meta(); + meta.setGasPerPubdata(fee.getGasPerPubdataLimitNumber()); + + Transaction712 transaction = + new Transaction712( + chainId.longValue(), + nonce, + fee.getGasLimitNumber(), + estimate.getTo(), + estimate.getValueNumber(), + estimate.getData(), + fee.getMaxPriorityFeePerErgNumber(), + fee.getGasPriceLimitNumber(), + credentials.getAddress(), + meta); + + 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(); + + assertResponse(sent); + + TransactionReceipt receipt = processor.waitForTransactionReceipt(sent.getResult()); + + assertTrue(receipt::isStatusOK); + } + + @Test + public void testTransferTokenToSelfWeb3jContract() throws Exception { + Token token = + zksync.zksGetConfirmedTokens(0, (short) 100).send().getResult().stream() + .filter(t -> t.getSymbol().equalsIgnoreCase("USDC")) + .findFirst() + .orElseThrow(IllegalArgumentException::new); + + ERC20 erc20 = + ERC20.load( + token.getL2Address(), + zksync, + new ZkSyncTransactionManager(zksync, signer, feeProvider), + feeProvider); + + TransactionReceipt receipt = + erc20.transfer(credentials.getAddress(), token.toBigInteger(10)).send(); + + assertTrue(receipt::isStatusOK); + } + + @Test + public void testWithdraw() throws IOException, TransactionException { + final Token token = ETH; + final double amount = 0.01; + + BigInteger nonce = + zksync + .ethGetTransactionCount(credentials.getAddress(), ZkBlockParameterName.COMMITTED) + .send() + .getTransactionCount(); + + String l2EthBridge = L2_ETH_TOKEN_ADDRESS; + + final Function withdraw = + new Function( + IL2Bridge.FUNC_WITHDRAW, + Arrays.asList( + new Address(credentials.getAddress()), + new Address(token.getL2Address()), + new Uint256(token.toBigInteger(amount))), + Collections.emptyList()); + + String calldata = FunctionEncoder.encode(withdraw); + + io.zksync.methods.request.Transaction estimate = + io.zksync.methods.request.Transaction.createFunctionCallTransaction( + credentials.getAddress(), l2EthBridge, BigInteger.ZERO, BigInteger.ZERO, calldata); + + ZksEstimateFee estimateFee = zksync.zksEstimateFee(estimate).send(); + + EthGasPrice gasPrice = zksync.ethGasPrice().send(); + + assertResponse(estimateFee); + assertResponse(gasPrice); + + Fee fee = estimateFee.getResult(); + + Eip712Meta meta = estimate.getEip712Meta(); + meta.setGasPerPubdata(fee.getGasPerPubdataLimitNumber()); - @Test - public void testDeployWeb3jContract() { - Executable execute = () -> { - TransactionManager transactionManager = new ZkSyncTransactionManager(zksync, signer, feeProvider); - CounterContract contract = CounterContract - .deploy(zksync, transactionManager, feeProvider).send(); + Transaction712 transaction = + new Transaction712( + chainId.longValue(), + nonce, + fee.getGasLimitNumber(), + estimate.getTo(), + estimate.getValueNumber(), + estimate.getData(), + fee.getMaxPriorityFeePerErgNumber(), + fee.getGasPriceLimitNumber(), + credentials.getAddress(), + meta); + + 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(); + + assertResponse(sent); + + TransactionReceipt receipt = processor.waitForTransactionReceipt(sent.getResult()); + + assertTrue(receipt::isStatusOK); + } + + @Test + public void testWithdrawToken() throws IOException, TransactionException { + Token token = + zksync.zksGetConfirmedTokens(0, (short) 100).send().getResult().stream() + .filter(t -> t.getSymbol().equalsIgnoreCase("USDC")) + .findFirst() + .orElseThrow(IllegalArgumentException::new); + final double amount = 10; + + BigInteger nonce = + zksync + .ethGetTransactionCount(credentials.getAddress(), ZkBlockParameterName.COMMITTED) + .send() + .getTransactionCount(); + + String l2Erc20Bridge = + zksync.zksGetBridgeContracts().send().getResult().getL2Erc20DefaultBridge(); + + final Function withdraw = + new Function( + IL2Bridge.FUNC_WITHDRAW, + Arrays.asList( + new Address(credentials.getAddress()), + new Address(token.getL2Address()), + new Uint256(token.toBigInteger(amount))), + Collections.emptyList()); + + String calldata = FunctionEncoder.encode(withdraw); + + io.zksync.methods.request.Transaction estimate = + io.zksync.methods.request.Transaction.createFunctionCallTransaction( + credentials.getAddress(), l2Erc20Bridge, BigInteger.ZERO, BigInteger.ZERO, calldata); + + ZksEstimateFee estimateFee = zksync.zksEstimateFee(estimate).send(); + + EthGasPrice gasPrice = zksync.ethGasPrice().send(); + + assertResponse(estimateFee); + assertResponse(gasPrice); + + Fee fee = estimateFee.getResult(); + + Eip712Meta meta = estimate.getEip712Meta(); + meta.setGasPerPubdata(fee.getGasPerPubdataLimitNumber()); + + Transaction712 transaction = + new Transaction712( + chainId.longValue(), + nonce, + fee.getGasLimitNumber(), + estimate.getTo(), + estimate.getValueNumber(), + estimate.getData(), + fee.getMaxPriorityFeePerErgNumber(), + fee.getGasPriceLimitNumber(), + credentials.getAddress(), + meta); + + 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(); + + assertResponse(sent); + + TransactionReceipt receipt = processor.waitForTransactionReceipt(sent.getResult()); + + assertTrue(receipt::isStatusOK); + } + + @Test + @Disabled + public void testEstimateGas_Withdraw() throws IOException { + String l2EthBridge = L2_ETH_TOKEN_ADDRESS; + final Function withdraw = + new Function( + IL2Bridge.FUNC_WITHDRAW, + Arrays.asList( + new Address(credentials.getAddress()), + new Address(ETH.getL2Address()), + new Uint256(ETH.toBigInteger(1))), + Collections.emptyList()); + + String calldata = FunctionEncoder.encode(withdraw); + + EthEstimateGas estimateGas = + zksync + .ethEstimateGas( + io.zksync.methods.request.Transaction.createFunctionCallTransaction( + credentials.getAddress(), + l2EthBridge, + BigInteger.ZERO, + BigInteger.ZERO, + calldata)) + .send(); + + assertResponse(estimateGas); + } + + @Test + @Disabled + public void testEstimateGas_TransferNative() throws IOException { + io.zksync.methods.request.Transaction estimate = + io.zksync.methods.request.Transaction.createFunctionCallTransaction( + credentials.getAddress(), + credentials.getAddress(), + BigInteger.ZERO, + BigInteger.ZERO, + "0x"); + + EthEstimateGas estimateGas = zksync.ethEstimateGas(estimate).send(); + + assertResponse(estimateGas); + } + + @Test + @Disabled + public void testEstimateFee_TransferNative() throws IOException { + io.zksync.methods.request.Transaction estimate = + io.zksync.methods.request.Transaction.createFunctionCallTransaction( + credentials.getAddress(), + credentials.getAddress(), + BigInteger.ZERO, + BigInteger.ZERO, + "0x"); + + ZksEstimateFee estimateFee = zksync.zksEstimateFee(estimate).send(); + + assertResponse(estimateFee); + System.out.println(estimateFee.getRawResponse()); + } + + @Test + @Disabled + public void testEstimateGas_Execute() throws IOException { + Function transfer = + ERC20.encodeTransfer("0xe1fab3efd74a77c23b426c302d96372140ff7d0c", BigInteger.valueOf(1L)); + String calldata = FunctionEncoder.encode(transfer); + + EthEstimateGas estimateGas = + zksync + .ethEstimateGas( + io.zksync.methods.request.Transaction.createFunctionCallTransaction( + credentials.getAddress(), + "0x79f73588fa338e685e9bbd7181b410f60895d2a3", + BigInteger.ZERO, + BigInteger.ZERO, + calldata)) + .send(); + + assertResponse(estimateGas); + } + + @Test + @Disabled + public void testEstimateGas_DeployContract() throws IOException { + EthEstimateGas estimateGas = + zksync + .ethEstimateGas( + io.zksync.methods.request.Transaction.create2ContractTransaction( + credentials.getAddress(), + BigInteger.ZERO, + BigInteger.ZERO, + CounterContract.BINARY)) + .send(); + + assertResponse(estimateGas); + } + + @Test + @Disabled + public void testEstimateFee_DeployContract() throws IOException { + ZksEstimateFee estimateFee = + zksync + .zksEstimateFee( + io.zksync.methods.request.Transaction.create2ContractTransaction( + credentials.getAddress(), + BigInteger.ZERO, + BigInteger.ZERO, + CounterContract.BINARY)) + .send(); + + assertResponse(estimateFee); + } + + @Test + public void testDeployWeb3jContract() { + Executable execute = + () -> { + TransactionManager transactionManager = + new ZkSyncTransactionManager(zksync, signer, feeProvider); + CounterContract contract = + CounterContract.deploy(zksync, transactionManager, feeProvider).send(); }; - assertThrows(RuntimeException.class, execute); - } - - @Test - public void testWeb3jContract() throws Exception { - io.zksync.methods.request.Transaction deploy = io.zksync.methods.request.Transaction.createContractTransaction( - credentials.getAddress(), - BigInteger.ZERO, - BigInteger.ZERO, - CounterContract.BINARY - ); - TransactionReceipt deployed = submitTransaction(deploy); - CounterContract zkCounterContract = CounterContract.load(deployed.getContractAddress(), zksync, new ZkSyncTransactionManager(zksync, signer, feeProvider), feeProvider); - - { - BigInteger result = zkCounterContract.get().send(); - - System.out.println(result); - - assertEquals(BigInteger.ZERO, result); - } + assertThrows(RuntimeException.class, execute); + } - { - TransactionReceipt receipt = zkCounterContract.increment(BigInteger.TEN).send(); + @Test + public void testWeb3jContract() throws Exception { + io.zksync.methods.request.Transaction deploy = + io.zksync.methods.request.Transaction.createContractTransaction( + credentials.getAddress(), BigInteger.ZERO, BigInteger.ZERO, CounterContract.BINARY); + TransactionReceipt deployed = submitTransaction(deploy); + CounterContract zkCounterContract = + CounterContract.load( + deployed.getContractAddress(), + zksync, + new ZkSyncTransactionManager(zksync, signer, feeProvider), + feeProvider); - assertTrue(receipt::isStatusOK); + { + BigInteger result = zkCounterContract.get().send(); - BigInteger result = zkCounterContract.get().send(); + System.out.println(result); - assertEquals(BigInteger.TEN, result); - } + assertEquals(BigInteger.ZERO, result); } - @Test - public void testDeployContract_Create() throws Exception { - BigInteger nonce = zksync - .ethGetTransactionCount(credentials.getAddress(), DefaultBlockParameterName.PENDING).send() - .getTransactionCount(); - - NonceHolder nonceHolder = NonceHolder.load(ZkSyncAddresses.NONCE_HOLDER_ADDRESS, zksync, new ReadonlyTransactionManager(zksync, credentials.getAddress()), new DefaultGasProvider()); - - BigInteger deploymentNonce = nonceHolder.getDeploymentNonce(credentials.getAddress()).send(); - - String precomputedAddress = ContractDeployer.computeL2CreateAddress(new Address(credentials.getAddress()), deploymentNonce).getValue(); - - io.zksync.methods.request.Transaction estimate = io.zksync.methods.request.Transaction.createContractTransaction( - credentials.getAddress(), - BigInteger.ZERO, - BigInteger.ZERO, - CounterContract.BINARY - ); - - ZksEstimateFee estimateFee = zksync.zksEstimateFee(estimate).send(); - - EthGasPrice gasPrice = zksync.ethGasPrice().send(); - - assertResponse(estimateFee); - assertResponse(gasPrice); - - Fee fee = estimateFee.getResult(); - - Eip712Meta meta = estimate.getEip712Meta(); - meta.setGasPerPubdata(fee.getGasPerPubdataLimitNumber()); - - Transaction712 transaction = new Transaction712( - chainId.longValue(), - nonce, - fee.getGasLimitNumber(), - estimate.getTo(), - estimate.getValueNumber(), - estimate.getData(), - fee.getMaxPriorityFeePerErgNumber(), - fee.getGasPriceLimitNumber(), - credentials.getAddress(), - meta - ); - - 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(); - - assertResponse(sent); + { + TransactionReceipt receipt = zkCounterContract.increment(BigInteger.TEN).send(); - TransactionReceipt receipt = processor.waitForTransactionReceipt(sent.getResult()); + assertTrue(receipt::isStatusOK); - assertTrue(receipt::isStatusOK); + BigInteger result = zkCounterContract.get().send(); - String contractAddress = receipt.getContractAddress(); - System.out.println("Deployed `CounterContract as: `" + contractAddress); - assertEquals(contractAddress.toLowerCase(), precomputedAddress.toLowerCase()); - - Transaction call = Transaction.createEthCallTransaction( - credentials.getAddress(), - contractAddress, - FunctionEncoder.encode(CounterContract.encodeGet()) - ); - - zksync.ethCall(call, ZkBlockParameterName.COMMITTED).send(); + assertEquals(BigInteger.TEN, result); } + } + + @Test + public void testDeployContract_Create() throws Exception { + BigInteger nonce = + zksync + .ethGetTransactionCount(credentials.getAddress(), DefaultBlockParameterName.PENDING) + .send() + .getTransactionCount(); + + NonceHolder nonceHolder = + NonceHolder.load( + ZkSyncAddresses.NONCE_HOLDER_ADDRESS, + zksync, + new ReadonlyTransactionManager(zksync, credentials.getAddress()), + new DefaultGasProvider()); + + BigInteger deploymentNonce = nonceHolder.getDeploymentNonce(credentials.getAddress()).send(); + + String precomputedAddress = + ContractDeployer.computeL2CreateAddress( + new Address(credentials.getAddress()), deploymentNonce) + .getValue(); + + io.zksync.methods.request.Transaction estimate = + io.zksync.methods.request.Transaction.createContractTransaction( + credentials.getAddress(), BigInteger.ZERO, BigInteger.ZERO, CounterContract.BINARY); + + ZksEstimateFee estimateFee = zksync.zksEstimateFee(estimate).send(); + + EthGasPrice gasPrice = zksync.ethGasPrice().send(); + + assertResponse(estimateFee); + assertResponse(gasPrice); + + Fee fee = estimateFee.getResult(); + + Eip712Meta meta = estimate.getEip712Meta(); + meta.setGasPerPubdata(fee.getGasPerPubdataLimitNumber()); + + Transaction712 transaction = + new Transaction712( + chainId.longValue(), + nonce, + fee.getGasLimitNumber(), + estimate.getTo(), + estimate.getValueNumber(), + estimate.getData(), + fee.getMaxPriorityFeePerErgNumber(), + fee.getGasPriceLimitNumber(), + credentials.getAddress(), + meta); + + 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(); + + assertResponse(sent); + + TransactionReceipt receipt = processor.waitForTransactionReceipt(sent.getResult()); + + assertTrue(receipt::isStatusOK); + + String contractAddress = receipt.getContractAddress(); + System.out.println("Deployed `CounterContract as: `" + contractAddress); + assertEquals(contractAddress.toLowerCase(), precomputedAddress.toLowerCase()); + + Transaction call = + Transaction.createEthCallTransaction( + credentials.getAddress(), + contractAddress, + FunctionEncoder.encode(CounterContract.encodeGet())); + + zksync.ethCall(call, ZkBlockParameterName.COMMITTED).send(); + } + + @Test + public void testDeployContractWithConstructor_Create() throws Exception { + BigInteger nonce = + zksync + .ethGetTransactionCount(credentials.getAddress(), DefaultBlockParameterName.PENDING) + .send() + .getTransactionCount(); + + NonceHolder nonceHolder = + NonceHolder.load( + ZkSyncAddresses.NONCE_HOLDER_ADDRESS, + zksync, + new ReadonlyTransactionManager(zksync, credentials.getAddress()), + new DefaultGasProvider()); + + BigInteger deploymentNonce = nonceHolder.getDeploymentNonce(credentials.getAddress()).send(); + + String precomputedAddress = + ContractDeployer.computeL2CreateAddress( + new Address(credentials.getAddress()), deploymentNonce) + .getValue(); + + String constructor = + ConstructorContract.encodeConstructor( + BigInteger.valueOf(42), BigInteger.valueOf(43), false); + + io.zksync.methods.request.Transaction estimate = + io.zksync.methods.request.Transaction.createContractTransaction( + credentials.getAddress(), + BigInteger.ZERO, + BigInteger.ZERO, + ConstructorContract.BINARY, + constructor); + + ZksEstimateFee estimateFee = zksync.zksEstimateFee(estimate).send(); + + EthGasPrice gasPrice = zksync.ethGasPrice().send(); + + assertResponse(estimateFee); + assertResponse(gasPrice); + + Fee fee = estimateFee.getResult(); + + Eip712Meta meta = estimate.getEip712Meta(); + meta.setGasPerPubdata(fee.getGasPerPubdataLimitNumber()); + + Transaction712 transaction = + new Transaction712( + chainId.longValue(), + nonce, + fee.getGasLimitNumber(), + estimate.getTo(), + estimate.getValueNumber(), + estimate.getData(), + fee.getMaxPriorityFeePerErgNumber(), + fee.getGasPriceLimitNumber(), + credentials.getAddress(), + meta); + + 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(); + + assertResponse(sent); + + TransactionReceipt receipt = processor.waitForTransactionReceipt(sent.getResult()); + + assertTrue(receipt::isStatusOK); + + String contractAddress = receipt.getContractAddress(); + System.out.println("Deployed `ConstructorContract as: `" + contractAddress); + assertContractDeployResponse(receipt, precomputedAddress); + + Transaction call = + Transaction.createEthCallTransaction( + credentials.getAddress(), + contractAddress, + FunctionEncoder.encode(ConstructorContract.encodeGet())); + + EthCall ethCall = zksync.ethCall(call, ZkBlockParameterName.COMMITTED).send(); + assertResponse(ethCall); + } + + @Test + public void testDeployContract_Create2() throws IOException, TransactionException { + BigInteger nonce = + zksync + .ethGetTransactionCount(credentials.getAddress(), DefaultBlockParameterName.PENDING) + .send() + .getTransactionCount(); + + byte[] salt = SecureRandom.getSeed(32); + + String precomputedAddress = + ContractDeployer.computeL2Create2Address( + new Address(credentials.getAddress()), + Numeric.hexStringToByteArray(CounterContract.BINARY), + new byte[] {}, + salt) + .getValue(); + + io.zksync.methods.request.Transaction estimate = + io.zksync.methods.request.Transaction.create2ContractTransaction( + credentials.getAddress(), + BigInteger.ZERO, + BigInteger.ZERO, + CounterContract.BINARY, + "0x", + salt); + + ZksEstimateFee estimateFee = zksync.zksEstimateFee(estimate).send(); + + EthGasPrice gasPrice = zksync.ethGasPrice().send(); + + assertResponse(estimateFee); + assertResponse(gasPrice); + + Fee fee = estimateFee.getResult(); + + Eip712Meta meta = estimate.getEip712Meta(); + meta.setGasPerPubdata(fee.getGasPerPubdataLimitNumber()); + + Transaction712 transaction = + new Transaction712( + chainId.longValue(), + nonce, + fee.getGasLimitNumber(), + estimate.getTo(), + estimate.getValueNumber(), + estimate.getData(), + fee.getMaxPriorityFeePerErgNumber(), + fee.getGasPriceLimitNumber(), + credentials.getAddress(), + meta); + + 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(); + + assertResponse(sent); + + TransactionReceipt receipt = processor.waitForTransactionReceipt(sent.getResult()); + + assertTrue(receipt::isStatusOK); + + String contractAddress = receipt.getContractAddress(); + System.out.println("Deployed `CounterContract as: `" + contractAddress); + assertContractDeployResponse(receipt, precomputedAddress); + + Transaction call = + Transaction.createEthCallTransaction( + credentials.getAddress(), + contractAddress, + FunctionEncoder.encode(CounterContract.encodeGet())); + + EthCall ethCall = zksync.ethCall(call, ZkBlockParameterName.COMMITTED).send(); + assertResponse(ethCall); + } + + @Test + public void testDeployContractWithDeps_Create() throws Exception { + BigInteger nonce = + zksync + .ethGetTransactionCount(credentials.getAddress(), DefaultBlockParameterName.PENDING) + .send() + .getTransactionCount(); + + NonceHolder nonceHolder = + NonceHolder.load( + ZkSyncAddresses.NONCE_HOLDER_ADDRESS, + zksync, + new ReadonlyTransactionManager(zksync, credentials.getAddress()), + new DefaultGasProvider()); + + BigInteger deploymentNonce = nonceHolder.getDeploymentNonce(credentials.getAddress()).send(); + + String precomputedAddress = + ContractDeployer.computeL2CreateAddress( + new Address(credentials.getAddress()), deploymentNonce) + .getValue(); + + io.zksync.methods.request.Transaction estimate = + io.zksync.methods.request.Transaction.createContractTransaction( + credentials.getAddress(), + BigInteger.ZERO, + BigInteger.ZERO, + Import.BINARY, + Collections.singletonList(Import.FOO_BINARY), + "0x"); + + ZksEstimateFee estimateFee = zksync.zksEstimateFee(estimate).send(); + + EthGasPrice gasPrice = zksync.ethGasPrice().send(); + + assertResponse(estimateFee); + assertResponse(gasPrice); + + Fee fee = estimateFee.getResult(); + + Eip712Meta meta = estimate.getEip712Meta(); + meta.setGasPerPubdata(fee.getGasPerPubdataLimitNumber()); + + Transaction712 transaction = + new Transaction712( + chainId.longValue(), + nonce, + fee.getGasLimitNumber(), + estimate.getTo(), + estimate.getValueNumber(), + estimate.getData(), + fee.getMaxPriorityFeePerErgNumber(), + fee.getGasPriceLimitNumber(), + credentials.getAddress(), + meta); + + 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(); + + assertResponse(sent); + + TransactionReceipt receipt = processor.waitForTransactionReceipt(sent.getResult()); + + assertTrue(receipt::isStatusOK); + + String contractAddress = ContractDeployer.extractContractAddress(receipt).getValue(); + System.out.println("Deployed `Import as: `" + contractAddress); + assertContractDeployResponse(receipt, precomputedAddress); + + Function getFooName = Import.encodeGetFooName(); + + Transaction call = + Transaction.createEthCallTransaction( + null, contractAddress, FunctionEncoder.encode(getFooName)); + + EthCall ethCall = zksync.ethCall(call, ZkBlockParameterName.COMMITTED).send(); + assertResponse(ethCall); + + String fooName = + (String) + FunctionReturnDecoder.decode(ethCall.getValue(), getFooName.getOutputParameters()) + .get(0) + .getValue(); + assertEquals("Foo", fooName); + } + + @Test + public void testDeployContractWithDeps_Create2() throws IOException, TransactionException { + BigInteger nonce = + zksync + .ethGetTransactionCount(credentials.getAddress(), DefaultBlockParameterName.PENDING) + .send() + .getTransactionCount(); + + byte[] salt = SecureRandom.getSeed(32); + + String precomputedAddress = + ContractDeployer.computeL2Create2Address( + new Address(credentials.getAddress()), + Numeric.hexStringToByteArray(Import.BINARY), + new byte[] {}, + salt) + .getValue(); + + io.zksync.methods.request.Transaction estimate = + io.zksync.methods.request.Transaction.create2ContractTransaction( + credentials.getAddress(), + BigInteger.ZERO, + BigInteger.ZERO, + Import.BINARY, + Collections.singletonList(Import.FOO_BINARY), + "0x", + salt); + + ZksEstimateFee estimateFee = zksync.zksEstimateFee(estimate).send(); + + EthGasPrice gasPrice = zksync.ethGasPrice().send(); + + assertResponse(estimateFee); + assertResponse(gasPrice); + + Fee fee = estimateFee.getResult(); + + Eip712Meta meta = estimate.getEip712Meta(); + meta.setGasPerPubdata(fee.getGasPerPubdataLimitNumber()); + + Transaction712 transaction = + new Transaction712( + chainId.longValue(), + nonce, + fee.getGasLimitNumber(), + estimate.getTo(), + estimate.getValueNumber(), + estimate.getData(), + fee.getMaxPriorityFeePerErgNumber(), + fee.getGasPriceLimitNumber(), + credentials.getAddress(), + meta); + + 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(); + + assertResponse(sent); + + TransactionReceipt receipt = processor.waitForTransactionReceipt(sent.getResult()); - @Test - public void testDeployContractWithConstructor_Create() throws Exception { - BigInteger nonce = zksync - .ethGetTransactionCount(credentials.getAddress(), DefaultBlockParameterName.PENDING).send() - .getTransactionCount(); - - NonceHolder nonceHolder = NonceHolder.load(ZkSyncAddresses.NONCE_HOLDER_ADDRESS, zksync, new ReadonlyTransactionManager(zksync, credentials.getAddress()), new DefaultGasProvider()); - - BigInteger deploymentNonce = nonceHolder.getDeploymentNonce(credentials.getAddress()).send(); - - String precomputedAddress = ContractDeployer.computeL2CreateAddress(new Address(credentials.getAddress()), deploymentNonce).getValue(); - - String constructor = ConstructorContract.encodeConstructor(BigInteger.valueOf(42), BigInteger.valueOf(43), false); - - io.zksync.methods.request.Transaction estimate = io.zksync.methods.request.Transaction.createContractTransaction( - credentials.getAddress(), - BigInteger.ZERO, - BigInteger.ZERO, - ConstructorContract.BINARY, - constructor - ); - - ZksEstimateFee estimateFee = zksync.zksEstimateFee(estimate).send(); + assertTrue(receipt::isStatusOK); - EthGasPrice gasPrice = zksync.ethGasPrice().send(); + String contractAddress = ContractDeployer.extractContractAddress(receipt).getValue(); + System.out.println("Deployed `Import as: `" + contractAddress); + assertContractDeployResponse(receipt, precomputedAddress); - assertResponse(estimateFee); - assertResponse(gasPrice); + Function getFooName = Import.encodeGetFooName(); - Fee fee = estimateFee.getResult(); + Transaction call = + Transaction.createEthCallTransaction( + null, contractAddress, FunctionEncoder.encode(getFooName)); - Eip712Meta meta = estimate.getEip712Meta(); - meta.setGasPerPubdata(fee.getGasPerPubdataLimitNumber()); + EthCall ethCall = zksync.ethCall(call, ZkBlockParameterName.COMMITTED).send(); + assertResponse(ethCall); - Transaction712 transaction = new Transaction712( - chainId.longValue(), - nonce, - fee.getGasLimitNumber(), - estimate.getTo(), - estimate.getValueNumber(), - estimate.getData(), - fee.getMaxPriorityFeePerErgNumber(), - fee.getGasPriceLimitNumber(), - credentials.getAddress(), - meta - ); + String fooName = + (String) + FunctionReturnDecoder.decode(ethCall.getValue(), getFooName.getOutputParameters()) + .get(0) + .getValue(); + assertEquals("Foo", fooName); + } + + @Test + public void testExecuteContract() throws IOException, TransactionException { + io.zksync.methods.request.Transaction deploy = + io.zksync.methods.request.Transaction.createContractTransaction( + credentials.getAddress(), BigInteger.ZERO, BigInteger.ZERO, CounterContract.BINARY); + TransactionReceipt deployed = submitTransaction(deploy); + String contractAddress = deployed.getContractAddress(); + BigInteger nonce = + zksync + .ethGetTransactionCount(credentials.getAddress(), ZkBlockParameterName.COMMITTED) + .send() + .getTransactionCount(); - String signature = signer.getDomain().thenCompose(domain -> signer.signTypedData(domain, transaction)).join(); - byte[] message = TransactionEncoder.encode(transaction, TransactionEncoder.getSignatureData(signature)); + Transaction call = + Transaction.createEthCallTransaction( + credentials.getAddress(), + contractAddress, + FunctionEncoder.encode(CounterContract.encodeGet())); - EthSendTransaction sent = zksync.ethSendRawTransaction(Numeric.toHexString(message)).send(); + BigInteger value = + Numeric.toBigInt(zksync.ethCall(call, ZkBlockParameterName.COMMITTED).send().getValue()); - assertResponse(sent); + Function increment = CounterContract.encodeIncrement(BigInteger.ONE); + String calldata = FunctionEncoder.encode(increment); - TransactionReceipt receipt = processor.waitForTransactionReceipt(sent.getResult()); + io.zksync.methods.request.Transaction estimate = + io.zksync.methods.request.Transaction.createFunctionCallTransaction( + credentials.getAddress(), contractAddress, BigInteger.ZERO, BigInteger.ZERO, calldata); - assertTrue(receipt::isStatusOK); + ZksEstimateFee estimateFee = zksync.zksEstimateFee(estimate).send(); - String contractAddress = receipt.getContractAddress(); - System.out.println("Deployed `ConstructorContract as: `" + contractAddress); - assertContractDeployResponse(receipt, precomputedAddress); + EthGasPrice gasPrice = zksync.ethGasPrice().send(); - Transaction call = Transaction.createEthCallTransaction( - credentials.getAddress(), - contractAddress, - FunctionEncoder.encode(ConstructorContract.encodeGet()) - ); + assertResponse(estimateFee); + assertResponse(gasPrice); - EthCall ethCall = zksync.ethCall(call, ZkBlockParameterName.COMMITTED).send(); - assertResponse(ethCall); - } + Fee fee = estimateFee.getResult(); - @Test - public void testDeployContract_Create2() throws IOException, TransactionException { - BigInteger nonce = zksync - .ethGetTransactionCount(credentials.getAddress(), DefaultBlockParameterName.PENDING).send() - .getTransactionCount(); + Eip712Meta meta = estimate.getEip712Meta(); + meta.setGasPerPubdata(fee.getGasPerPubdataLimitNumber()); - byte[] salt = SecureRandom.getSeed(32); + Transaction712 transaction = + new Transaction712( + chainId.longValue(), + nonce, + fee.getGasLimitNumber(), + estimate.getTo(), + estimate.getValueNumber(), + estimate.getData(), + fee.getMaxPriorityFeePerErgNumber(), + fee.getGasPriceLimitNumber(), + credentials.getAddress(), + meta); - String precomputedAddress = ContractDeployer.computeL2Create2Address(new Address(credentials.getAddress()), Numeric.hexStringToByteArray(CounterContract.BINARY), new byte[]{}, salt).getValue(); + String signature = + signer.getDomain().thenCompose(domain -> signer.signTypedData(domain, transaction)).join(); + byte[] message = + TransactionEncoder.encode(transaction, TransactionEncoder.getSignatureData(signature)); - io.zksync.methods.request.Transaction estimate = io.zksync.methods.request.Transaction.create2ContractTransaction( - credentials.getAddress(), - BigInteger.ZERO, - BigInteger.ZERO, - CounterContract.BINARY, - "0x", - salt - ); + EthSendTransaction sent = zksync.ethSendRawTransaction(Numeric.toHexString(message)).send(); - ZksEstimateFee estimateFee = zksync.zksEstimateFee(estimate).send(); + assertResponse(sent); - EthGasPrice gasPrice = zksync.ethGasPrice().send(); + TransactionReceipt receipt = processor.waitForTransactionReceipt(sent.getResult()); - assertResponse(estimateFee); - assertResponse(gasPrice); + assertTrue(receipt::isStatusOK); - Fee fee = estimateFee.getResult(); + BigInteger result = + Numeric.toBigInt(zksync.ethCall(call, ZkBlockParameterName.COMMITTED).send().getValue()); - Eip712Meta meta = estimate.getEip712Meta(); - meta.setGasPerPubdata(fee.getGasPerPubdataLimitNumber()); + assertEquals(value.add(BigInteger.ONE), result); + } - Transaction712 transaction = new Transaction712( - chainId.longValue(), - nonce, - fee.getGasLimitNumber(), - estimate.getTo(), - estimate.getValueNumber(), - estimate.getData(), - fee.getMaxPriorityFeePerErgNumber(), - fee.getGasPriceLimitNumber(), - credentials.getAddress(), - meta - ); + @Test + public void testGetAllAccountBalances() throws IOException { + ZksAccountBalances response = zksync.zksGetAllAccountBalances(credentials.getAddress()).send(); - String signature = signer.getDomain().thenCompose(domain -> signer.signTypedData(domain, transaction)).join(); - byte[] message = TransactionEncoder.encode(transaction, TransactionEncoder.getSignatureData(signature)); + assertResponse(response); - EthSendTransaction sent = zksync.ethSendRawTransaction(Numeric.toHexString(message)).send(); + Map balances = response.getBalances(); - assertResponse(sent); + System.out.println(balances); + } - TransactionReceipt receipt = processor.waitForTransactionReceipt(sent.getResult()); + @Test + public void testGetConfirmedTokens() throws IOException { + int offset = 0; + short limit = 10; // Get first 10 confirmed tokens - assertTrue(receipt::isStatusOK); + ZksTokens response = zksync.zksGetConfirmedTokens(offset, limit).send(); - String contractAddress = receipt.getContractAddress(); - System.out.println("Deployed `CounterContract as: `" + contractAddress); - assertContractDeployResponse(receipt, precomputedAddress); + assertResponse(response); + } + + @Test + public void testGetTokenPrice() throws IOException { + ZksTokenPrice response = zksync.zksGetTokenPrice(ETH.getL2Address()).send(); - Transaction call = Transaction.createEthCallTransaction( - credentials.getAddress(), - contractAddress, - FunctionEncoder.encode(CounterContract.encodeGet()) - ); + assertResponse(response); + } - EthCall ethCall = zksync.ethCall(call, ZkBlockParameterName.COMMITTED).send(); - assertResponse(ethCall); - } + @Test + public void testGetL1ChainId() throws IOException { + ZksL1ChainId response = zksync.zksL1ChainId().send(); - @Test - public void testDeployContractWithDeps_Create() throws Exception { - BigInteger nonce = zksync - .ethGetTransactionCount(credentials.getAddress(), DefaultBlockParameterName.PENDING).send() - .getTransactionCount(); + assertResponse(response); + } - NonceHolder nonceHolder = NonceHolder.load(ZkSyncAddresses.NONCE_HOLDER_ADDRESS, zksync, new ReadonlyTransactionManager(zksync, credentials.getAddress()), new DefaultGasProvider()); + @Test + public void testGetBridgeAddresses() throws IOException { + ZksBridgeAddresses response = zksync.zksGetBridgeContracts().send(); - BigInteger deploymentNonce = nonceHolder.getDeploymentNonce(credentials.getAddress()).send(); - - String precomputedAddress = ContractDeployer.computeL2CreateAddress(new Address(credentials.getAddress()), deploymentNonce).getValue(); - - io.zksync.methods.request.Transaction estimate = io.zksync.methods.request.Transaction.createContractTransaction( - credentials.getAddress(), - BigInteger.ZERO, - BigInteger.ZERO, - Import.BINARY, - Collections.singletonList(Import.FOO_BINARY), - "0x" - ); + assertResponse(response); + } - ZksEstimateFee estimateFee = zksync.zksEstimateFee(estimate).send(); + @Test + public void testGetTestnetPaymaster() throws IOException { + ZksTestnetPaymasterAddress response = zksync.zksGetTestnetPaymaster().send(); - EthGasPrice gasPrice = zksync.ethGasPrice().send(); + assertResponse(response); + } - assertResponse(estimateFee); - assertResponse(gasPrice); + @Test + public void testGetMainContract() throws IOException { + ZksMainContract response = zksync.zksMainContract().send(); - Fee fee = estimateFee.getResult(); + assertResponse(response); + } - Eip712Meta meta = estimate.getEip712Meta(); - meta.setGasPerPubdata(fee.getGasPerPubdataLimitNumber()); + @Test + public void testGetTransactionDetails() throws IOException { + ZksGetTransactionDetails response = + zksync + .zksGetTransactionDetails( + "0x0898f4b225276625e1d5d2cc4dc5b7a1acb896daece7e46c8202a47da9a13a27") + .send(); - Transaction712 transaction = new Transaction712( - chainId.longValue(), - nonce, - fee.getGasLimitNumber(), - estimate.getTo(), - estimate.getValueNumber(), - estimate.getData(), - fee.getMaxPriorityFeePerErgNumber(), - fee.getGasPriceLimitNumber(), - credentials.getAddress(), - meta - ); - - 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(); - - assertResponse(sent); - - TransactionReceipt receipt = processor.waitForTransactionReceipt(sent.getResult()); - - assertTrue(receipt::isStatusOK); - - String contractAddress = ContractDeployer.extractContractAddress(receipt).getValue(); - System.out.println("Deployed `Import as: `" + contractAddress); - assertContractDeployResponse(receipt, precomputedAddress); - - Function getFooName = Import.encodeGetFooName(); - - Transaction call = Transaction.createEthCallTransaction( - null, - contractAddress, - FunctionEncoder.encode(getFooName) - ); - - EthCall ethCall = zksync.ethCall(call, ZkBlockParameterName.COMMITTED).send(); - assertResponse(ethCall); - - String fooName = (String) FunctionReturnDecoder.decode(ethCall.getValue(), getFooName.getOutputParameters()).get(0).getValue(); - assertEquals("Foo", fooName); - } - - @Test - public void testDeployContractWithDeps_Create2() throws IOException, TransactionException { - BigInteger nonce = zksync - .ethGetTransactionCount(credentials.getAddress(), DefaultBlockParameterName.PENDING).send() - .getTransactionCount(); - - byte[] salt = SecureRandom.getSeed(32); - - String precomputedAddress = ContractDeployer.computeL2Create2Address(new Address(credentials.getAddress()), Numeric.hexStringToByteArray(Import.BINARY), new byte[]{}, salt).getValue(); - - io.zksync.methods.request.Transaction estimate = io.zksync.methods.request.Transaction.create2ContractTransaction( - credentials.getAddress(), - BigInteger.ZERO, - BigInteger.ZERO, - Import.BINARY, - Collections.singletonList(Import.FOO_BINARY), - "0x", - salt - ); + assertResponse(response); + } - ZksEstimateFee estimateFee = zksync.zksEstimateFee(estimate).send(); + @Test + public void testGetTransactionByHash() throws IOException { + ZksGetTransactionByHash response = + zksync + .zksGetTransactionByHash( + "0xd933be650bf97d92c591a88c993b702b368af5480adf019afddee7e8c1e5ce2e") + .send(); - EthGasPrice gasPrice = zksync.ethGasPrice().send(); + assertResponse(response); + } - assertResponse(estimateFee); - assertResponse(gasPrice); + @Test + public void testGetBlockByHash() throws IOException { + ZksBlock response = + zksync + .zksGetBlockByHash( + "0xd933be650bf97d92c591a88c993b702b368af5480adf019afddee7e8c1e5ce2e", true) + .send(); - Fee fee = estimateFee.getResult(); + assertResponse(response); + } - Eip712Meta meta = estimate.getEip712Meta(); - meta.setGasPerPubdata(fee.getGasPerPubdataLimitNumber()); + @Test + public void testGetBlockByNumber() throws IOException { + ZksBlock response = + zksync.zksGetBlockByNumber(DefaultBlockParameter.valueOf("0xb108e"), true).send(); - Transaction712 transaction = new Transaction712( - chainId.longValue(), - nonce, - fee.getGasLimitNumber(), - estimate.getTo(), - estimate.getValueNumber(), - estimate.getData(), - fee.getMaxPriorityFeePerErgNumber(), - fee.getGasPriceLimitNumber(), - credentials.getAddress(), - meta - ); - - 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(); - - assertResponse(sent); - - TransactionReceipt receipt = processor.waitForTransactionReceipt(sent.getResult()); - - assertTrue(receipt::isStatusOK); - - String contractAddress = ContractDeployer.extractContractAddress(receipt).getValue(); - System.out.println("Deployed `Import as: `" + contractAddress); - assertContractDeployResponse(receipt, precomputedAddress); - - Function getFooName = Import.encodeGetFooName(); - - Transaction call = Transaction.createEthCallTransaction( - null, - contractAddress, - FunctionEncoder.encode(getFooName) - ); - - EthCall ethCall = zksync.ethCall(call, ZkBlockParameterName.COMMITTED).send(); - assertResponse(ethCall); - - String fooName = (String) FunctionReturnDecoder.decode(ethCall.getValue(), getFooName.getOutputParameters()).get(0).getValue(); - assertEquals("Foo", fooName); - } - - @Test - public void testExecuteContract() throws IOException, TransactionException { - io.zksync.methods.request.Transaction deploy = io.zksync.methods.request.Transaction.createContractTransaction( - credentials.getAddress(), - BigInteger.ZERO, - BigInteger.ZERO, - CounterContract.BINARY - ); - TransactionReceipt deployed = submitTransaction(deploy); - String contractAddress = deployed.getContractAddress(); - BigInteger nonce = zksync - .ethGetTransactionCount(credentials.getAddress(), ZkBlockParameterName.COMMITTED).send() - .getTransactionCount(); - - Transaction call = Transaction.createEthCallTransaction( - credentials.getAddress(), - contractAddress, - FunctionEncoder.encode(CounterContract.encodeGet()) - ); - - BigInteger value = Numeric.toBigInt(zksync.ethCall(call, ZkBlockParameterName.COMMITTED).send().getValue()); - - Function increment = CounterContract.encodeIncrement(BigInteger.ONE); - String calldata = FunctionEncoder.encode(increment); - - io.zksync.methods.request.Transaction estimate = io.zksync.methods.request.Transaction.createFunctionCallTransaction( - credentials.getAddress(), - contractAddress, - BigInteger.ZERO, - BigInteger.ZERO, - calldata - ); - - ZksEstimateFee estimateFee = zksync.zksEstimateFee(estimate).send(); - - EthGasPrice gasPrice = zksync.ethGasPrice().send(); - - assertResponse(estimateFee); - assertResponse(gasPrice); - - Fee fee = estimateFee.getResult(); - - Eip712Meta meta = estimate.getEip712Meta(); - meta.setGasPerPubdata(fee.getGasPerPubdataLimitNumber()); - - Transaction712 transaction = new Transaction712( - chainId.longValue(), - nonce, - fee.getGasLimitNumber(), - estimate.getTo(), - estimate.getValueNumber(), - estimate.getData(), - fee.getMaxPriorityFeePerErgNumber(), - fee.getGasPriceLimitNumber(), - credentials.getAddress(), - meta - ); - - 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(); - - assertResponse(sent); - - TransactionReceipt receipt = processor.waitForTransactionReceipt(sent.getResult()); - - assertTrue(receipt::isStatusOK); - - BigInteger result = Numeric.toBigInt(zksync.ethCall(call, ZkBlockParameterName.COMMITTED).send().getValue()); - - assertEquals(value.add(BigInteger.ONE), result); - - } - - @Test - public void testGetAllAccountBalances() throws IOException { - ZksAccountBalances response = zksync.zksGetAllAccountBalances(credentials.getAddress()).send(); - - assertResponse(response); - - Map balances = response.getBalances(); - - System.out.println(balances); - } - - @Test - public void testGetConfirmedTokens() throws IOException { - int offset = 0; - short limit = 10; // Get first 10 confirmed tokens - - ZksTokens response = zksync.zksGetConfirmedTokens(offset, limit).send(); - - assertResponse(response); - } - - @Test - public void testGetTokenPrice() throws IOException { - ZksTokenPrice response = zksync.zksGetTokenPrice(ETH.getL2Address()).send(); - - assertResponse(response); - } - - @Test - public void testGetL1ChainId() throws IOException { - ZksL1ChainId response = zksync.zksL1ChainId().send(); - - assertResponse(response); - } - - @Test - public void testGetBridgeAddresses() throws IOException { - ZksBridgeAddresses response = zksync.zksGetBridgeContracts().send(); - - assertResponse(response); - } - - @Test - public void testGetTestnetPaymaster() throws IOException { - ZksTestnetPaymasterAddress response = zksync.zksGetTestnetPaymaster().send(); - - assertResponse(response); - } - - @Test - public void testGetMainContract() throws IOException { - ZksMainContract response = zksync.zksMainContract().send(); - - assertResponse(response); - } - - - @Test - public void testGetTransactionDetails() throws IOException { - ZksGetTransactionDetails response = zksync.zksGetTransactionDetails("0x0898f4b225276625e1d5d2cc4dc5b7a1acb896daece7e46c8202a47da9a13a27").send(); - - assertResponse(response); - } - - - @Test - public void testGetTransactionByHash() throws IOException { - ZksGetTransactionByHash response = zksync.zksGetTransactionByHash("0xd933be650bf97d92c591a88c993b702b368af5480adf019afddee7e8c1e5ce2e").send(); - - assertResponse(response); - } - - - @Test - public void testGetBlockByHash() throws IOException { - ZksBlock response = zksync.zksGetBlockByHash("0xd933be650bf97d92c591a88c993b702b368af5480adf019afddee7e8c1e5ce2e", true).send(); - - assertResponse(response); - } - - @Test - public void testGetBlockByNumber() throws IOException { - ZksBlock response = zksync.zksGetBlockByNumber(DefaultBlockParameter.valueOf("0xb108e"), true).send(); - - assertResponse(response); - } + assertResponse(response); + } } diff --git a/src/test/java/io/zksync/integration/account/CustomAccountTest.java b/src/test/java/io/zksync/integration/account/CustomAccountTest.java index 6395e05..a9d7266 100644 --- a/src/test/java/io/zksync/integration/account/CustomAccountTest.java +++ b/src/test/java/io/zksync/integration/account/CustomAccountTest.java @@ -1,5 +1,8 @@ package io.zksync.integration.account; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + import io.zksync.abi.TransactionEncoder; import io.zksync.crypto.eip712.Eip712Domain; import io.zksync.crypto.eip712.Eip712Encoder; @@ -9,8 +12,12 @@ import io.zksync.protocol.core.ZkBlockParameterName; import io.zksync.transaction.type.Transaction712; import io.zksync.utils.ContractDeployer; - import io.zksync.utils.ZkSyncAddresses; +import java.io.IOException; +import java.math.BigDecimal; +import java.math.BigInteger; +import java.security.SecureRandom; +import java.util.Collections; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable; @@ -30,198 +37,218 @@ import org.web3j.utils.Convert; import org.web3j.utils.Numeric; -import java.io.IOException; -import java.math.BigDecimal; -import java.math.BigInteger; -import java.security.SecureRandom; -import java.util.Collections; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - @EnabledIfEnvironmentVariables({ - @EnabledIfEnvironmentVariable(named = "ZKSYNC2_JAVA_CI_L1_NODE_URL", matches = "http*"), - @EnabledIfEnvironmentVariable(named = "ZKSYNC2_JAVA_CI_L2_NODE_URL", matches = "http*"), + @EnabledIfEnvironmentVariable(named = "ZKSYNC2_JAVA_CI_L1_NODE_URL", matches = "http*"), + @EnabledIfEnvironmentVariable(named = "ZKSYNC2_JAVA_CI_L2_NODE_URL", matches = "http*"), }) public class CustomAccountTest extends BaseIntegrationEnv { - static final SecureRandom random = new SecureRandom(); - - private String customAccountAddress; - - @BeforeEach - public void prepareBalance() throws IOException { - EthGetBalance getBalance = zksync - .ethGetBalance(credentials.getAddress(), DefaultBlockParameterName.LATEST) - .send(); - assertResponse(getBalance); - if (getBalance.getBalance().compareTo(BigInteger.ZERO) <= 0) { - sendTestMoney(); - deposit(); - } - } - - @Test - public void deployCustomAccount_Create2() throws IOException, TransactionException { - BigInteger nonce = this.zksync - .ethGetTransactionCount(this.credentials.getAddress(), DefaultBlockParameterName.PENDING).send() - .getTransactionCount(); - - String constructor = FunctionEncoder.encodeConstructor(Collections.singletonList(new Bool(false))); - - byte[] salt = random.generateSeed(32); - - String precomputedAddress = ContractDeployer.computeL2Create2Address(new Address(this.credentials.getAddress()), Numeric.hexStringToByteArray(CustomAccountContract.BINARY), Numeric.hexStringToByteArray(constructor), salt).getValue(); - - io.zksync.methods.request.Transaction estimate = io.zksync.methods.request.Transaction.create2AccountTransaction( - credentials.getAddress(), - BigInteger.ZERO, - BigInteger.ZERO, - CustomAccountContract.BINARY, - constructor, - salt - ); - - EthEstimateGas estimateGas = zksync.ethEstimateGas(estimate).send(); - EthGasPrice gasPrice = zksync.ethGasPrice().send(); - - assertResponse(estimateGas); - assertResponse(gasPrice); - - System.out.printf("Fee for transaction is: %d\n", estimateGas.getAmountUsed().multiply(gasPrice.getGasPrice())); - - Transaction712 transaction = new Transaction712( - chainId.longValue(), - nonce, - estimateGas.getAmountUsed(), - estimate.getTo(), - estimate.getValueNumber(), - estimate.getData(), - BigInteger.valueOf(100000000L), - gasPrice.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 = this.zksync.ethSendRawTransaction(Numeric.toHexString(message)).send(); + static final SecureRandom random = new SecureRandom(); - assertResponse(sent); + private String customAccountAddress; - TransactionReceipt receipt = this.processor.waitForTransactionReceipt(sent.getResult()); - - assertTrue(receipt::isStatusOK); - - this.customAccountAddress = receipt.getContractAddress(); - System.out.println("Deployed `CustomAccount as: `" + this.customAccountAddress); - assertEquals(this.customAccountAddress, precomputedAddress); - - Transaction call = Transaction.createEthCallTransaction( - credentials.getAddress(), - customAccountAddress, - FunctionEncoder.encode(CounterContract.encodeGet()) - ); - - zksync.ethCall(call, ZkBlockParameterName.COMMITTED).send(); + @BeforeEach + public void prepareBalance() throws IOException { + EthGetBalance getBalance = + zksync.ethGetBalance(credentials.getAddress(), DefaultBlockParameterName.LATEST).send(); + assertResponse(getBalance); + if (getBalance.getBalance().compareTo(BigInteger.ZERO) <= 0) { + sendTestMoney(); + deposit(); } - - @Test - public void isCustomAccount() { - Function isAccount = new Function("isAccount", Collections.singletonList(new Address(customAccountAddress)), Collections.singletonList(new TypeReference() {})); - - Transaction call = Transaction.createEthCallTransaction( - null, - ZkSyncAddresses.CONTRACT_DEPLOYER_ADDRESS, - FunctionEncoder.encode(isAccount) - ); - - Boolean result = zksync.ethCall(call, ZkBlockParameterName.COMMITTED).sendAsync() - .thenApply((ret) -> FunctionReturnDecoder.decode(ret.getValue(), isAccount.getOutputParameters())) - .thenApply((ret) -> (Boolean) ret.get(0).getValue()) - .join(); - assertTrue(result); - } - - @Test - public void sendMoneyToCustomAccount() throws Exception { - Transfer transfer = new Transfer(zksync, new RawTransactionManager(zksync, credentials, chainId.longValue())); - - EthGasPrice gasPrice = zksync.ethGasPrice().send(); - assertResponse(gasPrice); - - TransactionReceipt receipt = transfer.sendFunds( + } + + @Test + public void deployCustomAccount_Create2() throws IOException, TransactionException { + BigInteger nonce = + this.zksync + .ethGetTransactionCount( + this.credentials.getAddress(), DefaultBlockParameterName.PENDING) + .send() + .getTransactionCount(); + + String constructor = + FunctionEncoder.encodeConstructor(Collections.singletonList(new Bool(false))); + + byte[] salt = random.generateSeed(32); + + String precomputedAddress = + ContractDeployer.computeL2Create2Address( + new Address(this.credentials.getAddress()), + Numeric.hexStringToByteArray(CustomAccountContract.BINARY), + Numeric.hexStringToByteArray(constructor), + salt) + .getValue(); + + io.zksync.methods.request.Transaction estimate = + io.zksync.methods.request.Transaction.create2AccountTransaction( + credentials.getAddress(), + BigInteger.ZERO, + BigInteger.ZERO, + CustomAccountContract.BINARY, + constructor, + salt); + + EthEstimateGas estimateGas = zksync.ethEstimateGas(estimate).send(); + EthGasPrice gasPrice = zksync.ethGasPrice().send(); + + assertResponse(estimateGas); + assertResponse(gasPrice); + + System.out.printf( + "Fee for transaction is: %d\n", + estimateGas.getAmountUsed().multiply(gasPrice.getGasPrice())); + + Transaction712 transaction = + new Transaction712( + chainId.longValue(), + nonce, + estimateGas.getAmountUsed(), + estimate.getTo(), + estimate.getValueNumber(), + estimate.getData(), + BigInteger.valueOf(100000000L), + gasPrice.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 = + this.zksync.ethSendRawTransaction(Numeric.toHexString(message)).send(); + + assertResponse(sent); + + TransactionReceipt receipt = this.processor.waitForTransactionReceipt(sent.getResult()); + + assertTrue(receipt::isStatusOK); + + this.customAccountAddress = receipt.getContractAddress(); + System.out.println("Deployed `CustomAccount as: `" + this.customAccountAddress); + assertEquals(this.customAccountAddress, precomputedAddress); + + Transaction call = + Transaction.createEthCallTransaction( + credentials.getAddress(), + customAccountAddress, + FunctionEncoder.encode(CounterContract.encodeGet())); + + zksync.ethCall(call, ZkBlockParameterName.COMMITTED).send(); + } + + @Test + public void isCustomAccount() { + Function isAccount = + new Function( + "isAccount", + Collections.singletonList(new Address(customAccountAddress)), + Collections.singletonList(new TypeReference() {})); + + Transaction call = + Transaction.createEthCallTransaction( + null, ZkSyncAddresses.CONTRACT_DEPLOYER_ADDRESS, FunctionEncoder.encode(isAccount)); + + Boolean result = + zksync + .ethCall(call, ZkBlockParameterName.COMMITTED) + .sendAsync() + .thenApply( + (ret) -> + FunctionReturnDecoder.decode(ret.getValue(), isAccount.getOutputParameters())) + .thenApply((ret) -> (Boolean) ret.get(0).getValue()) + .join(); + assertTrue(result); + } + + @Test + public void sendMoneyToCustomAccount() throws Exception { + Transfer transfer = + new Transfer(zksync, new RawTransactionManager(zksync, credentials, chainId.longValue())); + + EthGasPrice gasPrice = zksync.ethGasPrice().send(); + assertResponse(gasPrice); + + TransactionReceipt receipt = + transfer + .sendFunds( customAccountAddress, BigDecimal.valueOf(1.1), Convert.Unit.ETHER, gasPrice.getGasPrice(), - BigInteger.valueOf(50_000L) - ).send(); - - assertTrue(receipt::isStatusOK); - } - - @Test - public void accountBalance() throws IOException { - EthGetBalance getBalance = zksync - .ethGetBalance(customAccountAddress, DefaultBlockParameterName.LATEST) - .send(); - - assertResponse(getBalance); - - System.out.printf("%s: %s ETH (%d)\n", customAccountAddress, Convert.fromWei(Numeric.toBigInt(getBalance.getResult()).toString(), Convert.Unit.ETHER), Numeric.toBigInt(getBalance.getResult())); - assertTrue(getBalance.getBalance().compareTo(BigInteger.ZERO) > 0); - } - - @Test - public void transferNative() throws IOException, TransactionException { - BigInteger nonce = zksync - .ethGetTransactionCount(customAccountAddress, ZkBlockParameterName.COMMITTED).send() - .getTransactionCount(); - - io.zksync.methods.request.Transaction estimate = io.zksync.methods.request.Transaction.createFunctionCallTransaction( - customAccountAddress, - credentials.getAddress(), - BigInteger.ZERO, - BigInteger.ZERO, - "0x" - ); - - EthEstimateGas estimateGas = zksync.ethEstimateGas(estimate).send(); - - EthGasPrice gasPrice = zksync.ethGasPrice().send(); - - assertResponse(estimateGas); - assertResponse(gasPrice); - - System.out.printf("Fee for transaction is: %d\n", estimateGas.getAmountUsed().multiply(gasPrice.getGasPrice())); - - Transaction712 transaction = new Transaction712( - chainId.longValue(), - nonce, - estimateGas.getAmountUsed(), - estimate.getTo(), - Convert.toWei(BigDecimal.valueOf(0.5), Convert.Unit.ETHER).toBigInteger(), - estimate.getData(), - BigInteger.valueOf(100000000L), - gasPrice.getGasPrice(), - customAccountAddress, - estimate.getEip712Meta() - ); - - byte[] digest = Eip712Encoder.typedDataToSignedBytes(Eip712Domain.defaultDomain(chainId.longValue()), transaction); - - String signature = Numeric.toHexString(digest) + Numeric.cleanHexPrefix(transaction.getFrom()); - transaction.getMeta().setCustomSignature(Numeric.hexStringToByteArray(signature)); - byte[] message = TransactionEncoder.encode(transaction, null); - - EthSendTransaction sent = zksync.ethSendRawTransaction(Numeric.toHexString(message)).send(); - - assertResponse(sent); - - TransactionReceipt receipt = processor.waitForTransactionReceipt(sent.getResult()); - - assertTrue(receipt::isStatusOK); - } + BigInteger.valueOf(50_000L)) + .send(); + + assertTrue(receipt::isStatusOK); + } + + @Test + public void accountBalance() throws IOException { + EthGetBalance getBalance = + zksync.ethGetBalance(customAccountAddress, DefaultBlockParameterName.LATEST).send(); + + assertResponse(getBalance); + + System.out.printf( + "%s: %s ETH (%d)\n", + customAccountAddress, + Convert.fromWei(Numeric.toBigInt(getBalance.getResult()).toString(), Convert.Unit.ETHER), + Numeric.toBigInt(getBalance.getResult())); + assertTrue(getBalance.getBalance().compareTo(BigInteger.ZERO) > 0); + } + + @Test + public void transferNative() throws IOException, TransactionException { + BigInteger nonce = + zksync + .ethGetTransactionCount(customAccountAddress, ZkBlockParameterName.COMMITTED) + .send() + .getTransactionCount(); + + io.zksync.methods.request.Transaction estimate = + io.zksync.methods.request.Transaction.createFunctionCallTransaction( + customAccountAddress, credentials.getAddress(), BigInteger.ZERO, BigInteger.ZERO, "0x"); + + EthEstimateGas estimateGas = zksync.ethEstimateGas(estimate).send(); + + EthGasPrice gasPrice = zksync.ethGasPrice().send(); + + assertResponse(estimateGas); + assertResponse(gasPrice); + + System.out.printf( + "Fee for transaction is: %d\n", + estimateGas.getAmountUsed().multiply(gasPrice.getGasPrice())); + + Transaction712 transaction = + new Transaction712( + chainId.longValue(), + nonce, + estimateGas.getAmountUsed(), + estimate.getTo(), + Convert.toWei(BigDecimal.valueOf(0.5), Convert.Unit.ETHER).toBigInteger(), + estimate.getData(), + BigInteger.valueOf(100000000L), + gasPrice.getGasPrice(), + customAccountAddress, + estimate.getEip712Meta()); + + byte[] digest = + Eip712Encoder.typedDataToSignedBytes( + Eip712Domain.defaultDomain(chainId.longValue()), transaction); + + String signature = Numeric.toHexString(digest) + Numeric.cleanHexPrefix(transaction.getFrom()); + transaction.getMeta().setCustomSignature(Numeric.hexStringToByteArray(signature)); + byte[] message = TransactionEncoder.encode(transaction, null); + + EthSendTransaction sent = zksync.ethSendRawTransaction(Numeric.toHexString(message)).send(); + + assertResponse(sent); + + TransactionReceipt receipt = processor.waitForTransactionReceipt(sent.getResult()); + + assertTrue(receipt::isStatusOK); + } } diff --git a/src/test/java/io/zksync/integration/paymaster/CustomPaymasterTest.java b/src/test/java/io/zksync/integration/paymaster/CustomPaymasterTest.java index b3ce4d4..91bad24 100644 --- a/src/test/java/io/zksync/integration/paymaster/CustomPaymasterTest.java +++ b/src/test/java/io/zksync/integration/paymaster/CustomPaymasterTest.java @@ -1,5 +1,7 @@ package io.zksync.integration.paymaster; +import static org.junit.jupiter.api.Assertions.*; + import io.zksync.abi.TransactionEncoder; import io.zksync.integration.BaseIntegrationEnv; import io.zksync.methods.request.Eip712Meta; @@ -11,6 +13,11 @@ import io.zksync.transaction.type.Transaction712; import io.zksync.utils.Paymaster; import io.zksync.wrappers.ERC20; +import java.io.ByteArrayOutputStream; +import java.io.FileInputStream; +import java.io.IOException; +import java.math.BigInteger; +import java.nio.charset.Charset; import org.junit.jupiter.api.Assumptions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; @@ -25,230 +32,255 @@ import org.web3j.utils.Convert; import org.web3j.utils.Numeric; -import java.io.ByteArrayOutputStream; -import java.io.FileInputStream; -import java.io.IOException; -import java.math.BigInteger; -import java.nio.charset.Charset; - -import static org.junit.jupiter.api.Assertions.*; - @EnabledIfEnvironmentVariables({ - @EnabledIfEnvironmentVariable(named = "ZKSYNC2_JAVA_CI_L1_NODE_URL", matches = "http*"), - @EnabledIfEnvironmentVariable(named = "ZKSYNC2_JAVA_CI_L2_NODE_URL", matches = "http*"), + @EnabledIfEnvironmentVariable(named = "ZKSYNC2_JAVA_CI_L1_NODE_URL", matches = "http*"), + @EnabledIfEnvironmentVariable(named = "ZKSYNC2_JAVA_CI_L2_NODE_URL", matches = "http*"), }) public class CustomPaymasterTest extends BaseIntegrationEnv { - private static final byte[] SALT = Hash.sha3("TestPaymaster".getBytes(Charset.defaultCharset())); - - private static final Token USDC = new Token("0xd35cceead182dcee0f148ebac9447da2c4d449c4", "0x72c4f199cb8784425542583d345e7c00d642e345", "USDC", 6); - - public static String BINARY; - - @BeforeAll - public static void loadBinary() throws IOException { - try (FileInputStream fis = new FileInputStream("src/test/resources/customPaymasterBinary.hex")) { - ByteArrayOutputStream buffer = new ByteArrayOutputStream(); - - int count; - byte[] bytes = new byte[16536]; - while ((count = fis.read(bytes)) != -1) { - buffer.write(bytes, 0, count); - } - BINARY = buffer.toString("UTF-8"); - } + private static final byte[] SALT = Hash.sha3("TestPaymaster".getBytes(Charset.defaultCharset())); + + private static final Token USDC = + new Token( + "0xd35cceead182dcee0f148ebac9447da2c4d449c4", + "0x72c4f199cb8784425542583d345e7c00d642e345", + "USDC", + 6); + + public static String BINARY; + + @BeforeAll + public static void loadBinary() throws IOException { + try (FileInputStream fis = + new FileInputStream("src/test/resources/customPaymasterBinary.hex")) { + ByteArrayOutputStream buffer = new ByteArrayOutputStream(); + + int count; + byte[] bytes = new byte[16536]; + while ((count = fis.read(bytes)) != -1) { + buffer.write(bytes, 0, count); + } + BINARY = buffer.toString("UTF-8"); } + } - @BeforeEach - public void checkBalance() throws IOException { - EthGetBalance balance = zksync.ethGetBalance(credentials.getAddress(), DefaultBlockParameterName.PENDING).send(); + @BeforeEach + public void checkBalance() throws IOException { + EthGetBalance balance = + zksync.ethGetBalance(credentials.getAddress(), DefaultBlockParameterName.PENDING).send(); - assertResponse(balance); + assertResponse(balance); - if (balance.getBalance().compareTo(Convert.toWei("0.005", Convert.Unit.ETHER).toBigInteger()) <= 0) { - fail("Not enough balance of the wallet (min 0.005 ETH): " + credentials.getAddress()); - } + if (balance.getBalance().compareTo(Convert.toWei("0.005", Convert.Unit.ETHER).toBigInteger()) + <= 0) { + fail("Not enough balance of the wallet (min 0.005 ETH): " + credentials.getAddress()); } + } - @Test - public void deployPaymaster() throws IOException, TransactionException { - Assumptions.assumeFalse(isDeployed(), "Test paymaster already deployed. Skipping"); - BigInteger nonce = this.zksync - .ethGetTransactionCount(this.credentials.getAddress(), DefaultBlockParameterName.PENDING).send() - .getTransactionCount(); + @Test + public void deployPaymaster() throws IOException, TransactionException { + Assumptions.assumeFalse(isDeployed(), "Test paymaster already deployed. Skipping"); + BigInteger nonce = + this.zksync + .ethGetTransactionCount( + this.credentials.getAddress(), DefaultBlockParameterName.PENDING) + .send() + .getTransactionCount(); - String constructor = ""; + String constructor = ""; - String precomputedAddress = paymasterAddress(); + String precomputedAddress = paymasterAddress(); - io.zksync.methods.request.Transaction estimate = io.zksync.methods.request.Transaction.create2ContractTransaction( - credentials.getAddress(), - BigInteger.ZERO, - BigInteger.ZERO, - BINARY, - constructor, - SALT - ); + io.zksync.methods.request.Transaction estimate = + io.zksync.methods.request.Transaction.create2ContractTransaction( + credentials.getAddress(), BigInteger.ZERO, BigInteger.ZERO, BINARY, constructor, SALT); - EthEstimateGas estimateGas = zksync.ethEstimateGas(estimate).send(); - EthGasPrice gasPrice = zksync.ethGasPrice().send(); + EthEstimateGas estimateGas = zksync.ethEstimateGas(estimate).send(); + EthGasPrice gasPrice = zksync.ethGasPrice().send(); - assertResponse(estimateGas); - assertResponse(gasPrice); + assertResponse(estimateGas); + assertResponse(gasPrice); - System.out.printf("Fee for transaction is: %d\n", estimateGas.getAmountUsed().multiply(gasPrice.getGasPrice())); + System.out.printf( + "Fee for transaction is: %d\n", + estimateGas.getAmountUsed().multiply(gasPrice.getGasPrice())); - Transaction712 transaction = new Transaction712( - chainId.longValue(), - nonce, - estimateGas.getAmountUsed(), - estimate.getTo(), - estimate.getValueNumber(), - estimate.getData(), - BigInteger.valueOf(100000000L), - gasPrice.getGasPrice(), - credentials.getAddress(), - estimate.getEip712Meta() - ); + Transaction712 transaction = + new Transaction712( + chainId.longValue(), + nonce, + estimateGas.getAmountUsed(), + estimate.getTo(), + estimate.getValueNumber(), + estimate.getData(), + BigInteger.valueOf(100000000L), + gasPrice.getGasPrice(), + credentials.getAddress(), + estimate.getEip712Meta()); - String signature = signer.getDomain().thenCompose(domain -> signer.signTypedData(domain, transaction)).join(); - byte[] message = TransactionEncoder.encode(transaction, TransactionEncoder.getSignatureData(signature)); + String signature = + signer.getDomain().thenCompose(domain -> signer.signTypedData(domain, transaction)).join(); + byte[] message = + TransactionEncoder.encode(transaction, TransactionEncoder.getSignatureData(signature)); - EthSendTransaction sent = this.zksync.ethSendRawTransaction(Numeric.toHexString(message)).send(); + EthSendTransaction sent = + this.zksync.ethSendRawTransaction(Numeric.toHexString(message)).send(); - assertResponse(sent); + assertResponse(sent); - TransactionReceipt receipt = this.processor.waitForTransactionReceipt(sent.getResult()); + TransactionReceipt receipt = this.processor.waitForTransactionReceipt(sent.getResult()); - assertTrue(receipt::isStatusOK); + assertTrue(receipt::isStatusOK); - System.out.println("Deployed `CustomAccount as: `" + precomputedAddress); - assertEquals(receipt.getContractAddress(), precomputedAddress); - } + System.out.println("Deployed `CustomAccount as: `" + precomputedAddress); + assertEquals(receipt.getContractAddress(), precomputedAddress); + } - @Test - public void sendFundsForFee() throws Exception { - Assumptions.assumeTrue(isDeployed(), "Test paymaster must be deployed. Skipping"); + @Test + public void sendFundsForFee() throws Exception { + Assumptions.assumeTrue(isDeployed(), "Test paymaster must be deployed. Skipping"); - String paymasterAddress = paymasterAddress(); + String paymasterAddress = paymasterAddress(); - io.zksync.methods.request.Transaction estimate = io.zksync.methods.request.Transaction.createFunctionCallTransaction( - credentials.getAddress(), - paymasterAddress, - BigInteger.ZERO, - BigInteger.ZERO, - "0x" - ); + io.zksync.methods.request.Transaction estimate = + io.zksync.methods.request.Transaction.createFunctionCallTransaction( + credentials.getAddress(), paymasterAddress, BigInteger.ZERO, BigInteger.ZERO, "0x"); - EthEstimateGas estimateGas = zksync.ethEstimateGas(estimate).send(); + EthEstimateGas estimateGas = zksync.ethEstimateGas(estimate).send(); - EthGasPrice gasPrice = zksync.ethGasPrice().send(); + EthGasPrice gasPrice = zksync.ethGasPrice().send(); - assertResponse(estimateGas); - assertResponse(gasPrice); + assertResponse(estimateGas); + assertResponse(gasPrice); - BigInteger fee = estimateGas.getAmountUsed().multiply(gasPrice.getGasPrice()); + BigInteger fee = estimateGas.getAmountUsed().multiply(gasPrice.getGasPrice()); - BigInteger balanceInUsdc = wallet.getBalance(USDC).send(); + BigInteger balanceInUsdc = wallet.getBalance(USDC).send(); - assertTrue(balanceInUsdc.compareTo(fee) >= 0, String.format("Not enough balance for pay fee %d (current) < %d (required", balanceInUsdc, fee)); + assertTrue( + balanceInUsdc.compareTo(fee) >= 0, + String.format( + "Not enough balance for pay fee %d (current) < %d (required", balanceInUsdc, fee)); - TransactionReceipt receipt = wallet.transfer(paymasterAddress, fee).send(); + TransactionReceipt receipt = wallet.transfer(paymasterAddress, fee).send(); - assertTrue(receipt::isStatusOK); - } - - @Test - public void sendFundsWithPaymaster() throws Exception { - Assumptions.assumeTrue(isDeployed(), "Test paymaster must be deployed. Skipping"); - - String paymasterAddress = paymasterAddress(); - - io.zksync.methods.request.Transaction estimate = io.zksync.methods.request.Transaction.createFunctionCallTransaction( - credentials.getAddress(), - credentials.getAddress(), - BigInteger.ZERO, - BigInteger.ZERO, - "0x" - ); - - EthEstimateGas estimateGas = zksync.ethEstimateGas(estimate).send(); - - EthGasPrice gasPrice = zksync.ethGasPrice().send(); - - assertResponse(estimateGas); - assertResponse(gasPrice); - - BigInteger fee = gasPrice.getGasPrice().multiply(estimateGas.getAmountUsed()); - - EthGetBalance balance = zksync.ethGetBalance(paymasterAddress, DefaultBlockParameterName.LATEST).send(); - assertResponse(balance); - - Assumptions.assumeTrue(balance.getBalance().compareTo(fee) > 0); + assertTrue(receipt::isStatusOK); + } - ERC20 erc20 = ERC20.load(USDC.getL2Address(), zksync, - new ZkSyncTransactionManager(zksync, signer, feeProvider), - feeProvider); + @Test + public void sendFundsWithPaymaster() throws Exception { + Assumptions.assumeTrue(isDeployed(), "Test paymaster must be deployed. Skipping"); - if (erc20.allowance(credentials.getAddress(), paymasterAddress).send().compareTo(fee) < 0) { - TransactionReceipt approve = erc20.approve(paymasterAddress, fee).send(); + String paymasterAddress = paymasterAddress(); - assertTrue(approve::isStatusOK); - } + io.zksync.methods.request.Transaction estimate = + io.zksync.methods.request.Transaction.createFunctionCallTransaction( + credentials.getAddress(), + credentials.getAddress(), + BigInteger.ZERO, + BigInteger.ZERO, + "0x"); - BigInteger balanceBefore = zksync.ethGetBalance(credentials.getAddress(), DefaultBlockParameterName.PENDING).send().getBalance(); + EthEstimateGas estimateGas = zksync.ethEstimateGas(estimate).send(); - Eip712Meta meta = estimate.getEip712Meta(); + EthGasPrice gasPrice = zksync.ethGasPrice().send(); - PaymasterParams paymasterParams = new PaymasterParams(paymasterAddress, Numeric.hexStringToByteArray(FunctionEncoder.encode(Paymaster.encodeApprovalBased(USDC.getL2Address(), fee, new byte[] {})))); + assertResponse(estimateGas); + assertResponse(gasPrice); - meta.setPaymasterParams(paymasterParams); + BigInteger fee = gasPrice.getGasPrice().multiply(estimateGas.getAmountUsed()); - BigInteger nonce = this.zksync - .ethGetTransactionCount(this.credentials.getAddress(), DefaultBlockParameterName.PENDING).send() - .getTransactionCount(); + EthGetBalance balance = + zksync.ethGetBalance(paymasterAddress, DefaultBlockParameterName.LATEST).send(); + assertResponse(balance); - Transaction712 transaction = new Transaction712( - chainId.longValue(), - nonce, - estimateGas.getAmountUsed(), - estimate.getTo(), - estimate.getValueNumber(), - estimate.getData(), - BigInteger.valueOf(100000000L), - gasPrice.getGasPrice(), - credentials.getAddress(), - meta - ); + Assumptions.assumeTrue(balance.getBalance().compareTo(fee) > 0); - 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(); - - assertResponse(sent); - - TransactionReceipt receipt = processor.waitForTransactionReceipt(sent.getResult()); - - assertTrue(receipt::isStatusOK); - - BigInteger balanceAfter = zksync.ethGetBalance(credentials.getAddress(), DefaultBlockParameterName.PENDING).send().getBalance(); - - assertEquals(balanceBefore, balanceAfter); - } - - private boolean isDeployed() throws IOException { - String paymasterAddress = paymasterAddress(); - EthGetCode code = zksync.ethGetCode(paymasterAddress, ZkBlockParameterName.COMMITTED).send(); - return Numeric.hexStringToByteArray(code.getCode()).length > 0; - } + ERC20 erc20 = + ERC20.load( + USDC.getL2Address(), + zksync, + new ZkSyncTransactionManager(zksync, signer, feeProvider), + feeProvider); - private String paymasterAddress() { -// return ContractDeployer.computeL2Create2Address(new Address(credentials.getAddress()), Numeric.hexStringToByteArray(BINARY), new byte[] {}, SALT).getValue(); - ZksTestnetPaymasterAddress paymasterAddress = zksync.zksGetTestnetPaymaster().sendAsync().join(); + if (erc20.allowance(credentials.getAddress(), paymasterAddress).send().compareTo(fee) < 0) { + TransactionReceipt approve = erc20.approve(paymasterAddress, fee).send(); - assertResponse(paymasterAddress); - return paymasterAddress.getResult(); + assertTrue(approve::isStatusOK); } + BigInteger balanceBefore = + zksync + .ethGetBalance(credentials.getAddress(), DefaultBlockParameterName.PENDING) + .send() + .getBalance(); + + Eip712Meta meta = estimate.getEip712Meta(); + + PaymasterParams paymasterParams = + new PaymasterParams( + paymasterAddress, + Numeric.hexStringToByteArray( + FunctionEncoder.encode( + Paymaster.encodeApprovalBased(USDC.getL2Address(), fee, new byte[] {})))); + + meta.setPaymasterParams(paymasterParams); + + BigInteger nonce = + this.zksync + .ethGetTransactionCount( + this.credentials.getAddress(), DefaultBlockParameterName.PENDING) + .send() + .getTransactionCount(); + + Transaction712 transaction = + new Transaction712( + chainId.longValue(), + nonce, + estimateGas.getAmountUsed(), + estimate.getTo(), + estimate.getValueNumber(), + estimate.getData(), + BigInteger.valueOf(100000000L), + gasPrice.getGasPrice(), + credentials.getAddress(), + meta); + + 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(); + + assertResponse(sent); + + TransactionReceipt receipt = processor.waitForTransactionReceipt(sent.getResult()); + + assertTrue(receipt::isStatusOK); + + BigInteger balanceAfter = + zksync + .ethGetBalance(credentials.getAddress(), DefaultBlockParameterName.PENDING) + .send() + .getBalance(); + + assertEquals(balanceBefore, balanceAfter); + } + + private boolean isDeployed() throws IOException { + String paymasterAddress = paymasterAddress(); + EthGetCode code = zksync.ethGetCode(paymasterAddress, ZkBlockParameterName.COMMITTED).send(); + return Numeric.hexStringToByteArray(code.getCode()).length > 0; + } + + private String paymasterAddress() { + // return ContractDeployer.computeL2Create2Address(new Address(credentials.getAddress()), + // Numeric.hexStringToByteArray(BINARY), new byte[] {}, SALT).getValue(); + ZksTestnetPaymasterAddress paymasterAddress = + zksync.zksGetTestnetPaymaster().sendAsync().join(); + + assertResponse(paymasterAddress); + return paymasterAddress.getResult(); + } } diff --git a/src/test/java/io/zksync/protocol/ZkSyncRequestTest.java b/src/test/java/io/zksync/protocol/ZkSyncRequestTest.java index 136531a..a874abc 100644 --- a/src/test/java/io/zksync/protocol/ZkSyncRequestTest.java +++ b/src/test/java/io/zksync/protocol/ZkSyncRequestTest.java @@ -2,136 +2,141 @@ import io.zksync.helper.CounterContract; import io.zksync.helper.RequestTester; +import java.math.BigInteger; import org.junit.jupiter.api.Test; import org.web3j.protocol.http.HttpService; -import java.math.BigInteger; - class ZkSyncRequestTest extends RequestTester { - private ZkSync zkSync; - - @Override - protected void initWeb3Client(HttpService httpService) { - zkSync = ZkSync.build(httpService); - } - - @Test - void zksEstimateFee() throws Exception { - io.zksync.methods.request.Transaction estimate = io.zksync.methods.request.Transaction.createFunctionCallTransaction( - "0x7e5f4552091a69125d5dfcb7b8c2659029395bdf", - "0x7e5f4552091a69125d5dfcb7b8c2659029395bdf", - BigInteger.ZERO, - BigInteger.ZERO, - "0x" - ); - - zkSync.zksEstimateFee(estimate).send(); - - verifyResult("{\"jsonrpc\":\"2.0\",\"method\":\"zks_estimateFee\",\"params\":[{\"from\":\"0x7e5f4552091a69125d5dfcb7b8c2659029395bdf\",\"to\":\"0x7e5f4552091a69125d5dfcb7b8c2659029395bdf\",\"gas\":\"0x0\",\"gasPrice\":\"0x0\",\"data\":\"0x\",\"transactionType\":\"0x71\",\"eip712Meta\":{\"gasPerPubdata\":\"0x27100\"}}],\"id\":1}"); - } - - @Test - void ethEstimateFee_DeployContract() throws Exception { - io.zksync.methods.request.Transaction estimate = io.zksync.methods.request.Transaction.create2ContractTransaction( - "0x7e5f4552091a69125d5dfcb7b8c2659029395bdf", - BigInteger.ZERO, - BigInteger.ZERO, - CounterContract.BINARY - ); - - zkSync.zksEstimateFee(estimate).send(); - - verifyResult("{\"jsonrpc\":\"2.0\",\"method\":\"zks_estimateFee\",\"params\":[{\"from\":\"0x7e5f4552091a69125d5dfcb7b8c2659029395bdf\",\"to\":\"0x0000000000000000000000000000000000008006\",\"gas\":\"0x0\",\"gasPrice\":\"0x0\",\"data\":\"0x3cda33510000000000000000000000000000000000000000000000000000000000000000010000517112c421df08d7b49e4dc1312f4ee62268ee4f5683b11d9e2d33525a00000000000000000000000000000000000000000000000000000000000000600000000000000000000000000000000000000000000000000000000000000000\",\"transactionType\":\"0x71\",\"eip712Meta\":{\"gasPerPubdata\":\"0x27100\",\"factoryDeps\":[[0,2,0,0,0,0,0,2,0,1,0,0,0,1,3,85,0,0,0,96,1,16,2,112,0,0,0,65,0,16,1,157,0,0,0,1,1,32,1,143,0,0,0,0,1,16,0,76,0,0,0,8,0,0,193,61,0,253,0,24,0,0,4,15,0,253,0,9,0,0,4,15,0,0,0,128,1,0,0,57,0,0,0,64,2,0,0,57,0,0,0,0,0,18,4,53,0,0,0,0,1,0,4,22,0,0,0,0,1,16,0,76,0,0,0,22,0,0,193,61,0,0,0,32,1,0,0,57,0,0,1,0,2,0,0,57,0,0,0,0,0,18,4,57,0,0,1,32,1,0,0,57,0,0,0,0,0,1,4,57,0,0,0,66,1,0,0,65,0,0,0,254,0,1,4,46,0,0,0,0,1,0,0,25,0,0,0,255,0,1,4,48,0,4,0,0,0,0,0,2,0,0,0,0,1,0,4,16,0,0,128,2,2,16,0,140,0,0,0,51,0,0,97,61,0,0,0,0,2,0,4,17,0,0,128,1,2,32,0,140,0,0,0,51,0,0,97,61,0,0,0,67,2,0,0,65,0,0,0,0,0,32,4,57,0,0,0,4,2,0,0,57,0,0,0,0,0,18,4,57,0,0,0,68,1,0,0,65,0,0,128,2,2,0,0,57,0,0,0,0,3,0,4,21,0,0,0,4,3,48,0,138,0,0,0,32,3,48,0,201,0,253,0,224,0,0,4,15,0,0,0,255,1,0,0,57,0,0,0,3,1,16,2,79,0,0,0,0,1,16,0,76,0,0,0,86,0,0,97,61,0,0,0,4,1,0,3,95,0,0,0,0,1,1,4,59,0,0,0,0,1,16,0,76,0,0,0,51,0,0,193,61,0,0,0,0,1,0,0,25,0,0,0,254,0,1,4,46,0,0,0,128,1,0,0,57,0,0,0,64,6,0,0,57,0,0,0,0,0,22,4,53,0,0,0,0,1,0,0,49,0,0,0,3,2,16,0,140,0,0,0,84,0,0,161,61,0,0,0,1,2,0,3,103,0,0,0,0,3,2,4,59,0,0,0,224,3,48,2,112,0,0,0,69,4,48,0,156,0,0,0,108,0,0,97,61,0,0,0,70,2,48,0,156,0,0,0,88,0,0,97,61,0,0,0,71,2,48,0,156,0,0,0,84,0,0,193,61,0,0,0,0,2,0,4,22,0,0,0,0,2,32,0,76,0,0,0,128,0,0,193,61,0,0,0,4,1,16,0,138,0,0,0,72,2,0,0,65,0,0,0,31,3,16,0,140,0,0,0,0,3,0,0,25,0,0,0,0,3,2,32,25,0,0,0,72,1,16,1,151,0,0,0,0,4,16,0,76,0,0,0,0,2,0,128,25,0,0,0,72,1,16,0,156,0,0,0,0,1,3,0,25,0,0,0,0,1,2,96,25,0,0,0,0,1,16,0,76,0,0,0,142,0,0,193,61,0,0,0,0,1,0,0,25,0,0,0,255,0,1,4,48,0,0,0,0,1,0,0,25,0,0,0,255,0,1,4,48,0,0,0,0,1,0,0,25,0,0,0,255,0,1,4,48,0,0,0,0,2,0,4,22,0,0,0,0,2,32,0,76,0,0,0,126,0,0,193,61,0,0,0,4,1,16,0,138,0,0,0,1,2,0,0,138,0,0,0,72,3,0,0,65,0,0,0,0,2,33,0,75,0,0,0,0,2,0,0,25,0,0,0,0,2,3,32,25,0,0,0,72,1,16,1,151,0,0,0,72,4,16,0,156,0,0,0,0,3,0,128,25,0,0,0,72,1,16,1,103,0,0,0,72,1,16,0,156,0,0,0,0,1,2,0,25,0,0,0,0,1,3,96,25,0,0,0,0,1,16,0,76,0,0,0,132,0,0,193,61,0,0,0,0,1,0,0,25,0,0,0,255,0,1,4,48,0,0,0,0,3,0,4,22,0,0,0,0,3,48,0,76,0,0,0,130,0,0,193,61,0,0,0,4,1,16,0,138,0,0,0,72,3,0,0,65,0,0,0,63,4,16,0,140,0,0,0,0,4,0,0,25,0,0,0,0,4,3,32,25,0,0,0,72,1,16,1,151,0,0,0,0,5,16,0,76,0,0,0,0,3,0,128,25,0,0,0,72,1,16,0,156,0,0,0,0,1,4,0,25,0,0,0,0,1,3,96,25,0,0,0,0,1,16,0,76,0,0,0,162,0,0,193,61,0,0,0,0,1,0,0,25,0,0,0,255,0,1,4,48,0,0,0,0,1,0,0,25,0,0,0,255,0,1,4,48,0,0,0,0,1,0,0,25,0,0,0,255,0,1,4,48,0,0,0,0,1,0,0,25,0,0,0,255,0,1,4,48,0,0,0,0,1,0,0,25,0,2,0,0,0,6,0,29,0,253,0,251,0,0,4,15,0,0,0,2,2,0,0,41,0,0,0,0,2,2,4,51,0,0,0,0,0,18,4,53,0,0,0,64,1,32,2,16,0,0,0,73,1,16,1,151,0,0,0,76,1,16,1,199,0,0,0,254,0,1,4,46,0,2,0,0,0,6,0,29,0,0,0,0,1,0,0,25,0,253,0,251,0,0,4,15,0,0,0,1,2,0,3,103,0,0,0,4,2,32,3,112,0,0,0,0,2,2,4,59,0,0,0,0,1,18,0,25,0,0,0,0,2,33,0,75,0,0,0,0,2,0,0,25,0,0,0,1,2,0,64,57,0,0,0,1,2,32,1,143,0,0,0,0,2,32,0,76,0,0,0,190,0,0,97,61,0,0,0,74,1,0,0,65,0,0,0,0,0,16,4,53,0,0,0,17,1,0,0,57,0,0,0,4,2,0,0,57,0,0,0,0,0,18,4,53,0,0,0,75,1,0,0,65,0,0,0,255,0,1,4,48,0,0,0,36,1,32,3,112,0,0,0,0,2,1,4,59,0,0,0,0,1,32,0,76,0,0,0,0,1,0,0,25,0,0,0,1,1,0,192,57,0,0,0,0,1,18,0,75,0,0,0,197,0,0,193,61,0,1,0,0,0,2,0,29,0,2,0,0,0,6,0,29,0,0,0,0,1,0,0,25,0,253,0,251,0,0,4,15,0,0,0,1,2,0,3,103,0,0,0,4,2,32,3,112,0,0,0,0,2,2,4,59,0,0,0,0,1,18,0,25,0,0,0,0,2,33,0,75,0,0,0,0,2,0,0,25,0,0,0,1,2,0,64,57,0,0,0,1,2,32,1,143,0,0,0,0,2,32,0,76,0,0,0,199,0,0,97,61,0,0,0,74,1,0,0,65,0,0,0,0,0,16,4,53,0,0,0,17,1,0,0,57,0,0,0,4,2,0,0,57,0,0,0,0,0,18,4,53,0,0,0,75,1,0,0,65,0,0,0,255,0,1,4,48,0,0,0,0,2,0,0,25,0,253,0,249,0,0,4,15,0,0,0,2,1,0,0,41,0,0,0,0,1,1,4,51,0,0,0,64,1,16,2,16,0,0,0,73,1,16,1,151,0,0,0,254,0,1,4,46,0,0,0,0,1,0,0,25,0,0,0,255,0,1,4,48,0,0,0,0,2,0,0,25,0,253,0,249,0,0,4,15,0,0,0,2,1,0,0,41,0,0,0,0,1,1,4,51,0,0,0,1,2,0,0,41,0,0,0,0,2,32,0,76,0,0,0,209,0,0,193,61,0,0,0,64,1,16,2,16,0,0,0,73,1,16,1,151,0,0,0,254,0,1,4,46,0,0,0,68,2,16,0,57,0,0,0,77,3,0,0,65,0,0,0,0,0,50,4,53,0,0,0,36,2,16,0,57,0,0,0,26,3,0,0,57,0,0,0,0,0,50,4,53,0,0,0,78,2,0,0,65,0,0,0,0,0,33,4,53,0,0,0,4,2,16,0,57,0,0,0,32,3,0,0,57,0,0,0,0,0,50,4,53,0,0,0,64,1,16,2,16,0,0,0,73,1,16,1,151,0,0,0,79,1,16,1,199,0,0,0,255,0,1,4,48,0,2,0,0,0,0,0,2,0,2,0,0,0,3,0,29,0,0,0,32,3,48,0,57,0,1,0,0,0,3,0,29,0,0,0,239,0,33,4,35,0,0,0,2,3,0,0,41,0,0,0,32,2,48,1,26,0,0,0,0,2,1,3,85,0,0,0,72,1,0,0,65,0,0,0,1,2,0,0,41,0,0,0,32,2,32,1,26,0,0,0,0,2,18,1,189,0,0,0,0,1,3,0,25,0,0,0,2,0,0,0,5,0,0,0,0,0,1,4,45,0,0,0,2,3,0,0,41,0,0,0,32,2,48,1,26,0,0,0,0,2,1,3,85,0,0,0,80,1,0,0,65,0,0,0,1,2,0,0,41,0,0,0,32,2,32,1,26,0,0,0,0,2,18,1,141,0,0,0,0,1,3,0,25,0,0,0,2,0,0,0,5,0,0,0,0,0,1,4,45,0,0,0,0,0,18,4,27,0,0,0,0,0,1,4,45,0,0,0,0,1,1,4,26,0,0,0,0,0,1,4,45,0,0,0,253,0,0,4,50,0,0,0,254,0,1,4,46,0,0,0,255,0,1,4,48,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,1,0,0,0,0,0,0,0,0,0,24,6,170,24,150,187,242,101,104,232,132,167,55,75,65,224,2,80,9,98,202,186,106,21,2,58,141,144,232,80,139,131,2,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,36,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,4,54,218,214,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,109,76,230,60,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,124,245,218,176,128,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255,0,0,0,0,0,0,0,0,78,72,123,113,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,36,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,32,0,0,0,0,0,0,0,0,0,0,0,0,84,104,105,115,32,109,101,116,104,111,100,32,97,108,119,97,121,115,32,114,101,118,101,114,116,115,0,0,0,0,0,0,8,195,121,160,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,100,0,0,0,0,0,0,0,0,0,0,0,0,127,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255]]}}],\"id\":1}"); - } - - @Test - void zksMainContract() throws Exception { - zkSync.zksMainContract().send(); - - verifyResult("{\"jsonrpc\":\"2.0\",\"method\":\"zks_getMainContract\",\"params\":[],\"id\":1}"); - } - - @Test - void zksGetConfirmedTokens() throws Exception { - zkSync.zksGetConfirmedTokens(0, (short) 10).send(); - - verifyResult("{\"jsonrpc\":\"2.0\",\"method\":\"zks_getConfirmedTokens\",\"params\":[0,10],\"id\":1}"); - } - - @Test - void zksGetTokenPrice() throws Exception { - zkSync.zksGetTokenPrice("0x0000000000000000000000000000000000000000").send(); - - verifyResult("{\"jsonrpc\":\"2.0\",\"method\":\"zks_getTokenPrice\",\"params\":[\"0x0000000000000000000000000000000000000000\"],\"id\":1}"); - } - - @Test - void zksL1ChainId() throws Exception { - zkSync.zksL1ChainId().send(); - - verifyResult("{\"jsonrpc\":\"2.0\",\"method\":\"zks_L1ChainId\",\"params\":[],\"id\":1}"); - } - - @Test - void zksGetContractDebugInfo() { - } - - @Test - void zksGetTransactionTrace() { - } - - @Test - void zksGetAllAccountBalances() throws Exception { - zkSync.zksGetAllAccountBalances("0x7e5f4552091a69125d5dfcb7b8c2659029395bdf").send(); - - verifyResult("{\"jsonrpc\":\"2.0\",\"method\":\"zks_getAllAccountBalances\",\"params\":[\"0x7e5f4552091a69125d5dfcb7b8c2659029395bdf\"],\"id\":1}"); - } - - @Test - void zksGetBridgeContracts() throws Exception { - zkSync.zksGetBridgeContracts().send(); - - verifyResult("{\"jsonrpc\":\"2.0\",\"method\":\"zks_getBridgeContracts\",\"params\":[],\"id\":1}"); - } - - @Test - void zksGetL2ToL1MsgProof() { - } - - @Test - void ethEstimateGas() throws Exception { - io.zksync.methods.request.Transaction estimate = io.zksync.methods.request.Transaction.createFunctionCallTransaction( - "0x7e5f4552091a69125d5dfcb7b8c2659029395bdf", - "0x7e5f4552091a69125d5dfcb7b8c2659029395bdf", - BigInteger.ZERO, - BigInteger.ZERO, - "0x" - ); - - zkSync.ethEstimateGas(estimate).send(); - - verifyResult("{\"jsonrpc\":\"2.0\",\"method\":\"eth_estimateGas\",\"params\":[{\"from\":\"0x7e5f4552091a69125d5dfcb7b8c2659029395bdf\",\"to\":\"0x7e5f4552091a69125d5dfcb7b8c2659029395bdf\",\"gas\":\"0x0\",\"gasPrice\":\"0x0\",\"data\":\"0x\",\"transactionType\":\"0x71\",\"eip712Meta\":{\"gasPerPubdata\":\"0x27100\"}}],\"id\":1}"); - } - - @Test - void ethEstimateGas_DeployContract() throws Exception { - io.zksync.methods.request.Transaction estimate = io.zksync.methods.request.Transaction.create2ContractTransaction( - "0x7e5f4552091a69125d5dfcb7b8c2659029395bdf", - BigInteger.ZERO, - BigInteger.ZERO, - CounterContract.BINARY - ); - - zkSync.ethEstimateGas(estimate).send(); - - verifyResult("{\"jsonrpc\":\"2.0\",\"method\":\"eth_estimateGas\",\"params\":[{\"from\":\"0x7e5f4552091a69125d5dfcb7b8c2659029395bdf\",\"to\":\"0x0000000000000000000000000000000000008006\",\"gas\":\"0x0\",\"gasPrice\":\"0x0\",\"data\":\"0x3cda33510000000000000000000000000000000000000000000000000000000000000000010000517112c421df08d7b49e4dc1312f4ee62268ee4f5683b11d9e2d33525a00000000000000000000000000000000000000000000000000000000000000600000000000000000000000000000000000000000000000000000000000000000\",\"transactionType\":\"0x71\",\"eip712Meta\":{\"gasPerPubdata\":\"0x27100\",\"factoryDeps\":[[0,2,0,0,0,0,0,2,0,1,0,0,0,1,3,85,0,0,0,96,1,16,2,112,0,0,0,65,0,16,1,157,0,0,0,1,1,32,1,143,0,0,0,0,1,16,0,76,0,0,0,8,0,0,193,61,0,253,0,24,0,0,4,15,0,253,0,9,0,0,4,15,0,0,0,128,1,0,0,57,0,0,0,64,2,0,0,57,0,0,0,0,0,18,4,53,0,0,0,0,1,0,4,22,0,0,0,0,1,16,0,76,0,0,0,22,0,0,193,61,0,0,0,32,1,0,0,57,0,0,1,0,2,0,0,57,0,0,0,0,0,18,4,57,0,0,1,32,1,0,0,57,0,0,0,0,0,1,4,57,0,0,0,66,1,0,0,65,0,0,0,254,0,1,4,46,0,0,0,0,1,0,0,25,0,0,0,255,0,1,4,48,0,4,0,0,0,0,0,2,0,0,0,0,1,0,4,16,0,0,128,2,2,16,0,140,0,0,0,51,0,0,97,61,0,0,0,0,2,0,4,17,0,0,128,1,2,32,0,140,0,0,0,51,0,0,97,61,0,0,0,67,2,0,0,65,0,0,0,0,0,32,4,57,0,0,0,4,2,0,0,57,0,0,0,0,0,18,4,57,0,0,0,68,1,0,0,65,0,0,128,2,2,0,0,57,0,0,0,0,3,0,4,21,0,0,0,4,3,48,0,138,0,0,0,32,3,48,0,201,0,253,0,224,0,0,4,15,0,0,0,255,1,0,0,57,0,0,0,3,1,16,2,79,0,0,0,0,1,16,0,76,0,0,0,86,0,0,97,61,0,0,0,4,1,0,3,95,0,0,0,0,1,1,4,59,0,0,0,0,1,16,0,76,0,0,0,51,0,0,193,61,0,0,0,0,1,0,0,25,0,0,0,254,0,1,4,46,0,0,0,128,1,0,0,57,0,0,0,64,6,0,0,57,0,0,0,0,0,22,4,53,0,0,0,0,1,0,0,49,0,0,0,3,2,16,0,140,0,0,0,84,0,0,161,61,0,0,0,1,2,0,3,103,0,0,0,0,3,2,4,59,0,0,0,224,3,48,2,112,0,0,0,69,4,48,0,156,0,0,0,108,0,0,97,61,0,0,0,70,2,48,0,156,0,0,0,88,0,0,97,61,0,0,0,71,2,48,0,156,0,0,0,84,0,0,193,61,0,0,0,0,2,0,4,22,0,0,0,0,2,32,0,76,0,0,0,128,0,0,193,61,0,0,0,4,1,16,0,138,0,0,0,72,2,0,0,65,0,0,0,31,3,16,0,140,0,0,0,0,3,0,0,25,0,0,0,0,3,2,32,25,0,0,0,72,1,16,1,151,0,0,0,0,4,16,0,76,0,0,0,0,2,0,128,25,0,0,0,72,1,16,0,156,0,0,0,0,1,3,0,25,0,0,0,0,1,2,96,25,0,0,0,0,1,16,0,76,0,0,0,142,0,0,193,61,0,0,0,0,1,0,0,25,0,0,0,255,0,1,4,48,0,0,0,0,1,0,0,25,0,0,0,255,0,1,4,48,0,0,0,0,1,0,0,25,0,0,0,255,0,1,4,48,0,0,0,0,2,0,4,22,0,0,0,0,2,32,0,76,0,0,0,126,0,0,193,61,0,0,0,4,1,16,0,138,0,0,0,1,2,0,0,138,0,0,0,72,3,0,0,65,0,0,0,0,2,33,0,75,0,0,0,0,2,0,0,25,0,0,0,0,2,3,32,25,0,0,0,72,1,16,1,151,0,0,0,72,4,16,0,156,0,0,0,0,3,0,128,25,0,0,0,72,1,16,1,103,0,0,0,72,1,16,0,156,0,0,0,0,1,2,0,25,0,0,0,0,1,3,96,25,0,0,0,0,1,16,0,76,0,0,0,132,0,0,193,61,0,0,0,0,1,0,0,25,0,0,0,255,0,1,4,48,0,0,0,0,3,0,4,22,0,0,0,0,3,48,0,76,0,0,0,130,0,0,193,61,0,0,0,4,1,16,0,138,0,0,0,72,3,0,0,65,0,0,0,63,4,16,0,140,0,0,0,0,4,0,0,25,0,0,0,0,4,3,32,25,0,0,0,72,1,16,1,151,0,0,0,0,5,16,0,76,0,0,0,0,3,0,128,25,0,0,0,72,1,16,0,156,0,0,0,0,1,4,0,25,0,0,0,0,1,3,96,25,0,0,0,0,1,16,0,76,0,0,0,162,0,0,193,61,0,0,0,0,1,0,0,25,0,0,0,255,0,1,4,48,0,0,0,0,1,0,0,25,0,0,0,255,0,1,4,48,0,0,0,0,1,0,0,25,0,0,0,255,0,1,4,48,0,0,0,0,1,0,0,25,0,0,0,255,0,1,4,48,0,0,0,0,1,0,0,25,0,2,0,0,0,6,0,29,0,253,0,251,0,0,4,15,0,0,0,2,2,0,0,41,0,0,0,0,2,2,4,51,0,0,0,0,0,18,4,53,0,0,0,64,1,32,2,16,0,0,0,73,1,16,1,151,0,0,0,76,1,16,1,199,0,0,0,254,0,1,4,46,0,2,0,0,0,6,0,29,0,0,0,0,1,0,0,25,0,253,0,251,0,0,4,15,0,0,0,1,2,0,3,103,0,0,0,4,2,32,3,112,0,0,0,0,2,2,4,59,0,0,0,0,1,18,0,25,0,0,0,0,2,33,0,75,0,0,0,0,2,0,0,25,0,0,0,1,2,0,64,57,0,0,0,1,2,32,1,143,0,0,0,0,2,32,0,76,0,0,0,190,0,0,97,61,0,0,0,74,1,0,0,65,0,0,0,0,0,16,4,53,0,0,0,17,1,0,0,57,0,0,0,4,2,0,0,57,0,0,0,0,0,18,4,53,0,0,0,75,1,0,0,65,0,0,0,255,0,1,4,48,0,0,0,36,1,32,3,112,0,0,0,0,2,1,4,59,0,0,0,0,1,32,0,76,0,0,0,0,1,0,0,25,0,0,0,1,1,0,192,57,0,0,0,0,1,18,0,75,0,0,0,197,0,0,193,61,0,1,0,0,0,2,0,29,0,2,0,0,0,6,0,29,0,0,0,0,1,0,0,25,0,253,0,251,0,0,4,15,0,0,0,1,2,0,3,103,0,0,0,4,2,32,3,112,0,0,0,0,2,2,4,59,0,0,0,0,1,18,0,25,0,0,0,0,2,33,0,75,0,0,0,0,2,0,0,25,0,0,0,1,2,0,64,57,0,0,0,1,2,32,1,143,0,0,0,0,2,32,0,76,0,0,0,199,0,0,97,61,0,0,0,74,1,0,0,65,0,0,0,0,0,16,4,53,0,0,0,17,1,0,0,57,0,0,0,4,2,0,0,57,0,0,0,0,0,18,4,53,0,0,0,75,1,0,0,65,0,0,0,255,0,1,4,48,0,0,0,0,2,0,0,25,0,253,0,249,0,0,4,15,0,0,0,2,1,0,0,41,0,0,0,0,1,1,4,51,0,0,0,64,1,16,2,16,0,0,0,73,1,16,1,151,0,0,0,254,0,1,4,46,0,0,0,0,1,0,0,25,0,0,0,255,0,1,4,48,0,0,0,0,2,0,0,25,0,253,0,249,0,0,4,15,0,0,0,2,1,0,0,41,0,0,0,0,1,1,4,51,0,0,0,1,2,0,0,41,0,0,0,0,2,32,0,76,0,0,0,209,0,0,193,61,0,0,0,64,1,16,2,16,0,0,0,73,1,16,1,151,0,0,0,254,0,1,4,46,0,0,0,68,2,16,0,57,0,0,0,77,3,0,0,65,0,0,0,0,0,50,4,53,0,0,0,36,2,16,0,57,0,0,0,26,3,0,0,57,0,0,0,0,0,50,4,53,0,0,0,78,2,0,0,65,0,0,0,0,0,33,4,53,0,0,0,4,2,16,0,57,0,0,0,32,3,0,0,57,0,0,0,0,0,50,4,53,0,0,0,64,1,16,2,16,0,0,0,73,1,16,1,151,0,0,0,79,1,16,1,199,0,0,0,255,0,1,4,48,0,2,0,0,0,0,0,2,0,2,0,0,0,3,0,29,0,0,0,32,3,48,0,57,0,1,0,0,0,3,0,29,0,0,0,239,0,33,4,35,0,0,0,2,3,0,0,41,0,0,0,32,2,48,1,26,0,0,0,0,2,1,3,85,0,0,0,72,1,0,0,65,0,0,0,1,2,0,0,41,0,0,0,32,2,32,1,26,0,0,0,0,2,18,1,189,0,0,0,0,1,3,0,25,0,0,0,2,0,0,0,5,0,0,0,0,0,1,4,45,0,0,0,2,3,0,0,41,0,0,0,32,2,48,1,26,0,0,0,0,2,1,3,85,0,0,0,80,1,0,0,65,0,0,0,1,2,0,0,41,0,0,0,32,2,32,1,26,0,0,0,0,2,18,1,141,0,0,0,0,1,3,0,25,0,0,0,2,0,0,0,5,0,0,0,0,0,1,4,45,0,0,0,0,0,18,4,27,0,0,0,0,0,1,4,45,0,0,0,0,1,1,4,26,0,0,0,0,0,1,4,45,0,0,0,253,0,0,4,50,0,0,0,254,0,1,4,46,0,0,0,255,0,1,4,48,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,1,0,0,0,0,0,0,0,0,0,24,6,170,24,150,187,242,101,104,232,132,167,55,75,65,224,2,80,9,98,202,186,106,21,2,58,141,144,232,80,139,131,2,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,36,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,4,54,218,214,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,109,76,230,60,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,124,245,218,176,128,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255,0,0,0,0,0,0,0,0,78,72,123,113,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,36,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,32,0,0,0,0,0,0,0,0,0,0,0,0,84,104,105,115,32,109,101,116,104,111,100,32,97,108,119,97,121,115,32,114,101,118,101,114,116,115,0,0,0,0,0,0,8,195,121,160,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,100,0,0,0,0,0,0,0,0,0,0,0,0,127,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255]]}}],\"id\":1}"); - } - - @Test - void zksGetTestnetPaymaster() throws Exception { - zkSync.zksGetTestnetPaymaster().send(); - - verifyResult("{\"jsonrpc\":\"2.0\",\"method\":\"zks_getTestnetPaymaster\",\"params\":[],\"id\":1}"); - } -} \ No newline at end of file + private ZkSync zkSync; + + @Override + protected void initWeb3Client(HttpService httpService) { + zkSync = ZkSync.build(httpService); + } + + @Test + void zksEstimateFee() throws Exception { + io.zksync.methods.request.Transaction estimate = + io.zksync.methods.request.Transaction.createFunctionCallTransaction( + "0x7e5f4552091a69125d5dfcb7b8c2659029395bdf", + "0x7e5f4552091a69125d5dfcb7b8c2659029395bdf", + BigInteger.ZERO, + BigInteger.ZERO, + "0x"); + + zkSync.zksEstimateFee(estimate).send(); + + verifyResult( + "{\"jsonrpc\":\"2.0\",\"method\":\"zks_estimateFee\",\"params\":[{\"from\":\"0x7e5f4552091a69125d5dfcb7b8c2659029395bdf\",\"to\":\"0x7e5f4552091a69125d5dfcb7b8c2659029395bdf\",\"gas\":\"0x0\",\"gasPrice\":\"0x0\",\"data\":\"0x\",\"transactionType\":\"0x71\",\"eip712Meta\":{\"gasPerPubdata\":\"0x27100\"}}],\"id\":1}"); + } + + @Test + void ethEstimateFee_DeployContract() throws Exception { + io.zksync.methods.request.Transaction estimate = + io.zksync.methods.request.Transaction.create2ContractTransaction( + "0x7e5f4552091a69125d5dfcb7b8c2659029395bdf", + BigInteger.ZERO, + BigInteger.ZERO, + CounterContract.BINARY); + + zkSync.zksEstimateFee(estimate).send(); + + verifyResult( + "{\"jsonrpc\":\"2.0\",\"method\":\"zks_estimateFee\",\"params\":[{\"from\":\"0x7e5f4552091a69125d5dfcb7b8c2659029395bdf\",\"to\":\"0x0000000000000000000000000000000000008006\",\"gas\":\"0x0\",\"gasPrice\":\"0x0\",\"data\":\"0x3cda33510000000000000000000000000000000000000000000000000000000000000000010000517112c421df08d7b49e4dc1312f4ee62268ee4f5683b11d9e2d33525a00000000000000000000000000000000000000000000000000000000000000600000000000000000000000000000000000000000000000000000000000000000\",\"transactionType\":\"0x71\",\"eip712Meta\":{\"gasPerPubdata\":\"0x27100\",\"factoryDeps\":[[0,2,0,0,0,0,0,2,0,1,0,0,0,1,3,85,0,0,0,96,1,16,2,112,0,0,0,65,0,16,1,157,0,0,0,1,1,32,1,143,0,0,0,0,1,16,0,76,0,0,0,8,0,0,193,61,0,253,0,24,0,0,4,15,0,253,0,9,0,0,4,15,0,0,0,128,1,0,0,57,0,0,0,64,2,0,0,57,0,0,0,0,0,18,4,53,0,0,0,0,1,0,4,22,0,0,0,0,1,16,0,76,0,0,0,22,0,0,193,61,0,0,0,32,1,0,0,57,0,0,1,0,2,0,0,57,0,0,0,0,0,18,4,57,0,0,1,32,1,0,0,57,0,0,0,0,0,1,4,57,0,0,0,66,1,0,0,65,0,0,0,254,0,1,4,46,0,0,0,0,1,0,0,25,0,0,0,255,0,1,4,48,0,4,0,0,0,0,0,2,0,0,0,0,1,0,4,16,0,0,128,2,2,16,0,140,0,0,0,51,0,0,97,61,0,0,0,0,2,0,4,17,0,0,128,1,2,32,0,140,0,0,0,51,0,0,97,61,0,0,0,67,2,0,0,65,0,0,0,0,0,32,4,57,0,0,0,4,2,0,0,57,0,0,0,0,0,18,4,57,0,0,0,68,1,0,0,65,0,0,128,2,2,0,0,57,0,0,0,0,3,0,4,21,0,0,0,4,3,48,0,138,0,0,0,32,3,48,0,201,0,253,0,224,0,0,4,15,0,0,0,255,1,0,0,57,0,0,0,3,1,16,2,79,0,0,0,0,1,16,0,76,0,0,0,86,0,0,97,61,0,0,0,4,1,0,3,95,0,0,0,0,1,1,4,59,0,0,0,0,1,16,0,76,0,0,0,51,0,0,193,61,0,0,0,0,1,0,0,25,0,0,0,254,0,1,4,46,0,0,0,128,1,0,0,57,0,0,0,64,6,0,0,57,0,0,0,0,0,22,4,53,0,0,0,0,1,0,0,49,0,0,0,3,2,16,0,140,0,0,0,84,0,0,161,61,0,0,0,1,2,0,3,103,0,0,0,0,3,2,4,59,0,0,0,224,3,48,2,112,0,0,0,69,4,48,0,156,0,0,0,108,0,0,97,61,0,0,0,70,2,48,0,156,0,0,0,88,0,0,97,61,0,0,0,71,2,48,0,156,0,0,0,84,0,0,193,61,0,0,0,0,2,0,4,22,0,0,0,0,2,32,0,76,0,0,0,128,0,0,193,61,0,0,0,4,1,16,0,138,0,0,0,72,2,0,0,65,0,0,0,31,3,16,0,140,0,0,0,0,3,0,0,25,0,0,0,0,3,2,32,25,0,0,0,72,1,16,1,151,0,0,0,0,4,16,0,76,0,0,0,0,2,0,128,25,0,0,0,72,1,16,0,156,0,0,0,0,1,3,0,25,0,0,0,0,1,2,96,25,0,0,0,0,1,16,0,76,0,0,0,142,0,0,193,61,0,0,0,0,1,0,0,25,0,0,0,255,0,1,4,48,0,0,0,0,1,0,0,25,0,0,0,255,0,1,4,48,0,0,0,0,1,0,0,25,0,0,0,255,0,1,4,48,0,0,0,0,2,0,4,22,0,0,0,0,2,32,0,76,0,0,0,126,0,0,193,61,0,0,0,4,1,16,0,138,0,0,0,1,2,0,0,138,0,0,0,72,3,0,0,65,0,0,0,0,2,33,0,75,0,0,0,0,2,0,0,25,0,0,0,0,2,3,32,25,0,0,0,72,1,16,1,151,0,0,0,72,4,16,0,156,0,0,0,0,3,0,128,25,0,0,0,72,1,16,1,103,0,0,0,72,1,16,0,156,0,0,0,0,1,2,0,25,0,0,0,0,1,3,96,25,0,0,0,0,1,16,0,76,0,0,0,132,0,0,193,61,0,0,0,0,1,0,0,25,0,0,0,255,0,1,4,48,0,0,0,0,3,0,4,22,0,0,0,0,3,48,0,76,0,0,0,130,0,0,193,61,0,0,0,4,1,16,0,138,0,0,0,72,3,0,0,65,0,0,0,63,4,16,0,140,0,0,0,0,4,0,0,25,0,0,0,0,4,3,32,25,0,0,0,72,1,16,1,151,0,0,0,0,5,16,0,76,0,0,0,0,3,0,128,25,0,0,0,72,1,16,0,156,0,0,0,0,1,4,0,25,0,0,0,0,1,3,96,25,0,0,0,0,1,16,0,76,0,0,0,162,0,0,193,61,0,0,0,0,1,0,0,25,0,0,0,255,0,1,4,48,0,0,0,0,1,0,0,25,0,0,0,255,0,1,4,48,0,0,0,0,1,0,0,25,0,0,0,255,0,1,4,48,0,0,0,0,1,0,0,25,0,0,0,255,0,1,4,48,0,0,0,0,1,0,0,25,0,2,0,0,0,6,0,29,0,253,0,251,0,0,4,15,0,0,0,2,2,0,0,41,0,0,0,0,2,2,4,51,0,0,0,0,0,18,4,53,0,0,0,64,1,32,2,16,0,0,0,73,1,16,1,151,0,0,0,76,1,16,1,199,0,0,0,254,0,1,4,46,0,2,0,0,0,6,0,29,0,0,0,0,1,0,0,25,0,253,0,251,0,0,4,15,0,0,0,1,2,0,3,103,0,0,0,4,2,32,3,112,0,0,0,0,2,2,4,59,0,0,0,0,1,18,0,25,0,0,0,0,2,33,0,75,0,0,0,0,2,0,0,25,0,0,0,1,2,0,64,57,0,0,0,1,2,32,1,143,0,0,0,0,2,32,0,76,0,0,0,190,0,0,97,61,0,0,0,74,1,0,0,65,0,0,0,0,0,16,4,53,0,0,0,17,1,0,0,57,0,0,0,4,2,0,0,57,0,0,0,0,0,18,4,53,0,0,0,75,1,0,0,65,0,0,0,255,0,1,4,48,0,0,0,36,1,32,3,112,0,0,0,0,2,1,4,59,0,0,0,0,1,32,0,76,0,0,0,0,1,0,0,25,0,0,0,1,1,0,192,57,0,0,0,0,1,18,0,75,0,0,0,197,0,0,193,61,0,1,0,0,0,2,0,29,0,2,0,0,0,6,0,29,0,0,0,0,1,0,0,25,0,253,0,251,0,0,4,15,0,0,0,1,2,0,3,103,0,0,0,4,2,32,3,112,0,0,0,0,2,2,4,59,0,0,0,0,1,18,0,25,0,0,0,0,2,33,0,75,0,0,0,0,2,0,0,25,0,0,0,1,2,0,64,57,0,0,0,1,2,32,1,143,0,0,0,0,2,32,0,76,0,0,0,199,0,0,97,61,0,0,0,74,1,0,0,65,0,0,0,0,0,16,4,53,0,0,0,17,1,0,0,57,0,0,0,4,2,0,0,57,0,0,0,0,0,18,4,53,0,0,0,75,1,0,0,65,0,0,0,255,0,1,4,48,0,0,0,0,2,0,0,25,0,253,0,249,0,0,4,15,0,0,0,2,1,0,0,41,0,0,0,0,1,1,4,51,0,0,0,64,1,16,2,16,0,0,0,73,1,16,1,151,0,0,0,254,0,1,4,46,0,0,0,0,1,0,0,25,0,0,0,255,0,1,4,48,0,0,0,0,2,0,0,25,0,253,0,249,0,0,4,15,0,0,0,2,1,0,0,41,0,0,0,0,1,1,4,51,0,0,0,1,2,0,0,41,0,0,0,0,2,32,0,76,0,0,0,209,0,0,193,61,0,0,0,64,1,16,2,16,0,0,0,73,1,16,1,151,0,0,0,254,0,1,4,46,0,0,0,68,2,16,0,57,0,0,0,77,3,0,0,65,0,0,0,0,0,50,4,53,0,0,0,36,2,16,0,57,0,0,0,26,3,0,0,57,0,0,0,0,0,50,4,53,0,0,0,78,2,0,0,65,0,0,0,0,0,33,4,53,0,0,0,4,2,16,0,57,0,0,0,32,3,0,0,57,0,0,0,0,0,50,4,53,0,0,0,64,1,16,2,16,0,0,0,73,1,16,1,151,0,0,0,79,1,16,1,199,0,0,0,255,0,1,4,48,0,2,0,0,0,0,0,2,0,2,0,0,0,3,0,29,0,0,0,32,3,48,0,57,0,1,0,0,0,3,0,29,0,0,0,239,0,33,4,35,0,0,0,2,3,0,0,41,0,0,0,32,2,48,1,26,0,0,0,0,2,1,3,85,0,0,0,72,1,0,0,65,0,0,0,1,2,0,0,41,0,0,0,32,2,32,1,26,0,0,0,0,2,18,1,189,0,0,0,0,1,3,0,25,0,0,0,2,0,0,0,5,0,0,0,0,0,1,4,45,0,0,0,2,3,0,0,41,0,0,0,32,2,48,1,26,0,0,0,0,2,1,3,85,0,0,0,80,1,0,0,65,0,0,0,1,2,0,0,41,0,0,0,32,2,32,1,26,0,0,0,0,2,18,1,141,0,0,0,0,1,3,0,25,0,0,0,2,0,0,0,5,0,0,0,0,0,1,4,45,0,0,0,0,0,18,4,27,0,0,0,0,0,1,4,45,0,0,0,0,1,1,4,26,0,0,0,0,0,1,4,45,0,0,0,253,0,0,4,50,0,0,0,254,0,1,4,46,0,0,0,255,0,1,4,48,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,1,0,0,0,0,0,0,0,0,0,24,6,170,24,150,187,242,101,104,232,132,167,55,75,65,224,2,80,9,98,202,186,106,21,2,58,141,144,232,80,139,131,2,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,36,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,4,54,218,214,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,109,76,230,60,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,124,245,218,176,128,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255,0,0,0,0,0,0,0,0,78,72,123,113,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,36,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,32,0,0,0,0,0,0,0,0,0,0,0,0,84,104,105,115,32,109,101,116,104,111,100,32,97,108,119,97,121,115,32,114,101,118,101,114,116,115,0,0,0,0,0,0,8,195,121,160,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,100,0,0,0,0,0,0,0,0,0,0,0,0,127,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255]]}}],\"id\":1}"); + } + + @Test + void zksMainContract() throws Exception { + zkSync.zksMainContract().send(); + + verifyResult("{\"jsonrpc\":\"2.0\",\"method\":\"zks_getMainContract\",\"params\":[],\"id\":1}"); + } + + @Test + void zksGetConfirmedTokens() throws Exception { + zkSync.zksGetConfirmedTokens(0, (short) 10).send(); + + verifyResult( + "{\"jsonrpc\":\"2.0\",\"method\":\"zks_getConfirmedTokens\",\"params\":[0,10],\"id\":1}"); + } + + @Test + void zksGetTokenPrice() throws Exception { + zkSync.zksGetTokenPrice("0x0000000000000000000000000000000000000000").send(); + + verifyResult( + "{\"jsonrpc\":\"2.0\",\"method\":\"zks_getTokenPrice\",\"params\":[\"0x0000000000000000000000000000000000000000\"],\"id\":1}"); + } + + @Test + void zksL1ChainId() throws Exception { + zkSync.zksL1ChainId().send(); + + verifyResult("{\"jsonrpc\":\"2.0\",\"method\":\"zks_L1ChainId\",\"params\":[],\"id\":1}"); + } + + @Test + void zksGetContractDebugInfo() {} + + @Test + void zksGetTransactionTrace() {} + + @Test + void zksGetAllAccountBalances() throws Exception { + zkSync.zksGetAllAccountBalances("0x7e5f4552091a69125d5dfcb7b8c2659029395bdf").send(); + + verifyResult( + "{\"jsonrpc\":\"2.0\",\"method\":\"zks_getAllAccountBalances\",\"params\":[\"0x7e5f4552091a69125d5dfcb7b8c2659029395bdf\"],\"id\":1}"); + } + + @Test + void zksGetBridgeContracts() throws Exception { + zkSync.zksGetBridgeContracts().send(); + + verifyResult( + "{\"jsonrpc\":\"2.0\",\"method\":\"zks_getBridgeContracts\",\"params\":[],\"id\":1}"); + } + + @Test + void zksGetL2ToL1MsgProof() {} + + @Test + void ethEstimateGas() throws Exception { + io.zksync.methods.request.Transaction estimate = + io.zksync.methods.request.Transaction.createFunctionCallTransaction( + "0x7e5f4552091a69125d5dfcb7b8c2659029395bdf", + "0x7e5f4552091a69125d5dfcb7b8c2659029395bdf", + BigInteger.ZERO, + BigInteger.ZERO, + "0x"); + + zkSync.ethEstimateGas(estimate).send(); + + verifyResult( + "{\"jsonrpc\":\"2.0\",\"method\":\"eth_estimateGas\",\"params\":[{\"from\":\"0x7e5f4552091a69125d5dfcb7b8c2659029395bdf\",\"to\":\"0x7e5f4552091a69125d5dfcb7b8c2659029395bdf\",\"gas\":\"0x0\",\"gasPrice\":\"0x0\",\"data\":\"0x\",\"transactionType\":\"0x71\",\"eip712Meta\":{\"gasPerPubdata\":\"0x27100\"}}],\"id\":1}"); + } + + @Test + void ethEstimateGas_DeployContract() throws Exception { + io.zksync.methods.request.Transaction estimate = + io.zksync.methods.request.Transaction.create2ContractTransaction( + "0x7e5f4552091a69125d5dfcb7b8c2659029395bdf", + BigInteger.ZERO, + BigInteger.ZERO, + CounterContract.BINARY); + + zkSync.ethEstimateGas(estimate).send(); + + verifyResult( + "{\"jsonrpc\":\"2.0\",\"method\":\"eth_estimateGas\",\"params\":[{\"from\":\"0x7e5f4552091a69125d5dfcb7b8c2659029395bdf\",\"to\":\"0x0000000000000000000000000000000000008006\",\"gas\":\"0x0\",\"gasPrice\":\"0x0\",\"data\":\"0x3cda33510000000000000000000000000000000000000000000000000000000000000000010000517112c421df08d7b49e4dc1312f4ee62268ee4f5683b11d9e2d33525a00000000000000000000000000000000000000000000000000000000000000600000000000000000000000000000000000000000000000000000000000000000\",\"transactionType\":\"0x71\",\"eip712Meta\":{\"gasPerPubdata\":\"0x27100\",\"factoryDeps\":[[0,2,0,0,0,0,0,2,0,1,0,0,0,1,3,85,0,0,0,96,1,16,2,112,0,0,0,65,0,16,1,157,0,0,0,1,1,32,1,143,0,0,0,0,1,16,0,76,0,0,0,8,0,0,193,61,0,253,0,24,0,0,4,15,0,253,0,9,0,0,4,15,0,0,0,128,1,0,0,57,0,0,0,64,2,0,0,57,0,0,0,0,0,18,4,53,0,0,0,0,1,0,4,22,0,0,0,0,1,16,0,76,0,0,0,22,0,0,193,61,0,0,0,32,1,0,0,57,0,0,1,0,2,0,0,57,0,0,0,0,0,18,4,57,0,0,1,32,1,0,0,57,0,0,0,0,0,1,4,57,0,0,0,66,1,0,0,65,0,0,0,254,0,1,4,46,0,0,0,0,1,0,0,25,0,0,0,255,0,1,4,48,0,4,0,0,0,0,0,2,0,0,0,0,1,0,4,16,0,0,128,2,2,16,0,140,0,0,0,51,0,0,97,61,0,0,0,0,2,0,4,17,0,0,128,1,2,32,0,140,0,0,0,51,0,0,97,61,0,0,0,67,2,0,0,65,0,0,0,0,0,32,4,57,0,0,0,4,2,0,0,57,0,0,0,0,0,18,4,57,0,0,0,68,1,0,0,65,0,0,128,2,2,0,0,57,0,0,0,0,3,0,4,21,0,0,0,4,3,48,0,138,0,0,0,32,3,48,0,201,0,253,0,224,0,0,4,15,0,0,0,255,1,0,0,57,0,0,0,3,1,16,2,79,0,0,0,0,1,16,0,76,0,0,0,86,0,0,97,61,0,0,0,4,1,0,3,95,0,0,0,0,1,1,4,59,0,0,0,0,1,16,0,76,0,0,0,51,0,0,193,61,0,0,0,0,1,0,0,25,0,0,0,254,0,1,4,46,0,0,0,128,1,0,0,57,0,0,0,64,6,0,0,57,0,0,0,0,0,22,4,53,0,0,0,0,1,0,0,49,0,0,0,3,2,16,0,140,0,0,0,84,0,0,161,61,0,0,0,1,2,0,3,103,0,0,0,0,3,2,4,59,0,0,0,224,3,48,2,112,0,0,0,69,4,48,0,156,0,0,0,108,0,0,97,61,0,0,0,70,2,48,0,156,0,0,0,88,0,0,97,61,0,0,0,71,2,48,0,156,0,0,0,84,0,0,193,61,0,0,0,0,2,0,4,22,0,0,0,0,2,32,0,76,0,0,0,128,0,0,193,61,0,0,0,4,1,16,0,138,0,0,0,72,2,0,0,65,0,0,0,31,3,16,0,140,0,0,0,0,3,0,0,25,0,0,0,0,3,2,32,25,0,0,0,72,1,16,1,151,0,0,0,0,4,16,0,76,0,0,0,0,2,0,128,25,0,0,0,72,1,16,0,156,0,0,0,0,1,3,0,25,0,0,0,0,1,2,96,25,0,0,0,0,1,16,0,76,0,0,0,142,0,0,193,61,0,0,0,0,1,0,0,25,0,0,0,255,0,1,4,48,0,0,0,0,1,0,0,25,0,0,0,255,0,1,4,48,0,0,0,0,1,0,0,25,0,0,0,255,0,1,4,48,0,0,0,0,2,0,4,22,0,0,0,0,2,32,0,76,0,0,0,126,0,0,193,61,0,0,0,4,1,16,0,138,0,0,0,1,2,0,0,138,0,0,0,72,3,0,0,65,0,0,0,0,2,33,0,75,0,0,0,0,2,0,0,25,0,0,0,0,2,3,32,25,0,0,0,72,1,16,1,151,0,0,0,72,4,16,0,156,0,0,0,0,3,0,128,25,0,0,0,72,1,16,1,103,0,0,0,72,1,16,0,156,0,0,0,0,1,2,0,25,0,0,0,0,1,3,96,25,0,0,0,0,1,16,0,76,0,0,0,132,0,0,193,61,0,0,0,0,1,0,0,25,0,0,0,255,0,1,4,48,0,0,0,0,3,0,4,22,0,0,0,0,3,48,0,76,0,0,0,130,0,0,193,61,0,0,0,4,1,16,0,138,0,0,0,72,3,0,0,65,0,0,0,63,4,16,0,140,0,0,0,0,4,0,0,25,0,0,0,0,4,3,32,25,0,0,0,72,1,16,1,151,0,0,0,0,5,16,0,76,0,0,0,0,3,0,128,25,0,0,0,72,1,16,0,156,0,0,0,0,1,4,0,25,0,0,0,0,1,3,96,25,0,0,0,0,1,16,0,76,0,0,0,162,0,0,193,61,0,0,0,0,1,0,0,25,0,0,0,255,0,1,4,48,0,0,0,0,1,0,0,25,0,0,0,255,0,1,4,48,0,0,0,0,1,0,0,25,0,0,0,255,0,1,4,48,0,0,0,0,1,0,0,25,0,0,0,255,0,1,4,48,0,0,0,0,1,0,0,25,0,2,0,0,0,6,0,29,0,253,0,251,0,0,4,15,0,0,0,2,2,0,0,41,0,0,0,0,2,2,4,51,0,0,0,0,0,18,4,53,0,0,0,64,1,32,2,16,0,0,0,73,1,16,1,151,0,0,0,76,1,16,1,199,0,0,0,254,0,1,4,46,0,2,0,0,0,6,0,29,0,0,0,0,1,0,0,25,0,253,0,251,0,0,4,15,0,0,0,1,2,0,3,103,0,0,0,4,2,32,3,112,0,0,0,0,2,2,4,59,0,0,0,0,1,18,0,25,0,0,0,0,2,33,0,75,0,0,0,0,2,0,0,25,0,0,0,1,2,0,64,57,0,0,0,1,2,32,1,143,0,0,0,0,2,32,0,76,0,0,0,190,0,0,97,61,0,0,0,74,1,0,0,65,0,0,0,0,0,16,4,53,0,0,0,17,1,0,0,57,0,0,0,4,2,0,0,57,0,0,0,0,0,18,4,53,0,0,0,75,1,0,0,65,0,0,0,255,0,1,4,48,0,0,0,36,1,32,3,112,0,0,0,0,2,1,4,59,0,0,0,0,1,32,0,76,0,0,0,0,1,0,0,25,0,0,0,1,1,0,192,57,0,0,0,0,1,18,0,75,0,0,0,197,0,0,193,61,0,1,0,0,0,2,0,29,0,2,0,0,0,6,0,29,0,0,0,0,1,0,0,25,0,253,0,251,0,0,4,15,0,0,0,1,2,0,3,103,0,0,0,4,2,32,3,112,0,0,0,0,2,2,4,59,0,0,0,0,1,18,0,25,0,0,0,0,2,33,0,75,0,0,0,0,2,0,0,25,0,0,0,1,2,0,64,57,0,0,0,1,2,32,1,143,0,0,0,0,2,32,0,76,0,0,0,199,0,0,97,61,0,0,0,74,1,0,0,65,0,0,0,0,0,16,4,53,0,0,0,17,1,0,0,57,0,0,0,4,2,0,0,57,0,0,0,0,0,18,4,53,0,0,0,75,1,0,0,65,0,0,0,255,0,1,4,48,0,0,0,0,2,0,0,25,0,253,0,249,0,0,4,15,0,0,0,2,1,0,0,41,0,0,0,0,1,1,4,51,0,0,0,64,1,16,2,16,0,0,0,73,1,16,1,151,0,0,0,254,0,1,4,46,0,0,0,0,1,0,0,25,0,0,0,255,0,1,4,48,0,0,0,0,2,0,0,25,0,253,0,249,0,0,4,15,0,0,0,2,1,0,0,41,0,0,0,0,1,1,4,51,0,0,0,1,2,0,0,41,0,0,0,0,2,32,0,76,0,0,0,209,0,0,193,61,0,0,0,64,1,16,2,16,0,0,0,73,1,16,1,151,0,0,0,254,0,1,4,46,0,0,0,68,2,16,0,57,0,0,0,77,3,0,0,65,0,0,0,0,0,50,4,53,0,0,0,36,2,16,0,57,0,0,0,26,3,0,0,57,0,0,0,0,0,50,4,53,0,0,0,78,2,0,0,65,0,0,0,0,0,33,4,53,0,0,0,4,2,16,0,57,0,0,0,32,3,0,0,57,0,0,0,0,0,50,4,53,0,0,0,64,1,16,2,16,0,0,0,73,1,16,1,151,0,0,0,79,1,16,1,199,0,0,0,255,0,1,4,48,0,2,0,0,0,0,0,2,0,2,0,0,0,3,0,29,0,0,0,32,3,48,0,57,0,1,0,0,0,3,0,29,0,0,0,239,0,33,4,35,0,0,0,2,3,0,0,41,0,0,0,32,2,48,1,26,0,0,0,0,2,1,3,85,0,0,0,72,1,0,0,65,0,0,0,1,2,0,0,41,0,0,0,32,2,32,1,26,0,0,0,0,2,18,1,189,0,0,0,0,1,3,0,25,0,0,0,2,0,0,0,5,0,0,0,0,0,1,4,45,0,0,0,2,3,0,0,41,0,0,0,32,2,48,1,26,0,0,0,0,2,1,3,85,0,0,0,80,1,0,0,65,0,0,0,1,2,0,0,41,0,0,0,32,2,32,1,26,0,0,0,0,2,18,1,141,0,0,0,0,1,3,0,25,0,0,0,2,0,0,0,5,0,0,0,0,0,1,4,45,0,0,0,0,0,18,4,27,0,0,0,0,0,1,4,45,0,0,0,0,1,1,4,26,0,0,0,0,0,1,4,45,0,0,0,253,0,0,4,50,0,0,0,254,0,1,4,46,0,0,0,255,0,1,4,48,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,1,0,0,0,0,0,0,0,0,0,24,6,170,24,150,187,242,101,104,232,132,167,55,75,65,224,2,80,9,98,202,186,106,21,2,58,141,144,232,80,139,131,2,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,36,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,4,54,218,214,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,109,76,230,60,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,124,245,218,176,128,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255,0,0,0,0,0,0,0,0,78,72,123,113,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,36,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,32,0,0,0,0,0,0,0,0,0,0,0,0,84,104,105,115,32,109,101,116,104,111,100,32,97,108,119,97,121,115,32,114,101,118,101,114,116,115,0,0,0,0,0,0,8,195,121,160,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,100,0,0,0,0,0,0,0,0,0,0,0,0,127,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255]]}}],\"id\":1}"); + } + + @Test + void zksGetTestnetPaymaster() throws Exception { + zkSync.zksGetTestnetPaymaster().send(); + + verifyResult( + "{\"jsonrpc\":\"2.0\",\"method\":\"zks_getTestnetPaymaster\",\"params\":[],\"id\":1}"); + } +} diff --git a/src/test/java/io/zksync/protocol/ZkSyncResponseTest.java b/src/test/java/io/zksync/protocol/ZkSyncResponseTest.java index 967bfe0..9717a1f 100644 --- a/src/test/java/io/zksync/protocol/ZkSyncResponseTest.java +++ b/src/test/java/io/zksync/protocol/ZkSyncResponseTest.java @@ -4,128 +4,142 @@ import io.zksync.methods.response.*; import io.zksync.protocol.core.Token; import io.zksync.transaction.fee.Fee; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; -import org.web3j.utils.Numeric; - import java.math.BigInteger; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; +import org.web3j.utils.Numeric; public class ZkSyncResponseTest extends ResponseTester { - @Test - @Disabled - void zksEstimateFee() { - buildResponse("{\"jsonrpc\":\"2.0\",\"result\":{\"gas_limit\":\"0x4be68\",\"gas_per_pubdata_limit\":\"0x27100\",\"max_fee_per_erg\":\"0x5f5e100\",\"max_priority_fee_per_erg\":\"0x5f5e100\"},\"id\":1}"); + @Test + @Disabled + void zksEstimateFee() { + buildResponse( + "{\"jsonrpc\":\"2.0\",\"result\":{\"gas_limit\":\"0x4be68\",\"gas_per_pubdata_limit\":\"0x27100\",\"max_fee_per_erg\":\"0x5f5e100\",\"max_priority_fee_per_erg\":\"0x5f5e100\"},\"id\":1}"); - ZksEstimateFee zksEstimateFee = deserialiseResponse(ZksEstimateFee.class); + ZksEstimateFee zksEstimateFee = deserialiseResponse(ZksEstimateFee.class); - Fee fee = zksEstimateFee.getResult(); - Assertions.assertEquals(BigInteger.valueOf(310888), fee.getGasLimitNumber()); - Assertions.assertEquals(BigInteger.valueOf(100000000), fee.getGasPriceLimitNumber()); - Assertions.assertEquals(BigInteger.valueOf(160000), fee.getGasPerPubdataLimitNumber()); - Assertions.assertEquals(BigInteger.valueOf(100000000), fee.getMaxPriorityFeePerErgNumber()); - } + Fee fee = zksEstimateFee.getResult(); + Assertions.assertEquals(BigInteger.valueOf(310888), fee.getGasLimitNumber()); + Assertions.assertEquals(BigInteger.valueOf(100000000), fee.getGasPriceLimitNumber()); + Assertions.assertEquals(BigInteger.valueOf(160000), fee.getGasPerPubdataLimitNumber()); + Assertions.assertEquals(BigInteger.valueOf(100000000), fee.getMaxPriorityFeePerErgNumber()); + } - @Test - void zksMainContract() { - buildResponse("{\"jsonrpc\":\"2.0\",\"result\":\"0xdbf3be149a9d1aa76870f44670e9db4cfe041766\",\"id\":1}"); + @Test + void zksMainContract() { + buildResponse( + "{\"jsonrpc\":\"2.0\",\"result\":\"0xdbf3be149a9d1aa76870f44670e9db4cfe041766\",\"id\":1}"); - ZksMainContract zksMainContract = deserialiseResponse(ZksMainContract.class); + ZksMainContract zksMainContract = deserialiseResponse(ZksMainContract.class); - Assertions.assertEquals("0xdbf3be149a9d1aa76870f44670e9db4cfe041766", zksMainContract.getResult()); - } + Assertions.assertEquals( + "0xdbf3be149a9d1aa76870f44670e9db4cfe041766", zksMainContract.getResult()); + } - @Test - void zksGetConfirmedTokens() { - buildResponse("{\"jsonrpc\":\"2.0\",\"result\":[{\"decimals\":18,\"l1Address\":\"0x0000000000000000000000000000000000000000\",\"l2Address\":\"0x0000000000000000000000000000000000000000\",\"name\":\"Ether\",\"symbol\":\"ETH\"}],\"id\":1}"); + @Test + void zksGetConfirmedTokens() { + buildResponse( + "{\"jsonrpc\":\"2.0\",\"result\":[{\"decimals\":18,\"l1Address\":\"0x0000000000000000000000000000000000000000\",\"l2Address\":\"0x0000000000000000000000000000000000000000\",\"name\":\"Ether\",\"symbol\":\"ETH\"}],\"id\":1}"); - ZksTokens zksTokens = deserialiseResponse(ZksTokens.class); + ZksTokens zksTokens = deserialiseResponse(ZksTokens.class); - List expected = Collections.singletonList(Token.ETH); + List expected = Collections.singletonList(Token.ETH); - Assertions.assertEquals(expected, zksTokens.getResult()); - } + Assertions.assertEquals(expected, zksTokens.getResult()); + } - @Test - void zksGetTokenPrice() { - buildResponse("{\"jsonrpc\":\"2.0\",\"result\":\"3500.00\",\"id\":1}"); + @Test + void zksGetTokenPrice() { + buildResponse("{\"jsonrpc\":\"2.0\",\"result\":\"3500.00\",\"id\":1}"); - ZksTokenPrice zksTokenPrice = deserialiseResponse(ZksTokenPrice.class); + ZksTokenPrice zksTokenPrice = deserialiseResponse(ZksTokenPrice.class); - Assertions.assertEquals(BigInteger.valueOf(3500), zksTokenPrice.getResult().toBigInteger()); - } + Assertions.assertEquals(BigInteger.valueOf(3500), zksTokenPrice.getResult().toBigInteger()); + } - @Test - void zksL1ChainId() { - buildResponse("{\"jsonrpc\":\"2.0\",\"result\":\"0x9\",\"id\":1}"); + @Test + void zksL1ChainId() { + buildResponse("{\"jsonrpc\":\"2.0\",\"result\":\"0x9\",\"id\":1}"); - ZksL1ChainId zksL1ChainId = deserialiseResponse(ZksL1ChainId.class); + ZksL1ChainId zksL1ChainId = deserialiseResponse(ZksL1ChainId.class); - Assertions.assertEquals(BigInteger.valueOf(9), zksL1ChainId.getChainId()); - } + Assertions.assertEquals(BigInteger.valueOf(9), zksL1ChainId.getChainId()); + } - @Test - void zksGetContractDebugInfo() { - } + @Test + void zksGetContractDebugInfo() {} - @Test - void zksGetTransactionTrace() { - } + @Test + void zksGetTransactionTrace() {} - @Test - void zksGetAllAccountBalances() { - buildResponse("{\"jsonrpc\":\"2.0\",\"result\":{\"0x0000000000000000000000000000000000000000\":\"0xa6886f73b1e\"},\"id\":1}"); + @Test + void zksGetAllAccountBalances() { + buildResponse( + "{\"jsonrpc\":\"2.0\",\"result\":{\"0x0000000000000000000000000000000000000000\":\"0xa6886f73b1e\"},\"id\":1}"); - ZksAccountBalances zksAccountBalances = deserialiseResponse(ZksAccountBalances.class); + ZksAccountBalances zksAccountBalances = deserialiseResponse(ZksAccountBalances.class); - Map expected = new HashMap() {{ + Map expected = + new HashMap() { + { put("0x0000000000000000000000000000000000000000", BigInteger.valueOf(11444057226014L)); - }}; - - Assertions.assertEquals(expected, zksAccountBalances.getBalances()); - } - - @Test - void zksGetBridgeContracts() { - buildResponse("{\"jsonrpc\":\"2.0\",\"result\":{\"l1Erc20DefaultBridge\":\"0x3f92815bec299f152eafa1dc9b1290b307b91cfb\",\"l2Erc20DefaultBridge\":\"0x39971d3297eb5b99d2f1f3ee42a5abecce0b751c\"},\"id\":1}"); - - ZksBridgeAddresses zksBridgeAddresses = deserialiseResponse(ZksBridgeAddresses.class); - - Assertions.assertEquals("0x3f92815bec299f152eafa1dc9b1290b307b91cfb", zksBridgeAddresses.getResult().getL1Erc20DefaultBridge()); - Assertions.assertEquals("0x39971d3297eb5b99d2f1f3ee42a5abecce0b751c", zksBridgeAddresses.getResult().getL2Erc20DefaultBridge()); - } - - @Test - void zksGetL2ToL1MsgProof() { - } - - @Test - void zksGetTestnetPaymaster() { - buildResponse("{\"jsonrpc\":\"2.0\",\"result\":\"0xd8128f25ec5446a89c223d1e546299183bc8b033\",\"id\":1}"); - - ZksTestnetPaymasterAddress zksTestnetPaymasterAddress = deserialiseResponse(ZksTestnetPaymasterAddress.class); - - Assertions.assertEquals("0xd8128f25ec5446a89c223d1e546299183bc8b033", zksTestnetPaymasterAddress.getResult()); - } - - @Test - void zksGetBlock() { - buildResponse("{\"jsonrpc\":\"2.0\",\"result\":{\"baseFeePerGas\":\"0x1dcd6500\",\"difficulty\":\"0x0\",\"extraData\":\"0x\",\"gasLimit\":\"0xffffffff\",\"gasUsed\":\"0x5deb6\",\"hash\":\"0xad7d3b645205e6651e447251f0f649d6d7a191a54e7140a4266e143e0de8e320\",\"l1BatchNumber\":\"0x730\",\"l1BatchTimestamp\":\"0x63eb7ae0\",\"logsBloom\":\"0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\",\"miner\":\"0x0000000000000000000000000000000000000000\",\"mixHash\":\"0x0000000000000000000000000000000000000000000000000000000000000000\",\"nonce\":\"0x0000000000000000\",\"number\":\"0x33450\",\"parentHash\":\"0xe47fa912bd7a769abb076cdf222e4fb643353b3cf4fccbe7b1562ace98bd9b29\",\"receiptsRoot\":\"0x0000000000000000000000000000000000000000000000000000000000000000\",\"sealFields\":[],\"sha3Uncles\":\"0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347\",\"size\":\"0x0\",\"stateRoot\":\"0x0000000000000000000000000000000000000000000000000000000000000000\",\"timestamp\":\"0x63eb7b59\",\"totalDifficulty\":\"0x0\",\"transactions\":[{\"blockHash\":\"0xad7d3b645205e6651e447251f0f649d6d7a191a54e7140a4266e143e0de8e320\",\"blockNumber\":\"0x33450\",\"chainId\":\"0x118\",\"from\":\"0x6b42ba9a6f3249779504fe5f3ee9869e74a185fc\",\"gas\":\"0x5de0b\",\"gasPrice\":\"0x1dcd6500\",\"hash\":\"0xcb7c744f0b0f04008cabd2cbe57ce81c173639df7e9a369140d1dc848518b122\",\"input\":\"0xfefe409d\",\"l1BatchNumber\":\"0x730\",\"l1BatchTxIndex\":\"0x6e\",\"maxFeePerGas\":\"0x1dcd6500\",\"maxPriorityFeePerGas\":\"0x1dcd6500\",\"nonce\":\"0x0\",\"r\":\"0x5a5f5e8ccdf2b105f3c59bd29881ccf8e1fab98ca5ac33a10fcc92be24074b80\",\"s\":\"0x44c5f61fcccca830b983713cc905a3c5bd653c104dd81c3aaf0ba328923f6f74\",\"to\":\"0x07a6ee401cb2c9e4d9c436fa65cfb800715fe6e9\",\"transactionIndex\":\"0x0\",\"type\":\"0x0\",\"v\":\"0x1\",\"value\":\"0x0\"},{\"blockHash\":\"0xad7d3b645205e6651e447251f0f649d6d7a191a54e7140a4266e143e0de8e320\",\"blockNumber\":\"0x33450\",\"chainId\":\"0x118\",\"from\":\"0x7f2a7868bfc7b4ffb3768f5abd1b68e9739cdd2e\",\"gas\":\"0x41448\",\"gasPrice\":\"0x1dcd6500\",\"hash\":\"0xcb75831c4ac88e5aca7437f48a58bfa701ffa6646d0e5495433c19dae543b33e\",\"input\":\"0xa72a241100000000000000000000000034bd12ea642608107ee573e956c3f5c789b6d2c50000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000053887e824808000\",\"l1BatchNumber\":\"0x730\",\"l1BatchTxIndex\":\"0x6f\",\"maxFeePerGas\":\"0x9502f900\",\"maxPriorityFeePerGas\":\"0x59682f00\",\"nonce\":\"0x11a\",\"r\":\"0xab9b8dedb64d2d9034c56245cee55d88ae4e867a05b9a94866dd208bb5a39fd6\",\"s\":\"0x27e447f696d7a2b4635eba277e501bd4c68b2d534c06f30eb1bdadc24b21afbd\",\"to\":\"0x2dd687e37323bd71a3b31b28dc6def2f2addd9b5\",\"transactionIndex\":\"0x1\",\"type\":\"0x2\",\"v\":\"0x0\",\"value\":\"0x0\"}],\"transactionsRoot\":\"0x0000000000000000000000000000000000000000000000000000000000000000\",\"uncles\":[]},\"id\":53}\n"); - - ZksBlock zksBlock = deserialiseResponse(ZksBlock.class); - - Assertions.assertEquals(Numeric.decodeQuantity("0x730"), zksBlock.getResult().getL1BatchNumber()); - Assertions.assertEquals(Numeric.decodeQuantity("0x63eb7ae0"), zksBlock.getResult().getL1BatchTimestamp()); - Assertions.assertEquals(Numeric.decodeQuantity("0x1dcd6500"), zksBlock.getResult().getBaseFeePerGas()); - Assertions.assertEquals("0xe47fa912bd7a769abb076cdf222e4fb643353b3cf4fccbe7b1562ace98bd9b29", zksBlock.getResult().getParentHash()); - - - } - - + } + }; + + Assertions.assertEquals(expected, zksAccountBalances.getBalances()); + } + + @Test + void zksGetBridgeContracts() { + buildResponse( + "{\"jsonrpc\":\"2.0\",\"result\":{\"l1Erc20DefaultBridge\":\"0x3f92815bec299f152eafa1dc9b1290b307b91cfb\",\"l2Erc20DefaultBridge\":\"0x39971d3297eb5b99d2f1f3ee42a5abecce0b751c\"},\"id\":1}"); + + ZksBridgeAddresses zksBridgeAddresses = deserialiseResponse(ZksBridgeAddresses.class); + + Assertions.assertEquals( + "0x3f92815bec299f152eafa1dc9b1290b307b91cfb", + zksBridgeAddresses.getResult().getL1Erc20DefaultBridge()); + Assertions.assertEquals( + "0x39971d3297eb5b99d2f1f3ee42a5abecce0b751c", + zksBridgeAddresses.getResult().getL2Erc20DefaultBridge()); + } + + @Test + void zksGetL2ToL1MsgProof() {} + + @Test + void zksGetTestnetPaymaster() { + buildResponse( + "{\"jsonrpc\":\"2.0\",\"result\":\"0xd8128f25ec5446a89c223d1e546299183bc8b033\",\"id\":1}"); + + ZksTestnetPaymasterAddress zksTestnetPaymasterAddress = + deserialiseResponse(ZksTestnetPaymasterAddress.class); + + Assertions.assertEquals( + "0xd8128f25ec5446a89c223d1e546299183bc8b033", zksTestnetPaymasterAddress.getResult()); + } + + @Test + void zksGetBlock() { + buildResponse( + "{\"jsonrpc\":\"2.0\",\"result\":{\"baseFeePerGas\":\"0x1dcd6500\",\"difficulty\":\"0x0\",\"extraData\":\"0x\",\"gasLimit\":\"0xffffffff\",\"gasUsed\":\"0x5deb6\",\"hash\":\"0xad7d3b645205e6651e447251f0f649d6d7a191a54e7140a4266e143e0de8e320\",\"l1BatchNumber\":\"0x730\",\"l1BatchTimestamp\":\"0x63eb7ae0\",\"logsBloom\":\"0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\",\"miner\":\"0x0000000000000000000000000000000000000000\",\"mixHash\":\"0x0000000000000000000000000000000000000000000000000000000000000000\",\"nonce\":\"0x0000000000000000\",\"number\":\"0x33450\",\"parentHash\":\"0xe47fa912bd7a769abb076cdf222e4fb643353b3cf4fccbe7b1562ace98bd9b29\",\"receiptsRoot\":\"0x0000000000000000000000000000000000000000000000000000000000000000\",\"sealFields\":[],\"sha3Uncles\":\"0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347\",\"size\":\"0x0\",\"stateRoot\":\"0x0000000000000000000000000000000000000000000000000000000000000000\",\"timestamp\":\"0x63eb7b59\",\"totalDifficulty\":\"0x0\",\"transactions\":[{\"blockHash\":\"0xad7d3b645205e6651e447251f0f649d6d7a191a54e7140a4266e143e0de8e320\",\"blockNumber\":\"0x33450\",\"chainId\":\"0x118\",\"from\":\"0x6b42ba9a6f3249779504fe5f3ee9869e74a185fc\",\"gas\":\"0x5de0b\",\"gasPrice\":\"0x1dcd6500\",\"hash\":\"0xcb7c744f0b0f04008cabd2cbe57ce81c173639df7e9a369140d1dc848518b122\",\"input\":\"0xfefe409d\",\"l1BatchNumber\":\"0x730\",\"l1BatchTxIndex\":\"0x6e\",\"maxFeePerGas\":\"0x1dcd6500\",\"maxPriorityFeePerGas\":\"0x1dcd6500\",\"nonce\":\"0x0\",\"r\":\"0x5a5f5e8ccdf2b105f3c59bd29881ccf8e1fab98ca5ac33a10fcc92be24074b80\",\"s\":\"0x44c5f61fcccca830b983713cc905a3c5bd653c104dd81c3aaf0ba328923f6f74\",\"to\":\"0x07a6ee401cb2c9e4d9c436fa65cfb800715fe6e9\",\"transactionIndex\":\"0x0\",\"type\":\"0x0\",\"v\":\"0x1\",\"value\":\"0x0\"},{\"blockHash\":\"0xad7d3b645205e6651e447251f0f649d6d7a191a54e7140a4266e143e0de8e320\",\"blockNumber\":\"0x33450\",\"chainId\":\"0x118\",\"from\":\"0x7f2a7868bfc7b4ffb3768f5abd1b68e9739cdd2e\",\"gas\":\"0x41448\",\"gasPrice\":\"0x1dcd6500\",\"hash\":\"0xcb75831c4ac88e5aca7437f48a58bfa701ffa6646d0e5495433c19dae543b33e\",\"input\":\"0xa72a241100000000000000000000000034bd12ea642608107ee573e956c3f5c789b6d2c50000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000053887e824808000\",\"l1BatchNumber\":\"0x730\",\"l1BatchTxIndex\":\"0x6f\",\"maxFeePerGas\":\"0x9502f900\",\"maxPriorityFeePerGas\":\"0x59682f00\",\"nonce\":\"0x11a\",\"r\":\"0xab9b8dedb64d2d9034c56245cee55d88ae4e867a05b9a94866dd208bb5a39fd6\",\"s\":\"0x27e447f696d7a2b4635eba277e501bd4c68b2d534c06f30eb1bdadc24b21afbd\",\"to\":\"0x2dd687e37323bd71a3b31b28dc6def2f2addd9b5\",\"transactionIndex\":\"0x1\",\"type\":\"0x2\",\"v\":\"0x0\",\"value\":\"0x0\"}],\"transactionsRoot\":\"0x0000000000000000000000000000000000000000000000000000000000000000\",\"uncles\":[]},\"id\":53}\n"); + + ZksBlock zksBlock = deserialiseResponse(ZksBlock.class); + + Assertions.assertEquals( + Numeric.decodeQuantity("0x730"), zksBlock.getResult().getL1BatchNumber()); + Assertions.assertEquals( + Numeric.decodeQuantity("0x63eb7ae0"), zksBlock.getResult().getL1BatchTimestamp()); + Assertions.assertEquals( + Numeric.decodeQuantity("0x1dcd6500"), zksBlock.getResult().getBaseFeePerGas()); + Assertions.assertEquals( + "0xe47fa912bd7a769abb076cdf222e4fb643353b3cf4fccbe7b1562ace98bd9b29", + zksBlock.getResult().getParentHash()); + } } diff --git a/src/test/java/io/zksync/transaction/BaseTransactionTest.java b/src/test/java/io/zksync/transaction/BaseTransactionTest.java index 4c3f094..a421ef7 100644 --- a/src/test/java/io/zksync/transaction/BaseTransactionTest.java +++ b/src/test/java/io/zksync/transaction/BaseTransactionTest.java @@ -2,22 +2,13 @@ import static org.junit.jupiter.api.Assertions.*; +import io.zksync.protocol.core.Token; import java.math.BigInteger; -import java.util.Iterator; - -import io.zksync.transaction.fee.Fee; -import org.apache.commons.lang3.tuple.Pair; -import org.web3j.abi.datatypes.Address; -import org.web3j.abi.datatypes.Type; -import org.web3j.abi.datatypes.generated.Uint256; -import org.web3j.abi.datatypes.generated.Uint32; import org.web3j.crypto.Credentials; import org.web3j.crypto.ECKeyPair; -import io.zksync.protocol.core.Token; - public class BaseTransactionTest { - protected static final Token FEE_TOKEN = Token.createETH(); - protected static final Credentials SENDER = Credentials.create(ECKeyPair.create(BigInteger.ONE)); - protected static final Integer NONCE = 42; + protected static final Token FEE_TOKEN = Token.createETH(); + protected static final Credentials SENDER = Credentials.create(ECKeyPair.create(BigInteger.ONE)); + protected static final Integer NONCE = 42; } diff --git a/src/test/java/io/zksync/transaction/Transaction712Test.java b/src/test/java/io/zksync/transaction/Transaction712Test.java index c62cd83..1977659 100644 --- a/src/test/java/io/zksync/transaction/Transaction712Test.java +++ b/src/test/java/io/zksync/transaction/Transaction712Test.java @@ -1,5 +1,7 @@ package io.zksync.transaction; +import static org.junit.jupiter.api.Assertions.assertEquals; + import io.zksync.crypto.eip712.Eip712Domain; import io.zksync.crypto.eip712.Eip712Encoder; import io.zksync.methods.request.Eip712Meta; @@ -7,73 +9,73 @@ import io.zksync.protocol.core.Token; import io.zksync.protocol.core.ZkSyncNetwork; import io.zksync.transaction.type.Transaction712; +import java.math.BigInteger; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.web3j.utils.Numeric; -import java.math.BigInteger; - -import static org.junit.jupiter.api.Assertions.assertEquals; - public class Transaction712Test extends BaseTransactionTest { - private static final Token FEE = BaseTransactionTest.FEE_TOKEN; - private static final String SENDER = "0x7e5f4552091a69125d5dfcb7b8c2659029395bdf"; - private static final String RECEIVER = "0x000102030405060708090a0b0c0d0e0f10111213"; - private static final BigInteger VALUE = new BigInteger(Numeric.hexStringToByteArray("0x1")); - private static final BigInteger GAS_PRICE = new BigInteger(Numeric.hexStringToByteArray("0xee6b280")); - private static final BigInteger GAS_LIMIT = new BigInteger(Numeric.hexStringToByteArray("0x1ece8d")); - private static final BigInteger MAX_PRIORITY_FEE_PER_GAS = new BigInteger(Numeric.hexStringToByteArray("0x0")); - + private static final Token FEE = BaseTransactionTest.FEE_TOKEN; + private static final String SENDER = "0x7e5f4552091a69125d5dfcb7b8c2659029395bdf"; + private static final String RECEIVER = "0x000102030405060708090a0b0c0d0e0f10111213"; + private static final BigInteger VALUE = new BigInteger(Numeric.hexStringToByteArray("0x1")); + private static final BigInteger GAS_PRICE = + new BigInteger(Numeric.hexStringToByteArray("0xee6b280")); + private static final BigInteger GAS_LIMIT = + new BigInteger(Numeric.hexStringToByteArray("0x1ece8d")); + private static final BigInteger MAX_PRIORITY_FEE_PER_GAS = + new BigInteger(Numeric.hexStringToByteArray("0x0")); - @Test - public void testEncodeToEIP712TypeString() { - Transaction712 transactionRequest = buildTransaction(); - String result = Eip712Encoder.encodeType(transactionRequest.intoEip712Struct()); + @Test + public void testEncodeToEIP712TypeString() { + Transaction712 transactionRequest = buildTransaction(); + String result = Eip712Encoder.encodeType(transactionRequest.intoEip712Struct()); - assertEquals( - "Transaction(uint256 txType,uint256 from,uint256 to,uint256 gasLimit,uint256 gasPerPubdataByteLimit,uint256 maxFeePerGas,uint256 maxPriorityFeePerGas,uint256 paymaster,uint256 nonce,uint256 value,bytes data,bytes32[] factoryDeps,bytes paymasterInput)", - result); - } + assertEquals( + "Transaction(uint256 txType,uint256 from,uint256 to,uint256 gasLimit,uint256 gasPerPubdataByteLimit,uint256 maxFeePerGas,uint256 maxPriorityFeePerGas,uint256 paymaster,uint256 nonce,uint256 value,bytes data,bytes32[] factoryDeps,bytes paymasterInput)", + result); + } - @Test - @Disabled - public void testSerializeToEIP712EncodedValue() { - Transaction712 transactionRequest = buildTransaction(); - byte[] encoded = Eip712Encoder.encodeValue(transactionRequest.intoEip712Struct()).getValue(); + @Test + @Disabled + public void testSerializeToEIP712EncodedValue() { + Transaction712 transactionRequest = buildTransaction(); + byte[] encoded = Eip712Encoder.encodeValue(transactionRequest.intoEip712Struct()).getValue(); - assertEquals("0x2360af215549f2e44413f5a6eb25ecf40590c231e24a70b23a942f995814dc77", - Numeric.toHexString(encoded)); - } + assertEquals( + "0x2360af215549f2e44413f5a6eb25ecf40590c231e24a70b23a942f995814dc77", + Numeric.toHexString(encoded)); + } - @Test - @Disabled - public void testSerializeToEIP712Message() { - Transaction712 transactionRequest = buildTransaction(); - byte[] encoded = Eip712Encoder.typedDataToSignedBytes(Eip712Domain.defaultDomain(ZkSyncNetwork.Localhost), - transactionRequest); + @Test + @Disabled + public void testSerializeToEIP712Message() { + Transaction712 transactionRequest = buildTransaction(); + byte[] encoded = + Eip712Encoder.typedDataToSignedBytes( + Eip712Domain.defaultDomain(ZkSyncNetwork.Localhost), transactionRequest); - assertEquals("0x2506074540188226a81a8dc006ab311c06b680232d39699d348e8ec83c81388b", - Numeric.toHexString(encoded)); - } + assertEquals( + "0x2506074540188226a81a8dc006ab311c06b680232d39699d348e8ec83c81388b", + Numeric.toHexString(encoded)); + } - private Transaction712 buildTransaction() { - return new Transaction712( - 280, - GAS_LIMIT, - new BigInteger(Numeric.hexStringToByteArray("0x1ece8d")), - RECEIVER, - VALUE, - "0x", - MAX_PRIORITY_FEE_PER_GAS, - GAS_PRICE, - SENDER, - new Eip712Meta( - new BigInteger(Numeric.hexStringToByteArray("0x1bb1")), - null, - null, - new PaymasterParams() - ) - ); - } + private Transaction712 buildTransaction() { + return new Transaction712( + 280, + GAS_LIMIT, + new BigInteger(Numeric.hexStringToByteArray("0x1ece8d")), + RECEIVER, + VALUE, + "0x", + MAX_PRIORITY_FEE_PER_GAS, + GAS_PRICE, + SENDER, + new Eip712Meta( + new BigInteger(Numeric.hexStringToByteArray("0x1bb1")), + null, + null, + new PaymasterParams())); + } } diff --git a/src/test/java/io/zksync/utils/ContractDeployerTest.java b/src/test/java/io/zksync/utils/ContractDeployerTest.java index 86bfb56..8584402 100644 --- a/src/test/java/io/zksync/utils/ContractDeployerTest.java +++ b/src/test/java/io/zksync/utils/ContractDeployerTest.java @@ -1,41 +1,48 @@ package io.zksync.utils; import io.zksync.helper.CounterContract; +import java.math.BigInteger; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.web3j.abi.datatypes.Address; import org.web3j.utils.Numeric; -import java.math.BigInteger; - public class ContractDeployerTest { - @Test - public void computeL2Create2AddressActual() { - String expected = "0x0790aff699b38f40929840469a72fb40e9763716"; - byte[] salt = new byte[32]; + @Test + public void computeL2Create2AddressActual() { + String expected = "0x0790aff699b38f40929840469a72fb40e9763716"; + byte[] salt = new byte[32]; - Address result = ContractDeployer.computeL2Create2Address(new Address("0xa909312acfc0ed4370b8bd20dfe41c8ff6595194"), Numeric.hexStringToByteArray(CounterContract.BINARY), new byte[] {}, salt); + Address result = + ContractDeployer.computeL2Create2Address( + new Address("0xa909312acfc0ed4370b8bd20dfe41c8ff6595194"), + Numeric.hexStringToByteArray(CounterContract.BINARY), + new byte[] {}, + salt); - Assertions.assertEquals(expected, result.getValue()); - } + Assertions.assertEquals(expected, result.getValue()); + } - @Test - public void computeL2CreateAddressActual() { - String expected = "0x5107b7154dfc1d3b7f1c4e19b5087e1d3393bcf4"; + @Test + public void computeL2CreateAddressActual() { + String expected = "0x5107b7154dfc1d3b7f1c4e19b5087e1d3393bcf4"; - Address result = ContractDeployer.computeL2CreateAddress(new Address("0x7e5f4552091a69125d5dfcb7b8c2659029395bdf"), BigInteger.valueOf(3)); + Address result = + ContractDeployer.computeL2CreateAddress( + new Address("0x7e5f4552091a69125d5dfcb7b8c2659029395bdf"), BigInteger.valueOf(3)); - Assertions.assertEquals(expected, result.getValue()); - } + Assertions.assertEquals(expected, result.getValue()); + } - @Test - public void hashBytecode() { - String expected = "0x010000517112c421df08d7b49e4dc1312f4ee62268ee4f5683b11d9e2d33525a"; + @Test + public void hashBytecode() { + String expected = "0x010000517112c421df08d7b49e4dc1312f4ee62268ee4f5683b11d9e2d33525a"; - byte[] result = ContractDeployer.hashBytecode(Numeric.hexStringToByteArray(CounterContract.BINARY)); - String resultHex = Numeric.toHexString(result); + byte[] result = + ContractDeployer.hashBytecode(Numeric.hexStringToByteArray(CounterContract.BINARY)); + String resultHex = Numeric.toHexString(result); - Assertions.assertEquals(expected, resultHex); - } -} \ No newline at end of file + Assertions.assertEquals(expected, resultHex); + } +} diff --git a/src/test/java/io/zksync/utils/MessengerTest.java b/src/test/java/io/zksync/utils/MessengerTest.java index ae96a91..0dd22ee 100644 --- a/src/test/java/io/zksync/utils/MessengerTest.java +++ b/src/test/java/io/zksync/utils/MessengerTest.java @@ -1,81 +1,79 @@ package io.zksync.utils; import io.zksync.protocol.core.L2ToL1MessageProof; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; import org.apache.commons.lang3.ArrayUtils; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; -import org.web3j.abi.EventEncoder; -import org.web3j.abi.TypeReference; import org.web3j.abi.datatypes.Address; -import org.web3j.abi.datatypes.Event; -import org.web3j.abi.datatypes.generated.Uint256; import org.web3j.crypto.Hash; import org.web3j.utils.Numeric; -import java.math.BigInteger; -import java.nio.charset.StandardCharsets; -import java.util.Arrays; - class MessengerTest { - @Test - void getHashedMessage() { - L2ToL1MessageProof proof = new L2ToL1MessageProof( - Arrays.asList("0x59ac0de84b4fe20a122ef45ef667d1ebd0b7f1dbba6c3b0580d1446e98616578", - "0xc3d03eebfd83049991ea3d3e358b6712e7aa2e2e63dc2d4b438987cec28ac8d0", - "0xe3697c7f33c31a9b0f0aeb8542287d0d21e8c4cf82163d0c44c7a98aa11aa111", - "0x199cc5812543ddceeddd0fc82807646a4899444240db2c0d2f20c3cceb5f51fa", - "0xe4733f281f18ba3ea8775dd62d2fcd84011c8c938f16ea5790fd29a03bf8db89", - "0x1798a1fd9c8fbb818c98cff190daa7cc10b6e5ac9716b4a2649f7c2ebcef2272", - "0x66d7c5983afe44cf15ea8cf565b34c6c31ff0cb4dd744524f7842b942d08770d", - "0xb04e5ee349086985f74b73971ce9dfe76bbed95c84906c5dffd96504e1e5396c"), - 1, - "0x35e7dfc84dc8d27ce2015f1243280f42a9e7bb00c465fa2156081dadc26403ed" - ); - - Address sender = new Address("0x7f0a50087b9426a9787c0ee458315ba73352ff74"); - byte[] message = "Some L2->L1 message".getBytes(StandardCharsets.UTF_8); - BigInteger txNumber = BigInteger.ZERO; + @Test + void getHashedMessage() { + L2ToL1MessageProof proof = + new L2ToL1MessageProof( + Arrays.asList( + "0x59ac0de84b4fe20a122ef45ef667d1ebd0b7f1dbba6c3b0580d1446e98616578", + "0xc3d03eebfd83049991ea3d3e358b6712e7aa2e2e63dc2d4b438987cec28ac8d0", + "0xe3697c7f33c31a9b0f0aeb8542287d0d21e8c4cf82163d0c44c7a98aa11aa111", + "0x199cc5812543ddceeddd0fc82807646a4899444240db2c0d2f20c3cceb5f51fa", + "0xe4733f281f18ba3ea8775dd62d2fcd84011c8c938f16ea5790fd29a03bf8db89", + "0x1798a1fd9c8fbb818c98cff190daa7cc10b6e5ac9716b4a2649f7c2ebcef2272", + "0x66d7c5983afe44cf15ea8cf565b34c6c31ff0cb4dd744524f7842b942d08770d", + "0xb04e5ee349086985f74b73971ce9dfe76bbed95c84906c5dffd96504e1e5396c"), + 1, + "0x35e7dfc84dc8d27ce2015f1243280f42a9e7bb00c465fa2156081dadc26403ed"); - byte[] result = Messenger.getHashedMessage(sender, message, txNumber); + Address sender = new Address("0x7f0a50087b9426a9787c0ee458315ba73352ff74"); + byte[] message = "Some L2->L1 message".getBytes(StandardCharsets.UTF_8); + BigInteger txNumber = BigInteger.ZERO; - int id = proof.getId(); + byte[] result = Messenger.getHashedMessage(sender, message, txNumber); - for (String e : proof.getProof()) { - byte[] bytes = (id & 1) == 0 ? - ArrayUtils.addAll(result, Numeric.hexStringToByteArray(e)) : - ArrayUtils.addAll(Numeric.hexStringToByteArray(e), result); + int id = proof.getId(); - result = Hash.sha3(bytes); - id /= 2; - } + for (String e : proof.getProof()) { + byte[] bytes = + (id & 1) == 0 + ? ArrayUtils.addAll(result, Numeric.hexStringToByteArray(e)) + : ArrayUtils.addAll(Numeric.hexStringToByteArray(e), result); - Assertions.assertArrayEquals(Numeric.hexStringToByteArray(proof.getRoot()), result); + result = Hash.sha3(bytes); + id /= 2; } - @Test - void verifyMessage() { - L2ToL1MessageProof proof = new L2ToL1MessageProof( - Arrays.asList("0x59ac0de84b4fe20a122ef45ef667d1ebd0b7f1dbba6c3b0580d1446e98616578", - "0xc3d03eebfd83049991ea3d3e358b6712e7aa2e2e63dc2d4b438987cec28ac8d0", - "0xe3697c7f33c31a9b0f0aeb8542287d0d21e8c4cf82163d0c44c7a98aa11aa111", - "0x199cc5812543ddceeddd0fc82807646a4899444240db2c0d2f20c3cceb5f51fa", - "0xe4733f281f18ba3ea8775dd62d2fcd84011c8c938f16ea5790fd29a03bf8db89", - "0x1798a1fd9c8fbb818c98cff190daa7cc10b6e5ac9716b4a2649f7c2ebcef2272", - "0x66d7c5983afe44cf15ea8cf565b34c6c31ff0cb4dd744524f7842b942d08770d", - "0xb04e5ee349086985f74b73971ce9dfe76bbed95c84906c5dffd96504e1e5396c"), - 1, - "0x35e7dfc84dc8d27ce2015f1243280f42a9e7bb00c465fa2156081dadc26403ed" - ); + Assertions.assertArrayEquals(Numeric.hexStringToByteArray(proof.getRoot()), result); + } - Address sender = new Address("0x7f0a50087b9426a9787c0ee458315ba73352ff74"); - byte[] message = "Some L2->L1 message".getBytes(StandardCharsets.UTF_8); - BigInteger txNumber = BigInteger.ZERO; + @Test + void verifyMessage() { + L2ToL1MessageProof proof = + new L2ToL1MessageProof( + Arrays.asList( + "0x59ac0de84b4fe20a122ef45ef667d1ebd0b7f1dbba6c3b0580d1446e98616578", + "0xc3d03eebfd83049991ea3d3e358b6712e7aa2e2e63dc2d4b438987cec28ac8d0", + "0xe3697c7f33c31a9b0f0aeb8542287d0d21e8c4cf82163d0c44c7a98aa11aa111", + "0x199cc5812543ddceeddd0fc82807646a4899444240db2c0d2f20c3cceb5f51fa", + "0xe4733f281f18ba3ea8775dd62d2fcd84011c8c938f16ea5790fd29a03bf8db89", + "0x1798a1fd9c8fbb818c98cff190daa7cc10b6e5ac9716b4a2649f7c2ebcef2272", + "0x66d7c5983afe44cf15ea8cf565b34c6c31ff0cb4dd744524f7842b942d08770d", + "0xb04e5ee349086985f74b73971ce9dfe76bbed95c84906c5dffd96504e1e5396c"), + 1, + "0x35e7dfc84dc8d27ce2015f1243280f42a9e7bb00c465fa2156081dadc26403ed"); - byte[] hashedMessage = Messenger.getHashedMessage(sender, message, txNumber); + Address sender = new Address("0x7f0a50087b9426a9787c0ee458315ba73352ff74"); + byte[] message = "Some L2->L1 message".getBytes(StandardCharsets.UTF_8); + BigInteger txNumber = BigInteger.ZERO; - boolean result = Messenger.verifyMessage(proof, hashedMessage); + byte[] hashedMessage = Messenger.getHashedMessage(sender, message, txNumber); - Assertions.assertTrue(result); - } -} \ No newline at end of file + boolean result = Messenger.verifyMessage(proof, hashedMessage); + + Assertions.assertTrue(result); + } +}