diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 02c4f4b1fa..308fda00dd 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -55,7 +55,7 @@ jobs: SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }} run: ./gradlew sonarqube local-dev-sm-docker-build: - name: Test state-manager docker build for local development + name: Test core-rust docker build for local development runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 @@ -76,8 +76,8 @@ jobs: path: ~/.gradle/caches key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle') }} restore-keys: ${{ runner.os }}-gradle - - name: Run local state-manager docker build - run: ./gradlew :state-manager:buildRustForDocker + - name: Run local core-rust docker build + run: ./gradlew :core-rust:buildRustForDocker steadystate-integration: name: Steady state integration tests runs-on: babylon-runner diff --git a/build.gradle b/build.gradle index 4cefb82d50..55980624fa 100644 --- a/build.gradle +++ b/build.gradle @@ -182,12 +182,12 @@ allprojects { tasks.withType(Test) { systemProperty "file.encoding", "UTF-8" jvmArgs("--enable-preview") - systemProperty "java.library.path", "${project(':state-manager').projectDir}/target/debug" + systemProperty "java.library.path", "${project(':core-rust').projectDir}/target/debug" } } subprojects { - if (project.name == "state-manager") { + if (project.name == "core-rust") { // The below is suitable for a java project, not for a rust project return } diff --git a/cli-tools/build.gradle b/cli-tools/build.gradle index 71a1492552..0ebacbd3d9 100644 --- a/cli-tools/build.gradle +++ b/cli-tools/build.gradle @@ -144,7 +144,7 @@ task getClassPathForRadixShell { task getNativeLibPathForRadixShell { doLast { - print "${project(':state-manager').projectDir}/target/debug/" + print "${project(':core-rust').projectDir}/target/debug/" } } @@ -249,7 +249,7 @@ task runAllIntegrationTests(type: Test) { task runP2pTests(type: JavaExec) { classpath = sourceSets.p2pTest.runtimeClasspath - systemProperty "java.library.path", "${project(':state-manager').projectDir}/target/debug/" + systemProperty "java.library.path", "${project(':core-rust').projectDir}/target/debug/" main = "com.radixdlt.p2ptest.LargeMessageTest" } diff --git a/state-manager-bridge/README.md b/core-rust-bridge/README.md similarity index 100% rename from state-manager-bridge/README.md rename to core-rust-bridge/README.md diff --git a/state-manager-bridge/build.gradle b/core-rust-bridge/build.gradle similarity index 97% rename from state-manager-bridge/build.gradle rename to core-rust-bridge/build.gradle index 00f33cb521..d296d9c355 100644 --- a/state-manager-bridge/build.gradle +++ b/core-rust-bridge/build.gradle @@ -79,11 +79,11 @@ compileJava { // This prevents it being output by the jobs EG generateDevUniverse run in quiet mode. Hence, lifecycle. // Side note: The method of using stdout for generateDevUniverse and friends should really be changed. if (System.getenv("SKIP_NATIVE_RUST_BUILD") == "TRUE") { - logger.lifecycle("As SKIP_NATIVE_RUST_BUILD=TRUE, the native state-manager rust build is being skipped at this point.") + logger.lifecycle("As SKIP_NATIVE_RUST_BUILD=TRUE, the native core-rust build is being skipped at this point.") } else { logger.lifecycle("A native debug rust build required for the node to run natively will be run.") logger.lifecycle("This can be skipped with SKIP_NATIVE_RUST_BUILD=TRUE, if the rust is being built separately.") - dependsOn(":state-manager:buildRustDebug") + dependsOn(":core-rust:buildRustDebug") } } diff --git a/state-manager-bridge/src/main/java/com/radixdlt/api/CoreApiServer.java b/core-rust-bridge/src/main/java/com/radixdlt/api/CoreApiServer.java similarity index 100% rename from state-manager-bridge/src/main/java/com/radixdlt/api/CoreApiServer.java rename to core-rust-bridge/src/main/java/com/radixdlt/api/CoreApiServer.java diff --git a/state-manager-bridge/src/main/java/com/radixdlt/api/CoreApiServerModule.java b/core-rust-bridge/src/main/java/com/radixdlt/api/CoreApiServerModule.java similarity index 100% rename from state-manager-bridge/src/main/java/com/radixdlt/api/CoreApiServerModule.java rename to core-rust-bridge/src/main/java/com/radixdlt/api/CoreApiServerModule.java diff --git a/state-manager-bridge/src/main/java/com/radixdlt/exceptions/ManifestCompilationException.java b/core-rust-bridge/src/main/java/com/radixdlt/exceptions/ManifestCompilationException.java similarity index 100% rename from state-manager-bridge/src/main/java/com/radixdlt/exceptions/ManifestCompilationException.java rename to core-rust-bridge/src/main/java/com/radixdlt/exceptions/ManifestCompilationException.java diff --git a/state-manager-bridge/src/main/java/com/radixdlt/exceptions/StateManagerRuntimeError.java b/core-rust-bridge/src/main/java/com/radixdlt/exceptions/StateManagerRuntimeError.java similarity index 100% rename from state-manager-bridge/src/main/java/com/radixdlt/exceptions/StateManagerRuntimeError.java rename to core-rust-bridge/src/main/java/com/radixdlt/exceptions/StateManagerRuntimeError.java diff --git a/state-manager-bridge/src/main/java/com/radixdlt/exceptions/StateManagerRuntimeException.java b/core-rust-bridge/src/main/java/com/radixdlt/exceptions/StateManagerRuntimeException.java similarity index 100% rename from state-manager-bridge/src/main/java/com/radixdlt/exceptions/StateManagerRuntimeException.java rename to core-rust-bridge/src/main/java/com/radixdlt/exceptions/StateManagerRuntimeException.java diff --git a/state-manager-bridge/src/main/java/com/radixdlt/mempool/MempoolDuplicateException.java b/core-rust-bridge/src/main/java/com/radixdlt/mempool/MempoolDuplicateException.java similarity index 100% rename from state-manager-bridge/src/main/java/com/radixdlt/mempool/MempoolDuplicateException.java rename to core-rust-bridge/src/main/java/com/radixdlt/mempool/MempoolDuplicateException.java diff --git a/state-manager-bridge/src/main/java/com/radixdlt/mempool/MempoolError.java b/core-rust-bridge/src/main/java/com/radixdlt/mempool/MempoolError.java similarity index 100% rename from state-manager-bridge/src/main/java/com/radixdlt/mempool/MempoolError.java rename to core-rust-bridge/src/main/java/com/radixdlt/mempool/MempoolError.java diff --git a/state-manager-bridge/src/main/java/com/radixdlt/mempool/MempoolFullException.java b/core-rust-bridge/src/main/java/com/radixdlt/mempool/MempoolFullException.java similarity index 100% rename from state-manager-bridge/src/main/java/com/radixdlt/mempool/MempoolFullException.java rename to core-rust-bridge/src/main/java/com/radixdlt/mempool/MempoolFullException.java diff --git a/state-manager-bridge/src/main/java/com/radixdlt/mempool/MempoolInserter.java b/core-rust-bridge/src/main/java/com/radixdlt/mempool/MempoolInserter.java similarity index 100% rename from state-manager-bridge/src/main/java/com/radixdlt/mempool/MempoolInserter.java rename to core-rust-bridge/src/main/java/com/radixdlt/mempool/MempoolInserter.java diff --git a/state-manager-bridge/src/main/java/com/radixdlt/mempool/MempoolReader.java b/core-rust-bridge/src/main/java/com/radixdlt/mempool/MempoolReader.java similarity index 100% rename from state-manager-bridge/src/main/java/com/radixdlt/mempool/MempoolReader.java rename to core-rust-bridge/src/main/java/com/radixdlt/mempool/MempoolReader.java diff --git a/state-manager-bridge/src/main/java/com/radixdlt/mempool/MempoolRejectedException.java b/core-rust-bridge/src/main/java/com/radixdlt/mempool/MempoolRejectedException.java similarity index 100% rename from state-manager-bridge/src/main/java/com/radixdlt/mempool/MempoolRejectedException.java rename to core-rust-bridge/src/main/java/com/radixdlt/mempool/MempoolRejectedException.java diff --git a/state-manager-bridge/src/main/java/com/radixdlt/mempool/RustMempool.java b/core-rust-bridge/src/main/java/com/radixdlt/mempool/RustMempool.java similarity index 100% rename from state-manager-bridge/src/main/java/com/radixdlt/mempool/RustMempool.java rename to core-rust-bridge/src/main/java/com/radixdlt/mempool/RustMempool.java diff --git a/state-manager-bridge/src/main/java/com/radixdlt/mempool/RustMempoolConfig.java b/core-rust-bridge/src/main/java/com/radixdlt/mempool/RustMempoolConfig.java similarity index 100% rename from state-manager-bridge/src/main/java/com/radixdlt/mempool/RustMempoolConfig.java rename to core-rust-bridge/src/main/java/com/radixdlt/mempool/RustMempoolConfig.java diff --git a/state-manager-bridge/src/main/java/com/radixdlt/rev2/ComponentAddress.java b/core-rust-bridge/src/main/java/com/radixdlt/rev2/ComponentAddress.java similarity index 100% rename from state-manager-bridge/src/main/java/com/radixdlt/rev2/ComponentAddress.java rename to core-rust-bridge/src/main/java/com/radixdlt/rev2/ComponentAddress.java diff --git a/state-manager-bridge/src/main/java/com/radixdlt/rev2/Decimal.java b/core-rust-bridge/src/main/java/com/radixdlt/rev2/Decimal.java similarity index 100% rename from state-manager-bridge/src/main/java/com/radixdlt/rev2/Decimal.java rename to core-rust-bridge/src/main/java/com/radixdlt/rev2/Decimal.java diff --git a/state-manager-bridge/src/main/java/com/radixdlt/rev2/LogLevel.java b/core-rust-bridge/src/main/java/com/radixdlt/rev2/LogLevel.java similarity index 100% rename from state-manager-bridge/src/main/java/com/radixdlt/rev2/LogLevel.java rename to core-rust-bridge/src/main/java/com/radixdlt/rev2/LogLevel.java diff --git a/state-manager-bridge/src/main/java/com/radixdlt/rev2/NetworkDefinition.java b/core-rust-bridge/src/main/java/com/radixdlt/rev2/NetworkDefinition.java similarity index 98% rename from state-manager-bridge/src/main/java/com/radixdlt/rev2/NetworkDefinition.java rename to core-rust-bridge/src/main/java/com/radixdlt/rev2/NetworkDefinition.java index c2a20f410e..06c3b2244a 100644 --- a/state-manager-bridge/src/main/java/com/radixdlt/rev2/NetworkDefinition.java +++ b/core-rust-bridge/src/main/java/com/radixdlt/rev2/NetworkDefinition.java @@ -88,4 +88,5 @@ public static NetworkDefinition from(Network network) { public static NetworkDefinition LOCAL_SIMULATOR = NetworkDefinition.from(Network.LOCALSIMULATOR); public static NetworkDefinition INT_TEST_NET = NetworkDefinition.from(Network.INTEGRATIONTESTNET); + public static NetworkDefinition LOCALNET = NetworkDefinition.from(Network.LOCALNET); } diff --git a/state-manager-bridge/src/main/java/com/radixdlt/rev2/PackageAddress.java b/core-rust-bridge/src/main/java/com/radixdlt/rev2/PackageAddress.java similarity index 100% rename from state-manager-bridge/src/main/java/com/radixdlt/rev2/PackageAddress.java rename to core-rust-bridge/src/main/java/com/radixdlt/rev2/PackageAddress.java diff --git a/state-manager-bridge/src/main/java/com/radixdlt/rev2/ResourceAddress.java b/core-rust-bridge/src/main/java/com/radixdlt/rev2/ResourceAddress.java similarity index 100% rename from state-manager-bridge/src/main/java/com/radixdlt/rev2/ResourceAddress.java rename to core-rust-bridge/src/main/java/com/radixdlt/rev2/ResourceAddress.java diff --git a/state-manager-bridge/src/main/java/com/radixdlt/rev2/TransactionHeader.java b/core-rust-bridge/src/main/java/com/radixdlt/rev2/TransactionHeader.java similarity index 100% rename from state-manager-bridge/src/main/java/com/radixdlt/rev2/TransactionHeader.java rename to core-rust-bridge/src/main/java/com/radixdlt/rev2/TransactionHeader.java diff --git a/state-manager-bridge/src/main/java/com/radixdlt/rev2/TransactionStatus.java b/core-rust-bridge/src/main/java/com/radixdlt/rev2/TransactionStatus.java similarity index 100% rename from state-manager-bridge/src/main/java/com/radixdlt/rev2/TransactionStatus.java rename to core-rust-bridge/src/main/java/com/radixdlt/rev2/TransactionStatus.java diff --git a/state-manager-bridge/src/main/java/com/radixdlt/sbor/NativeCalls.java b/core-rust-bridge/src/main/java/com/radixdlt/sbor/NativeCalls.java similarity index 100% rename from state-manager-bridge/src/main/java/com/radixdlt/sbor/NativeCalls.java rename to core-rust-bridge/src/main/java/com/radixdlt/sbor/NativeCalls.java diff --git a/state-manager-bridge/src/main/java/com/radixdlt/sbor/StateManagerSbor.java b/core-rust-bridge/src/main/java/com/radixdlt/sbor/StateManagerSbor.java similarity index 93% rename from state-manager-bridge/src/main/java/com/radixdlt/sbor/StateManagerSbor.java rename to core-rust-bridge/src/main/java/com/radixdlt/sbor/StateManagerSbor.java index e968f04cf2..1987515365 100644 --- a/state-manager-bridge/src/main/java/com/radixdlt/sbor/StateManagerSbor.java +++ b/core-rust-bridge/src/main/java/com/radixdlt/sbor/StateManagerSbor.java @@ -77,11 +77,6 @@ import com.radixdlt.sbor.codec.CodecMap; import com.radixdlt.sbor.codec.StructCodec; import com.radixdlt.statecomputer.commit.CommitRequest; -import com.radixdlt.statecomputer.preview.FeeSummary; -import com.radixdlt.statecomputer.preview.PreviewError; -import com.radixdlt.statecomputer.preview.PreviewFlags; -import com.radixdlt.statecomputer.preview.PreviewRequest; -import com.radixdlt.statecomputer.preview.PreviewResult; import com.radixdlt.statemanager.CoreApiServerConfig; import com.radixdlt.statemanager.REv2DatabaseConfig; import com.radixdlt.statemanager.StateManagerConfig; @@ -124,17 +119,12 @@ public static void registerCodecsWithCodecMap(CodecMap codecMap) { NetworkDefinition.registerCodec(codecMap); StateManagerConfig.registerCodec(codecMap); RawTransaction.registerCodec(codecMap); - PreviewFlags.registerCodec(codecMap); - PreviewRequest.registerCodec(codecMap); - PreviewResult.registerCodec(codecMap); - PreviewError.registerCodec(codecMap); TransactionStatus.registerCodec(codecMap); Decimal.registerCodec(codecMap); LogLevel.registerCodec(codecMap); ComponentAddress.registerCodec(codecMap); PackageAddress.registerCodec(codecMap); ResourceAddress.registerCodec(codecMap); - FeeSummary.registerCodec(codecMap); TID.registerCodec(codecMap); StateManagerRuntimeError.registerCodec(codecMap); MempoolError.registerCodec(codecMap); diff --git a/state-manager-bridge/src/main/java/com/radixdlt/statecomputer/RustStateComputer.java b/core-rust-bridge/src/main/java/com/radixdlt/statecomputer/RustStateComputer.java similarity index 91% rename from state-manager-bridge/src/main/java/com/radixdlt/statecomputer/RustStateComputer.java rename to core-rust-bridge/src/main/java/com/radixdlt/statecomputer/RustStateComputer.java index 158c3ab367..0420466db6 100644 --- a/state-manager-bridge/src/main/java/com/radixdlt/statecomputer/RustStateComputer.java +++ b/core-rust-bridge/src/main/java/com/radixdlt/statecomputer/RustStateComputer.java @@ -72,9 +72,6 @@ import com.radixdlt.rev2.Decimal; import com.radixdlt.sbor.NativeCalls; import com.radixdlt.statecomputer.commit.CommitRequest; -import com.radixdlt.statecomputer.preview.PreviewError; -import com.radixdlt.statecomputer.preview.PreviewRequest; -import com.radixdlt.statecomputer.preview.PreviewResult; import com.radixdlt.statemanager.StateManager; import com.radixdlt.transaction.REv2TransactionAndProofStore; import com.radixdlt.transactions.RawTransaction; @@ -93,9 +90,6 @@ public RustStateComputer(StateManager stateManager) { verifyFunc = NativeCalls.Func1.with( stateManager, new TypeToken<>() {}, new TypeToken<>() {}, RustStateComputer::verify); - previewFunc = - NativeCalls.Func1.with( - stateManager, new TypeToken<>() {}, new TypeToken<>() {}, RustStateComputer::preview); commitFunc = NativeCalls.Func1.with( stateManager, new TypeToken<>() {}, new TypeToken<>() {}, RustStateComputer::commit); @@ -136,19 +130,10 @@ public Result verify(RawTransaction transaction) { return verifyFunc.call(transaction); } - public Result preview(PreviewRequest previewRequest) { - return previewFunc.call(previewRequest); - } - private final NativeCalls.Func1> verifyFunc; private static native byte[] verify(StateManager stateManager, byte[] payload); - private final NativeCalls.Func1> - previewFunc; - - private static native byte[] preview(StateManager stateManager, byte[] payload); - private final NativeCalls.Func1 commitFunc; private static native byte[] commit(StateManager stateManager, byte[] payload); diff --git a/state-manager-bridge/src/main/java/com/radixdlt/statecomputer/commit/CommitRequest.java b/core-rust-bridge/src/main/java/com/radixdlt/statecomputer/commit/CommitRequest.java similarity index 100% rename from state-manager-bridge/src/main/java/com/radixdlt/statecomputer/commit/CommitRequest.java rename to core-rust-bridge/src/main/java/com/radixdlt/statecomputer/commit/CommitRequest.java diff --git a/state-manager-bridge/src/main/java/com/radixdlt/statemanager/CoreApiServerConfig.java b/core-rust-bridge/src/main/java/com/radixdlt/statemanager/CoreApiServerConfig.java similarity index 100% rename from state-manager-bridge/src/main/java/com/radixdlt/statemanager/CoreApiServerConfig.java rename to core-rust-bridge/src/main/java/com/radixdlt/statemanager/CoreApiServerConfig.java diff --git a/state-manager-bridge/src/main/java/com/radixdlt/statemanager/REv2DatabaseConfig.java b/core-rust-bridge/src/main/java/com/radixdlt/statemanager/REv2DatabaseConfig.java similarity index 100% rename from state-manager-bridge/src/main/java/com/radixdlt/statemanager/REv2DatabaseConfig.java rename to core-rust-bridge/src/main/java/com/radixdlt/statemanager/REv2DatabaseConfig.java diff --git a/state-manager-bridge/src/main/java/com/radixdlt/statemanager/StateManager.java b/core-rust-bridge/src/main/java/com/radixdlt/statemanager/StateManager.java similarity index 100% rename from state-manager-bridge/src/main/java/com/radixdlt/statemanager/StateManager.java rename to core-rust-bridge/src/main/java/com/radixdlt/statemanager/StateManager.java diff --git a/state-manager-bridge/src/main/java/com/radixdlt/statemanager/StateManagerConfig.java b/core-rust-bridge/src/main/java/com/radixdlt/statemanager/StateManagerConfig.java similarity index 100% rename from state-manager-bridge/src/main/java/com/radixdlt/statemanager/StateManagerConfig.java rename to core-rust-bridge/src/main/java/com/radixdlt/statemanager/StateManagerConfig.java diff --git a/state-manager-bridge/src/main/java/com/radixdlt/transaction/ExecutedTransactionReceipt.java b/core-rust-bridge/src/main/java/com/radixdlt/transaction/ExecutedTransactionReceipt.java similarity index 100% rename from state-manager-bridge/src/main/java/com/radixdlt/transaction/ExecutedTransactionReceipt.java rename to core-rust-bridge/src/main/java/com/radixdlt/transaction/ExecutedTransactionReceipt.java diff --git a/state-manager-bridge/src/main/java/com/radixdlt/transaction/REv2TransactionAndProofStore.java b/core-rust-bridge/src/main/java/com/radixdlt/transaction/REv2TransactionAndProofStore.java similarity index 100% rename from state-manager-bridge/src/main/java/com/radixdlt/transaction/REv2TransactionAndProofStore.java rename to core-rust-bridge/src/main/java/com/radixdlt/transaction/REv2TransactionAndProofStore.java diff --git a/state-manager-bridge/src/main/java/com/radixdlt/transaction/TransactionBuilder.java b/core-rust-bridge/src/main/java/com/radixdlt/transaction/TransactionBuilder.java similarity index 100% rename from state-manager-bridge/src/main/java/com/radixdlt/transaction/TransactionBuilder.java rename to core-rust-bridge/src/main/java/com/radixdlt/transaction/TransactionBuilder.java diff --git a/state-manager-bridge/src/test/java/com/radixdlt/transaction/TransactionBuilderTest.java b/core-rust-bridge/src/test/java/com/radixdlt/transaction/TransactionBuilderTest.java similarity index 100% rename from state-manager-bridge/src/test/java/com/radixdlt/transaction/TransactionBuilderTest.java rename to core-rust-bridge/src/test/java/com/radixdlt/transaction/TransactionBuilderTest.java diff --git a/state-manager/Cargo.lock b/core-rust/Cargo.lock similarity index 99% rename from state-manager/Cargo.lock rename to core-rust/Cargo.lock index b795e1f739..d45e3d6491 100644 --- a/state-manager/Cargo.lock +++ b/core-rust/Cargo.lock @@ -276,6 +276,7 @@ dependencies = [ "async-trait", "chrono", "futures", + "hex", "hyper", "jni", "lazy_static", diff --git a/state-manager/Cargo.toml b/core-rust/Cargo.toml similarity index 100% rename from state-manager/Cargo.toml rename to core-rust/Cargo.toml diff --git a/state-manager/build.gradle b/core-rust/build.gradle similarity index 98% rename from state-manager/build.gradle rename to core-rust/build.gradle index 282198e946..a244bd6c0c 100644 --- a/state-manager/build.gradle +++ b/core-rust/build.gradle @@ -113,7 +113,7 @@ task buildRustForDocker(type: Exec) { ignoreExitValue true if (project.hasProperty('ci')){ workingDir rootProject.projectDir - def outputDir="state-manager/target/$target" + def outputDir="core-rust/target/$target" def rustBuilderRepo = "eu.gcr.io/dev-container-repo/rust-builder-base" def rustCacheRepo = "eu.gcr.io/dev-container-repo/rust-cache-packages" def cacheTag = project.properties['cacheBranch'] ?: "latest" @@ -135,7 +135,7 @@ task buildRustForDocker(type: Exec) { docker build -f docker/rust-builder/Dockerfile \\ --target=artifact --build-arg TARGET=$target --build-arg BUILDKIT_INLINE_CACHE=1 \\ --cache-from=$rustBuilderRepo:$cacheTag --cache-from=$rustCacheRepo:$cacheTag \\ - --output type=local,dest=state-manager/target/$target/${project.property("rustBinaryBuildType")}/ . + --output type=local,dest=core-rust/target/$target/${project.property("rustBinaryBuildType")}/ . docker push $rustBuilderRepo:$cacheTag || true docker push $rustCacheRepo:$cacheTag || true [ -f $outputDir/${project.property("rustBinaryBuildType")}/libcorerust.so ] diff --git a/state-manager/core-api-server/Cargo.toml b/core-rust/core-api-server/Cargo.toml similarity index 96% rename from state-manager/core-api-server/Cargo.toml rename to core-rust/core-api-server/Cargo.toml index 9d68ef3821..e9ff7dcc44 100644 --- a/state-manager/core-api-server/Cargo.toml +++ b/core-rust/core-api-server/Cargo.toml @@ -42,3 +42,4 @@ serde_ignored = "0.1.1" url = "2.1" lazy_static = "1.4" regex = "1.3" +hex = { version = "0.4.3", default-features = false } diff --git a/core-rust/core-api-server/core-api-spec.yaml b/core-rust/core-api-server/core-api-spec.yaml new file mode 100644 index 0000000000..8fc80f7d6c --- /dev/null +++ b/core-rust/core-api-server/core-api-spec.yaml @@ -0,0 +1,516 @@ +openapi: 3.1.0 +info: + version: '0.1.0' + title: 'Babylon Core API' + license: + name: The Radix License, Version 1.0 + url: https://www.radixfoundation.org/licenses/LICENSE-v1 +servers: + - url: 'localhost:3333/core' +tags: + - name: Status + x-displayName: Status Endpoints + description: To query information about the Node / Ledger status. + - name: Transaction + x-displayName: Transaction Submission Endpoints + description: To submit transactions to the network. + - name: Mempool + x-displayName: Mempool Endpoints + description: To query mempool status. + - name: Ledger State + x-displayName: Ledger State Endpoints + description: To query the current ledger state. + - name: History Stream + x-displayName: History Stream Endpoints + description: To query the history of the ledger. + - name: Key + x-displayName: Key Endpoints + description: To sign certain transactions with the node's own key. +paths: + "/status/network-configuration": + post: + summary: Get Network Configuration + description: Returns the network configuration of the network the node is connected to. + tags: + - Status + responses: + '200': + description: Network Configuration + content: + application/json: + schema: + "$ref": "#/components/schemas/NetworkConfigurationResponse" + '500': + description: Server error + content: + application/json: + schema: + "$ref": "#/components/schemas/ErrorResponse" + "/transaction/submit": + post: + summary: Submit transaction to the network + description: Returns whether the transaction submission was accepted. + tags: + - Transaction + requestBody: + required: true + content: + application/json: + schema: + "$ref": "#/components/schemas/TransactionSubmitRequest" + responses: + '200': + description: Transaction Submit Response + content: + application/json: + schema: + "$ref": "#/components/schemas/TransactionSubmitResponse" + '400': + description: Client error + content: + application/json: + schema: + "$ref": "#/components/schemas/ErrorResponse" + '500': + description: Server error + content: + application/json: + schema: + "$ref": "#/components/schemas/ErrorResponse" + "/transaction/preview": + post: + summary: Preview a transaction against the latest network state + description: Returns the preview response + tags: + - Transaction + requestBody: + required: true + content: + application/json: + schema: + "$ref": "#/components/schemas/TransactionPreviewRequest" + responses: + '200': + description: Transaction preview response + content: + application/json: + schema: + "$ref": "#/components/schemas/TransactionPreviewResponse" + '400': + description: Client error + content: + application/json: + schema: + "$ref": "#/components/schemas/ErrorResponse" + '500': + description: Server error + content: + application/json: + schema: + "$ref": "#/components/schemas/ErrorResponse" + "/transactions": + post: + summary: Get committed transactions + tags: + - Transaction + requestBody: + required: true + content: + application/json: + schema: + "$ref": "#/components/schemas/CommittedTransactionsRequest" + responses: + '200': + description: Committed transactions response + content: + application/json: + schema: + "$ref": "#/components/schemas/CommittedTransactionsResponse" + '400': + description: Client error + content: + application/json: + schema: + "$ref": "#/components/schemas/ErrorResponse" + '500': + description: Server error + content: + application/json: + schema: + "$ref": "#/components/schemas/ErrorResponse" +components: + schemas: +########################### +# GENERAL / SHARED MODELS # +########################### + TransactionStatus: + type: string + enum: + - succeeded + - failed + - rejected + description: The status of the transaction + TransactionReceipt: + type: object + description: The transaction execution receipt + required: + - status + - fee_summary + properties: + status: + "$ref": "#/components/schemas/TransactionStatus" + fee_summary: + "$ref": "#/components/schemas/FeeSummary" + output: + type: array + items: + type: string + description: The engine return data (only present if status is succeeded) + error_message: + type: string + description: Error message (only present if status is failed or rejected) + NotarizedTransaction: + type: object + required: + - hash + - signed_intent + - notary_signature + properties: + hash: + type: string + description: The transaction hash, hex-encoded. + signed_intent: + "$ref": "#/components/schemas/SignedTransactionIntent" + notary_signature: + type: string + description: The notary signature, hex-encoded. + SignedTransactionIntent: + type: object + required: + - hash + - intent + - intent_signatures + properties: + hash: + type: string + description: Signed transaction intent hash, hex-encoded. + intent: + "$ref": "#/components/schemas/TransactionIntent" + intent_signatures: + type: array + items: + "$ref": "#/components/schemas/IntentSignature" + IntentSignature: + type: object + required: + - public_key + - signature + properties: + public_key: + type: string + description: Signer public key, hex-encoded. + signature: + type: string + description: The signature, hex-encoded. + TransactionIntent: + type: object + required: + - hash + - header + - manifest + properties: + hash: + type: string + description: Transaction intent hash, hex-encoded. + header: + "$ref": "#/components/schemas/TransactionHeader" + manifest: + type: string + description: Transaction manifest, SBOR-encoded and then hex-encoded. + TransactionHeader: + type: object + required: + - version + - network_id + - start_epoch_inclusive + - end_epoch_exclusive + - nonce + - notary_public_key + - notary_as_signatory + - cost_unit_limit + - tip_percentage + properties: + version: + type: integer + network_id: + type: integer + start_epoch_inclusive: + type: string + description: A decimal 64-bit unsigned integer. + end_epoch_exclusive: + type: string + description: A decimal 64-bit unsigned integer. + nonce: + type: string + description: A decimal 64-bit unsigned integer. + notary_public_key: + type: string + description: A hex-encoded public key of a notary. + notary_as_signatory: + type: boolean + description: Specifies whether the notary's signature should be included in transaction signers list + cost_unit_limit: + type: string + description: Maximum number of cost units available for transaction execution. A decimal 32-bit unsigned integer. + tip_percentage: + type: string + description: Specifies the validator tip. A decimal 32-bit unsigned integer, representing the percentage amount (a value of "1" corresponds to 1%). + NetworkIdentifier: + description: The name of the network. + type: object + required: + - network + properties: + network: + type: string + example: + network: mainnet + ErrorResponse: + type: object + required: + - code + - message + properties: + code: + description: A numeric code corresponding to the given error type. + type: integer + message: + description: A human-readable error message. + type: string + trace_id: + description: A GUID to be used when reporting errors, to allow correlation with the Core API's error logs, in the case where the Core API details are hidden. + type: string +######################################### +# GENERAL / SHARED MODELS - Transaction # +######################################### + FeeSummary: + description: Fees paid + type: object + required: + - loan_fully_repaid + - cost_unit_limit + - cost_unit_consumed + - cost_unit_price + - tip_percentage + - xrd_burned + - xrd_tipped + properties: + loan_fully_repaid: + type: boolean + description: Specifies whether the transaction execution loan has been fully repaid. + cost_unit_limit: + type: string + description: Maximum amount of cost units available for the transaction execution. A decimal 32-bit unsigned integer. + cost_unit_consumed: + type: string + description: The amount of cost units consumed by the transaction execution. A decimal 32-bit unsigned integer. + cost_unit_price: + type: string + description: The XRD price of a single cost unit. A fixed-scale 256-bit decimal number. + tip_percentage: + type: string + description: The validator tip. A decimal 32-bit unsigned integer, representing the percentage amount (a value of "1" corresponds to 1%). + xrd_burned: + type: string + description: The total amount of XRD burned. A fixed-scale 256-bit decimal number. + xrd_tipped: + type: string + description: The total amount of XRD tipped to validators. A fixed-scale 256-bit decimal number. + ########################################## +# REQUEST: /status/network-configuration # +########################################## + NetworkConfigurationResponse: + type: object + required: + - version + - network_identifier + - network_hrp_suffix + properties: + version: + description: Different versions regarding the node, network and api. + type: object + required: + - core_version + - api_version + properties: + core_version: + type: string + api_version: + type: string + network_identifier: + "$ref": "#/components/schemas/NetworkIdentifier" + network_hrp_suffix: + type: string + description: The network suffix used for bech32 hrps used for addressing. +################################ +# REQUEST: /transaction/submit # +################################ + TransactionSubmitRequest: + type: object + required: + - network_identifier + - notarized_transaction + properties: + network_identifier: + "$ref": "#/components/schemas/NetworkIdentifier" + notarized_transaction: + description: A notarized transaction encoded in the Radix transaction format, and then hex encoded. + type: string + TransactionSubmitResponse: + type: object + required: + - duplicate + properties: + duplicate: + description: Is true if the transaction is a duplicate of an existing transaction + in the mempool. + type: boolean +################################# +# REQUEST: /transaction/preview # +################################# + TransactionPreviewRequest: + type: object + required: + - network_identifier + - manifest + - cost_unit_limit + - tip_percentage + - nonce + - signer_public_keys + - flags + properties: + network_identifier: + "$ref": "#/components/schemas/NetworkIdentifier" + manifest: + description: A transaction manifest. Sbor encoded, and then hex encoded. + type: string + cost_unit_limit: + type: string + description: Maximum number of cost units available for transaction execution. A decimal 32-bit unsigned integer. + tip_percentage: + type: string + description: The validator tip. A decimal 32-bit unsigned integer, representing the percentage amount (a value of "1" corresponds to 1%). + nonce: + type: string + description: The nonce value to use for execution. A decimal 64-bit unsigned integer. + signer_public_keys: + type: array + items: + type: string + description: A list of public keys to be used as transaction signers, in a compressed format, hex encoded. + flags: + type: object + required: + - unlimited_loan + properties: + unlimited_loan: + type: boolean + TransactionPreviewResponse: + type: object + required: + - transaction_status + - transaction_fee + - logs + - new_package_addresses + - new_component_addresses + - new_resource_addresses + properties: + transaction_status: + "$ref": "#/components/schemas/TransactionStatus" + transaction_fee: + "$ref": "#/components/schemas/FeeSummary" + logs: + type: array + items: + type: object + required: + - level + - message + properties: + level: + type: string + message: + type: string + new_package_addresses: + description: A list of new package addresses, hex-encoded. + type: array + items: + type: string + new_component_addresses: + description: A list of new component addresses, hex-encoded. + type: array + items: + type: string + new_resource_addresses: + description: A list of new resource addresses, hex-encoded. + type: array + items: + type: string + output: + type: array + items: + type: string + error_message: + type: string +########################## +# REQUEST: /transactions # +########################## + CommittedTransactionsRequest: + description: A request to retrieve a sublist of committed transactions from the + ledger. + type: object + required: + - network_identifier + - start_state_version + - limit + properties: + network_identifier: + "$ref": "#/components/schemas/NetworkIdentifier" + start_state_version: + type: string + description: A decimal 64-bit unsigned integer. + limit: + description: The maximum number of transactions that will be returned. + type: integer + CommittedTransactionsResponse: + type: object + required: + - start_state_version + - max_state_version + - transactions + properties: + start_state_version: + type: string + description: The first state version returned. A decimal 64-bit unsigned integer. + max_state_version: + type: string + description: The maximum state version returned. A decimal 64-bit unsigned integer. + transactions: + description: A committed transactions list starting from the `start_state_version_inclusive`. + type: array + items: + "$ref": "#/components/schemas/CommittedTransaction" + CommittedTransaction: + type: object + required: + - state_version + - notarized_transaction + - receipt + properties: + state_version: + type: string + description: The resultant state version after the txn has been committed. A decimal 64-bit unsigned integer. + notarized_transaction: + "$ref": "#/components/schemas/NotarizedTransaction" + receipt: + "$ref": "#/components/schemas/TransactionReceipt" diff --git a/state-manager/core-api-server/scripts/generate-openapi-server.py b/core-rust/core-api-server/scripts/generate-openapi-server.py similarity index 100% rename from state-manager/core-api-server/scripts/generate-openapi-server.py rename to core-rust/core-api-server/scripts/generate-openapi-server.py diff --git a/core-rust/core-api-server/src/core_api/errors.rs b/core-rust/core-api-server/src/core_api/errors.rs new file mode 100644 index 0000000000..2ed289b185 --- /dev/null +++ b/core-rust/core-api-server/src/core_api/errors.rs @@ -0,0 +1,22 @@ +use crate::core_api::generated::models::ErrorResponse; + +pub(crate) enum RequestHandlingError { + ClientError(ErrorResponse), + ServerError(ErrorResponse), +} + +pub(crate) fn client_error(code: isize, message: &str) -> RequestHandlingError { + RequestHandlingError::ClientError(ErrorResponse::new(code, message.to_string())) +} + +pub(crate) fn server_error(code: isize, message: &str) -> RequestHandlingError { + RequestHandlingError::ServerError(ErrorResponse::new(code, message.to_string())) +} + +pub(crate) mod common_server_errors { + use crate::core_api::errors::{server_error, RequestHandlingError}; + + pub(crate) fn state_manager_lock_error() -> RequestHandlingError { + server_error(0, "Internal server error: state manager lock") + } +} diff --git a/state-manager/core-api-server/src/core_api/generated/context.rs b/core-rust/core-api-server/src/core_api/generated/context.rs similarity index 100% rename from state-manager/core-api-server/src/core_api/generated/context.rs rename to core-rust/core-api-server/src/core_api/generated/context.rs diff --git a/state-manager/core-api-server/src/core_api/generated/header.rs b/core-rust/core-api-server/src/core_api/generated/header.rs similarity index 100% rename from state-manager/core-api-server/src/core_api/generated/header.rs rename to core-rust/core-api-server/src/core_api/generated/header.rs diff --git a/state-manager/core-api-server/src/core_api/generated/mod.rs b/core-rust/core-api-server/src/core_api/generated/mod.rs similarity index 78% rename from state-manager/core-api-server/src/core_api/generated/mod.rs rename to core-rust/core-api-server/src/core_api/generated/mod.rs index 2b04ea075c..e9bd0d8963 100644 --- a/state-manager/core-api-server/src/core_api/generated/mod.rs +++ b/core-rust/core-api-server/src/core_api/generated/mod.rs @@ -19,8 +19,8 @@ pub enum StatusNetworkConfigurationPostResponse { NetworkConfiguration (models::NetworkConfigurationResponse) , - /// An error occurred - AnErrorOccurred + /// Server error + ServerError (models::ErrorResponse) } @@ -31,8 +31,12 @@ pub enum TransactionPreviewPostResponse { TransactionPreviewResponse (models::TransactionPreviewResponse) , - /// An error occurred - AnErrorOccurred + /// Client error + ClientError + (models::ErrorResponse) + , + /// Server error + ServerError (models::ErrorResponse) } @@ -43,8 +47,28 @@ pub enum TransactionSubmitPostResponse { TransactionSubmitResponse (models::TransactionSubmitResponse) , - /// An error occurred - AnErrorOccurred + /// Client error + ClientError + (models::ErrorResponse) + , + /// Server error + ServerError + (models::ErrorResponse) +} + +#[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +pub enum TransactionsPostResponse { + /// Committed transactions response + CommittedTransactionsResponse + (models::CommittedTransactionsResponse) + , + /// Client error + ClientError + (models::ErrorResponse) + , + /// Server error + ServerError (models::ErrorResponse) } @@ -72,6 +96,12 @@ pub trait Api { transaction_submit_request: models::TransactionSubmitRequest, context: &C) -> Result; + /// Get committed transactions + async fn transactions_post( + &self, + committed_transactions_request: models::CommittedTransactionsRequest, + context: &C) -> Result; + } /// API where `Context` isn't passed on every API call @@ -99,6 +129,12 @@ pub trait ApiNoContext { transaction_submit_request: models::TransactionSubmitRequest, ) -> Result; + /// Get committed transactions + async fn transactions_post( + &self, + committed_transactions_request: models::CommittedTransactionsRequest, + ) -> Result; + } /// Trait to extend an API to make it easy to bind it to a context. @@ -153,6 +189,16 @@ impl + Send + Sync, C: Clone + Send + Sync> ApiNoContext for Contex self.api().transaction_submit_post(transaction_submit_request, &context).await } + /// Get committed transactions + async fn transactions_post( + &self, + committed_transactions_request: models::CommittedTransactionsRequest, + ) -> Result + { + let context = self.context().clone(); + self.api().transactions_post(committed_transactions_request, &context).await + } + } diff --git a/state-manager/core-api-server/src/core_api/generated/models.rs b/core-rust/core-api-server/src/core_api/generated/models.rs similarity index 55% rename from state-manager/core-api-server/src/core_api/generated/models.rs rename to core-rust/core-api-server/src/core_api/generated/models.rs index ed0c554d66..81dfa83e1d 100644 --- a/state-manager/core-api-server/src/core_api/generated/models.rs +++ b/core-rust/core-api-server/src/core_api/generated/models.rs @@ -6,72 +6,195 @@ use crate::core_api::generated::header; #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] #[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] -pub struct Bech32Hrps { - #[serde(rename = "account_hrp")] - pub account_hrp: String, +pub struct CommittedTransaction { + /// The resultant state version after the txn has been committed. A decimal 64-bit unsigned integer. + #[serde(rename = "state_version")] + pub state_version: String, - #[serde(rename = "validator_hrp")] - pub validator_hrp: String, - - #[serde(rename = "node_hrp")] - pub node_hrp: String, + #[serde(rename = "notarized_transaction")] + pub notarized_transaction: models::NotarizedTransaction, - #[serde(rename = "resource_hrp_suffix")] - pub resource_hrp_suffix: String, + #[serde(rename = "receipt")] + pub receipt: models::TransactionReceipt, } -impl Bech32Hrps { - pub fn new(account_hrp: String, validator_hrp: String, node_hrp: String, resource_hrp_suffix: String, ) -> Bech32Hrps { - Bech32Hrps { - account_hrp: account_hrp, - validator_hrp: validator_hrp, - node_hrp: node_hrp, - resource_hrp_suffix: resource_hrp_suffix, +impl CommittedTransaction { + pub fn new(state_version: String, notarized_transaction: models::NotarizedTransaction, receipt: models::TransactionReceipt, ) -> CommittedTransaction { + CommittedTransaction { + state_version: state_version, + notarized_transaction: notarized_transaction, + receipt: receipt, } } } -/// Converts the Bech32Hrps value to the Query Parameters representation (style=form, explode=false) +/// Converts the CommittedTransaction value to the Query Parameters representation (style=form, explode=false) /// specified in https://swagger.io/docs/specification/serialization/ /// Should be implemented in a serde serializer -impl std::string::ToString for Bech32Hrps { +impl std::string::ToString for CommittedTransaction { fn to_string(&self) -> String { let mut params: Vec = vec![]; - params.push("account_hrp".to_string()); - params.push(self.account_hrp.to_string()); + params.push("state_version".to_string()); + params.push(self.state_version.to_string()); + + // Skipping notarized_transaction in query parameter serialization + + // Skipping receipt in query parameter serialization + + params.join(",").to_string() + } +} + +/// Converts Query Parameters representation (style=form, explode=false) to a CommittedTransaction value +/// as specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde deserializer +impl std::str::FromStr for CommittedTransaction { + type Err = String; + + fn from_str(s: &str) -> std::result::Result { + #[derive(Default)] + // An intermediate representation of the struct to use for parsing. + struct IntermediateRep { + pub state_version: Vec, + pub notarized_transaction: Vec, + pub receipt: Vec, + } + + let mut intermediate_rep = IntermediateRep::default(); + + // Parse into intermediate representation + let mut string_iter = s.split(',').into_iter(); + let mut key_result = string_iter.next(); + + while key_result.is_some() { + let val = match string_iter.next() { + Some(x) => x, + None => return std::result::Result::Err("Missing value while parsing CommittedTransaction".to_string()) + }; + + if let Some(key) = key_result { + match key { + "state_version" => intermediate_rep.state_version.push(::from_str(val).map_err(|x| format!("{}", x))?), + "notarized_transaction" => intermediate_rep.notarized_transaction.push(::from_str(val).map_err(|x| format!("{}", x))?), + "receipt" => intermediate_rep.receipt.push(::from_str(val).map_err(|x| format!("{}", x))?), + _ => return std::result::Result::Err("Unexpected key while parsing CommittedTransaction".to_string()) + } + } + + // Get the next key + key_result = string_iter.next(); + } + + // Use the intermediate representation to return the struct + std::result::Result::Ok(CommittedTransaction { + state_version: intermediate_rep.state_version.into_iter().next().ok_or("state_version missing in CommittedTransaction".to_string())?, + notarized_transaction: intermediate_rep.notarized_transaction.into_iter().next().ok_or("notarized_transaction missing in CommittedTransaction".to_string())?, + receipt: intermediate_rep.receipt.into_iter().next().ok_or("receipt missing in CommittedTransaction".to_string())?, + }) + } +} + +// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue + + +impl std::convert::TryFrom> for hyper::header::HeaderValue { + type Error = String; + + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + let hdr_value = hdr_value.to_string(); + match hyper::header::HeaderValue::from_str(&hdr_value) { + std::result::Result::Ok(value) => std::result::Result::Ok(value), + std::result::Result::Err(e) => std::result::Result::Err( + format!("Invalid header value for CommittedTransaction - value: {} is invalid {}", + hdr_value, e)) + } + } +} + + +impl std::convert::TryFrom for header::IntoHeaderValue { + type Error = String; + + fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { + match hdr_value.to_str() { + std::result::Result::Ok(value) => { + match ::from_str(value) { + std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), + std::result::Result::Err(err) => std::result::Result::Err( + format!("Unable to convert header value '{}' into CommittedTransaction - {}", + value, err)) + } + }, + std::result::Result::Err(e) => std::result::Result::Err( + format!("Unable to convert header: {:?} to string: {}", + hdr_value, e)) + } + } +} + + +/// A request to retrieve a sublist of committed transactions from the ledger. +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] +#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] +pub struct CommittedTransactionsRequest { + #[serde(rename = "network_identifier")] + pub network_identifier: models::NetworkIdentifier, + + /// A decimal 64-bit unsigned integer. + #[serde(rename = "start_state_version")] + pub start_state_version: String, + + /// The maximum number of transactions that will be returned. + #[serde(rename = "limit")] + pub limit: isize, + +} +impl CommittedTransactionsRequest { + pub fn new(network_identifier: models::NetworkIdentifier, start_state_version: String, limit: isize, ) -> CommittedTransactionsRequest { + CommittedTransactionsRequest { + network_identifier: network_identifier, + start_state_version: start_state_version, + limit: limit, + } + } +} - params.push("validator_hrp".to_string()); - params.push(self.validator_hrp.to_string()); +/// Converts the CommittedTransactionsRequest value to the Query Parameters representation (style=form, explode=false) +/// specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde serializer +impl std::string::ToString for CommittedTransactionsRequest { + fn to_string(&self) -> String { + let mut params: Vec = vec![]; + // Skipping network_identifier in query parameter serialization - params.push("node_hrp".to_string()); - params.push(self.node_hrp.to_string()); + params.push("start_state_version".to_string()); + params.push(self.start_state_version.to_string()); - params.push("resource_hrp_suffix".to_string()); - params.push(self.resource_hrp_suffix.to_string()); + params.push("limit".to_string()); + params.push(self.limit.to_string()); params.join(",").to_string() } } -/// Converts Query Parameters representation (style=form, explode=false) to a Bech32Hrps value +/// Converts Query Parameters representation (style=form, explode=false) to a CommittedTransactionsRequest value /// as specified in https://swagger.io/docs/specification/serialization/ /// Should be implemented in a serde deserializer -impl std::str::FromStr for Bech32Hrps { +impl std::str::FromStr for CommittedTransactionsRequest { type Err = String; fn from_str(s: &str) -> std::result::Result { #[derive(Default)] // An intermediate representation of the struct to use for parsing. struct IntermediateRep { - pub account_hrp: Vec, - pub validator_hrp: Vec, - pub node_hrp: Vec, - pub resource_hrp_suffix: Vec, + pub network_identifier: Vec, + pub start_state_version: Vec, + pub limit: Vec, } let mut intermediate_rep = IntermediateRep::default(); @@ -83,16 +206,15 @@ impl std::str::FromStr for Bech32Hrps { while key_result.is_some() { let val = match string_iter.next() { Some(x) => x, - None => return std::result::Result::Err("Missing value while parsing Bech32Hrps".to_string()) + None => return std::result::Result::Err("Missing value while parsing CommittedTransactionsRequest".to_string()) }; if let Some(key) = key_result { match key { - "account_hrp" => intermediate_rep.account_hrp.push(::from_str(val).map_err(|x| format!("{}", x))?), - "validator_hrp" => intermediate_rep.validator_hrp.push(::from_str(val).map_err(|x| format!("{}", x))?), - "node_hrp" => intermediate_rep.node_hrp.push(::from_str(val).map_err(|x| format!("{}", x))?), - "resource_hrp_suffix" => intermediate_rep.resource_hrp_suffix.push(::from_str(val).map_err(|x| format!("{}", x))?), - _ => return std::result::Result::Err("Unexpected key while parsing Bech32Hrps".to_string()) + "network_identifier" => intermediate_rep.network_identifier.push(::from_str(val).map_err(|x| format!("{}", x))?), + "start_state_version" => intermediate_rep.start_state_version.push(::from_str(val).map_err(|x| format!("{}", x))?), + "limit" => intermediate_rep.limit.push(::from_str(val).map_err(|x| format!("{}", x))?), + _ => return std::result::Result::Err("Unexpected key while parsing CommittedTransactionsRequest".to_string()) } } @@ -101,43 +223,42 @@ impl std::str::FromStr for Bech32Hrps { } // Use the intermediate representation to return the struct - std::result::Result::Ok(Bech32Hrps { - account_hrp: intermediate_rep.account_hrp.into_iter().next().ok_or("account_hrp missing in Bech32Hrps".to_string())?, - validator_hrp: intermediate_rep.validator_hrp.into_iter().next().ok_or("validator_hrp missing in Bech32Hrps".to_string())?, - node_hrp: intermediate_rep.node_hrp.into_iter().next().ok_or("node_hrp missing in Bech32Hrps".to_string())?, - resource_hrp_suffix: intermediate_rep.resource_hrp_suffix.into_iter().next().ok_or("resource_hrp_suffix missing in Bech32Hrps".to_string())?, + std::result::Result::Ok(CommittedTransactionsRequest { + network_identifier: intermediate_rep.network_identifier.into_iter().next().ok_or("network_identifier missing in CommittedTransactionsRequest".to_string())?, + start_state_version: intermediate_rep.start_state_version.into_iter().next().ok_or("start_state_version missing in CommittedTransactionsRequest".to_string())?, + limit: intermediate_rep.limit.into_iter().next().ok_or("limit missing in CommittedTransactionsRequest".to_string())?, }) } } -// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue +// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue -impl std::convert::TryFrom> for hyper::header::HeaderValue { +impl std::convert::TryFrom> for hyper::header::HeaderValue { type Error = String; - fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { let hdr_value = hdr_value.to_string(); match hyper::header::HeaderValue::from_str(&hdr_value) { std::result::Result::Ok(value) => std::result::Result::Ok(value), std::result::Result::Err(e) => std::result::Result::Err( - format!("Invalid header value for Bech32Hrps - value: {} is invalid {}", + format!("Invalid header value for CommittedTransactionsRequest - value: {} is invalid {}", hdr_value, e)) } } } -impl std::convert::TryFrom for header::IntoHeaderValue { +impl std::convert::TryFrom for header::IntoHeaderValue { type Error = String; fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { match hdr_value.to_str() { std::result::Result::Ok(value) => { - match ::from_str(value) { + match ::from_str(value) { std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), std::result::Result::Err(err) => std::result::Result::Err( - format!("Unable to convert header value '{}' into Bech32Hrps - {}", + format!("Unable to convert header value '{}' into CommittedTransactionsRequest - {}", value, err)) } }, @@ -151,45 +272,64 @@ impl std::convert::TryFrom for header::IntoHeaderVal #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] #[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] -pub struct CoreErrorDetails { - #[serde(rename = "type")] - pub type_: String, +pub struct CommittedTransactionsResponse { + /// The first state version returned. A decimal 64-bit unsigned integer. + #[serde(rename = "start_state_version")] + pub start_state_version: String, + + /// The maximum state version returned. A decimal 64-bit unsigned integer. + #[serde(rename = "max_state_version")] + pub max_state_version: String, + + /// A committed transactions list starting from the `start_state_version_inclusive`. + #[serde(rename = "transactions")] + pub transactions: Vec, } -impl CoreErrorDetails { - pub fn new(type_: String, ) -> CoreErrorDetails { - CoreErrorDetails { - type_: type_, +impl CommittedTransactionsResponse { + pub fn new(start_state_version: String, max_state_version: String, transactions: Vec, ) -> CommittedTransactionsResponse { + CommittedTransactionsResponse { + start_state_version: start_state_version, + max_state_version: max_state_version, + transactions: transactions, } } } -/// Converts the CoreErrorDetails value to the Query Parameters representation (style=form, explode=false) +/// Converts the CommittedTransactionsResponse value to the Query Parameters representation (style=form, explode=false) /// specified in https://swagger.io/docs/specification/serialization/ /// Should be implemented in a serde serializer -impl std::string::ToString for CoreErrorDetails { +impl std::string::ToString for CommittedTransactionsResponse { fn to_string(&self) -> String { let mut params: Vec = vec![]; - params.push("type".to_string()); - params.push(self.type_.to_string()); + params.push("start_state_version".to_string()); + params.push(self.start_state_version.to_string()); + + + params.push("max_state_version".to_string()); + params.push(self.max_state_version.to_string()); + + // Skipping transactions in query parameter serialization params.join(",").to_string() } } -/// Converts Query Parameters representation (style=form, explode=false) to a CoreErrorDetails value +/// Converts Query Parameters representation (style=form, explode=false) to a CommittedTransactionsResponse value /// as specified in https://swagger.io/docs/specification/serialization/ /// Should be implemented in a serde deserializer -impl std::str::FromStr for CoreErrorDetails { +impl std::str::FromStr for CommittedTransactionsResponse { type Err = String; fn from_str(s: &str) -> std::result::Result { #[derive(Default)] // An intermediate representation of the struct to use for parsing. struct IntermediateRep { - pub type_: Vec, + pub start_state_version: Vec, + pub max_state_version: Vec, + pub transactions: Vec>, } let mut intermediate_rep = IntermediateRep::default(); @@ -201,13 +341,15 @@ impl std::str::FromStr for CoreErrorDetails { while key_result.is_some() { let val = match string_iter.next() { Some(x) => x, - None => return std::result::Result::Err("Missing value while parsing CoreErrorDetails".to_string()) + None => return std::result::Result::Err("Missing value while parsing CommittedTransactionsResponse".to_string()) }; if let Some(key) = key_result { match key { - "type" => intermediate_rep.type_.push(::from_str(val).map_err(|x| format!("{}", x))?), - _ => return std::result::Result::Err("Unexpected key while parsing CoreErrorDetails".to_string()) + "start_state_version" => intermediate_rep.start_state_version.push(::from_str(val).map_err(|x| format!("{}", x))?), + "max_state_version" => intermediate_rep.max_state_version.push(::from_str(val).map_err(|x| format!("{}", x))?), + "transactions" => return std::result::Result::Err("Parsing a container in this style is not supported in CommittedTransactionsResponse".to_string()), + _ => return std::result::Result::Err("Unexpected key while parsing CommittedTransactionsResponse".to_string()) } } @@ -216,40 +358,42 @@ impl std::str::FromStr for CoreErrorDetails { } // Use the intermediate representation to return the struct - std::result::Result::Ok(CoreErrorDetails { - type_: intermediate_rep.type_.into_iter().next().ok_or("type missing in CoreErrorDetails".to_string())?, + std::result::Result::Ok(CommittedTransactionsResponse { + start_state_version: intermediate_rep.start_state_version.into_iter().next().ok_or("start_state_version missing in CommittedTransactionsResponse".to_string())?, + max_state_version: intermediate_rep.max_state_version.into_iter().next().ok_or("max_state_version missing in CommittedTransactionsResponse".to_string())?, + transactions: intermediate_rep.transactions.into_iter().next().ok_or("transactions missing in CommittedTransactionsResponse".to_string())?, }) } } -// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue +// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue -impl std::convert::TryFrom> for hyper::header::HeaderValue { +impl std::convert::TryFrom> for hyper::header::HeaderValue { type Error = String; - fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { let hdr_value = hdr_value.to_string(); match hyper::header::HeaderValue::from_str(&hdr_value) { std::result::Result::Ok(value) => std::result::Result::Ok(value), std::result::Result::Err(e) => std::result::Result::Err( - format!("Invalid header value for CoreErrorDetails - value: {} is invalid {}", + format!("Invalid header value for CommittedTransactionsResponse - value: {} is invalid {}", hdr_value, e)) } } } -impl std::convert::TryFrom for header::IntoHeaderValue { +impl std::convert::TryFrom for header::IntoHeaderValue { type Error = String; fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { match hdr_value.to_str() { std::result::Result::Ok(value) => { - match ::from_str(value) { + match ::from_str(value) { std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), std::result::Result::Err(err) => std::result::Result::Err( - format!("Unable to convert header value '{}' into CoreErrorDetails - {}", + format!("Unable to convert header value '{}' into CommittedTransactionsResponse - {}", value, err)) } }, @@ -264,7 +408,7 @@ impl std::convert::TryFrom for header::IntoHeaderVal #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] #[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] pub struct ErrorResponse { - /// A numeric code corresponding to the given error type, roughly aligned with HTTP Status Code semantics (eg 400/404/500). + /// A numeric code corresponding to the given error type. #[serde(rename = "code")] pub code: isize, @@ -272,10 +416,6 @@ pub struct ErrorResponse { #[serde(rename = "message")] pub message: String, - #[serde(rename = "details")] - #[serde(skip_serializing_if="Option::is_none")] - pub details: Option, - /// A GUID to be used when reporting errors, to allow correlation with the Core API's error logs, in the case where the Core API details are hidden. #[serde(rename = "trace_id")] #[serde(skip_serializing_if="Option::is_none")] @@ -288,7 +428,6 @@ impl ErrorResponse { ErrorResponse { code: code, message: message, - details: None, trace_id: None, } } @@ -308,8 +447,6 @@ impl std::string::ToString for ErrorResponse { params.push("message".to_string()); params.push(self.message.to_string()); - // Skipping details in query parameter serialization - if let Some(ref trace_id) = self.trace_id { params.push("trace_id".to_string()); @@ -332,7 +469,6 @@ impl std::str::FromStr for ErrorResponse { struct IntermediateRep { pub code: Vec, pub message: Vec, - pub details: Vec, pub trace_id: Vec, } @@ -352,7 +488,6 @@ impl std::str::FromStr for ErrorResponse { match key { "code" => intermediate_rep.code.push(::from_str(val).map_err(|x| format!("{}", x))?), "message" => intermediate_rep.message.push(::from_str(val).map_err(|x| format!("{}", x))?), - "details" => intermediate_rep.details.push(::from_str(val).map_err(|x| format!("{}", x))?), "trace_id" => intermediate_rep.trace_id.push(::from_str(val).map_err(|x| format!("{}", x))?), _ => return std::result::Result::Err("Unexpected key while parsing ErrorResponse".to_string()) } @@ -366,7 +501,6 @@ impl std::str::FromStr for ErrorResponse { std::result::Result::Ok(ErrorResponse { code: intermediate_rep.code.into_iter().next().ok_or("code missing in ErrorResponse".to_string())?, message: intermediate_rep.message.into_iter().next().ok_or("message missing in ErrorResponse".to_string())?, - details: intermediate_rep.details.into_iter().next(), trace_id: intermediate_rep.trace_id.into_iter().next(), }) } @@ -411,38 +545,46 @@ impl std::convert::TryFrom for header::IntoHeaderVal } +/// Fees paid #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] #[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] pub struct FeeSummary { + /// Specifies whether the transaction execution loan has been fully repaid. #[serde(rename = "loan_fully_repaid")] pub loan_fully_repaid: bool, + /// Maximum amount of cost units available for the transaction execution. A decimal 32-bit unsigned integer. #[serde(rename = "cost_unit_limit")] pub cost_unit_limit: String, - #[serde(rename = "cost_units_consumed")] - pub cost_units_consumed: String, + /// The amount of cost units consumed by the transaction execution. A decimal 32-bit unsigned integer. + #[serde(rename = "cost_unit_consumed")] + pub cost_unit_consumed: String, + /// The XRD price of a single cost unit. A fixed-scale 256-bit decimal number. #[serde(rename = "cost_unit_price")] pub cost_unit_price: String, + /// The validator tip. A decimal 32-bit unsigned integer, representing the percentage amount (a value of \"1\" corresponds to 1%). #[serde(rename = "tip_percentage")] pub tip_percentage: String, + /// The total amount of XRD burned. A fixed-scale 256-bit decimal number. #[serde(rename = "xrd_burned")] pub xrd_burned: String, + /// The total amount of XRD tipped to validators. A fixed-scale 256-bit decimal number. #[serde(rename = "xrd_tipped")] pub xrd_tipped: String, } impl FeeSummary { - pub fn new(loan_fully_repaid: bool, cost_unit_limit: String, cost_units_consumed: String, cost_unit_price: String, tip_percentage: String, xrd_burned: String, xrd_tipped: String, ) -> FeeSummary { + pub fn new(loan_fully_repaid: bool, cost_unit_limit: String, cost_unit_consumed: String, cost_unit_price: String, tip_percentage: String, xrd_burned: String, xrd_tipped: String, ) -> FeeSummary { FeeSummary { loan_fully_repaid: loan_fully_repaid, cost_unit_limit: cost_unit_limit, - cost_units_consumed: cost_units_consumed, + cost_unit_consumed: cost_unit_consumed, cost_unit_price: cost_unit_price, tip_percentage: tip_percentage, xrd_burned: xrd_burned, @@ -466,8 +608,8 @@ impl std::string::ToString for FeeSummary { params.push(self.cost_unit_limit.to_string()); - params.push("cost_units_consumed".to_string()); - params.push(self.cost_units_consumed.to_string()); + params.push("cost_unit_consumed".to_string()); + params.push(self.cost_unit_consumed.to_string()); params.push("cost_unit_price".to_string()); @@ -501,7 +643,7 @@ impl std::str::FromStr for FeeSummary { struct IntermediateRep { pub loan_fully_repaid: Vec, pub cost_unit_limit: Vec, - pub cost_units_consumed: Vec, + pub cost_unit_consumed: Vec, pub cost_unit_price: Vec, pub tip_percentage: Vec, pub xrd_burned: Vec, @@ -524,7 +666,7 @@ impl std::str::FromStr for FeeSummary { match key { "loan_fully_repaid" => intermediate_rep.loan_fully_repaid.push(::from_str(val).map_err(|x| format!("{}", x))?), "cost_unit_limit" => intermediate_rep.cost_unit_limit.push(::from_str(val).map_err(|x| format!("{}", x))?), - "cost_units_consumed" => intermediate_rep.cost_units_consumed.push(::from_str(val).map_err(|x| format!("{}", x))?), + "cost_unit_consumed" => intermediate_rep.cost_unit_consumed.push(::from_str(val).map_err(|x| format!("{}", x))?), "cost_unit_price" => intermediate_rep.cost_unit_price.push(::from_str(val).map_err(|x| format!("{}", x))?), "tip_percentage" => intermediate_rep.tip_percentage.push(::from_str(val).map_err(|x| format!("{}", x))?), "xrd_burned" => intermediate_rep.xrd_burned.push(::from_str(val).map_err(|x| format!("{}", x))?), @@ -541,7 +683,7 @@ impl std::str::FromStr for FeeSummary { std::result::Result::Ok(FeeSummary { loan_fully_repaid: intermediate_rep.loan_fully_repaid.into_iter().next().ok_or("loan_fully_repaid missing in FeeSummary".to_string())?, cost_unit_limit: intermediate_rep.cost_unit_limit.into_iter().next().ok_or("cost_unit_limit missing in FeeSummary".to_string())?, - cost_units_consumed: intermediate_rep.cost_units_consumed.into_iter().next().ok_or("cost_units_consumed missing in FeeSummary".to_string())?, + cost_unit_consumed: intermediate_rep.cost_unit_consumed.into_iter().next().ok_or("cost_unit_consumed missing in FeeSummary".to_string())?, cost_unit_price: intermediate_rep.cost_unit_price.into_iter().next().ok_or("cost_unit_price missing in FeeSummary".to_string())?, tip_percentage: intermediate_rep.tip_percentage.into_iter().next().ok_or("tip_percentage missing in FeeSummary".to_string())?, xrd_burned: intermediate_rep.xrd_burned.into_iter().next().ok_or("xrd_burned missing in FeeSummary".to_string())?, @@ -591,69 +733,56 @@ impl std::convert::TryFrom for header::IntoHeaderVal #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] #[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] -pub struct InternalServerError { - #[serde(rename = "type")] - pub type_: String, +pub struct IntentSignature { + /// Signer public key, hex-encoded. + #[serde(rename = "public_key")] + pub public_key: String, - #[serde(rename = "exception")] - #[serde(skip_serializing_if="Option::is_none")] - pub exception: Option, - - #[serde(rename = "cause")] - #[serde(skip_serializing_if="Option::is_none")] - pub cause: Option, + /// The signature, hex-encoded. + #[serde(rename = "signature")] + pub signature: String, } -impl InternalServerError { - pub fn new(type_: String, ) -> InternalServerError { - InternalServerError { - type_: type_, - exception: None, - cause: None, +impl IntentSignature { + pub fn new(public_key: String, signature: String, ) -> IntentSignature { + IntentSignature { + public_key: public_key, + signature: signature, } } } -/// Converts the InternalServerError value to the Query Parameters representation (style=form, explode=false) +/// Converts the IntentSignature value to the Query Parameters representation (style=form, explode=false) /// specified in https://swagger.io/docs/specification/serialization/ /// Should be implemented in a serde serializer -impl std::string::ToString for InternalServerError { +impl std::string::ToString for IntentSignature { fn to_string(&self) -> String { let mut params: Vec = vec![]; - params.push("type".to_string()); - params.push(self.type_.to_string()); - - - if let Some(ref exception) = self.exception { - params.push("exception".to_string()); - params.push(exception.to_string()); - } + params.push("public_key".to_string()); + params.push(self.public_key.to_string()); - if let Some(ref cause) = self.cause { - params.push("cause".to_string()); - params.push(cause.to_string()); - } + params.push("signature".to_string()); + params.push(self.signature.to_string()); params.join(",").to_string() } } -/// Converts Query Parameters representation (style=form, explode=false) to a InternalServerError value +/// Converts Query Parameters representation (style=form, explode=false) to a IntentSignature value /// as specified in https://swagger.io/docs/specification/serialization/ /// Should be implemented in a serde deserializer -impl std::str::FromStr for InternalServerError { +impl std::str::FromStr for IntentSignature { type Err = String; fn from_str(s: &str) -> std::result::Result { #[derive(Default)] // An intermediate representation of the struct to use for parsing. struct IntermediateRep { - pub type_: Vec, - pub exception: Vec, - pub cause: Vec, + pub public_key: Vec, + pub signature: Vec, } let mut intermediate_rep = IntermediateRep::default(); @@ -665,15 +794,14 @@ impl std::str::FromStr for InternalServerError { while key_result.is_some() { let val = match string_iter.next() { Some(x) => x, - None => return std::result::Result::Err("Missing value while parsing InternalServerError".to_string()) + None => return std::result::Result::Err("Missing value while parsing IntentSignature".to_string()) }; if let Some(key) = key_result { match key { - "type" => intermediate_rep.type_.push(::from_str(val).map_err(|x| format!("{}", x))?), - "exception" => intermediate_rep.exception.push(::from_str(val).map_err(|x| format!("{}", x))?), - "cause" => intermediate_rep.cause.push(::from_str(val).map_err(|x| format!("{}", x))?), - _ => return std::result::Result::Err("Unexpected key while parsing InternalServerError".to_string()) + "public_key" => intermediate_rep.public_key.push(::from_str(val).map_err(|x| format!("{}", x))?), + "signature" => intermediate_rep.signature.push(::from_str(val).map_err(|x| format!("{}", x))?), + _ => return std::result::Result::Err("Unexpected key while parsing IntentSignature".to_string()) } } @@ -682,42 +810,41 @@ impl std::str::FromStr for InternalServerError { } // Use the intermediate representation to return the struct - std::result::Result::Ok(InternalServerError { - type_: intermediate_rep.type_.into_iter().next().ok_or("type missing in InternalServerError".to_string())?, - exception: intermediate_rep.exception.into_iter().next(), - cause: intermediate_rep.cause.into_iter().next(), + std::result::Result::Ok(IntentSignature { + public_key: intermediate_rep.public_key.into_iter().next().ok_or("public_key missing in IntentSignature".to_string())?, + signature: intermediate_rep.signature.into_iter().next().ok_or("signature missing in IntentSignature".to_string())?, }) } } -// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue +// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue -impl std::convert::TryFrom> for hyper::header::HeaderValue { +impl std::convert::TryFrom> for hyper::header::HeaderValue { type Error = String; - fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { let hdr_value = hdr_value.to_string(); match hyper::header::HeaderValue::from_str(&hdr_value) { std::result::Result::Ok(value) => std::result::Result::Ok(value), std::result::Result::Err(e) => std::result::Result::Err( - format!("Invalid header value for InternalServerError - value: {} is invalid {}", + format!("Invalid header value for IntentSignature - value: {} is invalid {}", hdr_value, e)) } } } -impl std::convert::TryFrom for header::IntoHeaderValue { +impl std::convert::TryFrom for header::IntoHeaderValue { type Error = String; fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { match hdr_value.to_str() { std::result::Result::Ok(value) => { - match ::from_str(value) { + match ::from_str(value) { std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), std::result::Result::Err(err) => std::result::Result::Err( - format!("Unable to convert header value '{}' into InternalServerError - {}", + format!("Unable to convert header value '{}' into IntentSignature - {}", value, err)) } }, @@ -731,60 +858,60 @@ impl std::convert::TryFrom for header::IntoHeaderVal #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] #[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] -pub struct InternalServerErrorAllOf { - #[serde(rename = "exception")] - #[serde(skip_serializing_if="Option::is_none")] - pub exception: Option, +pub struct NetworkConfigurationResponse { + #[serde(rename = "version")] + pub version: models::NetworkConfigurationResponseVersion, - #[serde(rename = "cause")] - #[serde(skip_serializing_if="Option::is_none")] - pub cause: Option, + #[serde(rename = "network_identifier")] + pub network_identifier: models::NetworkIdentifier, + + /// The network suffix used for bech32 hrps used for addressing. + #[serde(rename = "network_hrp_suffix")] + pub network_hrp_suffix: String, } -impl InternalServerErrorAllOf { - pub fn new() -> InternalServerErrorAllOf { - InternalServerErrorAllOf { - exception: None, - cause: None, +impl NetworkConfigurationResponse { + pub fn new(version: models::NetworkConfigurationResponseVersion, network_identifier: models::NetworkIdentifier, network_hrp_suffix: String, ) -> NetworkConfigurationResponse { + NetworkConfigurationResponse { + version: version, + network_identifier: network_identifier, + network_hrp_suffix: network_hrp_suffix, } } } -/// Converts the InternalServerErrorAllOf value to the Query Parameters representation (style=form, explode=false) +/// Converts the NetworkConfigurationResponse value to the Query Parameters representation (style=form, explode=false) /// specified in https://swagger.io/docs/specification/serialization/ /// Should be implemented in a serde serializer -impl std::string::ToString for InternalServerErrorAllOf { +impl std::string::ToString for NetworkConfigurationResponse { fn to_string(&self) -> String { let mut params: Vec = vec![]; + // Skipping version in query parameter serialization - if let Some(ref exception) = self.exception { - params.push("exception".to_string()); - params.push(exception.to_string()); - } + // Skipping network_identifier in query parameter serialization - if let Some(ref cause) = self.cause { - params.push("cause".to_string()); - params.push(cause.to_string()); - } + params.push("network_hrp_suffix".to_string()); + params.push(self.network_hrp_suffix.to_string()); params.join(",").to_string() } } -/// Converts Query Parameters representation (style=form, explode=false) to a InternalServerErrorAllOf value +/// Converts Query Parameters representation (style=form, explode=false) to a NetworkConfigurationResponse value /// as specified in https://swagger.io/docs/specification/serialization/ /// Should be implemented in a serde deserializer -impl std::str::FromStr for InternalServerErrorAllOf { +impl std::str::FromStr for NetworkConfigurationResponse { type Err = String; fn from_str(s: &str) -> std::result::Result { #[derive(Default)] // An intermediate representation of the struct to use for parsing. struct IntermediateRep { - pub exception: Vec, - pub cause: Vec, + pub version: Vec, + pub network_identifier: Vec, + pub network_hrp_suffix: Vec, } let mut intermediate_rep = IntermediateRep::default(); @@ -796,14 +923,15 @@ impl std::str::FromStr for InternalServerErrorAllOf { while key_result.is_some() { let val = match string_iter.next() { Some(x) => x, - None => return std::result::Result::Err("Missing value while parsing InternalServerErrorAllOf".to_string()) + None => return std::result::Result::Err("Missing value while parsing NetworkConfigurationResponse".to_string()) }; if let Some(key) = key_result { match key { - "exception" => intermediate_rep.exception.push(::from_str(val).map_err(|x| format!("{}", x))?), - "cause" => intermediate_rep.cause.push(::from_str(val).map_err(|x| format!("{}", x))?), - _ => return std::result::Result::Err("Unexpected key while parsing InternalServerErrorAllOf".to_string()) + "version" => intermediate_rep.version.push(::from_str(val).map_err(|x| format!("{}", x))?), + "network_identifier" => intermediate_rep.network_identifier.push(::from_str(val).map_err(|x| format!("{}", x))?), + "network_hrp_suffix" => intermediate_rep.network_hrp_suffix.push(::from_str(val).map_err(|x| format!("{}", x))?), + _ => return std::result::Result::Err("Unexpected key while parsing NetworkConfigurationResponse".to_string()) } } @@ -812,41 +940,42 @@ impl std::str::FromStr for InternalServerErrorAllOf { } // Use the intermediate representation to return the struct - std::result::Result::Ok(InternalServerErrorAllOf { - exception: intermediate_rep.exception.into_iter().next(), - cause: intermediate_rep.cause.into_iter().next(), + std::result::Result::Ok(NetworkConfigurationResponse { + version: intermediate_rep.version.into_iter().next().ok_or("version missing in NetworkConfigurationResponse".to_string())?, + network_identifier: intermediate_rep.network_identifier.into_iter().next().ok_or("network_identifier missing in NetworkConfigurationResponse".to_string())?, + network_hrp_suffix: intermediate_rep.network_hrp_suffix.into_iter().next().ok_or("network_hrp_suffix missing in NetworkConfigurationResponse".to_string())?, }) } } -// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue +// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue -impl std::convert::TryFrom> for hyper::header::HeaderValue { +impl std::convert::TryFrom> for hyper::header::HeaderValue { type Error = String; - fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { let hdr_value = hdr_value.to_string(); match hyper::header::HeaderValue::from_str(&hdr_value) { std::result::Result::Ok(value) => std::result::Result::Ok(value), std::result::Result::Err(e) => std::result::Result::Err( - format!("Invalid header value for InternalServerErrorAllOf - value: {} is invalid {}", + format!("Invalid header value for NetworkConfigurationResponse - value: {} is invalid {}", hdr_value, e)) } } } -impl std::convert::TryFrom for header::IntoHeaderValue { +impl std::convert::TryFrom for header::IntoHeaderValue { type Error = String; fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { match hdr_value.to_str() { std::result::Result::Ok(value) => { - match ::from_str(value) { + match ::from_str(value) { std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), std::result::Result::Err(err) => std::result::Result::Err( - format!("Unable to convert header value '{}' into InternalServerErrorAllOf - {}", + format!("Unable to convert header value '{}' into NetworkConfigurationResponse - {}", value, err)) } }, @@ -858,56 +987,57 @@ impl std::convert::TryFrom for header::IntoHeaderVal } +/// Different versions regarding the node, network and api. #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] #[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] -pub struct InvalidHexError { - #[serde(rename = "type")] - pub type_: String, +pub struct NetworkConfigurationResponseVersion { + #[serde(rename = "core_version")] + pub core_version: String, - #[serde(rename = "invalid_hex")] - pub invalid_hex: String, + #[serde(rename = "api_version")] + pub api_version: String, } -impl InvalidHexError { - pub fn new(type_: String, invalid_hex: String, ) -> InvalidHexError { - InvalidHexError { - type_: type_, - invalid_hex: invalid_hex, +impl NetworkConfigurationResponseVersion { + pub fn new(core_version: String, api_version: String, ) -> NetworkConfigurationResponseVersion { + NetworkConfigurationResponseVersion { + core_version: core_version, + api_version: api_version, } } } -/// Converts the InvalidHexError value to the Query Parameters representation (style=form, explode=false) +/// Converts the NetworkConfigurationResponseVersion value to the Query Parameters representation (style=form, explode=false) /// specified in https://swagger.io/docs/specification/serialization/ /// Should be implemented in a serde serializer -impl std::string::ToString for InvalidHexError { +impl std::string::ToString for NetworkConfigurationResponseVersion { fn to_string(&self) -> String { let mut params: Vec = vec![]; - params.push("type".to_string()); - params.push(self.type_.to_string()); + params.push("core_version".to_string()); + params.push(self.core_version.to_string()); - params.push("invalid_hex".to_string()); - params.push(self.invalid_hex.to_string()); + params.push("api_version".to_string()); + params.push(self.api_version.to_string()); params.join(",").to_string() } } -/// Converts Query Parameters representation (style=form, explode=false) to a InvalidHexError value +/// Converts Query Parameters representation (style=form, explode=false) to a NetworkConfigurationResponseVersion value /// as specified in https://swagger.io/docs/specification/serialization/ /// Should be implemented in a serde deserializer -impl std::str::FromStr for InvalidHexError { +impl std::str::FromStr for NetworkConfigurationResponseVersion { type Err = String; fn from_str(s: &str) -> std::result::Result { #[derive(Default)] // An intermediate representation of the struct to use for parsing. struct IntermediateRep { - pub type_: Vec, - pub invalid_hex: Vec, + pub core_version: Vec, + pub api_version: Vec, } let mut intermediate_rep = IntermediateRep::default(); @@ -919,14 +1049,14 @@ impl std::str::FromStr for InvalidHexError { while key_result.is_some() { let val = match string_iter.next() { Some(x) => x, - None => return std::result::Result::Err("Missing value while parsing InvalidHexError".to_string()) + None => return std::result::Result::Err("Missing value while parsing NetworkConfigurationResponseVersion".to_string()) }; if let Some(key) = key_result { match key { - "type" => intermediate_rep.type_.push(::from_str(val).map_err(|x| format!("{}", x))?), - "invalid_hex" => intermediate_rep.invalid_hex.push(::from_str(val).map_err(|x| format!("{}", x))?), - _ => return std::result::Result::Err("Unexpected key while parsing InvalidHexError".to_string()) + "core_version" => intermediate_rep.core_version.push(::from_str(val).map_err(|x| format!("{}", x))?), + "api_version" => intermediate_rep.api_version.push(::from_str(val).map_err(|x| format!("{}", x))?), + _ => return std::result::Result::Err("Unexpected key while parsing NetworkConfigurationResponseVersion".to_string()) } } @@ -935,41 +1065,41 @@ impl std::str::FromStr for InvalidHexError { } // Use the intermediate representation to return the struct - std::result::Result::Ok(InvalidHexError { - type_: intermediate_rep.type_.into_iter().next().ok_or("type missing in InvalidHexError".to_string())?, - invalid_hex: intermediate_rep.invalid_hex.into_iter().next().ok_or("invalid_hex missing in InvalidHexError".to_string())?, + std::result::Result::Ok(NetworkConfigurationResponseVersion { + core_version: intermediate_rep.core_version.into_iter().next().ok_or("core_version missing in NetworkConfigurationResponseVersion".to_string())?, + api_version: intermediate_rep.api_version.into_iter().next().ok_or("api_version missing in NetworkConfigurationResponseVersion".to_string())?, }) } } -// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue +// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue -impl std::convert::TryFrom> for hyper::header::HeaderValue { +impl std::convert::TryFrom> for hyper::header::HeaderValue { type Error = String; - fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { let hdr_value = hdr_value.to_string(); match hyper::header::HeaderValue::from_str(&hdr_value) { std::result::Result::Ok(value) => std::result::Result::Ok(value), std::result::Result::Err(e) => std::result::Result::Err( - format!("Invalid header value for InvalidHexError - value: {} is invalid {}", + format!("Invalid header value for NetworkConfigurationResponseVersion - value: {} is invalid {}", hdr_value, e)) } } } -impl std::convert::TryFrom for header::IntoHeaderValue { +impl std::convert::TryFrom for header::IntoHeaderValue { type Error = String; fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { match hdr_value.to_str() { std::result::Result::Ok(value) => { - match ::from_str(value) { + match ::from_str(value) { std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), std::result::Result::Err(err) => std::result::Result::Err( - format!("Unable to convert header value '{}' into InvalidHexError - {}", + format!("Unable to convert header value '{}' into NetworkConfigurationResponseVersion - {}", value, err)) } }, @@ -981,47 +1111,48 @@ impl std::convert::TryFrom for header::IntoHeaderVal } +/// The name of the network. #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] #[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] -pub struct InvalidHexErrorAllOf { - #[serde(rename = "invalid_hex")] - pub invalid_hex: String, +pub struct NetworkIdentifier { + #[serde(rename = "network")] + pub network: String, } -impl InvalidHexErrorAllOf { - pub fn new(invalid_hex: String, ) -> InvalidHexErrorAllOf { - InvalidHexErrorAllOf { - invalid_hex: invalid_hex, +impl NetworkIdentifier { + pub fn new(network: String, ) -> NetworkIdentifier { + NetworkIdentifier { + network: network, } } } -/// Converts the InvalidHexErrorAllOf value to the Query Parameters representation (style=form, explode=false) +/// Converts the NetworkIdentifier value to the Query Parameters representation (style=form, explode=false) /// specified in https://swagger.io/docs/specification/serialization/ /// Should be implemented in a serde serializer -impl std::string::ToString for InvalidHexErrorAllOf { +impl std::string::ToString for NetworkIdentifier { fn to_string(&self) -> String { let mut params: Vec = vec![]; - params.push("invalid_hex".to_string()); - params.push(self.invalid_hex.to_string()); + params.push("network".to_string()); + params.push(self.network.to_string()); params.join(",").to_string() } } -/// Converts Query Parameters representation (style=form, explode=false) to a InvalidHexErrorAllOf value +/// Converts Query Parameters representation (style=form, explode=false) to a NetworkIdentifier value /// as specified in https://swagger.io/docs/specification/serialization/ /// Should be implemented in a serde deserializer -impl std::str::FromStr for InvalidHexErrorAllOf { +impl std::str::FromStr for NetworkIdentifier { type Err = String; fn from_str(s: &str) -> std::result::Result { #[derive(Default)] // An intermediate representation of the struct to use for parsing. struct IntermediateRep { - pub invalid_hex: Vec, + pub network: Vec, } let mut intermediate_rep = IntermediateRep::default(); @@ -1033,13 +1164,13 @@ impl std::str::FromStr for InvalidHexErrorAllOf { while key_result.is_some() { let val = match string_iter.next() { Some(x) => x, - None => return std::result::Result::Err("Missing value while parsing InvalidHexErrorAllOf".to_string()) + None => return std::result::Result::Err("Missing value while parsing NetworkIdentifier".to_string()) }; if let Some(key) = key_result { match key { - "invalid_hex" => intermediate_rep.invalid_hex.push(::from_str(val).map_err(|x| format!("{}", x))?), - _ => return std::result::Result::Err("Unexpected key while parsing InvalidHexErrorAllOf".to_string()) + "network" => intermediate_rep.network.push(::from_str(val).map_err(|x| format!("{}", x))?), + _ => return std::result::Result::Err("Unexpected key while parsing NetworkIdentifier".to_string()) } } @@ -1048,40 +1179,40 @@ impl std::str::FromStr for InvalidHexErrorAllOf { } // Use the intermediate representation to return the struct - std::result::Result::Ok(InvalidHexErrorAllOf { - invalid_hex: intermediate_rep.invalid_hex.into_iter().next().ok_or("invalid_hex missing in InvalidHexErrorAllOf".to_string())?, + std::result::Result::Ok(NetworkIdentifier { + network: intermediate_rep.network.into_iter().next().ok_or("network missing in NetworkIdentifier".to_string())?, }) } } -// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue +// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue -impl std::convert::TryFrom> for hyper::header::HeaderValue { +impl std::convert::TryFrom> for hyper::header::HeaderValue { type Error = String; - fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { let hdr_value = hdr_value.to_string(); match hyper::header::HeaderValue::from_str(&hdr_value) { std::result::Result::Ok(value) => std::result::Result::Ok(value), std::result::Result::Err(e) => std::result::Result::Err( - format!("Invalid header value for InvalidHexErrorAllOf - value: {} is invalid {}", + format!("Invalid header value for NetworkIdentifier - value: {} is invalid {}", hdr_value, e)) } } } -impl std::convert::TryFrom for header::IntoHeaderValue { +impl std::convert::TryFrom for header::IntoHeaderValue { type Error = String; fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { match hdr_value.to_str() { std::result::Result::Ok(value) => { - match ::from_str(value) { + match ::from_str(value) { std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), std::result::Result::Err(err) => std::result::Result::Err( - format!("Unable to convert header value '{}' into InvalidHexErrorAllOf - {}", + format!("Unable to convert header value '{}' into NetworkIdentifier - {}", value, err)) } }, @@ -1095,57 +1226,63 @@ impl std::convert::TryFrom for header::IntoHeaderVal #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] #[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] -pub struct InvalidJsonError { - #[serde(rename = "type")] - pub type_: String, +pub struct NotarizedTransaction { + /// The transaction hash, hex-encoded. + #[serde(rename = "hash")] + pub hash: String, - #[serde(rename = "cause")] - #[serde(skip_serializing_if="Option::is_none")] - pub cause: Option, + #[serde(rename = "signed_intent")] + pub signed_intent: models::SignedTransactionIntent, + + /// The notary signature, hex-encoded. + #[serde(rename = "notary_signature")] + pub notary_signature: String, } -impl InvalidJsonError { - pub fn new(type_: String, ) -> InvalidJsonError { - InvalidJsonError { - type_: type_, - cause: None, +impl NotarizedTransaction { + pub fn new(hash: String, signed_intent: models::SignedTransactionIntent, notary_signature: String, ) -> NotarizedTransaction { + NotarizedTransaction { + hash: hash, + signed_intent: signed_intent, + notary_signature: notary_signature, } } } -/// Converts the InvalidJsonError value to the Query Parameters representation (style=form, explode=false) +/// Converts the NotarizedTransaction value to the Query Parameters representation (style=form, explode=false) /// specified in https://swagger.io/docs/specification/serialization/ /// Should be implemented in a serde serializer -impl std::string::ToString for InvalidJsonError { +impl std::string::ToString for NotarizedTransaction { fn to_string(&self) -> String { let mut params: Vec = vec![]; - params.push("type".to_string()); - params.push(self.type_.to_string()); + params.push("hash".to_string()); + params.push(self.hash.to_string()); + // Skipping signed_intent in query parameter serialization - if let Some(ref cause) = self.cause { - params.push("cause".to_string()); - params.push(cause.to_string()); - } + + params.push("notary_signature".to_string()); + params.push(self.notary_signature.to_string()); params.join(",").to_string() } } -/// Converts Query Parameters representation (style=form, explode=false) to a InvalidJsonError value +/// Converts Query Parameters representation (style=form, explode=false) to a NotarizedTransaction value /// as specified in https://swagger.io/docs/specification/serialization/ /// Should be implemented in a serde deserializer -impl std::str::FromStr for InvalidJsonError { +impl std::str::FromStr for NotarizedTransaction { type Err = String; fn from_str(s: &str) -> std::result::Result { #[derive(Default)] // An intermediate representation of the struct to use for parsing. struct IntermediateRep { - pub type_: Vec, - pub cause: Vec, + pub hash: Vec, + pub signed_intent: Vec, + pub notary_signature: Vec, } let mut intermediate_rep = IntermediateRep::default(); @@ -1157,14 +1294,15 @@ impl std::str::FromStr for InvalidJsonError { while key_result.is_some() { let val = match string_iter.next() { Some(x) => x, - None => return std::result::Result::Err("Missing value while parsing InvalidJsonError".to_string()) + None => return std::result::Result::Err("Missing value while parsing NotarizedTransaction".to_string()) }; if let Some(key) = key_result { match key { - "type" => intermediate_rep.type_.push(::from_str(val).map_err(|x| format!("{}", x))?), - "cause" => intermediate_rep.cause.push(::from_str(val).map_err(|x| format!("{}", x))?), - _ => return std::result::Result::Err("Unexpected key while parsing InvalidJsonError".to_string()) + "hash" => intermediate_rep.hash.push(::from_str(val).map_err(|x| format!("{}", x))?), + "signed_intent" => intermediate_rep.signed_intent.push(::from_str(val).map_err(|x| format!("{}", x))?), + "notary_signature" => intermediate_rep.notary_signature.push(::from_str(val).map_err(|x| format!("{}", x))?), + _ => return std::result::Result::Err("Unexpected key while parsing NotarizedTransaction".to_string()) } } @@ -1173,41 +1311,42 @@ impl std::str::FromStr for InvalidJsonError { } // Use the intermediate representation to return the struct - std::result::Result::Ok(InvalidJsonError { - type_: intermediate_rep.type_.into_iter().next().ok_or("type missing in InvalidJsonError".to_string())?, - cause: intermediate_rep.cause.into_iter().next(), + std::result::Result::Ok(NotarizedTransaction { + hash: intermediate_rep.hash.into_iter().next().ok_or("hash missing in NotarizedTransaction".to_string())?, + signed_intent: intermediate_rep.signed_intent.into_iter().next().ok_or("signed_intent missing in NotarizedTransaction".to_string())?, + notary_signature: intermediate_rep.notary_signature.into_iter().next().ok_or("notary_signature missing in NotarizedTransaction".to_string())?, }) } } -// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue +// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue -impl std::convert::TryFrom> for hyper::header::HeaderValue { +impl std::convert::TryFrom> for hyper::header::HeaderValue { type Error = String; - fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { let hdr_value = hdr_value.to_string(); match hyper::header::HeaderValue::from_str(&hdr_value) { std::result::Result::Ok(value) => std::result::Result::Ok(value), std::result::Result::Err(e) => std::result::Result::Err( - format!("Invalid header value for InvalidJsonError - value: {} is invalid {}", + format!("Invalid header value for NotarizedTransaction - value: {} is invalid {}", hdr_value, e)) } } } -impl std::convert::TryFrom for header::IntoHeaderValue { +impl std::convert::TryFrom for header::IntoHeaderValue { type Error = String; fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { match hdr_value.to_str() { std::result::Result::Ok(value) => { - match ::from_str(value) { + match ::from_str(value) { std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), std::result::Result::Err(err) => std::result::Result::Err( - format!("Unable to convert header value '{}' into InvalidJsonError - {}", + format!("Unable to convert header value '{}' into NotarizedTransaction - {}", value, err)) } }, @@ -1221,48 +1360,60 @@ impl std::convert::TryFrom for header::IntoHeaderVal #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] #[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] -pub struct InvalidJsonErrorAllOf { - #[serde(rename = "cause")] - #[serde(skip_serializing_if="Option::is_none")] - pub cause: Option, +pub struct SignedTransactionIntent { + /// Signed transaction intent hash, hex-encoded. + #[serde(rename = "hash")] + pub hash: String, + + #[serde(rename = "intent")] + pub intent: models::TransactionIntent, + + #[serde(rename = "intent_signatures")] + pub intent_signatures: Vec, } -impl InvalidJsonErrorAllOf { - pub fn new() -> InvalidJsonErrorAllOf { - InvalidJsonErrorAllOf { - cause: None, +impl SignedTransactionIntent { + pub fn new(hash: String, intent: models::TransactionIntent, intent_signatures: Vec, ) -> SignedTransactionIntent { + SignedTransactionIntent { + hash: hash, + intent: intent, + intent_signatures: intent_signatures, } } } -/// Converts the InvalidJsonErrorAllOf value to the Query Parameters representation (style=form, explode=false) +/// Converts the SignedTransactionIntent value to the Query Parameters representation (style=form, explode=false) /// specified in https://swagger.io/docs/specification/serialization/ /// Should be implemented in a serde serializer -impl std::string::ToString for InvalidJsonErrorAllOf { +impl std::string::ToString for SignedTransactionIntent { fn to_string(&self) -> String { let mut params: Vec = vec![]; - if let Some(ref cause) = self.cause { - params.push("cause".to_string()); - params.push(cause.to_string()); - } + params.push("hash".to_string()); + params.push(self.hash.to_string()); + + // Skipping intent in query parameter serialization + + // Skipping intent_signatures in query parameter serialization params.join(",").to_string() } } -/// Converts Query Parameters representation (style=form, explode=false) to a InvalidJsonErrorAllOf value +/// Converts Query Parameters representation (style=form, explode=false) to a SignedTransactionIntent value /// as specified in https://swagger.io/docs/specification/serialization/ /// Should be implemented in a serde deserializer -impl std::str::FromStr for InvalidJsonErrorAllOf { +impl std::str::FromStr for SignedTransactionIntent { type Err = String; fn from_str(s: &str) -> std::result::Result { #[derive(Default)] // An intermediate representation of the struct to use for parsing. struct IntermediateRep { - pub cause: Vec, + pub hash: Vec, + pub intent: Vec, + pub intent_signatures: Vec>, } let mut intermediate_rep = IntermediateRep::default(); @@ -1274,13 +1425,15 @@ impl std::str::FromStr for InvalidJsonErrorAllOf { while key_result.is_some() { let val = match string_iter.next() { Some(x) => x, - None => return std::result::Result::Err("Missing value while parsing InvalidJsonErrorAllOf".to_string()) + None => return std::result::Result::Err("Missing value while parsing SignedTransactionIntent".to_string()) }; if let Some(key) = key_result { match key { - "cause" => intermediate_rep.cause.push(::from_str(val).map_err(|x| format!("{}", x))?), - _ => return std::result::Result::Err("Unexpected key while parsing InvalidJsonErrorAllOf".to_string()) + "hash" => intermediate_rep.hash.push(::from_str(val).map_err(|x| format!("{}", x))?), + "intent" => intermediate_rep.intent.push(::from_str(val).map_err(|x| format!("{}", x))?), + "intent_signatures" => return std::result::Result::Err("Parsing a container in this style is not supported in SignedTransactionIntent".to_string()), + _ => return std::result::Result::Err("Unexpected key while parsing SignedTransactionIntent".to_string()) } } @@ -1289,40 +1442,42 @@ impl std::str::FromStr for InvalidJsonErrorAllOf { } // Use the intermediate representation to return the struct - std::result::Result::Ok(InvalidJsonErrorAllOf { - cause: intermediate_rep.cause.into_iter().next(), + std::result::Result::Ok(SignedTransactionIntent { + hash: intermediate_rep.hash.into_iter().next().ok_or("hash missing in SignedTransactionIntent".to_string())?, + intent: intermediate_rep.intent.into_iter().next().ok_or("intent missing in SignedTransactionIntent".to_string())?, + intent_signatures: intermediate_rep.intent_signatures.into_iter().next().ok_or("intent_signatures missing in SignedTransactionIntent".to_string())?, }) } } -// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue +// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue -impl std::convert::TryFrom> for hyper::header::HeaderValue { +impl std::convert::TryFrom> for hyper::header::HeaderValue { type Error = String; - fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { let hdr_value = hdr_value.to_string(); match hyper::header::HeaderValue::from_str(&hdr_value) { std::result::Result::Ok(value) => std::result::Result::Ok(value), std::result::Result::Err(e) => std::result::Result::Err( - format!("Invalid header value for InvalidJsonErrorAllOf - value: {} is invalid {}", + format!("Invalid header value for SignedTransactionIntent - value: {} is invalid {}", hdr_value, e)) } } } -impl std::convert::TryFrom for header::IntoHeaderValue { +impl std::convert::TryFrom for header::IntoHeaderValue { type Error = String; fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { match hdr_value.to_str() { std::result::Result::Ok(value) => { - match ::from_str(value) { + match ::from_str(value) { std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), std::result::Result::Err(err) => std::result::Result::Err( - format!("Unable to convert header value '{}' into InvalidJsonErrorAllOf - {}", + format!("Unable to convert header value '{}' into SignedTransactionIntent - {}", value, err)) } }, @@ -1336,168 +1491,124 @@ impl std::convert::TryFrom for header::IntoHeaderVal #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] #[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] -pub struct InvalidTransactionError { - #[serde(rename = "type")] - pub type_: String, +pub struct TransactionHeader { + #[serde(rename = "version")] + pub version: isize, - #[serde(rename = "message")] - pub message: String, + #[serde(rename = "network_id")] + pub network_id: isize, + + /// A decimal 64-bit unsigned integer. + #[serde(rename = "start_epoch_inclusive")] + pub start_epoch_inclusive: String, + + /// A decimal 64-bit unsigned integer. + #[serde(rename = "end_epoch_exclusive")] + pub end_epoch_exclusive: String, + + /// A decimal 64-bit unsigned integer. + #[serde(rename = "nonce")] + pub nonce: String, + + /// A hex-encoded public key of a notary. + #[serde(rename = "notary_public_key")] + pub notary_public_key: String, + + /// Specifies whether the notary's signature should be included in transaction signers list + #[serde(rename = "notary_as_signatory")] + pub notary_as_signatory: bool, + + /// Maximum number of cost units available for transaction execution. A decimal 32-bit unsigned integer. + #[serde(rename = "cost_unit_limit")] + pub cost_unit_limit: String, + + /// Specifies the validator tip. A decimal 32-bit unsigned integer, representing the percentage amount (a value of \"1\" corresponds to 1%). + #[serde(rename = "tip_percentage")] + pub tip_percentage: String, } -impl InvalidTransactionError { - pub fn new(type_: String, message: String, ) -> InvalidTransactionError { - InvalidTransactionError { - type_: type_, - message: message, +impl TransactionHeader { + pub fn new(version: isize, network_id: isize, start_epoch_inclusive: String, end_epoch_exclusive: String, nonce: String, notary_public_key: String, notary_as_signatory: bool, cost_unit_limit: String, tip_percentage: String, ) -> TransactionHeader { + TransactionHeader { + version: version, + network_id: network_id, + start_epoch_inclusive: start_epoch_inclusive, + end_epoch_exclusive: end_epoch_exclusive, + nonce: nonce, + notary_public_key: notary_public_key, + notary_as_signatory: notary_as_signatory, + cost_unit_limit: cost_unit_limit, + tip_percentage: tip_percentage, } } } -/// Converts the InvalidTransactionError value to the Query Parameters representation (style=form, explode=false) +/// Converts the TransactionHeader value to the Query Parameters representation (style=form, explode=false) /// specified in https://swagger.io/docs/specification/serialization/ /// Should be implemented in a serde serializer -impl std::string::ToString for InvalidTransactionError { +impl std::string::ToString for TransactionHeader { fn to_string(&self) -> String { let mut params: Vec = vec![]; - params.push("type".to_string()); - params.push(self.type_.to_string()); + params.push("version".to_string()); + params.push(self.version.to_string()); - params.push("message".to_string()); - params.push(self.message.to_string()); + params.push("network_id".to_string()); + params.push(self.network_id.to_string()); - params.join(",").to_string() - } -} -/// Converts Query Parameters representation (style=form, explode=false) to a InvalidTransactionError value -/// as specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde deserializer -impl std::str::FromStr for InvalidTransactionError { - type Err = String; + params.push("start_epoch_inclusive".to_string()); + params.push(self.start_epoch_inclusive.to_string()); - fn from_str(s: &str) -> std::result::Result { - #[derive(Default)] - // An intermediate representation of the struct to use for parsing. - struct IntermediateRep { - pub type_: Vec, - pub message: Vec, - } - let mut intermediate_rep = IntermediateRep::default(); + params.push("end_epoch_exclusive".to_string()); + params.push(self.end_epoch_exclusive.to_string()); - // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); - let mut key_result = string_iter.next(); - - while key_result.is_some() { - let val = match string_iter.next() { - Some(x) => x, - None => return std::result::Result::Err("Missing value while parsing InvalidTransactionError".to_string()) - }; - - if let Some(key) = key_result { - match key { - "type" => intermediate_rep.type_.push(::from_str(val).map_err(|x| format!("{}", x))?), - "message" => intermediate_rep.message.push(::from_str(val).map_err(|x| format!("{}", x))?), - _ => return std::result::Result::Err("Unexpected key while parsing InvalidTransactionError".to_string()) - } - } - - // Get the next key - key_result = string_iter.next(); - } - - // Use the intermediate representation to return the struct - std::result::Result::Ok(InvalidTransactionError { - type_: intermediate_rep.type_.into_iter().next().ok_or("type missing in InvalidTransactionError".to_string())?, - message: intermediate_rep.message.into_iter().next().ok_or("message missing in InvalidTransactionError".to_string())?, - }) - } -} - -// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue - - -impl std::convert::TryFrom> for hyper::header::HeaderValue { - type Error = String; - - fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { - let hdr_value = hdr_value.to_string(); - match hyper::header::HeaderValue::from_str(&hdr_value) { - std::result::Result::Ok(value) => std::result::Result::Ok(value), - std::result::Result::Err(e) => std::result::Result::Err( - format!("Invalid header value for InvalidTransactionError - value: {} is invalid {}", - hdr_value, e)) - } - } -} + params.push("nonce".to_string()); + params.push(self.nonce.to_string()); -impl std::convert::TryFrom for header::IntoHeaderValue { - type Error = String; - fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { - match hdr_value.to_str() { - std::result::Result::Ok(value) => { - match ::from_str(value) { - std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), - std::result::Result::Err(err) => std::result::Result::Err( - format!("Unable to convert header value '{}' into InvalidTransactionError - {}", - value, err)) - } - }, - std::result::Result::Err(e) => std::result::Result::Err( - format!("Unable to convert header: {:?} to string: {}", - hdr_value, e)) - } - } -} + params.push("notary_public_key".to_string()); + params.push(self.notary_public_key.to_string()); -#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] -#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] -pub struct InvalidTransactionErrorAllOf { - #[serde(rename = "message")] - pub message: String, + params.push("notary_as_signatory".to_string()); + params.push(self.notary_as_signatory.to_string()); -} -impl InvalidTransactionErrorAllOf { - pub fn new(message: String, ) -> InvalidTransactionErrorAllOf { - InvalidTransactionErrorAllOf { - message: message, - } - } -} + params.push("cost_unit_limit".to_string()); + params.push(self.cost_unit_limit.to_string()); -/// Converts the InvalidTransactionErrorAllOf value to the Query Parameters representation (style=form, explode=false) -/// specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde serializer -impl std::string::ToString for InvalidTransactionErrorAllOf { - fn to_string(&self) -> String { - let mut params: Vec = vec![]; - params.push("message".to_string()); - params.push(self.message.to_string()); + params.push("tip_percentage".to_string()); + params.push(self.tip_percentage.to_string()); params.join(",").to_string() } } -/// Converts Query Parameters representation (style=form, explode=false) to a InvalidTransactionErrorAllOf value +/// Converts Query Parameters representation (style=form, explode=false) to a TransactionHeader value /// as specified in https://swagger.io/docs/specification/serialization/ /// Should be implemented in a serde deserializer -impl std::str::FromStr for InvalidTransactionErrorAllOf { +impl std::str::FromStr for TransactionHeader { type Err = String; fn from_str(s: &str) -> std::result::Result { #[derive(Default)] // An intermediate representation of the struct to use for parsing. struct IntermediateRep { - pub message: Vec, + pub version: Vec, + pub network_id: Vec, + pub start_epoch_inclusive: Vec, + pub end_epoch_exclusive: Vec, + pub nonce: Vec, + pub notary_public_key: Vec, + pub notary_as_signatory: Vec, + pub cost_unit_limit: Vec, + pub tip_percentage: Vec, } let mut intermediate_rep = IntermediateRep::default(); @@ -1509,13 +1620,21 @@ impl std::str::FromStr for InvalidTransactionErrorAllOf { while key_result.is_some() { let val = match string_iter.next() { Some(x) => x, - None => return std::result::Result::Err("Missing value while parsing InvalidTransactionErrorAllOf".to_string()) + None => return std::result::Result::Err("Missing value while parsing TransactionHeader".to_string()) }; if let Some(key) = key_result { match key { - "message" => intermediate_rep.message.push(::from_str(val).map_err(|x| format!("{}", x))?), - _ => return std::result::Result::Err("Unexpected key while parsing InvalidTransactionErrorAllOf".to_string()) + "version" => intermediate_rep.version.push(::from_str(val).map_err(|x| format!("{}", x))?), + "network_id" => intermediate_rep.network_id.push(::from_str(val).map_err(|x| format!("{}", x))?), + "start_epoch_inclusive" => intermediate_rep.start_epoch_inclusive.push(::from_str(val).map_err(|x| format!("{}", x))?), + "end_epoch_exclusive" => intermediate_rep.end_epoch_exclusive.push(::from_str(val).map_err(|x| format!("{}", x))?), + "nonce" => intermediate_rep.nonce.push(::from_str(val).map_err(|x| format!("{}", x))?), + "notary_public_key" => intermediate_rep.notary_public_key.push(::from_str(val).map_err(|x| format!("{}", x))?), + "notary_as_signatory" => intermediate_rep.notary_as_signatory.push(::from_str(val).map_err(|x| format!("{}", x))?), + "cost_unit_limit" => intermediate_rep.cost_unit_limit.push(::from_str(val).map_err(|x| format!("{}", x))?), + "tip_percentage" => intermediate_rep.tip_percentage.push(::from_str(val).map_err(|x| format!("{}", x))?), + _ => return std::result::Result::Err("Unexpected key while parsing TransactionHeader".to_string()) } } @@ -1524,40 +1643,48 @@ impl std::str::FromStr for InvalidTransactionErrorAllOf { } // Use the intermediate representation to return the struct - std::result::Result::Ok(InvalidTransactionErrorAllOf { - message: intermediate_rep.message.into_iter().next().ok_or("message missing in InvalidTransactionErrorAllOf".to_string())?, + std::result::Result::Ok(TransactionHeader { + version: intermediate_rep.version.into_iter().next().ok_or("version missing in TransactionHeader".to_string())?, + network_id: intermediate_rep.network_id.into_iter().next().ok_or("network_id missing in TransactionHeader".to_string())?, + start_epoch_inclusive: intermediate_rep.start_epoch_inclusive.into_iter().next().ok_or("start_epoch_inclusive missing in TransactionHeader".to_string())?, + end_epoch_exclusive: intermediate_rep.end_epoch_exclusive.into_iter().next().ok_or("end_epoch_exclusive missing in TransactionHeader".to_string())?, + nonce: intermediate_rep.nonce.into_iter().next().ok_or("nonce missing in TransactionHeader".to_string())?, + notary_public_key: intermediate_rep.notary_public_key.into_iter().next().ok_or("notary_public_key missing in TransactionHeader".to_string())?, + notary_as_signatory: intermediate_rep.notary_as_signatory.into_iter().next().ok_or("notary_as_signatory missing in TransactionHeader".to_string())?, + cost_unit_limit: intermediate_rep.cost_unit_limit.into_iter().next().ok_or("cost_unit_limit missing in TransactionHeader".to_string())?, + tip_percentage: intermediate_rep.tip_percentage.into_iter().next().ok_or("tip_percentage missing in TransactionHeader".to_string())?, }) } } -// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue +// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue -impl std::convert::TryFrom> for hyper::header::HeaderValue { +impl std::convert::TryFrom> for hyper::header::HeaderValue { type Error = String; - fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { let hdr_value = hdr_value.to_string(); match hyper::header::HeaderValue::from_str(&hdr_value) { std::result::Result::Ok(value) => std::result::Result::Ok(value), std::result::Result::Err(e) => std::result::Result::Err( - format!("Invalid header value for InvalidTransactionErrorAllOf - value: {} is invalid {}", + format!("Invalid header value for TransactionHeader - value: {} is invalid {}", hdr_value, e)) } } } -impl std::convert::TryFrom for header::IntoHeaderValue { +impl std::convert::TryFrom for header::IntoHeaderValue { type Error = String; fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { match hdr_value.to_str() { std::result::Result::Ok(value) => { - match ::from_str(value) { + match ::from_str(value) { std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), std::result::Result::Err(err) => std::result::Result::Err( - format!("Unable to convert header value '{}' into InvalidTransactionErrorAllOf - {}", + format!("Unable to convert header value '{}' into TransactionHeader - {}", value, err)) } }, @@ -1571,168 +1698,63 @@ impl std::convert::TryFrom for header::IntoHeaderVal #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] #[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] -pub struct MempoolFullError { - #[serde(rename = "type")] - pub type_: String, +pub struct TransactionIntent { + /// Transaction intent hash, hex-encoded. + #[serde(rename = "hash")] + pub hash: String, + + #[serde(rename = "header")] + pub header: models::TransactionHeader, - #[serde(rename = "mempool_transaction_count")] - pub mempool_transaction_count: i64, + /// Transaction manifest, SBOR-encoded and then hex-encoded. + #[serde(rename = "manifest")] + pub manifest: String, } -impl MempoolFullError { - pub fn new(type_: String, mempool_transaction_count: i64, ) -> MempoolFullError { - MempoolFullError { - type_: type_, - mempool_transaction_count: mempool_transaction_count, +impl TransactionIntent { + pub fn new(hash: String, header: models::TransactionHeader, manifest: String, ) -> TransactionIntent { + TransactionIntent { + hash: hash, + header: header, + manifest: manifest, } } } -/// Converts the MempoolFullError value to the Query Parameters representation (style=form, explode=false) +/// Converts the TransactionIntent value to the Query Parameters representation (style=form, explode=false) /// specified in https://swagger.io/docs/specification/serialization/ /// Should be implemented in a serde serializer -impl std::string::ToString for MempoolFullError { +impl std::string::ToString for TransactionIntent { fn to_string(&self) -> String { let mut params: Vec = vec![]; - params.push("type".to_string()); - params.push(self.type_.to_string()); - - - params.push("mempool_transaction_count".to_string()); - params.push(self.mempool_transaction_count.to_string()); - - params.join(",").to_string() - } -} - -/// Converts Query Parameters representation (style=form, explode=false) to a MempoolFullError value -/// as specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde deserializer -impl std::str::FromStr for MempoolFullError { - type Err = String; - - fn from_str(s: &str) -> std::result::Result { - #[derive(Default)] - // An intermediate representation of the struct to use for parsing. - struct IntermediateRep { - pub type_: Vec, - pub mempool_transaction_count: Vec, - } - - let mut intermediate_rep = IntermediateRep::default(); - - // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); - let mut key_result = string_iter.next(); - - while key_result.is_some() { - let val = match string_iter.next() { - Some(x) => x, - None => return std::result::Result::Err("Missing value while parsing MempoolFullError".to_string()) - }; - - if let Some(key) = key_result { - match key { - "type" => intermediate_rep.type_.push(::from_str(val).map_err(|x| format!("{}", x))?), - "mempool_transaction_count" => intermediate_rep.mempool_transaction_count.push(::from_str(val).map_err(|x| format!("{}", x))?), - _ => return std::result::Result::Err("Unexpected key while parsing MempoolFullError".to_string()) - } - } - - // Get the next key - key_result = string_iter.next(); - } - - // Use the intermediate representation to return the struct - std::result::Result::Ok(MempoolFullError { - type_: intermediate_rep.type_.into_iter().next().ok_or("type missing in MempoolFullError".to_string())?, - mempool_transaction_count: intermediate_rep.mempool_transaction_count.into_iter().next().ok_or("mempool_transaction_count missing in MempoolFullError".to_string())?, - }) - } -} - -// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue - - -impl std::convert::TryFrom> for hyper::header::HeaderValue { - type Error = String; - - fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { - let hdr_value = hdr_value.to_string(); - match hyper::header::HeaderValue::from_str(&hdr_value) { - std::result::Result::Ok(value) => std::result::Result::Ok(value), - std::result::Result::Err(e) => std::result::Result::Err( - format!("Invalid header value for MempoolFullError - value: {} is invalid {}", - hdr_value, e)) - } - } -} - - -impl std::convert::TryFrom for header::IntoHeaderValue { - type Error = String; - - fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { - match hdr_value.to_str() { - std::result::Result::Ok(value) => { - match ::from_str(value) { - std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), - std::result::Result::Err(err) => std::result::Result::Err( - format!("Unable to convert header value '{}' into MempoolFullError - {}", - value, err)) - } - }, - std::result::Result::Err(e) => std::result::Result::Err( - format!("Unable to convert header: {:?} to string: {}", - hdr_value, e)) - } - } -} - + params.push("hash".to_string()); + params.push(self.hash.to_string()); -#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] -#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] -pub struct MempoolFullErrorAllOf { - #[serde(rename = "mempool_transaction_count")] - pub mempool_transaction_count: i64, - -} - -impl MempoolFullErrorAllOf { - pub fn new(mempool_transaction_count: i64, ) -> MempoolFullErrorAllOf { - MempoolFullErrorAllOf { - mempool_transaction_count: mempool_transaction_count, - } - } -} + // Skipping header in query parameter serialization -/// Converts the MempoolFullErrorAllOf value to the Query Parameters representation (style=form, explode=false) -/// specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde serializer -impl std::string::ToString for MempoolFullErrorAllOf { - fn to_string(&self) -> String { - let mut params: Vec = vec![]; - params.push("mempool_transaction_count".to_string()); - params.push(self.mempool_transaction_count.to_string()); + params.push("manifest".to_string()); + params.push(self.manifest.to_string()); params.join(",").to_string() } } -/// Converts Query Parameters representation (style=form, explode=false) to a MempoolFullErrorAllOf value +/// Converts Query Parameters representation (style=form, explode=false) to a TransactionIntent value /// as specified in https://swagger.io/docs/specification/serialization/ /// Should be implemented in a serde deserializer -impl std::str::FromStr for MempoolFullErrorAllOf { +impl std::str::FromStr for TransactionIntent { type Err = String; fn from_str(s: &str) -> std::result::Result { #[derive(Default)] // An intermediate representation of the struct to use for parsing. struct IntermediateRep { - pub mempool_transaction_count: Vec, + pub hash: Vec, + pub header: Vec, + pub manifest: Vec, } let mut intermediate_rep = IntermediateRep::default(); @@ -1744,13 +1766,15 @@ impl std::str::FromStr for MempoolFullErrorAllOf { while key_result.is_some() { let val = match string_iter.next() { Some(x) => x, - None => return std::result::Result::Err("Missing value while parsing MempoolFullErrorAllOf".to_string()) + None => return std::result::Result::Err("Missing value while parsing TransactionIntent".to_string()) }; if let Some(key) = key_result { match key { - "mempool_transaction_count" => intermediate_rep.mempool_transaction_count.push(::from_str(val).map_err(|x| format!("{}", x))?), - _ => return std::result::Result::Err("Unexpected key while parsing MempoolFullErrorAllOf".to_string()) + "hash" => intermediate_rep.hash.push(::from_str(val).map_err(|x| format!("{}", x))?), + "header" => intermediate_rep.header.push(::from_str(val).map_err(|x| format!("{}", x))?), + "manifest" => intermediate_rep.manifest.push(::from_str(val).map_err(|x| format!("{}", x))?), + _ => return std::result::Result::Err("Unexpected key while parsing TransactionIntent".to_string()) } } @@ -1759,40 +1783,42 @@ impl std::str::FromStr for MempoolFullErrorAllOf { } // Use the intermediate representation to return the struct - std::result::Result::Ok(MempoolFullErrorAllOf { - mempool_transaction_count: intermediate_rep.mempool_transaction_count.into_iter().next().ok_or("mempool_transaction_count missing in MempoolFullErrorAllOf".to_string())?, + std::result::Result::Ok(TransactionIntent { + hash: intermediate_rep.hash.into_iter().next().ok_or("hash missing in TransactionIntent".to_string())?, + header: intermediate_rep.header.into_iter().next().ok_or("header missing in TransactionIntent".to_string())?, + manifest: intermediate_rep.manifest.into_iter().next().ok_or("manifest missing in TransactionIntent".to_string())?, }) } } -// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue +// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue -impl std::convert::TryFrom> for hyper::header::HeaderValue { +impl std::convert::TryFrom> for hyper::header::HeaderValue { type Error = String; - fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { let hdr_value = hdr_value.to_string(); match hyper::header::HeaderValue::from_str(&hdr_value) { std::result::Result::Ok(value) => std::result::Result::Ok(value), std::result::Result::Err(e) => std::result::Result::Err( - format!("Invalid header value for MempoolFullErrorAllOf - value: {} is invalid {}", + format!("Invalid header value for TransactionIntent - value: {} is invalid {}", hdr_value, e)) } } } -impl std::convert::TryFrom for header::IntoHeaderValue { +impl std::convert::TryFrom for header::IntoHeaderValue { type Error = String; fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { match hdr_value.to_str() { std::result::Result::Ok(value) => { - match ::from_str(value) { + match ::from_str(value) { std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), std::result::Result::Err(err) => std::result::Result::Err( - format!("Unable to convert header value '{}' into MempoolFullErrorAllOf - {}", + format!("Unable to convert header value '{}' into TransactionIntent - {}", value, err)) } }, @@ -1806,1341 +1832,100 @@ impl std::convert::TryFrom for header::IntoHeaderVal #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] #[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] -pub struct NetworkConfigurationResponse { - #[serde(rename = "version")] - pub version: models::NetworkConfigurationResponseVersion, - +pub struct TransactionPreviewRequest { #[serde(rename = "network_identifier")] pub network_identifier: models::NetworkIdentifier, - #[serde(rename = "bech32_human_readable_parts")] - pub bech32_human_readable_parts: models::Bech32Hrps, - -} - -impl NetworkConfigurationResponse { - pub fn new(version: models::NetworkConfigurationResponseVersion, network_identifier: models::NetworkIdentifier, bech32_human_readable_parts: models::Bech32Hrps, ) -> NetworkConfigurationResponse { - NetworkConfigurationResponse { - version: version, - network_identifier: network_identifier, - bech32_human_readable_parts: bech32_human_readable_parts, - } - } -} - -/// Converts the NetworkConfigurationResponse value to the Query Parameters representation (style=form, explode=false) -/// specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde serializer -impl std::string::ToString for NetworkConfigurationResponse { - fn to_string(&self) -> String { - let mut params: Vec = vec![]; - // Skipping version in query parameter serialization - - // Skipping network_identifier in query parameter serialization - - // Skipping bech32_human_readable_parts in query parameter serialization - - params.join(",").to_string() - } -} - -/// Converts Query Parameters representation (style=form, explode=false) to a NetworkConfigurationResponse value -/// as specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde deserializer -impl std::str::FromStr for NetworkConfigurationResponse { - type Err = String; - - fn from_str(s: &str) -> std::result::Result { - #[derive(Default)] - // An intermediate representation of the struct to use for parsing. - struct IntermediateRep { - pub version: Vec, - pub network_identifier: Vec, - pub bech32_human_readable_parts: Vec, - } - - let mut intermediate_rep = IntermediateRep::default(); - - // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); - let mut key_result = string_iter.next(); - - while key_result.is_some() { - let val = match string_iter.next() { - Some(x) => x, - None => return std::result::Result::Err("Missing value while parsing NetworkConfigurationResponse".to_string()) - }; - - if let Some(key) = key_result { - match key { - "version" => intermediate_rep.version.push(::from_str(val).map_err(|x| format!("{}", x))?), - "network_identifier" => intermediate_rep.network_identifier.push(::from_str(val).map_err(|x| format!("{}", x))?), - "bech32_human_readable_parts" => intermediate_rep.bech32_human_readable_parts.push(::from_str(val).map_err(|x| format!("{}", x))?), - _ => return std::result::Result::Err("Unexpected key while parsing NetworkConfigurationResponse".to_string()) - } - } - - // Get the next key - key_result = string_iter.next(); - } - - // Use the intermediate representation to return the struct - std::result::Result::Ok(NetworkConfigurationResponse { - version: intermediate_rep.version.into_iter().next().ok_or("version missing in NetworkConfigurationResponse".to_string())?, - network_identifier: intermediate_rep.network_identifier.into_iter().next().ok_or("network_identifier missing in NetworkConfigurationResponse".to_string())?, - bech32_human_readable_parts: intermediate_rep.bech32_human_readable_parts.into_iter().next().ok_or("bech32_human_readable_parts missing in NetworkConfigurationResponse".to_string())?, - }) - } -} - -// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue + /// A transaction manifest. Sbor encoded, and then hex encoded. + #[serde(rename = "manifest")] + pub manifest: String, + /// Maximum number of cost units available for transaction execution. A decimal 32-bit unsigned integer. + #[serde(rename = "cost_unit_limit")] + pub cost_unit_limit: String, -impl std::convert::TryFrom> for hyper::header::HeaderValue { - type Error = String; + /// The validator tip. A decimal 32-bit unsigned integer, representing the percentage amount (a value of \"1\" corresponds to 1%). + #[serde(rename = "tip_percentage")] + pub tip_percentage: String, - fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { - let hdr_value = hdr_value.to_string(); - match hyper::header::HeaderValue::from_str(&hdr_value) { - std::result::Result::Ok(value) => std::result::Result::Ok(value), - std::result::Result::Err(e) => std::result::Result::Err( - format!("Invalid header value for NetworkConfigurationResponse - value: {} is invalid {}", - hdr_value, e)) - } - } -} - - -impl std::convert::TryFrom for header::IntoHeaderValue { - type Error = String; - - fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { - match hdr_value.to_str() { - std::result::Result::Ok(value) => { - match ::from_str(value) { - std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), - std::result::Result::Err(err) => std::result::Result::Err( - format!("Unable to convert header value '{}' into NetworkConfigurationResponse - {}", - value, err)) - } - }, - std::result::Result::Err(e) => std::result::Result::Err( - format!("Unable to convert header: {:?} to string: {}", - hdr_value, e)) - } - } -} - - -/// Different versions regarding the node, network and api. -#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] -#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] -pub struct NetworkConfigurationResponseVersion { - #[serde(rename = "core_version")] - pub core_version: String, - - #[serde(rename = "api_version")] - pub api_version: String, - -} - -impl NetworkConfigurationResponseVersion { - pub fn new(core_version: String, api_version: String, ) -> NetworkConfigurationResponseVersion { - NetworkConfigurationResponseVersion { - core_version: core_version, - api_version: api_version, - } - } -} - -/// Converts the NetworkConfigurationResponseVersion value to the Query Parameters representation (style=form, explode=false) -/// specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde serializer -impl std::string::ToString for NetworkConfigurationResponseVersion { - fn to_string(&self) -> String { - let mut params: Vec = vec![]; - - params.push("core_version".to_string()); - params.push(self.core_version.to_string()); - - - params.push("api_version".to_string()); - params.push(self.api_version.to_string()); - - params.join(",").to_string() - } -} - -/// Converts Query Parameters representation (style=form, explode=false) to a NetworkConfigurationResponseVersion value -/// as specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde deserializer -impl std::str::FromStr for NetworkConfigurationResponseVersion { - type Err = String; - - fn from_str(s: &str) -> std::result::Result { - #[derive(Default)] - // An intermediate representation of the struct to use for parsing. - struct IntermediateRep { - pub core_version: Vec, - pub api_version: Vec, - } - - let mut intermediate_rep = IntermediateRep::default(); - - // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); - let mut key_result = string_iter.next(); - - while key_result.is_some() { - let val = match string_iter.next() { - Some(x) => x, - None => return std::result::Result::Err("Missing value while parsing NetworkConfigurationResponseVersion".to_string()) - }; - - if let Some(key) = key_result { - match key { - "core_version" => intermediate_rep.core_version.push(::from_str(val).map_err(|x| format!("{}", x))?), - "api_version" => intermediate_rep.api_version.push(::from_str(val).map_err(|x| format!("{}", x))?), - _ => return std::result::Result::Err("Unexpected key while parsing NetworkConfigurationResponseVersion".to_string()) - } - } - - // Get the next key - key_result = string_iter.next(); - } - - // Use the intermediate representation to return the struct - std::result::Result::Ok(NetworkConfigurationResponseVersion { - core_version: intermediate_rep.core_version.into_iter().next().ok_or("core_version missing in NetworkConfigurationResponseVersion".to_string())?, - api_version: intermediate_rep.api_version.into_iter().next().ok_or("api_version missing in NetworkConfigurationResponseVersion".to_string())?, - }) - } -} - -// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue - - -impl std::convert::TryFrom> for hyper::header::HeaderValue { - type Error = String; - - fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { - let hdr_value = hdr_value.to_string(); - match hyper::header::HeaderValue::from_str(&hdr_value) { - std::result::Result::Ok(value) => std::result::Result::Ok(value), - std::result::Result::Err(e) => std::result::Result::Err( - format!("Invalid header value for NetworkConfigurationResponseVersion - value: {} is invalid {}", - hdr_value, e)) - } - } -} - - -impl std::convert::TryFrom for header::IntoHeaderValue { - type Error = String; - - fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { - match hdr_value.to_str() { - std::result::Result::Ok(value) => { - match ::from_str(value) { - std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), - std::result::Result::Err(err) => std::result::Result::Err( - format!("Unable to convert header value '{}' into NetworkConfigurationResponseVersion - {}", - value, err)) - } - }, - std::result::Result::Err(e) => std::result::Result::Err( - format!("Unable to convert header: {:?} to string: {}", - hdr_value, e)) - } - } -} - - -#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] -#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] -pub struct NetworkIdentifier { - #[serde(rename = "network")] - pub network: String, - -} - -impl NetworkIdentifier { - pub fn new(network: String, ) -> NetworkIdentifier { - NetworkIdentifier { - network: network, - } - } -} - -/// Converts the NetworkIdentifier value to the Query Parameters representation (style=form, explode=false) -/// specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde serializer -impl std::string::ToString for NetworkIdentifier { - fn to_string(&self) -> String { - let mut params: Vec = vec![]; - - params.push("network".to_string()); - params.push(self.network.to_string()); - - params.join(",").to_string() - } -} - -/// Converts Query Parameters representation (style=form, explode=false) to a NetworkIdentifier value -/// as specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde deserializer -impl std::str::FromStr for NetworkIdentifier { - type Err = String; - - fn from_str(s: &str) -> std::result::Result { - #[derive(Default)] - // An intermediate representation of the struct to use for parsing. - struct IntermediateRep { - pub network: Vec, - } - - let mut intermediate_rep = IntermediateRep::default(); - - // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); - let mut key_result = string_iter.next(); - - while key_result.is_some() { - let val = match string_iter.next() { - Some(x) => x, - None => return std::result::Result::Err("Missing value while parsing NetworkIdentifier".to_string()) - }; - - if let Some(key) = key_result { - match key { - "network" => intermediate_rep.network.push(::from_str(val).map_err(|x| format!("{}", x))?), - _ => return std::result::Result::Err("Unexpected key while parsing NetworkIdentifier".to_string()) - } - } - - // Get the next key - key_result = string_iter.next(); - } - - // Use the intermediate representation to return the struct - std::result::Result::Ok(NetworkIdentifier { - network: intermediate_rep.network.into_iter().next().ok_or("network missing in NetworkIdentifier".to_string())?, - }) - } -} - -// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue - - -impl std::convert::TryFrom> for hyper::header::HeaderValue { - type Error = String; - - fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { - let hdr_value = hdr_value.to_string(); - match hyper::header::HeaderValue::from_str(&hdr_value) { - std::result::Result::Ok(value) => std::result::Result::Ok(value), - std::result::Result::Err(e) => std::result::Result::Err( - format!("Invalid header value for NetworkIdentifier - value: {} is invalid {}", - hdr_value, e)) - } - } -} - - -impl std::convert::TryFrom for header::IntoHeaderValue { - type Error = String; - - fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { - match hdr_value.to_str() { - std::result::Result::Ok(value) => { - match ::from_str(value) { - std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), - std::result::Result::Err(err) => std::result::Result::Err( - format!("Unable to convert header value '{}' into NetworkIdentifier - {}", - value, err)) - } - }, - std::result::Result::Err(e) => std::result::Result::Err( - format!("Unable to convert header: {:?} to string: {}", - hdr_value, e)) - } - } -} - - -#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] -#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] -pub struct NetworkNotSupportedError { - #[serde(rename = "type")] - pub type_: String, - - #[serde(rename = "supported_networks")] - pub supported_networks: Vec, - -} - -impl NetworkNotSupportedError { - pub fn new(type_: String, supported_networks: Vec, ) -> NetworkNotSupportedError { - NetworkNotSupportedError { - type_: type_, - supported_networks: supported_networks, - } - } -} - -/// Converts the NetworkNotSupportedError value to the Query Parameters representation (style=form, explode=false) -/// specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde serializer -impl std::string::ToString for NetworkNotSupportedError { - fn to_string(&self) -> String { - let mut params: Vec = vec![]; - - params.push("type".to_string()); - params.push(self.type_.to_string()); - - // Skipping supported_networks in query parameter serialization - - params.join(",").to_string() - } -} - -/// Converts Query Parameters representation (style=form, explode=false) to a NetworkNotSupportedError value -/// as specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde deserializer -impl std::str::FromStr for NetworkNotSupportedError { - type Err = String; - - fn from_str(s: &str) -> std::result::Result { - #[derive(Default)] - // An intermediate representation of the struct to use for parsing. - struct IntermediateRep { - pub type_: Vec, - pub supported_networks: Vec>, - } - - let mut intermediate_rep = IntermediateRep::default(); - - // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); - let mut key_result = string_iter.next(); - - while key_result.is_some() { - let val = match string_iter.next() { - Some(x) => x, - None => return std::result::Result::Err("Missing value while parsing NetworkNotSupportedError".to_string()) - }; - - if let Some(key) = key_result { - match key { - "type" => intermediate_rep.type_.push(::from_str(val).map_err(|x| format!("{}", x))?), - "supported_networks" => return std::result::Result::Err("Parsing a container in this style is not supported in NetworkNotSupportedError".to_string()), - _ => return std::result::Result::Err("Unexpected key while parsing NetworkNotSupportedError".to_string()) - } - } - - // Get the next key - key_result = string_iter.next(); - } - - // Use the intermediate representation to return the struct - std::result::Result::Ok(NetworkNotSupportedError { - type_: intermediate_rep.type_.into_iter().next().ok_or("type missing in NetworkNotSupportedError".to_string())?, - supported_networks: intermediate_rep.supported_networks.into_iter().next().ok_or("supported_networks missing in NetworkNotSupportedError".to_string())?, - }) - } -} - -// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue - - -impl std::convert::TryFrom> for hyper::header::HeaderValue { - type Error = String; - - fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { - let hdr_value = hdr_value.to_string(); - match hyper::header::HeaderValue::from_str(&hdr_value) { - std::result::Result::Ok(value) => std::result::Result::Ok(value), - std::result::Result::Err(e) => std::result::Result::Err( - format!("Invalid header value for NetworkNotSupportedError - value: {} is invalid {}", - hdr_value, e)) - } - } -} - - -impl std::convert::TryFrom for header::IntoHeaderValue { - type Error = String; - - fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { - match hdr_value.to_str() { - std::result::Result::Ok(value) => { - match ::from_str(value) { - std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), - std::result::Result::Err(err) => std::result::Result::Err( - format!("Unable to convert header value '{}' into NetworkNotSupportedError - {}", - value, err)) - } - }, - std::result::Result::Err(e) => std::result::Result::Err( - format!("Unable to convert header: {:?} to string: {}", - hdr_value, e)) - } - } -} - - -#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] -#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] -pub struct NetworkNotSupportedErrorAllOf { - #[serde(rename = "supported_networks")] - pub supported_networks: Vec, - -} - -impl NetworkNotSupportedErrorAllOf { - pub fn new(supported_networks: Vec, ) -> NetworkNotSupportedErrorAllOf { - NetworkNotSupportedErrorAllOf { - supported_networks: supported_networks, - } - } -} - -/// Converts the NetworkNotSupportedErrorAllOf value to the Query Parameters representation (style=form, explode=false) -/// specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde serializer -impl std::string::ToString for NetworkNotSupportedErrorAllOf { - fn to_string(&self) -> String { - let mut params: Vec = vec![]; - // Skipping supported_networks in query parameter serialization - - params.join(",").to_string() - } -} - -/// Converts Query Parameters representation (style=form, explode=false) to a NetworkNotSupportedErrorAllOf value -/// as specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde deserializer -impl std::str::FromStr for NetworkNotSupportedErrorAllOf { - type Err = String; - - fn from_str(s: &str) -> std::result::Result { - #[derive(Default)] - // An intermediate representation of the struct to use for parsing. - struct IntermediateRep { - pub supported_networks: Vec>, - } - - let mut intermediate_rep = IntermediateRep::default(); - - // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); - let mut key_result = string_iter.next(); - - while key_result.is_some() { - let val = match string_iter.next() { - Some(x) => x, - None => return std::result::Result::Err("Missing value while parsing NetworkNotSupportedErrorAllOf".to_string()) - }; - - if let Some(key) = key_result { - match key { - "supported_networks" => return std::result::Result::Err("Parsing a container in this style is not supported in NetworkNotSupportedErrorAllOf".to_string()), - _ => return std::result::Result::Err("Unexpected key while parsing NetworkNotSupportedErrorAllOf".to_string()) - } - } - - // Get the next key - key_result = string_iter.next(); - } - - // Use the intermediate representation to return the struct - std::result::Result::Ok(NetworkNotSupportedErrorAllOf { - supported_networks: intermediate_rep.supported_networks.into_iter().next().ok_or("supported_networks missing in NetworkNotSupportedErrorAllOf".to_string())?, - }) - } -} - -// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue - - -impl std::convert::TryFrom> for hyper::header::HeaderValue { - type Error = String; - - fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { - let hdr_value = hdr_value.to_string(); - match hyper::header::HeaderValue::from_str(&hdr_value) { - std::result::Result::Ok(value) => std::result::Result::Ok(value), - std::result::Result::Err(e) => std::result::Result::Err( - format!("Invalid header value for NetworkNotSupportedErrorAllOf - value: {} is invalid {}", - hdr_value, e)) - } - } -} - - -impl std::convert::TryFrom for header::IntoHeaderValue { - type Error = String; - - fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { - match hdr_value.to_str() { - std::result::Result::Ok(value) => { - match ::from_str(value) { - std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), - std::result::Result::Err(err) => std::result::Result::Err( - format!("Unable to convert header value '{}' into NetworkNotSupportedErrorAllOf - {}", - value, err)) - } - }, - std::result::Result::Err(e) => std::result::Result::Err( - format!("Unable to convert header: {:?} to string: {}", - hdr_value, e)) - } - } -} - - -#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] -#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] -pub struct PreviewError { - #[serde(rename = "type")] - pub type_: String, - - #[serde(rename = "message")] - pub message: String, - -} - -impl PreviewError { - pub fn new(type_: String, message: String, ) -> PreviewError { - PreviewError { - type_: type_, - message: message, - } - } -} - -/// Converts the PreviewError value to the Query Parameters representation (style=form, explode=false) -/// specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde serializer -impl std::string::ToString for PreviewError { - fn to_string(&self) -> String { - let mut params: Vec = vec![]; - - params.push("type".to_string()); - params.push(self.type_.to_string()); - - - params.push("message".to_string()); - params.push(self.message.to_string()); - - params.join(",").to_string() - } -} - -/// Converts Query Parameters representation (style=form, explode=false) to a PreviewError value -/// as specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde deserializer -impl std::str::FromStr for PreviewError { - type Err = String; - - fn from_str(s: &str) -> std::result::Result { - #[derive(Default)] - // An intermediate representation of the struct to use for parsing. - struct IntermediateRep { - pub type_: Vec, - pub message: Vec, - } - - let mut intermediate_rep = IntermediateRep::default(); - - // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); - let mut key_result = string_iter.next(); - - while key_result.is_some() { - let val = match string_iter.next() { - Some(x) => x, - None => return std::result::Result::Err("Missing value while parsing PreviewError".to_string()) - }; - - if let Some(key) = key_result { - match key { - "type" => intermediate_rep.type_.push(::from_str(val).map_err(|x| format!("{}", x))?), - "message" => intermediate_rep.message.push(::from_str(val).map_err(|x| format!("{}", x))?), - _ => return std::result::Result::Err("Unexpected key while parsing PreviewError".to_string()) - } - } - - // Get the next key - key_result = string_iter.next(); - } - - // Use the intermediate representation to return the struct - std::result::Result::Ok(PreviewError { - type_: intermediate_rep.type_.into_iter().next().ok_or("type missing in PreviewError".to_string())?, - message: intermediate_rep.message.into_iter().next().ok_or("message missing in PreviewError".to_string())?, - }) - } -} - -// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue - - -impl std::convert::TryFrom> for hyper::header::HeaderValue { - type Error = String; - - fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { - let hdr_value = hdr_value.to_string(); - match hyper::header::HeaderValue::from_str(&hdr_value) { - std::result::Result::Ok(value) => std::result::Result::Ok(value), - std::result::Result::Err(e) => std::result::Result::Err( - format!("Invalid header value for PreviewError - value: {} is invalid {}", - hdr_value, e)) - } - } -} - - -impl std::convert::TryFrom for header::IntoHeaderValue { - type Error = String; - - fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { - match hdr_value.to_str() { - std::result::Result::Ok(value) => { - match ::from_str(value) { - std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), - std::result::Result::Err(err) => std::result::Result::Err( - format!("Unable to convert header value '{}' into PreviewError - {}", - value, err)) - } - }, - std::result::Result::Err(e) => std::result::Result::Err( - format!("Unable to convert header: {:?} to string: {}", - hdr_value, e)) - } - } -} - - -#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] -#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] -pub struct TransactionPreviewRequest { - #[serde(rename = "network_identifier")] - pub network_identifier: models::NetworkIdentifier, - - /// A transaction manifest. Sbor encoded, and then hex encoded. - #[serde(rename = "manifest")] - pub manifest: String, - - /// A limit of cost units available for execution - #[serde(rename = "cost_unit_limit")] - pub cost_unit_limit: i32, - - /// A tip for the validator - #[serde(rename = "tip_percentage")] - pub tip_percentage: i32, - - /// A nonce value to use for execution - #[serde(rename = "nonce")] - pub nonce: i64, - - /// A list of public keys to be used as transaction signers, in a compressed format, hex encoded. - #[serde(rename = "signer_public_keys")] - pub signer_public_keys: Vec, - - #[serde(rename = "flags")] - pub flags: models::TransactionPreviewRequestFlags, - -} - -impl TransactionPreviewRequest { - pub fn new(network_identifier: models::NetworkIdentifier, manifest: String, cost_unit_limit: i32, tip_percentage: i32, nonce: i64, signer_public_keys: Vec, flags: models::TransactionPreviewRequestFlags, ) -> TransactionPreviewRequest { - TransactionPreviewRequest { - network_identifier: network_identifier, - manifest: manifest, - cost_unit_limit: cost_unit_limit, - tip_percentage: tip_percentage, - nonce: nonce, - signer_public_keys: signer_public_keys, - flags: flags, - } - } -} - -/// Converts the TransactionPreviewRequest value to the Query Parameters representation (style=form, explode=false) -/// specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde serializer -impl std::string::ToString for TransactionPreviewRequest { - fn to_string(&self) -> String { - let mut params: Vec = vec![]; - // Skipping network_identifier in query parameter serialization - - - params.push("manifest".to_string()); - params.push(self.manifest.to_string()); - - - params.push("cost_unit_limit".to_string()); - params.push(self.cost_unit_limit.to_string()); - - - params.push("tip_percentage".to_string()); - params.push(self.tip_percentage.to_string()); - - - params.push("nonce".to_string()); - params.push(self.nonce.to_string()); - - - params.push("signer_public_keys".to_string()); - params.push(self.signer_public_keys.iter().map(|x| x.to_string()).collect::>().join(",").to_string()); - - // Skipping flags in query parameter serialization - - params.join(",").to_string() - } -} - -/// Converts Query Parameters representation (style=form, explode=false) to a TransactionPreviewRequest value -/// as specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde deserializer -impl std::str::FromStr for TransactionPreviewRequest { - type Err = String; - - fn from_str(s: &str) -> std::result::Result { - #[derive(Default)] - // An intermediate representation of the struct to use for parsing. - struct IntermediateRep { - pub network_identifier: Vec, - pub manifest: Vec, - pub cost_unit_limit: Vec, - pub tip_percentage: Vec, - pub nonce: Vec, - pub signer_public_keys: Vec>, - pub flags: Vec, - } - - let mut intermediate_rep = IntermediateRep::default(); - - // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); - let mut key_result = string_iter.next(); - - while key_result.is_some() { - let val = match string_iter.next() { - Some(x) => x, - None => return std::result::Result::Err("Missing value while parsing TransactionPreviewRequest".to_string()) - }; - - if let Some(key) = key_result { - match key { - "network_identifier" => intermediate_rep.network_identifier.push(::from_str(val).map_err(|x| format!("{}", x))?), - "manifest" => intermediate_rep.manifest.push(::from_str(val).map_err(|x| format!("{}", x))?), - "cost_unit_limit" => intermediate_rep.cost_unit_limit.push(::from_str(val).map_err(|x| format!("{}", x))?), - "tip_percentage" => intermediate_rep.tip_percentage.push(::from_str(val).map_err(|x| format!("{}", x))?), - "nonce" => intermediate_rep.nonce.push(::from_str(val).map_err(|x| format!("{}", x))?), - "signer_public_keys" => return std::result::Result::Err("Parsing a container in this style is not supported in TransactionPreviewRequest".to_string()), - "flags" => intermediate_rep.flags.push(::from_str(val).map_err(|x| format!("{}", x))?), - _ => return std::result::Result::Err("Unexpected key while parsing TransactionPreviewRequest".to_string()) - } - } - - // Get the next key - key_result = string_iter.next(); - } - - // Use the intermediate representation to return the struct - std::result::Result::Ok(TransactionPreviewRequest { - network_identifier: intermediate_rep.network_identifier.into_iter().next().ok_or("network_identifier missing in TransactionPreviewRequest".to_string())?, - manifest: intermediate_rep.manifest.into_iter().next().ok_or("manifest missing in TransactionPreviewRequest".to_string())?, - cost_unit_limit: intermediate_rep.cost_unit_limit.into_iter().next().ok_or("cost_unit_limit missing in TransactionPreviewRequest".to_string())?, - tip_percentage: intermediate_rep.tip_percentage.into_iter().next().ok_or("tip_percentage missing in TransactionPreviewRequest".to_string())?, - nonce: intermediate_rep.nonce.into_iter().next().ok_or("nonce missing in TransactionPreviewRequest".to_string())?, - signer_public_keys: intermediate_rep.signer_public_keys.into_iter().next().ok_or("signer_public_keys missing in TransactionPreviewRequest".to_string())?, - flags: intermediate_rep.flags.into_iter().next().ok_or("flags missing in TransactionPreviewRequest".to_string())?, - }) - } -} - -// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue - - -impl std::convert::TryFrom> for hyper::header::HeaderValue { - type Error = String; - - fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { - let hdr_value = hdr_value.to_string(); - match hyper::header::HeaderValue::from_str(&hdr_value) { - std::result::Result::Ok(value) => std::result::Result::Ok(value), - std::result::Result::Err(e) => std::result::Result::Err( - format!("Invalid header value for TransactionPreviewRequest - value: {} is invalid {}", - hdr_value, e)) - } - } -} - - -impl std::convert::TryFrom for header::IntoHeaderValue { - type Error = String; - - fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { - match hdr_value.to_str() { - std::result::Result::Ok(value) => { - match ::from_str(value) { - std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), - std::result::Result::Err(err) => std::result::Result::Err( - format!("Unable to convert header value '{}' into TransactionPreviewRequest - {}", - value, err)) - } - }, - std::result::Result::Err(e) => std::result::Result::Err( - format!("Unable to convert header: {:?} to string: {}", - hdr_value, e)) - } - } -} - - -#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] -#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] -pub struct TransactionPreviewRequestFlags { - #[serde(rename = "unlimited_loan")] - pub unlimited_loan: bool, - -} - -impl TransactionPreviewRequestFlags { - pub fn new(unlimited_loan: bool, ) -> TransactionPreviewRequestFlags { - TransactionPreviewRequestFlags { - unlimited_loan: unlimited_loan, - } - } -} - -/// Converts the TransactionPreviewRequestFlags value to the Query Parameters representation (style=form, explode=false) -/// specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde serializer -impl std::string::ToString for TransactionPreviewRequestFlags { - fn to_string(&self) -> String { - let mut params: Vec = vec![]; - - params.push("unlimited_loan".to_string()); - params.push(self.unlimited_loan.to_string()); - - params.join(",").to_string() - } -} - -/// Converts Query Parameters representation (style=form, explode=false) to a TransactionPreviewRequestFlags value -/// as specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde deserializer -impl std::str::FromStr for TransactionPreviewRequestFlags { - type Err = String; - - fn from_str(s: &str) -> std::result::Result { - #[derive(Default)] - // An intermediate representation of the struct to use for parsing. - struct IntermediateRep { - pub unlimited_loan: Vec, - } - - let mut intermediate_rep = IntermediateRep::default(); - - // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); - let mut key_result = string_iter.next(); - - while key_result.is_some() { - let val = match string_iter.next() { - Some(x) => x, - None => return std::result::Result::Err("Missing value while parsing TransactionPreviewRequestFlags".to_string()) - }; - - if let Some(key) = key_result { - match key { - "unlimited_loan" => intermediate_rep.unlimited_loan.push(::from_str(val).map_err(|x| format!("{}", x))?), - _ => return std::result::Result::Err("Unexpected key while parsing TransactionPreviewRequestFlags".to_string()) - } - } - - // Get the next key - key_result = string_iter.next(); - } - - // Use the intermediate representation to return the struct - std::result::Result::Ok(TransactionPreviewRequestFlags { - unlimited_loan: intermediate_rep.unlimited_loan.into_iter().next().ok_or("unlimited_loan missing in TransactionPreviewRequestFlags".to_string())?, - }) - } -} - -// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue - - -impl std::convert::TryFrom> for hyper::header::HeaderValue { - type Error = String; - - fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { - let hdr_value = hdr_value.to_string(); - match hyper::header::HeaderValue::from_str(&hdr_value) { - std::result::Result::Ok(value) => std::result::Result::Ok(value), - std::result::Result::Err(e) => std::result::Result::Err( - format!("Invalid header value for TransactionPreviewRequestFlags - value: {} is invalid {}", - hdr_value, e)) - } - } -} - - -impl std::convert::TryFrom for header::IntoHeaderValue { - type Error = String; - - fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { - match hdr_value.to_str() { - std::result::Result::Ok(value) => { - match ::from_str(value) { - std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), - std::result::Result::Err(err) => std::result::Result::Err( - format!("Unable to convert header value '{}' into TransactionPreviewRequestFlags - {}", - value, err)) - } - }, - std::result::Result::Err(e) => std::result::Result::Err( - format!("Unable to convert header: {:?} to string: {}", - hdr_value, e)) - } - } -} - - -#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] -#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] -pub struct TransactionPreviewResponse { - #[serde(rename = "transaction_status")] - pub transaction_status: models::TransactionStatus, - - #[serde(rename = "transaction_fee")] - pub transaction_fee: models::FeeSummary, - - #[serde(rename = "logs")] - pub logs: Vec, - - /// A list of new package addresses - #[serde(rename = "new_package_addresses")] - pub new_package_addresses: Vec, - - /// A list of new component addresses - #[serde(rename = "new_component_addresses")] - pub new_component_addresses: Vec, - - /// A list of new resource addresses - #[serde(rename = "new_resource_addresses")] - pub new_resource_addresses: Vec, - -} - -impl TransactionPreviewResponse { - pub fn new(transaction_status: models::TransactionStatus, transaction_fee: models::FeeSummary, logs: Vec, new_package_addresses: Vec, new_component_addresses: Vec, new_resource_addresses: Vec, ) -> TransactionPreviewResponse { - TransactionPreviewResponse { - transaction_status: transaction_status, - transaction_fee: transaction_fee, - logs: logs, - new_package_addresses: new_package_addresses, - new_component_addresses: new_component_addresses, - new_resource_addresses: new_resource_addresses, - } - } -} - -/// Converts the TransactionPreviewResponse value to the Query Parameters representation (style=form, explode=false) -/// specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde serializer -impl std::string::ToString for TransactionPreviewResponse { - fn to_string(&self) -> String { - let mut params: Vec = vec![]; - // Skipping transaction_status in query parameter serialization - - // Skipping transaction_fee in query parameter serialization - - // Skipping logs in query parameter serialization - - - params.push("new_package_addresses".to_string()); - params.push(self.new_package_addresses.iter().map(|x| x.to_string()).collect::>().join(",").to_string()); - - - params.push("new_component_addresses".to_string()); - params.push(self.new_component_addresses.iter().map(|x| x.to_string()).collect::>().join(",").to_string()); - - - params.push("new_resource_addresses".to_string()); - params.push(self.new_resource_addresses.iter().map(|x| x.to_string()).collect::>().join(",").to_string()); - - params.join(",").to_string() - } -} - -/// Converts Query Parameters representation (style=form, explode=false) to a TransactionPreviewResponse value -/// as specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde deserializer -impl std::str::FromStr for TransactionPreviewResponse { - type Err = String; - - fn from_str(s: &str) -> std::result::Result { - #[derive(Default)] - // An intermediate representation of the struct to use for parsing. - struct IntermediateRep { - pub transaction_status: Vec, - pub transaction_fee: Vec, - pub logs: Vec>, - pub new_package_addresses: Vec>, - pub new_component_addresses: Vec>, - pub new_resource_addresses: Vec>, - } - - let mut intermediate_rep = IntermediateRep::default(); - - // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); - let mut key_result = string_iter.next(); - - while key_result.is_some() { - let val = match string_iter.next() { - Some(x) => x, - None => return std::result::Result::Err("Missing value while parsing TransactionPreviewResponse".to_string()) - }; - - if let Some(key) = key_result { - match key { - "transaction_status" => intermediate_rep.transaction_status.push(::from_str(val).map_err(|x| format!("{}", x))?), - "transaction_fee" => intermediate_rep.transaction_fee.push(::from_str(val).map_err(|x| format!("{}", x))?), - "logs" => return std::result::Result::Err("Parsing a container in this style is not supported in TransactionPreviewResponse".to_string()), - "new_package_addresses" => return std::result::Result::Err("Parsing a container in this style is not supported in TransactionPreviewResponse".to_string()), - "new_component_addresses" => return std::result::Result::Err("Parsing a container in this style is not supported in TransactionPreviewResponse".to_string()), - "new_resource_addresses" => return std::result::Result::Err("Parsing a container in this style is not supported in TransactionPreviewResponse".to_string()), - _ => return std::result::Result::Err("Unexpected key while parsing TransactionPreviewResponse".to_string()) - } - } - - // Get the next key - key_result = string_iter.next(); - } - - // Use the intermediate representation to return the struct - std::result::Result::Ok(TransactionPreviewResponse { - transaction_status: intermediate_rep.transaction_status.into_iter().next().ok_or("transaction_status missing in TransactionPreviewResponse".to_string())?, - transaction_fee: intermediate_rep.transaction_fee.into_iter().next().ok_or("transaction_fee missing in TransactionPreviewResponse".to_string())?, - logs: intermediate_rep.logs.into_iter().next().ok_or("logs missing in TransactionPreviewResponse".to_string())?, - new_package_addresses: intermediate_rep.new_package_addresses.into_iter().next().ok_or("new_package_addresses missing in TransactionPreviewResponse".to_string())?, - new_component_addresses: intermediate_rep.new_component_addresses.into_iter().next().ok_or("new_component_addresses missing in TransactionPreviewResponse".to_string())?, - new_resource_addresses: intermediate_rep.new_resource_addresses.into_iter().next().ok_or("new_resource_addresses missing in TransactionPreviewResponse".to_string())?, - }) - } -} - -// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue - - -impl std::convert::TryFrom> for hyper::header::HeaderValue { - type Error = String; - - fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { - let hdr_value = hdr_value.to_string(); - match hyper::header::HeaderValue::from_str(&hdr_value) { - std::result::Result::Ok(value) => std::result::Result::Ok(value), - std::result::Result::Err(e) => std::result::Result::Err( - format!("Invalid header value for TransactionPreviewResponse - value: {} is invalid {}", - hdr_value, e)) - } - } -} - - -impl std::convert::TryFrom for header::IntoHeaderValue { - type Error = String; - - fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { - match hdr_value.to_str() { - std::result::Result::Ok(value) => { - match ::from_str(value) { - std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), - std::result::Result::Err(err) => std::result::Result::Err( - format!("Unable to convert header value '{}' into TransactionPreviewResponse - {}", - value, err)) - } - }, - std::result::Result::Err(e) => std::result::Result::Err( - format!("Unable to convert header: {:?} to string: {}", - hdr_value, e)) - } - } -} - - -#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] -#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] -pub struct TransactionPreviewResponseLogsInner { - #[serde(rename = "level")] - pub level: String, - - #[serde(rename = "message")] - pub message: String, - -} - -impl TransactionPreviewResponseLogsInner { - pub fn new(level: String, message: String, ) -> TransactionPreviewResponseLogsInner { - TransactionPreviewResponseLogsInner { - level: level, - message: message, - } - } -} - -/// Converts the TransactionPreviewResponseLogsInner value to the Query Parameters representation (style=form, explode=false) -/// specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde serializer -impl std::string::ToString for TransactionPreviewResponseLogsInner { - fn to_string(&self) -> String { - let mut params: Vec = vec![]; - - params.push("level".to_string()); - params.push(self.level.to_string()); - - - params.push("message".to_string()); - params.push(self.message.to_string()); - - params.join(",").to_string() - } -} - -/// Converts Query Parameters representation (style=form, explode=false) to a TransactionPreviewResponseLogsInner value -/// as specified in https://swagger.io/docs/specification/serialization/ -/// Should be implemented in a serde deserializer -impl std::str::FromStr for TransactionPreviewResponseLogsInner { - type Err = String; - - fn from_str(s: &str) -> std::result::Result { - #[derive(Default)] - // An intermediate representation of the struct to use for parsing. - struct IntermediateRep { - pub level: Vec, - pub message: Vec, - } - - let mut intermediate_rep = IntermediateRep::default(); - - // Parse into intermediate representation - let mut string_iter = s.split(',').into_iter(); - let mut key_result = string_iter.next(); - - while key_result.is_some() { - let val = match string_iter.next() { - Some(x) => x, - None => return std::result::Result::Err("Missing value while parsing TransactionPreviewResponseLogsInner".to_string()) - }; - - if let Some(key) = key_result { - match key { - "level" => intermediate_rep.level.push(::from_str(val).map_err(|x| format!("{}", x))?), - "message" => intermediate_rep.message.push(::from_str(val).map_err(|x| format!("{}", x))?), - _ => return std::result::Result::Err("Unexpected key while parsing TransactionPreviewResponseLogsInner".to_string()) - } - } - - // Get the next key - key_result = string_iter.next(); - } - - // Use the intermediate representation to return the struct - std::result::Result::Ok(TransactionPreviewResponseLogsInner { - level: intermediate_rep.level.into_iter().next().ok_or("level missing in TransactionPreviewResponseLogsInner".to_string())?, - message: intermediate_rep.message.into_iter().next().ok_or("message missing in TransactionPreviewResponseLogsInner".to_string())?, - }) - } -} - -// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue - - -impl std::convert::TryFrom> for hyper::header::HeaderValue { - type Error = String; - - fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { - let hdr_value = hdr_value.to_string(); - match hyper::header::HeaderValue::from_str(&hdr_value) { - std::result::Result::Ok(value) => std::result::Result::Ok(value), - std::result::Result::Err(e) => std::result::Result::Err( - format!("Invalid header value for TransactionPreviewResponseLogsInner - value: {} is invalid {}", - hdr_value, e)) - } - } -} - - -impl std::convert::TryFrom for header::IntoHeaderValue { - type Error = String; - - fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { - match hdr_value.to_str() { - std::result::Result::Ok(value) => { - match ::from_str(value) { - std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), - std::result::Result::Err(err) => std::result::Result::Err( - format!("Unable to convert header value '{}' into TransactionPreviewResponseLogsInner - {}", - value, err)) - } - }, - std::result::Result::Err(e) => std::result::Result::Err( - format!("Unable to convert header: {:?} to string: {}", - hdr_value, e)) - } - } -} + /// The nonce value to use for execution. A decimal 64-bit unsigned integer. + #[serde(rename = "nonce")] + pub nonce: String, + /// A list of public keys to be used as transaction signers, in a compressed format, hex encoded. + #[serde(rename = "signer_public_keys")] + pub signer_public_keys: Vec, -#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] -#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] -pub struct TransactionStatus { - #[serde(rename = "type")] - pub type_: String, + #[serde(rename = "flags")] + pub flags: models::TransactionPreviewRequestFlags, } -impl TransactionStatus { - pub fn new(type_: String, ) -> TransactionStatus { - TransactionStatus { - type_: type_, +impl TransactionPreviewRequest { + pub fn new(network_identifier: models::NetworkIdentifier, manifest: String, cost_unit_limit: String, tip_percentage: String, nonce: String, signer_public_keys: Vec, flags: models::TransactionPreviewRequestFlags, ) -> TransactionPreviewRequest { + TransactionPreviewRequest { + network_identifier: network_identifier, + manifest: manifest, + cost_unit_limit: cost_unit_limit, + tip_percentage: tip_percentage, + nonce: nonce, + signer_public_keys: signer_public_keys, + flags: flags, } } } -/// Converts the TransactionStatus value to the Query Parameters representation (style=form, explode=false) +/// Converts the TransactionPreviewRequest value to the Query Parameters representation (style=form, explode=false) /// specified in https://swagger.io/docs/specification/serialization/ /// Should be implemented in a serde serializer -impl std::string::ToString for TransactionStatus { +impl std::string::ToString for TransactionPreviewRequest { fn to_string(&self) -> String { let mut params: Vec = vec![]; + // Skipping network_identifier in query parameter serialization + + + params.push("manifest".to_string()); + params.push(self.manifest.to_string()); + + + params.push("cost_unit_limit".to_string()); + params.push(self.cost_unit_limit.to_string()); + + + params.push("tip_percentage".to_string()); + params.push(self.tip_percentage.to_string()); + - params.push("type".to_string()); - params.push(self.type_.to_string()); + params.push("nonce".to_string()); + params.push(self.nonce.to_string()); + + + params.push("signer_public_keys".to_string()); + params.push(self.signer_public_keys.iter().map(|x| x.to_string()).collect::>().join(",").to_string()); + + // Skipping flags in query parameter serialization params.join(",").to_string() } } -/// Converts Query Parameters representation (style=form, explode=false) to a TransactionStatus value +/// Converts Query Parameters representation (style=form, explode=false) to a TransactionPreviewRequest value /// as specified in https://swagger.io/docs/specification/serialization/ /// Should be implemented in a serde deserializer -impl std::str::FromStr for TransactionStatus { +impl std::str::FromStr for TransactionPreviewRequest { type Err = String; fn from_str(s: &str) -> std::result::Result { #[derive(Default)] // An intermediate representation of the struct to use for parsing. struct IntermediateRep { - pub type_: Vec, + pub network_identifier: Vec, + pub manifest: Vec, + pub cost_unit_limit: Vec, + pub tip_percentage: Vec, + pub nonce: Vec, + pub signer_public_keys: Vec>, + pub flags: Vec, } let mut intermediate_rep = IntermediateRep::default(); @@ -3152,13 +1937,19 @@ impl std::str::FromStr for TransactionStatus { while key_result.is_some() { let val = match string_iter.next() { Some(x) => x, - None => return std::result::Result::Err("Missing value while parsing TransactionStatus".to_string()) + None => return std::result::Result::Err("Missing value while parsing TransactionPreviewRequest".to_string()) }; if let Some(key) = key_result { match key { - "type" => intermediate_rep.type_.push(::from_str(val).map_err(|x| format!("{}", x))?), - _ => return std::result::Result::Err("Unexpected key while parsing TransactionStatus".to_string()) + "network_identifier" => intermediate_rep.network_identifier.push(::from_str(val).map_err(|x| format!("{}", x))?), + "manifest" => intermediate_rep.manifest.push(::from_str(val).map_err(|x| format!("{}", x))?), + "cost_unit_limit" => intermediate_rep.cost_unit_limit.push(::from_str(val).map_err(|x| format!("{}", x))?), + "tip_percentage" => intermediate_rep.tip_percentage.push(::from_str(val).map_err(|x| format!("{}", x))?), + "nonce" => intermediate_rep.nonce.push(::from_str(val).map_err(|x| format!("{}", x))?), + "signer_public_keys" => return std::result::Result::Err("Parsing a container in this style is not supported in TransactionPreviewRequest".to_string()), + "flags" => intermediate_rep.flags.push(::from_str(val).map_err(|x| format!("{}", x))?), + _ => return std::result::Result::Err("Unexpected key while parsing TransactionPreviewRequest".to_string()) } } @@ -3167,40 +1958,46 @@ impl std::str::FromStr for TransactionStatus { } // Use the intermediate representation to return the struct - std::result::Result::Ok(TransactionStatus { - type_: intermediate_rep.type_.into_iter().next().ok_or("type missing in TransactionStatus".to_string())?, + std::result::Result::Ok(TransactionPreviewRequest { + network_identifier: intermediate_rep.network_identifier.into_iter().next().ok_or("network_identifier missing in TransactionPreviewRequest".to_string())?, + manifest: intermediate_rep.manifest.into_iter().next().ok_or("manifest missing in TransactionPreviewRequest".to_string())?, + cost_unit_limit: intermediate_rep.cost_unit_limit.into_iter().next().ok_or("cost_unit_limit missing in TransactionPreviewRequest".to_string())?, + tip_percentage: intermediate_rep.tip_percentage.into_iter().next().ok_or("tip_percentage missing in TransactionPreviewRequest".to_string())?, + nonce: intermediate_rep.nonce.into_iter().next().ok_or("nonce missing in TransactionPreviewRequest".to_string())?, + signer_public_keys: intermediate_rep.signer_public_keys.into_iter().next().ok_or("signer_public_keys missing in TransactionPreviewRequest".to_string())?, + flags: intermediate_rep.flags.into_iter().next().ok_or("flags missing in TransactionPreviewRequest".to_string())?, }) } } -// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue +// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue -impl std::convert::TryFrom> for hyper::header::HeaderValue { +impl std::convert::TryFrom> for hyper::header::HeaderValue { type Error = String; - fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { let hdr_value = hdr_value.to_string(); match hyper::header::HeaderValue::from_str(&hdr_value) { std::result::Result::Ok(value) => std::result::Result::Ok(value), std::result::Result::Err(e) => std::result::Result::Err( - format!("Invalid header value for TransactionStatus - value: {} is invalid {}", + format!("Invalid header value for TransactionPreviewRequest - value: {} is invalid {}", hdr_value, e)) } } } -impl std::convert::TryFrom for header::IntoHeaderValue { +impl std::convert::TryFrom for header::IntoHeaderValue { type Error = String; fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { match hdr_value.to_str() { std::result::Result::Ok(value) => { - match ::from_str(value) { + match ::from_str(value) { std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), std::result::Result::Err(err) => std::result::Result::Err( - format!("Unable to convert header value '{}' into TransactionStatus - {}", + format!("Unable to convert header value '{}' into TransactionPreviewRequest - {}", value, err)) } }, @@ -3214,54 +2011,45 @@ impl std::convert::TryFrom for header::IntoHeaderVal #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] #[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] -pub struct TransactionStatusFailed { - #[serde(rename = "type")] - pub type_: String, - - #[serde(rename = "message")] - pub message: String, +pub struct TransactionPreviewRequestFlags { + #[serde(rename = "unlimited_loan")] + pub unlimited_loan: bool, } -impl TransactionStatusFailed { - pub fn new(type_: String, message: String, ) -> TransactionStatusFailed { - TransactionStatusFailed { - type_: type_, - message: message, +impl TransactionPreviewRequestFlags { + pub fn new(unlimited_loan: bool, ) -> TransactionPreviewRequestFlags { + TransactionPreviewRequestFlags { + unlimited_loan: unlimited_loan, } } } -/// Converts the TransactionStatusFailed value to the Query Parameters representation (style=form, explode=false) +/// Converts the TransactionPreviewRequestFlags value to the Query Parameters representation (style=form, explode=false) /// specified in https://swagger.io/docs/specification/serialization/ /// Should be implemented in a serde serializer -impl std::string::ToString for TransactionStatusFailed { +impl std::string::ToString for TransactionPreviewRequestFlags { fn to_string(&self) -> String { let mut params: Vec = vec![]; - params.push("type".to_string()); - params.push(self.type_.to_string()); - - - params.push("message".to_string()); - params.push(self.message.to_string()); + params.push("unlimited_loan".to_string()); + params.push(self.unlimited_loan.to_string()); params.join(",").to_string() } } -/// Converts Query Parameters representation (style=form, explode=false) to a TransactionStatusFailed value +/// Converts Query Parameters representation (style=form, explode=false) to a TransactionPreviewRequestFlags value /// as specified in https://swagger.io/docs/specification/serialization/ /// Should be implemented in a serde deserializer -impl std::str::FromStr for TransactionStatusFailed { +impl std::str::FromStr for TransactionPreviewRequestFlags { type Err = String; fn from_str(s: &str) -> std::result::Result { #[derive(Default)] // An intermediate representation of the struct to use for parsing. struct IntermediateRep { - pub type_: Vec, - pub message: Vec, + pub unlimited_loan: Vec, } let mut intermediate_rep = IntermediateRep::default(); @@ -3273,14 +2061,13 @@ impl std::str::FromStr for TransactionStatusFailed { while key_result.is_some() { let val = match string_iter.next() { Some(x) => x, - None => return std::result::Result::Err("Missing value while parsing TransactionStatusFailed".to_string()) + None => return std::result::Result::Err("Missing value while parsing TransactionPreviewRequestFlags".to_string()) }; if let Some(key) = key_result { match key { - "type" => intermediate_rep.type_.push(::from_str(val).map_err(|x| format!("{}", x))?), - "message" => intermediate_rep.message.push(::from_str(val).map_err(|x| format!("{}", x))?), - _ => return std::result::Result::Err("Unexpected key while parsing TransactionStatusFailed".to_string()) + "unlimited_loan" => intermediate_rep.unlimited_loan.push(::from_str(val).map_err(|x| format!("{}", x))?), + _ => return std::result::Result::Err("Unexpected key while parsing TransactionPreviewRequestFlags".to_string()) } } @@ -3289,41 +2076,40 @@ impl std::str::FromStr for TransactionStatusFailed { } // Use the intermediate representation to return the struct - std::result::Result::Ok(TransactionStatusFailed { - type_: intermediate_rep.type_.into_iter().next().ok_or("type missing in TransactionStatusFailed".to_string())?, - message: intermediate_rep.message.into_iter().next().ok_or("message missing in TransactionStatusFailed".to_string())?, + std::result::Result::Ok(TransactionPreviewRequestFlags { + unlimited_loan: intermediate_rep.unlimited_loan.into_iter().next().ok_or("unlimited_loan missing in TransactionPreviewRequestFlags".to_string())?, }) } } -// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue +// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue -impl std::convert::TryFrom> for hyper::header::HeaderValue { +impl std::convert::TryFrom> for hyper::header::HeaderValue { type Error = String; - fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { let hdr_value = hdr_value.to_string(); match hyper::header::HeaderValue::from_str(&hdr_value) { std::result::Result::Ok(value) => std::result::Result::Ok(value), std::result::Result::Err(e) => std::result::Result::Err( - format!("Invalid header value for TransactionStatusFailed - value: {} is invalid {}", + format!("Invalid header value for TransactionPreviewRequestFlags - value: {} is invalid {}", hdr_value, e)) } } } -impl std::convert::TryFrom for header::IntoHeaderValue { +impl std::convert::TryFrom for header::IntoHeaderValue { type Error = String; fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { match hdr_value.to_str() { std::result::Result::Ok(value) => { - match ::from_str(value) { + match ::from_str(value) { std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), std::result::Result::Err(err) => std::result::Result::Err( - format!("Unable to convert header value '{}' into TransactionStatusFailed - {}", + format!("Unable to convert header value '{}' into TransactionPreviewRequestFlags - {}", value, err)) } }, @@ -3337,45 +2123,111 @@ impl std::convert::TryFrom for header::IntoHeaderVal #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] #[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] -pub struct TransactionStatusRejected { - #[serde(rename = "type")] - pub type_: String, +pub struct TransactionPreviewResponse { + #[serde(rename = "transaction_status")] + pub transaction_status: models::TransactionStatus, + + #[serde(rename = "transaction_fee")] + pub transaction_fee: models::FeeSummary, + + #[serde(rename = "logs")] + pub logs: Vec, + + /// A list of new package addresses, hex-encoded. + #[serde(rename = "new_package_addresses")] + pub new_package_addresses: Vec, + + /// A list of new component addresses, hex-encoded. + #[serde(rename = "new_component_addresses")] + pub new_component_addresses: Vec, + + /// A list of new resource addresses, hex-encoded. + #[serde(rename = "new_resource_addresses")] + pub new_resource_addresses: Vec, + + #[serde(rename = "output")] + #[serde(skip_serializing_if="Option::is_none")] + pub output: Option>, + + #[serde(rename = "error_message")] + #[serde(skip_serializing_if="Option::is_none")] + pub error_message: Option, } -impl TransactionStatusRejected { - pub fn new(type_: String, ) -> TransactionStatusRejected { - TransactionStatusRejected { - type_: type_, +impl TransactionPreviewResponse { + pub fn new(transaction_status: models::TransactionStatus, transaction_fee: models::FeeSummary, logs: Vec, new_package_addresses: Vec, new_component_addresses: Vec, new_resource_addresses: Vec, ) -> TransactionPreviewResponse { + TransactionPreviewResponse { + transaction_status: transaction_status, + transaction_fee: transaction_fee, + logs: logs, + new_package_addresses: new_package_addresses, + new_component_addresses: new_component_addresses, + new_resource_addresses: new_resource_addresses, + output: None, + error_message: None, } } } -/// Converts the TransactionStatusRejected value to the Query Parameters representation (style=form, explode=false) +/// Converts the TransactionPreviewResponse value to the Query Parameters representation (style=form, explode=false) /// specified in https://swagger.io/docs/specification/serialization/ /// Should be implemented in a serde serializer -impl std::string::ToString for TransactionStatusRejected { +impl std::string::ToString for TransactionPreviewResponse { fn to_string(&self) -> String { let mut params: Vec = vec![]; + // Skipping transaction_status in query parameter serialization + + // Skipping transaction_fee in query parameter serialization + + // Skipping logs in query parameter serialization + + + params.push("new_package_addresses".to_string()); + params.push(self.new_package_addresses.iter().map(|x| x.to_string()).collect::>().join(",").to_string()); + + + params.push("new_component_addresses".to_string()); + params.push(self.new_component_addresses.iter().map(|x| x.to_string()).collect::>().join(",").to_string()); + + + params.push("new_resource_addresses".to_string()); + params.push(self.new_resource_addresses.iter().map(|x| x.to_string()).collect::>().join(",").to_string()); + - params.push("type".to_string()); - params.push(self.type_.to_string()); + if let Some(ref output) = self.output { + params.push("output".to_string()); + params.push(output.iter().map(|x| x.to_string()).collect::>().join(",").to_string()); + } + + + if let Some(ref error_message) = self.error_message { + params.push("error_message".to_string()); + params.push(error_message.to_string()); + } params.join(",").to_string() } } -/// Converts Query Parameters representation (style=form, explode=false) to a TransactionStatusRejected value +/// Converts Query Parameters representation (style=form, explode=false) to a TransactionPreviewResponse value /// as specified in https://swagger.io/docs/specification/serialization/ /// Should be implemented in a serde deserializer -impl std::str::FromStr for TransactionStatusRejected { +impl std::str::FromStr for TransactionPreviewResponse { type Err = String; fn from_str(s: &str) -> std::result::Result { #[derive(Default)] // An intermediate representation of the struct to use for parsing. struct IntermediateRep { - pub type_: Vec, + pub transaction_status: Vec, + pub transaction_fee: Vec, + pub logs: Vec>, + pub new_package_addresses: Vec>, + pub new_component_addresses: Vec>, + pub new_resource_addresses: Vec>, + pub output: Vec>, + pub error_message: Vec, } let mut intermediate_rep = IntermediateRep::default(); @@ -3387,13 +2239,20 @@ impl std::str::FromStr for TransactionStatusRejected { while key_result.is_some() { let val = match string_iter.next() { Some(x) => x, - None => return std::result::Result::Err("Missing value while parsing TransactionStatusRejected".to_string()) + None => return std::result::Result::Err("Missing value while parsing TransactionPreviewResponse".to_string()) }; if let Some(key) = key_result { match key { - "type" => intermediate_rep.type_.push(::from_str(val).map_err(|x| format!("{}", x))?), - _ => return std::result::Result::Err("Unexpected key while parsing TransactionStatusRejected".to_string()) + "transaction_status" => intermediate_rep.transaction_status.push(::from_str(val).map_err(|x| format!("{}", x))?), + "transaction_fee" => intermediate_rep.transaction_fee.push(::from_str(val).map_err(|x| format!("{}", x))?), + "logs" => return std::result::Result::Err("Parsing a container in this style is not supported in TransactionPreviewResponse".to_string()), + "new_package_addresses" => return std::result::Result::Err("Parsing a container in this style is not supported in TransactionPreviewResponse".to_string()), + "new_component_addresses" => return std::result::Result::Err("Parsing a container in this style is not supported in TransactionPreviewResponse".to_string()), + "new_resource_addresses" => return std::result::Result::Err("Parsing a container in this style is not supported in TransactionPreviewResponse".to_string()), + "output" => return std::result::Result::Err("Parsing a container in this style is not supported in TransactionPreviewResponse".to_string()), + "error_message" => intermediate_rep.error_message.push(::from_str(val).map_err(|x| format!("{}", x))?), + _ => return std::result::Result::Err("Unexpected key while parsing TransactionPreviewResponse".to_string()) } } @@ -3402,40 +2261,47 @@ impl std::str::FromStr for TransactionStatusRejected { } // Use the intermediate representation to return the struct - std::result::Result::Ok(TransactionStatusRejected { - type_: intermediate_rep.type_.into_iter().next().ok_or("type missing in TransactionStatusRejected".to_string())?, + std::result::Result::Ok(TransactionPreviewResponse { + transaction_status: intermediate_rep.transaction_status.into_iter().next().ok_or("transaction_status missing in TransactionPreviewResponse".to_string())?, + transaction_fee: intermediate_rep.transaction_fee.into_iter().next().ok_or("transaction_fee missing in TransactionPreviewResponse".to_string())?, + logs: intermediate_rep.logs.into_iter().next().ok_or("logs missing in TransactionPreviewResponse".to_string())?, + new_package_addresses: intermediate_rep.new_package_addresses.into_iter().next().ok_or("new_package_addresses missing in TransactionPreviewResponse".to_string())?, + new_component_addresses: intermediate_rep.new_component_addresses.into_iter().next().ok_or("new_component_addresses missing in TransactionPreviewResponse".to_string())?, + new_resource_addresses: intermediate_rep.new_resource_addresses.into_iter().next().ok_or("new_resource_addresses missing in TransactionPreviewResponse".to_string())?, + output: intermediate_rep.output.into_iter().next(), + error_message: intermediate_rep.error_message.into_iter().next(), }) } } -// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue +// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue -impl std::convert::TryFrom> for hyper::header::HeaderValue { +impl std::convert::TryFrom> for hyper::header::HeaderValue { type Error = String; - fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { let hdr_value = hdr_value.to_string(); match hyper::header::HeaderValue::from_str(&hdr_value) { std::result::Result::Ok(value) => std::result::Result::Ok(value), std::result::Result::Err(e) => std::result::Result::Err( - format!("Invalid header value for TransactionStatusRejected - value: {} is invalid {}", + format!("Invalid header value for TransactionPreviewResponse - value: {} is invalid {}", hdr_value, e)) } } } -impl std::convert::TryFrom for header::IntoHeaderValue { +impl std::convert::TryFrom for header::IntoHeaderValue { type Error = String; fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { match hdr_value.to_str() { std::result::Result::Ok(value) => { - match ::from_str(value) { + match ::from_str(value) { std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), std::result::Result::Err(err) => std::result::Result::Err( - format!("Unable to convert header value '{}' into TransactionStatusRejected - {}", + format!("Unable to convert header value '{}' into TransactionPreviewResponse - {}", value, err)) } }, @@ -3449,54 +2315,54 @@ impl std::convert::TryFrom for header::IntoHeaderVal #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] #[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] -pub struct TransactionStatusSucceeded { - #[serde(rename = "type")] - pub type_: String, +pub struct TransactionPreviewResponseLogsInner { + #[serde(rename = "level")] + pub level: String, - #[serde(rename = "output")] - pub output: Vec, + #[serde(rename = "message")] + pub message: String, } -impl TransactionStatusSucceeded { - pub fn new(type_: String, output: Vec, ) -> TransactionStatusSucceeded { - TransactionStatusSucceeded { - type_: type_, - output: output, +impl TransactionPreviewResponseLogsInner { + pub fn new(level: String, message: String, ) -> TransactionPreviewResponseLogsInner { + TransactionPreviewResponseLogsInner { + level: level, + message: message, } } } -/// Converts the TransactionStatusSucceeded value to the Query Parameters representation (style=form, explode=false) +/// Converts the TransactionPreviewResponseLogsInner value to the Query Parameters representation (style=form, explode=false) /// specified in https://swagger.io/docs/specification/serialization/ /// Should be implemented in a serde serializer -impl std::string::ToString for TransactionStatusSucceeded { +impl std::string::ToString for TransactionPreviewResponseLogsInner { fn to_string(&self) -> String { let mut params: Vec = vec![]; - params.push("type".to_string()); - params.push(self.type_.to_string()); + params.push("level".to_string()); + params.push(self.level.to_string()); - params.push("output".to_string()); - params.push(self.output.iter().map(|x| x.to_string()).collect::>().join(",").to_string()); + params.push("message".to_string()); + params.push(self.message.to_string()); params.join(",").to_string() } } -/// Converts Query Parameters representation (style=form, explode=false) to a TransactionStatusSucceeded value +/// Converts Query Parameters representation (style=form, explode=false) to a TransactionPreviewResponseLogsInner value /// as specified in https://swagger.io/docs/specification/serialization/ /// Should be implemented in a serde deserializer -impl std::str::FromStr for TransactionStatusSucceeded { +impl std::str::FromStr for TransactionPreviewResponseLogsInner { type Err = String; fn from_str(s: &str) -> std::result::Result { #[derive(Default)] // An intermediate representation of the struct to use for parsing. struct IntermediateRep { - pub type_: Vec, - pub output: Vec>, + pub level: Vec, + pub message: Vec, } let mut intermediate_rep = IntermediateRep::default(); @@ -3508,14 +2374,14 @@ impl std::str::FromStr for TransactionStatusSucceeded { while key_result.is_some() { let val = match string_iter.next() { Some(x) => x, - None => return std::result::Result::Err("Missing value while parsing TransactionStatusSucceeded".to_string()) + None => return std::result::Result::Err("Missing value while parsing TransactionPreviewResponseLogsInner".to_string()) }; if let Some(key) = key_result { match key { - "type" => intermediate_rep.type_.push(::from_str(val).map_err(|x| format!("{}", x))?), - "output" => return std::result::Result::Err("Parsing a container in this style is not supported in TransactionStatusSucceeded".to_string()), - _ => return std::result::Result::Err("Unexpected key while parsing TransactionStatusSucceeded".to_string()) + "level" => intermediate_rep.level.push(::from_str(val).map_err(|x| format!("{}", x))?), + "message" => intermediate_rep.message.push(::from_str(val).map_err(|x| format!("{}", x))?), + _ => return std::result::Result::Err("Unexpected key while parsing TransactionPreviewResponseLogsInner".to_string()) } } @@ -3524,41 +2390,41 @@ impl std::str::FromStr for TransactionStatusSucceeded { } // Use the intermediate representation to return the struct - std::result::Result::Ok(TransactionStatusSucceeded { - type_: intermediate_rep.type_.into_iter().next().ok_or("type missing in TransactionStatusSucceeded".to_string())?, - output: intermediate_rep.output.into_iter().next().ok_or("output missing in TransactionStatusSucceeded".to_string())?, + std::result::Result::Ok(TransactionPreviewResponseLogsInner { + level: intermediate_rep.level.into_iter().next().ok_or("level missing in TransactionPreviewResponseLogsInner".to_string())?, + message: intermediate_rep.message.into_iter().next().ok_or("message missing in TransactionPreviewResponseLogsInner".to_string())?, }) } } -// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue +// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue -impl std::convert::TryFrom> for hyper::header::HeaderValue { +impl std::convert::TryFrom> for hyper::header::HeaderValue { type Error = String; - fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { let hdr_value = hdr_value.to_string(); match hyper::header::HeaderValue::from_str(&hdr_value) { std::result::Result::Ok(value) => std::result::Result::Ok(value), std::result::Result::Err(e) => std::result::Result::Err( - format!("Invalid header value for TransactionStatusSucceeded - value: {} is invalid {}", + format!("Invalid header value for TransactionPreviewResponseLogsInner - value: {} is invalid {}", hdr_value, e)) } } } -impl std::convert::TryFrom for header::IntoHeaderValue { +impl std::convert::TryFrom for header::IntoHeaderValue { type Error = String; fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { match hdr_value.to_str() { std::result::Result::Ok(value) => { - match ::from_str(value) { + match ::from_str(value) { std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), std::result::Result::Err(err) => std::result::Result::Err( - format!("Unable to convert header value '{}' into TransactionStatusSucceeded - {}", + format!("Unable to convert header value '{}' into TransactionPreviewResponseLogsInner - {}", value, err)) } }, @@ -3570,47 +2436,79 @@ impl std::convert::TryFrom for header::IntoHeaderVal } +/// The transaction execution receipt #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] #[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] -pub struct TransactionStatusSucceededAllOf { +pub struct TransactionReceipt { + #[serde(rename = "status")] + pub status: models::TransactionStatus, + + #[serde(rename = "fee_summary")] + pub fee_summary: models::FeeSummary, + + /// The engine return data (only present if status is succeeded) #[serde(rename = "output")] - pub output: Vec, + #[serde(skip_serializing_if="Option::is_none")] + pub output: Option>, + + /// Error message (only present if status is failed or rejected) + #[serde(rename = "error_message")] + #[serde(skip_serializing_if="Option::is_none")] + pub error_message: Option, } -impl TransactionStatusSucceededAllOf { - pub fn new(output: Vec, ) -> TransactionStatusSucceededAllOf { - TransactionStatusSucceededAllOf { - output: output, +impl TransactionReceipt { + pub fn new(status: models::TransactionStatus, fee_summary: models::FeeSummary, ) -> TransactionReceipt { + TransactionReceipt { + status: status, + fee_summary: fee_summary, + output: None, + error_message: None, } } } -/// Converts the TransactionStatusSucceededAllOf value to the Query Parameters representation (style=form, explode=false) +/// Converts the TransactionReceipt value to the Query Parameters representation (style=form, explode=false) /// specified in https://swagger.io/docs/specification/serialization/ /// Should be implemented in a serde serializer -impl std::string::ToString for TransactionStatusSucceededAllOf { +impl std::string::ToString for TransactionReceipt { fn to_string(&self) -> String { let mut params: Vec = vec![]; + // Skipping status in query parameter serialization + + // Skipping fee_summary in query parameter serialization + + + if let Some(ref output) = self.output { + params.push("output".to_string()); + params.push(output.iter().map(|x| x.to_string()).collect::>().join(",").to_string()); + } - params.push("output".to_string()); - params.push(self.output.iter().map(|x| x.to_string()).collect::>().join(",").to_string()); + + if let Some(ref error_message) = self.error_message { + params.push("error_message".to_string()); + params.push(error_message.to_string()); + } params.join(",").to_string() } } -/// Converts Query Parameters representation (style=form, explode=false) to a TransactionStatusSucceededAllOf value +/// Converts Query Parameters representation (style=form, explode=false) to a TransactionReceipt value /// as specified in https://swagger.io/docs/specification/serialization/ /// Should be implemented in a serde deserializer -impl std::str::FromStr for TransactionStatusSucceededAllOf { +impl std::str::FromStr for TransactionReceipt { type Err = String; fn from_str(s: &str) -> std::result::Result { #[derive(Default)] // An intermediate representation of the struct to use for parsing. struct IntermediateRep { + pub status: Vec, + pub fee_summary: Vec, pub output: Vec>, + pub error_message: Vec, } let mut intermediate_rep = IntermediateRep::default(); @@ -3622,13 +2520,16 @@ impl std::str::FromStr for TransactionStatusSucceededAllOf { while key_result.is_some() { let val = match string_iter.next() { Some(x) => x, - None => return std::result::Result::Err("Missing value while parsing TransactionStatusSucceededAllOf".to_string()) + None => return std::result::Result::Err("Missing value while parsing TransactionReceipt".to_string()) }; if let Some(key) = key_result { match key { - "output" => return std::result::Result::Err("Parsing a container in this style is not supported in TransactionStatusSucceededAllOf".to_string()), - _ => return std::result::Result::Err("Unexpected key while parsing TransactionStatusSucceededAllOf".to_string()) + "status" => intermediate_rep.status.push(::from_str(val).map_err(|x| format!("{}", x))?), + "fee_summary" => intermediate_rep.fee_summary.push(::from_str(val).map_err(|x| format!("{}", x))?), + "output" => return std::result::Result::Err("Parsing a container in this style is not supported in TransactionReceipt".to_string()), + "error_message" => intermediate_rep.error_message.push(::from_str(val).map_err(|x| format!("{}", x))?), + _ => return std::result::Result::Err("Unexpected key while parsing TransactionReceipt".to_string()) } } @@ -3637,40 +2538,43 @@ impl std::str::FromStr for TransactionStatusSucceededAllOf { } // Use the intermediate representation to return the struct - std::result::Result::Ok(TransactionStatusSucceededAllOf { - output: intermediate_rep.output.into_iter().next().ok_or("output missing in TransactionStatusSucceededAllOf".to_string())?, + std::result::Result::Ok(TransactionReceipt { + status: intermediate_rep.status.into_iter().next().ok_or("status missing in TransactionReceipt".to_string())?, + fee_summary: intermediate_rep.fee_summary.into_iter().next().ok_or("fee_summary missing in TransactionReceipt".to_string())?, + output: intermediate_rep.output.into_iter().next(), + error_message: intermediate_rep.error_message.into_iter().next(), }) } } -// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue +// Methods for converting between header::IntoHeaderValue and hyper::header::HeaderValue -impl std::convert::TryFrom> for hyper::header::HeaderValue { +impl std::convert::TryFrom> for hyper::header::HeaderValue { type Error = String; - fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { let hdr_value = hdr_value.to_string(); match hyper::header::HeaderValue::from_str(&hdr_value) { std::result::Result::Ok(value) => std::result::Result::Ok(value), std::result::Result::Err(e) => std::result::Result::Err( - format!("Invalid header value for TransactionStatusSucceededAllOf - value: {} is invalid {}", + format!("Invalid header value for TransactionReceipt - value: {} is invalid {}", hdr_value, e)) } } } -impl std::convert::TryFrom for header::IntoHeaderValue { +impl std::convert::TryFrom for header::IntoHeaderValue { type Error = String; fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result { match hdr_value.to_str() { std::result::Result::Ok(value) => { - match ::from_str(value) { + match ::from_str(value) { std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), std::result::Result::Err(err) => std::result::Result::Err( - format!("Unable to convert header value '{}' into TransactionStatusSucceededAllOf - {}", + format!("Unable to convert header value '{}' into TransactionReceipt - {}", value, err)) } }, @@ -3682,6 +2586,46 @@ impl std::convert::TryFrom for header::IntoHeaderVal } +/// The status of the transaction +/// Enumeration of values. +/// Since this enum's variants do not hold data, we can easily define them them as `#[repr(C)]` +/// which helps with FFI. +#[allow(non_camel_case_types)] +#[repr(C)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, serde::Serialize, serde::Deserialize)] +#[cfg_attr(feature = "conversion", derive(frunk_enum_derive::LabelledGenericEnum))] +pub enum TransactionStatus { + #[serde(rename = "succeeded")] + SUCCEEDED, + #[serde(rename = "failed")] + FAILED, + #[serde(rename = "rejected")] + REJECTED, +} + +impl std::fmt::Display for TransactionStatus { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match *self { + TransactionStatus::SUCCEEDED => write!(f, "succeeded"), + TransactionStatus::FAILED => write!(f, "failed"), + TransactionStatus::REJECTED => write!(f, "rejected"), + } + } +} + +impl std::str::FromStr for TransactionStatus { + type Err = String; + + fn from_str(s: &str) -> std::result::Result { + match s { + "succeeded" => std::result::Result::Ok(TransactionStatus::SUCCEEDED), + "failed" => std::result::Result::Ok(TransactionStatus::FAILED), + "rejected" => std::result::Result::Ok(TransactionStatus::REJECTED), + _ => std::result::Result::Err(format!("Value not valid: {}", s)), + } + } +} + #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] #[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] pub struct TransactionSubmitRequest { diff --git a/state-manager/core-api-server/src/core_api/generated/server.rs b/core-rust/core-api-server/src/core_api/generated/server.rs similarity index 68% rename from state-manager/core-api-server/src/core_api/generated/server.rs rename to core-rust/core-api-server/src/core_api/generated/server.rs index 7a460eb267..e42de67de5 100644 --- a/state-manager/core-api-server/src/core_api/generated/server.rs +++ b/core-rust/core-api-server/src/core_api/generated/server.rs @@ -24,7 +24,8 @@ type ServiceFuture = BoxFuture<'static, Result, crate::core_api:: use crate::core_api::generated::{Api, StatusNetworkConfigurationPostResponse, TransactionPreviewPostResponse, - TransactionSubmitPostResponse + TransactionSubmitPostResponse, + TransactionsPostResponse }; mod paths { @@ -34,13 +35,15 @@ mod paths { pub static ref GLOBAL_REGEX_SET: regex::RegexSet = regex::RegexSet::new(vec![ r"^/core/status/network-configuration$", r"^/core/transaction/preview$", - r"^/core/transaction/submit$" + r"^/core/transaction/submit$", + r"^/core/transactions$" ]) .expect("Unable to create global regex set"); } pub(crate) static ID_STATUS_NETWORK_CONFIGURATION: usize = 0; pub(crate) static ID_TRANSACTION_PREVIEW: usize = 1; pub(crate) static ID_TRANSACTION_SUBMIT: usize = 2; + pub(crate) static ID_TRANSACTIONS: usize = 3; } pub struct MakeService where @@ -169,14 +172,14 @@ impl hyper::service::Service<(Request, C)> for Service where let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); *response.body_mut() = Body::from(body); }, - StatusNetworkConfigurationPostResponse::AnErrorOccurred + StatusNetworkConfigurationPostResponse::ServerError (body) => { *response.status_mut() = StatusCode::from_u16(500).expect("Unable to turn 500 into a StatusCode"); response.headers_mut().insert( CONTENT_TYPE, HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for STATUS_NETWORK_CONFIGURATION_POST_AN_ERROR_OCCURRED")); + .expect("Unable to create Content-Type header for STATUS_NETWORK_CONFIGURATION_POST_SERVER_ERROR")); let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); *response.body_mut() = Body::from(body); }, @@ -254,14 +257,25 @@ impl hyper::service::Service<(Request, C)> for Service where let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); *response.body_mut() = Body::from(body); }, - TransactionPreviewPostResponse::AnErrorOccurred + TransactionPreviewPostResponse::ClientError + (body) + => { + *response.status_mut() = StatusCode::from_u16(400).expect("Unable to turn 400 into a StatusCode"); + response.headers_mut().insert( + CONTENT_TYPE, + HeaderValue::from_str("application/json") + .expect("Unable to create Content-Type header for TRANSACTION_PREVIEW_POST_CLIENT_ERROR")); + let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); + *response.body_mut() = Body::from(body); + }, + TransactionPreviewPostResponse::ServerError (body) => { *response.status_mut() = StatusCode::from_u16(500).expect("Unable to turn 500 into a StatusCode"); response.headers_mut().insert( CONTENT_TYPE, HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for TRANSACTION_PREVIEW_POST_AN_ERROR_OCCURRED")); + .expect("Unable to create Content-Type header for TRANSACTION_PREVIEW_POST_SERVER_ERROR")); let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); *response.body_mut() = Body::from(body); }, @@ -345,14 +359,25 @@ impl hyper::service::Service<(Request, C)> for Service where let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); *response.body_mut() = Body::from(body); }, - TransactionSubmitPostResponse::AnErrorOccurred + TransactionSubmitPostResponse::ClientError + (body) + => { + *response.status_mut() = StatusCode::from_u16(400).expect("Unable to turn 400 into a StatusCode"); + response.headers_mut().insert( + CONTENT_TYPE, + HeaderValue::from_str("application/json") + .expect("Unable to create Content-Type header for TRANSACTION_SUBMIT_POST_CLIENT_ERROR")); + let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); + *response.body_mut() = Body::from(body); + }, + TransactionSubmitPostResponse::ServerError (body) => { *response.status_mut() = StatusCode::from_u16(500).expect("Unable to turn 500 into a StatusCode"); response.headers_mut().insert( CONTENT_TYPE, HeaderValue::from_str("application/json") - .expect("Unable to create Content-Type header for TRANSACTION_SUBMIT_POST_AN_ERROR_OCCURRED")); + .expect("Unable to create Content-Type header for TRANSACTION_SUBMIT_POST_SERVER_ERROR")); let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); *response.body_mut() = Body::from(body); }, @@ -374,9 +399,112 @@ impl hyper::service::Service<(Request, C)> for Service where } }, + // TransactionsPost - POST /transactions + &hyper::Method::POST if path.matched(paths::ID_TRANSACTIONS) => { + // Body parameters (note that non-required body parameters will ignore garbage + // values, rather than causing a 400 response). Produce warning header and logs for + // any unused fields. + let result = body.into_raw().await; + match result { + Ok(body) => { + let mut unused_elements = Vec::new(); + let param_committed_transactions_request: Option = if !body.is_empty() { + let deserializer = &mut serde_json::Deserializer::from_slice(&*body); + match serde_ignored::deserialize(deserializer, |path| { + warn!("Ignoring unknown field in body: {}", path); + unused_elements.push(path.to_string()); + }) { + Ok(param_committed_transactions_request) => param_committed_transactions_request, + Err(e) => return Ok(Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(format!("Couldn't parse body parameter CommittedTransactionsRequest - doesn't match schema: {}", e))) + .expect("Unable to create Bad Request response for invalid body parameter CommittedTransactionsRequest due to schema")), + } + } else { + None + }; + let param_committed_transactions_request = match param_committed_transactions_request { + Some(param_committed_transactions_request) => param_committed_transactions_request, + None => return Ok(Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from("Missing required body parameter CommittedTransactionsRequest")) + .expect("Unable to create Bad Request response for missing body parameter CommittedTransactionsRequest")), + }; + + let result = api_impl.transactions_post( + param_committed_transactions_request, + &context + ).await; + let mut response = Response::new(Body::empty()); + response.headers_mut().insert( + HeaderName::from_static("x-span-id"), + HeaderValue::from_str((&context as &dyn Has).get().0.clone().to_string().as_str()) + .expect("Unable to create X-Span-ID header value")); + + if !unused_elements.is_empty() { + response.headers_mut().insert( + HeaderName::from_static("warning"), + HeaderValue::from_str(format!("Ignoring unknown fields in body: {:?}", unused_elements).as_str()) + .expect("Unable to create Warning header value")); + } + + match result { + Ok(rsp) => match rsp { + TransactionsPostResponse::CommittedTransactionsResponse + (body) + => { + *response.status_mut() = StatusCode::from_u16(200).expect("Unable to turn 200 into a StatusCode"); + response.headers_mut().insert( + CONTENT_TYPE, + HeaderValue::from_str("application/json") + .expect("Unable to create Content-Type header for TRANSACTIONS_POST_COMMITTED_TRANSACTIONS_RESPONSE")); + let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); + *response.body_mut() = Body::from(body); + }, + TransactionsPostResponse::ClientError + (body) + => { + *response.status_mut() = StatusCode::from_u16(400).expect("Unable to turn 400 into a StatusCode"); + response.headers_mut().insert( + CONTENT_TYPE, + HeaderValue::from_str("application/json") + .expect("Unable to create Content-Type header for TRANSACTIONS_POST_CLIENT_ERROR")); + let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); + *response.body_mut() = Body::from(body); + }, + TransactionsPostResponse::ServerError + (body) + => { + *response.status_mut() = StatusCode::from_u16(500).expect("Unable to turn 500 into a StatusCode"); + response.headers_mut().insert( + CONTENT_TYPE, + HeaderValue::from_str("application/json") + .expect("Unable to create Content-Type header for TRANSACTIONS_POST_SERVER_ERROR")); + let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); + *response.body_mut() = Body::from(body); + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR; + *response.body_mut() = Body::from("An internal error occurred"); + }, + } + + Ok(response) + }, + Err(e) => Ok(Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(format!("Couldn't read body parameter CommittedTransactionsRequest: {}", e))) + .expect("Unable to create Bad Request response due to unable to read body parameter CommittedTransactionsRequest")), + } + }, + _ if path.matched(paths::ID_STATUS_NETWORK_CONFIGURATION) => method_not_allowed(), _ if path.matched(paths::ID_TRANSACTION_PREVIEW) => method_not_allowed(), _ if path.matched(paths::ID_TRANSACTION_SUBMIT) => method_not_allowed(), + _ if path.matched(paths::ID_TRANSACTIONS) => method_not_allowed(), _ => Ok(Response::builder().status(StatusCode::NOT_FOUND) .body(Body::empty()) .expect("Unable to create Not Found response")) @@ -396,6 +524,8 @@ impl RequestParser for ApiRequestParser { &hyper::Method::POST if path.matched(paths::ID_TRANSACTION_PREVIEW) => Some("TransactionPreviewPost"), // TransactionSubmitPost - POST /transaction/submit &hyper::Method::POST if path.matched(paths::ID_TRANSACTION_SUBMIT) => Some("TransactionSubmitPost"), + // TransactionsPost - POST /transactions + &hyper::Method::POST if path.matched(paths::ID_TRANSACTIONS) => Some("TransactionsPost"), _ => None, } } diff --git a/state-manager/core-api-server/src/core_api/mod.rs b/core-rust/core-api-server/src/core_api/mod.rs similarity index 98% rename from state-manager/core-api-server/src/core_api/mod.rs rename to core-rust/core-api-server/src/core_api/mod.rs index 5190d084d1..5d02ef3d76 100644 --- a/state-manager/core-api-server/src/core_api/mod.rs +++ b/core-rust/core-api-server/src/core_api/mod.rs @@ -62,7 +62,12 @@ * permissions under this License. */ +mod errors; +mod network_configuration; +mod preview; pub mod server; +mod transactions; + #[allow(unused)] #[rustfmt::skip] diff --git a/core-rust/core-api-server/src/core_api/network_configuration.rs b/core-rust/core-api-server/src/core_api/network_configuration.rs new file mode 100644 index 0000000000..6f98091386 --- /dev/null +++ b/core-rust/core-api-server/src/core_api/network_configuration.rs @@ -0,0 +1,42 @@ +use crate::core_api::errors::{common_server_errors, RequestHandlingError}; +use crate::core_api::generated::models::*; +use crate::core_api::generated::{StatusNetworkConfigurationPostResponse, API_VERSION}; +use state_manager::jni::state_manager::ActualStateManager; +use std::sync::{Arc, Mutex}; + +pub(crate) fn handle_network_configuration( + state_manager: Arc>, +) -> StatusNetworkConfigurationPostResponse { + match handle_network_configuration_internal(state_manager) { + Ok(response) => StatusNetworkConfigurationPostResponse::NetworkConfiguration(response), + Err(RequestHandlingError::ServerError(error_response)) => { + StatusNetworkConfigurationPostResponse::ServerError(error_response) + } + Err(RequestHandlingError::ClientError(error_response)) => + // No client errors are expected; returning a server error + { + StatusNetworkConfigurationPostResponse::ServerError(error_response) + } + } +} + +fn handle_network_configuration_internal( + state_manager: Arc>, +) -> Result { + let locked_state_manager = state_manager + .lock() + .map_err(|_| common_server_errors::state_manager_lock_error())?; + + let network = locked_state_manager.network.clone(); + + Ok(NetworkConfigurationResponse { + version: NetworkConfigurationResponseVersion { + core_version: env!("CARGO_PKG_VERSION").to_string(), + api_version: API_VERSION.to_string(), + }, + network_identifier: NetworkIdentifier { + network: network.logical_name, + }, + network_hrp_suffix: network.hrp_suffix, + }) +} diff --git a/core-rust/core-api-server/src/core_api/preview.rs b/core-rust/core-api-server/src/core_api/preview.rs new file mode 100644 index 0000000000..8a584d9c3f --- /dev/null +++ b/core-rust/core-api-server/src/core_api/preview.rs @@ -0,0 +1,201 @@ +use crate::core_api::errors::{common_server_errors, RequestHandlingError}; +use crate::core_api::generated::models::*; +use crate::core_api::generated::TransactionPreviewPostResponse; +use radix_engine::transaction::{PreviewResult, TransactionOutcome, TransactionResult}; +use scrypto::address::Bech32Encoder; +use scrypto::crypto::EcdsaPublicKey; +use scrypto::prelude::scrypto_decode; +use state_manager::jni::state_manager::ActualStateManager; +use state_manager::PreviewRequest; +use std::sync::{Arc, Mutex}; +use transaction::model::{PreviewFlags, TransactionManifest}; + +pub(crate) fn handle_preview( + state_manager: Arc>, + request: TransactionPreviewRequest, +) -> TransactionPreviewPostResponse { + match handle_preview_internal(state_manager, request) { + Ok(response) => TransactionPreviewPostResponse::TransactionPreviewResponse(response), + Err(RequestHandlingError::ClientError(error_response)) => { + TransactionPreviewPostResponse::ClientError(error_response) + } + Err(RequestHandlingError::ServerError(error_response)) => { + TransactionPreviewPostResponse::ServerError(error_response) + } + } +} + +fn handle_preview_internal( + state_manager: Arc>, + request: TransactionPreviewRequest, +) -> Result { + let preview_request = parse_preview_request(request)?; + + let mut locked_state_manager = state_manager + .lock() + .map_err(|_| common_server_errors::state_manager_lock_error())?; + + let result = locked_state_manager + .preview(preview_request) + .map_err(preview_errors::engine_error)?; + + let bech32_encoder = Bech32Encoder::new(&locked_state_manager.network); + + to_api_response(result, bech32_encoder) +} + +fn parse_preview_request( + request: TransactionPreviewRequest, +) -> Result { + let cost_unit_limit: u32 = request + .cost_unit_limit + .parse() + .map_err(|_| preview_errors::invalid_int_field("cost_unit_limit"))?; + + let tip_percentage: u32 = request + .tip_percentage + .parse() + .map_err(|_| preview_errors::invalid_int_field("tip_percentage"))?; + + let nonce: u64 = request + .nonce + .parse() + .map_err(|_| preview_errors::invalid_int_field("nonce"))?; + + let manifest = hex::decode(request.manifest) + .map(|manifest_bytes| { + scrypto_decode::(&manifest_bytes) + .map_err(|_| preview_errors::invalid_manifest()) + }) + .map_err(|_| preview_errors::invalid_manifest())??; + + let signer_public_keys: Vec = request + .signer_public_keys + .into_iter() + .flat_map(|s| { + hex::decode(s.clone()).map(|pub_key_bytes| { + EcdsaPublicKey::try_from(&pub_key_bytes[..]) + .map_err(|_| preview_errors::invalid_signer_pub_key(&s)) + }) + }) + .collect::, RequestHandlingError>>()?; + + Ok(PreviewRequest { + manifest, + cost_unit_limit, + tip_percentage, + nonce, + signer_public_keys, + flags: PreviewFlags { + unlimited_loan: request.flags.unlimited_loan, + }, + }) +} + +fn to_api_response( + result: PreviewResult, + bech32_encoder: Bech32Encoder, +) -> Result { + let execution = result.receipt.execution; + let fee_summary = execution.fee_summary; + + let api_fee_summary = FeeSummary { + loan_fully_repaid: fee_summary.loan_fully_repaid, + cost_unit_limit: fee_summary.cost_unit_limit.to_string(), + cost_unit_consumed: fee_summary.cost_unit_consumed.to_string(), + cost_unit_price: fee_summary.cost_unit_price.to_string(), + tip_percentage: fee_summary.tip_percentage.to_string(), + xrd_burned: fee_summary.burned.to_string(), + xrd_tipped: fee_summary.tipped.to_string(), + }; + + let logs = execution + .application_logs + .into_iter() + .map(|(level, message)| TransactionPreviewResponseLogsInner { + level: level.to_string(), + message, + }) + .collect(); + + let response = match result.receipt.result { + TransactionResult::Commit(commit_result) => { + let new_package_addresses = commit_result + .entity_changes + .new_package_addresses + .into_iter() + .map(|addr| bech32_encoder.encode_package_address(&addr)) + .collect(); + + let new_component_addresses = commit_result + .entity_changes + .new_component_addresses + .into_iter() + .map(|addr| bech32_encoder.encode_component_address(&addr)) + .collect(); + + let new_resource_addresses = commit_result + .entity_changes + .new_resource_addresses + .into_iter() + .map(|addr| bech32_encoder.encode_resource_address(&addr)) + .collect(); + + let (status, output, error_message) = match commit_result.outcome { + TransactionOutcome::Success(output) => { + let output_hex = output.into_iter().map(hex::encode).collect(); + (TransactionStatus::SUCCEEDED, Some(output_hex), None) + } + TransactionOutcome::Failure(error) => ( + TransactionStatus::FAILED, + None, + Some(format!("{:?}", error)), + ), + }; + + TransactionPreviewResponse { + transaction_status: status, + transaction_fee: api_fee_summary, + logs, + new_package_addresses, + new_component_addresses, + new_resource_addresses, + output, + error_message, + } + } + TransactionResult::Reject(reject_result) => TransactionPreviewResponse { + transaction_status: TransactionStatus::REJECTED, + transaction_fee: api_fee_summary, + logs, + new_package_addresses: vec![], + new_component_addresses: vec![], + new_resource_addresses: vec![], + output: None, + error_message: Some(format!("{:?}", reject_result)), + }, + }; + + Ok(response) +} + +mod preview_errors { + use crate::core_api::errors::{client_error, RequestHandlingError}; + use radix_engine::transaction::PreviewError; + + pub(crate) fn engine_error(err: PreviewError) -> RequestHandlingError { + client_error(1, &format!("Engine error: {:?}", err)) + } + + pub(crate) fn invalid_int_field(field: &str) -> RequestHandlingError { + client_error(2, &format!("Invalid integer: {}", field)) + } + + pub(crate) fn invalid_manifest() -> RequestHandlingError { + client_error(3, "Invalid manifest") + } + + pub(crate) fn invalid_signer_pub_key(raw_key: &str) -> RequestHandlingError { + client_error(4, &format!("Invalid signer public key: {}", raw_key)) + } +} diff --git a/state-manager/core-api-server/src/core_api/server.rs b/core-rust/core-api-server/src/core_api/server.rs similarity index 78% rename from state-manager/core-api-server/src/core_api/server.rs rename to core-rust/core-api-server/src/core_api/server.rs index 10504021ea..2ee5cd1f29 100644 --- a/state-manager/core-api-server/src/core_api/server.rs +++ b/core-rust/core-api-server/src/core_api/server.rs @@ -63,7 +63,7 @@ */ use crate::core_api::generated::server::MakeService; -use crate::core_api::generated::{models, API_VERSION}; +use crate::core_api::generated::{models, TransactionsPostResponse}; use crate::core_api::generated::{ Api, StatusNetworkConfigurationPostResponse, TransactionPreviewPostResponse, TransactionSubmitPostResponse, @@ -74,13 +74,10 @@ use async_trait::async_trait; use std::future::Future; use std::marker::PhantomData; -use scrypto::address::{EntityType, HrpSet}; use std::sync::{Arc, Mutex}; -use crate::core_api::generated::models::{ - Bech32Hrps, NetworkConfigurationResponse, NetworkConfigurationResponseVersion, - NetworkIdentifier, -}; +use crate::core_api::generated::models::CommittedTransactionsRequest; +use crate::core_api::{network_configuration, preview, transactions}; use scrypto::prelude::*; use state_manager::jni::state_manager::ActualStateManager; use swagger::ApiError; @@ -143,54 +140,39 @@ where &self, _context: &C, ) -> Result { - let network = &self - .state_manager - .lock() - .expect("Can't acquire state manager lock") - .network - .clone(); - - let hrp_set: HrpSet = network.into(); - - Ok( - StatusNetworkConfigurationPostResponse::NetworkConfiguration( - NetworkConfigurationResponse { - version: NetworkConfigurationResponseVersion { - core_version: env!("CARGO_PKG_VERSION").to_string(), - api_version: API_VERSION.to_string(), - }, - network_identifier: NetworkIdentifier { - network: format!("{:?}", network), - }, - bech32_human_readable_parts: Bech32Hrps { - account_hrp: hrp_set - .get_entity_hrp(&EntityType::AccountComponent) - .to_string(), - validator_hrp: "TODO".to_string(), - node_hrp: "TODO".to_string(), - resource_hrp_suffix: hrp_set - .get_entity_hrp(&EntityType::Resource) - .to_string(), - }, - }, - ), - ) + Ok(network_configuration::handle_network_configuration( + self.state_manager.clone(), + )) } async fn transaction_preview_post( &self, - _transaction_preview_request: models::TransactionPreviewRequest, + request: models::TransactionPreviewRequest, _context: &C, ) -> Result { - Err(ApiError("To be implemented".into())) + Ok(preview::handle_preview(self.state_manager.clone(), request)) } async fn transaction_submit_post( &self, - _transaction_submit_request: models::TransactionSubmitRequest, + request: models::TransactionSubmitRequest, _context: &C, ) -> Result { - Err(ApiError("To be implemented".into())) + Ok(transactions::handle_submit_transaction( + self.state_manager.clone(), + request, + )) + } + + async fn transactions_post( + &self, + request: CommittedTransactionsRequest, + _context: &C, + ) -> Result { + Ok(transactions::handle_get_committed_transactions( + self.state_manager.clone(), + request, + )) } } diff --git a/core-rust/core-api-server/src/core_api/transactions.rs b/core-rust/core-api-server/src/core_api/transactions.rs new file mode 100644 index 0000000000..7884887d0b --- /dev/null +++ b/core-rust/core-api-server/src/core_api/transactions.rs @@ -0,0 +1,256 @@ +use crate::core_api::errors::{common_server_errors, RequestHandlingError}; +use crate::core_api::generated::models::*; +use crate::core_api::generated::{TransactionSubmitPostResponse, TransactionsPostResponse}; +use scrypto::buffer::scrypto_decode; +use scrypto::crypto::sha256_twice; +use scrypto::prelude::scrypto_encode; +use state_manager::jni::state_manager::ActualStateManager; +use state_manager::mempool::Mempool; +use state_manager::store::TransactionStore; +use state_manager::{MempoolError, TId, TemporaryTransactionReceipt, Transaction}; +use std::cmp; +use std::sync::{Arc, Mutex}; +use transaction::model::NotarizedTransaction as EngineNotarizedTransaction; + +pub(crate) fn handle_submit_transaction( + state_manager: Arc>, + request: TransactionSubmitRequest, +) -> TransactionSubmitPostResponse { + match handle_submit_transaction_internal(state_manager, request) { + Ok(response) => TransactionSubmitPostResponse::TransactionSubmitResponse(response), + Err(RequestHandlingError::ClientError(error_response)) => { + TransactionSubmitPostResponse::ClientError(error_response) + } + Err(RequestHandlingError::ServerError(error_response)) => { + TransactionSubmitPostResponse::ServerError(error_response) + } + } +} + +fn handle_submit_transaction_internal( + state_manager: Arc>, + request: TransactionSubmitRequest, +) -> Result { + let transaction_bytes = hex::decode(request.notarized_transaction) + .map_err(|_| transaction_errors::invalid_transaction())?; + + let tid = sha256_twice(transaction_bytes.clone()); + + let transaction = Transaction { + payload: transaction_bytes, + id: TId { + bytes: tid.to_vec(), + }, + }; + + let mut locked_state_manager = state_manager + .lock() + .map_err(|_| common_server_errors::state_manager_lock_error())?; + + let result = locked_state_manager.mempool.add_transaction(transaction); + + match result { + Ok(_) => Ok(TransactionSubmitResponse::new(false)), + Err(MempoolError::Duplicate) => Ok(TransactionSubmitResponse::new(true)), + Err(MempoolError::Full { + current_size: _, + max_size: _, + }) => Err(transaction_errors::mempool_is_full()), + Err(MempoolError::TransactionValidationError(err)) => { + Err(transaction_errors::transaction_validation_error(err)) + } + } +} + +pub(crate) fn handle_get_committed_transactions( + state_manager: Arc>, + request: CommittedTransactionsRequest, +) -> TransactionsPostResponse { + match handle_get_committed_transactions_internal(state_manager, request) { + Ok(response) => TransactionsPostResponse::CommittedTransactionsResponse(response), + Err(RequestHandlingError::ClientError(error_response)) => { + TransactionsPostResponse::ClientError(error_response) + } + Err(RequestHandlingError::ServerError(error_response)) => { + TransactionsPostResponse::ServerError(error_response) + } + } +} + +fn handle_get_committed_transactions_internal( + state_manager: Arc>, + request: CommittedTransactionsRequest, +) -> Result { + let start_state_version: u64 = request + .start_state_version + .parse() + .map_err(|_| transaction_errors::invalid_int_field("state_version"))?; + + if start_state_version < 1 { + return Err(transaction_errors::invalid_start_state_version()); + } + + let limit: u64 = request + .limit + .try_into() + .map_err(|_| transaction_errors::invalid_int_field("limit"))?; + + let state_version_at_limit: u64 = start_state_version + .checked_add(limit) + .and_then(|v| v.checked_sub(1)) + .ok_or_else(|| transaction_errors::invalid_int_field("limit"))?; + + let locked_state_manager = state_manager + .lock() + .map_err(|_| common_server_errors::state_manager_lock_error())?; + + let up_to_state_version_inclusive = cmp::min( + state_version_at_limit, + locked_state_manager.proof_store.max_state_version(), + ); + + let mut txns = vec![]; + let mut state_version = start_state_version; + while state_version <= up_to_state_version_inclusive { + let next_tid = locked_state_manager + .proof_store + .get_tid(state_version) + .ok_or_else(|| { + transaction_errors::missing_transaction_at_state_version(state_version) + })?; + let next_tx = locked_state_manager + .transaction_store + .get_transaction(&next_tid); + txns.push((next_tx, state_version)); + state_version += 1; + } + + let api_txns = txns + .into_iter() + .map(|((tx, receipt), state_version)| { + scrypto_decode(&tx) + .map(|notarized_tx| { + to_api_committed_transaction(notarized_tx, receipt.clone(), state_version) + }) + .map_err(|_| transaction_errors::invalid_committed_txn()) + }) + .collect::, RequestHandlingError>>()?; + + let start_state_version = if api_txns.is_empty() { + 0 + } else { + start_state_version + }; + + Ok(CommittedTransactionsResponse { + start_state_version: start_state_version.to_string(), + max_state_version: up_to_state_version_inclusive.to_string(), + transactions: api_txns, + }) +} + +fn to_api_committed_transaction( + tx: EngineNotarizedTransaction, + _receipt: TemporaryTransactionReceipt, + state_version: u64, +) -> CommittedTransaction { + let tx_hash = tx.hash(); + let signed_intent = tx.signed_intent; + let signed_intent_hash = signed_intent.hash(); + let intent = signed_intent.intent; + let intent_hash = intent.hash(); + let header = intent.header; + + CommittedTransaction { + state_version: state_version.to_string(), + notarized_transaction: NotarizedTransaction { + hash: tx_hash.to_string(), + signed_intent: SignedTransactionIntent { + hash: signed_intent_hash.to_string(), + intent: TransactionIntent { + hash: intent_hash.to_string(), + header: TransactionHeader { + version: header.version as isize, + network_id: header.network_id as isize, + start_epoch_inclusive: header.start_epoch_inclusive.to_string(), + end_epoch_exclusive: header.end_epoch_exclusive.to_string(), + nonce: header.nonce.to_string(), + notary_public_key: header.notary_public_key.to_string(), + notary_as_signatory: header.notary_as_signatory, + cost_unit_limit: header.cost_unit_limit.to_string(), + tip_percentage: header.tip_percentage.to_string(), + }, + manifest: hex::encode(scrypto_encode(&intent.manifest)), + }, + intent_signatures: signed_intent + .intent_signatures + .into_iter() + .map(|(public_key, signature)| IntentSignature { + public_key: public_key.to_string(), + signature: signature.to_string(), + }) + .collect(), + }, + notary_signature: tx.notary_signature.to_string(), + }, + receipt: TransactionReceipt { + status: TransactionStatus::SUCCEEDED, // TODO: fixme (needs receipt) + fee_summary: FeeSummary { + // TODO: fixme + loan_fully_repaid: true, + cost_unit_limit: "0".to_string(), + cost_unit_consumed: "0".to_string(), + cost_unit_price: "0".to_string(), + tip_percentage: "0".to_string(), + xrd_burned: "0".to_string(), + xrd_tipped: "0".to_string(), + }, + output: Some(vec!["00".to_string()]), // TODO: fixme (needs receipt) + error_message: None, // TODO: fixme (needs receipt) + }, + } +} + +mod transaction_errors { + use crate::core_api::errors::{client_error, server_error, RequestHandlingError}; + use transaction::errors::TransactionValidationError; + + pub(crate) fn invalid_transaction() -> RequestHandlingError { + client_error(1, "Invalid transaction payload") + } + + pub(crate) fn mempool_is_full() -> RequestHandlingError { + client_error(2, "Mempool is full") + } + + pub(crate) fn transaction_validation_error( + err: TransactionValidationError, + ) -> RequestHandlingError { + client_error(3, &format!("Transaction validation error: {:?}", err)) + } + + pub(crate) fn invalid_int_field(field: &str) -> RequestHandlingError { + client_error(4, &format!("Invalid integer: {}", field)) + } + + pub(crate) fn invalid_start_state_version() -> RequestHandlingError { + client_error( + 5, + "start_state_version is invalid (minimum state version is 1)", + ) + } + + pub(crate) fn invalid_committed_txn() -> RequestHandlingError { + server_error(6, "Internal server error: invalid committed txn payload") + } + + pub(crate) fn missing_transaction_at_state_version(state_version: u64) -> RequestHandlingError { + server_error( + 7, + &format!( + "A transaction is missing at state version {}", + state_version + ), + ) + } +} diff --git a/state-manager/core-api-server/src/jni/mod.rs b/core-rust/core-api-server/src/jni/mod.rs similarity index 100% rename from state-manager/core-api-server/src/jni/mod.rs rename to core-rust/core-api-server/src/jni/mod.rs diff --git a/state-manager/core-api-server/src/lib.rs b/core-rust/core-api-server/src/lib.rs similarity index 100% rename from state-manager/core-api-server/src/lib.rs rename to core-rust/core-api-server/src/lib.rs diff --git a/state-manager/core-rust/Cargo.toml b/core-rust/core-rust/Cargo.toml similarity index 100% rename from state-manager/core-rust/Cargo.toml rename to core-rust/core-rust/Cargo.toml diff --git a/state-manager/core-rust/src/lib.rs b/core-rust/core-rust/src/lib.rs similarity index 100% rename from state-manager/core-rust/src/lib.rs rename to core-rust/core-rust/src/lib.rs diff --git a/state-manager/state-manager/Cargo.toml b/core-rust/state-manager/Cargo.toml similarity index 100% rename from state-manager/state-manager/Cargo.toml rename to core-rust/state-manager/Cargo.toml diff --git a/state-manager/state-manager/src/jni/dtos/java_structure.rs b/core-rust/state-manager/src/jni/dtos/java_structure.rs similarity index 100% rename from state-manager/state-manager/src/jni/dtos/java_structure.rs rename to core-rust/state-manager/src/jni/dtos/java_structure.rs diff --git a/state-manager/state-manager/src/jni/dtos/mod.rs b/core-rust/state-manager/src/jni/dtos/mod.rs similarity index 100% rename from state-manager/state-manager/src/jni/dtos/mod.rs rename to core-rust/state-manager/src/jni/dtos/mod.rs diff --git a/state-manager/state-manager/src/jni/mempool.rs b/core-rust/state-manager/src/jni/mempool.rs similarity index 100% rename from state-manager/state-manager/src/jni/mempool.rs rename to core-rust/state-manager/src/jni/mempool.rs diff --git a/state-manager/state-manager/src/jni/mod.rs b/core-rust/state-manager/src/jni/mod.rs similarity index 100% rename from state-manager/state-manager/src/jni/mod.rs rename to core-rust/state-manager/src/jni/mod.rs diff --git a/state-manager/state-manager/src/jni/state_computer/mod.rs b/core-rust/state-manager/src/jni/state_computer/mod.rs similarity index 85% rename from state-manager/state-manager/src/jni/state_computer/mod.rs rename to core-rust/state-manager/src/jni/state_computer/mod.rs index 9e3e1ed908..6ebdda8d67 100644 --- a/state-manager/state-manager/src/jni/state_computer/mod.rs +++ b/core-rust/state-manager/src/jni/state_computer/mod.rs @@ -62,10 +62,7 @@ * permissions under this License. */ -mod dto; - use crate::jni::dtos::JavaStructure; -use dto::*; use jni::objects::{JClass, JObject}; use jni::sys::jbyteArray; use jni::JNIEnv; @@ -73,8 +70,8 @@ use scrypto::prelude::*; use crate::jni::state_manager::JNIStateManager; use crate::jni::utils::*; -use crate::result::{ResultStateManagerMaps, StateManagerResult}; -use crate::types::{CommitRequest, PreviewRequest, Transaction}; +use crate::result::StateManagerResult; +use crate::types::{CommitRequest, Transaction}; // // JNI Interface @@ -110,34 +107,6 @@ fn do_verify( Ok(ret) } -#[no_mangle] -extern "system" fn Java_com_radixdlt_statecomputer_RustStateComputer_preview( - env: JNIEnv, - _class: JClass, - j_state_manager: JObject, - request_payload: jbyteArray, -) -> jbyteArray { - let ret = do_preview(&env, j_state_manager, request_payload).to_java(); - jni_slice_to_jbytearray(&env, &ret) -} - -fn do_preview( - env: &JNIEnv, - j_state_manager: JObject, - request_payload: jbyteArray, -) -> StateManagerResult> { - let state_manager = JNIStateManager::get_state_manager(env, j_state_manager); - let request_payload: Vec = jni_jbytearray_to_vector(env, request_payload)?; - let preview_request = PreviewRequest::from_java(&request_payload)?; - let preview_result: Result = state_manager - .lock() - .expect("Can't acquire a state manager mutex lock") - .preview(&preview_request) - .map(|result| result.into()) - .map_err_sm(|err| err.into())?; - Ok(preview_result) -} - #[no_mangle] extern "system" fn Java_com_radixdlt_statecomputer_RustStateComputer_commit( env: JNIEnv, diff --git a/state-manager/state-manager/src/jni/state_manager.rs b/core-rust/state-manager/src/jni/state_manager.rs similarity index 100% rename from state-manager/state-manager/src/jni/state_manager.rs rename to core-rust/state-manager/src/jni/state_manager.rs diff --git a/state-manager/state-manager/src/jni/transaction_builder.rs b/core-rust/state-manager/src/jni/transaction_builder.rs similarity index 100% rename from state-manager/state-manager/src/jni/transaction_builder.rs rename to core-rust/state-manager/src/jni/transaction_builder.rs diff --git a/state-manager/state-manager/src/jni/transaction_store.rs b/core-rust/state-manager/src/jni/transaction_store.rs similarity index 98% rename from state-manager/state-manager/src/jni/transaction_store.rs rename to core-rust/state-manager/src/jni/transaction_store.rs index df8e1303eb..2128b527c2 100644 --- a/state-manager/state-manager/src/jni/transaction_store.rs +++ b/core-rust/state-manager/src/jni/transaction_store.rs @@ -99,7 +99,7 @@ fn do_get_transaction_at_state_version( state_manager: &mut ActualStateManager, state_version: u64, ) -> ExecutedTransactionReceipt { - let tid = state_manager.proof_store.get_tid(state_version); + let tid = state_manager.proof_store.get_tid(state_version).unwrap(); let (transaction_data, receipt) = state_manager.transaction_store.get_transaction(&tid); diff --git a/state-manager/state-manager/src/jni/utils.rs b/core-rust/state-manager/src/jni/utils.rs similarity index 100% rename from state-manager/state-manager/src/jni/utils.rs rename to core-rust/state-manager/src/jni/utils.rs diff --git a/state-manager/state-manager/src/lib.rs b/core-rust/state-manager/src/lib.rs similarity index 96% rename from state-manager/state-manager/src/lib.rs rename to core-rust/state-manager/src/lib.rs index a6156aa358..84c3c7c42a 100644 --- a/state-manager/state-manager/src/lib.rs +++ b/core-rust/state-manager/src/lib.rs @@ -67,8 +67,11 @@ pub mod mempool; mod query; mod result; mod state_manager; -mod store; +pub mod store; mod transaction_builder; mod types; +pub use mempool::MempoolError; pub use state_manager::StateManager; +pub use store::TemporaryTransactionReceipt; +pub use types::{CommitRequest, PreviewRequest, TId, Transaction}; diff --git a/state-manager/state-manager/src/mempool/mod.rs b/core-rust/state-manager/src/mempool/mod.rs similarity index 100% rename from state-manager/state-manager/src/mempool/mod.rs rename to core-rust/state-manager/src/mempool/mod.rs diff --git a/state-manager/state-manager/src/mempool/simple.rs b/core-rust/state-manager/src/mempool/simple.rs similarity index 100% rename from state-manager/state-manager/src/mempool/simple.rs rename to core-rust/state-manager/src/mempool/simple.rs diff --git a/state-manager/state-manager/src/query/mod.rs b/core-rust/state-manager/src/query/mod.rs similarity index 100% rename from state-manager/state-manager/src/query/mod.rs rename to core-rust/state-manager/src/query/mod.rs diff --git a/state-manager/state-manager/src/query/query_db.rs b/core-rust/state-manager/src/query/query_db.rs similarity index 100% rename from state-manager/state-manager/src/query/query_db.rs rename to core-rust/state-manager/src/query/query_db.rs diff --git a/state-manager/state-manager/src/result.rs b/core-rust/state-manager/src/result.rs similarity index 100% rename from state-manager/state-manager/src/result.rs rename to core-rust/state-manager/src/result.rs diff --git a/state-manager/state-manager/src/state_manager.rs b/core-rust/state-manager/src/state_manager.rs similarity index 91% rename from state-manager/state-manager/src/state_manager.rs rename to core-rust/state-manager/src/state_manager.rs index e4513de264..2de575b162 100644 --- a/state-manager/state-manager/src/state_manager.rs +++ b/core-rust/state-manager/src/state_manager.rs @@ -66,13 +66,14 @@ use crate::jni::dtos::*; use crate::mempool::{Mempool, MempoolConfig}; use crate::query::ResourceAccounter; use crate::store::{ProofStore, TransactionStore}; -use crate::types::{CommitRequest, PreviewError, PreviewRequest, Transaction}; +use crate::types::{CommitRequest, PreviewRequest, Transaction}; use radix_engine::constants::{ DEFAULT_COST_UNIT_LIMIT, DEFAULT_COST_UNIT_PRICE, DEFAULT_MAX_CALL_DEPTH, DEFAULT_SYSTEM_LOAN, }; use radix_engine::ledger::{QueryableSubstateStore, ReadableSubstateStore, WriteableSubstateStore}; use radix_engine::transaction::{ - ExecutionConfig, PreviewExecutor, PreviewResult, TransactionExecutor, TransactionReceipt, + ExecutionConfig, PreviewError, PreviewExecutor, PreviewResult, TransactionExecutor, + TransactionReceipt, }; use radix_engine::wasm::{DefaultWasmEngine, WasmInstrumenter}; use scrypto::engine::types::RENodeId; @@ -80,15 +81,14 @@ use scrypto::prelude::*; use std::collections::HashMap; use transaction::errors::TransactionValidationError; use transaction::model::{ - PreviewFlags, PreviewIntent, TransactionHeader, TransactionIntent, TransactionManifest, - ValidatedTransaction, + PreviewFlags, PreviewIntent, TransactionHeader, TransactionIntent, ValidatedTransaction, }; use transaction::signing::EcdsaPrivateKey; use transaction::validation::{TestIntentHashManager, TransactionValidator, ValidationConfig}; pub struct StateManager { pub mempool: M, - pub transaction_store: T, // TODO: remove dyn + pub transaction_store: T, pub proof_store: ProofStore, pub network: NetworkDefinition, substate_store: S, @@ -197,19 +197,8 @@ impl Result { - let manifest: TransactionManifest = - scrypto_decode(&preview_request.manifest).map_err(|_| PreviewError::InvalidManifest)?; - - let signer_public_keys: Result, PreviewError> = preview_request - .signer_public_keys - .iter() - .map(|pk| { - EcdsaPublicKey::try_from(&pk[..]).map_err(|_| PreviewError::InvalidSignerPublicKey) - }) - .collect(); - // not really used for preview let notary_private_key = EcdsaPrivateKey::from_u64(2).unwrap(); @@ -226,15 +215,15 @@ impl TId { + pub fn max_state_version(&self) -> u64 { self.in_memory_txid_store - .get(&state_version) - .cloned() - .unwrap() + .iter() + .next_back() + .map(|(k, _v)| *k) + .unwrap_or_default() + } + + pub fn get_tid(&self, state_version: u64) -> Option { + self.in_memory_txid_store.get(&state_version).cloned() } /// Returns the next proof from a state version (excluded) diff --git a/state-manager/state-manager/src/store/in_memory_transaction_store.rs b/core-rust/state-manager/src/store/in_memory_transaction_store.rs similarity index 100% rename from state-manager/state-manager/src/store/in_memory_transaction_store.rs rename to core-rust/state-manager/src/store/in_memory_transaction_store.rs diff --git a/state-manager/state-manager/src/store/mod.rs b/core-rust/state-manager/src/store/mod.rs similarity index 100% rename from state-manager/state-manager/src/store/mod.rs rename to core-rust/state-manager/src/store/mod.rs diff --git a/state-manager/state-manager/src/store/rocks_db_transaction_store.rs b/core-rust/state-manager/src/store/rocks_db_transaction_store.rs similarity index 100% rename from state-manager/state-manager/src/store/rocks_db_transaction_store.rs rename to core-rust/state-manager/src/store/rocks_db_transaction_store.rs diff --git a/state-manager/state-manager/src/store/transaction_store.rs b/core-rust/state-manager/src/store/transaction_store.rs similarity index 100% rename from state-manager/state-manager/src/store/transaction_store.rs rename to core-rust/state-manager/src/store/transaction_store.rs diff --git a/state-manager/state-manager/src/transaction_builder/builder.rs b/core-rust/state-manager/src/transaction_builder/builder.rs similarity index 100% rename from state-manager/state-manager/src/transaction_builder/builder.rs rename to core-rust/state-manager/src/transaction_builder/builder.rs diff --git a/state-manager/state-manager/src/transaction_builder/mod.rs b/core-rust/state-manager/src/transaction_builder/mod.rs similarity index 100% rename from state-manager/state-manager/src/transaction_builder/mod.rs rename to core-rust/state-manager/src/transaction_builder/mod.rs diff --git a/state-manager/state-manager/src/types.rs b/core-rust/state-manager/src/types.rs similarity index 93% rename from state-manager/state-manager/src/types.rs rename to core-rust/state-manager/src/types.rs index e5b045eb27..eff790a865 100644 --- a/state-manager/state-manager/src/types.rs +++ b/core-rust/state-manager/src/types.rs @@ -62,9 +62,9 @@ * permissions under this License. */ -use radix_engine::transaction::PreviewError as EnginePreviewError; use sbor::{Decode, Encode, TypeId}; -use transaction::model::PreviewFlags; +use scrypto::crypto::EcdsaPublicKey; +use transaction::model::{PreviewFlags, TransactionManifest}; #[derive(Debug, PartialEq, Eq, Hash, Clone, Decode, Encode, TypeId)] pub struct TId { @@ -79,21 +79,14 @@ pub struct Transaction { #[derive(Debug, PartialEq, Eq, Clone, Decode, Encode, TypeId)] pub struct PreviewRequest { - pub manifest: Vec, + pub manifest: TransactionManifest, pub cost_unit_limit: u32, pub tip_percentage: u32, pub nonce: u64, - pub signer_public_keys: Vec>, + pub signer_public_keys: Vec, pub flags: PreviewFlags, } -#[derive(Debug)] -pub enum PreviewError { - InvalidManifest, - InvalidSignerPublicKey, - EngineError(EnginePreviewError), -} - #[derive(Debug, PartialEq, Eq, Clone, Decode, Encode, TypeId)] pub struct CommitRequest { pub transactions: Vec, diff --git a/core/Makefile b/core/Makefile index d98a0f6100..58ae568b6c 100644 --- a/core/Makefile +++ b/core/Makefile @@ -27,7 +27,7 @@ gcloud-token: gcloud-authenticate .PHONY: build-sm build-sm: gcloud-token - cd .. && SKIP_NATIVE_RUST_BUILD=TRUE ./gradlew :state-manager:buildRustForDocker -Pci=true -PcacheBranch=$(GIT_BRANCH) -PrustBinaryBuildType=release + cd .. && SKIP_NATIVE_RUST_BUILD=TRUE ./gradlew :core-rust:buildRustForDocker -Pci=true -PcacheBranch=$(GIT_BRANCH) -PrustBinaryBuildType=release .PHONY: build build-core: diff --git a/core/build.gradle b/core/build.gradle index e25651a271..3c29feae6c 100644 --- a/core/build.gradle +++ b/core/build.gradle @@ -206,7 +206,7 @@ jacocoTestReport { dependencies { implementation project(':olympia-engine') implementation project(':common') - implementation project(':state-manager-bridge') + implementation project(':core-rust-bridge') implementation 'com.fasterxml.jackson.core:jackson-databind' implementation 'io.swagger:swagger-annotations:1.5.0' @@ -294,15 +294,15 @@ ospackage() { if (System.getProperty("os.arch") == "aarch64") { target= "aarch64-unknown-linux-gnu" } - def stateManagerBuildType = project.property("rustBinaryBuildType") + def coreRustBuildType = project.property("rustBinaryBuildType") - from("${project(':state-manager').projectDir}/target/${target}/${stateManagerBuildType}/libcorerust.so") { + from("${project(':core-rust').projectDir}/target/${target}/${coreRustBuildType}/libcorerust.so") { into "/usr/lib/jni/" } // See https://github.com/nebula-plugins/gradle-ospackage-plugin/wiki/Deb-Plugin#basic-usage buildDeb { - dependsOn += [installDist, ":state-manager:buildRustForDocker"] + dependsOn += [installDist, ":core-rust:buildRustForDocker"] version = debSafeVersionName() packageName = debPackageName() @@ -312,7 +312,7 @@ ospackage() { } } buildRpm { - dependsOn += [installDist, ":state-manager:buildRustForDocker"] + dependsOn += [installDist, ":core-rust:buildRustForDocker"] } } diff --git a/docker/rust-builder/Dockerfile b/docker/rust-builder/Dockerfile index e3065f8d1f..00b421ac2b 100644 --- a/docker/rust-builder/Dockerfile +++ b/docker/rust-builder/Dockerfile @@ -29,16 +29,16 @@ ENV CARGO_TARGET_X86_64_UNKNOWN_LINUX_GNU_LINKER=x86_64-linux-gnu-gcc # First - we build a dummy rust file, to cache the compilation of all our dependencies in a Docker layer RUN USER=root cargo new dummy RUN USER=root mkdir -p ./dummy/core-rust/src -RUN USER=root mkdir -p ./dummy/state-manager/src +RUN USER=root mkdir -p ./dummy/core-rust/src RUN USER=root mkdir -p ./dummy/core-api-server/src RUN USER=root touch ./dummy/core-rust/src/lib.rs -RUN USER=root touch ./dummy/state-manager/src/lib.rs +RUN USER=root touch ./dummy/core-rust/src/lib.rs RUN USER=root touch ./dummy/core-api-server/src/lib.rs -COPY state-manager/Cargo.toml ./dummy -COPY state-manager/Cargo.lock ./dummy -COPY state-manager/core-rust/Cargo.toml ./dummy/core-rust -COPY state-manager/state-manager/Cargo.toml ./dummy/state-manager -COPY state-manager/core-api-server/Cargo.toml ./dummy/core-api-server +COPY core-rust/Cargo.toml ./dummy +COPY core-rust/Cargo.lock ./dummy +COPY core-rust/core-rust/Cargo.toml ./dummy/core-rust +COPY core-rust/state-manager/Cargo.toml ./dummy/state-manager +COPY core-rust/core-api-server/Cargo.toml ./dummy/core-api-server RUN mv ./dummy/src/main.rs ./dummy/src/lib.rs WORKDIR /app/dummy @@ -48,7 +48,7 @@ RUN rm -rf /app/dummy/* FROM cache-packages as prod-build WORKDIR /app # Now - we copy in everything, and do the actual built -COPY state-manager ./ +COPY core-rust ./ RUN cargo build --target=$TARGET --release RUN cp -R target/$TARGET/release/libcorerust.so / diff --git a/docker/rust-builder/build-sm.yaml b/docker/rust-builder/build-sm.yaml index 256b212b43..9f17e5e9e6 100644 --- a/docker/rust-builder/build-sm.yaml +++ b/docker/rust-builder/build-sm.yaml @@ -8,5 +8,5 @@ services: dockerfile: Dockerfile target: mapped-volume-build volumes: - - ../../state-manager:/app + - ../../core-rust:/app - .cargo:/usr/local/cargo/registry \ No newline at end of file diff --git a/settings.gradle b/settings.gradle index a3eb87080c..65512bdbf7 100644 --- a/settings.gradle +++ b/settings.gradle @@ -3,13 +3,12 @@ include ':core' include ':cli-tools' include ':olympia-engine' include ':common' -include ':state-manager-bridge' -include ':state-manager' +include ':core-rust-bridge' +include ':core-rust' project(':core').projectDir = new File('core') project(':cli-tools').projectDir = new File('cli-tools') project(':olympia-engine').projectDir = new File('olympia-engine') project(':common').projectDir = new File('common') -project(':state-manager-bridge').projectDir = new File('state-manager-bridge') -project(':state-manager').projectDir = new File('state-manager') - +project(':core-rust-bridge').projectDir = new File('core-rust-bridge') +project(':core-rust').projectDir = new File('core-rust') diff --git a/state-manager-bridge/src/main/java/com/radixdlt/statecomputer/preview/FeeSummary.java b/state-manager-bridge/src/main/java/com/radixdlt/statecomputer/preview/FeeSummary.java deleted file mode 100644 index 1f7c41fa93..0000000000 --- a/state-manager-bridge/src/main/java/com/radixdlt/statecomputer/preview/FeeSummary.java +++ /dev/null @@ -1,103 +0,0 @@ -/* Copyright 2021 Radix Publishing Ltd incorporated in Jersey (Channel Islands). - * - * Licensed under the Radix License, Version 1.0 (the "License"); you may not use this - * file except in compliance with the License. You may obtain a copy of the License at: - * - * radixfoundation.org/licenses/LICENSE-v1 - * - * The Licensor hereby grants permission for the Canonical version of the Work to be - * published, distributed and used under or by reference to the Licensor’s trademark - * Radix ® and use of any unregistered trade names, logos or get-up. - * - * The Licensor provides the Work (and each Contributor provides its Contributions) on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, - * including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, - * MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. - * - * Whilst the Work is capable of being deployed, used and adopted (instantiated) to create - * a distributed ledger it is your responsibility to test and validate the code, together - * with all logic and performance of that code under all foreseeable scenarios. - * - * The Licensor does not make or purport to make and hereby excludes liability for all - * and any representation, warranty or undertaking in any form whatsoever, whether express - * or implied, to any entity or person, including any representation, warranty or - * undertaking, as to the functionality security use, value or other characteristics of - * any distributed ledger nor in respect the functioning or value of any tokens which may - * be created stored or transferred using the Work. The Licensor does not warrant that the - * Work or any use of the Work complies with any law or regulation in any territory where - * it may be implemented or used or that it will be appropriate for any specific purpose. - * - * Neither the licensor nor any current or former employees, officers, directors, partners, - * trustees, representatives, agents, advisors, contractors, or volunteers of the Licensor - * shall be liable for any direct or indirect, special, incidental, consequential or other - * losses of any kind, in tort, contract or otherwise (including but not limited to loss - * of revenue, income or profits, or loss of use or data, or loss of reputation, or loss - * of any economic or other opportunity of whatsoever nature or howsoever arising), arising - * out of or in connection with (without limitation of any use, misuse, of any ledger system - * or use made or its functionality or any performance or operation of any code or protocol - * caused by bugs or programming or logic errors or otherwise); - * - * A. any offer, purchase, holding, use, sale, exchange or transmission of any - * cryptographic keys, tokens or assets created, exchanged, stored or arising from any - * interaction with the Work; - * - * B. any failure in a transmission or loss of any token or assets keys or other digital - * artefacts due to errors in transmission; - * - * C. bugs, hacks, logic errors or faults in the Work or any communication; - * - * D. system software or apparatus including but not limited to losses caused by errors - * in holding or transmitting tokens by any third-party; - * - * E. breaches or failure of security including hacker attacks, loss or disclosure of - * password, loss of private key, unauthorised use or misuse of such passwords or keys; - * - * F. any losses including loss of anticipated savings or other benefits resulting from - * use of the Work or any changes to the Work (however implemented). - * - * You are solely responsible for; testing, validating and evaluation of all operation - * logic, functionality, security and appropriateness of using the Work for any commercial - * or non-commercial purpose and for any reproduction or redistribution by You of the - * Work. You assume all risks associated with Your use of the Work and the exercise of - * permissions under this License. - */ - -package com.radixdlt.statecomputer.preview; - -import com.radixdlt.rev2.Decimal; -import com.radixdlt.sbor.codec.CodecMap; -import com.radixdlt.sbor.codec.StructCodec; -import com.radixdlt.utils.UInt32; - -public record FeeSummary( - boolean loanFullyRepaid, - UInt32 costUnitLimit, - UInt32 costUnitsConsumed, - Decimal costUnitPrice, - UInt32 tipPercentage, - Decimal burned, - Decimal tipped) { - public static void registerCodec(CodecMap codecMap) { - codecMap.register( - FeeSummary.class, - codecs -> - StructCodec.with( - FeeSummary::new, - codecs.of(boolean.class), - codecs.of(UInt32.class), - codecs.of(UInt32.class), - codecs.of(Decimal.class), - codecs.of(UInt32.class), - codecs.of(Decimal.class), - codecs.of(Decimal.class), - (t, encoder) -> - encoder.encode( - t.loanFullyRepaid, - t.costUnitLimit, - t.costUnitsConsumed, - t.costUnitPrice, - t.tipPercentage, - t.burned, - t.tipped))); - } -} diff --git a/state-manager-bridge/src/main/java/com/radixdlt/statecomputer/preview/PreviewError.java b/state-manager-bridge/src/main/java/com/radixdlt/statecomputer/preview/PreviewError.java deleted file mode 100644 index 28134503a4..0000000000 --- a/state-manager-bridge/src/main/java/com/radixdlt/statecomputer/preview/PreviewError.java +++ /dev/null @@ -1,80 +0,0 @@ -/* Copyright 2021 Radix Publishing Ltd incorporated in Jersey (Channel Islands). - * - * Licensed under the Radix License, Version 1.0 (the "License"); you may not use this - * file except in compliance with the License. You may obtain a copy of the License at: - * - * radixfoundation.org/licenses/LICENSE-v1 - * - * The Licensor hereby grants permission for the Canonical version of the Work to be - * published, distributed and used under or by reference to the Licensor’s trademark - * Radix ® and use of any unregistered trade names, logos or get-up. - * - * The Licensor provides the Work (and each Contributor provides its Contributions) on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, - * including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, - * MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. - * - * Whilst the Work is capable of being deployed, used and adopted (instantiated) to create - * a distributed ledger it is your responsibility to test and validate the code, together - * with all logic and performance of that code under all foreseeable scenarios. - * - * The Licensor does not make or purport to make and hereby excludes liability for all - * and any representation, warranty or undertaking in any form whatsoever, whether express - * or implied, to any entity or person, including any representation, warranty or - * undertaking, as to the functionality security use, value or other characteristics of - * any distributed ledger nor in respect the functioning or value of any tokens which may - * be created stored or transferred using the Work. The Licensor does not warrant that the - * Work or any use of the Work complies with any law or regulation in any territory where - * it may be implemented or used or that it will be appropriate for any specific purpose. - * - * Neither the licensor nor any current or former employees, officers, directors, partners, - * trustees, representatives, agents, advisors, contractors, or volunteers of the Licensor - * shall be liable for any direct or indirect, special, incidental, consequential or other - * losses of any kind, in tort, contract or otherwise (including but not limited to loss - * of revenue, income or profits, or loss of use or data, or loss of reputation, or loss - * of any economic or other opportunity of whatsoever nature or howsoever arising), arising - * out of or in connection with (without limitation of any use, misuse, of any ledger system - * or use made or its functionality or any performance or operation of any code or protocol - * caused by bugs or programming or logic errors or otherwise); - * - * A. any offer, purchase, holding, use, sale, exchange or transmission of any - * cryptographic keys, tokens or assets created, exchanged, stored or arising from any - * interaction with the Work; - * - * B. any failure in a transmission or loss of any token or assets keys or other digital - * artefacts due to errors in transmission; - * - * C. bugs, hacks, logic errors or faults in the Work or any communication; - * - * D. system software or apparatus including but not limited to losses caused by errors - * in holding or transmitting tokens by any third-party; - * - * E. breaches or failure of security including hacker attacks, loss or disclosure of - * password, loss of private key, unauthorised use or misuse of such passwords or keys; - * - * F. any losses including loss of anticipated savings or other benefits resulting from - * use of the Work or any changes to the Work (however implemented). - * - * You are solely responsible for; testing, validating and evaluation of all operation - * logic, functionality, security and appropriateness of using the Work for any commercial - * or non-commercial purpose and for any reproduction or redistribution by You of the - * Work. You assume all risks associated with Your use of the Work and the exercise of - * permissions under this License. - */ - -package com.radixdlt.statecomputer.preview; - -import com.radixdlt.sbor.codec.CodecMap; -import com.radixdlt.sbor.codec.StructCodec; - -public record PreviewError(String message) { - public static void registerCodec(CodecMap codecMap) { - codecMap.register( - PreviewError.class, - codecs -> - StructCodec.with( - PreviewError::new, - codecs.of(String.class), - (t, encoder) -> encoder.encode(t.message))); - } -} diff --git a/state-manager-bridge/src/main/java/com/radixdlt/statecomputer/preview/PreviewFlags.java b/state-manager-bridge/src/main/java/com/radixdlt/statecomputer/preview/PreviewFlags.java deleted file mode 100644 index 055b676f98..0000000000 --- a/state-manager-bridge/src/main/java/com/radixdlt/statecomputer/preview/PreviewFlags.java +++ /dev/null @@ -1,80 +0,0 @@ -/* Copyright 2021 Radix Publishing Ltd incorporated in Jersey (Channel Islands). - * - * Licensed under the Radix License, Version 1.0 (the "License"); you may not use this - * file except in compliance with the License. You may obtain a copy of the License at: - * - * radixfoundation.org/licenses/LICENSE-v1 - * - * The Licensor hereby grants permission for the Canonical version of the Work to be - * published, distributed and used under or by reference to the Licensor’s trademark - * Radix ® and use of any unregistered trade names, logos or get-up. - * - * The Licensor provides the Work (and each Contributor provides its Contributions) on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, - * including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, - * MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. - * - * Whilst the Work is capable of being deployed, used and adopted (instantiated) to create - * a distributed ledger it is your responsibility to test and validate the code, together - * with all logic and performance of that code under all foreseeable scenarios. - * - * The Licensor does not make or purport to make and hereby excludes liability for all - * and any representation, warranty or undertaking in any form whatsoever, whether express - * or implied, to any entity or person, including any representation, warranty or - * undertaking, as to the functionality security use, value or other characteristics of - * any distributed ledger nor in respect the functioning or value of any tokens which may - * be created stored or transferred using the Work. The Licensor does not warrant that the - * Work or any use of the Work complies with any law or regulation in any territory where - * it may be implemented or used or that it will be appropriate for any specific purpose. - * - * Neither the licensor nor any current or former employees, officers, directors, partners, - * trustees, representatives, agents, advisors, contractors, or volunteers of the Licensor - * shall be liable for any direct or indirect, special, incidental, consequential or other - * losses of any kind, in tort, contract or otherwise (including but not limited to loss - * of revenue, income or profits, or loss of use or data, or loss of reputation, or loss - * of any economic or other opportunity of whatsoever nature or howsoever arising), arising - * out of or in connection with (without limitation of any use, misuse, of any ledger system - * or use made or its functionality or any performance or operation of any code or protocol - * caused by bugs or programming or logic errors or otherwise); - * - * A. any offer, purchase, holding, use, sale, exchange or transmission of any - * cryptographic keys, tokens or assets created, exchanged, stored or arising from any - * interaction with the Work; - * - * B. any failure in a transmission or loss of any token or assets keys or other digital - * artefacts due to errors in transmission; - * - * C. bugs, hacks, logic errors or faults in the Work or any communication; - * - * D. system software or apparatus including but not limited to losses caused by errors - * in holding or transmitting tokens by any third-party; - * - * E. breaches or failure of security including hacker attacks, loss or disclosure of - * password, loss of private key, unauthorised use or misuse of such passwords or keys; - * - * F. any losses including loss of anticipated savings or other benefits resulting from - * use of the Work or any changes to the Work (however implemented). - * - * You are solely responsible for; testing, validating and evaluation of all operation - * logic, functionality, security and appropriateness of using the Work for any commercial - * or non-commercial purpose and for any reproduction or redistribution by You of the - * Work. You assume all risks associated with Your use of the Work and the exercise of - * permissions under this License. - */ - -package com.radixdlt.statecomputer.preview; - -import com.radixdlt.sbor.codec.CodecMap; -import com.radixdlt.sbor.codec.StructCodec; - -public record PreviewFlags(boolean unlimitedLoan) { - public static void registerCodec(CodecMap codecMap) { - codecMap.register( - PreviewFlags.class, - codecs -> - StructCodec.with( - PreviewFlags::new, - codecs.of(boolean.class), - (t, encoder) -> encoder.encode(t.unlimitedLoan))); - } -} diff --git a/state-manager-bridge/src/main/java/com/radixdlt/statecomputer/preview/PreviewRequest.java b/state-manager-bridge/src/main/java/com/radixdlt/statecomputer/preview/PreviewRequest.java deleted file mode 100644 index 56ca6463d0..0000000000 --- a/state-manager-bridge/src/main/java/com/radixdlt/statecomputer/preview/PreviewRequest.java +++ /dev/null @@ -1,140 +0,0 @@ -/* Copyright 2021 Radix Publishing Ltd incorporated in Jersey (Channel Islands). - * - * Licensed under the Radix License, Version 1.0 (the "License"); you may not use this - * file except in compliance with the License. You may obtain a copy of the License at: - * - * radixfoundation.org/licenses/LICENSE-v1 - * - * The Licensor hereby grants permission for the Canonical version of the Work to be - * published, distributed and used under or by reference to the Licensor’s trademark - * Radix ® and use of any unregistered trade names, logos or get-up. - * - * The Licensor provides the Work (and each Contributor provides its Contributions) on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, - * including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, - * MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. - * - * Whilst the Work is capable of being deployed, used and adopted (instantiated) to create - * a distributed ledger it is your responsibility to test and validate the code, together - * with all logic and performance of that code under all foreseeable scenarios. - * - * The Licensor does not make or purport to make and hereby excludes liability for all - * and any representation, warranty or undertaking in any form whatsoever, whether express - * or implied, to any entity or person, including any representation, warranty or - * undertaking, as to the functionality security use, value or other characteristics of - * any distributed ledger nor in respect the functioning or value of any tokens which may - * be created stored or transferred using the Work. The Licensor does not warrant that the - * Work or any use of the Work complies with any law or regulation in any territory where - * it may be implemented or used or that it will be appropriate for any specific purpose. - * - * Neither the licensor nor any current or former employees, officers, directors, partners, - * trustees, representatives, agents, advisors, contractors, or volunteers of the Licensor - * shall be liable for any direct or indirect, special, incidental, consequential or other - * losses of any kind, in tort, contract or otherwise (including but not limited to loss - * of revenue, income or profits, or loss of use or data, or loss of reputation, or loss - * of any economic or other opportunity of whatsoever nature or howsoever arising), arising - * out of or in connection with (without limitation of any use, misuse, of any ledger system - * or use made or its functionality or any performance or operation of any code or protocol - * caused by bugs or programming or logic errors or otherwise); - * - * A. any offer, purchase, holding, use, sale, exchange or transmission of any - * cryptographic keys, tokens or assets created, exchanged, stored or arising from any - * interaction with the Work; - * - * B. any failure in a transmission or loss of any token or assets keys or other digital - * artefacts due to errors in transmission; - * - * C. bugs, hacks, logic errors or faults in the Work or any communication; - * - * D. system software or apparatus including but not limited to losses caused by errors - * in holding or transmitting tokens by any third-party; - * - * E. breaches or failure of security including hacker attacks, loss or disclosure of - * password, loss of private key, unauthorised use or misuse of such passwords or keys; - * - * F. any losses including loss of anticipated savings or other benefits resulting from - * use of the Work or any changes to the Work (however implemented). - * - * You are solely responsible for; testing, validating and evaluation of all operation - * logic, functionality, security and appropriateness of using the Work for any commercial - * or non-commercial purpose and for any reproduction or redistribution by You of the - * Work. You assume all risks associated with Your use of the Work and the exercise of - * permissions under this License. - */ - -package com.radixdlt.statecomputer.preview; - -import com.google.common.reflect.TypeToken; -import com.radixdlt.sbor.codec.CodecMap; -import com.radixdlt.sbor.codec.StructCodec; -import com.radixdlt.utils.UInt32; -import com.radixdlt.utils.UInt64; -import java.util.Arrays; -import java.util.List; -import java.util.Objects; - -public record PreviewRequest( - byte[] manifest, - UInt32 costUnitLimit, - UInt32 tipPercentage, - UInt64 nonce, - List signerPublicKeys, - PreviewFlags flags) { - public static void registerCodec(CodecMap codecMap) { - codecMap.register( - PreviewRequest.class, - codecs -> - StructCodec.with( - PreviewRequest::new, - codecs.of(byte[].class), - codecs.of(UInt32.class), - codecs.of(UInt32.class), - codecs.of(UInt64.class), - codecs.of(new TypeToken>() {}), - codecs.of(PreviewFlags.class), - (t, encoder) -> - encoder.encode( - t.manifest, - t.costUnitLimit, - t.tipPercentage, - t.nonce, - t.signerPublicKeys, - t.flags))); - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o instanceof PreviewRequest other) { - return Arrays.equals(other.manifest, manifest) - && Objects.equals(other.nonce, nonce) - && Objects.equals(other.costUnitLimit, costUnitLimit) - && Objects.equals(other.tipPercentage, tipPercentage) - && Objects.equals(other.signerPublicKeys, signerPublicKeys) - && Objects.equals(other.flags, flags); - } - return false; - } - - @Override - public int hashCode() { - return Objects.hash( - Arrays.hashCode(manifest), nonce, costUnitLimit, tipPercentage, signerPublicKeys, flags); - } - - @Override - public String toString() { - return "PreviewRequest{" - + "costUnitLimit=" - + costUnitLimit - + ", tipPercentage=" - + tipPercentage - + ", nonce=" - + nonce - + ", flags=" - + flags - + '}'; - } -} diff --git a/state-manager-bridge/src/main/java/com/radixdlt/statecomputer/preview/PreviewResult.java b/state-manager-bridge/src/main/java/com/radixdlt/statecomputer/preview/PreviewResult.java deleted file mode 100644 index 6d4f587af0..0000000000 --- a/state-manager-bridge/src/main/java/com/radixdlt/statecomputer/preview/PreviewResult.java +++ /dev/null @@ -1,106 +0,0 @@ -/* Copyright 2021 Radix Publishing Ltd incorporated in Jersey (Channel Islands). - * - * Licensed under the Radix License, Version 1.0 (the "License"); you may not use this - * file except in compliance with the License. You may obtain a copy of the License at: - * - * radixfoundation.org/licenses/LICENSE-v1 - * - * The Licensor hereby grants permission for the Canonical version of the Work to be - * published, distributed and used under or by reference to the Licensor’s trademark - * Radix ® and use of any unregistered trade names, logos or get-up. - * - * The Licensor provides the Work (and each Contributor provides its Contributions) on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, - * including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, - * MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. - * - * Whilst the Work is capable of being deployed, used and adopted (instantiated) to create - * a distributed ledger it is your responsibility to test and validate the code, together - * with all logic and performance of that code under all foreseeable scenarios. - * - * The Licensor does not make or purport to make and hereby excludes liability for all - * and any representation, warranty or undertaking in any form whatsoever, whether express - * or implied, to any entity or person, including any representation, warranty or - * undertaking, as to the functionality security use, value or other characteristics of - * any distributed ledger nor in respect the functioning or value of any tokens which may - * be created stored or transferred using the Work. The Licensor does not warrant that the - * Work or any use of the Work complies with any law or regulation in any territory where - * it may be implemented or used or that it will be appropriate for any specific purpose. - * - * Neither the licensor nor any current or former employees, officers, directors, partners, - * trustees, representatives, agents, advisors, contractors, or volunteers of the Licensor - * shall be liable for any direct or indirect, special, incidental, consequential or other - * losses of any kind, in tort, contract or otherwise (including but not limited to loss - * of revenue, income or profits, or loss of use or data, or loss of reputation, or loss - * of any economic or other opportunity of whatsoever nature or howsoever arising), arising - * out of or in connection with (without limitation of any use, misuse, of any ledger system - * or use made or its functionality or any performance or operation of any code or protocol - * caused by bugs or programming or logic errors or otherwise); - * - * A. any offer, purchase, holding, use, sale, exchange or transmission of any - * cryptographic keys, tokens or assets created, exchanged, stored or arising from any - * interaction with the Work; - * - * B. any failure in a transmission or loss of any token or assets keys or other digital - * artefacts due to errors in transmission; - * - * C. bugs, hacks, logic errors or faults in the Work or any communication; - * - * D. system software or apparatus including but not limited to losses caused by errors - * in holding or transmitting tokens by any third-party; - * - * E. breaches or failure of security including hacker attacks, loss or disclosure of - * password, loss of private key, unauthorised use or misuse of such passwords or keys; - * - * F. any losses including loss of anticipated savings or other benefits resulting from - * use of the Work or any changes to the Work (however implemented). - * - * You are solely responsible for; testing, validating and evaluation of all operation - * logic, functionality, security and appropriateness of using the Work for any commercial - * or non-commercial purpose and for any reproduction or redistribution by You of the - * Work. You assume all risks associated with Your use of the Work and the exercise of - * permissions under this License. - */ - -package com.radixdlt.statecomputer.preview; - -import com.google.common.reflect.TypeToken; -import com.radixdlt.lang.Tuple; -import com.radixdlt.rev2.ComponentAddress; -import com.radixdlt.rev2.LogLevel; -import com.radixdlt.rev2.PackageAddress; -import com.radixdlt.rev2.ResourceAddress; -import com.radixdlt.rev2.TransactionStatus; -import com.radixdlt.sbor.codec.CodecMap; -import com.radixdlt.sbor.codec.StructCodec; -import java.util.List; - -public record PreviewResult( - TransactionStatus transactionStatus, - FeeSummary transactionFee, - List> logs, - List newPackageAddresses, - List newComponentAddresses, - List newResourceAddresses) { - public static void registerCodec(CodecMap codecMap) { - codecMap.register( - PreviewResult.class, - codecs -> - StructCodec.with( - PreviewResult::new, - codecs.of(TransactionStatus.class), - codecs.of(FeeSummary.class), - codecs.of(new TypeToken>>() {}), - codecs.of(new TypeToken>() {}), - codecs.of(new TypeToken>() {}), - codecs.of(new TypeToken>() {}), - (t, encoder) -> - encoder.encode( - t.transactionStatus, - t.transactionFee, - t.logs, - t.newPackageAddresses, - t.newComponentAddresses, - t.newResourceAddresses))); - } -} diff --git a/state-manager-bridge/src/test/java/com/radixdlt/statecomputer/PreviewTest.java b/state-manager-bridge/src/test/java/com/radixdlt/statecomputer/PreviewTest.java deleted file mode 100644 index 86e5aaff9b..0000000000 --- a/state-manager-bridge/src/test/java/com/radixdlt/statecomputer/PreviewTest.java +++ /dev/null @@ -1,146 +0,0 @@ -/* Copyright 2021 Radix Publishing Ltd incorporated in Jersey (Channel Islands). - * - * Licensed under the Radix License, Version 1.0 (the "License"); you may not use this - * file except in compliance with the License. You may obtain a copy of the License at: - * - * radixfoundation.org/licenses/LICENSE-v1 - * - * The Licensor hereby grants permission for the Canonical version of the Work to be - * published, distributed and used under or by reference to the Licensor’s trademark - * Radix ® and use of any unregistered trade names, logos or get-up. - * - * The Licensor provides the Work (and each Contributor provides its Contributions) on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, - * including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, - * MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. - * - * Whilst the Work is capable of being deployed, used and adopted (instantiated) to create - * a distributed ledger it is your responsibility to test and validate the code, together - * with all logic and performance of that code under all foreseeable scenarios. - * - * The Licensor does not make or purport to make and hereby excludes liability for all - * and any representation, warranty or undertaking in any form whatsoever, whether express - * or implied, to any entity or person, including any representation, warranty or - * undertaking, as to the functionality security use, value or other characteristics of - * any distributed ledger nor in respect the functioning or value of any tokens which may - * be created stored or transferred using the Work. The Licensor does not warrant that the - * Work or any use of the Work complies with any law or regulation in any territory where - * it may be implemented or used or that it will be appropriate for any specific purpose. - * - * Neither the licensor nor any current or former employees, officers, directors, partners, - * trustees, representatives, agents, advisors, contractors, or volunteers of the Licensor - * shall be liable for any direct or indirect, special, incidental, consequential or other - * losses of any kind, in tort, contract or otherwise (including but not limited to loss - * of revenue, income or profits, or loss of use or data, or loss of reputation, or loss - * of any economic or other opportunity of whatsoever nature or howsoever arising), arising - * out of or in connection with (without limitation of any use, misuse, of any ledger system - * or use made or its functionality or any performance or operation of any code or protocol - * caused by bugs or programming or logic errors or otherwise); - * - * A. any offer, purchase, holding, use, sale, exchange or transmission of any - * cryptographic keys, tokens or assets created, exchanged, stored or arising from any - * interaction with the Work; - * - * B. any failure in a transmission or loss of any token or assets keys or other digital - * artefacts due to errors in transmission; - * - * C. bugs, hacks, logic errors or faults in the Work or any communication; - * - * D. system software or apparatus including but not limited to losses caused by errors - * in holding or transmitting tokens by any third-party; - * - * E. breaches or failure of security including hacker attacks, loss or disclosure of - * password, loss of private key, unauthorised use or misuse of such passwords or keys; - * - * F. any losses including loss of anticipated savings or other benefits resulting from - * use of the Work or any changes to the Work (however implemented). - * - * You are solely responsible for; testing, validating and evaluation of all operation - * logic, functionality, security and appropriateness of using the Work for any commercial - * or non-commercial purpose and for any reproduction or redistribution by You of the - * Work. You assume all risks associated with Your use of the Work and the exercise of - * permissions under this License. - */ - -package com.radixdlt.statecomputer; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import com.radixdlt.crypto.ECKeyPair; -import com.radixdlt.lang.Option; -import com.radixdlt.rev2.NetworkDefinition; -import com.radixdlt.rev2.TransactionStatus; -import com.radixdlt.statecomputer.preview.PreviewFlags; -import com.radixdlt.statecomputer.preview.PreviewRequest; -import com.radixdlt.statemanager.REv2DatabaseConfig; -import com.radixdlt.statemanager.StateManager; -import com.radixdlt.statemanager.StateManagerConfig; -import com.radixdlt.transaction.TransactionBuilder; -import com.radixdlt.utils.UInt32; -import com.radixdlt.utils.UInt64; -import java.util.List; -import org.bouncycastle.util.encoders.Hex; -import org.junit.Test; - -public final class PreviewTest { - @Test - public void test_successful_preview() { - // Arrange - try (final var stateManager = - StateManager.createAndInitialize( - new StateManagerConfig( - NetworkDefinition.INT_TEST_NET, Option.none(), REv2DatabaseConfig.inMemory()))) { - final var stateComputer = new RustStateComputer(stateManager); - final var manifest = - TransactionBuilder.compileManifest(NetworkDefinition.INT_TEST_NET, "CLEAR_AUTH_ZONE;"); - final var somePublicKey = ECKeyPair.generateNew().getPublicKey().getCompressedBytes(); - final var previewRequest = - new PreviewRequest( - manifest, - UInt32.fromNonNegativeInt(10000000), - UInt32.fromNonNegativeInt(0), - UInt64.fromNonNegativeLong(0L), - List.of(somePublicKey), - new PreviewFlags(true)); - - // Act - final var result = stateComputer.preview(previewRequest); - final var costUnitsConsumed = result.unwrap().transactionFee().costUnitsConsumed(); - - // Assert - assertTrue(result.unwrap().transactionStatus() instanceof TransactionStatus.Succeeded); - // Just to make sure we're getting some reasonable values back - assertTrue(costUnitsConsumed.gt(UInt32.fromNonNegativeInt(1000))); - assertTrue(costUnitsConsumed.lte(UInt32.fromNonNegativeInt(1000000))); - } - } - - @Test - public void test_decode_error_result() { - // Arrange - try (final var stateManager = - StateManager.createAndInitialize( - new StateManagerConfig( - NetworkDefinition.INT_TEST_NET, Option.none(), REv2DatabaseConfig.inMemory()))) { - final var stateComputer = new RustStateComputer(stateManager); - final var manifest = Hex.decode("00"); // invalid manifest - final var somePublicKey = ECKeyPair.generateNew().getPublicKey().getCompressedBytes(); - final var previewRequest = - new PreviewRequest( - manifest, - UInt32.fromNonNegativeInt(100000000), - UInt32.fromNonNegativeInt(0), - UInt64.fromNonNegativeLong(0L), - List.of(somePublicKey), - new PreviewFlags(true)); - - // Act - final var result = stateComputer.preview(previewRequest); - - // Assert - assertTrue(result.isError()); - assertFalse(result.unwrapError().message().isBlank()); - } - } -} diff --git a/state-manager/core-api-server/core-api-spec.yaml b/state-manager/core-api-server/core-api-spec.yaml deleted file mode 100644 index 5e589451bb..0000000000 --- a/state-manager/core-api-server/core-api-spec.yaml +++ /dev/null @@ -1,430 +0,0 @@ -openapi: 3.1.0 -info: - version: '0.1.0' - title: 'Babylon Core API' - license: - name: The Radix License, Version 1.0 - url: https://www.radixfoundation.org/licenses/LICENSE-v1 -servers: - - url: 'localhost:3333/core' -tags: - - name: Status - x-displayName: Status Endpoints - description: To query information about the Node / Ledger status. - - name: Transaction - x-displayName: Transaction Submission Endpoints - description: To submit transactions to the network. - - name: Mempool - x-displayName: Mempool Endpoints - description: To query mempool status. - - name: Ledger State - x-displayName: Ledger State Endpoints - description: To query the current ledger state. - - name: History Stream - x-displayName: History Stream Endpoints - description: To query the history of the ledger. - - name: Key - x-displayName: Key Endpoints - description: To sign certain transactions with the node's own key. -paths: - "/status/network-configuration": - post: - summary: Get Network Configuration - description: Returns the network configuration of the network the node is connected to. - tags: - - Status - responses: - '200': - description: Network Configuration - content: - application/json: - schema: - "$ref": "#/components/schemas/NetworkConfigurationResponse" - '500': - description: An error occurred - content: - application/json: - schema: - "$ref": "#/components/schemas/ErrorResponse" - "/transaction/submit": - post: - summary: Submit transaction to the network - description: Returns whether the transaction submission was accepted. - tags: - - Transaction - requestBody: - required: true - content: - application/json: - schema: - "$ref": "#/components/schemas/TransactionSubmitRequest" - responses: - '200': - description: Transaction Submit Response - content: - application/json: - schema: - "$ref": "#/components/schemas/TransactionSubmitResponse" - '500': - description: An error occurred - content: - application/json: - schema: - "$ref": "#/components/schemas/ErrorResponse" - "/transaction/preview": - post: - summary: Preview a transaction against the latest network state - description: Returns the preview response - tags: - - Transaction - requestBody: - required: true - content: - application/json: - schema: - "$ref": "#/components/schemas/TransactionPreviewRequest" - responses: - '200': - description: Transaction preview response - content: - application/json: - schema: - "$ref": "#/components/schemas/TransactionPreviewResponse" - '500': - description: An error occurred - content: - application/json: - schema: - "$ref": "#/components/schemas/ErrorResponse" -components: - schemas: -########################### -# GENERAL / SHARED MODELS # -########################### - NetworkIdentifier: - type: object - required: - - network - properties: - network: - type: string - example: - network: mainnet - ErrorResponse: - type: object - required: - - code - - message - properties: - code: - description: A numeric code corresponding to the given error type, roughly aligned with HTTP Status Code semantics (eg 400/404/500). - type: integer - message: - description: A human-readable error message. - type: string - details: - description: A structured/typed details object. - $ref: "#/components/schemas/CoreErrorDetails" - trace_id: - description: A GUID to be used when reporting errors, to allow correlation with the Core API's error logs, in the case where the Core API details are hidden. - type: string - CoreErrorDetails: - type: object - required: - - type - properties: - type: - type: string - discriminator: - propertyName: type - mapping: - NetworkNotSupportedError: "#/components/schemas/NetworkNotSupportedError" - InternalServerError: "#/components/schemas/InternalServerError" - InvalidJsonError: "#/components/schemas/InvalidJsonError" - InvalidHexError: "#/components/schemas/InvalidHexError" - MempoolFullError: "#/components/schemas/MempoolFullError" - InvalidTransactionError: "#/components/schemas/InvalidTransactionError" - PreviewError: "#/components/schemas/PreviewError" - NetworkNotSupportedError: - allOf: - - $ref: "#/components/schemas/CoreErrorDetails" - - type: object - required: - - supported_networks - properties: - supported_networks: - type: array - items: - $ref: "#/components/schemas/NetworkIdentifier" - InternalServerError: - allOf: - - $ref: "#/components/schemas/CoreErrorDetails" - - type: object - properties: - exception: - type: string - cause: - type: string - InvalidJsonError: - allOf: - - $ref: "#/components/schemas/CoreErrorDetails" - - type: object - properties: - cause: - type: string - InvalidHexError: - allOf: - - $ref: "#/components/schemas/CoreErrorDetails" - - type: object - required: - - invalid_hex - properties: - invalid_hex: - type: string - MempoolFullError: - allOf: - - $ref: "#/components/schemas/CoreErrorDetails" - - type: object - required: - - mempool_transaction_count - properties: - mempool_transaction_count: - type: integer - format: int64 - InvalidTransactionError: - allOf: - - $ref: "#/components/schemas/CoreErrorDetails" - - type: object - required: - - message - properties: - message: - type: string - PreviewError: - allOf: - - $ref: "#/components/schemas/CoreErrorDetails" - - type: object - required: - - message - properties: - message: - type: string -######################################### -# GENERAL / SHARED MODELS - Transaction # -######################################### - TransactionStatus: - type: object - required: - - type - properties: - type: - type: string - discriminator: - propertyName: type - mapping: - TransactionStatusRejected: "#/components/schemas/TransactionStatusRejected" - TransactionStatusSucceeded: "#/components/schemas/TransactionStatusSucceeded" - TransactionStatusFailed: "#/components/schemas/TransactionStatusFailed" - TransactionStatusRejected: - allOf: - - $ref: "#/components/schemas/TransactionStatus" - - type: object - TransactionStatusSucceeded: - allOf: - - $ref: "#/components/schemas/TransactionStatus" - - type: object - required: - - output - properties: - output: - type: array - items: - type: string - TransactionStatusFailed: - allOf: - - $ref: "#/components/schemas/TransactionStatus" - - type: object - required: - - message - properties: - message: - type: string - FeeSummary: - type: object - required: - - loan_fully_repaid - - cost_unit_limit - - cost_units_consumed - - cost_unit_price - - tip_percentage - - xrd_burned - - xrd_tipped - properties: - loan_fully_repaid: - type: boolean - cost_unit_limit: - type: string - cost_units_consumed: - type: string - cost_unit_price: - type: string - tip_percentage: - type: string - xrd_burned: - type: string - xrd_tipped: - type: string -########################################## -# REQUEST: /status/network-configuration # -########################################## - NetworkConfigurationResponse: - type: object - required: - - version - - network_identifier - - bech32_human_readable_parts - properties: - version: - description: Different versions regarding the node, network and api. - type: object - required: - - core_version - - api_version - properties: - core_version: - type: string - api_version: - type: string - network_identifier: - "$ref": "#/components/schemas/NetworkIdentifier" - description: The name of the network. - bech32_human_readable_parts: - "$ref": "#/components/schemas/Bech32HRPs" - description: The unique bech32 hrps used for addressing. - Bech32HRPs: - type: object - required: - - account_hrp - - validator_hrp - - node_hrp - - resource_hrp_suffix - properties: - account_hrp: - type: string - validator_hrp: - type: string - node_hrp: - type: string - resource_hrp_suffix: - type: string -################################ -# REQUEST: /transaction/submit # -################################ - TransactionSubmitRequest: - type: object - required: - - network_identifier - - notarized_transaction - properties: - network_identifier: - "$ref": "#/components/schemas/NetworkIdentifier" - description: The name of the network. - notarized_transaction: - description: A notarized transaction encoded in the Radix transaction format, and then hex encoded. - type: string - TransactionSubmitResponse: - type: object - required: - - duplicate - properties: - duplicate: - description: Is true if the transaction is a duplicate of an existing transaction - in the mempool. - type: boolean -################################# -# REQUEST: /transaction/preview # -################################# - TransactionPreviewRequest: - type: object - required: - - network_identifier - - manifest - - cost_unit_limit - - tip_percentage - - nonce - - signer_public_keys - - flags - properties: - network_identifier: - "$ref": "#/components/schemas/NetworkIdentifier" - description: The name of the network. - manifest: - description: A transaction manifest. Sbor encoded, and then hex encoded. - type: string - cost_unit_limit: - description: A limit of cost units available for execution - type: integer - format: int32 - tip_percentage: - description: A tip for the validator - type: integer - format: int32 - nonce: - description: A nonce value to use for execution - type: integer - format: int64 - signer_public_keys: - description: A list of public keys to be used as transaction signers, in a compressed format, hex encoded. - type: array - items: - type: string - flags: - type: object - required: - - unlimited_loan - properties: - unlimited_loan: - type: boolean - TransactionPreviewResponse: - type: object - required: - - transaction_status - - transaction_fee - - logs - - new_package_addresses - - new_component_addresses - - new_resource_addresses - properties: - transaction_status: - "$ref": "#/components/schemas/TransactionStatus" - description: The status of the transaction - transaction_fee: - "$ref": "#/components/schemas/FeeSummary" - description: Fees to be paid - logs: - type: array - items: - type: object - required: - - level - - message - properties: - level: - type: string - message: - type: string - new_package_addresses: - description: A list of new package addresses - type: array - items: - type: string - new_component_addresses: - description: A list of new component addresses - type: array - items: - type: string - new_resource_addresses: - description: A list of new resource addresses - type: array - items: - type: string \ No newline at end of file diff --git a/state-manager/state-manager/src/jni/state_computer/dto.rs b/state-manager/state-manager/src/jni/state_computer/dto.rs deleted file mode 100644 index 912f2c5970..0000000000 --- a/state-manager/state-manager/src/jni/state_computer/dto.rs +++ /dev/null @@ -1,181 +0,0 @@ -/* Copyright 2021 Radix Publishing Ltd incorporated in Jersey (Channel Islands). - * - * Licensed under the Radix License, Version 1.0 (the "License"); you may not use this - * file except in compliance with the License. You may obtain a copy of the License at: - * - * radixfoundation.org/licenses/LICENSE-v1 - * - * The Licensor hereby grants permission for the Canonical version of the Work to be - * published, distributed and used under or by reference to the Licensor’s trademark - * Radix ® and use of any unregistered trade names, logos or get-up. - * - * The Licensor provides the Work (and each Contributor provides its Contributions) on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, - * including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, - * MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. - * - * Whilst the Work is capable of being deployed, used and adopted (instantiated) to create - * a distributed ledger it is your responsibility to test and validate the code, together - * with all logic and performance of that code under all foreseeable scenarios. - * - * The Licensor does not make or purport to make and hereby excludes liability for all - * and any representation, warranty or undertaking in any form whatsoever, whether express - * or implied, to any entity or person, including any representation, warranty or - * undertaking, as to the functionality security use, value or other characteristics of - * any distributed ledger nor in respect the functioning or value of any tokens which may - * be created stored or transferred using the Work. The Licensor does not warrant that the - * Work or any use of the Work complies with any law or regulation in any territory where - * it may be implemented or used or that it will be appropriate for any specific purpose. - * - * Neither the licensor nor any current or former employees, officers, directors, partners, - * trustees, representatives, agents, advisors, contractors, or volunteers of the Licensor - * shall be liable for any direct or indirect, special, incidental, consequential or other - * losses of any kind, in tort, contract or otherwise (including but not limited to loss - * of revenue, income or profits, or loss of use or data, or loss of reputation, or loss - * of any economic or other opportunity of whatsoever nature or howsoever arising), arising - * out of or in connection with (without limitation of any use, misuse, of any ledger system - * or use made or its functionality or any performance or operation of any code or protocol - * caused by bugs or programming or logic errors or otherwise); - * - * A. any offer, purchase, holding, use, sale, exchange or transmission of any - * cryptographic keys, tokens or assets created, exchanged, stored or arising from any - * interaction with the Work; - * - * B. any failure in a transmission or loss of any token or assets keys or other digital - * artefacts due to errors in transmission; - * - * C. bugs, hacks, logic errors or faults in the Work or any communication; - * - * D. system software or apparatus including but not limited to losses caused by errors - * in holding or transmitting tokens by any third-party; - * - * E. breaches or failure of security including hacker attacks, loss or disclosure of - * password, loss of private key, unauthorised use or misuse of such passwords or keys; - * - * F. any losses including loss of anticipated savings or other benefits resulting from - * use of the Work or any changes to the Work (however implemented). - * - * You are solely responsible for; testing, validating and evaluation of all operation - * logic, functionality, security and appropriateness of using the Work for any commercial - * or non-commercial purpose and for any reproduction or redistribution by You of the - * Work. You assume all risks associated with Your use of the Work and the exercise of - * permissions under this License. - */ - -use radix_engine::fee::FeeSummary; -use radix_engine::transaction::{PreviewResult, TransactionOutcome, TransactionResult}; -use sbor::{Decode, Encode, TypeId}; -use scrypto::component::{ComponentAddress, PackageAddress}; -use scrypto::core::Level; -use scrypto::math::Decimal; -use scrypto::prelude::ResourceAddress; - -use crate::result::StateManagerResult; -use crate::types::PreviewError; - -#[derive(Debug, PartialEq, Eq, TypeId, Encode, Decode)] -pub struct PreviewErrorJava { - message: String, -} - -impl From for StateManagerResult { - fn from(err: PreviewError) -> Self { - let msg: String = match err { - PreviewError::InvalidManifest => "Invalid manifest".to_string(), - PreviewError::InvalidSignerPublicKey => "Invalid signer public key".to_string(), - PreviewError::EngineError(engine_preview_error) => { - format!("Preview execution failed: {:?}", engine_preview_error) - } - }; - Ok(PreviewErrorJava { message: msg }) - } -} - -#[derive(Debug, TypeId, Encode, Decode)] -pub enum TransactionStatusJava { - Rejected(String), - Succeeded(Vec>), - Failed(String), -} - -#[derive(Debug, TypeId, Encode, Decode)] -pub struct FeeSummaryJava { - pub loan_fully_repaid: bool, - pub cost_unit_limit: u32, - pub cost_units_consumed: u32, - pub cost_unit_price: Decimal, - pub tip_percentage: u32, - pub burned: Decimal, - pub tipped: Decimal, -} - -impl From for FeeSummaryJava { - fn from(fee_summary: FeeSummary) -> Self { - FeeSummaryJava { - loan_fully_repaid: fee_summary.loan_fully_repaid, - cost_unit_limit: fee_summary.cost_unit_limit, - cost_units_consumed: fee_summary.cost_unit_consumed, - cost_unit_price: fee_summary.cost_unit_price, - tip_percentage: fee_summary.tip_percentage, - burned: fee_summary.burned, - tipped: fee_summary.tipped, - } - } -} - -#[derive(Debug, TypeId, Encode, Decode)] -pub struct PreviewResultJava { - status: TransactionStatusJava, - fee_summary: FeeSummaryJava, - application_logs: Vec<(Level, String)>, - new_package_addresses: Vec, - new_component_addresses: Vec, - new_resource_addresses: Vec, -} - -impl From for PreviewResultJava { - fn from(result: PreviewResult) -> Self { - let receipt = result.receipt; - - let (status, entity_changes) = match receipt.result { - TransactionResult::Commit(commit) => match commit.outcome { - TransactionOutcome::Success(output) => ( - TransactionStatusJava::Succeeded(output), - Some(commit.entity_changes), - ), - TransactionOutcome::Failure(error) => ( - TransactionStatusJava::Failed(error.to_string()), - Some(commit.entity_changes), - ), - }, - TransactionResult::Reject(reject) => ( - TransactionStatusJava::Rejected(reject.error.to_string()), - None, - ), - }; - - let (new_package_addresses, new_component_addresses, new_resource_addresses) = - match entity_changes { - Some(ec) => ( - ec.new_package_addresses, - ec.new_component_addresses, - ec.new_resource_addresses, - ), - None => (Vec::new(), Vec::new(), Vec::new()), - }; - - let (fee_summary, application_logs) = { - let execution = receipt.execution; - (execution.fee_summary, execution.application_logs) - }; - - PreviewResultJava { - status, - fee_summary: fee_summary.into(), - application_logs, - new_package_addresses, - new_component_addresses, - new_resource_addresses, - } - } -}