├── .github └── workflows │ ├── release.yaml │ └── test.yaml ├── .gitignore ├── README.md ├── build.gradle ├── gradlew ├── gradlew.bat └── src ├── main └── java │ └── io │ └── zksync │ ├── domain │ ├── ChainId.java │ ├── Signature.java │ ├── TimeRange.java │ ├── TransactionBuildHelper.java │ ├── auth │ │ ├── ChangePubKeyAuthType.java │ │ ├── ChangePubKeyCREATE2.java │ │ ├── ChangePubKeyECDSA.java │ │ ├── ChangePubKeyOnchain.java │ │ ├── ChangePubKeyVariant.java │ │ └── Toggle2FA.java │ ├── block │ │ └── BlockInfo.java │ ├── contract │ │ └── ContractAddress.java │ ├── fee │ │ ├── TransactionFee.java │ │ ├── TransactionFeeBatchRequest.java │ │ ├── TransactionFeeDetails.java │ │ ├── TransactionFeeRequest.java │ │ └── TransactionType.java │ ├── operation │ │ └── EthOpInfo.java │ ├── state │ │ ├── AccountState.java │ │ ├── DepositingBalance.java │ │ ├── DepositingState.java │ │ └── State.java │ ├── swap │ │ └── Order.java │ ├── token │ │ ├── NFT.java │ │ ├── Token.java │ │ ├── TokenId.java │ │ └── Tokens.java │ └── transaction │ │ ├── ChangePubKey.java │ │ ├── ForcedExit.java │ │ ├── MintNFT.java │ │ ├── Swap.java │ │ ├── TransactionDetails.java │ │ ├── Transfer.java │ │ ├── Withdraw.java │ │ ├── WithdrawNFT.java │ │ └── ZkSyncTransaction.java │ ├── ethereum │ ├── DefaultEthereumProvider.java │ ├── EthereumProvider.java │ ├── transaction │ │ └── NoOpTransactionManager.java │ └── wrappers │ │ ├── ERC20.java │ │ ├── IEIP1271.java │ │ └── ZkSync.java │ ├── exception │ ├── ZkSyncException.java │ └── ZkSyncIncorrectCredentialsException.java │ ├── provider │ ├── AsyncProvider.java │ ├── DefaultAsyncProvider.java │ ├── DefaultProvider.java │ └── Provider.java │ ├── signer │ ├── Bits.java │ ├── Create2EthSigner.java │ ├── DefaultEthSigner.java │ ├── EthSignature.java │ ├── EthSigner.java │ ├── SigningUtils.java │ └── ZkSigner.java │ ├── transport │ ├── HttpTransport.java │ ├── ZkSyncError.java │ ├── ZkSyncRequest.java │ ├── ZkSyncResponse.java │ ├── ZkSyncSuccess.java │ ├── ZkSyncTransport.java │ ├── ZkTransactionStatus.java │ ├── receipt │ │ ├── ZkSyncPollingTransactionReceiptProcessor.java │ │ └── ZkSyncTransactionReceiptProcessor.java │ └── response │ │ ├── ZksAccountState.java │ │ ├── ZksContractAddress.java │ │ ├── ZksEthOpInfo.java │ │ ├── ZksGetConfirmationsForEthOpAmount.java │ │ ├── ZksSentTransaction.java │ │ ├── ZksSentTransactionBatch.java │ │ ├── ZksToggle2FA.java │ │ ├── ZksTokenPrice.java │ │ ├── ZksTokens.java │ │ ├── ZksTransactionDetails.java │ │ └── ZksTransactionFeeDetails.java │ └── wallet │ ├── DefaultZkASyncWallet.java │ ├── DefaultZkSyncWallet.java │ ├── SignedTransaction.java │ ├── ZkASyncWallet.java │ └── ZkSyncWallet.java └── test └── java └── io └── zksync ├── IntegrationTestCreate2ShortFlow.java ├── IntegrationTestFullFlow.java ├── IntegrationTestTransactionReceiptProcessor.java ├── signer └── ZkSignerTest.java └── wallet └── DefaultZkSyncWalletTest.java /.github/workflows/release.yaml: -------------------------------------------------------------------------------- 1 | name: Release Java library 2 | 3 | on: 4 | push: 5 | tags: 6 | - "v*" 7 | 8 | env: 9 | GITHUB_REF: "${{ github.ref }}" 10 | 11 | jobs: 12 | build_and_publish: 13 | name: Build jar library 14 | runs-on: ubuntu-latest 15 | steps: 16 | - name: Query app version number 17 | id: get_version 18 | shell: bash 19 | run: | 20 | echo "using app version ${GITHUB_REF:11}" 21 | echo ::set-output name=app::"${GITHUB_REF:11}" 22 | - uses: actions/checkout@v2 23 | - name: Set up JDK 13 24 | uses: actions/setup-java@v1 25 | with: 26 | java-version: 13 27 | - name: Build with Gradle 28 | run: gradle build 29 | env: 30 | VERSION: ${{ steps.get_version.outputs.APP }} 31 | - name: Publish package 32 | run: gradle clean build sign publish 33 | env: 34 | VERSION: ${{ steps.get_version.outputs.APP }} 35 | ORG_GRADLE_PROJECT_signingKey: ${{ secrets.GPG_PRIVATE_KEY }} 36 | ORG_GRADLE_PROJECT_signingPassword: ${{ secrets.PASSPHRASE }} 37 | ORG_GRADLE_PROJECT_sonatypeUsername: ${{ secrets.OSSRH_USERNAME }} 38 | ORG_GRADLE_PROJECT_sonatypePassword: ${{ secrets.OSSRH_TOKEN }} 39 | -------------------------------------------------------------------------------- /.github/workflows/test.yaml: -------------------------------------------------------------------------------- 1 | name: Test Java SDK library 2 | 3 | on: 4 | pull_request: 5 | branches: 6 | - master 7 | push: 8 | branches: 9 | - develop 10 | 11 | jobs: 12 | test: 13 | name: Test java project 14 | runs-on: ubuntu-latest 15 | steps: 16 | - uses: actions/checkout@v2 17 | - name: Set up JDK 8 18 | uses: actions/setup-java@v1 19 | with: 20 | java-version: 1.8 21 | - name: Test with Gradle 22 | run: gradle clean test 23 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled class file 2 | *.class 3 | 4 | # Log file 5 | *.log 6 | 7 | # BlueJ files 8 | *.ctxt 9 | 10 | # Mobile Tools for Java (J2ME) 11 | .mtj.tmp/ 12 | 13 | # Package Files # 14 | *.jar 15 | *.war 16 | *.nar 17 | *.ear 18 | *.zip 19 | *.tar.gz 20 | *.rar 21 | 22 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 23 | hs_err_pid* 24 | 25 | .vscode 26 | .gradle 27 | build 28 | .DS_Store 29 | .settings 30 | gradle.properties 31 | gradle 32 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # zkSync Java SDK 2 | 3 | [![Live on Mainnet](https://img.shields.io/badge/wallet-Live%20on%20Mainnet-blue)](https://wallet.zksync.io) 4 | [![Live on Rinkeby](https://img.shields.io/badge/wallet-Live%20on%20Rinkeby-blue)](https://rinkeby.zksync.io) 5 | [![Live on Ropsten](https://img.shields.io/badge/wallet-Live%20on%20Ropsten-blue)](https://ropsten.zksync.io) 6 | [![Join the technical discussion chat at https://gitter.im/matter-labs/zksync](https://badges.gitter.im/matter-labs/zksync.svg)](https://gitter.im/matter-labs/zksync?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) 7 | 8 | This repository provides a Java SDK for zkSync developers, which can be used either on PC or Android. 9 | Presented to you with ❤️ by [Matter Labs](https://matter-labs.io/) and [Argent](https://www.argent.xyz/). 10 | 11 | ## What is zkSync 12 | 13 | zkSync is a scaling and privacy engine for Ethereum. Its current functionality scope includes low gas transfers of ETH 14 | and ERC20 tokens in the Ethereum network. 15 | zkSync is built on ZK Rollup architecture. ZK Rollup is an L2 scaling solution in which all funds are held by a smart 16 | contract on the mainchain, while computation and storage are performed off-chain. For every Rollup block, a state 17 | transition zero-knowledge proof (SNARK) is generated and verified by the mainchain contract. This SNARK includes the 18 | proof of the validity of every single transaction in the Rollup block. 19 | Additionally, the public data update for every block is published over the mainchain network in the cheap calldata. 20 | This architecture provides the following guarantees: 21 | 22 | - The Rollup validator(s) can never corrupt the state or steal funds (unlike Sidechains). 23 | - Users can always retrieve the funds from the Rollup even if validator(s) stop cooperating because the data is available (unlike Plasma). 24 | - Thanks to validity proofs, neither users nor a single other trusted party needs to be online to monitor Rollup blocks in order to prevent fraud. 25 | In other words, ZK Rollup strictly inherits the security guarantees of the underlying L1. 26 | 27 | To learn how to use zkSync, please refer to the [zkSync SDK documentation](https://www.zksync.io/). 28 | 29 | ## License 30 | 31 | zkSync Java SDK is distributed under the terms of the MIT license. 32 | See [LICENSE](LICENSE) for details. 33 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'java-library' 3 | id 'maven-publish' 4 | id 'signing' 5 | } 6 | 7 | group = 'io.zksync' 8 | version System.getenv('VERSION') 9 | sourceCompatibility = '1.8' 10 | 11 | configurations { 12 | compileOnly { 13 | extendsFrom annotationProcessor 14 | } 15 | } 16 | 17 | repositories { 18 | mavenCentral() 19 | } 20 | 21 | java { 22 | withJavadocJar() 23 | withSourcesJar() 24 | } 25 | 26 | publishing { 27 | publications { 28 | mavenJava(MavenPublication) { 29 | artifactId = 'zksync' 30 | from components.java 31 | versionMapping { 32 | usage('java-api') { 33 | fromResolutionOf('runtimeClasspath') 34 | } 35 | usage('java-runtime') { 36 | fromResolutionResult() 37 | } 38 | } 39 | pom { 40 | name = 'ZkSync SDK' 41 | description = 'This repository provides a Java SDK for zkSync developers, which can be used either on PC or Android.' 42 | url = 'https://github.com/zksync-sdk/zksync-java' 43 | organization { 44 | name = 'Matter Labs' 45 | url = 'https://matter-labs.io' 46 | } 47 | licenses { 48 | license { 49 | name = 'MIT License' 50 | url = 'https://www.mit.edu/~amini/LICENSE.md' 51 | } 52 | } 53 | developers { 54 | developer { 55 | id = 'mfischuk' 56 | name = 'Maxim Fischuk' 57 | email = 'mfischuk@vareger.com' 58 | } 59 | } 60 | scm { 61 | connection = 'scm:git:git://github.com/zksync-sdk/zksync-java' 62 | url = 'https://github.com/zksync-sdk/zksync-java' 63 | } 64 | } 65 | } 66 | } 67 | repositories { 68 | maven { 69 | def releasesRepoUrl = "https://oss.sonatype.org/service/local/staging/deploy/maven2/" 70 | def snapshotsRepoUrl = "https://oss.sonatype.org/content/repositories/snapshots" 71 | url = version.endsWith('SNAPSHOT') ? snapshotsRepoUrl : releasesRepoUrl 72 | credentials { 73 | username findProperty("sonatypeUsername") 74 | password findProperty("sonatypePassword") 75 | } 76 | } 77 | } 78 | } 79 | 80 | 81 | signing { 82 | def signingKeyId = findProperty("signingKeyId") 83 | def signingKey = findProperty("signingKey") 84 | def signingPassword = findProperty("signingPassword") 85 | useInMemoryPgpKeys(signingKeyId, signingKey, signingPassword) 86 | sign publishing.publications.mavenJava 87 | } 88 | 89 | dependencies { 90 | 91 | // === Code Generation === 92 | compileOnly 'org.projectlombok:lombok:1.18.20' 93 | annotationProcessor 'org.projectlombok:lombok:1.18.20' 94 | 95 | // === DTO === 96 | implementation('org.modelmapper:modelmapper:1.1.0') 97 | 98 | // === Utils === 99 | implementation('org.apache.commons:commons-lang3:3.7') 100 | implementation('commons-validator:commons-validator:1.6') 101 | implementation('org.jsoup:jsoup:1.11.3') 102 | 103 | // === Http Client === 104 | implementation 'com.squareup.okhttp3:okhttp:4.8.0' 105 | 106 | // === Web3 client === 107 | implementation 'org.web3j:core:5.0.0' 108 | 109 | // === For Eth Signing === 110 | implementation 'org.web3j:crypto:5.0.0' 111 | 112 | // === For Zk Signing === 113 | implementation 'io.zksync.sdk:zkscrypto:0.0.5.5' 114 | implementation 'net.java.dev.jna:jna:5.6.0' 115 | implementation 'org.scijava:native-lib-loader:2.3.4' 116 | 117 | // === Test dependencies === 118 | testImplementation 'junit:junit:4.13.1' 119 | testImplementation "org.mockito:mockito-inline:+" 120 | testImplementation 'org.junit.jupiter:junit-jupiter-api:5.6.2' 121 | } 122 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | # 4 | # Copyright 2015 the original author or authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | ## 21 | ## Gradle start up script for UN*X 22 | ## 23 | ############################################################################## 24 | 25 | # Attempt to set APP_HOME 26 | # Resolve links: $0 may be a link 27 | PRG="$0" 28 | # Need this for relative symlinks. 29 | while [ -h "$PRG" ] ; do 30 | ls=`ls -ld "$PRG"` 31 | link=`expr "$ls" : '.*-> \(.*\)$'` 32 | if expr "$link" : '/.*' > /dev/null; then 33 | PRG="$link" 34 | else 35 | PRG=`dirname "$PRG"`"/$link" 36 | fi 37 | done 38 | SAVED="`pwd`" 39 | cd "`dirname \"$PRG\"`/" >/dev/null 40 | APP_HOME="`pwd -P`" 41 | cd "$SAVED" >/dev/null 42 | 43 | APP_NAME="Gradle" 44 | APP_BASE_NAME=`basename "$0"` 45 | 46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 48 | 49 | # Use the maximum available, or set MAX_FD != -1 to use that value. 50 | MAX_FD="maximum" 51 | 52 | warn () { 53 | echo "$*" 54 | } 55 | 56 | die () { 57 | echo 58 | echo "$*" 59 | echo 60 | exit 1 61 | } 62 | 63 | # OS specific support (must be 'true' or 'false'). 64 | cygwin=false 65 | msys=false 66 | darwin=false 67 | nonstop=false 68 | case "`uname`" in 69 | CYGWIN* ) 70 | cygwin=true 71 | ;; 72 | Darwin* ) 73 | darwin=true 74 | ;; 75 | MINGW* ) 76 | msys=true 77 | ;; 78 | NONSTOP* ) 79 | nonstop=true 80 | ;; 81 | esac 82 | 83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 84 | 85 | 86 | # Determine the Java command to use to start the JVM. 87 | if [ -n "$JAVA_HOME" ] ; then 88 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 89 | # IBM's JDK on AIX uses strange locations for the executables 90 | JAVACMD="$JAVA_HOME/jre/sh/java" 91 | else 92 | JAVACMD="$JAVA_HOME/bin/java" 93 | fi 94 | if [ ! -x "$JAVACMD" ] ; then 95 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 96 | 97 | Please set the JAVA_HOME variable in your environment to match the 98 | location of your Java installation." 99 | fi 100 | else 101 | JAVACMD="java" 102 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 103 | 104 | Please set the JAVA_HOME variable in your environment to match the 105 | location of your Java installation." 106 | fi 107 | 108 | # Increase the maximum file descriptors if we can. 109 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 110 | MAX_FD_LIMIT=`ulimit -H -n` 111 | if [ $? -eq 0 ] ; then 112 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 113 | MAX_FD="$MAX_FD_LIMIT" 114 | fi 115 | ulimit -n $MAX_FD 116 | if [ $? -ne 0 ] ; then 117 | warn "Could not set maximum file descriptor limit: $MAX_FD" 118 | fi 119 | else 120 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 121 | fi 122 | fi 123 | 124 | # For Darwin, add options to specify how the application appears in the dock 125 | if $darwin; then 126 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 127 | fi 128 | 129 | # For Cygwin or MSYS, switch paths to Windows format before running java 130 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then 131 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 132 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 133 | 134 | JAVACMD=`cygpath --unix "$JAVACMD"` 135 | 136 | # We build the pattern for arguments to be converted via cygpath 137 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 138 | SEP="" 139 | for dir in $ROOTDIRSRAW ; do 140 | ROOTDIRS="$ROOTDIRS$SEP$dir" 141 | SEP="|" 142 | done 143 | OURCYGPATTERN="(^($ROOTDIRS))" 144 | # Add a user-defined pattern to the cygpath arguments 145 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 146 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 147 | fi 148 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 149 | i=0 150 | for arg in "$@" ; do 151 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 152 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 153 | 154 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 155 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 156 | else 157 | eval `echo args$i`="\"$arg\"" 158 | fi 159 | i=`expr $i + 1` 160 | done 161 | case $i in 162 | 0) set -- ;; 163 | 1) set -- "$args0" ;; 164 | 2) set -- "$args0" "$args1" ;; 165 | 3) set -- "$args0" "$args1" "$args2" ;; 166 | 4) set -- "$args0" "$args1" "$args2" "$args3" ;; 167 | 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 168 | 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 169 | 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 170 | 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 171 | 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 172 | esac 173 | fi 174 | 175 | # Escape application args 176 | save () { 177 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 178 | echo " " 179 | } 180 | APP_ARGS=`save "$@"` 181 | 182 | # Collect all arguments for the java command, following the shell quoting and substitution rules 183 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 184 | 185 | exec "$JAVACMD" "$@" 186 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if "%ERRORLEVEL%" == "0" goto execute 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto execute 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :execute 68 | @rem Setup the command line 69 | 70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 71 | 72 | 73 | @rem Execute Gradle 74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 75 | 76 | :end 77 | @rem End local scope for the variables with windows NT shell 78 | if "%ERRORLEVEL%"=="0" goto mainEnd 79 | 80 | :fail 81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 82 | rem the _cmd.exe /c_ return code! 83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 84 | exit /b 1 85 | 86 | :mainEnd 87 | if "%OS%"=="Windows_NT" endlocal 88 | 89 | :omega 90 | -------------------------------------------------------------------------------- /src/main/java/io/zksync/domain/ChainId.java: -------------------------------------------------------------------------------- 1 | package io.zksync.domain; 2 | 3 | import lombok.Getter; 4 | 5 | @Getter 6 | public enum ChainId { 7 | /// Ethereum Mainnet. 8 | Mainnet(1), 9 | /// Ethereum Rinkeby testnet. 10 | Rinkeby(4), 11 | /// Ethereum Ropsten testnet. 12 | Ropsten(3), 13 | /// Goerli Testnet 14 | Goerli(5), 15 | /// Ethereum Sepolia Testnet 16 | Sepolia(11155111), 17 | 18 | /// Self-hosted Ethereum & zkSync networks. 19 | Localhost(9); 20 | 21 | private final long id; 22 | 23 | ChainId(long id) { 24 | this.id = id; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/io/zksync/domain/Signature.java: -------------------------------------------------------------------------------- 1 | package io.zksync.domain; 2 | 3 | import lombok.Builder; 4 | import lombok.EqualsAndHashCode; 5 | import lombok.Getter; 6 | import lombok.ToString; 7 | 8 | @Getter 9 | @ToString 10 | @EqualsAndHashCode 11 | @Builder 12 | public class Signature { 13 | 14 | String pubKey; 15 | 16 | String signature; 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/io/zksync/domain/TimeRange.java: -------------------------------------------------------------------------------- 1 | package io.zksync.domain; 2 | 3 | import lombok.AllArgsConstructor; 4 | import lombok.Data; 5 | 6 | @Data 7 | @AllArgsConstructor 8 | public class TimeRange { 9 | private long validFrom; 10 | private long validUntil; 11 | 12 | public TimeRange() { 13 | this.validFrom = 0; 14 | this.validUntil = 4294967295L; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/io/zksync/domain/auth/ChangePubKeyAuthType.java: -------------------------------------------------------------------------------- 1 | package io.zksync.domain.auth; 2 | 3 | public enum ChangePubKeyAuthType { 4 | Onchain, 5 | ECDSA, 6 | CREATE2, 7 | } 8 | -------------------------------------------------------------------------------- /src/main/java/io/zksync/domain/auth/ChangePubKeyCREATE2.java: -------------------------------------------------------------------------------- 1 | package io.zksync.domain.auth; 2 | 3 | import lombok.AllArgsConstructor; 4 | import lombok.Data; 5 | 6 | @Data 7 | @AllArgsConstructor 8 | public class ChangePubKeyCREATE2 implements ChangePubKeyVariant { 9 | 10 | private final ChangePubKeyAuthType type = ChangePubKeyAuthType.CREATE2; 11 | 12 | private String creatorAddress; 13 | private String saltArg; 14 | private String codeHash; 15 | 16 | @Override 17 | public byte[] getBytes() { 18 | return new byte[32]; 19 | } 20 | 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/io/zksync/domain/auth/ChangePubKeyECDSA.java: -------------------------------------------------------------------------------- 1 | package io.zksync.domain.auth; 2 | 3 | import org.web3j.utils.Numeric; 4 | 5 | import lombok.AllArgsConstructor; 6 | import lombok.Data; 7 | 8 | @Data 9 | @AllArgsConstructor 10 | public class ChangePubKeyECDSA implements ChangePubKeyVariant { 11 | 12 | private final ChangePubKeyAuthType type = ChangePubKeyAuthType.ECDSA; 13 | 14 | private String ethSignature; 15 | private String batchHash; 16 | 17 | @Override 18 | public byte[] getBytes() { 19 | return Numeric.hexStringToByteArray(batchHash); 20 | } 21 | 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/io/zksync/domain/auth/ChangePubKeyOnchain.java: -------------------------------------------------------------------------------- 1 | package io.zksync.domain.auth; 2 | 3 | import lombok.Data; 4 | import lombok.NoArgsConstructor; 5 | 6 | @Data 7 | @NoArgsConstructor 8 | public class ChangePubKeyOnchain implements ChangePubKeyVariant { 9 | 10 | private final ChangePubKeyAuthType type = ChangePubKeyAuthType.Onchain; 11 | 12 | @Override 13 | public byte[] getBytes() { 14 | return new byte[32]; 15 | } 16 | 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/io/zksync/domain/auth/ChangePubKeyVariant.java: -------------------------------------------------------------------------------- 1 | package io.zksync.domain.auth; 2 | 3 | import com.fasterxml.jackson.annotation.JsonIgnore; 4 | 5 | public interface ChangePubKeyVariant { 6 | 7 | ChangePubKeyAuthType getType(); 8 | 9 | @JsonIgnore 10 | byte[] getBytes(); 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/io/zksync/domain/auth/Toggle2FA.java: -------------------------------------------------------------------------------- 1 | package io.zksync.domain.auth; 2 | 3 | import io.zksync.signer.EthSignature; 4 | import lombok.AllArgsConstructor; 5 | import lombok.Data; 6 | 7 | @Data 8 | @AllArgsConstructor 9 | public class Toggle2FA { 10 | 11 | private boolean enable; 12 | 13 | private Integer accountId; 14 | 15 | private Long timestamp; 16 | 17 | private EthSignature signature; 18 | 19 | private String pubKeyHash; 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/io/zksync/domain/block/BlockInfo.java: -------------------------------------------------------------------------------- 1 | package io.zksync.domain.block; 2 | 3 | import lombok.*; 4 | 5 | @Data 6 | @Builder 7 | @NoArgsConstructor 8 | @AllArgsConstructor 9 | public class BlockInfo { 10 | 11 | Integer blockNumber; 12 | Boolean committed; 13 | Boolean verified; 14 | 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/io/zksync/domain/contract/ContractAddress.java: -------------------------------------------------------------------------------- 1 | package io.zksync.domain.contract; 2 | 3 | import lombok.*; 4 | 5 | @Data 6 | @Builder 7 | @NoArgsConstructor 8 | @AllArgsConstructor 9 | public class ContractAddress { 10 | 11 | String mainContract; 12 | String govContract; 13 | 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/io/zksync/domain/fee/TransactionFee.java: -------------------------------------------------------------------------------- 1 | package io.zksync.domain.fee; 2 | 3 | import lombok.*; 4 | 5 | import java.math.BigInteger; 6 | 7 | @Data 8 | @Builder 9 | @NoArgsConstructor 10 | @AllArgsConstructor 11 | public class TransactionFee { 12 | 13 | String feeToken; 14 | 15 | BigInteger fee; 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/io/zksync/domain/fee/TransactionFeeBatchRequest.java: -------------------------------------------------------------------------------- 1 | package io.zksync.domain.fee; 2 | 3 | import java.util.List; 4 | import java.util.stream.Collectors; 5 | 6 | import com.fasterxml.jackson.annotation.JsonIgnore; 7 | import com.fasterxml.jackson.annotation.JsonIgnoreProperties; 8 | 9 | import org.apache.commons.lang3.tuple.Pair; 10 | 11 | import lombok.*; 12 | 13 | @Builder 14 | @NoArgsConstructor 15 | @AllArgsConstructor 16 | @JsonIgnoreProperties(ignoreUnknown = true) 17 | public class TransactionFeeBatchRequest { 18 | 19 | @JsonIgnore 20 | @Singular 21 | private List> transactionTypes; 22 | 23 | @Getter 24 | private String tokenIdentifier; 25 | 26 | public List getTransactionTypes() { 27 | return this.transactionTypes 28 | .stream() 29 | .map(Pair::getLeft) 30 | .collect(Collectors.toList()); 31 | } 32 | 33 | public List getTransactionTypesRaw() { 34 | return this.transactionTypes 35 | .stream() 36 | .map(Pair::getLeft) 37 | .map(TransactionType::getRaw) 38 | .collect(Collectors.toList()); 39 | } 40 | 41 | public List getAddresses() { 42 | return this.transactionTypes 43 | .stream() 44 | .map(Pair::getRight) 45 | .collect(Collectors.toList()); 46 | } 47 | 48 | } 49 | -------------------------------------------------------------------------------- /src/main/java/io/zksync/domain/fee/TransactionFeeDetails.java: -------------------------------------------------------------------------------- 1 | package io.zksync.domain.fee; 2 | 3 | import com.fasterxml.jackson.annotation.JsonIgnoreProperties; 4 | import lombok.AllArgsConstructor; 5 | import lombok.Data; 6 | import lombok.NoArgsConstructor; 7 | 8 | import java.math.BigInteger; 9 | 10 | @Data 11 | @NoArgsConstructor 12 | @AllArgsConstructor 13 | @JsonIgnoreProperties(ignoreUnknown = true) 14 | public class TransactionFeeDetails { 15 | 16 | private String gasTxAmount; 17 | 18 | private String gasPriceWei; 19 | 20 | private String gasFee; 21 | 22 | private String zkpFee; 23 | 24 | private String totalFee; 25 | 26 | public BigInteger getTotalFeeInteger() { 27 | return new BigInteger(totalFee); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/io/zksync/domain/fee/TransactionFeeRequest.java: -------------------------------------------------------------------------------- 1 | package io.zksync.domain.fee; 2 | 3 | import com.fasterxml.jackson.annotation.JsonIgnoreProperties; 4 | import lombok.AllArgsConstructor; 5 | import lombok.Builder; 6 | import lombok.Data; 7 | import lombok.NoArgsConstructor; 8 | 9 | @Data 10 | @Builder 11 | @NoArgsConstructor 12 | @AllArgsConstructor 13 | @JsonIgnoreProperties(ignoreUnknown = true) 14 | public class TransactionFeeRequest { 15 | 16 | private TransactionType transactionType; 17 | 18 | private String address; 19 | 20 | private String tokenIdentifier; 21 | 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/io/zksync/domain/fee/TransactionType.java: -------------------------------------------------------------------------------- 1 | package io.zksync.domain.fee; 2 | 3 | import com.fasterxml.jackson.databind.ObjectMapper; 4 | import com.fasterxml.jackson.databind.node.ObjectNode; 5 | 6 | public enum TransactionType { 7 | 8 | WITHDRAW("Withdraw"), 9 | 10 | TRANSFER("Transfer"), 11 | 12 | FAST_WITHDRAW("FastWithdraw"), 13 | 14 | CHANGE_PUB_KEY_ONCHAIN("Onchain"), 15 | CHANGE_PUB_KEY_ECDSA("ECDSA"), 16 | CHANGE_PUB_KEY_CREATE2("CREATE2"), 17 | 18 | LEGACY_CHANGE_PUB_KEY("ChangePubKey"), 19 | 20 | LEGACY_CHANGE_PUB_KEY_ONCHAIN_AUTH("ChangePubKey"), 21 | 22 | FORCED_EXIT("Withdraw"), 23 | 24 | SWAP("Swap"), 25 | 26 | MINT_NFT("MintNFT"), 27 | 28 | WITHDRAW_NFT("WithdrawNFT"), 29 | 30 | FAST_WITHDRAW_NFT("FastWithdrawNFT"); 31 | 32 | private String feeIdentifier; 33 | 34 | TransactionType(String feeIdentifier) { 35 | this.feeIdentifier = feeIdentifier; 36 | } 37 | 38 | public String getFeeIdentifier() { 39 | return feeIdentifier; 40 | } 41 | 42 | public Object getRaw() { 43 | switch (this) { 44 | case LEGACY_CHANGE_PUB_KEY: 45 | return buildChangePubKeyLegacy(false); 46 | case LEGACY_CHANGE_PUB_KEY_ONCHAIN_AUTH: 47 | return buildChangePubKeyLegacy(true); 48 | case CHANGE_PUB_KEY_ECDSA: 49 | case CHANGE_PUB_KEY_CREATE2: 50 | case CHANGE_PUB_KEY_ONCHAIN: 51 | return buildChangePubKey(this.getFeeIdentifier()); 52 | default: 53 | return this.getFeeIdentifier(); 54 | } 55 | } 56 | 57 | private Object buildChangePubKeyLegacy(boolean onchainPubkeyAuth) { 58 | ObjectMapper mapper = new ObjectMapper(); 59 | ObjectNode root = mapper.createObjectNode(); 60 | ObjectNode child = mapper.createObjectNode(); 61 | child.put("onchainPubkeyAuth", onchainPubkeyAuth); 62 | root.set(this.getFeeIdentifier(), child); 63 | return root; 64 | } 65 | 66 | private Object buildChangePubKey(String authType) { 67 | ObjectMapper mapper = new ObjectMapper(); 68 | ObjectNode root = mapper.createObjectNode(); 69 | root.put("ChangePubKey", authType); 70 | return root; 71 | } 72 | 73 | } 74 | -------------------------------------------------------------------------------- /src/main/java/io/zksync/domain/operation/EthOpInfo.java: -------------------------------------------------------------------------------- 1 | package io.zksync.domain.operation; 2 | 3 | import io.zksync.domain.block.BlockInfo; 4 | import lombok.*; 5 | 6 | @Data 7 | @Builder 8 | @NoArgsConstructor 9 | @AllArgsConstructor 10 | public class EthOpInfo { 11 | 12 | Boolean executed; 13 | BlockInfo block; 14 | 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/io/zksync/domain/state/AccountState.java: -------------------------------------------------------------------------------- 1 | package io.zksync.domain.state; 2 | 3 | import com.fasterxml.jackson.annotation.JsonIgnoreProperties; 4 | import lombok.AllArgsConstructor; 5 | import lombok.Data; 6 | import lombok.NoArgsConstructor; 7 | 8 | @Data 9 | @NoArgsConstructor 10 | @AllArgsConstructor 11 | @JsonIgnoreProperties(ignoreUnknown = true) 12 | public class AccountState { 13 | 14 | private String address; 15 | 16 | private Integer id; 17 | 18 | private DepositingState depositing; 19 | 20 | private State committed; 21 | 22 | private State verified; 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/io/zksync/domain/state/DepositingBalance.java: -------------------------------------------------------------------------------- 1 | package io.zksync.domain.state; 2 | 3 | import com.fasterxml.jackson.annotation.JsonIgnoreProperties; 4 | import lombok.AllArgsConstructor; 5 | import lombok.Data; 6 | import lombok.NoArgsConstructor; 7 | 8 | import java.math.BigInteger; 9 | 10 | @Data 11 | @NoArgsConstructor 12 | @AllArgsConstructor 13 | @JsonIgnoreProperties(ignoreUnknown = true) 14 | public class DepositingBalance { 15 | 16 | private String amount; 17 | 18 | private BigInteger expectedBlockNumber; 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/io/zksync/domain/state/DepositingState.java: -------------------------------------------------------------------------------- 1 | package io.zksync.domain.state; 2 | 3 | import com.fasterxml.jackson.annotation.JsonIgnoreProperties; 4 | import lombok.AllArgsConstructor; 5 | import lombok.Data; 6 | import lombok.NoArgsConstructor; 7 | 8 | import java.util.Map; 9 | 10 | @Data 11 | @NoArgsConstructor 12 | @AllArgsConstructor 13 | @JsonIgnoreProperties(ignoreUnknown = true) 14 | public class DepositingState { 15 | 16 | private Map balances; 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/io/zksync/domain/state/State.java: -------------------------------------------------------------------------------- 1 | package io.zksync.domain.state; 2 | 3 | import com.fasterxml.jackson.annotation.JsonIgnoreProperties; 4 | 5 | import io.zksync.domain.token.NFT; 6 | import lombok.AllArgsConstructor; 7 | import lombok.Data; 8 | import lombok.NoArgsConstructor; 9 | 10 | import java.util.Map; 11 | 12 | @Data 13 | @NoArgsConstructor 14 | @AllArgsConstructor 15 | @JsonIgnoreProperties(ignoreUnknown = true) 16 | public class State { 17 | 18 | private Integer nonce; 19 | 20 | private String pubKeyHash; 21 | 22 | private Map balances; 23 | 24 | private Map nfts; 25 | 26 | private Map mintedNfts; 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/io/zksync/domain/swap/Order.java: -------------------------------------------------------------------------------- 1 | package io.zksync.domain.swap; 2 | 3 | import com.fasterxml.jackson.annotation.JsonGetter; 4 | import com.fasterxml.jackson.annotation.JsonIgnore; 5 | import com.fasterxml.jackson.annotation.JsonSetter; 6 | import com.fasterxml.jackson.annotation.JsonUnwrapped; 7 | 8 | import org.web3j.tuples.generated.Tuple2; 9 | 10 | import io.zksync.domain.Signature; 11 | import io.zksync.domain.TimeRange; 12 | import io.zksync.signer.EthSignature; 13 | import lombok.AllArgsConstructor; 14 | import lombok.Builder; 15 | import lombok.Data; 16 | import lombok.NoArgsConstructor; 17 | 18 | import java.math.BigInteger; 19 | import java.util.Arrays; 20 | import java.util.List; 21 | 22 | @Data 23 | @Builder 24 | @NoArgsConstructor 25 | @AllArgsConstructor 26 | public class Order { 27 | 28 | private Integer accountId; 29 | 30 | @JsonIgnore 31 | private String recipientAddress; 32 | 33 | private Integer nonce; 34 | 35 | private Integer tokenBuy; 36 | 37 | private Integer tokenSell; 38 | 39 | @JsonIgnore 40 | private Tuple2 ratio; 41 | 42 | @JsonIgnore 43 | private BigInteger amount; 44 | 45 | private Signature signature; 46 | 47 | @JsonGetter 48 | public String getRecipient() { 49 | return this.recipientAddress; 50 | } 51 | 52 | @JsonSetter 53 | public void setRecipient(String recipientAddress) { 54 | this.recipientAddress = recipientAddress; 55 | } 56 | 57 | @JsonGetter("ratio") 58 | public List getRatioJson() { 59 | return Arrays.asList(ratio.component1().toString(), ratio.component2().toString()); 60 | } 61 | 62 | @JsonSetter("ratio") 63 | public void setRatio(List ratio) { 64 | if (ratio == null || ratio.size() != 2) { 65 | throw new IllegalArgumentException("Incorrect amount of ratio"); 66 | } 67 | this.ratio = new Tuple2<>(new BigInteger(ratio.get(0)), new BigInteger(ratio.get(1))); 68 | } 69 | 70 | @JsonGetter("amount") 71 | public String getAmountString() { 72 | return amount.toString(); 73 | } 74 | 75 | @JsonSetter("amount") 76 | public void setAmountString(String amount) { 77 | this.amount = new BigInteger(amount); 78 | } 79 | 80 | @JsonIgnore 81 | private EthSignature ethereumSignature; 82 | 83 | @JsonUnwrapped 84 | private TimeRange timeRange; 85 | } 86 | -------------------------------------------------------------------------------- /src/main/java/io/zksync/domain/token/NFT.java: -------------------------------------------------------------------------------- 1 | package io.zksync.domain.token; 2 | 3 | import java.math.BigDecimal; 4 | import java.math.BigInteger; 5 | import java.math.RoundingMode; 6 | 7 | import lombok.AllArgsConstructor; 8 | import lombok.Data; 9 | import lombok.NoArgsConstructor; 10 | 11 | @Data 12 | @NoArgsConstructor 13 | @AllArgsConstructor 14 | public class NFT implements TokenId { 15 | 16 | private Integer id; 17 | 18 | private String symbol; 19 | 20 | private Integer creatorId; 21 | 22 | private String contentHash; 23 | 24 | private String creatorAddress; 25 | 26 | private Integer serialId; 27 | 28 | private String address; 29 | 30 | @Override 31 | public BigDecimal intoDecimal(BigInteger amount) { 32 | return new BigDecimal(amount) 33 | .setScale(1) 34 | .divide(BigDecimal.ONE, RoundingMode.DOWN); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/io/zksync/domain/token/Token.java: -------------------------------------------------------------------------------- 1 | package io.zksync.domain.token; 2 | 3 | import com.fasterxml.jackson.annotation.JsonIgnoreProperties; 4 | 5 | import org.web3j.abi.datatypes.Address; 6 | 7 | import lombok.AllArgsConstructor; 8 | import lombok.Data; 9 | import lombok.NoArgsConstructor; 10 | 11 | import java.math.BigDecimal; 12 | import java.math.BigInteger; 13 | import java.math.RoundingMode; 14 | 15 | @Data 16 | @NoArgsConstructor 17 | @AllArgsConstructor 18 | @JsonIgnoreProperties(ignoreUnknown = true) 19 | public class Token implements TokenId { 20 | 21 | private Integer id; 22 | 23 | private String address; 24 | 25 | private String symbol; 26 | 27 | private Integer decimals; 28 | 29 | public String formatToken(BigInteger amount) { 30 | return new BigDecimal(amount).divide(BigDecimal.TEN.pow(decimals)).toString(); 31 | } 32 | 33 | public boolean isETH() { 34 | return address.equals(Address.DEFAULT.getValue()) && symbol.equals("ETH"); 35 | } 36 | 37 | public BigDecimal intoDecimal(BigInteger amount) { 38 | return new BigDecimal(amount) 39 | .setScale(decimals) 40 | .divide(BigDecimal.TEN.pow(decimals), RoundingMode.DOWN); 41 | } 42 | 43 | public static Token createETH() { 44 | return new Token( 45 | 0, 46 | Address.DEFAULT.getValue(), 47 | "ETH", 48 | 18 49 | ); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/main/java/io/zksync/domain/token/TokenId.java: -------------------------------------------------------------------------------- 1 | package io.zksync.domain.token; 2 | 3 | import java.math.BigDecimal; 4 | import java.math.BigInteger; 5 | 6 | public interface TokenId { 7 | 8 | Integer getId(); 9 | 10 | String getSymbol(); 11 | 12 | BigDecimal intoDecimal(BigInteger amount); 13 | 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/io/zksync/domain/token/Tokens.java: -------------------------------------------------------------------------------- 1 | package io.zksync.domain.token; 2 | 3 | import io.zksync.exception.ZkSyncException; 4 | import lombok.*; 5 | 6 | import java.util.HashMap; 7 | import java.util.Map; 8 | 9 | import com.fasterxml.jackson.annotation.JsonAnySetter; 10 | 11 | @Getter 12 | @ToString 13 | @AllArgsConstructor 14 | @NoArgsConstructor 15 | public class Tokens { 16 | 17 | Map tokens = new HashMap(); 18 | 19 | @JsonAnySetter 20 | public void setUnrecognizedFields(String key, Token value) { 21 | this.tokens.put(key, value); 22 | } 23 | 24 | public Token getTokenBySymbol(String symbol) { 25 | return tokens.get(symbol); 26 | } 27 | 28 | public Token getTokenByAddress(String tokenAddress) { 29 | return tokens 30 | .values() 31 | .stream() 32 | .filter(token -> token.getAddress().equals(tokenAddress)) 33 | .findFirst() 34 | .orElseThrow(() -> new ZkSyncException("No token with address " + tokenAddress)); 35 | } 36 | 37 | public Token getToken(String tokenIdentifier) { 38 | 39 | return getTokenBySymbol(tokenIdentifier) != null ? 40 | getTokenBySymbol(tokenIdentifier) : getTokenByAddress(tokenIdentifier); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/io/zksync/domain/transaction/ChangePubKey.java: -------------------------------------------------------------------------------- 1 | package io.zksync.domain.transaction; 2 | 3 | import com.fasterxml.jackson.annotation.JsonIgnore; 4 | import com.fasterxml.jackson.annotation.JsonUnwrapped; 5 | 6 | import io.zksync.domain.Signature; 7 | import io.zksync.domain.TimeRange; 8 | import io.zksync.domain.auth.ChangePubKeyVariant; 9 | import lombok.AllArgsConstructor; 10 | import lombok.Builder; 11 | import lombok.Data; 12 | import lombok.NoArgsConstructor; 13 | 14 | import java.math.BigInteger; 15 | 16 | @Data 17 | @Builder 18 | @NoArgsConstructor 19 | @AllArgsConstructor 20 | public class ChangePubKey implements ZkSyncTransaction { 21 | 22 | private final String type = "ChangePubKey"; 23 | 24 | private Integer accountId; 25 | 26 | private String account; 27 | 28 | private String newPkHash; 29 | 30 | private Integer feeToken; 31 | 32 | private String fee; 33 | 34 | private Integer nonce; 35 | 36 | private Signature signature; 37 | 38 | private T ethAuthData; 39 | 40 | @JsonUnwrapped 41 | private TimeRange timeRange; 42 | 43 | @JsonIgnore 44 | public BigInteger getFeeInteger() { 45 | return new BigInteger(fee); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/main/java/io/zksync/domain/transaction/ForcedExit.java: -------------------------------------------------------------------------------- 1 | package io.zksync.domain.transaction; 2 | 3 | import com.fasterxml.jackson.annotation.JsonIgnore; 4 | import com.fasterxml.jackson.annotation.JsonUnwrapped; 5 | 6 | import io.zksync.domain.Signature; 7 | import io.zksync.domain.TimeRange; 8 | import lombok.AllArgsConstructor; 9 | import lombok.Builder; 10 | import lombok.Data; 11 | import lombok.NoArgsConstructor; 12 | 13 | import java.math.BigInteger; 14 | 15 | @Data 16 | @Builder 17 | @NoArgsConstructor 18 | @AllArgsConstructor 19 | public class ForcedExit implements ZkSyncTransaction { 20 | 21 | private final String type = "ForcedExit"; 22 | 23 | private Integer initiatorAccountId; 24 | 25 | private String target; 26 | 27 | private Integer token; 28 | 29 | private String fee; 30 | 31 | private Integer nonce; 32 | 33 | private Signature signature; 34 | 35 | @JsonUnwrapped 36 | private TimeRange timeRange; 37 | 38 | @JsonIgnore 39 | public BigInteger getFeeInteger() { 40 | return new BigInteger(fee); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/io/zksync/domain/transaction/MintNFT.java: -------------------------------------------------------------------------------- 1 | package io.zksync.domain.transaction; 2 | 3 | import com.fasterxml.jackson.annotation.JsonIgnore; 4 | 5 | import io.zksync.domain.Signature; 6 | import lombok.AllArgsConstructor; 7 | import lombok.Builder; 8 | import lombok.Data; 9 | import lombok.NoArgsConstructor; 10 | 11 | import java.math.BigInteger; 12 | 13 | @Data 14 | @Builder 15 | @NoArgsConstructor 16 | @AllArgsConstructor 17 | public class MintNFT implements ZkSyncTransaction { 18 | 19 | private final String type = "MintNFT"; 20 | 21 | private Integer creatorId; 22 | 23 | private String creatorAddress; 24 | 25 | private String contentHash; 26 | 27 | private String recipient; 28 | 29 | private String fee; 30 | 31 | private Integer feeToken; 32 | 33 | private Integer nonce; 34 | 35 | private Signature signature; 36 | 37 | @JsonIgnore 38 | public BigInteger getFeeInteger() { 39 | return new BigInteger(fee); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/main/java/io/zksync/domain/transaction/Swap.java: -------------------------------------------------------------------------------- 1 | package io.zksync.domain.transaction; 2 | 3 | import com.fasterxml.jackson.annotation.JsonGetter; 4 | import com.fasterxml.jackson.annotation.JsonIgnore; 5 | 6 | import org.web3j.tuples.generated.Tuple2; 7 | 8 | import io.zksync.domain.Signature; 9 | import io.zksync.domain.swap.Order; 10 | import lombok.AllArgsConstructor; 11 | import lombok.Builder; 12 | import lombok.Data; 13 | import lombok.NoArgsConstructor; 14 | 15 | import java.math.BigInteger; 16 | import java.util.Arrays; 17 | import java.util.List; 18 | 19 | @Data 20 | @Builder 21 | @NoArgsConstructor 22 | @AllArgsConstructor 23 | public class Swap implements ZkSyncTransaction { 24 | 25 | private final String type = "Swap"; 26 | 27 | private Integer submitterId; 28 | 29 | private String submitterAddress; 30 | 31 | private Integer nonce; 32 | 33 | @JsonIgnore 34 | private Tuple2 orders; 35 | 36 | @JsonIgnore 37 | private Tuple2 amounts; 38 | 39 | private String fee; 40 | 41 | private Integer feeToken; 42 | 43 | private Signature signature; 44 | 45 | @JsonGetter("orders") 46 | public List getOrdersJson() { 47 | return Arrays.asList(orders.component1(), orders.component2()); 48 | } 49 | 50 | @JsonGetter("amounts") 51 | public List getAmountsJson() { 52 | return Arrays.asList(amounts.component1().toString(), amounts.component2().toString()); 53 | } 54 | 55 | @JsonIgnore 56 | public BigInteger getFeeInteger() { 57 | return new BigInteger(fee); 58 | } 59 | 60 | } 61 | -------------------------------------------------------------------------------- /src/main/java/io/zksync/domain/transaction/TransactionDetails.java: -------------------------------------------------------------------------------- 1 | package io.zksync.domain.transaction; 2 | 3 | import io.zksync.domain.block.BlockInfo; 4 | import lombok.*; 5 | 6 | @Data 7 | @Builder 8 | @NoArgsConstructor 9 | @AllArgsConstructor 10 | public class TransactionDetails { 11 | 12 | Boolean executed; 13 | Boolean success; 14 | String failReason; 15 | BlockInfo block; 16 | 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/io/zksync/domain/transaction/Transfer.java: -------------------------------------------------------------------------------- 1 | package io.zksync.domain.transaction; 2 | 3 | import com.fasterxml.jackson.annotation.JsonGetter; 4 | import com.fasterxml.jackson.annotation.JsonIgnore; 5 | import com.fasterxml.jackson.annotation.JsonSetter; 6 | import com.fasterxml.jackson.annotation.JsonUnwrapped; 7 | 8 | import io.zksync.domain.Signature; 9 | import io.zksync.domain.TimeRange; 10 | import io.zksync.domain.token.TokenId; 11 | import lombok.AllArgsConstructor; 12 | import lombok.Builder; 13 | import lombok.Data; 14 | import lombok.NoArgsConstructor; 15 | 16 | import java.math.BigInteger; 17 | 18 | @Data 19 | @Builder 20 | @NoArgsConstructor 21 | @AllArgsConstructor 22 | public class Transfer implements ZkSyncTransaction { 23 | 24 | private final String type = "Transfer"; 25 | 26 | private Integer accountId; 27 | 28 | private String from; 29 | 30 | private String to; 31 | 32 | private Integer token; 33 | 34 | @JsonIgnore 35 | private BigInteger amount; 36 | 37 | private String fee; 38 | 39 | private Integer nonce; 40 | 41 | private Signature signature; 42 | 43 | @JsonIgnore 44 | private TokenId tokenId; 45 | 46 | @JsonUnwrapped 47 | private TimeRange timeRange; 48 | 49 | @JsonGetter("amount") 50 | public String getAmountString() { 51 | return amount.toString(); 52 | } 53 | 54 | @JsonSetter("amount") 55 | public void setAmountString(String amount) { 56 | this.amount = new BigInteger(amount); 57 | } 58 | 59 | @JsonIgnore 60 | public BigInteger getFeeInteger() { 61 | return new BigInteger(fee); 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /src/main/java/io/zksync/domain/transaction/Withdraw.java: -------------------------------------------------------------------------------- 1 | package io.zksync.domain.transaction; 2 | 3 | import com.fasterxml.jackson.annotation.JsonGetter; 4 | import com.fasterxml.jackson.annotation.JsonIgnore; 5 | import com.fasterxml.jackson.annotation.JsonSetter; 6 | import com.fasterxml.jackson.annotation.JsonUnwrapped; 7 | 8 | import io.zksync.domain.Signature; 9 | import io.zksync.domain.TimeRange; 10 | import lombok.AllArgsConstructor; 11 | import lombok.Builder; 12 | import lombok.Data; 13 | import lombok.NoArgsConstructor; 14 | 15 | import java.math.BigInteger; 16 | 17 | @Data 18 | @Builder 19 | @NoArgsConstructor 20 | @AllArgsConstructor 21 | public class Withdraw implements ZkSyncTransaction { 22 | 23 | private final String type = "Withdraw"; 24 | 25 | private Integer accountId; 26 | 27 | private String from; 28 | 29 | private String to; 30 | 31 | private Integer token; 32 | 33 | @JsonIgnore 34 | private BigInteger amount; 35 | 36 | private String fee; 37 | 38 | private Integer nonce; 39 | 40 | private Signature signature; 41 | 42 | @JsonUnwrapped 43 | private TimeRange timeRange; 44 | 45 | @JsonGetter("amount") 46 | public String getAmountString() { 47 | return amount.toString(); 48 | } 49 | 50 | @JsonSetter("amount") 51 | public void setAmountString(String amount) { 52 | this.amount = new BigInteger(amount); 53 | } 54 | 55 | @JsonIgnore 56 | public BigInteger getFeeInteger() { 57 | return new BigInteger(fee); 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /src/main/java/io/zksync/domain/transaction/WithdrawNFT.java: -------------------------------------------------------------------------------- 1 | package io.zksync.domain.transaction; 2 | 3 | import com.fasterxml.jackson.annotation.JsonIgnore; 4 | import com.fasterxml.jackson.annotation.JsonUnwrapped; 5 | 6 | import io.zksync.domain.Signature; 7 | import io.zksync.domain.TimeRange; 8 | import lombok.AllArgsConstructor; 9 | import lombok.Builder; 10 | import lombok.Data; 11 | import lombok.NoArgsConstructor; 12 | 13 | import java.math.BigInteger; 14 | 15 | @Data 16 | @Builder 17 | @NoArgsConstructor 18 | @AllArgsConstructor 19 | public class WithdrawNFT implements ZkSyncTransaction { 20 | 21 | private final String type = "WithdrawNFT"; 22 | 23 | private Integer accountId; 24 | 25 | private String from; 26 | 27 | private String to; 28 | 29 | private Integer token; 30 | 31 | private Integer feeToken; 32 | 33 | private String fee; 34 | 35 | private Integer nonce; 36 | 37 | private Signature signature; 38 | 39 | @JsonUnwrapped 40 | private TimeRange timeRange; 41 | 42 | @JsonIgnore 43 | public BigInteger getFeeInteger() { 44 | return new BigInteger(fee); 45 | } 46 | 47 | } 48 | -------------------------------------------------------------------------------- /src/main/java/io/zksync/domain/transaction/ZkSyncTransaction.java: -------------------------------------------------------------------------------- 1 | package io.zksync.domain.transaction; 2 | 3 | public interface ZkSyncTransaction { 4 | 5 | String getType(); 6 | } 7 | -------------------------------------------------------------------------------- /src/main/java/io/zksync/ethereum/DefaultEthereumProvider.java: -------------------------------------------------------------------------------- 1 | package io.zksync.ethereum; 2 | 3 | import java.math.BigDecimal; 4 | import java.math.BigInteger; 5 | import java.util.Arrays; 6 | import java.util.Optional; 7 | import java.util.concurrent.CompletableFuture; 8 | 9 | import org.web3j.abi.datatypes.generated.Bytes32; 10 | import org.web3j.protocol.Web3j; 11 | import org.web3j.protocol.core.DefaultBlockParameterName; 12 | import org.web3j.protocol.core.methods.response.EthGetBalance; 13 | import org.web3j.protocol.core.methods.response.EthGetTransactionCount; 14 | import org.web3j.protocol.core.methods.response.TransactionReceipt; 15 | import org.web3j.tx.Transfer; 16 | import org.web3j.tx.gas.ContractGasProvider; 17 | import org.web3j.tx.gas.StaticGasProvider; 18 | import org.web3j.utils.Numeric; 19 | import org.web3j.utils.Convert.Unit; 20 | 21 | import io.zksync.domain.token.NFT; 22 | import io.zksync.domain.token.Token; 23 | import io.zksync.ethereum.wrappers.ERC20; 24 | import io.zksync.ethereum.wrappers.ZkSync; 25 | import io.zksync.signer.EthSigner; 26 | import lombok.RequiredArgsConstructor; 27 | 28 | @RequiredArgsConstructor 29 | public class DefaultEthereumProvider implements EthereumProvider { 30 | 31 | private static final BigInteger MAX_APPROVE_AMOUNT = BigInteger.valueOf(2).pow(256).subtract(BigInteger.ONE); 32 | private static final BigInteger DEFAULT_THRESHOLD = BigInteger.valueOf(2).pow(255); 33 | private static final ContractGasProvider DEFAULT_GAS_PROVIDER = new StaticGasProvider(BigInteger.ZERO, 34 | BigInteger.ZERO); 35 | 36 | private final Web3j web3j; 37 | private final EthSigner ethSigner; 38 | private final ZkSync contract; 39 | 40 | @Override 41 | public CompletableFuture approveDeposits(Token token, Optional limit) { 42 | ERC20 tokenContract = ERC20.load(token.getAddress(), this.web3j, this.ethSigner.getTransactionManager(), 43 | this.contract.getGasProvider()); 44 | return tokenContract.approve(this.contractAddress(), limit.orElse(MAX_APPROVE_AMOUNT)).sendAsync(); 45 | } 46 | 47 | @Override 48 | public CompletableFuture transfer(Token token, BigInteger amount, String to) { 49 | if (token.isETH()) { 50 | Transfer transfer = new Transfer(web3j, contract.getTransactionManager()); 51 | return transfer.sendFunds(to, new BigDecimal(amount), Unit.WEI).sendAsync(); 52 | } else { 53 | ERC20 tokenContract = ERC20.load(token.getAddress(), this.web3j, this.ethSigner.getTransactionManager(), 54 | this.contract.getGasProvider()); 55 | return tokenContract.transfer(to, amount).sendAsync(); 56 | } 57 | } 58 | 59 | @Override 60 | public CompletableFuture deposit(Token token, BigInteger amount, String userAddress) { 61 | if (token.isETH()) { 62 | return contract.depositETH(userAddress, amount).sendAsync(); 63 | } else { 64 | return contract.depositERC20(token.getAddress(), amount, userAddress).sendAsync(); 65 | } 66 | } 67 | 68 | @Override 69 | public CompletableFuture withdraw(Token token, BigInteger amount) { 70 | if (token.isETH()) { 71 | return contract.withdrawETH(amount).sendAsync(); 72 | } else { 73 | return contract.withdrawERC20(token.getAddress(), amount).sendAsync(); 74 | } 75 | } 76 | 77 | @Override 78 | public CompletableFuture fullExit(Token token, Integer accountId) { 79 | return contract.requestFullExit(BigInteger.valueOf(accountId), token.getAddress()).sendAsync(); 80 | } 81 | 82 | @Override 83 | public CompletableFuture fullExitNFT(NFT token, Integer accountId) { 84 | return contract.requestFullExitNFT(BigInteger.valueOf(accountId), BigInteger.valueOf(token.getId())).sendAsync(); 85 | } 86 | 87 | @Override 88 | public CompletableFuture setAuthPubkeyHash(String pubKeyhash, BigInteger nonce) { 89 | return contract.setAuthPubkeyHash(Numeric.hexStringToByteArray(pubKeyhash), nonce).sendAsync(); 90 | } 91 | 92 | @Override 93 | public CompletableFuture isDepositApproved(Token token, Optional threshold) { 94 | ERC20 tokenContract = ERC20.load(token.getAddress(), this.web3j, this.ethSigner.getTransactionManager(), 95 | DEFAULT_GAS_PROVIDER); 96 | return tokenContract.allowance(this.ethSigner.getAddress(), this.contractAddress()).sendAsync() 97 | .thenApply(allowance -> { 98 | return allowance.compareTo(threshold.orElse(DEFAULT_THRESHOLD)) >= 0; 99 | }); 100 | } 101 | 102 | @Override 103 | public CompletableFuture isOnChainAuthPubkeyHashSet(BigInteger nonce) { 104 | return contract.authFacts(ethSigner.getAddress(), nonce).sendAsync().thenApply(publicKeyHash -> { 105 | return !Arrays.equals(publicKeyHash, Bytes32.DEFAULT.getValue()); 106 | }); 107 | } 108 | 109 | @Override 110 | public CompletableFuture getBalance() { 111 | return web3j.ethGetBalance(this.ethSigner.getAddress(), DefaultBlockParameterName.LATEST).sendAsync() 112 | .thenApply(EthGetBalance::getBalance); 113 | } 114 | 115 | @Override 116 | public CompletableFuture getNonce() { 117 | return web3j.ethGetTransactionCount(this.ethSigner.getAddress(), DefaultBlockParameterName.PENDING).sendAsync() 118 | .thenApply(EthGetTransactionCount::getTransactionCount); 119 | } 120 | 121 | @Override 122 | public String contractAddress() { 123 | return this.contract.getContractAddress(); 124 | } 125 | 126 | } 127 | -------------------------------------------------------------------------------- /src/main/java/io/zksync/ethereum/EthereumProvider.java: -------------------------------------------------------------------------------- 1 | package io.zksync.ethereum; 2 | 3 | import java.math.BigInteger; 4 | import java.util.Optional; 5 | import java.util.concurrent.CompletableFuture; 6 | 7 | import org.web3j.protocol.core.methods.response.TransactionReceipt; 8 | 9 | import io.zksync.domain.token.NFT; 10 | import io.zksync.domain.token.Token; 11 | 12 | public interface EthereumProvider { 13 | 14 | /** 15 | * Send approve transaction to token contract. 16 | * 17 | * @param token - Token object supported by ZkSync 18 | * @param limit - Maximum amount to approve for ZkSync contract 19 | * @return CompletableFuture for waiting for transaction mine 20 | */ 21 | CompletableFuture approveDeposits(Token token, Optional limit); 22 | 23 | /** 24 | * Send transfer transaction. This is the regular transfer of ERC20 token 25 | * 26 | * @param token - Token object supported by ZkSync 27 | * @param amount - Amount tokens to transfer 28 | * @param to - Address of receiver tokens 29 | * @return CompletableFuture for waiting for transaction mine 30 | */ 31 | CompletableFuture transfer(Token token, BigInteger amount, String to); 32 | 33 | /** 34 | * Send deposit transaction to ZkSync contract. For ERC20 token must be approved before. @see EthereumProvider.approveDepodits 35 | * 36 | * @param token - Token object supported by ZkSync 37 | * @param amount - Amount tokens to transfer 38 | * @param userAddress - Address of L2 receiver deposit in ZkSync 39 | * @return CompletableFuture for waiting for transaction mine 40 | */ 41 | CompletableFuture deposit(Token token, BigInteger amount, String userAddress); 42 | 43 | /** 44 | * Send withdraw transaction to ZkSync contract. 45 | * 46 | * @param token - Token object supported by ZkSync 47 | * @param amount - Amount tokens to transfer 48 | * @return CompletableFuture for waiting for transaction mine 49 | */ 50 | CompletableFuture withdraw(Token token, BigInteger amount); 51 | 52 | /** 53 | * Return back deposit by token. 54 | * 55 | * @param token - Token object supported by ZkSync 56 | * @param accountId - Id of account in ZkSync 57 | * @return CompletableFuture for waiting for transaction mine 58 | */ 59 | CompletableFuture fullExit(Token token, Integer accountId); 60 | 61 | /** 62 | * Return back nft. 63 | * 64 | * @param token - NFT Token object supported by ZkSync 65 | * @param accountId - Id of account in ZkSync 66 | * @return CompletableFuture for waiting for transaction mine 67 | */ 68 | CompletableFuture fullExitNFT(NFT token, Integer accountId); 69 | 70 | /** 71 | * Setup L2 public key hash for specific nonce 72 | * 73 | * @param pubKeyhash - Public key hash generated by ZkSigner 74 | * @param nonce - Nonce value of account 75 | * @return CompletableFuture for waiting for transaction mine 76 | */ 77 | CompletableFuture setAuthPubkeyHash(String pubKeyhash, BigInteger nonce); 78 | 79 | /** 80 | * Check if deposit is approved in enough amount 81 | * 82 | * @param token - Token object supported by ZkSync 83 | * @param threshold - Minimum threshold of approved tokens 84 | * @return CompletableFuture of blockchain smart-contract call 85 | */ 86 | CompletableFuture isDepositApproved(Token token, Optional threshold); 87 | 88 | /** 89 | * Check if public key hash set for specific nonce 90 | * 91 | * @param nonce - Nonce value of account 92 | * @return CompletableFuture of blockchain smart-contract call 93 | */ 94 | CompletableFuture isOnChainAuthPubkeyHashSet(BigInteger nonce); 95 | 96 | /** 97 | * Get balance of account in Etereum 98 | * 99 | * @return CompletableFuture of blockchain call 100 | */ 101 | CompletableFuture getBalance(); 102 | 103 | /** 104 | * Get current nonce of account 105 | * 106 | * @return CompletableFuture of blockchain call 107 | */ 108 | CompletableFuture getNonce(); 109 | 110 | /** 111 | * Get ZkSync smart-contract address in Ethereum blockchain 112 | * 113 | * @return Contract address in hex string 114 | */ 115 | String contractAddress(); 116 | 117 | } 118 | -------------------------------------------------------------------------------- /src/main/java/io/zksync/ethereum/transaction/NoOpTransactionManager.java: -------------------------------------------------------------------------------- 1 | package io.zksync.ethereum.transaction; 2 | 3 | import java.io.IOException; 4 | import java.math.BigInteger; 5 | 6 | import org.web3j.crypto.Credentials; 7 | import org.web3j.protocol.core.DefaultBlockParameter; 8 | import org.web3j.protocol.core.methods.response.EthGetCode; 9 | import org.web3j.protocol.core.methods.response.EthSendTransaction; 10 | import org.web3j.tx.TransactionManager; 11 | import org.web3j.tx.response.NoOpProcessor; 12 | 13 | public class NoOpTransactionManager extends TransactionManager { 14 | 15 | public NoOpTransactionManager(Credentials credentials) { 16 | super(new NoOpProcessor(null), credentials.getAddress()); 17 | } 18 | 19 | @Override 20 | public EthSendTransaction sendTransaction(BigInteger gasPrice, BigInteger gasLimit, String to, String data, 21 | BigInteger value, boolean constructor) throws IOException { 22 | throw new UnsupportedOperationException(); 23 | } 24 | 25 | @Override 26 | public EthSendTransaction sendTransactionEIP1559(BigInteger gasPremium, BigInteger feeCap, BigInteger gasLimit, 27 | String to, String data, BigInteger value, boolean constructor) throws IOException { 28 | throw new UnsupportedOperationException(); 29 | } 30 | 31 | @Override 32 | public String sendCall(String to, String data, DefaultBlockParameter defaultBlockParameter) throws IOException { 33 | throw new UnsupportedOperationException(); 34 | } 35 | 36 | @Override 37 | public EthGetCode getCode(String contractAddress, DefaultBlockParameter defaultBlockParameter) throws IOException { 38 | throw new UnsupportedOperationException(); 39 | } 40 | 41 | } 42 | -------------------------------------------------------------------------------- /src/main/java/io/zksync/ethereum/wrappers/ERC20.java: -------------------------------------------------------------------------------- 1 | package io.zksync.ethereum.wrappers; 2 | 3 | import io.reactivex.Flowable; 4 | import io.reactivex.functions.Function; 5 | import java.math.BigInteger; 6 | import java.util.ArrayList; 7 | import java.util.Arrays; 8 | import java.util.Collections; 9 | import java.util.List; 10 | import org.web3j.abi.EventEncoder; 11 | import org.web3j.abi.TypeReference; 12 | import org.web3j.abi.datatypes.Address; 13 | import org.web3j.abi.datatypes.Event; 14 | import org.web3j.abi.datatypes.Type; 15 | import org.web3j.abi.datatypes.generated.Uint256; 16 | import org.web3j.contracts.token.ERC20Interface; 17 | import org.web3j.crypto.Credentials; 18 | import org.web3j.protocol.Web3j; 19 | import org.web3j.protocol.core.DefaultBlockParameter; 20 | import org.web3j.protocol.core.RemoteFunctionCall; 21 | import org.web3j.protocol.core.methods.request.EthFilter; 22 | import org.web3j.protocol.core.methods.response.BaseEventResponse; 23 | import org.web3j.protocol.core.methods.response.Log; 24 | import org.web3j.protocol.core.methods.response.TransactionReceipt; 25 | import org.web3j.tx.Contract; 26 | import org.web3j.tx.TransactionManager; 27 | import org.web3j.tx.gas.ContractGasProvider; 28 | 29 | /** 30 | *

Auto generated code. 31 | *

Do not modify! 32 | *

Please use the web3j command line tools, 33 | * or the org.web3j.codegen.SolidityFunctionWrapperGenerator in the 34 | * codegen module to update. 35 | * 36 | *

Generated with web3j version 4.7.0. 37 | */ 38 | @SuppressWarnings("rawtypes") 39 | public class ERC20 extends Contract implements ERC20Interface { 40 | public static final String BINARY = "Bin file was not provided"; 41 | 42 | public static final String FUNC_ALLOWANCE = "allowance"; 43 | 44 | public static final String FUNC_APPROVE = "approve"; 45 | 46 | public static final String FUNC_BALANCEOF = "balanceOf"; 47 | 48 | public static final String FUNC_TOTALSUPPLY = "totalSupply"; 49 | 50 | public static final String FUNC_TRANSFER = "transfer"; 51 | 52 | public static final String FUNC_TRANSFERFROM = "transferFrom"; 53 | 54 | public static final Event APPROVAL_EVENT = new Event("Approval", 55 | Arrays.>asList(new TypeReference

(true) {}, new TypeReference
(true) {}, new TypeReference() {})); 56 | ; 57 | 58 | public static final Event TRANSFER_EVENT = new Event("Transfer", 59 | Arrays.>asList(new TypeReference
(true) {}, new TypeReference
(true) {}, new TypeReference() {})); 60 | ; 61 | 62 | @Deprecated 63 | protected ERC20(String contractAddress, Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) { 64 | super(BINARY, contractAddress, web3j, credentials, gasPrice, gasLimit); 65 | } 66 | 67 | protected ERC20(String contractAddress, Web3j web3j, Credentials credentials, ContractGasProvider contractGasProvider) { 68 | super(BINARY, contractAddress, web3j, credentials, contractGasProvider); 69 | } 70 | 71 | @Deprecated 72 | protected ERC20(String contractAddress, Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit) { 73 | super(BINARY, contractAddress, web3j, transactionManager, gasPrice, gasLimit); 74 | } 75 | 76 | protected ERC20(String contractAddress, Web3j web3j, TransactionManager transactionManager, ContractGasProvider contractGasProvider) { 77 | super(BINARY, contractAddress, web3j, transactionManager, contractGasProvider); 78 | } 79 | 80 | public List getApprovalEvents(TransactionReceipt transactionReceipt) { 81 | List valueList = extractEventParametersWithLog(APPROVAL_EVENT, transactionReceipt); 82 | ArrayList responses = new ArrayList(valueList.size()); 83 | for (Contract.EventValuesWithLog eventValues : valueList) { 84 | ApprovalEventResponse typedResponse = new ApprovalEventResponse(); 85 | typedResponse.log = eventValues.getLog(); 86 | typedResponse.owner = (String) eventValues.getIndexedValues().get(0).getValue(); 87 | typedResponse.spender = (String) eventValues.getIndexedValues().get(1).getValue(); 88 | typedResponse.value = (BigInteger) eventValues.getNonIndexedValues().get(0).getValue(); 89 | responses.add(typedResponse); 90 | } 91 | return responses; 92 | } 93 | 94 | public Flowable approvalEventFlowable(EthFilter filter) { 95 | return web3j.ethLogFlowable(filter).map(new Function() { 96 | @Override 97 | public ApprovalEventResponse apply(Log log) { 98 | Contract.EventValuesWithLog eventValues = extractEventParametersWithLog(APPROVAL_EVENT, log); 99 | ApprovalEventResponse typedResponse = new ApprovalEventResponse(); 100 | typedResponse.log = log; 101 | typedResponse.owner = (String) eventValues.getIndexedValues().get(0).getValue(); 102 | typedResponse.spender = (String) eventValues.getIndexedValues().get(1).getValue(); 103 | typedResponse.value = (BigInteger) eventValues.getNonIndexedValues().get(0).getValue(); 104 | return typedResponse; 105 | } 106 | }); 107 | } 108 | 109 | public Flowable approvalEventFlowable(DefaultBlockParameter startBlock, DefaultBlockParameter endBlock) { 110 | EthFilter filter = new EthFilter(startBlock, endBlock, getContractAddress()); 111 | filter.addSingleTopic(EventEncoder.encode(APPROVAL_EVENT)); 112 | return approvalEventFlowable(filter); 113 | } 114 | 115 | public List getTransferEvents(TransactionReceipt transactionReceipt) { 116 | List valueList = extractEventParametersWithLog(TRANSFER_EVENT, transactionReceipt); 117 | ArrayList responses = new ArrayList(valueList.size()); 118 | for (Contract.EventValuesWithLog eventValues : valueList) { 119 | TransferEventResponse typedResponse = new TransferEventResponse(); 120 | typedResponse.log = eventValues.getLog(); 121 | typedResponse.from = (String) eventValues.getIndexedValues().get(0).getValue(); 122 | typedResponse.to = (String) eventValues.getIndexedValues().get(1).getValue(); 123 | typedResponse.value = (BigInteger) eventValues.getNonIndexedValues().get(0).getValue(); 124 | responses.add(typedResponse); 125 | } 126 | return responses; 127 | } 128 | 129 | public Flowable transferEventFlowable(EthFilter filter) { 130 | return web3j.ethLogFlowable(filter).map(new Function() { 131 | @Override 132 | public TransferEventResponse apply(Log log) { 133 | Contract.EventValuesWithLog eventValues = extractEventParametersWithLog(TRANSFER_EVENT, log); 134 | TransferEventResponse typedResponse = new TransferEventResponse(); 135 | typedResponse.log = log; 136 | typedResponse.from = (String) eventValues.getIndexedValues().get(0).getValue(); 137 | typedResponse.to = (String) eventValues.getIndexedValues().get(1).getValue(); 138 | typedResponse.value = (BigInteger) eventValues.getNonIndexedValues().get(0).getValue(); 139 | return typedResponse; 140 | } 141 | }); 142 | } 143 | 144 | public Flowable transferEventFlowable(DefaultBlockParameter startBlock, DefaultBlockParameter endBlock) { 145 | EthFilter filter = new EthFilter(startBlock, endBlock, getContractAddress()); 146 | filter.addSingleTopic(EventEncoder.encode(TRANSFER_EVENT)); 147 | return transferEventFlowable(filter); 148 | } 149 | 150 | public RemoteFunctionCall allowance(String owner, String spender) { 151 | final org.web3j.abi.datatypes.Function function = new org.web3j.abi.datatypes.Function(FUNC_ALLOWANCE, 152 | Arrays.asList(new org.web3j.abi.datatypes.Address(160, owner), 153 | new org.web3j.abi.datatypes.Address(160, spender)), 154 | Arrays.>asList(new TypeReference() {})); 155 | return executeRemoteCallSingleValueReturn(function, BigInteger.class); 156 | } 157 | 158 | public RemoteFunctionCall approve(String spender, BigInteger amount) { 159 | final org.web3j.abi.datatypes.Function function = new org.web3j.abi.datatypes.Function( 160 | FUNC_APPROVE, 161 | Arrays.asList(new org.web3j.abi.datatypes.Address(160, spender), 162 | new org.web3j.abi.datatypes.generated.Uint256(amount)), 163 | Collections.>emptyList()); 164 | return executeRemoteCallTransaction(function); 165 | } 166 | 167 | public RemoteFunctionCall balanceOf(String account) { 168 | final org.web3j.abi.datatypes.Function function = new org.web3j.abi.datatypes.Function(FUNC_BALANCEOF, 169 | Arrays.asList(new org.web3j.abi.datatypes.Address(160, account)), 170 | Arrays.>asList(new TypeReference() {})); 171 | return executeRemoteCallSingleValueReturn(function, BigInteger.class); 172 | } 173 | 174 | public RemoteFunctionCall totalSupply() { 175 | final org.web3j.abi.datatypes.Function function = new org.web3j.abi.datatypes.Function(FUNC_TOTALSUPPLY, 176 | Arrays.asList(), 177 | Arrays.>asList(new TypeReference() {})); 178 | return executeRemoteCallSingleValueReturn(function, BigInteger.class); 179 | } 180 | 181 | public RemoteFunctionCall transfer(String recipient, BigInteger amount) { 182 | final org.web3j.abi.datatypes.Function function = new org.web3j.abi.datatypes.Function( 183 | FUNC_TRANSFER, 184 | Arrays.asList(new org.web3j.abi.datatypes.Address(160, recipient), 185 | new org.web3j.abi.datatypes.generated.Uint256(amount)), 186 | Collections.>emptyList()); 187 | return executeRemoteCallTransaction(function); 188 | } 189 | 190 | public RemoteFunctionCall transferFrom(String sender, String recipient, BigInteger amount) { 191 | final org.web3j.abi.datatypes.Function function = new org.web3j.abi.datatypes.Function( 192 | FUNC_TRANSFERFROM, 193 | Arrays.asList(new org.web3j.abi.datatypes.Address(160, sender), 194 | new org.web3j.abi.datatypes.Address(160, recipient), 195 | new org.web3j.abi.datatypes.generated.Uint256(amount)), 196 | Collections.>emptyList()); 197 | return executeRemoteCallTransaction(function); 198 | } 199 | 200 | @Deprecated 201 | public static ERC20 load(String contractAddress, Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) { 202 | return new ERC20(contractAddress, web3j, credentials, gasPrice, gasLimit); 203 | } 204 | 205 | @Deprecated 206 | public static ERC20 load(String contractAddress, Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit) { 207 | return new ERC20(contractAddress, web3j, transactionManager, gasPrice, gasLimit); 208 | } 209 | 210 | public static ERC20 load(String contractAddress, Web3j web3j, Credentials credentials, ContractGasProvider contractGasProvider) { 211 | return new ERC20(contractAddress, web3j, credentials, contractGasProvider); 212 | } 213 | 214 | public static ERC20 load(String contractAddress, Web3j web3j, TransactionManager transactionManager, ContractGasProvider contractGasProvider) { 215 | return new ERC20(contractAddress, web3j, transactionManager, contractGasProvider); 216 | } 217 | 218 | public static class ApprovalEventResponse extends BaseEventResponse { 219 | public String owner; 220 | 221 | public String spender; 222 | 223 | public BigInteger value; 224 | } 225 | 226 | public static class TransferEventResponse extends BaseEventResponse { 227 | public String from; 228 | 229 | public String to; 230 | 231 | public BigInteger value; 232 | } 233 | } 234 | -------------------------------------------------------------------------------- /src/main/java/io/zksync/ethereum/wrappers/IEIP1271.java: -------------------------------------------------------------------------------- 1 | package io.zksync.ethereum.wrappers; 2 | 3 | import java.math.BigInteger; 4 | import java.util.Arrays; 5 | import org.web3j.abi.TypeReference; 6 | import org.web3j.abi.datatypes.Function; 7 | import org.web3j.abi.datatypes.Type; 8 | import org.web3j.abi.datatypes.generated.Bytes4; 9 | import org.web3j.crypto.Credentials; 10 | import org.web3j.protocol.Web3j; 11 | import org.web3j.protocol.core.RemoteFunctionCall; 12 | import org.web3j.tx.Contract; 13 | import org.web3j.tx.TransactionManager; 14 | import org.web3j.tx.gas.ContractGasProvider; 15 | 16 | /** 17 | *

Auto generated code. 18 | *

Do not modify! 19 | *

Please use the web3j command line tools, 20 | * or the org.web3j.codegen.SolidityFunctionWrapperGenerator in the 21 | * codegen module to update. 22 | * 23 | *

Generated with web3j version 1.4.1. 24 | */ 25 | @SuppressWarnings("rawtypes") 26 | public class IEIP1271 extends Contract { 27 | public static final String BINARY = "Bin file was not provided"; 28 | 29 | public static final String FUNC_ISVALIDSIGNATURE = "isValidSignature"; 30 | 31 | @Deprecated 32 | protected IEIP1271(String contractAddress, Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) { 33 | super(BINARY, contractAddress, web3j, credentials, gasPrice, gasLimit); 34 | } 35 | 36 | protected IEIP1271(String contractAddress, Web3j web3j, Credentials credentials, ContractGasProvider contractGasProvider) { 37 | super(BINARY, contractAddress, web3j, credentials, contractGasProvider); 38 | } 39 | 40 | @Deprecated 41 | protected IEIP1271(String contractAddress, Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit) { 42 | super(BINARY, contractAddress, web3j, transactionManager, gasPrice, gasLimit); 43 | } 44 | 45 | protected IEIP1271(String contractAddress, Web3j web3j, TransactionManager transactionManager, ContractGasProvider contractGasProvider) { 46 | super(BINARY, contractAddress, web3j, transactionManager, contractGasProvider); 47 | } 48 | 49 | public RemoteFunctionCall isValidSignature(byte[] _hash, byte[] _signature) { 50 | final Function function = new Function(FUNC_ISVALIDSIGNATURE, 51 | Arrays.asList(new org.web3j.abi.datatypes.generated.Bytes32(_hash), 52 | new org.web3j.abi.datatypes.DynamicBytes(_signature)), 53 | Arrays.>asList(new TypeReference() {})); 54 | return executeRemoteCallSingleValueReturn(function, byte[].class); 55 | } 56 | 57 | @Deprecated 58 | public static IEIP1271 load(String contractAddress, Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) { 59 | return new IEIP1271(contractAddress, web3j, credentials, gasPrice, gasLimit); 60 | } 61 | 62 | @Deprecated 63 | public static IEIP1271 load(String contractAddress, Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit) { 64 | return new IEIP1271(contractAddress, web3j, transactionManager, gasPrice, gasLimit); 65 | } 66 | 67 | public static IEIP1271 load(String contractAddress, Web3j web3j, Credentials credentials, ContractGasProvider contractGasProvider) { 68 | return new IEIP1271(contractAddress, web3j, credentials, contractGasProvider); 69 | } 70 | 71 | public static IEIP1271 load(String contractAddress, Web3j web3j, TransactionManager transactionManager, ContractGasProvider contractGasProvider) { 72 | return new IEIP1271(contractAddress, web3j, transactionManager, contractGasProvider); 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /src/main/java/io/zksync/exception/ZkSyncException.java: -------------------------------------------------------------------------------- 1 | package io.zksync.exception; 2 | 3 | import io.zksync.transport.ZkSyncError; 4 | 5 | public class ZkSyncException extends RuntimeException { 6 | private static final long serialVersionUID = 4907339762891790110L; 7 | 8 | public ZkSyncException(String message) { 9 | super(message); 10 | } 11 | 12 | public ZkSyncException(Throwable cause) { 13 | super(cause); 14 | } 15 | 16 | public ZkSyncException(String message, Throwable cause) { 17 | super(message, cause); 18 | } 19 | 20 | public ZkSyncException(ZkSyncError error) { 21 | super(error.getMessage() + " (" + error.getCode() + ")"); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/io/zksync/exception/ZkSyncIncorrectCredentialsException.java: -------------------------------------------------------------------------------- 1 | package io.zksync.exception; 2 | 3 | import io.zksync.transport.ZkSyncError; 4 | 5 | public class ZkSyncIncorrectCredentialsException extends ZkSyncException { 6 | private static final long serialVersionUID = 5338333199906830236L; 7 | 8 | public ZkSyncIncorrectCredentialsException(String message) { 9 | super(message); 10 | } 11 | 12 | public ZkSyncIncorrectCredentialsException(Throwable cause) { 13 | super(cause); 14 | } 15 | 16 | public ZkSyncIncorrectCredentialsException(String message, Throwable cause) { 17 | super(message, cause); 18 | } 19 | 20 | public ZkSyncIncorrectCredentialsException(ZkSyncError error) { 21 | super(error.getMessage() + " (" + error.getCode() + ")"); 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/io/zksync/provider/AsyncProvider.java: -------------------------------------------------------------------------------- 1 | package io.zksync.provider; 2 | 3 | import java.math.BigDecimal; 4 | import java.math.BigInteger; 5 | import java.util.List; 6 | import java.util.concurrent.CompletableFuture; 7 | 8 | import org.apache.commons.lang3.tuple.Pair; 9 | 10 | import io.zksync.domain.ChainId; 11 | import io.zksync.domain.auth.Toggle2FA; 12 | import io.zksync.domain.contract.ContractAddress; 13 | import io.zksync.domain.fee.TransactionFeeBatchRequest; 14 | import io.zksync.domain.fee.TransactionFeeDetails; 15 | import io.zksync.domain.fee.TransactionFeeRequest; 16 | import io.zksync.domain.operation.EthOpInfo; 17 | import io.zksync.domain.state.AccountState; 18 | import io.zksync.domain.token.Token; 19 | import io.zksync.domain.token.Tokens; 20 | import io.zksync.domain.transaction.TransactionDetails; 21 | import io.zksync.domain.transaction.ZkSyncTransaction; 22 | import io.zksync.signer.EthSignature; 23 | import io.zksync.transport.HttpTransport; 24 | 25 | public interface AsyncProvider { 26 | /** 27 | * Get current state of the account 28 | * 29 | * @param accountAddress - Address of the account in hex format 30 | * @return AccountState that represent state of the account 31 | */ 32 | CompletableFuture getState(String accountAddress); 33 | 34 | /** 35 | * Get fee of transaction that means cost of transaction execution in ZkSync network 36 | * 37 | * @param feeRequest - Transaction information for estimation fee 38 | * @return Details of fee amount for transaction execution 39 | */ 40 | CompletableFuture getTransactionFee(TransactionFeeRequest feeRequest); 41 | 42 | /** 43 | * Get fee of batch of transaction that means cost of transaction batch execution in ZkSync network 44 | * 45 | * @param feeRequest - Transaction batch information for estimation fee 46 | * @return Details of fee amount for transaction execution 47 | */ 48 | CompletableFuture getTransactionFee(TransactionFeeBatchRequest feeRequest); 49 | 50 | /** 51 | * Get list of tokens supproted by ZkSync network 52 | * 53 | * @return Token information 54 | */ 55 | CompletableFuture getTokens(); 56 | 57 | /** 58 | * Get the token price in USD known to server 59 | * 60 | * @param token - Token details object 61 | * @return current token price 62 | */ 63 | CompletableFuture getTokenPrice(Token token); 64 | 65 | /** 66 | * Submit signed transaction to ZkSync network 67 | * 68 | * @param tx - Signed transaction object 69 | * @param ethereumSignature - Signature of Ethereum account as 2-FA authorization 70 | * @param fastProcessing - Mark the transaction should be executed as soon as possible 71 | * @return Hash of the sent transaction in ZkSync network 72 | */ 73 | CompletableFuture submitTx(ZkSyncTransaction tx, EthSignature ethereumSignature, boolean fastProcessing); 74 | 75 | /** 76 | * Submit signed transaction to ZkSync network 77 | * 78 | * @param tx - Signed transaction object 79 | * @param fastProcessing - Mark the transaction should be executed as soon as possible 80 | * @return Hash of the sent transaction in ZkSync network 81 | */ 82 | CompletableFuture submitTx(ZkSyncTransaction tx, boolean fastProcessing); 83 | 84 | /** 85 | * Submit signed transaction to ZkSync network 86 | * 87 | * @param tx - Signed transaction object 88 | * @param ethereumSignature - Signatures of Ethereum accounts as 2-FA authorization 89 | * @return Hash of the sent transaction in ZkSync network 90 | */ 91 | CompletableFuture submitTx(ZkSyncTransaction tx, EthSignature ...ethereumSignature); 92 | 93 | /** 94 | * Submit signed transaction batch to ZkSync network 95 | * 96 | * @param txs- List of signed transaction objects 97 | * @param ethereumSignature - Signature of Ethereum account as 2-FA authorization 98 | * @return List of hashes of the sent transactions in ZkSync network 99 | */ 100 | CompletableFuture> submitTxBatch(List> txs, EthSignature ethereumSignature); 101 | 102 | /** 103 | * Submit signed transaction batch to ZkSync network 104 | * 105 | * @param txs - List of signed transaction objects 106 | * @return List of hashes of the sent transactions in ZkSync network 107 | */ 108 | CompletableFuture> submitTxBatch(List> txs); 109 | 110 | /** 111 | * Get details of the transaction in ZkSync network by hash 112 | * 113 | * @param txHash - Hash of the transaction in format: `sync-tx:[hex]` 114 | * @return Details of the transaction 115 | */ 116 | CompletableFuture getTransactionDetails(String txHash); 117 | 118 | /** 119 | * Get address of ZkSync contract deployed in Ethereum network 120 | * 121 | * @return Address of contract in hex 122 | */ 123 | CompletableFuture contractAddress(); 124 | 125 | /** 126 | * Get information for Priority Operation by id 127 | * 128 | * @param priorityOperationId - Identifier of Priority Operation 129 | * @return Information of Priority Operation 130 | */ 131 | CompletableFuture getEthOpInfo(Integer priorityOperationId); 132 | 133 | /** 134 | * Get the amount of confirmations on Ethereum required for Priority Operation to be processed 135 | * 136 | * @return Amount of confirmations 137 | */ 138 | CompletableFuture getConfirmationsForEthOpAmount(); 139 | 140 | /** 141 | * Get hash of the transaction in Ethereum network by hash of the transaction sent in ZkSync 142 | * 143 | * @param zkSyncWithdrawalHash - Hash of the transaction in format: `sync-tx:[hex]` 144 | * @return Hash of the sent transaction in Ethereum network 145 | */ 146 | CompletableFuture getEthTransactionForWithdrawal(String zkSyncWithdrawalHash); 147 | 148 | /** 149 | * Send signed toggle 2FA request to ZkSync network. 150 | * 151 | * @param toggle2FA - Request object 152 | * @return - true if successful, false otherwise 153 | */ 154 | CompletableFuture toggle2FA(Toggle2FA toggle2FA); 155 | 156 | /** 157 | * Fetch and update local cache of token list 158 | * 159 | * @return Tokens information 160 | */ 161 | CompletableFuture updateTokenSet(); 162 | 163 | /** 164 | * Create default ZkSync provider by given chain id 165 | * 166 | * @param chainId - Chain id supproted by ZkSync network 167 | * @return ZkSync provider object 168 | */ 169 | static AsyncProvider defaultProvider(ChainId chainId) { 170 | HttpTransport transport; 171 | switch (chainId) { 172 | case Mainnet: transport = new HttpTransport("https://api.zksync.io/jsrpc"); break; 173 | case Sepolia: transport = new HttpTransport("https://sepolia-api.zksync.io/jsrpc"); break; 174 | case Goerli: transport = new HttpTransport("https://goerli-api.zksync.io/jsrpc"); break; 175 | case Localhost: transport = new HttpTransport("http://127.0.0.1:3030"); break; 176 | default: throw new IllegalArgumentException("Unsupported beta network for given chain id"); 177 | } 178 | return new DefaultAsyncProvider(transport); 179 | } 180 | 181 | static AsyncProvider betaProvider(ChainId chainId) { 182 | HttpTransport transport; 183 | switch (chainId) { 184 | case Sepolia: transport = new HttpTransport("https://sepolia-api.zksync.io/jsrpc"); break; 185 | case Goerli: transport = new HttpTransport("https://goerli-api.zksync.io/jsrpc"); break; 186 | default: throw new IllegalArgumentException("Unsupported beta network for given chain id"); 187 | } 188 | return new DefaultAsyncProvider(transport); 189 | } 190 | } 191 | -------------------------------------------------------------------------------- /src/main/java/io/zksync/provider/DefaultAsyncProvider.java: -------------------------------------------------------------------------------- 1 | package io.zksync.provider; 2 | 3 | import org.apache.commons.lang3.tuple.Pair; 4 | 5 | import io.zksync.domain.auth.Toggle2FA; 6 | import io.zksync.domain.contract.ContractAddress; 7 | import io.zksync.domain.fee.TransactionFeeBatchRequest; 8 | import io.zksync.domain.fee.TransactionFeeDetails; 9 | import io.zksync.domain.fee.TransactionFeeRequest; 10 | import io.zksync.domain.operation.EthOpInfo; 11 | import io.zksync.domain.state.AccountState; 12 | import io.zksync.domain.token.Token; 13 | import io.zksync.domain.token.Tokens; 14 | import io.zksync.domain.transaction.TransactionDetails; 15 | import io.zksync.domain.transaction.ZkSyncTransaction; 16 | import io.zksync.signer.EthSignature; 17 | import io.zksync.transport.ZkSyncSuccess; 18 | import io.zksync.transport.ZkSyncTransport; 19 | import io.zksync.transport.response.ZksAccountState; 20 | import io.zksync.transport.response.ZksContractAddress; 21 | import io.zksync.transport.response.ZksEthOpInfo; 22 | import io.zksync.transport.response.ZksGetConfirmationsForEthOpAmount; 23 | import io.zksync.transport.response.ZksSentTransaction; 24 | import io.zksync.transport.response.ZksSentTransactionBatch; 25 | import io.zksync.transport.response.ZksToggle2FA; 26 | import io.zksync.transport.response.ZksTokenPrice; 27 | import io.zksync.transport.response.ZksTokens; 28 | import io.zksync.transport.response.ZksTransactionDetails; 29 | import io.zksync.transport.response.ZksTransactionFeeDetails; 30 | import io.zksync.wallet.SignedTransaction; 31 | 32 | import java.math.BigDecimal; 33 | import java.math.BigInteger; 34 | import java.util.Arrays; 35 | import java.util.Collections; 36 | import java.util.List; 37 | import java.util.concurrent.CompletableFuture; 38 | import java.util.stream.Collectors; 39 | 40 | public class DefaultAsyncProvider implements AsyncProvider { 41 | private ZkSyncTransport transport; 42 | 43 | private Tokens tokens; 44 | 45 | public DefaultAsyncProvider(ZkSyncTransport transport) { 46 | this.transport = transport; 47 | this.tokens = null; 48 | } 49 | 50 | @Override 51 | public CompletableFuture getState(String accountAddress) { 52 | final CompletableFuture response = transport.sendAsync("account_info", Collections.singletonList(accountAddress), 53 | ZksAccountState.class); 54 | 55 | return response; 56 | } 57 | 58 | @Override 59 | public CompletableFuture getTransactionFee(TransactionFeeRequest feeRequest) { 60 | final CompletableFuture response = transport.sendAsync("get_tx_fee", 61 | Arrays.asList(feeRequest.getTransactionType().getRaw(), feeRequest.getAddress(), 62 | feeRequest.getTokenIdentifier()), 63 | ZksTransactionFeeDetails.class); 64 | 65 | return response; 66 | } 67 | 68 | @Override 69 | public CompletableFuture getTransactionFee(TransactionFeeBatchRequest feeRequest) { 70 | final CompletableFuture response = transport.sendAsync("get_txs_batch_fee_in_wei", 71 | Arrays.asList(feeRequest.getTransactionTypesRaw(), feeRequest.getAddresses(), 72 | feeRequest.getTokenIdentifier()), 73 | ZksTransactionFeeDetails.class); 74 | 75 | return response; 76 | } 77 | 78 | @Override 79 | public CompletableFuture getTokens() { 80 | if (this.tokens == null) { 81 | return this.updateTokenSet(); 82 | } else { 83 | return CompletableFuture.completedFuture(this.tokens); 84 | } 85 | } 86 | 87 | @Override 88 | public CompletableFuture getTokenPrice(Token token) { 89 | final CompletableFuture response = transport.sendAsync("get_token_price", Collections.singletonList(token.getSymbol()), 90 | ZksTokenPrice.class); 91 | 92 | return response; 93 | } 94 | 95 | @Override 96 | public CompletableFuture submitTx(ZkSyncTransaction tx, EthSignature ethereumSignature, boolean fastProcessing) { 97 | final CompletableFuture responseBody = transport.sendAsync("tx_submit", Arrays.asList(tx, ethereumSignature, fastProcessing), 98 | ZksSentTransaction.class); 99 | 100 | return responseBody; 101 | } 102 | 103 | @Override 104 | public CompletableFuture submitTx(ZkSyncTransaction tx, boolean fastProcessing) { 105 | return submitTx(tx, null, fastProcessing); 106 | } 107 | 108 | @Override 109 | public CompletableFuture submitTx(ZkSyncTransaction tx, EthSignature... ethereumSignature) { 110 | final CompletableFuture responseBody = transport.sendAsync("tx_submit", Arrays.asList(tx, ethereumSignature), 111 | ZksSentTransaction.class); 112 | 113 | return responseBody; 114 | } 115 | 116 | @Override 117 | public CompletableFuture> submitTxBatch(List> txs, EthSignature ethereumSignature) { 118 | final CompletableFuture> responseBody = transport.sendAsync("submit_txs_batch", Arrays.asList(txs.stream().map(SignedTransaction::fromPair).collect(Collectors.toList()), ethereumSignature), 119 | ZksSentTransactionBatch.class); 120 | 121 | return responseBody; 122 | } 123 | 124 | @Override 125 | public CompletableFuture> submitTxBatch(List> txs) { 126 | return submitTxBatch(txs, null); 127 | } 128 | 129 | @Override 130 | public CompletableFuture contractAddress() { 131 | final CompletableFuture contractAddress = transport.sendAsync("contract_address", Collections.emptyList(), 132 | ZksContractAddress.class); 133 | 134 | return contractAddress; 135 | } 136 | 137 | @Override 138 | public CompletableFuture getTransactionDetails(String txHash) { 139 | final CompletableFuture response = transport.sendAsync("tx_info", Collections.singletonList(txHash), 140 | ZksTransactionDetails.class); 141 | 142 | return response; 143 | } 144 | 145 | @Override 146 | public CompletableFuture getEthOpInfo(Integer priority) { 147 | final CompletableFuture response = transport.sendAsync("ethop_info", Collections.singletonList(priority), 148 | ZksEthOpInfo.class); 149 | 150 | return response; 151 | } 152 | 153 | @Override 154 | public CompletableFuture getConfirmationsForEthOpAmount() { 155 | final CompletableFuture response = transport.sendAsync("get_confirmations_for_eth_op_amount", Collections.emptyList(), 156 | ZksGetConfirmationsForEthOpAmount.class); 157 | 158 | return response; 159 | } 160 | 161 | @Override 162 | public CompletableFuture getEthTransactionForWithdrawal(String zkSyncWithdrawalHash) { 163 | final CompletableFuture response = transport.sendAsync("get_eth_tx_for_withdrawal", Collections.singletonList(zkSyncWithdrawalHash), 164 | ZksSentTransaction.class); 165 | 166 | return response; 167 | } 168 | 169 | @Override 170 | public CompletableFuture toggle2FA(Toggle2FA toggle2fa) { 171 | final CompletableFuture result = transport.sendAsync("toggle_2fa", Collections.singletonList(toggle2fa), ZksToggle2FA.class); 172 | 173 | return result.thenApply(ZkSyncSuccess::getSuccess); 174 | } 175 | 176 | @Override 177 | public CompletableFuture updateTokenSet() { 178 | final CompletableFuture response = transport.sendAsync("tokens", Collections.emptyList(), ZksTokens.class); 179 | 180 | return response.thenApply(tokens -> { 181 | this.tokens = tokens; 182 | return tokens; 183 | }); 184 | } 185 | } 186 | -------------------------------------------------------------------------------- /src/main/java/io/zksync/provider/DefaultProvider.java: -------------------------------------------------------------------------------- 1 | package io.zksync.provider; 2 | 3 | import org.apache.commons.lang3.tuple.Pair; 4 | 5 | import io.zksync.domain.auth.Toggle2FA; 6 | import io.zksync.domain.contract.ContractAddress; 7 | import io.zksync.domain.fee.TransactionFeeBatchRequest; 8 | import io.zksync.domain.fee.TransactionFeeDetails; 9 | import io.zksync.domain.fee.TransactionFeeRequest; 10 | import io.zksync.domain.operation.EthOpInfo; 11 | import io.zksync.domain.state.AccountState; 12 | import io.zksync.domain.token.Token; 13 | import io.zksync.domain.token.Tokens; 14 | import io.zksync.domain.transaction.TransactionDetails; 15 | import io.zksync.domain.transaction.ZkSyncTransaction; 16 | import io.zksync.signer.EthSignature; 17 | import io.zksync.transport.ZkSyncSuccess; 18 | import io.zksync.transport.ZkSyncTransport; 19 | import io.zksync.transport.response.ZksAccountState; 20 | import io.zksync.transport.response.ZksContractAddress; 21 | import io.zksync.transport.response.ZksEthOpInfo; 22 | import io.zksync.transport.response.ZksGetConfirmationsForEthOpAmount; 23 | import io.zksync.transport.response.ZksSentTransaction; 24 | import io.zksync.transport.response.ZksSentTransactionBatch; 25 | import io.zksync.transport.response.ZksToggle2FA; 26 | import io.zksync.transport.response.ZksTokenPrice; 27 | import io.zksync.transport.response.ZksTokens; 28 | import io.zksync.transport.response.ZksTransactionDetails; 29 | import io.zksync.transport.response.ZksTransactionFeeDetails; 30 | import io.zksync.wallet.SignedTransaction; 31 | 32 | import java.math.BigDecimal; 33 | import java.math.BigInteger; 34 | import java.util.Arrays; 35 | import java.util.Collections; 36 | import java.util.List; 37 | import java.util.stream.Collectors; 38 | 39 | public class DefaultProvider implements Provider { 40 | 41 | private ZkSyncTransport transport; 42 | 43 | private Tokens tokens; 44 | 45 | public DefaultProvider(ZkSyncTransport transport) { 46 | this.transport = transport; 47 | this.tokens = null; 48 | } 49 | 50 | @Override 51 | public AccountState getState(String accountAddress) { 52 | final AccountState response = transport.send("account_info", Collections.singletonList(accountAddress), 53 | ZksAccountState.class); 54 | 55 | return response; 56 | } 57 | 58 | @Override 59 | public TransactionFeeDetails getTransactionFee(TransactionFeeRequest feeRequest) { 60 | TransactionFeeDetails response = transport.send("get_tx_fee", 61 | Arrays.asList(feeRequest.getTransactionType().getRaw(), feeRequest.getAddress(), 62 | feeRequest.getTokenIdentifier()), 63 | ZksTransactionFeeDetails.class); 64 | 65 | return response; 66 | } 67 | 68 | @Override 69 | public TransactionFeeDetails getTransactionFee(TransactionFeeBatchRequest feeRequest) { 70 | TransactionFeeDetails response = transport.send("get_txs_batch_fee_in_wei", 71 | Arrays.asList(feeRequest.getTransactionTypesRaw(), feeRequest.getAddresses(), 72 | feeRequest.getTokenIdentifier()), 73 | ZksTransactionFeeDetails.class); 74 | 75 | return response; 76 | } 77 | 78 | @Override 79 | public Tokens getTokens() { 80 | if (this.tokens == null) { 81 | this.updateTokenSet(); 82 | } 83 | 84 | return this.tokens; 85 | } 86 | 87 | @Override 88 | public BigDecimal getTokenPrice(Token token) { 89 | final BigDecimal response = transport.send("get_token_price", Collections.singletonList(token.getSymbol()), 90 | ZksTokenPrice.class); 91 | 92 | return response; 93 | } 94 | 95 | @Override 96 | public String submitTx(ZkSyncTransaction tx, EthSignature ethereumSignature, boolean fastProcessing) { 97 | final String responseBody = transport.send("tx_submit", Arrays.asList(tx, ethereumSignature, fastProcessing), 98 | ZksSentTransaction.class); 99 | 100 | return responseBody; 101 | } 102 | 103 | @Override 104 | public String submitTx(ZkSyncTransaction tx, boolean fastProcessing) { 105 | return submitTx(tx, null, fastProcessing); 106 | } 107 | 108 | @Override 109 | public String submitTx(ZkSyncTransaction tx, EthSignature... ethereumSignature) { 110 | final String responseBody = transport.send("tx_submit", Arrays.asList(tx, ethereumSignature), 111 | ZksSentTransaction.class); 112 | 113 | return responseBody; 114 | } 115 | 116 | @Override 117 | public List submitTxBatch(List> txs, EthSignature ethereumSignature) { 118 | final List responseBody = transport.send("submit_txs_batch", Arrays.asList(txs.stream().map(SignedTransaction::fromPair).collect(Collectors.toList()), ethereumSignature), 119 | ZksSentTransactionBatch.class); 120 | 121 | return responseBody; 122 | } 123 | 124 | @Override 125 | public List submitTxBatch(List> txs) { 126 | return submitTxBatch(txs, null); 127 | } 128 | 129 | @Override 130 | public ContractAddress contractAddress() { 131 | final ContractAddress contractAddress = transport.send("contract_address", Collections.emptyList(), 132 | ZksContractAddress.class); 133 | 134 | return contractAddress; 135 | } 136 | 137 | @Override 138 | public TransactionDetails getTransactionDetails(String txHash) { 139 | final TransactionDetails response = transport.send("tx_info", Collections.singletonList(txHash), 140 | ZksTransactionDetails.class); 141 | 142 | return response; 143 | } 144 | 145 | @Override 146 | public EthOpInfo getEthOpInfo(Integer priority) { 147 | final EthOpInfo response = transport.send("ethop_info", Collections.singletonList(priority), 148 | ZksEthOpInfo.class); 149 | 150 | return response; 151 | } 152 | 153 | @Override 154 | public BigInteger getConfirmationsForEthOpAmount() { 155 | final BigInteger response = transport.send("get_confirmations_for_eth_op_amount", Collections.emptyList(), 156 | ZksGetConfirmationsForEthOpAmount.class); 157 | 158 | return response; 159 | } 160 | 161 | @Override 162 | public String getEthTransactionForWithdrawal(String zkSyncWithdrawalHash) { 163 | final String response = transport.send("get_eth_tx_for_withdrawal", Collections.singletonList(zkSyncWithdrawalHash), 164 | ZksSentTransaction.class); 165 | 166 | return response; 167 | } 168 | 169 | @Override 170 | public boolean toggle2FA(Toggle2FA toggle2fa) { 171 | final ZkSyncSuccess result = transport.send("toggle_2fa", Collections.singletonList(toggle2fa), ZksToggle2FA.class); 172 | 173 | return result.getSuccess(); 174 | } 175 | 176 | public void updateTokenSet() { 177 | final Tokens response = transport.send("tokens", Collections.emptyList(), ZksTokens.class); 178 | this.tokens = response; 179 | } 180 | } 181 | -------------------------------------------------------------------------------- /src/main/java/io/zksync/provider/Provider.java: -------------------------------------------------------------------------------- 1 | package io.zksync.provider; 2 | 3 | import java.math.BigDecimal; 4 | import java.math.BigInteger; 5 | import java.util.List; 6 | 7 | import org.apache.commons.lang3.tuple.Pair; 8 | 9 | import io.zksync.domain.ChainId; 10 | import io.zksync.domain.auth.Toggle2FA; 11 | import io.zksync.domain.contract.ContractAddress; 12 | import io.zksync.domain.fee.TransactionFeeBatchRequest; 13 | import io.zksync.domain.fee.TransactionFeeDetails; 14 | import io.zksync.domain.fee.TransactionFeeRequest; 15 | import io.zksync.domain.operation.EthOpInfo; 16 | import io.zksync.domain.state.AccountState; 17 | import io.zksync.domain.token.Token; 18 | import io.zksync.domain.token.Tokens; 19 | import io.zksync.domain.transaction.TransactionDetails; 20 | import io.zksync.domain.transaction.ZkSyncTransaction; 21 | import io.zksync.signer.EthSignature; 22 | import io.zksync.transport.HttpTransport; 23 | 24 | public interface Provider { 25 | 26 | /** 27 | * Get current state of the account 28 | * 29 | * @param accountAddress - Address of the account in hex format 30 | * @return AccountState that represent state of the account 31 | */ 32 | AccountState getState(String accountAddress); 33 | 34 | /** 35 | * Get fee of transaction that means cost of transaction execution in ZkSync network 36 | * 37 | * @param feeRequest - Transaction information for estimation fee 38 | * @return Details of fee amount for transaction execution 39 | */ 40 | TransactionFeeDetails getTransactionFee(TransactionFeeRequest feeRequest); 41 | 42 | /** 43 | * Get fee of batch of transaction that means cost of transaction batch execution in ZkSync network 44 | * 45 | * @param feeRequest - Transaction batch information for estimation fee 46 | * @return Details of fee amount for transaction execution 47 | */ 48 | TransactionFeeDetails getTransactionFee(TransactionFeeBatchRequest feeRequest); 49 | 50 | /** 51 | * Get list of tokens supproted by ZkSync network 52 | * 53 | * @return Token information 54 | */ 55 | Tokens getTokens(); 56 | 57 | /** 58 | * Get the token price in USD known to server 59 | * 60 | * @param token - Token details object 61 | * @return current token price 62 | */ 63 | BigDecimal getTokenPrice(Token token); 64 | 65 | /** 66 | * Submit signed transaction to ZkSync network 67 | * 68 | * @param tx - Signed transaction object 69 | * @param ethereumSignature - Signature of Ethereum account as 2-FA authorization 70 | * @param fastProcessing - Mark the transaction should be executed as soon as possible 71 | * @return Hash of the sent transaction in ZkSync network 72 | */ 73 | String submitTx(ZkSyncTransaction tx, EthSignature ethereumSignature, boolean fastProcessing); 74 | 75 | /** 76 | * Submit signed transaction to ZkSync network 77 | * 78 | * @param tx - Signed transaction object 79 | * @param fastProcessing - Mark the transaction should be executed as soon as possible 80 | * @return Hash of the sent transaction in ZkSync network 81 | */ 82 | String submitTx(ZkSyncTransaction tx, boolean fastProcessing); 83 | 84 | /** 85 | * Submit signed transaction to ZkSync network 86 | * 87 | * @param tx - Signed transaction object 88 | * @param ethereumSignature - Signatures of Ethereum accounts as 2-FA authorization 89 | * @return Hash of the sent transaction in ZkSync network 90 | */ 91 | String submitTx(ZkSyncTransaction tx, EthSignature ...ethereumSignature); 92 | 93 | /** 94 | * Submit signed transaction batch to ZkSync network 95 | * 96 | * @param txs- List of signed transaction objects 97 | * @param ethereumSignature - Signature of Ethereum account as 2-FA authorization 98 | * @return List of hashes of the sent transactions in ZkSync network 99 | */ 100 | List submitTxBatch(List> txs, EthSignature ethereumSignature); 101 | 102 | /** 103 | * Submit signed transaction batch to ZkSync network 104 | * 105 | * @param txs - List of signed transaction objects 106 | * @return List of hashes of the sent transactions in ZkSync network 107 | */ 108 | List submitTxBatch(List> txs); 109 | 110 | /** 111 | * Get details of the transaction in ZkSync network by hash 112 | * 113 | * @param txHash - Hash of the transaction in format: `sync-tx:[hex]` 114 | * @return Details of the transaction 115 | */ 116 | TransactionDetails getTransactionDetails(String txHash); 117 | 118 | /** 119 | * Get address of ZkSync contract deployed in Ethereum network 120 | * 121 | * @return Address of contract in hex 122 | */ 123 | ContractAddress contractAddress(); 124 | 125 | /** 126 | * Get information for Priority Operation by id 127 | * 128 | * @param priorityOperationId - Identifier of Priority Operation 129 | * @return Information of Priority Operation 130 | */ 131 | EthOpInfo getEthOpInfo(Integer priorityOperationId); 132 | 133 | /** 134 | * Get the amount of confirmations on Ethereum required for Priority Operation to be processed 135 | * 136 | * @return Amount of confirmations 137 | */ 138 | BigInteger getConfirmationsForEthOpAmount(); 139 | 140 | /** 141 | * Get hash of the transaction in Ethereum network by hash of the transaction sent in ZkSync 142 | * 143 | * @param zkSyncWithdrawalHash - Hash of the transaction in format: `sync-tx:[hex]` 144 | * @return Hash of the sent transaction in Ethereum network 145 | */ 146 | String getEthTransactionForWithdrawal(String zkSyncWithdrawalHash); 147 | 148 | /** 149 | * Send signed toggle 2FA request to ZkSync network. 150 | * 151 | * @param toggle2FA - Request object 152 | * @return - true if successful, false otherwise 153 | */ 154 | boolean toggle2FA(Toggle2FA toggle2FA); 155 | 156 | /** 157 | * Fetch and update local cache of token list 158 | * 159 | */ 160 | void updateTokenSet(); 161 | 162 | /** 163 | * Create default ZkSync provider by given chain id 164 | * 165 | * @param chainId - Chain id supproted by ZkSync network 166 | * @return ZkSync provider object 167 | */ 168 | static Provider defaultProvider(ChainId chainId) { 169 | HttpTransport transport; 170 | switch (chainId) { 171 | case Mainnet: transport = new HttpTransport("https://api.zksync.io/jsrpc"); break; 172 | case Sepolia: transport = new HttpTransport("https://sepolia-api.zksync.io/jsrpc"); break; 173 | case Goerli: transport = new HttpTransport("https://goerli-api.zksync.io/jsrpc"); break; 174 | case Localhost: transport = new HttpTransport("http://127.0.0.1:3030"); break; 175 | default: throw new IllegalArgumentException("Unsupported network for given chain id"); 176 | } 177 | return new DefaultProvider(transport); 178 | } 179 | 180 | static Provider betaProvider(ChainId chainId) { 181 | HttpTransport transport; 182 | switch (chainId) { 183 | case Sepolia: transport = new HttpTransport("https://sepolia-beta-api.zksync.io/jsrpc"); break; 184 | case Goerli: transport = new HttpTransport("https://goerli-beta-api.zksync.io/jsrpc"); break; 185 | default: throw new IllegalArgumentException("Unsupported beta network for given chain id"); 186 | } 187 | return new DefaultProvider(transport); 188 | } 189 | 190 | } 191 | -------------------------------------------------------------------------------- /src/main/java/io/zksync/signer/Bits.java: -------------------------------------------------------------------------------- 1 | package io.zksync.signer; 2 | 3 | public class Bits { 4 | 5 | boolean[] bits; 6 | 7 | public Bits(int size) { 8 | bits = new boolean[size]; 9 | } 10 | 11 | public Bits(boolean[] bits) { 12 | this.bits = bits; 13 | } 14 | 15 | public boolean get(int i) { 16 | return bits[i]; 17 | } 18 | 19 | public void set(int index) { 20 | bits[index] = true; 21 | } 22 | 23 | public void set(int index, boolean value) { 24 | bits[index] = value; 25 | } 26 | 27 | public void set(int index, int value) { 28 | bits[index] = value == 0 ? false : true; 29 | } 30 | 31 | public int size() { 32 | return bits.length; 33 | } 34 | 35 | public Bits reverse() { 36 | boolean[] reversed = new boolean[bits.length]; 37 | int bitsLength = bits.length; 38 | 39 | for (int i = 0; i < bitsLength; i++) { 40 | reversed[i] = bits[bitsLength - 1 - i]; 41 | } 42 | 43 | return new Bits(reversed); 44 | } 45 | 46 | public String toString() { 47 | final StringBuilder builder = new StringBuilder(); 48 | for (boolean bit : bits) { 49 | builder.append(bit ? 1 : 0); 50 | builder.append(", "); 51 | } 52 | return builder.toString(); 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/main/java/io/zksync/signer/Create2EthSigner.java: -------------------------------------------------------------------------------- 1 | package io.zksync.signer; 2 | 3 | import java.io.ByteArrayOutputStream; 4 | import java.io.IOException; 5 | import java.math.BigInteger; 6 | import java.util.Collection; 7 | import java.util.concurrent.CompletableFuture; 8 | 9 | import org.bouncycastle.util.Arrays; 10 | import org.web3j.crypto.Hash; 11 | import org.web3j.protocol.Web3j; 12 | import org.web3j.tx.ReadonlyTransactionManager; 13 | import org.web3j.tx.TransactionManager; 14 | import org.web3j.utils.Numeric; 15 | 16 | import io.zksync.domain.auth.ChangePubKeyCREATE2; 17 | import io.zksync.domain.swap.Order; 18 | import io.zksync.domain.token.Token; 19 | import io.zksync.domain.token.TokenId; 20 | import io.zksync.domain.transaction.ChangePubKey; 21 | import io.zksync.domain.transaction.ZkSyncTransaction; 22 | import io.zksync.exception.ZkSyncException; 23 | 24 | public class Create2EthSigner implements EthSigner { 25 | private final TransactionManager transactionManager; 26 | 27 | private ChangePubKeyCREATE2 authData; 28 | private String address; 29 | 30 | private Create2EthSigner(String address, ChangePubKeyCREATE2 create2Data, TransactionManager transactionManager) { 31 | this.transactionManager = transactionManager; 32 | this.authData = create2Data; 33 | this.address = address; 34 | } 35 | 36 | public static Create2EthSigner fromData(Web3j web3j, String zkSyncAddress, ChangePubKeyCREATE2 create2Data) { 37 | final byte[] pubKeyHashStripped = Numeric.hexStringToByteArray(zkSyncAddress.replace("sync:", "").toLowerCase()); 38 | final byte[] arg = Numeric.hexStringToByteArray(create2Data.getSaltArg()); 39 | 40 | final byte[] salt = generateSalt(arg, pubKeyHashStripped); 41 | final String address = generateAddress(create2Data.getCreatorAddress(), salt, Numeric.hexStringToByteArray(create2Data.getCodeHash())); 42 | final TransactionManager transactionManager = new ReadonlyTransactionManager(web3j, create2Data.getCreatorAddress()); 43 | return new Create2EthSigner(address, create2Data, transactionManager); 44 | } 45 | 46 | public static Create2EthSigner fromData(String zkSyncAddress, ChangePubKeyCREATE2 create2Data) { 47 | final byte[] pubKeyHashStripped = Numeric.hexStringToByteArray(zkSyncAddress.replace("sync:", "").toLowerCase()); 48 | final byte[] arg = Numeric.hexStringToByteArray(create2Data.getSaltArg()); 49 | 50 | final byte[] salt = generateSalt(arg, pubKeyHashStripped); 51 | final String address = generateAddress(create2Data.getCreatorAddress(), salt, Numeric.hexStringToByteArray(create2Data.getCodeHash())); 52 | return new Create2EthSigner(address, create2Data, null); 53 | } 54 | 55 | public static Create2EthSigner fromData(Web3j web3j, ZkSigner zkSigner, ChangePubKeyCREATE2 create2Data) { 56 | return Create2EthSigner.fromData(web3j, zkSigner.getPublicKeyHash(), create2Data); 57 | } 58 | 59 | public static Create2EthSigner fromData(ZkSigner zkSigner, ChangePubKeyCREATE2 create2Data) { 60 | return Create2EthSigner.fromData(zkSigner.getPublicKeyHash(), create2Data); 61 | } 62 | 63 | @Override 64 | public String getAddress() { 65 | return address; 66 | } 67 | 68 | @Override 69 | public TransactionManager getTransactionManager() { 70 | return this.transactionManager; 71 | } 72 | 73 | @Override 74 | public CompletableFuture> signAuth( 75 | ChangePubKey changePubKey) { 76 | changePubKey.setEthAuthData(authData); 77 | return CompletableFuture.completedFuture(changePubKey); 78 | } 79 | 80 | @Override 81 | public CompletableFuture signToggle(boolean enable, Long timestamp) { 82 | return CompletableFuture.completedFuture(null); 83 | } 84 | 85 | @Override 86 | public CompletableFuture signToggle(boolean enable, Long timestamp, String publicKeyHash) { 87 | return CompletableFuture.completedFuture(null); 88 | } 89 | 90 | @Override 91 | public CompletableFuture signTransaction(T transaction, Integer nonce, 92 | Token token, BigInteger fee) { 93 | return CompletableFuture.completedFuture(null); 94 | } 95 | 96 | @Override 97 | public CompletableFuture signOrder(Order order, T tokenSell, T tokenBuy) { 98 | return CompletableFuture.completedFuture(null); 99 | } 100 | 101 | @Override 102 | public CompletableFuture signBatch(Collection transactions, 103 | Integer nonce, Token token, BigInteger fee) { 104 | return CompletableFuture.completedFuture(null); 105 | } 106 | 107 | @Override 108 | public CompletableFuture signMessage(byte[] message) { 109 | return CompletableFuture.completedFuture(null); 110 | } 111 | 112 | @Override 113 | public CompletableFuture signMessage(byte[] message, boolean addPrefix) { 114 | return CompletableFuture.completedFuture(null); 115 | } 116 | 117 | @Override 118 | public CompletableFuture verifySignature(EthSignature signature, byte[] message) { 119 | throw new UnsupportedOperationException("Create2 signer does not support signatures"); 120 | } 121 | 122 | @Override 123 | public CompletableFuture verifySignature(EthSignature signature, byte[] message, boolean prefixed) { 124 | throw new UnsupportedOperationException("Create2 signer does not support signatures"); 125 | } 126 | 127 | private static byte[] generateSalt(byte[] saltArg, byte[] pubKeyHash) { 128 | try { 129 | final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); 130 | 131 | outputStream.write(saltArg); 132 | outputStream.write(pubKeyHash); 133 | 134 | byte[] data = outputStream.toByteArray(); 135 | 136 | byte[] hash = Hash.sha3(data); 137 | 138 | return hash; 139 | } catch (IOException e) { 140 | throw new ZkSyncException(e); 141 | } 142 | } 143 | 144 | private static String generateAddress(String creatorAddress, byte[] salt, byte[] codeHash) { 145 | try { 146 | final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); 147 | 148 | outputStream.write(0xff); 149 | outputStream.write(Numeric.hexStringToByteArray(creatorAddress)); 150 | outputStream.write(salt); 151 | outputStream.write(codeHash); 152 | 153 | byte[] data = outputStream.toByteArray(); 154 | 155 | byte[] hash = Hash.sha3(data); 156 | byte[] address = Arrays.copyOfRange(hash, 12, hash.length); 157 | 158 | return Numeric.toHexString(address); 159 | } catch (IOException e) { 160 | throw new ZkSyncException(e); 161 | } 162 | } 163 | 164 | } 165 | -------------------------------------------------------------------------------- /src/main/java/io/zksync/signer/DefaultEthSigner.java: -------------------------------------------------------------------------------- 1 | package io.zksync.signer; 2 | 3 | import io.zksync.domain.auth.ChangePubKeyECDSA; 4 | import io.zksync.domain.swap.Order; 5 | import io.zksync.domain.token.Token; 6 | import io.zksync.domain.token.TokenId; 7 | import io.zksync.domain.transaction.*; 8 | import io.zksync.ethereum.transaction.NoOpTransactionManager; 9 | import io.zksync.ethereum.wrappers.IEIP1271; 10 | import io.zksync.exception.ZkSyncException; 11 | 12 | import org.web3j.crypto.Bip32ECKeyPair; 13 | import org.web3j.crypto.Credentials; 14 | import org.web3j.crypto.ECDSASignature; 15 | import org.web3j.crypto.Hash; 16 | import org.web3j.crypto.Keys; 17 | import org.web3j.crypto.MnemonicUtils; 18 | import org.web3j.crypto.Sign; 19 | import org.web3j.protocol.Web3j; 20 | import org.web3j.tx.RawTransactionManager; 21 | import org.web3j.tx.TransactionManager; 22 | import org.web3j.utils.Numeric; 23 | 24 | import java.io.ByteArrayOutputStream; 25 | import java.io.IOException; 26 | import java.math.BigInteger; 27 | import java.security.SignatureException; 28 | import java.util.Arrays; 29 | import java.util.Collection; 30 | import java.util.concurrent.CompletableFuture; 31 | import java.util.stream.Collectors; 32 | 33 | import static io.zksync.signer.SigningUtils.*; 34 | 35 | public class DefaultEthSigner implements EthSigner { 36 | 37 | private final Credentials credentials; 38 | private final TransactionManager transactionManager; 39 | private final String address; 40 | 41 | private DefaultEthSigner(TransactionManager transactionManager, Credentials credentials) { 42 | this.credentials = credentials; 43 | this.transactionManager = transactionManager; 44 | this.address = credentials.getAddress(); 45 | } 46 | 47 | private DefaultEthSigner(TransactionManager transactionManager, Credentials credentials, String address) { 48 | this.credentials = credentials; 49 | this.transactionManager = transactionManager; 50 | this.address = address; 51 | } 52 | 53 | public static DefaultEthSigner fromMnemonic(String mnemonic) { 54 | Credentials credentials = generateCredentialsFromMnemonic(mnemonic, 0); 55 | return new DefaultEthSigner(new NoOpTransactionManager(credentials), credentials); 56 | } 57 | 58 | public static DefaultEthSigner fromMnemonic(String mnemonic, int accountIndex) { 59 | Credentials credentials = generateCredentialsFromMnemonic(mnemonic, accountIndex); 60 | return new DefaultEthSigner(new NoOpTransactionManager(credentials), credentials); 61 | } 62 | 63 | public static DefaultEthSigner fromRawPrivateKey(String rawPrivateKey) { 64 | Credentials credentials = Credentials.create(rawPrivateKey); 65 | return new DefaultEthSigner(new NoOpTransactionManager(credentials), credentials); 66 | } 67 | 68 | public static DefaultEthSigner fromMnemonic(Web3j web3j, String mnemonic) { 69 | Credentials credentials = generateCredentialsFromMnemonic(mnemonic, 0); 70 | return new DefaultEthSigner(new RawTransactionManager(web3j, credentials), credentials); 71 | } 72 | 73 | public static DefaultEthSigner fromMnemonic(Web3j web3j, String mnemonic, int accountIndex) { 74 | Credentials credentials = generateCredentialsFromMnemonic(mnemonic, accountIndex); 75 | return new DefaultEthSigner(new RawTransactionManager(web3j, credentials), credentials); 76 | } 77 | 78 | public static DefaultEthSigner fromRawPrivateKey(Web3j web3j, String rawPrivateKey) { 79 | Credentials credentials = Credentials.create(rawPrivateKey); 80 | return new DefaultEthSigner(new RawTransactionManager(web3j, credentials), credentials); 81 | } 82 | 83 | public static DefaultEthSigner fromMnemonicEIP1271(Web3j web3j, String mnemonic, String contractAddress) { 84 | Credentials credentials = generateCredentialsFromMnemonic(mnemonic, 0); 85 | return new DefaultEthSigner(new RawTransactionManager(web3j, credentials), credentials, contractAddress); 86 | } 87 | 88 | public static DefaultEthSigner fromMnemonicEIP1271(Web3j web3j, String mnemonic, int accountIndex, String contractAddress) { 89 | Credentials credentials = generateCredentialsFromMnemonic(mnemonic, accountIndex); 90 | return new DefaultEthSigner(new RawTransactionManager(web3j, credentials), credentials, contractAddress); 91 | } 92 | 93 | public static DefaultEthSigner fromRawPrivateKeyEIP1271(Web3j web3j, String rawPrivateKey, String contractAddress) { 94 | Credentials credentials = Credentials.create(rawPrivateKey); 95 | return new DefaultEthSigner(new RawTransactionManager(web3j, credentials), credentials, contractAddress); 96 | } 97 | 98 | public String getAddress() { 99 | return this.address; 100 | } 101 | 102 | public TransactionManager getTransactionManager() { 103 | return this.transactionManager; 104 | } 105 | 106 | @Override 107 | public CompletableFuture> signAuth(ChangePubKey changePubKey) { 108 | ChangePubKeyECDSA auth = new ChangePubKeyECDSA(null, Numeric.toHexString(Numeric.toBytesPadded(BigInteger.ZERO, 32))); 109 | return signMessage(getChangePubKeyData(changePubKey.getNewPkHash(), changePubKey.getNonce(), changePubKey.getAccountId(), auth)) 110 | .thenApply(sig -> { 111 | auth.setEthSignature(sig.getSignature()); 112 | changePubKey.setEthAuthData(auth); 113 | return changePubKey; 114 | }); 115 | } 116 | 117 | @Override 118 | public CompletableFuture signToggle(boolean enable, Long timestamp) { 119 | final String message = SigningUtils.getToggle2FAMessage(enable, timestamp); 120 | 121 | return signMessage(message.getBytes(), true); 122 | } 123 | 124 | @Override 125 | public CompletableFuture signToggle(boolean enable, Long timestamp, String publicKeyHash) { 126 | final String message = SigningUtils.getToggle2FAMessage(enable, timestamp, publicKeyHash); 127 | 128 | return signMessage(message.getBytes(), true); 129 | } 130 | 131 | public CompletableFuture signTransaction(T tx, Integer nonce, Token token, BigInteger fee) { 132 | switch (tx.getType()) { 133 | case "ChangePubKey": 134 | ChangePubKey changePubKey = (ChangePubKey) tx; 135 | return signMessage(getChangePubKeyData(changePubKey.getNewPkHash(), nonce, changePubKey.getAccountId(), changePubKey.getEthAuthData())); 136 | case "ForcedExit": 137 | ForcedExit forcedExit = (ForcedExit) tx; 138 | return signMessage(String.join("\n", getForcedExitMessagePart(forcedExit.getTarget(), token, fee), getNonceMessagePart(nonce)).getBytes()); 139 | case "MintNFT": 140 | MintNFT mintNFT = (MintNFT) tx; 141 | return signMessage(String.join("\n", getMintNFTMessagePart(mintNFT.getContentHash(), mintNFT.getRecipient(), token, fee), getNonceMessagePart(nonce)).getBytes()); 142 | case "Transfer": 143 | Transfer transfer = (Transfer) tx; 144 | TokenId tokenId = transfer.getTokenId() != null ? transfer.getTokenId() : token; 145 | return signMessage(String.join("\n", getTransferMessagePart(transfer.getTo(), transfer.getAccountId(), transfer.getAmount(), tokenId, new BigInteger(transfer.getFee())), getNonceMessagePart(nonce)).getBytes()); 146 | case "Withdraw": 147 | Withdraw withdraw = (Withdraw) tx; 148 | return signMessage(String.join("\n", getWithdrawMessagePart(withdraw.getTo(), withdraw.getAccountId(), withdraw.getAmount(), token, fee), getNonceMessagePart(nonce)).getBytes()); 149 | case "WithdrawNFT": 150 | WithdrawNFT withdrawNft = (WithdrawNFT) tx; 151 | return signMessage(String.join("\n", getWithdrawNFTMessagePart(withdrawNft.getTo(), withdrawNft.getToken(), token, fee), getNonceMessagePart(nonce)).getBytes()); 152 | case "Swap": 153 | return signMessage(String.join("\n", getSwapMessagePart(token, fee), getNonceMessagePart(nonce)).getBytes()); 154 | default: throw new IllegalArgumentException(String.format("Transaction type {} is not supported yet", tx.getType())); 155 | } 156 | } 157 | 158 | @Override 159 | public CompletableFuture signOrder(Order order, T tokenSell, T tokenBuy) { 160 | String message = getOrderMessagePart(order.getRecipientAddress(), order.getAmount(), tokenSell, tokenBuy, order.getRatio(), order.getNonce()); 161 | 162 | return signMessage(message.getBytes()); 163 | } 164 | 165 | public CompletableFuture signBatch(Collection transactions, Integer nonce, Token token, BigInteger fee) { 166 | String message = transactions.stream() 167 | .map(tx -> { 168 | switch (tx.getType()) { 169 | case "ForcedExit": 170 | ForcedExit forcedExit = (ForcedExit) tx; 171 | return getForcedExitMessagePart(forcedExit.getTarget(), token, fee); 172 | case "MintNFT": 173 | MintNFT mintNFT = (MintNFT) tx; 174 | return getMintNFTMessagePart(mintNFT.getRecipient(), mintNFT.getContentHash(), token, fee); 175 | case "Transfer": 176 | Transfer transfer = (Transfer) tx; 177 | TokenId tokenId = transfer.getTokenId() != null ? transfer.getTokenId() : token; 178 | return getTransferMessagePart(transfer.getTo(), transfer.getAccountId(), transfer.getAmount(), tokenId, new BigInteger(transfer.getFee())); 179 | case "Withdraw": 180 | Withdraw withdraw = (Withdraw) tx; 181 | return getWithdrawMessagePart(withdraw.getTo(), withdraw.getAccountId(), withdraw.getAmount(), token, fee); 182 | case "WithdrawNFT": 183 | WithdrawNFT withdrawNft = (WithdrawNFT) tx; 184 | return getWithdrawNFTMessagePart(withdrawNft.getTo(), withdrawNft.getToken(), token, fee); 185 | case "Swap": 186 | return getSwapMessagePart(token, fee); 187 | default: throw new IllegalArgumentException(String.format("Transaction type {} is not supported by batch", tx.getType())); 188 | } 189 | }) 190 | .collect(Collectors.joining("\n")); 191 | String result = String.join("\n", message, getNonceMessagePart(nonce)); 192 | return signMessage(result.getBytes()); 193 | } 194 | 195 | public CompletableFuture signMessage(byte[] message) { 196 | return signMessage(message, true); 197 | } 198 | 199 | public CompletableFuture signMessage(byte[] message, boolean addPrefix) { 200 | Sign.SignatureData sig = addPrefix ? 201 | Sign.signPrefixedMessage(message, credentials.getEcKeyPair()) : 202 | Sign.signMessage(message, credentials.getEcKeyPair()); 203 | 204 | final ByteArrayOutputStream output = new ByteArrayOutputStream(); 205 | 206 | try { 207 | output.write(sig.getR()); 208 | output.write(sig.getS()); 209 | output.write(sig.getV()); 210 | } catch (IOException e) { 211 | throw new ZkSyncException("Error when creating ETH signature", e); 212 | } 213 | 214 | final String signature = Numeric.toHexString(output.toByteArray()); 215 | 216 | return this.getEthSignatureType(output.toByteArray(), message, addPrefix) 217 | .thenApply(type -> EthSignature.builder().signature(signature).type(type).build()); 218 | } 219 | 220 | public CompletableFuture verifySignature(EthSignature signature, byte[] message) throws SignatureException { 221 | return verifySignature(signature, message, true); 222 | } 223 | 224 | public CompletableFuture verifySignature(EthSignature signature, byte[] message, boolean prefixed) throws SignatureException { 225 | byte[] sig = Numeric.hexStringToByteArray(signature.getSignature()); 226 | return this.getEthSignatureType(sig, message, prefixed) 227 | .thenApply(ignored -> true) 228 | .exceptionally(ignored -> false); 229 | } 230 | 231 | private CompletableFuture getEthSignatureType(byte[] signature, byte[] message, boolean prefixed) { 232 | byte[] messageHash = prefixed ? EthSigner.getEthereumMessageHash(message) : Hash.sha3(message); 233 | 234 | String address = DefaultEthSigner.ecrecover(signature, messageHash); 235 | 236 | if (address.equalsIgnoreCase(this.address)) { 237 | return CompletableFuture.completedFuture(EthSignature.SignatureType.EthereumSignature); 238 | } else { 239 | IEIP1271 validator = IEIP1271.load(this.address, null, this.getTransactionManager(), null); 240 | return validator.isValidSignature(messageHash, signature).sendAsync() 241 | .thenApply(result -> { 242 | if (Arrays.equals(result, EIP1271_SUCCESS_VALUE)) { 243 | return EthSignature.SignatureType.EIP1271Signature; 244 | } else { 245 | throw new ZkSyncException("Invalid signature"); 246 | } 247 | }); 248 | } 249 | 250 | } 251 | 252 | private static String ecrecover(byte[] signature, byte[] hash) { 253 | ECDSASignature sig = new ECDSASignature( 254 | Numeric.toBigInt(Arrays.copyOfRange(signature, 0, 32)), 255 | Numeric.toBigInt(Arrays.copyOfRange(signature, 32, 64)) 256 | ); 257 | 258 | byte v = signature[64]; 259 | 260 | int recId; 261 | if (v >= 3) { 262 | recId = v - 27; 263 | } else { 264 | recId = v; 265 | } 266 | 267 | BigInteger recovered = Sign.recoverFromSignature(recId, sig, hash); 268 | return "0x" + Keys.getAddress(recovered); 269 | } 270 | 271 | private static Credentials generateCredentialsFromMnemonic(String mnemonic, int accountIndex) { 272 | //m/44'/60'/0'/0 derivation path 273 | int[] derivationPath = {44 | Bip32ECKeyPair.HARDENED_BIT, 60 | Bip32ECKeyPair.HARDENED_BIT, 0 | Bip32ECKeyPair.HARDENED_BIT, 0, accountIndex}; 274 | 275 | // Generate a BIP32 master keypair from the mnemonic phrase 276 | Bip32ECKeyPair masterKeypair = Bip32ECKeyPair.generateKeyPair( 277 | MnemonicUtils.generateSeed(mnemonic, "")); 278 | 279 | // Derive the keypair using the derivation path 280 | Bip32ECKeyPair derivedKeyPair = Bip32ECKeyPair.deriveKeyPair(masterKeypair, derivationPath); 281 | 282 | // Load the wallet for the derived keypair 283 | return Credentials.create(derivedKeyPair); 284 | } 285 | } 286 | -------------------------------------------------------------------------------- /src/main/java/io/zksync/signer/EthSignature.java: -------------------------------------------------------------------------------- 1 | package io.zksync.signer; 2 | 3 | import lombok.AllArgsConstructor; 4 | import lombok.Builder; 5 | import lombok.EqualsAndHashCode; 6 | import lombok.Getter; 7 | import lombok.ToString; 8 | 9 | @Getter 10 | @Builder 11 | @ToString 12 | @EqualsAndHashCode 13 | @AllArgsConstructor 14 | public class EthSignature { 15 | 16 | private SignatureType type; 17 | 18 | private String signature; 19 | 20 | public enum SignatureType { 21 | EthereumSignature, 22 | EIP1271Signature 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/io/zksync/signer/EthSigner.java: -------------------------------------------------------------------------------- 1 | package io.zksync.signer; 2 | 3 | import java.math.BigInteger; 4 | import java.security.SignatureException; 5 | import java.util.Collection; 6 | import java.util.concurrent.CompletableFuture; 7 | 8 | import org.web3j.crypto.Hash; 9 | import org.web3j.tx.TransactionManager; 10 | import org.web3j.utils.Numeric; 11 | 12 | import io.zksync.domain.auth.ChangePubKeyVariant; 13 | import io.zksync.domain.swap.Order; 14 | import io.zksync.domain.token.Token; 15 | import io.zksync.domain.token.TokenId; 16 | import io.zksync.domain.transaction.ChangePubKey; 17 | import io.zksync.domain.transaction.ZkSyncTransaction; 18 | 19 | public interface EthSigner { 20 | 21 | static final String MESSAGE_PREFIX = "\u0019Ethereum Signed Message:\n"; 22 | static final byte[] EIP1271_SUCCESS_VALUE = Numeric.hexStringToByteArray("0x1626ba7e"); 23 | 24 | /** 25 | * Get wallet address 26 | * 27 | * @return Address in hex string 28 | */ 29 | String getAddress(); 30 | 31 | /** 32 | * Get internal transaction manager. @see org.web3j.tx.TransactionManager 33 | * 34 | * @return TransactionManager object that implements signing and sending transactions 35 | */ 36 | TransactionManager getTransactionManager(); 37 | 38 | CompletableFuture> signAuth(ChangePubKey changePubKey); 39 | 40 | CompletableFuture signToggle(boolean enable, Long timestamp); 41 | 42 | CompletableFuture signToggle(boolean enable, Long timestamp, String publicKeyHash); 43 | 44 | /** 45 | * Sign `ZkSync` type operation message 46 | * 47 | * @param - ZkSyncTransaction transaction type 48 | * @param transaction - Prepared transaction 49 | * @param nonce - Nonce of the account 50 | * @param token - Token object supported by ZkSync 51 | * @param fee - Cost of transaction in ZkSync network 52 | * @return Signature object 53 | */ 54 | CompletableFuture signTransaction(T transaction, Integer nonce, Token token, BigInteger fee); 55 | 56 | /** 57 | * Sign `Order` message 58 | * 59 | * @param order - Prepared order 60 | * @param tokenSell - Token object supported by ZkSync 61 | * @param tokenBuy - Token object supported by ZkSync 62 | * @return Signature object 63 | */ 64 | CompletableFuture signOrder(Order order, T tokenSell, T tokenBuy); 65 | 66 | /** 67 | * Sign batch of `ZkSync` type operation messages 68 | * 69 | * @param - ZkSyncTransaction transaction type 70 | * @param transactions - List of the prepared transactions 71 | * @param nonce - Nonce of the account 72 | * @param token - Token object supported by ZkSync 73 | * @param fee - Cost of transaction in ZkSync network 74 | * @return Signature object 75 | */ 76 | CompletableFuture signBatch(Collection transactions, Integer nonce, Token token, BigInteger fee); 77 | 78 | /** 79 | * Sign raw message 80 | * 81 | * @param message - Message to sign 82 | * @return Signature object 83 | */ 84 | CompletableFuture signMessage(byte[] message); 85 | 86 | /** 87 | * Sign raw message 88 | * 89 | * @param message - Message to sign 90 | * @param addPrefix - If true then add secure prefix (https://eips.ethereum.org/EIPS/eip-712) 91 | * @return 92 | */ 93 | CompletableFuture signMessage(byte[] message, boolean addPrefix); 94 | 95 | /** 96 | * Verify signature with raw message 97 | * 98 | * @param signature - Signature object 99 | * @param message - Message to verify 100 | * @return true on verification success 101 | * @throws SignatureException If the public key could not be recovered or if there was a 102 | * signature format error. 103 | */ 104 | CompletableFuture verifySignature(EthSignature signature, byte[] message) throws SignatureException; 105 | 106 | /** 107 | * Verify signature with raw message 108 | * 109 | * @param signature - Signature object 110 | * @param message - Message to verify 111 | * @param prefixed - If true then add secure prefix (https://eips.ethereum.org/EIPS/eip-712) 112 | * @return true on verification success 113 | * @throws SignatureException If the public key could not be recovered or if there was a 114 | * signature format error. 115 | */ 116 | CompletableFuture verifySignature(EthSignature signature, byte[] message, boolean prefixed) throws SignatureException; 117 | 118 | static byte[] getEthereumMessagePrefix(int messageLength) { 119 | return MESSAGE_PREFIX.concat(String.valueOf(messageLength)).getBytes(); 120 | } 121 | 122 | static byte[] getEthereumMessageHash(byte[] message) { 123 | byte[] prefix = getEthereumMessagePrefix(message.length); 124 | 125 | byte[] result = new byte[prefix.length + message.length]; 126 | System.arraycopy(prefix, 0, result, 0, prefix.length); 127 | System.arraycopy(message, 0, result, prefix.length, message.length); 128 | 129 | return Hash.sha3(result); 130 | } 131 | 132 | } 133 | -------------------------------------------------------------------------------- /src/main/java/io/zksync/signer/ZkSigner.java: -------------------------------------------------------------------------------- 1 | package io.zksync.signer; 2 | 3 | import io.zksync.domain.ChainId; 4 | import io.zksync.domain.Signature; 5 | import io.zksync.domain.auth.ChangePubKeyVariant; 6 | import io.zksync.domain.swap.Order; 7 | import io.zksync.domain.transaction.ChangePubKey; 8 | import io.zksync.domain.transaction.ForcedExit; 9 | import io.zksync.domain.transaction.MintNFT; 10 | import io.zksync.domain.transaction.Swap; 11 | import io.zksync.domain.transaction.Transfer; 12 | import io.zksync.domain.transaction.Withdraw; 13 | import io.zksync.domain.transaction.WithdrawNFT; 14 | import io.zksync.exception.ZkSyncException; 15 | import io.zksync.exception.ZkSyncIncorrectCredentialsException; 16 | import io.zksync.sdk.zkscrypto.lib.ZksCrypto; 17 | import io.zksync.sdk.zkscrypto.lib.entity.ZksPackedPublicKey; 18 | import io.zksync.sdk.zkscrypto.lib.entity.ZksPrivateKey; 19 | import io.zksync.sdk.zkscrypto.lib.entity.ZksSignature; 20 | import io.zksync.sdk.zkscrypto.lib.exception.ZksMusigTooLongException; 21 | import io.zksync.sdk.zkscrypto.lib.exception.ZksSeedTooShortException; 22 | import io.zksync.signer.EthSignature.SignatureType; 23 | 24 | import org.apache.commons.lang.ArrayUtils; 25 | import org.web3j.utils.Numeric; 26 | 27 | import java.io.ByteArrayOutputStream; 28 | import java.io.IOException; 29 | 30 | import static io.zksync.signer.SigningUtils.*; 31 | 32 | public class ZkSigner { 33 | 34 | private static final ZksCrypto crypto = ZksCrypto.load(); 35 | 36 | public static final String MESSAGE = "Access zkSync account.\n\nOnly sign this message for a trusted client!"; 37 | 38 | public static final Integer TRANSACTION_VERSION = 0x01; 39 | 40 | private final ZksPrivateKey privateKey; 41 | 42 | private final ZksPackedPublicKey publicKey; 43 | 44 | private final String publicKeyHash; 45 | 46 | private ZkSigner(ZksPrivateKey privateKey) { 47 | this.privateKey = privateKey; 48 | 49 | // Generate public key from private key 50 | publicKey = crypto.getPublicKey(privateKey); 51 | 52 | // Generate hash from public key 53 | publicKeyHash = Numeric.toHexStringNoPrefix(crypto.getPublicKeyHash(publicKey).getData()); 54 | } 55 | 56 | public static ZkSigner fromSeed(byte[] seed) { 57 | try { 58 | // Generate private key from seed 59 | ZksPrivateKey privateKey = crypto.generatePrivateKey(seed); 60 | 61 | return new ZkSigner(privateKey); 62 | } catch (ZksSeedTooShortException e) { 63 | throw new ZkSyncException(e); 64 | } 65 | } 66 | 67 | public static ZkSigner fromRawPrivateKey(byte[] rawPrivateKey) { 68 | ZksPrivateKey privateKey = new ZksPrivateKey.ByReference(); 69 | privateKey.data = rawPrivateKey; 70 | 71 | return new ZkSigner(privateKey); 72 | } 73 | 74 | public static ZkSigner fromEthSigner(EthSigner ethSigner, ChainId chainId) { 75 | String message = MESSAGE; 76 | if (chainId != ChainId.Mainnet) { 77 | message = String.format("%s\nChain ID: %d.", MESSAGE, chainId.getId()); 78 | } 79 | EthSignature signature = ethSigner.signMessage(message.getBytes(), true).join(); 80 | if (signature.getType() != SignatureType.EthereumSignature) { 81 | throw new ZkSyncIncorrectCredentialsException("Invalid signature type: " + signature.getType()); 82 | } 83 | 84 | return fromSeed(Numeric.hexStringToByteArray(signature.getSignature())); 85 | 86 | } 87 | 88 | public Signature sign(byte[] message) { 89 | try { 90 | final byte[] signature = crypto.signMessage(privateKey, message).getData(); 91 | 92 | return Signature 93 | .builder() 94 | .pubKey(Numeric.toHexStringNoPrefix(publicKey.getData())) 95 | .signature(Numeric.toHexString(signature).substring(2)) 96 | .build(); 97 | } catch (ZksMusigTooLongException e) { 98 | throw new ZkSyncException(e); 99 | } 100 | } 101 | 102 | public boolean verify(byte[] message, Signature signature) { 103 | ZksPackedPublicKey zksPublicKey = new ZksPackedPublicKey.ByReference(); 104 | zksPublicKey.data = Numeric.hexStringToByteArray(signature.getPubKey()); 105 | ZksSignature zksSignature = new ZksSignature.ByReference(); 106 | zksSignature.data = Numeric.hexStringToByteArray(signature.getSignature()); 107 | 108 | return crypto.verifySignature(zksPublicKey, zksSignature, message); 109 | } 110 | 111 | public String getPublicKeyHash() { 112 | return "sync:" + publicKeyHash; 113 | } 114 | 115 | public String getPublicKey() { 116 | return Numeric.toHexString(publicKey.getData()); 117 | } 118 | 119 | public ChangePubKey signChangePubKey(ChangePubKey changePubKey) { 120 | try { 121 | final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); 122 | outputStream.write(0xff - 0x07); 123 | outputStream.write(TRANSACTION_VERSION); 124 | outputStream.write(accountIdToBytes(changePubKey.getAccountId())); 125 | outputStream.write(addressToBytes(changePubKey.getAccount())); 126 | outputStream.write(addressToBytes(changePubKey.getNewPkHash())); 127 | outputStream.write(tokenIdToBytes(changePubKey.getFeeToken())); 128 | outputStream.write(feeToBytes(changePubKey.getFeeInteger())); 129 | outputStream.write(nonceToBytes(changePubKey.getNonce())); 130 | outputStream.write(numberToBytesBE(changePubKey.getTimeRange().getValidFrom(), 8)); 131 | outputStream.write(numberToBytesBE(changePubKey.getTimeRange().getValidUntil(), 8)); 132 | 133 | byte[] message = outputStream.toByteArray(); 134 | 135 | final Signature signature = sign(message); 136 | 137 | changePubKey.setSignature(signature); 138 | 139 | return changePubKey; 140 | } catch (IOException e) { 141 | throw new ZkSyncException(e); 142 | } 143 | } 144 | 145 | public Transfer signTransfer(Transfer transfer) { 146 | try { 147 | final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); 148 | outputStream.write(0xff - 0x05); 149 | outputStream.write(TRANSACTION_VERSION); 150 | outputStream.write(accountIdToBytes(transfer.getAccountId())); 151 | outputStream.write(addressToBytes(transfer.getFrom())); 152 | outputStream.write(addressToBytes(transfer.getTo())); 153 | outputStream.write(tokenIdToBytes(transfer.getToken())); 154 | outputStream.write(amountPackedToBytes(transfer.getAmount())); 155 | outputStream.write(feeToBytes(transfer.getFeeInteger())); 156 | outputStream.write(nonceToBytes(transfer.getNonce())); 157 | outputStream.write(numberToBytesBE(transfer.getTimeRange().getValidFrom(), 8)); 158 | outputStream.write(numberToBytesBE(transfer.getTimeRange().getValidUntil(), 8)); 159 | 160 | byte[] message = outputStream.toByteArray(); 161 | 162 | final Signature signature = sign(message); 163 | 164 | transfer.setSignature(signature); 165 | 166 | return transfer; 167 | } catch (IOException e) { 168 | throw new ZkSyncException(e); 169 | } 170 | } 171 | 172 | public Withdraw signWithdraw(Withdraw withdraw) { 173 | try { 174 | final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); 175 | outputStream.write(0xff - 0x03); 176 | outputStream.write(TRANSACTION_VERSION); 177 | outputStream.write(accountIdToBytes(withdraw.getAccountId())); 178 | outputStream.write(addressToBytes(withdraw.getFrom())); 179 | outputStream.write(addressToBytes(withdraw.getTo())); 180 | outputStream.write(tokenIdToBytes(withdraw.getToken())); 181 | outputStream.write(amountFullToBytes(withdraw.getAmount())); 182 | outputStream.write(feeToBytes(withdraw.getFeeInteger())); 183 | outputStream.write(nonceToBytes(withdraw.getNonce())); 184 | outputStream.write(numberToBytesBE(withdraw.getTimeRange().getValidFrom(), 8)); 185 | outputStream.write(numberToBytesBE(withdraw.getTimeRange().getValidUntil(), 8)); 186 | 187 | byte[] message = outputStream.toByteArray(); 188 | 189 | final Signature signature = sign(message); 190 | 191 | withdraw.setSignature(signature); 192 | 193 | return withdraw; 194 | } catch (IOException e) { 195 | throw new ZkSyncException(e); 196 | } 197 | } 198 | 199 | public ForcedExit signForcedExit(ForcedExit forcedExit) { 200 | try { 201 | final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); 202 | outputStream.write(0xff - 0x08); 203 | outputStream.write(TRANSACTION_VERSION); 204 | outputStream.write(accountIdToBytes(forcedExit.getInitiatorAccountId())); 205 | outputStream.write(addressToBytes(forcedExit.getTarget())); 206 | outputStream.write(tokenIdToBytes(forcedExit.getToken())); 207 | outputStream.write(feeToBytes(forcedExit.getFeeInteger())); 208 | outputStream.write(nonceToBytes(forcedExit.getNonce())); 209 | outputStream.write(numberToBytesBE(forcedExit.getTimeRange().getValidFrom(), 8)); 210 | outputStream.write(numberToBytesBE(forcedExit.getTimeRange().getValidUntil(), 8)); 211 | 212 | byte[] message = outputStream.toByteArray(); 213 | 214 | final Signature signature = sign(message); 215 | 216 | forcedExit.setSignature(signature); 217 | 218 | return forcedExit; 219 | } catch (IOException e) { 220 | throw new ZkSyncException(e); 221 | } 222 | } 223 | 224 | public MintNFT signMintNFT(MintNFT mintNFT) { 225 | try{ 226 | final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); 227 | outputStream.write(0xff - 0x09); 228 | outputStream.write(TRANSACTION_VERSION); 229 | outputStream.write(accountIdToBytes(mintNFT.getCreatorId())); 230 | outputStream.write(addressToBytes(mintNFT.getCreatorAddress())); 231 | outputStream.write(Numeric.hexStringToByteArray(mintNFT.getContentHash())); 232 | outputStream.write(addressToBytes(mintNFT.getRecipient())); 233 | outputStream.write(tokenIdToBytes(mintNFT.getFeeToken())); 234 | outputStream.write(feeToBytes(mintNFT.getFeeInteger())); 235 | outputStream.write(nonceToBytes(mintNFT.getNonce())); 236 | 237 | byte[] message = outputStream.toByteArray(); 238 | 239 | final Signature signature = sign(message); 240 | 241 | mintNFT.setSignature(signature); 242 | 243 | return mintNFT; 244 | } catch (IOException e) { 245 | throw new ZkSyncException(e); 246 | } 247 | } 248 | 249 | public WithdrawNFT signWithdrawNFT(WithdrawNFT withdrawNFT) { 250 | try { 251 | final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); 252 | outputStream.write(0xff - 0x0a); 253 | outputStream.write(TRANSACTION_VERSION); 254 | outputStream.write(accountIdToBytes(withdrawNFT.getAccountId())); 255 | outputStream.write(addressToBytes(withdrawNFT.getFrom())); 256 | outputStream.write(addressToBytes(withdrawNFT.getTo())); 257 | outputStream.write(tokenIdToBytes(withdrawNFT.getToken())); 258 | outputStream.write(tokenIdToBytes(withdrawNFT.getFeeToken())); 259 | outputStream.write(feeToBytes(withdrawNFT.getFeeInteger())); 260 | outputStream.write(nonceToBytes(withdrawNFT.getNonce())); 261 | outputStream.write(numberToBytesBE(withdrawNFT.getTimeRange().getValidFrom(), 8)); 262 | outputStream.write(numberToBytesBE(withdrawNFT.getTimeRange().getValidUntil(), 8)); 263 | 264 | byte[] message = outputStream.toByteArray(); 265 | 266 | final Signature signature = sign(message); 267 | 268 | withdrawNFT.setSignature(signature); 269 | 270 | return withdrawNFT; 271 | } catch (IOException e) { 272 | throw new ZkSyncException(e); 273 | } 274 | } 275 | 276 | public Swap signSwap(Swap swap) { 277 | try { 278 | final byte[] order1 = getOrderBytes(swap.getOrders().component1()); 279 | final byte[] order2 = getOrderBytes(swap.getOrders().component2()); 280 | final byte[] ordersHash = crypto.rescueHashOrders(ArrayUtils.addAll(order1, order2)).getData(); 281 | final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); 282 | outputStream.write(0xff - 0x0b); 283 | outputStream.write(TRANSACTION_VERSION); 284 | outputStream.write(accountIdToBytes(swap.getSubmitterId())); 285 | outputStream.write(addressToBytes(swap.getSubmitterAddress())); 286 | outputStream.write(nonceToBytes(swap.getNonce())); 287 | outputStream.write(ordersHash); 288 | outputStream.write(tokenIdToBytes(swap.getFeeToken())); 289 | outputStream.write(feeToBytes(swap.getFeeInteger())); 290 | outputStream.write(amountPackedToBytes(swap.getAmounts().component1())); 291 | outputStream.write(amountPackedToBytes(swap.getAmounts().component2())); 292 | 293 | byte[] message = outputStream.toByteArray(); 294 | 295 | final Signature signature = sign(message); 296 | 297 | swap.setSignature(signature); 298 | 299 | return swap; 300 | } catch (IOException e) { 301 | throw new ZkSyncException(e); 302 | } 303 | } 304 | 305 | public Order signOrder(Order order) { 306 | byte[] message = getOrderBytes(order); 307 | 308 | final Signature signature = sign(message); 309 | 310 | order.setSignature(signature); 311 | 312 | return order; 313 | } 314 | 315 | public byte[] getOrderBytes(Order order) { 316 | try { 317 | final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); 318 | outputStream.write(0x6f); // ASCII 'o' in hex for (o)rder 319 | outputStream.write(TRANSACTION_VERSION); 320 | outputStream.write(accountIdToBytes(order.getAccountId())); 321 | outputStream.write(addressToBytes(order.getRecipientAddress())); 322 | outputStream.write(nonceToBytes(order.getNonce())); 323 | outputStream.write(tokenIdToBytes(order.getTokenSell())); 324 | outputStream.write(tokenIdToBytes(order.getTokenBuy())); 325 | outputStream.write(bigIntToBytesBE(order.getRatio().component1(), 15)); 326 | outputStream.write(bigIntToBytesBE(order.getRatio().component2(), 15)); 327 | outputStream.write(amountPackedToBytes(order.getAmount())); 328 | outputStream.write(numberToBytesBE(order.getTimeRange().getValidFrom(), 8)); 329 | outputStream.write(numberToBytesBE(order.getTimeRange().getValidUntil(), 8)); 330 | 331 | byte[] message = outputStream.toByteArray(); 332 | 333 | return message; 334 | } catch (IOException e) { 335 | throw new ZkSyncException(e); 336 | } 337 | } 338 | } 339 | -------------------------------------------------------------------------------- /src/main/java/io/zksync/transport/HttpTransport.java: -------------------------------------------------------------------------------- 1 | package io.zksync.transport; 2 | 3 | import com.fasterxml.jackson.core.JsonProcessingException; 4 | import com.fasterxml.jackson.databind.ObjectMapper; 5 | import io.zksync.exception.ZkSyncException; 6 | import okhttp3.*; 7 | 8 | import java.io.IOException; 9 | import java.time.Duration; 10 | import java.util.List; 11 | import java.util.concurrent.CompletableFuture; 12 | 13 | public class HttpTransport implements ZkSyncTransport { 14 | 15 | public static final MediaType APPLICATION_JSON = MediaType.get("application/json; charset=utf-8"); 16 | 17 | private final OkHttpClient httpClient; 18 | 19 | private final String url; 20 | 21 | private final ObjectMapper objectMapper; 22 | 23 | public HttpTransport(String url) { 24 | this.url = url; 25 | 26 | httpClient = new OkHttpClient 27 | .Builder() 28 | .callTimeout(Duration.ofSeconds(5)) 29 | .connectTimeout(Duration.ofSeconds(5)) 30 | .build(); 31 | 32 | objectMapper = new ObjectMapper(); 33 | } 34 | 35 | @Override 36 | public > R send(String method, List params, Class returntype) { 37 | try { 38 | final ZkSyncRequest zkRequest = ZkSyncRequest 39 | .builder() 40 | .method(method) 41 | .params(params) 42 | .build(); 43 | final String bodyJson = objectMapper.writeValueAsString(zkRequest); 44 | final RequestBody body = RequestBody.create(bodyJson, APPLICATION_JSON); 45 | 46 | final Request request = new Request.Builder() 47 | .url(url) 48 | .post(body) 49 | .build(); 50 | 51 | final Response response = httpClient.newCall(request).execute(); 52 | 53 | final String responseString = response.body().string(); 54 | 55 | final ZkSyncResponse resultJson = objectMapper.readValue(responseString, returntype); 56 | 57 | if (resultJson.getError() != null) { 58 | throw new ZkSyncException(resultJson.getError()); 59 | } 60 | 61 | return resultJson.getResult(); 62 | 63 | } catch (IOException e) { 64 | throw new ZkSyncException("There was an error when sending the request", e); 65 | } 66 | } 67 | 68 | @Override 69 | public > CompletableFuture sendAsync(String method, List params, Class returntype) { 70 | final CompletableFuture future = new CompletableFuture<>(); 71 | final ZkSyncRequest zkRequest = ZkSyncRequest 72 | .builder() 73 | .method(method) 74 | .params(params) 75 | .build(); 76 | String bodyJson; 77 | try { 78 | bodyJson = objectMapper.writeValueAsString(zkRequest); 79 | } catch (JsonProcessingException e) { 80 | future.completeExceptionally(e); 81 | return future; 82 | } 83 | final RequestBody body = RequestBody.create(bodyJson, APPLICATION_JSON); 84 | 85 | final Request request = new Request.Builder() 86 | .url(url) 87 | .post(body) 88 | .build(); 89 | httpClient.newCall(request).enqueue(new Callback() { 90 | @Override 91 | public void onResponse(Call _arg0, Response response) throws IOException { 92 | final String responseString = response.body().string(); 93 | 94 | final ZkSyncResponse resultJson = objectMapper.readValue(responseString, returntype); 95 | 96 | if (resultJson.getError() != null) { 97 | future.completeExceptionally(new ZkSyncException(resultJson.getError())); 98 | } 99 | 100 | future.complete(resultJson.getResult()); 101 | } 102 | 103 | @Override 104 | public void onFailure(Call _arg0, IOException error) { 105 | future.completeExceptionally(error); 106 | } 107 | }); 108 | 109 | return future; 110 | } 111 | } 112 | -------------------------------------------------------------------------------- /src/main/java/io/zksync/transport/ZkSyncError.java: -------------------------------------------------------------------------------- 1 | package io.zksync.transport; 2 | 3 | import lombok.AllArgsConstructor; 4 | import lombok.Getter; 5 | import lombok.NoArgsConstructor; 6 | 7 | @Getter 8 | @NoArgsConstructor 9 | @AllArgsConstructor 10 | public class ZkSyncError { 11 | 12 | private Integer code; 13 | 14 | private String message; 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/io/zksync/transport/ZkSyncRequest.java: -------------------------------------------------------------------------------- 1 | package io.zksync.transport; 2 | 3 | import lombok.AllArgsConstructor; 4 | import lombok.Builder; 5 | import lombok.Data; 6 | import lombok.NoArgsConstructor; 7 | 8 | import java.util.List; 9 | import java.util.concurrent.atomic.AtomicLong; 10 | 11 | @Data 12 | @Builder 13 | @NoArgsConstructor 14 | @AllArgsConstructor 15 | public class ZkSyncRequest { 16 | private static AtomicLong nextId = new AtomicLong(0); 17 | 18 | private final long id = nextId.getAndIncrement(); 19 | 20 | private final String jsonrpc = "2.0"; 21 | 22 | private String method; 23 | 24 | private List params; 25 | 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/io/zksync/transport/ZkSyncResponse.java: -------------------------------------------------------------------------------- 1 | package io.zksync.transport; 2 | 3 | import lombok.AllArgsConstructor; 4 | import lombok.Builder; 5 | import lombok.Data; 6 | import lombok.NoArgsConstructor; 7 | 8 | @Data 9 | @Builder 10 | @NoArgsConstructor 11 | @AllArgsConstructor 12 | public class ZkSyncResponse { 13 | 14 | private int id; 15 | 16 | private String jsonrpc; 17 | 18 | private T result; 19 | 20 | private ZkSyncError error; 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/io/zksync/transport/ZkSyncSuccess.java: -------------------------------------------------------------------------------- 1 | package io.zksync.transport; 2 | 3 | import lombok.Data; 4 | 5 | @Data 6 | public class ZkSyncSuccess { 7 | 8 | private Boolean success; 9 | 10 | } 11 | -------------------------------------------------------------------------------- /src/main/java/io/zksync/transport/ZkSyncTransport.java: -------------------------------------------------------------------------------- 1 | package io.zksync.transport; 2 | 3 | import java.util.List; 4 | import java.util.concurrent.CompletableFuture; 5 | 6 | public interface ZkSyncTransport { 7 | 8 | > R send(String method, List params, Class returntype); 9 | > CompletableFuture sendAsync(String method, List params, Class returntype); 10 | } 11 | -------------------------------------------------------------------------------- /src/main/java/io/zksync/transport/ZkTransactionStatus.java: -------------------------------------------------------------------------------- 1 | package io.zksync.transport; 2 | 3 | public enum ZkTransactionStatus { 4 | SENT, 5 | COMMITED, 6 | VERIFIED 7 | } 8 | -------------------------------------------------------------------------------- /src/main/java/io/zksync/transport/receipt/ZkSyncPollingTransactionReceiptProcessor.java: -------------------------------------------------------------------------------- 1 | package io.zksync.transport.receipt; 2 | 3 | import java.util.concurrent.CompletableFuture; 4 | 5 | import io.zksync.domain.transaction.TransactionDetails; 6 | import io.zksync.exception.ZkSyncException; 7 | import io.zksync.provider.AsyncProvider; 8 | import io.zksync.transport.ZkTransactionStatus; 9 | import io.zksync.wallet.ZkASyncWallet; 10 | 11 | public class ZkSyncPollingTransactionReceiptProcessor extends ZkSyncTransactionReceiptProcessor { 12 | 13 | protected final long sleepDuration; 14 | protected final int attempts; 15 | 16 | public ZkSyncPollingTransactionReceiptProcessor(AsyncProvider provider, long sleepDuration, int attempts) { 17 | super(provider); 18 | 19 | this.sleepDuration = sleepDuration; 20 | this.attempts = attempts; 21 | } 22 | 23 | public ZkSyncPollingTransactionReceiptProcessor(ZkASyncWallet wallet, long sleepDuration, int attempts) { 24 | this(wallet.getProvider(), sleepDuration, attempts); 25 | } 26 | 27 | public ZkSyncPollingTransactionReceiptProcessor(AsyncProvider provider) { 28 | this(provider, 100, Integer.MAX_VALUE); 29 | } 30 | 31 | public ZkSyncPollingTransactionReceiptProcessor(ZkASyncWallet wallet) { 32 | this(wallet.getProvider()); 33 | } 34 | 35 | @Override 36 | public CompletableFuture waitForTransaction(String hash, ZkTransactionStatus status) { 37 | final CompletableFuture result = CompletableFuture.supplyAsync(() -> { 38 | TransactionDetails details = this.getTransactionDetails(hash).join(); 39 | for (int i = 0; i < attempts; i++) { 40 | if (!details.getExecuted()) { 41 | try { 42 | Thread.sleep(sleepDuration); 43 | } catch (InterruptedException e) { 44 | throw new ZkSyncException(e); 45 | } 46 | 47 | details = this.getTransactionDetails(hash).join(); 48 | } else { 49 | switch (status) { 50 | case SENT: 51 | if (details.getBlock() != null) { 52 | return details; 53 | } 54 | break; 55 | case COMMITED: 56 | if (details.getBlock() != null && details.getBlock().getCommitted()) { 57 | return details; 58 | } 59 | break; 60 | case VERIFIED: 61 | if (details.getBlock() != null && details.getBlock().getVerified()) { 62 | return details; 63 | } 64 | break; 65 | } 66 | } 67 | } 68 | 69 | throw new ZkSyncException( 70 | "Transaction was not generated after " 71 | + ((sleepDuration * attempts) / 1000 72 | + " seconds for transaction: " 73 | + hash)); 74 | }); 75 | 76 | return result; 77 | } 78 | 79 | } 80 | -------------------------------------------------------------------------------- /src/main/java/io/zksync/transport/receipt/ZkSyncTransactionReceiptProcessor.java: -------------------------------------------------------------------------------- 1 | package io.zksync.transport.receipt; 2 | 3 | import java.util.concurrent.CompletableFuture; 4 | 5 | import io.zksync.domain.transaction.TransactionDetails; 6 | import io.zksync.provider.AsyncProvider; 7 | import io.zksync.transport.ZkTransactionStatus; 8 | import lombok.Getter; 9 | 10 | public abstract class ZkSyncTransactionReceiptProcessor { 11 | 12 | @Getter 13 | private final AsyncProvider provider; 14 | 15 | public ZkSyncTransactionReceiptProcessor(AsyncProvider provider) { 16 | this.provider = provider; 17 | } 18 | 19 | public abstract CompletableFuture waitForTransaction(String hash, ZkTransactionStatus status); 20 | 21 | public CompletableFuture getTransactionDetails(String txHash) { 22 | return this.provider.getTransactionDetails(txHash); 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/io/zksync/transport/response/ZksAccountState.java: -------------------------------------------------------------------------------- 1 | package io.zksync.transport.response; 2 | 3 | import io.zksync.domain.state.AccountState; 4 | import io.zksync.transport.ZkSyncResponse; 5 | 6 | public class ZksAccountState extends ZkSyncResponse {} 7 | -------------------------------------------------------------------------------- /src/main/java/io/zksync/transport/response/ZksContractAddress.java: -------------------------------------------------------------------------------- 1 | package io.zksync.transport.response; 2 | 3 | import io.zksync.domain.contract.ContractAddress; 4 | import io.zksync.transport.ZkSyncResponse; 5 | 6 | public class ZksContractAddress extends ZkSyncResponse {} 7 | -------------------------------------------------------------------------------- /src/main/java/io/zksync/transport/response/ZksEthOpInfo.java: -------------------------------------------------------------------------------- 1 | package io.zksync.transport.response; 2 | 3 | import io.zksync.domain.operation.EthOpInfo; 4 | import io.zksync.transport.ZkSyncResponse; 5 | 6 | public class ZksEthOpInfo extends ZkSyncResponse {} 7 | -------------------------------------------------------------------------------- /src/main/java/io/zksync/transport/response/ZksGetConfirmationsForEthOpAmount.java: -------------------------------------------------------------------------------- 1 | package io.zksync.transport.response; 2 | 3 | import java.math.BigInteger; 4 | 5 | import io.zksync.transport.ZkSyncResponse; 6 | 7 | public class ZksGetConfirmationsForEthOpAmount extends ZkSyncResponse {} 8 | -------------------------------------------------------------------------------- /src/main/java/io/zksync/transport/response/ZksSentTransaction.java: -------------------------------------------------------------------------------- 1 | package io.zksync.transport.response; 2 | 3 | import io.zksync.transport.ZkSyncResponse; 4 | 5 | public class ZksSentTransaction extends ZkSyncResponse {} 6 | -------------------------------------------------------------------------------- /src/main/java/io/zksync/transport/response/ZksSentTransactionBatch.java: -------------------------------------------------------------------------------- 1 | package io.zksync.transport.response; 2 | 3 | import java.util.List; 4 | 5 | import io.zksync.transport.ZkSyncResponse; 6 | 7 | public class ZksSentTransactionBatch extends ZkSyncResponse> {} 8 | -------------------------------------------------------------------------------- /src/main/java/io/zksync/transport/response/ZksToggle2FA.java: -------------------------------------------------------------------------------- 1 | package io.zksync.transport.response; 2 | 3 | import io.zksync.transport.ZkSyncResponse; 4 | import io.zksync.transport.ZkSyncSuccess; 5 | 6 | public class ZksToggle2FA extends ZkSyncResponse { 7 | 8 | } 9 | -------------------------------------------------------------------------------- /src/main/java/io/zksync/transport/response/ZksTokenPrice.java: -------------------------------------------------------------------------------- 1 | package io.zksync.transport.response; 2 | 3 | import java.math.BigDecimal; 4 | 5 | import io.zksync.transport.ZkSyncResponse; 6 | 7 | public class ZksTokenPrice extends ZkSyncResponse {} 8 | -------------------------------------------------------------------------------- /src/main/java/io/zksync/transport/response/ZksTokens.java: -------------------------------------------------------------------------------- 1 | package io.zksync.transport.response; 2 | 3 | import io.zksync.domain.token.Tokens; 4 | import io.zksync.transport.ZkSyncResponse; 5 | 6 | public class ZksTokens extends ZkSyncResponse {} 7 | -------------------------------------------------------------------------------- /src/main/java/io/zksync/transport/response/ZksTransactionDetails.java: -------------------------------------------------------------------------------- 1 | package io.zksync.transport.response; 2 | 3 | import io.zksync.domain.transaction.TransactionDetails; 4 | import io.zksync.transport.ZkSyncResponse; 5 | 6 | public class ZksTransactionDetails extends ZkSyncResponse {} 7 | -------------------------------------------------------------------------------- /src/main/java/io/zksync/transport/response/ZksTransactionFeeDetails.java: -------------------------------------------------------------------------------- 1 | package io.zksync.transport.response; 2 | 3 | import io.zksync.domain.fee.TransactionFeeDetails; 4 | import io.zksync.transport.ZkSyncResponse; 5 | 6 | public class ZksTransactionFeeDetails extends ZkSyncResponse {} 7 | -------------------------------------------------------------------------------- /src/main/java/io/zksync/wallet/DefaultZkASyncWallet.java: -------------------------------------------------------------------------------- 1 | package io.zksync.wallet; 2 | 3 | import java.math.BigInteger; 4 | import java.util.Arrays; 5 | import java.util.List; 6 | import java.util.Objects; 7 | import java.util.concurrent.CompletableFuture; 8 | import java.util.stream.Collectors; 9 | 10 | import org.apache.commons.lang3.tuple.Pair; 11 | import org.web3j.protocol.Web3j; 12 | import org.web3j.tuples.generated.Tuple2; 13 | import org.web3j.tx.gas.ContractGasProvider; 14 | import org.web3j.utils.Strings; 15 | 16 | import io.reactivex.annotations.Nullable; 17 | import io.zksync.domain.TimeRange; 18 | import io.zksync.domain.TransactionBuildHelper; 19 | import io.zksync.domain.auth.ChangePubKeyOnchain; 20 | import io.zksync.domain.auth.ChangePubKeyVariant; 21 | import io.zksync.domain.auth.Toggle2FA; 22 | import io.zksync.domain.fee.TransactionFee; 23 | import io.zksync.domain.state.AccountState; 24 | import io.zksync.domain.swap.Order; 25 | import io.zksync.domain.token.NFT; 26 | import io.zksync.domain.token.TokenId; 27 | import io.zksync.domain.token.Tokens; 28 | import io.zksync.domain.transaction.ChangePubKey; 29 | import io.zksync.domain.transaction.Transfer; 30 | import io.zksync.domain.transaction.ZkSyncTransaction; 31 | import io.zksync.ethereum.DefaultEthereumProvider; 32 | import io.zksync.ethereum.EthereumProvider; 33 | import io.zksync.ethereum.wrappers.ZkSync; 34 | import io.zksync.provider.AsyncProvider; 35 | import io.zksync.signer.EthSignature; 36 | import io.zksync.signer.EthSigner; 37 | import io.zksync.signer.ZkSigner; 38 | 39 | public class DefaultZkASyncWallet> implements ZkASyncWallet { 40 | 41 | private final TransactionBuildHelper helper; 42 | 43 | private S ethSigner; 44 | private ZkSigner zkSigner; 45 | private AsyncProvider provider; 46 | 47 | private Integer accountId; 48 | 49 | private String pubKeyHash; 50 | 51 | DefaultZkASyncWallet(S ethSigner, ZkSigner zkSigner, AsyncProvider provider) { 52 | this.ethSigner = ethSigner; 53 | this.zkSigner = zkSigner; 54 | 55 | this.provider = provider; 56 | 57 | this.accountId = null; 58 | this.pubKeyHash = null; 59 | 60 | this.helper = new TransactionBuildHelper(this, this.getTokens().join()); 61 | } 62 | 63 | @Override 64 | public CompletableFuture setSigningKey(TransactionFee fee, Integer nonce, boolean onchainAuth, 65 | TimeRange timeRange) { 66 | if (onchainAuth) { 67 | return this.helper.changePubKey(this.getPubKeyHash().join(), fee, nonce, timeRange) 68 | .thenApply(changePubKey -> { 69 | zkSigner.signChangePubKey(changePubKey); 70 | 71 | return this.submitSignedTransaction(changePubKey).join(); 72 | }); 73 | } else { 74 | return this.helper.changePubKey(this.getPubKeyHash().join(), fee, nonce, timeRange) 75 | .thenApply(changePubKey -> { 76 | final ChangePubKey changePubKeyAuth = ethSigner.signAuth(changePubKey).join(); 77 | final EthSignature ethSignature = ethSigner.signTransaction(changePubKey, nonce, this.helper.getToken(fee.getFeeToken()), fee.getFee()).join(); 78 | zkSigner.signChangePubKey(changePubKeyAuth); 79 | 80 | return this.submitSignedTransaction(changePubKeyAuth, ethSignature).join(); 81 | }); 82 | } 83 | } 84 | 85 | @Override 86 | public CompletableFuture syncTransfer(String to, BigInteger amount, TransactionFee fee, Integer nonce, 87 | TimeRange timeRange) { 88 | return this.helper.transfer(to, amount, fee, nonce, timeRange) 89 | .thenApply(transfer -> { 90 | final EthSignature ethSignature = ethSigner.signTransaction(transfer, nonce, this.helper.getToken(fee.getFeeToken()), fee.getFee()).join(); 91 | zkSigner.signTransfer(transfer); 92 | 93 | return this.submitSignedTransaction(transfer, ethSignature).join(); 94 | }); 95 | } 96 | 97 | @Override 98 | public CompletableFuture syncWithdraw(String ethAddress, BigInteger amount, TransactionFee fee, 99 | Integer nonce, boolean fastProcessing, TimeRange timeRange) { 100 | return this.helper.withdraw(ethAddress, amount, fee, nonce, timeRange) 101 | .thenApply(withdraw -> { 102 | final EthSignature ethSignature = ethSigner.signTransaction(withdraw, nonce, this.helper.getToken(fee.getFeeToken()), fee.getFee()).join(); 103 | zkSigner.signWithdraw(withdraw); 104 | 105 | return this.submitSignedTransaction(withdraw, ethSignature, fastProcessing).join(); 106 | }); 107 | } 108 | 109 | @Override 110 | public CompletableFuture syncForcedExit(String target, TransactionFee fee, Integer nonce, 111 | TimeRange timeRange) { 112 | return this.helper.forcedExit(target, fee, nonce, timeRange) 113 | .thenApply(forcedExit -> { 114 | final EthSignature ethSignature = ethSigner.signTransaction(forcedExit, nonce, this.helper.getToken(fee.getFeeToken()), fee.getFee()).join(); 115 | zkSigner.signForcedExit(forcedExit); 116 | 117 | return this.submitSignedTransaction(forcedExit, ethSignature).join(); 118 | }); 119 | } 120 | 121 | @Override 122 | public CompletableFuture syncMintNFT(String recipient, String contentHash, TransactionFee fee, 123 | Integer nonce) { 124 | return this.helper.mintNFT(recipient, contentHash, fee, nonce) 125 | .thenApply(mintNft -> { 126 | final EthSignature ethSignature = ethSigner.signTransaction(mintNft, nonce, this.helper.getToken(fee.getFeeToken()), fee.getFee()).join(); 127 | zkSigner.signMintNFT(mintNft); 128 | 129 | return this.submitSignedTransaction(mintNft, ethSignature).join(); 130 | }); 131 | } 132 | 133 | @Override 134 | public CompletableFuture syncWithdrawNFT(String to, NFT token, TransactionFee fee, Integer nonce, 135 | TimeRange timeRange) { 136 | return this.helper.withdrawNFT(to, token, fee, nonce, timeRange) 137 | .thenApply(withdrawNft -> { 138 | final EthSignature ethSignature = ethSigner.signTransaction(withdrawNft, nonce, this.helper.getToken(fee.getFeeToken()), fee.getFee()).join(); 139 | zkSigner.signWithdrawNFT(withdrawNft); 140 | 141 | return this.submitSignedTransaction(withdrawNft, ethSignature).join(); 142 | }); 143 | } 144 | 145 | @Override 146 | public CompletableFuture> syncTransferNFT(String to, NFT token, TransactionFee fee, Integer nonce, 147 | TimeRange timeRange) { 148 | return this.helper.transferNFT(to, token, fee, nonce, timeRange) 149 | .thenApply(transferNft -> { 150 | final Transfer nft = transferNft.component1(); 151 | final Transfer fees = transferNft.component2(); 152 | EthSignature ethSignature = ethSigner.signBatch(Arrays.asList(nft, fees), nft.getNonce(), this.helper.getToken(fee.getFeeToken()), fee.getFee()).join(); 153 | return submitSignedBatch(Arrays.asList( 154 | zkSigner.signTransfer(nft), 155 | zkSigner.signTransfer(fees) 156 | ), ethSignature).join(); 157 | }); 158 | } 159 | 160 | @Override 161 | public CompletableFuture syncSwap(Order order1, Order order2, BigInteger amount1, BigInteger amount2, 162 | TransactionFee fee, Integer nonce) { 163 | return this.helper.swap(order1, order2, amount1, amount2, fee, nonce) 164 | .thenApply(swap -> { 165 | final EthSignature ethSignature = ethSigner.signTransaction(swap, nonce, this.helper.getToken(fee.getFeeToken()), fee.getFee()).join(); 166 | zkSigner.signSwap(swap); 167 | 168 | return this.submitSignedTransaction(swap, ethSignature).join(); 169 | }); 170 | } 171 | 172 | @Override 173 | public CompletableFuture buildSignedOrder(String recipient, T sell, T buy, 174 | Tuple2 ratio, BigInteger amount, Integer nonce, TimeRange timeRange) { 175 | return this.helper.order(recipient, sell, buy, ratio, amount, nonce, timeRange) 176 | .thenApply(order -> { 177 | final EthSignature ethSignature = ethSigner.signOrder(order, sell, buy).join(); 178 | order.setEthereumSignature(ethSignature); 179 | 180 | return zkSigner.signOrder(order); 181 | }); 182 | } 183 | 184 | @Override 185 | public CompletableFuture buildSignedLimitOrder(String recipient, T sell, T buy, 186 | Tuple2 ratio, Integer nonce, TimeRange timeRange) { 187 | return this.helper.limitOrder(recipient, sell, buy, ratio, nonce, timeRange) 188 | .thenApply(order -> { 189 | final EthSignature ethSignature = ethSigner.signOrder(order, sell, buy).join(); 190 | order.setEthereumSignature(ethSignature); 191 | 192 | return zkSigner.signOrder(order); 193 | }); 194 | } 195 | 196 | @Override 197 | public CompletableFuture isSigningKeySet() { 198 | return this.getPubKeyHash() 199 | .thenApply(pubKey -> Objects.equals(pubKey, this.zkSigner.getPublicKeyHash())); 200 | } 201 | 202 | @Override 203 | public CompletableFuture getState() { 204 | return this.provider.getState(this.getAddress()); 205 | } 206 | 207 | @Override 208 | public AsyncProvider getProvider() { 209 | return this.provider; 210 | } 211 | 212 | @Override 213 | public CompletableFuture getPubKeyHash() { 214 | if (this.pubKeyHash == null) { 215 | return getState() 216 | .thenApply(this::setAccountInfo) 217 | .thenApply(state -> state.getCommitted().getPubKeyHash()); 218 | } else { 219 | return CompletableFuture.completedFuture(this.pubKeyHash); 220 | } 221 | } 222 | 223 | @Override 224 | public CompletableFuture getAccountId() { 225 | if (this.accountId == null) { 226 | return getState() 227 | .thenApply(this::setAccountInfo) 228 | .thenApply(AccountState::getId); 229 | } else { 230 | return CompletableFuture.completedFuture(this.accountId); 231 | } 232 | } 233 | 234 | @Override 235 | public CompletableFuture getTokens() { 236 | return this.provider.getTokens(); 237 | } 238 | 239 | @Override 240 | public CompletableFuture submitTransaction(SignedTransaction transaction) { 241 | return submitSignedTransaction(transaction.getTransaction(), transaction.getEthereumSignature()); 242 | } 243 | 244 | @Override 245 | public String getAddress() { 246 | return this.ethSigner.getAddress(); 247 | } 248 | 249 | @Override 250 | public CompletableFuture getNonce() { 251 | return getState() 252 | .thenApply(state -> state.getCommitted().getNonce()); 253 | } 254 | 255 | @Override 256 | public EthereumProvider createEthereumProvider(Web3j web3j, ContractGasProvider contractGasProvider) { 257 | String contractAddress = this.provider.contractAddress().join().getMainContract(); 258 | ZkSync contract = ZkSync.load(contractAddress, web3j, this.ethSigner.getTransactionManager(), contractGasProvider); 259 | DefaultEthereumProvider ethereum = new DefaultEthereumProvider(web3j, this.ethSigner, contract); 260 | return ethereum; 261 | } 262 | 263 | @Override 264 | public CompletableFuture enable2FA() { 265 | final Long timestamp = System.currentTimeMillis(); 266 | 267 | return ethSigner.signToggle(true, timestamp).thenApply(ethSignature -> { 268 | final Toggle2FA toggle2Fa = new Toggle2FA( 269 | true, 270 | this.getAccountId().join(), 271 | timestamp, 272 | ethSignature, 273 | null 274 | ); 275 | 276 | return provider.toggle2FA(toggle2Fa).join(); 277 | }); 278 | } 279 | 280 | @Override 281 | public CompletableFuture disable2FA(@Nullable String pubKeyHash) { 282 | final Long timestamp = System.currentTimeMillis(); 283 | 284 | return (Strings.isEmpty(pubKeyHash) ? 285 | ethSigner.signToggle(false, timestamp) : 286 | ethSigner.signToggle(false, timestamp, pubKeyHash) 287 | ).thenApply(ethSignature -> { 288 | final Toggle2FA toggle2Fa = new Toggle2FA( 289 | false, 290 | this.getAccountId().join(), 291 | timestamp, 292 | ethSignature, 293 | pubKeyHash 294 | ); 295 | 296 | return provider.toggle2FA(toggle2Fa).join(); 297 | }); 298 | } 299 | 300 | private CompletableFuture submitSignedTransaction(ZkSyncTransaction signedTransaction, 301 | EthSignature ethereumSignature, 302 | boolean fastProcessing) { 303 | return provider.submitTx(signedTransaction, ethereumSignature, fastProcessing); 304 | } 305 | 306 | private CompletableFuture submitSignedTransaction(ZkSyncTransaction signedTransaction, 307 | EthSignature ...ethereumSignature) { 308 | if (ethereumSignature == null || ethereumSignature.length == 0) { 309 | return provider.submitTx(signedTransaction, null, false); 310 | } else if (ethereumSignature.length == 1) { 311 | return provider.submitTx(signedTransaction, ethereumSignature[0], false); 312 | } else { 313 | return provider.submitTx(signedTransaction, ethereumSignature); 314 | } 315 | } 316 | 317 | private CompletableFuture> submitSignedBatch(List transactions, EthSignature ethereumSignature) { 318 | return provider.submitTxBatch( 319 | transactions.stream().map(tx -> Pair.of(tx, (EthSignature) null)).collect(Collectors.toList()), 320 | ethereumSignature 321 | ); 322 | } 323 | 324 | private AccountState setAccountInfo(AccountState state) { 325 | this.accountId = state.getId(); 326 | this.pubKeyHash = state.getCommitted().getPubKeyHash(); 327 | 328 | return state; 329 | } 330 | 331 | } 332 | -------------------------------------------------------------------------------- /src/main/java/io/zksync/wallet/SignedTransaction.java: -------------------------------------------------------------------------------- 1 | package io.zksync.wallet; 2 | 3 | import com.fasterxml.jackson.annotation.JsonGetter; 4 | import com.fasterxml.jackson.annotation.JsonIgnore; 5 | 6 | import org.apache.commons.lang3.tuple.Pair; 7 | 8 | import io.zksync.domain.transaction.ZkSyncTransaction; 9 | import io.zksync.signer.EthSignature; 10 | import lombok.Builder; 11 | import lombok.Getter; 12 | 13 | @Getter 14 | @Builder 15 | public class SignedTransaction { 16 | 17 | @JsonIgnore 18 | T transaction; 19 | 20 | @JsonIgnore 21 | EthSignature []ethereumSignature; 22 | 23 | public SignedTransaction(T transaction, EthSignature ...ethereumSignature) { 24 | this.transaction = transaction; 25 | this.ethereumSignature = ethereumSignature; 26 | } 27 | 28 | @JsonGetter 29 | public T getTx() { 30 | return transaction; 31 | } 32 | 33 | @JsonGetter 34 | public EthSignature[] getSignature() { 35 | return ethereumSignature; 36 | } 37 | 38 | public static SignedTransaction fromPair(Pair tx) { 39 | if (tx.getRight() == null) { 40 | return new SignedTransaction(tx.getLeft(), null); 41 | } else { 42 | return new SignedTransaction(tx.getLeft(), new EthSignature[] {tx.getRight()}); 43 | } 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/main/java/io/zksync/wallet/ZkASyncWallet.java: -------------------------------------------------------------------------------- 1 | package io.zksync.wallet; 2 | 3 | import java.math.BigInteger; 4 | import java.util.List; 5 | import java.util.concurrent.CompletableFuture; 6 | 7 | import org.web3j.protocol.Web3j; 8 | import org.web3j.tuples.generated.Tuple2; 9 | import org.web3j.tx.gas.ContractGasProvider; 10 | 11 | import io.reactivex.annotations.Nullable; 12 | import io.zksync.domain.TimeRange; 13 | import io.zksync.domain.auth.ChangePubKeyVariant; 14 | import io.zksync.domain.fee.TransactionFee; 15 | import io.zksync.domain.state.AccountState; 16 | import io.zksync.domain.swap.Order; 17 | import io.zksync.domain.token.NFT; 18 | import io.zksync.domain.token.TokenId; 19 | import io.zksync.domain.token.Tokens; 20 | import io.zksync.domain.transaction.ZkSyncTransaction; 21 | import io.zksync.ethereum.EthereumProvider; 22 | import io.zksync.provider.AsyncProvider; 23 | import io.zksync.provider.DefaultAsyncProvider; 24 | import io.zksync.signer.EthSigner; 25 | import io.zksync.signer.ZkSigner; 26 | import io.zksync.transport.ZkSyncTransport; 27 | 28 | public interface ZkASyncWallet { 29 | 30 | public static > DefaultZkASyncWallet build(T ethSigner, ZkSigner zkSigner, ZkSyncTransport transport) { 31 | return new DefaultZkASyncWallet<>(ethSigner, zkSigner, new DefaultAsyncProvider(transport)); 32 | } 33 | 34 | public static > DefaultZkASyncWallet build(T ethSigner, ZkSigner zkSigner, AsyncProvider provider) { 35 | return new DefaultZkASyncWallet<>(ethSigner, zkSigner, provider); 36 | } 37 | 38 | /** 39 | * Send set signing key transaction 40 | * 41 | * @param fee - Fee amount for paying the transaction 42 | * @param nonce - Nonce value 43 | * @param onchainAuth - Use authentication onchain 44 | * @param timeRange - Timerange of validity of the transcation 45 | * @return - Hash of the sent transaction in hex string 46 | */ 47 | CompletableFuture setSigningKey(TransactionFee fee, Integer nonce, boolean onchainAuth, TimeRange timeRange); 48 | 49 | /** 50 | * Send transfer coins (or tokens) transaction 51 | * 52 | * @param to - Ethereum address of the receiver of the funds 53 | * @param amount - Amount of the funds to be transferred 54 | * @param fee - Fee amount for paying the transaction 55 | * @param nonce - Nonce value 56 | * @param timeRange - Timerange of validity of the transcation 57 | * @return - Hash of the sent transaction in hex string 58 | */ 59 | CompletableFuture syncTransfer(String to, BigInteger amount, TransactionFee fee, Integer nonce, TimeRange timeRange); 60 | 61 | /** 62 | * Send withdraw coins (or tokens) transaction 63 | * Given funds amount will be withdrawn to the wallet on Ethereum L1 network 64 | * 65 | * @param ethAddress - Ethereum address of the receiver of the funds 66 | * @param amount - Amount of the funds to be withdrawn 67 | * @param fee - Fee amount for paying the transaction 68 | * @param nonce - Nonce value 69 | * @param fastProcessing - Increase speed of the execution 70 | * @param timeRange - Timerange of validity of the transcation 71 | * @return - Hash of the sent transaction in hex string 72 | */ 73 | CompletableFuture syncWithdraw(String ethAddress, 74 | BigInteger amount, 75 | TransactionFee fee, 76 | Integer nonce, 77 | boolean fastProcessing, 78 | TimeRange timeRange); 79 | 80 | /** 81 | * Send forced exit transaction 82 | * 83 | * @param target - Ethereum address of the receiver of the funds 84 | * @param fee - Fee amount for paying the transaction 85 | * @param nonce - Nonce value 86 | * @param timeRange - Timerange of validity of the transcation 87 | * @return - Hash of the sent transaction in hex string 88 | */ 89 | CompletableFuture syncForcedExit(String target, TransactionFee fee, Integer nonce, TimeRange timeRange); 90 | 91 | /** 92 | * Send mint NFT transaction 93 | * 94 | * @param recipient - Ethereum address of the receiver of the NFT 95 | * @param contentHash - Hash for creation Non-fundible token 96 | * @param fee - Fee amount for paying the transaction 97 | * @param nonce - Nonce value 98 | * @return - Hash of the sent transaction in hex string 99 | */ 100 | CompletableFuture syncMintNFT(String recipient, String contentHash, TransactionFee fee, Integer nonce); 101 | 102 | /** 103 | * Send withdraw NFT transaction 104 | * NFT will be withdrawn to the wallet in Ethereum L1 network 105 | * 106 | * @param to - Ethereum address of the receiver of the NFT 107 | * @param token - Existing Non-fundible token 108 | * @param fee - Fee amount for paying the transaction 109 | * @param nonce - Nonce value 110 | * @param timeRange - Timerange of validity of the transcation 111 | * @return - Hash of the sent transaction in hex string 112 | */ 113 | CompletableFuture syncWithdrawNFT(String to, NFT token, TransactionFee fee, Integer nonce, TimeRange timeRange); 114 | 115 | /** 116 | * Send transfer NFT transaction 117 | * 118 | * @param to - Ethereum address of the receiver of the NFT 119 | * @param token - Existing Non-fundible token 120 | * @param fee - Fee amount for paying the transaction 121 | * @param nonce - Nonce value 122 | * @param timeRange - Timerange of validity of the transcation 123 | * @return - List of 2 hashes of the sent transactions in hex string 124 | */ 125 | CompletableFuture> syncTransferNFT(String to, NFT token, TransactionFee fee, Integer nonce, TimeRange timeRange); 126 | 127 | /** 128 | * Send swap transaction 129 | * 130 | * @param order1 - Signed order 131 | * @param order2 - Signed order 132 | * @param amount1 - Amount funds to be swapped 133 | * @param amount2 - Amount funds to be swapped 134 | * @param fee - Fee amount for paying the transaction 135 | * @param nonce - Nonce value 136 | * @return - Hash of the sent transaction in hex string 137 | */ 138 | CompletableFuture syncSwap(Order order1, Order order2, BigInteger amount1, BigInteger amount2, TransactionFee fee, Integer nonce); 139 | 140 | /** 141 | * Build swap order 142 | * 143 | * @param recipient - Ethereum address of the receiver of the funds 144 | * @param sell - Token to sell 145 | * @param buy - Token to buy 146 | * @param ratio - Swap ratio 147 | * @param amount - Amount to swap 148 | * @param nonce - Nonce value 149 | * @param timeRange - Timerange of validity of the order 150 | * @return - Signed order object 151 | */ 152 | CompletableFuture buildSignedOrder(String recipient, T sell, T buy, Tuple2 ratio, BigInteger amount, Integer nonce, TimeRange timeRange); 153 | 154 | /** 155 | * Build swap limit order 156 | * 157 | * @param recipient - Ethereum address of the receiver of the funds 158 | * @param sell - Token to sell 159 | * @param buy - Token to buy 160 | * @param ratio - Swap ratio 161 | * @param nonce - Nonce value 162 | * @param timeRange - Timerange of validity of the order 163 | * @return - Signed order object 164 | */ 165 | CompletableFuture buildSignedLimitOrder(String recipient, T sell, T buy, Tuple2 ratio, Integer nonce, TimeRange timeRange); 166 | 167 | /** 168 | * Submit signed transaction to ZkSync network 169 | * 170 | * @param - ZkSyncTransaction transaction type 171 | * @param transaction - Prepared signed transaction 172 | * @return - Hash of the sent transaction in hex string 173 | */ 174 | CompletableFuture submitTransaction(SignedTransaction transaction); 175 | 176 | /** 177 | * Check if wallet public key hash is set 178 | * 179 | * @return - True if pubkey hash is set otherwise false 180 | */ 181 | CompletableFuture isSigningKeySet(); 182 | 183 | /** 184 | * Get current account state 185 | * 186 | * @return - State object 187 | */ 188 | CompletableFuture getState(); 189 | 190 | /** 191 | * Get low level ZkSync API provider 192 | * 193 | * @return - Provider 194 | */ 195 | AsyncProvider getProvider(); 196 | 197 | /** 198 | * Get wallet public key hash 199 | * 200 | * @return - Pubkey hash in ZkSync format 201 | */ 202 | CompletableFuture getPubKeyHash(); 203 | 204 | /** 205 | * Get id of the account within current ZkSync network 206 | * 207 | * @return - Account Id 208 | */ 209 | CompletableFuture getAccountId(); 210 | 211 | /** 212 | * Get latest commited nonce value of the account 213 | * 214 | * @return - Nonce 215 | */ 216 | CompletableFuture getNonce(); 217 | 218 | /** 219 | * Get list of the supported tokens by current ZkSync network 220 | * 221 | * @return - Token list object 222 | */ 223 | CompletableFuture getTokens(); 224 | 225 | /** 226 | * Get current wallet address 227 | * 228 | * @return - Wallet address in hex string 229 | */ 230 | String getAddress(); 231 | 232 | /** 233 | * Send request to enable 2-Factor authentication 234 | * 235 | * @return true if successful, false otherwise 236 | */ 237 | CompletableFuture enable2FA(); 238 | 239 | /** 240 | * Send request to disable 2-Factor authentication 241 | * 242 | * @param pubKeyHash - ZkSync public key hash of the account 243 | * @return true if successful, false otherwise 244 | */ 245 | CompletableFuture disable2FA(@Nullable String pubKeyHash); 246 | 247 | EthereumProvider createEthereumProvider(Web3j web3j, ContractGasProvider contractGasProvider); 248 | } 249 | -------------------------------------------------------------------------------- /src/main/java/io/zksync/wallet/ZkSyncWallet.java: -------------------------------------------------------------------------------- 1 | package io.zksync.wallet; 2 | 3 | import io.zksync.domain.TimeRange; 4 | import io.zksync.domain.auth.ChangePubKeyVariant; 5 | import io.zksync.domain.fee.TransactionFee; 6 | import io.zksync.domain.state.AccountState; 7 | import io.zksync.domain.swap.Order; 8 | import io.zksync.domain.token.NFT; 9 | import io.zksync.domain.token.TokenId; 10 | import io.zksync.domain.token.Tokens; 11 | import io.zksync.domain.transaction.ZkSyncTransaction; 12 | import io.zksync.ethereum.EthereumProvider; 13 | import io.zksync.provider.DefaultProvider; 14 | import io.zksync.provider.Provider; 15 | import io.zksync.signer.EthSigner; 16 | import io.zksync.signer.ZkSigner; 17 | import io.zksync.transport.ZkSyncTransport; 18 | 19 | import java.math.BigInteger; 20 | import java.util.List; 21 | 22 | import org.jetbrains.annotations.NotNull; 23 | import org.jetbrains.annotations.Nullable; 24 | import org.web3j.protocol.Web3j; 25 | import org.web3j.tuples.generated.Tuple2; 26 | import org.web3j.tx.gas.ContractGasProvider; 27 | 28 | public interface ZkSyncWallet { 29 | 30 | public static > DefaultZkSyncWallet build(T ethSigner, ZkSigner zkSigner, ZkSyncTransport transport) { 31 | return new DefaultZkSyncWallet<>(ethSigner, zkSigner, new DefaultProvider(transport)); 32 | } 33 | 34 | public static > DefaultZkSyncWallet build(T ethSigner, ZkSigner zkSigner, Provider provider) { 35 | return new DefaultZkSyncWallet<>(ethSigner, zkSigner, provider); 36 | } 37 | 38 | /** 39 | * Send set signing key transaction 40 | * 41 | * @param fee - Fee amount for paying the transaction 42 | * @param nonce - Nonce value 43 | * @param onchainAuth - Use authentication onchain 44 | * @param timeRange - Timerange of validity of the transcation 45 | * @return - Hash of the sent transaction in hex string 46 | */ 47 | String setSigningKey(@NotNull TransactionFee fee, @Nullable Integer nonce, @NotNull boolean onchainAuth, @Nullable TimeRange timeRange); 48 | 49 | /** 50 | * Send transfer coins (or tokens) transaction 51 | * 52 | * @param to - Ethereum address of the receiver of the funds 53 | * @param amount - Amount of the funds to be transferred 54 | * @param fee - Fee amount for paying the transaction 55 | * @param nonce - Nonce value 56 | * @param timeRange - Timerange of validity of the transcation 57 | * @return - Hash of the sent transaction in hex string 58 | */ 59 | String syncTransfer(@NotNull String to, @NotNull BigInteger amount, @NotNull TransactionFee fee, @Nullable Integer nonce, @Nullable TimeRange timeRange); 60 | 61 | /** 62 | * Send withdraw coins (or tokens) transaction 63 | * Given funds amount will be withdrawn to the wallet on Ethereum L1 network 64 | * 65 | * @param ethAddress - Ethereum address of the receiver of the funds 66 | * @param amount - Amount of the funds to be withdrawn 67 | * @param fee - Fee amount for paying the transaction 68 | * @param nonce - Nonce value 69 | * @param fastProcessing - Increase speed of the execution 70 | * @param timeRange - Timerange of validity of the transcation 71 | * @return - Hash of the sent transaction in hex string 72 | */ 73 | String syncWithdraw(@NotNull String ethAddress, 74 | @NotNull BigInteger amount, 75 | @NotNull TransactionFee fee, 76 | @Nullable Integer nonce, 77 | @NotNull boolean fastProcessing, 78 | @Nullable TimeRange timeRange); 79 | 80 | /** 81 | * Send forced exit transaction 82 | * 83 | * @param target - Ethereum address of the receiver of the funds 84 | * @param fee - Fee amount for paying the transaction 85 | * @param nonce - Nonce value 86 | * @param timeRange - Timerange of validity of the transcation 87 | * @return - Hash of the sent transaction in hex string 88 | */ 89 | String syncForcedExit(@NotNull String target, @NotNull TransactionFee fee, @Nullable Integer nonce, @Nullable TimeRange timeRange); 90 | 91 | /** 92 | * Send mint NFT transaction 93 | * 94 | * @param recipient - Ethereum address of the receiver of the NFT 95 | * @param contentHash - Hash for creation Non-fundible token 96 | * @param fee - Fee amount for paying the transaction 97 | * @param nonce - Nonce value 98 | * @return - Hash of the sent transaction in hex string 99 | */ 100 | String syncMintNFT(@NotNull String recipient, @NotNull String contentHash, @NotNull TransactionFee fee, @Nullable Integer nonce); 101 | 102 | /** 103 | * Send withdraw NFT transaction 104 | * NFT will be withdrawn to the wallet in Ethereum L1 network 105 | * 106 | * @param to - Ethereum address of the receiver of the NFT 107 | * @param token - Existing Non-fundible token 108 | * @param fee - Fee amount for paying the transaction 109 | * @param nonce - Nonce value 110 | * @param timeRange - Timerange of validity of the transcation 111 | * @return - Hash of the sent transaction in hex string 112 | */ 113 | String syncWithdrawNFT(@NotNull String to, @NotNull NFT token, @NotNull TransactionFee fee, @Nullable Integer nonce, @Nullable TimeRange timeRange); 114 | 115 | /** 116 | * Send transfer NFT transaction 117 | * 118 | * @param to - Ethereum address of the receiver of the NFT 119 | * @param token - Existing Non-fundible token 120 | * @param fee - Fee amount for paying the transaction 121 | * @param nonce - Nonce value 122 | * @param timeRange - Timerange of validity of the transcation 123 | * @return - List of 2 hashes of the sent transactions in hex string 124 | */ 125 | List syncTransferNFT(@NotNull String to, @NotNull NFT token, @NotNull TransactionFee fee, @Nullable Integer nonce, @Nullable TimeRange timeRange); 126 | 127 | /** 128 | * Send swap transaction 129 | * 130 | * @param order1 - Signed order 131 | * @param order2 - Signed order 132 | * @param amount1 - Amount funds to be swapped 133 | * @param amount2 - Amount funds to be swapped 134 | * @param fee - Fee amount for paying the transaction 135 | * @param nonce - Nonce value 136 | * @return - Hash of the sent transaction in hex string 137 | */ 138 | String syncSwap(@NotNull Order order1, @NotNull Order order2, @NotNull BigInteger amount1, @NotNull BigInteger amount2, @NotNull TransactionFee fee, @Nullable Integer nonce); 139 | 140 | /** 141 | * Build swap order 142 | * 143 | * @param recipient - Ethereum address of the receiver of the funds 144 | * @param sell - Token to sell 145 | * @param buy - Token to buy 146 | * @param ratio - Swap ratio 147 | * @param amount - Amount to swap 148 | * @param nonce - Nonce value 149 | * @param timeRange - Timerange of validity of the order 150 | * @return - Signed order object 151 | */ 152 | Order buildSignedOrder(@NotNull String recipient, @NotNull T sell, @NotNull T buy, @NotNull Tuple2 ratio, @NotNull BigInteger amount, @Nullable Integer nonce, @Nullable TimeRange timeRange); 153 | 154 | /** 155 | * Build swap limit order 156 | * 157 | * @param recipient - Ethereum address of the receiver of the funds 158 | * @param sell - Token to sell 159 | * @param buy - Token to buy 160 | * @param ratio - Swap ratio 161 | * @param nonce - Nonce value 162 | * @param timeRange - Timerange of validity of the order 163 | * @return - Signed order object 164 | */ 165 | Order buildSignedLimitOrder(@NotNull String recipient, @NotNull T sell, @NotNull T buy, @NotNull Tuple2 ratio, @Nullable Integer nonce, @Nullable TimeRange timeRange); 166 | 167 | /** 168 | * Submit signed transaction to ZkSync network 169 | * 170 | * @param - ZkSyncTransaction transaction type 171 | * @param transaction - Prepared signed transaction 172 | * @return - Hash of the sent transaction in hex string 173 | */ 174 | String submitTransaction(SignedTransaction transaction); 175 | 176 | /** 177 | * Check if wallet public key hash is set 178 | * 179 | * @return - True if pubkey hash is set otherwise false 180 | */ 181 | boolean isSigningKeySet(); 182 | 183 | /** 184 | * Get current account state 185 | * 186 | * @return - State object 187 | */ 188 | AccountState getState(); 189 | 190 | /** 191 | * Get low level ZkSync API provider 192 | * 193 | * @return - Provider 194 | */ 195 | Provider getProvider(); 196 | 197 | /** 198 | * Get wallet public key hash 199 | * 200 | * @return - Pubkey hash in ZkSync format 201 | */ 202 | String getPubKeyHash(); 203 | 204 | /** 205 | * Get id of the account within current ZkSync network 206 | * 207 | * @return - Account Id 208 | */ 209 | Integer getAccountId(); 210 | 211 | /** 212 | * Get current wallet address 213 | * 214 | * @return - Wallet address in hex string 215 | */ 216 | String getAddress(); 217 | 218 | /** 219 | * Get list of the supported tokens by current ZkSync network 220 | * 221 | * @return - Token list object 222 | */ 223 | Tokens getTokens(); 224 | 225 | /** 226 | * Send request to enable 2-Factor authentication 227 | * 228 | * @return true if successful, false otherwise 229 | */ 230 | boolean enable2FA(); 231 | 232 | /** 233 | * Send request to disable 2-Factor authentication 234 | * 235 | * @param pubKeyHash - ZkSync public key hash of the account 236 | * @return true if successful, false otherwise 237 | */ 238 | boolean disable2FA(@Nullable String pubKeyHash); 239 | 240 | EthereumProvider createEthereumProvider(Web3j web3j, ContractGasProvider contractGasProvider); 241 | } 242 | 243 | -------------------------------------------------------------------------------- /src/test/java/io/zksync/IntegrationTestCreate2ShortFlow.java: -------------------------------------------------------------------------------- 1 | package io.zksync; 2 | 3 | import static org.junit.Assert.assertNotNull; 4 | import static org.junit.Assert.assertTrue; 5 | 6 | import java.math.BigDecimal; 7 | import java.math.BigInteger; 8 | import java.util.concurrent.ExecutionException; 9 | import java.util.concurrent.TimeUnit; 10 | import java.util.concurrent.TimeoutException; 11 | 12 | import org.junit.Before; 13 | import org.junit.Ignore; 14 | import org.junit.Test; 15 | import org.web3j.protocol.Web3j; 16 | import org.web3j.protocol.http.HttpService; 17 | import org.web3j.utils.Convert; 18 | import org.web3j.utils.Numeric; 19 | import org.web3j.utils.Convert.Unit; 20 | 21 | import io.zksync.domain.ChainId; 22 | import io.zksync.domain.TransactionBuildHelper; 23 | import io.zksync.domain.auth.ChangePubKeyCREATE2; 24 | import io.zksync.domain.token.Token; 25 | import io.zksync.domain.transaction.ChangePubKey; 26 | import io.zksync.domain.transaction.TransactionDetails; 27 | import io.zksync.domain.transaction.Transfer; 28 | import io.zksync.signer.Create2EthSigner; 29 | import io.zksync.signer.EthSignature; 30 | import io.zksync.signer.ZkSigner; 31 | import io.zksync.transport.ZkTransactionStatus; 32 | import io.zksync.transport.receipt.ZkSyncPollingTransactionReceiptProcessor; 33 | import io.zksync.transport.receipt.ZkSyncTransactionReceiptProcessor; 34 | import io.zksync.wallet.SignedTransaction; 35 | import io.zksync.wallet.ZkASyncWallet; 36 | import io.zksync.provider.AsyncProvider; 37 | 38 | @Ignore 39 | public class IntegrationTestCreate2ShortFlow { 40 | 41 | private static final Token ETHEREUM_COIN = Token.createETH(); 42 | 43 | private ZkASyncWallet wallet; 44 | 45 | private ChangePubKeyCREATE2 create2Data; 46 | private Create2EthSigner ethSigner; 47 | private ZkSigner zkSigner; 48 | 49 | private ZkSyncTransactionReceiptProcessor receiptProcessor; 50 | 51 | @Before 52 | public void setup() { 53 | Web3j web3j = Web3j.build(new HttpService("{{ethereum_web3_rpc_url}}")); 54 | zkSigner = ZkSigner.fromSeed(Numeric.toBytesPadded(BigInteger.ZERO, 32)); 55 | create2Data = new ChangePubKeyCREATE2("0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f", Numeric.toHexStringWithPrefixZeroPadded(BigInteger.ZERO, 64), "0x96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f"); 56 | ethSigner = Create2EthSigner.fromData(web3j, zkSigner, create2Data); 57 | 58 | wallet = ZkASyncWallet.build(ethSigner, zkSigner, AsyncProvider.defaultProvider(ChainId.Rinkeby)); 59 | receiptProcessor = new ZkSyncPollingTransactionReceiptProcessor(wallet); 60 | } 61 | 62 | @Test 63 | public void setupPublicKey() throws InterruptedException, ExecutionException, TimeoutException { 64 | TransactionBuildHelper helper = new TransactionBuildHelper(this.wallet, this.wallet.getTokens().join()); 65 | ChangePubKey changePubKey = helper.changePubKey(zkSigner.getPublicKeyHash(), ETHEREUM_COIN, create2Data).join(); 66 | changePubKey = ethSigner.signAuth(changePubKey).join(); 67 | EthSignature ethSignature = ethSigner.signTransaction(changePubKey, changePubKey.getNonce(), ETHEREUM_COIN, changePubKey.getFeeInteger()).join(); 68 | SignedTransaction> transaction = new SignedTransaction<>(zkSigner.signChangePubKey(changePubKey), ethSignature); 69 | String hash = wallet.submitTransaction(transaction).join(); 70 | 71 | System.out.println(hash); 72 | 73 | TransactionDetails receipt = receiptProcessor.waitForTransaction(hash, ZkTransactionStatus.COMMITED).get(30, TimeUnit.SECONDS); 74 | assertNotNull(receipt); 75 | assertTrue(receipt.getExecuted()); 76 | assertTrue(receipt.getSuccess()); 77 | } 78 | 79 | @Test 80 | public void transferFunds() throws InterruptedException, ExecutionException, TimeoutException { 81 | TransactionBuildHelper helper = new TransactionBuildHelper(this.wallet, this.wallet.getTokens().join()); 82 | Transfer transfer = helper.transfer(ethSigner.getAddress(), Convert.toWei(BigDecimal.valueOf(100000), Unit.GWEI).toBigInteger(), ETHEREUM_COIN).join(); 83 | EthSignature ethSignature = ethSigner.signTransaction(transfer, transfer.getNonce(), ETHEREUM_COIN, transfer.getFeeInteger()).join(); 84 | SignedTransaction transaction = new SignedTransaction<>(zkSigner.signTransfer(transfer), ethSignature); 85 | String hash = wallet.submitTransaction(transaction).join(); 86 | 87 | System.out.println(hash); 88 | 89 | TransactionDetails receipt = receiptProcessor.waitForTransaction(hash, ZkTransactionStatus.COMMITED).get(30, TimeUnit.SECONDS); 90 | assertNotNull(receipt); 91 | assertTrue(receipt.getExecuted()); 92 | assertTrue(receipt.getSuccess()); 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /src/test/java/io/zksync/signer/ZkSignerTest.java: -------------------------------------------------------------------------------- 1 | package io.zksync.signer; 2 | 3 | import static org.junit.jupiter.api.Assertions.*; 4 | 5 | import org.junit.Test; 6 | import org.web3j.utils.Numeric; 7 | 8 | import io.zksync.domain.ChainId; 9 | import io.zksync.domain.Signature; 10 | 11 | public class ZkSignerTest { 12 | 13 | private static final String PRIVATE_KEY = "0x000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f"; 14 | private static final byte[] SEED = Numeric.hexStringToByteArray(PRIVATE_KEY); 15 | private static final byte[] MESSAGE = Numeric.hexStringToByteArray("0x000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f"); 16 | private static final String PUBKEY = "0x17f3708f5e2b2c39c640def0cf0010fd9dd9219650e389114ea9da47f5874184"; 17 | private static final String PUBKEY_HASH = "sync:4f3015a1d2b93239f9510d8bc2cf49376a78a08e"; 18 | private static final String PUBKEY_HASH_ETH = "sync:18e8446d7748f2de52b28345bdbc76160e6b35eb"; 19 | private static final String PUBKEY_HASH_RAW = "sync:45ef0ae7362eb021ae2d9ac251a3ee434f37ed73"; 20 | private static final String SIGNATURE = "5462c3083d92b832d540c9068eed0a0450520f6dd2e4ab169de1a46585b394a4292896a2ebca3c0378378963a6bc1710b64c573598e73de3a33d6cec2f5d7403"; 21 | 22 | @Test 23 | public void testCreationFromSeed() { 24 | ZkSigner signer = ZkSigner.fromSeed(SEED); 25 | assertEquals(signer.getPublicKey(), PUBKEY); 26 | } 27 | 28 | @Test 29 | public void testCreationFromEthSigner() { 30 | DefaultEthSigner ethSigner = DefaultEthSigner.fromRawPrivateKey(PRIVATE_KEY); 31 | ZkSigner signer = ZkSigner.fromEthSigner(ethSigner, ChainId.Mainnet); 32 | 33 | assertEquals(signer.getPublicKeyHash(), PUBKEY_HASH_ETH); 34 | } 35 | 36 | @Test 37 | public void testCreationFromRawPrivateKey() throws Exception { 38 | ZkSigner signer = ZkSigner.fromRawPrivateKey(Numeric.hexStringToByteArray(PRIVATE_KEY)); 39 | 40 | assertEquals(signer.getPublicKeyHash(), PUBKEY_HASH_RAW); 41 | } 42 | 43 | @Test 44 | public void testSigningMessage() { 45 | ZkSigner signer = ZkSigner.fromSeed(SEED); 46 | Signature sign = signer.sign(MESSAGE); 47 | 48 | assertEquals(sign.getSignature(), SIGNATURE); 49 | } 50 | 51 | @Test 52 | public void testPublicKeyGeneration() { 53 | ZkSigner signer = ZkSigner.fromSeed(SEED); 54 | String publicKey = signer.getPublicKey(); 55 | 56 | assertEquals(publicKey, PUBKEY); 57 | } 58 | 59 | @Test 60 | public void testPublicKeyHashGeneration() { 61 | ZkSigner signer = ZkSigner.fromSeed(SEED); 62 | String pubKeyHash = signer.getPublicKeyHash(); 63 | 64 | assertEquals(pubKeyHash, PUBKEY_HASH); 65 | } 66 | 67 | } 68 | --------------------------------------------------------------------------------