├── .gitignore ├── LICENSE ├── README.md ├── build.gradle ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── hello-world ├── build.gradle └── src │ ├── main │ └── java │ │ └── com │ │ └── iconloop │ │ └── score │ │ └── example │ │ └── HelloWorld.java │ └── test │ └── java │ └── com │ └── iconloop │ └── score │ └── example │ └── HelloWorldTest.java ├── irc2-token ├── build.gradle └── src │ ├── main │ └── java │ │ └── com │ │ └── iconloop │ │ └── score │ │ └── example │ │ ├── IRC2BasicToken.java │ │ └── IRC2BurnableToken.java │ └── test │ └── java │ └── com │ └── iconloop │ └── score │ └── example │ ├── IRC2BasicTest.java │ └── IRC2BurnableTest.java ├── irc3-token ├── build.gradle └── src │ ├── intTest │ └── java │ │ └── foundation │ │ └── icon │ │ └── test │ │ ├── cases │ │ └── IRC3TokenTest.java │ │ └── score │ │ └── IRC3TokenScore.java │ ├── main │ └── java │ │ └── com │ │ └── iconloop │ │ └── score │ │ └── example │ │ └── IRC3BasicToken.java │ └── test │ └── java │ └── com │ └── iconloop │ └── score │ └── example │ └── IRC3BasicTest.java ├── irc31-token ├── build.gradle └── src │ ├── main │ └── java │ │ └── com │ │ └── iconloop │ │ └── score │ │ └── example │ │ └── IRC31MultiToken.java │ └── test │ └── java │ └── com │ └── iconloop │ └── score │ └── example │ └── IRC31MultiTokenTest.java ├── multisig-wallet ├── README.md ├── build.gradle └── src │ ├── intTest │ └── java │ │ └── foundation │ │ └── icon │ │ └── test │ │ ├── cases │ │ └── MultiSigWalletTest.java │ │ └── score │ │ ├── HelloWorld.java │ │ └── MultiSigWalletScore.java │ ├── main │ └── java │ │ └── com │ │ └── iconloop │ │ └── score │ │ └── example │ │ ├── MultiSigWallet.java │ │ └── Transaction.java │ └── test │ └── java │ └── com │ └── iconloop │ └── score │ └── example │ └── MultiSigWalletTest.java ├── sample-crowdsale ├── build.gradle └── src │ ├── intTest │ └── java │ │ └── foundation │ │ └── icon │ │ └── test │ │ ├── cases │ │ └── CrowdsaleTest.java │ │ └── score │ │ ├── CrowdSaleScore.java │ │ └── SampleTokenScore.java │ ├── main │ └── java │ │ └── com │ │ └── iconloop │ │ └── score │ │ └── example │ │ └── SampleCrowdsale.java │ └── test │ └── java │ └── com │ └── iconloop │ └── score │ └── example │ └── SampleCrowdsaleTest.java ├── sample-token ├── build.gradle └── src │ ├── main │ └── java │ │ └── com │ │ └── iconloop │ │ └── score │ │ └── example │ │ └── SampleToken.java │ └── test │ └── java │ └── com │ └── iconloop │ └── score │ └── example │ └── SampleTokenTest.java ├── settings.gradle └── testinteg ├── README.md ├── build.gradle ├── conf ├── env.props └── godWallet.json ├── gradle.properties └── src └── main └── java └── foundation └── icon └── test ├── Constants.java ├── Env.java ├── EventLog.java ├── Log.java ├── ResultTimeoutException.java ├── TestBase.java ├── TransactionFailureException.java ├── TransactionHandler.java ├── score ├── ChainScore.java └── Score.java └── util └── ZipFile.java /.gitignore: -------------------------------------------------------------------------------- 1 | .gradle 2 | .idea 3 | build 4 | out 5 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2020 ICON Foundation 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Java SCORE Examples 2 | 3 | This repository contains SCORE (Smart Contract for ICON) examples written in Java. 4 | 5 | ## Requirements 6 | 7 | You need to install JDK 11 or later version. Visit [OpenJDK.net](http://openjdk.java.net/) for prebuilt binaries. 8 | Or you can install a proper OpenJDK package from your OS vendors. 9 | 10 | In macOS: 11 | ``` 12 | $ brew tap AdoptOpenJDK/openjdk 13 | $ brew cask install adoptopenjdk11 14 | ``` 15 | 16 | In Linux (Ubuntu 20.04): 17 | ``` 18 | $ sudo apt install openjdk-11-jdk 19 | ``` 20 | 21 | ## How to Run 22 | 23 | ### 1. Build the project 24 | 25 | ``` 26 | $ ./gradlew build 27 | ``` 28 | The compiled jar bundle will be generated at `./hello-world/build/libs/hello-world-0.1.0.jar`. 29 | 30 | ### 2. Optimize the jar 31 | 32 | You need to optimize your jar bundle before you deploy it to local or ICON networks. 33 | This involves some pre-processing to ensure the actual deployment successful. 34 | 35 | `gradle-javaee-plugin` is a Gradle plugin to automate the process of generating the optimized jar bundle. 36 | Run the `optimizedJar` task to generate the optimized jar bundle. 37 | 38 | ``` 39 | $ ./gradlew optimizedJar 40 | ``` 41 | The output jar will be located at `./hello-world/build/libs/hello-world-0.1.0-optimized.jar`. 42 | 43 | ### 3. Deploy the optimized jar 44 | 45 | #### Using `goloop` CLI command 46 | 47 | Now you can deploy the optimized jar to ICON networks that support the Java SCORE execution environment. 48 | Assuming you are running a local network that is listening on port 9082 for incoming requests, 49 | you can create a deploy transaction with the optimized jar and deploy it to the local network as follows. 50 | 51 | ``` 52 | $ goloop rpc sendtx deploy ./hello-world/build/libs/hello-world-0.1.0-optimized.jar \ 53 | --uri http://localhost:9082/api/v3 \ 54 | --key_store --key_password \ 55 | --nid 3 --step_limit=1000000 \ 56 | --content_type application/java \ 57 | --param name=Alice 58 | ``` 59 | 60 | **[Note]** The content type should be `application/java` instead of `application/zip` to differentiate it with the Python SCORE deployment. 61 | 62 | #### Using `deployJar` extension 63 | 64 | Starting with version `0.7.2` of `gradle-javaee-plugin`, you can also use the `deployJar` extension to specify all the information required for deployment. 65 | 66 | ```groovy 67 | deployJar { 68 | endpoints { 69 | local { 70 | uri = 'http://localhost:9082/api/v3' 71 | nid = 3 72 | } 73 | } 74 | keystore = rootProject.hasProperty('keystoreName') ? "$keystoreName" : '' 75 | password = rootProject.hasProperty('keystorePass') ? "$keystorePass" : '' 76 | parameters { 77 | arg('name', 'Alice') 78 | } 79 | } 80 | ``` 81 | 82 | Now you can run `deployToLocal` task as follows. 83 | 84 | ``` 85 | $ ./gradlew hello-world:deployToLocal -PkeystoreName= -PkeystorePass= 86 | 87 | > Task :hello-world:deployToLocal 88 | >>> deploy to http://localhost:9082/api/v3 89 | >>> optimizedJar = ./hello-world/build/libs/hello-world-0.1.0-optimized.jar 90 | >>> keystore = 91 | Succeeded to deploy: 0x699534c9f5277539e1b572420819141c7cf3e52a6904a34b2a2cdb05b95ab0a3 92 | SCORE address: cxd6d044b01db068cded47bde12ed4f15a6da9f1d8 93 | ``` 94 | 95 | **[Note]** If you want to deploy to Lisbon testnet, use the following configuration for the endpoint and run `deployToLisbon` task. 96 | ```groovy 97 | deployJar { 98 | endpoints { 99 | lisbon { 100 | uri = 'https://lisbon.net.solidwallet.io/api/v3' 101 | nid = 0x2 102 | } 103 | ... 104 | } 105 | } 106 | ``` 107 | 108 | ### 4. Verify the execution 109 | 110 | Check the deployed SCORE address first using the `txresult` command. 111 | ``` 112 | $ goloop rpc txresult --uri http://localhost:9082/api/v3 113 | { 114 | ... 115 | "scoreAddress": "cxaa736426a9caed44c59520e94da2d64888d9241b", 116 | ... 117 | } 118 | ``` 119 | 120 | Then you can invoke `getGreeting` method via the following `call` command. 121 | ``` 122 | $ goloop rpc call --to --method getGreeting --uri http://localhost:9082/api/v3 123 | "Hello Alice!" 124 | ``` 125 | 126 | ## Testing 127 | 128 | Two testing frameworks are provided as to be used for different purposes: 129 | one is for unit testing and the other is for integration testing. 130 | 131 | ### Unit testing 132 | 133 | ~~`testsvc` subproject can be used for the unit testing, 134 | and it provides a SCORE execution emulation layer can be integrated with the JUnit 5 and Mockito frameworks.~~ 135 | Now [`javaee-unittest`](https://github.com/icon-project/javaee-unittest) artifact is used to perform the unit testing. 136 | 137 | Here are the sample unit test cases. 138 | - [HelloWorld](hello-world/src/test/java/com/iconloop/score/example/AppTest.java) 139 | - [MultisigWallet](multisig-wallet/src/test/java/com/iconloop/score/example/MultiSigWalletTest.java) 140 | - [Crowdsale](sample-crowdsale/src/test/java/com/iconloop/score/example/SampleCrowdsaleTest.java) 141 | - [IRC3Token (NFT)](irc3-token/src/test/java/com/iconloop/score/example/IRC3BasicTest.java) 142 | - [IRC2BurnableToken](irc2-token/src/test/java/com/iconloop/score/example/IRC2BurnableTest.java) 143 | - [SampleToken](sample-token/src/test/java/com/iconloop/score/example/SampleTokenTest.java) 144 | 145 | ### Integration testing 146 | 147 | [`testinteg`](testinteg) subproject can be used for the integration testing. 148 | It assumes there is a running ICON network (either local or remote) that can be connected for the testing. 149 | It uses the [ICON SDK for Java](https://github.com/icon-project/icon-sdk-java) to interact with the network. 150 | The [default configuration](testinteg/conf/env.props) is for [gochain-local](https://github.com/icon-project/gochain-local) network. 151 | If you want to change this configuration, either modify the configuration file directly 152 | or set the proper system property (`env.props`) when you run the integration testing 153 | (see [example](https://github.com/icon-project/java-score-examples/blob/14c4df50b146c12c27a040410411271e87efa94a/multisig-wallet/build.gradle#L69)). 154 | 155 | Here are the sample integration test cases. 156 | - [MultisigWallet](multisig-wallet/src/intTest/java/foundation/icon/test/cases/MultiSigWalletTest.java) 157 | - [Crowdsale](sample-crowdsale/src/intTest/java/foundation/icon/test/cases/CrowdsaleTest.java) 158 | - [IRC3Token (NFT)](irc3-token/src/intTest/java/foundation/icon/test/cases/IRC3TokenTest.java) 159 | 160 | Use `integrationTest` task to run the integration testing. 161 | Here is the example of invoking the MultisigWallet integration testing. 162 | ``` 163 | $ ./gradlew multisig-wallet:integrationTest 164 | ``` 165 | 166 | ## Java SCORE Structure 167 | 168 | 169 | ### Comparison to Python SCORE 170 | 171 | | Name | Python SCORE | Java SCORE | 172 | |--------------------|------------------------------|-----------------------------| 173 | | External decorator | `@external` | `@External` | 174 | | - (readonly) | `@external(readonly=True)` | `@External(readonly=true)` | 175 | | Payable decorator | `@payable` | `@Payable` | 176 | | Eventlog decorator | `@eventlog` | `@EventLog` | 177 | | - (indexed) | `@eventlog(indexed=1)` | `@EventLog(indexed=1)` | 178 | | fallback signature | `def fallback` | `void fallback()` | 179 | | SCORE initialize | override `on_install` method | define a public constructor | 180 | | Default parameters | native language support | `@Optional` | 181 | 182 | **[NOTE]** All external Java methods must have a `public` modifier, and should be instance methods. 183 | 184 | ### How to invoke a external method of another SCORE 185 | 186 | One SCORE can invoke an external method of another SCORE using the following APIs. 187 | 188 | ```java 189 | // [package score.Context] 190 | public static Object call(Address targetAddress, String method, Object... params); 191 | 192 | public static Object call(BigInteger value, 193 | Address targetAddress, String method, Object... params); 194 | ``` 195 | 196 | The following example is for calling `tokenFallback`. 197 | ```java 198 | if (_to.isContract()) { 199 | Context.call(_to, "tokenFallback", _from, _value, dataBytes); 200 | } 201 | ``` 202 | 203 | ## References 204 | 205 | * [Java SCORE Overview](https://docs.google.com/presentation/d/1S24vCTcPJ5GOGfPu1sApJLwyOTTdgYEf/export/pdf) 206 | * [SCORE API document](https://www.javadoc.io/doc/foundation.icon/javaee-api) 207 | * [Gradle plugin for JavaEE](https://github.com/icon-project/gradle-javaee-plugin) 208 | * [A Java SCORE Library for Standard Tokens](https://github.com/sink772/javaee-tokens) 209 | * [scorex package for Java SCORE](https://github.com/icon-project/javaee-scorex) 210 | * [An Unit Testing Framework for Java SCORE](https://github.com/icon-project/javaee-unittest) 211 | * [A fast and small JSON parser and writer for Java](https://github.com/sink772/minimal-json) 212 | * [`goloop` CLI command reference](https://github.com/icon-project/goloop/blob/master/doc/goloop_cli.md) 213 | 214 | ## License 215 | 216 | This project is available under the [Apache License, Version 2.0](LICENSE). 217 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | buildscript { 2 | repositories { 3 | mavenCentral() 4 | } 5 | dependencies { 6 | classpath 'foundation.icon:gradle-javaee-plugin:0.8.5' 7 | } 8 | } 9 | 10 | subprojects { 11 | repositories { 12 | mavenCentral() 13 | } 14 | 15 | apply plugin: 'java' 16 | apply plugin: 'foundation.icon.javaee' 17 | 18 | java { 19 | sourceCompatibility = JavaVersion.VERSION_11 20 | targetCompatibility = JavaVersion.VERSION_11 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/icon-project/java-score-examples/a746103c4cab714c8bdd0644cbfa4d27e4e99f3f/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-7.6.1-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | # 4 | # Copyright 2015 the original author or authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | ## 21 | ## Gradle start up script for UN*X 22 | ## 23 | ############################################################################## 24 | 25 | # Attempt to set APP_HOME 26 | # Resolve links: $0 may be a link 27 | PRG="$0" 28 | # Need this for relative symlinks. 29 | while [ -h "$PRG" ] ; do 30 | ls=`ls -ld "$PRG"` 31 | link=`expr "$ls" : '.*-> \(.*\)$'` 32 | if expr "$link" : '/.*' > /dev/null; then 33 | PRG="$link" 34 | else 35 | PRG=`dirname "$PRG"`"/$link" 36 | fi 37 | done 38 | SAVED="`pwd`" 39 | cd "`dirname \"$PRG\"`/" >/dev/null 40 | APP_HOME="`pwd -P`" 41 | cd "$SAVED" >/dev/null 42 | 43 | APP_NAME="Gradle" 44 | APP_BASE_NAME=`basename "$0"` 45 | 46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 48 | 49 | # Use the maximum available, or set MAX_FD != -1 to use that value. 50 | MAX_FD="maximum" 51 | 52 | warn () { 53 | echo "$*" 54 | } 55 | 56 | die () { 57 | echo 58 | echo "$*" 59 | echo 60 | exit 1 61 | } 62 | 63 | # OS specific support (must be 'true' or 'false'). 64 | cygwin=false 65 | msys=false 66 | darwin=false 67 | nonstop=false 68 | case "`uname`" in 69 | CYGWIN* ) 70 | cygwin=true 71 | ;; 72 | Darwin* ) 73 | darwin=true 74 | ;; 75 | MINGW* ) 76 | msys=true 77 | ;; 78 | NONSTOP* ) 79 | nonstop=true 80 | ;; 81 | esac 82 | 83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 84 | 85 | 86 | # Determine the Java command to use to start the JVM. 87 | if [ -n "$JAVA_HOME" ] ; then 88 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 89 | # IBM's JDK on AIX uses strange locations for the executables 90 | JAVACMD="$JAVA_HOME/jre/sh/java" 91 | else 92 | JAVACMD="$JAVA_HOME/bin/java" 93 | fi 94 | if [ ! -x "$JAVACMD" ] ; then 95 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 96 | 97 | Please set the JAVA_HOME variable in your environment to match the 98 | location of your Java installation." 99 | fi 100 | else 101 | JAVACMD="java" 102 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 103 | 104 | Please set the JAVA_HOME variable in your environment to match the 105 | location of your Java installation." 106 | fi 107 | 108 | # Increase the maximum file descriptors if we can. 109 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 110 | MAX_FD_LIMIT=`ulimit -H -n` 111 | if [ $? -eq 0 ] ; then 112 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 113 | MAX_FD="$MAX_FD_LIMIT" 114 | fi 115 | ulimit -n $MAX_FD 116 | if [ $? -ne 0 ] ; then 117 | warn "Could not set maximum file descriptor limit: $MAX_FD" 118 | fi 119 | else 120 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 121 | fi 122 | fi 123 | 124 | # For Darwin, add options to specify how the application appears in the dock 125 | if $darwin; then 126 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 127 | fi 128 | 129 | # For Cygwin or MSYS, switch paths to Windows format before running java 130 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then 131 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 132 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 133 | 134 | JAVACMD=`cygpath --unix "$JAVACMD"` 135 | 136 | # We build the pattern for arguments to be converted via cygpath 137 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 138 | SEP="" 139 | for dir in $ROOTDIRSRAW ; do 140 | ROOTDIRS="$ROOTDIRS$SEP$dir" 141 | SEP="|" 142 | done 143 | OURCYGPATTERN="(^($ROOTDIRS))" 144 | # Add a user-defined pattern to the cygpath arguments 145 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 146 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 147 | fi 148 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 149 | i=0 150 | for arg in "$@" ; do 151 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 152 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 153 | 154 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 155 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 156 | else 157 | eval `echo args$i`="\"$arg\"" 158 | fi 159 | i=`expr $i + 1` 160 | done 161 | case $i in 162 | 0) set -- ;; 163 | 1) set -- "$args0" ;; 164 | 2) set -- "$args0" "$args1" ;; 165 | 3) set -- "$args0" "$args1" "$args2" ;; 166 | 4) set -- "$args0" "$args1" "$args2" "$args3" ;; 167 | 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 168 | 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 169 | 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 170 | 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 171 | 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 172 | esac 173 | fi 174 | 175 | # Escape application args 176 | save () { 177 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 178 | echo " " 179 | } 180 | APP_ARGS=`save "$@"` 181 | 182 | # Collect all arguments for the java command, following the shell quoting and substitution rules 183 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 184 | 185 | exec "$JAVACMD" "$@" 186 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if "%ERRORLEVEL%" == "0" goto init 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto init 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :init 68 | @rem Get command-line arguments, handling Windows variants 69 | 70 | if not "%OS%" == "Windows_NT" goto win9xME_args 71 | 72 | :win9xME_args 73 | @rem Slurp the command line arguments. 74 | set CMD_LINE_ARGS= 75 | set _SKIP=2 76 | 77 | :win9xME_args_slurp 78 | if "x%~1" == "x" goto execute 79 | 80 | set CMD_LINE_ARGS=%* 81 | 82 | :execute 83 | @rem Setup the command line 84 | 85 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 86 | 87 | 88 | @rem Execute Gradle 89 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 90 | 91 | :end 92 | @rem End local scope for the variables with windows NT shell 93 | if "%ERRORLEVEL%"=="0" goto mainEnd 94 | 95 | :fail 96 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 97 | rem the _cmd.exe /c_ return code! 98 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 99 | exit /b 1 100 | 101 | :mainEnd 102 | if "%OS%"=="Windows_NT" endlocal 103 | 104 | :omega 105 | -------------------------------------------------------------------------------- /hello-world/build.gradle: -------------------------------------------------------------------------------- 1 | version = '0.1.0' 2 | 3 | dependencies { 4 | compileOnly 'foundation.icon:javaee-api:0.9.6' 5 | 6 | testImplementation 'foundation.icon:javaee-unittest:0.12.1' 7 | testImplementation 'org.junit.jupiter:junit-jupiter-api:5.9.3' 8 | testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.9.3' 9 | } 10 | 11 | optimizedJar { 12 | mainClassName = 'com.iconloop.score.example.HelloWorld' 13 | archivesBaseName = 'hello-world' 14 | } 15 | 16 | deployJar { 17 | endpoints { 18 | lisbon { 19 | uri = 'https://lisbon.net.solidwallet.io/api/v3' 20 | nid = 0x2 21 | } 22 | local { 23 | uri = 'http://localhost:9082/api/v3' 24 | nid = 0x3 25 | } 26 | } 27 | keystore = rootProject.hasProperty('keystoreName') ? "$keystoreName" : '' 28 | password = rootProject.hasProperty('keystorePass') ? "$keystorePass" : '' 29 | parameters { 30 | arg('name', 'Alice') 31 | } 32 | } 33 | 34 | test { 35 | useJUnitPlatform() 36 | } 37 | -------------------------------------------------------------------------------- /hello-world/src/main/java/com/iconloop/score/example/HelloWorld.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2020 ICONLOOP Inc. 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 com.iconloop.score.example; 18 | 19 | import score.Context; 20 | import score.annotation.External; 21 | import score.annotation.Payable; 22 | 23 | public class HelloWorld { 24 | private String name; 25 | 26 | public HelloWorld(String name) { 27 | this.name = name; 28 | } 29 | 30 | @External() 31 | public void setName(String name) { 32 | this.name = name; 33 | } 34 | 35 | @External(readonly=true) 36 | public String name() { 37 | return name; 38 | } 39 | 40 | @External(readonly=true) 41 | public String getGreeting() { 42 | String msg = "Hello " + name + "!"; 43 | Context.println(msg); 44 | return msg; 45 | } 46 | 47 | @Payable 48 | public void fallback() { 49 | // just receive incoming funds 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /hello-world/src/test/java/com/iconloop/score/example/HelloWorldTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2020 ICONLOOP Inc. 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 com.iconloop.score.example; 18 | 19 | import com.iconloop.score.test.Account; 20 | import com.iconloop.score.test.ServiceManager; 21 | import com.iconloop.score.test.TestBase; 22 | import org.junit.jupiter.api.Test; 23 | 24 | import static org.junit.jupiter.api.Assertions.assertEquals; 25 | import static org.junit.jupiter.api.Assertions.assertNotNull; 26 | 27 | class HelloWorldTest extends TestBase { 28 | private static final ServiceManager sm = getServiceManager(); 29 | private static final Account owner = sm.createAccount(); 30 | 31 | @Test 32 | void appHasAName() { 33 | final String name = "Alice"; 34 | HelloWorld classUnderTest = new HelloWorld(name); 35 | assertEquals(classUnderTest.name(), name); 36 | } 37 | 38 | @Test 39 | void appHasAGreeting() { 40 | HelloWorld classUnderTest = new HelloWorld("Alice"); 41 | assertNotNull(classUnderTest.getGreeting(), "app should have a greeting"); 42 | } 43 | 44 | @Test 45 | void setName() throws Exception { 46 | final String alice = "Alice"; 47 | var score = sm.deploy(owner, HelloWorld.class, alice); 48 | assertEquals(alice, score.call("name")); 49 | 50 | final String bob = "Bob"; 51 | score.invoke(owner, "setName", bob); 52 | assertEquals(bob, score.call("name")); 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /irc2-token/build.gradle: -------------------------------------------------------------------------------- 1 | version = '0.9.1' 2 | 3 | dependencies { 4 | compileOnly 'foundation.icon:javaee-api:0.9.6' 5 | implementation 'com.github.sink772:javaee-tokens:0.6.4' 6 | 7 | testImplementation 'foundation.icon:javaee-unittest:0.12.1' 8 | testImplementation 'org.mockito:mockito-core:4.11.0' 9 | testImplementation 'org.junit.jupiter:junit-jupiter-api:5.9.3' 10 | testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.9.3' 11 | } 12 | 13 | optimizedJar { 14 | mainClassName = 'com.iconloop.score.example.IRC2BasicToken' 15 | from { 16 | configurations.runtimeClasspath.collect { it.isDirectory() ? it : zipTree(it) } 17 | } 18 | } 19 | 20 | deployJar { 21 | endpoints { 22 | lisbon { 23 | uri = 'https://lisbon.net.solidwallet.io/api/v3' 24 | nid = 0x2 25 | } 26 | local { 27 | uri = 'http://localhost:9082/api/v3' 28 | nid = 0x3 29 | } 30 | } 31 | keystore = rootProject.hasProperty('keystoreName') ? "$keystoreName" : '' 32 | password = rootProject.hasProperty('keystorePass') ? "$keystorePass" : '' 33 | parameters { 34 | arg('_name', 'MyIRC2Token') 35 | arg('_symbol', 'MIT') 36 | arg('_decimals', '0x12') 37 | arg('_initialSupply', '0x3e8') 38 | } 39 | } 40 | 41 | test { 42 | useJUnitPlatform() 43 | } 44 | -------------------------------------------------------------------------------- /irc2-token/src/main/java/com/iconloop/score/example/IRC2BasicToken.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2020 ICONLOOP Inc. 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 com.iconloop.score.example; 18 | 19 | import com.iconloop.score.token.irc2.IRC2Basic; 20 | import score.Context; 21 | 22 | import java.math.BigInteger; 23 | 24 | public class IRC2BasicToken extends IRC2Basic { 25 | public IRC2BasicToken(String _name, String _symbol, int _decimals, BigInteger _initialSupply) { 26 | super(_name, _symbol, _decimals); 27 | 28 | // mint the initial token supply here 29 | Context.require(_initialSupply.compareTo(BigInteger.ZERO) >= 0); 30 | _mint(Context.getCaller(), _initialSupply.multiply(pow10(_decimals))); 31 | } 32 | 33 | private static BigInteger pow10(int exponent) { 34 | BigInteger result = BigInteger.ONE; 35 | for (int i = 0; i < exponent; i++) { 36 | result = result.multiply(BigInteger.TEN); 37 | } 38 | return result; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /irc2-token/src/main/java/com/iconloop/score/example/IRC2BurnableToken.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2020 ICONLOOP Inc. 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 com.iconloop.score.example; 18 | 19 | import com.iconloop.score.token.irc2.IRC2Burnable; 20 | import score.Context; 21 | 22 | import java.math.BigInteger; 23 | 24 | public class IRC2BurnableToken extends IRC2Burnable { 25 | public IRC2BurnableToken(String _name, String _symbol, int _decimals, BigInteger _initialSupply) { 26 | super(_name, _symbol, _decimals); 27 | 28 | // mint the initial token supply here 29 | Context.require(_initialSupply.compareTo(BigInteger.ZERO) >= 0); 30 | _mint(Context.getCaller(), _initialSupply.multiply(pow10(_decimals))); 31 | } 32 | 33 | private static BigInteger pow10(int exponent) { 34 | BigInteger result = BigInteger.ONE; 35 | for (int i = 0; i < exponent; i++) { 36 | result = result.multiply(BigInteger.TEN); 37 | } 38 | return result; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /irc2-token/src/test/java/com/iconloop/score/example/IRC2BasicTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2020 ICONLOOP Inc. 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 com.iconloop.score.example; 18 | 19 | import com.iconloop.score.test.Account; 20 | import com.iconloop.score.test.Score; 21 | import com.iconloop.score.test.ServiceManager; 22 | import com.iconloop.score.test.TestBase; 23 | import org.junit.jupiter.api.BeforeAll; 24 | import org.junit.jupiter.api.Test; 25 | 26 | import java.math.BigInteger; 27 | 28 | import static java.math.BigInteger.TEN; 29 | import static org.junit.jupiter.api.Assertions.assertEquals; 30 | 31 | class IRC2BasicTest extends TestBase { 32 | private static final String name = "MyIRC2Token"; 33 | private static final String symbol = "MIT"; 34 | private static final int decimals = 18; 35 | private static final BigInteger initialSupply = BigInteger.valueOf(1000); 36 | 37 | private static final BigInteger totalSupply = initialSupply.multiply(TEN.pow(decimals)); 38 | private static final ServiceManager sm = getServiceManager(); 39 | private static final Account owner = sm.createAccount(); 40 | private static Score tokenScore; 41 | 42 | @BeforeAll 43 | public static void setup() throws Exception { 44 | tokenScore = sm.deploy(owner, IRC2BasicToken.class, 45 | name, symbol, decimals, initialSupply); 46 | owner.addBalance(symbol, totalSupply); 47 | } 48 | 49 | @Test 50 | void name() { 51 | assertEquals(name, tokenScore.call("name")); 52 | } 53 | 54 | @Test 55 | void symbol() { 56 | assertEquals(symbol, tokenScore.call("symbol")); 57 | } 58 | 59 | @Test 60 | void decimals() { 61 | assertEquals(BigInteger.valueOf(decimals), tokenScore.call("decimals")); 62 | } 63 | 64 | @Test 65 | void totalSupply() { 66 | assertEquals(totalSupply, tokenScore.call("totalSupply")); 67 | } 68 | 69 | @Test 70 | void balanceOf() { 71 | assertEquals(owner.getBalance(symbol), 72 | tokenScore.call("balanceOf", tokenScore.getOwner().getAddress())); 73 | } 74 | 75 | @Test 76 | void transfer() { 77 | Account alice = sm.createAccount(); 78 | BigInteger value = TEN.pow(decimals); 79 | tokenScore.invoke(owner, "transfer", alice.getAddress(), value, "to alice".getBytes()); 80 | owner.subtractBalance(symbol, value); 81 | assertEquals(owner.getBalance(symbol), 82 | tokenScore.call("balanceOf", tokenScore.getOwner().getAddress())); 83 | assertEquals(value, 84 | tokenScore.call("balanceOf", alice.getAddress())); 85 | 86 | // transfer self 87 | tokenScore.invoke(alice, "transfer", alice.getAddress(), value, "self transfer".getBytes()); 88 | assertEquals(value, tokenScore.call("balanceOf", alice.getAddress())); 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /irc2-token/src/test/java/com/iconloop/score/example/IRC2BurnableTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2020 ICONLOOP Inc. 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 com.iconloop.score.example; 18 | 19 | import com.iconloop.score.test.Account; 20 | import com.iconloop.score.test.Score; 21 | import com.iconloop.score.test.ServiceManager; 22 | import com.iconloop.score.test.TestBase; 23 | import org.junit.jupiter.api.BeforeAll; 24 | import org.junit.jupiter.api.Test; 25 | import score.Address; 26 | 27 | import java.math.BigInteger; 28 | 29 | import static java.math.BigInteger.TEN; 30 | import static org.junit.jupiter.api.Assertions.assertEquals; 31 | import static org.mockito.Mockito.spy; 32 | import static org.mockito.Mockito.verify; 33 | 34 | public class IRC2BurnableTest extends TestBase { 35 | private static final String name = "MyIRC2Burnable"; 36 | private static final String symbol = "MIB"; 37 | private static final int decimals = 18; 38 | private static final BigInteger initialSupply = BigInteger.valueOf(1000); 39 | 40 | private static BigInteger totalSupply = initialSupply.multiply(TEN.pow(decimals)); 41 | private static final ServiceManager sm = getServiceManager(); 42 | private static final Account owner = sm.createAccount(); 43 | private static Score tokenScore; 44 | private static IRC2BurnableToken tokenSpy; 45 | 46 | @BeforeAll 47 | public static void setup() throws Exception { 48 | tokenScore = sm.deploy(owner, IRC2BurnableToken.class, 49 | name, symbol, decimals, initialSupply); 50 | owner.addBalance(symbol, totalSupply); 51 | 52 | // setup spy object against the tokenScore object 53 | tokenSpy = (IRC2BurnableToken) spy(tokenScore.getInstance()); 54 | tokenScore.setInstance(tokenSpy); 55 | } 56 | 57 | @Test 58 | void burn() { 59 | final Address zeroAddress = new Address(new byte[Address.LENGTH]); 60 | Account alice = sm.createAccount(); 61 | alice.addBalance(symbol, transferToken(owner, alice, TEN)); 62 | assertEquals(totalSupply, tokenScore.call("totalSupply")); 63 | 64 | // burn one token 65 | BigInteger amount = TEN.pow(decimals); 66 | tokenScore.invoke(alice, "burn", amount); 67 | alice.subtractBalance(symbol, amount); 68 | totalSupply = totalSupply.subtract(amount); 69 | assertEquals(alice.getBalance(symbol), tokenScore.call("balanceOf", alice.getAddress())); 70 | assertEquals(totalSupply, tokenScore.call("totalSupply")); 71 | verify(tokenSpy).Transfer(alice.getAddress(), zeroAddress, amount, "burn".getBytes()); 72 | 73 | // burn all the tokens 74 | amount = (BigInteger) tokenScore.call("balanceOf", alice.getAddress()); 75 | tokenScore.invoke(alice, "burn", amount); 76 | totalSupply = totalSupply.subtract(amount); 77 | assertEquals(BigInteger.ZERO, tokenScore.call("balanceOf", alice.getAddress())); 78 | assertEquals(totalSupply, tokenScore.call("totalSupply")); 79 | verify(tokenSpy).Transfer(alice.getAddress(), zeroAddress, amount, "burn".getBytes()); 80 | } 81 | 82 | BigInteger transferToken(Account from, Account to, BigInteger tokenAmount) { 83 | BigInteger value = TEN.pow(decimals).multiply(tokenAmount); 84 | tokenScore.invoke(from, "transfer", to.getAddress(), value, "data".getBytes()); 85 | from.subtractBalance(symbol, value); 86 | assertEquals(from.getBalance(symbol), 87 | tokenScore.call("balanceOf", from.getAddress())); 88 | assertEquals(value, 89 | tokenScore.call("balanceOf", to.getAddress())); 90 | return value; 91 | } 92 | } 93 | -------------------------------------------------------------------------------- /irc3-token/build.gradle: -------------------------------------------------------------------------------- 1 | version = '0.9.0' 2 | 3 | // for integration tests 4 | sourceSets { 5 | intTest {} 6 | } 7 | configurations { 8 | intTestImplementation.extendsFrom testImplementation 9 | intTestRuntimeOnly.extendsFrom testRuntimeOnly 10 | } 11 | 12 | dependencies { 13 | compileOnly 'foundation.icon:javaee-api:0.9.6' 14 | implementation 'com.github.sink772:javaee-tokens:0.6.4' 15 | 16 | testImplementation 'foundation.icon:javaee-unittest:0.12.1' 17 | testImplementation 'org.junit.jupiter:junit-jupiter-api:5.9.3' 18 | testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.9.3' 19 | 20 | intTestImplementation 'foundation.icon:javaee-integration-test:0.9.0' 21 | intTestImplementation 'foundation.icon:icon-sdk:2.5.1' 22 | } 23 | 24 | optimizedJar { 25 | mainClassName = 'com.iconloop.score.example.IRC3BasicToken' 26 | from { 27 | configurations.runtimeClasspath.collect { it.isDirectory() ? it : zipTree(it) } 28 | } 29 | } 30 | 31 | deployJar { 32 | endpoints { 33 | lisbon { 34 | uri = 'https://lisbon.net.solidwallet.io/api/v3' 35 | nid = 0x2 36 | } 37 | local { 38 | uri = 'http://localhost:9082/api/v3' 39 | nid = 0x3 40 | } 41 | } 42 | keystore = rootProject.hasProperty('keystoreName') ? "$keystoreName" : '' 43 | password = rootProject.hasProperty('keystorePass') ? "$keystorePass" : '' 44 | parameters { 45 | arg('_name', 'MyIRC3Token') 46 | arg('_symbol', 'NFT') 47 | } 48 | } 49 | 50 | test { 51 | useJUnitPlatform() 52 | } 53 | 54 | task integrationTest(type: Test, dependsOn: optimizedJar) { 55 | useJUnitPlatform() 56 | description = 'Runs integration tests.' 57 | group = 'verification' 58 | 59 | testClassesDirs = sourceSets.intTest.output.classesDirs 60 | classpath = sourceSets.intTest.runtimeClasspath 61 | testLogging.showStandardStreams = true 62 | 63 | // use the common config files 64 | systemProperty('env.props', new File(project(':testinteg').projectDir, 'conf/env.props')) 65 | 66 | def prefix = 'score.path.' 67 | systemProperty(prefix + project.name, optimizedJar.outputJarName) 68 | } 69 | -------------------------------------------------------------------------------- /irc3-token/src/intTest/java/foundation/icon/test/cases/IRC3TokenTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2020 ICONLOOP Inc. 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.test.cases; 18 | 19 | import foundation.icon.icx.IconService; 20 | import foundation.icon.icx.KeyWallet; 21 | import foundation.icon.icx.data.Address; 22 | import foundation.icon.icx.data.Bytes; 23 | import foundation.icon.icx.transport.http.HttpProvider; 24 | import foundation.icon.icx.transport.jsonrpc.RpcError; 25 | import foundation.icon.test.Env; 26 | import foundation.icon.test.TestBase; 27 | import foundation.icon.test.TransactionHandler; 28 | import foundation.icon.test.score.IRC3TokenScore; 29 | import org.junit.jupiter.api.AfterAll; 30 | import org.junit.jupiter.api.BeforeAll; 31 | import org.junit.jupiter.api.Test; 32 | 33 | import java.math.BigInteger; 34 | import java.security.SecureRandom; 35 | 36 | import static foundation.icon.test.Env.LOG; 37 | import static org.junit.jupiter.api.Assertions.assertEquals; 38 | import static org.junit.jupiter.api.Assertions.assertThrows; 39 | 40 | public class IRC3TokenTest extends TestBase { 41 | private static final boolean DEBUG = true; 42 | private static final Address ZERO_ADDRESS = new Address("hx0000000000000000000000000000000000000000"); 43 | private static TransactionHandler txHandler; 44 | private static SecureRandom secureRandom; 45 | private static KeyWallet[] wallets; 46 | private static KeyWallet ownerWallet, caller; 47 | 48 | @BeforeAll 49 | static void setup() throws Exception { 50 | Env.Chain chain = Env.getDefaultChain(); 51 | IconService iconService = new IconService(new HttpProvider(chain.getEndpointURL(3))); 52 | txHandler = new TransactionHandler(iconService, chain); 53 | secureRandom = new SecureRandom(); 54 | 55 | // init wallets 56 | wallets = new KeyWallet[2]; 57 | BigInteger amount = ICX.multiply(BigInteger.valueOf(50)); 58 | for (int i = 0; i < wallets.length; i++) { 59 | wallets[i] = KeyWallet.create(); 60 | txHandler.transfer(wallets[i].getAddress(), amount); 61 | } 62 | for (KeyWallet wallet : wallets) { 63 | ensureIcxBalance(txHandler, wallet.getAddress(), BigInteger.ZERO, amount); 64 | } 65 | ownerWallet = wallets[0]; 66 | caller = wallets[1]; 67 | } 68 | 69 | @AfterAll 70 | static void shutdown() throws Exception { 71 | for (KeyWallet wallet : wallets) { 72 | txHandler.refundAll(wallet); 73 | } 74 | } 75 | 76 | @Test 77 | public void testIRC3Token() throws Exception { 78 | // 1. deploy 79 | IRC3TokenScore tokenScore = IRC3TokenScore.mustDeploy(txHandler, ownerWallet); 80 | 81 | // 2. initial check 82 | LOG.infoEntering("initial check"); 83 | assertEquals(BigInteger.ZERO, tokenScore.balanceOf(ownerWallet.getAddress())); 84 | assertEquals(BigInteger.ZERO, tokenScore.balanceOf(caller.getAddress())); 85 | assertEquals(BigInteger.ZERO, tokenScore.totalSupply()); 86 | LOG.infoExiting(); 87 | 88 | // 3. mint some tokens 89 | LOG.infoEntering("mint some tokens"); 90 | BigInteger[] tokenId = new BigInteger[] { 91 | new BigInteger(getRandomBytes(8)), 92 | new BigInteger(getRandomBytes(8)), 93 | new BigInteger(getRandomBytes(8)), 94 | new BigInteger(getRandomBytes(8)), 95 | }; 96 | Bytes[] ids = new Bytes[tokenId.length]; 97 | for (int i = 0; i < ids.length; i++) { 98 | ids[i] = tokenScore.mint(ownerWallet, tokenId[i]); 99 | } 100 | for (Bytes id : ids) { 101 | assertSuccess(txHandler.getResult(id)); 102 | } 103 | assertEquals(BigInteger.valueOf(tokenId.length), tokenScore.balanceOf(ownerWallet.getAddress())); 104 | assertEquals(BigInteger.valueOf(tokenId.length), tokenScore.totalSupply()); 105 | showTokenStatus(tokenScore); 106 | LOG.infoExiting(); 107 | 108 | // 4. transfer and check 109 | LOG.infoEntering("transfer and check"); 110 | BigInteger token = tokenId[0]; 111 | assertEquals(ownerWallet.getAddress(), tokenScore.ownerOf(token)); 112 | ids[0] = tokenScore.transfer(ownerWallet, caller.getAddress(), token); 113 | assertSuccess(txHandler.getResult(ids[0])); 114 | assertEquals(caller.getAddress(), tokenScore.ownerOf(token)); 115 | assertEquals(BigInteger.ONE, tokenScore.balanceOf(caller.getAddress())); 116 | assertEquals(BigInteger.valueOf(tokenId.length-1), tokenScore.balanceOf(ownerWallet.getAddress())); 117 | assertEquals(BigInteger.valueOf(tokenId.length), tokenScore.totalSupply()); 118 | assertEquals(token, tokenScore.tokenOfOwnerByIndex(caller.getAddress(), 0)); 119 | assertEquals(tokenId[tokenId.length-1], tokenScore.tokenOfOwnerByIndex(ownerWallet.getAddress(), 0)); 120 | showTokenStatus(tokenScore); 121 | LOG.infoExiting(); 122 | 123 | // 5. approve and check 124 | LOG.infoEntering("approve and check"); 125 | token = tokenId[1]; 126 | assertEquals(ZERO_ADDRESS, tokenScore.getApproved(token)); 127 | ids[1] = tokenScore.approve(ownerWallet, caller.getAddress(), token); 128 | assertSuccess(txHandler.getResult(ids[1])); 129 | assertEquals(caller.getAddress(), tokenScore.getApproved(token)); 130 | showTokenStatus(tokenScore); 131 | 132 | assertEquals(ownerWallet.getAddress(), tokenScore.ownerOf(token)); 133 | ids[2] = tokenScore.transferFrom(caller, ownerWallet.getAddress(), caller.getAddress(), token); 134 | assertSuccess(txHandler.getResult(ids[2])); 135 | assertEquals(ZERO_ADDRESS, tokenScore.getApproved(token)); 136 | assertEquals(caller.getAddress(), tokenScore.ownerOf(token)); 137 | assertEquals(BigInteger.TWO, tokenScore.balanceOf(caller.getAddress())); 138 | assertEquals(BigInteger.valueOf(tokenId.length-2), tokenScore.balanceOf(ownerWallet.getAddress())); 139 | assertEquals(BigInteger.valueOf(tokenId.length), tokenScore.totalSupply()); 140 | assertEquals(token, tokenScore.tokenOfOwnerByIndex(caller.getAddress(), 1)); 141 | assertEquals(tokenId[tokenId.length-2], tokenScore.tokenOfOwnerByIndex(ownerWallet.getAddress(), 1)); 142 | showTokenStatus(tokenScore); 143 | LOG.infoExiting(); 144 | 145 | // 6. burn and check 146 | LOG.infoEntering("burn and check"); 147 | var balance = tokenScore.balanceOf(ownerWallet.getAddress()); 148 | token = tokenScore.tokenOfOwnerByIndex(ownerWallet.getAddress(), 0); 149 | ids[0] = tokenScore.burn(ownerWallet, token); 150 | assertSuccess(txHandler.getResult(ids[0])); 151 | assertEquals(balance.subtract(BigInteger.ONE), tokenScore.balanceOf(ownerWallet.getAddress())); 152 | assertEquals(BigInteger.valueOf(tokenId.length-1), tokenScore.totalSupply()); 153 | showTokenStatus(tokenScore); 154 | LOG.infoExiting(); 155 | 156 | // 7. negative tests 157 | LOG.infoEntering("negative tests"); 158 | final var nonExistToken = token; // burned token 159 | assertThrows(RpcError.class, () -> tokenScore.ownerOf(nonExistToken)); 160 | assertFailure(txHandler.getResult( 161 | tokenScore.transferFrom(caller, ownerWallet.getAddress(), caller.getAddress(), tokenId[2]))); 162 | LOG.infoExiting(); 163 | } 164 | 165 | private void showTokenStatus(IRC3TokenScore tokenScore) throws Exception { 166 | if (!DEBUG) { return; } 167 | var totalSupply = tokenScore.totalSupply(); 168 | System.out.println(">>> totalSupply = " + totalSupply); 169 | for (int i = 0; i < totalSupply.intValue(); i++) { 170 | var token = tokenScore.tokenByIndex(i); 171 | var owner = tokenScore.ownerOf(token); 172 | var approved = tokenScore.getApproved(token); 173 | System.out.printf(" [%s](%s)<%s>\n", token, owner, 174 | approved.equals(ZERO_ADDRESS) ? "null" : approved); 175 | } 176 | var ownerBalance = tokenScore.balanceOf(ownerWallet.getAddress()); 177 | System.out.println(" == balanceOf owner: " + ownerBalance); 178 | for (int i = 0; i < ownerBalance.intValue(); i++) { 179 | var token = tokenScore.tokenOfOwnerByIndex(ownerWallet.getAddress(), i); 180 | System.out.printf(" -- %d: [%s]\n", i, token); 181 | } 182 | var callerBalance = tokenScore.balanceOf(caller.getAddress()); 183 | System.out.println(" == balanceOf caller: " + callerBalance); 184 | for (int i = 0; i < callerBalance.intValue(); i++) { 185 | var token = tokenScore.tokenOfOwnerByIndex(caller.getAddress(), i); 186 | System.out.printf(" -- %d: [%s]\n", i, token); 187 | } 188 | } 189 | 190 | private byte[] getRandomBytes(int size) { 191 | byte[] bytes = new byte[size]; 192 | secureRandom.nextBytes(bytes); 193 | bytes[0] = 0; // make positive 194 | return bytes; 195 | } 196 | } 197 | -------------------------------------------------------------------------------- /irc3-token/src/intTest/java/foundation/icon/test/score/IRC3TokenScore.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2020 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.test.score; 18 | 19 | import foundation.icon.icx.Wallet; 20 | import foundation.icon.icx.data.Address; 21 | import foundation.icon.icx.data.Bytes; 22 | import foundation.icon.icx.transport.jsonrpc.RpcObject; 23 | import foundation.icon.icx.transport.jsonrpc.RpcValue; 24 | import foundation.icon.test.ResultTimeoutException; 25 | import foundation.icon.test.TransactionFailureException; 26 | import foundation.icon.test.TransactionHandler; 27 | 28 | import java.io.IOException; 29 | import java.math.BigInteger; 30 | 31 | import static foundation.icon.test.Env.LOG; 32 | 33 | public class IRC3TokenScore extends Score { 34 | public IRC3TokenScore(Score other) { 35 | super(other); 36 | } 37 | 38 | public static IRC3TokenScore mustDeploy(TransactionHandler txHandler, Wallet owner) 39 | throws ResultTimeoutException, TransactionFailureException, IOException { 40 | LOG.infoEntering("deploy", "IRC3Token"); 41 | RpcObject params = new RpcObject.Builder() 42 | .put("_name", new RpcValue("IRC3Token")) 43 | .put("_symbol", new RpcValue("NFT")) 44 | .build(); 45 | Score score = txHandler.deploy(owner, getFilePath("irc3-token"), params); 46 | LOG.info("scoreAddr = " + score.getAddress()); 47 | LOG.infoExiting(); 48 | return new IRC3TokenScore(score); 49 | } 50 | 51 | public Address ownerOf(BigInteger tokenId) throws IOException { 52 | RpcObject params = new RpcObject.Builder() 53 | .put("_tokenId", new RpcValue(tokenId)) 54 | .build(); 55 | return call("ownerOf", params).asAddress(); 56 | } 57 | 58 | public Address getApproved(BigInteger tokenId) throws IOException { 59 | RpcObject params = new RpcObject.Builder() 60 | .put("_tokenId", new RpcValue(tokenId)) 61 | .build(); 62 | return call("getApproved", params).asAddress(); 63 | } 64 | 65 | public BigInteger balanceOf(Address owner) throws IOException { 66 | RpcObject params = new RpcObject.Builder() 67 | .put("_owner", new RpcValue(owner)) 68 | .build(); 69 | return call("balanceOf", params).asInteger(); 70 | } 71 | 72 | public BigInteger totalSupply() throws IOException { 73 | return call("totalSupply", null).asInteger(); 74 | } 75 | 76 | public BigInteger tokenByIndex(int index) throws IOException { 77 | RpcObject params = new RpcObject.Builder() 78 | .put("_index", new RpcValue(BigInteger.valueOf(index))) 79 | .build(); 80 | return call("tokenByIndex", params).asInteger(); 81 | } 82 | 83 | public BigInteger tokenOfOwnerByIndex(Address owner, int index) throws IOException { 84 | RpcObject params = new RpcObject.Builder() 85 | .put("_owner", new RpcValue(owner)) 86 | .put("_index", new RpcValue(BigInteger.valueOf(index))) 87 | .build(); 88 | return call("tokenOfOwnerByIndex", params).asInteger(); 89 | } 90 | 91 | public Bytes mint(Wallet wallet, BigInteger tokenId) throws IOException { 92 | RpcObject params = new RpcObject.Builder() 93 | .put("_tokenId", new RpcValue(tokenId)) 94 | .build(); 95 | return invoke(wallet, "mint", params); 96 | } 97 | 98 | public Bytes burn(Wallet wallet, BigInteger tokenId) throws IOException { 99 | RpcObject params = new RpcObject.Builder() 100 | .put("_tokenId", new RpcValue(tokenId)) 101 | .build(); 102 | return invoke(wallet, "burn", params); 103 | } 104 | 105 | public Bytes approve(Wallet wallet, Address to, BigInteger tokenId) throws IOException { 106 | RpcObject params = new RpcObject.Builder() 107 | .put("_to", new RpcValue(to)) 108 | .put("_tokenId", new RpcValue(tokenId)) 109 | .build(); 110 | return invoke(wallet, "approve", params); 111 | } 112 | 113 | public Bytes transfer(Wallet wallet, Address to, BigInteger tokenId) throws IOException { 114 | RpcObject params = new RpcObject.Builder() 115 | .put("_to", new RpcValue(to)) 116 | .put("_tokenId", new RpcValue(tokenId)) 117 | .build(); 118 | return invoke(wallet, "transfer", params); 119 | } 120 | 121 | public Bytes transferFrom(Wallet wallet, Address from, Address to, BigInteger tokenId) throws IOException { 122 | RpcObject params = new RpcObject.Builder() 123 | .put("_from", new RpcValue(from)) 124 | .put("_to", new RpcValue(to)) 125 | .put("_tokenId", new RpcValue(tokenId)) 126 | .build(); 127 | return invoke(wallet, "transferFrom", params); 128 | } 129 | } 130 | -------------------------------------------------------------------------------- /irc3-token/src/main/java/com/iconloop/score/example/IRC3BasicToken.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2020 ICONLOOP Inc. 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 com.iconloop.score.example; 18 | 19 | import com.iconloop.score.token.irc3.IRC3Basic; 20 | import score.Address; 21 | import score.Context; 22 | import score.annotation.External; 23 | 24 | import java.math.BigInteger; 25 | 26 | public class IRC3BasicToken extends IRC3Basic { 27 | public IRC3BasicToken(String _name, String _symbol) { 28 | super(_name, _symbol); 29 | } 30 | 31 | @External 32 | public void mint(BigInteger _tokenId) { 33 | // simple access control - only the contract owner can mint new token 34 | Context.require(Context.getCaller().equals(Context.getOwner())); 35 | super._mint(Context.getCaller(), _tokenId); 36 | } 37 | 38 | @External 39 | public void burn(BigInteger _tokenId) { 40 | // simple access control - only the owner of token can burn it 41 | Address owner = ownerOf(_tokenId); 42 | Context.require(Context.getCaller().equals(owner)); 43 | super._burn(_tokenId); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /irc3-token/src/test/java/com/iconloop/score/example/IRC3BasicTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2020 ICONLOOP Inc. 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 com.iconloop.score.example; 18 | 19 | import com.iconloop.score.test.Account; 20 | import com.iconloop.score.test.Score; 21 | import com.iconloop.score.test.ServiceManager; 22 | import com.iconloop.score.test.TestBase; 23 | import org.junit.jupiter.api.BeforeEach; 24 | import org.junit.jupiter.api.Test; 25 | import score.Address; 26 | import score.UserRevertedException; 27 | 28 | import java.math.BigInteger; 29 | import java.security.SecureRandom; 30 | 31 | import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; 32 | import static org.junit.jupiter.api.Assertions.assertEquals; 33 | import static org.junit.jupiter.api.Assertions.assertThrows; 34 | 35 | public class IRC3BasicTest extends TestBase { 36 | private static final Address ZERO_ADDRESS = new Address(new byte[Address.LENGTH]); 37 | private static final String name = "MyIRC3Token"; 38 | private static final String symbol = "NFT"; 39 | 40 | private static final ServiceManager sm = getServiceManager(); 41 | private static final Account owner = sm.createAccount(); 42 | private Score tokenScore; 43 | private final SecureRandom secureRandom = new SecureRandom(); 44 | 45 | @BeforeEach 46 | public void setup() throws Exception { 47 | tokenScore = sm.deploy(owner, IRC3BasicToken.class, name, symbol); 48 | } 49 | 50 | @Test 51 | void name() { 52 | assertEquals(name, tokenScore.call("name")); 53 | } 54 | 55 | @Test 56 | void symbol() { 57 | assertEquals(symbol, tokenScore.call("symbol")); 58 | } 59 | 60 | private BigInteger getTokenId() { 61 | byte[] bytes = new byte[8]; 62 | secureRandom.nextBytes(bytes); 63 | bytes[0] = 0; // make positive 64 | return new BigInteger(bytes); 65 | } 66 | 67 | private BigInteger mintToken() { 68 | int supply = (int) tokenScore.call("totalSupply"); 69 | var tokenId = getTokenId(); 70 | tokenScore.invoke(owner, "mint", tokenId); 71 | assertEquals(supply + 1, tokenScore.call("totalSupply")); 72 | return tokenId; 73 | } 74 | 75 | @Test 76 | void balanceOf() { 77 | mintToken(); 78 | assertEquals(1, tokenScore.call("balanceOf", owner.getAddress())); 79 | } 80 | 81 | @Test 82 | void ownerOf() { 83 | var tokenId = mintToken(); 84 | assertEquals(owner.getAddress(), tokenScore.call("ownerOf", tokenId)); 85 | } 86 | 87 | @Test 88 | void approve() { 89 | var tokenId = mintToken(); 90 | var alice = sm.createAccount(); 91 | approveToken(owner, alice.getAddress(), tokenId); 92 | } 93 | 94 | private void approveToken(Account owner, Address to, BigInteger tokenId) { 95 | assertEquals(ZERO_ADDRESS, tokenScore.call("getApproved", tokenId)); 96 | tokenScore.invoke(owner, "approve", to, tokenId); 97 | assertEquals(owner.getAddress(), tokenScore.call("ownerOf", tokenId)); 98 | assertEquals(to, tokenScore.call("getApproved", tokenId)); 99 | } 100 | 101 | @Test 102 | void transfer() { 103 | var tokenId = mintToken(); 104 | var alice = sm.createAccount(); 105 | tokenScore.invoke(owner, "transfer", alice.getAddress(), tokenId); 106 | assertEquals(alice.getAddress(), tokenScore.call("ownerOf", tokenId)); 107 | } 108 | 109 | @Test 110 | void transferFrom() { 111 | var tokenId = mintToken(); 112 | var alice = sm.createAccount(); 113 | var bob = sm.createAccount(); 114 | assertThrows(UserRevertedException.class, () -> 115 | tokenScore.invoke(alice, "transferFrom", owner.getAddress(), bob.getAddress(), tokenId)); 116 | approveToken(owner, alice.getAddress(), tokenId); 117 | assertDoesNotThrow(() -> 118 | tokenScore.invoke(alice, "transferFrom", owner.getAddress(), bob.getAddress(), tokenId)); 119 | assertEquals(bob.getAddress(), tokenScore.call("ownerOf", tokenId)); 120 | assertEquals(ZERO_ADDRESS, tokenScore.call("getApproved", tokenId)); 121 | assertDoesNotThrow(() -> 122 | tokenScore.invoke(bob, "transferFrom", bob.getAddress(), alice.getAddress(), tokenId)); 123 | assertEquals(alice.getAddress(), tokenScore.call("ownerOf", tokenId)); 124 | } 125 | 126 | @Test 127 | void burn() { 128 | var tokenId = mintToken(); 129 | var tokenId2 = mintToken(); 130 | var alice = sm.createAccount(); 131 | tokenScore.invoke(owner, "transfer", alice.getAddress(), tokenId); 132 | assertThrows(UserRevertedException.class, () -> 133 | tokenScore.invoke(owner, "burn", tokenId)); 134 | assertDoesNotThrow(() -> 135 | tokenScore.invoke(alice, "burn", tokenId)); 136 | assertEquals(1, tokenScore.call("totalSupply")); 137 | tokenScore.invoke(owner, "burn", tokenId2); 138 | assertEquals(0, tokenScore.call("totalSupply")); 139 | } 140 | } 141 | -------------------------------------------------------------------------------- /irc31-token/build.gradle: -------------------------------------------------------------------------------- 1 | version = '0.1.0' 2 | 3 | dependencies { 4 | compileOnly 'foundation.icon:javaee-api:0.9.6' 5 | implementation 'com.github.sink772:javaee-tokens:0.6.4' 6 | 7 | testImplementation 'foundation.icon:javaee-unittest:0.12.1' 8 | testImplementation 'org.junit.jupiter:junit-jupiter-api:5.9.3' 9 | testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.9.3' 10 | } 11 | 12 | optimizedJar { 13 | mainClassName = 'com.iconloop.score.example.IRC31MultiToken' 14 | from { 15 | configurations.runtimeClasspath.collect { it.isDirectory() ? it : zipTree(it) } 16 | } 17 | } 18 | 19 | deployJar { 20 | endpoints { 21 | lisbon { 22 | uri = 'https://lisbon.net.solidwallet.io/api/v3' 23 | nid = 0x2 24 | } 25 | local { 26 | uri = 'http://localhost:9082/api/v3' 27 | nid = 0x3 28 | } 29 | } 30 | keystore = rootProject.hasProperty('keystoreName') ? "$keystoreName" : '' 31 | password = rootProject.hasProperty('keystorePass') ? "$keystorePass" : '' 32 | } 33 | 34 | test { 35 | useJUnitPlatform() 36 | } 37 | -------------------------------------------------------------------------------- /irc31-token/src/main/java/com/iconloop/score/example/IRC31MultiToken.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2021 ICONLOOP Inc. 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 com.iconloop.score.example; 18 | 19 | import com.iconloop.score.token.irc31.IRC31MintBurn; 20 | import score.annotation.External; 21 | 22 | public class IRC31MultiToken extends IRC31MintBurn { 23 | 24 | @External(readonly=true) 25 | public String name() { 26 | return "IRC31MultiToken"; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /irc31-token/src/test/java/com/iconloop/score/example/IRC31MultiTokenTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2021 ICONLOOP Inc. 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 com.iconloop.score.example; 18 | 19 | import com.iconloop.score.test.Account; 20 | import com.iconloop.score.test.Score; 21 | import com.iconloop.score.test.ServiceManager; 22 | import com.iconloop.score.test.TestBase; 23 | import org.junit.jupiter.api.BeforeEach; 24 | import org.junit.jupiter.api.Test; 25 | 26 | import static org.junit.jupiter.api.Assertions.assertEquals; 27 | 28 | public class IRC31MultiTokenTest extends TestBase { 29 | private static final ServiceManager sm = getServiceManager(); 30 | private static final Account owner = sm.createAccount(); 31 | private Score tokenScore; 32 | 33 | @BeforeEach 34 | public void setup() throws Exception { 35 | tokenScore = sm.deploy(owner, IRC31MultiToken.class); 36 | } 37 | 38 | @Test 39 | void name() { 40 | assertEquals("IRC31MultiToken", tokenScore.call("name")); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /multisig-wallet/README.md: -------------------------------------------------------------------------------- 1 | # Multisignature Wallet SCORE for Java 2 | 3 | This subproject contains the Java implementation of Multisignature Wallet SCORE. 4 | Please visit the [original repository](https://github.com/icon-project/multisig-wallet) written in Python 5 | if you want to know how to interact with the SCORE. 6 | 7 | ## Comparison with Python version 8 | 9 | | Method | Python | Java | Notes | 10 | | ------ | ------ | ---- | ----- | 11 | | `fallback` | O | O | | 12 | | `tokenFallback` | O | O | | 13 | | `submitTransaction` | O | O | | 14 | | `confirmTransaction` | O | O | | 15 | | `revokeTransaction` | O | O | | 16 | | `addWalletOwner` | O | O | | 17 | | `replaceWalletOwner` | O | O | | 18 | | `removeWalletOwner` | O | O | | 19 | | `changeRequirement` | O | O | | 20 | | `getRequirement` | O | O | | 21 | | `getTransactionInfo` | O | O | | 22 | | `getTransactionsExecuted` | O | X | Use `getTransactionInfo` instead and check `_executed` field. | 23 | | `checkIfWalletOwner` | O | X | Use `getWalletOwners` instead. | 24 | | `getWalletOwnerCount` | O | X | Use `getWalletOwners` instead. | 25 | | `getWalletOwners` | O | O | No `_offset` and `_count` parameters. | 26 | | `getConfirmationCount` | O | O | | 27 | | `getConfirmations` | O | O | No `_offset` and `_count` parameters. | 28 | | `getTransactionCount` | O | O | | 29 | | `getTransactionList` | O | O | | 30 | | `getTransactionIds` | X | O | Returns a list of transaction IDs. | 31 | -------------------------------------------------------------------------------- /multisig-wallet/build.gradle: -------------------------------------------------------------------------------- 1 | version = '0.9.2' 2 | 3 | // for integration tests 4 | sourceSets { 5 | intTest {} 6 | } 7 | configurations { 8 | intTestImplementation.extendsFrom testImplementation 9 | intTestRuntimeOnly.extendsFrom testRuntimeOnly 10 | } 11 | 12 | dependencies { 13 | compileOnly 'foundation.icon:javaee-api:0.9.6' 14 | implementation 'foundation.icon:javaee-scorex:0.5.4.1' 15 | implementation 'com.github.sink772:minimal-json:0.9.7' 16 | 17 | testImplementation 'foundation.icon:javaee-unittest:0.12.1' 18 | testImplementation 'org.mockito:mockito-core:4.11.0' 19 | testImplementation 'org.junit.jupiter:junit-jupiter-api:5.9.3' 20 | testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.9.3' 21 | 22 | intTestImplementation 'foundation.icon:javaee-integration-test:0.9.0' 23 | intTestImplementation 'foundation.icon:icon-sdk:2.5.1' 24 | intTestRuntimeOnly project(':hello-world') 25 | } 26 | 27 | optimizedJar { 28 | mainClassName = 'com.iconloop.score.example.MultiSigWallet' 29 | from { 30 | configurations.runtimeClasspath.collect { it.isDirectory() ? it : zipTree(it) } 31 | } 32 | } 33 | 34 | deployJar { 35 | endpoints { 36 | lisbon { 37 | uri = 'https://lisbon.net.solidwallet.io/api/v3' 38 | nid = 0x2 39 | } 40 | local { 41 | uri = 'http://localhost:9082/api/v3' 42 | nid = 0x3 43 | } 44 | } 45 | keystore = rootProject.hasProperty('keystoreName') ? "$keystoreName" : '' 46 | password = rootProject.hasProperty('keystorePass') ? "$keystorePass" : '' 47 | parameters { 48 | arg('_walletOwners', 'hxe5679f118e093657b71967b0dfddb4d00cbd80b4,hx65f5d819d4b3897c39790f1f8b8a2bdcaeb605d0') 49 | arg('_required', '0x2') 50 | } 51 | } 52 | 53 | test { 54 | useJUnitPlatform() 55 | } 56 | 57 | def helloWorldJar = project(':hello-world').getTasks().getByName('optimizedJar') 58 | 59 | task integrationTest(type: Test, dependsOn: optimizedJar) { 60 | useJUnitPlatform() 61 | description = 'Runs integration tests.' 62 | group = 'verification' 63 | 64 | testClassesDirs = sourceSets.intTest.output.classesDirs 65 | classpath = sourceSets.intTest.runtimeClasspath 66 | testLogging.showStandardStreams = true 67 | 68 | // use the common config files 69 | systemProperty('env.props', new File(project(':testinteg').projectDir, 'conf/env.props')) 70 | 71 | def prefix = 'score.path.' 72 | systemProperty(prefix + project.name, optimizedJar.outputJarName) 73 | systemProperty(prefix + 'hello-world', helloWorldJar.outputJarName) 74 | } 75 | 76 | integrationTest.dependsOn(helloWorldJar) 77 | -------------------------------------------------------------------------------- /multisig-wallet/src/intTest/java/foundation/icon/test/cases/MultiSigWalletTest.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.test.cases; 18 | 19 | import foundation.icon.icx.IconService; 20 | import foundation.icon.icx.KeyWallet; 21 | import foundation.icon.icx.data.Address; 22 | import foundation.icon.icx.data.TransactionResult; 23 | import foundation.icon.icx.transport.http.HttpProvider; 24 | import foundation.icon.icx.transport.jsonrpc.RpcItem; 25 | import foundation.icon.test.Env; 26 | import foundation.icon.test.TestBase; 27 | import foundation.icon.test.TransactionHandler; 28 | import foundation.icon.test.score.HelloWorld; 29 | import foundation.icon.test.score.MultiSigWalletScore; 30 | import org.junit.jupiter.api.AfterAll; 31 | import org.junit.jupiter.api.BeforeAll; 32 | import org.junit.jupiter.api.Test; 33 | 34 | import java.math.BigInteger; 35 | 36 | import static foundation.icon.test.Env.LOG; 37 | import static org.junit.jupiter.api.Assertions.assertEquals; 38 | 39 | public class MultiSigWalletTest extends TestBase { 40 | private static final BigInteger TWO = BigInteger.valueOf(2); 41 | private static final BigInteger THREE = BigInteger.valueOf(3); 42 | private static final BigInteger FIVE = BigInteger.valueOf(5); 43 | private static TransactionHandler txHandler; 44 | private static KeyWallet[] wallets; 45 | 46 | @BeforeAll 47 | static void setup() throws Exception { 48 | Env.Chain chain = Env.getDefaultChain(); 49 | IconService iconService = new IconService(new HttpProvider(chain.getEndpointURL(3))); 50 | txHandler = new TransactionHandler(iconService, chain); 51 | 52 | // init wallets 53 | wallets = new KeyWallet[5]; 54 | BigInteger amount = ICX.multiply(BigInteger.valueOf(50)); 55 | for (int i = 0; i < wallets.length; i++) { 56 | wallets[i] = KeyWallet.create(); 57 | txHandler.transfer(wallets[i].getAddress(), amount); 58 | } 59 | for (KeyWallet wallet : wallets) { 60 | ensureIcxBalance(txHandler, wallet.getAddress(), BigInteger.ZERO, amount); 61 | } 62 | } 63 | 64 | @AfterAll 65 | static void shutdown() throws Exception { 66 | for (KeyWallet wallet : wallets) { 67 | txHandler.refundAll(wallet); 68 | } 69 | } 70 | 71 | @Test 72 | public void deployAndStartTest() throws Exception { 73 | // deploy MultiSigWallet SCORE 74 | Address[] walletOwners = new Address[] { 75 | wallets[0].getAddress(), wallets[1].getAddress(), wallets[2].getAddress()}; 76 | MultiSigWalletScore multiSigWalletScore = MultiSigWalletScore.mustDeploy(txHandler, 77 | wallets[0], walletOwners, 2); 78 | startTest(multiSigWalletScore); 79 | } 80 | 81 | private void startTest(MultiSigWalletScore multiSigWalletScore) throws Exception { 82 | LOG.infoEntering("setup", "initial wallets"); 83 | KeyWallet ownerWallet = wallets[0]; 84 | KeyWallet aliceWallet = wallets[1]; 85 | KeyWallet bobWallet = wallets[2]; 86 | LOG.info("Address of owner: " + ownerWallet.getAddress()); 87 | LOG.info("Address of Alice: " + aliceWallet.getAddress()); 88 | LOG.info("Address of Bob: " + bobWallet.getAddress()); 89 | Address multiSigWalletAddress = multiSigWalletScore.getAddress(); 90 | 91 | // deposit 5 icx to the multiSigWallet first 92 | LOG.info("transfer: 5 icx to multiSigWallet"); 93 | transferAndCheckResult(txHandler, multiSigWalletAddress, ICX.multiply(FIVE)); 94 | ensureIcxBalance(txHandler, multiSigWalletAddress, BigInteger.ZERO, ICX.multiply(FIVE)); 95 | LOG.infoExiting(); 96 | 97 | // *** 1. Send 2 icx to Bob (EOA) 98 | LOG.infoEntering("call", "submitIcxTransaction() - send 2 icx to Bob"); 99 | // tx is initiated by ownerWallet first 100 | TransactionResult result = multiSigWalletScore.submitIcxTransaction( 101 | ownerWallet, bobWallet.getAddress(), ICX.multiply(TWO), "send 2 icx to Bob"); 102 | BigInteger txId = multiSigWalletScore.getTransactionId(result); 103 | BigInteger bobBalance = txHandler.getBalance(bobWallet.getAddress()); 104 | 105 | // Alice confirms the tx to make it executed 106 | LOG.info("confirmTransaction() by Alice"); 107 | result = multiSigWalletScore.confirmTransaction(aliceWallet, txId); 108 | multiSigWalletScore.ensureIcxTransfer(result, multiSigWalletAddress, bobWallet.getAddress(), 2); 109 | multiSigWalletScore.ensureExecution(result, txId); 110 | 111 | // check icx balances 112 | ensureIcxBalance(txHandler, multiSigWalletAddress, ICX.multiply(FIVE), ICX.multiply(THREE)); 113 | ensureIcxBalance(txHandler, bobWallet.getAddress(), bobBalance, bobBalance.add(ICX.multiply(TWO))); 114 | LOG.infoExiting(); 115 | 116 | // *** 2. Send 1 icx to Contract 117 | LOG.infoEntering("call", "submitIcxTransaction() - send 1 icx to hello"); 118 | // deploy another sample score to accept icx 119 | LOG.info("deploy: HelloWorld"); 120 | HelloWorld helloScore = HelloWorld.install(txHandler, ownerWallet); 121 | // tx is initiated by ownerWallet first 122 | result = multiSigWalletScore.submitIcxTransaction( 123 | ownerWallet, helloScore.getAddress(), ICX.multiply(BigInteger.ONE), "send 1 icx to hello"); 124 | txId = multiSigWalletScore.getTransactionId(result); 125 | 126 | // Bob confirms the tx to make it executed 127 | LOG.info("confirmTransaction() by Bob"); 128 | result = multiSigWalletScore.confirmTransaction(bobWallet, txId); 129 | multiSigWalletScore.ensureIcxTransfer(result, multiSigWalletAddress, helloScore.getAddress(), 1); 130 | multiSigWalletScore.ensureExecution(result, txId); 131 | 132 | // check icx balances 133 | ensureIcxBalance(txHandler, multiSigWalletAddress, ICX.multiply(THREE), ICX.multiply(TWO)); 134 | ensureIcxBalance(txHandler, helloScore.getAddress(), BigInteger.ZERO, ICX.multiply(BigInteger.ONE)); 135 | LOG.infoExiting(); 136 | 137 | // *** 3. Send a test transaction (this will not be executed intentionally) 138 | LOG.infoEntering("call", "submitIcxTransaction() - pending transaction"); 139 | result = multiSigWalletScore.submitIcxTransaction( 140 | ownerWallet, aliceWallet.getAddress(), ICX.multiply(TWO), "send 2 icx to Alice"); 141 | BigInteger pendingTx = multiSigWalletScore.getTransactionId(result); 142 | LOG.infoExiting(); 143 | 144 | // *** 4. Add new wallet owner (charlie) 145 | LOG.infoEntering("call", "addWalletOwner(Charlie)"); 146 | KeyWallet charlieWallet = wallets[3]; 147 | LOG.info("Address of Charlie: " + charlieWallet.getAddress()); 148 | result = multiSigWalletScore.addWalletOwner(aliceWallet, charlieWallet.getAddress(), "add new wallet owner"); 149 | txId = multiSigWalletScore.getTransactionId(result); 150 | 151 | // Revocation test 152 | LOG.info("revokeTransaction() by Alice"); 153 | result = multiSigWalletScore.revokeTransaction(aliceWallet, txId); 154 | multiSigWalletScore.ensureRevocation(result, aliceWallet.getAddress(), txId); 155 | multiSigWalletScore.getConfirmationsAndCheck(txId); 156 | 157 | // Owner and Bob confirm the tx to make it executed 158 | LOG.info("confirmTransaction() by Owner and Bob"); 159 | result = multiSigWalletScore.confirmTransaction(ownerWallet, txId); 160 | result = multiSigWalletScore.confirmTransaction(bobWallet, txId); 161 | multiSigWalletScore.ensureWalletOwnerAddition(result, charlieWallet.getAddress()); 162 | multiSigWalletScore.ensureExecution(result, txId); 163 | multiSigWalletScore.ensureOwners( 164 | ownerWallet.getAddress(), aliceWallet.getAddress(), bobWallet.getAddress(), charlieWallet.getAddress()); 165 | LOG.infoExiting(); 166 | 167 | // *** 5. Replace wallet owner (bob -> david) 168 | LOG.infoEntering("call", "replaceWalletOwner(Bob to David)"); 169 | KeyWallet davidWallet = wallets[4]; 170 | LOG.info("Address of David: " + davidWallet.getAddress()); 171 | result = multiSigWalletScore.replaceWalletOwner(aliceWallet, bobWallet.getAddress(), 172 | davidWallet.getAddress(), "replace wallet owner"); 173 | txId = multiSigWalletScore.getTransactionId(result); 174 | 175 | // Charlie confirms the tx to make it executed 176 | LOG.info("confirmTransaction() by Charlie"); 177 | result = multiSigWalletScore.confirmTransaction(charlieWallet, txId); 178 | multiSigWalletScore.ensureWalletOwnerRemoval(result, bobWallet.getAddress()); 179 | multiSigWalletScore.ensureWalletOwnerAddition(result, davidWallet.getAddress()); 180 | multiSigWalletScore.ensureExecution(result, txId); 181 | multiSigWalletScore.ensureOwners( 182 | ownerWallet.getAddress(), aliceWallet.getAddress(), davidWallet.getAddress(), charlieWallet.getAddress()); 183 | LOG.infoExiting(); 184 | 185 | // *** 6. Change requirement 186 | LOG.infoEntering("call", "changeRequirement(3)"); 187 | // check the current requirement first 188 | RpcItem item = multiSigWalletScore.call("getRequirement", null); 189 | assertEquals(2, item.asInteger().intValue()); 190 | // tx is initiated by ownerWallet first 191 | result = multiSigWalletScore.changeRequirement(ownerWallet, 3, "change requirement to 3"); 192 | txId = multiSigWalletScore.getTransactionId(result); 193 | 194 | // Alice confirms the tx to make it executed 195 | LOG.info("confirmTransaction() by Alice"); 196 | result = multiSigWalletScore.confirmTransaction(aliceWallet, txId); 197 | multiSigWalletScore.ensureRequirementChange(result, 3); 198 | multiSigWalletScore.ensureExecution(result, txId); 199 | // check the changed requirement 200 | item = multiSigWalletScore.call("getRequirement", null); 201 | assertEquals(3, item.asInteger().intValue()); 202 | LOG.infoExiting(); 203 | 204 | // *** 7. Remove wallet owner 205 | LOG.infoEntering("call", "removeWalletOwner(owner)"); 206 | result = multiSigWalletScore.removeWalletOwner(aliceWallet, ownerWallet.getAddress(), "remove the owner"); 207 | txId = multiSigWalletScore.getTransactionId(result); 208 | 209 | // Charlie and David confirm the tx to make it executed 210 | LOG.info("confirmTransaction() by Charlie"); 211 | result = multiSigWalletScore.confirmTransaction(charlieWallet, txId); 212 | multiSigWalletScore.ensureConfirmationCount(txId, 2); 213 | multiSigWalletScore.getConfirmationsAndCheck(txId, 214 | aliceWallet.getAddress(), charlieWallet.getAddress()); 215 | // check getTransactionCount before executing the tx 216 | multiSigWalletScore.ensureTransactionCount(2, 5); 217 | // check getTransactionList before executing the tx 218 | multiSigWalletScore.ensurePendingTransactionIds(0, 7, pendingTx, txId); 219 | 220 | LOG.info("confirmTransaction() by David"); 221 | result = multiSigWalletScore.confirmTransaction(davidWallet, txId); 222 | multiSigWalletScore.ensureWalletOwnerRemoval(result, ownerWallet.getAddress()); 223 | multiSigWalletScore.ensureExecution(result, txId); 224 | multiSigWalletScore.ensureConfirmationCount(txId, 3); 225 | multiSigWalletScore.getConfirmationsAndCheck(txId, 226 | charlieWallet.getAddress(), aliceWallet.getAddress(), davidWallet.getAddress()); 227 | multiSigWalletScore.ensureOwners( 228 | charlieWallet.getAddress(), aliceWallet.getAddress(), davidWallet.getAddress()); 229 | LOG.infoExiting(); 230 | } 231 | } 232 | -------------------------------------------------------------------------------- /multisig-wallet/src/intTest/java/foundation/icon/test/score/HelloWorld.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.test.score; 18 | 19 | import foundation.icon.icx.Wallet; 20 | import foundation.icon.icx.transport.jsonrpc.RpcObject; 21 | import foundation.icon.icx.transport.jsonrpc.RpcValue; 22 | import foundation.icon.test.ResultTimeoutException; 23 | import foundation.icon.test.TransactionFailureException; 24 | import foundation.icon.test.TransactionHandler; 25 | 26 | import java.io.IOException; 27 | 28 | public class HelloWorld extends Score { 29 | public HelloWorld(Score other) { 30 | super(other); 31 | } 32 | 33 | public static HelloWorld install(TransactionHandler txHandler, Wallet wallet) 34 | throws TransactionFailureException, ResultTimeoutException, IOException { 35 | RpcObject params = new RpcObject.Builder() 36 | .put("name", new RpcValue("HelloWorld")) 37 | .build(); 38 | return install(txHandler, wallet, params); 39 | } 40 | 41 | public static HelloWorld install(TransactionHandler txHandler, Wallet wallet, RpcObject params) 42 | throws TransactionFailureException, ResultTimeoutException, IOException { 43 | return new HelloWorld(txHandler.deploy(wallet, getFilePath("hello-world"), params)); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /multisig-wallet/src/intTest/java/foundation/icon/test/score/MultiSigWalletScore.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.test.score; 18 | 19 | import foundation.icon.icx.Wallet; 20 | import foundation.icon.icx.data.Address; 21 | import foundation.icon.icx.data.IconAmount; 22 | import foundation.icon.icx.data.TransactionResult; 23 | import foundation.icon.icx.transport.jsonrpc.RpcItem; 24 | import foundation.icon.icx.transport.jsonrpc.RpcObject; 25 | import foundation.icon.icx.transport.jsonrpc.RpcValue; 26 | import foundation.icon.test.ResultTimeoutException; 27 | import foundation.icon.test.TransactionFailureException; 28 | import foundation.icon.test.TransactionHandler; 29 | 30 | import java.io.IOException; 31 | import java.math.BigInteger; 32 | import java.util.Arrays; 33 | import java.util.List; 34 | import java.util.stream.Collectors; 35 | 36 | import static foundation.icon.test.Env.LOG; 37 | import static org.junit.jupiter.api.Assertions.assertArrayEquals; 38 | import static org.junit.jupiter.api.Assertions.assertEquals; 39 | 40 | public class MultiSigWalletScore extends Score { 41 | 42 | public MultiSigWalletScore(Score other) { 43 | super(other); 44 | } 45 | 46 | public static MultiSigWalletScore mustDeploy(TransactionHandler txHandler, Wallet wallet, 47 | Address[] walletOwners, int required) 48 | throws IOException, TransactionFailureException, ResultTimeoutException { 49 | LOG.infoEntering("deploy", "MultiSigWallet"); 50 | String initialOwners = Arrays.stream(walletOwners) 51 | .map(Address::toString) 52 | .collect(Collectors.joining(",")); 53 | RpcObject params = new RpcObject.Builder() 54 | .put("_walletOwners", new RpcValue(initialOwners)) 55 | .put("_required", new RpcValue(BigInteger.valueOf(required))) 56 | .build(); 57 | Score score = txHandler.deploy(wallet, getFilePath("multisig-wallet"), params); 58 | LOG.info("scoreAddr = " + score.getAddress()); 59 | LOG.infoExiting(); 60 | return new MultiSigWalletScore(score); 61 | } 62 | 63 | public TransactionResult submitIcxTransaction(Wallet fromWallet, Address dest, BigInteger value, String description) 64 | throws IOException, ResultTimeoutException { 65 | RpcObject params = new RpcObject.Builder() 66 | .put("_destination", new RpcValue(dest)) 67 | .put("_value", new RpcValue(value)) 68 | .put("_description", new RpcValue(description)) 69 | .build(); 70 | return invokeAndWaitResult(fromWallet, "submitTransaction", params); 71 | } 72 | 73 | public TransactionResult confirmTransaction(Wallet fromWallet, BigInteger txId) 74 | throws IOException, ResultTimeoutException { 75 | RpcObject params = new RpcObject.Builder() 76 | .put("_transactionId", new RpcValue(txId)) 77 | .build(); 78 | TransactionResult result = invokeAndWaitResult(fromWallet, "confirmTransaction", params); 79 | ensureConfirmation(result, fromWallet.getAddress(), txId); 80 | return result; 81 | } 82 | 83 | public TransactionResult revokeTransaction(Wallet fromWallet, BigInteger txId) 84 | throws IOException, ResultTimeoutException { 85 | RpcObject params = new RpcObject.Builder() 86 | .put("_transactionId", new RpcValue(txId)) 87 | .build(); 88 | return invokeAndWaitResult(fromWallet, "revokeTransaction", params); 89 | } 90 | 91 | public TransactionResult addWalletOwner(Wallet fromWallet, Address newOwner, String description) 92 | throws IOException, ResultTimeoutException { 93 | String methodParams = String.format("[{\"name\": \"_walletOwner\", \"type\": \"Address\", \"value\": \"%s\"}]", newOwner); 94 | RpcObject params = new RpcObject.Builder() 95 | .put("_destination", new RpcValue(getAddress())) 96 | .put("_method", new RpcValue("addWalletOwner")) 97 | .put("_params", new RpcValue(methodParams)) 98 | .put("_description", new RpcValue(description)) 99 | .build(); 100 | return invokeAndWaitResult(fromWallet, "submitTransaction", params); 101 | } 102 | 103 | public TransactionResult removeWalletOwner(Wallet fromWallet, Address owner, String description) 104 | throws IOException, ResultTimeoutException { 105 | String methodParams = String.format("[{\"name\": \"_walletOwner\", \"type\": \"Address\", \"value\": \"%s\"}]", owner); 106 | RpcObject params = new RpcObject.Builder() 107 | .put("_destination", new RpcValue(getAddress())) 108 | .put("_method", new RpcValue("removeWalletOwner")) 109 | .put("_params", new RpcValue(methodParams)) 110 | .put("_description", new RpcValue(description)) 111 | .build(); 112 | return invokeAndWaitResult(fromWallet, "submitTransaction", params); 113 | } 114 | 115 | public TransactionResult replaceWalletOwner(Wallet fromWallet, Address oldOwner, Address newOwner, String description) 116 | throws IOException, ResultTimeoutException { 117 | String methodParams = String.format( 118 | "[{\"name\": \"_walletOwner\", \"type\": \"Address\", \"value\": \"%s\"}," 119 | + "{\"name\": \"_newWalletOwner\", \"type\": \"Address\", \"value\": \"%s\"}]", oldOwner, newOwner); 120 | RpcObject params = new RpcObject.Builder() 121 | .put("_destination", new RpcValue(getAddress())) 122 | .put("_method", new RpcValue("replaceWalletOwner")) 123 | .put("_params", new RpcValue(methodParams)) 124 | .put("_description", new RpcValue(description)) 125 | .build(); 126 | return invokeAndWaitResult(fromWallet, "submitTransaction", params); 127 | } 128 | 129 | public TransactionResult changeRequirement(Wallet fromWallet, int required, String description) 130 | throws IOException, ResultTimeoutException { 131 | String methodParams = String.format("[{\"name\": \"_required\", \"type\": \"int\", \"value\": \"%d\"}]", required); 132 | RpcObject params = new RpcObject.Builder() 133 | .put("_destination", new RpcValue(getAddress())) 134 | .put("_method", new RpcValue("changeRequirement")) 135 | .put("_params", new RpcValue(methodParams)) 136 | .put("_description", new RpcValue(description)) 137 | .build(); 138 | return invokeAndWaitResult(fromWallet, "submitTransaction", params); 139 | } 140 | 141 | public BigInteger getTransactionId(TransactionResult result) throws IOException { 142 | TransactionResult.EventLog event = findEventLog(result, getAddress(), "Submission(int)"); 143 | if (event != null) { 144 | return event.getIndexed().get(1).asInteger(); 145 | } 146 | throw new IOException("Failed to get transactionId."); 147 | } 148 | 149 | public void ensureConfirmation(TransactionResult result, Address sender, BigInteger txId) throws IOException { 150 | TransactionResult.EventLog event = findEventLog(result, getAddress(), "Confirmation(Address,int)"); 151 | if (event != null) { 152 | Address _sender = event.getIndexed().get(1).asAddress(); 153 | BigInteger _txId = event.getIndexed().get(2).asInteger(); 154 | if (sender.equals(_sender) && txId.equals(_txId)) { 155 | return; // ensured 156 | } 157 | } 158 | throw new IOException("Failed to get Confirmation."); 159 | } 160 | 161 | public void ensureRevocation(TransactionResult result, Address sender, BigInteger txId) throws IOException { 162 | TransactionResult.EventLog event = findEventLog(result, getAddress(), "Revocation(Address,int)"); 163 | if (event != null) { 164 | Address _sender = event.getIndexed().get(1).asAddress(); 165 | BigInteger _txId = event.getIndexed().get(2).asInteger(); 166 | if (sender.equals(_sender) && txId.equals(_txId)) { 167 | return; // ensured 168 | } 169 | } 170 | throw new IOException("Failed to get Revocation."); 171 | } 172 | 173 | public void ensureIcxTransfer(TransactionResult result, Address from, Address to, long value) throws IOException { 174 | TransactionResult.EventLog event = findEventLog(result, getAddress(), "ICXTransfer(Address,Address,int)"); 175 | if (event != null) { 176 | BigInteger icxValue = IconAmount.of(BigInteger.valueOf(value), IconAmount.Unit.ICX).toLoop(); 177 | Address _from = event.getIndexed().get(1).asAddress(); 178 | Address _to = event.getIndexed().get(2).asAddress(); 179 | BigInteger _value = event.getIndexed().get(3).asInteger(); 180 | if (from.equals(_from) && to.equals(_to) && icxValue.equals(_value)) { 181 | return; // ensured 182 | } 183 | } 184 | throw new IOException("Failed to get ICXTransfer."); 185 | } 186 | 187 | public void ensureExecution(TransactionResult result, BigInteger txId) throws IOException { 188 | TransactionResult.EventLog event = findEventLog(result, getAddress(), "Execution(int)"); 189 | if (event != null) { 190 | BigInteger _txId = event.getIndexed().get(1).asInteger(); 191 | if (txId.equals(_txId)) { 192 | return; // ensured 193 | } 194 | } 195 | throw new IOException("Failed to get Execution."); 196 | } 197 | 198 | public void ensureWalletOwnerAddition(TransactionResult result, Address address) throws IOException { 199 | TransactionResult.EventLog event = findEventLog(result, getAddress(), "WalletOwnerAddition(Address)"); 200 | if (event != null) { 201 | Address _address = event.getIndexed().get(1).asAddress(); 202 | if (address.equals(_address)) { 203 | return; // ensured 204 | } 205 | } 206 | throw new IOException("Failed to get WalletOwnerAddition."); 207 | } 208 | 209 | public void ensureWalletOwnerRemoval(TransactionResult result, Address address) throws IOException { 210 | TransactionResult.EventLog event = findEventLog(result, getAddress(), "WalletOwnerRemoval(Address)"); 211 | if (event != null) { 212 | Address _address = event.getIndexed().get(1).asAddress(); 213 | if (address.equals(_address)) { 214 | return; // ensured 215 | } 216 | } 217 | throw new IOException("Failed to get WalletOwnerRemoval."); 218 | } 219 | 220 | public void ensureRequirementChange(TransactionResult result, Integer required) throws IOException { 221 | TransactionResult.EventLog event = findEventLog(result, getAddress(), "RequirementChange(int)"); 222 | if (event != null) { 223 | BigInteger _required = event.getData().get(0).asInteger(); 224 | if (required.equals(_required.intValue())) { 225 | return; // ensured 226 | } 227 | } 228 | throw new IOException("Failed to get RequirementChange."); 229 | } 230 | 231 | public void ensureOwners(Address... expected) throws IOException { 232 | List items = getWalletOwners().asArray().asList(); 233 | assertAddressEquals(items, expected); 234 | } 235 | 236 | private RpcItem getWalletOwners() throws IOException { 237 | return this.call("getWalletOwners", null); 238 | } 239 | 240 | public void ensureConfirmationCount(BigInteger txId, int count) throws IOException { 241 | RpcObject params = new RpcObject.Builder() 242 | .put("_transactionId", new RpcValue(txId)) 243 | .build(); 244 | assertEquals(count, this.call("getConfirmationCount", params).asInteger().intValue()); 245 | } 246 | 247 | public void getConfirmationsAndCheck(BigInteger txId, Address... expected) throws IOException { 248 | List items = getConfirmations(txId).asArray().asList(); 249 | assertAddressEquals(items, expected); 250 | } 251 | 252 | private RpcItem getConfirmations(BigInteger txId) throws IOException { 253 | RpcObject params = new RpcObject.Builder() 254 | .put("_transactionId", new RpcValue(txId)) 255 | .build(); 256 | return this.call("getConfirmations", params); 257 | } 258 | 259 | public void ensureTransactionCount(int pending, int executed) throws IOException { 260 | assertEquals(pending, getTransactionCount(true, false)); 261 | assertEquals(executed, getTransactionCount(false, true)); 262 | assertEquals(pending + executed, getTransactionCount(true, true)); 263 | } 264 | 265 | private int getTransactionCount(boolean pending, boolean executed) throws IOException { 266 | RpcObject params = new RpcObject.Builder() 267 | .put("_pending", new RpcValue(pending)) 268 | .put("_executed", new RpcValue(executed)) 269 | .build(); 270 | return this.call("getTransactionCount", params).asInteger().intValue(); 271 | } 272 | 273 | public void ensurePendingTransactionIds(int offset, int count, BigInteger... expected) throws IOException { 274 | RpcObject params = new RpcObject.Builder() 275 | .put("_offset", new RpcValue(BigInteger.valueOf(offset))) 276 | .put("_count", new RpcValue(BigInteger.valueOf(count))) 277 | .put("_pending", new RpcValue(true)) 278 | .put("_executed", new RpcValue(false)) 279 | .build(); 280 | List items = this.call("getTransactionList", params).asArray().asList(); 281 | assertEquals(expected.length, items.size()); 282 | BigInteger[] actual = new BigInteger[items.size()]; 283 | for (int i = 0; i < actual.length; i++) { 284 | actual[i] = items.get(i).asObject().getItem("_transactionId").asInteger(); 285 | } 286 | assertArrayEquals(expected, actual); 287 | } 288 | 289 | private void assertAddressEquals(List items, Address[] expected) { 290 | assertEquals(expected.length, items.size()); 291 | Address[] actual = new Address[items.size()]; 292 | for (int i = 0; i < actual.length; i++) { 293 | actual[i] = items.get(i).asAddress(); 294 | } 295 | assertArrayEquals(expected, actual); 296 | } 297 | } 298 | -------------------------------------------------------------------------------- /multisig-wallet/src/main/java/com/iconloop/score/example/Transaction.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2020 ICONLOOP Inc. 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 com.iconloop.score.example; 18 | 19 | import com.eclipsesource.json.Json; 20 | import com.eclipsesource.json.JsonArray; 21 | import com.eclipsesource.json.JsonObject; 22 | import com.eclipsesource.json.JsonValue; 23 | import score.Address; 24 | import score.ObjectReader; 25 | import score.ObjectWriter; 26 | 27 | import java.math.BigInteger; 28 | import java.util.Map; 29 | 30 | public class Transaction { 31 | private final Address destination; 32 | private final String method; 33 | private final String params; 34 | private final BigInteger value; 35 | private final String description; 36 | private boolean executed; 37 | 38 | public Transaction(Address destination, String method, String params, BigInteger value, String description) { 39 | if (destination == null) { 40 | throw new IllegalArgumentException(); 41 | } 42 | this.destination = destination; 43 | this.method = method; 44 | this.params = params; 45 | this.value = value; 46 | this.description = description; 47 | } 48 | 49 | public static void writeObject(ObjectWriter w, Transaction t) { 50 | w.beginList(6); 51 | w.write(t.destination); 52 | w.writeNullable( 53 | t.method, 54 | t.params, 55 | t.value, 56 | t.description 57 | ); 58 | w.write(t.executed); 59 | w.end(); 60 | } 61 | 62 | public static Transaction readObject(ObjectReader r) { 63 | r.beginList(); 64 | Transaction t = new Transaction( 65 | r.readAddress(), 66 | r.readNullable(String.class), 67 | r.readNullable(String.class), 68 | r.readNullable(BigInteger.class), 69 | r.readNullable(String.class)); 70 | t.setExecuted(r.readBoolean()); 71 | r.end(); 72 | return t; 73 | } 74 | 75 | public boolean executed() { 76 | return this.executed; 77 | } 78 | 79 | public void setExecuted(boolean status) { 80 | this.executed = status; 81 | } 82 | 83 | public BigInteger value() { 84 | return this.value; 85 | } 86 | 87 | public Address destination() { 88 | return this.destination; 89 | } 90 | 91 | public String method() { 92 | return this.method; 93 | } 94 | 95 | public String params() { 96 | return this.params; 97 | } 98 | 99 | public String description() { 100 | return this.description; 101 | } 102 | 103 | public Object[] getConvertedParams() { 104 | if (params == null || params.equals("")) { 105 | return null; 106 | } 107 | JsonValue json = Json.parse(params); 108 | if (!json.isArray()) { 109 | throw new IllegalArgumentException("Not json array"); 110 | } 111 | JsonArray array = json.asArray(); 112 | Object[] ret = new Object[array.size()]; 113 | int i = 0; 114 | for (JsonValue item : array) { 115 | JsonObject member = item.asObject(); 116 | if (member.size() != 3) { 117 | throw new IllegalArgumentException("Invalid member size"); 118 | } 119 | String name = member.getString("name", null); 120 | String type = member.getString("type", null); 121 | String value = member.getString("value", null); 122 | if (name != null && type != null && value != null) { 123 | ret[i++] = convertParam(type, value); 124 | } else { 125 | throw new IllegalArgumentException("Incomplete params"); 126 | } 127 | } 128 | return ret; 129 | } 130 | 131 | private Object convertParam(String type, String value) { 132 | switch (type) { 133 | case "Address": 134 | return Address.fromString(value); 135 | case "str": 136 | return value; 137 | case "int": 138 | if (value.startsWith("0x")) { 139 | return new BigInteger(value.substring(2), 16); 140 | } 141 | return new BigInteger(value); 142 | case "bool": 143 | if (value.equals("0x0") || value.equals("false")) { 144 | return Boolean.FALSE; 145 | } else if (value.equals("0x1") || value.equals("true")) { 146 | return Boolean.TRUE; 147 | } 148 | break; 149 | case "bytes": 150 | if (value.startsWith("0x") && (value.length() % 2 == 0)) { 151 | String hex = value.substring(2); 152 | int len = hex.length() / 2; 153 | byte[] bytes = new byte[len]; 154 | for (int i = 0; i < len; i++) { 155 | int j = i * 2; 156 | bytes[i] = (byte) Integer.parseInt(hex.substring(j, j + 2), 16); 157 | } 158 | return bytes; 159 | } 160 | } 161 | throw new IllegalArgumentException("Unknown type"); 162 | } 163 | 164 | @Override 165 | public String toString() { 166 | return "Transaction{" + 167 | "destination=" + destination + 168 | ", method='" + method + '\'' + 169 | ", params='" + params + '\'' + 170 | ", value=" + value + 171 | ", description='" + description + '\'' + 172 | ", executed=" + executed + 173 | '}'; 174 | } 175 | 176 | public Map toMap(BigInteger transactionId) { 177 | return Map.of( 178 | "_destination", destination.toString(), 179 | "_method", getSafeString(method), 180 | "_params", getSafeString(params), 181 | "_value", (value == null) ? "0x0" : "0x" + value.toString(16), 182 | "_description", getSafeString(description), 183 | "_executed", (executed) ? "0x1" : "0x0", 184 | "_transactionId", "0x" + transactionId.toString(16) 185 | ); 186 | } 187 | 188 | private String getSafeString(String s) { 189 | if (s == null) return ""; 190 | return s; 191 | } 192 | } 193 | -------------------------------------------------------------------------------- /multisig-wallet/src/test/java/com/iconloop/score/example/MultiSigWalletTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2020 ICONLOOP Inc. 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 com.iconloop.score.example; 18 | 19 | import com.iconloop.score.test.Account; 20 | import com.iconloop.score.test.Score; 21 | import com.iconloop.score.test.ServiceManager; 22 | import com.iconloop.score.test.TestBase; 23 | import org.junit.jupiter.api.BeforeEach; 24 | import org.junit.jupiter.api.Test; 25 | import org.mockito.ArgumentCaptor; 26 | import score.Address; 27 | import score.UserRevertedException; 28 | 29 | import java.math.BigInteger; 30 | import java.util.Arrays; 31 | import java.util.List; 32 | import java.util.Map; 33 | import java.util.stream.Collectors; 34 | 35 | import static org.junit.jupiter.api.Assertions.assertArrayEquals; 36 | import static org.junit.jupiter.api.Assertions.assertEquals; 37 | import static org.junit.jupiter.api.Assertions.assertThrows; 38 | import static org.mockito.Mockito.reset; 39 | import static org.mockito.Mockito.spy; 40 | import static org.mockito.Mockito.verify; 41 | 42 | class MultiSigWalletTest extends TestBase { 43 | private static final ServiceManager sm = getServiceManager(); 44 | private Account[] owners; 45 | private Score multisigScore; 46 | private MultiSigWallet multisigSpy; 47 | 48 | @BeforeEach 49 | void setup() throws Exception { 50 | // setup accounts and deploy 51 | owners = new Account[3]; 52 | for (int i = 0; i < owners.length; i++) { 53 | owners[i] = sm.createAccount(100); 54 | } 55 | String initialOwners = Arrays.stream(owners) 56 | .map(a -> a.getAddress().toString()) 57 | .collect(Collectors.joining(",")); 58 | multisigScore = sm.deploy(owners[0], MultiSigWallet.class, 59 | initialOwners, BigInteger.TWO); 60 | 61 | // setup spy 62 | multisigSpy = (MultiSigWallet) spy(multisigScore.getInstance()); 63 | multisigScore.setInstance(multisigSpy); 64 | } 65 | 66 | @Test 67 | void fallback() { 68 | sm.transfer(owners[0], multisigScore.getAddress(), ICX); 69 | verify(multisigSpy).Deposit(owners[0].getAddress(), ICX); 70 | } 71 | 72 | @Test 73 | void tokenFallback() { 74 | byte[] data = "test".getBytes(); 75 | multisigScore.invoke(owners[0], "tokenFallback", owners[0].getAddress(), ICX, data); 76 | verify(multisigSpy).DepositToken(owners[0].getAddress(), ICX, data); 77 | } 78 | 79 | @Test 80 | void addWalletOwner() { 81 | // add new wallet owner 82 | Account alice = sm.createAccount(); 83 | BigInteger txId = submitAddWalletOwner(owners[0], alice); 84 | // confirmation from another owner 85 | confirmByOwner(owners[1], txId); 86 | 87 | verify(multisigSpy).Execution(txId); 88 | verify(multisigSpy).addWalletOwner(alice.getAddress()); 89 | verify(multisigSpy).WalletOwnerAddition(alice.getAddress()); 90 | 91 | @SuppressWarnings("unchecked") 92 | var walletOwners = (List
) multisigScore.call("getWalletOwners"); 93 | assertEquals(4, walletOwners.size()); 94 | } 95 | 96 | private BigInteger submitAddWalletOwner(Account submitter, Account acct) { 97 | String params = String.format("[{\"name\": \"_walletOwner\", \"type\": \"Address\", \"value\": \"%s\"}]", 98 | acct.getAddress()); 99 | multisigScore.invoke(submitter, "submitTransaction", 100 | multisigScore.getAddress(), "addWalletOwner", params, BigInteger.ZERO, ""); 101 | ArgumentCaptor txId = ArgumentCaptor.forClass(BigInteger.class); 102 | verify(multisigSpy).Submission(txId.capture()); 103 | verify(multisigSpy).Confirmation(submitter.getAddress(), txId.getValue()); 104 | return txId.getValue(); 105 | } 106 | 107 | private void confirmByOwner(Account acct, BigInteger txId) { 108 | multisigScore.invoke(acct, "confirmTransaction", txId); 109 | verify(multisigSpy).Confirmation(acct.getAddress(), txId); 110 | } 111 | 112 | @Test 113 | void removeWalletOwner() { 114 | // remove 1st wallet 115 | String params = String.format("[{\"name\": \"_walletOwner\", \"type\": \"Address\", \"value\": \"%s\"}]", 116 | owners[0].getAddress()); 117 | multisigScore.invoke(owners[1], "submitTransaction", 118 | multisigScore.getAddress(), "removeWalletOwner", params, BigInteger.ZERO, ""); 119 | ArgumentCaptor txId = ArgumentCaptor.forClass(BigInteger.class); 120 | verify(multisigSpy).Submission(txId.capture()); 121 | verify(multisigSpy).Confirmation(owners[1].getAddress(), txId.getValue()); 122 | 123 | // confirmation from another owner 124 | confirmByOwner(owners[2], txId.getValue()); 125 | 126 | verify(multisigSpy).Execution(txId.getValue()); 127 | verify(multisigSpy).removeWalletOwner(owners[0].getAddress()); 128 | verify(multisigSpy).WalletOwnerRemoval(owners[0].getAddress()); 129 | 130 | @SuppressWarnings("unchecked") 131 | var walletOwners = (List
) multisigScore.call("getWalletOwners"); 132 | assertEquals(2, walletOwners.size()); 133 | } 134 | 135 | @Test 136 | void replaceWalletOwner() { 137 | // replace 2nd wallet with new owner 138 | Account alice = sm.createAccount(); 139 | String params = String.format( 140 | "[{\"name\": \"_walletOwner\", \"type\": \"Address\", \"value\": \"%s\"}," 141 | + "{\"name\": \"_newWalletOwner\", \"type\": \"Address\", \"value\": \"%s\"}]", 142 | owners[1].getAddress(), alice.getAddress()); 143 | multisigScore.invoke(owners[0], "submitTransaction", 144 | multisigScore.getAddress(), "replaceWalletOwner", params, BigInteger.ZERO, ""); 145 | ArgumentCaptor txId = ArgumentCaptor.forClass(BigInteger.class); 146 | verify(multisigSpy).Submission(txId.capture()); 147 | verify(multisigSpy).Confirmation(owners[0].getAddress(), txId.getValue()); 148 | 149 | // confirmation from another owner 150 | confirmByOwner(owners[2], txId.getValue()); 151 | 152 | verify(multisigSpy).Execution(txId.getValue()); 153 | verify(multisigSpy).replaceWalletOwner(owners[1].getAddress(), alice.getAddress()); 154 | verify(multisigSpy).WalletOwnerAddition(alice.getAddress()); 155 | verify(multisigSpy).WalletOwnerRemoval(owners[1].getAddress()); 156 | 157 | @SuppressWarnings("unchecked") 158 | var walletOwners = (List
) multisigScore.call("getWalletOwners"); 159 | assertEquals(3, walletOwners.size()); 160 | } 161 | 162 | @Test 163 | void changeRequirement() { 164 | // check the current requirement first 165 | BigInteger oldReq = (BigInteger) multisigScore.call("getRequirement"); 166 | assertEquals(2, oldReq.intValue()); 167 | 168 | // change requirement 169 | var newReq = oldReq.add(BigInteger.ONE); 170 | String params = String.format("[{\"name\": \"_required\", \"type\": \"int\", \"value\": \"%d\"}]", newReq); 171 | multisigScore.invoke(owners[0], "submitTransaction", 172 | multisigScore.getAddress(), "changeRequirement", params, BigInteger.ZERO, ""); 173 | ArgumentCaptor txId = ArgumentCaptor.forClass(BigInteger.class); 174 | verify(multisigSpy).Submission(txId.capture()); 175 | verify(multisigSpy).Confirmation(owners[0].getAddress(), txId.getValue()); 176 | 177 | // confirmation from another owner 178 | confirmByOwner(owners[1], txId.getValue()); 179 | 180 | verify(multisigSpy).Execution(txId.getValue()); 181 | verify(multisigSpy).changeRequirement(newReq); 182 | verify(multisigSpy).RequirementChange(newReq); 183 | 184 | assertEquals(newReq, multisigScore.call("getRequirement")); 185 | } 186 | 187 | @Test 188 | void confirmTransaction_notOwner() { 189 | // add new wallet owner first 190 | Account alice = sm.createAccount(); 191 | BigInteger txId = submitAddWalletOwner(owners[0], alice); 192 | // confirm by alice herself 193 | assertThrows(UserRevertedException.class, () -> 194 | multisigScore.invoke(alice, "confirmTransaction", txId)); 195 | } 196 | 197 | @Test 198 | void revokeTransaction() { 199 | // add new wallet owner and confirm first 200 | BigInteger txId = submitAddWalletOwner(owners[0], sm.createAccount()); 201 | assertEquals(1, getConfirmationCount(txId)); 202 | 203 | // revoke the transaction 204 | multisigScore.invoke(owners[0], "revokeTransaction", txId); 205 | verify(multisigSpy).Revocation(owners[0].getAddress(), txId); 206 | assertEquals(0, getConfirmationCount(txId)); 207 | } 208 | 209 | private int getConfirmationCount(BigInteger txId) { 210 | return (int) multisigScore.call("getConfirmationCount", txId); 211 | } 212 | 213 | @Test 214 | void getConfirmations() { 215 | // add new wallet owner and confirm first 216 | BigInteger txId = submitAddWalletOwner(owners[2], sm.createAccount()); 217 | assertEquals(1, getConfirmationCount(txId)); 218 | 219 | // confirmation from another owner 220 | confirmByOwner(owners[1], txId); 221 | assertEquals(2, getConfirmationCount(txId)); 222 | 223 | // get confirmations 224 | @SuppressWarnings("unchecked") 225 | var confirmations = (List
) multisigScore.call("getConfirmations", txId); 226 | var sortedOwners = confirmations.stream() 227 | .map(Address::toString) 228 | .sorted() 229 | .collect(Collectors.joining(",")); 230 | var expected = List.of(owners[1].getAddress(), owners[2].getAddress()) 231 | .stream() 232 | .map(Address::toString) 233 | .sorted() 234 | .collect(Collectors.joining(",")); 235 | assertEquals(expected, sortedOwners); 236 | } 237 | 238 | @Test 239 | void getTransactionCount() { 240 | // submit dummy transactions 241 | int count = 5; 242 | for (int i = 0; i < count; i++) { 243 | multisigScore.invoke(owners[0], "submitTransaction", owners[0].getAddress(), "", "", BigInteger.ZERO, ""); 244 | } 245 | // verify pending transactions 246 | var txCount = (BigInteger) multisigScore.call("getTransactionCount", true, false); 247 | assertEquals(count, txCount.intValue()); 248 | 249 | // confirm two transactions 250 | multisigScore.invoke(owners[1], "confirmTransaction", BigInteger.ZERO); 251 | multisigScore.invoke(owners[1], "confirmTransaction", BigInteger.ONE); 252 | 253 | // verify executed transactions 254 | txCount = (BigInteger) multisigScore.call("getTransactionCount", false, true); 255 | assertEquals(2, txCount.intValue()); 256 | // verify total transactions 257 | txCount = (BigInteger) multisigScore.call("getTransactionCount", true, true); 258 | assertEquals(count, txCount.intValue()); 259 | } 260 | 261 | @Test 262 | void getTransactionInfo() { 263 | // add new wallet owner 264 | Account alice = sm.createAccount(); 265 | BigInteger txId = submitAddWalletOwner(owners[0], alice); 266 | 267 | @SuppressWarnings("unchecked") 268 | var txInfo = (Map) multisigScore.call("getTransactionInfo", txId); 269 | assertEquals(txInfo.get("_transactionId"), "0x0"); 270 | assertEquals(txInfo.get("_method"), "addWalletOwner"); 271 | assertEquals(txInfo.get("_destination"), multisigScore.getAddress().toString()); 272 | assertEquals(txInfo.get("_executed"), "0x0"); 273 | 274 | // confirmation from another owner 275 | confirmByOwner(owners[1], txId); 276 | 277 | @SuppressWarnings("unchecked") 278 | var txInfo2 = (Map) multisigScore.call("getTransactionInfo", txId); 279 | assertEquals(txInfo2.get("_executed"), "0x1"); 280 | } 281 | 282 | @Test 283 | void getTransactionIds() { 284 | // submit dummy transactions 285 | int count = 5; 286 | for (int i = 0; i < count; i++) { 287 | multisigScore.invoke(owners[0], "submitTransaction", owners[0].getAddress(), "", "", BigInteger.ZERO, ""); 288 | } 289 | 290 | // get total transaction ids 291 | @SuppressWarnings("unchecked") 292 | var txIds = (List) multisigScore.call("getTransactionIds", 293 | BigInteger.valueOf(0), BigInteger.valueOf(count), true, true); 294 | assertEquals(count, txIds.size()); 295 | 296 | // confirm two transactions 297 | multisigScore.invoke(owners[1], "confirmTransaction", BigInteger.ZERO); 298 | multisigScore.invoke(owners[1], "confirmTransaction", BigInteger.TWO); 299 | 300 | // get executed transaction ids 301 | @SuppressWarnings("unchecked") 302 | var txIds2 = (List) multisigScore.call("getTransactionIds", 303 | BigInteger.valueOf(0), BigInteger.valueOf(count), false, true); 304 | assertArrayEquals( 305 | new BigInteger[]{BigInteger.ZERO, BigInteger.TWO}, 306 | txIds2.toArray(new BigInteger[0])); 307 | 308 | // get pending transaction ids 309 | @SuppressWarnings("unchecked") 310 | var txIds3 = (List) multisigScore.call("getTransactionIds", 311 | BigInteger.valueOf(0), BigInteger.valueOf(count), true, false); 312 | assertArrayEquals( 313 | new BigInteger[]{BigInteger.ONE, BigInteger.valueOf(3), BigInteger.valueOf(4)}, 314 | txIds3.toArray(new BigInteger[0])); 315 | } 316 | 317 | @Test 318 | void getTransactionList() { 319 | // submit dummy transactions 320 | int count = 5; 321 | for (int i = 0; i < count; i++) { 322 | multisigScore.invoke(owners[0], "submitTransaction", owners[0].getAddress(), "", "", BigInteger.ZERO, ""); 323 | } 324 | 325 | // confirm two transactions 326 | multisigScore.invoke(owners[1], "confirmTransaction", BigInteger.ONE); 327 | multisigScore.invoke(owners[1], "confirmTransaction", BigInteger.TWO); 328 | 329 | // get executed transaction list 330 | @SuppressWarnings("unchecked") 331 | var txList = (List>) multisigScore.call("getTransactionList", 332 | BigInteger.valueOf(0), BigInteger.valueOf(count), false, true); 333 | var received = txList.stream() 334 | .map((tx) -> tx.get("_transactionId")) 335 | .collect(Collectors.joining(",")); 336 | assertEquals("0x1,0x2", received); 337 | 338 | // get pending transaction list 339 | @SuppressWarnings("unchecked") 340 | var txList2 = (List>) multisigScore.call("getTransactionList", 341 | BigInteger.valueOf(0), BigInteger.valueOf(count), true, false); 342 | received = txList2.stream() 343 | .map((tx) -> tx.get("_transactionId")) 344 | .collect(Collectors.joining(",")); 345 | assertEquals("0x0,0x3,0x4", received); 346 | } 347 | 348 | @Test 349 | void getConvertedParams_wrongFormat() { 350 | String[] wrongFormats = { 351 | "{\"name\": \"_walletOwner\", \"type\": \"Address\", \"value\": \"%s\"}", 352 | "[{\"name\": \"_walletOwner\", \"type\": \"Address\", \"value\": \"%s\"}", 353 | "[{\"name\": \"_walletOwner\", \"type\": \"String\", \"value\": \"%s\"}]", 354 | "[{\"name\": \"_walletOwner\", \"type_\": \"Address\", \"value\": \"%s\"}]", 355 | "[{\"name\": \"_walletOwner\", \"type\": \"%s\"}]", 356 | "[{\"name\": \"_walletOwner\", \"value\": \"%s\"}]", 357 | "[{\"type\": \"_walletOwner\", \"type\": \"Address\", \"value\": \"%s\"}]", 358 | }; 359 | BigInteger txId = BigInteger.ZERO; 360 | for (String format : wrongFormats) { 361 | String params = String.format(format, sm.createAccount().getAddress()); 362 | System.out.println(">>> params=" + params); 363 | multisigScore.invoke(owners[0], "submitTransaction", 364 | multisigScore.getAddress(), "addWalletOwner", params, BigInteger.ZERO, ""); 365 | confirmByOwner(owners[1], txId); 366 | 367 | verify(multisigSpy).ExecutionFailure(txId); 368 | reset(multisigSpy); 369 | txId = txId.add(BigInteger.ONE); 370 | } 371 | } 372 | } 373 | -------------------------------------------------------------------------------- /sample-crowdsale/build.gradle: -------------------------------------------------------------------------------- 1 | version = '0.1.0' 2 | 3 | // for integration tests 4 | sourceSets { 5 | intTest {} 6 | } 7 | configurations { 8 | intTestImplementation.extendsFrom testImplementation 9 | intTestRuntimeOnly.extendsFrom testRuntimeOnly 10 | } 11 | 12 | dependencies { 13 | compileOnly 'foundation.icon:javaee-api:0.9.6' 14 | 15 | testImplementation project(':irc2-token') 16 | testImplementation 'foundation.icon:javaee-unittest:0.12.1' 17 | testImplementation 'org.mockito:mockito-core:4.11.0' 18 | testImplementation 'org.junit.jupiter:junit-jupiter-api:5.9.3' 19 | testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.9.3' 20 | 21 | intTestImplementation 'foundation.icon:javaee-integration-test:0.9.0' 22 | intTestImplementation 'foundation.icon:icon-sdk:2.5.1' 23 | } 24 | 25 | optimizedJar { 26 | mainClassName = 'com.iconloop.score.example.SampleCrowdsale' 27 | archivesBaseName = 'sample-crowdsale' 28 | } 29 | 30 | deployJar { 31 | endpoints { 32 | lisbon { 33 | uri = 'https://lisbon.net.solidwallet.io/api/v3' 34 | nid = 0x2 35 | } 36 | local { 37 | uri = 'http://localhost:9082/api/v3' 38 | nid = 0x3 39 | } 40 | } 41 | keystore = rootProject.hasProperty('keystoreName') ? "$keystoreName" : '' 42 | password = rootProject.hasProperty('keystorePass') ? "$keystorePass" : '' 43 | parameters { 44 | arg('_fundingGoalInIcx', '0x64') 45 | arg('_tokenScore', 'cx451cee702db0e48aacbe446d53cbd8aa00142354') 46 | arg('_durationInBlocks', '0x20') 47 | } 48 | } 49 | 50 | test { 51 | useJUnitPlatform() 52 | } 53 | 54 | def sampleTokenJar = project(':irc2-token').getTasks().getByName('optimizedJar') 55 | 56 | task integrationTest(type: Test, dependsOn: optimizedJar) { 57 | useJUnitPlatform() 58 | description = 'Runs integration tests.' 59 | group = 'verification' 60 | 61 | testClassesDirs = sourceSets.intTest.output.classesDirs 62 | classpath = sourceSets.intTest.runtimeClasspath 63 | testLogging.showStandardStreams = true 64 | 65 | // use the common config files 66 | systemProperty('env.props', new File(project(':testinteg').projectDir, 'conf/env.props')) 67 | 68 | def prefix = 'score.path.' 69 | systemProperty(prefix + project.name, optimizedJar.outputJarName) 70 | systemProperty(prefix + 'sample-token', sampleTokenJar.outputJarName) 71 | } 72 | 73 | integrationTest.dependsOn(sampleTokenJar) 74 | -------------------------------------------------------------------------------- /sample-crowdsale/src/intTest/java/foundation/icon/test/cases/CrowdsaleTest.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.test.cases; 18 | 19 | import foundation.icon.icx.IconService; 20 | import foundation.icon.icx.KeyWallet; 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.test.Constants; 25 | import foundation.icon.test.Env; 26 | import foundation.icon.test.TestBase; 27 | import foundation.icon.test.TransactionHandler; 28 | import foundation.icon.test.score.CrowdSaleScore; 29 | import foundation.icon.test.score.SampleTokenScore; 30 | import org.junit.jupiter.api.AfterAll; 31 | import org.junit.jupiter.api.BeforeAll; 32 | import org.junit.jupiter.api.Test; 33 | 34 | import java.io.IOException; 35 | import java.math.BigInteger; 36 | 37 | import static foundation.icon.test.Env.LOG; 38 | 39 | class CrowdsaleTest extends TestBase { 40 | private static TransactionHandler txHandler; 41 | private static KeyWallet[] wallets; 42 | private static KeyWallet ownerWallet; 43 | 44 | @BeforeAll 45 | static void setup() throws Exception { 46 | Env.Chain chain = Env.getDefaultChain(); 47 | IconService iconService = new IconService(new HttpProvider(chain.getEndpointURL(3))); 48 | txHandler = new TransactionHandler(iconService, chain); 49 | 50 | // init wallets 51 | wallets = new KeyWallet[3]; 52 | BigInteger amount = ICX.multiply(BigInteger.valueOf(30)); 53 | for (int i = 0; i < wallets.length; i++) { 54 | wallets[i] = KeyWallet.create(); 55 | txHandler.transfer(wallets[i].getAddress(), amount); 56 | } 57 | for (KeyWallet wallet : wallets) { 58 | ensureIcxBalance(txHandler, wallet.getAddress(), BigInteger.ZERO, amount); 59 | } 60 | ownerWallet = wallets[0]; 61 | } 62 | 63 | @AfterAll 64 | static void shutdown() throws Exception { 65 | for (KeyWallet wallet : wallets) { 66 | txHandler.refundAll(wallet); 67 | } 68 | } 69 | 70 | @Test 71 | void deployAndStartCrowdsale() throws Exception { 72 | // deploy token SCORE 73 | BigInteger decimals = BigInteger.valueOf(18); 74 | BigInteger initialSupply = BigInteger.valueOf(1000); 75 | SampleTokenScore tokenScore = SampleTokenScore.mustDeploy(txHandler, ownerWallet, 76 | decimals, initialSupply); 77 | 78 | // deploy crowdsale SCORE 79 | BigInteger fundingGoalInIcx = BigInteger.valueOf(100); 80 | CrowdSaleScore crowdsaleScore = CrowdSaleScore.mustDeploy(txHandler, ownerWallet, 81 | tokenScore.getAddress(), fundingGoalInIcx); 82 | 83 | startCrowdsale(tokenScore, crowdsaleScore, initialSupply, fundingGoalInIcx); 84 | } 85 | 86 | void startCrowdsale(SampleTokenScore tokenScore, CrowdSaleScore crowdsaleScore, 87 | BigInteger initialSupply, BigInteger fundingGoalInIcx) throws Exception { 88 | KeyWallet aliceWallet = wallets[1]; 89 | KeyWallet bobWallet = wallets[2]; 90 | 91 | // send 50 icx to Alice, 100 to Bob 92 | LOG.infoEntering("transfer icx", "50 to Alice; 100 to Bob"); 93 | transferAndCheckResult(txHandler, aliceWallet.getAddress(), ICX.multiply(BigInteger.valueOf(50))); 94 | transferAndCheckResult(txHandler, bobWallet.getAddress(), ICX.multiply(BigInteger.valueOf(100))); 95 | LOG.infoExiting(); 96 | 97 | // transfer all tokens to crowdsale score 98 | LOG.infoEntering("transfer token", "all tokens to crowdsale score from owner"); 99 | TransactionResult result = tokenScore.transfer(ownerWallet, crowdsaleScore.getAddress(), ICX.multiply(initialSupply)); 100 | crowdsaleScore.ensureFundingGoal(result, fundingGoalInIcx); 101 | tokenScore.ensureTokenBalance(crowdsaleScore.getAddress(), initialSupply.longValue()); 102 | LOG.infoExiting(); 103 | 104 | // send icx to crowdsale score from Alice and Bob 105 | LOG.infoEntering("transfer icx", "to crowdsale score (40 from Alice, 60 from Bob)"); 106 | Bytes[] ids = new Bytes[2]; 107 | ids[0] = txHandler.transfer(aliceWallet, crowdsaleScore.getAddress(), ICX.multiply(BigInteger.valueOf(40))); 108 | ids[1] = txHandler.transfer(bobWallet, crowdsaleScore.getAddress(), ICX.multiply(BigInteger.valueOf(60))); 109 | for (Bytes id : ids) { 110 | assertSuccess(txHandler.getResult(id)); 111 | } 112 | tokenScore.ensureTokenBalance(aliceWallet.getAddress(), 40); 113 | tokenScore.ensureTokenBalance(bobWallet.getAddress(), 60); 114 | LOG.infoExiting(); 115 | 116 | // check if goal reached 117 | LOG.infoEntering("call", "checkGoalReached()"); 118 | crowdsaleScore.ensureCheckGoalReached(ownerWallet); 119 | LOG.infoExiting(); 120 | 121 | // do safe withdrawal 122 | LOG.infoEntering("call", "safeWithdrawal()"); 123 | BigInteger oldBal = txHandler.getBalance(ownerWallet.getAddress()); 124 | result = crowdsaleScore.safeWithdrawal(ownerWallet); 125 | if (!Constants.STATUS_SUCCESS.equals(result.getStatus())) { 126 | throw new IOException("Failed to execute safeWithdrawal."); 127 | } 128 | BigInteger amount = ICX.multiply(BigInteger.valueOf(100)); 129 | crowdsaleScore.ensureFundTransfer(result, ownerWallet.getAddress(), amount); 130 | 131 | // check the final icx balance of owner 132 | LOG.info("ICX balance before safeWithdrawal: " + oldBal); 133 | BigInteger fee = result.getStepUsed().multiply(result.getStepPrice()); 134 | BigInteger newBal = oldBal.add(amount).subtract(fee); 135 | ensureIcxBalance(txHandler, ownerWallet.getAddress(), oldBal, newBal); 136 | LOG.infoExiting(); 137 | } 138 | } 139 | -------------------------------------------------------------------------------- /sample-crowdsale/src/intTest/java/foundation/icon/test/score/CrowdSaleScore.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.test.score; 18 | 19 | import foundation.icon.icx.Wallet; 20 | import foundation.icon.icx.data.Address; 21 | import foundation.icon.icx.data.IconAmount; 22 | import foundation.icon.icx.data.TransactionResult; 23 | import foundation.icon.icx.transport.jsonrpc.RpcObject; 24 | import foundation.icon.icx.transport.jsonrpc.RpcValue; 25 | import foundation.icon.test.Constants; 26 | import foundation.icon.test.ResultTimeoutException; 27 | import foundation.icon.test.TransactionFailureException; 28 | import foundation.icon.test.TransactionHandler; 29 | 30 | import java.io.IOException; 31 | import java.math.BigInteger; 32 | 33 | import static foundation.icon.test.Env.LOG; 34 | 35 | public class CrowdSaleScore extends Score { 36 | 37 | public static CrowdSaleScore mustDeploy(TransactionHandler txHandler, Wallet wallet, 38 | Address tokenAddress, BigInteger fundingGoalInIcx) 39 | throws ResultTimeoutException, TransactionFailureException, IOException { 40 | LOG.infoEntering("deploy", "Crowdsale"); 41 | RpcObject params = new RpcObject.Builder() 42 | .put("_fundingGoalInIcx", new RpcValue(fundingGoalInIcx)) 43 | .put("_tokenScore", new RpcValue(tokenAddress)) 44 | .put("_durationInBlocks", new RpcValue(BigInteger.valueOf(10))) 45 | .build(); 46 | Score score = txHandler.deploy(wallet, getFilePath("sample-crowdsale"), params); 47 | LOG.info("scoreAddr = " + score.getAddress()); 48 | LOG.infoExiting(); 49 | return new CrowdSaleScore(score); 50 | } 51 | 52 | public CrowdSaleScore(Score other) { 53 | super(other); 54 | } 55 | 56 | public TransactionResult checkGoalReached(Wallet wallet) 57 | throws ResultTimeoutException, IOException { 58 | return invokeAndWaitResult(wallet, "checkGoalReached", null, null); 59 | } 60 | 61 | public TransactionResult safeWithdrawal(Wallet wallet) 62 | throws ResultTimeoutException, IOException { 63 | return invokeAndWaitResult(wallet, "safeWithdrawal", null, null); 64 | } 65 | 66 | public void ensureCheckGoalReached(Wallet wallet) throws Exception { 67 | while (true) { 68 | TransactionResult result = checkGoalReached(wallet); 69 | if (!Constants.STATUS_SUCCESS.equals(result.getStatus())) { 70 | throw new IOException("Failed to execute checkGoalReached."); 71 | } 72 | TransactionResult.EventLog event = findEventLog(result, getAddress(), "GoalReached(Address,int)"); 73 | if (event != null) { 74 | break; 75 | } 76 | LOG.info("Sleep 1 second."); 77 | Thread.sleep(1000); 78 | } 79 | } 80 | 81 | public void ensureFundingGoal(TransactionResult result, BigInteger fundingGoalInIcx) 82 | throws IOException { 83 | TransactionResult.EventLog event = findEventLog(result, getAddress(), "CrowdsaleStarted(int,int)"); 84 | if (event != null) { 85 | BigInteger fundingGoalInLoop = IconAmount.of(fundingGoalInIcx, IconAmount.Unit.ICX).toLoop(); 86 | BigInteger fundingGoalFromScore = event.getData().get(0).asInteger(); 87 | if (fundingGoalInLoop.equals(fundingGoalFromScore)) { 88 | return; // ensured 89 | } 90 | } 91 | throw new IOException("ensureFundingGoal failed."); 92 | } 93 | 94 | public void ensureFundTransfer(TransactionResult result, Address backer, BigInteger amount) 95 | throws IOException { 96 | TransactionResult.EventLog event = findEventLog(result, getAddress(), "FundTransfer(Address,int,bool)"); 97 | if (event != null) { 98 | Address _backer = event.getIndexed().get(1).asAddress(); 99 | BigInteger _amount = event.getIndexed().get(2).asInteger(); 100 | Boolean isContribution = event.getIndexed().get(3).asBoolean(); 101 | if (backer.equals(_backer) && amount.equals(_amount) && !isContribution) { 102 | return; // ensured 103 | } 104 | } 105 | throw new IOException("ensureFundTransfer failed."); 106 | } 107 | } 108 | -------------------------------------------------------------------------------- /sample-crowdsale/src/intTest/java/foundation/icon/test/score/SampleTokenScore.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.test.score; 18 | 19 | import foundation.icon.icx.Wallet; 20 | import foundation.icon.icx.data.Address; 21 | import foundation.icon.icx.data.TransactionResult; 22 | import foundation.icon.icx.transport.jsonrpc.RpcObject; 23 | import foundation.icon.icx.transport.jsonrpc.RpcValue; 24 | import foundation.icon.test.Constants; 25 | import foundation.icon.test.ResultTimeoutException; 26 | import foundation.icon.test.TransactionFailureException; 27 | import foundation.icon.test.TransactionHandler; 28 | 29 | import java.io.IOException; 30 | import java.math.BigInteger; 31 | import java.util.Arrays; 32 | 33 | import static foundation.icon.test.Env.LOG; 34 | 35 | public class SampleTokenScore extends Score { 36 | 37 | public static SampleTokenScore mustDeploy(TransactionHandler txHandler, Wallet wallet, 38 | BigInteger decimals, BigInteger initialSupply) 39 | throws ResultTimeoutException, TransactionFailureException, IOException { 40 | LOG.infoEntering("deploy", "SampleToken"); 41 | RpcObject params = new RpcObject.Builder() 42 | .put("_name", new RpcValue("MySampleToken")) 43 | .put("_symbol", new RpcValue("MST")) 44 | .put("_decimals", new RpcValue(decimals)) 45 | .put("_initialSupply", new RpcValue(initialSupply)) 46 | .build(); 47 | Score score = txHandler.deploy(wallet, getFilePath("sample-token"), params); 48 | LOG.info("scoreAddr = " + score.getAddress()); 49 | LOG.infoExiting(); 50 | return new SampleTokenScore(score); 51 | } 52 | 53 | public SampleTokenScore(Score other) { 54 | super(other); 55 | } 56 | 57 | public BigInteger balanceOf(Address owner) throws IOException { 58 | RpcObject params = new RpcObject.Builder() 59 | .put("_owner", new RpcValue(owner)) 60 | .build(); 61 | return call("balanceOf", params).asInteger(); 62 | } 63 | 64 | public TransactionResult transfer(Wallet wallet, Address to, BigInteger value) 65 | throws IOException, ResultTimeoutException { 66 | return this.transfer(wallet, to, value, null); 67 | } 68 | 69 | public TransactionResult transfer(Wallet wallet, Address to, BigInteger value, byte[] data) 70 | throws IOException, ResultTimeoutException { 71 | RpcObject.Builder builder = new RpcObject.Builder() 72 | .put("_to", new RpcValue(to)) 73 | .put("_value", new RpcValue(value)); 74 | if (data != null) { 75 | builder.put("_data", new RpcValue(data)); 76 | } 77 | return this.invokeAndWaitResult(wallet, "transfer", builder.build()); 78 | } 79 | 80 | public void ensureTransfer(TransactionResult result, Address from, Address to, BigInteger value, byte[] data) 81 | throws IOException { 82 | TransactionResult.EventLog event = findEventLog(result, getAddress(), "Transfer(Address,Address,int,bytes)"); 83 | if (event != null) { 84 | if (data == null) { 85 | data = new byte[0]; 86 | } 87 | Address _from = event.getIndexed().get(1).asAddress(); 88 | Address _to = event.getIndexed().get(2).asAddress(); 89 | BigInteger _value = event.getIndexed().get(3).asInteger(); 90 | byte[] _data = event.getData().get(0).asByteArray(); 91 | if (from.equals(_from) && to.equals(_to) && value.equals(_value) && Arrays.equals(data, _data)) { 92 | return; // ensured 93 | } 94 | } 95 | throw new IOException("ensureTransfer failed."); 96 | } 97 | 98 | public void ensureTokenBalance(Address owner, long value) throws ResultTimeoutException, IOException { 99 | long limitTime = System.currentTimeMillis() + Constants.DEFAULT_WAITING_TIME; 100 | while (true) { 101 | BigInteger balance = balanceOf(owner); 102 | String msg = "Token balance of " + owner + ": " + balance; 103 | if (balance.equals(BigInteger.valueOf(0))) { 104 | try { 105 | if (limitTime < System.currentTimeMillis()) { 106 | throw new ResultTimeoutException(); 107 | } 108 | // wait until block confirmation 109 | LOG.info(msg + "; Retry in 1 sec."); 110 | Thread.sleep(1000); 111 | } catch (InterruptedException e) { 112 | e.printStackTrace(); 113 | } 114 | } else if (balance.equals(BigInteger.valueOf(value).multiply(BigInteger.TEN.pow(18)))) { 115 | LOG.info(msg); 116 | break; 117 | } else { 118 | throw new IOException("Token balance mismatch!"); 119 | } 120 | } 121 | } 122 | } 123 | -------------------------------------------------------------------------------- /sample-crowdsale/src/main/java/com/iconloop/score/example/SampleCrowdsale.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2020 ICONLOOP Inc. 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 com.iconloop.score.example; 18 | 19 | import score.Address; 20 | import score.Context; 21 | import score.DictDB; 22 | import score.VarDB; 23 | import score.annotation.EventLog; 24 | import score.annotation.External; 25 | import score.annotation.Payable; 26 | 27 | import java.math.BigInteger; 28 | 29 | public class SampleCrowdsale 30 | { 31 | private static final BigInteger ONE_ICX = new BigInteger("1000000000000000000"); 32 | private final Address beneficiary; 33 | private final Address tokenScore; 34 | private final BigInteger fundingGoal; 35 | private final long deadline; 36 | private boolean fundingGoalReached; 37 | private boolean crowdsaleClosed; 38 | private final DictDB balances; 39 | private final VarDB amountRaised; 40 | 41 | public SampleCrowdsale(BigInteger _fundingGoalInIcx, Address _tokenScore, BigInteger _durationInBlocks) { 42 | // some basic requirements 43 | Context.require(_fundingGoalInIcx.compareTo(BigInteger.ZERO) >= 0); 44 | Context.require(_durationInBlocks.compareTo(BigInteger.ZERO) >= 0); 45 | 46 | this.beneficiary = Context.getCaller(); 47 | this.fundingGoal = ONE_ICX.multiply(_fundingGoalInIcx); 48 | this.tokenScore = _tokenScore; 49 | this.deadline = Context.getBlockHeight() + _durationInBlocks.longValue(); 50 | 51 | this.fundingGoalReached = false; 52 | this.crowdsaleClosed = true; // Crowdsale closed by default 53 | 54 | this.balances = Context.newDictDB("balances", BigInteger.class); 55 | this.amountRaised = Context.newVarDB("amountRaised", BigInteger.class); 56 | } 57 | 58 | @External(readonly=true) 59 | public String name() { 60 | return "SampleCrowdsale"; 61 | } 62 | 63 | /* 64 | * Receives initial tokens to reward to the contributors. 65 | */ 66 | @External 67 | public void tokenFallback(Address _from, BigInteger _value, byte[] _data) { 68 | // check if the caller is a token SCORE address that this SCORE is interested in 69 | Context.require(Context.getCaller().equals(this.tokenScore)); 70 | 71 | // depositing tokens can only be done by owner 72 | Context.require(Context.getOwner().equals(_from)); 73 | 74 | // value should be greater than zero 75 | Context.require(_value.compareTo(BigInteger.ZERO) >= 0); 76 | 77 | // start Crowdsale hereafter 78 | Context.require(this.crowdsaleClosed); 79 | this.crowdsaleClosed = false; 80 | // emit eventlog 81 | CrowdsaleStarted(this.fundingGoal, this.deadline); 82 | } 83 | 84 | /* 85 | * Called when anyone sends funds to the SCORE and that funds would be regarded as a contribution. 86 | */ 87 | @Payable 88 | public void fallback() { 89 | // check if the crowdsale is closed 90 | Context.require(!this.crowdsaleClosed); 91 | 92 | Address _from = Context.getCaller(); 93 | BigInteger _value = Context.getValue(); 94 | Context.require(_value.compareTo(BigInteger.ZERO) > 0); 95 | 96 | // accept the contribution 97 | BigInteger fromBalance = safeGetBalance(_from); 98 | this.balances.set(_from, fromBalance.add(_value)); 99 | 100 | // increase the total amount of funding 101 | BigInteger amountRaised = safeGetAmountRaised(); 102 | this.amountRaised.set(amountRaised.add(_value)); 103 | 104 | // give tokens to the contributor as a reward 105 | byte[] _data = "called from Crowdsale".getBytes(); 106 | Context.call(this.tokenScore, "transfer", _from, _value, _data); 107 | // emit eventlog 108 | FundTransfer(_from, _value, true); 109 | } 110 | 111 | /* 112 | * Checks if the goal has been reached and ends the campaign. 113 | */ 114 | @External 115 | public void checkGoalReached() { 116 | if (afterDeadline()) { 117 | if (!this.crowdsaleClosed) { 118 | this.crowdsaleClosed = true; 119 | // emit eventlog 120 | CrowdsaleEnded(); 121 | } 122 | BigInteger amountRaised = safeGetAmountRaised(); 123 | if (amountRaised.compareTo(this.fundingGoal) >= 0) { 124 | this.fundingGoalReached = true; 125 | // emit eventlog 126 | GoalReached(this.beneficiary, amountRaised); 127 | } 128 | } 129 | } 130 | 131 | /* 132 | * Withdraws the funds safely. 133 | * 134 | * - If the funding goal has been reached, sends the entire amount to the beneficiary. 135 | * - If the goal was not reached, each contributor can withdraw the amount they contributed. 136 | */ 137 | @External 138 | public void safeWithdrawal() { 139 | if (afterDeadline()) { 140 | Address _from = Context.getCaller(); 141 | 142 | // each contributor can withdraw the amount they contributed if the goal was not reached 143 | if (!this.fundingGoalReached) { 144 | BigInteger amount = safeGetBalance(_from); 145 | if (amount.compareTo(BigInteger.ZERO) > 0) { 146 | // set their balance to ZERO first before transferring the amount to prevent reentrancy attack 147 | this.balances.set(_from, BigInteger.ZERO); 148 | // transfer the icx back to them 149 | Context.transfer(_from, amount); 150 | // emit eventlog 151 | FundTransfer(_from, amount, false); 152 | } 153 | } 154 | 155 | // owner can withdraw the contribution since the sales target has been met. 156 | if (this.fundingGoalReached && this.beneficiary.equals(_from)) { 157 | BigInteger amountRaised = safeGetAmountRaised(); 158 | if (amountRaised.compareTo(BigInteger.ZERO) > 0) { 159 | // transfer the funds to beneficiary 160 | Context.transfer(this.beneficiary, amountRaised); 161 | // emit eventlog 162 | FundTransfer(this.beneficiary, amountRaised, false); 163 | // reset amountRaised 164 | this.amountRaised.set(BigInteger.ZERO); 165 | } 166 | } 167 | } 168 | } 169 | 170 | private BigInteger safeGetBalance(Address owner) { 171 | return this.balances.getOrDefault(owner, BigInteger.ZERO); 172 | } 173 | 174 | private BigInteger safeGetAmountRaised() { 175 | return this.amountRaised.getOrDefault(BigInteger.ZERO); 176 | } 177 | 178 | private boolean afterDeadline() { 179 | // checks if it has been reached to the deadline block 180 | return Context.getBlockHeight() >= this.deadline; 181 | } 182 | 183 | @EventLog 184 | protected void CrowdsaleStarted(BigInteger fundingGoal, long deadline) {} 185 | 186 | @EventLog 187 | protected void CrowdsaleEnded() {} 188 | 189 | @EventLog(indexed=3) 190 | protected void FundTransfer(Address backer, BigInteger amount, boolean isContribution) {} 191 | 192 | @EventLog(indexed=2) 193 | protected void GoalReached(Address recipient, BigInteger totalAmountRaised) {} 194 | } 195 | -------------------------------------------------------------------------------- /sample-crowdsale/src/test/java/com/iconloop/score/example/SampleCrowdsaleTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2020 ICONLOOP Inc. 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 com.iconloop.score.example; 18 | 19 | import com.iconloop.score.test.Account; 20 | import com.iconloop.score.test.Score; 21 | import com.iconloop.score.test.ServiceManager; 22 | import com.iconloop.score.test.TestBase; 23 | import org.junit.jupiter.api.BeforeEach; 24 | import org.junit.jupiter.api.Test; 25 | import score.UserRevertedException; 26 | 27 | import java.math.BigInteger; 28 | 29 | import static java.math.BigInteger.TEN; 30 | import static org.junit.jupiter.api.Assertions.assertEquals; 31 | import static org.junit.jupiter.api.Assertions.assertThrows; 32 | import static org.mockito.ArgumentMatchers.any; 33 | import static org.mockito.ArgumentMatchers.anyLong; 34 | import static org.mockito.ArgumentMatchers.eq; 35 | import static org.mockito.Mockito.never; 36 | import static org.mockito.Mockito.spy; 37 | import static org.mockito.Mockito.verify; 38 | 39 | class SampleCrowdsaleTest extends TestBase { 40 | // sample-token 41 | private static final String name = "MySampleToken"; 42 | private static final String symbol = "MST"; 43 | private static final int decimals = 18; 44 | private static final BigInteger initialSupply = BigInteger.valueOf(1000); 45 | private static final BigInteger totalSupply = initialSupply.multiply(TEN.pow(decimals)); 46 | 47 | // sample-crowdsale 48 | private static final BigInteger fundingGoalInICX = BigInteger.valueOf(100); 49 | private static final BigInteger durationInBlocks = BigInteger.valueOf(32); 50 | 51 | private static final ServiceManager sm = getServiceManager(); 52 | private static final Account owner = sm.createAccount(); 53 | private Score tokenScore; 54 | private Score crowdsaleScore; 55 | 56 | private SampleCrowdsale crowdsaleSpy; 57 | private final byte[] startCrowdsaleBytes = "start crowdsale".getBytes(); 58 | 59 | @BeforeEach 60 | public void setup() throws Exception { 61 | // deploy token and crowdsale scores 62 | tokenScore = sm.deploy(owner, IRC2BasicToken.class, 63 | name, symbol, decimals, initialSupply); 64 | crowdsaleScore = sm.deploy(owner, SampleCrowdsale.class, 65 | fundingGoalInICX, tokenScore.getAddress(), durationInBlocks); 66 | 67 | // setup spy object against the crowdsale object 68 | crowdsaleSpy = (SampleCrowdsale) spy(crowdsaleScore.getInstance()); 69 | crowdsaleScore.setInstance(crowdsaleSpy); 70 | } 71 | 72 | private void startCrowdsale() { 73 | // transfer all tokens to crowdsale score 74 | tokenScore.invoke(owner, "transfer", crowdsaleScore.getAddress(), totalSupply, startCrowdsaleBytes); 75 | } 76 | 77 | @Test 78 | void tokenFallback() { 79 | startCrowdsale(); 80 | // verify 81 | verify(crowdsaleSpy).tokenFallback(owner.getAddress(), totalSupply, startCrowdsaleBytes); 82 | verify(crowdsaleSpy).CrowdsaleStarted(eq(ICX.multiply(fundingGoalInICX)), anyLong()); 83 | assertEquals(totalSupply, tokenScore.call("balanceOf", crowdsaleScore.getAddress())); 84 | } 85 | 86 | @Test 87 | void fallback_crowdsaleNotYetStarted() { 88 | Account alice = sm.createAccount(100); 89 | BigInteger fund = ICX.multiply(BigInteger.valueOf(40)); 90 | // crowdsale is not yet started 91 | assertThrows(UserRevertedException.class, () -> 92 | sm.transfer(alice, crowdsaleScore.getAddress(), fund)); 93 | } 94 | 95 | @Test 96 | void fallback() { 97 | startCrowdsale(); 98 | // fund 40 icx from Alice 99 | Account alice = sm.createAccount(100); 100 | BigInteger fund = ICX.multiply(BigInteger.valueOf(40)); 101 | sm.transfer(alice, crowdsaleScore.getAddress(), fund); 102 | // verify 103 | verify(crowdsaleSpy).fallback(); 104 | verify(crowdsaleSpy).FundTransfer(alice.getAddress(), fund, true); 105 | assertEquals(fund, Account.getAccount(crowdsaleScore.getAddress()).getBalance()); 106 | } 107 | 108 | @Test 109 | void checkGoalReached() { 110 | startCrowdsale(); 111 | // increase the block height 112 | sm.getBlock().increase(durationInBlocks.longValue()); 113 | crowdsaleScore.invoke(owner, "checkGoalReached"); 114 | // verify 115 | verify(crowdsaleSpy).CrowdsaleEnded(); 116 | verify(crowdsaleSpy, never()).GoalReached(any(), any()); 117 | } 118 | 119 | @Test 120 | void safeWithdrawal() { 121 | startCrowdsale(); 122 | // fund 40 icx from Alice 123 | Account alice = sm.createAccount(100); 124 | sm.transfer(alice, crowdsaleScore.getAddress(), ICX.multiply(BigInteger.valueOf(40))); 125 | // fund 60 icx from Bob 126 | Account bob = sm.createAccount(100); 127 | sm.transfer(bob, crowdsaleScore.getAddress(), ICX.multiply(BigInteger.valueOf(60))); 128 | // make the goal reached 129 | sm.getBlock().increase(durationInBlocks.longValue()); 130 | crowdsaleScore.invoke(owner, "checkGoalReached"); 131 | // invoke safeWithdrawal 132 | crowdsaleScore.invoke(owner, "safeWithdrawal"); 133 | // verify 134 | verify(crowdsaleSpy).GoalReached(owner.getAddress(), ICX.multiply(fundingGoalInICX)); 135 | verify(crowdsaleSpy).FundTransfer(owner.getAddress(), ICX.multiply(fundingGoalInICX), false); 136 | assertEquals(ICX.multiply(fundingGoalInICX), Account.getAccount(owner.getAddress()).getBalance()); 137 | } 138 | 139 | @Test 140 | void safeWithdrawal_refund() { 141 | startCrowdsale(); 142 | // fund 40 icx from Alice 143 | Account alice = sm.createAccount(100); 144 | sm.transfer(alice, crowdsaleScore.getAddress(), ICX.multiply(BigInteger.valueOf(40))); 145 | // fund 50 icx from Bob 146 | Account bob = sm.createAccount(100); 147 | sm.transfer(bob, crowdsaleScore.getAddress(), ICX.multiply(BigInteger.valueOf(50))); 148 | // make the goal reached 149 | sm.getBlock().increase(durationInBlocks.longValue()); 150 | crowdsaleScore.invoke(owner, "checkGoalReached"); 151 | verify(crowdsaleSpy, never()).GoalReached(owner.getAddress(), ICX.multiply(fundingGoalInICX)); 152 | 153 | // invoke safeWithdrawal from alice to refund 154 | crowdsaleScore.invoke(alice, "safeWithdrawal"); 155 | verify(crowdsaleSpy).FundTransfer(alice.getAddress(), ICX.multiply(BigInteger.valueOf(40)), false); 156 | // invoke safeWithdrawal from bob to refund 157 | crowdsaleScore.invoke(bob, "safeWithdrawal"); 158 | verify(crowdsaleSpy).FundTransfer(bob.getAddress(), ICX.multiply(BigInteger.valueOf(50)), false); 159 | } 160 | } 161 | -------------------------------------------------------------------------------- /sample-token/build.gradle: -------------------------------------------------------------------------------- 1 | version = '0.2.0' 2 | 3 | dependencies { 4 | compileOnly 'foundation.icon:javaee-api:0.9.6' 5 | 6 | testImplementation 'foundation.icon:javaee-unittest:0.12.1' 7 | testImplementation 'org.junit.jupiter:junit-jupiter-api:5.9.3' 8 | testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.9.3' 9 | } 10 | 11 | optimizedJar { 12 | mainClassName = 'com.iconloop.score.example.SampleToken' 13 | archivesBaseName = 'sample-token' 14 | } 15 | 16 | deployJar { 17 | endpoints { 18 | lisbon { 19 | uri = 'https://lisbon.net.solidwallet.io/api/v3' 20 | nid = 0x2 21 | } 22 | local { 23 | uri = 'http://localhost:9082/api/v3' 24 | nid = 0x3 25 | } 26 | } 27 | keystore = rootProject.hasProperty('keystoreName') ? "$keystoreName" : '' 28 | password = rootProject.hasProperty('keystorePass') ? "$keystorePass" : '' 29 | parameters { 30 | arg('_name', 'MySampleToken') 31 | arg('_symbol', 'MST') 32 | arg('_decimals', '0x12') 33 | arg('_initialSupply', '0x3e8') 34 | } 35 | } 36 | 37 | test { 38 | useJUnitPlatform() 39 | } 40 | -------------------------------------------------------------------------------- /sample-token/src/main/java/com/iconloop/score/example/SampleToken.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2020 ICONLOOP Inc. 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 com.iconloop.score.example; 18 | 19 | import score.Address; 20 | import score.Context; 21 | import score.DictDB; 22 | import score.VarDB; 23 | import score.annotation.EventLog; 24 | import score.annotation.External; 25 | import score.annotation.Optional; 26 | 27 | import java.math.BigInteger; 28 | 29 | public class SampleToken 30 | { 31 | private final String name; 32 | private final String symbol; 33 | private final int decimals; 34 | private final VarDB totalSupply = Context.newVarDB("totalSupply", BigInteger.class); 35 | private final DictDB balances = Context.newDictDB("balances", BigInteger.class); 36 | 37 | public SampleToken(String _name, String _symbol, BigInteger _decimals, BigInteger _initialSupply) { 38 | this.name = _name; 39 | this.symbol = _symbol; 40 | this.decimals = _decimals.intValue(); 41 | 42 | // decimals must be larger than 0 and less than 21 43 | Context.require(this.decimals >= 0); 44 | Context.require(this.decimals <= 21); 45 | 46 | // initialSupply must be larger than 0 47 | Context.require(_initialSupply.compareTo(BigInteger.ZERO) >= 0); 48 | 49 | // calculate totalSupply 50 | BigInteger _totalSupply; 51 | if (_initialSupply.compareTo(BigInteger.ZERO) > 0) { 52 | BigInteger oneToken = pow(BigInteger.TEN, this.decimals); 53 | _totalSupply = oneToken.multiply(_initialSupply); 54 | } else { 55 | _totalSupply = BigInteger.ZERO; 56 | } 57 | 58 | // set the total supply and initial balance of the owner 59 | this.totalSupply.set(_totalSupply); 60 | this.balances.set(Context.getCaller(), _totalSupply); 61 | } 62 | 63 | // BigInteger#pow() is not implemented in the shadow BigInteger. 64 | // we need to use our implementation for that. 65 | private static BigInteger pow(BigInteger base, int exponent) { 66 | BigInteger result = BigInteger.ONE; 67 | for (int i = 0; i < exponent; i++) { 68 | result = result.multiply(base); 69 | } 70 | return result; 71 | } 72 | 73 | @External(readonly=true) 74 | public String name() { 75 | return name; 76 | } 77 | 78 | @External(readonly=true) 79 | public String symbol() { 80 | return symbol; 81 | } 82 | 83 | @External(readonly=true) 84 | public int decimals() { 85 | return decimals; 86 | } 87 | 88 | @External(readonly=true) 89 | public BigInteger totalSupply() { 90 | return totalSupply.getOrDefault(BigInteger.ZERO); 91 | } 92 | 93 | @External(readonly=true) 94 | public BigInteger balanceOf(Address _owner) { 95 | return safeGetBalance(_owner); 96 | } 97 | 98 | @External 99 | public void transfer(Address _to, BigInteger _value, @Optional byte[] _data) { 100 | Address _from = Context.getCaller(); 101 | 102 | // check some basic requirements 103 | Context.require(_value.compareTo(BigInteger.ZERO) >= 0); 104 | Context.require(safeGetBalance(_from).compareTo(_value) >= 0); 105 | 106 | // adjust the balances 107 | safeSetBalance(_from, safeGetBalance(_from).subtract(_value)); 108 | safeSetBalance(_to, safeGetBalance(_to).add(_value)); 109 | 110 | // if the recipient is SCORE, call 'tokenFallback' to handle further operation 111 | byte[] dataBytes = (_data == null) ? new byte[0] : _data; 112 | if (_to.isContract()) { 113 | Context.call(_to, "tokenFallback", _from, _value, dataBytes); 114 | } 115 | 116 | // emit Transfer event 117 | Transfer(_from, _to, _value, dataBytes); 118 | } 119 | 120 | private BigInteger safeGetBalance(Address owner) { 121 | return balances.getOrDefault(owner, BigInteger.ZERO); 122 | } 123 | 124 | private void safeSetBalance(Address owner, BigInteger amount) { 125 | balances.set(owner, amount); 126 | } 127 | 128 | @EventLog(indexed=3) 129 | public void Transfer(Address _from, Address _to, BigInteger _value, byte[] _data) {} 130 | } 131 | -------------------------------------------------------------------------------- /sample-token/src/test/java/com/iconloop/score/example/SampleTokenTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2020 ICONLOOP Inc. 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 com.iconloop.score.example; 18 | 19 | import com.iconloop.score.test.Account; 20 | import com.iconloop.score.test.Score; 21 | import com.iconloop.score.test.ServiceManager; 22 | import com.iconloop.score.test.TestBase; 23 | import org.junit.jupiter.api.BeforeAll; 24 | import org.junit.jupiter.api.Test; 25 | 26 | import java.math.BigInteger; 27 | 28 | import static java.math.BigInteger.TEN; 29 | import static org.junit.jupiter.api.Assertions.assertEquals; 30 | 31 | class SampleTokenTest extends TestBase { 32 | private static final String name = "MySampleToken"; 33 | private static final String symbol = "MST"; 34 | private static final int decimals = 18; 35 | private static final BigInteger initialSupply = BigInteger.valueOf(1000); 36 | 37 | private static final BigInteger totalSupply = initialSupply.multiply(TEN.pow(decimals)); 38 | private static final ServiceManager sm = getServiceManager(); 39 | private static final Account owner = sm.createAccount(); 40 | 41 | private static Score tokenScore; 42 | 43 | @BeforeAll 44 | public static void setup() throws Exception { 45 | tokenScore = sm.deploy(owner, SampleToken.class, 46 | name, symbol, BigInteger.valueOf(decimals), initialSupply); 47 | owner.addBalance(symbol, totalSupply); 48 | } 49 | 50 | @Test 51 | void name() { 52 | assertEquals(name, tokenScore.call("name")); 53 | } 54 | 55 | @Test 56 | void symbol() { 57 | assertEquals(symbol, tokenScore.call("symbol")); 58 | } 59 | 60 | @Test 61 | void decimals() { 62 | assertEquals(decimals, tokenScore.call("decimals")); 63 | } 64 | 65 | @Test 66 | void totalSupply() { 67 | assertEquals(totalSupply, tokenScore.call("totalSupply")); 68 | } 69 | 70 | @Test 71 | void balanceOf() { 72 | assertEquals(owner.getBalance(symbol), 73 | tokenScore.call("balanceOf", tokenScore.getOwner().getAddress())); 74 | } 75 | 76 | @Test 77 | void transfer() { 78 | Account alice = sm.createAccount(); 79 | BigInteger value = TEN.pow(decimals); 80 | tokenScore.invoke(owner, "transfer", alice.getAddress(), value, "to alice".getBytes()); 81 | owner.subtractBalance(symbol, value); 82 | assertEquals(owner.getBalance(symbol), 83 | tokenScore.call("balanceOf", tokenScore.getOwner().getAddress())); 84 | assertEquals(value, 85 | tokenScore.call("balanceOf", alice.getAddress())); 86 | 87 | // transfer self 88 | tokenScore.invoke(alice, "transfer", alice.getAddress(), value, "self transfer".getBytes()); 89 | assertEquals(value, tokenScore.call("balanceOf", alice.getAddress())); 90 | } 91 | } 92 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'java-score-examples' 2 | include ( 3 | 'hello-world', 4 | 'irc2-token', 5 | 'irc3-token', 6 | 'irc31-token', 7 | 'multisig-wallet', 8 | 'sample-crowdsale', 9 | 'sample-token', 10 | 'testinteg') 11 | -------------------------------------------------------------------------------- /testinteg/README.md: -------------------------------------------------------------------------------- 1 | [![Maven Central](https://maven-badges.herokuapp.com/maven-central/foundation.icon/javaee-integration-test/badge.svg)](https://search.maven.org/search?q=g:foundation.icon%20a:javaee-integration-test) 2 | 3 | # An Integration Testing Framework for Java SCORE 4 | 5 | This subproject contains a Java library that can be used to perform the integration testing on your Java SCORE implementation. 6 | It assumes there is a running ICON network (either local or remote) that can be connected for the testing, 7 | and provides some utility classes and methods to interact with the ICON network using [ICON SDK for Java](https://github.com/icon-project/icon-sdk-java). 8 | 9 | ## Usage 10 | 11 | You can include this package from [Maven Central](https://search.maven.org/search?q=g:foundation.icon%20a:javaee-integration-test) 12 | by adding the following dependency in your `build.gradle`. 13 | 14 | ```groovy 15 | testImplementation 'foundation.icon:javaee-integration-test:0.9.0' 16 | ``` 17 | 18 | For a more complete example, please visit [Java SCORE Examples](https://github.com/icon-project/java-score-examples). 19 | -------------------------------------------------------------------------------- /testinteg/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'java-library' 3 | id 'maven-publish' 4 | id 'signing' 5 | } 6 | 7 | optimizedJar.enabled = false 8 | 9 | dependencies { 10 | implementation 'foundation.icon:icon-sdk:2.5.1' 11 | implementation 'org.junit.jupiter:junit-jupiter-api:5.8.2' 12 | } 13 | 14 | task sourcesJar(type: Jar, dependsOn: classes) { 15 | classifier 'sources' 16 | from sourceSets.main.allSource 17 | } 18 | 19 | task javadocJar(type: Jar, dependsOn: javadoc) { 20 | classifier 'javadoc' 21 | from javadoc.destinationDir 22 | } 23 | 24 | def projectName = 'javaee-integration-test' 25 | def repoUrl = 'https://github.com/icon-project/java-score-examples/tree/master/testinteg' 26 | def snapshotSuffix = rootProject.hasProperty('release') ? '' : '-SNAPSHOT' 27 | version = VERSION + snapshotSuffix 28 | 29 | def pomConfig = { 30 | licenses { 31 | license { 32 | name "The Apache Software License, Version 2.0" 33 | url "http://www.apache.org/licenses/LICENSE-2.0.txt" 34 | distribution "repo" 35 | } 36 | } 37 | developers { 38 | developer { 39 | id "iconfoundation" 40 | name "icon.foundation" 41 | email "foo@icon.foundation" 42 | } 43 | } 44 | scm { 45 | url repoUrl 46 | } 47 | } 48 | 49 | publishing { 50 | repositories { 51 | maven { 52 | name = 'mavenCentral' 53 | def releasesUrl = "https://oss.sonatype.org/service/local/staging/deploy/maven2" 54 | def snapshotsUrl = "https://oss.sonatype.org/content/repositories/snapshots" 55 | url = version.endsWith('SNAPSHOT') ? snapshotsUrl : releasesUrl 56 | credentials { 57 | username = rootProject.hasProperty('mavenCentralUsername') ? "$mavenCentralUsername" : '' 58 | password = rootProject.hasProperty('mavenCentralPassword') ? "$mavenCentralPassword" : '' 59 | } 60 | } 61 | } 62 | publications { 63 | mavenJava(MavenPublication) { 64 | groupId = GROUP 65 | artifactId = projectName 66 | from components.java 67 | artifact sourcesJar 68 | artifact javadocJar 69 | pom.withXml { 70 | def root = asNode() 71 | root.appendNode('name', projectName) 72 | root.appendNode('description', 'An Integration Testing Framework for Java SCORE') 73 | root.appendNode('url', repoUrl) 74 | root.children().last() + pomConfig 75 | } 76 | } 77 | } 78 | } 79 | 80 | signing { 81 | required rootProject.hasProperty('release') 82 | if (rootProject.hasProperty('signingKey')) { 83 | def signingKey = rootProject.findProperty("signingKey") 84 | def signingPassword = rootProject.findProperty("signingPassword") 85 | useInMemoryPgpKeys(signingKey, signingPassword) 86 | } 87 | sign publishing.publications.mavenJava 88 | } 89 | -------------------------------------------------------------------------------- /testinteg/conf/env.props: -------------------------------------------------------------------------------- 1 | node.url=http://localhost:9082 2 | 3 | chain.nid=0x3 4 | chain.godWallet=godWallet.json 5 | chain.godPassword=gochain 6 | -------------------------------------------------------------------------------- /testinteg/conf/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 | -------------------------------------------------------------------------------- /testinteg/gradle.properties: -------------------------------------------------------------------------------- 1 | GROUP=foundation.icon 2 | VERSION=0.9.0 3 | -------------------------------------------------------------------------------- /testinteg/src/main/java/foundation/icon/test/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.test; 18 | 19 | import foundation.icon.icx.data.Address; 20 | 21 | import java.math.BigInteger; 22 | 23 | public class Constants { 24 | public static final BigInteger STATUS_SUCCESS = BigInteger.ONE; 25 | public static final BigInteger STATUS_FAILURE = BigInteger.ZERO; 26 | 27 | public static final BigInteger DEFAULT_STEPS = BigInteger.valueOf(100000); 28 | public static final long DEFAULT_WAITING_TIME = 7000; 29 | 30 | public static final Address SYSTEM_ADDRESS = 31 | new Address("cx0000000000000000000000000000000000000000"); 32 | public static final Address TREASURY_ADDRESS = 33 | new Address("hx1000000000000000000000000000000000000000"); 34 | 35 | public static final String CONTENT_TYPE_PYTHON = "application/zip"; 36 | public static final String CONTENT_TYPE_JAVA = "application/java"; 37 | } 38 | -------------------------------------------------------------------------------- /testinteg/src/main/java/foundation/icon/test/Env.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2020 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.test; 18 | 19 | import foundation.icon.icx.KeyWallet; 20 | import foundation.icon.icx.Wallet; 21 | import foundation.icon.icx.crypto.KeystoreException; 22 | 23 | import java.io.File; 24 | import java.io.FileInputStream; 25 | import java.io.IOException; 26 | import java.nio.file.Path; 27 | import java.util.Properties; 28 | 29 | public class Env { 30 | public static final Log LOG = Log.getGlobal(); 31 | private static Chain chain; 32 | private static String scoreRoot; 33 | 34 | static { 35 | String envFile = System.getProperty("env.props", "conf/env.props"); 36 | Properties props = new Properties(); 37 | try { 38 | LOG.info("Using env.props: " + envFile); 39 | FileInputStream fis = new FileInputStream(envFile); 40 | props.load(fis); 41 | fis.close(); 42 | } catch (IOException e) { 43 | System.err.printf("'%s' does not exist\n", envFile); 44 | throw new IllegalArgumentException(e.getMessage()); 45 | } 46 | String confPath = Path.of(envFile).getParent().toString() + "/"; 47 | readProperties(props, confPath); 48 | } 49 | 50 | private static void readProperties(Properties props, String confPath) { 51 | String chainName = "chain"; 52 | String nid = props.getProperty(chainName + ".nid"); 53 | if (nid == null) { 54 | throw new IllegalArgumentException("nid not found"); 55 | } 56 | String godWalletPath = confPath + props.getProperty(chainName + ".godWallet"); 57 | String godPassword = props.getProperty(chainName + ".godPassword"); 58 | KeyWallet godWallet; 59 | try { 60 | godWallet = readWalletFromFile(godWalletPath, godPassword); 61 | } catch (IOException e) { 62 | throw new IllegalArgumentException(e.getMessage()); 63 | } 64 | String nodeName = "node"; 65 | String url = props.getProperty(nodeName + ".url"); 66 | if (url == null) { 67 | throw new IllegalArgumentException("node url not found"); 68 | } 69 | chain = new Chain(Integer.parseInt(nid.substring(2), 16), godWallet, url); 70 | 71 | // try to read the default score root path 72 | scoreRoot = props.getProperty("score.root"); 73 | if (scoreRoot != null && !scoreRoot.endsWith("/")) { 74 | scoreRoot = scoreRoot + "/"; 75 | } 76 | } 77 | 78 | private static KeyWallet readWalletFromFile(String path, String password) throws IOException { 79 | try { 80 | File file = new File(path); 81 | return KeyWallet.load(password, file); 82 | } catch (KeystoreException e) { 83 | e.printStackTrace(); 84 | throw new IOException("Key load failed!"); 85 | } 86 | } 87 | 88 | public static String getScoreRoot() { 89 | return scoreRoot; 90 | } 91 | 92 | public static Chain getDefaultChain() { 93 | if (chain == null) { 94 | throw new AssertionError("Chain not found"); 95 | } 96 | return chain; 97 | } 98 | 99 | public static class Chain { 100 | public final int networkId; 101 | public final Wallet godWallet; 102 | private final String nodeUrl; 103 | 104 | public Chain(int networkId, Wallet godWallet, String url) { 105 | this.networkId = networkId; 106 | this.godWallet = godWallet; 107 | this.nodeUrl = url; 108 | } 109 | 110 | public String getEndpointURL(int v) { 111 | return this.nodeUrl + "/api/v" + v; 112 | } 113 | } 114 | } 115 | -------------------------------------------------------------------------------- /testinteg/src/main/java/foundation/icon/test/EventLog.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2020 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.test; 18 | 19 | import foundation.icon.icx.data.TransactionResult; 20 | 21 | import java.util.ArrayList; 22 | import java.util.List; 23 | 24 | import static foundation.icon.test.Env.LOG; 25 | 26 | public class EventLog { 27 | final private boolean debug; 28 | final private String score; 29 | final private String[] params; 30 | 31 | public EventLog(boolean debug, String score, String ...params) { 32 | this.debug = debug; 33 | this.score = score; 34 | this.params = params; 35 | } 36 | 37 | public EventLog(String score, String ...params) { 38 | this(false, score, params); 39 | } 40 | 41 | public boolean check(TransactionResult.EventLog log) { 42 | if (score != null && !score.equals(log.getScoreAddress())) { 43 | return false; 44 | } 45 | var items = new ArrayList<>(log.getIndexed()); 46 | var data = log.getData(); 47 | if (data != null) { 48 | items.addAll(data); 49 | } 50 | for (int idx = 0; idx < params.length; idx++) { 51 | debugInfo(String.format("params[%d] = %s", idx, params[idx])); 52 | if (params[idx] == null) continue; 53 | var item = items.get(idx); 54 | debugInfo(String.format(" item = %s", item != null ? item.asString() : "null")); 55 | if (item == null) { 56 | return false; 57 | } 58 | if (!params[idx].equals(item.asString())) { 59 | return false; 60 | } 61 | } 62 | return true; 63 | } 64 | 65 | public static boolean checkScenario(List scenario, TransactionResult result) { 66 | var itr = scenario.iterator(); 67 | var seq = itr.next(); 68 | for (var log : result.getEventLogs()) { 69 | if (seq.check(log)) { 70 | if (!itr.hasNext()) { 71 | return true; 72 | } 73 | seq = itr.next(); 74 | } 75 | } 76 | return false; 77 | } 78 | 79 | private void debugInfo(String msg) { 80 | if (debug) { 81 | LOG.info(msg); 82 | } 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /testinteg/src/main/java/foundation/icon/test/Log.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.test; 18 | 19 | import java.util.EmptyStackException; 20 | import java.util.Stack; 21 | 22 | public class Log { 23 | private static final String[] PREFIX_LEVELS = {null, "[S]", "[W]", null, null}; 24 | private static final String PREFIX_STEP_IN = "--> "; 25 | private static final String PREFIX_STEP_OUT = "<-- "; 26 | private static final String DEPTH_STRING = " "; 27 | 28 | private static final int LEVEL_START = 0; 29 | public static final int LEVEL_NONE = LEVEL_START; 30 | public static final int LEVEL_SEVERE = LEVEL_NONE + 1; 31 | public static final int LEVEL_WARNING = LEVEL_SEVERE + 1; 32 | public static final int LEVEL_INFO = LEVEL_WARNING + 1; 33 | public static final int LEVEL_DEBUG = LEVEL_INFO + 1; 34 | private static final int LEVEL_END = LEVEL_DEBUG; 35 | 36 | private int level = LEVEL_INFO; 37 | private Stack frames = new Stack<>(); 38 | 39 | public static Log getGlobal() { 40 | return new Log(); 41 | } 42 | 43 | public void setLevel(int newLevel) { 44 | if (newLevel >= LEVEL_START && newLevel <= LEVEL_END) { 45 | level = newLevel; 46 | } 47 | } 48 | 49 | private boolean isLoggable(int level) { 50 | return this.level >= level && level > LEVEL_START; 51 | } 52 | 53 | public void info(String msg) { 54 | log(LEVEL_INFO, msg); 55 | } 56 | 57 | public void warning(String msg) { 58 | log(LEVEL_WARNING, msg); 59 | } 60 | 61 | public void severe(String msg) { 62 | log(LEVEL_SEVERE, msg); 63 | } 64 | 65 | public void infoEntering(String taskName, String msg) { 66 | if (taskName == null) { 67 | taskName = ""; 68 | } 69 | if (msg == null) { 70 | msg = ""; 71 | } 72 | StringBuilder buf = new StringBuilder(5 + taskName.length() + msg.length()); 73 | buf.append(PREFIX_STEP_IN).append(taskName); 74 | if (msg.length() > 0) { 75 | buf.append(": ").append(msg); 76 | } 77 | log(LEVEL_INFO, buf.toString()); 78 | frames.push(taskName); 79 | } 80 | 81 | public void infoEntering(String taskName) { 82 | infoEntering(taskName, null); 83 | } 84 | 85 | public void infoExiting(String msg) { 86 | if (msg == null) { 87 | msg = ""; 88 | } 89 | try { 90 | String taskName = frames.pop(); 91 | StringBuilder buf = new StringBuilder(5 + taskName.length() + msg.length()); 92 | buf.append(PREFIX_STEP_OUT).append(taskName); 93 | if (msg.length() > 0) { 94 | buf.append(": ").append(msg); 95 | } 96 | log(LEVEL_INFO, buf.toString()); 97 | } catch (EmptyStackException e) { 98 | log(LEVEL_WARNING, "(INVALID) Exiting without no entering" + msg); 99 | } 100 | } 101 | 102 | public void infoExiting() { 103 | infoExiting(null); 104 | } 105 | 106 | public void debug(String msg) { 107 | log(LEVEL_DEBUG, msg); 108 | } 109 | 110 | public void log(int level, String msg) { 111 | if (msg != null && isLoggable(level)) { 112 | if (PREFIX_LEVELS[level] != null || !frames.empty()) { 113 | StringBuilder buf = new StringBuilder(msg.length() + frames.size() * 3 + 3); 114 | for (int i = frames.size(); i > 0; i--) { 115 | buf.append(DEPTH_STRING); 116 | } 117 | if (PREFIX_LEVELS[level] != null) { 118 | buf.append(PREFIX_LEVELS[level]); 119 | } 120 | buf.append(msg); 121 | msg = buf.toString(); 122 | } 123 | System.out.println(msg); 124 | } 125 | } 126 | } 127 | -------------------------------------------------------------------------------- /testinteg/src/main/java/foundation/icon/test/ResultTimeoutException.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.test; 18 | 19 | import foundation.icon.icx.data.Bytes; 20 | 21 | public class ResultTimeoutException extends Exception { 22 | Bytes txHash; 23 | 24 | public ResultTimeoutException() { 25 | super(); 26 | } 27 | 28 | public ResultTimeoutException(String message) { 29 | super(message); 30 | } 31 | 32 | public ResultTimeoutException(Bytes txHash) { 33 | super("Timeout. txHash=" + txHash); 34 | this.txHash = txHash; 35 | } 36 | 37 | public Bytes getTxHash() { 38 | return this.txHash; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /testinteg/src/main/java/foundation/icon/test/TestBase.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2020 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.test; 18 | 19 | import foundation.icon.icx.data.Address; 20 | import foundation.icon.icx.data.Bytes; 21 | import foundation.icon.icx.data.TransactionResult; 22 | import org.opentest4j.AssertionFailedError; 23 | 24 | import java.io.IOException; 25 | import java.math.BigInteger; 26 | import java.util.ArrayList; 27 | import java.util.List; 28 | 29 | import static foundation.icon.test.Env.LOG; 30 | import static org.junit.jupiter.api.Assertions.assertEquals; 31 | import static org.junit.jupiter.api.Assertions.fail; 32 | 33 | public class TestBase { 34 | protected static final BigInteger ICX = BigInteger.TEN.pow(18); 35 | 36 | protected static void assertSuccess(TransactionResult result) { 37 | assertStatus(Constants.STATUS_SUCCESS, result); 38 | } 39 | 40 | protected static void assertFailure(TransactionResult result) { 41 | assertStatus(Constants.STATUS_FAILURE, result); 42 | LOG.info("Expected " + result.getFailure()); 43 | } 44 | 45 | protected static void assertStatus(BigInteger status, TransactionResult result) { 46 | try { 47 | assertEquals(status, result.getStatus()); 48 | } catch (AssertionFailedError e) { 49 | LOG.info("Assertion Failed: result=" + result); 50 | fail(e.getMessage()); 51 | } 52 | } 53 | 54 | protected static void transferAndCheckResult(TransactionHandler txHandler, Address to, BigInteger amount) 55 | throws IOException, ResultTimeoutException { 56 | Bytes txHash = txHandler.transfer(to, amount); 57 | assertSuccess(txHandler.getResult(txHash)); 58 | } 59 | 60 | protected static void transferAndCheckResult(TransactionHandler txHandler, Address[] addresses, BigInteger amount) 61 | throws IOException, ResultTimeoutException { 62 | List hashes = new ArrayList<>(); 63 | for (Address to : addresses) { 64 | hashes.add(txHandler.transfer(to, amount)); 65 | } 66 | for (Bytes hash : hashes) { 67 | assertSuccess(txHandler.getResult(hash)); 68 | } 69 | } 70 | 71 | protected static void ensureIcxBalance(TransactionHandler txHandler, Address address, 72 | BigInteger oldVal, BigInteger newVal) throws Exception { 73 | long limitTime = System.currentTimeMillis() + Constants.DEFAULT_WAITING_TIME; 74 | while (true) { 75 | BigInteger icxBalance = txHandler.getBalance(address); 76 | String msg = "ICX balance of " + address + ": " + icxBalance; 77 | if (icxBalance.equals(oldVal)) { 78 | if (limitTime < System.currentTimeMillis()) { 79 | throw new ResultTimeoutException(); 80 | } 81 | try { 82 | // wait until block confirmation 83 | LOG.debug(msg + "; Retry in 1 sec."); 84 | Thread.sleep(1000); 85 | } catch (InterruptedException e) { 86 | e.printStackTrace(); 87 | } 88 | } else if (icxBalance.equals(newVal)) { 89 | LOG.info(msg); 90 | break; 91 | } else { 92 | throw new IOException(String.format("ICX balance mismatch: expected <%s>, but was <%s>", 93 | newVal, icxBalance)); 94 | } 95 | } 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /testinteg/src/main/java/foundation/icon/test/TransactionFailureException.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.test; 18 | 19 | import foundation.icon.icx.data.TransactionResult; 20 | 21 | import java.math.BigInteger; 22 | 23 | public class TransactionFailureException extends Exception { 24 | private final TransactionResult.Failure failure; 25 | 26 | public TransactionFailureException(TransactionResult.Failure failure) { 27 | this.failure = failure; 28 | } 29 | 30 | @Override 31 | public String toString() { 32 | return this.failure.toString(); 33 | } 34 | 35 | public BigInteger getCode() { 36 | return this.failure.getCode(); 37 | } 38 | 39 | public String getMessage() { 40 | return this.failure.getMessage(); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /testinteg/src/main/java/foundation/icon/test/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.test; 18 | 19 | import foundation.icon.icx.Call; 20 | import foundation.icon.icx.IconService; 21 | import foundation.icon.icx.SignedTransaction; 22 | import foundation.icon.icx.Transaction; 23 | import foundation.icon.icx.TransactionBuilder; 24 | import foundation.icon.icx.Wallet; 25 | import foundation.icon.icx.data.Address; 26 | import foundation.icon.icx.data.Bytes; 27 | import foundation.icon.icx.data.ConfirmedTransaction; 28 | import foundation.icon.icx.data.ScoreApi; 29 | import foundation.icon.icx.data.TransactionResult; 30 | import foundation.icon.icx.transport.jsonrpc.RpcError; 31 | import foundation.icon.icx.transport.jsonrpc.RpcItem; 32 | import foundation.icon.icx.transport.jsonrpc.RpcObject; 33 | import foundation.icon.test.score.ChainScore; 34 | import foundation.icon.test.score.Score; 35 | import foundation.icon.test.util.ZipFile; 36 | 37 | import java.io.IOException; 38 | import java.math.BigInteger; 39 | import java.nio.file.Files; 40 | import java.nio.file.Path; 41 | import java.util.List; 42 | 43 | import static foundation.icon.test.Env.LOG; 44 | 45 | public class TransactionHandler { 46 | private final IconService iconService; 47 | private final Env.Chain chain; 48 | 49 | public TransactionHandler(IconService iconService, Env.Chain chain) { 50 | this.iconService = iconService; 51 | this.chain = chain; 52 | } 53 | 54 | public Score deploy(Wallet owner, String scorePath, RpcObject params) 55 | throws IOException, ResultTimeoutException, TransactionFailureException { 56 | return deploy(owner, scorePath, params, null); 57 | } 58 | 59 | public Score deploy(Wallet owner, String scorePath, RpcObject params, BigInteger steps) 60 | throws IOException, ResultTimeoutException, TransactionFailureException { 61 | return deploy(owner, scorePath, Constants.SYSTEM_ADDRESS, params, steps); 62 | } 63 | 64 | public Score deploy(Wallet owner, String scorePath, Address to, RpcObject params, BigInteger steps) 65 | throws IOException, ResultTimeoutException, TransactionFailureException { 66 | if (scorePath.endsWith(".jar")) { 67 | byte[] data = Files.readAllBytes(Path.of(scorePath)); 68 | return getScore(doDeploy(owner, data, to, params, steps, Constants.CONTENT_TYPE_JAVA)); 69 | } else { 70 | byte[] data = ZipFile.zipContent(scorePath); 71 | return getScore(doDeploy(owner, data, to, params, steps, Constants.CONTENT_TYPE_PYTHON)); 72 | } 73 | } 74 | 75 | public Bytes doDeploy(Wallet owner, byte[] content, Address to, RpcObject params, 76 | BigInteger steps, String contentType) throws IOException { 77 | Transaction transaction = TransactionBuilder.newBuilder() 78 | .nid(getNetworkId()) 79 | .from(owner.getAddress()) 80 | .to(to) 81 | .deploy(contentType, content) 82 | .params(params) 83 | .build(); 84 | if (steps == null) { 85 | steps = estimateStep(transaction); 86 | } 87 | SignedTransaction signedTransaction = new SignedTransaction(transaction, owner, steps); 88 | return iconService.sendTransaction(signedTransaction).execute(); 89 | } 90 | 91 | public Score getScore(Bytes txHash) 92 | throws IOException, ResultTimeoutException, TransactionFailureException { 93 | TransactionResult result = getResult(txHash, Constants.DEFAULT_WAITING_TIME); 94 | if (!Constants.STATUS_SUCCESS.equals(result.getStatus())) { 95 | throw new TransactionFailureException(result.getFailure()); 96 | } 97 | return new Score(this, new Address(result.getScoreAddress())); 98 | } 99 | 100 | public Bytes deployOnly(Wallet owner, String scorePath, RpcObject params) throws IOException { 101 | return deployOnly(owner, Constants.SYSTEM_ADDRESS, scorePath, params); 102 | } 103 | 104 | public Bytes deployOnly(Wallet owner, Address to, String scorePath, RpcObject params) throws IOException { 105 | byte[] data = ZipFile.zipContent(scorePath); 106 | return doDeploy(owner, data, to, params, null, Constants.CONTENT_TYPE_PYTHON); 107 | } 108 | 109 | public Env.Chain getChain() { 110 | return this.chain; 111 | } 112 | 113 | public BigInteger getNetworkId() { 114 | return BigInteger.valueOf(chain.networkId); 115 | } 116 | 117 | public BigInteger getBalance(Address address) throws IOException { 118 | return iconService.getBalance(address).execute(); 119 | } 120 | 121 | public List getScoreApi(Address scoreAddress) throws IOException { 122 | return iconService.getScoreApi(scoreAddress).execute(); 123 | } 124 | 125 | public BigInteger estimateStep(Transaction transaction) throws IOException { 126 | try { 127 | return iconService.estimateStep(transaction).execute(); 128 | } catch (RpcError e) { 129 | LOG.info("estimateStep failed(" + e.getCode() + ", " + e.getMessage() + "); use default steps."); 130 | return Constants.DEFAULT_STEPS.multiply(BigInteger.TEN); 131 | } 132 | } 133 | 134 | public RpcItem call(Call call) throws IOException { 135 | return this.iconService.call(call).execute(); 136 | } 137 | 138 | public Bytes invoke(Wallet wallet, Transaction tx, BigInteger steps) throws IOException { 139 | if (steps == null) { 140 | steps = estimateStep(tx); 141 | } 142 | return this.iconService.sendTransaction(new SignedTransaction(tx, wallet, steps)).execute(); 143 | } 144 | 145 | public TransactionResult getResult(Bytes txHash) 146 | throws IOException, ResultTimeoutException { 147 | return getResult(txHash, Constants.DEFAULT_WAITING_TIME); 148 | } 149 | 150 | public TransactionResult getResult(Bytes txHash, long waiting) 151 | throws IOException, ResultTimeoutException { 152 | long limitTime = System.currentTimeMillis() + waiting; 153 | while (true) { 154 | try { 155 | return iconService.getTransactionResult(txHash).execute(); 156 | } catch (RpcError e) { 157 | if (e.getCode() == -31002 /* pending */ 158 | || e.getCode() == -31003 /* executing */ 159 | || e.getCode() == -31004 /* not found */) { 160 | if (limitTime < System.currentTimeMillis()) { 161 | throw new ResultTimeoutException(txHash); 162 | } 163 | try { 164 | // wait until block confirmation 165 | LOG.debug("RpcError: code(" + e.getCode() + ") message(" + e.getMessage() + "); Retry in 1 sec."); 166 | Thread.sleep(1000); 167 | } catch (InterruptedException ex) { 168 | ex.printStackTrace(); 169 | } 170 | continue; 171 | } 172 | LOG.warning("RpcError: code(" + e.getCode() + ") message(" + e.getMessage() + ")"); 173 | throw e; 174 | } 175 | } 176 | } 177 | 178 | public Bytes transfer(Address to, BigInteger amount) throws IOException { 179 | return transfer(chain.godWallet, to, amount); 180 | } 181 | 182 | public Bytes transfer(Wallet owner, Address to, BigInteger amount) throws IOException { 183 | return transfer(owner, to, amount, null); 184 | } 185 | 186 | public Bytes transfer(Wallet owner, Address to, BigInteger amount, BigInteger steps) throws IOException { 187 | Transaction transaction = TransactionBuilder.newBuilder() 188 | .nid(getNetworkId()) 189 | .from(owner.getAddress()) 190 | .to(to) 191 | .value(amount) 192 | .build(); 193 | if (steps == null) { 194 | steps = estimateStep(transaction).add(BigInteger.valueOf(10000)); 195 | } 196 | SignedTransaction signedTransaction = new SignedTransaction(transaction, owner, steps); 197 | return iconService.sendTransaction(signedTransaction).execute(); 198 | } 199 | 200 | public void refundAll(Wallet owner) throws IOException { 201 | BigInteger stepPrice = new ChainScore(this).getStepPrice(); 202 | BigInteger remaining = getBalance(owner.getAddress()); 203 | BigInteger fee = Constants.DEFAULT_STEPS.multiply(stepPrice); 204 | transfer(owner, chain.godWallet.getAddress(), remaining.subtract(fee), Constants.DEFAULT_STEPS); 205 | } 206 | 207 | public ConfirmedTransaction getTransaction(Bytes txHash) throws IOException { 208 | return iconService.getTransaction(txHash).execute(); 209 | } 210 | } 211 | -------------------------------------------------------------------------------- /testinteg/src/main/java/foundation/icon/test/score/ChainScore.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2020 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.test.score; 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 | import foundation.icon.icx.transport.jsonrpc.RpcValue; 23 | import foundation.icon.test.Constants; 24 | import foundation.icon.test.TransactionHandler; 25 | 26 | import java.io.IOException; 27 | import java.math.BigInteger; 28 | import java.util.HashMap; 29 | import java.util.Map; 30 | import java.util.Set; 31 | 32 | public class ChainScore extends Score { 33 | private static final int CONFIG_AUDIT = 0x2; 34 | 35 | public ChainScore(TransactionHandler txHandler) { 36 | super(txHandler, Constants.SYSTEM_ADDRESS); 37 | } 38 | 39 | public int getRevision() throws IOException { 40 | return call("getRevision", null).asInteger().intValue(); 41 | } 42 | 43 | public BigInteger getStepPrice() throws IOException { 44 | return call("getStepPrice", null).asInteger(); 45 | } 46 | 47 | public int getServiceConfig() throws IOException { 48 | return call("getServiceConfig", null).asInteger().intValue(); 49 | } 50 | 51 | public Map getStepCosts() throws Exception { 52 | RpcItem rpcItem = call("getStepCosts", null); 53 | Map map = new HashMap<>(); 54 | Set stepCostTypes = rpcItem.asObject().keySet(); 55 | for (String type: stepCostTypes) { 56 | map.put(type, rpcItem.asObject().getItem(type).asInteger()); 57 | } 58 | return map; 59 | } 60 | 61 | public static boolean isAuditEnabled(int config) { 62 | return (config & CONFIG_AUDIT) != 0; 63 | } 64 | 65 | public boolean isAuditEnabled() throws IOException { 66 | return isAuditEnabled(this.getServiceConfig()); 67 | } 68 | 69 | public RpcObject getScoreStatus(Address address) throws IOException { 70 | RpcObject params = new RpcObject.Builder() 71 | .put("address", new RpcValue(address)) 72 | .build(); 73 | return call("getScoreStatus", params).asObject(); 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /testinteg/src/main/java/foundation/icon/test/score/Score.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.test.score; 18 | 19 | import foundation.icon.icx.Call; 20 | import foundation.icon.icx.Transaction; 21 | import foundation.icon.icx.TransactionBuilder; 22 | import foundation.icon.icx.Wallet; 23 | import foundation.icon.icx.data.Address; 24 | import foundation.icon.icx.data.Bytes; 25 | import foundation.icon.icx.data.TransactionResult; 26 | import foundation.icon.icx.data.TransactionResult.EventLog; 27 | import foundation.icon.icx.transport.jsonrpc.RpcItem; 28 | import foundation.icon.icx.transport.jsonrpc.RpcObject; 29 | import foundation.icon.test.Constants; 30 | import foundation.icon.test.Env; 31 | import foundation.icon.test.ResultTimeoutException; 32 | import foundation.icon.test.TransactionHandler; 33 | 34 | import java.io.IOException; 35 | import java.math.BigInteger; 36 | import java.util.List; 37 | 38 | public class Score { 39 | private final TransactionHandler txHandler; 40 | private final Address address; 41 | 42 | public Score(TransactionHandler txHandler, Address scoreAddress) { 43 | this.txHandler = txHandler; 44 | this.address = scoreAddress; 45 | } 46 | 47 | public Score(Score other) { 48 | this(other.txHandler, other.address); 49 | } 50 | 51 | public static String getFilePath(String pkgName) { 52 | String key = "score.path." + pkgName; 53 | String path = System.getProperty(key); 54 | if (path == null) { 55 | String scoreRoot = Env.getScoreRoot(); 56 | if (scoreRoot != null) { 57 | return scoreRoot + pkgName; 58 | } 59 | throw new IllegalArgumentException("No such property: " + key); 60 | } 61 | return path; 62 | } 63 | 64 | protected static EventLog findEventLog(TransactionResult result, Address scoreAddress, String funcSig) { 65 | List eventLogs = result.getEventLogs(); 66 | for (EventLog event : eventLogs) { 67 | if (event.getScoreAddress().equals(scoreAddress.toString())) { 68 | String signature = event.getIndexed().get(0).asString(); 69 | if (funcSig.equals(signature)) { 70 | return event; 71 | } 72 | } 73 | } 74 | return null; 75 | } 76 | 77 | public RpcItem call(String method, RpcObject params) 78 | throws IOException { 79 | if (params == null) { 80 | params = new RpcObject.Builder().build(); 81 | } 82 | Call call = new Call.Builder() 83 | .to(getAddress()) 84 | .method(method) 85 | .params(params) 86 | .build(); 87 | return this.txHandler.call(call); 88 | } 89 | 90 | public Bytes invoke(Wallet wallet, String method, RpcObject params) throws IOException { 91 | return invoke(wallet, method, params, BigInteger.ZERO, null); 92 | } 93 | 94 | public Bytes invoke(Wallet wallet, String method, RpcObject params, 95 | BigInteger value, BigInteger steps) throws IOException { 96 | return invoke(wallet, method, params, value, steps, null, null); 97 | } 98 | 99 | public Bytes invoke(Wallet wallet, Transaction tx) throws IOException { 100 | return this.txHandler.invoke(wallet, tx, null); 101 | } 102 | 103 | public Bytes invoke(Wallet wallet, String method, RpcObject params, BigInteger value, 104 | BigInteger steps, BigInteger timestamp, BigInteger nonce) throws IOException { 105 | Transaction tx = getTransaction(wallet, method, params, value, timestamp, nonce); 106 | return this.txHandler.invoke(wallet, tx, steps); 107 | } 108 | 109 | private Transaction getTransaction(Wallet wallet, String method, RpcObject params, BigInteger value, 110 | BigInteger timestamp, BigInteger nonce) { 111 | TransactionBuilder.Builder builder = TransactionBuilder.newBuilder() 112 | .nid(getNetworkId()) 113 | .from(wallet.getAddress()) 114 | .to(getAddress()); 115 | 116 | if ((value != null) && value.bitLength() != 0) { 117 | builder.value(value); 118 | } 119 | if ((timestamp != null) && timestamp.bitLength() != 0) { 120 | builder.timestamp(timestamp); 121 | } 122 | if (nonce != null) { 123 | builder.nonce(nonce); 124 | } 125 | 126 | Transaction tx; 127 | if (params != null) { 128 | tx = builder.call(method).params(params).build(); 129 | } else { 130 | tx = builder.call(method).build(); 131 | } 132 | return tx; 133 | } 134 | 135 | public TransactionResult invokeAndWaitResult(Wallet wallet, String method, RpcObject params) 136 | throws ResultTimeoutException, IOException { 137 | return invokeAndWaitResult(wallet, method, params, null, null); 138 | } 139 | 140 | public TransactionResult invokeAndWaitResult(Wallet wallet, String method, RpcObject params, 141 | BigInteger steps) 142 | throws ResultTimeoutException, IOException { 143 | return invokeAndWaitResult(wallet, method, params, null, steps); 144 | } 145 | 146 | public TransactionResult invokeAndWaitResult(Wallet wallet, String method, RpcObject params, 147 | BigInteger value, BigInteger steps) 148 | throws ResultTimeoutException, IOException { 149 | Bytes txHash = this.invoke(wallet, method, params, value, steps); 150 | return getResult(txHash); 151 | } 152 | 153 | public TransactionResult getResult(Bytes txHash) throws ResultTimeoutException, IOException { 154 | return getResult(txHash, Constants.DEFAULT_WAITING_TIME); 155 | } 156 | 157 | public TransactionResult getResult(Bytes txHash, long waiting) throws ResultTimeoutException, IOException { 158 | return this.txHandler.getResult(txHash, waiting); 159 | } 160 | 161 | protected TransactionHandler getTxHandler() { 162 | return this.txHandler; 163 | } 164 | 165 | public Address getAddress() { 166 | return this.address; 167 | } 168 | 169 | public BigInteger getNetworkId() { 170 | return txHandler.getNetworkId(); 171 | } 172 | 173 | @Override 174 | public String toString() { 175 | return "SCORE(" + getAddress().toString() + ")"; 176 | } 177 | } 178 | -------------------------------------------------------------------------------- /testinteg/src/main/java/foundation/icon/test/util/ZipFile.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2020 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.test.util; 18 | 19 | import java.io.ByteArrayOutputStream; 20 | import java.io.File; 21 | import java.io.IOException; 22 | import java.nio.file.Files; 23 | import java.util.zip.ZipEntry; 24 | import java.util.zip.ZipOutputStream; 25 | 26 | public class ZipFile { 27 | public static byte[] zipContent(String path) throws IOException { 28 | ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); 29 | ZipOutputStream zos = new ZipOutputStream(outputStream); 30 | recursiveZip(new File(path), null, zos); 31 | zos.close(); 32 | outputStream.close(); 33 | return outputStream.toByteArray(); 34 | } 35 | 36 | private static void recursiveZip(File source, String zipPath, ZipOutputStream zos) throws IOException { 37 | if (source.isHidden()) { 38 | return; 39 | } 40 | if (source.isDirectory()) { 41 | String dir = source.getName(); 42 | if (!dir.endsWith(File.separator)) { 43 | dir = dir + File.separator; 44 | } 45 | zos.putNextEntry(new ZipEntry(dir)); 46 | zos.closeEntry(); 47 | File[] files = source.listFiles(); 48 | if (files == null) { 49 | return; 50 | } 51 | String path = zipPath == null ? dir : zipPath + dir; 52 | for (File file : files) { 53 | recursiveZip(file, path, zos); 54 | } 55 | } else { 56 | ZipEntry ze = new ZipEntry(zipPath + source.getName()); 57 | zos.putNextEntry(ze); 58 | zos.write(Files.readAllBytes(source.toPath())); 59 | zos.closeEntry(); 60 | } 61 | } 62 | } 63 | --------------------------------------------------------------------------------