diff --git a/.gitignore b/.gitignore index 13c9c3fe..c15ea32a 100644 --- a/.gitignore +++ b/.gitignore @@ -49,11 +49,3 @@ docs/build **/.project **/.settings **/bin - -gradle/bintray -gradle/jacoco -gradle/java -gradle/javadoc -gradle/publish -gradle/repositories -gradle/spotless \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 01849a08..fadabf64 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,7 +3,7 @@ All notable changes to this project will be documented in this file. See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. -# [4.11.3]() (Upcoming) +# [4.12.3]() (Upcoming) ### Bug Fixes @@ -11,6 +11,7 @@ See [Conventional Commits](https://conventionalcommits.org) for commit guideline ### Features +* updated to gradle 8.7 and removed Epirus [#113](https://github.com/hyperledger/web3j-openapi/pull/113) * Bump snapshot version to 4.11.3 [#109](https://github.com/hyperledger/web3j-openapi/pull/109) ### BREAKING CHANGES diff --git a/README.md b/README.md index 96a72838..d69f476f 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,8 @@ Web3j Open API [![Build Status](https://travis-ci.org/web3j/web3j-openapi.svg?branch=master)](https://travis-ci.org/web3j/web3j-openapi) Web3j-OpenAPI is a [OpenAPI](https://swagger.io/specification/) client and server generator from -[Solidity](https://solidity.readthedocs.io/) smart contracts. it provides a way to interact with the Ethereum blockchain via simple and intuitive HTTP requests, abstracting the coding layer. These interactions can be done using : +[Solidity](https://solidity.readthedocs.io/) smart contracts. it provides a way to interact with the Ethereum blockchain via simple and intuitive +HTTP requests, abstracting the coding layer. These interactions can be done using : - Plain HTTP requests - Via the `Swagger-UI`, which is generated with every project - A client application using the [`webj3-openapi-client`](/client) implementation @@ -16,31 +17,25 @@ The workflow can be summed in the following steps: - Sending HTTP requests using `Swagger-UI`, client application or `Curl` request. # Getting started with Web3j-OpenAPI -To generate an OpenAPI project using the [Web3j-OpenAPI](https://github.com/web3j/web3j-openapi) generator, you need to have the [Epirus-CLI](https://docs.epirus.io/quickstart) installed on your machine (Note - the Epirus CLI has replaced the Web3j CLI). -It’s easy to do (for Windows instructions head [here](https://docs.epirus.io/quickstart/#installation)): +To generate an OpenAPI project using the [Web3j-OpenAPI](https://github.com/hyperledger/web3j-openapi) generator, +you need to have the [Web3j-CLI](https://docs.web3j.io/latest/command_line_tools/) installed on your machine. +It’s easy to do (for Windows instructions head [here](https://github.com/hyperledger/web3j-cli/)): ```ssh -$ curl -L get.epirus.io | sh +$ curl -L get.web3j.io | sh ``` ### Create a Hello World project To create a base OpenAPI project using a `Hello World` contract, run the following : ```ssh -$ epirus openapi new +$ web3j openapi new ``` You can also generate a `Web3j-OpenAPI` project using the [Web3j-OpenAPI-gradle-plugin](https://github.com/web3j/web3j-openapi-gradle-plugin). ### Configure the project -After having the generated project, you can use the [Epirus-CLI](https://docs.epirus.io) to run it using the following command (Note: You will need to create an [Epirus](https://www.web3labs.com/epirus) Account). - -```ssh -$ epirus login -$ epirus run rinkeby|ropsten -``` - -Alternatively, you can configure your application with the following environment variables: +After having the generated project, you can configure your application with the following environment variables: ```ssh $ export WEB3J_ENDPOINT= @@ -50,7 +45,7 @@ $ export WEB3J_OPENAPI_PORT=9090 ``` ### Run the project -If you aren't using the [Epirus-CLI](https://docs.epirus.io/quickstart/#deployment), you may run the project using the following Gradle target: +If you aren't using the Web3j-CLI you may run the project using the following Gradle target: ```ssh $ cd @@ -70,7 +65,7 @@ The easiest way to interact with the generated project is via the generated `Swa Also, you can use our client implementation via adding the following dependency to your project: ```groovy dependencies { - implementation "org.web3j.openapi:web3j-openapi-client:4.7.1" + implementation "org.web3j.openapi:web3j-openapi-client:4.12.2" } ``` diff --git a/build.gradle b/build.gradle index 83ad19b5..d7f6dd5d 100644 --- a/build.gradle +++ b/build.gradle @@ -5,15 +5,14 @@ buildscript { } dependencies { classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:${kotlinVersion}" - classpath 'com.jfrog.bintray.gradle:gradle-bintray-plugin:1.8.5' - classpath 'org.unbroken-dome.gradle-plugins:gradle-testsets-plugin:4.0.0' + classpath 'org.unbroken-dome.gradle-plugins:gradle-testsets-plugin:4.1.0' } } plugins { - id 'de.undercouch.download' version '4.1.1' - id 'com.diffplug.gradle.spotless' version '4.5.1' - id 'io.codearte.nexus-staging' version '0.22.0' + id 'de.undercouch.download' version '4.1.2' + id 'com.diffplug.spotless' version '6.25.0' + id 'io.codearte.nexus-staging' version '0.30.0' id 'de.marcphilipp.nexus-publish' version '0.4.0' } @@ -34,7 +33,6 @@ subprojects { apply { [ - 'bintray', 'publish', 'jacoco', 'java', @@ -113,4 +111,8 @@ subprojects { } sourceCompatibility = 17 + + tasks.named("spotlessJava") { + dependsOn(tasks.named("spotlessGroovyGradle")) + } } diff --git a/client/build.gradle b/client/build.gradle index 5269c717..10c4245f 100644 --- a/client/build.gradle +++ b/client/build.gradle @@ -12,5 +12,12 @@ dependencies { implementation "com.fasterxml.jackson.module:jackson-module-kotlin:${versions.jackson}" } -// To publish in mavenLocal() -// tasks.withType(Sign)*.enabled = false +tasks.named("spotlessJava") { + dependsOn(tasks.named("spotlessGroovyGradle")) + dependsOn(tasks.named("compileKotlin")) +} + +tasks.named("spotlessKotlin") { + dependsOn(tasks.named("spotlessGroovyGradle")) + dependsOn(tasks.named("spotlessJava")) +} diff --git a/client/src/main/kotlin/org/web3j/openapi/client/ClientException.kt b/client/src/main/kotlin/org/web3j/openapi/client/ClientException.kt index 6388bcb2..970d5bff 100644 --- a/client/src/main/kotlin/org/web3j/openapi/client/ClientException.kt +++ b/client/src/main/kotlin/org/web3j/openapi/client/ClientException.kt @@ -20,7 +20,7 @@ import javax.ws.rs.core.MediaType * Client API exception containing error data. */ class ClientException internal constructor( - val error: ErrorResponse? + val error: ErrorResponse?, ) : RuntimeException(error?.title) { companion object { @@ -34,8 +34,8 @@ class ClientException internal constructor( ErrorResponse( title = exception.response.statusInfo.reasonPhrase, requestUrl = exception.response.location?.toString(), - responseStatus = exception.response.status - ) + responseStatus = exception.response.status, + ), ) } } diff --git a/client/src/main/kotlin/org/web3j/openapi/client/ClientInvocationHandler.kt b/client/src/main/kotlin/org/web3j/openapi/client/ClientInvocationHandler.kt index 40bff328..f7bb14e7 100644 --- a/client/src/main/kotlin/org/web3j/openapi/client/ClientInvocationHandler.kt +++ b/client/src/main/kotlin/org/web3j/openapi/client/ClientInvocationHandler.kt @@ -38,7 +38,7 @@ import javax.ws.rs.sse.SseEventSource */ internal class ClientInvocationHandler( private val target: WebTarget, - private val client: Any + private val client: Any, ) : InvocationHandler { override fun invoke(proxy: Any, method: Method, args: Array?): Any? { @@ -71,7 +71,7 @@ internal class ClientInvocationHandler( Proxy.newProxyInstance( method.returnType.classLoader, arrayOf(method.returnType), - ClientInvocationHandler(target, it) + ClientInvocationHandler(target, it), ) } else { it @@ -91,7 +91,7 @@ internal class ClientInvocationHandler( } else { logger.error { "Unexpected exception while invoking method $method: " + - (error.message ?: error::class.java.canonicalName) + (error.message ?: error::class.java.canonicalName) } error.targetException } @@ -101,7 +101,7 @@ internal class ClientInvocationHandler( private fun handleClientError(error: ClientErrorException, method: Method): RuntimeException { logger.error { "Client exception while invoking method $method: " + - (error.message ?: error.response.statusInfo.reasonPhrase) + (error.message ?: error.response.statusInfo.reasonPhrase) } return ClientException.of(error) } @@ -115,9 +115,9 @@ internal class ClientInvocationHandler( } private fun Method.isEvent() = name == "onEvent" && - parameterTypes.size == 1 && - parameterTypes[0] == Consumer::class.java && - returnType == CompletableFuture::class.java + parameterTypes.size == 1 && + parameterTypes[0] == Consumer::class.java && + returnType == CompletableFuture::class.java private val Any.typeArguments: List> get() { @@ -128,13 +128,13 @@ internal class ClientInvocationHandler( private class SseEventSourceResult( private val source: SseEventSource, onEvent: Consumer, - eventType: Class + eventType: Class, ) : CompletableFuture() { init { source.register( { onEvent.accept(it.readData(eventType)) }, { completeExceptionally(it) }, - { complete(null) } + { complete(null) }, ) whenComplete { _, _ -> // Close the source gracefully by client diff --git a/client/src/main/kotlin/org/web3j/openapi/client/ClientService.kt b/client/src/main/kotlin/org/web3j/openapi/client/ClientService.kt index 321288fe..da9d72ae 100644 --- a/client/src/main/kotlin/org/web3j/openapi/client/ClientService.kt +++ b/client/src/main/kotlin/org/web3j/openapi/client/ClientService.kt @@ -28,10 +28,10 @@ import java.util.logging.Logger import javax.ws.rs.client.Client import javax.ws.rs.client.ClientBuilder -class ClientService @JvmOverloads constructor ( +class ClientService @JvmOverloads constructor( val uri: String, readTimeout: Int = DEFAULT_READ_TIMEOUT, - connectTimeout: Int = DEFAULT_CONNECT_TIMEOUT + connectTimeout: Int = DEFAULT_CONNECT_TIMEOUT, ) : AutoCloseable { private val mapper = jacksonObjectMapper() diff --git a/codegen/build.gradle b/codegen/build.gradle index 1134a35b..593bc3d9 100644 --- a/codegen/build.gradle +++ b/codegen/build.gradle @@ -69,5 +69,17 @@ task copyIntegrationTestResources(type: Copy) { integrationTest.dependsOn copyIntegrationTestResources, publishToMavenLocal -// To publish in mavenLocal() -// tasks.withType(Sign)*.enabled = false +tasks.named("spotlessKotlin") { + dependsOn(tasks.named("spotlessGroovyGradle")) + dependsOn(tasks.named("spotlessJava")) + dependsOn(tasks.named("test")) +} + +tasks.named("spotlessJava") { + dependsOn(tasks.named("spotlessGroovyGradle")) + dependsOn(tasks.named("compileKotlin")) + dependsOn(tasks.named("compileTestKotlin")) + dependsOn(tasks.named("processResources")) + dependsOn(tasks.named("processTestResources")) + dependsOn(tasks.named("test")) +} diff --git a/codegen/src/integration-test/kotlin/org/web3j/openapi/codegen/generators/GenerationTest.kt b/codegen/src/integration-test/kotlin/org/web3j/openapi/codegen/generators/GenerationTest.kt index de0e18de..33b2b45d 100644 --- a/codegen/src/integration-test/kotlin/org/web3j/openapi/codegen/generators/GenerationTest.kt +++ b/codegen/src/integration-test/kotlin/org/web3j/openapi/codegen/generators/GenerationTest.kt @@ -32,14 +32,15 @@ class GenerationTest { "src", "test", "resources", - "contracts").toFile() + "contracts", + ).toFile() val generatorConfiguration = GeneratorConfiguration( projectName = "testProject", packageName = "com.test", outputDir = tempFolder.canonicalPath, contracts = loadContractConfigurations(listOf(contractsFolder)), - contextPath = "test" + contextPath = "test", ) assertDoesNotThrow { OpenApiGenerator(generatorConfiguration).generate() diff --git a/codegen/src/main/kotlin/org/web3j/openapi/codegen/AbstractGenerator.kt b/codegen/src/main/kotlin/org/web3j/openapi/codegen/AbstractGenerator.kt index d912ac84..5ee9eb7f 100644 --- a/codegen/src/main/kotlin/org/web3j/openapi/codegen/AbstractGenerator.kt +++ b/codegen/src/main/kotlin/org/web3j/openapi/codegen/AbstractGenerator.kt @@ -15,7 +15,7 @@ package org.web3j.openapi.codegen import org.web3j.openapi.codegen.config.GeneratorConfiguration abstract class AbstractGenerator( - val configuration: GeneratorConfiguration + val configuration: GeneratorConfiguration, ) { protected val packageDir = configuration.packageName.split(".").joinToString("/") diff --git a/codegen/src/main/kotlin/org/web3j/openapi/codegen/OpenApiGenerator.kt b/codegen/src/main/kotlin/org/web3j/openapi/codegen/OpenApiGenerator.kt index a42f256f..18987825 100644 --- a/codegen/src/main/kotlin/org/web3j/openapi/codegen/OpenApiGenerator.kt +++ b/codegen/src/main/kotlin/org/web3j/openapi/codegen/OpenApiGenerator.kt @@ -17,7 +17,7 @@ import org.web3j.openapi.codegen.coregen.CoreGenerator import org.web3j.openapi.codegen.servergen.ServerGenerator class OpenApiGenerator( - private val configuration: GeneratorConfiguration + private val configuration: GeneratorConfiguration, ) { fun generate() { println("Generating Web3j-OpenAPI project ... Files written to ${configuration.outputDir}") diff --git a/codegen/src/main/kotlin/org/web3j/openapi/codegen/common/ContractResources.kt b/codegen/src/main/kotlin/org/web3j/openapi/codegen/common/ContractResources.kt index 6a575d62..6ddd380b 100644 --- a/codegen/src/main/kotlin/org/web3j/openapi/codegen/common/ContractResources.kt +++ b/codegen/src/main/kotlin/org/web3j/openapi/codegen/common/ContractResources.kt @@ -14,5 +14,5 @@ package org.web3j.openapi.codegen.common class ContractResources( val functionResources: List, - val eventResources: List + val eventResources: List, ) diff --git a/codegen/src/main/kotlin/org/web3j/openapi/codegen/common/EventResource.kt b/codegen/src/main/kotlin/org/web3j/openapi/codegen/common/EventResource.kt index 35cf1f30..68b4068b 100644 --- a/codegen/src/main/kotlin/org/web3j/openapi/codegen/common/EventResource.kt +++ b/codegen/src/main/kotlin/org/web3j/openapi/codegen/common/EventResource.kt @@ -17,5 +17,5 @@ data class EventResource( val returnType: String = "", val path: String = "", val capitalizedName: String, - val decapitalizedName: String = capitalizedName.decapitalize() + val decapitalizedName: String = capitalizedName.decapitalize(), ) diff --git a/codegen/src/main/kotlin/org/web3j/openapi/codegen/common/FunctionResource.kt b/codegen/src/main/kotlin/org/web3j/openapi/codegen/common/FunctionResource.kt index bb01a59a..a6d061a3 100644 --- a/codegen/src/main/kotlin/org/web3j/openapi/codegen/common/FunctionResource.kt +++ b/codegen/src/main/kotlin/org/web3j/openapi/codegen/common/FunctionResource.kt @@ -19,5 +19,5 @@ data class FunctionResource( val returnType: String, val mediaType: String = "", val path: String = "", - val operationTag: String = "" + val operationTag: String = "", ) diff --git a/codegen/src/main/kotlin/org/web3j/openapi/codegen/common/ParameterDefinition.kt b/codegen/src/main/kotlin/org/web3j/openapi/codegen/common/ParameterDefinition.kt index 0aecdc43..7fb03fcc 100644 --- a/codegen/src/main/kotlin/org/web3j/openapi/codegen/common/ParameterDefinition.kt +++ b/codegen/src/main/kotlin/org/web3j/openapi/codegen/common/ParameterDefinition.kt @@ -14,5 +14,5 @@ package org.web3j.openapi.codegen.common data class ParameterDefinition( val name: String, - val type: String + val type: String, ) diff --git a/codegen/src/main/kotlin/org/web3j/openapi/codegen/common/Tag.kt b/codegen/src/main/kotlin/org/web3j/openapi/codegen/common/Tag.kt index 29fe2527..08d4f8c8 100644 --- a/codegen/src/main/kotlin/org/web3j/openapi/codegen/common/Tag.kt +++ b/codegen/src/main/kotlin/org/web3j/openapi/codegen/common/Tag.kt @@ -15,5 +15,5 @@ package org.web3j.openapi.codegen.common data class Tag( val name: String, val description: String, - var lastCharacter: String = "," + var lastCharacter: String = ",", ) diff --git a/codegen/src/main/kotlin/org/web3j/openapi/codegen/config/ContractConfiguration.kt b/codegen/src/main/kotlin/org/web3j/openapi/codegen/config/ContractConfiguration.kt index fe064613..d38404e5 100644 --- a/codegen/src/main/kotlin/org/web3j/openapi/codegen/config/ContractConfiguration.kt +++ b/codegen/src/main/kotlin/org/web3j/openapi/codegen/config/ContractConfiguration.kt @@ -16,5 +16,5 @@ import java.io.File data class ContractConfiguration( val abiFile: File, - val contractDetails: ContractDetails + val contractDetails: ContractDetails, ) diff --git a/codegen/src/main/kotlin/org/web3j/openapi/codegen/config/ContractDetails.kt b/codegen/src/main/kotlin/org/web3j/openapi/codegen/config/ContractDetails.kt index 111da2b1..fda87213 100644 --- a/codegen/src/main/kotlin/org/web3j/openapi/codegen/config/ContractDetails.kt +++ b/codegen/src/main/kotlin/org/web3j/openapi/codegen/config/ContractDetails.kt @@ -18,7 +18,7 @@ import org.web3j.protocol.core.methods.response.AbiDefinition data class ContractDetails( val contractName: String, - var abiDefinitions: List + var abiDefinitions: List, ) { init { abiDefinitions.filter { it.isPayable } diff --git a/codegen/src/main/kotlin/org/web3j/openapi/codegen/config/GeneratorConfiguration.kt b/codegen/src/main/kotlin/org/web3j/openapi/codegen/config/GeneratorConfiguration.kt index 75300b37..4d04d11d 100644 --- a/codegen/src/main/kotlin/org/web3j/openapi/codegen/config/GeneratorConfiguration.kt +++ b/codegen/src/main/kotlin/org/web3j/openapi/codegen/config/GeneratorConfiguration.kt @@ -24,7 +24,7 @@ data class GeneratorConfiguration @JvmOverloads constructor( val contextPath: String, val version: String = VersionProvider.versionName, val sanitizedProjectName: String = sanitizeName(projectName), - val withImplementations: Boolean = true + val withImplementations: Boolean = true, ) { val rootProjectName = sanitizedProjectName.toLowerCase().replace(' ', '-') diff --git a/codegen/src/main/kotlin/org/web3j/openapi/codegen/config/VersionProvider.kt b/codegen/src/main/kotlin/org/web3j/openapi/codegen/config/VersionProvider.kt index 9b457654..32b8768c 100644 --- a/codegen/src/main/kotlin/org/web3j/openapi/codegen/config/VersionProvider.kt +++ b/codegen/src/main/kotlin/org/web3j/openapi/codegen/config/VersionProvider.kt @@ -40,7 +40,7 @@ object VersionProvider { fun getVersion(): Array { return arrayOf( "Version: $versionName", - "Build timestamp: ${buildTimestamp.let { timeFormatter.format(it) }}" + "Build timestamp: ${buildTimestamp.let { timeFormatter.format(it) }}", ) } } diff --git a/codegen/src/main/kotlin/org/web3j/openapi/codegen/coregen/CoreGenerator.kt b/codegen/src/main/kotlin/org/web3j/openapi/codegen/coregen/CoreGenerator.kt index 4b2db797..4d8cbb7d 100644 --- a/codegen/src/main/kotlin/org/web3j/openapi/codegen/coregen/CoreGenerator.kt +++ b/codegen/src/main/kotlin/org/web3j/openapi/codegen/coregen/CoreGenerator.kt @@ -26,9 +26,9 @@ import java.io.FileNotFoundException import java.nio.file.Paths class CoreGenerator( - configuration: GeneratorConfiguration + configuration: GeneratorConfiguration, ) : AbstractGenerator( - configuration + configuration, ) { init { context["contractsConfiguration"] = configuration.contracts @@ -50,9 +50,9 @@ class CoreGenerator( configuration.packageName, folderPath = Paths.get( folderPath, - it.contractDetails.lowerCaseContractName + it.contractDetails.lowerCaseContractName, ).toString(), - contractDetails = it.contractDetails + contractDetails = it.contractDetails, ).generate() } } @@ -63,14 +63,14 @@ class CoreGenerator( tags.add( Tag( "${it.contractDetails.capitalizedContractName} Methods", - "List ${it.contractDetails.capitalizedContractName} method's calls" - ) + "List ${it.contractDetails.capitalizedContractName} method's calls", + ), ) tags.add( Tag( "${it.contractDetails.capitalizedContractName} Events", - "List ${it.contractDetails.capitalizedContractName} event's calls" - ) + "List ${it.contractDetails.capitalizedContractName} event's calls", + ), ) } return tags.also { @@ -89,13 +89,13 @@ class CoreGenerator( context = context, outputDir = folderPath, template = mustacheTemplate("core/src/ContractsApi.mustache"), - name = "${configuration.sanitizedProjectName.capitalize()}Api.kt" + name = "${configuration.sanitizedProjectName.capitalize()}Api.kt", ) generateFromTemplate( context = context, outputDir = folderPath, template = mustacheTemplate("core/src/GeneratedContractsResource.mustache"), - name = "${configuration.sanitizedProjectName.capitalize()}Resource.kt" + name = "${configuration.sanitizedProjectName.capitalize()}Resource.kt", ) } diff --git a/codegen/src/main/kotlin/org/web3j/openapi/codegen/coregen/subgenerators/CoreApiGenerator.kt b/codegen/src/main/kotlin/org/web3j/openapi/codegen/coregen/subgenerators/CoreApiGenerator.kt index 52fc5e2b..d11a1368 100644 --- a/codegen/src/main/kotlin/org/web3j/openapi/codegen/coregen/subgenerators/CoreApiGenerator.kt +++ b/codegen/src/main/kotlin/org/web3j/openapi/codegen/coregen/subgenerators/CoreApiGenerator.kt @@ -30,7 +30,7 @@ import java.nio.file.Paths internal class CoreApiGenerator( val packageName: String, val folderPath: String, - val contractDetails: ContractDetails + val contractDetails: ContractDetails, ) { private val context = mutableMapOf() private val outputDir = folderPath.substringBefore(packageName.substringBefore(".")) @@ -61,7 +61,7 @@ internal class CoreApiGenerator( contractName = contractDetails.capitalizedContractName, functionName = structDefinition!!.internalType.split(".").last(), folderPath = outputDir, - components = structDefinition.components + components = structDefinition.components, ).generate() } } @@ -70,18 +70,19 @@ internal class CoreApiGenerator( return contractDetails.abiDefinitions .filter { it.type == "function" && it.inputs.isNotEmpty() || it.type == "event" } .map { - if (it.type == "function") + if (it.type == "function") { Import( "import $packageName.core.${contractDetails.lowerCaseContractName}.model.${ it.sanitizedName().capitalize() - }Parameters" + }Parameters", ) - else + } else { Import( "import $packageName.core.${contractDetails.lowerCaseContractName}.model.${ it.sanitizedName().capitalize() - }EventResponse" + }EventResponse", ) + } } } @@ -92,7 +93,7 @@ internal class CoreApiGenerator( Import( "import $packageName.core.${contractDetails.lowerCaseContractName}.events.${ it.sanitizedName().capitalize() - }EventResource" + }EventResource", ) } } @@ -107,9 +108,11 @@ internal class CoreApiGenerator( if (it.type == "function") { if (!it.isTransactional() && it.outputs.isEmpty()) return@forEach val parameters = - if (it.inputs.isNotEmpty()) + if (it.inputs.isNotEmpty()) { "${sanitizedAbiDefinitionName.decapitalize()}Parameters : ${sanitizedAbiDefinitionName.capitalize()}Parameters" - else "" + } else { + "" + } val operationTag = "@Operation(tags = [\"${contractDetails.capitalizedContractName} Methods\"], summary = \"Execute the ${ sanitizedAbiDefinitionName @@ -124,8 +127,8 @@ internal class CoreApiGenerator( .toString(), operationTag = operationTag, mediaType = "@Produces(MediaType.APPLICATION_JSON)", - path = "@Path(\"$sanitizedAbiDefinitionName\")" - ) + path = "@Path(\"$sanitizedAbiDefinitionName\")", + ), ) } else { eventResources.add( @@ -133,8 +136,8 @@ internal class CoreApiGenerator( capitalizedName = sanitizedAbiDefinitionName, resource = "val ${sanitizedAbiDefinitionName.decapitalize()}", path = "@get:Path(\"${sanitizedAbiDefinitionName.decapitalize()}\")", - returnType = "${sanitizedAbiDefinitionName.capitalize()}EventResource" - ) + returnType = "${sanitizedAbiDefinitionName.capitalize()}EventResource", + ), ) } } @@ -147,23 +150,25 @@ internal class CoreApiGenerator( when (it.type) { "constructor" -> { - if (it.inputs.isNotEmpty()) + if (it.inputs.isNotEmpty()) { CoreDeployModelGenerator( packageName = packageName, contractName = contractDetails.capitalizedContractName, folderPath = outputDir, - inputs = it.inputs + inputs = it.inputs, ).generate() + } } "function" -> { - if (it.inputs.isNotEmpty()) + if (it.inputs.isNotEmpty()) { CoreFunctionsModelGenerator( packageName = packageName, contractName = contractDetails.capitalizedContractName, functionName = it.sanitizedName(), folderPath = outputDir, - inputs = it.inputs + inputs = it.inputs, ).generate() + } } "event" -> { CoreEventsModelGenerator( @@ -171,7 +176,7 @@ internal class CoreApiGenerator( contractName = contractDetails.capitalizedContractName, eventName = it.sanitizedName(), folderPath = outputDir, - outputs = it.inputs + outputs = it.inputs, ).generate() } } @@ -183,26 +188,26 @@ internal class CoreApiGenerator( context = context, outputDir = folderPath, template = TemplateUtils.mustacheTemplate("core/src/api/ContractLifecycle.mustache"), - name = "${contractDetails.capitalizedContractName}Lifecycle.kt" + name = "${contractDetails.capitalizedContractName}Lifecycle.kt", ) TemplateUtils.generateFromTemplate( context = context, outputDir = folderPath, template = TemplateUtils.mustacheTemplate("core/src/api/ContractResource.mustache"), - name = "${contractDetails.capitalizedContractName}Resource.kt" + name = "${contractDetails.capitalizedContractName}Resource.kt", ) TemplateUtils.generateFromTemplate( context = context, outputDir = folderPath, template = TemplateUtils.mustacheTemplate("core/src/api/EventsResource.mustache"), - name = "${contractDetails.capitalizedContractName}Events.kt" + name = "${contractDetails.capitalizedContractName}Events.kt", ) val eventsFolder = File( Paths.get( folderPath, - "events" - ).toString() + "events", + ).toString(), ) contractDetails.abiDefinitions @@ -215,7 +220,7 @@ internal class CoreApiGenerator( context = context, outputDir = eventsFolder.canonicalPath, template = TemplateUtils.mustacheTemplate("core/src/api/NamedEventResource.mustache"), - name = "${sanitizedAbiDefinitionName.capitalize()}EventResource.kt" + name = "${sanitizedAbiDefinitionName.capitalize()}EventResource.kt", ) } } diff --git a/codegen/src/main/kotlin/org/web3j/openapi/codegen/coregen/subgenerators/CoreDeployModelGenerator.kt b/codegen/src/main/kotlin/org/web3j/openapi/codegen/coregen/subgenerators/CoreDeployModelGenerator.kt index 4a7df8b6..13a24f8d 100644 --- a/codegen/src/main/kotlin/org/web3j/openapi/codegen/coregen/subgenerators/CoreDeployModelGenerator.kt +++ b/codegen/src/main/kotlin/org/web3j/openapi/codegen/coregen/subgenerators/CoreDeployModelGenerator.kt @@ -21,7 +21,7 @@ internal class CoreDeployModelGenerator( val packageName: String, private val contractName: String, val folderPath: String, - val inputs: List + val inputs: List, ) { fun generate() { val constructorFile = inputs.toDataClass( @@ -29,7 +29,7 @@ internal class CoreDeployModelGenerator( contractName, "DeployParameters", packageName, - contractName + contractName, ) logger.debug("Generating $contractName deploy parameters") constructorFile.writeTo(File(folderPath)) diff --git a/codegen/src/main/kotlin/org/web3j/openapi/codegen/coregen/subgenerators/CoreEventsModelGenerator.kt b/codegen/src/main/kotlin/org/web3j/openapi/codegen/coregen/subgenerators/CoreEventsModelGenerator.kt index 4ee00f03..3356da2a 100644 --- a/codegen/src/main/kotlin/org/web3j/openapi/codegen/coregen/subgenerators/CoreEventsModelGenerator.kt +++ b/codegen/src/main/kotlin/org/web3j/openapi/codegen/coregen/subgenerators/CoreEventsModelGenerator.kt @@ -22,7 +22,7 @@ internal class CoreEventsModelGenerator( private val contractName: String, private val eventName: String, private val folderPath: String, - private val outputs: List + private val outputs: List, ) { fun generate() { val functionFile = outputs.toDataClass( @@ -30,7 +30,7 @@ internal class CoreEventsModelGenerator( eventName, "EventResponse", packageName, - contractName + contractName, ) logger.debug("Generating $contractName $eventName model") functionFile.writeTo(File(folderPath)) diff --git a/codegen/src/main/kotlin/org/web3j/openapi/codegen/coregen/subgenerators/CoreFunctionsModelGenerator.kt b/codegen/src/main/kotlin/org/web3j/openapi/codegen/coregen/subgenerators/CoreFunctionsModelGenerator.kt index d5d47c69..9af021b4 100644 --- a/codegen/src/main/kotlin/org/web3j/openapi/codegen/coregen/subgenerators/CoreFunctionsModelGenerator.kt +++ b/codegen/src/main/kotlin/org/web3j/openapi/codegen/coregen/subgenerators/CoreFunctionsModelGenerator.kt @@ -22,7 +22,7 @@ internal class CoreFunctionsModelGenerator( private val contractName: String, private val functionName: String, val folderPath: String, - val inputs: List + val inputs: List, ) { fun generate() { val functionFile = inputs.toDataClass( @@ -30,7 +30,7 @@ internal class CoreFunctionsModelGenerator( functionName, "Parameters", packageName, - contractName + contractName, ) logger.debug("Generating $contractName $functionName parameters") functionFile.writeTo(File(folderPath)) diff --git a/codegen/src/main/kotlin/org/web3j/openapi/codegen/coregen/subgenerators/CoreStructsModelGenerator.kt b/codegen/src/main/kotlin/org/web3j/openapi/codegen/coregen/subgenerators/CoreStructsModelGenerator.kt index 6f9f2c14..cc78217f 100644 --- a/codegen/src/main/kotlin/org/web3j/openapi/codegen/coregen/subgenerators/CoreStructsModelGenerator.kt +++ b/codegen/src/main/kotlin/org/web3j/openapi/codegen/coregen/subgenerators/CoreStructsModelGenerator.kt @@ -21,7 +21,7 @@ class CoreStructsModelGenerator( val contractName: String, val functionName: String, val folderPath: String, - val components: List + val components: List, ) { fun generate() { val functionFile = components.toDataClass( @@ -29,7 +29,7 @@ class CoreStructsModelGenerator( functionName, "StructModel", packageName, - contractName + contractName, ) CoreFunctionsModelGenerator.logger.debug("Generating $contractName $functionName parameters") functionFile.writeTo(File(folderPath)) diff --git a/codegen/src/main/kotlin/org/web3j/openapi/codegen/servergen/ServerGenerator.kt b/codegen/src/main/kotlin/org/web3j/openapi/codegen/servergen/ServerGenerator.kt index 3b6a3562..70849a65 100644 --- a/codegen/src/main/kotlin/org/web3j/openapi/codegen/servergen/ServerGenerator.kt +++ b/codegen/src/main/kotlin/org/web3j/openapi/codegen/servergen/ServerGenerator.kt @@ -60,16 +60,16 @@ internal class ServerGenerator(configuration: GeneratorConfiguration) : Abstract packageName = configuration.packageName, folderPath = Paths.get( folderPath, - it.contractDetails.lowerCaseContractName + it.contractDetails.lowerCaseContractName, ).toString(), - contractDetails = it.contractDetails + contractDetails = it.contractDetails, ).generate() ResourcesImplGenerator( packageName = configuration.packageName, contractName = it.contractDetails.contractName, folderPath = outputDir, - resourcesDefinition = it.contractDetails.abiDefinitions + resourcesDefinition = it.contractDetails.abiDefinitions, ).generate() EventsResourceImplGenerator( @@ -77,16 +77,16 @@ internal class ServerGenerator(configuration: GeneratorConfiguration) : Abstract contractName = it.contractDetails.contractName, folderPath = Paths.get( folderPath, - it.contractDetails.lowerCaseContractName + it.contractDetails.lowerCaseContractName, ).toString(), - abiDefinitions = it.contractDetails.abiDefinitions + abiDefinitions = it.contractDetails.abiDefinitions, ).generate() StructExtensionsGenerator( packageName = configuration.packageName, contractName = it.contractDetails.contractName, folderPath = outputDir, - resourcesDefinition = it.contractDetails.abiDefinitions + resourcesDefinition = it.contractDetails.abiDefinitions, ).generate() } } @@ -115,16 +115,16 @@ internal class ServerGenerator(configuration: GeneratorConfiguration) : Abstract folderPath.substringBefore("kotlin"), "resources", "META-INF", - "services" - ).toString() + "services", + ).toString(), ).apply { mkdirs() } TemplateUtils.generateFromTemplate( context = context, outputDir = spiFolder.absolutePath, template = TemplateUtils.mustacheTemplate( - "server/src/main/resources/META-INF/services/org.web3j.openapi.server.spi.OpenApiResourceProvider.mustache" + "server/src/main/resources/META-INF/services/org.web3j.openapi.server.spi.OpenApiResourceProvider.mustache", ), - name = "org.web3j.openapi.server.spi.OpenApiResourceProvider" + name = "org.web3j.openapi.server.spi.OpenApiResourceProvider", ) } @@ -133,19 +133,19 @@ internal class ServerGenerator(configuration: GeneratorConfiguration) : Abstract context = context, outputDir = folderPath, template = TemplateUtils.mustacheTemplate("server/src/ContractsApiImpl.mustache"), - name = "${configuration.sanitizedProjectName.capitalize()}ApiImpl.kt" + name = "${configuration.sanitizedProjectName.capitalize()}ApiImpl.kt", ) TemplateUtils.generateFromTemplate( context = context, outputDir = folderPath, template = TemplateUtils.mustacheTemplate("server/src/ContractsResourceProvider.mustache"), - name = "${configuration.sanitizedProjectName.capitalize()}ResourceProvider.kt" + name = "${configuration.sanitizedProjectName.capitalize()}ResourceProvider.kt", ) TemplateUtils.generateFromTemplate( context = context, outputDir = folderPath, template = TemplateUtils.mustacheTemplate("server/src/GeneratedContractsResourceImpl.mustache"), - name = "${configuration.sanitizedProjectName.capitalize()}ResourceImpl.kt" + name = "${configuration.sanitizedProjectName.capitalize()}ResourceImpl.kt", ) } diff --git a/codegen/src/main/kotlin/org/web3j/openapi/codegen/servergen/subgenerators/EventsResourceImplGenerator.kt b/codegen/src/main/kotlin/org/web3j/openapi/codegen/servergen/subgenerators/EventsResourceImplGenerator.kt index db30fbf4..cb037d65 100644 --- a/codegen/src/main/kotlin/org/web3j/openapi/codegen/servergen/subgenerators/EventsResourceImplGenerator.kt +++ b/codegen/src/main/kotlin/org/web3j/openapi/codegen/servergen/subgenerators/EventsResourceImplGenerator.kt @@ -24,7 +24,7 @@ class EventsResourceImplGenerator( val packageName: String, val contractName: String, private val folderPath: String, - private val abiDefinitions: List + private val abiDefinitions: List, ) { private val context = mutableMapOf() @@ -40,8 +40,9 @@ class EventsResourceImplGenerator( val eventsFolder = File( Paths.get( folderPath, - "events" - ).toString()) + "events", + ).toString(), + ) abiDefinitions .filter { it.type == "event" } @@ -57,24 +58,29 @@ class EventsResourceImplGenerator( context = context, outputDir = eventsFolder.canonicalPath, template = TemplateUtils.mustacheTemplate("server/src/contractImpl/NamedEventResourceImpl.mustache"), - name = "${sanitizedAbiDefinitionName.capitalize()}EventResourceImpl.kt" + name = "${sanitizedAbiDefinitionName.capitalize()}EventResourceImpl.kt", ) } } private fun getEventResponseParameters(abiDef: AbiDefinition): String { return abiDef.inputs.joinToString(",") { - if (it.components.isEmpty()) "it.${it.name}" - else + if (it.components.isEmpty()) { + "it.${it.name}" + } else { getStructEventParameters(it, abiDef.sanitizedName(), "it.${it.name}") + } } } private fun getStructEventParameters(input: AbiDefinition.NamedType, functionName: String, callTree: String = ""): String { val structName = input.internalType.structName val parameters = input.components.joinToString(",") { component -> - if (component.components.isNullOrEmpty()) "$callTree.${component.name}" - else getStructEventParameters(component, functionName.decapitalize(), "$callTree.${component.name}".removeSuffix(".")) + if (component.components.isNullOrEmpty()) { + "$callTree.${component.name}" + } else { + getStructEventParameters(component, functionName.decapitalize(), "$callTree.${component.name}".removeSuffix(".")) + } } return "$packageName.core.${contractName.toLowerCase()}.model.${structName}StructModel($parameters)" } diff --git a/codegen/src/main/kotlin/org/web3j/openapi/codegen/servergen/subgenerators/LifecycleImplGenerator.kt b/codegen/src/main/kotlin/org/web3j/openapi/codegen/servergen/subgenerators/LifecycleImplGenerator.kt index 25a383fb..3a675ea2 100644 --- a/codegen/src/main/kotlin/org/web3j/openapi/codegen/servergen/subgenerators/LifecycleImplGenerator.kt +++ b/codegen/src/main/kotlin/org/web3j/openapi/codegen/servergen/subgenerators/LifecycleImplGenerator.kt @@ -21,28 +21,30 @@ import java.io.File class LifecycleImplGenerator( val packageName: String, val folderPath: String, - val contractDetails: ContractDetails + val contractDetails: ContractDetails, ) { private val context = mutableMapOf() private val parameters: String by lazy { - if (contractDetails.deployParameters == "()") "" - else { + if (contractDetails.deployParameters == "()") { + "" + } else { var parameters = "" contractDetails.abiDefinitions .filter { it.type == "constructor" } .map { it.inputs } .first() .forEach { input -> - parameters += if (input.type == "tuple") + parameters += if (input.type == "tuple") { ", ${getStructCallParameters( contractDetails.contractName, input, "", - "parameters.${input.name}" + "parameters.${input.name}", )}" - else + } else { ", parameters.${input.name}" + } } parameters.removeSuffix(",") } @@ -67,7 +69,7 @@ class LifecycleImplGenerator( context = context, outputDir = folderPath, template = TemplateUtils.mustacheTemplate("server/src/contractImpl/ContractLifecycleImpl.mustache"), - name = "${contractDetails.capitalizedContractName}LifecycleImpl.kt" + name = "${contractDetails.capitalizedContractName}LifecycleImpl.kt", ) } diff --git a/codegen/src/main/kotlin/org/web3j/openapi/codegen/servergen/subgenerators/ResourcesImplGenerator.kt b/codegen/src/main/kotlin/org/web3j/openapi/codegen/servergen/subgenerators/ResourcesImplGenerator.kt index 96771998..6bfc2e0f 100644 --- a/codegen/src/main/kotlin/org/web3j/openapi/codegen/servergen/subgenerators/ResourcesImplGenerator.kt +++ b/codegen/src/main/kotlin/org/web3j/openapi/codegen/servergen/subgenerators/ResourcesImplGenerator.kt @@ -20,12 +20,12 @@ import com.squareup.kotlinpoet.PropertySpec import com.squareup.kotlinpoet.TypeSpec import org.web3j.openapi.codegen.common.EventResource import org.web3j.openapi.codegen.common.Import -import org.web3j.openapi.codegen.utils.getStructCallParameters import org.web3j.openapi.codegen.utils.CopyUtils import org.web3j.openapi.codegen.utils.GeneratorUtils.argumentName import org.web3j.openapi.codegen.utils.GeneratorUtils.sanitizedName import org.web3j.openapi.codegen.utils.TemplateUtils import org.web3j.openapi.codegen.utils.getReturnType +import org.web3j.openapi.codegen.utils.getStructCallParameters import org.web3j.openapi.codegen.utils.isTransactional import org.web3j.protocol.core.methods.response.AbiDefinition import java.io.File @@ -35,7 +35,7 @@ internal class ResourcesImplGenerator( val packageName: String, private val contractName: String, private val resourcesDefinition: List, - private val folderPath: String + private val folderPath: String, ) { fun generate() { generateClass().writeTo(File(folderPath)) @@ -51,35 +51,35 @@ internal class ResourcesImplGenerator( private fun generateClass(): FileSpec { val resourcesFile = FileSpec.builder( "$packageName.server.${contractName.toLowerCase()}", - "${contractName.capitalize()}ResourceImpl" + "${contractName.capitalize()}ResourceImpl", ) val contractClass = ClassName( "$packageName.wrappers", - contractName.capitalize() + contractName.capitalize(), ) val extendedUriInfoClass = ClassName( "org.glassfish.jersey.server", - "ExtendedUriInfo" + "ExtendedUriInfo", ) val constructorBuilder = FunSpec.constructorBuilder() .addParameter( contractName.decapitalize(), - contractClass + contractClass, ).addParameter( "uriInfo", - extendedUriInfoClass + extendedUriInfoClass, ) val contractResourceClass = ClassName( "$packageName.core.${contractName.toLowerCase()}", - "${contractName.capitalize()}Resource" + "${contractName.capitalize()}Resource", ) val eventsResourcesClass = ClassName( "$packageName.core.${contractName.toLowerCase()}", - "${contractName.capitalize()}Events" + "${contractName.capitalize()}Events", ) val resourcesClass = TypeSpec @@ -89,26 +89,26 @@ internal class ResourcesImplGenerator( PropertySpec.builder( contractName.decapitalize(), contractClass, - KModifier.PRIVATE + KModifier.PRIVATE, ) .initializer(contractName.decapitalize()) - .build() + .build(), ).addProperty( PropertySpec.builder( "uriInfo", extendedUriInfoClass, - KModifier.PRIVATE + KModifier.PRIVATE, ) .initializer("uriInfo") - .build() + .build(), ).addProperty( PropertySpec.builder( "events", eventsResourcesClass, - KModifier.OVERRIDE + KModifier.OVERRIDE, ) .initializer("${contractName.capitalize()}EventsImpl(${contractName.decapitalize()}, uriInfo)") - .build() + .build(), ).addSuperinterface(contractResourceClass) resourcesClass.addFunctions(generateFunctions()) @@ -134,11 +134,11 @@ internal class ResourcesImplGenerator( } else { val nameClass = ClassName( "$packageName.core.${contractName.toLowerCase()}.model", - "${sanitizedAbiDefinitionName.capitalize()}Parameters" + "${sanitizedAbiDefinitionName.capitalize()}Parameters", ) funSpec.addParameter( "${sanitizedAbiDefinitionName.decapitalize()}Parameters", - nameClass + nameClass, ) """ ${contractName.decapitalize()}.${getFunctionName(it.sanitizedName(true))}( @@ -154,9 +154,9 @@ internal class ResourcesImplGenerator( } private fun wrapCode(code: String, returnType: String): String { - return if (returnType.startsWith("org.web3j.openapi.core.models.TransactionReceiptModel")) + return if (returnType.startsWith("org.web3j.openapi.core.models.TransactionReceiptModel")) { "return TransactionReceiptModel($code)" - else { + } else { val innerType = returnType.substringAfter("<").removeSuffix(">") when { innerType.startsWith("org.web3j.tuples") -> wrapTuplesCode(code, innerType) @@ -172,34 +172,45 @@ internal class ResourcesImplGenerator( .split(",") val variableNames = components.mapIndexed { index, component -> - if (component.endsWith("StructModel")) "${component.removeSuffix("StructModel").substringAfterLast(".").decapitalize()}$index" - else "${component.substringBefore("<").substringAfterLast(".").decapitalize()}$index" + if (component.endsWith("StructModel")) { + "${component.removeSuffix("StructModel").substringAfterLast(".").decapitalize()}$index" + } else { + "${component.substringBefore("<").substringAfterLast(".").decapitalize()}$index" + } }.joinToString(",") val tupleConstructor = components.mapIndexed { index, component -> - if (component.endsWith("StructModel")) "${component.removeSuffix("StructModel").substringAfterLast(".").decapitalize()}$index.toModel()" - else "${component.substringBefore("<").substringAfterLast(".").decapitalize()}$index" + if (component.endsWith("StructModel")) { + "${component.removeSuffix("StructModel").substringAfterLast(".").decapitalize()}$index.toModel()" + } else { + "${component.substringBefore("<").substringAfterLast(".").decapitalize()}$index" + } }.joinToString(",") return """val ($variableNames) = $code return org.web3j.openapi.core.models.ResultModel( Tuple${components.size}($tupleConstructor) - )""".trimMargin() + ) + """.trimMargin() } private fun getFunctionName(name: String): String { - return if (name == "short" || name == "long" || name == "double" || name == "float" || name == "char") "_$name" - else name + return if (name == "short" || name == "long" || name == "double" || name == "float" || name == "char") { + "_$name" + } else { + name + } } private fun getCallParameters(inputs: MutableList, functionName: String): String { var callParameters = "" inputs.forEachIndexed { index, input -> callParameters += - if (input.type == "tuple") + if (input.type == "tuple") { "${getStructCallParameters(contractName, input, functionName, "${functionName.decapitalize()}Parameters.${argumentName(input.name, index)}")}," - else + } else { "${functionName.decapitalize()}Parameters.${argumentName(input.name, index)}," + } } return callParameters.removeSuffix(",") } @@ -209,7 +220,7 @@ internal class ResourcesImplGenerator( .filter { it.type == "event" } .map { abiDefinition -> Import( - "import $packageName.server.${contractName.toLowerCase()}.events.${abiDefinition.name.capitalize()}EventResourceImpl" + "import $packageName.server.${contractName.toLowerCase()}.events.${abiDefinition.name.capitalize()}EventResourceImpl", ) } } @@ -219,7 +230,7 @@ internal class ResourcesImplGenerator( .filter { it.type == "event" } .map { abiDefinition -> EventResource( - capitalizedName = abiDefinition.sanitizedName().capitalize() + capitalizedName = abiDefinition.sanitizedName().capitalize(), ) } } @@ -239,8 +250,8 @@ internal class ResourcesImplGenerator( folderPath, packageName.replace(".", "/"), "server", - contractName.toLowerCase() - ).toString() + contractName.toLowerCase(), + ).toString(), ).apply { mkdirs() } @@ -249,7 +260,7 @@ internal class ResourcesImplGenerator( context = context, outputDir = contractFolder.canonicalPath, template = TemplateUtils.mustacheTemplate("server/src/contractImpl/EventsResourceImpl.mustache"), - name = "${contractName.capitalize()}EventsImpl.kt" + name = "${contractName.capitalize()}EventsImpl.kt", ) } } diff --git a/codegen/src/main/kotlin/org/web3j/openapi/codegen/servergen/subgenerators/StructExtensionsGenerator.kt b/codegen/src/main/kotlin/org/web3j/openapi/codegen/servergen/subgenerators/StructExtensionsGenerator.kt index 75a08357..35b4cbad 100644 --- a/codegen/src/main/kotlin/org/web3j/openapi/codegen/servergen/subgenerators/StructExtensionsGenerator.kt +++ b/codegen/src/main/kotlin/org/web3j/openapi/codegen/servergen/subgenerators/StructExtensionsGenerator.kt @@ -25,7 +25,7 @@ class StructExtensionsGenerator( val packageName: String, private val contractName: String, private val resourcesDefinition: List, - private val folderPath: String + private val folderPath: String, ) { fun generate() { @@ -42,7 +42,7 @@ class StructExtensionsGenerator( private fun generateExtensions(structs: List): FileSpec { val extensionsFile = FileSpec.builder( "$packageName.server.${contractName.toLowerCase()}", - "${contractName.capitalize()}Extensions" + "${contractName.capitalize()}Extensions", ) structs.forEach { structDefinition -> @@ -50,12 +50,12 @@ class StructExtensionsGenerator( val contractClass = ClassName( "$packageName.wrappers.${contractName.capitalize()}", - structName + structName, ) val modelClass = ClassName( "$packageName.core.${contractName.toLowerCase()}.model", - "${structName}StructModel" + "${structName}StructModel", ) val code = "return ${modelClass.simpleName}(${extensionDefinitionParameters(structDefinition)})" @@ -74,10 +74,11 @@ class StructExtensionsGenerator( private fun extensionDefinitionParameters(structDefinition: AbiDefinition.NamedType): String { return structDefinition.components.joinToString(",") { structField -> - if (structField.components.isNullOrEmpty()) + if (structField.components.isNullOrEmpty()) { structField.name - else + } else { "${structField.name}.toModel()" + } } } } diff --git a/codegen/src/main/kotlin/org/web3j/openapi/codegen/utils/CopyUtils.kt b/codegen/src/main/kotlin/org/web3j/openapi/codegen/utils/CopyUtils.kt index 71637673..9ed2b843 100644 --- a/codegen/src/main/kotlin/org/web3j/openapi/codegen/utils/CopyUtils.kt +++ b/codegen/src/main/kotlin/org/web3j/openapi/codegen/utils/CopyUtils.kt @@ -25,14 +25,14 @@ internal object CopyUtils : KLogging() { private val ruleSets = listOf( StandardRuleSetProvider().get(), - ExperimentalRuleSetProvider().get() + ExperimentalRuleSetProvider().get(), ) fun copyResource(name: String, outputDir: File) { Files.copy( javaClass.classLoader.getResourceAsStream(name)!!, outputDir.resolve(name).toPath(), - StandardCopyOption.REPLACE_EXISTING + StandardCopyOption.REPLACE_EXISTING, ) } @@ -41,8 +41,8 @@ internal object CopyUtils : KLogging() { Paths.get( outputDir, packageDir, - module - ).toString() + module, + ).toString(), ).apply { mkdirs() } return folder.absolutePath } @@ -55,8 +55,8 @@ internal object CopyUtils : KLogging() { KtLint.Params( ruleSets = ruleSets, cb = { _, _ -> }, - text = file.readText() - ) + text = file.readText(), + ), ).run { file.writeText(this) } diff --git a/codegen/src/main/kotlin/org/web3j/openapi/codegen/utils/GeneratorUtils.kt b/codegen/src/main/kotlin/org/web3j/openapi/codegen/utils/GeneratorUtils.kt index 4cf1443c..09d2eccc 100644 --- a/codegen/src/main/kotlin/org/web3j/openapi/codegen/utils/GeneratorUtils.kt +++ b/codegen/src/main/kotlin/org/web3j/openapi/codegen/utils/GeneratorUtils.kt @@ -27,8 +27,8 @@ object GeneratorUtils { abiFile, ContractDetails( abiFile.name.removeSuffix(".abi"), - loadContractDefinition(abiFile) // TODO: Use the web3j.codegen function - ) + loadContractDefinition(abiFile), // TODO: Use the web3j.codegen function + ), ) } } diff --git a/codegen/src/main/kotlin/org/web3j/openapi/codegen/utils/KPoetUtils.kt b/codegen/src/main/kotlin/org/web3j/openapi/codegen/utils/KPoetUtils.kt index 97ca6b31..7fd89f10 100644 --- a/codegen/src/main/kotlin/org/web3j/openapi/codegen/utils/KPoetUtils.kt +++ b/codegen/src/main/kotlin/org/web3j/openapi/codegen/utils/KPoetUtils.kt @@ -13,12 +13,12 @@ package org.web3j.openapi.codegen.utils import com.fasterxml.jackson.annotation.JsonProperty +import com.squareup.kotlinpoet.AnnotationSpec import com.squareup.kotlinpoet.FileSpec import com.squareup.kotlinpoet.FunSpec import com.squareup.kotlinpoet.KModifier import com.squareup.kotlinpoet.PropertySpec import com.squareup.kotlinpoet.TypeSpec -import com.squareup.kotlinpoet.AnnotationSpec import org.web3j.protocol.core.methods.response.AbiDefinition.NamedType internal fun List.toDataClass( @@ -26,11 +26,11 @@ internal fun List.toDataClass( name: String, type: String, basePackageName: String = "", - contractName: String = "" + contractName: String = "", ): FileSpec { val outputFile = FileSpec.builder( modelPackageName, - "${name.capitalize()}$type" + "${name.capitalize()}$type", ) val constructor = TypeSpec @@ -52,19 +52,19 @@ internal fun List.toDataClass( constructorBuilder.addParameter( inputName, - inputType + inputType, ) constructor.addProperty( PropertySpec.builder( inputName, - inputType + inputType, ).initializer(inputName) .addAnnotation( AnnotationSpec.builder(JsonProperty::class.java) .addMember("value = %S", inputName) - .build() + .build(), ) - .build() + .build(), ) } constructor.primaryConstructor(constructorBuilder.build()) diff --git a/codegen/src/main/kotlin/org/web3j/openapi/codegen/utils/SolidityUtils.kt b/codegen/src/main/kotlin/org/web3j/openapi/codegen/utils/SolidityUtils.kt index efe25b01..9604f27c 100644 --- a/codegen/src/main/kotlin/org/web3j/openapi/codegen/utils/SolidityUtils.kt +++ b/codegen/src/main/kotlin/org/web3j/openapi/codegen/utils/SolidityUtils.kt @@ -65,7 +65,7 @@ internal fun String.mapType(isParameter: Boolean = true, structName: String = "" getParameterMapping(isParameter, ClassName("$packageName.core.$contractName.model", "${structName}StructModel")) } else { throw UnsupportedOperationException( - "Unsupported type: $this, no native type mapping exists." + "Unsupported type: $this, no native type mapping exists.", ) } } @@ -74,32 +74,42 @@ internal fun String.mapType(isParameter: Boolean = true, structName: String = "" * Maps the different number variations to their specific types depending on their size */ fun getNumbersMapping(isParameter: Boolean, type: String): TypeName { - return if (isParameter) getParameterMapping(isParameter, BigInteger::class.asTypeName()) - else if (type == "uint8") getParameterMapping(isParameter, BigInteger::class.asTypeName()) // FIXME: remove this when web3j-codegen fixes this problem - else if (type.startsWith("int") && type.substringAfter("int").toInt() < 16 || - type.startsWith("uint") && type.substringAfter("int").toInt() < 16) + return if (isParameter) { + getParameterMapping(isParameter, BigInteger::class.asTypeName()) + } else if (type == "uint8") { + getParameterMapping(isParameter, BigInteger::class.asTypeName()) // FIXME: remove this when web3j-codegen fixes this problem + } else if (type.startsWith("int") && type.substringAfter("int").toInt() < 16 || + type.startsWith("uint") && type.substringAfter("int").toInt() < 16 + ) { getParameterMapping(isParameter, Short::class.asTypeName()) - else if (type.startsWith("int") && type.substringAfter("int").toInt() <= 32 || - type.startsWith("uint") && type.substringAfter("int").toInt() < 32) + } else if (type.startsWith("int") && type.substringAfter("int").toInt() <= 32 || + type.startsWith("uint") && type.substringAfter("int").toInt() < 32 + ) { getParameterMapping(isParameter, Integer::class.asTypeName()) - else if (type.startsWith("int") && type.substringAfter("int").toInt() <= 64 || - type.startsWith("uint") && type.substringAfter("int").toInt() < 64) + } else if (type.startsWith("int") && type.substringAfter("int").toInt() <= 64 || + type.startsWith("uint") && type.substringAfter("int").toInt() < 64 + ) { getParameterMapping(isParameter, Long::class.asTypeName()) - else + } else { getParameterMapping(isParameter, BigInteger::class.asTypeName()) + } } /** * Maps events indexed types using java native types */ fun String.mapIndexedType(): TypeName { - return if (this == "string" || this.contains("[")) ByteArray::class.asTypeName() - else mapType(true) + return if (this == "string" || this.contains("[")) { + ByteArray::class.asTypeName() + } else { + mapType(true) + } } private fun getParameterMapping(isParameter: Boolean, typeName: TypeName): TypeName { - return if (isParameter) typeName - else { + return if (isParameter) { + typeName + } else { ClassName("org.web3j.openapi.core.models", "ResultModel") .parameterizedBy(typeName) } @@ -123,7 +133,8 @@ internal fun AbiDefinition.getReturnType(packageName: String = "", contractName: getParameterMapping( false, ClassName("org.web3j.tuples.generated", "Tuple${outputs.size}") - .parameterizedBy(outputs.map { it.type.mapType(true, it.internalType.structName, packageName, contractName).copy() })) + .parameterizedBy(outputs.map { it.type.mapType(true, it.internalType.structName, packageName, contractName).copy() }), + ) } } else { ClassName("org.web3j.openapi.core.models", "TransactionReceiptModel") @@ -141,7 +152,7 @@ internal fun loadContractDefinition(absFile: File?): List { val abiDefinition: Array = objectMapper.readValue( absFile, - Array::class.java + Array::class.java, ) return listOf(*abiDefinition) } @@ -151,10 +162,9 @@ internal val String.structName // FIXME: Use web3j.codegen one fun extractStructs( - functionDefinitions: List + functionDefinitions: List, ): List? { - val structMap: HashMap = - LinkedHashMap() + val structMap: HashMap = LinkedHashMap() functionDefinitions.stream() .flatMap { definition: AbiDefinition -> val parameters: MutableList = @@ -179,7 +189,7 @@ fun extractStructs( // FIXME: Use web3j.codegen one private fun extractNested( - namedType: AbiDefinition.NamedType + namedType: AbiDefinition.NamedType, ): Collection? { return if (namedType.components.size == 0) { ArrayList() @@ -200,8 +210,11 @@ fun getStructCallParameters(contractName: String, input: AbiDefinition.NamedType val structName = input.internalType.structName val decapitalizedFunctionName = functionName.decapitalize() // FIXME: do we need this ? val parameters = input.components.joinToString(",") { component -> - if (component.components.isNullOrEmpty()) "$callTree.${component.name}" - else getStructCallParameters(contractName, component, decapitalizedFunctionName, "$callTree.${component.name}".removeSuffix(".")) + if (component.components.isNullOrEmpty()) { + "$callTree.${component.name}" + } else { + getStructCallParameters(contractName, component, decapitalizedFunctionName, "$callTree.${component.name}".removeSuffix(".")) + } } return "$contractName.$structName($parameters)" } diff --git a/codegen/src/main/kotlin/org/web3j/openapi/codegen/utils/TemplateUtils.kt b/codegen/src/main/kotlin/org/web3j/openapi/codegen/utils/TemplateUtils.kt index a55388ff..e91bb212 100644 --- a/codegen/src/main/kotlin/org/web3j/openapi/codegen/utils/TemplateUtils.kt +++ b/codegen/src/main/kotlin/org/web3j/openapi/codegen/utils/TemplateUtils.kt @@ -15,10 +15,10 @@ package org.web3j.openapi.codegen.utils import com.samskivert.mustache.Mustache import com.samskivert.mustache.Template import java.io.File +import java.io.FileOutputStream import java.io.InputStreamReader import java.io.OutputStreamWriter import java.io.PrintWriter -import java.io.FileOutputStream internal object TemplateUtils { fun mustacheTemplate(filePath: String): Template { diff --git a/codegen/src/main/kotlin/org/web3j/openapi/codegen/web3jCodegenStuff/FunctionWrapperGenerator.kt b/codegen/src/main/kotlin/org/web3j/openapi/codegen/web3jCodegenStuff/FunctionWrapperGenerator.kt index eb9ec400..05ef4503 100644 --- a/codegen/src/main/kotlin/org/web3j/openapi/codegen/web3jCodegenStuff/FunctionWrapperGenerator.kt +++ b/codegen/src/main/kotlin/org/web3j/openapi/codegen/web3jCodegenStuff/FunctionWrapperGenerator.kt @@ -22,7 +22,7 @@ abstract class FunctionWrapperGenerator( val destinationDirLocation: File?, open val basePackageName: String?, open val useJavaNativeTypes: Boolean, - open val useJavaPrimitiveTypes: Boolean + open val useJavaPrimitiveTypes: Boolean, ) { @Throws(IOException::class, ClassNotFoundException::class) diff --git a/codegen/src/main/kotlin/org/web3j/openapi/codegen/web3jCodegenStuff/SolidityFunctionWrapperGenerator.kt b/codegen/src/main/kotlin/org/web3j/openapi/codegen/web3jCodegenStuff/SolidityFunctionWrapperGenerator.kt index 84bef983..3cc5edde 100644 --- a/codegen/src/main/kotlin/org/web3j/openapi/codegen/web3jCodegenStuff/SolidityFunctionWrapperGenerator.kt +++ b/codegen/src/main/kotlin/org/web3j/openapi/codegen/web3jCodegenStuff/SolidityFunctionWrapperGenerator.kt @@ -29,13 +29,14 @@ class SolidityFunctionWrapperGenerator( override val useJavaPrimitiveTypes: Boolean = false, val generateSendTxForCalls: Boolean = false, override val contractClass: Class = Contract::class.java, - val addressLength: Int + val addressLength: Int, ) : FunctionWrapperGenerator( contractClass, destinationDir, basePackageName, useJavaNativeTypes, - useJavaPrimitiveTypes) { + useJavaPrimitiveTypes, +) { private val COMMAND_SOLIDITY = "solidity" private val COMMAND_GENERATE = "generate" @@ -70,7 +71,7 @@ class SolidityFunctionWrapperGenerator( val abiDefinition: Array = objectMapper.readValue( absFile, - Array::class.java + Array::class.java, ) return listOf(*abiDefinition) } @@ -93,7 +94,7 @@ class SolidityFunctionWrapperGenerator( useJavaNativeTypes, useJavaPrimitiveTypes, generateSendTxForCalls, - addressLength + addressLength, ) .generateJavaFiles( contractClass, @@ -102,13 +103,13 @@ class SolidityFunctionWrapperGenerator( functionDefinitions, destinationDirLocation.toString(), basePackageName, - null + null, ) println( """ File written to $destinationDirLocation - """.trimIndent() + """.trimIndent(), ) } } @@ -127,7 +128,7 @@ class SolidityFunctionWrapperGenerator( packageName, useJavaTypes, primitiveTypes, - addressLength = addressLength + addressLength = addressLength, ) .generate() } catch (e: Exception) { diff --git a/codegen/src/test/kotlin/org/web3j/openapi/codegen/utils/GeneratorUtilsTest.kt b/codegen/src/test/kotlin/org/web3j/openapi/codegen/utils/GeneratorUtilsTest.kt index 46fcc6d0..2c47916a 100644 --- a/codegen/src/test/kotlin/org/web3j/openapi/codegen/utils/GeneratorUtilsTest.kt +++ b/codegen/src/test/kotlin/org/web3j/openapi/codegen/utils/GeneratorUtilsTest.kt @@ -24,7 +24,8 @@ class GeneratorUtilsTest { "src", "test", "resources", - "contracts").toFile() + "contracts", + ).toFile() @Test fun `function names duplicates handling`() { @@ -33,15 +34,17 @@ class GeneratorUtilsTest { contractsFolder.absolutePath, "duplicate", "build", - "DuplicateField.abi" - ).toString() + "DuplicateField.abi", + ).toString(), ) val contractAbiDefinition = loadContractDefinition(duplicatesAbi) val sanitizedAbiDefinitions = handleDuplicateNames(contractAbiDefinition, "function") - assert(sanitizedAbiDefinitions.filter { it.type == "function" }.map { it.name.decapitalize() }.toSet().size - == loadContractDefinition(duplicatesAbi).filter { it.type == "function" }.size) + assert( + sanitizedAbiDefinitions.filter { it.type == "function" }.map { it.name.decapitalize() }.toSet().size + == loadContractDefinition(duplicatesAbi).filter { it.type == "function" }.size, + ) } @Test @@ -51,14 +54,16 @@ class GeneratorUtilsTest { contractsFolder.absolutePath, "duplicate", "build", - "DuplicateField.abi" - ).toString() + "DuplicateField.abi", + ).toString(), ) val inputWithDuplicates = loadContractDefinition(duplicatesAbi).filter { it.name == "Sum" }.map { it.inputs }.first() val sanitizedInputs = handleDuplicateInputNames(inputWithDuplicates) - assert(sanitizedInputs.map { it.name.decapitalize() }.toSet().size - == sanitizedInputs.size) + assert( + sanitizedInputs.map { it.name.decapitalize() }.toSet().size + == sanitizedInputs.size, + ) } } diff --git a/codegen/src/test/kotlin/org/web3j/openapi/codegen/utils/KPoetUtilsTest.kt b/codegen/src/test/kotlin/org/web3j/openapi/codegen/utils/KPoetUtilsTest.kt index 905dcb0e..b80eac29 100644 --- a/codegen/src/test/kotlin/org/web3j/openapi/codegen/utils/KPoetUtilsTest.kt +++ b/codegen/src/test/kotlin/org/web3j/openapi/codegen/utils/KPoetUtilsTest.kt @@ -30,34 +30,34 @@ class KPoetUtilsTest { val expectedOutput = """ package test - import com.fasterxml.jackson.annotation.JsonProperty + import com.fasterxml.jackson.`annotation`.JsonProperty import java.math.BigInteger import kotlin.String - data class TestFunctionParameters( + public data class TestFunctionParameters( @JsonProperty(value = "number") - val number: BigInteger, + public val number: BigInteger, @JsonProperty(value = "string") - val string: String + public val string: String, ) """.replace("\\s".toRegex(), "") val namedTypes = listOf( NamedType("number", "uint256"), - NamedType("string", "string") + NamedType("string", "string"), ) namedTypes.toDataClass( "test", "testFunction", - "Parameters" + "Parameters", ).writeTo(tempFolder) val actualOutput = File( Paths.get( tempFolder.absolutePath, "test", - "TestFunctionParameters.kt" - ).toString() + "TestFunctionParameters.kt", + ).toString(), ).readText().replace("\\s".toRegex(), "") assertThat(actualOutput).isEqualTo(expectedOutput) diff --git a/codegen/src/test/kotlin/org/web3j/openapi/codegen/utils/SolidityUtilsTest.kt b/codegen/src/test/kotlin/org/web3j/openapi/codegen/utils/SolidityUtilsTest.kt index 4738ff78..b0f63c65 100644 --- a/codegen/src/test/kotlin/org/web3j/openapi/codegen/utils/SolidityUtilsTest.kt +++ b/codegen/src/test/kotlin/org/web3j/openapi/codegen/utils/SolidityUtilsTest.kt @@ -30,7 +30,7 @@ class SolidityUtilsTest { val expectedResult = ClassName("kotlin.collections", "List") .plusParameter( ClassName("kotlin.collections", "List") - .plusParameter(Integer::class.asClassName()) + .plusParameter(Integer::class.asClassName()), ) val actualResult = "int[10][20]".mapType() @@ -43,7 +43,7 @@ class SolidityUtilsTest { .parameterizedBy( ClassName("kotlin.collections", "List") .plusParameter(ANY.copy(true)) - .copy(true) + .copy(true), ) val actualResult = "int[10][20]".mapType(false) @@ -84,15 +84,15 @@ class SolidityUtilsTest { .parameterizedBy( listOf( Integer::class.asClassName(), - String::class.asClassName() - ) - ) + String::class.asClassName(), + ), + ), ) val actualResult = AbiDefinition().apply { outputs = listOf( NamedType("param1", "int"), - NamedType("param2", "address") + NamedType("param2", "address"), ) isConstant = true } diff --git a/codegen/src/test/kotlin/org/web3j/openapi/codegen/utils/TemplateUtilsTest.kt b/codegen/src/test/kotlin/org/web3j/openapi/codegen/utils/TemplateUtilsTest.kt index 33c6cad1..8a86b859 100644 --- a/codegen/src/test/kotlin/org/web3j/openapi/codegen/utils/TemplateUtilsTest.kt +++ b/codegen/src/test/kotlin/org/web3j/openapi/codegen/utils/TemplateUtilsTest.kt @@ -29,8 +29,9 @@ class TemplateUtilsTest { fun mustacheTemplateTest() { assertThat( TemplateUtils.mustacheTemplate( - "server/src/GeneratedContractsResourceImpl.mustache" - )).isNotNull() + "server/src/GeneratedContractsResourceImpl.mustache", + ), + ).isNotNull() } @Test @@ -42,8 +43,8 @@ class TemplateUtilsTest { tempFolder.absolutePath, "testTemplate.txt", TemplateUtils.mustacheTemplate( - "testTemplate.mustache" - ) + "testTemplate.mustache", + ), ).readText().replace("\\s".toRegex(), "") assertThat(actualOutput).isEqualTo(expectedOutput) diff --git a/codegen/src/test/resources/contracts/radish34/BN256G2.sol b/codegen/src/test/resources/contracts/radish34/BN256G2.sol index 52c6e38a..458e44f9 100644 --- a/codegen/src/test/resources/contracts/radish34/BN256G2.sol +++ b/codegen/src/test/resources/contracts/radish34/BN256G2.sol @@ -1,5 +1,4 @@ -// This file is LGPL3 Licensed - +// SPDX-License-Identifier: MIT pragma solidity ^0.5.8; /** diff --git a/core/build.gradle b/core/build.gradle index f3deec1c..91b80429 100644 --- a/core/build.gradle +++ b/core/build.gradle @@ -8,5 +8,12 @@ dependencies { implementation "io.swagger.core.v3:swagger-annotations:${versions.swagger}" } -// To publish in mavenLocal() -// tasks.withType(Sign)*.enabled = false +tasks.named("spotlessJava") { + dependsOn(tasks.named("spotlessGroovyGradle")) + dependsOn(tasks.named("compileKotlin")) +} + +tasks.named("spotlessKotlin") { + dependsOn(tasks.named("spotlessGroovyGradle")) + dependsOn(tasks.named("spotlessJava")) +} diff --git a/core/src/main/kotlin/org/web3j/openapi/core/ErrorResponse.kt b/core/src/main/kotlin/org/web3j/openapi/core/ErrorResponse.kt index e91acb76..ff2a351e 100644 --- a/core/src/main/kotlin/org/web3j/openapi/core/ErrorResponse.kt +++ b/core/src/main/kotlin/org/web3j/openapi/core/ErrorResponse.kt @@ -21,7 +21,7 @@ import io.swagger.v3.oas.annotations.media.Schema "responseStatus", "requestMethod", "requestUrl", - "user" + "user", ) data class ErrorResponse( // @ApiModelProperty(value = "The error title", readOnly = true) @@ -37,5 +37,5 @@ data class ErrorResponse( val responseStatus: Int? = null, // @ApiModelProperty(value = "The UA string if provided with a request") - val userAgent: String? = null + val userAgent: String? = null, ) diff --git a/core/src/main/kotlin/org/web3j/openapi/core/models/LogsModel.kt b/core/src/main/kotlin/org/web3j/openapi/core/models/LogsModel.kt index cd91c753..928a3119 100644 --- a/core/src/main/kotlin/org/web3j/openapi/core/models/LogsModel.kt +++ b/core/src/main/kotlin/org/web3j/openapi/core/models/LogsModel.kt @@ -25,7 +25,7 @@ data class LogsModel( val address: String? = null, val data: String? = null, val type: String? = null, - val topics: List? = null + val topics: List? = null, ) { constructor(log: Log) : this ( log.isRemoved, @@ -37,6 +37,6 @@ data class LogsModel( log.address, log.data, log.type, - log.topics + log.topics, ) } diff --git a/core/src/main/kotlin/org/web3j/openapi/core/models/ResultModel.kt b/core/src/main/kotlin/org/web3j/openapi/core/models/ResultModel.kt index aa4cff49..00d88b9a 100644 --- a/core/src/main/kotlin/org/web3j/openapi/core/models/ResultModel.kt +++ b/core/src/main/kotlin/org/web3j/openapi/core/models/ResultModel.kt @@ -13,5 +13,5 @@ package org.web3j.openapi.core.models data class ResultModel( - val result: T? = null + val result: T? = null, ) diff --git a/core/src/main/kotlin/org/web3j/openapi/core/models/TransactionReceiptModel.kt b/core/src/main/kotlin/org/web3j/openapi/core/models/TransactionReceiptModel.kt index 8ab13bb5..8e442ada 100644 --- a/core/src/main/kotlin/org/web3j/openapi/core/models/TransactionReceiptModel.kt +++ b/core/src/main/kotlin/org/web3j/openapi/core/models/TransactionReceiptModel.kt @@ -32,7 +32,7 @@ data class TransactionReceiptModel( val logsBloom: String?, val revertReason: String?, val type: String, - val effectiveGasPrice: String + val effectiveGasPrice: String, ) { constructor(txReceipt: TransactionReceipt) : this( txReceipt.transactionHash, @@ -50,7 +50,7 @@ data class TransactionReceiptModel( txReceipt.logsBloom, txReceipt.revertReason, txReceipt.type, - txReceipt.effectiveGasPrice + txReceipt.effectiveGasPrice, ) { } @@ -78,13 +78,13 @@ data class TransactionReceiptModel( it.address, it.data, it.type, - it.topics + it.topics, ) }, this.logsBloom, this.revertReason, this.type, - this.effectiveGasPrice + this.effectiveGasPrice, ) } } diff --git a/gradle.properties b/gradle.properties index f33d95ec..e7b9ea44 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1,8 +1,9 @@ group=org.web3j -version=4.11.3-SNAPSHOT +version=4.12.3-SNAPSHOT kotlin.code.style=official kotlin.caching.enabled=true kotlin.incremental=true -kotlinVersion=1.8.10 +kotlinVersion=1.9.24 org.gradle.caching=true org.gradle.parallel=true +org.gradle.jvmargs=-Xmx2g diff --git a/gradle/jacoco/build.gradle b/gradle/jacoco/build.gradle new file mode 100644 index 00000000..4ef78502 --- /dev/null +++ b/gradle/jacoco/build.gradle @@ -0,0 +1,33 @@ +apply plugin: 'jacoco' + +task jacocoRootTestReport(type: org.gradle.testing.jacoco.tasks.JacocoReport) { + dependsOn = subprojects.test + getSourceDirectories().from(subprojects.sourceSets.main.allSource.srcDirs) + getAdditionalSourceDirs().from(subprojects.sourceSets.main.allSource.srcDirs) + getClassDirectories().from(subprojects.sourceSets.main.output) + getExecutionData().from(subprojects.jacocoTestReport.executionData) + reports { + xml.required.set(true) + } + + doFirst { + getExecutionData().from(executionData.findAll { it.exists() }) + } + + afterEvaluate { + getClassDirectories().from(files(classDirectories.files.collect { + fileTree(dir: it, + exclude: [ + 'org/web3j/abi/datatypes/generated/**', + 'org/web3j/tuples/generated/**', + 'org/web3j/ens/contracts/generated/**', + 'org/gradle/**' + ]) + })) + } +} + +jacoco { + toolVersion = "0.8.10" +} + diff --git a/gradle/java/build.gradle b/gradle/java/build.gradle new file mode 100644 index 00000000..bdb987d4 --- /dev/null +++ b/gradle/java/build.gradle @@ -0,0 +1,12 @@ +apply plugin: 'java' + +sourceCompatibility = 17 +targetCompatibility = 17 + +compileJava { + options.compilerArgs << "-Xlint:unchecked" << "-Xlint:deprecation" +} + +compileTestJava { + options.compilerArgs << "-Xlint:unchecked" << "-Xlint:deprecation" +} diff --git a/gradle/javadoc/build.gradle b/gradle/javadoc/build.gradle new file mode 100644 index 00000000..a141609f --- /dev/null +++ b/gradle/javadoc/build.gradle @@ -0,0 +1 @@ +javadoc { options.encoding = 'UTF-8' } diff --git a/gradle/publish/build.gradle b/gradle/publish/build.gradle new file mode 100644 index 00000000..f0794ad3 --- /dev/null +++ b/gradle/publish/build.gradle @@ -0,0 +1,90 @@ +apply plugin: 'maven-publish' +apply plugin: 'signing' +apply plugin: "de.marcphilipp.nexus-publish" + +task javadocsJar(type: Jar) { + archiveClassifier.set('javadoc') + from javadoc +} + +task sourcesJar(type: Jar) { + archiveClassifier.set('sources') + from sourceSets.main.allSource +} + +task testsJar(type: Jar) { + archiveClassifier.set('tests') + from sourceSets.test.output +} + +javadoc { options.encoding = 'UTF-8' } + +artifacts { archives sourcesJar, javadocsJar, testsJar } + +publishing { + publications { + maven(MavenPublication) { + from components.java + + artifact sourcesJar + artifact javadocsJar + artifact testsJar + + pom { + name = project.name + description.set(project.provider({ project.description })) + url = 'https://web3j.io' + + licenses { + license { + name = 'The Apache License, Version 2.0' + url = 'http://www.apache.org/licenses/LICENSE-2.0.txt' + } + } + + scm { + def slug = rootProject.name + if (project.hasProperty('rootProjectOverride')) { + slug = project.rootProjectOverride + } + + url = "https://github.com/hyperledger/$slug" + connection = "scm:https://github.com/hyperledger/${slug}.git" + developerConnection = "scm:git://github.com/hyperledger/${slug}.git" + } + + developers { + developer { + id = 'conor10' + name = 'Conor Svensson' + email = 'conor10@gmail.com' + } + } + } + } + } +} + +nexusPublishing { + repositories { + sonatype { + username = System.getenv('OSSRH_USERNAME') + password = System.getenv('OSSRH_PASSWORD') + } + } +} + + +nexusStaging { + username System.getenv('OSSRH_USERNAME') + password System.getenv('OSSRH_PASSWORD') + packageGroup = rootProject.group +} + + +signing { + sign publishing.publications.maven + def gpgSecretKey = System.getenv('OSSRH_GPG_SECRET_KEY') + def password = System.getenv('OSSRH_GPG_SECRET_KEY_PASSWORD') + useInMemoryPgpKeys(gpgSecretKey, password) +} diff --git a/gradle/repositories/build.gradle b/gradle/repositories/build.gradle new file mode 100644 index 00000000..b70c78d1 --- /dev/null +++ b/gradle/repositories/build.gradle @@ -0,0 +1,10 @@ +repositories { + mavenCentral() + maven { + url = uri("https://plugins.gradle.org/m2/") + } + jcenter() + maven { url 'https://oss.sonatype.org/content/repositories/releases/' } + maven { url "https://oss.sonatype.org/content/repositories/snapshots/" } + maven { url "https://artifacts.consensys.net/public/maven/maven/" } +} diff --git a/gradle/spotless/build.gradle b/gradle/spotless/build.gradle new file mode 100644 index 00000000..cba3ba48 --- /dev/null +++ b/gradle/spotless/build.gradle @@ -0,0 +1,55 @@ + +apply plugin: 'com.diffplug.spotless' +apply plugin: "de.undercouch.download" + +task downloadJavaLicense(type: Download) { + src 'https://raw.githubusercontent.com/hyperledger/web3j-build-tools/main/gradle/spotless/java.license' + dest new File("$rootDir/gradle/spotless",'java.license') + quiet true + onlyIfModified true +} + +task downloadFormatterProperties(type: Download) { + src 'https://raw.githubusercontent.com/hyperledger/web3j-build-tools/main/gradle/spotless/formatter.properties' + dest new File("$rootDir/gradle/spotless",'formatter.properties') + quiet true + onlyIfModified true +} + +spotless { + java { + // This path needs to be relative to each project + target fileTree('.') { + include '**/src/*/java/**/*.java' + exclude '**/.gradle/**' + exclude '**/generated/**' + exclude '**/build/install/**' + } + removeUnusedImports() + googleJavaFormat("1.17.0").aosp() + importOrder 'java', '', 'org.web3j', '\\#' + trimTrailingWhitespace() + endWithNewline() + licenseHeaderFile "$rootDir/gradle/spotless/java.license" + } + kotlin { + // This path needs to be relative to each project + target fileTree('.') { + include '**/*.kt' + exclude '**/.gradle/**' + exclude '**/build/install/**' + } + ktlint('0.49.1') + trimTrailingWhitespace() + endWithNewline() + licenseHeaderFile "$rootDir/gradle/spotless/java.license" + } + groovyGradle { + target '*.gradle' + greclipse().configFile("$rootDir/gradle/spotless/formatter.properties") + endWithNewline() + indentWithSpaces(4) + } +} + +spotlessCheck.dependsOn('downloadJavaLicense', 'downloadFormatterProperties') diff --git a/gradle/spotless/formatter.properties b/gradle/spotless/formatter.properties new file mode 100644 index 00000000..82650a05 --- /dev/null +++ b/gradle/spotless/formatter.properties @@ -0,0 +1,42 @@ +#Whether to use 'space', 'tab' or 'mixed' (both) characters for indentation. +#The default value is 'tab'. +org.eclipse.jdt.core.formatter.tabulation.char=space + +#Whether or not indentation characters are inserted into empty lines. +#The default value is 'true'. +org.eclipse.jdt.core.formatter.indent_empty_lines=false + +#Length after which list are considered too long. These will be wrapped. +#The default value is 30. +groovy.formatter.longListLength=30 + +#Whether opening braces position shall be the next line. +#The default value is 'same'. +groovy.formatter.braces.start=same + +#Whether closing braces position shall be the next line. +#The default value is 'next'. +groovy.formatter.braces.end=next + +#Remove unnecessary semicolons. The default value is 'false'. +groovy.formatter.remove.unnecessary.semicolons=false + +org.eclipse.jdt.core.formatter.brace_position_for_anonymous_type_declaration=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_method_declaration=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_block=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_constructor_declaration=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_lambda_body=end_of_line +org.eclipse.jdt.core.formatter.insert_new_line_before_closing_brace_in_array_initializer=do not insert +org.eclipse.jdt.core.formatter.brace_position_for_enum_declaration=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_block_in_case=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_annotation_type_declaration=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_switch=end_of_line +org.eclipse.jdt.core.formatter.insert_new_line_after_opening_brace_in_array_initializer=do not insert +org.eclipse.jdt.core.formatter.brace_position_for_array_initializer=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_enum_constant=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_type_declaration=end_of_line + +org.eclipse.jdt.core.formatter.insert_new_line_at_end_of_file_if_missing=insert + +# Formatter can be buggy in CI +ignoreFormatterProblems=true diff --git a/gradle/spotless/java.license b/gradle/spotless/java.license new file mode 100644 index 00000000..bb72b968 --- /dev/null +++ b/gradle/spotless/java.license @@ -0,0 +1,12 @@ +/* + * Copyright $YEAR Web3 Labs Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar index e708b1c0..e6441136 100644 Binary files a/gradle/wrapper/gradle-wrapper.jar and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 070cb702..b82aa23a 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,5 +1,7 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-7.6-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-8.7-bin.zip +networkTimeout=10000 +validateDistributionUrl=true zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew index 4f906e0c..1aa94a42 100755 --- a/gradlew +++ b/gradlew @@ -1,7 +1,7 @@ -#!/usr/bin/env sh +#!/bin/sh # -# Copyright 2015 the original author or authors. +# Copyright © 2015-2021 the original authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -17,67 +17,99 @@ # ############################################################################## -## -## Gradle start up script for UN*X -## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# ############################################################################## # Attempt to set APP_HOME + # Resolve links: $0 may be a link -PRG="$0" -# Need this for relative symlinks. -while [ -h "$PRG" ] ; do - ls=`ls -ld "$PRG"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - PRG="$link" - else - PRG=`dirname "$PRG"`"/$link" - fi +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac done -SAVED="`pwd`" -cd "`dirname \"$PRG\"`/" >/dev/null -APP_HOME="`pwd -P`" -cd "$SAVED" >/dev/null -APP_NAME="Gradle" -APP_BASE_NAME=`basename "$0"` - -# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit # Use the maximum available, or set MAX_FD != -1 to use that value. -MAX_FD="maximum" +MAX_FD=maximum warn () { echo "$*" -} +} >&2 die () { echo echo "$*" echo exit 1 -} +} >&2 # OS specific support (must be 'true' or 'false'). cygwin=false msys=false darwin=false nonstop=false -case "`uname`" in - CYGWIN* ) - cygwin=true - ;; - Darwin* ) - darwin=true - ;; - MINGW* ) - msys=true - ;; - NONSTOP* ) - nonstop=true - ;; +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; esac CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar @@ -87,9 +119,9 @@ CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar if [ -n "$JAVA_HOME" ] ; then if [ -x "$JAVA_HOME/jre/sh/java" ] ; then # IBM's JDK on AIX uses strange locations for the executables - JAVACMD="$JAVA_HOME/jre/sh/java" + JAVACMD=$JAVA_HOME/jre/sh/java else - JAVACMD="$JAVA_HOME/bin/java" + JAVACMD=$JAVA_HOME/bin/java fi if [ ! -x "$JAVACMD" ] ; then die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME @@ -98,88 +130,120 @@ Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi else - JAVACMD="java" - which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. Please set the JAVA_HOME variable in your environment to match the location of your Java installation." + fi fi # Increase the maximum file descriptors if we can. -if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then - MAX_FD_LIMIT=`ulimit -H -n` - if [ $? -eq 0 ] ; then - if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then - MAX_FD="$MAX_FD_LIMIT" - fi - ulimit -n $MAX_FD - if [ $? -ne 0 ] ; then - warn "Could not set maximum file descriptor limit: $MAX_FD" - fi - else - warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" - fi +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac fi -# For Darwin, add options to specify how the application appears in the dock -if $darwin; then - GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" -fi +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. # For Cygwin or MSYS, switch paths to Windows format before running java -if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then - APP_HOME=`cygpath --path --mixed "$APP_HOME"` - CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` - - JAVACMD=`cygpath --unix "$JAVACMD"` - - # We build the pattern for arguments to be converted via cygpath - ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` - SEP="" - for dir in $ROOTDIRSRAW ; do - ROOTDIRS="$ROOTDIRS$SEP$dir" - SEP="|" - done - OURCYGPATTERN="(^($ROOTDIRS))" - # Add a user-defined pattern to the cygpath arguments - if [ "$GRADLE_CYGPATTERN" != "" ] ; then - OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" - fi +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + # Now convert the arguments - kludge to limit ourselves to /bin/sh - i=0 - for arg in "$@" ; do - CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` - CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option - - if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition - eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` - else - eval `echo args$i`="\"$arg\"" + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) fi - i=`expr $i + 1` + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg done - case $i in - 0) set -- ;; - 1) set -- "$args0" ;; - 2) set -- "$args0" "$args1" ;; - 3) set -- "$args0" "$args1" "$args2" ;; - 4) set -- "$args0" "$args1" "$args2" "$args3" ;; - 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; - 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; - 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; - 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; - 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; - esac fi -# Escape application args -save () { - for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done - echo " " -} -APP_ARGS=`save "$@"` -# Collect all arguments for the java command, following the shell quoting and substitution rules -eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat index ac1b06f9..7101f8e4 100644 --- a/gradlew.bat +++ b/gradlew.bat @@ -14,7 +14,7 @@ @rem limitations under the License. @rem -@if "%DEBUG%" == "" @echo off +@if "%DEBUG%"=="" @echo off @rem ########################################################################## @rem @rem Gradle startup script for Windows @@ -25,7 +25,8 @@ if "%OS%"=="Windows_NT" setlocal set DIRNAME=%~dp0 -if "%DIRNAME%" == "" set DIRNAME=. +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused set APP_BASE_NAME=%~n0 set APP_HOME=%DIRNAME% @@ -40,13 +41,13 @@ if defined JAVA_HOME goto findJavaFromJavaHome set JAVA_EXE=java.exe %JAVA_EXE% -version >NUL 2>&1 -if "%ERRORLEVEL%" == "0" goto execute +if %ERRORLEVEL% equ 0 goto execute -echo. -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 goto fail @@ -56,11 +57,11 @@ set JAVA_EXE=%JAVA_HOME%/bin/java.exe if exist "%JAVA_EXE%" goto execute -echo. -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 goto fail @@ -75,13 +76,15 @@ set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar :end @rem End local scope for the variables with windows NT shell -if "%ERRORLEVEL%"=="0" goto mainEnd +if %ERRORLEVEL% equ 0 goto mainEnd :fail rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of rem the _cmd.exe /c_ return code! -if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 -exit /b 1 +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% :mainEnd if "%OS%"=="Windows_NT" endlocal diff --git a/server/build.gradle b/server/build.gradle index f50ea3c7..d5998255 100644 --- a/server/build.gradle +++ b/server/build.gradle @@ -25,9 +25,6 @@ dependencies { api project(':web3j-openapi-core') implementation "org.web3j:core:$web3jVersion" - implementation("io.epirus:epirus-web3j:${versions.web3jEpirus}") { - exclude group: 'org.web3j' - } implementation "org.glassfish.jersey.containers:jersey-container-servlet:${versions.jersey}" implementation "org.glassfish.jersey.media:jersey-media-json-jackson:${versions.jersey}" @@ -76,51 +73,13 @@ dependencies { integrationTestImplementation "org.hyperledger.besu:secp256k1:$besuCryptoDepVersion" } -// To publish in mavenLocal() -// tasks.withType(Sign)*.enabled = false - -//ext { -// generatedProjectName = "testProject" -// outputDirectory = "$projectDir/build/tmp/web3j-openapi/generated" -//} - -//task copyOpenApiResources(type: Copy) { -// from 'build/resources/integrationTest/server/src/main/resources' -// into "$outputDirectory/$generatedProjectName/server/src/main/resources" -// delete('src/main/resources/logging.properties') -// delete('src/main/resources/META-INF') -//} - -//task generateOpenApiProject(type : Exec, group: 'web3j') { -// dependsOn(":web3j-openapi-console:installShadowDist") -// dependsOn copyOpenApiResources -// commandLine "$rootDir/console/build/install/web3j-openapi-console-shadow/bin/web3j-openapi", -// 'generate', -// '--name', "$generatedProjectName", -// '--context-path', 'api', -// '--package-name', 'com.test', -// '--abi', "$projectDir/src/integration-test/resources/contracts", -// '--bin', "$projectDir/src/integration-test/resources/contracts", -// '--output', "$outputDirectory" -//} - -//compileIntegrationTestKotlin.dependsOn generateOpenApiProject - -//sourceSets { -// integrationTest.java.srcDirs += [ -// "$outputDirectory/$generatedProjectName/server/src/main/java" -// ] -// integrationTest.kotlin.srcDirs += [ -// "$outputDirectory/$generatedProjectName/core/src/main/kotlin", -// "$outputDirectory/$generatedProjectName/server/src/main/kotlin", -// "$outputDirectory/$generatedProjectName/server/src/main/java" -// ] -//} - -//task copyIntegrationTestResources(type: Copy) { -// from "$rootDir/codegen/build/resources/main/server/src/main/resources" -// into 'build/resources/integrationTest/server/src/main/resources' -// dependsOn processTestResources -//} +tasks.named("spotlessJava") { + dependsOn(tasks.named("spotlessGroovyGradle")) + dependsOn(tasks.named("compileKotlin")) + dependsOn(tasks.named("processResources")) +} -//integrationTest.dependsOn copyIntegrationTestResources +tasks.named("spotlessKotlin") { + dependsOn(tasks.named("spotlessGroovyGradle")) + dependsOn(tasks.named("spotlessJava")) +} diff --git a/server/src/integration-test/kotlin/org/web3j/openapi/server/ServerTest.kt b/server/src/integration-test/kotlin/org/web3j/openapi/server/ServerTest.kt index e6668b83..c9a36d6e 100644 --- a/server/src/integration-test/kotlin/org/web3j/openapi/server/ServerTest.kt +++ b/server/src/integration-test/kotlin/org/web3j/openapi/server/ServerTest.kt @@ -17,10 +17,6 @@ import assertk.assertions.containsExactly import assertk.assertions.isEqualTo import assertk.assertions.isNotNull import assertk.assertions.isTrue -import org.web3j.test.core.TestProjectApi -import org.web3j.test.core.humanstandardtoken.HumanStandardTokenResource -import org.web3j.test.core.humanstandardtoken.model.ApproveParameters -import org.web3j.test.core.humanstandardtoken.model.HumanStandardTokenDeployParameters import org.glassfish.jersey.test.JerseyTest import org.junit.jupiter.api.AfterAll import org.junit.jupiter.api.BeforeAll @@ -33,6 +29,10 @@ import org.web3j.openapi.client.ClientFactory import org.web3j.openapi.client.ClientService import org.web3j.openapi.server.config.OpenApiResourceConfig import org.web3j.openapi.server.config.OpenApiServerConfig +import org.web3j.test.core.TestProjectApi +import org.web3j.test.core.humanstandardtoken.HumanStandardTokenResource +import org.web3j.test.core.humanstandardtoken.model.ApproveParameters +import org.web3j.test.core.humanstandardtoken.model.HumanStandardTokenDeployParameters import java.math.BigInteger import java.net.URL import java.util.concurrent.CountDownLatch @@ -51,7 +51,7 @@ class ServerTest : JerseyTest() { private val client: TestProjectApi by lazy { ClientFactory.create( TestProjectApi::class.java, - ClientService(target().uri.toString()) + ClientService(target().uri.toString()), ) } @@ -62,8 +62,8 @@ class ServerTest : JerseyTest() { nodeEndpoint = URL("http://localhost:8545"), privateKey = PRIVATE_KEY, host = "localhost", - port = 0 - ) + port = 0, + ), ) @BeforeAll @@ -71,8 +71,11 @@ class ServerTest : JerseyTest() { super.setUp() contract = client.contracts.humanStandardToken.deploy( HumanStandardTokenDeployParameters( - BigInteger.TEN, "Test", BigInteger.ZERO, "TEST" - ) + BigInteger.TEN, + "Test", + BigInteger.ZERO, + "TEST", + ), ).let { client.contracts.humanStandardToken.load(it.contractAddress) } diff --git a/server/src/main/kotlin/org/web3j/openapi/server/ExceptionMappings.kt b/server/src/main/kotlin/org/web3j/openapi/server/ExceptionMappings.kt index dd0367b2..dbafe7f0 100644 --- a/server/src/main/kotlin/org/web3j/openapi/server/ExceptionMappings.kt +++ b/server/src/main/kotlin/org/web3j/openapi/server/ExceptionMappings.kt @@ -29,7 +29,7 @@ import javax.ws.rs.core.UriInfo import javax.ws.rs.ext.ExceptionMapper sealed class BaseExceptionMapper( - private val status: Response.StatusType + private val status: Response.StatusType, ) : ExceptionMapper { @Context @@ -39,13 +39,12 @@ sealed class BaseExceptionMapper( private lateinit var request: HttpServletRequest override fun toResponse(exception: E): Response { - val error = ErrorResponse( title = exception.message ?: status.reasonPhrase, userAgent = request.getHeader(HttpHeaders.USER_AGENT), responseStatus = status.statusCode, requestMethod = request.method, - requestUrl = uriInfo.requestUri.toString() + requestUrl = uriInfo.requestUri.toString(), ) return Response.status(status.statusCode).entity(error).build() @@ -64,13 +63,14 @@ class NotFoundExceptionMapper : BaseExceptionMapper(Status.NO enum class CustomStatus( private val _statusCode: Int, - private val _reasonPhrase: String + private val _reasonPhrase: String, ) : Response.StatusType { UNPROCESSABLE_ENTITY( HttpStatus.Code.UNPROCESSABLE_ENTITY.code, - HttpStatus.Code.UNPROCESSABLE_ENTITY.message - ); + HttpStatus.Code.UNPROCESSABLE_ENTITY.message, + ), + ; override fun getStatusCode(): Int = _statusCode override fun getFamily(): Family = Family.familyOf(_statusCode) diff --git a/server/src/main/kotlin/org/web3j/openapi/server/Factories.kt b/server/src/main/kotlin/org/web3j/openapi/server/Factories.kt index 72582eb9..5dea9ffd 100644 --- a/server/src/main/kotlin/org/web3j/openapi/server/Factories.kt +++ b/server/src/main/kotlin/org/web3j/openapi/server/Factories.kt @@ -12,22 +12,17 @@ */ package org.web3j.openapi.server -import io.epirus.web3j.Epirus -import io.epirus.web3j.gas.EpirusGasProvider -import io.epirus.web3j.gas.GasPrice import mu.KLogging import org.glassfish.hk2.api.Factory import org.web3j.crypto.Credentials import org.web3j.crypto.WalletUtils import org.web3j.openapi.server.Properties.CONTRACT_ADDRESSES -import org.web3j.openapi.server.Properties.GAS_PRICE import org.web3j.openapi.server.Properties.NETWORK import org.web3j.openapi.server.Properties.NODE_ADDRESS import org.web3j.openapi.server.Properties.PRIVATE_KEY import org.web3j.openapi.server.Properties.WALLET_FILE import org.web3j.openapi.server.Properties.WALLET_PASSWORD import org.web3j.openapi.server.config.ContractAddresses -import org.web3j.protocol.Network import org.web3j.protocol.Web3j import org.web3j.protocol.http.HttpService import org.web3j.tx.gas.ContractGasProvider @@ -37,23 +32,19 @@ import javax.ws.rs.core.Configuration import javax.ws.rs.core.Context class Web3jFactory( - @Context private val configuration: Configuration + @Context private val configuration: Configuration, ) : Factory { override fun provide(): Web3j { val nodeAddress = configuration.getProperty(NODE_ADDRESS)?.toString() - val network = configuration.getProperty(NETWORK)?.toString() - return if (network != null && network.isNotEmpty()) - Epirus.buildWeb3j(Network.valueOf(network.uppercase())) - else - Web3j.build(HttpService(nodeAddress)) + return Web3j.build(HttpService(nodeAddress)) } override fun dispose(web3j: Web3j) = web3j.shutdown() } class CredentialsFactory( - @Context private val configuration: Configuration + @Context private val configuration: Configuration, ) : Factory, KLogging() { override fun provide(): Credentials { @@ -69,8 +60,8 @@ class CredentialsFactory( logger.info("Loading credentials from raw private key") Credentials.create(privateKey) } else if (network != null && network.isNotEmpty()) { - val walletPath = System.getenv("EPIRUS_WALLET_PATH") - val walletPassword = System.getenv().getOrDefault("EPIRUS_WALLET_PASSWORD", "") + val walletPath = System.getenv("WEB3J_WALLET_PATH") + val walletPassword = System.getenv().getOrDefault("WEB3J_WALLET_PASSWORD", "") WalletUtils.loadCredentials(walletPassword, File(walletPath)) } else { logger.warn("Missing credentials! Aborting.") @@ -83,16 +74,11 @@ class CredentialsFactory( } class ContractGasProviderFactory( - @Context private val configuration: Configuration + @Context private val configuration: Configuration, ) : Factory { override fun provide(): ContractGasProvider { - val network = configuration.getProperty(NETWORK)?.toString() - val gasPrice = configuration.getProperty(GAS_PRICE) as GasPrice? ?: GasPrice.High - return if (network != null && network.isNotEmpty()) - EpirusGasProvider(Network.valueOf(network.uppercase()), gasPrice) - else - DefaultGasProvider() + return DefaultGasProvider() } override fun dispose(gasProvider: ContractGasProvider) { @@ -101,7 +87,7 @@ class ContractGasProviderFactory( @SuppressWarnings("Unchecked cast") class ContractAddressesFactory( - @Context private val configuration: Configuration + @Context private val configuration: Configuration, ) : Factory { override fun provide(): ContractAddresses { diff --git a/server/src/main/kotlin/org/web3j/openapi/server/OpenApiServer.kt b/server/src/main/kotlin/org/web3j/openapi/server/OpenApiServer.kt index 3b447e09..2483eb5c 100644 --- a/server/src/main/kotlin/org/web3j/openapi/server/OpenApiServer.kt +++ b/server/src/main/kotlin/org/web3j/openapi/server/OpenApiServer.kt @@ -28,10 +28,12 @@ import java.net.URI class OpenApiServer(private val serverConfig: OpenApiServerConfig) : Server() { init { - addConnector(ServerConnector(this).apply { - host = serverConfig.host - port = serverConfig.port - }) + addConnector( + ServerConnector(this).apply { + host = serverConfig.host + port = serverConfig.port + }, + ) handler = ServletContextHandler(NO_SESSIONS) configureSwaggerUi() configureOpenApi() diff --git a/server/src/main/kotlin/org/web3j/openapi/server/SseUtils.kt b/server/src/main/kotlin/org/web3j/openapi/server/SseUtils.kt index 53872318..3b810b1f 100644 --- a/server/src/main/kotlin/org/web3j/openapi/server/SseUtils.kt +++ b/server/src/main/kotlin/org/web3j/openapi/server/SseUtils.kt @@ -26,7 +26,7 @@ object SseUtils : KLogging() { flowable: Flowable, eventSink: SseEventSink, sse: Sse, - mapping: (T) -> R + mapping: (T) -> R, ) { flowable.blockingSubscribe({ event -> logger.debug { "Received ${eventType.name} event." } @@ -35,7 +35,7 @@ object SseUtils : KLogging() { .name(eventType.name) .mediaType(MediaType.APPLICATION_JSON_TYPE) .data(eventClass, mapping.invoke(event)) - .build() + .build(), ) }, { logger.warn { "Error on ${eventType.name} event sink: ${it.javaClass.canonicalName}" } diff --git a/server/src/main/kotlin/org/web3j/openapi/server/SubResourceImpl.kt b/server/src/main/kotlin/org/web3j/openapi/server/SubResourceImpl.kt index de2b855b..859e0041 100644 --- a/server/src/main/kotlin/org/web3j/openapi/server/SubResourceImpl.kt +++ b/server/src/main/kotlin/org/web3j/openapi/server/SubResourceImpl.kt @@ -18,7 +18,7 @@ import org.glassfish.jersey.server.model.Resource import org.web3j.openapi.core.SubResource abstract class SubResourceImpl( - private val uriInfo: ExtendedUriInfo + private val uriInfo: ExtendedUriInfo, ) : SubResource { override fun findAll(): List { diff --git a/server/src/main/kotlin/org/web3j/openapi/server/config/OpenApiResourceConfig.kt b/server/src/main/kotlin/org/web3j/openapi/server/config/OpenApiResourceConfig.kt index 8331e83f..cbe95cf8 100644 --- a/server/src/main/kotlin/org/web3j/openapi/server/config/OpenApiResourceConfig.kt +++ b/server/src/main/kotlin/org/web3j/openapi/server/config/OpenApiResourceConfig.kt @@ -32,11 +32,11 @@ import org.web3j.openapi.server.ContractGasProviderFactory import org.web3j.openapi.server.CredentialsFactory import org.web3j.openapi.server.IllegalArgumentExceptionMapper import org.web3j.openapi.server.IllegalStateExceptionMapper -import org.web3j.openapi.server.RuntimeExceptionMapper import org.web3j.openapi.server.JsonMappingExceptionMapper import org.web3j.openapi.server.JsonParseExceptionMapper import org.web3j.openapi.server.NotFoundExceptionMapper import org.web3j.openapi.server.Properties +import org.web3j.openapi.server.RuntimeExceptionMapper import org.web3j.openapi.server.TransactionExceptionMapper import org.web3j.openapi.server.UnsupportedOperationExceptionMapper import org.web3j.openapi.server.Web3jFactory @@ -54,7 +54,7 @@ import javax.inject.Singleton * @see OpenApiResourceProvider */ class OpenApiResourceConfig( - serverConfig: OpenApiServerConfig + serverConfig: OpenApiServerConfig, ) : ResourceConfig() { // /** @@ -107,8 +107,6 @@ class OpenApiResourceConfig( property(Properties.WALLET_FILE, serverConfig.walletFile?.absolutePath) property(Properties.WALLET_PASSWORD, serverConfig.walletPassword) property(Properties.CONTRACT_ADDRESSES, serverConfig.contractAddresses) - property(Properties.NETWORK, serverConfig.network) - property(Properties.GAS_PRICE, serverConfig.gasPrice) } private class InjectionBinder : AbstractBinder() { diff --git a/server/src/main/kotlin/org/web3j/openapi/server/config/OpenApiServerConfig.kt b/server/src/main/kotlin/org/web3j/openapi/server/config/OpenApiServerConfig.kt index 9173ba6f..ad17e6f0 100644 --- a/server/src/main/kotlin/org/web3j/openapi/server/config/OpenApiServerConfig.kt +++ b/server/src/main/kotlin/org/web3j/openapi/server/config/OpenApiServerConfig.kt @@ -12,7 +12,6 @@ */ package org.web3j.openapi.server.config -import io.epirus.web3j.gas.GasPrice import java.io.File import java.net.URL @@ -25,19 +24,18 @@ data class OpenApiServerConfig( val host: String, val port: Int, val contractAddresses: ContractAddresses = ContractAddresses.EMPTY, - val network: String = "", - val gasPrice: GasPrice = GasPrice.High ) { init { - if (nodeEndpoint == null && network.isBlank()) { - throw IllegalArgumentException("Invalid Ethereum node URL. Please specify the network endpoint or run using the Epirus-CLI") + if (nodeEndpoint == null) { + throw IllegalArgumentException("Invalid Ethereum node URL. Please specify the network endpoint or run using the Web3j-CLI") } else if (privateKey == null && walletFile == null) { - throw IllegalArgumentException("Invalid credentials, use a private key, wallet file or run using the Epirus-CLI") + throw IllegalArgumentException("Invalid credentials, use a private key, wallet file or run using the Web3j-CLI") } else if (walletFile != null) { - if (!walletFile.exists()) + if (!walletFile.exists()) { throw IllegalArgumentException("Wallet file $walletFile not found!") - else if (walletPassword == null) + } else if (walletPassword == null) { throw IllegalArgumentException("Wallet file $walletFile password not found!") + } } } } diff --git a/server/src/main/kotlin/org/web3j/openapi/server/console/ConfigFileCommand.kt b/server/src/main/kotlin/org/web3j/openapi/server/console/ConfigFileCommand.kt index 1a3d443c..e32623f3 100644 --- a/server/src/main/kotlin/org/web3j/openapi/server/console/ConfigFileCommand.kt +++ b/server/src/main/kotlin/org/web3j/openapi/server/console/ConfigFileCommand.kt @@ -21,7 +21,7 @@ import picocli.CommandLine.Unmatched * Allows two-pass approach to obtain an optional config file. */ @Command( - mixinStandardHelpOptions = true + mixinStandardHelpOptions = true, ) class ConfigFileCommand { diff --git a/server/src/main/kotlin/org/web3j/openapi/server/console/ConsoleConfiguration.kt b/server/src/main/kotlin/org/web3j/openapi/server/console/ConsoleConfiguration.kt index 80d0eff3..be32c482 100644 --- a/server/src/main/kotlin/org/web3j/openapi/server/console/ConsoleConfiguration.kt +++ b/server/src/main/kotlin/org/web3j/openapi/server/console/ConsoleConfiguration.kt @@ -14,12 +14,12 @@ package org.web3j.openapi.server.console import com.fasterxml.jackson.annotation.JsonProperty import org.web3j.openapi.server.console.options.ConfigFileOptions -import org.web3j.openapi.server.console.options.ProjectOptions +import org.web3j.openapi.server.console.options.CredentialsOptions import org.web3j.openapi.server.console.options.NetworkOptions +import org.web3j.openapi.server.console.options.ProjectOptions import org.web3j.openapi.server.console.options.ServerOptions -import org.web3j.openapi.server.console.options.CredentialsOptions -import picocli.CommandLine.Mixin import picocli.CommandLine.ArgGroup +import picocli.CommandLine.Mixin import picocli.CommandLine.Option class ConsoleConfiguration { @@ -49,7 +49,7 @@ class ConsoleConfiguration { description = ["Add pre-deployed contract addresses"], arity = "0..*", split = ",", - required = false + required = false, ) var contractAddresses: Map? = null } diff --git a/server/src/main/kotlin/org/web3j/openapi/server/console/RunServerCommand.kt b/server/src/main/kotlin/org/web3j/openapi/server/console/RunServerCommand.kt index b75edfd7..15b3a199 100644 --- a/server/src/main/kotlin/org/web3j/openapi/server/console/RunServerCommand.kt +++ b/server/src/main/kotlin/org/web3j/openapi/server/console/RunServerCommand.kt @@ -33,7 +33,7 @@ import kotlin.system.exitProcess showDefaultValues = true, mixinStandardHelpOptions = true, description = ["Runs a Web3j OpenAPI server."], - version = ["1.0"] // TODO: Make version not hardcoded + version = ["1.0"], // TODO: Make version not hardcoded ) class RunServerCommand : Callable { @@ -70,11 +70,10 @@ class RunServerCommand : Callable { putAll( contractAddresses .mapKeys { it.key.lowercase() } - .mapValues { Address(it.value) } + .mapValues { Address(it.value) }, ) } }, - network = consoleConfiguration.networkOptions.network ) } @@ -93,7 +92,6 @@ class RunServerCommand : Callable { } private fun configureDefaultProvider(args: Array, commandLine: CommandLine) { - // First pass to get the configuration file val configFileCommand = ConfigFileCommand() val configFileCommandLine = CommandLine(configFileCommand).apply { diff --git a/server/src/main/kotlin/org/web3j/openapi/server/console/defaultproviders/CascadingDefaultProvider.kt b/server/src/main/kotlin/org/web3j/openapi/server/console/defaultproviders/CascadingDefaultProvider.kt index c960ee97..10d28da5 100644 --- a/server/src/main/kotlin/org/web3j/openapi/server/console/defaultproviders/CascadingDefaultProvider.kt +++ b/server/src/main/kotlin/org/web3j/openapi/server/console/defaultproviders/CascadingDefaultProvider.kt @@ -16,7 +16,7 @@ import picocli.CommandLine.IDefaultValueProvider import picocli.CommandLine.Model.ArgSpec internal class CascadingDefaultProvider( - private vararg val defaultProviders: IDefaultValueProvider + private vararg val defaultProviders: IDefaultValueProvider, ) : IDefaultValueProvider { override fun defaultValue(argSpec: ArgSpec): String? { diff --git a/server/src/main/kotlin/org/web3j/openapi/server/console/defaultproviders/ConfigMapper.kt b/server/src/main/kotlin/org/web3j/openapi/server/console/defaultproviders/ConfigMapper.kt index c84778b8..6401138f 100644 --- a/server/src/main/kotlin/org/web3j/openapi/server/console/defaultproviders/ConfigMapper.kt +++ b/server/src/main/kotlin/org/web3j/openapi/server/console/defaultproviders/ConfigMapper.kt @@ -16,7 +16,7 @@ import org.web3j.openapi.server.console.ConsoleConfiguration import picocli.CommandLine internal class ConfigMapper( - private val consoleConfiguration: ConsoleConfiguration? + private val consoleConfiguration: ConsoleConfiguration?, ) { fun value(param: CommandLine.Model.ArgSpec): String? { diff --git a/server/src/main/kotlin/org/web3j/openapi/server/console/defaultproviders/EnvironmentVariableDefaultProvider.kt b/server/src/main/kotlin/org/web3j/openapi/server/console/defaultproviders/EnvironmentVariableDefaultProvider.kt index c8ce1bd3..e94fd1a3 100644 --- a/server/src/main/kotlin/org/web3j/openapi/server/console/defaultproviders/EnvironmentVariableDefaultProvider.kt +++ b/server/src/main/kotlin/org/web3j/openapi/server/console/defaultproviders/EnvironmentVariableDefaultProvider.kt @@ -15,7 +15,7 @@ package org.web3j.openapi.server.console.defaultproviders import picocli.CommandLine internal class EnvironmentVariableDefaultProvider( - private val environment: Map + private val environment: Map, ) : CommandLine.IDefaultValueProvider { private val WEB3J_VAR_PREFIX = "WEB3J_" diff --git a/server/src/main/kotlin/org/web3j/openapi/server/console/defaultproviders/JavaPropDefaultProvider.kt b/server/src/main/kotlin/org/web3j/openapi/server/console/defaultproviders/JavaPropDefaultProvider.kt index 4442829f..895547bb 100644 --- a/server/src/main/kotlin/org/web3j/openapi/server/console/defaultproviders/JavaPropDefaultProvider.kt +++ b/server/src/main/kotlin/org/web3j/openapi/server/console/defaultproviders/JavaPropDefaultProvider.kt @@ -12,13 +12,13 @@ */ package org.web3j.openapi.server.console.defaultproviders +import com.fasterxml.jackson.dataformat.javaprop.JavaPropsMapper import org.web3j.openapi.server.console.ConsoleConfiguration import picocli.CommandLine import java.io.File -import com.fasterxml.jackson.dataformat.javaprop.JavaPropsMapper internal class JavaPropDefaultProvider( - configFile: File? + configFile: File?, ) : CommandLine.IDefaultValueProvider { private val consoleConfiguration: ConsoleConfiguration? = JavaPropsMapper() diff --git a/server/src/main/kotlin/org/web3j/openapi/server/console/defaultproviders/JsonDefaultProvider.kt b/server/src/main/kotlin/org/web3j/openapi/server/console/defaultproviders/JsonDefaultProvider.kt index 4338b4c4..d2ff1c1f 100644 --- a/server/src/main/kotlin/org/web3j/openapi/server/console/defaultproviders/JsonDefaultProvider.kt +++ b/server/src/main/kotlin/org/web3j/openapi/server/console/defaultproviders/JsonDefaultProvider.kt @@ -18,7 +18,7 @@ import picocli.CommandLine import java.io.File internal class JsonDefaultProvider( - configFile: File? + configFile: File?, ) : CommandLine.IDefaultValueProvider { private val consoleConfiguration: ConsoleConfiguration? = ObjectMapper().readValue(configFile, ConsoleConfiguration::class.java) diff --git a/server/src/main/kotlin/org/web3j/openapi/server/console/defaultproviders/YamlDefaultProvider.kt b/server/src/main/kotlin/org/web3j/openapi/server/console/defaultproviders/YamlDefaultProvider.kt index ca82df92..7d945c2e 100644 --- a/server/src/main/kotlin/org/web3j/openapi/server/console/defaultproviders/YamlDefaultProvider.kt +++ b/server/src/main/kotlin/org/web3j/openapi/server/console/defaultproviders/YamlDefaultProvider.kt @@ -19,7 +19,7 @@ import picocli.CommandLine import java.io.File internal class YamlDefaultProvider( - configFile: File? + configFile: File?, ) : CommandLine.IDefaultValueProvider { private val consoleConfiguration: ConsoleConfiguration? = ObjectMapper(YAMLFactory()).readValue(configFile, ConsoleConfiguration::class.java) diff --git a/server/src/main/kotlin/org/web3j/openapi/server/console/options/ConfigFileOptions.kt b/server/src/main/kotlin/org/web3j/openapi/server/console/options/ConfigFileOptions.kt index b048346a..457f7d91 100644 --- a/server/src/main/kotlin/org/web3j/openapi/server/console/options/ConfigFileOptions.kt +++ b/server/src/main/kotlin/org/web3j/openapi/server/console/options/ConfigFileOptions.kt @@ -21,7 +21,7 @@ class ConfigFileOptions { names = ["-c", "--config-file"], paramLabel = "", description = ["name of the YAML configuration file"], - arity = "1" + arity = "1", ) var configFile: File? = null } diff --git a/server/src/main/kotlin/org/web3j/openapi/server/console/options/CredentialsOptions.kt b/server/src/main/kotlin/org/web3j/openapi/server/console/options/CredentialsOptions.kt index e8b53ff7..d6ea4259 100644 --- a/server/src/main/kotlin/org/web3j/openapi/server/console/options/CredentialsOptions.kt +++ b/server/src/main/kotlin/org/web3j/openapi/server/console/options/CredentialsOptions.kt @@ -20,7 +20,7 @@ class CredentialsOptions { @Option( names = ["--private-key"], - description = ["private key for signed transactions"] + description = ["private key for signed transactions"], ) var privateKey: String? = null diff --git a/server/src/main/kotlin/org/web3j/openapi/server/console/options/NetworkOptions.kt b/server/src/main/kotlin/org/web3j/openapi/server/console/options/NetworkOptions.kt index 4a28014b..292aa457 100644 --- a/server/src/main/kotlin/org/web3j/openapi/server/console/options/NetworkOptions.kt +++ b/server/src/main/kotlin/org/web3j/openapi/server/console/options/NetworkOptions.kt @@ -12,7 +12,6 @@ */ package org.web3j.openapi.server.console.options -import picocli.CommandLine import picocli.CommandLine.Option import java.net.URL @@ -20,16 +19,7 @@ class NetworkOptions { @Option( names = ["-e", "--endpoint"], description = ["specify the endpoint"], - required = true - ) - var endpoint: URL? = null - - @CommandLine.Option( - names = ["--network"], - description = ["specify the network rinkeby|ropsten|mainnet - For Epirus use"], required = true, - defaultValue = "", - hidden = true ) - var network: String = "" + var endpoint: URL? = null } diff --git a/server/src/main/kotlin/org/web3j/openapi/server/console/options/ProjectOptions.kt b/server/src/main/kotlin/org/web3j/openapi/server/console/options/ProjectOptions.kt index b12f636e..b88a0f90 100644 --- a/server/src/main/kotlin/org/web3j/openapi/server/console/options/ProjectOptions.kt +++ b/server/src/main/kotlin/org/web3j/openapi/server/console/options/ProjectOptions.kt @@ -20,13 +20,13 @@ class ProjectOptions { names = ["-n", "--name"], description = ["specify the project name."], defaultValue = "Web3j-OpenAPI", - required = true + required = true, ) lateinit var projectName: String @Option( names = ["--context-path"], - description = ["set the API context path (default: the project name)"] + description = ["set the API context path (default: the project name)"], ) var contextPath: String? = null } diff --git a/server/src/main/kotlin/org/web3j/openapi/server/console/options/ServerOptions.kt b/server/src/main/kotlin/org/web3j/openapi/server/console/options/ServerOptions.kt index 97f9a798..8628ef56 100644 --- a/server/src/main/kotlin/org/web3j/openapi/server/console/options/ServerOptions.kt +++ b/server/src/main/kotlin/org/web3j/openapi/server/console/options/ServerOptions.kt @@ -20,14 +20,14 @@ class ServerOptions { @Option( names = ["--host"], description = ["specify the host name"], - defaultValue = "localhost" + defaultValue = "localhost", ) lateinit var host: InetAddress @Option( names = ["--port"], description = ["specify the port number"], - defaultValue = "8080" + defaultValue = "8080", ) var port: Int = 8080 } diff --git a/server/src/main/kotlin/org/web3j/openapi/server/console/options/WalletOptions.kt b/server/src/main/kotlin/org/web3j/openapi/server/console/options/WalletOptions.kt index d55b4f1c..5c86d950 100644 --- a/server/src/main/kotlin/org/web3j/openapi/server/console/options/WalletOptions.kt +++ b/server/src/main/kotlin/org/web3j/openapi/server/console/options/WalletOptions.kt @@ -19,13 +19,13 @@ class WalletOptions { @Option( names = ["--wallet-path"], - description = ["specify the wallet file path"] + description = ["specify the wallet file path"], ) var walletFile: File? = null @Option( names = ["--wallet-password"], - description = ["specify the wallet file password"] + description = ["specify the wallet file password"], ) var walletPassword: String? = null } diff --git a/versions.properties b/versions.properties index d0db5e79..8f601bca 100644 --- a/versions.properties +++ b/versions.properties @@ -1,15 +1,14 @@ assertk=0.22 -gradle=6.2 -jackson=2.15.2 +gradle=8.7 +jackson=2.17.1 jersey=2.32 jetty=9.4.32.v20200930 -kotlinLogging=1.7.10 -kotlinPoet=1.5.0 +kotlinLogging=3.0.5 +kotlinPoet=1.18.1 ktlint=0.34.2 -logback=1.2.3 +logback=1.5.6 mockitoJunit=3.1.0 openApiGenerator=4.0.3 -picocli=4.3.2 -slf4j=1.7.30 -swagger=2.2.11 -web3jEpirus=0.0.6 +picocli=4.7.6 +slf4j=2.0.13 +swagger=2.2.11 \ No newline at end of file