├── .github └── workflows │ ├── build.yml │ └── maven_publish.yml ├── .gitignore ├── CHANGELOG.md ├── LICENSE ├── README.md ├── build.gradle ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── library ├── build.gradle └── src │ ├── main │ └── java │ │ └── foundation │ │ └── icon │ │ └── icx │ │ ├── Call.java │ │ ├── Callback.java │ │ ├── IconService.java │ │ ├── KeyWallet.java │ │ ├── Provider.java │ │ ├── Request.java │ │ ├── SignedTransaction.java │ │ ├── Transaction.java │ │ ├── TransactionBuilder.java │ │ ├── Wallet.java │ │ ├── crypto │ │ ├── ECDSASignature.java │ │ ├── IconKeys.java │ │ ├── KeyStoreUtils.java │ │ ├── Keystore.java │ │ ├── KeystoreException.java │ │ ├── KeystoreFile.java │ │ └── LinuxSecureRandom.java │ │ ├── data │ │ ├── Address.java │ │ ├── BTPNetworkInfo.java │ │ ├── BTPNetworkTypeInfo.java │ │ ├── BTPNotification.java │ │ ├── BTPSourceInfo.java │ │ ├── Base64.java │ │ ├── Block.java │ │ ├── BlockNotification.java │ │ ├── Bytes.java │ │ ├── ConfirmedTransaction.java │ │ ├── Converters.java │ │ ├── EventNotification.java │ │ ├── IconAmount.java │ │ ├── NetworkId.java │ │ ├── NetworkInfo.java │ │ ├── ScoreApi.java │ │ ├── ScoreStatus.java │ │ └── TransactionResult.java │ │ └── transport │ │ ├── http │ │ ├── HttpCall.java │ │ └── HttpProvider.java │ │ ├── jsonrpc │ │ ├── AnnotatedConverterFactory.java │ │ ├── AnnotationConverter.java │ │ ├── ConverterName.java │ │ ├── Request.java │ │ ├── Response.java │ │ ├── RpcArray.java │ │ ├── RpcConverter.java │ │ ├── RpcError.java │ │ ├── RpcItem.java │ │ ├── RpcItemCreator.java │ │ ├── RpcItemDeserializer.java │ │ ├── RpcItemSerializer.java │ │ ├── RpcObject.java │ │ └── RpcValue.java │ │ └── monitor │ │ ├── BTPMonitorSpec.java │ │ ├── BlockMonitorSpec.java │ │ ├── EventMonitorSpec.java │ │ ├── Monitor.java │ │ └── MonitorSpec.java │ └── test │ ├── java │ └── foundation │ │ └── icon │ │ └── icx │ │ ├── CallTest.java │ │ ├── Constants.java │ │ ├── DepositTest.java │ │ ├── EstimateStepTest.java │ │ ├── IconServiceIntegTest.java │ │ ├── IconServiceTest.java │ │ ├── IconServiceVCRTest.java │ │ ├── KeyWalletTest.java │ │ ├── SampleKeys.java │ │ ├── SignedTransactionTest.java │ │ ├── TransactionHandler.java │ │ ├── data │ │ ├── AddressTest.java │ │ ├── BytesTest.java │ │ └── IconAmountTest.java │ │ └── transport │ │ ├── http │ │ └── HttpProviderTest.java │ │ └── jsonrpc │ │ ├── AnnotationTest.java │ │ ├── DeserializerTest.java │ │ ├── RpcItemCreatorTest.java │ │ ├── RpcValueTest.java │ │ ├── SerializerTest.java │ │ └── TransactionV2Test.java │ └── resources │ ├── godWallet.json │ └── sampleToken.zip ├── publish.gradle ├── quickstart ├── README.md ├── build.gradle └── src │ └── main │ ├── java │ └── foundation │ │ └── icon │ │ └── icx │ │ ├── DeployTokenExample.java │ │ ├── IcxTransactionExample.java │ │ ├── SyncBlockExample.java │ │ ├── TokenTransactionExample.java │ │ ├── WalletExample.java │ │ └── data │ │ └── CommonData.java │ └── resources │ └── sampleToken.zip ├── samples ├── build.gradle └── src │ └── main │ ├── java │ └── foundation │ │ └── icon │ │ └── icx │ │ ├── Constants.java │ │ ├── ExecuteSyncAsync.java │ │ ├── GenerateWallet.java │ │ ├── SendDepositTransaction.java │ │ ├── SendIcxTransaction.java │ │ ├── SendMessageTransaction.java │ │ ├── Utils.java │ │ ├── call │ │ ├── CustomRequestParam.java │ │ ├── CustomResponseClass.java │ │ └── SendIcxCall.java │ │ ├── get │ │ ├── GetBlock.java │ │ ├── GetScoreApi.java │ │ ├── GetTotalSupply.java │ │ ├── GetTransaction.java │ │ └── IcxGetBalance.java │ │ └── token │ │ ├── DeploySampleToken.java │ │ ├── GetTokenBalance.java │ │ └── SendTokenTransaction.java │ └── resources │ └── sampleToken.zip └── settings.gradle /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | name: Build and test 2 | 3 | on: 4 | push: 5 | branches: [ "master" ] 6 | pull_request: 7 | branches: [ "master" ] 8 | 9 | jobs: 10 | build: 11 | runs-on: ubuntu-latest 12 | steps: 13 | - uses: actions/checkout@v3 14 | - name: Set up JDK 11 15 | uses: actions/setup-java@v3 16 | with: 17 | java-version: '11' 18 | distribution: 'temurin' 19 | cache: 'gradle' 20 | - name: Build with Gradle 21 | run: ./gradlew clean build --no-daemon 22 | -------------------------------------------------------------------------------- /.github/workflows/maven_publish.yml: -------------------------------------------------------------------------------- 1 | name: Publish package to the Maven Central Repository 2 | 3 | on: 4 | release: 5 | types: [created] 6 | 7 | jobs: 8 | publish: 9 | runs-on: ubuntu-latest 10 | steps: 11 | - uses: actions/checkout@v3 12 | - name: Set up JDK 11 13 | uses: actions/setup-java@v3 14 | with: 15 | java-version: '11' 16 | distribution: 'temurin' 17 | cache: 'gradle' 18 | - name: Publish package 19 | run: ./gradlew -Prelease publishToSonatype closeAndReleaseSonatypeStagingRepository 20 | env: 21 | STAGING_PROFILE_ID : ${{ secrets.STAGING_PROFILE_ID }} 22 | OSSRH_USERNAME: ${{ secrets.OSSRH_USERNAME }} 23 | OSSRH_PASSWORD: ${{ secrets.OSSRH_PASSWORD }} 24 | ORG_GRADLE_PROJECT_signingKey : ${{ secrets.SIGNING_KEY }} 25 | ORG_GRADLE_PROJECT_signingPassword : ${{ secrets.SIGNING_PASSWORD }} 26 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Created by .ignore support plugin (hsz.mobi) 2 | ### Java template 3 | *.class 4 | 5 | # Mobile Tools for Java (J2ME) 6 | .mtj.tmp/ 7 | 8 | # Package Files # 9 | *.jar 10 | *.war 11 | *.ear 12 | 13 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 14 | hs_err_pid* 15 | ### Gradle template 16 | .gradle 17 | /build 18 | /out 19 | */build/ 20 | */out/ 21 | 22 | local.properties 23 | 24 | # Ignore Gradle GUI config 25 | gradle-app.setting 26 | 27 | # Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored) 28 | !gradle-wrapper.jar 29 | 30 | # Cache of project 31 | .gradletasknamecache 32 | 33 | # Work around https://youtrack.jetbrains.com/issue/IDEA-116898 34 | # gradle/wrapper/gradle-wrapper.properties 35 | 36 | .idea 37 | *.iml 38 | geth.sh 39 | 40 | # Sphinx generated docs 41 | docs/build 42 | 43 | # OS X 44 | .DS_Store 45 | 46 | *.pdf 47 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | ## 1.0.0 - Sep 11, 2020 4 | - There are no special features or incompatibilities related to the version number change. This is just a numbering change to drop the beta tag. 5 | - Remove unused field and method of `jsonrpc.Response` 6 | - Add `Address.getBody()` method 7 | 8 | ## 0.9.15 - Dec 9, 2019 9 | - Fix the wrong handling of null and empty bytes when `RpcObject` is serialized/deserialized 10 | - Define `RpcValue.NULL` for null value 11 | - Add a new method `getDefault` in `ScoreApi.Param` 12 | 13 | ## 0.9.14 - Jun 21, 2019 14 | - Fix the bug that generates an invalid signature when a `stepLimit` is given 15 | 16 | ## 0.9.13 - Jun 14, 2019 17 | - Add a new `DepositBuilder` to support add/withdraw deposit transactions 18 | - Add a new `getStepUsedDetails` method to `TransactionResult` 19 | - Resurrect the older `HttpProvider` constructors to keep the source-code compatibility 20 | 21 | ## 0.9.12 - May 23, 2019 22 | - Add new constructors to `HttpProvider` to accept a server-based authority URI and a JSON-RPC version. The older constructors have been deprecated. 23 | - Add a new `estimateStep` method to `IconService` to get an estimated Step of how much Step is necessary to allow the transaction to complete. 24 | - Add a new constructor to `SignedTransaction` to override the `stepLimit` in the given raw `Transaction`. The `stepLimit` could be obtained from the `estimateStep` method. 25 | - All the sample codes (including quickstart) have been improved and work against the T-Bears Docker instance. 26 | 27 | ## 0.9.11 - January 8, 2019 28 | - Fix the generation of the wrong address caused by the wrong conversion of `BigInteger` to byte array 29 | 30 | ## 0.9.10 - December 21, 2018 31 | - Override `hashCode` to keep identities corresponding to equality rule in data classes of `Address` and `Bytes` 32 | - Throw an exception rather than print stack trace when conversion failure in `AnnotatedConverterFactory` 33 | - Fix some bugs in samples and quickstart example 34 | 35 | ## 0.9.9 - November 27, 2018 36 | - Fix signature mismatch error in case of the non UTF-8 environment 37 | 38 | ## 0.9.8 - October 31, 2018 39 | - Removes the crypto package of web3j and add the corresponding abilities into `foundation.icon.icx.crypto` 40 | - Supports Android 3.0 or newer 41 | 42 | ## 0.9.7 - September 19, 2018 43 | - Adds a method `getIndexed` in ScoreApi.Param 44 | - Sets the step limit as max step limit of the governance in the quickstart sample. 45 | - Adds a method that queries SCORE API in the quickstart sample. 46 | 47 | ## 0.9.6 - September 12, 2018 48 | - Change logic to check token transfer in quickstart sample 49 | - Fix converting publicKey of `Address` class to bytearray 50 | - Add logic to get default step cost to quickstart sample 51 | 52 | ## 0.9.5 - September 10, 2018 53 | - Deprecates `TransactionBuilder.of` and adds `TransactionBuilder.newBuilder` to create an instance of TransactionBuilder 54 | - `EventLog` class is moved into `TransactionResult` as an inner class 55 | - Adds failure field to TransactionResult. 56 | - Migrates ICON-RPC-V2 block data 57 | - Adds quickstart sample 58 | - Validates a transaction to send when using the TransactionBuilder 59 | - Adds a default value for Timestamp and NetworkId when missing 60 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id "io.github.gradle-nexus.publish-plugin" version "1.2.0" 3 | } 4 | 5 | allprojects { 6 | group GROUP 7 | version VERSION_NAME 8 | } 9 | 10 | subprojects { 11 | repositories { 12 | mavenCentral() 13 | } 14 | } 15 | 16 | configure([project(':library')]) { 17 | apply plugin: 'java-library' 18 | apply plugin: 'maven-publish' 19 | apply plugin: 'signing' 20 | 21 | apply from: '../publish.gradle' 22 | } 23 | 24 | nexusPublishing { 25 | packageGroup = GROUP 26 | repositories { 27 | sonatype { 28 | stagingProfileId = findProperty('mavenProfileId') ?: System.getenv("STAGING_PROFILE_ID") 29 | username = findProperty('mavenCentralUsername') ?: System.getenv("OSSRH_USERNAME") 30 | password = findProperty('mavenCentralPassword') ?: System.getenv("OSSRH_PASSWORD") 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | # 2 | # Copyright 2018 ICON Foundation. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | # 16 | 17 | GROUP=foundation.icon 18 | VERSION_NAME=2.5.2 19 | 20 | BINTRAY_USER_ORG=icon 21 | BINTRAY_REPO=icon-sdk 22 | BINTRAY_PKG_NAME=icon-sdk 23 | 24 | POM_DESCRIPTION=Official ICON SDK for java 25 | POM_URL=https://github.com/icon-project/icon-sdk-java 26 | POM_SCM_URL=https://github.com/icon-project/icon-sdk-java 27 | POM_SCM_CONNECTION=scm:git:https://github.com/icon-project/icon-sdk-java.git 28 | POM_SCM_DEV_CONNECTION=scm:git:https://github.com/icon-project/icon-sdk-java.git 29 | POM_LICENCE_NAME=The Apache Software License, Version 2.0 30 | POM_LICENCE_URL=http://www.apache.org/licenses/LICENSE-2.0.txt 31 | POM_LICENCE_DIST=repo 32 | POM_ARTIFACT_ID=icon-sdk 33 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/icon-project/icon-sdk-java/9a50cb1cc18c4fdb21615ed7c42a8b4a97dd8d4f/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-6.4.1-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /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 Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 33 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 34 | 35 | @rem Find java.exe 36 | if defined JAVA_HOME goto findJavaFromJavaHome 37 | 38 | set JAVA_EXE=java.exe 39 | %JAVA_EXE% -version >NUL 2>&1 40 | if "%ERRORLEVEL%" == "0" goto init 41 | 42 | echo. 43 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 44 | echo. 45 | echo Please set the JAVA_HOME variable in your environment to match the 46 | echo location of your Java installation. 47 | 48 | goto fail 49 | 50 | :findJavaFromJavaHome 51 | set JAVA_HOME=%JAVA_HOME:"=% 52 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 53 | 54 | if exist "%JAVA_EXE%" goto init 55 | 56 | echo. 57 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 58 | echo. 59 | echo Please set the JAVA_HOME variable in your environment to match the 60 | echo location of your Java installation. 61 | 62 | goto fail 63 | 64 | :init 65 | @rem Get command-line arguments, handling Windows variants 66 | 67 | if not "%OS%" == "Windows_NT" goto win9xME_args 68 | 69 | :win9xME_args 70 | @rem Slurp the command line arguments. 71 | set CMD_LINE_ARGS= 72 | set _SKIP=2 73 | 74 | :win9xME_args_slurp 75 | if "x%~1" == "x" goto execute 76 | 77 | set CMD_LINE_ARGS=%* 78 | 79 | :execute 80 | @rem Setup the command line 81 | 82 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 83 | 84 | @rem Execute Gradle 85 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 86 | 87 | :end 88 | @rem End local scope for the variables with windows NT shell 89 | if "%ERRORLEVEL%"=="0" goto mainEnd 90 | 91 | :fail 92 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 93 | rem the _cmd.exe /c_ return code! 94 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 95 | exit /b 1 96 | 97 | :mainEnd 98 | if "%OS%"=="Windows_NT" endlocal 99 | 100 | :omega 101 | -------------------------------------------------------------------------------- /library/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'java-library' 3 | } 4 | 5 | repositories { 6 | mavenCentral() 7 | } 8 | 9 | java { 10 | sourceCompatibility = JavaVersion.VERSION_1_8 11 | targetCompatibility = JavaVersion.VERSION_1_8 12 | } 13 | 14 | ext { 15 | bouncycastleVersion = '1.78.1' 16 | jacksonVersion = '2.15.3' 17 | okhttpVersion = '4.12.0' 18 | 19 | junitVersion = '5.9.3' 20 | mockitoVersion = '4.8.0' 21 | } 22 | 23 | dependencies { 24 | implementation "org.bouncycastle:bcprov-jdk18on:$bouncycastleVersion" 25 | implementation "com.fasterxml.jackson.core:jackson-databind:$jacksonVersion" 26 | implementation "com.squareup.okhttp3:okhttp:$okhttpVersion" 27 | 28 | testImplementation "com.squareup.okhttp3:logging-interceptor:$okhttpVersion" 29 | testImplementation "org.mockito:mockito-core:$mockitoVersion" 30 | testImplementation "org.junit.jupiter:junit-jupiter-api:$junitVersion" 31 | testRuntimeOnly "org.junit.jupiter:junit-jupiter-engine:$junitVersion" 32 | } 33 | 34 | test { 35 | useJUnitPlatform { 36 | excludeTags "integration" 37 | } 38 | } 39 | 40 | task integrationTest(type: Test) { 41 | useJUnitPlatform { 42 | includeTags "integration" 43 | } 44 | description = 'Runs integration tests.' 45 | group = 'verification' 46 | } 47 | -------------------------------------------------------------------------------- /library/src/main/java/foundation/icon/icx/Call.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 ICON Foundation 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package foundation.icon.icx; 18 | 19 | import foundation.icon.icx.crypto.IconKeys; 20 | import foundation.icon.icx.data.Address; 21 | import foundation.icon.icx.transport.jsonrpc.RpcItem; 22 | import foundation.icon.icx.transport.jsonrpc.RpcItemCreator; 23 | import foundation.icon.icx.transport.jsonrpc.RpcObject; 24 | import foundation.icon.icx.transport.jsonrpc.RpcValue; 25 | 26 | import java.math.BigInteger; 27 | 28 | import static foundation.icon.icx.TransactionBuilder.checkArgument; 29 | 30 | /** 31 | * Call contains parameters for querying request. 32 | * 33 | * @param Response type 34 | */ 35 | public final class Call { 36 | 37 | private final RpcObject properties; 38 | private final Class responseType; 39 | 40 | private Call(RpcObject properties, Class responseType) { 41 | this.properties = properties; 42 | this.responseType = responseType; 43 | } 44 | 45 | RpcObject getProperties() { 46 | return properties; 47 | } 48 | 49 | Class responseType() { 50 | return responseType; 51 | } 52 | 53 | /** 54 | * Builder for creating immutable object of Call.
55 | * It has following properties
56 | * - {@link #from(Address)} the request account
57 | * - {@link #to(Address)} the SCORE address to call
58 | * - {@link #method(String)} the method name to call
59 | * - {@link #params(Object)} the parameter of call
60 | */ 61 | @SuppressWarnings("WeakerAccess") 62 | public static class Builder { 63 | private Address from; 64 | private Address to; 65 | private String method; 66 | private BigInteger height; 67 | private RpcItem params; 68 | 69 | public Builder() { 70 | } 71 | 72 | public Builder from(Address from) { 73 | this.from = from; 74 | return this; 75 | } 76 | 77 | public Builder to(Address to) { 78 | if (!IconKeys.isContractAddress(to)) 79 | throw new IllegalArgumentException("Only the contract address can be called."); 80 | this.to = to; 81 | return this; 82 | } 83 | 84 | public Builder method(String method) { 85 | this.method = method; 86 | return this; 87 | } 88 | 89 | public Builder height(BigInteger height) { 90 | this.height = height; 91 | return this; 92 | } 93 | 94 | public Builder params(T params) { 95 | this.params = RpcItemCreator.create(params); 96 | return this; 97 | } 98 | 99 | public Builder params(RpcItem params) { 100 | this.params = params; 101 | return this; 102 | } 103 | 104 | /** 105 | * Builds with RpcItem. that means the return type is RpcItem 106 | * 107 | * @return Call 108 | */ 109 | public Call build() { 110 | checkArgument(to, "to not found"); 111 | checkArgument(method, "method not found"); 112 | return buildWith(RpcItem.class); 113 | } 114 | 115 | /** 116 | * Builds with User defined class. an object of the class would be returned 117 | * 118 | * @param responseType Response type 119 | * @param responseType 120 | * @return Call 121 | */ 122 | public Call buildWith(Class responseType) { 123 | RpcObject data = new RpcObject.Builder() 124 | .put("method", new RpcValue(method)) 125 | .put("params", params) 126 | .build(); 127 | 128 | RpcObject.Builder propertiesBuilder = new RpcObject.Builder() 129 | .put("to", new RpcValue(to)) 130 | .put("data", data) 131 | .put("dataType", new RpcValue("call")); 132 | 133 | // optional 134 | if (from != null) { 135 | propertiesBuilder.put("from", new RpcValue(from)); 136 | } 137 | if (height != null) { 138 | propertiesBuilder.put("height", new RpcValue(height)); 139 | } 140 | 141 | return new Call<>(propertiesBuilder.build(), responseType); 142 | } 143 | } 144 | } 145 | -------------------------------------------------------------------------------- /library/src/main/java/foundation/icon/icx/Callback.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 ICON Foundation 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package foundation.icon.icx; 18 | 19 | /** 20 | * A callback of the asynchronous execution 21 | */ 22 | public interface Callback { 23 | 24 | /** 25 | * Invoked when the execution is successful 26 | * @param result a result of the execution 27 | */ 28 | void onSuccess(T result); 29 | 30 | /** 31 | * Invoked when the execution is completed with an exception 32 | * @param exception an exception thrown during the execution 33 | */ 34 | void onFailure(Exception exception); 35 | } 36 | -------------------------------------------------------------------------------- /library/src/main/java/foundation/icon/icx/KeyWallet.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 ICON Foundation 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package foundation.icon.icx; 18 | 19 | import foundation.icon.icx.crypto.ECDSASignature; 20 | import foundation.icon.icx.crypto.IconKeys; 21 | import foundation.icon.icx.crypto.KeyStoreUtils; 22 | import foundation.icon.icx.crypto.Keystore; 23 | import foundation.icon.icx.crypto.KeystoreException; 24 | import foundation.icon.icx.crypto.KeystoreFile; 25 | import foundation.icon.icx.data.Address; 26 | import foundation.icon.icx.data.Bytes; 27 | 28 | import java.io.File; 29 | import java.io.IOException; 30 | import java.math.BigInteger; 31 | import java.security.InvalidAlgorithmParameterException; 32 | import java.security.NoSuchAlgorithmException; 33 | import java.security.NoSuchProviderException; 34 | 35 | import static foundation.icon.icx.TransactionBuilder.checkArgument; 36 | 37 | /** 38 | * An implementation of Wallet which uses of the key pair. 39 | */ 40 | @SuppressWarnings({"WeakerAccess", "unused"}) 41 | public class KeyWallet implements Wallet { 42 | 43 | private final Bytes privateKey; 44 | private final Bytes publicKey; 45 | 46 | private KeyWallet(Bytes privateKey, Bytes publicKey) { 47 | this.privateKey = privateKey; 48 | this.publicKey = publicKey; 49 | } 50 | 51 | /** 52 | * Loads a key wallet from the private key 53 | * 54 | * @param privateKey the private key to load 55 | * @return KeyWallet 56 | */ 57 | public static KeyWallet load(Bytes privateKey) { 58 | Bytes publicKey = IconKeys.getPublicKey(privateKey); 59 | return new KeyWallet(privateKey, publicKey); 60 | } 61 | 62 | /** 63 | * Creates a new KeyWallet with generating a new key pair. 64 | * 65 | * @return new KeyWallet 66 | */ 67 | public static KeyWallet create() throws 68 | InvalidAlgorithmParameterException, NoSuchAlgorithmException, NoSuchProviderException { 69 | Bytes privateKey = IconKeys.createPrivateKey(); 70 | Bytes publicKey = IconKeys.getPublicKey(privateKey); 71 | return new KeyWallet(privateKey, publicKey); 72 | } 73 | 74 | /** 75 | * Loads a key wallet from the KeyStore file 76 | * 77 | * @param password the password of KeyStore 78 | * @param file the KeyStore file 79 | * @return KeyWallet 80 | */ 81 | public static KeyWallet load(String password, File file) throws IOException, KeystoreException { 82 | Bytes privateKey = KeyStoreUtils.loadPrivateKey(password, file); 83 | Bytes pubicKey = IconKeys.getPublicKey(privateKey); 84 | return new KeyWallet(privateKey, pubicKey); 85 | } 86 | 87 | /** 88 | * Stores the KeyWallet as a KeyStore 89 | * 90 | * @param wallet the wallet to store 91 | * @param password the password of KeyStore 92 | * @param destinationDirectory the KeyStore file is stored at. 93 | * @return name of the KeyStore file 94 | */ 95 | public static String store(KeyWallet wallet, String password, File destinationDirectory) throws 96 | KeystoreException, IOException { 97 | KeystoreFile keystoreFile = Keystore.create(password, wallet.getPrivateKey(), 1 << 14, 1); 98 | return KeyStoreUtils.generateWalletFile(keystoreFile, destinationDirectory); 99 | } 100 | 101 | /** 102 | * @see Wallet#getAddress() 103 | */ 104 | @Override 105 | public Address getAddress() { 106 | return IconKeys.getAddress(publicKey); 107 | } 108 | 109 | /** 110 | * @see Wallet#sign(byte[]) 111 | */ 112 | @Override 113 | public byte[] sign(byte[] data) { 114 | checkArgument(data, "hash not found"); 115 | ECDSASignature signature = new ECDSASignature(privateKey); 116 | BigInteger[] sig = signature.generateSignature(data); 117 | return signature.recoverableSerialize(sig, data); 118 | } 119 | 120 | /** 121 | * Gets the private key 122 | * 123 | * @return private key 124 | */ 125 | public Bytes getPrivateKey() { 126 | return privateKey; 127 | } 128 | 129 | /** 130 | * Gets the public key 131 | * 132 | * @return public key in uncompressed format 133 | */ 134 | public Bytes getPublicKey() { 135 | return publicKey; 136 | } 137 | 138 | /** 139 | * Gets the public key in the specified format 140 | * 141 | * @param compressed whether to generate a compressed format 142 | * @return public key in the specified format 143 | */ 144 | public Bytes getPublicKey(boolean compressed) { 145 | return IconKeys.getPublicKey(privateKey, compressed); 146 | } 147 | } 148 | -------------------------------------------------------------------------------- /library/src/main/java/foundation/icon/icx/Provider.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 ICON Foundation 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package foundation.icon.icx; 18 | 19 | import foundation.icon.icx.transport.jsonrpc.RpcConverter; 20 | import foundation.icon.icx.transport.monitor.Monitor; 21 | import foundation.icon.icx.transport.monitor.MonitorSpec; 22 | 23 | /** 24 | * The {@code Provider} class transports the request and receives the response. 25 | */ 26 | public interface Provider { 27 | 28 | /** 29 | * Prepares to execute the request 30 | * 31 | * @param request the request to send 32 | * @param converter the converter for the response data 33 | * @param the return type 34 | * @return a {@code Request} object to be executed 35 | */ 36 | Request request(foundation.icon.icx.transport.jsonrpc.Request request, RpcConverter converter); 37 | 38 | /** 39 | * Prepares a Websocket monitor to get notification 40 | * 41 | * @param spec the monitor spec 42 | * @param converter the converter for the notification data 43 | * @param the return type 44 | * @return a {@code Monitor} object to be used for monitoring 45 | */ 46 | default Monitor monitor(MonitorSpec spec, RpcConverter converter) { 47 | throw new UnsupportedOperationException(); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /library/src/main/java/foundation/icon/icx/Request.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 ICON Foundation 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package foundation.icon.icx; 18 | 19 | import java.io.IOException; 20 | 21 | /** 22 | * Request class executes the request that has been prepared 23 | */ 24 | public interface Request { 25 | 26 | /** 27 | * Executes synchronously 28 | * 29 | * @return Response 30 | * @throws IOException an exception if there exist errors 31 | */ 32 | T execute() throws IOException; 33 | 34 | /** 35 | * Executes asynchronously 36 | * 37 | * @param callback the callback is invoked when the execution is completed 38 | */ 39 | void execute(Callback callback); 40 | } 41 | -------------------------------------------------------------------------------- /library/src/main/java/foundation/icon/icx/Transaction.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 ICON Foundation 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package foundation.icon.icx; 18 | 19 | import foundation.icon.icx.data.Address; 20 | import foundation.icon.icx.transport.jsonrpc.RpcItem; 21 | import foundation.icon.icx.transport.jsonrpc.RpcObject; 22 | 23 | import java.math.BigInteger; 24 | 25 | public interface Transaction { 26 | BigInteger getVersion(); 27 | 28 | Address getFrom(); 29 | 30 | Address getTo(); 31 | 32 | BigInteger getValue(); 33 | 34 | BigInteger getStepLimit(); 35 | 36 | BigInteger getTimestamp(); 37 | 38 | BigInteger getNid(); 39 | 40 | BigInteger getNonce(); 41 | 42 | String getDataType(); 43 | 44 | RpcItem getData(); 45 | 46 | RpcObject getProperties(); 47 | } 48 | -------------------------------------------------------------------------------- /library/src/main/java/foundation/icon/icx/Wallet.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 ICON Foundation 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package foundation.icon.icx; 18 | 19 | import foundation.icon.icx.data.Address; 20 | 21 | /** 22 | * Wallet class signs the message(a transaction message to send) 23 | * using own key-pair 24 | */ 25 | public interface Wallet { 26 | 27 | /** 28 | * Gets the address corresponding the key of the wallet 29 | * 30 | * @return address 31 | */ 32 | Address getAddress(); 33 | 34 | /** 35 | * Signs the data to generate a signature 36 | * 37 | * @param data to sign 38 | * @return signature 39 | */ 40 | byte[] sign(byte[] data); 41 | } 42 | -------------------------------------------------------------------------------- /library/src/main/java/foundation/icon/icx/crypto/KeyStoreUtils.java: -------------------------------------------------------------------------------- 1 | package foundation.icon.icx.crypto; 2 | 3 | import com.fasterxml.jackson.core.JsonParser; 4 | import com.fasterxml.jackson.databind.DeserializationFeature; 5 | import com.fasterxml.jackson.databind.ObjectMapper; 6 | import foundation.icon.icx.data.Bytes; 7 | 8 | import java.io.File; 9 | import java.io.IOException; 10 | import java.text.SimpleDateFormat; 11 | import java.util.Date; 12 | import java.util.InputMismatchException; 13 | import java.util.TimeZone; 14 | 15 | /** 16 | * Original Code 17 | * https://github.com/web3j/web3j/blob/master/crypto/src/main/java/org/web3j/crypto/WalletUtils.java 18 | * Utility functions for working with Keystore files. 19 | */ 20 | public class KeyStoreUtils { 21 | 22 | private KeyStoreUtils() { } 23 | 24 | private static final ObjectMapper objectMapper = new ObjectMapper(); 25 | 26 | static { 27 | objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true); 28 | objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); 29 | } 30 | 31 | public static String generateWalletFile( 32 | KeystoreFile file, File destinationDirectory) throws IOException { 33 | 34 | String fileName = getWalletFileName(file); 35 | File destination = new File(destinationDirectory, fileName); 36 | objectMapper.writeValue(destination, file); 37 | return fileName; 38 | } 39 | 40 | public static Bytes loadPrivateKey(String password, File source) 41 | throws IOException, KeystoreException { 42 | ObjectMapper mapper = new ObjectMapper(); 43 | KeystoreFile keystoreFile = mapper.readValue(source, KeystoreFile.class); 44 | if (keystoreFile.getCoinType() == null || !keystoreFile.getCoinType().equalsIgnoreCase("icx")) 45 | throw new InputMismatchException("Invalid Keystore file"); 46 | return Keystore.decrypt(password, keystoreFile); 47 | } 48 | 49 | private static String getWalletFileName(KeystoreFile keystoreFile) { 50 | SimpleDateFormat dateFormat = new SimpleDateFormat("'UTC--'yyyy-MM-dd'T'HH-mm-ss.SSS'--'"); 51 | dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); 52 | return dateFormat.format(new Date()) + keystoreFile.getAddress() + ".json"; 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /library/src/main/java/foundation/icon/icx/crypto/KeystoreException.java: -------------------------------------------------------------------------------- 1 | package foundation.icon.icx.crypto; 2 | 3 | /** 4 | * Original Code 5 | * https://github.com/web3j/web3j/blob/master/crypto/src/main/java/org/web3j/crypto/CipherException.java 6 | */ 7 | public class KeystoreException extends Exception { 8 | 9 | KeystoreException(String message) { 10 | super(message); 11 | } 12 | 13 | KeystoreException(Throwable cause) { 14 | super(cause); 15 | } 16 | 17 | KeystoreException(String message, Throwable cause) { 18 | super(message, cause); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /library/src/main/java/foundation/icon/icx/crypto/LinuxSecureRandom.java: -------------------------------------------------------------------------------- 1 | package foundation.icon.icx.crypto; 2 | 3 | import java.io.DataInputStream; 4 | import java.io.File; 5 | import java.io.FileInputStream; 6 | import java.io.FileNotFoundException; 7 | import java.io.IOException; 8 | import java.security.Provider; 9 | import java.security.SecureRandomSpi; 10 | import java.security.Security; 11 | 12 | /** 13 | * Implementation from 14 | * BitcoinJ implementation 15 | * 16 | *

A SecureRandom implementation that is able to override the standard JVM provided 17 | * implementation, and which simply serves random numbers by reading /dev/urandom. That is, it 18 | * delegates to the kernel on UNIX systems and is unusable on other platforms. Attempts to manually 19 | * set the seed are ignored. There is no difference between seed bytes and non-seed bytes, they are 20 | * all from the same source. 21 | */ 22 | public class LinuxSecureRandom extends SecureRandomSpi { 23 | private static final FileInputStream urandom; 24 | 25 | static { 26 | try { 27 | File file = new File("/dev/urandom"); 28 | // This stream is deliberately leaked. 29 | urandom = new FileInputStream(file); 30 | if (urandom.read() == -1) { 31 | throw new RuntimeException("/dev/urandom not readable?"); 32 | } 33 | // Now override the default SecureRandom implementation with this one. 34 | Security.insertProviderAt(new LinuxSecureRandomProvider(), 1); 35 | 36 | } catch (FileNotFoundException e) { 37 | // Should never happen. 38 | throw new RuntimeException(e); 39 | } catch (IOException e) { 40 | throw new RuntimeException(e); 41 | } 42 | } 43 | 44 | private final DataInputStream dis; 45 | 46 | public LinuxSecureRandom() { 47 | // DataInputStream is not thread safe, so each random object has its own. 48 | dis = new DataInputStream(urandom); 49 | } 50 | 51 | @Override 52 | protected void engineSetSeed(byte[] bytes) { 53 | // Ignore. 54 | } 55 | 56 | @Override 57 | protected void engineNextBytes(byte[] bytes) { 58 | try { 59 | dis.readFully(bytes); // This will block until all the bytes can be read. 60 | } catch (IOException e) { 61 | throw new RuntimeException(e); // Fatal error. Do not attempt to recover from this. 62 | } 63 | } 64 | 65 | @Override 66 | protected byte[] engineGenerateSeed(int i) { 67 | byte[] bits = new byte[i]; 68 | engineNextBytes(bits); 69 | return bits; 70 | } 71 | 72 | private static class LinuxSecureRandomProvider extends Provider { 73 | public LinuxSecureRandomProvider() { 74 | super("LinuxSecureRandom", 1.0, 75 | "A Linux specific random number provider that uses /dev/urandom"); 76 | put("SecureRandom.LinuxSecureRandom", LinuxSecureRandom.class.getName()); 77 | } 78 | } 79 | } -------------------------------------------------------------------------------- /library/src/main/java/foundation/icon/icx/data/Address.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 ICON Foundation 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package foundation.icon.icx.data; 18 | 19 | import foundation.icon.icx.crypto.IconKeys; 20 | import org.bouncycastle.util.encoders.Hex; 21 | 22 | import java.util.Arrays; 23 | 24 | public class Address { 25 | 26 | private AddressPrefix prefix; 27 | private byte[] body; 28 | private boolean isMalformed = false; 29 | private String malformedAddress; 30 | 31 | public static Address createMalformedAddress(String malformedAddress) { 32 | Address address = new Address(); 33 | address.isMalformed = true; 34 | address.malformedAddress = malformedAddress; 35 | return address; 36 | } 37 | 38 | private Address() { 39 | } 40 | 41 | public Address(String address) { 42 | AddressPrefix addressPrefix = IconKeys.getAddressHexPrefix(address); 43 | if (addressPrefix == null) { 44 | throw new IllegalArgumentException("Invalid address prefix"); 45 | } else if (!IconKeys.isValidAddress(address)) { 46 | throw new IllegalArgumentException("Invalid address"); 47 | } 48 | 49 | this.prefix = addressPrefix; 50 | this.body = getAddressBody(address); 51 | } 52 | 53 | public Address(AddressPrefix prefix, byte[] body) { 54 | if (!IconKeys.isValidAddressBody(body)) { 55 | throw new IllegalArgumentException("Invalid address"); 56 | } 57 | 58 | this.prefix = prefix; 59 | this.body = body; 60 | } 61 | 62 | private byte[] getAddressBody(String address) { 63 | String cleanInput = IconKeys.cleanHexPrefix(address); 64 | return Hex.decode(cleanInput); 65 | } 66 | 67 | public AddressPrefix getPrefix() { 68 | return prefix; 69 | } 70 | 71 | public byte[] getBody() { 72 | return this.body.clone(); 73 | } 74 | 75 | public boolean isMalformed() { 76 | return isMalformed; 77 | } 78 | 79 | @Override 80 | public String toString() { 81 | if (isMalformed) { 82 | return malformedAddress; 83 | } else { 84 | return getPrefix().getValue() + Hex.toHexString(body); 85 | } 86 | } 87 | 88 | @Override 89 | public boolean equals(Object obj) { 90 | if (obj == this) return true; 91 | if (obj instanceof Address) { 92 | Address other = (Address) obj; 93 | if (isMalformed) { 94 | return malformedAddress.equals(other.malformedAddress); 95 | } else { 96 | return !other.isMalformed && other.prefix == prefix && Arrays.equals(other.body, body); 97 | } 98 | } 99 | return false; 100 | } 101 | 102 | @Override 103 | public int hashCode() { 104 | if (isMalformed) { 105 | return malformedAddress.hashCode(); 106 | } else { 107 | byte[] raw = new byte[body.length + 1]; 108 | raw[0] = (byte) prefix.ordinal(); 109 | System.arraycopy(body, 0, raw, 1, body.length); 110 | return Arrays.hashCode(raw); 111 | } 112 | } 113 | 114 | public enum AddressPrefix { 115 | 116 | EOA("hx"), 117 | CONTRACT("cx"); 118 | 119 | private final String prefix; 120 | 121 | AddressPrefix(String prefix) { 122 | this.prefix = prefix; 123 | } 124 | 125 | public String getValue() { 126 | return prefix; 127 | } 128 | 129 | public static AddressPrefix fromString(String prefix) { 130 | if (prefix != null) { 131 | for (AddressPrefix p : AddressPrefix.values()) { 132 | if (prefix.equalsIgnoreCase(p.getValue())) { 133 | return p; 134 | } 135 | } 136 | } 137 | return null; 138 | } 139 | } 140 | } 141 | -------------------------------------------------------------------------------- /library/src/main/java/foundation/icon/icx/data/BTPNetworkInfo.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 ICON Foundation 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package foundation.icon.icx.data; 18 | 19 | import foundation.icon.icx.transport.jsonrpc.RpcItem; 20 | import foundation.icon.icx.transport.jsonrpc.RpcObject; 21 | 22 | import java.math.BigInteger; 23 | 24 | public class BTPNetworkInfo { 25 | 26 | private final RpcObject properties; 27 | 28 | public BTPNetworkInfo(RpcObject properties) { 29 | this.properties = properties; 30 | } 31 | 32 | public RpcObject getProperties() { 33 | return properties; 34 | } 35 | 36 | public BigInteger getStartHeight() { 37 | RpcItem item = properties.getItem("startHeight"); 38 | return item != null ? item.asInteger() : null; 39 | } 40 | 41 | public BigInteger getNetworkTypeID() { 42 | RpcItem item = properties.getItem("networkTypeID"); 43 | return item != null ? item.asInteger() : null; 44 | } 45 | 46 | public String getNetworkTypeName() { 47 | RpcItem item = properties.getItem("networkTypeName"); 48 | return item != null ? item.asString() : null; 49 | } 50 | 51 | public BigInteger getNetworkID() { 52 | RpcItem item = properties.getItem("networkID"); 53 | return item != null ? item.asInteger() : null; 54 | } 55 | 56 | public String getNetworkName() { 57 | RpcItem item = properties.getItem("networkName"); 58 | return item != null ? item.asString() : null; 59 | } 60 | 61 | public Boolean getOpen() { 62 | RpcItem item = properties.getItem("open"); 63 | return item != null ? item.asBoolean() : null; 64 | } 65 | 66 | public Address getOwner() { 67 | RpcItem item = properties.getItem("owner"); 68 | return item != null ? item.asAddress() : null; 69 | } 70 | 71 | public BigInteger getNextMessageSN() { 72 | RpcItem item = properties.getItem("nextMessageSN"); 73 | return item != null ? item.asInteger() : null; 74 | } 75 | 76 | public Boolean getNextProofContextChanged() { 77 | RpcItem item = properties.getItem("nextProofContextChanged"); 78 | return item != null ? item.asBoolean() : null; 79 | } 80 | 81 | public Bytes getPrevNSHash() { 82 | RpcItem item = properties.getItem("prevNSHash"); 83 | if (item == null || item.isEmpty()) { 84 | return null; 85 | } 86 | return item.asBytes(); 87 | } 88 | 89 | public Bytes getLastNSHash() { 90 | RpcItem item = properties.getItem("lastNSHash"); 91 | return item != null ? item.asBytes() : null; 92 | } 93 | 94 | @Override 95 | public boolean equals(Object obj) { 96 | if (this == obj) return true; 97 | if (!(obj instanceof BTPNetworkInfo)) return false; 98 | BTPNetworkInfo o = (BTPNetworkInfo) obj; 99 | return properties.equals(o.properties); 100 | } 101 | 102 | @Override 103 | public String toString() { 104 | return "BTPNetworkInfo{" + 105 | "properties=" + properties + 106 | '}'; 107 | } 108 | } 109 | -------------------------------------------------------------------------------- /library/src/main/java/foundation/icon/icx/data/BTPNetworkTypeInfo.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 ICON Foundation 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package foundation.icon.icx.data; 18 | 19 | import foundation.icon.icx.transport.jsonrpc.RpcItem; 20 | import foundation.icon.icx.transport.jsonrpc.RpcObject; 21 | 22 | import java.math.BigInteger; 23 | import java.util.ArrayList; 24 | import java.util.List; 25 | 26 | import static foundation.icon.icx.data.Converters.BIG_INTEGER; 27 | 28 | public class BTPNetworkTypeInfo { 29 | 30 | private final RpcObject properties; 31 | 32 | BTPNetworkTypeInfo(RpcObject properties) { 33 | this.properties = properties; 34 | } 35 | 36 | public RpcObject getProperties() { 37 | return properties; 38 | } 39 | 40 | public BigInteger getNetworkTypeID() { 41 | RpcItem item = properties.getItem("networkTypeID"); 42 | return item != null ? item.asInteger() : null; 43 | } 44 | 45 | public String getNetworkTypeName() { 46 | RpcItem item = properties.getItem("networkTypeName"); 47 | return item != null ? item.asString() : null; 48 | } 49 | 50 | public List getOpenNetworkIDs() { 51 | RpcItem item = properties.getItem("openNetworkIDs"); 52 | List ids = new ArrayList<>(); 53 | if (item != null) { 54 | for (RpcItem rpcItem : item.asArray()) { 55 | ids.add(BIG_INTEGER.convertTo(rpcItem)); 56 | } 57 | } 58 | return ids; 59 | } 60 | 61 | public String getNextProofContext() { 62 | RpcItem item = properties.getItem("nextProofContext"); 63 | return item != null ? item.asString() : null; 64 | } 65 | 66 | @Override 67 | public boolean equals(Object obj) { 68 | if (this == obj) { 69 | return true; 70 | } 71 | if (!(obj instanceof BTPNetworkTypeInfo)) { 72 | return false; 73 | } 74 | BTPNetworkTypeInfo ntInfo = (BTPNetworkTypeInfo) obj; 75 | return properties.equals(ntInfo.properties); 76 | } 77 | 78 | @Override 79 | public String toString() { 80 | return "BTPNetworkTypeInfo{" + 81 | "properties=" + properties + 82 | '}'; 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /library/src/main/java/foundation/icon/icx/data/BTPNotification.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 ICON Foundation 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package foundation.icon.icx.data; 18 | 19 | import foundation.icon.icx.transport.jsonrpc.RpcItem; 20 | import foundation.icon.icx.transport.jsonrpc.RpcObject; 21 | 22 | public class BTPNotification { 23 | private final RpcObject properties; 24 | 25 | BTPNotification(RpcObject properties) { 26 | this.properties = properties; 27 | } 28 | 29 | public Base64 getHeader() { 30 | RpcItem item = properties.getItem("header"); 31 | return item != null ? new Base64(item.asString()) : null; 32 | } 33 | 34 | public Base64 getProof() { 35 | RpcItem item = properties.getItem("proof"); 36 | return item != null ? new Base64(item.asString()) : null; 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /library/src/main/java/foundation/icon/icx/data/BTPSourceInfo.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 ICON Foundation 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package foundation.icon.icx.data; 18 | 19 | import foundation.icon.icx.transport.jsonrpc.RpcItem; 20 | import foundation.icon.icx.transport.jsonrpc.RpcObject; 21 | 22 | import java.math.BigInteger; 23 | import java.util.ArrayList; 24 | import java.util.List; 25 | 26 | import static foundation.icon.icx.data.Converters.BIG_INTEGER; 27 | 28 | public class BTPSourceInfo { 29 | 30 | private final RpcObject properties; 31 | 32 | public BTPSourceInfo(RpcObject properties) { 33 | this.properties = properties; 34 | } 35 | 36 | public String getSrcNetworkUID() { 37 | RpcItem item = properties.getItem("srcNetworkUID"); 38 | return item != null ? item.asString() : null; 39 | } 40 | 41 | public List getNetworkTypeIDs() { 42 | RpcItem item = properties.getItem("networkTypeIDs"); 43 | List ids = new ArrayList<>(); 44 | if (item != null) { 45 | for (RpcItem rpcItem : item.asArray()) { 46 | ids.add(BIG_INTEGER.convertTo(rpcItem)); 47 | } 48 | } 49 | return ids; 50 | } 51 | 52 | @Override 53 | public String toString() { 54 | return "BTPSourceInfo{" + 55 | "properties=" + properties + 56 | '}'; 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /library/src/main/java/foundation/icon/icx/data/Base64.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019 ICON Foundation 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package foundation.icon.icx.data; 18 | 19 | public class Base64 { 20 | private final String data; 21 | 22 | public Base64(String data) { 23 | this.data = data; 24 | } 25 | 26 | public byte[] decode() { 27 | return java.util.Base64.getDecoder().decode(data); 28 | } 29 | 30 | @Override 31 | public boolean equals(Object obj) { 32 | if (obj == this) return true; 33 | if (obj instanceof Base64) { 34 | Base64 other = (Base64) obj; 35 | return this.data.equals(other.data); 36 | } 37 | return false; 38 | } 39 | 40 | @Override 41 | public String toString() { 42 | return this.data; 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /library/src/main/java/foundation/icon/icx/data/Block.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 ICON Foundation 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package foundation.icon.icx.data; 18 | 19 | import foundation.icon.icx.transport.jsonrpc.RpcItem; 20 | import foundation.icon.icx.transport.jsonrpc.RpcObject; 21 | 22 | import java.math.BigInteger; 23 | import java.util.ArrayList; 24 | import java.util.List; 25 | 26 | import static foundation.icon.icx.data.Converters.CONFIRMED_TRANSACTION; 27 | 28 | public class Block { 29 | 30 | private final RpcObject properties; 31 | 32 | Block(RpcObject properties) { 33 | this.properties = properties; 34 | } 35 | 36 | public RpcObject getProperties() { 37 | return properties; 38 | } 39 | 40 | public Bytes getPrevBlockHash() { 41 | RpcItem item = properties.getItem("prev_block_hash"); 42 | return item != null ? item.asBytes() : null; 43 | } 44 | 45 | public Bytes getMerkleTreeRootHash() { 46 | RpcItem item = properties.getItem("merkle_tree_root_hash"); 47 | return item != null ? item.asBytes() : null; 48 | } 49 | 50 | public BigInteger getTimestamp() { 51 | RpcItem item = properties.getItem("time_stamp"); 52 | return item != null ? item.asInteger() : null; 53 | } 54 | 55 | public List getTransactions() { 56 | RpcItem item = properties.getItem("confirmed_transaction_list"); 57 | List transactions = new ArrayList<>(); 58 | if (item != null && getHeight().intValue() > 0) { 59 | for (RpcItem tx : item.asArray()) { 60 | transactions.add(CONFIRMED_TRANSACTION.convertTo(tx.asObject())); 61 | } 62 | } 63 | return transactions; 64 | } 65 | 66 | public Bytes getBlockHash() { 67 | RpcItem item = properties.getItem("block_hash"); 68 | return item != null ? item.asBytes() : null; 69 | } 70 | 71 | public String getPeerId() { 72 | RpcItem item = properties.getItem("peer_id"); 73 | return item != null ? item.asString() : null; 74 | } 75 | 76 | public BigInteger getVersion() { 77 | RpcItem item = properties.getItem("version"); 78 | return item != null ? item.asInteger() : null; 79 | } 80 | 81 | public BigInteger getHeight() { 82 | RpcItem item = properties.getItem("height"); 83 | return item != null ? item.asInteger() : null; 84 | } 85 | 86 | public String getSignature() { 87 | RpcItem item = properties.getItem("signature"); 88 | return item != null ? item.asString() : null; 89 | } 90 | 91 | @Override 92 | public String toString() { 93 | return "Block{" + 94 | "properties=" + properties + 95 | '}'; 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /library/src/main/java/foundation/icon/icx/data/BlockNotification.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019 ICON Foundation 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package foundation.icon.icx.data; 18 | 19 | import foundation.icon.icx.transport.jsonrpc.RpcArray; 20 | import foundation.icon.icx.transport.jsonrpc.RpcItem; 21 | import foundation.icon.icx.transport.jsonrpc.RpcObject; 22 | 23 | import java.math.BigInteger; 24 | import java.util.ArrayList; 25 | import java.util.List; 26 | 27 | public class BlockNotification { 28 | private final RpcObject properties; 29 | 30 | BlockNotification(RpcObject properties) { 31 | this.properties = properties; 32 | } 33 | 34 | public Bytes getHash() { 35 | RpcItem item = properties.getItem("hash"); 36 | return item != null ? item.asBytes() : null; 37 | } 38 | 39 | public BigInteger getHeight() { 40 | return asInteger(properties.getItem("height")); 41 | } 42 | 43 | public BigInteger[][] getIndexes() { 44 | return asIntegerArrayArray(properties.getItem("indexes")); 45 | } 46 | 47 | public BigInteger[][][] getEvents() { 48 | RpcItem item = properties.getItem("events"); 49 | BigInteger[][][] events = null; 50 | if (item != null) { 51 | RpcArray rpcArray = item.asArray(); 52 | int size = rpcArray.size(); 53 | events = new BigInteger[size][][]; 54 | for (int i = 0; i < size; i++) { 55 | events[i] = asIntegerArrayArray(rpcArray.get(i)); 56 | } 57 | } 58 | return events; 59 | } 60 | 61 | public static BigInteger[][] asIntegerArrayArray(RpcItem item) { 62 | BigInteger[][] arr = null; 63 | if (item != null) { 64 | RpcArray rpcArray = item.asArray(); 65 | int size = rpcArray.size(); 66 | arr = new BigInteger[size][]; 67 | for (int i = 0; i < size; i++) { 68 | arr[i] = asIntegerArray(rpcArray.get(i)); 69 | } 70 | } 71 | return arr; 72 | } 73 | 74 | public static BigInteger[] asIntegerArray(RpcItem item) { 75 | BigInteger[] arr = null; 76 | if (item != null) { 77 | RpcArray rpcArray = item.asArray(); 78 | int size = rpcArray.size(); 79 | arr = new BigInteger[size]; 80 | for (int i = 0; i < size; i++) { 81 | arr[i] = asInteger(rpcArray.get(i)); 82 | } 83 | } 84 | return arr; 85 | } 86 | 87 | public static BigInteger asInteger(RpcItem item) { 88 | return item != null ? item.asInteger() : null; 89 | } 90 | 91 | public List getLogs() { 92 | RpcItem item = properties.getItem("logs"); 93 | List eventLogs = new ArrayList<>(); 94 | if (item != null) { 95 | for (RpcItem rpcItem : item.asArray()) { 96 | eventLogs.add(new TransactionResult.EventLog(rpcItem.asObject())); 97 | } 98 | } 99 | return eventLogs; 100 | } 101 | 102 | @Override 103 | public String toString() { 104 | return "BlockNotification{Properties="+properties+"}"; 105 | } 106 | } 107 | -------------------------------------------------------------------------------- /library/src/main/java/foundation/icon/icx/data/EventNotification.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019 ICON Foundation 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package foundation.icon.icx.data; 18 | 19 | import foundation.icon.icx.transport.jsonrpc.RpcArray; 20 | import foundation.icon.icx.transport.jsonrpc.RpcItem; 21 | import foundation.icon.icx.transport.jsonrpc.RpcObject; 22 | 23 | import java.math.BigInteger; 24 | import java.util.ArrayList; 25 | import java.util.List; 26 | 27 | public class EventNotification { 28 | private final RpcObject properties; 29 | 30 | EventNotification(RpcObject properties) { 31 | this.properties = properties; 32 | } 33 | 34 | public Bytes getHash() { 35 | RpcItem item = properties.getItem("hash"); 36 | return item != null ? item.asBytes() : null; 37 | } 38 | 39 | public BigInteger getHeight() { 40 | return asInteger(properties.getItem("height")); 41 | } 42 | 43 | public BigInteger getIndex() { 44 | return asInteger(properties.getItem("index")); 45 | } 46 | 47 | public BigInteger[] getEvents() { 48 | RpcItem item = properties.getItem("events"); 49 | BigInteger[] events = null; 50 | if (item != null) { 51 | RpcArray rpcArray = item.asArray(); 52 | int size = rpcArray.size(); 53 | events = new BigInteger[size]; 54 | for (int i = 0; i < size; i++) { 55 | events[i] = asInteger(rpcArray.get(i)); 56 | } 57 | } 58 | return events; 59 | } 60 | 61 | public static BigInteger asInteger(RpcItem item) { 62 | return item != null ? item.asInteger() : null; 63 | } 64 | 65 | public List getLogs() { 66 | RpcItem item = properties.getItem("logs"); 67 | List eventLogs = new ArrayList<>(); 68 | if (item != null) { 69 | for (RpcItem rpcItem : item.asArray()) { 70 | eventLogs.add(new TransactionResult.EventLog(rpcItem.asObject())); 71 | } 72 | } 73 | return eventLogs; 74 | } 75 | 76 | @Override 77 | public String toString() { 78 | return "EventNotification{Properties="+properties+"}"; 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /library/src/main/java/foundation/icon/icx/data/IconAmount.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 ICON Foundation 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package foundation.icon.icx.data; 18 | 19 | import java.math.BigDecimal; 20 | import java.math.BigInteger; 21 | 22 | public class IconAmount { 23 | 24 | private final BigDecimal value; 25 | private final int digit; 26 | 27 | public IconAmount(BigDecimal value, int digit) { 28 | this.value = value; 29 | this.digit = digit; 30 | } 31 | 32 | public int getDigit() { 33 | return digit; 34 | } 35 | 36 | @Override 37 | public String toString() { 38 | return value.toString(); 39 | } 40 | 41 | public BigInteger asInteger() { 42 | return value.toBigInteger(); 43 | } 44 | 45 | public BigDecimal asDecimal() { 46 | return value; 47 | } 48 | 49 | public BigInteger toLoop() { 50 | return value.multiply(getTenDigit(digit)).toBigInteger(); 51 | } 52 | 53 | public IconAmount convertUnit(Unit unit) { 54 | BigInteger loop = toLoop(); 55 | return IconAmount.of(new BigDecimal(loop).divide(getTenDigit(unit.getValue())), unit); 56 | } 57 | 58 | public IconAmount convertUnit(int digit) { 59 | BigInteger loop = toLoop(); 60 | return IconAmount.of(new BigDecimal(loop).divide(getTenDigit(digit)), digit); 61 | } 62 | 63 | private BigDecimal getTenDigit(int digit) { 64 | return BigDecimal.TEN.pow(digit); 65 | } 66 | 67 | public enum Unit { 68 | LOOP(0), 69 | ICX(18); 70 | 71 | int digit; 72 | 73 | Unit(int digit) { 74 | this.digit = digit; 75 | } 76 | 77 | public int getValue() { 78 | return digit; 79 | } 80 | } 81 | 82 | public static IconAmount of(BigDecimal loop, int digit) { 83 | return new IconAmount(loop, digit); 84 | } 85 | 86 | public static IconAmount of(BigDecimal loop, Unit unit) { 87 | return of(loop, unit.getValue()); 88 | } 89 | 90 | public static IconAmount of(String loop, int digit) { 91 | return of(new BigDecimal(loop), digit); 92 | } 93 | 94 | public static IconAmount of(String loop, Unit unit) { 95 | return of(new BigDecimal(loop), unit.getValue()); 96 | } 97 | 98 | public static IconAmount of(BigInteger loop, int digit) { 99 | return of(new BigDecimal(loop), digit); 100 | } 101 | 102 | public static IconAmount of(BigInteger loop, Unit unit) { 103 | return of(new BigDecimal(loop), unit.getValue()); 104 | } 105 | } 106 | -------------------------------------------------------------------------------- /library/src/main/java/foundation/icon/icx/data/NetworkId.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 ICON Foundation 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package foundation.icon.icx.data; 18 | 19 | import java.math.BigInteger; 20 | 21 | /** 22 | * Defines network ids 23 | */ 24 | public enum NetworkId { 25 | 26 | MAIN(BigInteger.valueOf(1)), 27 | LISBON(BigInteger.valueOf(2)), 28 | BERLIN(BigInteger.valueOf(7)), 29 | LOCAL(BigInteger.valueOf(3)); 30 | 31 | private final BigInteger nid; 32 | 33 | NetworkId(BigInteger nid) { 34 | this.nid = nid; 35 | } 36 | 37 | public BigInteger getValue() { 38 | return nid; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /library/src/main/java/foundation/icon/icx/data/NetworkInfo.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2023 ICON Foundation 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package foundation.icon.icx.data; 18 | 19 | import foundation.icon.icx.transport.jsonrpc.RpcArray; 20 | import foundation.icon.icx.transport.jsonrpc.RpcItem; 21 | import foundation.icon.icx.transport.jsonrpc.RpcObject; 22 | 23 | import java.math.BigInteger; 24 | 25 | public class NetworkInfo { 26 | private final RpcObject properties; 27 | 28 | NetworkInfo(RpcObject properties) { 29 | this.properties = properties; 30 | } 31 | 32 | public RpcObject getProperties() { 33 | return properties; 34 | } 35 | 36 | public String getPlatform() { 37 | RpcItem item = properties.getItem("platform"); 38 | return item != null ? item.asString() : null; 39 | } 40 | 41 | public BigInteger getNID() { 42 | RpcItem item = properties.getItem("nid"); 43 | return item != null ? item.asInteger() : null; 44 | } 45 | 46 | public String getChannel() { 47 | RpcItem item = properties.getItem("channel"); 48 | return item != null ? item.asString() : null; 49 | } 50 | 51 | public BigInteger getEarliest() { 52 | RpcItem item = properties.getItem("earliest"); 53 | return item != null ? item.asInteger() : null; 54 | } 55 | 56 | public BigInteger getLatest() { 57 | RpcItem item = properties.getItem("latest"); 58 | return item != null ? item.asInteger() : null; 59 | } 60 | 61 | public BigInteger getStepPrice() { 62 | RpcItem item = properties.getItem("stepPrice"); 63 | return item != null ? item.asInteger() : null; 64 | } 65 | 66 | @Override 67 | public String toString() { 68 | return "NetworkInfo{" + 69 | "properties=" + properties + 70 | '}'; 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /library/src/main/java/foundation/icon/icx/data/ScoreApi.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 ICON Foundation 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package foundation.icon.icx.data; 18 | 19 | import foundation.icon.icx.transport.jsonrpc.RpcItem; 20 | import foundation.icon.icx.transport.jsonrpc.RpcObject; 21 | 22 | import java.math.BigInteger; 23 | import java.util.ArrayList; 24 | import java.util.List; 25 | 26 | public class ScoreApi { 27 | 28 | private final RpcObject properties; 29 | 30 | ScoreApi(RpcObject properties) { 31 | this.properties = properties; 32 | } 33 | 34 | public RpcObject getProperties() { 35 | return properties; 36 | } 37 | 38 | public String getType() { 39 | RpcItem item = properties.getItem("type"); 40 | return item != null ? item.asString() : null; 41 | } 42 | 43 | public String getName() { 44 | RpcItem item = properties.getItem("name"); 45 | return item != null ? item.asString() : null; 46 | } 47 | 48 | public List getInputs() { 49 | return getParams(properties.getItem("inputs")); 50 | } 51 | 52 | public List getOutputs() { 53 | return getParams(properties.getItem("outputs")); 54 | } 55 | 56 | List getParams(RpcItem item) { 57 | List params = new ArrayList<>(); 58 | if (item != null) { 59 | for (RpcItem rpcItem : item.asArray()) { 60 | RpcObject object = (RpcObject) rpcItem; 61 | params.add(new Param(object)); 62 | } 63 | } 64 | return params; 65 | } 66 | 67 | public String getReadonly() { 68 | RpcItem item = properties.getItem("readonly"); 69 | return item != null ? item.asString() : null; 70 | } 71 | 72 | @Override 73 | public String toString() { 74 | return "ScoreApi{" + 75 | "properties=" + properties + 76 | '}'; 77 | } 78 | 79 | public static class Param { 80 | private final RpcObject properties; 81 | 82 | Param(RpcObject properties) { 83 | this.properties = properties; 84 | } 85 | 86 | public String getType() { 87 | RpcItem item = properties.getItem("type"); 88 | return item != null ? item.asString() : null; 89 | } 90 | 91 | public String getName() { 92 | RpcItem item = properties.getItem("name"); 93 | return item != null ? item.asString() : null; 94 | } 95 | 96 | public BigInteger getIndexed() { 97 | RpcItem item = properties.getItem("indexed"); 98 | return item != null ? item.asInteger() : null; 99 | } 100 | 101 | public RpcItem getDefault() { 102 | return properties.getItem("default"); 103 | } 104 | 105 | @Override 106 | public String toString() { 107 | return "Param{" + 108 | "properties=" + properties + 109 | '}'; 110 | } 111 | } 112 | } 113 | -------------------------------------------------------------------------------- /library/src/main/java/foundation/icon/icx/data/ScoreStatus.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 ICON Foundation 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package foundation.icon.icx.data; 18 | 19 | import foundation.icon.icx.transport.jsonrpc.RpcArray; 20 | import foundation.icon.icx.transport.jsonrpc.RpcItem; 21 | import foundation.icon.icx.transport.jsonrpc.RpcObject; 22 | 23 | import java.math.BigInteger; 24 | 25 | public class ScoreStatus { 26 | private final RpcObject properties; 27 | 28 | ScoreStatus(RpcObject properties) { 29 | this.properties = properties; 30 | } 31 | 32 | public RpcObject getProperties() { 33 | return properties; 34 | } 35 | 36 | public Address getOwner() { 37 | RpcItem item = properties.getItem("owner"); 38 | return item != null ? item.asAddress() : null; 39 | } 40 | 41 | public ContractStatus getCurrent() { 42 | RpcItem item = properties.getItem("current"); 43 | return item != null ? new ContractStatus(item.asObject()) : null; 44 | } 45 | 46 | public ContractStatus getNext() { 47 | RpcItem item = properties.getItem("next"); 48 | return item != null ? new ContractStatus(item.asObject()) : null; 49 | } 50 | 51 | public static class ContractStatus { 52 | private final RpcObject properties; 53 | 54 | ContractStatus(RpcObject properties) { 55 | this.properties = properties; 56 | } 57 | 58 | public Bytes getDeployTxHash() { 59 | RpcItem item = properties.getItem("deployTxHash"); 60 | return item != null ? item.asBytes() : null; 61 | } 62 | 63 | public Bytes getAuditTxHash() { 64 | RpcItem item = properties.getItem("auditTxHash"); 65 | return item != null ? item.asBytes() : null; 66 | } 67 | 68 | public Bytes getCodeHash() { 69 | RpcItem code_hash = this.properties.getItem("codeHash"); 70 | return code_hash.asBytes(); 71 | } 72 | 73 | public String getType() { 74 | RpcItem item = properties.getItem("type"); 75 | return item.asString(); 76 | } 77 | 78 | public String getStatus() { 79 | RpcItem item = properties.getItem("status"); 80 | return item.asString(); 81 | } 82 | 83 | @Override 84 | public String toString() { 85 | return "Contract{properties="+ properties + "}"; 86 | } 87 | } 88 | 89 | public DepositInfo getDepositInfo() { 90 | RpcItem item = properties.getItem("depositInfo"); 91 | return item != null ? new DepositInfo(item.asObject()) : null; 92 | } 93 | 94 | public static class DepositInfo { 95 | private final RpcObject properties; 96 | private final RpcArray deposits; 97 | 98 | DepositInfo(RpcObject properties) { 99 | this.properties = properties; 100 | this.deposits = properties.getItem("deposits").asArray(); 101 | } 102 | 103 | @Override 104 | public String toString() { 105 | return "DepositInfo{properties="+properties+"}"; 106 | } 107 | 108 | public BigInteger getAvailableDeposit() { 109 | RpcItem item = properties.getItem("availableDeposit"); 110 | return item.asInteger(); 111 | } 112 | 113 | public BigInteger getAvailableVirtualStep() { 114 | RpcItem item = properties.getItem("availableVirtualStep"); 115 | return item.asInteger(); 116 | } 117 | 118 | public RpcObject getDeposit(int idx) { 119 | return deposits.get(idx).asObject(); 120 | } 121 | 122 | public int getSizeOfDeposits() { 123 | return deposits.size(); 124 | } 125 | } 126 | 127 | public boolean isDisabled() { 128 | RpcItem value = properties.getItem("disabled"); 129 | return value != null && value.asBoolean(); 130 | } 131 | 132 | public boolean isBlocked() { 133 | RpcItem value = properties.getItem("blocked"); 134 | return value != null && value.asBoolean(); 135 | } 136 | 137 | public boolean useSystemDeposit() { 138 | RpcItem value = properties.getItem("useSystemDeposit"); 139 | return value != null && value.asBoolean(); 140 | } 141 | 142 | @Override 143 | public String toString() { 144 | return "ScoreStatus{" + 145 | "properties=" + properties + 146 | '}'; 147 | } 148 | } 149 | -------------------------------------------------------------------------------- /library/src/main/java/foundation/icon/icx/transport/http/HttpCall.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 ICON Foundation 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package foundation.icon.icx.transport.http; 18 | 19 | import com.fasterxml.jackson.databind.DeserializationFeature; 20 | import com.fasterxml.jackson.databind.ObjectMapper; 21 | import com.fasterxml.jackson.databind.module.SimpleModule; 22 | import foundation.icon.icx.Callback; 23 | import foundation.icon.icx.Request; 24 | import foundation.icon.icx.transport.jsonrpc.Response; 25 | import foundation.icon.icx.transport.jsonrpc.RpcConverter; 26 | import foundation.icon.icx.transport.jsonrpc.RpcError; 27 | import foundation.icon.icx.transport.jsonrpc.RpcItem; 28 | import foundation.icon.icx.transport.jsonrpc.RpcItemDeserializer; 29 | import okhttp3.ResponseBody; 30 | 31 | import java.io.IOException; 32 | 33 | /** 34 | * Http call can be executed by this class 35 | * 36 | * @param the data type of the response 37 | */ 38 | public class HttpCall implements Request { 39 | 40 | private final okhttp3.Call httpCall; 41 | private final RpcConverter converter; 42 | 43 | HttpCall(okhttp3.Call httpCall, RpcConverter converter) { 44 | this.httpCall = httpCall; 45 | this.converter = converter; 46 | } 47 | 48 | @Override 49 | public T execute() throws IOException { 50 | return convertResponse(httpCall.execute()); 51 | } 52 | 53 | @Override 54 | public void execute(final Callback callback) { 55 | httpCall.enqueue(new okhttp3.Callback() { 56 | @Override 57 | public void onFailure(okhttp3.Call call, IOException e) { 58 | callback.onFailure(e); 59 | } 60 | 61 | @Override 62 | public void onResponse( 63 | okhttp3.Call call, okhttp3.Response response) { 64 | try { 65 | T result = convertResponse(response); 66 | callback.onSuccess(result); 67 | } catch (IOException e) { 68 | callback.onFailure(e); 69 | } 70 | } 71 | }); 72 | } 73 | 74 | // Converts the response data from the OkHttp response 75 | private T convertResponse(okhttp3.Response httpResponse) throws IOException { 76 | ResponseBody body = httpResponse.body(); 77 | if (body != null) { 78 | ObjectMapper mapper = new ObjectMapper(); 79 | mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); 80 | mapper.registerModule(createDeserializerModule()); 81 | String content = body.string(); 82 | Response response = mapper.readValue(content, Response.class); 83 | if (converter == null) { 84 | throw new IllegalArgumentException("There is no converter for response:'" + content + "'"); 85 | } 86 | if (response.getError() != null) { 87 | throw response.getError(); 88 | } 89 | return converter.convertTo(response.getResult()); 90 | } else { 91 | throw new RpcError(httpResponse.code(), httpResponse.message()); 92 | } 93 | } 94 | 95 | private SimpleModule createDeserializerModule() { 96 | SimpleModule module = new SimpleModule(); 97 | module.addDeserializer(RpcItem.class, new RpcItemDeserializer()); 98 | return module; 99 | } 100 | } 101 | -------------------------------------------------------------------------------- /library/src/main/java/foundation/icon/icx/transport/jsonrpc/AnnotatedConverterFactory.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 ICON Foundation 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package foundation.icon.icx.transport.jsonrpc; 18 | 19 | import java.lang.reflect.Field; 20 | import java.lang.reflect.InvocationTargetException; 21 | import java.lang.reflect.Modifier; 22 | 23 | import static foundation.icon.icx.data.Converters.fromRpcItem; 24 | 25 | public class AnnotatedConverterFactory implements RpcConverter.RpcConverterFactory { 26 | 27 | @Override 28 | public RpcConverter create(Class type) { 29 | return new RpcConverter() { 30 | @Override 31 | public T convertTo(RpcItem object) { 32 | try { 33 | T result; 34 | try { 35 | result = getClassInstance(type); 36 | } catch (ClassNotFoundException | NoSuchMethodException | InvocationTargetException e) { 37 | throw new IllegalArgumentException(e); 38 | } 39 | 40 | RpcObject o = object.asObject(); 41 | Field[] fields = type.getDeclaredFields(); 42 | for (Field field : fields) { 43 | field.setAccessible(true); 44 | if (field.isAnnotationPresent(ConverterName.class)) { 45 | ConverterName n = field.getAnnotation(ConverterName.class); 46 | Object value = fromRpcItem(o.getItem(n.value()), field.getType()); 47 | if (value != null) field.set(result, value); 48 | } 49 | } 50 | return result; 51 | } catch (InstantiationException | IllegalAccessException e) { 52 | throw new IllegalArgumentException(e); 53 | } 54 | } 55 | 56 | @Override 57 | public RpcItem convertFrom(T object) { 58 | return RpcItemCreator.create(object); 59 | } 60 | }; 61 | 62 | } 63 | 64 | private T getClassInstance(Class type) throws IllegalAccessException, InstantiationException, ClassNotFoundException, NoSuchMethodException, InvocationTargetException { 65 | if (isInnerClass(type)) { 66 | String className = type.getCanonicalName().subSequence(0, type.getCanonicalName().length() - type.getSimpleName().length() - 1).toString(); 67 | Class m = Class.forName(className); 68 | return type.getConstructor(m).newInstance(m.newInstance()); 69 | } 70 | return type.newInstance(); 71 | } 72 | 73 | private boolean isInnerClass(Class clazz) { 74 | return clazz.isMemberClass() && !Modifier.isStatic(clazz.getModifiers()); 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /library/src/main/java/foundation/icon/icx/transport/jsonrpc/AnnotationConverter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 ICON Foundation 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package foundation.icon.icx.transport.jsonrpc; 18 | 19 | import java.lang.annotation.ElementType; 20 | import java.lang.annotation.Retention; 21 | import java.lang.annotation.RetentionPolicy; 22 | import java.lang.annotation.Target; 23 | 24 | @Retention(RetentionPolicy.RUNTIME) 25 | @Target(ElementType.TYPE) 26 | public @interface AnnotationConverter { 27 | boolean use() default true; 28 | } 29 | -------------------------------------------------------------------------------- /library/src/main/java/foundation/icon/icx/transport/jsonrpc/ConverterName.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 ICON Foundation 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package foundation.icon.icx.transport.jsonrpc; 18 | 19 | import java.lang.annotation.Documented; 20 | import java.lang.annotation.ElementType; 21 | import java.lang.annotation.Retention; 22 | import java.lang.annotation.Target; 23 | 24 | import static java.lang.annotation.RetentionPolicy.RUNTIME; 25 | 26 | @Documented 27 | @Target(ElementType.FIELD) 28 | @Retention(RUNTIME) 29 | public @interface ConverterName { 30 | /** 31 | * @return the desired name of the field when it is converted 32 | */ 33 | String value(); 34 | } 35 | -------------------------------------------------------------------------------- /library/src/main/java/foundation/icon/icx/transport/jsonrpc/Request.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 ICON Foundation 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package foundation.icon.icx.transport.jsonrpc; 18 | 19 | /** 20 | * A jsonrpc request to be execute 21 | */ 22 | public class Request { 23 | 24 | private String jsonrpc = "2.0"; 25 | 26 | private long id; 27 | 28 | private String method; 29 | 30 | private RpcObject params; 31 | 32 | public Request(long id, String method, RpcObject params) { 33 | this.id = id; 34 | this.method = method; 35 | this.params = params; 36 | } 37 | 38 | public String getJsonrpc() { 39 | return jsonrpc; 40 | } 41 | 42 | public long getId() { 43 | return id; 44 | } 45 | 46 | public String getMethod() { 47 | return method; 48 | } 49 | 50 | public RpcObject getParams() { 51 | return params; 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /library/src/main/java/foundation/icon/icx/transport/jsonrpc/Response.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 ICON Foundation 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package foundation.icon.icx.transport.jsonrpc; 18 | 19 | /** 20 | * A jsonrpc response of the request 21 | */ 22 | public class Response { 23 | private String jsonrpc = "2.0"; 24 | 25 | private long id; 26 | 27 | private RpcItem result; 28 | 29 | private RpcError error; 30 | 31 | public String getJsonrpc() { 32 | return jsonrpc; 33 | } 34 | 35 | public long getId() { 36 | return id; 37 | } 38 | 39 | public RpcItem getResult() { 40 | return result; 41 | } 42 | 43 | public RpcError getError() { 44 | return error; 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /library/src/main/java/foundation/icon/icx/transport/jsonrpc/RpcArray.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 ICON Foundation 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package foundation.icon.icx.transport.jsonrpc; 18 | 19 | import java.util.ArrayList; 20 | import java.util.Iterator; 21 | import java.util.List; 22 | 23 | /** 24 | * A read-only data class of RpcArray 25 | */ 26 | public class RpcArray implements RpcItem, Iterable { 27 | private final List items; 28 | 29 | private RpcArray(List items) { 30 | this.items = items; 31 | } 32 | 33 | public Iterator iterator() { 34 | return items.iterator(); 35 | } 36 | 37 | public RpcItem get(int index) { 38 | return items.get(index); 39 | } 40 | 41 | public int size() { 42 | return items.size(); 43 | } 44 | 45 | public List asList() { 46 | return new ArrayList<>(items); 47 | } 48 | 49 | @Override 50 | public String toString() { 51 | return "RpcArray(" + 52 | "items=" + items + 53 | ')'; 54 | } 55 | 56 | @Override 57 | public boolean isEmpty() { 58 | return items == null || items.isEmpty(); 59 | } 60 | 61 | @Override 62 | public boolean equals(Object o) { 63 | if (this == o) return true; 64 | if (!(o instanceof RpcArray)) return false; 65 | RpcArray obj = (RpcArray) o; 66 | return items.equals(obj.items); 67 | } 68 | /** 69 | * Builder for RpcArray 70 | */ 71 | public static class Builder { 72 | 73 | private final List items; 74 | 75 | public Builder() { 76 | items = new ArrayList<>(); 77 | } 78 | 79 | public Builder add(RpcItem item) { 80 | items.add(item); 81 | return this; 82 | } 83 | 84 | public RpcArray build() { 85 | return new RpcArray(items); 86 | } 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /library/src/main/java/foundation/icon/icx/transport/jsonrpc/RpcConverter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 ICON Foundation 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package foundation.icon.icx.transport.jsonrpc; 18 | 19 | public interface RpcConverter { 20 | 21 | T convertTo(RpcItem object); 22 | 23 | RpcItem convertFrom(T object); 24 | 25 | interface RpcConverterFactory { 26 | RpcConverter create(Class type); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /library/src/main/java/foundation/icon/icx/transport/jsonrpc/RpcError.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 ICON Foundation 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package foundation.icon.icx.transport.jsonrpc; 18 | 19 | import foundation.icon.icx.data.Bytes; 20 | 21 | import java.io.IOException; 22 | 23 | /** 24 | * RpcError defines the error that occurred during communicating through jsonrpc 25 | */ 26 | public class RpcError extends IOException { 27 | private long code; 28 | private String message; 29 | private Bytes data; 30 | 31 | public RpcError() { 32 | // jackson needs a default constructor 33 | } 34 | 35 | public RpcError(long code, String message) { 36 | super(message); 37 | this.code = code; 38 | this.message = message; 39 | } 40 | 41 | /** 42 | * Returns the code of rpc error 43 | * @return error code 44 | */ 45 | public long getCode() { 46 | return code; 47 | } 48 | 49 | /** 50 | * Returns the message of rpc error 51 | * @return error message 52 | */ 53 | @Override 54 | public String getMessage() { 55 | return message; 56 | } 57 | 58 | /** 59 | * Returns the data of rpc error 60 | * @return data 61 | */ 62 | public Bytes getData() { 63 | return data; 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /library/src/main/java/foundation/icon/icx/transport/jsonrpc/RpcItem.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 ICON Foundation 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package foundation.icon.icx.transport.jsonrpc; 18 | 19 | import foundation.icon.icx.data.Address; 20 | import foundation.icon.icx.data.Bytes; 21 | 22 | import java.math.BigInteger; 23 | 24 | public interface RpcItem { 25 | 26 | boolean isEmpty(); 27 | boolean equals(Object o); 28 | default boolean isNull() { 29 | return false; 30 | } 31 | 32 | default RpcObject asObject() { 33 | if (this instanceof RpcObject) return (RpcObject) this; 34 | throw new RpcValueException("This item can not be converted to RpcObject"); 35 | } 36 | 37 | default RpcArray asArray() { 38 | if (this instanceof RpcArray) return (RpcArray) this; 39 | throw new RpcValueException("This item can not be converted to RpcArray"); 40 | } 41 | 42 | default RpcValue asValue() { 43 | if (this instanceof RpcValue) return (RpcValue) this; 44 | throw new RpcValueException("This item can not be converted to RpcValue"); 45 | } 46 | 47 | default String asString() { 48 | return asValue().asString(); 49 | } 50 | 51 | default BigInteger asInteger() { 52 | return asValue().asInteger(); 53 | } 54 | 55 | default byte[] asByteArray() { 56 | return asValue().asByteArray(); 57 | } 58 | 59 | default Boolean asBoolean() { 60 | return asValue().asBoolean(); 61 | } 62 | 63 | default Address asAddress() { 64 | return asValue().asAddress(); 65 | } 66 | 67 | default Bytes asBytes() { 68 | return asValue().asBytes(); 69 | } 70 | 71 | class RpcValueException extends IllegalArgumentException { 72 | RpcValueException(String message) { 73 | super(message); 74 | } 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /library/src/main/java/foundation/icon/icx/transport/jsonrpc/RpcItemCreator.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 ICON Foundation 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package foundation.icon.icx.transport.jsonrpc; 18 | 19 | import foundation.icon.icx.data.Address; 20 | import foundation.icon.icx.data.Bytes; 21 | 22 | import java.lang.reflect.Array; 23 | import java.lang.reflect.Field; 24 | import java.math.BigInteger; 25 | 26 | public class RpcItemCreator { 27 | 28 | public static RpcItem create(T item) { 29 | return toRpcItem(item); 30 | } 31 | 32 | static RpcItem toRpcItem(T item) { 33 | return item != null ? toRpcItem(item.getClass(), item) : null; 34 | } 35 | 36 | static RpcItem toRpcItem(Class type, T item) { 37 | RpcValue rpcValue = toRpcValue(item); 38 | if (rpcValue != null) { 39 | return rpcValue; 40 | } 41 | 42 | if (type.isArray()) { 43 | return toRpcArray(item); 44 | } 45 | 46 | if (!type.isPrimitive()) { 47 | return toRpcObject(item); 48 | } 49 | 50 | return null; 51 | } 52 | 53 | static RpcObject toRpcObject(Object object) { 54 | RpcObject.Builder builder = new RpcObject.Builder(); 55 | addObjectFields(builder, object, object.getClass().getDeclaredFields()); 56 | addObjectFields(builder, object, object.getClass().getFields()); 57 | return builder.build(); 58 | } 59 | 60 | static String getKeyFromObjectField(Field field) { 61 | return field.getName(); 62 | } 63 | 64 | static void addObjectFields(RpcObject.Builder builder, Object parent, Field[] fields) { 65 | for (Field field : fields) { 66 | String key = getKeyFromObjectField(field); 67 | if (key.equals("this$0")) continue; 68 | 69 | Class type = field.getType(); 70 | Object fieldObject = null; 71 | try { 72 | field.setAccessible(true); 73 | fieldObject = field.get(parent); 74 | } catch (IllegalAccessException ignored) { 75 | } 76 | if (fieldObject != null || !type.isInstance(fieldObject)) { 77 | RpcItem rpcItem = toRpcItem(type, fieldObject); 78 | if (rpcItem != null && !rpcItem.isEmpty()) { 79 | builder.put(key, rpcItem); 80 | } 81 | } 82 | } 83 | } 84 | 85 | static RpcArray toRpcArray(Object obj) { 86 | Class componentType = obj.getClass().getComponentType(); 87 | if (componentType == boolean.class || !componentType.isPrimitive()) { 88 | RpcArray.Builder builder = new RpcArray.Builder(); 89 | 90 | int length = Array.getLength(obj); 91 | for (int i = 0; i < length; i++) { 92 | builder.add(toRpcItem(Array.get(obj, i))); 93 | } 94 | return builder.build(); 95 | } 96 | return null; 97 | } 98 | 99 | static RpcValue toRpcValue(Object object) { 100 | if (object.getClass().isAssignableFrom(Boolean.class)) { 101 | return new RpcValue((Boolean) object); 102 | } else if (object.getClass().isAssignableFrom(String.class)) { 103 | return new RpcValue((String) object); 104 | } else if (object.getClass().isAssignableFrom(BigInteger.class)) { 105 | return new RpcValue((BigInteger) object); 106 | } else if (object.getClass().isAssignableFrom(byte[].class)) { 107 | return new RpcValue((byte[]) object); 108 | } else if (object.getClass().isAssignableFrom(Bytes.class)) { 109 | return new RpcValue((Bytes) object); 110 | } else if (object.getClass().isAssignableFrom(Address.class)) { 111 | return new RpcValue((Address) object); 112 | } 113 | return null; 114 | } 115 | } 116 | -------------------------------------------------------------------------------- /library/src/main/java/foundation/icon/icx/transport/jsonrpc/RpcItemDeserializer.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 ICON Foundation 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package foundation.icon.icx.transport.jsonrpc; 18 | 19 | import com.fasterxml.jackson.core.JsonParser; 20 | import com.fasterxml.jackson.core.TreeNode; 21 | import com.fasterxml.jackson.databind.DeserializationContext; 22 | import com.fasterxml.jackson.databind.JsonDeserializer; 23 | import com.fasterxml.jackson.databind.JsonNode; 24 | 25 | import java.io.IOException; 26 | import java.math.BigInteger; 27 | import java.util.Iterator; 28 | 29 | /** 30 | * Deserializers for jsonrpc value 31 | */ 32 | public class RpcItemDeserializer extends JsonDeserializer { 33 | 34 | @Override 35 | public RpcItem deserialize( 36 | JsonParser parser, DeserializationContext context) 37 | throws IOException { 38 | TreeNode node = parser.readValueAsTree(); 39 | return deserialize(node); 40 | } 41 | 42 | private RpcItem deserialize(TreeNode node) { 43 | if (node.isObject()) { 44 | RpcObject.Builder builder = new RpcObject.Builder(); 45 | for (Iterator it = node.fieldNames(); it.hasNext(); ) { 46 | String fieldName = it.next(); 47 | TreeNode childNode = node.get(fieldName); 48 | builder.put(fieldName, deserialize(childNode)); 49 | } 50 | return builder.build(); 51 | } else if (node.isArray()) { 52 | RpcArray.Builder builder = new RpcArray.Builder(); 53 | for (int i = 0; i < node.size(); i++) { 54 | TreeNode childNode = node.get(i); 55 | builder.add(deserialize(childNode)); 56 | } 57 | return builder.build(); 58 | } else { 59 | JsonNode n = ((JsonNode) node); 60 | if (n.isLong()) { 61 | return new RpcValue(new BigInteger(String.valueOf(n.asLong()))); 62 | } else if (n.isInt()) { 63 | return new RpcValue(new BigInteger(String.valueOf(n.asInt()))); 64 | } else if (n.isBoolean()) { 65 | return new RpcValue(n.asBoolean()); 66 | } else if (n.isNull()) { 67 | return RpcValue.NULL; 68 | } 69 | return new RpcValue(n.asText()); 70 | } 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /library/src/main/java/foundation/icon/icx/transport/jsonrpc/RpcItemSerializer.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 ICON Foundation 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package foundation.icon.icx.transport.jsonrpc; 18 | 19 | import com.fasterxml.jackson.core.JsonGenerator; 20 | import com.fasterxml.jackson.databind.JsonSerializer; 21 | import com.fasterxml.jackson.databind.SerializerProvider; 22 | 23 | import java.io.IOException; 24 | 25 | /** 26 | * Serializers for jsonrpc value 27 | */ 28 | public class RpcItemSerializer extends JsonSerializer { 29 | 30 | @Override 31 | public void serialize( 32 | RpcItem item, JsonGenerator gen, SerializerProvider serializers) 33 | throws IOException { 34 | serialize(item, gen); 35 | } 36 | 37 | private void serialize(RpcItem item, JsonGenerator gen) 38 | throws IOException { 39 | 40 | if (item instanceof RpcObject) { 41 | RpcObject object = item.asObject(); 42 | gen.writeStartObject(); 43 | for (String key : object.keySet()) { 44 | RpcItem value = object.getItem(key); 45 | if (value != null) { 46 | gen.writeFieldName(key); 47 | serialize(value, gen); 48 | } 49 | } 50 | gen.writeEndObject(); 51 | } else if (item instanceof RpcArray) { 52 | RpcArray array = item.asArray(); 53 | gen.writeStartArray(); 54 | for (RpcItem childItem : array) { 55 | serialize(childItem, gen); 56 | } 57 | gen.writeEndArray(); 58 | } else if (item == null || item.isNull()) { 59 | gen.writeNull(); 60 | } else { 61 | gen.writeString(item.asString()); 62 | } 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /library/src/main/java/foundation/icon/icx/transport/jsonrpc/RpcObject.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 ICON Foundation 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package foundation.icon.icx.transport.jsonrpc; 18 | 19 | import java.util.HashMap; 20 | import java.util.LinkedHashMap; 21 | import java.util.Map; 22 | import java.util.Set; 23 | import java.util.TreeMap; 24 | 25 | /** 26 | * A read-only data class of RpcObject 27 | */ 28 | public class RpcObject implements RpcItem { 29 | private final Map items; 30 | 31 | private RpcObject(Map items) { 32 | this.items = items; 33 | } 34 | 35 | public Set keySet() { 36 | return items.keySet(); 37 | } 38 | 39 | public RpcItem getItem(String key) { 40 | return items.get(key); 41 | } 42 | 43 | @Override 44 | public String toString() { 45 | return "RpcObject(" + 46 | "items=" + items + 47 | ')'; 48 | } 49 | 50 | @Override 51 | public boolean isEmpty() { 52 | return items == null || items.isEmpty(); 53 | } 54 | 55 | @Override 56 | public boolean equals(Object o) { 57 | if (this == o) return true; 58 | if (!(o instanceof RpcObject)) return false; 59 | RpcObject obj = (RpcObject) o; 60 | return items.equals(obj.items); 61 | } 62 | 63 | /** 64 | * Builder for RpcObject 65 | */ 66 | public static class Builder { 67 | 68 | /** 69 | * Sort policy of the properties 70 | */ 71 | public enum Sort { 72 | NONE, 73 | KEY, 74 | INSERT 75 | } 76 | 77 | private final Map items; 78 | 79 | public Builder() { 80 | this(Sort.NONE); 81 | } 82 | 83 | public Builder(Sort sort) { 84 | switch (sort) { 85 | case KEY: 86 | items = new TreeMap<>(); 87 | break; 88 | case INSERT: 89 | items = new LinkedHashMap<>(); 90 | break; 91 | default: 92 | items = new HashMap<>(); 93 | break; 94 | } 95 | } 96 | 97 | public Builder put(String key, RpcItem item) { 98 | if (item != null) { 99 | items.put(key, item); 100 | } 101 | return this; 102 | } 103 | 104 | public RpcObject build() { 105 | return new RpcObject(items); 106 | } 107 | 108 | public boolean isNullOrEmpty(RpcItem item) { 109 | return item == null || item.isEmpty(); 110 | } 111 | } 112 | } 113 | -------------------------------------------------------------------------------- /library/src/main/java/foundation/icon/icx/transport/monitor/BTPMonitorSpec.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 ICON Foundation 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package foundation.icon.icx.transport.monitor; 18 | 19 | import foundation.icon.icx.data.BTPNotification; 20 | import foundation.icon.icx.transport.jsonrpc.RpcObject; 21 | import foundation.icon.icx.transport.jsonrpc.RpcValue; 22 | 23 | import java.math.BigInteger; 24 | 25 | public class BTPMonitorSpec extends MonitorSpec { 26 | private final BigInteger height; 27 | private final BigInteger networkId; 28 | private final boolean proofFlag; 29 | private final long progressInterval; 30 | 31 | public BTPMonitorSpec(BigInteger height, BigInteger networkId, boolean proofFlag) { 32 | this(height, networkId, proofFlag, 0); 33 | } 34 | 35 | public BTPMonitorSpec(BigInteger height, BigInteger networkId, boolean proofFlag, long progressInterval) { 36 | this.path = "btp"; 37 | this.height = height; 38 | this.networkId = networkId; 39 | this.proofFlag = proofFlag; 40 | this.progressInterval = progressInterval; 41 | } 42 | 43 | @Override 44 | public RpcObject getParams() { 45 | RpcObject.Builder builder = new RpcObject.Builder() 46 | .put("height", new RpcValue(this.height)) 47 | .put("networkID", new RpcValue(this.networkId)) 48 | .put("proofFlag", new RpcValue(this.proofFlag)); 49 | if (this.progressInterval > 0) { 50 | builder.put("progressInterval", new RpcValue(BigInteger.valueOf(this.progressInterval))); 51 | } 52 | return builder.build(); 53 | } 54 | 55 | @Override 56 | public Class getNotificationClass() { 57 | return BTPNotification.class; 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /library/src/main/java/foundation/icon/icx/transport/monitor/BlockMonitorSpec.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019 ICON Foundation 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package foundation.icon.icx.transport.monitor; 18 | 19 | import foundation.icon.icx.data.BlockNotification; 20 | import foundation.icon.icx.transport.jsonrpc.RpcArray; 21 | import foundation.icon.icx.transport.jsonrpc.RpcObject; 22 | import foundation.icon.icx.transport.jsonrpc.RpcValue; 23 | 24 | import java.math.BigInteger; 25 | 26 | public class BlockMonitorSpec extends MonitorSpec { 27 | private final BigInteger height; 28 | private final EventMonitorSpec.EventFilter[] eventFilters; 29 | 30 | public BlockMonitorSpec(BigInteger height, EventMonitorSpec.EventFilter[] eventFilters) { 31 | this.height = height; 32 | this.path = "block"; 33 | this.eventFilters = eventFilters; 34 | } 35 | 36 | @Override 37 | public RpcObject getParams() { 38 | RpcObject.Builder builder = new RpcObject.Builder() 39 | .put("height", new RpcValue(this.height)); 40 | if (this.eventFilters != null) { 41 | RpcArray.Builder arrBuilder = new RpcArray.Builder(); 42 | for (EventMonitorSpec.EventFilter ef : this.eventFilters) { 43 | RpcObject.Builder efBuilder = new RpcObject.Builder(); 44 | ef.apply(efBuilder); 45 | arrBuilder.add(efBuilder.build()); 46 | } 47 | builder.put("eventFilters", arrBuilder.build()); 48 | } 49 | return builder.build(); 50 | } 51 | 52 | @Override 53 | public Class getNotificationClass() { 54 | return BlockNotification.class; 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /library/src/main/java/foundation/icon/icx/transport/monitor/EventMonitorSpec.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019 ICON Foundation 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package foundation.icon.icx.transport.monitor; 18 | 19 | import foundation.icon.icx.data.Address; 20 | import foundation.icon.icx.data.EventNotification; 21 | import foundation.icon.icx.transport.jsonrpc.RpcArray; 22 | import foundation.icon.icx.transport.jsonrpc.RpcObject; 23 | import foundation.icon.icx.transport.jsonrpc.RpcValue; 24 | 25 | import java.math.BigInteger; 26 | 27 | public class EventMonitorSpec extends MonitorSpec { 28 | private final BigInteger height; 29 | private final EventFilter[] filters; 30 | private final boolean logs; 31 | private final long progressInterval; 32 | 33 | public static class EventFilter { 34 | private final String event; 35 | private final Address addr; 36 | private String[] indexed; 37 | private String[] data; 38 | 39 | public EventFilter(String event, Address addr, String[] indexed, String[] data) { 40 | this.event = event; 41 | this.addr = addr; 42 | if(indexed != null && indexed.length > 0) { 43 | this.indexed = new String[indexed.length]; 44 | System.arraycopy(indexed, 0, this.indexed, 0, indexed.length); 45 | } 46 | if(data != null && data.length > 0) { 47 | this.data = new String[data.length]; 48 | System.arraycopy(data, 0, this.data, 0, data.length); 49 | } 50 | } 51 | 52 | public void apply(RpcObject.Builder builder) { 53 | builder.put("event", new RpcValue(event)); 54 | if (this.addr != null) { 55 | builder.put("addr", new RpcValue(addr)); 56 | } 57 | if (this.data != null) { 58 | RpcArray.Builder arrayBuilder = new RpcArray.Builder(); 59 | for(String d : this.data) { 60 | arrayBuilder.add(new RpcValue(d)); 61 | } 62 | builder.put("data", arrayBuilder.build()); 63 | } 64 | if (this.indexed != null) { 65 | RpcArray.Builder arrayBuilder = new RpcArray.Builder(); 66 | for(String d : this.indexed) { 67 | arrayBuilder.add(new RpcValue(d)); 68 | } 69 | builder.put("indexed", arrayBuilder.build()); 70 | } 71 | } 72 | } 73 | 74 | public EventMonitorSpec(BigInteger height, String event, Address addr, String[] indexed, String[] data) { 75 | this(height, event, addr, indexed, data, false); 76 | } 77 | 78 | public EventMonitorSpec(BigInteger height, String event, Address addr, String[] indexed, String[] data, boolean logs) { 79 | this(height, event, addr, indexed, data, logs, 0); 80 | } 81 | 82 | public EventMonitorSpec(BigInteger height, String event, Address addr, String[] indexed, String[] data, boolean logs, long progressInterval) { 83 | this(height, new EventFilter[]{new EventFilter(event, addr, indexed, data)}, logs, progressInterval); 84 | } 85 | 86 | public EventMonitorSpec(BigInteger height, EventFilter[] filters, boolean logs, long progressInterval) { 87 | this.path = "event"; 88 | this.height = height; 89 | this.filters = filters; 90 | this.logs = logs; 91 | this.progressInterval = progressInterval; 92 | } 93 | 94 | @Override 95 | public RpcObject getParams() { 96 | RpcObject.Builder builder = new RpcObject.Builder() 97 | .put("height", new RpcValue(height)); 98 | if (this.logs) { 99 | builder = builder.put("logs", new RpcValue(true)); 100 | } 101 | if (filters.length==1) { 102 | this.filters[0].apply(builder); 103 | } else { 104 | RpcArray.Builder arrBuilder = new RpcArray.Builder(); 105 | for (EventFilter ef : this.filters) { 106 | RpcObject.Builder efBuilder = new RpcObject.Builder(); 107 | ef.apply(efBuilder); 108 | arrBuilder.add(efBuilder.build()); 109 | } 110 | builder = builder.put("eventFilters", arrBuilder.build()); 111 | } 112 | if (this.progressInterval>0) { 113 | builder = builder.put("progressInterval", new RpcValue(BigInteger.valueOf(this.progressInterval))); 114 | } 115 | return builder.build(); 116 | } 117 | 118 | @Override 119 | public Class getNotificationClass() { 120 | return EventNotification.class; 121 | } 122 | } 123 | -------------------------------------------------------------------------------- /library/src/main/java/foundation/icon/icx/transport/monitor/Monitor.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019 ICON Foundation 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package foundation.icon.icx.transport.monitor; 18 | 19 | import java.math.BigInteger; 20 | 21 | public interface Monitor { 22 | interface Listener { 23 | void onStart(); 24 | void onEvent(T msg); 25 | void onError(long code); 26 | default void onProgress(BigInteger height) { } 27 | void onClose(); 28 | } 29 | 30 | boolean start(Listener listener); 31 | 32 | void stop(); 33 | } 34 | -------------------------------------------------------------------------------- /library/src/main/java/foundation/icon/icx/transport/monitor/MonitorSpec.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019 ICON Foundation 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package foundation.icon.icx.transport.monitor; 18 | 19 | import foundation.icon.icx.transport.jsonrpc.RpcObject; 20 | 21 | public abstract class MonitorSpec { 22 | protected String path; 23 | 24 | public abstract RpcObject getParams(); 25 | 26 | public String getPath() {return path;} 27 | public abstract Class getNotificationClass(); 28 | } 29 | -------------------------------------------------------------------------------- /library/src/test/java/foundation/icon/icx/CallTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 ICON Foundation 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | * 16 | */ 17 | 18 | package foundation.icon.icx; 19 | 20 | import foundation.icon.icx.data.Address; 21 | import foundation.icon.icx.transport.jsonrpc.RpcObject; 22 | import org.junit.jupiter.api.Assertions; 23 | import org.junit.jupiter.api.Test; 24 | 25 | import java.math.BigInteger; 26 | 27 | class CallTest { 28 | @Test 29 | void testCallBuilder() { 30 | Address from = new Address("hx0000000000000000000000000000000000000000"); 31 | Address to = new Address("cx1111111111111111111111111111111111111111"); 32 | String method = "myMethod"; 33 | BigInteger height = BigInteger.ONE; 34 | Person person = new Person(); 35 | person.name = "gold bug"; 36 | person.age = new BigInteger("20"); 37 | 38 | Call call = new Call.Builder() 39 | .from(from) 40 | .to(to) 41 | .height(height) 42 | .method(method) 43 | .params(person) 44 | .buildWith(PersonResponse.class); 45 | 46 | RpcObject properties = call.getProperties(); 47 | RpcObject data = properties.getItem("data").asObject(); 48 | RpcObject dataParams = data.getItem("params").asObject(); 49 | 50 | Assertions.assertEquals(from, properties.getItem("from").asAddress()); 51 | Assertions.assertEquals(to, properties.getItem("to").asAddress()); 52 | Assertions.assertEquals(height, properties.getItem("height").asInteger()); 53 | Assertions.assertEquals(method, data.getItem("method").asString()); 54 | Assertions.assertEquals(person.name, dataParams.getItem("name").asString()); 55 | Assertions.assertEquals(person.age, dataParams.getItem("age").asInteger()); 56 | Assertions.assertEquals(PersonResponse.class, call.responseType()); 57 | } 58 | 59 | 60 | @SuppressWarnings("WeakerAccess") 61 | static class Person { 62 | public String name; 63 | public BigInteger age; 64 | } 65 | 66 | @SuppressWarnings("unused") 67 | static class PersonResponse { 68 | public boolean isOk; 69 | public String message; 70 | } 71 | 72 | 73 | } 74 | -------------------------------------------------------------------------------- /library/src/test/java/foundation/icon/icx/Constants.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019 ICON Foundation 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package foundation.icon.icx; 18 | 19 | import foundation.icon.icx.data.Address; 20 | 21 | import java.math.BigInteger; 22 | 23 | public class Constants { 24 | public static final Address ZERO_ADDRESS = new Address("cx0000000000000000000000000000000000000000"); 25 | public static final BigInteger DEFAULT_STEP = BigInteger.valueOf(100000); 26 | 27 | public static final String SERVER_URL = "http://localhost:9082"; 28 | public static final String GOD_WALLET_PASSWORD = "gochain"; 29 | public static final String GOD_WALLET_FILENAME = "godWallet.json"; 30 | } 31 | -------------------------------------------------------------------------------- /library/src/test/java/foundation/icon/icx/IconServiceIntegTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2022 ICON Foundation 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package foundation.icon.icx; 18 | 19 | import foundation.icon.icx.data.Bytes; 20 | import foundation.icon.icx.data.IconAmount; 21 | import foundation.icon.icx.data.NetworkId; 22 | import foundation.icon.icx.data.TransactionResult; 23 | import foundation.icon.icx.transport.http.HttpProvider; 24 | import org.junit.jupiter.api.BeforeEach; 25 | import org.junit.jupiter.api.Tag; 26 | import org.junit.jupiter.api.Test; 27 | 28 | import java.io.File; 29 | import java.io.IOException; 30 | import java.math.BigInteger; 31 | 32 | import static org.junit.jupiter.api.Assertions.assertEquals; 33 | 34 | @Tag("integration") 35 | public class IconServiceIntegTest { 36 | private IconService iconService; 37 | private KeyWallet owner; 38 | private TransactionHandler txHandler; 39 | 40 | @BeforeEach 41 | void init() throws Exception { 42 | iconService = new IconService(new HttpProvider(Constants.SERVER_URL, 3)); 43 | txHandler = new TransactionHandler(iconService); 44 | owner = KeyWallet.load(Constants.GOD_WALLET_PASSWORD, 45 | new File(getClass().getClassLoader().getResource(Constants.GOD_WALLET_FILENAME).getFile())); 46 | } 47 | 48 | @Test 49 | void testGetTotalSupply() throws IOException { 50 | BigInteger beforeTs = iconService.getTotalSupply().execute(); 51 | BigInteger burnAmount = IconAmount.of("100", IconAmount.Unit.ICX).toLoop(); 52 | TransactionResult result = burnICX(burnAmount); 53 | BigInteger afterTs = iconService.getTotalSupply().execute(); 54 | BigInteger delta = beforeTs.subtract(afterTs); 55 | assertEquals(burnAmount, delta); 56 | 57 | BigInteger height = result.getBlockHeight(); 58 | BigInteger heightTs = iconService.getTotalSupply(height).execute(); 59 | assertEquals(beforeTs, heightTs); 60 | BigInteger heightTs1 = iconService.getTotalSupply(height.add(BigInteger.ONE)).execute(); 61 | assertEquals(afterTs, heightTs1); 62 | } 63 | 64 | @Test 65 | void testGetBalance() throws IOException { 66 | BigInteger beforeBal = iconService.getBalance(owner.getAddress()).execute(); 67 | BigInteger burnAmount = IconAmount.of("200", IconAmount.Unit.ICX).toLoop(); 68 | TransactionResult result = burnICX(burnAmount); 69 | BigInteger afterBal = iconService.getBalance(owner.getAddress()).execute(); 70 | BigInteger delta = beforeBal.subtract(afterBal); 71 | BigInteger fee = result.getStepPrice().multiply(result.getStepUsed()); 72 | assertEquals(burnAmount.add(fee), delta); 73 | 74 | BigInteger height = result.getBlockHeight(); 75 | BigInteger heightBal = iconService.getBalance(owner.getAddress(), height).execute(); 76 | assertEquals(beforeBal, heightBal); 77 | BigInteger heightBal1 = iconService.getBalance(owner.getAddress(), height.add(BigInteger.ONE)).execute(); 78 | assertEquals(afterBal, heightBal1); 79 | } 80 | 81 | private TransactionResult burnICX(BigInteger burnAmount) throws IOException { 82 | Transaction transaction = TransactionBuilder.newBuilder() 83 | .nid(NetworkId.LOCAL) 84 | .from(owner.getAddress()) 85 | .to(Constants.ZERO_ADDRESS) 86 | .value(burnAmount) 87 | .stepLimit(Constants.DEFAULT_STEP.multiply(BigInteger.TEN)) 88 | .call("burn") 89 | .build(); 90 | SignedTransaction signedTransaction = new SignedTransaction(transaction, owner); 91 | Bytes txHash = iconService.sendTransaction(signedTransaction).execute(); 92 | TransactionResult result = txHandler.getTransactionResult(txHash); 93 | assertEquals(BigInteger.ONE, result.getStatus()); 94 | return result; 95 | } 96 | } 97 | -------------------------------------------------------------------------------- /library/src/test/java/foundation/icon/icx/SampleKeys.java: -------------------------------------------------------------------------------- 1 | package foundation.icon.icx; 2 | 3 | public class SampleKeys { 4 | 5 | public static final String PRIVATE_KEY_STRING = 6 | "2d42994b2f7735bbc93a3e64381864d06747e574aa94655c516f9ad0a74eed79"; 7 | 8 | public static final String ADDRESS = "hx4873b94352c8c1f3b2f09aaeccea31ce9e90bd31"; 9 | public static final String PASSWORD = "Pa55w0rd"; 10 | } 11 | -------------------------------------------------------------------------------- /library/src/test/java/foundation/icon/icx/TransactionHandler.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019 ICON Foundation 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package foundation.icon.icx; 18 | 19 | import foundation.icon.icx.data.Bytes; 20 | import foundation.icon.icx.data.TransactionResult; 21 | import foundation.icon.icx.transport.jsonrpc.RpcError; 22 | import foundation.icon.icx.transport.jsonrpc.RpcObject; 23 | 24 | import java.io.DataInputStream; 25 | import java.io.File; 26 | import java.io.FileInputStream; 27 | import java.io.IOException; 28 | import java.math.BigInteger; 29 | 30 | class TransactionHandler { 31 | private final IconService iconService; 32 | 33 | TransactionHandler(IconService iconService) { 34 | this.iconService = iconService; 35 | } 36 | 37 | Bytes install(KeyWallet wallet, String filename, RpcObject params) throws IOException { 38 | byte[] content = readFile(filename); 39 | Transaction transaction = TransactionBuilder.newBuilder() 40 | .nid(BigInteger.valueOf(3)) 41 | .from(wallet.getAddress()) 42 | .to(Constants.ZERO_ADDRESS) 43 | .deploy("application/zip", content) 44 | .params(params) 45 | .build(); 46 | 47 | // get an estimated step value and add some margin 48 | BigInteger estimatedStep = iconService.estimateStep(transaction).execute(); 49 | BigInteger margin = Constants.DEFAULT_STEP; 50 | 51 | // make a signed transaction with the same raw transaction and the estimated step 52 | SignedTransaction signedTransaction = new SignedTransaction(transaction, wallet, estimatedStep.add(margin)); 53 | return iconService.sendTransaction(signedTransaction).execute(); 54 | } 55 | 56 | TransactionResult getTransactionResult(Bytes txHash) throws IOException { 57 | TransactionResult result = null; 58 | while (result == null) { 59 | try { 60 | result = iconService.getTransactionResult(txHash).execute(); 61 | } catch (RpcError e) { 62 | System.out.println("RpcError: code: " + e.getCode() + ", message: " + e.getMessage()); 63 | try { 64 | // wait until block confirmation 65 | System.out.println("Sleep 1.5 seconds."); 66 | Thread.sleep(1500); 67 | } catch (InterruptedException ie) { 68 | ie.printStackTrace(); 69 | } 70 | } 71 | } 72 | return result; 73 | } 74 | 75 | private byte[] readFile(String filename) throws IOException { 76 | File file = new File(getClass().getClassLoader().getResource(filename).getFile()); 77 | long length = file.length(); 78 | if (length > Integer.MAX_VALUE) throw new OutOfMemoryError("File is too big!!"); 79 | byte[] result = new byte[(int) length]; 80 | try (DataInputStream inputStream = new DataInputStream(new FileInputStream(file))) { 81 | inputStream.readFully(result); 82 | } 83 | return result; 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /library/src/test/java/foundation/icon/icx/data/AddressTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 ICON Foundation 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | * 16 | */ 17 | 18 | package foundation.icon.icx.data; 19 | 20 | import foundation.icon.icx.crypto.IconKeys; 21 | import org.bouncycastle.util.encoders.Hex; 22 | import org.junit.jupiter.api.Assertions; 23 | import org.junit.jupiter.api.Test; 24 | 25 | import java.math.BigInteger; 26 | 27 | import static foundation.icon.icx.data.Address.AddressPrefix.CONTRACT; 28 | import static foundation.icon.icx.data.Address.AddressPrefix.EOA; 29 | import static org.junit.jupiter.api.Assertions.*; 30 | 31 | @SuppressWarnings("ALL") 32 | public class AddressTest { 33 | private String eoa = "hx4873b94352c8c1f3b2f09aaeccea31ce9e90bd31"; 34 | private String contract = "cx1ca4697e8229e29adce3cded4412a137be6d7edb"; 35 | 36 | @Test 37 | void testEoaAddress() { 38 | Address address = new Address(eoa); 39 | assertEquals(eoa, address.toString()); 40 | assertEquals(EOA, address.getPrefix()); 41 | assertTrue(IconKeys.isValidAddress(address)); 42 | assertFalse(IconKeys.isContractAddress(address)); 43 | } 44 | 45 | @Test 46 | void testContractCreate() { 47 | Address address = new Address(contract); 48 | assertEquals(contract, address.toString()); 49 | assertEquals(CONTRACT, address.getPrefix()); 50 | assertTrue(IconKeys.isValidAddress(address)); 51 | assertTrue(IconKeys.isContractAddress(address)); 52 | } 53 | 54 | @Test 55 | void testInvalidCreate() { 56 | String noPrefix = "4873b94352c8c1f3b2f09aaeccea31ce9e90bd31"; 57 | assertThrows(IllegalArgumentException.class, () -> { 58 | new Address(noPrefix); 59 | }); 60 | 61 | String missCharacter = "4873b94352c8c1f3b2f09aaeccea31ce9e90bd3"; 62 | assertThrows(IllegalArgumentException.class, () -> { 63 | new Address(missCharacter); 64 | }); 65 | 66 | String notHex = "4873b94352c8c1f3b2f09aaeccea31ce9e90bd3g"; 67 | assertThrows(IllegalArgumentException.class, () -> { 68 | new Address(notHex); 69 | }); 70 | 71 | String words = "helloworldhelloworldhelloworldhelloworld"; 72 | assertThrows(IllegalArgumentException.class, () -> { 73 | new Address(words); 74 | }); 75 | 76 | String upperAddress = "hx" + noPrefix.toUpperCase(); 77 | assertThrows(IllegalArgumentException.class, () -> { 78 | new Address(upperAddress); 79 | }); 80 | } 81 | 82 | @Test 83 | void testLoadPublicKey() { 84 | String pub = "04ffbb75929194621714be8998ea5c4f81d875188670b43a5ec0cef3a579fdf2280b882fddfcd6d2df8006978e35b37af5ca923e244672b07f98b95c21b4b9f03f"; 85 | Address expected = new Address("hx18cc6371aeb01eecff91e68c01584e982755ca5d"); 86 | 87 | Bytes publicKey = new Bytes(pub); 88 | Address address = IconKeys.getAddress(publicKey); 89 | Assertions.assertEquals(expected, address); 90 | 91 | publicKey = new Bytes(Hex.decode(pub)); 92 | address = IconKeys.getAddress(publicKey); 93 | Assertions.assertEquals(expected, address); 94 | 95 | BigInteger bigPub = new BigInteger(pub, 16); 96 | byte[] hash = IconKeys.getAddressHash(bigPub); 97 | Assertions.assertEquals(expected, new Address(EOA, hash)); 98 | 99 | BigInteger b = new BigInteger(1, Hex.decode(pub)); 100 | Assertions.assertEquals(expected, new Address(EOA, IconKeys.getAddressHash(b))); 101 | 102 | } 103 | } 104 | -------------------------------------------------------------------------------- /library/src/test/java/foundation/icon/icx/data/BytesTest.java: -------------------------------------------------------------------------------- 1 | package foundation.icon.icx.data; 2 | 3 | import org.bouncycastle.util.encoders.DecoderException; 4 | import org.bouncycastle.util.encoders.Hex; 5 | import org.junit.jupiter.api.Assertions; 6 | import org.junit.jupiter.api.Test; 7 | 8 | import java.math.BigInteger; 9 | import java.nio.charset.StandardCharsets; 10 | import java.security.SecureRandom; 11 | 12 | 13 | class BytesTest { 14 | 15 | @Test 16 | void testCreate() { 17 | 18 | byte[] byteArray = new byte[]{ 19 | (byte) 10, (byte) 16, (byte) 8 20 | }; 21 | String hexValue = Hex.toHexString(byteArray); 22 | BigInteger bigIntegerValue = new BigInteger(byteArray); 23 | 24 | Assertions.assertArrayEquals(byteArray, new Bytes(byteArray).toByteArray()); 25 | Assertions.assertArrayEquals(Hex.decode(hexValue), new Bytes(hexValue).toByteArray()); 26 | Assertions.assertArrayEquals(bigIntegerValue.toByteArray(), new Bytes(bigIntegerValue).toByteArray()); 27 | 28 | String tx = "2600770376fbf291d3d445054d45ed15280dd33c2038931aace3f7ea2ab59dbc"; 29 | Assertions.assertArrayEquals(Hex.decode(tx), new Bytes(tx).toByteArray()); 30 | 31 | byte[] secret = new SecureRandom().generateSeed(32); 32 | Assertions.assertArrayEquals(secret, new Bytes(secret).toByteArray()); 33 | 34 | String stringValue = "string value"; 35 | byte[] b = stringValue.getBytes(StandardCharsets.UTF_8); 36 | Assertions.assertArrayEquals(b, new Bytes(b).toByteArray()); 37 | 38 | } 39 | 40 | @Test 41 | void testBigInteger() { 42 | String hexValue = "ff80"; 43 | 44 | // The first byte is sign bytes 45 | // positive value : { 0x00, 0xff, 0x80 } 46 | BigInteger positive = new BigInteger(hexValue, 16); 47 | // negative value : { 0x80 } 48 | BigInteger negative = new BigInteger(Hex.decode("ff0101")); 49 | 50 | Assertions.assertArrayEquals(positive.toByteArray(), new Bytes(positive).toByteArray()); 51 | Assertions.assertArrayEquals(negative.toByteArray(), new Bytes(negative).toByteArray()); 52 | 53 | } 54 | 55 | @Test 56 | void testThrow() { 57 | String stringValue = "string value"; 58 | Assertions.assertThrows(IllegalArgumentException.class, () -> new Bytes(stringValue)); 59 | 60 | byte[] b = stringValue.getBytes(StandardCharsets.UTF_8); 61 | Assertions.assertThrows(IllegalArgumentException.class, () -> Bytes.toBytesPadded(b, b.length - 1)); 62 | 63 | String oddHex = "4d2"; 64 | Assertions.assertThrows(DecoderException.class, () -> new Bytes(oddHex)); 65 | } 66 | 67 | @Test 68 | void testEquals() { 69 | // same byte array 70 | String hex = "7979"; 71 | byte[] byteArray = new byte[]{0x79, 0x79}; 72 | BigInteger big = new BigInteger("31097"); 73 | 74 | Bytes b1 = new Bytes(hex); 75 | Bytes b2 = new Bytes(byteArray); 76 | Bytes b3 = new Bytes(big); 77 | 78 | // reflexive 79 | compareFuncs(b1, b1, true); 80 | compareFuncs(b2, b2, true); 81 | compareFuncs(b3, b3, true); 82 | 83 | // symmetric 84 | compareFuncs(b1, b2, true); 85 | compareFuncs(b2, b1, true); 86 | 87 | // transitive 88 | compareFuncs(b1, b2, true); 89 | compareFuncs(b2, b3, true); 90 | compareFuncs(b3, b1, true); 91 | 92 | // nonullity 93 | compareFuncs(b1, null, false); 94 | compareFuncs(b2, null, false); 95 | compareFuncs(b3, null, false); 96 | compareFuncs(b3, null, false); 97 | 98 | // different 99 | String diff = "ffff"; 100 | Bytes b4 = new Bytes(diff); 101 | compareFuncs(b3, b4, false); 102 | } 103 | 104 | private void compareFuncs(Bytes b1, Bytes b2, boolean expectEquals) { 105 | Assertions.assertEquals(expectEquals, b1.equals(b2)); 106 | } 107 | 108 | } 109 | -------------------------------------------------------------------------------- /library/src/test/java/foundation/icon/icx/data/IconAmountTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 ICON Foundation. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package foundation.icon.icx.data; 18 | 19 | import org.junit.jupiter.api.Test; 20 | 21 | import java.math.BigDecimal; 22 | import java.math.BigInteger; 23 | 24 | import static org.junit.jupiter.api.Assertions.assertEquals; 25 | 26 | 27 | public class IconAmountTest { 28 | 29 | 30 | @Test 31 | void testCreate() { 32 | BigInteger loop = new BigInteger("1000000000000000000"); 33 | 34 | IconAmount amount = IconAmount.of("1", IconAmount.Unit.ICX); 35 | assertEquals(new BigInteger("1"), amount.asInteger()); 36 | assertEquals(IconAmount.Unit.ICX.getValue(), amount.getDigit()); 37 | 38 | amount = IconAmount.of("1000000000000000000", IconAmount.Unit.LOOP); 39 | assertEquals("1000000000000000000", amount.toString()); 40 | assertEquals(IconAmount.Unit.LOOP.getValue(), amount.getDigit()); 41 | 42 | amount = IconAmount.of(new BigInteger("1000000000000000000"), 16); 43 | assertEquals(new BigInteger("1000000000000000000"), amount.asInteger()); 44 | assertEquals(16, amount.getDigit()); 45 | 46 | amount = IconAmount.of(new BigDecimal("0.1"), IconAmount.Unit.ICX); 47 | assertEquals(new BigDecimal("0.1"), amount.asDecimal()); 48 | assertEquals(IconAmount.Unit.ICX.getValue(), amount.getDigit()); 49 | 50 | amount = IconAmount.of(new BigDecimal("0.1"), 16); 51 | assertEquals(new BigDecimal("0.1"), amount.asDecimal()); 52 | assertEquals(16, amount.getDigit()); 53 | } 54 | 55 | @Test 56 | void testToLoop() { 57 | BigInteger loop = new BigInteger("1000000000000000000"); 58 | 59 | IconAmount amount = IconAmount.of("1", IconAmount.Unit.ICX); 60 | assertEquals(loop, amount.toLoop()); 61 | 62 | amount = IconAmount.of("1000000000000000000", IconAmount.Unit.LOOP); 63 | assertEquals(loop, amount.toLoop()); 64 | 65 | amount = IconAmount.of(new BigInteger("1"), IconAmount.Unit.ICX); 66 | assertEquals(loop, amount.toLoop()); 67 | 68 | amount = IconAmount.of(new BigInteger("1000"), IconAmount.Unit.ICX); 69 | assertEquals(new BigInteger("1000000000000000000000"), amount.toLoop()); 70 | 71 | amount = IconAmount.of("0.1", IconAmount.Unit.ICX); 72 | assertEquals(new BigInteger("100000000000000000"), amount.toLoop()); 73 | 74 | amount = IconAmount.of(new BigDecimal("0.1"), IconAmount.Unit.ICX); 75 | assertEquals(new BigInteger("100000000000000000"), amount.toLoop()); 76 | } 77 | 78 | @Test 79 | void testConvertUnit() { 80 | 81 | BigDecimal loop = new BigDecimal("1000000000000000000"); 82 | 83 | IconAmount amount = IconAmount.of("1", IconAmount.Unit.ICX); 84 | assertEquals(new BigInteger("10"), amount.convertUnit(17).asInteger()); 85 | 86 | amount = IconAmount.of("1", IconAmount.Unit.ICX); 87 | assertEquals(new BigInteger("100"), amount.convertUnit(16).asInteger()); 88 | 89 | amount = IconAmount.of(new BigDecimal("1"), IconAmount.Unit.ICX); 90 | assertEquals(new BigDecimal("0.1"), amount.convertUnit(19).asDecimal()); 91 | 92 | amount = IconAmount.of(new BigDecimal("1"), IconAmount.Unit.ICX); 93 | assertEquals(new BigInteger("1000000000000000000"), amount.convertUnit(IconAmount.Unit.LOOP).asInteger()); 94 | } 95 | 96 | } 97 | -------------------------------------------------------------------------------- /library/src/test/java/foundation/icon/icx/transport/http/HttpProviderTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019 ICON Foundation 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package foundation.icon.icx.transport.http; 18 | 19 | import org.junit.jupiter.api.Test; 20 | 21 | import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; 22 | import static org.junit.jupiter.api.Assertions.assertThrows; 23 | 24 | class HttpProviderTest { 25 | 26 | @Test 27 | void testHttpProviderURILegacy() { 28 | String[] validEndpoints = { 29 | "http://localhost:9000/api/v3", 30 | "https://ctz.solidwallet.io/api/v3", 31 | "http://localhost:9000/api/v3/channel", 32 | }; 33 | for (String endpoint : validEndpoints) { 34 | assertDoesNotThrow(() -> { 35 | new HttpProvider(endpoint); 36 | }); 37 | } 38 | } 39 | 40 | @Test 41 | void testHttpProviderURI() { 42 | String[] validEndpoints = { 43 | "http://localhost:9000", 44 | "https://ctz.solidwallet.io", 45 | }; 46 | String[] invalidEndpoints = { 47 | "http://localhost:9000/", 48 | "http://localhost:9000/api/v3", 49 | "http://localhost:9000/api/v3/", 50 | "http://localhost:9000/api/v3/file", 51 | "https://ctz.solidwallet.io/", 52 | "https://ctz.solidwallet.io/api/v3", 53 | }; 54 | for (String endpoint : validEndpoints) { 55 | assertDoesNotThrow(() -> { 56 | new HttpProvider(endpoint, 3); 57 | }); 58 | } 59 | for (String endpoint : validEndpoints) { 60 | assertThrows(IllegalArgumentException.class, () -> { 61 | new HttpProvider(endpoint, 2); 62 | }); 63 | } 64 | for (String endpoint : invalidEndpoints) { 65 | assertThrows(IllegalArgumentException.class, () -> { 66 | new HttpProvider(endpoint, 3); 67 | }); 68 | } 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /library/src/test/java/foundation/icon/icx/transport/jsonrpc/AnnotationTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 ICON Foundation. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package foundation.icon.icx.transport.jsonrpc; 18 | 19 | import foundation.icon.icx.data.Address; 20 | import foundation.icon.icx.data.Bytes; 21 | import org.junit.jupiter.api.Assertions; 22 | import org.junit.jupiter.api.Test; 23 | 24 | import java.math.BigInteger; 25 | import java.util.Arrays; 26 | 27 | 28 | public class AnnotationTest { 29 | 30 | @Test 31 | void testConvert() { 32 | 33 | RpcObject rpcObject = new RpcObject.Builder() 34 | .put("boolean", new RpcValue(true)) 35 | .put("string", new RpcValue("string value")) 36 | .put("BigInteger", new RpcValue(new BigInteger("1234"))) 37 | .put("Address", new RpcValue(new Address("hx4873b94352c8c1f3b2f09aaeccea31ce9e90bd31"))) 38 | .put("bytes", new RpcValue(new Bytes("0xf123"))) 39 | .put("byteArray", new RpcValue(new byte[]{1, 2, 3, 4, 5})) 40 | .build(); 41 | 42 | RpcConverter converter = new AnnotatedConverterFactory().create(AnnotationClass.class); 43 | AnnotationClass result = converter.convertTo(rpcObject); 44 | 45 | Assertions.assertEquals(rpcObject.getItem("boolean").asBoolean(), result.booleanType); 46 | Assertions.assertEquals(rpcObject.getItem("string").asString(), result.stringType); 47 | Assertions.assertEquals(rpcObject.getItem("BigInteger").asInteger(), result.bigIntegerType); 48 | Assertions.assertEquals(rpcObject.getItem("Address").asAddress(), result.addressType); 49 | Assertions.assertEquals(rpcObject.getItem("bytes").asBytes(), result.bytesType); 50 | Assertions.assertArrayEquals(rpcObject.getItem("byteArray").asByteArray(), result.byteArrayType); 51 | 52 | } 53 | 54 | 55 | @AnnotationConverter 56 | public class AnnotationClass { 57 | 58 | @ConverterName("boolean") 59 | boolean booleanType; 60 | @ConverterName("string") 61 | String stringType; 62 | @ConverterName("BigInteger") 63 | BigInteger bigIntegerType; 64 | @ConverterName("Address") 65 | Address addressType; 66 | @ConverterName("bytes") 67 | Bytes bytesType; 68 | @ConverterName("byteArray") 69 | byte[] byteArrayType; 70 | 71 | public AnnotationClass() { 72 | } 73 | 74 | @Override 75 | public String toString() { 76 | return "AnnotationClass{" + 77 | "booleanType=" + booleanType + 78 | ", stringType='" + stringType + '\'' + 79 | ", bigIntegerType=" + bigIntegerType + 80 | ", addressType=" + addressType + 81 | ", bytesType=" + bytesType + 82 | ", byteArrayType=" + Arrays.toString(byteArrayType) + 83 | '}'; 84 | } 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /library/src/test/java/foundation/icon/icx/transport/jsonrpc/DeserializerTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 ICON Foundation 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package foundation.icon.icx.transport.jsonrpc; 18 | 19 | import com.fasterxml.jackson.databind.ObjectMapper; 20 | import com.fasterxml.jackson.databind.module.SimpleModule; 21 | import org.junit.jupiter.api.BeforeEach; 22 | import org.junit.jupiter.api.Test; 23 | 24 | import java.io.IOException; 25 | import java.math.BigInteger; 26 | 27 | import static org.junit.jupiter.api.Assertions.*; 28 | 29 | class DeserializerTest { 30 | private ObjectMapper mapper; 31 | 32 | @BeforeEach 33 | void initAll() { 34 | mapper = new ObjectMapper(); 35 | SimpleModule module = new SimpleModule(); 36 | module.addDeserializer(RpcItem.class, new RpcItemDeserializer()); 37 | mapper.registerModule(module); 38 | } 39 | 40 | @Test 41 | void testRpcDeserializer() throws IOException { 42 | String json = "{\"stringValue\":\"string\",\"array\":[{\"longValue\":1533018344753765,\"stringValue\":\"string\",\"intValue\":\"0x4d2\",\"booleanValue\":\"0x0\",\"bytesValue\":\"0x010203\"},\"0x4d2\",\"0x0\",\"string\",\"0x010203\"],\"intValue\":\"0x4d2\",\"booleanValue\":\"0x0\",\"bytesValue\":\"0x010203\",\"object\":{\"stringValue\":\"string\",\"intValue\":\"0x4d2\",\"booleanValue\":\"0x0\",\"bytesValue\":\"0x010203\"}}"; 43 | RpcObject root = (RpcObject) mapper.readValue(json, RpcItem.class); 44 | RpcValue rpcValue; 45 | RpcArray array = (RpcArray) root.getItem("array"); 46 | 47 | RpcObject obj = (RpcObject) array.get(0); 48 | rpcValue = (RpcValue) obj.getItem("intValue"); 49 | assertEquals(new BigInteger("4d2", 16), rpcValue.asInteger()); 50 | rpcValue = (RpcValue) obj.getItem("booleanValue"); 51 | assertEquals(false, rpcValue.asBoolean()); 52 | rpcValue = (RpcValue) obj.getItem("stringValue"); 53 | assertEquals("string", rpcValue.asString()); 54 | rpcValue = (RpcValue) obj.getItem("bytesValue"); 55 | assertArrayEquals(new byte[]{0x1, 0x2, 0x3}, rpcValue.asByteArray()); 56 | rpcValue = (RpcValue) obj.getItem("longValue"); 57 | assertEquals(new BigInteger(String.valueOf(1533018344753765L)), rpcValue.asInteger()); 58 | 59 | rpcValue = (RpcValue) array.get(1); 60 | assertEquals(new BigInteger("4d2", 16), rpcValue.asInteger()); 61 | rpcValue = (RpcValue) array.get(2); 62 | assertEquals(false, rpcValue.asBoolean()); 63 | rpcValue = (RpcValue) array.get(3); 64 | assertEquals("string", rpcValue.asString()); 65 | rpcValue = (RpcValue) array.get(4); 66 | assertArrayEquals(new byte[]{0x1, 0x2, 0x3}, rpcValue.asByteArray()); 67 | 68 | rpcValue = (RpcValue) root.getItem("intValue"); 69 | assertEquals(new BigInteger("4d2", 16), rpcValue.asInteger()); 70 | rpcValue = (RpcValue) root.getItem("booleanValue"); 71 | assertEquals(false, rpcValue.asBoolean()); 72 | rpcValue = (RpcValue) root.getItem("stringValue"); 73 | assertEquals("string", rpcValue.asString()); 74 | rpcValue = (RpcValue) root.getItem("bytesValue"); 75 | assertArrayEquals(new byte[]{0x1, 0x2, 0x3}, rpcValue.asByteArray()); 76 | } 77 | 78 | @Test 79 | void testRpcValue() throws IOException { 80 | String json = "\"0x1234\""; 81 | RpcItem rpcItem = mapper.readValue(json, RpcItem.class); 82 | 83 | assertTrue(rpcItem instanceof RpcValue); 84 | assertEquals("0x1234", rpcItem.asString()); 85 | } 86 | 87 | @Test 88 | void testNullAndEmptyBytes() throws IOException { 89 | String json = "null"; 90 | RpcItem rpcItem = mapper.readValue(json, RpcItem.class); 91 | assertNull(rpcItem); 92 | 93 | json = "{\"key\": null}"; 94 | rpcItem = mapper.readValue(json, RpcItem.class); 95 | assertTrue(rpcItem.asObject().getItem("key").isNull()); 96 | 97 | json = "\"0x\""; 98 | rpcItem = mapper.readValue(json, RpcItem.class); 99 | assertEquals(0, rpcItem.asByteArray().length); 100 | assertArrayEquals(new byte[0], rpcItem.asByteArray()); 101 | } 102 | } 103 | -------------------------------------------------------------------------------- /library/src/test/java/foundation/icon/icx/transport/jsonrpc/RpcItemCreatorTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 ICON Foundation 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | * 16 | */ 17 | 18 | package foundation.icon.icx.transport.jsonrpc; 19 | 20 | 21 | import org.junit.jupiter.api.Test; 22 | 23 | import static org.junit.jupiter.api.Assertions.assertEquals; 24 | import static org.junit.jupiter.api.Assertions.assertNull; 25 | 26 | public class RpcItemCreatorTest { 27 | 28 | public final String outerVar = "outerVar"; 29 | 30 | 31 | class TokenBalance { 32 | private String _owner; 33 | } 34 | 35 | 36 | @Test 37 | void testCreate() { 38 | String address = "hx4873b94352c8c1f3b2f09aaeccea31ce9e90bd31"; 39 | TokenBalance p = new TokenBalance(); 40 | p._owner = address; 41 | RpcObject params = (RpcObject) RpcItemCreator.create(p); 42 | 43 | RpcObject expectedParams = new RpcObject.Builder() 44 | .put("_owner", new RpcValue(address)) 45 | .build(); 46 | 47 | assertEquals(params.getItem("_owner").asString(), 48 | expectedParams.getItem("_owner").asString()); 49 | 50 | assertNull(params.getItem("outerVar")); 51 | } 52 | 53 | } 54 | -------------------------------------------------------------------------------- /library/src/test/java/foundation/icon/icx/transport/jsonrpc/RpcValueTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 ICON Foundation 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | * 16 | */ 17 | 18 | package foundation.icon.icx.transport.jsonrpc; 19 | 20 | import foundation.icon.icx.transport.jsonrpc.RpcItem.RpcValueException; 21 | import org.junit.jupiter.api.BeforeEach; 22 | import org.junit.jupiter.api.Test; 23 | 24 | import java.math.BigInteger; 25 | 26 | import static org.junit.jupiter.api.Assertions.*; 27 | 28 | class RpcValueTest { 29 | private RpcValue plainStringValue; 30 | private RpcValue bytesValue; 31 | private RpcValue oddIntegerValue; 32 | private RpcValue evenIntegerValue; 33 | private RpcValue booleanValue; 34 | 35 | @BeforeEach 36 | void initAll() { 37 | plainStringValue = new RpcValue("string value"); 38 | bytesValue = new RpcValue(new byte[]{1, 2, 3, 4, 5}); 39 | oddIntegerValue = new RpcValue(new BigInteger("1234")); 40 | evenIntegerValue = new RpcValue(new BigInteger("61731")); 41 | booleanValue = new RpcValue(true); 42 | } 43 | 44 | @Test 45 | void testAsString() { 46 | assertEquals("string value", plainStringValue.asString()); 47 | assertEquals("0x0102030405", bytesValue.asString()); 48 | assertEquals("0x4d2", oddIntegerValue.asString()); 49 | assertEquals("0xf123", evenIntegerValue.asString()); 50 | assertEquals("0x1", booleanValue.asString()); 51 | } 52 | 53 | @Test 54 | void testAsBytes() { 55 | assertThrows(RpcValueException.class, plainStringValue::asByteArray); 56 | assertArrayEquals(new byte[]{1, 2, 3, 4, 5}, bytesValue.asByteArray()); 57 | assertThrows(RpcValueException.class, oddIntegerValue::asByteArray); 58 | assertArrayEquals(new byte[]{-15, 35}, evenIntegerValue.asByteArray()); 59 | assertThrows(RpcValueException.class, booleanValue::asByteArray); 60 | } 61 | 62 | @Test 63 | void testAsInteger() { 64 | assertThrows(RpcValueException.class, plainStringValue::asInteger); 65 | assertEquals(new BigInteger("0102030405", 16), bytesValue.asInteger()); 66 | assertEquals(new BigInteger("1234"), oddIntegerValue.asInteger()); 67 | assertEquals(new BigInteger("61731"), evenIntegerValue.asInteger()); 68 | assertEquals(new BigInteger("1"), booleanValue.asInteger()); 69 | 70 | RpcValue minusHex = new RpcValue("-0x4d2"); 71 | assertEquals(new BigInteger("-1234"), minusHex.asInteger()); 72 | 73 | RpcValue plusHex = new RpcValue("+0x4d2"); 74 | assertThrows(RpcValueException.class, plusHex::asInteger); 75 | } 76 | 77 | @Test 78 | void testAsBoolean() { 79 | assertThrows(RpcValueException.class, plainStringValue::asBoolean); 80 | assertThrows(RpcValueException.class, bytesValue::asBoolean); 81 | assertThrows(RpcValueException.class, oddIntegerValue::asBoolean); 82 | assertThrows(RpcValueException.class, evenIntegerValue::asBoolean); 83 | assertTrue(booleanValue.asBoolean()); 84 | } 85 | 86 | } 87 | -------------------------------------------------------------------------------- /library/src/test/java/foundation/icon/icx/transport/jsonrpc/SerializerTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 ICON Foundation 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package foundation.icon.icx.transport.jsonrpc; 18 | 19 | import com.fasterxml.jackson.core.JsonProcessingException; 20 | import com.fasterxml.jackson.databind.ObjectMapper; 21 | import com.fasterxml.jackson.databind.module.SimpleModule; 22 | import org.junit.jupiter.api.BeforeEach; 23 | import org.junit.jupiter.api.Test; 24 | 25 | import java.math.BigInteger; 26 | 27 | import static org.junit.jupiter.api.Assertions.assertEquals; 28 | import static org.junit.jupiter.api.Assertions.assertTrue; 29 | 30 | class SerializerTest { 31 | private ObjectMapper mapper; 32 | 33 | @BeforeEach 34 | void initAll() { 35 | mapper = new ObjectMapper(); 36 | SimpleModule module = new SimpleModule(); 37 | module.addSerializer(RpcItem.class, new RpcItemSerializer()); 38 | mapper.registerModule(module); 39 | } 40 | 41 | @Test 42 | void testRpcSerializer() throws JsonProcessingException { 43 | RpcItem intValue = new RpcValue(new BigInteger("1234")); 44 | RpcItem booleanValue = new RpcValue(false); 45 | RpcItem stringValue = new RpcValue("string"); 46 | RpcItem bytesValue = new RpcValue(new byte[]{0x1, 0x2, 0x3}); 47 | RpcItem escapeValue = new RpcValue("\\.{}[]"); 48 | 49 | RpcItem object = new RpcObject.Builder() 50 | .put("intValue", intValue) 51 | .put("booleanValue", booleanValue) 52 | .put("stringValue", stringValue) 53 | .put("bytesValue", bytesValue) 54 | .put("escapeValue", escapeValue) 55 | .build(); 56 | 57 | RpcItem array = new RpcArray.Builder() 58 | .add(object) 59 | .add(intValue) 60 | .add(booleanValue) 61 | .add(stringValue) 62 | .add(bytesValue) 63 | .build(); 64 | 65 | RpcItem root = new RpcObject.Builder() 66 | .put("object", object) 67 | .put("array", array) 68 | .put("intValue", intValue) 69 | .put("booleanValue", booleanValue) 70 | .put("stringValue", stringValue) 71 | .put("bytesValue", bytesValue) 72 | .build(); 73 | 74 | String json = mapper.writeValueAsString(root); 75 | assertTrue(json.length() > 0); 76 | } 77 | 78 | @Test 79 | void testNullAndEmptyBytes() throws JsonProcessingException { 80 | String expected = "{\"key\":null}"; 81 | RpcItem rpcItem = new RpcObject.Builder() 82 | .put("key", RpcValue.NULL) 83 | .build(); 84 | String json = mapper.writeValueAsString(rpcItem); 85 | assertEquals(expected, json); 86 | 87 | expected = "{\"key\":\"0x\"}"; 88 | rpcItem = new RpcObject.Builder() 89 | .put("key", new RpcValue(new byte[0])) 90 | .build(); 91 | json = mapper.writeValueAsString(rpcItem); 92 | assertEquals(expected, json); 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /library/src/test/resources/godWallet.json: -------------------------------------------------------------------------------- 1 | { 2 | "address": "hxb6b5791be0b5ef67063b3c10b840fb81514db2fd", 3 | "id": "87323a66-289a-4ce2-88e4-00278deb5b84", 4 | "version": 3, 5 | "coinType": "icx", 6 | "crypto": { 7 | "cipher": "aes-128-ctr", 8 | "cipherparams": { 9 | "iv": "069e46aaefae8f1c1f840d6b09144999" 10 | }, 11 | "ciphertext": "f35ff7cf4f5759cb0878088d0887574a896f7f0fc2a73898d88be1fe52977dbd", 12 | "kdf": "scrypt", 13 | "kdfparams": { 14 | "dklen": 32, 15 | "n": 65536, 16 | "r": 8, 17 | "p": 1, 18 | "salt": "0fc9c3b24cdb8175" 19 | }, 20 | "mac": "1ef4ff51fdee8d4de9cf59e160da049eb0099eb691510994f5eca492f56c817a" 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /library/src/test/resources/sampleToken.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/icon-project/icon-sdk-java/9a50cb1cc18c4fdb21615ed7c42a8b4a97dd8d4f/library/src/test/resources/sampleToken.zip -------------------------------------------------------------------------------- /publish.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 ICON Foundation. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | def snapshotSuffix = rootProject.hasProperty('release') ? '' : '-SNAPSHOT' 18 | version = VERSION_NAME + snapshotSuffix 19 | 20 | def pomConfig = { 21 | licenses { 22 | license { 23 | name "The Apache Software License, Version 2.0" 24 | url "http://www.apache.org/licenses/LICENSE-2.0.txt" 25 | distribution "repo" 26 | } 27 | } 28 | developers { 29 | developer { 30 | id "iconfoundation" 31 | name "icon.foundation" 32 | email "foo@icon.foundation" 33 | } 34 | } 35 | scm { 36 | url POM_SCM_URL 37 | } 38 | } 39 | 40 | project(':library') { 41 | task sourcesJar(type: Jar, dependsOn: classes) { 42 | classifier 'sources' 43 | from sourceSets.main.allSource 44 | } 45 | 46 | task javadocJar(type: Jar, dependsOn: javadoc) { 47 | classifier 'javadoc' 48 | from javadoc.destinationDir 49 | } 50 | 51 | publishing { 52 | repositories { 53 | maven { 54 | name = 'mavenCentral' 55 | def releasesUrl = "https://oss.sonatype.org/service/local/staging/deploy/maven2" 56 | def snapshotsUrl = "https://oss.sonatype.org/content/repositories/snapshots" 57 | url = version.endsWith('SNAPSHOT') ? snapshotsUrl : releasesUrl 58 | credentials { 59 | username = rootProject.hasProperty('mavenCentralUsername') ? "$mavenCentralUsername" : '' 60 | password = rootProject.hasProperty('mavenCentralPassword') ? "$mavenCentralPassword" : '' 61 | } 62 | } 63 | } 64 | publications { 65 | mavenJava(MavenPublication) { 66 | from components.java 67 | artifact sourcesJar 68 | artifact javadocJar 69 | groupId GROUP 70 | artifactId POM_ARTIFACT_ID 71 | pom.withXml { 72 | def root = asNode() 73 | root.appendNode('name', POM_ARTIFACT_ID) 74 | root.appendNode('description', POM_DESCRIPTION) 75 | root.appendNode('url', POM_URL) 76 | root.children().last() + pomConfig 77 | 78 | // Iterate over the compile dependencies (we don't want the test ones), adding a node for each 79 | configurations.compile.allDependencies.each { 80 | def dependencyNode = dependenciesNode.appendNode('dependency') 81 | dependencyNode.appendNode('groupId', it.group) 82 | dependencyNode.appendNode('artifactId', it.name) 83 | dependencyNode.appendNode('version', it.version) 84 | } 85 | } 86 | } 87 | } 88 | } 89 | 90 | signing { 91 | required rootProject.hasProperty('release') 92 | if (rootProject.hasProperty('signingKey')) { 93 | def signingKey = rootProject.findProperty("signingKey") 94 | def signingPassword = rootProject.findProperty("signingPassword") 95 | useInMemoryPgpKeys(signingKey, signingPassword) 96 | } 97 | sign publishing.publications.mavenJava 98 | } 99 | } 100 | -------------------------------------------------------------------------------- /quickstart/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'java' 3 | } 4 | 5 | group 'foundation.icon.icx' 6 | 7 | sourceCompatibility = 1.8 8 | 9 | repositories { 10 | mavenCentral() 11 | } 12 | 13 | dependencies { 14 | implementation project(':library') 15 | 16 | implementation 'com.squareup.okhttp3:okhttp:3.11.0' 17 | implementation 'com.squareup.okhttp3:logging-interceptor:3.11.0' 18 | } 19 | -------------------------------------------------------------------------------- /quickstart/src/main/java/foundation/icon/icx/WalletExample.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 ICON Foundation 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package foundation.icon.icx; 18 | 19 | import foundation.icon.icx.crypto.KeystoreException; 20 | import foundation.icon.icx.data.Bytes; 21 | import foundation.icon.icx.data.CommonData; 22 | 23 | import java.io.File; 24 | import java.io.IOException; 25 | import java.security.InvalidAlgorithmParameterException; 26 | import java.security.NoSuchAlgorithmException; 27 | import java.security.NoSuchProviderException; 28 | 29 | public class WalletExample { 30 | 31 | private static final String PASSWORD = "P@ssw0rd"; 32 | 33 | private static void print(KeyWallet wallet) { 34 | System.out.println("address: " + wallet.getAddress()); 35 | System.out.println("privateKey: " + wallet.getPrivateKey().toHexString(false)); 36 | System.out.println(); 37 | } 38 | 39 | public static void main(String[] args) throws InvalidAlgorithmParameterException, NoSuchAlgorithmException, 40 | NoSuchProviderException, IOException, KeystoreException { 41 | 42 | String dirPath = "./"; 43 | // File of directory for keystore file. 44 | File destinationDirectory = new File(dirPath); 45 | 46 | // Create keyWallet and store it as a keystore file 47 | System.out.println("Create KeyWallet"); 48 | KeyWallet wallet1 = KeyWallet.create(); 49 | print(wallet1); 50 | 51 | System.out.println("Store KeyWallet"); 52 | String fileName = KeyWallet.store(wallet1, PASSWORD, destinationDirectory); 53 | System.out.println("keystore fileName: " + fileName); 54 | System.out.println(); 55 | 56 | // Loads a wallet from bytes of the private key 57 | System.out.println("Load KeyWallet using private key"); 58 | KeyWallet wallet2 = KeyWallet.load(new Bytes(CommonData.PRIVATE_KEY_STRING)); 59 | print(wallet2); 60 | 61 | // Loads a wallet from a key store file 62 | System.out.println("Load KeyWallet using keystore file"); 63 | File file = new File(destinationDirectory, fileName); 64 | KeyWallet wallet3 = KeyWallet.load(PASSWORD, file); 65 | print(wallet3); 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /quickstart/src/main/java/foundation/icon/icx/data/CommonData.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 ICON Foundation. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package foundation.icon.icx.data; 18 | 19 | public class CommonData { 20 | 21 | public static final String PRIVATE_KEY_STRING = "592eb276d534e2c41a2d9356c0ab262dc233d87e4dd71ce705ec130a8d27ff0c"; 22 | public static final String SERVER_URI = "http://127.0.0.1:9000"; 23 | 24 | // Default address to deploy score. 25 | public static final Address SCORE_INSTALL_ADDRESS = new Address("cx0000000000000000000000000000000000000000"); 26 | 27 | // Default address to call Governance SCORE API. 28 | public static final Address GOVERNANCE_ADDRESS = new Address("cx0000000000000000000000000000000000000001"); 29 | 30 | public static final String ADDRESS_1 = "hxc5bdfc07a86869e345c9eec73283654df6a0559b"; 31 | } 32 | -------------------------------------------------------------------------------- /quickstart/src/main/resources/sampleToken.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/icon-project/icon-sdk-java/9a50cb1cc18c4fdb21615ed7c42a8b4a97dd8d4f/quickstart/src/main/resources/sampleToken.zip -------------------------------------------------------------------------------- /samples/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'java' 3 | } 4 | 5 | group 'foundation.icon.icx' 6 | 7 | sourceCompatibility = 1.8 8 | 9 | repositories { 10 | mavenCentral() 11 | } 12 | 13 | dependencies { 14 | implementation project(':library') 15 | 16 | implementation 'com.squareup.okhttp3:okhttp:3.11.0' 17 | implementation 'com.squareup.okhttp3:logging-interceptor:3.11.0' 18 | } 19 | -------------------------------------------------------------------------------- /samples/src/main/java/foundation/icon/icx/Constants.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019 ICON Foundation 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package foundation.icon.icx; 18 | 19 | import foundation.icon.icx.data.Address; 20 | import foundation.icon.icx.data.Bytes; 21 | 22 | public class Constants { 23 | public static final String SERVER_URL = "http://localhost:9000"; 24 | public static final Bytes privateKey = new Bytes("592eb276d534e2c41a2d9356c0ab262dc233d87e4dd71ce705ec130a8d27ff0c"); 25 | public static final Address testAddress1 = new Address("hx4873b94352c8c1f3b2f09aaeccea31ce9e90bd31"); 26 | } 27 | -------------------------------------------------------------------------------- /samples/src/main/java/foundation/icon/icx/ExecuteSyncAsync.java: -------------------------------------------------------------------------------- 1 | package foundation.icon.icx; 2 | 3 | import foundation.icon.icx.data.Block; 4 | import foundation.icon.icx.transport.http.HttpProvider; 5 | import okhttp3.OkHttpClient; 6 | import okhttp3.logging.HttpLoggingInterceptor; 7 | 8 | import java.io.IOException; 9 | 10 | public class ExecuteSyncAsync { 11 | 12 | private IconService iconService; 13 | 14 | private ExecuteSyncAsync() { 15 | HttpLoggingInterceptor logging = new HttpLoggingInterceptor(); 16 | logging.setLevel(HttpLoggingInterceptor.Level.BODY); 17 | OkHttpClient httpClient = new OkHttpClient.Builder() 18 | .addInterceptor(logging) 19 | .build(); 20 | iconService = new IconService(new HttpProvider(httpClient, Constants.SERVER_URL, 3)); 21 | } 22 | 23 | private void sync() throws IOException { 24 | Block block = iconService.getLastBlock().execute(); 25 | System.out.println("sync call block hash:" + block.getBlockHash()); 26 | } 27 | 28 | private void async() { 29 | iconService.getLastBlock().execute(new Callback() { 30 | @Override 31 | public void onSuccess(Block block) { 32 | System.out.println("async call block hash:" + block.getBlockHash()); 33 | } 34 | 35 | @Override 36 | public void onFailure(Exception exception) { 37 | // exception 38 | System.out.println("exception:" + exception.getMessage()); 39 | } 40 | }); 41 | } 42 | 43 | public static void main(String[] args) throws IOException { 44 | ExecuteSyncAsync call = new ExecuteSyncAsync(); 45 | call.sync(); 46 | call.async(); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /samples/src/main/java/foundation/icon/icx/GenerateWallet.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 ICON Foundation. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package foundation.icon.icx; 18 | 19 | import foundation.icon.icx.crypto.KeystoreException; 20 | import foundation.icon.icx.data.Bytes; 21 | 22 | import java.io.File; 23 | import java.io.IOException; 24 | import java.nio.file.Files; 25 | import java.security.InvalidAlgorithmParameterException; 26 | import java.security.NoSuchAlgorithmException; 27 | import java.security.NoSuchProviderException; 28 | 29 | public class GenerateWallet { 30 | 31 | private String PRIVATE_KEY_STRING = "2d42994b2f7735bbc93a3e64381864d06747e574aa94655c516f9ad0a74eed79"; 32 | private String PASSWORD = "Pa55w0rd"; 33 | private File tempDir; 34 | 35 | private GenerateWallet() throws IOException { 36 | tempDir = Files.createTempDirectory("testkeys").toFile(); 37 | } 38 | 39 | private KeyWallet create() throws InvalidAlgorithmParameterException, NoSuchAlgorithmException, NoSuchProviderException { 40 | return KeyWallet.create(); 41 | } 42 | 43 | private KeyWallet loadPrivateKey() { 44 | return KeyWallet.load(new Bytes(PRIVATE_KEY_STRING)); 45 | } 46 | 47 | private String storeKeyStore(KeyWallet wallet) throws KeystoreException, IOException { 48 | return KeyWallet.store(wallet, PASSWORD, tempDir); 49 | } 50 | 51 | private KeyWallet loadKeyStore(String fileName) throws IOException, KeystoreException { 52 | File file = new File(tempDir, fileName); 53 | return KeyWallet.load(PASSWORD, file); 54 | } 55 | 56 | public static void main(String[] args) throws InvalidAlgorithmParameterException, NoSuchAlgorithmException, 57 | NoSuchProviderException, IOException, KeystoreException { 58 | GenerateWallet sample = new GenerateWallet(); 59 | 60 | KeyWallet wallet = sample.create(); 61 | System.out.println("address: " + wallet.getAddress()); 62 | System.out.println("privateKey: " + wallet.getPrivateKey().toHexString(false)); 63 | 64 | wallet = sample.loadPrivateKey(); 65 | System.out.println("address: " + wallet.getAddress()); 66 | System.out.println("privateKey: " + wallet.getPrivateKey().toHexString(false)); 67 | 68 | String fileName = sample.storeKeyStore(wallet); 69 | System.out.println("keystore fileName: " + fileName); 70 | 71 | wallet = sample.loadKeyStore(fileName); 72 | System.out.println("address: " + wallet.getAddress()); 73 | System.out.println("privateKey: " + wallet.getPrivateKey().toHexString(false)); 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /samples/src/main/java/foundation/icon/icx/SendIcxTransaction.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 ICON Foundation 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package foundation.icon.icx; 18 | 19 | import foundation.icon.icx.data.Address; 20 | import foundation.icon.icx.data.Bytes; 21 | import foundation.icon.icx.data.IconAmount; 22 | import foundation.icon.icx.data.TransactionResult; 23 | import foundation.icon.icx.transport.http.HttpProvider; 24 | import okhttp3.OkHttpClient; 25 | import okhttp3.logging.HttpLoggingInterceptor; 26 | 27 | import java.io.IOException; 28 | import java.math.BigInteger; 29 | 30 | public class SendIcxTransaction { 31 | 32 | private IconService iconService; 33 | private Wallet wallet; 34 | 35 | public SendIcxTransaction() { 36 | HttpLoggingInterceptor logging = new HttpLoggingInterceptor(); 37 | logging.setLevel(HttpLoggingInterceptor.Level.BODY); 38 | OkHttpClient httpClient = new OkHttpClient.Builder() 39 | .addInterceptor(logging) 40 | .build(); 41 | iconService = new IconService(new HttpProvider(httpClient, Constants.SERVER_URL, 3)); 42 | wallet = KeyWallet.load(Constants.privateKey); 43 | } 44 | 45 | public TransactionResult sendTransaction() throws IOException { 46 | BigInteger networkId = new BigInteger("3"); 47 | Address fromAddress = wallet.getAddress(); 48 | Address toAddress = Constants.testAddress1; 49 | 50 | BigInteger value = IconAmount.of("1", IconAmount.Unit.ICX).toLoop(); 51 | BigInteger stepLimit = new BigInteger("100000"); 52 | long timestamp = System.currentTimeMillis() * 1000L; 53 | BigInteger nonce = new BigInteger("1"); 54 | 55 | Transaction transaction = TransactionBuilder.newBuilder() 56 | .nid(networkId) 57 | .from(fromAddress) 58 | .to(toAddress) 59 | .value(value) 60 | .stepLimit(stepLimit) 61 | .timestamp(new BigInteger(Long.toString(timestamp))) 62 | .nonce(nonce) 63 | .build(); 64 | 65 | SignedTransaction signedTransaction = new SignedTransaction(transaction, wallet); 66 | Bytes hash = iconService.sendTransaction(signedTransaction).execute(); 67 | System.out.println("txHash: " + hash); 68 | TransactionResult result = Utils.getTransactionResult(iconService, hash); 69 | System.out.println("status: " + result.getStatus()); 70 | return result; 71 | } 72 | 73 | public static void main(String[] args) throws IOException { 74 | new SendIcxTransaction().sendTransaction(); 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /samples/src/main/java/foundation/icon/icx/SendMessageTransaction.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 ICON Foundation 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package foundation.icon.icx; 18 | 19 | import foundation.icon.icx.data.Address; 20 | import foundation.icon.icx.data.Bytes; 21 | import foundation.icon.icx.data.TransactionResult; 22 | import foundation.icon.icx.transport.http.HttpProvider; 23 | import okhttp3.OkHttpClient; 24 | import okhttp3.logging.HttpLoggingInterceptor; 25 | 26 | import java.io.IOException; 27 | import java.math.BigInteger; 28 | 29 | public class SendMessageTransaction { 30 | 31 | private IconService iconService; 32 | private Wallet wallet; 33 | 34 | private SendMessageTransaction() { 35 | HttpLoggingInterceptor logging = new HttpLoggingInterceptor(); 36 | logging.setLevel(HttpLoggingInterceptor.Level.BODY); 37 | OkHttpClient httpClient = new OkHttpClient.Builder() 38 | .addInterceptor(logging) 39 | .build(); 40 | iconService = new IconService(new HttpProvider(httpClient, Constants.SERVER_URL, 3)); 41 | wallet = KeyWallet.load(Constants.privateKey); 42 | } 43 | 44 | private void sendTransaction() throws IOException { 45 | BigInteger networkId = BigInteger.valueOf(3); 46 | Address fromAddress = wallet.getAddress(); 47 | Address toAddress = Constants.testAddress1; 48 | BigInteger nonce = BigInteger.valueOf(1); 49 | String message = "Hello World"; 50 | 51 | // make a raw transaction without the stepLimit 52 | Transaction transaction = TransactionBuilder.newBuilder() 53 | .nid(networkId) 54 | .from(fromAddress) 55 | .to(toAddress) 56 | .nonce(nonce) 57 | .message(message) 58 | .build(); 59 | 60 | // get an estimated step value 61 | BigInteger estimatedStep = iconService.estimateStep(transaction).execute(); 62 | 63 | // make a signed transaction with the same raw transaction and the estimated step 64 | SignedTransaction signedTransaction = new SignedTransaction(transaction, wallet, estimatedStep); 65 | Bytes hash = iconService.sendTransaction(signedTransaction).execute(); 66 | System.out.println("txHash: " + hash); 67 | TransactionResult result = Utils.getTransactionResult(iconService, hash); 68 | System.out.println("status: " + result.getStatus()); 69 | } 70 | 71 | public static void main(String[] args) throws IOException { 72 | new SendMessageTransaction().sendTransaction(); 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /samples/src/main/java/foundation/icon/icx/Utils.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019 ICON Foundation 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package foundation.icon.icx; 18 | 19 | import foundation.icon.icx.data.Bytes; 20 | import foundation.icon.icx.data.TransactionResult; 21 | import foundation.icon.icx.transport.jsonrpc.RpcError; 22 | 23 | import java.io.IOException; 24 | 25 | public class Utils { 26 | 27 | public static TransactionResult getTransactionResult(IconService iconService, Bytes txHash) throws IOException { 28 | TransactionResult result = null; 29 | while (result == null) { 30 | try { 31 | result = iconService.getTransactionResult(txHash).execute(); 32 | } catch (RpcError e) { 33 | System.out.println("RpcError: code: " + e.getCode() + ", message: " + e.getMessage()); 34 | try { 35 | // wait until block confirmation 36 | System.out.println("Sleep 1.2 second."); 37 | Thread.sleep(1200); 38 | } catch (InterruptedException ie) { 39 | ie.printStackTrace(); 40 | } 41 | } 42 | } 43 | return result; 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /samples/src/main/java/foundation/icon/icx/call/CustomRequestParam.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 ICON Foundation. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package foundation.icon.icx.call; 18 | 19 | import foundation.icon.icx.Call; 20 | import foundation.icon.icx.Constants; 21 | import foundation.icon.icx.IconService; 22 | import foundation.icon.icx.data.Address; 23 | import foundation.icon.icx.data.TransactionResult; 24 | import foundation.icon.icx.token.DeploySampleToken; 25 | import foundation.icon.icx.token.SendTokenTransaction; 26 | import foundation.icon.icx.transport.http.HttpProvider; 27 | import foundation.icon.icx.transport.jsonrpc.RpcItem; 28 | import okhttp3.OkHttpClient; 29 | import okhttp3.logging.HttpLoggingInterceptor; 30 | 31 | import java.io.IOException; 32 | import java.math.BigInteger; 33 | 34 | public class CustomRequestParam { 35 | 36 | private IconService iconService; 37 | 38 | private CustomRequestParam() { 39 | HttpLoggingInterceptor logging = new HttpLoggingInterceptor(); 40 | logging.setLevel(HttpLoggingInterceptor.Level.BODY); 41 | OkHttpClient httpClient = new OkHttpClient.Builder() 42 | .addInterceptor(logging) 43 | .build(); 44 | iconService = new IconService(new HttpProvider(httpClient, Constants.SERVER_URL, 3)); 45 | } 46 | 47 | private void getBalance(Address scoreAddress) throws IOException { 48 | Address address = Constants.testAddress1; 49 | Param params = new Param(); 50 | params._owner = address; 51 | 52 | Call call = new Call.Builder() 53 | .from(address) 54 | .to(scoreAddress) 55 | .method("balanceOf") 56 | .params(params) 57 | .build(); 58 | 59 | RpcItem result = iconService.call(call).execute(); 60 | System.out.println("balance: " + result); 61 | } 62 | 63 | class Param { 64 | Address _owner; 65 | } 66 | 67 | public static void main(String[] args) throws IOException { 68 | TransactionResult result = new DeploySampleToken().sendTransaction(); 69 | if (BigInteger.ONE.equals(result.getStatus())) { 70 | Address scoreAddress = new Address(result.getScoreAddress()); 71 | new SendTokenTransaction().sendTransaction(scoreAddress); 72 | new CustomRequestParam().getBalance(scoreAddress); 73 | } else { 74 | System.out.println("Deploy failed!"); 75 | } 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /samples/src/main/java/foundation/icon/icx/call/SendIcxCall.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 ICON Foundation. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package foundation.icon.icx.call; 18 | 19 | import foundation.icon.icx.Call; 20 | import foundation.icon.icx.Constants; 21 | import foundation.icon.icx.IconService; 22 | import foundation.icon.icx.data.Address; 23 | import foundation.icon.icx.transport.http.HttpProvider; 24 | import foundation.icon.icx.transport.jsonrpc.RpcItem; 25 | import foundation.icon.icx.transport.jsonrpc.RpcObject; 26 | import okhttp3.OkHttpClient; 27 | import okhttp3.logging.HttpLoggingInterceptor; 28 | 29 | import java.io.IOException; 30 | 31 | public class SendIcxCall { 32 | 33 | private final Address scoreAddress = new Address("cx0000000000000000000000000000000000000001"); 34 | private IconService iconService; 35 | 36 | private SendIcxCall() { 37 | HttpLoggingInterceptor logging = new HttpLoggingInterceptor(); 38 | logging.setLevel(HttpLoggingInterceptor.Level.BODY); 39 | OkHttpClient httpClient = new OkHttpClient.Builder() 40 | .addInterceptor(logging) 41 | .build(); 42 | iconService = new IconService(new HttpProvider(httpClient, Constants.SERVER_URL, 3)); 43 | } 44 | 45 | private void getStepCosts() throws IOException { 46 | Call call = new Call.Builder() 47 | .to(scoreAddress) 48 | .method("getStepCosts") 49 | .build(); 50 | 51 | RpcItem result = iconService.call(call).execute(); 52 | RpcObject object = result.asObject(); 53 | 54 | System.out.println("default:"+object.getItem("default").asInteger()); 55 | System.out.println("contractCall:"+object.getItem("contractCall").asInteger()); 56 | System.out.println("contractUpdate:"+object.getItem("contractUpdate").asInteger()); 57 | System.out.println("contractDestruct:"+object.getItem("contractDestruct").asInteger()); 58 | System.out.println("contractCreate:"+object.getItem("contractCreate").asInteger()); 59 | System.out.println("contractSet:"+object.getItem("contractSet").asInteger()); 60 | System.out.println("get:"+object.getItem("get").asInteger()); 61 | System.out.println("set:"+object.getItem("set").asInteger()); 62 | System.out.println("replace:"+object.getItem("replace").asInteger()); 63 | System.out.println("delete:"+object.getItem("delete").asInteger()); 64 | System.out.println("input:"+object.getItem("input").asInteger()); 65 | System.out.println("eventLog:"+object.getItem("eventLog").asInteger()); 66 | System.out.println("apiCall:"+object.getItem("apiCall").asInteger()); 67 | } 68 | 69 | public static void main(String[] args) throws IOException { 70 | new SendIcxCall().getStepCosts(); 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /samples/src/main/java/foundation/icon/icx/get/GetBlock.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 ICON Foundation. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package foundation.icon.icx.get; 18 | 19 | import foundation.icon.icx.Constants; 20 | import foundation.icon.icx.IconService; 21 | import foundation.icon.icx.SendIcxTransaction; 22 | import foundation.icon.icx.Transaction; 23 | import foundation.icon.icx.data.Block; 24 | import foundation.icon.icx.data.Bytes; 25 | import foundation.icon.icx.data.TransactionResult; 26 | import foundation.icon.icx.transport.http.HttpProvider; 27 | import okhttp3.OkHttpClient; 28 | import okhttp3.logging.HttpLoggingInterceptor; 29 | 30 | import java.io.IOException; 31 | import java.math.BigInteger; 32 | 33 | public class GetBlock { 34 | 35 | private IconService iconService; 36 | 37 | private GetBlock() { 38 | HttpLoggingInterceptor logging = new HttpLoggingInterceptor(); 39 | logging.setLevel(HttpLoggingInterceptor.Level.BODY); 40 | OkHttpClient httpClient = new OkHttpClient.Builder() 41 | .addInterceptor(logging) 42 | .build(); 43 | iconService = new IconService(new HttpProvider(httpClient, Constants.SERVER_URL, 3)); 44 | } 45 | 46 | private void getLastBlock() throws IOException { 47 | Block block = iconService.getLastBlock().execute(); 48 | System.out.println("getLastBlock: " + block); 49 | } 50 | 51 | private void getBlockByHash(Bytes blockHash) throws IOException { 52 | Block block = iconService.getBlock(blockHash).execute(); 53 | System.out.println("getBlockByHash: " + block); 54 | } 55 | 56 | private void getBlockByHeight(BigInteger blockHeight) throws IOException { 57 | Block block = iconService.getBlock(blockHeight).execute(); 58 | System.out.println("getBlockByHeight:" + block); 59 | } 60 | 61 | public static void main(String[] args) throws IOException { 62 | TransactionResult result = new SendIcxTransaction().sendTransaction(); 63 | if (!BigInteger.ONE.equals(result.getStatus())) { 64 | System.out.println("SendIcxTransaction failed!"); 65 | return; 66 | } 67 | GetBlock block = new GetBlock(); 68 | block.getLastBlock(); 69 | block.getBlockByHash(result.getBlockHash()); 70 | block.getBlockByHeight(result.getBlockHeight()); 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /samples/src/main/java/foundation/icon/icx/get/GetScoreApi.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 ICON Foundation. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package foundation.icon.icx.get; 18 | 19 | import foundation.icon.icx.Constants; 20 | import foundation.icon.icx.IconService; 21 | import foundation.icon.icx.data.Address; 22 | import foundation.icon.icx.data.ScoreApi; 23 | import foundation.icon.icx.data.TransactionResult; 24 | import foundation.icon.icx.token.DeploySampleToken; 25 | import foundation.icon.icx.transport.http.HttpProvider; 26 | import okhttp3.OkHttpClient; 27 | import okhttp3.logging.HttpLoggingInterceptor; 28 | 29 | import java.io.IOException; 30 | import java.math.BigInteger; 31 | import java.util.List; 32 | 33 | public class GetScoreApi { 34 | 35 | private IconService iconService; 36 | 37 | private GetScoreApi() { 38 | HttpLoggingInterceptor logging = new HttpLoggingInterceptor(); 39 | logging.setLevel(HttpLoggingInterceptor.Level.BODY); 40 | OkHttpClient httpClient = new OkHttpClient.Builder() 41 | .addInterceptor(logging) 42 | .build(); 43 | iconService = new IconService(new HttpProvider(httpClient, Constants.SERVER_URL, 3)); 44 | } 45 | 46 | private void getScoreApi(Address scoreAddress) throws IOException { 47 | List apis = iconService.getScoreApi(scoreAddress).execute(); 48 | System.out.println("SCORE APIs: " + apis); 49 | } 50 | 51 | public static void main(String[] args) throws IOException { 52 | TransactionResult result = new DeploySampleToken().sendTransaction(); 53 | if (BigInteger.ONE.equals(result.getStatus())) { 54 | Address scoreAddress = new Address(result.getScoreAddress()); 55 | new GetScoreApi().getScoreApi(scoreAddress); 56 | } else { 57 | System.out.println("Deploy failed!"); 58 | } 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /samples/src/main/java/foundation/icon/icx/get/GetTotalSupply.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 ICON Foundation. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package foundation.icon.icx.get; 18 | 19 | import foundation.icon.icx.Constants; 20 | import foundation.icon.icx.IconService; 21 | import foundation.icon.icx.transport.http.HttpProvider; 22 | import okhttp3.OkHttpClient; 23 | import okhttp3.logging.HttpLoggingInterceptor; 24 | 25 | import java.io.IOException; 26 | import java.math.BigInteger; 27 | 28 | public class GetTotalSupply { 29 | 30 | private IconService iconService; 31 | 32 | private GetTotalSupply() { 33 | HttpLoggingInterceptor logging = new HttpLoggingInterceptor(); 34 | logging.setLevel(HttpLoggingInterceptor.Level.BODY); 35 | OkHttpClient httpClient = new OkHttpClient.Builder() 36 | .addInterceptor(logging) 37 | .build(); 38 | iconService = new IconService(new HttpProvider(httpClient, Constants.SERVER_URL, 3)); 39 | } 40 | 41 | private void getTotalSupply() throws IOException { 42 | BigInteger totalSupply = iconService.getTotalSupply().execute(); 43 | System.out.println("totalSupply: " + totalSupply); 44 | } 45 | 46 | public static void main(String[] args) throws IOException { 47 | new GetTotalSupply().getTotalSupply(); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /samples/src/main/java/foundation/icon/icx/get/GetTransaction.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 ICON Foundation. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package foundation.icon.icx.get; 18 | 19 | import foundation.icon.icx.Constants; 20 | import foundation.icon.icx.IconService; 21 | import foundation.icon.icx.SendIcxTransaction; 22 | import foundation.icon.icx.data.Bytes; 23 | import foundation.icon.icx.data.ConfirmedTransaction; 24 | import foundation.icon.icx.data.TransactionResult; 25 | import foundation.icon.icx.transport.http.HttpProvider; 26 | import okhttp3.OkHttpClient; 27 | import okhttp3.logging.HttpLoggingInterceptor; 28 | 29 | import java.io.IOException; 30 | import java.math.BigInteger; 31 | 32 | public class GetTransaction { 33 | 34 | private IconService iconService; 35 | 36 | private GetTransaction() { 37 | HttpLoggingInterceptor logging = new HttpLoggingInterceptor(); 38 | logging.setLevel(HttpLoggingInterceptor.Level.BODY); 39 | OkHttpClient httpClient = new OkHttpClient.Builder() 40 | .addInterceptor(logging) 41 | .build(); 42 | iconService = new IconService(new HttpProvider(httpClient, Constants.SERVER_URL, 3)); 43 | } 44 | 45 | private void getTransaction(Bytes txHash) throws IOException { 46 | ConfirmedTransaction tx = iconService.getTransaction(txHash).execute(); 47 | System.out.println("ConfirmedTransaction: " + tx); 48 | } 49 | 50 | private void getTransactionResult(Bytes txHash) throws IOException { 51 | TransactionResult result = iconService.getTransactionResult(txHash).execute(); 52 | System.out.println("TransactionResult: " + result); 53 | } 54 | 55 | public static void main(String[] args) throws IOException { 56 | TransactionResult result = new SendIcxTransaction().sendTransaction(); 57 | if (!BigInteger.ONE.equals(result.getStatus())) { 58 | System.out.println("SendIcxTransaction failed!"); 59 | return; 60 | } 61 | GetTransaction transaction = new GetTransaction(); 62 | transaction.getTransaction(result.getTxHash()); 63 | transaction.getTransactionResult(result.getTxHash()); 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /samples/src/main/java/foundation/icon/icx/get/IcxGetBalance.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 ICON Foundation. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package foundation.icon.icx.get; 18 | 19 | import foundation.icon.icx.Constants; 20 | import foundation.icon.icx.IconService; 21 | import foundation.icon.icx.data.Address; 22 | import foundation.icon.icx.transport.http.HttpProvider; 23 | import okhttp3.OkHttpClient; 24 | import okhttp3.logging.HttpLoggingInterceptor; 25 | 26 | import java.io.IOException; 27 | import java.math.BigInteger; 28 | 29 | public class IcxGetBalance { 30 | 31 | private IconService iconService; 32 | 33 | private IcxGetBalance() { 34 | HttpLoggingInterceptor logging = new HttpLoggingInterceptor(); 35 | logging.setLevel(HttpLoggingInterceptor.Level.BODY); 36 | OkHttpClient httpClient = new OkHttpClient.Builder() 37 | .addInterceptor(logging) 38 | .build(); 39 | iconService = new IconService(new HttpProvider(httpClient, Constants.SERVER_URL, 3)); 40 | } 41 | 42 | private void getBalance() throws IOException { 43 | Address address = Constants.testAddress1; 44 | BigInteger balance = iconService.getBalance(address).execute(); 45 | System.out.println("balance: " + balance); 46 | } 47 | 48 | public static void main(String[] args) throws IOException { 49 | new IcxGetBalance().getBalance(); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /samples/src/main/java/foundation/icon/icx/token/DeploySampleToken.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 ICON Foundation. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package foundation.icon.icx.token; 18 | 19 | import foundation.icon.icx.*; 20 | import foundation.icon.icx.data.Address; 21 | import foundation.icon.icx.data.Bytes; 22 | import foundation.icon.icx.data.TransactionResult; 23 | import foundation.icon.icx.transport.http.HttpProvider; 24 | import foundation.icon.icx.transport.jsonrpc.RpcObject; 25 | import foundation.icon.icx.transport.jsonrpc.RpcValue; 26 | import okhttp3.OkHttpClient; 27 | import okhttp3.logging.HttpLoggingInterceptor; 28 | 29 | import java.io.DataInputStream; 30 | import java.io.File; 31 | import java.io.FileInputStream; 32 | import java.io.IOException; 33 | import java.math.BigInteger; 34 | 35 | public class DeploySampleToken { 36 | 37 | private IconService iconService; 38 | private Wallet wallet; 39 | 40 | public DeploySampleToken() { 41 | HttpLoggingInterceptor logging = new HttpLoggingInterceptor(); 42 | logging.setLevel(HttpLoggingInterceptor.Level.BODY); 43 | OkHttpClient httpClient = new OkHttpClient.Builder() 44 | //.addInterceptor(logging) 45 | .build(); 46 | iconService = new IconService(new HttpProvider(httpClient, Constants.SERVER_URL, 3)); 47 | wallet = KeyWallet.load(Constants.privateKey); 48 | } 49 | 50 | public TransactionResult sendTransaction() throws IOException { 51 | String contentType = "application/zip"; 52 | byte[] content = readFile(); 53 | BigInteger networkId = new BigInteger("3"); 54 | Address fromAddress = wallet.getAddress(); 55 | Address toAddress = new Address("cx0000000000000000000000000000000000000000"); 56 | long timestamp = System.currentTimeMillis() * 1000L; 57 | BigInteger nonce = new BigInteger("1"); 58 | 59 | BigInteger initialSupply = new BigInteger("10000"); 60 | BigInteger decimals = new BigInteger("18"); 61 | 62 | RpcObject params = new RpcObject.Builder() 63 | .put("_initialSupply", new RpcValue(initialSupply)) 64 | .put("_decimals", new RpcValue(decimals)) 65 | .build(); 66 | 67 | // make a raw transaction without the stepLimit 68 | Transaction transaction = TransactionBuilder.newBuilder() 69 | .nid(networkId) 70 | .from(fromAddress) 71 | .to(toAddress) 72 | .timestamp(new BigInteger(Long.toString(timestamp))) 73 | .nonce(nonce) 74 | .deploy(contentType, content) 75 | .params(params) 76 | .build(); 77 | 78 | // get an estimated step value 79 | BigInteger estimatedStep = iconService.estimateStep(transaction).execute(); 80 | 81 | // set some margin value for the operation of `on_install` 82 | BigInteger margin = BigInteger.valueOf(10000); 83 | 84 | // make a signed transaction with the same raw transaction and the estimated step 85 | SignedTransaction signedTransaction = new SignedTransaction(transaction, wallet, estimatedStep.add(margin)); 86 | Bytes hash = iconService.sendTransaction(signedTransaction).execute(); 87 | System.out.println("txHash: " + hash); 88 | TransactionResult result = Utils.getTransactionResult(iconService, hash); 89 | System.out.println("Status: " + result.getStatus()); 90 | return result; 91 | } 92 | 93 | private byte[] readFile() throws IOException { 94 | File file = new File(getClass().getClassLoader().getResource("sampleToken.zip").getFile()); 95 | return readBytes(file); 96 | } 97 | 98 | private byte[] readBytes(File file) throws IOException { 99 | long length = file.length(); 100 | if (length > Integer.MAX_VALUE) throw new OutOfMemoryError("File is too big!!"); 101 | byte[] result = new byte[(int) length]; 102 | try (DataInputStream inputStream = new DataInputStream(new FileInputStream(file))) { 103 | inputStream.readFully(result); 104 | } 105 | return result; 106 | } 107 | 108 | public static void main(String[] args) throws IOException { 109 | new DeploySampleToken().sendTransaction(); 110 | } 111 | } 112 | -------------------------------------------------------------------------------- /samples/src/main/java/foundation/icon/icx/token/GetTokenBalance.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 ICON Foundation. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package foundation.icon.icx.token; 18 | 19 | import foundation.icon.icx.Call; 20 | import foundation.icon.icx.Constants; 21 | import foundation.icon.icx.IconService; 22 | import foundation.icon.icx.data.Address; 23 | import foundation.icon.icx.data.TransactionResult; 24 | import foundation.icon.icx.transport.http.HttpProvider; 25 | import foundation.icon.icx.transport.jsonrpc.RpcItem; 26 | import foundation.icon.icx.transport.jsonrpc.RpcObject; 27 | import foundation.icon.icx.transport.jsonrpc.RpcValue; 28 | import okhttp3.OkHttpClient; 29 | import okhttp3.logging.HttpLoggingInterceptor; 30 | 31 | import java.io.IOException; 32 | import java.math.BigInteger; 33 | 34 | public class GetTokenBalance { 35 | 36 | private IconService iconService; 37 | 38 | private GetTokenBalance() { 39 | HttpLoggingInterceptor logging = new HttpLoggingInterceptor(); 40 | logging.setLevel(HttpLoggingInterceptor.Level.BODY); 41 | OkHttpClient httpClient = new OkHttpClient.Builder() 42 | .addInterceptor(logging) 43 | .build(); 44 | iconService = new IconService(new HttpProvider(httpClient, Constants.SERVER_URL, 3)); 45 | } 46 | 47 | private void query(Address scoreAddress) throws IOException { 48 | Address ownerAddress = Constants.testAddress1; 49 | 50 | RpcObject params = new RpcObject.Builder() 51 | .put("_owner", new RpcValue(ownerAddress)) 52 | .build(); 53 | 54 | Call call = new Call.Builder() 55 | .to(scoreAddress) 56 | .method("balanceOf") 57 | .params(params) 58 | .build(); 59 | 60 | RpcItem result = iconService.call(call).execute(); 61 | System.out.println("balance: "+ result.asInteger()); 62 | } 63 | 64 | public static void main(String[] args) throws IOException { 65 | TransactionResult result = new DeploySampleToken().sendTransaction(); 66 | if (!BigInteger.ONE.equals(result.getStatus())) { 67 | System.out.println("Deploy failed!"); 68 | return; 69 | } 70 | Address scoreAddress = new Address(result.getScoreAddress()); 71 | new SendTokenTransaction().sendTransaction(scoreAddress); 72 | new GetTokenBalance().query(scoreAddress); 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /samples/src/main/java/foundation/icon/icx/token/SendTokenTransaction.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018 ICON Foundation. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package foundation.icon.icx.token; 18 | 19 | import foundation.icon.icx.*; 20 | import foundation.icon.icx.data.Address; 21 | import foundation.icon.icx.data.Bytes; 22 | import foundation.icon.icx.data.IconAmount; 23 | import foundation.icon.icx.data.TransactionResult; 24 | import foundation.icon.icx.transport.http.HttpProvider; 25 | import foundation.icon.icx.transport.jsonrpc.RpcObject; 26 | import foundation.icon.icx.transport.jsonrpc.RpcValue; 27 | import okhttp3.OkHttpClient; 28 | import okhttp3.logging.HttpLoggingInterceptor; 29 | 30 | import java.io.IOException; 31 | import java.math.BigInteger; 32 | 33 | public class SendTokenTransaction { 34 | 35 | private IconService iconService; 36 | private Wallet wallet; 37 | 38 | public SendTokenTransaction() { 39 | HttpLoggingInterceptor logging = new HttpLoggingInterceptor(); 40 | logging.setLevel(HttpLoggingInterceptor.Level.BODY); 41 | OkHttpClient httpClient = new OkHttpClient.Builder() 42 | .addInterceptor(logging) 43 | .build(); 44 | iconService = new IconService(new HttpProvider(httpClient, Constants.SERVER_URL, 3)); 45 | wallet = KeyWallet.load(Constants.privateKey); 46 | } 47 | 48 | public void sendTransaction(Address scoreAddress) throws IOException { 49 | BigInteger networkId = new BigInteger("3"); 50 | Address fromAddress = wallet.getAddress(); 51 | Address toAddress = Constants.testAddress1; 52 | BigInteger value = IconAmount.of("1", 18).toLoop(); 53 | long timestamp = System.currentTimeMillis() * 1000L; 54 | BigInteger nonce = new BigInteger("1"); 55 | String methodName = "transfer"; 56 | 57 | RpcObject params = new RpcObject.Builder() 58 | .put("_to", new RpcValue(toAddress)) 59 | .put("_value", new RpcValue(value)) 60 | .build(); 61 | 62 | // make a raw transaction without the stepLimit 63 | Transaction transaction = TransactionBuilder.newBuilder() 64 | .nid(networkId) 65 | .from(fromAddress) 66 | .to(scoreAddress) 67 | .timestamp(new BigInteger(Long.toString(timestamp))) 68 | .nonce(nonce) 69 | .call(methodName) 70 | .params(params) 71 | .build(); 72 | 73 | // get an estimated step value 74 | BigInteger estimatedStep = iconService.estimateStep(transaction).execute(); 75 | 76 | // make a signed transaction with the same raw transaction and the estimated step 77 | SignedTransaction signedTransaction = new SignedTransaction(transaction, wallet, estimatedStep); 78 | Bytes hash = iconService.sendTransaction(signedTransaction).execute(); 79 | System.out.println("txHash: " + hash); 80 | TransactionResult result = Utils.getTransactionResult(iconService, hash); 81 | System.out.println("status: " + result.getStatus()); 82 | } 83 | 84 | public static void main(String[] args) throws IOException { 85 | TransactionResult result = new DeploySampleToken().sendTransaction(); 86 | if (BigInteger.ONE.equals(result.getStatus())) { 87 | Address scoreAddress = new Address(result.getScoreAddress()); 88 | new SendTokenTransaction().sendTransaction(scoreAddress); 89 | } else { 90 | System.out.println("Deploy failed!"); 91 | } 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /samples/src/main/resources/sampleToken.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/icon-project/icon-sdk-java/9a50cb1cc18c4fdb21615ed7c42a8b4a97dd8d4f/samples/src/main/resources/sampleToken.zip -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'icon-sdk' 2 | include 'library' 3 | include 'samples' 4 | include 'quickstart' 5 | 6 | --------------------------------------------------------------------------------